From 3738b5f8f052d91624b9f143b2431722a1775001 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 30 Jul 2023 11:27:53 +0000 Subject: [PATCH 0001/1381] [CI] Updating repo.json for testing_0.7.2.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 2631d285..0a8fb60c 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.2.2", - "TestingAssemblyVersion": "0.7.2.3", + "TestingAssemblyVersion": "0.7.2.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a95877b9e45d7b77a1188df03ec99c65a7fa71c2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 1 Aug 2023 13:11:33 +0200 Subject: [PATCH 0002/1381] Add priority display to mod selector. --- Penumbra/Configuration.cs | 1 + Penumbra/Mods/ModCreator.cs | 1 - Penumbra/UI/Classes/Colors.cs | 4 ++- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 28 +++++++++++++++++++- Penumbra/UI/Tabs/SettingsTab.cs | 3 +++ 5 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index da2fd935..beaf1960 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -50,6 +50,7 @@ public class Configuration : IPluginConfiguration, ISavable public bool UseNoModsInInspect { get; set; } = false; public bool HideChangedItemFilters { get; set; } = false; + public bool HidePrioritiesInSelector { get; set; } = false; public bool HideRedrawBar { get; set; } = false; public int OptionGroupCollapsibleMin { get; set; } = 5; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index ce63fd42..d63627f5 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -18,7 +18,6 @@ using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.String.Classes; -using Penumbra.Util; namespace Penumbra.Mods; diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 42577034..450f3787 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -23,7 +23,8 @@ public enum ColorId SelectedCollection, RedundantAssignment, NoModsAssignment, - NoAssignment, + NoAssignment, + SelectorPriority, } public static class Colors @@ -62,6 +63,7 @@ public static class Colors ColorId.RedundantAssignment => ( 0x6050D0D0, "Redundant Collection Assignment", "A collection assignment that currently has no effect as it is redundant with more general assignments."), ColorId.NoModsAssignment => ( 0x50000080, "'Use No Mods' Collection Assignment", "A collection assignment set to not use any mods at all."), ColorId.NoAssignment => ( 0x00000000, "Unassigned Collection Assignment", "A collection assignment that is not configured to any collection and thus just has no specific treatment."), + ColorId.SelectorPriority => ( 0xFF808080, "Mod Selector Priority", "The priority displayed for non-zero priority mods in the mod selector."), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 2b943f82..f3ea815a 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -168,6 +168,27 @@ public sealed class ModFileSystemSelector : FileSystemSelector ImGui.GetStyle().ItemSpacing.X) + { + c.Push(ImGuiCol.Text, ColorId.SelectorPriority.Value()); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + offset); + ImGui.TextUnformatted(priorityString); + } + else + { + ImGui.NewLine(); + } + } } @@ -468,6 +489,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Combined wrapper for handling all filters and setting state. private bool ApplyFiltersAndState(ModFileSystem.Leaf leaf, out ModState state) { - state = new ModState { Color = ColorId.EnabledMod }; var mod = leaf.Value; var (settings, collection) = _collectionManager.Active.Current[mod.Index]; + state = new ModState + { + Color = ColorId.EnabledMod, + Priority = settings?.Priority ?? 0, + }; if (ApplyStringFilters(leaf, mod)) return true; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 84432ce6..375ada2d 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -379,6 +379,9 @@ public class SettingsTab : ITab if (v) _config.ChangedItemFilter = ChangedItemDrawer.AllFlags; }); + Checkbox("Hide Priority Numbers in Mod Selector", + "Hides the bracketed non-zero priority numbers displayed in the mod selector when there is enough space for them.", + _config.HidePrioritiesInSelector, v => _config.HidePrioritiesInSelector = v); DrawSingleSelectRadioMax(); DrawCollapsibleGroupMin(); } From 2da6a33a62bcfe844ba28eea72fa93988bdb922e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 1 Aug 2023 13:11:57 +0200 Subject: [PATCH 0003/1381] Some texfile formatting. --- Penumbra/Import/Textures/TexFileParser.cs | 143 ++++++++++------------ 1 file changed, 63 insertions(+), 80 deletions(-) diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 6b77bd0e..f0c3beca 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -8,36 +8,30 @@ namespace Penumbra.Import.Textures; public static class TexFileParser { - public static ScratchImage Parse( Stream data ) + public static ScratchImage Parse(Stream data) { - using var r = new BinaryReader( data ); - var header = r.ReadStructure< TexFile.TexHeader >(); + using var r = new BinaryReader(data); + var header = r.ReadStructure(); var meta = header.ToTexMeta(); - if( meta.Format == DXGIFormat.Unknown ) - { - throw new Exception( $"Could not convert format {header.Format} to DXGI Format." ); - } + if (meta.Format == DXGIFormat.Unknown) + throw new Exception($"Could not convert format {header.Format} to DXGI Format."); - if( meta.Dimension == TexDimension.Unknown ) - { - throw new Exception( $"Could not obtain dimensionality from {header.Type}." ); - } + if (meta.Dimension == TexDimension.Unknown) + throw new Exception($"Could not obtain dimensionality from {header.Type}."); - meta.MipLevels = CountMipLevels( data, in meta, in header ); - if( meta.MipLevels == 0 ) - { - throw new Exception( "Could not load file. Image is corrupted and does not contain enough data for its size." ); - } + meta.MipLevels = CountMipLevels(data, in meta, in header); + if (meta.MipLevels == 0) + throw new Exception("Could not load file. Image is corrupted and does not contain enough data for its size."); - var scratch = ScratchImage.Initialize( meta ); + var scratch = ScratchImage.Initialize(meta); - CopyData( scratch, r ); + CopyData(scratch, r); return scratch; } - private static unsafe int CountMipLevels( Stream data, in TexMeta meta, in TexFile.TexHeader header ) + private static unsafe int CountMipLevels(Stream data, in TexMeta meta, in TexFile.TexHeader header) { var width = meta.Width; var height = meta.Height; @@ -46,28 +40,22 @@ public static class TexFileParser var lastOffset = 0L; var lastSize = 80L; var minSize = meta.Format.IsCompressed() ? 4 : 1; - for( var i = 0; i < 13; ++i ) + for (var i = 0; i < 13; ++i) { - var offset = header.OffsetToSurface[ i ]; - if( offset == 0 ) - { + var offset = header.OffsetToSurface[i]; + if (offset == 0) return i; - } var requiredSize = width * height * bits / 8; - if( offset + requiredSize > data.Length ) - { + if (offset + requiredSize > data.Length) return i; - } var diff = offset - lastOffset; - if( diff != lastSize ) - { + if (diff != lastSize) return i; - } - width = Math.Max( width / 2, minSize ); - height = Math.Max( height / 2, minSize ); + width = Math.Max(width / 2, minSize); + height = Math.Max(height / 2, minSize); lastOffset = offset; lastSize = requiredSize; } @@ -75,48 +63,45 @@ public static class TexFileParser return 13; } - private static unsafe void CopyData( ScratchImage image, BinaryReader r ) + private static unsafe void CopyData(ScratchImage image, BinaryReader r) { - fixed( byte* ptr = image.Pixels ) + fixed (byte* ptr = image.Pixels) { - var span = new Span< byte >( ptr, image.Pixels.Length ); - var readBytes = r.Read( span ); - if( readBytes < image.Pixels.Length ) - { - throw new Exception( $"Invalid data length {readBytes} < {image.Pixels.Length}." ); - } + var span = new Span(ptr, image.Pixels.Length); + var readBytes = r.Read(span); + if (readBytes < image.Pixels.Length) + throw new Exception($"Invalid data length {readBytes} < {image.Pixels.Length}."); } } - public static void Write( this TexFile.TexHeader header, BinaryWriter w ) + public static void Write(this TexFile.TexHeader header, BinaryWriter w) { - w.Write( ( uint )header.Type ); - w.Write( ( uint )header.Format ); - w.Write( header.Width ); - w.Write( header.Height ); - w.Write( header.Depth ); - w.Write( header.MipLevels ); + w.Write((uint)header.Type); + w.Write((uint)header.Format); + w.Write(header.Width); + w.Write(header.Height); + w.Write(header.Depth); + w.Write((byte) header.MipLevels); + w.Write((byte) 0); // TODO Lumina Update unsafe { - w.Write( header.LodOffset[ 0 ] ); - w.Write( header.LodOffset[ 1 ] ); - w.Write( header.LodOffset[ 2 ] ); - for( var i = 0; i < 13; ++i ) - { - w.Write( header.OffsetToSurface[ i ] ); - } + w.Write(header.LodOffset[0]); + w.Write(header.LodOffset[1]); + w.Write(header.LodOffset[2]); + for (var i = 0; i < 13; ++i) + w.Write(header.OffsetToSurface[i]); } } - public static TexFile.TexHeader ToTexHeader( this ScratchImage scratch ) + public static TexFile.TexHeader ToTexHeader(this ScratchImage scratch) { var meta = scratch.Meta; var ret = new TexFile.TexHeader() { - Height = ( ushort )meta.Height, - Width = ( ushort )meta.Width, - Depth = ( ushort )Math.Max( meta.Depth, 1 ), - MipLevels = ( ushort )Math.Min( meta.MipLevels, 12 ), + Height = (ushort)meta.Height, + Width = (ushort)meta.Width, + Depth = (ushort)Math.Max(meta.Depth, 1), + MipLevels = (byte)Math.Min(meta.MipLevels, 12), Format = meta.Format.ToTexFormat(), Type = meta.Dimension switch { @@ -128,50 +113,48 @@ public static class TexFileParser }, }; - ret.FillSurfaceOffsets( scratch ); + ret.FillSurfaceOffsets(scratch); return ret; } - private static unsafe void FillSurfaceOffsets( this ref TexFile.TexHeader header, ScratchImage scratch ) + private static unsafe void FillSurfaceOffsets(this ref TexFile.TexHeader header, ScratchImage scratch) { var idx = 0; - fixed( byte* ptr = scratch.Pixels ) + fixed (byte* ptr = scratch.Pixels) { - foreach( var image in scratch.Images ) + foreach (var image in scratch.Images) { - var offset = ( byte* )image.Pixels - ptr; - header.OffsetToSurface[ idx++ ] = ( uint )( 80 + offset ); + var offset = (byte*)image.Pixels - ptr; + header.OffsetToSurface[idx++] = (uint)(80 + offset); } } - for( ; idx < 13; ++idx ) - { - header.OffsetToSurface[ idx ] = 0; - } + for (; idx < 13; ++idx) + header.OffsetToSurface[idx] = 0; - header.LodOffset[ 0 ] = 0; - header.LodOffset[ 1 ] = 1; - header.LodOffset[ 2 ] = 2; + header.LodOffset[0] = 0; + header.LodOffset[1] = 1; + header.LodOffset[2] = 2; } - public static TexMeta ToTexMeta( this TexFile.TexHeader header ) + public static TexMeta ToTexMeta(this TexFile.TexHeader header) => new() { Height = header.Height, Width = header.Width, - Depth = Math.Max( header.Depth, ( ushort )1 ), + Depth = Math.Max(header.Depth, (ushort)1), MipLevels = header.MipLevels, ArraySize = 1, Format = header.Format.ToDXGI(), Dimension = header.Type.ToDimension(), - MiscFlags = header.Type.HasFlag( TexFile.Attribute.TextureTypeCube ) ? D3DResourceMiscFlags.TextureCube : 0, + MiscFlags = header.Type.HasFlag(TexFile.Attribute.TextureTypeCube) ? D3DResourceMiscFlags.TextureCube : 0, MiscFlags2 = 0, }; - private static TexDimension ToDimension( this TexFile.Attribute attribute ) - => ( attribute & TexFile.Attribute.TextureTypeMask ) switch + private static TexDimension ToDimension(this TexFile.Attribute attribute) + => (attribute & TexFile.Attribute.TextureTypeMask) switch { TexFile.Attribute.TextureType1D => TexDimension.Tex1D, TexFile.Attribute.TextureType2D => TexDimension.Tex2D, @@ -179,7 +162,7 @@ public static class TexFileParser _ => TexDimension.Unknown, }; - public static TexFile.TextureFormat ToTexFormat( this DXGIFormat format ) + public static TexFile.TextureFormat ToTexFormat(this DXGIFormat format) => format switch { DXGIFormat.R8UNorm => TexFile.TextureFormat.L8, @@ -204,7 +187,7 @@ public static class TexFileParser _ => TexFile.TextureFormat.Unknown, }; - public static DXGIFormat ToDXGI( this TexFile.TextureFormat format ) + public static DXGIFormat ToDXGI(this TexFile.TextureFormat format) => format switch { TexFile.TextureFormat.L8 => DXGIFormat.R8UNorm, @@ -229,4 +212,4 @@ public static class TexFileParser TexFile.TextureFormat.Shadow24 => DXGIFormat.R24G8Typeless, _ => DXGIFormat.Unknown, }; -} \ No newline at end of file +} From 930931a8463e27a8530fd1e7d9b4627b347afa54 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 1 Aug 2023 17:39:41 +0200 Subject: [PATCH 0004/1381] Fix ChangeCustomize not loading decals from collections. --- Penumbra/Interop/PathResolving/MetaState.cs | 29 +++++++++------------ 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 2f6260a9..a4cbc967 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Threading; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; @@ -54,6 +53,7 @@ public unsafe class MetaState : IDisposable private readonly CharacterUtility _characterUtility; private ResolveData _lastCreatedCollection = ResolveData.Invalid; + private ResolveData _customizeChangeCollection = ResolveData.Invalid; private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; public MetaState(PerformanceTracker performance, CommunicatorService communicator, CollectionResolver collectionResolver, @@ -81,10 +81,10 @@ public unsafe class MetaState : IDisposable public bool HandleDecalFile(ResourceType type, Utf8GamePath gamePath, out ResolveData resolveData) { if (type == ResourceType.Tex - && _lastCreatedCollection.Valid + && (_lastCreatedCollection.Valid || _customizeChangeCollection.Valid) && gamePath.Path.Substring("chara/common/texture/".Length).StartsWith("decal"u8)) { - resolveData = _lastCreatedCollection; + resolveData = _lastCreatedCollection.Valid ? _lastCreatedCollection : _customizeChangeCollection; return true; } @@ -129,8 +129,9 @@ public unsafe class MetaState : IDisposable _communicator.CreatingCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, _lastCreatedCollection.ModCollection.Name, modelCharaId, customize, equipData); - var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, UsesDecal(*(uint*)modelCharaId, customize)); - var cmp = _lastCreatedCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); + var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, + UsesDecal(*(uint*)modelCharaId, customize)); + var cmp = _lastCreatedCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); _characterBaseCreateMetaChanges.Dispose(); // Should always be empty. _characterBaseCreateMetaChanges = new DisposableContainer(decal, cmp); } @@ -228,7 +229,7 @@ public unsafe class MetaState : IDisposable private void RspSetupCharacterDetour(nint drawObject, nint unk2, float unk3, nint unk4, byte unk5) { - if (_inChangeCustomize) + if (_customizeChangeCollection.Valid) { _rspSetupCharacterHook.Original(drawObject, unk2, unk3, unk4, unk5); } @@ -241,9 +242,6 @@ public unsafe class MetaState : IDisposable } } - /// ChangeCustomize calls RspSetupCharacter, so skip the additional cmp change. - private bool _inChangeCustomize; - private delegate bool ChangeCustomizeDelegate(nint human, nint data, byte skipEquipment); [Signature(Sigs.ChangeCustomize, DetourName = nameof(ChangeCustomizeDetour))] @@ -252,13 +250,12 @@ public unsafe class MetaState : IDisposable private bool ChangeCustomizeDetour(nint human, nint data, byte skipEquipment) { using var performance = _performance.Measure(PerformanceType.ChangeCustomize); - _inChangeCustomize = true; - var resolveData = _collectionResolver.IdentifyCollection((DrawObject*)human, true); - using var cmp = resolveData.ModCollection.TemporarilySetCmpFile(_characterUtility); - using var decals = new DecalReverter(_config, _characterUtility, _resources, resolveData, true); - using var decal2 = new DecalReverter(_config, _characterUtility, _resources, resolveData, false); - var ret = _changeCustomize.Original(human, data, skipEquipment); - _inChangeCustomize = false; + _customizeChangeCollection = _collectionResolver.IdentifyCollection((DrawObject*)human, true); + using var cmp = _customizeChangeCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); + using var decals = new DecalReverter(_config, _characterUtility, _resources, _customizeChangeCollection, true); + using var decal2 = new DecalReverter(_config, _characterUtility, _resources, _customizeChangeCollection, false); + var ret = _changeCustomize.Original(human, data, skipEquipment); + _customizeChangeCollection = ResolveData.Invalid; return ret; } From 622af4e7e9f2abe45b0b8a9bcbd46f095fcdc67f Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 1 Aug 2023 15:45:07 +0000 Subject: [PATCH 0005/1381] [CI] Updating repo.json for testing_0.7.2.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 0a8fb60c..a3ea22c3 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.2.2", - "TestingAssemblyVersion": "0.7.2.4", + "TestingAssemblyVersion": "0.7.2.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 01b88950bf2fa9b9cbf4cdfb6d9108d946ddbe8c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 1 Aug 2023 20:37:57 +0200 Subject: [PATCH 0006/1381] Fix shit. --- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 24 ++++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index f3ea815a..6eecf36a 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -170,24 +170,18 @@ public sealed class ModFileSystemSelector : FileSystemSelector ImGui.GetStyle().ItemSpacing.X) - { - c.Push(ImGuiCol.Text, ColorId.SelectorPriority.Value()); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + offset); - ImGui.TextUnformatted(priorityString); - } - else - { - ImGui.NewLine(); - } + ImGui.GetWindowDrawList().AddText(new Vector2(itemPos + offset, line), ColorId.SelectorPriority.Value(), priorityString); } } From af0edf30029b4c0de1abed888e5834f1b7c90856 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 1 Aug 2023 18:40:28 +0000 Subject: [PATCH 0007/1381] [CI] Updating repo.json for testing_0.7.2.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a3ea22c3..fb7afb7e 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.2.2", - "TestingAssemblyVersion": "0.7.2.5", + "TestingAssemblyVersion": "0.7.2.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0e252d489ae721a5ff842df31c016f16f54c8dc4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 4 Aug 2023 02:14:47 +0200 Subject: [PATCH 0008/1381] Update SharpCompress. --- Penumbra/Penumbra.csproj | 2 +- Penumbra/packages.lock.json | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index cddc5812..ec433113 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -70,7 +70,7 @@ - + diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 26a67367..eed5d7c8 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -22,9 +22,9 @@ }, "SharpCompress": { "type": "Direct", - "requested": "[0.32.1, )", - "resolved": "0.32.1", - "contentHash": "9Cwj3lK/p7wkiBaQPCvaKINuHYuZ0ACDldA4M3o5ISSq7cjbbq3yqigTDBUoKjtyyXpqmQHUkw6fhLnjNF30ow==" + "requested": "[0.33.0, )", + "resolved": "0.33.0", + "contentHash": "FlHfpTAADzaSlVCBF33iKJk9UhOr3Xj+r5LXbW2GzqYr0SrhiOf6shLX2LC2fqs7g7d+YlwKbBXqWFtb+e7icw==" }, "SixLabors.ImageSharp": { "type": "Direct", @@ -81,8 +81,8 @@ "penumbra.gamedata": { "type": "Project", "dependencies": { - "Penumbra.Api": "[1.0.7, )", - "Penumbra.String": "[1.0.3, )" + "Penumbra.Api": "[1.0.8, )", + "Penumbra.String": "[1.0.4, )" } }, "penumbra.string": { From 2a7ccb952de46595428c86f109592e56735951b1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 4 Aug 2023 02:33:25 +0200 Subject: [PATCH 0009/1381] Fix missing scaling for item combos. --- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 51 +++-------------------- 1 file changed, 5 insertions(+), 46 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 726a83e1..6e810000 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; +using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; using ImGuiNET; @@ -469,7 +470,7 @@ public class ItemSwapTab : IDisposable, ITab } ImGui.TableNextColumn(); - _dirty |= selector.Draw("##itemSource", selector.CurrentSelection.Name ?? string.Empty, string.Empty, InputWidth * 2, + _dirty |= selector.Draw("##itemSource", selector.CurrentSelection.Name ?? string.Empty, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); (article1, _, selector) = GetAccessorySelector(_slotTo, false); @@ -494,7 +495,7 @@ public class ItemSwapTab : IDisposable, ITab ImGui.TableNextColumn(); - _dirty |= selector.Draw("##itemTarget", selector.CurrentSelection.Name, string.Empty, InputWidth * 2, + _dirty |= selector.Draw("##itemTarget", selector.CurrentSelection.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); if (_affectedItems is not { Length: > 1 }) return; @@ -535,7 +536,7 @@ public class ItemSwapTab : IDisposable, ITab ImGui.AlignTextToFramePadding(); ImGui.TextUnformatted(text1); ImGui.TableNextColumn(); - _dirty |= sourceSelector.Draw("##itemSource", sourceSelector.CurrentSelection.Name, string.Empty, InputWidth * 2, + _dirty |= sourceSelector.Draw("##itemSource", sourceSelector.CurrentSelection.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); if (type == SwapType.Ring) @@ -548,7 +549,7 @@ public class ItemSwapTab : IDisposable, ITab ImGui.AlignTextToFramePadding(); ImGui.TextUnformatted(text2); ImGui.TableNextColumn(); - _dirty |= targetSelector.Draw("##itemTarget", targetSelector.CurrentSelection.Name, string.Empty, InputWidth * 2, + _dirty |= targetSelector.Draw("##itemTarget", targetSelector.CurrentSelection.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); if (type == SwapType.Ring) { @@ -617,48 +618,6 @@ public class ItemSwapTab : IDisposable, ITab DrawGenderInput("for all Viera", 0); } - - private void DrawWeaponSwap() - { - using var disabled = ImRaii.Disabled(); - using var tab = DrawTab(SwapType.Weapon); - if (!tab) - return; - - using var table = ImRaii.Table("##settings", 2, ImGuiTableFlags.SizingFixedFit); - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted("Select the weapon or tool you want"); - ImGui.TableNextColumn(); - if (_slotSelector.Draw("##weaponSlot", _slotSelector.CurrentSelection.ToName(), string.Empty, InputWidth * 2, - ImGui.GetTextLineHeightWithSpacing())) - { - _dirty = true; - _weaponSource = new ItemSelector(_itemService, _slotSelector.CurrentSelection); - _weaponTarget = new ItemSelector(_itemService, _slotSelector.CurrentSelection); - } - else - { - _dirty = _weaponSource == null || _weaponTarget == null; - _weaponSource ??= new ItemSelector(_itemService, _slotSelector.CurrentSelection); - _weaponTarget ??= new ItemSelector(_itemService, _slotSelector.CurrentSelection); - } - - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted("and put this variant of it"); - ImGui.TableNextColumn(); - _dirty |= _weaponSource.Draw("##weaponSource", _weaponSource.CurrentSelection.Name, string.Empty, InputWidth * 2, - ImGui.GetTextLineHeightWithSpacing()); - - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted("onto this one"); - ImGui.TableNextColumn(); - _dirty |= _weaponTarget.Draw("##weaponTarget", _weaponTarget.CurrentSelection.Name, string.Empty, InputWidth * 2, - ImGui.GetTextLineHeightWithSpacing()); - } - private const float InputWidth = 120; private void DrawTargetIdInput(string text = "Take this ID") From 2f836426d6520ff5d74544617ed195b1acb34a1f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 4 Aug 2023 17:01:53 +0200 Subject: [PATCH 0010/1381] Temporary fix for broken CS offset. --- Penumbra.GameData | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 6 +----- Penumbra/UI/Tabs/DebugTab.cs | 6 ++++-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 1e65d3fd..9eb60aa0 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1e65d3fd028d3ac58090a8c886f351acbd9f3a2a +Subproject commit 9eb60aa0fdaad4a10af2edd77b154a20c7647ce4 diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 6e810000..c7c09de2 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -152,11 +152,7 @@ public class ItemSwapTab : IDisposable, ITab } private readonly Dictionary _selectors; - - private ItemSelector? _weaponSource; - private ItemSelector? _weaponTarget; - private readonly WeaponSelector _slotSelector = new(); - private readonly ItemSwapContainer _swapData; + private readonly ItemSwapContainer _swapData; private Mod? _mod; private ModSettings? _modSettings; diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index 9d5caa0c..ee12e8a2 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -500,11 +500,13 @@ public class DebugTab : Window, ITab if (agent->Data != null) { - using var table = Table("###PBannerTable", 2, ImGuiTableFlags.SizingFixedFit); + // TODO fix when updated in CS. + var characterData = (AgentBannerInterface.Storage.CharacterData*)((byte*)agent->Data + 0x20); + using var table = Table("###PBannerTable", 2, ImGuiTableFlags.SizingFixedFit); if (table) for (var i = 0; i < 8; ++i) { - ref var c = ref agent->Data->CharacterArraySpan[i]; + ref var c = ref *(characterData + i); ImGuiUtil.DrawTableColumn($"Character {i}"); var name = c.Name1.ToString(); ImGuiUtil.DrawTableColumn(name.Length == 0 ? "NULL" : $"{name} ({c.WorldId})"); From e24a535a93fe85bd8b308d1e9ef769f35901ff90 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 8 Aug 2023 01:10:57 +0200 Subject: [PATCH 0011/1381] Initial Texture rework. --- OtterGui | 2 +- Penumbra/Import/Textures/BaseImage.cs | 111 +++++ .../Textures/CombinedTexture.Manipulation.cs | 38 +- Penumbra/Import/Textures/CombinedTexture.cs | 182 ++------ Penumbra/Import/Textures/TexFileParser.cs | 2 +- Penumbra/Import/Textures/Texture.cs | 256 ++-------- Penumbra/Import/Textures/TextureDrawer.cs | 139 ++++++ Penumbra/Import/Textures/TextureImporter.cs | 61 --- Penumbra/Import/Textures/TextureManager.cs | 438 ++++++++++++++++++ Penumbra/Mods/Editor/ModBackup.cs | 2 +- Penumbra/Mods/Editor/ModNormalizer.cs | 1 + Penumbra/Penumbra.cs | 3 +- Penumbra/Services/ServiceManager.cs | 4 +- Penumbra/Services/ServiceWrapper.cs | 2 +- .../AdvancedWindow/ModEditWindow.Textures.cs | 76 ++- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 3 +- 16 files changed, 831 insertions(+), 489 deletions(-) create mode 100644 Penumbra/Import/Textures/BaseImage.cs create mode 100644 Penumbra/Import/Textures/TextureDrawer.cs delete mode 100644 Penumbra/Import/Textures/TextureImporter.cs create mode 100644 Penumbra/Import/Textures/TextureManager.cs diff --git a/OtterGui b/OtterGui index e3d26f16..8d61845c 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit e3d26f16234a4295bf3c7802d87ce43293c6ffe0 +Subproject commit 8d61845cd900fc0a3b58d475c43303b13c1165f4 diff --git a/Penumbra/Import/Textures/BaseImage.cs b/Penumbra/Import/Textures/BaseImage.cs new file mode 100644 index 00000000..f0f6a47e --- /dev/null +++ b/Penumbra/Import/Textures/BaseImage.cs @@ -0,0 +1,111 @@ +using System; +using System.Numerics; +using Lumina.Data.Files; +using OtterTex; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; + +namespace Penumbra.Import.Textures; + +public readonly struct BaseImage : IDisposable +{ + public readonly object? Image; + + public BaseImage(ScratchImage scratch) + => Image = scratch; + + public BaseImage(Image image) + => Image = image; + + public static implicit operator BaseImage(ScratchImage scratch) + => new(scratch); + + public static implicit operator BaseImage(Image img) + => new(img); + + public ScratchImage? AsDds + => Image as ScratchImage; + + public Image? AsPng + => Image as Image; + + public TexFile? AsTex + => Image as TexFile; + + public TextureType Type + => Image switch + { + null => TextureType.Unknown, + ScratchImage => TextureType.Dds, + Image => TextureType.Png, + _ => TextureType.Unknown, + }; + + public void Dispose() + => (Image as IDisposable)?.Dispose(); + + /// Obtain RGBA pixel data for the given image (not including any mip maps.) + public (byte[] Rgba, int Width, int Height) GetPixelData() + { + switch (Image) + { + case null: return (Array.Empty(), 0, 0); + case ScratchImage scratch: + { + var rgba = scratch.GetRGBA(out var f).ThrowIfError(f); + return (rgba.Pixels[..(f.Meta.Width * f.Meta.Height * (f.Meta.Format.BitsPerPixel() / 8))].ToArray(), f.Meta.Width, + f.Meta.Height); + } + case Image img: + { + var ret = new byte[img.Height * img.Width * 4]; + img.CopyPixelDataTo(ret); + return (ret, img.Width, img.Height); + } + default: return (Array.Empty(), 0, 0); + } + } + + public (int Width, int Height) Dimensions + => Image switch + { + null => (0, 0), + ScratchImage scratch => (scratch.Meta.Width, scratch.Meta.Height), + Image img => (img.Width, img.Height), + _ => (0, 0), + }; + + public int Width + => Dimensions.Width; + + public int Height + => Dimensions.Height; + + public Vector2 ImageSize + { + get + { + var (width, height) = Dimensions; + return new Vector2(width, height); + } + } + + public DXGIFormat Format + => Image switch + { + null => DXGIFormat.Unknown, + ScratchImage s => s.Meta.Format, + TexFile t => t.Header.Format.ToDXGI(), + Image => DXGIFormat.B8G8R8X8UNorm, + _ => DXGIFormat.Unknown, + }; + + public int MipMaps + => Image switch + { + null => 0, + ScratchImage s => s.Meta.MipLevels, + TexFile t => t.Header.MipLevels, + _ => 1, + }; +} diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 16bd6dfe..a32b9578 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -16,14 +16,13 @@ public partial class CombinedTexture private bool _invertLeft = false; private bool _invertRight = false; private int _offsetX = 0; - private int _offsetY = 0; - + private int _offsetY = 0; private Vector4 DataLeft( int offset ) - => CappedVector( _left.RGBAPixels, offset, _multiplierLeft, _invertLeft ); + => CappedVector( _left.RgbaPixels, offset, _multiplierLeft, _invertLeft ); private Vector4 DataRight( int offset ) - => CappedVector( _right.RGBAPixels, offset, _multiplierRight, _invertRight ); + => CappedVector( _right.RgbaPixels, offset, _multiplierRight, _invertRight ); private Vector4 DataRight( int x, int y ) { @@ -35,7 +34,7 @@ public partial class CombinedTexture } var offset = ( y * _right.TextureWrap!.Width + x ) * 4; - return CappedVector( _right.RGBAPixels, offset, _multiplierRight, _invertRight ); + return CappedVector( _right.RgbaPixels, offset, _multiplierRight, _invertRight ); } private void AddPixelsMultiplied( int y, ParallelLoopState _ ) @@ -49,10 +48,10 @@ public partial class CombinedTexture var rgba = alpha == 0 ? new Rgba32() : new Rgba32( ( ( right * right.W + left * left.W * ( 1 - right.W ) ) / alpha ) with { W = alpha } ); - _centerStorage.RGBAPixels[ offset ] = rgba.R; - _centerStorage.RGBAPixels[ offset + 1 ] = rgba.G; - _centerStorage.RGBAPixels[ offset + 2 ] = rgba.B; - _centerStorage.RGBAPixels[ offset + 3 ] = rgba.A; + _centerStorage.RgbaPixels[ offset ] = rgba.R; + _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; + _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; + _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; } } @@ -63,10 +62,10 @@ public partial class CombinedTexture var offset = ( _left.TextureWrap!.Width * y + x ) * 4; var left = DataLeft( offset ); var rgba = new Rgba32( left ); - _centerStorage.RGBAPixels[ offset ] = rgba.R; - _centerStorage.RGBAPixels[ offset + 1 ] = rgba.G; - _centerStorage.RGBAPixels[ offset + 2 ] = rgba.B; - _centerStorage.RGBAPixels[ offset + 3 ] = rgba.A; + _centerStorage.RgbaPixels[ offset ] = rgba.R; + _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; + _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; + _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; } } @@ -77,10 +76,10 @@ public partial class CombinedTexture var offset = ( _right.TextureWrap!.Width * y + x ) * 4; var left = DataRight( offset ); var rgba = new Rgba32( left ); - _centerStorage.RGBAPixels[ offset ] = rgba.R; - _centerStorage.RGBAPixels[ offset + 1 ] = rgba.G; - _centerStorage.RGBAPixels[ offset + 2 ] = rgba.B; - _centerStorage.RGBAPixels[ offset + 3 ] = rgba.A; + _centerStorage.RgbaPixels[ offset ] = rgba.R; + _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; + _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; + _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; } } @@ -90,8 +89,8 @@ public partial class CombinedTexture var (width, height) = _left.IsLoaded ? ( _left.TextureWrap!.Width, _left.TextureWrap!.Height ) : ( _right.TextureWrap!.Width, _right.TextureWrap!.Height ); - _centerStorage.RGBAPixels = new byte[width * height * 4]; - _centerStorage.Type = Texture.FileType.Bitmap; + _centerStorage.RgbaPixels = new byte[width * height * 4]; + _centerStorage.Type = TextureType.Bitmap; if( _left.IsLoaded ) { Parallel.For( 0, height, _right.IsLoaded ? AddPixelsMultiplied : MultiplyPixelsLeft ); @@ -103,7 +102,6 @@ public partial class CombinedTexture return ( width, height ); } - private static Vector4 CappedVector( IReadOnlyList< byte > bytes, int offset, Matrix4x4 transform, bool invert ) { if( bytes.Count == 0 ) diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index bf017048..99303234 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -1,14 +1,5 @@ using System; -using System.IO; using System.Numerics; -using Dalamud.Interface; -using Lumina.Data.Files; -using OtterTex; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Png; -using SixLabors.ImageSharp.PixelFormats; -using DalamudUtil = Dalamud.Utility.Util; -using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; @@ -38,170 +29,58 @@ public partial class CombinedTexture : IDisposable private readonly Texture _centerStorage = new(); + public Guid SaveGuid { get; private set; } = Guid.Empty; + public bool IsLoaded => _mode != Mode.Empty; - - public bool IsLeftCopy - => _mode == Mode.LeftCopy; - public Exception? SaveException { get; private set; } = null; + public bool IsLeftCopy + => _mode == Mode.LeftCopy; - public void Draw( UiBuilder builder, Vector2 size ) + public void Draw(TextureManager textures, Vector2 size) { - if( _mode == Mode.Custom && !_centerStorage.IsLoaded ) + if (_mode == Mode.Custom && !_centerStorage.IsLoaded) { - var (width, height) = CombineImage(); - _centerStorage.TextureWrap = - builder.LoadImageRaw( _centerStorage.RGBAPixels, width, height, 4 ); + var (width, height) = CombineImage(); + _centerStorage.TextureWrap = textures.LoadTextureWrap(_centerStorage.RgbaPixels, width, height); } - _current?.Draw( size ); + if (_current != null) + TextureDrawer.Draw(_current, size); } - public void SaveAsPng( string path ) + public void SaveAsPng(TextureManager textures, string path) { - if( !IsLoaded || _current == null ) - { + if (!IsLoaded || _current == null) return; - } - try - { - var image = Image.LoadPixelData< Rgba32 >( _current.RGBAPixels, _current.TextureWrap!.Width, - _current.TextureWrap!.Height ); - image.Save( path, new PngEncoder() { CompressionLevel = PngCompressionLevel.NoCompression } ); - SaveException = null; - } - catch( Exception e ) - { - SaveException = e; - } + SaveGuid = textures.SavePng(_current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, _current.TextureWrap!.Height); } - private void SaveAs( string path, TextureSaveType type, bool mipMaps, bool writeTex ) + private void SaveAs(TextureManager textures, string path, TextureSaveType type, bool mipMaps, bool writeTex) { - if( _current == null || _mode == Mode.Empty ) - { + if (!IsLoaded || _current == null) return; - } - try - { - if( _current.BaseImage is not ScratchImage s ) - { - s = ScratchImage.FromRGBA( _current.RGBAPixels, _current.TextureWrap!.Width, - _current.TextureWrap!.Height, out var i ).ThrowIfError( i ); - } - - var tex = type switch - { - TextureSaveType.AsIs => _current.Type is Texture.FileType.Bitmap or Texture.FileType.Png ? CreateUncompressed( s, mipMaps ) : s, - TextureSaveType.Bitmap => CreateUncompressed( s, mipMaps ), - TextureSaveType.BC3 => CreateCompressed( s, mipMaps, false ), - TextureSaveType.BC7 => CreateCompressed( s, mipMaps, true ), - _ => throw new ArgumentOutOfRangeException( nameof( type ), type, null ), - }; - - if( !writeTex ) - { - tex.SaveDDS( path ); - } - else - { - SaveTex( path, tex ); - } - - SaveException = null; - } - catch( Exception e ) - { - SaveException = e; - } + SaveGuid = textures.SaveAs(type, mipMaps, writeTex, _current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, + _current.TextureWrap!.Height); } - private static void SaveTex( string path, ScratchImage input ) - { - var header = input.ToTexHeader(); - if( header.Format == TexFile.TextureFormat.Unknown ) - { - throw new Exception( $"Could not save tex file with format {input.Meta.Format}, not convertible to a valid .tex formats." ); - } + public void SaveAsTex(TextureManager textures, string path, TextureSaveType type, bool mipMaps) + => SaveAs(textures, path, type, mipMaps, true); - using var stream = File.Open( path, File.Exists(path) ? FileMode.Truncate : FileMode.CreateNew); - using var w = new BinaryWriter( stream ); - header.Write( w ); - w.Write( input.Pixels ); - } - - private static ScratchImage AddMipMaps( ScratchImage input, bool mipMaps ) - { - if( !mipMaps ) - { - return input; - } - - var numMips = Math.Min( 13, 1 + BitOperations.Log2( ( uint )Math.Max( input.Meta.Width, input.Meta.Height ) ) ); - var ec = input.GenerateMipMaps( out var ret, numMips, ( DalamudUtil.IsLinux() ? FilterFlags.ForceNonWIC : 0 ) | FilterFlags.SeparateAlpha ); - if (ec != ErrorCode.Ok) - { - throw new Exception( $"Could not create the requested {numMips} mip maps, maybe retry with the top-right checkbox unchecked:\n{ec}" ); - } - - return ret; - } - - private static ScratchImage CreateUncompressed( ScratchImage input, bool mipMaps ) - { - if( input.Meta.Format == DXGIFormat.B8G8R8A8UNorm ) - { - return AddMipMaps( input, mipMaps ); - } - - if( input.Meta.Format.IsCompressed() ) - { - input = input.Decompress( DXGIFormat.B8G8R8A8UNorm ); - } - else - { - input = input.Convert( DXGIFormat.B8G8R8A8UNorm ); - } - - return AddMipMaps( input, mipMaps ); - } - - private static ScratchImage CreateCompressed( ScratchImage input, bool mipMaps, bool bc7 ) - { - var format = bc7 ? DXGIFormat.BC7UNorm : DXGIFormat.BC3UNorm; - if( input.Meta.Format == format ) - { - return input; - } - - if( input.Meta.Format.IsCompressed() ) - { - input = input.Decompress( DXGIFormat.B8G8R8A8UNorm ); - } - - input = AddMipMaps( input, mipMaps ); - - return input.Compress( format, CompressFlags.BC7Quick | CompressFlags.Parallel ); - } - - public void SaveAsTex( string path, TextureSaveType type, bool mipMaps ) - => SaveAs( path, type, mipMaps, true ); - - public void SaveAsDds( string path, TextureSaveType type, bool mipMaps ) - => SaveAs( path, type, mipMaps, false ); + public void SaveAsDds(TextureManager textures, string path, TextureSaveType type, bool mipMaps) + => SaveAs(textures, path, type, mipMaps, false); - public CombinedTexture( Texture left, Texture right ) + public CombinedTexture(Texture left, Texture right) { _left = left; _right = right; _left.Loaded += OnLoaded; _right.Loaded += OnLoaded; - OnLoaded( false ); + OnLoaded(false); } public void Dispose() @@ -211,20 +90,20 @@ public partial class CombinedTexture : IDisposable _right.Loaded -= OnLoaded; } - private void OnLoaded( bool _ ) + private void OnLoaded(bool _) => Update(); public void Update() { Clean(); - if( _left.IsLoaded ) + if (_left.IsLoaded) { - if( _right.IsLoaded ) + if (_right.IsLoaded) { _current = _centerStorage; _mode = Mode.Custom; } - else if( !_invertLeft && _multiplierLeft.IsIdentity ) + else if (!_invertLeft && _multiplierLeft.IsIdentity) { _mode = Mode.LeftCopy; _current = _left; @@ -235,9 +114,9 @@ public partial class CombinedTexture : IDisposable _mode = Mode.Custom; } } - else if( _right.IsLoaded ) + else if (_right.IsLoaded) { - if( !_invertRight && _multiplierRight.IsIdentity ) + if (!_invertRight && _multiplierRight.IsIdentity) { _current = _right; _mode = Mode.RightCopy; @@ -254,6 +133,7 @@ public partial class CombinedTexture : IDisposable { _centerStorage.Dispose(); _current = null; + SaveGuid = Guid.Empty; _mode = Mode.Empty; } -} \ No newline at end of file +} diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index f0c3beca..f84442c1 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -101,7 +101,7 @@ public static class TexFileParser Height = (ushort)meta.Height, Width = (ushort)meta.Width, Depth = (ushort)Math.Max(meta.Depth, 1), - MipLevels = (byte)Math.Min(meta.MipLevels, 12), + MipLevels = (byte)Math.Min(meta.MipLevels, 13), Format = meta.Format.ToTexFormat(), Type = meta.Dimension switch { diff --git a/Penumbra/Import/Textures/Texture.cs b/Penumbra/Import/Textures/Texture.cs index ef8e16fc..aefe72b4 100644 --- a/Penumbra/Import/Textures/Texture.cs +++ b/Penumbra/Import/Textures/Texture.cs @@ -1,135 +1,61 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Numerics; -using Dalamud.Data; -using Dalamud.Interface; -using ImGuiNET; using ImGuiScene; -using Lumina.Data.Files; -using OtterGui; -using OtterGui.Raii; using OtterTex; -using Penumbra.Services; -using Penumbra.String.Classes; -using Penumbra.UI; -using Penumbra.UI.Classes; -using SixLabors.ImageSharp.PixelFormats; -using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; +public enum TextureType +{ + Unknown, + Dds, + Tex, + Png, + Bitmap, +} + public sealed class Texture : IDisposable { - public enum FileType - { - Unknown, - Dds, - Tex, - Png, - Bitmap, - } - // Path to the file we tried to load. public string Path = string.Empty; + // Path for changing paths. + internal string? TmpPath; + // If the load failed, an exception is stored. public Exception? LoadError = null; // The pixels of the main image in RGBA order. // Empty if LoadError != null or Path is empty. - public byte[] RGBAPixels = Array.Empty(); + public byte[] RgbaPixels = Array.Empty(); // The ImGui wrapper to load the image. // null if LoadError != null or Path is empty. public TextureWrap? TextureWrap = null; // The base image in whatever format it has. - public object? BaseImage = null; + public BaseImage BaseImage; // Original File Type. - public FileType Type = FileType.Unknown; + public TextureType Type = TextureType.Unknown; // Whether the file is successfully loaded and drawable. public bool IsLoaded => TextureWrap != null; public DXGIFormat Format - => BaseImage switch - { - ScratchImage s => s.Meta.Format, - TexFile t => t.Header.Format.ToDXGI(), - _ => DXGIFormat.Unknown, - }; + => BaseImage.Format; public int MipMaps - => BaseImage switch - { - ScratchImage s => s.Meta.MipLevels, - TexFile t => t.Header.MipLevels, - _ => 1, - }; - - public void Draw(Vector2 size) - { - if (TextureWrap != null) - { - size = size.X < TextureWrap.Width - ? size with { Y = TextureWrap.Height * size.X / TextureWrap.Width } - : new Vector2(TextureWrap.Width, TextureWrap.Height); - - ImGui.Image(TextureWrap.ImGuiHandle, size); - DrawData(); - } - else if (LoadError != null) - { - ImGui.TextUnformatted("Could not load file:"); - ImGuiUtil.TextColored(Colors.RegexWarningBorder, LoadError.ToString()); - } - } - - public void DrawData() - { - using var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit); - ImGuiUtil.DrawTableColumn("Width"); - ImGuiUtil.DrawTableColumn(TextureWrap!.Width.ToString()); - ImGuiUtil.DrawTableColumn("Height"); - ImGuiUtil.DrawTableColumn(TextureWrap!.Height.ToString()); - ImGuiUtil.DrawTableColumn("File Type"); - ImGuiUtil.DrawTableColumn(Type.ToString()); - ImGuiUtil.DrawTableColumn("Bitmap Size"); - ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(RGBAPixels.Length)} ({RGBAPixels.Length} Bytes)"); - switch (BaseImage) - { - case ScratchImage s: - ImGuiUtil.DrawTableColumn("Format"); - ImGuiUtil.DrawTableColumn(s.Meta.Format.ToString()); - ImGuiUtil.DrawTableColumn("Mip Levels"); - ImGuiUtil.DrawTableColumn(s.Meta.MipLevels.ToString()); - ImGuiUtil.DrawTableColumn("Data Size"); - ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(s.Pixels.Length)} ({s.Pixels.Length} Bytes)"); - ImGuiUtil.DrawTableColumn("Number of Images"); - ImGuiUtil.DrawTableColumn(s.Images.Length.ToString()); - break; - case TexFile t: - ImGuiUtil.DrawTableColumn("Format"); - ImGuiUtil.DrawTableColumn(t.Header.Format.ToString()); - ImGuiUtil.DrawTableColumn("Mip Levels"); - ImGuiUtil.DrawTableColumn(t.Header.MipLevels.ToString()); - ImGuiUtil.DrawTableColumn("Data Size"); - ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(t.ImageData.Length)} ({t.ImageData.Length} Bytes)"); - break; - } - } + => BaseImage.MipMaps; private void Clean() { - RGBAPixels = Array.Empty(); + RgbaPixels = Array.Empty(); TextureWrap?.Dispose(); TextureWrap = null; - (BaseImage as IDisposable)?.Dispose(); - BaseImage = null; - Type = FileType.Unknown; + BaseImage.Dispose(); + BaseImage = new BaseImage(); + Type = TextureType.Unknown; Loaded?.Invoke(false); } @@ -138,9 +64,9 @@ public sealed class Texture : IDisposable public event Action? Loaded; - private void Load(DalamudServices dalamud, string path) + public void Load(TextureManager textures, string path) { - _tmpPath = null; + TmpPath = null; if (path == Path) return; @@ -151,13 +77,9 @@ public sealed class Texture : IDisposable try { - var _ = System.IO.Path.GetExtension(Path).ToLowerInvariant() switch - { - ".dds" => LoadDds(dalamud), - ".png" => LoadPng(dalamud), - ".tex" => LoadTex(dalamud), - _ => throw new Exception($"Extension {System.IO.Path.GetExtension(Path)} unknown."), - }; + (BaseImage, Type) = textures.Load(path); + (RgbaPixels, var width, var height) = BaseImage.GetPixelData(); + TextureWrap = textures.LoadTextureWrap(BaseImage, RgbaPixels); Loaded?.Invoke(true); } catch (Exception e) @@ -167,130 +89,10 @@ public sealed class Texture : IDisposable } } - public void Reload(DalamudServices dalamud) + public void Reload(TextureManager textures) { var path = Path; - Path = string.Empty; - Load(dalamud, path); - } - - private bool LoadDds(DalamudServices dalamud) - { - Type = FileType.Dds; - var scratch = ScratchImage.LoadDDS(Path); - BaseImage = scratch; - var rgba = scratch.GetRGBA(out var f).ThrowIfError(f); - RGBAPixels = rgba.Pixels[..(f.Meta.Width * f.Meta.Height * f.Meta.Format.BitsPerPixel() / 8)].ToArray(); - CreateTextureWrap(dalamud.UiBuilder, f.Meta.Width, f.Meta.Height); - return true; - } - - private bool LoadPng(DalamudServices dalamud) - { - Type = FileType.Png; - BaseImage = null; - using var stream = File.OpenRead(Path); - using var png = Image.Load(stream); - RGBAPixels = new byte[png.Height * png.Width * 4]; - png.CopyPixelDataTo(RGBAPixels); - CreateTextureWrap(dalamud.UiBuilder, png.Width, png.Height); - return true; - } - - private bool LoadTex(DalamudServices dalamud) - { - Type = FileType.Tex; - using var stream = OpenTexStream(dalamud.GameData); - var scratch = TexFileParser.Parse(stream); - BaseImage = scratch; - var rgba = scratch.GetRGBA(out var f).ThrowIfError(f); - RGBAPixels = rgba.Pixels[..(f.Meta.Width * f.Meta.Height * (f.Meta.Format.BitsPerPixel() / 8))].ToArray(); - CreateTextureWrap(dalamud.UiBuilder, scratch.Meta.Width, scratch.Meta.Height); - return true; - } - - private Stream OpenTexStream(DataManager gameData) - { - if (System.IO.Path.IsPathRooted(Path)) - return File.OpenRead(Path); - - var file = gameData.GetFile(Path); - return file != null ? new MemoryStream(file.Data) : throw new Exception($"Unable to obtain \"{Path}\" from game files."); - } - - private void CreateTextureWrap(UiBuilder builder, int width, int height) - => TextureWrap = builder.LoadImageRaw(RGBAPixels, width, height, 4); - - private string? _tmpPath; - - public void PathSelectBox(DalamudServices dalamud, string label, string tooltip, IEnumerable<(string, bool)> paths, int skipPrefix) - { - ImGui.SetNextItemWidth(-0.0001f); - var startPath = Path.Length > 0 ? Path : "Choose a modded texture from this mod here..."; - using var combo = ImRaii.Combo(label, startPath); - if (combo) - foreach (var ((path, game), idx) in paths.WithIndex()) - { - if (game) - { - if (!dalamud.GameData.FileExists(path)) - continue; - } - else if (!File.Exists(path)) - { - continue; - } - - using var id = ImRaii.PushId(idx); - using (var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value(), game)) - { - var p = game ? $"--> {path}" : path[skipPrefix..]; - if (ImGui.Selectable(p, path == startPath) && path != startPath) - Load(dalamud, path); - } - - ImGuiUtil.HoverTooltip(game - ? "This is a game path and refers to an unmanipulated file from your game data." - : "This is a path to a modded file on your file system."); - } - - ImGuiUtil.HoverTooltip(tooltip); - } - - public void PathInputBox(DalamudServices dalamud, string label, string hint, string tooltip, string startPath, FileDialogService fileDialog, - string defaultModImportPath) - { - _tmpPath ??= Path; - using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(UiHelpers.ScaleX3, ImGui.GetStyle().ItemSpacing.Y)); - ImGui.SetNextItemWidth(-2 * ImGui.GetFrameHeight() - 7 * UiHelpers.Scale); - ImGui.InputTextWithHint(label, hint, ref _tmpPath, Utf8GamePath.MaxGamePathLength); - if (ImGui.IsItemDeactivatedAfterEdit()) - Load(dalamud, _tmpPath); - - ImGuiUtil.HoverTooltip(tooltip); - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Folder.ToIconString(), new Vector2(ImGui.GetFrameHeight()), string.Empty, false, - true)) - { - if (defaultModImportPath.Length > 0) - startPath = defaultModImportPath; - - var texture = this; - - void UpdatePath(bool success, List paths) - { - if (success && paths.Count > 0) - texture.Load(dalamud, paths[0]); - } - - fileDialog.OpenFilePicker("Open Image...", "Textures{.png,.dds,.tex}", UpdatePath, 1, startPath, false); - } - - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), new Vector2(ImGui.GetFrameHeight()), - "Reload the currently selected path.", false, - true)) - Reload(dalamud); + Path = string.Empty; + Load(textures, path); } } diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs new file mode 100644 index 00000000..b077f6fd --- /dev/null +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -0,0 +1,139 @@ +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using Dalamud.Interface; +using ImGuiNET; +using Lumina.Data.Files; +using OtterGui; +using OtterGui.Raii; +using OtterTex; +using Penumbra.String.Classes; +using Penumbra.UI; +using Penumbra.UI.Classes; + +namespace Penumbra.Import.Textures; + +public static class TextureDrawer +{ + public static void Draw(Texture texture, Vector2 size) + { + if (texture.TextureWrap != null) + { + size = size.X < texture.TextureWrap.Width + ? size with { Y = texture.TextureWrap.Height * size.X / texture.TextureWrap.Width } + : new Vector2(texture.TextureWrap.Width, texture.TextureWrap.Height); + + ImGui.Image(texture.TextureWrap.ImGuiHandle, size); + DrawData(texture); + } + else if (texture.LoadError != null) + { + ImGui.TextUnformatted("Could not load file:"); + ImGuiUtil.TextColored(Colors.RegexWarningBorder, texture.LoadError.ToString()); + } + } + + public static void PathSelectBox(TextureManager textures, Texture current, string label, string tooltip, IEnumerable<(string, bool)> paths, + int skipPrefix) + { + ImGui.SetNextItemWidth(-0.0001f); + var startPath = current.Path.Length > 0 ? current.Path : "Choose a modded texture from this mod here..."; + using var combo = ImRaii.Combo(label, startPath); + if (combo) + foreach (var ((path, game), idx) in paths.WithIndex()) + { + if (game) + { + if (!textures.GameFileExists(path)) + continue; + } + else if (!File.Exists(path)) + { + continue; + } + + using var id = ImRaii.PushId(idx); + using (var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value(), game)) + { + var p = game ? $"--> {path}" : path[skipPrefix..]; + if (ImGui.Selectable(p, path == startPath) && path != startPath) + current.Load(textures, path); + } + + ImGuiUtil.HoverTooltip(game + ? "This is a game path and refers to an unmanipulated file from your game data." + : "This is a path to a modded file on your file system."); + } + + ImGuiUtil.HoverTooltip(tooltip); + } + + public static void PathInputBox(TextureManager textures, Texture current, ref string? tmpPath, string label, string hint, string tooltip, + string startPath, FileDialogService fileDialog, string defaultModImportPath) + { + tmpPath ??= current.Path; + using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, + new Vector2(UiHelpers.ScaleX3, ImGui.GetStyle().ItemSpacing.Y)); + ImGui.SetNextItemWidth(-2 * ImGui.GetFrameHeight() - 7 * UiHelpers.Scale); + ImGui.InputTextWithHint(label, hint, ref tmpPath, Utf8GamePath.MaxGamePathLength); + if (ImGui.IsItemDeactivatedAfterEdit()) + current.Load(textures, tmpPath); + + ImGuiUtil.HoverTooltip(tooltip); + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Folder.ToIconString(), new Vector2(ImGui.GetFrameHeight()), string.Empty, false, + true)) + { + if (defaultModImportPath.Length > 0) + startPath = defaultModImportPath; + + void UpdatePath(bool success, List paths) + { + if (success && paths.Count > 0) + current.Load(textures, paths[0]); + } + + fileDialog.OpenFilePicker("Open Image...", "Textures{.png,.dds,.tex}", UpdatePath, 1, startPath, false); + } + + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), new Vector2(ImGui.GetFrameHeight()), + "Reload the currently selected path.", false, + true)) + current.Reload(textures); + } + + private static void DrawData(Texture texture) + { + using var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit); + ImGuiUtil.DrawTableColumn("Width"); + ImGuiUtil.DrawTableColumn(texture.TextureWrap!.Width.ToString()); + ImGuiUtil.DrawTableColumn("Height"); + ImGuiUtil.DrawTableColumn(texture.TextureWrap!.Height.ToString()); + ImGuiUtil.DrawTableColumn("File Type"); + ImGuiUtil.DrawTableColumn(texture.Type.ToString()); + ImGuiUtil.DrawTableColumn("Bitmap Size"); + ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(texture.RgbaPixels.Length)} ({texture.RgbaPixels.Length} Bytes)"); + switch (texture.BaseImage.Image) + { + case ScratchImage s: + ImGuiUtil.DrawTableColumn("Format"); + ImGuiUtil.DrawTableColumn(s.Meta.Format.ToString()); + ImGuiUtil.DrawTableColumn("Mip Levels"); + ImGuiUtil.DrawTableColumn(s.Meta.MipLevels.ToString()); + ImGuiUtil.DrawTableColumn("Data Size"); + ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(s.Pixels.Length)} ({s.Pixels.Length} Bytes)"); + ImGuiUtil.DrawTableColumn("Number of Images"); + ImGuiUtil.DrawTableColumn(s.Images.Length.ToString()); + break; + case TexFile t: + ImGuiUtil.DrawTableColumn("Format"); + ImGuiUtil.DrawTableColumn(t.Header.Format.ToString()); + ImGuiUtil.DrawTableColumn("Mip Levels"); + ImGuiUtil.DrawTableColumn(t.Header.MipLevels.ToString()); + ImGuiUtil.DrawTableColumn("Data Size"); + ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(t.ImageData.Length)} ({t.ImageData.Length} Bytes)"); + break; + } + } +} diff --git a/Penumbra/Import/Textures/TextureImporter.cs b/Penumbra/Import/Textures/TextureImporter.cs deleted file mode 100644 index 74bef485..00000000 --- a/Penumbra/Import/Textures/TextureImporter.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.IO; -using Lumina.Data.Files; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; - -namespace Penumbra.Import.Textures; - -public static class TextureImporter -{ - private static void WriteHeader( byte[] target, int width, int height ) - { - using var mem = new MemoryStream( target ); - using var bw = new BinaryWriter( mem ); - bw.Write( ( uint )TexFile.Attribute.TextureType2D ); - bw.Write( ( uint )TexFile.TextureFormat.B8G8R8A8 ); - bw.Write( ( ushort )width ); - bw.Write( ( ushort )height ); - bw.Write( ( ushort )1 ); - bw.Write( ( ushort )1 ); - bw.Write( 0 ); - bw.Write( 1 ); - bw.Write( 2 ); - bw.Write( 80 ); - for( var i = 1; i < 13; ++i ) - { - bw.Write( 0 ); - } - } - - public static bool RgbaBytesToTex( byte[] rgba, int width, int height, out byte[] texData ) - { - texData = Array.Empty< byte >(); - if( rgba.Length != width * height * 4 ) - { - return false; - } - - texData = new byte[80 + width * height * 4]; - WriteHeader( texData, width, height ); - rgba.CopyTo( texData.AsSpan( 80 ) ); - for( var i = 80; i < texData.Length; i += 4 ) - (texData[ i ], texData[i + 2]) = (texData[ i + 2], texData[i]); - return true; - } - - public static bool PngToTex( string inputFile, out byte[] texData ) - { - using var file = File.OpenRead( inputFile ); - var image = Image.Load< Bgra32 >( file ); - - var buffer = new byte[80 + image.Height * image.Width * 4]; - WriteHeader( buffer, image.Width, image.Height ); - - var span = new Span< byte >( buffer, 80, buffer.Length - 80 ); - image.CopyPixelDataTo( span ); - - texData = buffer; - return true; - } -} \ No newline at end of file diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs new file mode 100644 index 00000000..9ac503df --- /dev/null +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -0,0 +1,438 @@ +using System; +using System.IO; +using System.Linq; +using System.Numerics; +using System.Threading; +using Dalamud.Data; +using Dalamud.Interface; +using ImGuiScene; +using Lumina.Data.Files; +using OtterGui.Log; +using OtterGui.Tasks; +using OtterTex; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using Image = SixLabors.ImageSharp.Image; + +namespace Penumbra.Import.Textures; + +public sealed class TextureManager : AsyncTaskManager +{ + private readonly UiBuilder _uiBuilder; + private readonly DataManager _gameData; + + public TextureManager(Logger logger, UiBuilder uiBuilder, DataManager gameData) + : base(logger) + { + _uiBuilder = uiBuilder; + _gameData = gameData; + } + + public Guid SavePng(string input, string output) + => Enqueue(new SavePngAction(this, input, output)); + + public Guid SavePng(BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) + => Enqueue(new SavePngAction(this, image, path, rgba, width, height)); + + public Guid SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, string output) + => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, input, output)); + + public Guid SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, string path, byte[]? rgba = null, + int width = 0, int height = 0) + => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, image, path, rgba, width, height)); + + private readonly struct ImageInputData + { + private readonly string? _inputPath; + + private readonly BaseImage _image; + private readonly byte[]? _rgba; + private readonly int _width; + private readonly int _height; + + public ImageInputData(string inputPath) + { + _inputPath = inputPath; + _image = new BaseImage(); + _rgba = null; + _width = 0; + _height = 0; + } + + public ImageInputData(BaseImage image, byte[]? rgba = null, int width = 0, int height = 0) + { + _inputPath = null; + _image = image.Width == 0 || image.Height == 0 ? new BaseImage() : image; + _rgba = rgba?.ToArray(); + _width = width; + _height = height; + } + + public (BaseImage Image, byte[]? Rgba, int Width, int Height) GetData(TextureManager textures) + { + if (_inputPath == null) + return (_image, _rgba, _width, _height); + + if (!File.Exists(_inputPath)) + throw new FileNotFoundException($"Input texture file {_inputPath} not Found.", _inputPath); + + var (image, _) = textures.Load(_inputPath); + return (image, null, 0, 0); + } + + public bool Equals(ImageInputData rhs) + { + if (_inputPath != null) + return string.Equals(_inputPath, rhs._inputPath, StringComparison.OrdinalIgnoreCase); + + if (rhs._inputPath != null) + return false; + + if (_image.Image != null) + return ReferenceEquals(_image.Image, rhs._image.Image); + + return _width == rhs._width && _height == rhs._height && _rgba != null && rhs._rgba != null && _rgba.SequenceEqual(rhs._rgba); + } + + public override string ToString() + => _inputPath + ?? _image.Type switch + { + TextureType.Unknown => $"Custom {_width} x {_height} RGBA Image", + TextureType.Dds => $"Custom {_width} x {_height} {_image.Format} Image", + TextureType.Tex => $"Custom {_width} x {_height} {_image.Format} Image", + TextureType.Png => $"Custom {_width} x {_height} .png Image", + TextureType.Bitmap => $"Custom {_width} x {_height} RGBA Image", + _ => "Unknown Image", + }; + } + + private class SavePngAction : IAction + { + private readonly TextureManager _textures; + private readonly string _outputPath; + private readonly ImageInputData _input; + + public SavePngAction(TextureManager textures, string input, string output) + { + _textures = textures; + _input = new ImageInputData(input); + _outputPath = output; + } + + public SavePngAction(TextureManager textures, BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) + { + _textures = textures; + _input = new ImageInputData(image, rgba, width, height); + _outputPath = path; + } + + public void Execute(CancellationToken cancel) + { + _textures.Logger.Information($"[{nameof(TextureManager)}] Saving {_input} as .png to {_outputPath}..."); + var (image, rgba, width, height) = _input.GetData(_textures); + cancel.ThrowIfCancellationRequested(); + Image? png = null; + if (image.Type is TextureType.Unknown) + { + if (rgba != null && width > 0 && height > 0) + png = ConvertToPng(rgba, width, height).AsPng!; + } + else + { + png = ConvertToPng(image, cancel, rgba).AsPng!; + } + + cancel.ThrowIfCancellationRequested(); + png?.SaveAsync(_outputPath, cancel).Wait(cancel); + } + + public bool Equals(IAction? other) + { + if (other is not SavePngAction rhs) + return false; + + return string.Equals(_outputPath, rhs._outputPath, StringComparison.OrdinalIgnoreCase) && _input.Equals(rhs._input); + } + } + + private class SaveAsAction : IAction + { + private readonly TextureManager _textures; + private readonly string _outputPath; + private readonly ImageInputData _input; + private readonly CombinedTexture.TextureSaveType _type; + private readonly bool _mipMaps; + private readonly bool _asTex; + + public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, + string output) + { + _textures = textures; + _input = new ImageInputData(input); + _outputPath = output; + _type = type; + _mipMaps = mipMaps; + _asTex = asTex; + } + + public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, + string path, + byte[]? rgba = null, int width = 0, int height = 0) + { + _textures = textures; + _input = new ImageInputData(image, rgba, width, height); + _outputPath = path; + _type = type; + _mipMaps = mipMaps; + _asTex = asTex; + } + + public void Execute(CancellationToken cancel) + { + _textures.Logger.Information( + $"[{nameof(TextureManager)}] Saving {_input} as {_type} {(_asTex ? ".tex" : ".dds")} file{(_mipMaps ? " with mip maps" : string.Empty)} to {_outputPath}..."); + var (image, rgba, width, height) = _input.GetData(_textures); + if (image.Type is TextureType.Unknown) + { + if (rgba != null && width > 0 && height > 0) + image = ConvertToDds(rgba, width, height); + else + return; + } + + var dds = _type switch + { + CombinedTexture.TextureSaveType.AsIs when image.Type is TextureType.Png => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, + width, height), + CombinedTexture.TextureSaveType.AsIs when image.Type is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), + CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC7 => + ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), + _ => throw new Exception("Wrong save type."), + }; + + cancel.ThrowIfCancellationRequested(); + if (_asTex) + SaveTex(_outputPath, dds.AsDds!); + else + dds.AsDds!.SaveDDS(_outputPath); + } + + public bool Equals(IAction? other) + { + if (other is not SaveAsAction rhs) + return false; + + return _type == rhs._type + && _mipMaps == rhs._mipMaps + && _asTex == rhs._asTex + && string.Equals(_outputPath, rhs._outputPath, StringComparison.OrdinalIgnoreCase) + && _input.Equals(rhs._input); + } + } + + /// Load a texture wrap for a given image. + public TextureWrap LoadTextureWrap(BaseImage image, byte[]? rgba = null, int width = 0, int height = 0) + { + (rgba, width, height) = GetData(image, rgba, width, height); + return LoadTextureWrap(rgba, width, height); + } + + /// Load a texture wrap for a given image. + public TextureWrap LoadTextureWrap(byte[] rgba, int width, int height) + => _uiBuilder.LoadImageRaw(rgba, width, height, 4); + + /// Load any supported file from game data or drive depending on extension and if the path is rooted. + public (BaseImage, TextureType) Load(string path) + => Path.GetExtension(path).ToLowerInvariant() switch + { + ".dds" => (LoadDds(path), TextureType.Dds), + ".png" => (LoadPng(path), TextureType.Png), + ".tex" => (LoadTex(path), TextureType.Tex), + _ => throw new Exception($"Extension {Path.GetExtension(path)} unknown."), + }; + + /// Load a .tex file from game data or drive depending on if the path is rooted. + public BaseImage LoadTex(string path) + { + using var stream = OpenTexStream(path); + return TexFileParser.Parse(stream); + } + + /// Load a .dds file from drive using OtterTex. + public BaseImage LoadDds(string path) + => ScratchImage.LoadDDS(path); + + /// Load a .png file from drive using ImageSharp. + public BaseImage LoadPng(string path) + { + using var stream = File.OpenRead(path); + return Image.Load(stream); + } + + /// Convert an existing image to .png. Does not create a deep copy of an existing .png and just returns the existing one. + public static BaseImage ConvertToPng(BaseImage input, CancellationToken cancel, byte[]? rgba = null, int width = 0, int height = 0) + { + switch (input.Type) + { + case TextureType.Png: return input; + case TextureType.Dds: + { + (rgba, width, height) = GetData(input, rgba, width, height); + cancel.ThrowIfCancellationRequested(); + return ConvertToPng(rgba, width, height); + } + default: return new BaseImage(); + } + } + + /// Convert an existing image to a RGBA32 .dds. Does not create a deep copy of an existing RGBA32 dds and just returns the existing one. + public static BaseImage ConvertToRgbaDds(BaseImage input, bool mipMaps, CancellationToken cancel, byte[]? rgba = null, int width = 0, + int height = 0) + { + switch (input.Type) + { + case TextureType.Png: + { + (rgba, width, height) = GetData(input, rgba, width, height); + cancel.ThrowIfCancellationRequested(); + var dds = ConvertToDds(rgba, width, height).AsDds!; + cancel.ThrowIfCancellationRequested(); + return AddMipMaps(dds, mipMaps); + } + case TextureType.Dds: + { + var scratch = input.AsDds!; + if (rgba == null) + return CreateUncompressed(scratch, mipMaps, cancel); + + (rgba, width, height) = GetData(input, rgba, width, height); + cancel.ThrowIfCancellationRequested(); + var dds = ConvertToDds(rgba, width, height).AsDds!; + cancel.ThrowIfCancellationRequested(); + return AddMipMaps(dds, mipMaps); + } + default: return new BaseImage(); + } + } + + /// Convert an existing image to a block compressed .dds. Does not create a deep copy of an existing dds of the correct format and just returns the existing one. + public static BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, CancellationToken cancel, byte[]? rgba = null, + int width = 0, int height = 0) + { + switch (input.Type) + { + case TextureType.Png: + { + (rgba, width, height) = GetData(input, rgba, width, height); + cancel.ThrowIfCancellationRequested(); + var dds = ConvertToDds(rgba, width, height).AsDds!; + cancel.ThrowIfCancellationRequested(); + return CreateCompressed(dds, mipMaps, bc7, cancel); + } + case TextureType.Dds: + { + var scratch = input.AsDds!; + return CreateCompressed(scratch, mipMaps, bc7, cancel); + } + default: return new BaseImage(); + } + } + + public static BaseImage ConvertToPng(byte[] rgba, int width, int height) + => Image.LoadPixelData(rgba, width, height); + + public static BaseImage ConvertToDds(byte[] rgba, int width, int height) + { + var scratch = ScratchImage.FromRGBA(rgba, width, height, out var i).ThrowIfError(i); + return scratch.Convert(DXGIFormat.B8G8R8A8UNorm); + } + + public bool GameFileExists(string path) + => _gameData.FileExists(path); + + /// Add up to 13 mip maps to the input if mip maps is true, otherwise return input. + public static ScratchImage AddMipMaps(ScratchImage input, bool mipMaps) + { + var numMips = mipMaps ? Math.Min(13, 1 + BitOperations.Log2((uint)Math.Max(input.Meta.Width, input.Meta.Height))) : 1; + if (numMips == input.Meta.MipLevels) + return input; + + var ec = input.GenerateMipMaps(out var ret, numMips, + (Dalamud.Utility.Util.IsLinux() ? FilterFlags.ForceNonWIC : 0) | FilterFlags.SeparateAlpha); + if (ec != ErrorCode.Ok) + throw new Exception($"Could not create the requested {numMips} mip maps, maybe retry with the top-right checkbox unchecked:\n{ec}"); + + return ret; + } + + /// Create an uncompressed .dds (optionally with mip maps) from the input. Returns input (+ mipmaps) if it is already uncompressed. + public static ScratchImage CreateUncompressed(ScratchImage input, bool mipMaps, CancellationToken cancel) + { + if (input.Meta.Format == DXGIFormat.B8G8R8A8UNorm) + return AddMipMaps(input, mipMaps); + + input = input.Meta.Format.IsCompressed() + ? input.Decompress(DXGIFormat.B8G8R8A8UNorm) + : input.Convert(DXGIFormat.B8G8R8A8UNorm); + cancel.ThrowIfCancellationRequested(); + return AddMipMaps(input, mipMaps); + } + + /// Create a BC3 or BC7 block-compressed .dds from the input (optionally with mipmaps). Returns input (+ mipmaps) if it is already the correct format. + public static ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, bool bc7, CancellationToken cancel) + { + var format = bc7 ? DXGIFormat.BC7UNorm : DXGIFormat.BC3UNorm; + if (input.Meta.Format == format) + return input; + + if (input.Meta.Format.IsCompressed()) + { + input = input.Decompress(DXGIFormat.B8G8R8A8UNorm); + cancel.ThrowIfCancellationRequested(); + } + + input = AddMipMaps(input, mipMaps); + cancel.ThrowIfCancellationRequested(); + return input.Compress(format, CompressFlags.BC7Quick | CompressFlags.Parallel); + } + + + /// Load a tex file either from game data if the path is not rooted, or from drive if it is rooted. + private Stream OpenTexStream(string path) + { + if (Path.IsPathRooted(path)) + return File.OpenRead(path); + + var file = _gameData.GetFile(path); + return file != null ? new MemoryStream(file.Data) : throw new Exception($"Unable to obtain \"{path}\" from game files."); + } + + /// Obtain the checked rgba data, width and height for an image. + private static (byte[], int, int) GetData(BaseImage input, byte[]? rgba, int width, int height) + { + if (rgba == null) + return input.GetPixelData(); + + if (width == 0 || height == 0) + (width, height) = input.Dimensions; + return width * height * 4 != rgba.Length + ? input.GetPixelData() + : (rgba, width, height); + } + + /// Save a .dds file as .tex file with appropriately changed header. + public static void SaveTex(string path, ScratchImage input) + { + var header = input.ToTexHeader(); + if (header.Format == TexFile.TextureFormat.Unknown) + throw new Exception($"Could not save tex file with format {input.Meta.Format}, not convertible to a valid .tex format."); + + using var stream = File.Open(path, File.Exists(path) ? FileMode.Truncate : FileMode.CreateNew); + using var w = new BinaryWriter(stream); + header.Write(w); + w.Write(input.Pixels); + } +} diff --git a/Penumbra/Mods/Editor/ModBackup.cs b/Penumbra/Mods/Editor/ModBackup.cs index cbb98a38..eb15de87 100644 --- a/Penumbra/Mods/Editor/ModBackup.cs +++ b/Penumbra/Mods/Editor/ModBackup.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Threading.Tasks; -using OtterGui; +using OtterGui.Tasks; using Penumbra.Mods.Manager; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 1726eab2..62d87815 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading.Tasks; using Dalamud.Interface.Internal.Notifications; using OtterGui; +using OtterGui.Tasks; using Penumbra.Mods.Manager; using Penumbra.String.Classes; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index fbbaab51..b291e392 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -22,7 +22,8 @@ using Penumbra.Collections.Manager; using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; - +using OtterGui.Tasks; + namespace Penumbra; public class Penumbra : IDalamudPlugin diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 782d40a0..f0864b97 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -7,6 +7,7 @@ using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.GameData; using Penumbra.GameData.Data; +using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.ResourceTree; @@ -173,7 +174,8 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddApi(this IServiceCollection services) => services.AddSingleton() diff --git a/Penumbra/Services/ServiceWrapper.cs b/Penumbra/Services/ServiceWrapper.cs index 783acc49..ca1e3624 100644 --- a/Penumbra/Services/ServiceWrapper.cs +++ b/Penumbra/Services/ServiceWrapper.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using OtterGui; +using OtterGui.Tasks; using Penumbra.Util; namespace Penumbra.Services; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index f96ab4da..6fd7b130 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -5,6 +5,7 @@ using System.Numerics; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Tasks; using OtterTex; using Penumbra.Import.Textures; @@ -12,13 +13,14 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { + private readonly TextureManager _textures; + private readonly Texture _left = new(); private readonly Texture _right = new(); private readonly CombinedTexture _center; private bool _overlayCollapsed = true; - - private bool _addMipMaps = true; + private bool _addMipMaps = true; private int _currentSaveAs; private static readonly (string, string)[] SaveAsStrings = @@ -42,13 +44,13 @@ public partial class ModEditWindow ImGuiUtil.DrawTextButton(label, new Vector2(-1, 0), ImGui.GetColorU32(ImGuiCol.FrameBg)); ImGui.NewLine(); - tex.PathInputBox(_dalamud, "##input", "Import Image...", "Can import game paths as well as your own files.", _mod!.ModPath.FullName, - _fileDialog, _config.DefaultModImportPath); + TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", + "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); var files = _editor.Files.Tex.SelectMany(f => f.SubModUsage.Select(p => (p.Item2.ToString(), true)) .Prepend((f.File.FullName, false))); - tex.PathSelectBox(_dalamud, "##combo", - "Select the textures included in this mod on your drive or the ones they replace from the game files.", - files, _mod.ModPath.FullName.Length + 1); + TextureDrawer.PathSelectBox(_textures, tex, "##combo", + "Select the textures included in this mod on your drive or the ones they replace from the game files.", files, + _mod.ModPath.FullName.Length + 1); if (tex == _left) _center.DrawMatrixInputLeft(size.X); @@ -58,7 +60,7 @@ public partial class ModEditWindow ImGui.NewLine(); using var child2 = ImRaii.Child("image"); if (child2) - tex.Draw(imageSize); + TextureDrawer.Draw(tex, imageSize); } private void SaveAsCombo() @@ -105,7 +107,7 @@ public partial class ModEditWindow _fileDialog.OpenSavePicker("Save Texture as TEX...", ".tex", fileName, ".tex", (a, b) => { if (a) - _center.SaveAsTex(b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + _center.SaveAsTex(_textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); }, _mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } @@ -116,7 +118,7 @@ public partial class ModEditWindow _fileDialog.OpenSavePicker("Save Texture as DDS...", ".dds", fileName, ".dds", (a, b) => { if (a) - _center.SaveAsDds(b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + _center.SaveAsDds(_textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); }, _mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } @@ -129,20 +131,20 @@ public partial class ModEditWindow _fileDialog.OpenSavePicker("Save Texture as PNG...", ".png", fileName, ".png", (a, b) => { if (a) - _center.SaveAsPng(b); + _center.SaveAsPng(_textures, b); }, _mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } - if (_left.Type is Texture.FileType.Tex && _center.IsLeftCopy) + if (_left.Type is TextureType.Tex && _center.IsLeftCopy) { var buttonSize = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X * 2) / 3, 0); if (ImGuiUtil.DrawDisabledButton("Convert to BC7", buttonSize, "This converts the texture to BC7 format in place. This is not revertible.", _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) { - _center.SaveAsTex(_left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); - _left.Reload(_dalamud); + _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); + ReloadConvertedSubscribe(_left.Path, _center.SaveGuid); } ImGui.SameLine(); @@ -150,8 +152,8 @@ public partial class ModEditWindow "This converts the texture to BC3 format in place. This is not revertible.", _left.Format is DXGIFormat.BC3Typeless or DXGIFormat.BC3UNorm or DXGIFormat.BC3UNormSRGB)) { - _center.SaveAsTex(_left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); - _left.Reload(_dalamud); + _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); + ReloadConvertedSubscribe(_left.Path, _center.SaveGuid); } ImGui.SameLine(); @@ -159,27 +161,55 @@ public partial class ModEditWindow "This converts the texture to RGBA format in place. This is not revertible.", _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) { - _center.SaveAsTex(_left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); - _left.Reload(_dalamud); + _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); + ReloadConvertedSubscribe(_left.Path, _center.SaveGuid); } } else { ImGui.NewLine(); } + ImGui.NewLine(); } - if (_center.SaveException != null) + if (_center.SaveGuid != Guid.Empty) { - ImGui.TextUnformatted("Could not save file:"); - using var color = ImRaii.PushColor(ImGuiCol.Text, 0xFF0000FF); - ImGuiUtil.TextWrapped(_center.SaveException.ToString()); + var state = _textures.GetState(_center.SaveGuid, out var saveException, out _, out _); + if (saveException != null) + { + ImGui.TextUnformatted("Could not save file:"); + using var color = ImRaii.PushColor(ImGuiCol.Text, 0xFF0000FF); + ImGuiUtil.TextWrapped(saveException.ToString()); + } + else if (state == ActionState.Running) + { + ImGui.TextUnformatted("Computing..."); + } } using var child2 = ImRaii.Child("image"); if (child2) - _center.Draw(_dalamud.UiBuilder, imageSize); + _center.Draw(_textures, imageSize); + } + + + private void ReloadConvertedSubscribe(string path, Guid guid) + { + void Reload(Guid eventGuid, ActionState state, Exception? ex) + { + if (guid != eventGuid) + return; + + if (_left.Path != path) + return; + + if (state is ActionState.Succeeded) + _dalamud.Framework.RunOnFrameworkThread(() => _left.Reload(_textures)); + _textures.Finished -= Reload; + } + + _textures.Finished += Reload; } private Vector2 GetChildWidth() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index b6051136..93d28b85 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -521,7 +521,7 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, DataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, UiBuilder uiBuilder, DalamudServices dalamud, ModMergeTab modMergeTab, - CommunicatorService communicator) + CommunicatorService communicator, TextureManager textures) : base(WindowBaseLabel) { _performance = performance; @@ -534,6 +534,7 @@ public partial class ModEditWindow : Window, IDisposable _dalamud = dalamud; _modMergeTab = modMergeTab; _communicator = communicator; + _textures = textures; _fileDialog = fileDialog; _materialTab = new FileEditor(this, gameData, config, _fileDialog, "Materials", ".mtrl", () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, From af93c2aca9bfa7fa2679231c3a690b83ff09b2b0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Aug 2023 14:32:02 +0200 Subject: [PATCH 0012/1381] Revert CS change. --- Penumbra.GameData | 2 +- Penumbra/UI/Tabs/DebugTab.cs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 9eb60aa0..e5b733c6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 9eb60aa0fdaad4a10af2edd77b154a20c7647ce4 +Subproject commit e5b733c6fcc5436c8f767dd99a37e5e8c16b4fc8 diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index ee12e8a2..066aec6c 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -500,13 +500,11 @@ public class DebugTab : Window, ITab if (agent->Data != null) { - // TODO fix when updated in CS. - var characterData = (AgentBannerInterface.Storage.CharacterData*)((byte*)agent->Data + 0x20); using var table = Table("###PBannerTable", 2, ImGuiTableFlags.SizingFixedFit); if (table) for (var i = 0; i < 8; ++i) { - ref var c = ref *(characterData + i); + ref var c = ref agent->Data->CharacterArraySpan[i]; ImGuiUtil.DrawTableColumn($"Character {i}"); var name = c.Name1.ToString(); ImGuiUtil.DrawTableColumn(name.Length == 0 ? "NULL" : $"{name} ({c.WorldId})"); From 6e11b36401c7cc248fc627d044d42dc78515971c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Aug 2023 16:55:43 +0200 Subject: [PATCH 0013/1381] Add Texture Conversion IPC and use texture tasks. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra/Api/IpcTester.cs | 76 ++++++- Penumbra/Api/PenumbraApi.cs | 44 +++- Penumbra/Api/PenumbraIpcProviders.cs | 13 ++ Penumbra/Import/Textures/CombinedTexture.cs | 9 +- Penumbra/Import/Textures/TextureManager.cs | 196 +++++++++++------- .../AdvancedWindow/ModEditWindow.Textures.cs | 40 ++-- Penumbra/UI/Tabs/DebugTab.cs | 32 ++- 9 files changed, 305 insertions(+), 109 deletions(-) diff --git a/OtterGui b/OtterGui index 8d61845c..9dad9558 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 8d61845cd900fc0a3b58d475c43303b13c1165f4 +Subproject commit 9dad955808831a5d154d778d1123acbe648c42ac diff --git a/Penumbra.Api b/Penumbra.Api index 983c98f7..623e802b 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 983c98f74e7cd052b21f6ca35ef0ceaa9b388964 +Subproject commit 623e802bbc18496aab4030b444154a5b015093c2 diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index d1124847..fea91b0e 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -9,6 +9,8 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Numerics; +using System.Reflection.Metadata.Ecma335; +using System.Threading.Tasks; using Dalamud.Utility; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; @@ -19,7 +21,6 @@ using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; using Penumbra.Collections.Manager; -using Penumbra.Util; namespace Penumbra.Api; @@ -38,6 +39,7 @@ public class IpcTester : IDisposable private readonly Meta _meta; private readonly Mods _mods; private readonly ModSettings _modSettings; + private readonly Editing _editing; private readonly Temporary _temporary; public IpcTester(Configuration config, DalamudServices dalamud, PenumbraIpcProviders ipcProviders, ModManager modManager, @@ -54,6 +56,7 @@ public class IpcTester : IDisposable _meta = new Meta(dalamud.PluginInterface); _mods = new Mods(dalamud.PluginInterface); _modSettings = new ModSettings(dalamud.PluginInterface); + _editing = new Editing(dalamud.PluginInterface); _temporary = new Temporary(dalamud.PluginInterface, modManager, collections, tempMods, tempCollections, saveService, config); UnsubscribeEvents(); } @@ -74,6 +77,7 @@ public class IpcTester : IDisposable _meta.Draw(); _mods.Draw(); _modSettings.Draw(); + _editing.Draw(); _temporary.Draw(); _temporary.DrawCollections(); _temporary.DrawMods(); @@ -402,9 +406,9 @@ public class IpcTester : IDisposable private string _lastRedrawnString = "None"; public Redrawing(DalamudServices dalamud) - { + { _dalamud = dalamud; - Redrawn = Ipc.GameObjectRedrawn.Subscriber(_dalamud.PluginInterface, SetLastRedrawn); + Redrawn = Ipc.GameObjectRedrawn.Subscriber(_dalamud.PluginInterface, SetLastRedrawn); } public void Draw() @@ -1149,6 +1153,72 @@ public class IpcTester : IDisposable } } + private class Editing + { + private readonly DalamudPluginInterface _pi; + + private string _inputPath = string.Empty; + private string _inputPath2 = string.Empty; + private string _outputPath = string.Empty; + private string _outputPath2 = string.Empty; + + private TextureType _typeSelector; + private bool _mipMaps = true; + + private Task? _task1; + private Task? _task2; + + public Editing(DalamudPluginInterface pi) + => _pi = pi; + + public void Draw() + { + using var _ = ImRaii.TreeNode("Editing"); + if (!_) + return; + + ImGui.InputTextWithHint("##inputPath", "Input Texture Path...", ref _inputPath, 256); + ImGui.InputTextWithHint("##outputPath", "Output Texture Path...", ref _outputPath, 256); + ImGui.InputTextWithHint("##inputPath2", "Input Texture Path 2...", ref _inputPath2, 256); + ImGui.InputTextWithHint("##outputPath2", "Output Texture Path 2...", ref _outputPath2, 256); + TypeCombo(); + ImGui.Checkbox("Add MipMaps", ref _mipMaps); + + using var table = ImRaii.Table("...", 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + DrawIntro(Ipc.ConvertTextureFile.Label, "Convert Texture 1"); + if (ImGuiUtil.DrawDisabledButton("Save 1", Vector2.Zero, string.Empty, _task1 is { IsCompleted: false })) + _task1 = Ipc.ConvertTextureFile.Subscriber(_pi).Invoke(_inputPath, _outputPath, _typeSelector, _mipMaps); + ImGui.SameLine(); + ImGui.TextUnformatted(_task1 == null ? "Not Initiated" : _task1.Status.ToString()); + if (ImGui.IsItemHovered() && _task1?.Status == TaskStatus.Faulted) + ImGui.SetTooltip(_task1.Exception?.ToString()); + + DrawIntro(Ipc.ConvertTextureFile.Label, "Convert Texture 2"); + if (ImGuiUtil.DrawDisabledButton("Save 2", Vector2.Zero, string.Empty, _task2 is { IsCompleted: false })) + _task2 = Ipc.ConvertTextureFile.Subscriber(_pi).Invoke(_inputPath2, _outputPath2, _typeSelector, _mipMaps); + ImGui.SameLine(); + ImGui.TextUnformatted(_task2 == null ? "Not Initiated" : _task2.Status.ToString()); + if (ImGui.IsItemHovered() && _task2?.Status == TaskStatus.Faulted) + ImGui.SetTooltip(_task2.Exception?.ToString()); + } + + private void TypeCombo() + { + using var combo = ImRaii.Combo("Convert To", _typeSelector.ToString()); + if (!combo) + return; + + foreach (var value in Enum.GetValues()) + { + if (ImGui.Selectable(value.ToString(), _typeSelector == value)) + _typeSelector = value; + } + } + } + private class Temporary { private readonly DalamudPluginInterface _pi; diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 9b7e6410..140a928b 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -8,11 +8,13 @@ using Penumbra.Interop.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Api.Enums; using Penumbra.GameData.Actors; @@ -23,15 +25,17 @@ using Penumbra.String.Classes; using Penumbra.Services; using Penumbra.Collections.Manager; using Penumbra.Communication; +using Penumbra.Import.Textures; using Penumbra.Interop.Services; using Penumbra.UI; +using TextureType = Penumbra.Api.Enums.TextureType; namespace Penumbra.Api; public class PenumbraApi : IDisposable, IPenumbraApi { public (int, int) ApiVersion - => (4, 20); + => (4, 21); public event Action? PreSettingsPanelDraw { @@ -124,12 +128,13 @@ public class PenumbraApi : IDisposable, IPenumbraApi private RedrawService _redrawService; private ModFileSystem _modFileSystem; private ConfigWindow _configWindow; + private TextureManager _textureManager; public unsafe PenumbraApi(CommunicatorService communicator, ModManager modManager, ResourceLoader resourceLoader, Configuration config, CollectionManager collectionManager, DalamudServices dalamud, TempCollectionManager tempCollections, TempModManager tempMods, ActorService actors, CollectionResolver collectionResolver, CutsceneService cutsceneService, ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, ModFileSystem modFileSystem, - ConfigWindow configWindow) + ConfigWindow configWindow, TextureManager textureManager) { _communicator = communicator; _modManager = modManager; @@ -147,6 +152,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _redrawService = redrawService; _modFileSystem = modFileSystem; _configWindow = configWindow; + _textureManager = textureManager; _lumina = _dalamud.GameData.GameData; _resourceLoader.ResourceLoaded += OnResourceLoaded; @@ -179,6 +185,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _redrawService = null!; _modFileSystem = null!; _configWindow = null!; + _textureManager = null!; } public event ChangedItemClick? ChangedItemClicked @@ -992,6 +999,39 @@ public class PenumbraApi : IDisposable, IPenumbraApi return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); } + public Task ConvertTextureFile(string inputFile, string outputFile, TextureType textureType, bool mipMaps) + => textureType switch + { + TextureType.Png => _textureManager.SavePng(inputFile, outputFile), + TextureType.AsIsTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, inputFile, outputFile), + TextureType.AsIsDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, inputFile, outputFile), + TextureType.RgbaTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, inputFile, outputFile), + TextureType.RgbaDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, false, inputFile, outputFile), + TextureType.Bc3Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, true, inputFile, outputFile), + TextureType.Bc3Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, inputFile, outputFile), + TextureType.Bc7Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, inputFile, outputFile), + TextureType.Bc7Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, inputFile, outputFile), + _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), + }; + + // @formatter:off + public Task ConvertTextureData(byte[] rgbaData, int width, string outputFile, TextureType textureType, bool mipMaps) + => textureType switch + { + TextureType.Png => _textureManager.SavePng(new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.AsIsTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.AsIsDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.RgbaTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.RgbaDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc3Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc3Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc7Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc7Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), + }; + // @formatter:on + + // TODO: cleanup when incrementing API public string GetMetaManipulations(string characterName) => GetMetaManipulations(characterName, ushort.MaxValue); diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 7ccd7e20..73f87b94 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -3,6 +3,7 @@ using Dalamud.Plugin; using Penumbra.GameData.Enums; using System; using System.Collections.Generic; +using System.Threading.Tasks; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; using Penumbra.Collections.Manager; @@ -105,6 +106,10 @@ public class PenumbraIpcProviders : IDisposable internal readonly EventProvider ModSettingChanged; internal readonly FuncProvider CopyModSettings; + // Editing + internal readonly FuncProvider ConvertTextureFile; + internal readonly FuncProvider ConvertTextureData; + // Temporary internal readonly FuncProvider CreateTemporaryCollection; internal readonly FuncProvider RemoveTemporaryCollection; @@ -219,6 +224,10 @@ public class PenumbraIpcProviders : IDisposable () => Api.ModSettingChanged -= ModSettingChangedEvent); CopyModSettings = Ipc.CopyModSettings.Provider(pi, Api.CopyModSettings); + // Editing + ConvertTextureFile = Ipc.ConvertTextureFile.Provider(pi, Api.ConvertTextureFile); + ConvertTextureData = Ipc.ConvertTextureData.Provider(pi, Api.ConvertTextureData); + // Temporary CreateTemporaryCollection = Ipc.CreateTemporaryCollection.Provider(pi, Api.CreateTemporaryCollection); RemoveTemporaryCollection = Ipc.RemoveTemporaryCollection.Provider(pi, Api.RemoveTemporaryCollection); @@ -335,6 +344,10 @@ public class PenumbraIpcProviders : IDisposable RemoveTemporaryModAll.Dispose(); RemoveTemporaryMod.Dispose(); + // Editing + ConvertTextureFile.Dispose(); + ConvertTextureData.Dispose(); + Disposed.Invoke(); Disposed.Dispose(); } diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index 99303234..c26cb900 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -1,5 +1,6 @@ using System; using System.Numerics; +using System.Threading.Tasks; namespace Penumbra.Import.Textures; @@ -29,7 +30,7 @@ public partial class CombinedTexture : IDisposable private readonly Texture _centerStorage = new(); - public Guid SaveGuid { get; private set; } = Guid.Empty; + public Task SaveTask { get; private set; } = Task.CompletedTask; public bool IsLoaded => _mode != Mode.Empty; @@ -55,7 +56,7 @@ public partial class CombinedTexture : IDisposable if (!IsLoaded || _current == null) return; - SaveGuid = textures.SavePng(_current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, _current.TextureWrap!.Height); + SaveTask = textures.SavePng(_current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, _current.TextureWrap!.Height); } private void SaveAs(TextureManager textures, string path, TextureSaveType type, bool mipMaps, bool writeTex) @@ -63,7 +64,7 @@ public partial class CombinedTexture : IDisposable if (!IsLoaded || _current == null) return; - SaveGuid = textures.SaveAs(type, mipMaps, writeTex, _current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, + SaveTask = textures.SaveAs(type, mipMaps, writeTex, _current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, _current.TextureWrap!.Height); } @@ -133,7 +134,7 @@ public partial class CombinedTexture : IDisposable { _centerStorage.Dispose(); _current = null; - SaveGuid = Guid.Empty; + SaveTask = Task.CompletedTask; _mode = Mode.Empty; } } diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 9ac503df..76604e84 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -1,8 +1,11 @@ using System; +using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Threading; +using System.Threading.Tasks; using Dalamud.Data; using Dalamud.Interface; using ImGuiScene; @@ -11,100 +14,71 @@ using OtterGui.Log; using OtterGui.Tasks; using OtterTex; using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; +using Swan; using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; -public sealed class TextureManager : AsyncTaskManager +public sealed class TextureManager : SingleTaskQueue, IDisposable { + private readonly Logger _logger; private readonly UiBuilder _uiBuilder; private readonly DataManager _gameData; - public TextureManager(Logger logger, UiBuilder uiBuilder, DataManager gameData) - : base(logger) + private readonly ConcurrentDictionary _tasks = new(); + private bool _disposed = false; + + public TextureManager(UiBuilder uiBuilder, DataManager gameData, Logger logger) { _uiBuilder = uiBuilder; _gameData = gameData; + _logger = logger; } - public Guid SavePng(string input, string output) + public IReadOnlyDictionary Tasks + => _tasks; + + public void Dispose() + { + _disposed = true; + foreach (var (_, cancel) in _tasks.Values.ToArray()) + cancel.Cancel(); + _tasks.Clear(); + } + + public Task SavePng(string input, string output) => Enqueue(new SavePngAction(this, input, output)); - public Guid SavePng(BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) + public Task SavePng(BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) => Enqueue(new SavePngAction(this, image, path, rgba, width, height)); - public Guid SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, string output) + public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, string output) => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, input, output)); - public Guid SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, string path, byte[]? rgba = null, + public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, image, path, rgba, width, height)); - private readonly struct ImageInputData + private Task Enqueue(IAction action) { - private readonly string? _inputPath; + if (_disposed) + return Task.FromException(new ObjectDisposedException(nameof(TextureManager))); - private readonly BaseImage _image; - private readonly byte[]? _rgba; - private readonly int _width; - private readonly int _height; - - public ImageInputData(string inputPath) + Task t; + lock (_tasks) { - _inputPath = inputPath; - _image = new BaseImage(); - _rgba = null; - _width = 0; - _height = 0; + t = _tasks.GetOrAdd(action, a => + { + var token = new CancellationTokenSource(); + var task = Enqueue(a, token.Token); + task.ContinueWith(_ => _tasks.TryRemove(a, out var unused), CancellationToken.None); + return (task, token); + }).Item1; } - public ImageInputData(BaseImage image, byte[]? rgba = null, int width = 0, int height = 0) - { - _inputPath = null; - _image = image.Width == 0 || image.Height == 0 ? new BaseImage() : image; - _rgba = rgba?.ToArray(); - _width = width; - _height = height; - } - - public (BaseImage Image, byte[]? Rgba, int Width, int Height) GetData(TextureManager textures) - { - if (_inputPath == null) - return (_image, _rgba, _width, _height); - - if (!File.Exists(_inputPath)) - throw new FileNotFoundException($"Input texture file {_inputPath} not Found.", _inputPath); - - var (image, _) = textures.Load(_inputPath); - return (image, null, 0, 0); - } - - public bool Equals(ImageInputData rhs) - { - if (_inputPath != null) - return string.Equals(_inputPath, rhs._inputPath, StringComparison.OrdinalIgnoreCase); - - if (rhs._inputPath != null) - return false; - - if (_image.Image != null) - return ReferenceEquals(_image.Image, rhs._image.Image); - - return _width == rhs._width && _height == rhs._height && _rgba != null && rhs._rgba != null && _rgba.SequenceEqual(rhs._rgba); - } - - public override string ToString() - => _inputPath - ?? _image.Type switch - { - TextureType.Unknown => $"Custom {_width} x {_height} RGBA Image", - TextureType.Dds => $"Custom {_width} x {_height} {_image.Format} Image", - TextureType.Tex => $"Custom {_width} x {_height} {_image.Format} Image", - TextureType.Png => $"Custom {_width} x {_height} .png Image", - TextureType.Bitmap => $"Custom {_width} x {_height} RGBA Image", - _ => "Unknown Image", - }; + return t; } private class SavePngAction : IAction @@ -129,7 +103,7 @@ public sealed class TextureManager : AsyncTaskManager public void Execute(CancellationToken cancel) { - _textures.Logger.Information($"[{nameof(TextureManager)}] Saving {_input} as .png to {_outputPath}..."); + _textures._logger.Information($"[{nameof(TextureManager)}] Saving {_input} as .png to {_outputPath}..."); var (image, rgba, width, height) = _input.GetData(_textures); cancel.ThrowIfCancellationRequested(); Image? png = null; @@ -144,9 +118,12 @@ public sealed class TextureManager : AsyncTaskManager } cancel.ThrowIfCancellationRequested(); - png?.SaveAsync(_outputPath, cancel).Wait(cancel); + png?.SaveAsync(_outputPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.NoCompression }, cancel).Wait(cancel); } + public override string ToString() + => $"{_input} to {_outputPath} PNG"; + public bool Equals(IAction? other) { if (other is not SavePngAction rhs) @@ -154,6 +131,9 @@ public sealed class TextureManager : AsyncTaskManager return string.Equals(_outputPath, rhs._outputPath, StringComparison.OrdinalIgnoreCase) && _input.Equals(rhs._input); } + + public override int GetHashCode() + => HashCode.Combine(_outputPath.ToLowerInvariant(), _input); } private class SaveAsAction : IAction @@ -177,8 +157,7 @@ public sealed class TextureManager : AsyncTaskManager } public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, - string path, - byte[]? rgba = null, int width = 0, int height = 0) + string path, byte[]? rgba = null, int width = 0, int height = 0) { _textures = textures; _input = new ImageInputData(image, rgba, width, height); @@ -190,7 +169,7 @@ public sealed class TextureManager : AsyncTaskManager public void Execute(CancellationToken cancel) { - _textures.Logger.Information( + _textures._logger.Information( $"[{nameof(TextureManager)}] Saving {_input} as {_type} {(_asTex ? ".tex" : ".dds")} file{(_mipMaps ? " with mip maps" : string.Empty)} to {_outputPath}..."); var (image, rgba, width, height) = _input.GetData(_textures); if (image.Type is TextureType.Unknown) @@ -220,6 +199,9 @@ public sealed class TextureManager : AsyncTaskManager dds.AsDds!.SaveDDS(_outputPath); } + public override string ToString() + => $"{_input} to {_outputPath} {_type} {(_asTex ? "TEX" : "DDS")}{(_mipMaps ? " with MipMaps" : string.Empty)}"; + public bool Equals(IAction? other) { if (other is not SaveAsAction rhs) @@ -231,6 +213,9 @@ public sealed class TextureManager : AsyncTaskManager && string.Equals(_outputPath, rhs._outputPath, StringComparison.OrdinalIgnoreCase) && _input.Equals(rhs._input); } + + public override int GetHashCode() + => HashCode.Combine(_outputPath.ToLowerInvariant(), _type, _mipMaps, _asTex, _input); } /// Load a texture wrap for a given image. @@ -435,4 +420,73 @@ public sealed class TextureManager : AsyncTaskManager header.Write(w); w.Write(input.Pixels); } + + private readonly struct ImageInputData + { + private readonly string? _inputPath; + + private readonly BaseImage _image; + private readonly byte[]? _rgba; + private readonly int _width; + private readonly int _height; + + public ImageInputData(string inputPath) + { + _inputPath = inputPath; + _image = new BaseImage(); + _rgba = null; + _width = 0; + _height = 0; + } + + public ImageInputData(BaseImage image, byte[]? rgba = null, int width = 0, int height = 0) + { + _inputPath = null; + _image = image.Width == 0 || image.Height == 0 ? new BaseImage() : image; + _rgba = rgba?.ToArray(); + _width = width; + _height = height; + } + + public (BaseImage Image, byte[]? Rgba, int Width, int Height) GetData(TextureManager textures) + { + if (_inputPath == null) + return (_image, _rgba, _width, _height); + + if (!File.Exists(_inputPath)) + throw new FileNotFoundException($"Input texture file {_inputPath} not Found.", _inputPath); + + var (image, _) = textures.Load(_inputPath); + return (image, null, 0, 0); + } + + public bool Equals(ImageInputData rhs) + { + if (_inputPath != null) + return string.Equals(_inputPath, rhs._inputPath, StringComparison.OrdinalIgnoreCase); + + if (rhs._inputPath != null) + return false; + + if (_image.Image != null) + return ReferenceEquals(_image.Image, rhs._image.Image); + + return _width == rhs._width && _height == rhs._height && _rgba != null && rhs._rgba != null && _rgba.SequenceEqual(rhs._rgba); + } + + public override string ToString() + => _inputPath + ?? _image.Type switch + { + TextureType.Unknown => $"Custom {_width} x {_height} RGBA Image", + TextureType.Dds => $"Custom {_width} x {_height} {_image.Format} Image", + TextureType.Tex => $"Custom {_width} x {_height} {_image.Format} Image", + TextureType.Png => $"Custom {_width} x {_height} .png Image", + TextureType.Bitmap => $"Custom {_width} x {_height} RGBA Image", + _ => "Unknown Image", + }; + + public override int GetHashCode() + => _inputPath != null ? _inputPath.ToLowerInvariant().GetHashCode() : HashCode.Combine(_width, _height); + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 6fd7b130..07607d11 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Linq; using System.Numerics; +using System.Threading.Tasks; using ImGuiNET; using OtterGui; using OtterGui.Raii; @@ -144,7 +145,7 @@ public partial class ModEditWindow _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); - ReloadConvertedSubscribe(_left.Path, _center.SaveGuid); + AddReloadTask(_left.Path); } ImGui.SameLine(); @@ -153,7 +154,7 @@ public partial class ModEditWindow _left.Format is DXGIFormat.BC3Typeless or DXGIFormat.BC3UNorm or DXGIFormat.BC3UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); - ReloadConvertedSubscribe(_left.Path, _center.SaveGuid); + AddReloadTask(_left.Path); } ImGui.SameLine(); @@ -162,7 +163,7 @@ public partial class ModEditWindow _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); - ReloadConvertedSubscribe(_left.Path, _center.SaveGuid); + AddReloadTask(_left.Path); } } else @@ -173,18 +174,20 @@ public partial class ModEditWindow ImGui.NewLine(); } - if (_center.SaveGuid != Guid.Empty) + switch (_center.SaveTask.Status) { - var state = _textures.GetState(_center.SaveGuid, out var saveException, out _, out _); - if (saveException != null) + case TaskStatus.WaitingForActivation: + case TaskStatus.WaitingToRun: + case TaskStatus.Running: + ImGui.TextUnformatted("Computing..."); + break; + case TaskStatus.Canceled: + case TaskStatus.Faulted: { ImGui.TextUnformatted("Could not save file:"); using var color = ImRaii.PushColor(ImGuiCol.Text, 0xFF0000FF); - ImGuiUtil.TextWrapped(saveException.ToString()); - } - else if (state == ActionState.Running) - { - ImGui.TextUnformatted("Computing..."); + ImGuiUtil.TextWrapped(_center.SaveTask.Exception?.ToString() ?? "Unknown Error"); + break; } } @@ -193,23 +196,18 @@ public partial class ModEditWindow _center.Draw(_textures, imageSize); } - - private void ReloadConvertedSubscribe(string path, Guid guid) + private void AddReloadTask(string path) { - void Reload(Guid eventGuid, ActionState state, Exception? ex) + _center.SaveTask.ContinueWith(t => { - if (guid != eventGuid) + if (!t.IsCompletedSuccessfully) return; if (_left.Path != path) return; - if (state is ActionState.Succeeded) - _dalamud.Framework.RunOnFrameworkThread(() => _left.Reload(_textures)); - _textures.Finished -= Reload; - } - - _textures.Finished += Reload; + _dalamud.Framework.RunOnFrameworkThread(() => _left.Reload(_textures)); + }); } private Vector2 GetChildWidth() diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index 066aec6c..a48fd714 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -19,6 +19,7 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.Files; using Penumbra.Import.Structs; +using Penumbra.Import.Textures; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.PathResolving; using Penumbra.Interop.Structs; @@ -61,13 +62,15 @@ public class DebugTab : Window, ITab private readonly ModImportManager _modImporter; private readonly ImportPopup _importPopup; private readonly FrameworkManager _framework; + private readonly TextureManager _textureManager; public DebugTab(StartTracker timer, PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorService actorService, DalamudServices dalamud, StainService stains, CharacterUtility characterUtility, ResidentResourceManager residentResources, ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, - CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework) + CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, + TextureManager textureManager) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse, false) { IsOpen = true; @@ -99,6 +102,7 @@ public class DebugTab : Window, ITab _modImporter = modImporter; _importPopup = importPopup; _framework = framework; + _textureManager = textureManager; } public ReadOnlySpan Label @@ -147,14 +151,15 @@ public class DebugTab : Window, ITab private void DrawCollectionCaches() { - if (!ImGui.CollapsingHeader($"Collections ({_collectionManager.Caches.Count}/{_collectionManager.Storage.Count - 1} Caches)###Collections")) + if (!ImGui.CollapsingHeader( + $"Collections ({_collectionManager.Caches.Count}/{_collectionManager.Storage.Count - 1} Caches)###Collections")) return; foreach (var collection in _collectionManager.Storage) { if (collection.HasCache) { - using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()); + using var color = PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()); using var node = TreeNode($"{collection.AnonymizedName} (Change Counter {collection.ChangeCounter})"); if (!node) continue; @@ -177,8 +182,9 @@ public class DebugTab : Window, ITab } else { - using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.UndefinedMod.Value()); - TreeNode($"{collection.AnonymizedName} (Change Counter {collection.ChangeCounter})", ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + using var color = PushColor(ImGuiCol.Text, ColorId.UndefinedMod.Value()); + TreeNode($"{collection.AnonymizedName} (Change Counter {collection.ChangeCounter})", + ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); } } } @@ -293,6 +299,20 @@ public class DebugTab : Window, ITab } } } + + using (var tree = TreeNode($"Texture Manager {_textureManager.Tasks.Count}###Texture Manager")) + { + if (tree) + { + using var table = Table("##Tasks", 2, ImGuiTableFlags.RowBg); + if (table) + foreach (var task in _textureManager.Tasks) + { + ImGuiUtil.DrawTableColumn(task.Key.ToString()!); + ImGuiUtil.DrawTableColumn(task.Value.Item1.Status.ToString()); + } + } + } } private void DrawPerformanceTab() @@ -500,7 +520,7 @@ public class DebugTab : Window, ITab if (agent->Data != null) { - using var table = Table("###PBannerTable", 2, ImGuiTableFlags.SizingFixedFit); + using var table = Table("###PBannerTable", 2, ImGuiTableFlags.SizingFixedFit); if (table) for (var i = 0; i < 8; ++i) { From e615ffcf3def127f458c5633b8ff9a0f5c599362 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Aug 2023 17:01:55 +0200 Subject: [PATCH 0014/1381] Increment API --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 623e802b..97610e1c 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 623e802bbc18496aab4030b444154a5b015093c2 +Subproject commit 97610e1c9d27d863ae8563bb9c8525cc6f8a3709 From df808187e25bcea93f913c9fb295c0a8f77b1b55 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 10 Aug 2023 15:07:04 +0000 Subject: [PATCH 0015/1381] [CI] Updating repo.json for testing_0.7.2.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index fb7afb7e..760f1ad1 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.2.2", - "TestingAssemblyVersion": "0.7.2.6", + "TestingAssemblyVersion": "0.7.2.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 09ca32f33dd084bbe9e8e8c702efe5e89c6776f8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Aug 2023 17:38:35 +0200 Subject: [PATCH 0016/1381] Add DalamudSubstitutionProvider --- Penumbra/Api/DalamudSubstitutionProvider.cs | 46 +++++++++++++++++++++ Penumbra/Services/DalamudServices.cs | 19 +++++---- 2 files changed, 58 insertions(+), 7 deletions(-) create mode 100644 Penumbra/Api/DalamudSubstitutionProvider.cs diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs new file mode 100644 index 00000000..faa6710a --- /dev/null +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -0,0 +1,46 @@ +using System; +using Dalamud.Plugin.Services; +using Penumbra.Collections.Manager; +using Penumbra.String.Classes; + +namespace Penumbra.Api; + +public class DalamudSubstitutionProvider : IDisposable +{ + private readonly ITextureSubstitutionProvider _substitution; + private readonly ActiveCollectionData _activeCollectionData; + + public DalamudSubstitutionProvider(ITextureSubstitutionProvider substitution, ActiveCollectionData activeCollectionData) + { + _substitution = substitution; + _activeCollectionData = activeCollectionData; + _substitution.InterceptTexDataLoad += Substitute; + } + + public void Dispose() + => _substitution.InterceptTexDataLoad -= Substitute; + + private void Substitute(string path, ref string? replacementPath) + { + // Let other plugins prioritize replacement paths. + if (replacementPath != null) + return; + + // Only replace interface textures. + if (!path.StartsWith("ui/") && !path.StartsWith("common/font/")) + return; + + try + { + if (!Utf8GamePath.FromString(path, out var utf8Path, true)) + return; + + var resolved = _activeCollectionData.Interface.ResolvePath(utf8Path); + replacementPath = resolved?.FullName; + } + catch + { + // ignored + } + } +} \ No newline at end of file diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudServices.cs index c2cf0c75..491e2161 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudServices.cs @@ -13,6 +13,7 @@ using Dalamud.Plugin; using System.Linq; using System.Reflection; using Dalamud.Interface.DragDrop; +using Dalamud.Plugin.Services; using Microsoft.Extensions.DependencyInjection; // ReSharper disable AutoPropertyCanBeMadeGetOnly.Local @@ -78,24 +79,28 @@ public class DalamudServices services.AddSingleton(this); services.AddSingleton(UiBuilder); services.AddSingleton(DragDropManager); + services.AddSingleton(TextureProvider); + services.AddSingleton(TextureSubstitutionProvider); } // TODO remove static // @formatter:off - [PluginService][RequiredVersion("1.0")] public DalamudPluginInterface PluginInterface { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public DalamudPluginInterface PluginInterface { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public CommandManager Commands { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public DataManager GameData { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ClientState ClientState { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ChatGui Chat { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public Framework Framework { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public Condition Conditions { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ChatGui Chat { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public Framework Framework { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public Condition Conditions { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public TargetManager Targets { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ObjectTable Objects { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public TitleScreenMenu TitleScreenMenu { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public TitleScreenMenu TitleScreenMenu { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public GameGui GameGui { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public KeyState KeyState { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public KeyState KeyState { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public SigScanner SigScanner { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IDragDropManager DragDropManager { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IDragDropManager DragDropManager { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ITextureProvider TextureProvider { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ITextureSubstitutionProvider TextureSubstitutionProvider { get; private set; } = null!; // @formatter:on public UiBuilder UiBuilder From af536b34236f73d62c4894b6f0d2bc7df1665f3f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Aug 2023 18:10:26 +0200 Subject: [PATCH 0017/1381] Update some Dalamud Services. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/CommandHandler.cs | 6 +++--- Penumbra/Import/Textures/TextureManager.cs | 11 +++++------ .../PathResolving/AnimationHookService.cs | 7 +++---- .../PathResolving/CollectionResolver.cs | 9 ++++----- .../Interop/PathResolving/CutsceneService.cs | 6 +++--- .../Interop/PathResolving/DrawObjectState.cs | 6 +++--- .../PathResolving/IdentifiedCollectionCache.cs | 6 +++--- .../ResourceTree/ResourceTreeFactory.cs | 9 ++++----- .../Interop/ResourceTree/TreeBuildCache.cs | 9 ++++----- Penumbra/Interop/Services/RedrawService.cs | 8 ++++---- Penumbra/Meta/MetaFileManager.cs | 6 +++--- Penumbra/Services/ChatService.cs | 3 +-- Penumbra/Services/DalamudServices.cs | 17 +++++++---------- Penumbra/Services/StainService.cs | 4 ++-- Penumbra/Services/Wrappers.cs | 13 +++++-------- Penumbra/UI/AdvancedWindow/FileEditor.cs | 6 +++--- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 4 ++-- Penumbra/UI/ChangedItemDrawer.cs | 18 +++++++++--------- Penumbra/UI/CollectionTab/CollectionPanel.cs | 4 ++-- Penumbra/UI/Tabs/CollectionsTab.cs | 2 +- Penumbra/UI/Tabs/ModsTab.cs | 6 +++--- Penumbra/UI/Tabs/ResourceTab.cs | 5 ++--- 24 files changed, 78 insertions(+), 91 deletions(-) diff --git a/OtterGui b/OtterGui index 9dad9558..863d08bd 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9dad955808831a5d154d778d1123acbe648c42ac +Subproject commit 863d08bd83381bb7fe4a8d5c514f0ba55379336f diff --git a/Penumbra.GameData b/Penumbra.GameData index e5b733c6..d84508ea 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e5b733c6fcc5436c8f767dd99a37e5e8c16b4fc8 +Subproject commit d84508ea1a607976525265e8f75a329667eec0e5 diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 4ef04e77..a78c4da7 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -5,6 +5,7 @@ using Dalamud.Game; using Dalamud.Game.Command; using Dalamud.Game.Gui; using Dalamud.Game.Text.SeStringHandling; +using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui.Classes; using Penumbra.Api.Enums; @@ -16,7 +17,6 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; -using Penumbra.Util; namespace Penumbra; @@ -24,7 +24,7 @@ public class CommandHandler : IDisposable { private const string CommandName = "/penumbra"; - private readonly CommandManager _commandManager; + private readonly ICommandManager _commandManager; private readonly RedrawService _redrawService; private readonly ChatGui _chat; private readonly Configuration _config; @@ -35,7 +35,7 @@ public class CommandHandler : IDisposable private readonly Penumbra _penumbra; private readonly CollectionEditor _collectionEditor; - public CommandHandler(Framework framework, CommandManager commandManager, ChatGui chat, RedrawService redrawService, Configuration config, + public CommandHandler(Framework framework, ICommandManager commandManager, ChatGui chat, RedrawService redrawService, Configuration config, ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorService actors, Penumbra penumbra, CollectionEditor collectionEditor) { diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 76604e84..3b4c7f67 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -6,8 +6,8 @@ using System.Linq; using System.Numerics; using System.Threading; using System.Threading.Tasks; -using Dalamud.Data; using Dalamud.Interface; +using Dalamud.Plugin.Services; using ImGuiScene; using Lumina.Data.Files; using OtterGui.Log; @@ -16,21 +16,20 @@ using OtterTex; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; -using Swan; using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; public sealed class TextureManager : SingleTaskQueue, IDisposable { - private readonly Logger _logger; - private readonly UiBuilder _uiBuilder; - private readonly DataManager _gameData; + private readonly Logger _logger; + private readonly UiBuilder _uiBuilder; + private readonly IDataManager _gameData; private readonly ConcurrentDictionary _tasks = new(); private bool _disposed = false; - public TextureManager(UiBuilder uiBuilder, DataManager gameData, Logger logger) + public TextureManager(UiBuilder uiBuilder, IDataManager gameData, Logger logger) { _uiBuilder = uiBuilder; _gameData = gameData; diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index 130c0926..b1efb1b9 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -1,10 +1,9 @@ using System; using System.Threading; using Dalamud.Game.ClientState.Conditions; -using Dalamud.Game.ClientState.Objects; using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.Game.Event; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Collections; using Penumbra.GameData; @@ -20,7 +19,7 @@ namespace Penumbra.Interop.PathResolving; public unsafe class AnimationHookService : IDisposable { private readonly PerformanceTracker _performance; - private readonly ObjectTable _objects; + private readonly IObjectTable _objects; private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; private readonly CollectionResolver _resolver; @@ -29,7 +28,7 @@ public unsafe class AnimationHookService : IDisposable private readonly ThreadLocal _animationLoadData = new(() => ResolveData.Invalid, true); private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); - public AnimationHookService(PerformanceTracker performance, ObjectTable objects, CollectionResolver collectionResolver, + public AnimationHookService(PerformanceTracker performance, IObjectTable objects, CollectionResolver collectionResolver, DrawObjectState drawObjectState, CollectionResolver resolver, Condition conditions) { _performance = performance; diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 67d9e96d..a795b46b 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,6 +1,5 @@ using System; -using Dalamud.Game.ClientState; -using Dalamud.Game.Gui; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -21,8 +20,8 @@ public unsafe class CollectionResolver private readonly IdentifiedCollectionCache _cache; private readonly HumanModelList _humanModels; - private readonly ClientState _clientState; - private readonly GameGui _gameGui; + private readonly IClientState _clientState; + private readonly IGameGui _gameGui; private readonly ActorService _actors; private readonly CutsceneService _cutscenes; @@ -31,7 +30,7 @@ public unsafe class CollectionResolver private readonly TempCollectionManager _tempCollections; private readonly DrawObjectState _drawObjectState; - public CollectionResolver(PerformanceTracker performance, IdentifiedCollectionCache cache, ClientState clientState, GameGui gameGui, + public CollectionResolver(PerformanceTracker performance, IdentifiedCollectionCache cache, IClientState clientState, IGameGui gameGui, ActorService actors, CutsceneService cutscenes, Configuration config, CollectionManager collectionManager, TempCollectionManager tempCollections, DrawObjectState drawObjectState, HumanModelList humanModels) { diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 2c59a086..4273ae01 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using Dalamud.Game.ClientState.Objects; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using Penumbra.GameData.Actors; using Penumbra.Interop.Services; @@ -16,7 +16,7 @@ public class CutsceneService : IDisposable public const int CutsceneSlots = CutsceneEndIdx - CutsceneStartIdx; private readonly GameEventManager _events; - private readonly ObjectTable _objects; + private readonly IObjectTable _objects; private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); public IEnumerable> Actors @@ -24,7 +24,7 @@ public class CutsceneService : IDisposable .Where(i => _objects[i] != null) .Select(i => KeyValuePair.Create(i, this[i] ?? _objects[i]!)); - public unsafe CutsceneService(ObjectTable objects, GameEventManager events) + public unsafe CutsceneService(IObjectTable objects, GameEventManager events) { _objects = objects; _events = events; diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 88e600b8..12f867b4 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -4,7 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Threading; -using Dalamud.Game.ClientState.Objects; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.GameData; using Penumbra.Interop.Services; @@ -14,7 +14,7 @@ namespace Penumbra.Interop.PathResolving; public class DrawObjectState : IDisposable, IReadOnlyDictionary { - private readonly ObjectTable _objects; + private readonly IObjectTable _objects; private readonly GameEventManager _gameEvents; private readonly Dictionary _drawObjectToGameObject = new(); @@ -24,7 +24,7 @@ public class DrawObjectState : IDisposable, IReadOnlyDictionary _lastGameObject.IsValueCreated && _lastGameObject.Value!.Count > 0 ? _lastGameObject.Value.Peek() : nint.Zero; - public DrawObjectState(ObjectTable objects, GameEventManager gameEvents) + public DrawObjectState(IObjectTable objects, GameEventManager gameEvents) { SignatureHelper.Initialise(this); _enableDrawHook.Enable(); diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 67ab584e..2bf165c1 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -1,7 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; -using Dalamud.Game.ClientState; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.Collections; @@ -17,11 +17,11 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A { private readonly CommunicatorService _communicator; private readonly GameEventManager _events; - private readonly ClientState _clientState; + private readonly IClientState _clientState; private readonly Dictionary _cache = new(317); private bool _dirty; - public IdentifiedCollectionCache(ClientState clientState, CommunicatorService communicator, GameEventManager events) + public IdentifiedCollectionCache(IClientState clientState, CommunicatorService communicator, GameEventManager events) { _clientState = clientState; _communicator = communicator; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 965769a7..98c1b305 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; -using Dalamud.Data; -using Dalamud.Game.ClientState.Objects; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.GameData.Actors; @@ -12,14 +11,14 @@ namespace Penumbra.Interop.ResourceTree; public class ResourceTreeFactory { - private readonly DataManager _gameData; - private readonly ObjectTable _objects; + private readonly IDataManager _gameData; + private readonly IObjectTable _objects; private readonly CollectionResolver _collectionResolver; private readonly IdentifierService _identifier; private readonly Configuration _config; private readonly ActorService _actors; - public ResourceTreeFactory(DataManager gameData, ObjectTable objects, CollectionResolver resolver, IdentifierService identifier, + public ResourceTreeFactory(IDataManager gameData, IObjectTable objects, CollectionResolver resolver, IdentifierService identifier, Configuration config, ActorService actors) { _gameData = gameData; diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 4e432dd4..e9939496 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -2,9 +2,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using Dalamud.Data; -using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.Plugin.Services; using Penumbra.GameData.Files; using Penumbra.String.Classes; @@ -12,13 +11,13 @@ namespace Penumbra.Interop.ResourceTree; internal class TreeBuildCache { - private readonly DataManager _dataManager; + private readonly IDataManager _dataManager; private readonly Dictionary _materials = new(); private readonly Dictionary _shaderPackages = new(); public readonly List Characters; public readonly Dictionary CharactersById; - public TreeBuildCache(ObjectTable objects, DataManager dataManager) + public TreeBuildCache(IObjectTable objects, IDataManager dataManager) { _dataManager = dataManager; Characters = objects.Where(c => c is Character ch && ch.IsValid()).Cast().ToList(); @@ -36,7 +35,7 @@ internal class TreeBuildCache public ShpkFile? ReadShaderPackage(FullPath path) => ReadFile(_dataManager, path, _shaderPackages, bytes => new ShpkFile(bytes)); - private static T? ReadFile(DataManager dataManager, FullPath path, Dictionary cache, Func parseFile) + private static T? ReadFile(IDataManager dataManager, FullPath path, Dictionary cache, Func parseFile) where T : class { if (path.FullName.Length == 0) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 825eda5c..38b7de1c 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -7,12 +7,12 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.Plugin.Services; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.GameData.Actors; using Penumbra.Interop.Structs; -using Penumbra.Services; namespace Penumbra.Interop.Services; @@ -104,8 +104,8 @@ public unsafe partial class RedrawService public sealed unsafe partial class RedrawService : IDisposable { private readonly Framework _framework; - private readonly ObjectTable _objects; - private readonly TargetManager _targets; + private readonly IObjectTable _objects; + private readonly ITargetManager _targets; private readonly Condition _conditions; private readonly List _queue = new(100); @@ -114,7 +114,7 @@ public sealed unsafe partial class RedrawService : IDisposable public event GameObjectRedrawnDelegate? GameObjectRedrawn; - public RedrawService(Framework framework, ObjectTable objects, TargetManager targets, Condition conditions) + public RedrawService(Framework framework, IObjectTable objects, ITargetManager targets, Condition conditions) { _framework = framework; _objects = objects; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 1cb3319e..7287204c 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -1,7 +1,7 @@ using System; using System.Linq; using System.Runtime.CompilerServices; -using Dalamud.Data; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Memory; using Penumbra.Collections; @@ -22,12 +22,12 @@ public unsafe class MetaFileManager internal readonly Configuration Config; internal readonly CharacterUtility CharacterUtility; internal readonly ResidentResourceManager ResidentResources; - internal readonly DataManager GameData; + internal readonly IDataManager GameData; internal readonly ActiveCollectionData ActiveCollections; internal readonly ValidityChecker ValidityChecker; internal readonly IdentifierService Identifier; - public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, DataManager gameData, + public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, IdentifierService identifier) { CharacterUtility = characterUtility; diff --git a/Penumbra/Services/ChatService.cs b/Penumbra/Services/ChatService.cs index f4d4ead0..9ea52cac 100644 --- a/Penumbra/Services/ChatService.cs +++ b/Penumbra/Services/ChatService.cs @@ -3,7 +3,6 @@ using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; -using Dalamud.Interface; using Dalamud.Plugin; using Lumina.Excel.GeneratedSheets; using OtterGui.Log; @@ -14,7 +13,7 @@ public class ChatService : OtterGui.Classes.ChatService { private readonly ChatGui _chat; - public ChatService(Logger log, DalamudPluginInterface pi, ChatGui chat, UiBuilder uiBuilder) + public ChatService(Logger log, DalamudPluginInterface pi, ChatGui chat) : base(log, pi) => _chat = chat; diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudServices.cs index 491e2161..03978566 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudServices.cs @@ -1,11 +1,8 @@ using System; -using Dalamud.Data; using Dalamud.Game; -using Dalamud.Game.ClientState; using Dalamud.Game.ClientState.Conditions; using Dalamud.Game.ClientState.Keys; using Dalamud.Game.ClientState.Objects; -using Dalamud.Game.Command; using Dalamud.Game.Gui; using Dalamud.Interface; using Dalamud.IoC; @@ -86,18 +83,18 @@ public class DalamudServices // TODO remove static // @formatter:off [PluginService][RequiredVersion("1.0")] public DalamudPluginInterface PluginInterface { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public CommandManager Commands { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public DataManager GameData { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ClientState ClientState { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ICommandManager Commands { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IDataManager GameData { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IClientState ClientState { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ChatGui Chat { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public Framework Framework { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public Condition Conditions { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public TargetManager Targets { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ObjectTable Objects { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ITargetManager Targets { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IObjectTable Objects { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public TitleScreenMenu TitleScreenMenu { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public GameGui GameGui { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IGameGui GameGui { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public KeyState KeyState { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public SigScanner SigScanner { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ISigScanner SigScanner { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public IDragDropManager DragDropManager { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ITextureProvider TextureProvider { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ITextureSubstitutionProvider TextureSubstitutionProvider { get; private set; } = null!; diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index d795062c..56893d70 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using Dalamud.Data; using Dalamud.Plugin; +using Dalamud.Plugin.Services; using OtterGui.Widgets; using Penumbra.GameData.Data; using Penumbra.GameData.Files; @@ -24,7 +24,7 @@ public class StainService : IDisposable public readonly StmFile StmFile; public readonly StainTemplateCombo TemplateCombo; - public StainService(StartTracker timer, DalamudPluginInterface pluginInterface, DataManager dataManager) + public StainService(StartTracker timer, DalamudPluginInterface pluginInterface, IDataManager dataManager) { using var t = timer.Measure(StartTimeType.Stains); StainData = new StainData(pluginInterface, dataManager, dataManager.Language); diff --git a/Penumbra/Services/Wrappers.cs b/Penumbra/Services/Wrappers.cs index c0ffec79..d9bef172 100644 --- a/Penumbra/Services/Wrappers.cs +++ b/Penumbra/Services/Wrappers.cs @@ -1,9 +1,6 @@ -using Dalamud.Data; using Dalamud.Game; -using Dalamud.Game.ClientState; -using Dalamud.Game.ClientState.Objects; -using Dalamud.Game.Gui; using Dalamud.Plugin; +using Dalamud.Plugin.Services; using Penumbra.GameData; using Penumbra.GameData.Actors; using Penumbra.GameData.Data; @@ -14,22 +11,22 @@ namespace Penumbra.Services; public sealed class IdentifierService : AsyncServiceWrapper { - public IdentifierService(StartTracker tracker, DalamudPluginInterface pi, DataManager data, ItemService items) + public IdentifierService(StartTracker tracker, DalamudPluginInterface pi, IDataManager data, ItemService items) : base(nameof(IdentifierService), tracker, StartTimeType.Identifier, () => GameData.GameData.GetIdentifier(pi, data, items.AwaitedService)) { } } public sealed class ItemService : AsyncServiceWrapper { - public ItemService(StartTracker tracker, DalamudPluginInterface pi, DataManager gameData) + public ItemService(StartTracker tracker, DalamudPluginInterface pi, IDataManager gameData) : base(nameof(ItemService), tracker, StartTimeType.Items, () => new ItemData(pi, gameData, gameData.Language)) { } } public sealed class ActorService : AsyncServiceWrapper { - public ActorService(StartTracker tracker, DalamudPluginInterface pi, ObjectTable objects, ClientState clientState, - Framework framework, DataManager gameData, GameGui gui, CutsceneService cutscene) + public ActorService(StartTracker tracker, DalamudPluginInterface pi, IObjectTable objects, IClientState clientState, + Framework framework, IDataManager gameData, IGameGui gui, CutsceneService cutscene) : base(nameof(ActorService), tracker, StartTimeType.Actors, () => new ActorManager(pi, objects, clientState, framework, gameData, gui, idx => (short)cutscene.GetParentIndex(idx))) { } diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 0f163994..acead332 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; -using Dalamud.Data; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; +using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Classes; @@ -21,10 +21,10 @@ namespace Penumbra.UI.AdvancedWindow; public class FileEditor where T : class, IWritable { private readonly FileDialogService _fileDialog; - private readonly DataManager _gameData; + private readonly IDataManager _gameData; private readonly ModEditWindow _owner; - public FileEditor(ModEditWindow owner, DataManager gameData, Configuration config, FileDialogService fileDialog, string tabName, + public FileEditor(ModEditWindow owner, IDataManager gameData, Configuration config, FileDialogService fileDialog, string tabName, string fileType, Func> getFiles, Func drawEdit, Func getInitialPath, Func parseFile) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 93d28b85..a36dcf14 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -3,10 +3,10 @@ using System.IO; using System.Linq; using System.Numerics; using System.Text; -using Dalamud.Data; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.Windowing; +using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Raii; @@ -518,7 +518,7 @@ public partial class ModEditWindow : Window, IDisposable return new FullPath(path); } - public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, DataManager gameData, + public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, UiBuilder uiBuilder, DalamudServices dalamud, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures) diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index b2f13e51..7a81ec60 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -2,8 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; using System.Numerics; -using Dalamud.Data; using Dalamud.Interface; +using Dalamud.Plugin.Services; using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; @@ -54,10 +54,10 @@ public class ChangedItemDrawer : IDisposable private readonly Dictionary _icons = new(16); private float _smallestIconWidth; - public ChangedItemDrawer(UiBuilder uiBuilder, DataManager gameData, CommunicatorService communicator, Configuration config) + public ChangedItemDrawer(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, Configuration config) { _items = gameData.GetExcelSheet()!; - uiBuilder.RunWhenUiPrepared(() => CreateEquipSlotIcons(uiBuilder, gameData), true); + uiBuilder.RunWhenUiPrepared(() => CreateEquipSlotIcons(uiBuilder, gameData, textureProvider), true); _communicator = communicator; _config = config; } @@ -321,7 +321,7 @@ public class ChangedItemDrawer : IDisposable }; /// Initialize the icons. - private bool CreateEquipSlotIcons(UiBuilder uiBuilder, DataManager gameData) + private bool CreateEquipSlotIcons(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider) { using var equipTypeIcons = uiBuilder.LoadUld("ui/uld/ArmouryBoard.uld"); @@ -345,11 +345,11 @@ public class ChangedItemDrawer : IDisposable Add(ChangedItemIcon.Neck, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 9)); Add(ChangedItemIcon.Wrists, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 10)); Add(ChangedItemIcon.Finger, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 11)); - Add(ChangedItemIcon.Monster, gameData.GetImGuiTexture("ui/icon/062000/062042_hr1.tex")); - Add(ChangedItemIcon.Demihuman, gameData.GetImGuiTexture("ui/icon/062000/062041_hr1.tex")); - Add(ChangedItemIcon.Customization, gameData.GetImGuiTexture("ui/icon/062000/062043_hr1.tex")); - Add(ChangedItemIcon.Action, gameData.GetImGuiTexture("ui/icon/062000/062001_hr1.tex")); - Add(AllFlags, gameData.GetImGuiTexture("ui/icon/114000/114052_hr1.tex")); + Add(ChangedItemIcon.Monster, textureProvider.GetTextureFromGame("ui/icon/062000/062042_hr1.tex", true)); + Add(ChangedItemIcon.Demihuman, textureProvider.GetTextureFromGame("ui/icon/062000/062041_hr1.tex", true)); + Add(ChangedItemIcon.Customization, textureProvider.GetTextureFromGame("ui/icon/062000/062043_hr1.tex", true)); + Add(ChangedItemIcon.Action, textureProvider.GetTextureFromGame("ui/icon/062000/062001_hr1.tex", true)); + Add(AllFlags, textureProvider.GetTextureFromGame("ui/icon/114000/114052_hr1.tex", true)); var unk = gameData.GetFile("ui/uld/levelup2_hr1.tex"); if (unk == null) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 1774cf1d..b5e60380 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -26,7 +26,7 @@ public sealed class CollectionPanel : IDisposable private readonly ActiveCollections _active; private readonly CollectionSelector _selector; private readonly ActorService _actors; - private readonly TargetManager _targets; + private readonly ITargetManager _targets; private readonly IndividualAssignmentUi _individualAssignmentUi; private readonly InheritanceUi _inheritanceUi; private readonly ModStorage _mods; @@ -40,7 +40,7 @@ public sealed class CollectionPanel : IDisposable private int _draggedIndividualAssignment = -1; public CollectionPanel(DalamudPluginInterface pi, CommunicatorService communicator, CollectionManager manager, - CollectionSelector selector, ActorService actors, TargetManager targets, ModStorage mods) + CollectionSelector selector, ActorService actors, ITargetManager targets, ModStorage mods) { _collections = manager.Storage; _active = manager.Active; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index d6941ba0..d0f227c8 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -41,7 +41,7 @@ public class CollectionsTab : IDisposable, ITab } public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, - CollectionManager collectionManager, ModStorage modStorage, ActorService actors, TargetManager targets, TutorialService tutorial) + CollectionManager collectionManager, ModStorage modStorage, ActorService actors, ITargetManager targets, TutorialService tutorial) { _config = configuration; _tutorial = tutorial; diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 36bf9c7d..10e4be1d 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -5,8 +5,8 @@ using Penumbra.UI.Classes; using System; using System.Linq; using System.Numerics; -using Dalamud.Game.ClientState; using Dalamud.Interface; +using Dalamud.Plugin.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Interop.Services; @@ -27,11 +27,11 @@ public class ModsTab : ITab private readonly ActiveCollections _activeCollections; private readonly RedrawService _redrawService; private readonly Configuration _config; - private readonly ClientState _clientState; + private readonly IClientState _clientState; private readonly CollectionSelectHeader _collectionHeader; public ModsTab(ModManager modManager, CollectionManager collectionManager, ModFileSystemSelector selector, ModPanel panel, - TutorialService tutorial, RedrawService redrawService, Configuration config, ClientState clientState, + TutorialService tutorial, RedrawService redrawService, Configuration config, IClientState clientState, CollectionSelectHeader collectionHeader) { _modManager = modManager; diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index 95ff0d2a..db1236bb 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -2,7 +2,6 @@ using System; using System.Linq; using System.Numerics; using Dalamud.Game; -using Dalamud.Interface; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; @@ -20,9 +19,9 @@ public class ResourceTab : ITab { private readonly Configuration _config; private readonly ResourceManagerService _resourceManager; - private readonly SigScanner _sigScanner; + private readonly ISigScanner _sigScanner; - public ResourceTab(Configuration config, ResourceManagerService resourceManager, SigScanner sigScanner) + public ResourceTab(Configuration config, ResourceManagerService resourceManager, ISigScanner sigScanner) { _config = config; _resourceManager = resourceManager; From cf3810a1b8840745d2b0f984b0e4e2c3c3882aca Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 13 Aug 2023 14:30:06 +0200 Subject: [PATCH 0018/1381] Add filter to texturedrawer. --- Penumbra/Import/Textures/TextureDrawer.cs | 88 +++++++++++-------- .../AdvancedWindow/ModEditWindow.Textures.cs | 17 ++-- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 31 +++---- 3 files changed, 77 insertions(+), 59 deletions(-) diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index b077f6fd..fead989e 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -1,12 +1,16 @@ +using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Numerics; using Dalamud.Interface; using ImGuiNET; using Lumina.Data.Files; using OtterGui; using OtterGui.Raii; +using OtterGui.Widgets; using OtterTex; +using Penumbra.Mods; using Penumbra.String.Classes; using Penumbra.UI; using Penumbra.UI.Classes; @@ -33,41 +37,6 @@ public static class TextureDrawer } } - public static void PathSelectBox(TextureManager textures, Texture current, string label, string tooltip, IEnumerable<(string, bool)> paths, - int skipPrefix) - { - ImGui.SetNextItemWidth(-0.0001f); - var startPath = current.Path.Length > 0 ? current.Path : "Choose a modded texture from this mod here..."; - using var combo = ImRaii.Combo(label, startPath); - if (combo) - foreach (var ((path, game), idx) in paths.WithIndex()) - { - if (game) - { - if (!textures.GameFileExists(path)) - continue; - } - else if (!File.Exists(path)) - { - continue; - } - - using var id = ImRaii.PushId(idx); - using (var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value(), game)) - { - var p = game ? $"--> {path}" : path[skipPrefix..]; - if (ImGui.Selectable(p, path == startPath) && path != startPath) - current.Load(textures, path); - } - - ImGuiUtil.HoverTooltip(game - ? "This is a game path and refers to an unmanipulated file from your game data." - : "This is a path to a modded file on your file system."); - } - - ImGuiUtil.HoverTooltip(tooltip); - } - public static void PathInputBox(TextureManager textures, Texture current, ref string? tmpPath, string label, string hint, string tooltip, string startPath, FileDialogService fileDialog, string defaultModImportPath) { @@ -136,4 +105,53 @@ public static class TextureDrawer break; } } + + public sealed class PathSelectCombo : FilterComboCache<(string, bool)> + { + private int _skipPrefix = 0; + + public PathSelectCombo(TextureManager textures, ModEditor editor) + : base(() => CreateFiles(textures, editor)) + { } + + protected override string ToString((string, bool) obj) + => obj.Item1; + + protected override bool DrawSelectable(int globalIdx, bool selected) + { + var (path, game) = Items[globalIdx]; + bool ret; + using (var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value(), game)) + { + var equals = string.Equals(CurrentSelection.Item1, path, StringComparison.OrdinalIgnoreCase); + var p = game ? $"--> {path}" : path[_skipPrefix..]; + ret = ImGui.Selectable(p, selected) && !equals; + } + + ImGuiUtil.HoverTooltip(game + ? "This is a game path and refers to an unmanipulated file from your game data." + : "This is a path to a modded file on your file system."); + return ret; + } + + private static IReadOnlyList<(string, bool)> CreateFiles(TextureManager textures, ModEditor editor) + => editor.Files.Tex.SelectMany(f => f.SubModUsage.Select(p => (p.Item2.ToString(), true)) + .Prepend((f.File.FullName, false))) + .Where(p => p.Item2 ? textures.GameFileExists(p.Item1) : File.Exists(p.Item1)) + .ToList(); + + public bool Draw(string label, string tooltip, string current, int skipPrefix, out string newPath) + { + _skipPrefix = skipPrefix; + var startPath = current.Length > 0 ? current : "Choose a modded texture from this mod here..."; + if (!Draw(label, startPath, tooltip, -0.0001f, ImGui.GetTextLineHeightWithSpacing())) + { + newPath = current; + return false; + } + + newPath = CurrentSelection.Item1; + return true; + } + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 07607d11..32cd400f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using ImGuiNET; using OtterGui; using OtterGui.Raii; -using OtterGui.Tasks; using OtterTex; using Penumbra.Import.Textures; @@ -16,9 +15,10 @@ public partial class ModEditWindow { private readonly TextureManager _textures; - private readonly Texture _left = new(); - private readonly Texture _right = new(); - private readonly CombinedTexture _center; + private readonly Texture _left = new(); + private readonly Texture _right = new(); + private readonly CombinedTexture _center; + private readonly TextureDrawer.PathSelectCombo _textureSelectCombo; private bool _overlayCollapsed = true; private bool _addMipMaps = true; @@ -47,11 +47,10 @@ public partial class ModEditWindow TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); - var files = _editor.Files.Tex.SelectMany(f => f.SubModUsage.Select(p => (p.Item2.ToString(), true)) - .Prepend((f.File.FullName, false))); - TextureDrawer.PathSelectBox(_textures, tex, "##combo", - "Select the textures included in this mod on your drive or the ones they replace from the game files.", files, - _mod.ModPath.FullName.Length + 1); + if (_textureSelectCombo.Draw("##combo", + "Select the textures included in this mod on your drive or the ones they replace from the game files.", tex.Path, + _mod.ModPath.FullName.Length + 1, out var newPath) && newPath != tex.Path) + tex.Load(_textures, newPath); if (tex == _left) _center.DrawMatrixInputLeft(size.X); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index a36dcf14..8b870937 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -520,22 +520,22 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, - StainService stainService, ActiveCollections activeCollections, UiBuilder uiBuilder, DalamudServices dalamud, ModMergeTab modMergeTab, + StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures) : base(WindowBaseLabel) { - _performance = performance; - _itemSwapTab = itemSwapTab; - _config = config; - _editor = editor; - _metaFileManager = metaFileManager; - _stainService = stainService; - _activeCollections = activeCollections; - _dalamud = dalamud; - _modMergeTab = modMergeTab; - _communicator = communicator; - _textures = textures; - _fileDialog = fileDialog; + _performance = performance; + _itemSwapTab = itemSwapTab; + _config = config; + _editor = editor; + _metaFileManager = metaFileManager; + _stainService = stainService; + _activeCollections = activeCollections; + _dalamud = dalamud; + _modMergeTab = modMergeTab; + _communicator = communicator; + _textures = textures; + _fileDialog = fileDialog; _materialTab = new FileEditor(this, gameData, config, _fileDialog, "Materials", ".mtrl", () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, bytes => new MtrlTab(this, new MtrlFile(bytes))); @@ -544,8 +544,9 @@ public partial class ModEditWindow : Window, IDisposable _shaderPackageTab = new FileEditor(this, gameData, config, _fileDialog, "Shaders", ".shpk", () => _editor.Files.Shpk, DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, bytes => new ShpkTab(_fileDialog, bytes)); - _center = new CombinedTexture(_left, _right); - _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, 2, OnQuickImportRefresh, DrawQuickImportActions); + _center = new CombinedTexture(_left, _right); + _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); + _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, 2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ModEditWindow); } From 04b76ddee1e36664cb2ba118a520e401b2ed06f2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 16 Aug 2023 17:25:06 +0200 Subject: [PATCH 0019/1381] Add support for the DalamudSubstitutionProvider for textures. --- Penumbra/Api/DalamudSubstitutionProvider.cs | 127 +++++++++++++++++- Penumbra/Collections/Cache/CollectionCache.cs | 62 ++++++--- .../Cache/CollectionCacheManager.cs | 39 +++--- Penumbra/Communication/CollectionChange.cs | 4 + Penumbra/Communication/EnabledChanged.cs | 3 + Penumbra/Communication/ResolvedFileChanged.cs | 43 ++++++ Penumbra/Configuration.cs | 7 +- Penumbra/Services/CommunicatorService.cs | 4 + Penumbra/Services/ServiceManager.cs | 3 +- Penumbra/UI/Tabs/SettingsTab.cs | 59 ++++---- 10 files changed, 285 insertions(+), 66 deletions(-) create mode 100644 Penumbra/Communication/ResolvedFileChanged.cs diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index faa6710a..42abd1cd 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -1,7 +1,14 @@ using System; +using System.Collections.Generic; +using System.Linq; using Dalamud.Plugin.Services; +using Penumbra.Collections; using Penumbra.Collections.Manager; +using Penumbra.Communication; +using Penumbra.Mods; +using Penumbra.Services; using Penumbra.String.Classes; +using static Penumbra.Api.Ipc; namespace Penumbra.Api; @@ -9,19 +16,109 @@ public class DalamudSubstitutionProvider : IDisposable { private readonly ITextureSubstitutionProvider _substitution; private readonly ActiveCollectionData _activeCollectionData; + private readonly Configuration _config; + private readonly CommunicatorService _communicator; - public DalamudSubstitutionProvider(ITextureSubstitutionProvider substitution, ActiveCollectionData activeCollectionData) + public bool Enabled + => _config.UseDalamudUiTextureRedirection; + + public DalamudSubstitutionProvider(ITextureSubstitutionProvider substitution, ActiveCollectionData activeCollectionData, + Configuration config, CommunicatorService communicator) { - _substitution = substitution; - _activeCollectionData = activeCollectionData; - _substitution.InterceptTexDataLoad += Substitute; + _substitution = substitution; + _activeCollectionData = activeCollectionData; + _config = config; + _communicator = communicator; + if (Enabled) + Subscribe(); + } + + public void Set(bool value) + { + if (value) + Enable(); + else + Disable(); + } + + public void ResetSubstitutions(IEnumerable paths) + { + var transformed = paths + .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) + .Select(p => p.ToString()); + _substitution.InvalidatePaths(transformed); + } + + public void Enable() + { + if (Enabled) + return; + + _config.UseDalamudUiTextureRedirection = true; + _config.Save(); + Subscribe(); + } + + public void Disable() + { + if (!Enabled) + return; + + Unsubscribe(); + _config.UseDalamudUiTextureRedirection = false; + _config.Save(); } public void Dispose() - => _substitution.InterceptTexDataLoad -= Substitute; + => Unsubscribe(); + + private void OnCollectionChange(CollectionType type, ModCollection? oldCollection, ModCollection? newCollection, string _) + { + if (type is not CollectionType.Interface) + return; + + var enumerable = oldCollection?.ResolvedFiles.Keys ?? Array.Empty().AsEnumerable(); + enumerable = enumerable.Concat(newCollection?.ResolvedFiles.Keys ?? Array.Empty().AsEnumerable()); + ResetSubstitutions(enumerable); + } + + private void OnResolvedFileChange(ModCollection collection, ResolvedFileChanged.Type type, Utf8GamePath key, FullPath _1, FullPath _2, + IMod? _3) + { + if (_activeCollectionData.Interface != collection) + return; + + switch (type) + { + case ResolvedFileChanged.Type.Added: + case ResolvedFileChanged.Type.Removed: + case ResolvedFileChanged.Type.Replaced: + ResetSubstitutions(new[] + { + key, + }); + break; + case ResolvedFileChanged.Type.FullRecomputeStart: + case ResolvedFileChanged.Type.FullRecomputeFinished: + ResetSubstitutions(collection.ResolvedFiles.Keys); + break; + } + } + + private void OnEnabledChange(bool state) + { + if (state) + OnCollectionChange(CollectionType.Interface, null, _activeCollectionData.Interface, string.Empty); + else + OnCollectionChange(CollectionType.Interface, _activeCollectionData.Interface, null, string.Empty); + } private void Substitute(string path, ref string? replacementPath) { + // Do not replace when not enabled. + if (!_config.EnableMods) + return; + // Let other plugins prioritize replacement paths. if (replacementPath != null) return; @@ -43,4 +140,22 @@ public class DalamudSubstitutionProvider : IDisposable // ignored } } -} \ No newline at end of file + + private void Subscribe() + { + _substitution.InterceptTexDataLoad += Substitute; + _communicator.CollectionChange.Subscribe(OnCollectionChange, CollectionChange.Priority.DalamudSubstitutionProvider); + _communicator.ResolvedFileChanged.Subscribe(OnResolvedFileChange, ResolvedFileChanged.Priority.DalamudSubstitutionProvider); + _communicator.EnabledChanged.Subscribe(OnEnabledChange, EnabledChanged.Priority.DalamudSubstitutionProvider); + OnCollectionChange(CollectionType.Interface, null, _activeCollectionData.Interface, string.Empty); + } + + private void Unsubscribe() + { + _substitution.InterceptTexDataLoad -= Substitute; + _communicator.CollectionChange.Unsubscribe(OnCollectionChange); + _communicator.ResolvedFileChanged.Unsubscribe(OnResolvedFileChange); + _communicator.EnabledChanged.Unsubscribe(OnEnabledChange); + OnCollectionChange(CollectionType.Interface, _activeCollectionData.Interface, null, string.Empty); + } +} diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 3477fdf0..1f712124 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Penumbra.Api.Enums; +using Penumbra.Communication; using Penumbra.String.Classes; using Penumbra.Mods.Manager; @@ -34,7 +35,7 @@ public class CollectionCache : IDisposable public int Calculating = -1; public string AnonymizedName - => _collection.AnonymizedName; + => _collection.AnonymizedName; public IEnumerable> AllConflicts => _conflicts.Values; @@ -63,9 +64,7 @@ public class CollectionCache : IDisposable } public void Dispose() - { - Meta.Dispose(); - } + => Meta.Dispose(); ~CollectionCache() => Meta.Dispose(); @@ -130,8 +129,8 @@ public class CollectionCache : IDisposable => _manager.AddChange(ChangeData.ForcedFile(this, path, fullPath)); public void RemovePath(Utf8GamePath path) - => _manager.AddChange(ChangeData.ForcedFile(this, path, FullPath.Empty)); - + => _manager.AddChange(ChangeData.ForcedFile(this, path, FullPath.Empty)); + public void ReloadMod(IMod mod, bool addMetaChanges) => _manager.AddChange(ChangeData.ModReload(this, mod, addMetaChanges)); @@ -139,8 +138,8 @@ public class CollectionCache : IDisposable => _manager.AddChange(ChangeData.ModAddition(this, mod, addMetaChanges)); public void RemoveMod(IMod mod, bool addMetaChanges) - => _manager.AddChange(ChangeData.ModRemoval(this, mod, addMetaChanges)); - + => _manager.AddChange(ChangeData.ModRemoval(this, mod, addMetaChanges)); + /// Force a file to be resolved to a specific path regardless of conflicts. internal void ForceFileSync(Utf8GamePath path, FullPath fullPath) { @@ -148,9 +147,24 @@ public class CollectionCache : IDisposable return; if (ResolvedFiles.Remove(path, out var modPath)) + { ModData.RemovePath(modPath.Mod, path); - if (fullPath.FullName.Length > 0) + if (fullPath.FullName.Length > 0) + { + ResolvedFiles.Add(path, new ModPath(Mod.ForcedFiles, fullPath)); + InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, fullPath, modPath.Path, + Mod.ForcedFiles); + } + else + { + InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Removed, path, FullPath.Empty, modPath.Path, null); + } + } + else if (fullPath.FullName.Length > 0) + { ResolvedFiles.Add(path, new ModPath(Mod.ForcedFiles, fullPath)); + InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, fullPath, FullPath.Empty, Mod.ForcedFiles); + } } private void ReloadModSync(IMod mod, bool addMetaChanges) @@ -169,9 +183,14 @@ public class CollectionCache : IDisposable foreach (var path in paths) { - if (ResolvedFiles.Remove(path, out var mp) && mp.Mod != mod) - Penumbra.Log.Warning( - $"Invalid mod state, removing {mod.Name} and associated file {path} returned current mod {mp.Mod.Name}."); + if (ResolvedFiles.Remove(path, out var mp)) + { + if (mp.Mod != mod) + Penumbra.Log.Warning( + $"Invalid mod state, removing {mod.Name} and associated file {path} returned current mod {mp.Mod.Name}."); + else + _manager.ResolvedFileChanged.Invoke(_collection, ResolvedFileChanged.Type.Removed, path, FullPath.Empty, mp.Path, mp.Mod); + } } foreach (var manipulation in manipulations) @@ -203,7 +222,7 @@ public class CollectionCache : IDisposable } - /// Add all files and possibly manipulations of a given mod according to its settings in this collection. + /// Add all files and possibly manipulations of a given mod according to its settings in this collection. internal void AddModSync(IMod mod, bool addMetaChanges) { if (mod.Index >= 0) @@ -257,6 +276,14 @@ public class CollectionCache : IDisposable foreach (var manip in subMod.Manipulations) AddManipulation(manip, parentMod); } + + /// Invoke only if not in a full recalculation. + private void InvokeResolvedFileChange(ModCollection collection, ResolvedFileChanged.Type type, Utf8GamePath key, FullPath value, + FullPath old, IMod? mod) + { + if (Calculating == -1) + _manager.ResolvedFileChanged.Invoke(collection, type, key, value, old, mod); + } // Add a specific file redirection, handling potential conflicts. // For different mods, higher mod priority takes precedence before option group priority, @@ -271,7 +298,8 @@ public class CollectionCache : IDisposable { if (ResolvedFiles.TryAdd(path, new ModPath(mod, file))) { - ModData.AddPath(mod, path); + ModData.AddPath(mod, path); + InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, file, FullPath.Empty, mod); return; } @@ -285,11 +313,13 @@ public class CollectionCache : IDisposable ModData.RemovePath(modPath.Mod, path); ResolvedFiles[path] = new ModPath(mod, file); ModData.AddPath(mod, path); + InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, file, modPath.Path, mod); } } catch (Exception ex) { - Penumbra.Log.Error($"[{Thread.CurrentThread.ManagedThreadId}] Error adding redirection {file} -> {path} for mod {mod.Name} to collection cache {AnonymizedName}:\n{ex}"); + Penumbra.Log.Error( + $"[{Thread.CurrentThread.ManagedThreadId}] Error adding redirection {file} -> {path} for mod {mod.Name} to collection cache {AnonymizedName}:\n{ex}"); } } @@ -491,7 +521,7 @@ public class CollectionCache : IDisposable case 2: Cache.ReloadModSync(Mod, AddMetaChanges); break; - case 3: + case 3: Cache.ForceFileSync(Path, FullPath); break; } diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index f2223849..abe5bfca 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -15,17 +15,19 @@ using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; +using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; public class CollectionCacheManager : IDisposable { - private readonly FrameworkManager _framework; - private readonly CommunicatorService _communicator; - private readonly TempModManager _tempMods; - private readonly ModStorage _modStorage; - private readonly CollectionStorage _storage; - private readonly ActiveCollections _active; + private readonly FrameworkManager _framework; + private readonly CommunicatorService _communicator; + private readonly TempModManager _tempMods; + private readonly ModStorage _modStorage; + private readonly CollectionStorage _storage; + private readonly ActiveCollections _active; + internal readonly ResolvedFileChanged ResolvedFileChanged; internal readonly MetaFileManager MetaFileManager; @@ -39,16 +41,17 @@ public class CollectionCacheManager : IDisposable public IEnumerable Active => _storage.Where(c => c.HasCache); - public CollectionCacheManager(FrameworkManager framework, CommunicatorService communicator, - TempModManager tempMods, ModStorage modStorage, MetaFileManager metaFileManager, ActiveCollections active, CollectionStorage storage) + public CollectionCacheManager(FrameworkManager framework, CommunicatorService communicator, TempModManager tempMods, ModStorage modStorage, + MetaFileManager metaFileManager, ActiveCollections active, CollectionStorage storage) { - _framework = framework; - _communicator = communicator; - _tempMods = tempMods; - _modStorage = modStorage; - MetaFileManager = metaFileManager; - _active = active; - _storage = storage; + _framework = framework; + _communicator = communicator; + _tempMods = tempMods; + _modStorage = modStorage; + MetaFileManager = metaFileManager; + _active = active; + _storage = storage; + ResolvedFileChanged = _communicator.ResolvedFileChanged; if (!_active.Individuals.IsLoaded) _active.Individuals.Loaded += CreateNecessaryCaches; @@ -158,6 +161,9 @@ public class CollectionCacheManager : IDisposable cache.Calculating = Environment.CurrentManagedThreadId; try { + ResolvedFileChanged.Invoke(collection, ResolvedFileChanged.Type.FullRecomputeStart, Utf8GamePath.Empty, FullPath.Empty, + FullPath.Empty, + null); cache.ResolvedFiles.Clear(); cache.Meta.Reset(); cache._conflicts.Clear(); @@ -177,6 +183,9 @@ public class CollectionCacheManager : IDisposable collection.IncrementCounter(); MetaFileManager.ApplyDefaultFiles(collection); + ResolvedFileChanged.Invoke(collection, ResolvedFileChanged.Type.FullRecomputeFinished, Utf8GamePath.Empty, FullPath.Empty, + FullPath.Empty, + null); } finally { diff --git a/Penumbra/Communication/CollectionChange.cs b/Penumbra/Communication/CollectionChange.cs index 7c4946d2..96dd61ab 100644 --- a/Penumbra/Communication/CollectionChange.cs +++ b/Penumbra/Communication/CollectionChange.cs @@ -17,6 +17,9 @@ public sealed class CollectionChange : EventWrapper + DalamudSubstitutionProvider = -3, + /// CollectionCacheManager = -2, @@ -43,6 +46,7 @@ public sealed class CollectionChange : EventWrapper ModFileSystemSelector = 0, + } public CollectionChange() diff --git a/Penumbra/Communication/EnabledChanged.cs b/Penumbra/Communication/EnabledChanged.cs index dee5e50f..38c6b387 100644 --- a/Penumbra/Communication/EnabledChanged.cs +++ b/Penumbra/Communication/EnabledChanged.cs @@ -16,6 +16,9 @@ public sealed class EnabledChanged : EventWrapper, EnabledChanged.P { /// Api = int.MinValue, + + /// + DalamudSubstitutionProvider = 0, } public EnabledChanged() diff --git a/Penumbra/Communication/ResolvedFileChanged.cs b/Penumbra/Communication/ResolvedFileChanged.cs new file mode 100644 index 00000000..99cec829 --- /dev/null +++ b/Penumbra/Communication/ResolvedFileChanged.cs @@ -0,0 +1,43 @@ +using System; +using OtterGui.Classes; +using Penumbra.Collections; +using Penumbra.Mods; +using Penumbra.String.Classes; + +namespace Penumbra.Communication; + +/// +/// Triggered whenever a redirection in a mod collection cache is manipulated. +/// +/// Parameter is collection with a changed cache. +/// Parameter is the type of change. +/// Parameter is the game path to be redirected or empty for FullRecompute. +/// Parameter is the new redirection path or empty for Removed or FullRecompute +/// Parameter is the old redirection path for Replaced, or empty. +/// Parameter is the mod responsible for the new redirection if any. +/// +public sealed class ResolvedFileChanged : EventWrapper, + ResolvedFileChanged.Priority> +{ + public enum Type + { + Added, + Removed, + Replaced, + FullRecomputeStart, + FullRecomputeFinished, + } + + public enum Priority + { + /// + DalamudSubstitutionProvider = 0, + } + + public ResolvedFileChanged() + : base(nameof(ResolvedFileChanged)) + { } + + public void Invoke(ModCollection collection, Type type, Utf8GamePath key, FullPath value, FullPath old, IMod? mod) + => Invoke(this, collection, type, key, value, old, mod); +} diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index beaf1960..cc7cc026 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -38,9 +38,10 @@ public class Configuration : IPluginConfiguration, ISavable public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; - public bool HideUiInGPose { get; set; } = false; - public bool HideUiInCutscenes { get; set; } = true; - public bool HideUiWhenUiHidden { get; set; } = false; + public bool HideUiInGPose { get; set; } = false; + public bool HideUiInCutscenes { get; set; } = true; + public bool HideUiWhenUiHidden { get; set; } = false; + public bool UseDalamudUiTextureRedirection { get; set; } = true; public bool UseCharacterCollectionInMainWindow { get; set; } = true; public bool UseCharacterCollectionsInCards { get; set; } = true; diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index 784b7f89..728b391c 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -66,6 +66,9 @@ public class CommunicatorService : IDisposable /// public readonly SelectTab SelectTab = new(); + /// + public readonly ResolvedFileChanged ResolvedFileChanged = new(); + public void Dispose() { CollectionChange.Dispose(); @@ -86,5 +89,6 @@ public class CommunicatorService : IDisposable ChangedItemHover.Dispose(); ChangedItemClick.Dispose(); SelectTab.Dispose(); + ResolvedFileChanged.Dispose(); } } diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index f0864b97..728585ae 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -181,5 +181,6 @@ public static class ServiceManager => services.AddSingleton() .AddSingleton(x => x.GetRequiredService()) .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 375ada2d..fa4c23f9 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -26,38 +26,41 @@ public class SettingsTab : ITab public ReadOnlySpan Label => "Settings"u8; - private readonly Configuration _config; - private readonly FontReloader _fontReloader; - private readonly TutorialService _tutorial; - private readonly Penumbra _penumbra; - private readonly FileDialogService _fileDialog; - private readonly ModManager _modManager; - private readonly ModExportManager _modExportManager; - private readonly ModFileSystemSelector _selector; - private readonly CharacterUtility _characterUtility; - private readonly ResidentResourceManager _residentResources; - private readonly DalamudServices _dalamud; - private readonly HttpApi _httpApi; + private readonly Configuration _config; + private readonly FontReloader _fontReloader; + private readonly TutorialService _tutorial; + private readonly Penumbra _penumbra; + private readonly FileDialogService _fileDialog; + private readonly ModManager _modManager; + private readonly ModExportManager _modExportManager; + private readonly ModFileSystemSelector _selector; + private readonly CharacterUtility _characterUtility; + private readonly ResidentResourceManager _residentResources; + private readonly DalamudServices _dalamud; + private readonly HttpApi _httpApi; + private readonly DalamudSubstitutionProvider _dalamudSubstitutionProvider; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; public SettingsTab(Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, - ResidentResourceManager residentResources, DalamudServices dalamud, ModExportManager modExportManager, HttpApi httpApi) + ResidentResourceManager residentResources, DalamudServices dalamud, ModExportManager modExportManager, HttpApi httpApi, + DalamudSubstitutionProvider dalamudSubstitutionProvider) { - _config = config; - _fontReloader = fontReloader; - _tutorial = tutorial; - _penumbra = penumbra; - _fileDialog = fileDialog; - _modManager = modManager; - _selector = selector; - _characterUtility = characterUtility; - _residentResources = residentResources; - _dalamud = dalamud; - _modExportManager = modExportManager; - _httpApi = httpApi; + _config = config; + _fontReloader = fontReloader; + _tutorial = tutorial; + _penumbra = penumbra; + _fileDialog = fileDialog; + _modManager = modManager; + _selector = selector; + _characterUtility = characterUtility; + _residentResources = residentResources; + _dalamud = dalamud; + _modExportManager = modExportManager; + _httpApi = httpApi; + _dalamudSubstitutionProvider = dalamudSubstitutionProvider; } public void DrawHeader() @@ -389,6 +392,12 @@ public class SettingsTab : ITab /// Draw all settings pertaining to actor identification for collections. private void DrawIdentificationSettings() { + Checkbox("Use Interface Collection for other Plugin UIs", + "Use the collection assigned to your interface for other plugins requesting UI-textures and icons through Dalamud.", + _dalamudSubstitutionProvider.Enabled, _dalamudSubstitutionProvider.Set); + var icon = _dalamud.TextureProvider.GetIcon(60026); + if (icon != null) + ImGui.Image(icon.ImGuiHandle, new Vector2(icon.Width, icon.Height)); Checkbox($"Use {TutorialService.AssignedCollections} in Character Window", "Use the individual collection for your characters name or the Your Character collection in your main character window, if it is set.", _config.UseCharacterCollectionInMainWindow, v => _config.UseCharacterCollectionInMainWindow = v); From 0c07d4bec677182156b56f4f3c649e556e8f3fcf Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 16 Aug 2023 17:39:40 +0200 Subject: [PATCH 0020/1381] Cleanup. --- Penumbra/Api/DalamudSubstitutionProvider.cs | 1 - Penumbra/UI/Tabs/SettingsTab.cs | 3 --- 2 files changed, 4 deletions(-) diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index 42abd1cd..ef6555bb 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -8,7 +8,6 @@ using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Services; using Penumbra.String.Classes; -using static Penumbra.Api.Ipc; namespace Penumbra.Api; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index fa4c23f9..ac834e7c 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -395,9 +395,6 @@ public class SettingsTab : ITab Checkbox("Use Interface Collection for other Plugin UIs", "Use the collection assigned to your interface for other plugins requesting UI-textures and icons through Dalamud.", _dalamudSubstitutionProvider.Enabled, _dalamudSubstitutionProvider.Set); - var icon = _dalamud.TextureProvider.GetIcon(60026); - if (icon != null) - ImGui.Image(icon.ImGuiHandle, new Vector2(icon.Width, icon.Height)); Checkbox($"Use {TutorialService.AssignedCollections} in Character Window", "Use the individual collection for your characters name or the Your Character collection in your main character window, if it is set.", _config.UseCharacterCollectionInMainWindow, v => _config.UseCharacterCollectionInMainWindow = v); From 53b36f2597696ffce4de6048d190ce6b7eb60c0f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 18 Aug 2023 17:16:38 +0200 Subject: [PATCH 0021/1381] Add drag & drop to texture import. --- Penumbra/Api/PenumbraApi.cs | 1 - .../AdvancedWindow/ModEditWindow.Textures.cs | 70 +++++++++++++------ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 35 +++++----- 3 files changed, 69 insertions(+), 37 deletions(-) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 140a928b..01078450 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -8,7 +8,6 @@ using Penumbra.Interop.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods; using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 32cd400f..fcbb054d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Numerics; @@ -37,30 +39,36 @@ public partial class ModEditWindow private void DrawInputChild(string label, Texture tex, Vector2 size, Vector2 imageSize) { - using var child = ImRaii.Child(label, size, true); - if (!child) - return; + using (var child = ImRaii.Child(label, size, true)) + { + if (!child) + return; - using var id = ImRaii.PushId(label); - ImGuiUtil.DrawTextButton(label, new Vector2(-1, 0), ImGui.GetColorU32(ImGuiCol.FrameBg)); - ImGui.NewLine(); + using var id = ImRaii.PushId(label); + ImGuiUtil.DrawTextButton(label, new Vector2(-1, 0), ImGui.GetColorU32(ImGuiCol.FrameBg)); + ImGui.NewLine(); - TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", - "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); - if (_textureSelectCombo.Draw("##combo", - "Select the textures included in this mod on your drive or the ones they replace from the game files.", tex.Path, - _mod.ModPath.FullName.Length + 1, out var newPath) && newPath != tex.Path) - tex.Load(_textures, newPath); + TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", + "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); + if (_textureSelectCombo.Draw("##combo", + "Select the textures included in this mod on your drive or the ones they replace from the game files.", tex.Path, + _mod.ModPath.FullName.Length + 1, out var newPath) + && newPath != tex.Path) + tex.Load(_textures, newPath); - if (tex == _left) - _center.DrawMatrixInputLeft(size.X); - else - _center.DrawMatrixInputRight(size.X); + if (tex == _left) + _center.DrawMatrixInputLeft(size.X); + else + _center.DrawMatrixInputRight(size.X); - ImGui.NewLine(); - using var child2 = ImRaii.Child("image"); - if (child2) - TextureDrawer.Draw(tex, imageSize); + ImGui.NewLine(); + using var child2 = ImRaii.Child("image"); + if (child2) + TextureDrawer.Draw(tex, imageSize); + } + + if (_dragDropManager.CreateImGuiTarget("TextureDragDrop", out var files, out _) && GetFirstTexture(files, out var file)) + tex.Load(_textures, file); } private void SaveAsCombo() @@ -229,6 +237,15 @@ public partial class ModEditWindow try { + _dragDropManager.CreateImGuiSource("TextureDragDrop", + m => m.Extensions.Any(e => ValidTextureExtensions.Contains(e.ToLowerInvariant())), m => + { + if (!GetFirstTexture(m.Files, out var file)) + return false; + + ImGui.TextUnformatted($"Dragging texture for editing: {Path.GetFileName(file)}"); + return true; + }); var childWidth = GetChildWidth(); var imageSize = new Vector2(childWidth.X - ImGui.GetStyle().FramePadding.X * 2); DrawInputChild("Input Texture", _left, childWidth, imageSize); @@ -259,4 +276,17 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip(tooltip); } + + private static bool GetFirstTexture(IEnumerable files, [NotNullWhen(true)] out string? file) + { + file = files.FirstOrDefault(f => ValidTextureExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())); + return file != null; + } + + private static readonly string[] ValidTextureExtensions = + { + ".png", + ".dds", + ".tex", + }; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 8b870937..59cf8b80 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -5,6 +5,7 @@ using System.Numerics; using System.Text; using Dalamud.Interface; using Dalamud.Interface.Components; +using Dalamud.Interface.DragDrop; using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; using ImGuiNET; @@ -40,6 +41,7 @@ public partial class ModEditWindow : Window, IDisposable private readonly StainService _stainService; private readonly ModMergeTab _modMergeTab; private readonly CommunicatorService _communicator; + private readonly IDragDropManager _dragDropManager; private Mod? _mod; private Vector2 _iconSize = Vector2.Zero; @@ -283,7 +285,7 @@ public partial class ModEditWindow : Window, IDisposable } else { - if (ImGuiUtil.DrawDisabledButton("Cancel Scanning for Duplicates", Vector2.Zero, "Cancel the current scanning operation...", false)) + if (ImGuiUtil.DrawDisabledButton("Cancel Scanning for Duplicates", Vector2.Zero, "Cancel the current scanning operation...", false)) _editor.Duplicates.Clear(); } @@ -303,14 +305,14 @@ public partial class ModEditWindow : Window, IDisposable new Vector2(300 * UiHelpers.Scale, ImGui.GetFrameHeight()), $"{_editor.ModNormalizer.Step} / {_editor.ModNormalizer.TotalSteps}"); } - else if(ImGuiUtil.DrawDisabledButton("Re-Duplicate and Normalize Mod", Vector2.Zero, tt, !_allowReduplicate && !modifier)) + else if (ImGuiUtil.DrawDisabledButton("Re-Duplicate and Normalize Mod", Vector2.Zero, tt, !_allowReduplicate && !modifier)) { _editor.ModNormalizer.Normalize(_mod!); _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(_mod!, _editor.GroupIdx, _editor.OptionIdx)); } if (!_editor.Duplicates.Worker.IsCompleted) - return; + return; if (_editor.Duplicates.Duplicates.Count == 0) { @@ -521,21 +523,22 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, - CommunicatorService communicator, TextureManager textures) + CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager) : base(WindowBaseLabel) { - _performance = performance; - _itemSwapTab = itemSwapTab; - _config = config; - _editor = editor; - _metaFileManager = metaFileManager; - _stainService = stainService; - _activeCollections = activeCollections; - _dalamud = dalamud; - _modMergeTab = modMergeTab; - _communicator = communicator; - _textures = textures; - _fileDialog = fileDialog; + _performance = performance; + _itemSwapTab = itemSwapTab; + _config = config; + _editor = editor; + _metaFileManager = metaFileManager; + _stainService = stainService; + _activeCollections = activeCollections; + _dalamud = dalamud; + _modMergeTab = modMergeTab; + _communicator = communicator; + _dragDropManager = dragDropManager; + _textures = textures; + _fileDialog = fileDialog; _materialTab = new FileEditor(this, gameData, config, _fileDialog, "Materials", ".mtrl", () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, bytes => new MtrlTab(this, new MtrlFile(bytes))); From 635d5e05ce2ad4dc923280e615d14b5196a1aa52 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 18 Aug 2023 20:05:15 +0200 Subject: [PATCH 0022/1381] 0.7.3.0 --- Penumbra.GameData | 2 +- Penumbra/UI/Changelog.cs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index d84508ea..ad67dfcd 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d84508ea1a607976525265e8f75a329667eec0e5 +Subproject commit ad67dfcd95912d171f2c9576d70d328bdd68b1ca diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index cecd1380..a91c2150 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -41,10 +41,30 @@ public class PenumbraChangelog Add7_1_0(Changelog); Add7_1_2(Changelog); Add7_2_0(Changelog); + Add7_3_0(Changelog); } #region Changelogs + private static void Add7_3_0(Changelog log) + => log.NextVersion("Version 0.7.3.0") + .RegisterEntry("Added the ability to drag and drop mod files from external sources (like a file explorer or browser) into Penumbras mod selector to import them.") + .RegisterEntry("You can also drag and drop texture files into the textures tab of the Advanced Editing Window.", 1) + .RegisterEntry("Added a priority display to the mod selector using the currently selected collections priorities. This can be hidden in settings.") + .RegisterEntry("Added IPC for texture conversion, improved texture handling backend and threading.") + .RegisterEntry("Added Dalamud Substitution so that other plugins can more easily use replaced icons from Penumbras Interface collection when using Dalamuds new Texture Provider.") + .RegisterEntry("Added a filter to texture selection combos in the textures tab of the Advanced Editing Window.") + .RegisterEntry("Changed behaviour when failing to load group JSON files for mods - the pre-existing but failing files are now backed up before being deleted or overwritten.") + .RegisterEntry("Further backend changes, mostly relating to the Glamourer rework.") + .RegisterEntry("Fixed an issue with modded decals not loading correctly when used with the Glamourer rework.") + .RegisterEntry("Fixed missing scaling with UI Scale for some combos.") + .RegisterEntry("Updated the used version of SharpCompress to deal with Zip64 correctly.") + .RegisterEntry("Added a toggle to not display the Changed Item categories in settings (0.7.2.2).") + .RegisterEntry("Many backend changes relating to the Glamourer rework (0.7.2.2).") + .RegisterEntry("Fixed an issue when multiple options in the same option group had the same label (0.7.2.2).") + .RegisterEntry("Fixed an issue with a GPose condition breaking animation and vfx modding in GPose (0.7.2.1).") + .RegisterEntry("Fixed some handling of decals (0.7.2.1)."); + private static void Add7_2_0(Changelog log) => log.NextVersion("Version 0.7.2.0") .RegisterEntry("Added Changed Item Categories and icons that can filter for specific types of Changed Items, in the Changed Items Tab as well as in the Changed Items panel for specific mods..") From 82ba2cd16a45c4cb9dd544db27e09e0a1c51148c Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 18 Aug 2023 18:07:12 +0000 Subject: [PATCH 0023/1381] [CI] Updating repo.json for 0.7.3.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 760f1ad1..0e4bba68 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.7.2.2", - "TestingAssemblyVersion": "0.7.2.7", + "AssemblyVersion": "0.7.3.0", + "TestingAssemblyVersion": "0.7.3.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.2.7/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.2.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 4c611530f397aa6463bd01a7fdc728d9b3fd29b2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 18 Aug 2023 20:34:16 +0200 Subject: [PATCH 0024/1381] Temporarily not use dalamud function because it is not available in release yet. --- Penumbra/Api/DalamudSubstitutionProvider.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index ef6555bb..e608b854 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -42,10 +42,10 @@ public class DalamudSubstitutionProvider : IDisposable public void ResetSubstitutions(IEnumerable paths) { - var transformed = paths - .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) - .Select(p => p.ToString()); - _substitution.InvalidatePaths(transformed); + //var transformed = paths + // .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) + // .Select(p => p.ToString()); + //_substitution.InvalidatePaths(transformed); } public void Enable() From ebaa42f3111341218272e1b3fa083c48561e5cf9 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 18 Aug 2023 18:37:27 +0000 Subject: [PATCH 0025/1381] [CI] Updating repo.json for 0.7.3.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 0e4bba68..23e4cc96 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.7.3.0", - "TestingAssemblyVersion": "0.7.3.0", + "AssemblyVersion": "0.7.3.1", + "TestingAssemblyVersion": "0.7.3.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From ad830dc56e19b664d99adac284edb26079120436 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 22 Aug 2023 14:18:29 +0200 Subject: [PATCH 0026/1381] Disable UI for textures when converting. --- Penumbra.GameData | 2 +- Penumbra/Api/DalamudSubstitutionProvider.cs | 1 + Penumbra/Import/Textures/TextureManager.cs | 10 ++--- .../AdvancedWindow/ModEditWindow.Textures.cs | 37 ++++++++++++------- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ad67dfcd..36df7a87 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ad67dfcd95912d171f2c9576d70d328bdd68b1ca +Subproject commit 36df7a87680eecde48801a38271f0ed8696233ed diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index e608b854..07da761f 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -42,6 +42,7 @@ public class DalamudSubstitutionProvider : IDisposable public void ResetSubstitutions(IEnumerable paths) { + // TODO fix //var transformed = paths // .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) // .Select(p => p.ToString()); diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 3b4c7f67..8c7ec609 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -186,8 +186,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable CombinedTexture.TextureSaveType.AsIs when image.Type is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC7 => - ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC7 => ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), _ => throw new Exception("Wrong save type."), }; @@ -344,10 +343,11 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable if (numMips == input.Meta.MipLevels) return input; - var ec = input.GenerateMipMaps(out var ret, numMips, - (Dalamud.Utility.Util.IsLinux() ? FilterFlags.ForceNonWIC : 0) | FilterFlags.SeparateAlpha); + var flags = (Dalamud.Utility.Util.IsLinux() ? FilterFlags.ForceNonWIC : 0) | FilterFlags.SeparateAlpha; + var ec = input.GenerateMipMaps(out var ret, numMips, flags); if (ec != ErrorCode.Ok) - throw new Exception($"Could not create the requested {numMips} mip maps, maybe retry with the top-right checkbox unchecked:\n{ec}"); + throw new Exception( + $"Could not create the requested {numMips} mip maps (input has {input.Meta.MipLevels}) with flags [{flags}], maybe retry with the top-right checkbox unchecked:\n{ec}"); return ret; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index fcbb054d..4d36ff8a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -5,11 +5,13 @@ using System.IO; using System.Linq; using System.Numerics; using System.Threading.Tasks; +using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterTex; using Penumbra.Import.Textures; +using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -48,18 +50,21 @@ public partial class ModEditWindow ImGuiUtil.DrawTextButton(label, new Vector2(-1, 0), ImGui.GetColorU32(ImGuiCol.FrameBg)); ImGui.NewLine(); - TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", - "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); - if (_textureSelectCombo.Draw("##combo", - "Select the textures included in this mod on your drive or the ones they replace from the game files.", tex.Path, - _mod.ModPath.FullName.Length + 1, out var newPath) - && newPath != tex.Path) - tex.Load(_textures, newPath); + using (var disabled = ImRaii.Disabled(!_center.SaveTask.IsCompleted)) + { + TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", + "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); + if (_textureSelectCombo.Draw("##combo", + "Select the textures included in this mod on your drive or the ones they replace from the game files.", tex.Path, + _mod.ModPath.FullName.Length + 1, out var newPath) + && newPath != tex.Path) + tex.Load(_textures, newPath); - if (tex == _left) - _center.DrawMatrixInputLeft(size.X); - else - _center.DrawMatrixInputRight(size.X); + if (tex == _left) + _center.DrawMatrixInputLeft(size.X); + else + _center.DrawMatrixInputRight(size.X); + } ImGui.NewLine(); using var child2 = ImRaii.Child("image"); @@ -177,8 +182,6 @@ public partial class ModEditWindow { ImGui.NewLine(); } - - ImGui.NewLine(); } switch (_center.SaveTask.Status) @@ -186,7 +189,8 @@ public partial class ModEditWindow case TaskStatus.WaitingForActivation: case TaskStatus.WaitingToRun: case TaskStatus.Running: - ImGui.TextUnformatted("Computing..."); + ImGuiUtil.DrawTextButton("Computing...", -Vector2.UnitX, Colors.PressEnterWarningBg); + break; case TaskStatus.Canceled: case TaskStatus.Faulted: @@ -196,8 +200,13 @@ public partial class ModEditWindow ImGuiUtil.TextWrapped(_center.SaveTask.Exception?.ToString() ?? "Unknown Error"); break; } + default: + ImGui.Dummy(new Vector2(1, ImGui.GetFrameHeight())); + break; } + ImGui.NewLine(); + using var child2 = ImRaii.Child("image"); if (child2) _center.Draw(_textures, imageSize); From bc6e9d1d84516408d04ceee12cb1ffc61538ada0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 22 Aug 2023 15:18:30 +0200 Subject: [PATCH 0027/1381] Update DirectXTex/OtterTex --- Penumbra/lib/DirectXTexC.dll | Bin 585728 -> 806400 bytes Penumbra/lib/OtterTex.dll | Bin 32256 -> 32256 bytes 2 files changed, 0 insertions(+), 0 deletions(-) diff --git a/Penumbra/lib/DirectXTexC.dll b/Penumbra/lib/DirectXTexC.dll index 083c20e9efd442251c355fa32f721295f3f6ef4d..5e0aa0c43150ac1a01cfb8e0e016517559f6328a 100644 GIT binary patch delta 239984 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 jzIx8;^3|2At5($#)xQ4^>>8Ct delta 124823 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 ahU>!hVTp2`ky$nuZ(g*yb~Bx~_kRF@j05EW diff --git a/Penumbra/lib/OtterTex.dll b/Penumbra/lib/OtterTex.dll index 32744d0dc101a9eac49f9111cdffddd8f23ffaf4..d4819ff2a44a62390ff6e861cf98b902676fd91e 100644 GIT binary patch literal 32256 zcmdsg34E00wfA}6d1p_COcoL_z$l9&gfttA7L_bOq5(n@HbujbOp<{~CeBP)1T|FT z;#Rd)YQ1W);;pUPs#jaJ)>5^$F1XyPt!-`bYF%!z)oNR9UB3T0?=mw1tlr-5cfa2^ zF#qSA^PJ~A+j-V`XR`RT%gI4RI^G|DOmq)Ie$5yBWEeqoVA6d7y34!&=zCP_{-Znl zW2w+kGSQce41~HPgM*25Xk9dv93BkC2189tJ3<4Ao@ix$zHf?Yx@`eb&rXf@ZJzNR zE4R1kn2=wqBH9cI7tDHvgcwmAFs)^xZMA)d9Ef_Yy}+)?e3tO5zz9M{z-US`0;cv5 z&EtkS!mI2nM01Z2_o>7oqUJ2c%5-#d8vJdW0Em;iqkh@15YgJoWGdMWp_FY82(I|q zcxS!l+m+4|9)aXCXyl}HEzw>WmbN{D?k9;SYT;5M-}Ez$P%FJO3}aKrI<7qjCiUqj zm~zKxmisU(7EP{CpI993ByvrM(TQd_$qYkgc(fTFV}_H>5Pl`;rkde2Gd$J|Q7VZ) zj>BWL@N|SRCT0kM94kzXnPymNhMzM-_@!8==8%f2T+&^rWN_?y-`Mqj&9PozUr2>2 z;0)J5$LWf726T65^TFowc)P#yb`KK3I8{nTu5(?^LbGg{MYG)WL1#~n61i*eXd z<2kCqh#I3r9kx;SqAHD$j^~V^W4I8NsTkw9i9?^}3ZKL|kL7;j5=~!dW}30kK3c*> z&MsS03!jLjQ)lYaif1?zXdK_vnXYL`G|SNRQIX|lYzI0<+xk9u z?%=I|vxpBY;zJ>7w5=b3U{CW+Ut%!YR*6f&>wMFvX}Tl4l zS3CrR=W2-Yx%_S|973Wr`uM24^H}I{hr!J7x!kn}*k2Bt25$VxX=2ESU)t1}lczmh z3?dAd_a)%(z66}z7lx-xQ%P%tm!Z7pDr7%%)+p_BYayLFvuIlJN3P}2N}&qAsUs{6 zV|4gRM>v_$*G@u@Vs=3NFkpN>Em?wo;6dZ7I4<0V)G}~}9!0}C!c9=TTF>Qud zb30rKj3S?FdZiS~Xth(cFou**+jbo1*v;))V=_I=py8^NJtu47RS^CL%{mr|emz}b zvPN@~$3t#zkJ(02M>uMvEvnK94n!^eAEK$F6smu7V#*<;7U6=KFRVZ<`G@yTSWl!=7!WESNjUi?S5bMG)gZ*EZ`O<%A z9$J>QbJ*G;w$_if<)r_1d9h|5w!HDtd3>t!o_pBx4vx0I*(6P-t!Jy z-sGXS;OC#gA2RN+%_uJVTO+IvmOq5kxmk$6U?|Yx{2^m)M68XrwK2!meObdqoHT0$ z7^L_<=JM@q?KIP~P5;&O@NO0#;&Wff$>iLCZVZTkZuq^d_RjTK>%YRuQ6Cp!BV^Q9 z=8S+I-jQSDqJY!1;moz6uMfDwSBn|gamzX@;|O*F7#zrC=V!3=Rkm~lJG(xEoohb9 z&P6$P&K%vQ&hWo-VzdX3d#qZPA2{^zB{@lX9>lavd6*Y6a}Kh+mzUw;JKUm9)OO(Q6GKH6kbxkE24 zbz;BBF5q*88xinI?59$ZY?I1K)jqkz8 zp<`}Oj%gVS^U)6c`fS-?;ScE63U!Z>my@uE$@rl&{PmpN{`T2&2R(K}didu58SD46^}~(-f5tv`bXMtq za3uS;=9K@x>7Ng<^+V=>Z|9i)j2?rj+$#GIt+F5Dleg#O@ZT)_KEpi5&!|1wojKM& zTlrCZyZk>oV)^gN$pPby=l6vO`K5)|B6@2z=ATLBwLZ;(S#1xS%8CekAgDmxr1CHq z7boILpiy-U;RoBK!&}6_a_E_d{clr#U(MT%$JKj_~ie0qlM);PUZa`)3f#l&te! zTh6VoiYB+e;RCkrb2+*aKk<|Eb%b9tj9L3I(^mNBIi`-$9O2hRakSnGIeNyN@Q>^I zhG}b5`G1vTOzQeyqIsCQzL=wny6W_g^Zotd^Zjj(Ey?%bk@9^hN7uU5qK1xB8kBj{ z#{RXjuCl7KwyL%oUc{&EIPh|8eI}nv^Z~*Vbj;+AbTT&Bmtu`=owzeaIC*&o9RQ7f zpvjAtw=^Mq3;bPh*vSp?#5(Z&(r}bqdER#?c_F92sahHf0Z5$a=qS9g5g^ooN}!1U z#Kl+%*$oIe3F~qm9P%6Y0aS+f(I#)nuqBarob<#F%i)Q5Jw1kLv<7+o&Jq{>T5w|? z(@EcB#YHp~i?WNpJr3bzxJfi@N-b z^L??2E}H6N`xoVnEpSm{9OG#|#{GWA$AXMkj%U16%CnW2Zjn-b(aZEwk=#C7^dILXZg2_8DE9v0R2&a95uaO za`~;K+8X$(=A#J{SpRIvaR~Og)!^57iO1mjqsaH@*kv}i6Ln;c`?!FrQ1)e@(dyu? zL9LeIrp`&Y(V=t3UR@qRj7zwyz08d5Sv@87CAlz8SbCOY?e2zER5f@i@l5qZr>E&v?Jc zgFxl^#SjAKs{xfW#lX_3z^V0xO+PfFV3L}#Z+iUdm}?E^wj6Z)G%zaje9iiNL= z$>j{i_TQD*Geq+gp<|-cCV5Q|&6h;pEIM<9eo^d)L}!-Z6(XM~c&AvH zT+a625ZWj7KA}@$Q;B4Q*jy>8HcRXpu~sZP#|a*k*iO-G5PH98o+Gj4VrN)l*GlYC zkzXm2A8K5Ns7O`{{;QPyVu?LYTHr&GJS>vgBJqm-{UT`;$vly~B9bYB%_4bI=$V3l z5j;n*Me@2p@HUa$Ao>Zh_6wo63;lu6`-#i>u;31n)JWPk(V6AoSii*nP;i5w61-dR zM|rHXQE1G#pzjkrS@0WzUl)8$@OOgGOWB?m`d5Mn1oeEj@Pyc`K?_@R!W{ZKp!V6)(yB9_b)dcNQi!Cl2H-z4+{LjQ}-l7m6UoAMYR zle9Amnf`l#v8$YMo5&Z7{tF^$5OjDr_D`bul-Rjk(I@l@vnt{~m2|Hv-Sh2AHjvrS{v3mKObG2W&a z?-2Q97t`TV#sXs8CHP)B)B8)F%(C_$ki4uhe#yZ&Q85+^Mv9oe0kqYs7kZzEu0p=XHZ>T;HE6v-l;>3NVS9QuEm(@KgSk(N0t zpWDq*%I!7-D~pT1LYJ9s=%R60p~lkK;@?1WatZ5ff zW^&Ky%I%=LP3{MU%B|B6OzxT@<#y7KO>Py^VRvY97mrbHH$7)*D&_XjizfGyrrcio zoyi>qO&`5!axa4O)1OUluS2=>=tGn18RK^66C4t+-PBp^b_ZyT$$eSnyT?$e$qf|c zy9;QN$$7`+yMuJBr5Vh}=WU-ex#;+OcM;7oxvRa!?qZs6a^nL>xl1T+bJN{N(QcD_ zt>k#O6pKdaiqKBf{TMEmaMQp|vAJKO1*h5EkI{l*o4XM$$Y*6ET@>jmZ0;JgM5WEu z!Ah0QH54m%jm^!3W}VF)1cw`5ytrf!papSxX>wn69~yT-kQ-W6^qZN*qw zN=iD0xqkOj8e?)d7Y@1GNbW@FRdrzOFt{p-dxQ>*-RfRO%T4Y)SBGk+GlbjiSvqmV z-A)OUI~`mn?J&7$`5N~My4+0nm;6CmNw*2N(-Uwp_n2_T_*+TO=WxF z$=x!ZxwlO2Sc!YzlIBhaF@J>%j=`Qz58e?+L2QL9P+2E)p|0;0&VxRDPuXC@a znG(0#Q#!S9va{r)}=*o-fk}Hg}t6Hf;q4K_Dp!a>i!+1$W{zk6=6x$jKyd2hG5M?9t8yKFAcGu4X^ z81UkLIK@-zz2D|`dFs9UY)FBB zW^*InpHa%>3baeSzo4sa?pp6}=?5lvBI15W2W;+I??H0PB)yyd(|L*aPsC4faDM;k zyw>|ZEjGDr`QP+@O#L?ZJ+DLUGPxJaAN0D^!#4M<*QZ`Fx&L&&>Vxf@GX`6`^-JE}sZ>4(6=63r|S3x}V!s9(v{x#p3s?FwZ^{rE9ncO1p zcYRTHtIa*&>s61L+}hHIzI(KTo}4 zbL0Hml|z>Co#ZMC`M;o=Y;LB1r|LJk59qtT3+?v&n|F@?BAfe8{zCs{Hn+8WrGK~0 zt?~N2*V)`qY0Q6v&2{K8|2Hz6dyD@zoBNq#m;c{wZuYpZ`0uf~mE*qY|Dny57Tx22 zSlwro)5B}kU~=90PI^+g@T?G8-t*en4)v58V{(5U>!hbtxyij*w9Eapsx!IQ3(51eYBjkt z9n7sZxv#q(^FOV+P40HrQ{Xn5++UFH8MWQu=!Wv={LiS%h1*RN9KZHItM0eCgZ`hZ zU)kLI{uk8iHmB$PT6tuPwwqqi^74M8>TGU&-T~Eab5rwPQfq9kGVf)z&E)b_UEV9| zW}9oudrkes=9cBXp`Nw5HF*csyC(M&)sy!J72*qO%nUzK>Abhq$u_q=?;X`@bC=}( zMQsqySPkE^d-~huSLS87qKVh%ePGAE>iJflTvE$y^UQ?1^BfxI#&gfjo~d~*n_E2L zhj|{GtMELYmuGXAO?Wd2o(%tFg>Yw%|c+!|T+1^xXzmOS7( zJQ}gj6mjf+SWxtd>Um2K@ODBGvA zW@&zswHJ#&tu;&2u*U7SAEVM53z}xksD_-|lO={P;Z_YFw2s!y_~#=fpQN8XhZ~y4 zJeF<#7vS&+{@aKw#FB!RH<`9Q?MW#11GitUD=cQvM;#TE; zccI_;dFn&0WovRzeL79f+@ zN6L$P)`@l&e>*~XK8+5ywiB)WkL?_(B%i)6hUSs%7^USNamlX0Y7=Wu!fk#edi1V? z=L(+F#$#__&2oqC6S8Bi-4W+vr8Q_qV|C`4$J!TJI{%FQ&zhEJ@8@KXH)^LOWoBQs zb_hI|vZhg5VIkA$qfnzKUn|`E!;a(23{B znLZlmqiSFQp73F;7iI$SSpbE)x3U#3V_*oUdq2wlb6}Vb04wMXU={rdSVw;c&c#=QJT#y3flX8h zY^G9RE0qJ==xAUkP1C%1$|xVW7CK%$<5ddmhmN0O$k&S}!;Xd|EwP&=b{iyqI!9th zXa-_;P!(_&%>rIRCjc*}lYv)K6Yy$k0bWZ>fP1I|xR+J|Z>BSVx6(S`?bHXni{ik0 z=q%v;L0X^z6V4k`XSfIWNELPV8%hZj)a&q_~b#)NR19x)WHTz6Y#Q_XF$HkAQR4 zBfxp;ao~LQG_XlM2W(cq1h%T*0^8Ipz)tlBaFzN4aE*EgxK>r6JtK-+yGOkTNx%9K z7+0FZOGEf55$&(?fSXkixJ`|96w*10du>D=1<4K-0`5{%ftRT1z{}O=fLE$I;MMAQ z;I--`;2zZo+^d>_H><_KTU9&ocC`|Cms$h7M@4}5t6tzfwE_6B8Up@Q4FjK0X9J&B z=K-HpJAl7X7Xp8+z6d;^*au!wUv~KEcT%I*)zy$6RM!FDQeTJsZIQpLz5&U5>Q>+f z>JG?16gg?%g+$lB4~bLbHt}ftAj#8y3@p$dgFGnmV(lqN%Cu*J<=P97PY`)X`wb*h zw3mTl?RChH6M2R9CL~qbpCG9gNuBmrNakuE0Ox5+_tS|YpRc)e^q}SkHfsftw}`w| zD}kg<8xQQ%CPBVjCtL|{n}h$Tssjsq%{E3+9Kd)trfUU zTLv7_Rv_(mNxMTk9gtIIs3{Jfqrwj5MDIAbBoz)H=qg7Muv#Q_j&jg*9aDkx1m`;{K{q+(0Gl22fi0rh z>SzJo=4c0YI!*_!a`XV#I0k@ch)$1Szk}-=cW`}nuqZkDuLL}x^Bhm>=dl=BkD zM%cOBp<|q0A+c9F&V%G?Df6{rXOGy~D|T*{+;0=j+Xe5EeD9Hb?{{!J?{jcVKJ3^9 zJ3khkpGsRjA#L@v;|j>1l@|Mj;~LN}iO&1L0Da)N5&K`K{y5}bom;N}h&{GQigm7I ziO9=zu4%c>d4=?!L+5DGnWA(5P8FT7&OKP6a}QSOe}Yc6=+x=lN3%p{E;d8x1)bZx zUL;L|&5~EEKZDP4oY_1ZUt3|#>e-LSVgpLaKOWL@k9g-5J1viU@ZDL_WEbNf9 zyL9%eOHe}eg_P||oqgtNoqgt7oxNp`&fXGpa+?eT^Ju$sKO`3jeW}n_fcDUJ&V1D9 z2BB{f`kO-EA@tos-z)SFK>O(h!50PJ0Orw~V(rgDzb|yq#qtst=Qu&=qlI4WW(yI) z0l{IxuL|BEc$?tef`RPZ^$7lBjpt;U0{W9fXXbjQ+k`c_~%jVFJg65nJj)GF~E z*kki6@pN?+a560g&Y)GmTG|c#JlzCrq&tD9(xbo*dLDQ>y#(wQ+(3T>odVV(uaEN^ z>0(%J#5b1;wFQ!Uw@A80(oJ8cvcUNwIbS5_LvnK9Mv>eok{coE4Ln5u3JV9MoP?Gr z)Ix%j70c%f-6(X6;ySJsNlfSwq0blGBY2}|epB6owEINzkVp;){j$)6zAe-o8ru&E zJz41aLN{v1kTcMTFEAW*HEL{Ut;k0N&zIQqC3cTUZj`k9gnmfq146$nG+{kKUJkbD zz{-5k6%xs0kxUlJe33LdF6O+1?ndlESC8XHx->8%l0AYWF4o!OJ_hZ7KyaUzEgujh zAIF9S=L@bC9PzRK6#p%p*3Xvr`q?-33H`9pl+W^zU{5}4jtIR+kOC4bI3l=5P#;r> z+?xb@3Ygw2xG%{1593?gD4Wn!$P&GfB_W~b3$7I$5!@pZS|-cijsrG`lDcrU|yIo_-BJ_GLv-ch_`cn{!x7Tz!7{d>GUIA#5Z^8`AXVss(BN0Zd& z)I8OoR;q5*uaY=>T&=Fh*@HiBx>d)B1yzI-UNO#PWf+U&`1?I{cix-$#G%mjHt@>< zrtcfiI74WM;JDI1L-Nbu`@jVgHQb@Kmbif9N?G#daRs1D^b+7Zc@u%zcJ_&dzI?X% z{#eGhi`d%1Le^a8V7$w94DfG|c&Htx(gMsxd^)W|X*F7ay9y0w6*sU2W!LablOK30 zzLToq^fCsx7^h4PXP6??aT!p{aT^Jn)+)p!rPtr`_Q~1`fqNjlxJ%iJ2 z8NQ7$llF}{7T@??NLz6tAax?)={B4+P9{9phOnOSL>t0J!n14$7Z9FeL%4|W{2Ia* z!jo$VPbECFhHx?AX*GmP3D2n^Tt;|84Pgi2*))X9=`7(_QbhDt(boPH*D_R}Oc z>pw*yJbOgy9eR5LhkvFS68@D2Bz&K~gHTt0r$;;-en@!|eoUuGsMIbA9ZDDbGu6L{ zz0axF72B&;6EqHM)hQCrQg2K9%uyfU*-KK#s~b^XQlD36OL(H{knm*nW;x3f>ThEA zEcG3+n^IdvKCIS=e3Kd~WxXw`L)vSr>X3S!qkbmsdY+ms_1&&kN_f61mG*p8eOv52 zu8Q!$h>p+UUqwC89_ksX?=$LV;eVzU3;&#|5dP=tGT~oP>$%<|NP;HR9MB}Y z!%zoUm`HXaHQih4Dxqezc^e zzOIhyTNt|2vBcooIzpLebD05kfQH7|%^eF(VmT9SHC1zIg+Lvs`nhd$Y2M;Q&u~0? z5-m(72HF=j)YGD9TEf;uq^EOHy+laJZP0-zYUvwHBn`5mv3mKEL~=mn4UIL~Ol>wZ zC&RSQT{O30ZvEVhqydul!$?+T>2xNHyi*c1MSCN|@wCv=Ib1F-@yeD)qt%2!oovC9 z#30ixgRyih5|5o7t!|=JcQTUh?vD*b`l4O2?3hSAp4bG9&gf=fCQ;216Cno5z>IS3 z5tR|MC^{HL?$O1up~aD*6eLIvY>oCsy0Z+-0XltXc>e(DDNf=?*T;|%3UvzxK@e5{k^hc7>o&~Ggq-mO)+NCo&Y)LgN zYUi$Au(>-r#14d3Y;LE{{$yg)C>b|vQ&R_ZL^eh_WKZF+lU61pL(Acn$z&qAoa$FE zUm>CurpVw{n%qj-$gbVhMSan9S4*lb867|u#)jgtXit57s6Rp-(V+-8iNQ7Y0NHl6~v4g|U<&S{RF`qshkMb+PVTSL-wTzH1;h zG=R?Us_mi9OclktQobjIRPGdzbHhI@OXNqnhwxH~-zSAw0!!~j|k zB^hn2I}_2ovMrfNN4wKd${JQiG2+p58l!J?@}Y7#pns?}2O{qK2a#`Gcq>)`` zGSVHTR6GV;uo?4rPwVhNY%nqi-t4xFK-{i9iuQ|gJjPmEY;celfsC*{n!*=`yVFK< zgG&r!l4V_ZcYh;(g^?EU;1a5-wn_XOGqzEt43|O)Gh8<-L?l_BhOAn3XUgfNvSxnAm`zDV7>aq_{y%cV$65vPC3|npz}XI+lrF(%FnI zgL?b$U^+Gs?c6dHH6^G$b3C<~lFnodxj{LnJ>nRlUD6WiJ`@>ah0@W@JSp&WA#ITx zdxX@RV%?vR+KxR!>i(YOC#1GxkC3{jC-n)b?bw{uDa`#{=|q*#Zlm;2h z<;iSc^xPnNKaHgu12rCPi$?}WwP&}X!KPE9(}f;{68dgk3?UZnsJSIV_wdS&S)F?- zdm@vjPqQ$m%*kjx8c9VdG1Rp%5(i;847xvxQZWyOJ}fu1FdiE+Hg>rddLi$^OvXA3 z2G&J;FtOIBF=E#ZL&E+A2S{2Ac~;bNu6L|A#;(X?HF8hz+k=eADgzd`=nAysVIx}xIj;zBEF$qkv^t{Q!^v2BOItKK5KA520(_@8);Emp zKu!jjJ3Au1(e##f>{?TqQpt{aK|DGT9Za)7W<|-4IiqQGo0x5n#v_}B%2K!Lhb62B z%U&j-6~Rk#GS=6h6=n4l3XSO?E21T3ZTAmn2lLwCmP~{>Y^-@JhWR@ywqXnV9Hv0* zi5jp5TDt?GdA^jD(b#0s!n&HOr9+Xkpw_`FK{UBA8tqw!H4O7}d$bR2x*SWmslusS zjNKHrSVu}Xh@@s*&N#z9!kEFaXYNWEnPSX!CMENYJl=StBFkufG8x&@f#siM$+Eew zh)rg;&$)v!vntat$gW+~-Pi!)^uyZ!3tUXq@q24tlhT5>Z#g8rz^;1(k z-ZH>Lvm+WwcK5eM(*0-=n;c@Et*?yrNQ^~wZ4v=TwMGZ~5EnNBmNa1}&t@#Dt49Qh zb?d1OlTFu8BCUq zb&z)rMU!YVj%i6rwK^~lb;oiPk(pGm3r8Y}TY{mCBT77unVxrptFYl~tn2~5G>r`| zIAJn1ScoHfcGlU&@8vk&47Vi`af;#8WqJ-Z4yV$I0W@S?2OoVw%rc1f>e-8M46B}9 zUp+fpV$&vJo_{l(MHykktVOfhXVn`AYgjjlb~~(ER9)3jT~%+KwyC|^6s&4*h~ZFV zimlT)EEp$oYN%UO*Irj&CkJmXzeUV4iCK$gx0`f!U5wbK>e&WiMA@{Nw$V7@Q_kt0 za!&Tdr+hy9n`wn!l*L(c)1=%An0EjeoR;4ivC9YLjF;Vgau&1wZy1*p1GHdp7##;! zZy7X(HKtr^7G0E#MhC5F)L^i;gu{2l`UbJ}FizsK(dRXa&ks%5Hp+TP=DYz{+KyDC3AvU+T9&D1Tt0=-LlN!glnvP#-)ut7e#yH@K?^GKG`?SYuM7^^wQpT-tXF{ zaax39K|8iUIg$*sd~m~HV$&c-%!*h~G?CphaO{mD!}Olmv^X)CAU;S-i{MCyLk_MW zOm0OYjuJ3$R)w8B5@$iqv~Nvq+{}@97ml%V_$M4`d0v*2Ok*624_Xo~3WtT;*4HeI zZ5|#nu4r1Z!;2)*vnF92mrW*XMv#7u8_GDyVuOfOS@EbH?;0UA&Z|^!bP9K^NhP?G z%wqytjJsxIbS3s6ka7pLC1QLA=7JyQK-QFmc9P~*oz&H3&)i(cIEy>56}F~xTbNtC zb$uwCG2b;N;)$Hn+w)zw#K;XyORpUJ%$pOcq zB9b;~b4T73i{R2Og{eG67!lm#Dck#u(@>?{0wjhyqREX|`VNU^Z{Y2&9dB$|v2gN% zG-Y@X9}iQw`W%q6q~v8%Ilhxw%e!iujPsNnAyc`P%u?fn_@`2ojYN*7_ z<}r)I?O7I=Iei$q;vsEv9b%@&*fXMx5n`zs7cmCc%h$rxl#Fa@8SIhO4>L&$4%D4Y zq!PX9N;!sL+q5MWOA+5k$Biz-rmhv|A#l8L$Z&i*HzVRkyo?iGlT&1@%_(ZY&ETre z!Olnw!lqS=TI}FgDClrWpMX>8PN z+FDd?fwivMg7%uaMRPM8md-53CXHmPvf^rtO+c22KR2)wWLDkmv5~XT$|y==$CulS zJbpyl6t&5mIiM#aw~s)^k(4`m4vr_a9mDJ3lvz`YY!;XH_KMV)>}7PfM>eg9MK>8f zXj~G|Qq0XsEP5uJlQ&;8aU5Sd;gpIkRQ00jYAjLGpE-UtN@B20wKdstn>LB8ePFi4 zrVS#~wg#WIWaKn(S1-@!v~=Bi>=7s}XMMs+CBkP=nRc6_Lh=AM$*z7wgmW0q892(s z(tHnsy^KMdpP%3kIfXlT>K#BEWDTYctOXfC7H5%0m{rd#fkhgjZ1U>o+KfpUK~|Q_ zbF$3hEYb)w<5l=onSn23Q-oIUbnv(|lVx`1SpthRLbIecBShAC$4*tsXar5>$muXx zcv*K;;>|fa!Yyd-CZauZF#w4XDZ35skJdyVAFh@p(ilau^&CBj3?Xk|u_Lt4G1kh3 zxjwo%=LXVRwqg=v+$*0N-4g9tj8p4oYDjF(y85o?LpOEfKEpVFTc0-`Z|r=?Hf_!5N>@WAtR4hT-@g{-7*-pICFbuEt0rp9D)vh9CZmLD1;|F zlK7XvyOL;96P{y9;#Uy6@of1jeEf#zUhv6vC7wW!^RJQ4XrV#ci03zOT!kzI901n` zy%54~{KK^i{=pVrr~H1yU3Y3fU-YfBudl5>>)h{=BScCMDdlkjf+b7_gsc}_&Nw09 zDkuMj_G2cI9*-(HP~K>~>@sKRk)YTM9?+F#hKiD91!9n25jHGm-L< zVWwmrWH@qfaO4Nh5TT?fL;zLNRCyVml0npkg(Fv?^kpbY8J?lh5KDl7i|K+ge@K^F z6lp~chg*qC84#sJrB$%iEd>v@I^Eg?RNActdlnQpJt3Mja$Nx)B?^%Te;A~2ZLnGQ zslv6KrpN2n#spgz6a-rf+|FRL$Ef=lClbQ42Mq)Th4>ycxKHM^ZjxVN>j&Fd;*B43WM?7?V zH5R|%%)q~)tK-=b(($!z((!$8{IE5{(G15h@GlPOQy8W)Ok+5fA;R1%83?Jj=ae(5N2c9M`kJ}?yPY@%9XyPZY03K5f#n6%9k;1{P$=szrz(Q!@FE_c@c#0o`QE6?+U!@@ScnJ zJiO=Q-Gq0u!!-tpwLC0M_L>BFC*G^@UW0dBcVVgr(WARC`#Qx5bS!92OtNZ%6MdjC z`)a`oo`ZuG`1$2vg%OkoD*}XEf)yT50saNc0+?!Km19w`42uO)@Z#pTRsH?~{F68c z{bITqi22@Kr4+AJI+mn!c#6lY4lKvhn;>OnEc1lOSQfC32Ac!HP9Hgf%~&#modFaz zfXNms86d01W5`j)%P|sOs)8d|i0KM%2;XT#!Le3_9KlwQUek846(zu`Wh_>~9!H2Y z{?+M%U>r+@h9FphZxxk+@MC#LaQB5zb0FMO-6r>slNsfxMr2dhvnWZ4XS{KLs`)1C`o{@)Ry^!omf^; z4U1is%dRolJS;CzHkf>7P?H?aOlQWK$^6_l0n3Es2L?TsXLKGO1z#KFjYr{Hmcxxq zukuI)zPp8ZcobY}47m-5L(g%dJaUj|L@OyrruU`1YVu9u}kxkDIJNX(;YtuMr* z1p2|b7&sC_(-7skM3QIcHqXdyUdC{6K4QhNP-dwr484jhy(U|)DbI8zZk9S!vVeO| zdZN_d9sHUyCjBHuxHe;WjTgbum{ebJ*|HIjpcZWm#a9T^`<+X3!emu*<`n z?dA+`$a#3%`quDfxv9Sf^A8V0IGOm3Ie?9MK!&83J=$n)b}T6H&@>g8w9@eyHN{Li z!uaN0m;!j0dBWyo>+n#(YciM}!#q2NWh*ZU@W;o{uGnfD>ogu}R`^QeSbhi+kEz(7 z!^j1GNZ|tmPT0M4TPrn0rP2!c3{`0p|1JH$4ACfn^6e7Era-6 z1)rkyuv#m2;h#c{o8=#=;mL7U^H`s*`#Lfo$Mb2&k4W?7_`?hLG0FP8M{WBG-h776 zdKF~ROtyD4b?o=-N&euu{!>Sm-*)b43xD%_-V!vQum+EP@I6~<&BBFk@!`JMU}}xk zXc+<@sjt~QyKary6?R1BP|vziS^ZyNjla8z3(HIKPD94WjuY_h8D;0uB=;rw zeOcr^1f5LTGHHxk7&cgic_EW_g;-2wrK!ffOO^fRyz-&XEn?(8h_c1AN;oM|6NF{2JGAuRIaSL-9tlnbI zXsu5wOO3Qy8*JbsXZ%$TzMaZ$=h107U->&FI6!5m8Qo%;_Ts&ucD4PNeg)%Oq;Wkj{r8Jb?=C-Bmmht`1d50ut6x#dy-S78(O7wru zInQ~{v(7X1N^U;>yW}7u9q%u{B)ShFzv=`J3`2;{ANN2$-Q|6D{C#TCv*X))W2w+U zGO;EZ=?is7`uh{<(5h%CIoKbH^@kdlw1xT-J<*E1Jl`bKbjv)Vo~;@^@0@65O@E;Y zA-`5hv=K^NFzXc(Vn}how3dms)pi(iAnMh1wq27tmhh{<2tr1{Xi72yrmi8H!ws{a zS9&|q?ES=jC2@#oVU}V=I=V3p-n#*SIH^18m;DM6byXx&$!-XxY}bI`il2ga)~n90 zbe3>GB$q)WC-u~z9bj16c0alY5|7owBZ+)dPclMnMD7!)-*asjxD}49A+`I5P~H;dnEgV1^UT5Dq2jC!66EGd$P~Q5@IQ30n9NgfS+j z3V|FCH8rN0;dC>sFvG*l5Dw{@T2$$h?m?x3rE7hqYyFyIt-iL93RS){Tm==UE7qQ` zyJPL5i)yf&1~rGyI;CsFqoETh)LiaV85%4MLx)bC3M1iaM8wbpn?L3znV^-PCd5%D zp*alxh!GSop9$LLPr!5kZvNCF{%#SU z2~n+W{v1RYJ>#3Y*kH8H5|@Ir`KC_MbVqnG*Jt$Um=WQf+K_}rl@5YC@sJCit`zA$ zm*1_0Lr9cHA0HGrgM}V<7|fwQm%C>7RJ7kd)4+QVoF;~R_@zyrK5@#S}9b)H+hJqVGIi2$RSQ< z^tF?YLY_{pAI6E#rzK0!4?I+S(+&wQL24N;KEJz=!Wb{UDbfy;r#q$`>ebv1R|12_ z=bBm}g)&<07%hyEHutNs`WoDq*#C+c`StW48fQjY&OqCbxg7bWGsd8>ziuD z&dS8rO02jRk0&Rch&()Yc{g+FZ=a6=q_ zhAsMew~Q087;L_^n8O?`Mn`UBQ(PYh!8^&v^+9ZS4dnhpeSu$DiBQ@L4)zhEfPzWgC$?F_Lt+}2=@tp~D(i8yK22rx+T zeaz)UZ0&f{vrYfi^zfxD-pl8<#FBs;$ zUZe;0-FecwUP1TT@YT>Q-Cd-g{t@qaa@v^puHlOjpPAVIWOmwD9fanpaSs=0uQvXE zj%gVSb!Z2EeZ6e3@aOB+3U#lMmy=3h$6BA@MAzoz_P4K>L%!~`?BBN^``72#|HId^ zZ`r=zu$?=X{vgNjM_dl8iKB}_}huSF?GxZqFAjf^y>F7F*HE_P)T!nBn z^o}rh5aHKRshG^O+H!7vQ#85# z4Ii*|cjf3x{MZBM>j=MP7_;_armgUcIi@CPj_})}I9%_g96e)B_{Vj9$Fw!9{J+UD zCUt#RH1|>0S8{YwSDpTGzJJ(vzOUxkl6?QTzkGM+=vtRr)X;WJgEDW{*uU1-R#aBh zRMu3%i}WPX(xyg) zmw-PN4m+_Sp1|2!UN|qSvHP1R5-1R!hh9*s9P0)#qH2^8_4xERYJ!#0I| zUvxPSPQz~}-eq`?H+f4o*W?`t*$&I$iFn;Nf@!n{dHrt|yXY~&lLAa9eYX@BkrRuu zi~imBSe}dK1r`>%XtSU3bHQ@K!v)_Eyv)b3Z;Jktf`=DQ8tI}=KVzM*X{?JT`^0|W zixDnbGK%qdALHGA#-9Wk)1w)$kn(IMrmLh>7kHUoB9e0pnO-UMt%83n=iD1X`=}}Z z@nRnp6hDr-+~8)-&wWgvihOyIMe&85fL+*Z_)Iqu^EDnr?i1FaKop6JBVjpY&C)H#K_ z%*$N9$$b%IuEgX>G!HVlOI;jyn8{r}in*EKw!mh|$c^Puy2FfXmUMT(lQ_SP!rfsUz^-n68EafC4~C}I4??lF7g|skAx%oNVre1T5Lhw)gw5+FVGX5!_ksXQ_F;# zDBK8>s}gP`b7-xXVI@joa9*&5I_GeRdW6n|%}dc(QL0vZ$PezXaMwYq0XKz8N>6c3 zp&#d+?sB=7Ikvc#4V~jX3wWx=cyvDF`9fbPc)v(IBUygENNzFYK(??A@;{cH3tTdq z@$4XDX945La>j;(&K1q?fWEZwBH(33j6RKVmf(6ITVtL6k=udF$@rq+Wu;7?J&MsI zl28%TH)kE==@Y?`Y$6G|1R{=V&QhtzZW`IzLyqW0iAD-W_(m< zRC$cf0>&5eugKE88j^2~Wc=MI#svp4?i$T_rO4kCd56f~6nSkK$Bq^H4+Tu$F0o^U zb_xAsN$VAz)gpOc=nqAHwMblI=NzG*68TwTVUtL9O1=Z4Gcm}yoTwOgN$fn)oGNsa z=v0b*r)WMR@=DPeDfB~PpG2ob@MMvHA@oIJ!BNikpAz~H5_^r%Cy340MA9ZUX9?XQ zv2(=2XCe=Z<}(sIMp=XKwRFV8l<1#dhXoQu36<9wII9 zTanxJ3 z!&0^vh5j$W-GY0>+FgQ$=tpZ#m_^sYa)sa|!O?=XBUt{Y{OfGZM@HWW$-xfBBLo); zjx1uybfN167Yp_lvwVZlR}1|uoh7@1jOPa!Z;`bALZ)BOXFR%`aiz$cMgM-0Ob~Q< zIQBQ9d9T{!M4s+aNJAmcze<4urfG=B`q4~rPT zFL;aKxj~k6jbeN>pYdLi43smyO=Fxp;>THbegesT#w`KHvmJ~zF2?CX*9rC( zv*b0=JgD#|u9>tW{~p(Py2825rD#k37T~p`x42w%D@MJda*=$L$8s9^0Mb@?lN6*o zoQ%ghA9e-lR{asXJm+|ygU+cMR@S{ULT%hs|)G4EPhZ0@hfv)AT62DicHIBu(O z7nXgi_;YX<2)CV1cPh7{?It%0oJLoh-1E9}JLpD}yQ)yRb^5W%ol>OSPP)hBI*`sq z51U+SgmSy-ag)13DYu87Gr89^<@VBxCg*^rk6tyoUx4$|TPAmdL%9R=CzD$=!tKtZ zk4>(&*zLydc|75@oi0{+?h)iMx#prgcL5cc+`DCY?jV(!+~!~&K1~am+`Q3w?jj1C z+-2TkcQI9(oR)u(yM$KS+*J2LwAJLEC^_6M1)(9jFtinQpTGqXZVI?bHuoE};1rwt z0a_5B0^-H#&O{6HN!Z|`NH@*qzKNEou(?`TskFHX#mbG3zwlx!CD5$3xn1C9+T6ov zL0nDZ#hNQd)VYtax%%Qd_cv^AoSx^NV{_eT!6R+%1GL~#Hg_>v@MxP`iWaQ1x$Dt_ z^)@#pf4;lH=3XjU>Rw0}N(*lFTpnms$I#^lC!Tx^U1xJnI);8C+;-2+qgT3*rAKUT zm3t9AWpan)t#mijOD6ZMccptVy&>FIIsv0&3B6}?z3wISrO9n89B{W#KsxO$wWD+p zTu8XbX-Da1_i;4ONL4;fNQ6;$;~TY>0U-dX1Z7N`e`{` zCEQj|zKgjBgfqt9a(X<6d(PDC%WqT5>DMNA?r7$Ao7@PAd)MUN&f~bhn%sw_+uY0P zOOtyzcpkW-iQM>GsVeVMaQtE~@O!Uvub?p!x7|}T_9pjAnk3wXp7CRE1vkx%yGXyo zeIj+4+z-H=M3)#G_2k{^?xesZwt6AXXFJ?ow9MdSe(9!F!WpwvHw_B+mUa$fyoaBrF1uLIYM!O6a>xi?s`@FgbA28y@ZFc7(pKJ`$?0mT=bQ8w zn~QqRrh#%YtPm6fN)!>#Br(n`*z)*AM;z!wKnG; zv&VCz%{7nty9c+#cySAUXN=E#yUjiB8R@;t<^rC{UR>|v#hS->YP`61Ho0w{dhZUK z)4k2!N9kR&WIcJud!Hmagrm2^BiDGJrg0|sU+QGQfouk?OON19wu-p$@Gsl(>(^*Yo> zlY6NA=U$h(%jR}@eQKA<{oeVyH(wPTYSiKP&JVmnRcUfZYOi~XRov!2@QzgHncVw$ zBxtlMlLccty-$U{v5IYQ3nuc$`6k%hJ8GJ5vdxXrzTv|?t*LnoI6RtSa_>36;XB;s zK64%GtFyT?OIG+AZSMGz)xIX1s{z++bI+D1eaETUQnIb|XYVFoyGq;KnZ9M}5|jIG z-nV_r)oz>H?mI!L>0Fwv)K>m|-$|;@=5F<^QW29|;JwEeRae^F!@kw(0h6m6`6#$g zZ0sK31Zl?Q1-+;Q$=63s1>LruA&GEKxP!%6$llq#3RFq2c%CiV=H96$ncS0wrcd9m%yWRCmaH~!3 zMWlOPoosNlrThi|^J+-A?KH;mihq~7)#mp2f32RjxljEstCws}54@s2F}atuK;Tt1 zNj7ZT>1AznV7F?pxygao)FPX!2)wT1CKph(fj87;HrE(xBAA*C|gFepg@;cOMcyG3T0{j z-$4J9?U|_~f6_1pEyJzBpCoW=WYrh+^#PVV?AkXPv3C@4?A@@V=%?lUDaMKT>}78n zr`Y_00u8zF`4*4rK$CNHK+gJxH46(0SfAxJUe^2omK}7WNDN;pN4^?;I)de6;GDYH z#GOTs+~_m5qw6Nxea8~b^h|^1v<|U}mT_fz+)ArKztUY$;EEHQzbvWA{$QrLwGTMvXM$c>p(yc^Z2EDUledF2WeG zBvxx@R#=v3XcNO9GMYO@@{BX1$r6oN!k%Mj8p!fLl^SwhJDBF#|N%b1JY`xD5lPL-w%3b-feWUde6NJ_;&ekDX69u_T#ya z3EtQ7v__)%9Xdzl75@nq9xePF)(#s>Y6~p5)Hy1x2UIa#lihOw&6@aP3UPtvyMWU*B73t9-$xQU8MYYlIl)iF+B(@qhA2aak}?o z^ZaYzB-#xO)4RZF^jBad{T*0~FaCIF4&?#ss1VplBY_L49Jq+a16yc{=A{nkc=04r zA+QTNUOdND4(x@FpJK?}O9K*{me`Gud+Ag<6tSmC>=0E#au&@1ZlfcB=h4x??@}Z1 z5^4foMvH-0QXB9Z>HywACjxJxRlr+m4e)k~1Mi}ff%nmR;0`ITUDc&a+c zQAnpL?zx?@|%qeQGuELA4IJLk$2QQ-i=K)hWPd)EU5?>MYW7fOC-M)}t&n`8?f`zK?t%Psk(2gQNOWxnBuB>&S%=w zpvkcds5^cO^f=xE1{^#u6*zcaDt7!Ck}}69z;XxAQ6UGzE9Bw%{B`1?W1*EMTLf4!F?K1Z)z`MUGa`Eshg_?T#K`hocX8qQrIy z_Bgn{y$-H#Tr3QTg|wvIBs!-G4oNxBl5%cytcRWR96CnmcO7SdzEE^7k&<5~cCHjV z*NB}PB==iI=QhFHCEvRw-}@Zg&JQ}cC3iTs!P;ZeO1}`zC#9{Paa;)bPHC}Sjw?XF zhS+@i#Bn|7PeJ2MtUnFft8=>r1Pk;BArFeYSm!#Hh`dbayvlX%*^que_D$nOXOhl+ zH(7MTI``l-T~-kN@32!PIx8ZsY($Re1<7j>Ec>Zhsb)J{0;>p@S}#m$*2`F+z_QdWD-ULBjXf^PlY9kx z@%*d;h5 zIH^c%3f@r0Wza`4_6XLEmNE$L5ZohcL?qld~NKxNc-A2#y7^Xo$(>A_4p7= zdO|FDBP2PFXM96&(gdb&5PZX+C$i)*!JbK+s(uRh-J~$nXH_vys%F${7~c@=sTKJQ zkqF)}lj+7;BA?Cpn4o?%)AMjw(}Z_3-pAp+6z>&ypNMw^?4PRY{yNE>l;lBAojOPX_vM-clH!{5=#ePGLTr z5OCb5s{;RxPZkPY?*TXGGkwKq#v-Brn8);|r5^%+9{dzId8~%JvS}qQ;HRZ5NsTH1 zU80u&|0^&Sm~H1Kv9m<%yj;rGo-bl+&lIxeDhK0Tt_i^3K;j{O{=a})ff{Bd+>_xn z;sh?h&76iai5J*}8AHPpOnJa#Q40;Hlpt^k>W1g_fErFICBPF=Q;kl-DO00P%zGNn zEn|R>;2SiGeh$>=QJg*%JqFb17nl_lJr30937QQ0Ng(c+@Jktr{sXAd({u>%89EgB zEKLVKhi@Aw`XvybVc--y66cfYbkm4~@x9&ov>AJTQr{pv#fG!Qk%Z^h5FSl#n;Le>?lwQJZysoYyzsP?< zgJSOqx=;A0=+05BhbKYY96n1PJYz)aJ$il&hwqbL!Vjrg!jI`Y2zB)-J?`P~?-Y>m zb2>)CFKL^E3Y%(9f2c}`z3J*5#r$DvjK*P=I!3}8^`5lP4D}hFu_QH1or&_2I$Rwu z;Wt!`gh#4p%URy1{w8)4>U(1MWOahbQ);Ei2UW{R*4v=kq`fw&HmTQU^($%D(^RR{ z_Y5^l!Y%4!>8~f$1!CtZ^}f{aY4sNBf%Z^$2>(lUlkm^0>B9d?O%whFl@R{dYAx4$ z2uUysGp~)fslm0E{klcX#u0S5>~Y*J50~AEF+}k6BCPl$nWPOg*|DCMVnu(P*3(I9 zJ^g?)YpJZNq!rZ+wSf7FWOuZ&15|4w9Z5&4XIWI$Y>PVFA}VR|vZ^XtJQ$BhR>h-T zRn#=^F~_e#Akynwt94HPy6Y>56Jv7Ksl=+Xn}busV}(b1chi=uXEH{av+O=9ye(KrNtQ?#zX4^G#wY6D`%1vuT+?EvWk0 zEwgD(bE0Q39zBZYClh_G3mWQaK{PGlqC}*peL=lMNXTu_hA3)U)1OEhWW(I5rHd2E zK9M)ftvp*LwJZ!y68tH>0gLl8pAu>u8at zS=iVroylQSs$oGZclErD-O&MdAhhDbR%-7}CN>O{akDlywozMTeUwA?6b{>Ic``Dv z6keH3CX$#`S1es7qGhJY;Fg=*a$3)>-PuWNqUp}2R7*12hc1i_#ADH(`uIR^gxaD5 z5pEKLo7;<@lZ(a;rk?u)aC|hGFeD2jDTBxu+GGfNHm-@ShEqn;oxPD%XGCo0boGFp z_a-yC&G3XK_Jl@^RqE_v|-V?gTBbRXlE+9W>vN@mNG>1WASt}Id^bX ztUK4$)|h?Y*%uq=L+5wa^iX?p6Sp*()ozXU5S)5$Vqg=Kk)EE;`cx{~w<<1b5TOo< z_0i$d1%r`f4`MT|g62hkw?w+vfygR4N;zN%G5ti7@q{R}$Kp^kJck+vSFesH@x|1^ z?(`sB33lct`p|kP$#7fUnTUnUTat-%v^x!@tYKvoBOXnsG5UrlABflyO({%*vEd5v z9?0e(YA|}#y3Wo9lpWufoga(FA#RK%kzXRYX|JesFN)infD-zUYk~fVW(`tdbG#!n z5p;I5E;~V68riicBi&I-#bdyE8!>K^+)=_o86WXh}*SB(SA{m$5?BL_4o54 zkP)^^Gtp)j4?I)=Ed8+~X_XHpu>DRbeX$-UB~ zSkrd?2oKOsjM&a@OPh^0!^=1&dmQF5%u1LLz&G`;Ppm`G7)uQ#Qrw`XyRsl2*(8z$ zjZKm+9m~WoZeNHlgL>;=e>&C|ZQnEyH6^G$b3C<~lJ;Z_xj{LnJ>nRlozfENH7GL1 z3ZfWB@0aDws`$^r?lR7|ZJ2oeE3UhyFI?-vz zqQUGTw>Z)lrG5r;c{1A(=5y>b21u_Mp98q40O(q#6cJigYJ)_RLnzR4VD|4ACCk8pOINR$c)5V0or5fY{m9S5(8#Feu6c+A(32{(Qg|Z7)T^B4KHa!2d&%wPSRG7;wRu;!;2=IN~1hE42SnCh_i zX~0@%?E-}6c~MqCV>3nbYpW}l3`96;9n` z?3%EZ+F!bUBsJr5#uN4n#!QX9ac9EF6l1GBDVeY5am5=FSuX37$;hTQEb}Bwlg)KT zY%;S=&K-1_)tBaDZRMRhET_a)_I4esI?J$7a>rX!4>qtkUtub-1ZHDbm`=zsn2+SA zHjIUxSM!z_P65;@E4x8+=U|W<47XcrVuPuL9kM}X?WMX6_09n?)Ph|seh_(}mm1^o zram5mZP7@wySF8h?nR5(OV;7|H|w~;Sob=dAr>?=M^fv^-XI9q7)$p?lS16q7MyO+r~#+5Hk#-wQA-99Ji`w z)>qBUme{mOnCILKXHiDjFk``t)*1E20UFj#qSX#77gSX?R8`g+r)p}gG6fy24KW;k zOtE$9h6UrqO%1gRYFlgTYvq8=<+q3#CNX2d%vO`mu8R@dST)lij3}En)6O+c@|1Im zr<@Z!@oApV_-0z67i4jk+%zetfAg%5!D;!O5xcZs&T`q^Cuc6({|0dx(MR+82hnkG z^`?GfSYyhyX3+)7Xtdv&MhymgNH~03Y)wD57{-ZPHuSs}@j0Op+e2CR;9@*Z8e^+h z4@#stF)ZosjvE3Qqls==UT}gnRyN~O#-4+stK;xfwq2iGGstV#lEL(n)vdgrwNKl$ z0NegnY;kfV8D?q!y8gt5evFi5v7TrmyG7v8>qUlXJ+YxV(VrkbC`(J=$c94hl0=W1gmD};nXH*W`ZI1QZo^jBn#OHmZt+&F zLD`IXZf+u;$SJ)&&vi?T+^{sQmSdfHGeQ-7avj$CEUD<02prE_(n&OPM>P+8Y*!PJ zv`L#g?#5UImvSjg;VHsM;2uxe-e;V4D&&-(7-)+o*JH`sE1JE5x3hMPtJ;xmr3RLPG$}7tZ6jPOL9a^f(Ph}oEy8&R9B&vh9G||;h`13iM9MwWA{tObBtYpNI2R5#RA*Vk0< zEgUAvW;3+4X4Yp6V8OKGv1Zyd=Qg{ex;9&247D67)>B&pTLPQTUP*@uvss(Q2F<3e z#ncv9>!~eht*%`#JHuhg%wlZPNY;@RS8Xi*St9;iz)p}^ZL`Nl&H^i=D2bh3ZZGoq z5ou%8CUfS1o{Zc+`WQz}?&MiGmejNju7Xo$O)auXT(Ww#NR7!}Mt5su!?IX(gW-e5 zB>*kK+?>RsXRf{Y-Gvq&S%s%MtKB8^ZsclEPv#w3g&E6b%h zS!Qt-X@r^aDtt#~;LF$)q18KWJTA>-nH_nSz#@&%EUC>1ku~12LzOZbL8Ccx+6)$6 z)*Y32bB>O13!1x$XpdY7Kw?D7ZiD+{QDO}rsum~G7)7$>96pE)A#Yr}ttBsOMUZP)W*o4Rq2VVt|I&l3+fcD&+S)@=tx z%ug4{I9@G^tx86cn{vyWd;Qsm^FB0?@4hcU&G?*=nX$l^oCmUy6~7+~e9?Iz3t92| zvB1}v2eObA&#R+-<7phet&bdJiTd#wbp&(_vJkKj+#2YG5O(7q zu3PXAw(u%D`8da5^PTf=EITiCdEYBua)e0fA*DP{K(K_#d?D)vmokpYca;=wQo%-l zN#W4hdVYT4&^cwgTl4!}ZimMcY;=_b`!tWo9n$dFOp)^Vlp)ZG4ddsdPV?w)q(^4? znhRg6S7jp<5)ExpP8Sl5P@aiyN0#w@lX!TgaOe)>f1p4)#!|sp;(vL_FjF!QG90=; zIP{P+L?|f=k&h~As=N%(z#!_J!l6r1`Z5%y3{S{th$TS2i|K+ge@K^F6lp~chg*qC z84#sJrB!gDTM8ar=yYpiP-(Xo?3!2L^n_^K&{YLR+@c=*@s7fk!A9Mu3RiNPF0We~ z5nMR0Ah@u=?F=@0jJl6-A|Wh$&_Ga7i0?v!YlRV~8;lcXf?Z-J*yXwX=*}~OFZhn| zNJj$ru?Tq?Uu0(qzLjD~EF}+~tT80=bFm;1W26IN#DOr<3G%}ncr2X3!N5Wt-wq?a zfFZ8gz|&R$ zJnT$59(5v}pUlwlg)sibdO(n&kO5zECY_(<(DC&$((w&0()rm9oqwQK#}{1jE6WTA zG2qD%(#J61Tiy8aX@>C(6Bs5kOk$YKFooe@hA_h+4E&QQI{&_jK8;~I1CJ;DFb4kF z2c3UYLFXSj&}$fK8D=odWSGUkzjvkckL>D4Fz`=Y>2nzP2d#Ae9V?xGzDloWXkeJj z(8w^4VLrnGhJ_4G4974W%dm){nPD-*5{4Fr;}}{Q+8EjymNG13;NM@;I~Z0l9M5n9 z!%Bt|8BSv8WawguFsx$eX6RvvGOT7;!_dnRV_3_ujscSu>3t0S3<-t-hLahR3@L_h zGMve97Q@*LTN%E@%i{pWFAqFTULLnage;=YBG^2?Fe6w*$Rg@2LZ0T6abcK*Ga5=D zDn$u|p$($NlKjOY4BLp}VIX$!^qont*CKcGZ_68|)!i#BWvO-?Y$N zY#s4=`H}t6LF`83(?TtStFXPqcB361!1f=xssa6(6&x4 zlkwq~aV4gd!{Hj^)Li)QcesMZn#+TrOmle=l;a)3dlKGZyesjp#d|j1bMUUiyV2nq zfy7z>OOw4OLEeIQJKi05_v$W8^&q-*7iM3lIDw7@&521?jd7w66lPy780I-R7{(7B z2E#^B77XVTatVe#o&x*}7UyHCkyVaGLHt;=h7`QG`E6CdzX1Ov4nn_}ZUkb!cULOK zE0vBV=`^0=F{=a1@oXkYSsBYbAu^T)tfRrk{9ucZ9Kl8`8Nrr(6g3}{Emkr>R*grH zql}khBs^aQhb|P;VQ&cEOhdu3R)rkFg&@7A?chR`0IQaX!_@D<&p3^st} z1*AIv#>S&?CClMPrdN3+0^hwtJUj|6 zHGtNY+u z$kj^klzdTcyE#2(C3-VO7Y~7Jn8meN@Ma02%f$+C+atEj4+h^`G8rBm4pmm>_p*<3 zH7i{q^i{AD+b$8HC2Bn(l!1wWDGY`K!CEg%g>r{5rjVFN(@I~6M+x+UwHP=OLemfh zTp|hBxy?3mo1HNnoP$^~ERu(yO!e>H?-KakEsSk_Fsz;yY-VT5c0tfC;5G z0LcjMcTow}!pY!_7VqciEQ7O$r=K%SA)KpF7YMQhZ4sQr^IC8cz9RvL@?;Myc1aAY zVArr=%W@2>U>BS{dsqd#Fsv+Xb68<-%Ch`nc6oSPnn7!L!!8eRwwp7&A?M+3>s!N{ z<)(fI<{uu0a5C{5a{wFjfDB2TTCC<~$ASV6O;dqMD;?h$58CgVdMforJyI90Ggqw ztYY!J_PKZ_wtiq>nzf9s$2tlF`Nj5g8Rqjz^0*8hB=@%A-c~-b#2>Cwu))Am zh;jn4B*Fr395ls`jZaZ@7IteI>X>JIY-Bu*8HK>x)Q`_o@aahpt1ZIr`yZ*{L2qsj zkM%LRuPyVrI^=jg_)^~|9I_hkHE-RH_ePdvUIiIasMfZ|wqswq;O-UYPielt{Y~E+ z>)zeSOZ&njR^qV@zAsCyoIk%MKDZ{bQnzH+QD_+O6?PXc@i_*9n|Qt)QCleUruD zn}G8{^Xnn~&tDh^Q^S^ZNaX_&zr;fg(#A$m3RWYyADNGPk2r2R_%>uU?oRkMNm8{V zHUeo1@e$mi;1>|U8L!**I+RtROlfGvAYZc&OXZ?diFzCVYH5{h(rfWuAceb_1a4dg zB#%v~Q3PC6%(o$CH7qZ|I}I5hagM$jZ#$O+dTYgkTNVW({T%P8LZx7&S Date: Tue, 22 Aug 2023 15:18:59 +0200 Subject: [PATCH 0028/1381] Keep the texture alive during write. --- Penumbra/Import/Textures/TextureManager.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 8c7ec609..f67dabb0 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -418,6 +418,8 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable using var w = new BinaryWriter(stream); header.Write(w); w.Write(input.Pixels); + // No idea why this is necessary, but it is. + GC.KeepAlive(input); } private readonly struct ImageInputData From 3a8bf5dfa15ad819b041cb35939c576f68842375 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 22 Aug 2023 13:21:39 +0000 Subject: [PATCH 0029/1381] [CI] Updating repo.json for 0.7.3.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 23e4cc96..630dab0d 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.7.3.1", - "TestingAssemblyVersion": "0.7.3.1", + "AssemblyVersion": "0.7.3.2", + "TestingAssemblyVersion": "0.7.3.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a6ae580b9f23f7f43acf3637b866435616929396 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 23 Aug 2023 18:42:12 +0200 Subject: [PATCH 0030/1381] Explain comment. --- Penumbra/Import/Textures/TextureManager.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index f67dabb0..9e4890f2 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -418,7 +418,8 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable using var w = new BinaryWriter(stream); header.Write(w); w.Write(input.Pixels); - // No idea why this is necessary, but it is. + // Necessary due to the GC being allowed to collect after the last invocation of an object, + // thus invalidating the ReadOnlySpan. GC.KeepAlive(input); } From 3530e139d1d4a3cd1c39a02dcdf5eec15b6de178 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 23 Aug 2023 18:47:22 +0200 Subject: [PATCH 0031/1381] Add some unnamed mounts to actor identification. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 36df7a87..97643cad 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 36df7a87680eecde48801a38271f0ed8696233ed +Subproject commit 97643cad67b6981c3ee510d1ca12c4321e6a80bf From ccca2f14340899c8ce3e4eac6323766f970db90d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 19 Aug 2023 03:16:45 +0200 Subject: [PATCH 0032/1381] Material editor: improve color accuracy --- .../UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs index cd599f11..c03272ef 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs @@ -412,12 +412,13 @@ public partial class ModEditWindow private static bool ColorPicker( string label, string tooltip, Vector3 input, Action< Vector3 > setter, string letter = "" ) { var ret = false; - var tmp = input; + var inputSqrt = Vector3.SquareRoot( input ); + var tmp = inputSqrt; if( ImGui.ColorEdit3( label, ref tmp, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.DisplayRGB | ImGuiColorEditFlags.InputRGB | ImGuiColorEditFlags.NoTooltip ) - && tmp != input ) + && tmp != inputSqrt ) { - setter( tmp ); + setter( tmp * tmp ); ret = true; } From f64fdd2b26d53bae3a1c24b256637e71ae53ba40 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 19 Aug 2023 05:42:26 +0200 Subject: [PATCH 0033/1381] Material editor: live-preview changes --- .../Interop/ResourceTree/ResolveContext.cs | 26 +- Penumbra/Interop/Structs/ConstantBuffer.cs | 31 ++ Penumbra/Interop/Structs/Material.cs | 35 +- Penumbra/Interop/Structs/MtrlResource.cs | 22 +- Penumbra/Interop/Structs/ResourceHandle.cs | 14 +- .../Interop/Structs/ShaderPackageUtility.cs | 19 + Penumbra/Interop/Structs/TextureUtility.cs | 36 ++ Penumbra/UI/AdvancedWindow/FileEditor.cs | 41 +- .../ModEditWindow.Materials.ColorSet.cs | 136 +++-- .../ModEditWindow.Materials.LivePreview.cs | 484 ++++++++++++++++++ .../ModEditWindow.Materials.MtrlTab.cs | 269 +++++++++- .../ModEditWindow.Materials.Shpk.cs | 20 +- .../AdvancedWindow/ModEditWindow.Materials.cs | 32 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 12 +- 14 files changed, 1067 insertions(+), 110 deletions(-) create mode 100644 Penumbra/Interop/Structs/ConstantBuffer.cs create mode 100644 Penumbra/Interop/Structs/ShaderPackageUtility.cs create mode 100644 Penumbra/Interop/Structs/TextureUtility.cs create mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 90ee1a16..6dc005ee 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -65,26 +65,34 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide private ResourceNode CreateNodeFromGamePath(ResourceType type, nint sourceAddress, Utf8GamePath gamePath, bool @internal) => new(null, type, sourceAddress, gamePath, FilterFullPath(Collection.ResolvePath(gamePath) ?? new FullPath(gamePath)), @internal); - private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint sourceAddress, ResourceHandle* handle, bool @internal, - bool withName) + public static unsafe FullPath GetResourceHandlePath(ResourceHandle* handle) { - if (handle == null) - return null; - var name = handle->FileName(); if (name.IsEmpty) - return null; + return FullPath.Empty; if (name[0] == (byte)'|') { var pos = name.IndexOf((byte)'|', 1); if (pos < 0) - return null; + return FullPath.Empty; name = name.Substring(pos + 1); } - var fullPath = new FullPath(Utf8GamePath.FromByteString(name, out var p) ? p : Utf8GamePath.Empty); + return new FullPath(Utf8GamePath.FromByteString(name, out var p) ? p : Utf8GamePath.Empty); + } + + private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint sourceAddress, ResourceHandle* handle, bool @internal, + bool withName) + { + if (handle == null) + return null; + + var fullPath = GetResourceHandlePath(handle); + if (fullPath.InternalName.IsEmpty) + return null; + var gamePaths = Collection.ReverseResolvePath(fullPath).ToList(); fullPath = FilterFullPath(fullPath); @@ -161,7 +169,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (mtrl == null) return null; - var resource = (MtrlResource*)mtrl->ResourceHandle; + var resource = mtrl->ResourceHandle; var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint) mtrl, &resource->Handle, false, WithNames); if (node == null) return null; diff --git a/Penumbra/Interop/Structs/ConstantBuffer.cs b/Penumbra/Interop/Structs/ConstantBuffer.cs new file mode 100644 index 00000000..52df6477 --- /dev/null +++ b/Penumbra/Interop/Structs/ConstantBuffer.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.InteropServices; + +namespace Penumbra.Interop.Structs; + +[StructLayout(LayoutKind.Explicit, Size = 0x70)] +public unsafe struct ConstantBuffer +{ + [FieldOffset(0x20)] + public int Size; + + [FieldOffset(0x24)] + public int Flags; + + [FieldOffset(0x28)] + private void* _maybeSourcePointer; + + public bool TryGetBuffer(out Span buffer) + { + if ((Flags & 0x4003) == 0 && _maybeSourcePointer != null) + { + buffer = new Span(_maybeSourcePointer, Size >> 2); + return true; + } + else + { + buffer = null; + return false; + } + } +} diff --git a/Penumbra/Interop/Structs/Material.cs b/Penumbra/Interop/Structs/Material.cs index 7cee271e..7b66531c 100644 --- a/Penumbra/Interop/Structs/Material.cs +++ b/Penumbra/Interop/Structs/Material.cs @@ -3,17 +3,42 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout( LayoutKind.Explicit, Size = 0x40 )] public unsafe struct Material { [FieldOffset( 0x10 )] - public ResourceHandle* ResourceHandle; + public MtrlResource* ResourceHandle; + + [FieldOffset( 0x18 )] + public uint ShaderPackageFlags; + + [FieldOffset( 0x20 )] + public uint* ShaderKeys; + + public int ShaderKeyCount + => (int)((uint*)Textures - ShaderKeys); [FieldOffset( 0x28 )] - public void* MaterialData; + public ConstantBuffer* MaterialParameter; [FieldOffset( 0x30 )] - public void** Textures; + public TextureEntry* Textures; - public Texture* Texture( int index ) => ( Texture* )Textures[3 * index + 1]; + [FieldOffset( 0x38 )] + public ushort TextureCount; + + public Texture* Texture( int index ) => Textures[index].ResourceHandle->KernelTexture; + + [StructLayout( LayoutKind.Explicit, Size = 0x18 )] + public struct TextureEntry + { + [FieldOffset( 0x00 )] + public uint Id; + + [FieldOffset( 0x08 )] + public TextureResourceHandle* ResourceHandle; + + [FieldOffset( 0x10 )] + public uint SamplerFlags; + } } \ No newline at end of file diff --git a/Penumbra/Interop/Structs/MtrlResource.cs b/Penumbra/Interop/Structs/MtrlResource.cs index 28756877..424adfe4 100644 --- a/Penumbra/Interop/Structs/MtrlResource.cs +++ b/Penumbra/Interop/Structs/MtrlResource.cs @@ -8,8 +8,11 @@ public unsafe struct MtrlResource [FieldOffset( 0x00 )] public ResourceHandle Handle; + [FieldOffset( 0xC8 )] + public ShaderPackageResourceHandle* ShpkResourceHandle; + [FieldOffset( 0xD0 )] - public ushort* TexSpace; // Contains the offsets for the tex files inside the string list. + public TextureEntry* TexSpace; // Contains the offsets for the tex files inside the string list. [FieldOffset( 0xE0 )] public byte* StringList; @@ -24,8 +27,21 @@ public unsafe struct MtrlResource => StringList + ShpkOffset; public byte* TexString( int idx ) - => StringList + *( TexSpace + 4 + idx * 8 ); + => StringList + TexSpace[idx].PathOffset; public bool TexIsDX11( int idx ) - => *(TexSpace + 5 + idx * 8) >= 0x8000; + => TexSpace[idx].Flags >= 0x8000; + + [StructLayout(LayoutKind.Explicit, Size = 0x10)] + public struct TextureEntry + { + [FieldOffset( 0x00 )] + public TextureResourceHandle* ResourceHandle; + + [FieldOffset( 0x08 )] + public ushort PathOffset; + + [FieldOffset( 0x0A )] + public ushort Flags; + } } \ No newline at end of file diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 4de81903..5db0f8e1 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -1,5 +1,7 @@ using System; using System.Runtime.InteropServices; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.GameData; using Penumbra.GameData.Enums; @@ -18,12 +20,22 @@ public unsafe struct TextureResourceHandle public IntPtr Unk; [FieldOffset( 0x118 )] - public IntPtr KernelTexture; + public Texture* KernelTexture; [FieldOffset( 0x20 )] public IntPtr NewKernelTexture; } +[StructLayout(LayoutKind.Explicit)] +public unsafe struct ShaderPackageResourceHandle +{ + [FieldOffset( 0x0 )] + public ResourceHandle Handle; + + [FieldOffset( 0xB0 )] + public ShaderPackage* ShaderPackage; +} + [StructLayout( LayoutKind.Explicit )] public unsafe struct ResourceHandle { diff --git a/Penumbra/Interop/Structs/ShaderPackageUtility.cs b/Penumbra/Interop/Structs/ShaderPackageUtility.cs new file mode 100644 index 00000000..5bf95f5b --- /dev/null +++ b/Penumbra/Interop/Structs/ShaderPackageUtility.cs @@ -0,0 +1,19 @@ +using System.Runtime.InteropServices; + +namespace Penumbra.Interop.Structs; + +public static class ShaderPackageUtility +{ + [StructLayout(LayoutKind.Explicit, Size = 0xC)] + public unsafe struct Sampler + { + [FieldOffset(0x0)] + public uint Crc; + + [FieldOffset(0x4)] + public uint Id; + + [FieldOffset(0xA)] + public ushort Slot; + } +} diff --git a/Penumbra/Interop/Structs/TextureUtility.cs b/Penumbra/Interop/Structs/TextureUtility.cs new file mode 100644 index 00000000..ec9c4b71 --- /dev/null +++ b/Penumbra/Interop/Structs/TextureUtility.cs @@ -0,0 +1,36 @@ +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; + +namespace Penumbra.Interop.Structs; + +public unsafe static class TextureUtility +{ + private static readonly Functions Funcs = new(); + + public static Texture* Create2D(Device* device, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk) + => ((delegate* unmanaged)Funcs.TextureCreate2D)(device, size, mipLevel, textureFormat, flags, unk); + + public static bool InitializeContents(Texture* texture, void* contents) + => ((delegate* unmanaged)Funcs.TextureInitializeContents)(texture, contents); + + public static void IncRef(Texture* texture) + => ((delegate* unmanaged)(*(void***)texture)[2])(texture); + + public static void DecRef(Texture* texture) + => ((delegate* unmanaged)(*(void***)texture)[3])(texture); + + private sealed class Functions + { + [Signature("E8 ?? ?? ?? ?? 8B 0F 48 8D 54 24")] + public nint TextureCreate2D = nint.Zero; + + [Signature("E9 ?? ?? ?? ?? 8B 02 25")] + public nint TextureInitializeContents = nint.Zero; + + public Functions() + { + SignatureHelper.Initialise(this); + } + } +} diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index acead332..ac873ce2 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -18,7 +18,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; -public class FileEditor where T : class, IWritable +public class FileEditor : IDisposable where T : class, IWritable { private readonly FileDialogService _fileDialog; private readonly IDataManager _gameData; @@ -26,7 +26,7 @@ public class FileEditor where T : class, IWritable public FileEditor(ModEditWindow owner, IDataManager gameData, Configuration config, FileDialogService fileDialog, string tabName, string fileType, Func> getFiles, Func drawEdit, Func getInitialPath, - Func parseFile) + Func parseFile) { _owner = owner; _gameData = gameData; @@ -39,6 +39,11 @@ public class FileEditor where T : class, IWritable _combo = new Combo(config, getFiles); } + ~FileEditor() + { + DoDispose(); + } + public void Draw() { using var tab = ImRaii.TabItem(_tabName); @@ -60,11 +65,23 @@ public class FileEditor where T : class, IWritable DrawFilePanel(); } - private readonly string _tabName; - private readonly string _fileType; - private readonly Func _drawEdit; - private readonly Func _getInitialPath; - private readonly Func _parseFile; + public void Dispose() + { + DoDispose(); + GC.SuppressFinalize(this); + } + + private void DoDispose() + { + (_currentFile as IDisposable)?.Dispose(); + _currentFile = null; + } + + private readonly string _tabName; + private readonly string _fileType; + private readonly Func _drawEdit; + private readonly Func _getInitialPath; + private readonly Func _parseFile; private FileRegistry? _currentPath; private T? _currentFile; @@ -99,7 +116,9 @@ public class FileEditor where T : class, IWritable if (file != null) { _defaultException = null; - _defaultFile = _parseFile(file.Data); + (_defaultFile as IDisposable)?.Dispose(); + _defaultFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. + _defaultFile = _parseFile(file.Data, _defaultPath, false); } else { @@ -158,6 +177,7 @@ public class FileEditor where T : class, IWritable { _currentException = null; _currentPath = null; + (_currentFile as IDisposable)?.Dispose(); _currentFile = null; _changed = false; } @@ -181,10 +201,13 @@ public class FileEditor where T : class, IWritable try { var bytes = File.ReadAllBytes(_currentPath.File.FullName); - _currentFile = _parseFile(bytes); + (_currentFile as IDisposable)?.Dispose(); + _currentFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. + _currentFile = _parseFile(bytes, _currentPath.File.FullName, true); } catch (Exception e) { + (_currentFile as IDisposable)?.Dispose(); _currentFile = null; _currentException = e; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs index c03272ef..1d6c480a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs @@ -13,20 +13,20 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private bool DrawMaterialColorSetChange( MtrlFile file, bool disabled ) + private bool DrawMaterialColorSetChange( MtrlTab tab, bool disabled ) { - if( !file.ColorSets.Any( c => c.HasRows ) ) + if( !tab.Mtrl.ColorSets.Any( c => c.HasRows ) ) { return false; } - ColorSetCopyAllClipboardButton( file, 0 ); + ColorSetCopyAllClipboardButton( tab.Mtrl, 0 ); ImGui.SameLine(); - var ret = ColorSetPasteAllClipboardButton( file, 0 ); + var ret = ColorSetPasteAllClipboardButton( tab, 0 ); ImGui.SameLine(); ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); ImGui.SameLine(); - ret |= DrawPreviewDye( file, disabled ); + ret |= DrawPreviewDye( tab, disabled ); using var table = ImRaii.Table( "##ColorSets", 11, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV ); @@ -58,12 +58,12 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ImGui.TableHeader( "Dye Preview" ); - for( var j = 0; j < file.ColorSets.Length; ++j ) + for( var j = 0; j < tab.Mtrl.ColorSets.Length; ++j ) { using var _ = ImRaii.PushId( j ); for( var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i ) { - ret |= DrawColorSetRow( file, j, i, disabled ); + ret |= DrawColorSetRow( tab, j, i, disabled ); ImGui.TableNextRow(); } } @@ -95,33 +95,36 @@ public partial class ModEditWindow } } - private bool DrawPreviewDye( MtrlFile file, bool disabled ) + private bool DrawPreviewDye( MtrlTab tab, bool disabled ) { var (dyeId, (name, dyeColor, gloss)) = _stainService.StainCombo.CurrentSelection; var tt = dyeId == 0 ? "Select a preview dye first." : "Apply all preview values corresponding to the dye template and chosen dye where dyeing is enabled."; if( ImGuiUtil.DrawDisabledButton( "Apply Preview Dye", Vector2.Zero, tt, disabled || dyeId == 0 ) ) { var ret = false; - for( var j = 0; j < file.ColorDyeSets.Length; ++j ) + for( var j = 0; j < tab.Mtrl.ColorDyeSets.Length; ++j ) { for( var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i ) { - ret |= file.ApplyDyeTemplate( _stainService.StmFile, j, i, dyeId ); + ret |= tab.Mtrl.ApplyDyeTemplate( _stainService.StmFile, j, i, dyeId ); } } + tab.UpdateColorSetPreview(); + return ret; } ImGui.SameLine(); var label = dyeId == 0 ? "Preview Dye###previewDye" : $"{name} (Preview)###previewDye"; - _stainService.StainCombo.Draw( label, dyeColor, string.Empty, true, gloss); + if (_stainService.StainCombo.Draw(label, dyeColor, string.Empty, true, gloss)) + tab.UpdateColorSetPreview(); return false; } - private static unsafe bool ColorSetPasteAllClipboardButton( MtrlFile file, int colorSetIdx ) + private static unsafe bool ColorSetPasteAllClipboardButton( MtrlTab tab, int colorSetIdx ) { - if( !ImGui.Button( "Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2( 200, 0 ) ) || file.ColorSets.Length <= colorSetIdx ) + if( !ImGui.Button( "Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2( 200, 0 ) ) || tab.Mtrl.ColorSets.Length <= colorSetIdx ) { return false; } @@ -135,14 +138,14 @@ public partial class ModEditWindow return false; } - ref var rows = ref file.ColorSets[ colorSetIdx ].Rows; + ref var rows = ref tab.Mtrl.ColorSets[ colorSetIdx ].Rows; fixed( void* ptr = data, output = &rows ) { MemoryUtility.MemCpyUnchecked( output, ptr, Marshal.SizeOf< MtrlFile.ColorSet.RowArray >() ); if( data.Length >= Marshal.SizeOf< MtrlFile.ColorSet.RowArray >() + Marshal.SizeOf< MtrlFile.ColorDyeSet.RowArray >() - && file.ColorDyeSets.Length > colorSetIdx ) + && tab.Mtrl.ColorDyeSets.Length > colorSetIdx ) { - ref var dyeRows = ref file.ColorDyeSets[ colorSetIdx ].Rows; + ref var dyeRows = ref tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows; fixed( void* output2 = &dyeRows ) { MemoryUtility.MemCpyUnchecked( output2, ( byte* )ptr + Marshal.SizeOf< MtrlFile.ColorSet.RowArray >(), Marshal.SizeOf< MtrlFile.ColorDyeSet.RowArray >() ); @@ -150,6 +153,8 @@ public partial class ModEditWindow } } + tab.UpdateColorSetPreview(); + return true; } catch @@ -182,7 +187,7 @@ public partial class ModEditWindow } } - private static unsafe bool ColorSetPasteFromClipboardButton( MtrlFile file, int colorSetIdx, int rowIdx, bool disabled ) + private static unsafe bool ColorSetPasteFromClipboardButton( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled ) { if( ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, "Import an exported row from your clipboard onto this row.", disabled, true ) ) @@ -192,20 +197,22 @@ public partial class ModEditWindow var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String( text ); if( data.Length != MtrlFile.ColorSet.Row.Size + 2 - || file.ColorSets.Length <= colorSetIdx ) + || tab.Mtrl.ColorSets.Length <= colorSetIdx ) { return false; } fixed( byte* ptr = data ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ] = *( MtrlFile.ColorSet.Row* )ptr; - if( colorSetIdx < file.ColorDyeSets.Length ) + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ] = *( MtrlFile.ColorSet.Row* )ptr; + if( colorSetIdx < tab.Mtrl.ColorDyeSets.Length ) { - file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] = *( MtrlFile.ColorDyeSet.Row* )( ptr + MtrlFile.ColorSet.Row.Size ); + tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] = *( MtrlFile.ColorDyeSet.Row* )( ptr + MtrlFile.ColorSet.Row.Size ); } } + tab.UpdateColorSetRowPreview(rowIdx); + return true; } catch @@ -217,7 +224,18 @@ public partial class ModEditWindow return false; } - private bool DrawColorSetRow( MtrlFile file, int colorSetIdx, int rowIdx, bool disabled ) + private static void ColorSetHighlightButton( MtrlTab tab, int rowIdx, bool disabled ) + { + ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Crosshairs.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, + "Highlight this row on your character, if possible.", disabled || tab.ColorSetPreviewers.Count == 0, true ); + + if( ImGui.IsItemHovered() ) + tab.HighlightColorSetRow( rowIdx ); + else if( tab.HighlightedColorSetRow == rowIdx ) + tab.CancelColorSetHighlight(); + } + + private bool DrawColorSetRow( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled ) { static bool FixFloat( ref float val, float current ) { @@ -226,38 +244,41 @@ public partial class ModEditWindow } using var id = ImRaii.PushId( rowIdx ); - var row = file.ColorSets[ colorSetIdx ].Rows[ rowIdx ]; - var hasDye = file.ColorDyeSets.Length > colorSetIdx; - var dye = hasDye ? file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] : new MtrlFile.ColorDyeSet.Row(); + var row = tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ]; + var hasDye = tab.Mtrl.ColorDyeSets.Length > colorSetIdx; + var dye = hasDye ? tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] : new MtrlFile.ColorDyeSet.Row(); var floatSize = 70 * UiHelpers.Scale; var intSize = 45 * UiHelpers.Scale; ImGui.TableNextColumn(); ColorSetCopyClipboardButton( row, dye ); ImGui.SameLine(); - var ret = ColorSetPasteFromClipboardButton( file, colorSetIdx, rowIdx, disabled ); + var ret = ColorSetPasteFromClipboardButton( tab, colorSetIdx, rowIdx, disabled ); + ImGui.SameLine(); + ColorSetHighlightButton( tab, rowIdx, disabled ); ImGui.TableNextColumn(); ImGui.TextUnformatted( $"#{rowIdx + 1:D2}" ); ImGui.TableNextColumn(); using var dis = ImRaii.Disabled( disabled ); - ret |= ColorPicker( "##Diffuse", "Diffuse Color", row.Diffuse, c => file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Diffuse = c ); + ret |= ColorPicker( "##Diffuse", "Diffuse Color", row.Diffuse, c => { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Diffuse = c; tab.UpdateColorSetRowPreview(rowIdx); } ); if( hasDye ) { ImGui.SameLine(); ret |= ImGuiUtil.Checkbox( "##dyeDiffuse", "Apply Diffuse Color on Dye", dye.Diffuse, - b => file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Diffuse = b, ImGuiHoveredFlags.AllowWhenDisabled ); + b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Diffuse = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); } ImGui.TableNextColumn(); - ret |= ColorPicker( "##Specular", "Specular Color", row.Specular, c => file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Specular = c ); + ret |= ColorPicker( "##Specular", "Specular Color", row.Specular, c => { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Specular = c; tab.UpdateColorSetRowPreview(rowIdx); } ); ImGui.SameLine(); var tmpFloat = row.SpecularStrength; ImGui.SetNextItemWidth( floatSize ); if( ImGui.DragFloat( "##SpecularStrength", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.SpecularStrength ) ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = tmpFloat; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = tmpFloat; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Specular Strength", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -266,19 +287,19 @@ public partial class ModEditWindow { ImGui.SameLine(); ret |= ImGuiUtil.Checkbox( "##dyeSpecular", "Apply Specular Color on Dye", dye.Specular, - b => file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Specular = b, ImGuiHoveredFlags.AllowWhenDisabled ); + b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Specular = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); ImGui.SameLine(); ret |= ImGuiUtil.Checkbox( "##dyeSpecularStrength", "Apply Specular Strength on Dye", dye.SpecularStrength, - b => file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = b, ImGuiHoveredFlags.AllowWhenDisabled ); + b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); } ImGui.TableNextColumn(); - ret |= ColorPicker( "##Emissive", "Emissive Color", row.Emissive, c => file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Emissive = c ); + ret |= ColorPicker( "##Emissive", "Emissive Color", row.Emissive, c => { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Emissive = c; tab.UpdateColorSetRowPreview(rowIdx); } ); if( hasDye ) { ImGui.SameLine(); ret |= ImGuiUtil.Checkbox( "##dyeEmissive", "Apply Emissive Color on Dye", dye.Emissive, - b => file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Emissive = b, ImGuiHoveredFlags.AllowWhenDisabled ); + b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Emissive = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); } ImGui.TableNextColumn(); @@ -286,8 +307,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth( floatSize ); if( ImGui.DragFloat( "##GlossStrength", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.GlossStrength ) ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].GlossStrength = tmpFloat; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].GlossStrength = tmpFloat; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Gloss Strength", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -295,7 +317,7 @@ public partial class ModEditWindow { ImGui.SameLine(); ret |= ImGuiUtil.Checkbox( "##dyeGloss", "Apply Gloss Strength on Dye", dye.Gloss, - b => file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Gloss = b, ImGuiHoveredFlags.AllowWhenDisabled ); + b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Gloss = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); } ImGui.TableNextColumn(); @@ -303,8 +325,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth( intSize ); if( ImGui.InputInt( "##TileSet", ref tmpInt, 0, 0 ) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].TileSet = ( ushort )tmpInt; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].TileSet = ( ushort )tmpInt; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Tile Set", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -314,8 +337,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth( floatSize ); if( ImGui.DragFloat( "##RepeatX", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialRepeat.X ) ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Repeat X", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -324,8 +348,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth( floatSize ); if( ImGui.DragFloat( "##RepeatY", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialRepeat.Y ) ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Repeat Y", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -335,8 +360,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth( floatSize ); if( ImGui.DragFloat( "##SkewX", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialSkew.X ) ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { X = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { X = tmpFloat }; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Skew X", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -346,8 +372,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth( floatSize ); if( ImGui.DragFloat( "##SkewY", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialSkew.Y ) ) { - file.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Skew Y", ImGuiHoveredFlags.AllowWhenDisabled ); @@ -358,14 +385,15 @@ public partial class ModEditWindow if(_stainService.TemplateCombo.Draw( "##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton ) ) { - file.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Template = _stainService.TemplateCombo.CurrentSelection; - ret = true; + tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Template = _stainService.TemplateCombo.CurrentSelection; + ret = true; + tab.UpdateColorSetRowPreview(rowIdx); } ImGuiUtil.HoverTooltip( "Dye Template", ImGuiHoveredFlags.AllowWhenDisabled ); ImGui.TableNextColumn(); - ret |= DrawDyePreview( file, colorSetIdx, rowIdx, disabled, dye, floatSize ); + ret |= DrawDyePreview( tab, colorSetIdx, rowIdx, disabled, dye, floatSize ); } else { @@ -376,7 +404,7 @@ public partial class ModEditWindow return ret; } - private bool DrawDyePreview( MtrlFile file, int colorSetIdx, int rowIdx, bool disabled, MtrlFile.ColorDyeSet.Row dye, float floatSize ) + private bool DrawDyePreview( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, MtrlFile.ColorDyeSet.Row dye, float floatSize ) { var stain = _stainService.StainCombo.CurrentSelection.Key; if( stain == 0 || !_stainService.StmFile.Entries.TryGetValue( dye.Template, out var entry ) ) @@ -390,7 +418,9 @@ public partial class ModEditWindow var ret = ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2( ImGui.GetFrameHeight() ), "Apply the selected dye to this row.", disabled, true ); - ret = ret && file.ApplyDyeTemplate(_stainService.StmFile, colorSetIdx, rowIdx, stain ); + ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, colorSetIdx, rowIdx, stain ); + if (ret) + tab.UpdateColorSetRowPreview(rowIdx); ImGui.SameLine(); ColorPicker( "##diffusePreview", string.Empty, values.Diffuse, _ => { }, "D" ); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs new file mode 100644 index 00000000..376e656f --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs @@ -0,0 +1,484 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Dalamud.Game; +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.GameData.Files; +using Penumbra.Interop.ResourceTree; +using Structs = Penumbra.Interop.Structs; + +namespace Penumbra.UI.AdvancedWindow; + +public partial class ModEditWindow +{ + private static unsafe Character* FindLocalPlayer(IObjectTable objects) + { + var localPlayer = objects[0]; + if (localPlayer is not Dalamud.Game.ClientState.Objects.Types.Character) + return null; + + return (Character*)localPlayer.Address; + } + + private static unsafe Character* FindSubActor(Character* character, int subActorType) + { + if (character == null) + return null; + + switch (subActorType) + { + case -1: + return character; + case 0: + return character->Mount.MountObject; + case 1: + var companion = character->Companion.CompanionObject; + if (companion == null) + return null; + return &companion->Character; + case 2: + var ornament = character->Ornament.OrnamentObject; + if (ornament == null) + return null; + return &ornament->Character; + default: + return null; + } + } + + private static unsafe List<(int SubActorType, int ChildObjectIndex, int ModelSlot, int MaterialSlot)> FindMaterial(CharacterBase* drawObject, int subActorType, string materialPath) + { + static void CollectMaterials(List<(int, int, int, int)> result, int subActorType, int childObjectIndex, CharacterBase* drawObject, string materialPath) + { + for (var i = 0; i < drawObject->SlotCount; ++i) + { + var model = drawObject->Models[i]; + if (model == null) + continue; + + for (var j = 0; j < model->MaterialCount; ++j) + { + var material = model->Materials[j]; + if (material == null) + continue; + + var mtrlHandle = material->MaterialResourceHandle; + if (mtrlHandle == null) + continue; + + var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); + if (path.ToString() == materialPath) + result.Add((subActorType, childObjectIndex, i, j)); + } + } + } + + var result = new List<(int, int, int, int)>(); + + if (drawObject == null) + return result; + + materialPath = materialPath.Replace('/', '\\').ToLowerInvariant(); + + CollectMaterials(result, subActorType, -1, drawObject, materialPath); + + var firstChildObject = (CharacterBase*)drawObject->DrawObject.Object.ChildObject; + if (firstChildObject != null) + { + var childObject = firstChildObject; + var childObjectIndex = 0; + do + { + CollectMaterials(result, subActorType, childObjectIndex, childObject, materialPath); + + childObject = (CharacterBase*)childObject->DrawObject.Object.NextSiblingObject; + ++childObjectIndex; + } + while (childObject != null && childObject != firstChildObject); + } + + return result; + } + + private static unsafe CharacterBase* GetChildObject(CharacterBase* drawObject, int index) + { + if (drawObject == null) + return null; + + if (index >= 0) + { + drawObject = (CharacterBase*)drawObject->DrawObject.Object.ChildObject; + if (drawObject == null) + return null; + } + + var first = drawObject; + while (index-- > 0) + { + drawObject = (CharacterBase*)drawObject->DrawObject.Object.NextSiblingObject; + if (drawObject == null || drawObject == first) + return null; + } + + return drawObject; + } + + private static unsafe Material* GetDrawObjectMaterial(CharacterBase* drawObject, int modelSlot, int materialSlot) + { + if (drawObject == null) + return null; + + if (modelSlot < 0 || modelSlot >= drawObject->SlotCount) + return null; + + var model = drawObject->Models[modelSlot]; + if (model == null) + return null; + + if (materialSlot < 0 || materialSlot >= model->MaterialCount) + return null; + + return model->Materials[materialSlot]; + } + + private abstract unsafe class LiveMaterialPreviewerBase : IDisposable + { + private readonly IObjectTable _objects; + + protected readonly int SubActorType; + protected readonly int ChildObjectIndex; + protected readonly int ModelSlot; + protected readonly int MaterialSlot; + + protected readonly CharacterBase* DrawObject; + protected readonly Material* Material; + + protected bool Valid; + + public LiveMaterialPreviewerBase(IObjectTable objects, int subActorType, int childObjectIndex, int modelSlot, int materialSlot) + { + _objects = objects; + + SubActorType = subActorType; + ChildObjectIndex = childObjectIndex; + ModelSlot = modelSlot; + MaterialSlot = materialSlot; + + var localPlayer = FindLocalPlayer(objects); + if (localPlayer == null) + throw new InvalidOperationException("Cannot retrieve local player object"); + + var subActor = FindSubActor(localPlayer, subActorType); + if (subActor == null) + throw new InvalidOperationException("Cannot retrieve sub-actor (mount, companion or ornament)"); + + DrawObject = GetChildObject((CharacterBase*)subActor->GameObject.GetDrawObject(), childObjectIndex); + if (DrawObject == null) + throw new InvalidOperationException("Cannot retrieve draw object"); + + Material = GetDrawObjectMaterial(DrawObject, modelSlot, materialSlot); + if (Material == null) + throw new InvalidOperationException("Cannot retrieve material"); + + Valid = true; + } + + ~LiveMaterialPreviewerBase() + { + if (Valid) + Dispose(false, IsStillValid()); + } + + public void Dispose() + { + if (Valid) + Dispose(true, IsStillValid()); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing, bool reset) + { + Valid = false; + } + + public bool CheckValidity() + { + if (Valid && !IsStillValid()) + Dispose(false, false); + + return Valid; + } + + protected virtual bool IsStillValid() + { + var localPlayer = FindLocalPlayer(_objects); + if (localPlayer == null) + return false; + + var subActor = FindSubActor(localPlayer, SubActorType); + if (subActor == null) + return false; + + if (DrawObject != GetChildObject((CharacterBase*)subActor->GameObject.GetDrawObject(), ChildObjectIndex)) + return false; + + if (Material != GetDrawObjectMaterial(DrawObject, ModelSlot, MaterialSlot)) + return false; + + return true; + } + } + + private sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase + { + private readonly ShaderPackage* _shaderPackage; + + private readonly uint _originalShPkFlags; + private readonly float[] _originalMaterialParameter; + private readonly uint[] _originalSamplerFlags; + + public LiveMaterialPreviewer(IObjectTable objects, int subActorType, int childObjectIndex, int modelSlot, int materialSlot) : base(objects, subActorType, childObjectIndex, modelSlot, materialSlot) + { + var mtrlHandle = Material->MaterialResourceHandle; + if (mtrlHandle == null) + throw new InvalidOperationException("Material doesn't have a resource handle"); + + var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; + if (shpkHandle == null) + throw new InvalidOperationException("Material doesn't have a ShPk resource handle"); + + _shaderPackage = shpkHandle->ShaderPackage; + if (_shaderPackage == null) + throw new InvalidOperationException("Material doesn't have a shader package"); + + var material = (Structs.Material*)Material; + + _originalShPkFlags = material->ShaderPackageFlags; + + if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) + _originalMaterialParameter = materialParameter.ToArray(); + else + _originalMaterialParameter = Array.Empty(); + + _originalSamplerFlags = new uint[material->TextureCount]; + for (var i = 0; i < _originalSamplerFlags.Length; ++i) + _originalSamplerFlags[i] = material->Textures[i].SamplerFlags; + } + + protected override void Dispose(bool disposing, bool reset) + { + base.Dispose(disposing, reset); + + if (reset) + { + var material = (Structs.Material*)Material; + + material->ShaderPackageFlags = _originalShPkFlags; + + if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) + _originalMaterialParameter.AsSpan().CopyTo(materialParameter); + + for (var i = 0; i < _originalSamplerFlags.Length; ++i) + material->Textures[i].SamplerFlags = _originalSamplerFlags[i]; + } + } + + public void SetShaderPackageFlags(uint shPkFlags) + { + if (!CheckValidity()) + return; + + ((Structs.Material*)Material)->ShaderPackageFlags = shPkFlags; + } + + public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) + { + if (!CheckValidity()) + return; + + var cbuffer = ((Structs.Material*)Material)->MaterialParameter; + if (cbuffer == null) + return; + + if (!cbuffer->TryGetBuffer(out var buffer)) + return; + + for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) + { + ref var parameter = ref _shaderPackage->MaterialElements[i]; + if (parameter.CRC == parameterCrc) + { + if ((parameter.Offset & 0x3) != 0 || (parameter.Size & 0x3) != 0 || (parameter.Offset + parameter.Size) >> 2 > buffer.Length) + return; + + value.TryCopyTo(buffer.Slice(parameter.Offset >> 2, parameter.Size >> 2)[offset..]); + return; + } + } + } + + public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) + { + if (!CheckValidity()) + return; + + var id = 0u; + var found = false; + + var samplers = (Structs.ShaderPackageUtility.Sampler*)_shaderPackage->Samplers; + for (var i = 0; i < _shaderPackage->SamplerCount; ++i) + { + if (samplers[i].Crc == samplerCrc) + { + id = samplers[i].Id; + found = true; + break; + } + } + + if (!found) + return; + + var material = (Structs.Material*)Material; + for (var i = 0; i < material->TextureCount; ++i) + { + if (material->Textures[i].Id == id) + { + material->Textures[i].SamplerFlags = (samplerFlags & 0xFFFFFDFF) | 0x000001C0; + break; + } + } + } + + protected override bool IsStillValid() + { + if (!base.IsStillValid()) + return false; + + var mtrlHandle = Material->MaterialResourceHandle; + if (mtrlHandle == null) + return false; + + var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; + if (shpkHandle == null) + return false; + + if (_shaderPackage != shpkHandle->ShaderPackage) + return false; + + return true; + } + } + + private sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase + { + public const int TextureWidth = 4; + public const int TextureHeight = MtrlFile.ColorSet.RowArray.NumRows; + public const int TextureLength = TextureWidth * TextureHeight * 4; + + private readonly Framework _framework; + + private readonly Texture** _colorSetTexture; + private readonly Texture* _originalColorSetTexture; + + private Half[] _colorSet; + private bool _updatePending; + + public Half[] ColorSet => _colorSet; + + public LiveColorSetPreviewer(IObjectTable objects, Framework framework, int subActorType, int childObjectIndex, int modelSlot, int materialSlot) : base(objects, subActorType, childObjectIndex, modelSlot, materialSlot) + { + _framework = framework; + + var mtrlHandle = Material->MaterialResourceHandle; + if (mtrlHandle == null) + throw new InvalidOperationException("Material doesn't have a resource handle"); + + var colorSetTextures = *(Texture***)((nint)DrawObject + 0x258); + if (colorSetTextures == null) + throw new InvalidOperationException("Draw object doesn't have color set textures"); + + _colorSetTexture = colorSetTextures + (modelSlot * 4 + materialSlot); + + _originalColorSetTexture = *_colorSetTexture; + if (_originalColorSetTexture == null) + throw new InvalidOperationException("Material doesn't have a color set"); + Structs.TextureUtility.IncRef(_originalColorSetTexture); + + _colorSet = new Half[TextureLength]; + _updatePending = true; + + framework.Update += OnFrameworkUpdate; + } + + protected override void Dispose(bool disposing, bool reset) + { + _framework.Update -= OnFrameworkUpdate; + + base.Dispose(disposing, reset); + + if (reset) + { + var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)_originalColorSetTexture); + Structs.TextureUtility.DecRef(oldTexture); + } + else + Structs.TextureUtility.DecRef(_originalColorSetTexture); + } + + public void ScheduleUpdate() + { + _updatePending = true; + } + + private void OnFrameworkUpdate(Framework _) + { + if (!_updatePending) + return; + _updatePending = false; + + if (!CheckValidity()) + return; + + var textureSize = stackalloc int[2]; + textureSize[0] = TextureWidth; + textureSize[1] = TextureHeight; + + var newTexture = Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7); + if (newTexture == null) + return; + + bool success; + lock (_colorSet) + fixed (Half* colorSet = _colorSet) + success = Structs.TextureUtility.InitializeContents(newTexture, colorSet); + + if (success) + { + var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)newTexture); + Structs.TextureUtility.DecRef(oldTexture); + } + else + Structs.TextureUtility.DecRef(newTexture); + } + + protected override bool IsStillValid() + { + if (!base.IsStillValid()) + return false; + + var colorSetTextures = *(Texture***)((nint)DrawObject + 0x258); + if (colorSetTextures == null) + return false; + + if (_colorSetTexture != colorSetTextures + (ModelSlot * 4 + MaterialSlot)) + return false; + + return true; + } + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 753ad8e9..9cff681a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -2,15 +2,20 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; -using Penumbra.Services; +using Penumbra.GameData.Structs; +using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Util; using static Penumbra.GameData.Files.ShpkFile; @@ -19,10 +24,12 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private sealed class MtrlTab : IWritable + private sealed class MtrlTab : IWritable, IDisposable { private readonly ModEditWindow _edit; public readonly MtrlFile Mtrl; + public readonly string FilePath; + public readonly bool Writable; public uint NewKeyId; public uint NewKeyDefault; @@ -57,11 +64,17 @@ public partial class ModEditWindow public bool HasMalformedMaterialConstants; // Samplers - public readonly List< (string Label, string FileName) > Samplers = new(4); - public readonly List< (string Name, uint Id) > MissingSamplers = new(4); - public readonly HashSet< uint > DefinedSamplers = new(4); - public IndexSet OrphanedSamplers = new(0, false); - public int AliasedSamplerCount; + public readonly List< (string Label, string FileName, uint Id) > Samplers = new(4); + public readonly List< (string Name, uint Id) > MissingSamplers = new(4); + public readonly HashSet< uint > DefinedSamplers = new(4); + public IndexSet OrphanedSamplers = new(0, false); + public int AliasedSamplerCount; + + // Live-Previewers + public readonly List MaterialPreviewers = new(4); + public readonly List ColorSetPreviewers = new(4); + public int HighlightedColorSetRow = -1; + public int HighlightTime = -1; public FullPath FindAssociatedShpk( out string defaultPath, out Utf8GamePath defaultGamePath ) { @@ -243,7 +256,7 @@ public partial class ModEditWindow ? $"#{idx}: {shpk.Value.Name} (ID: 0x{sampler.SamplerId:X8})##{sampler.SamplerId}" : $"#{idx} (ID: 0x{sampler.SamplerId:X8})##{sampler.SamplerId}"; var fileName = $"Texture #{sampler.TextureIndex} - {Path.GetFileName( Mtrl.Textures[ sampler.TextureIndex ].Path )}"; - Samplers.Add( ( label, fileName ) ); + Samplers.Add( ( label, fileName, sampler.SamplerId ) ); } MissingSamplers.Clear(); @@ -269,6 +282,220 @@ public partial class ModEditWindow } } + public unsafe void BindToMaterialInstances() + { + UnbindFromMaterialInstances(); + + var localPlayer = FindLocalPlayer(_edit._dalamud.Objects); + if (null == localPlayer) + return; + + var drawObject = (CharacterBase*)localPlayer->GameObject.GetDrawObject(); + if (null == drawObject) + return; + + var instances = FindMaterial(drawObject, -1, FilePath); + + var drawObjects = stackalloc CharacterBase*[4]; + drawObjects[0] = drawObject; + + for (var i = 0; i < 3; ++i) + { + var subActor = FindSubActor(localPlayer, i); + if (null == subActor) + continue; + + var subDrawObject = (CharacterBase*)subActor->GameObject.GetDrawObject(); + if (null == subDrawObject) + continue; + + instances.AddRange(FindMaterial(subDrawObject, i, FilePath)); + drawObjects[i + 1] = subDrawObject; + } + + var foundMaterials = new HashSet(); + foreach (var (subActorType, childObjectIndex, modelSlot, materialSlot) in instances) + { + var material = GetDrawObjectMaterial(drawObjects[subActorType + 1], modelSlot, materialSlot); + if (foundMaterials.Contains((nint)material)) + continue; + try + { + MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._dalamud.Objects, subActorType, childObjectIndex, modelSlot, materialSlot)); + foundMaterials.Add((nint)material); + } + catch (InvalidOperationException) + { + // Carry on without that previewer. + } + } + + var colorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); + + if (colorSet.HasValue) + { + foreach (var (subActorType, childObjectIndex, modelSlot, materialSlot) in instances) + { + try + { + ColorSetPreviewers.Add(new LiveColorSetPreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, subActorType, childObjectIndex, modelSlot, materialSlot)); + } + catch (InvalidOperationException) + { + // Carry on without that previewer. + } + } + UpdateColorSetPreview(); + } + } + + public void UnbindFromMaterialInstances() + { + foreach (var previewer in MaterialPreviewers) + previewer.Dispose(); + MaterialPreviewers.Clear(); + + foreach (var previewer in ColorSetPreviewers) + previewer.Dispose(); + ColorSetPreviewers.Clear(); + } + + public void SetShaderPackageFlags(uint shPkFlags) + { + foreach (var previewer in MaterialPreviewers) + previewer.SetShaderPackageFlags(shPkFlags); + } + + public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) + { + foreach (var previewer in MaterialPreviewers) + previewer.SetMaterialParameter(parameterCrc, offset, value); + } + + public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) + { + foreach (var previewer in MaterialPreviewers) + previewer.SetSamplerFlags(samplerCrc, samplerFlags); + } + + public void HighlightColorSetRow(int rowIdx) + { + var oldRowIdx = HighlightedColorSetRow; + + HighlightedColorSetRow = rowIdx; + HighlightTime = (HighlightTime + 1) % 32; + + if (oldRowIdx >= 0) + UpdateColorSetRowPreview(oldRowIdx); + if (rowIdx >= 0) + UpdateColorSetRowPreview(rowIdx); + } + + public void CancelColorSetHighlight() + { + var rowIdx = HighlightedColorSetRow; + + HighlightedColorSetRow = -1; + HighlightTime = -1; + + if (rowIdx >= 0) + UpdateColorSetRowPreview(rowIdx); + } + + public unsafe void UpdateColorSetRowPreview(int rowIdx) + { + if (ColorSetPreviewers.Count == 0) + return; + + var maybeColorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); + if (!maybeColorSet.HasValue) + return; + + var colorSet = maybeColorSet.Value; + var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); + + var row = colorSet.Rows[rowIdx]; + if (maybeColorDyeSet.HasValue) + { + var stm = _edit._stainService.StmFile; + var dye = maybeColorDyeSet.Value.Rows[rowIdx]; + if (stm.TryGetValue(dye.Template, (StainId)_edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) + ApplyDye(ref row, dye, dyes); + } + + if (HighlightedColorSetRow == rowIdx) + ApplyHighlight(ref row, HighlightTime); + + foreach (var previewer in ColorSetPreviewers) + { + fixed (Half* pDest = previewer.ColorSet) + Buffer.MemoryCopy(&row, pDest + LiveColorSetPreviewer.TextureWidth * 4 * rowIdx, LiveColorSetPreviewer.TextureWidth * 4 * sizeof(Half), sizeof(MtrlFile.ColorSet.Row)); + previewer.ScheduleUpdate(); + } + } + + public unsafe void UpdateColorSetPreview() + { + if (ColorSetPreviewers.Count == 0) + return; + + var maybeColorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); + if (!maybeColorSet.HasValue) + return; + + var colorSet = maybeColorSet.Value; + var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); + + var rows = colorSet.Rows; + if (maybeColorDyeSet.HasValue) + { + var stm = _edit._stainService.StmFile; + var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; + var colorDyeSet = maybeColorDyeSet.Value; + for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) + { + ref var row = ref rows[i]; + var dye = colorDyeSet.Rows[i]; + if (stm.TryGetValue(dye.Template, stainId, out var dyes)) + ApplyDye(ref row, dye, dyes); + } + } + + if (HighlightedColorSetRow >= 0) + ApplyHighlight(ref rows[HighlightedColorSetRow], HighlightTime); + + foreach (var previewer in ColorSetPreviewers) + { + fixed (Half* pDest = previewer.ColorSet) + Buffer.MemoryCopy(&rows, pDest, LiveColorSetPreviewer.TextureLength * sizeof(Half), sizeof(MtrlFile.ColorSet.RowArray)); + previewer.ScheduleUpdate(); + } + } + + private static void ApplyDye(ref MtrlFile.ColorSet.Row row, MtrlFile.ColorDyeSet.Row dye, StmFile.DyePack dyes) + { + if (dye.Diffuse) + row.Diffuse = dyes.Diffuse; + if (dye.Specular) + row.Specular = dyes.Specular; + if (dye.SpecularStrength) + row.SpecularStrength = dyes.SpecularPower; + if (dye.Emissive) + row.Emissive = dyes.Emissive; + if (dye.Gloss) + row.GlossStrength = dyes.Gloss; + } + + private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, int time) + { + var level = Math.Sin(time * Math.PI / 16) * 0.5 + 0.5; + var levelSq = (float)(level * level); + + row.Diffuse = Vector3.Zero; + row.Specular = Vector3.Zero; + row.Emissive = new Vector3(levelSq); + } + public void Update() { UpdateTextureLabels(); @@ -277,11 +504,31 @@ public partial class ModEditWindow UpdateSamplers(); } - public MtrlTab( ModEditWindow edit, MtrlFile file ) + public MtrlTab( ModEditWindow edit, MtrlFile file, string filePath, bool writable ) { - _edit = edit; - Mtrl = file; + _edit = edit; + Mtrl = file; + FilePath = filePath; + Writable = writable; LoadShpk( FindAssociatedShpk( out _, out _ ) ); + if (writable) + BindToMaterialInstances(); + } + + ~MtrlTab() + { + DoDispose(); + } + + public void Dispose() + { + DoDispose(); + GC.SuppressFinalize(this); + } + + private void DoDispose() + { + UnbindFromMaterialInstances(); } public bool Valid diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 16ad708c..2d1859bd 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -37,16 +37,17 @@ public partial class ModEditWindow return ret; } - private static bool DrawShaderFlagsInput(MtrlFile file, bool disabled) + private static bool DrawShaderFlagsInput(MtrlTab tab, bool disabled) { var ret = false; - var shpkFlags = (int)file.ShaderPackage.Flags; + var shpkFlags = (int)tab.Mtrl.ShaderPackage.Flags; ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); if (ImGui.InputInt("Shader Package Flags", ref shpkFlags, 0, 0, ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) { - file.ShaderPackage.Flags = (uint)shpkFlags; - ret = true; + tab.Mtrl.ShaderPackage.Flags = (uint)shpkFlags; + ret = true; + tab.SetShaderPackageFlags((uint)shpkFlags); } return ret; @@ -221,6 +222,7 @@ public partial class ModEditWindow { ret = true; tab.UpdateConstantLabels(); + tab.SetMaterialParameter(constant.Id, valueIdx, values.Slice(valueIdx, 1)); } } } @@ -247,6 +249,7 @@ public partial class ModEditWindow ret = true; tab.UpdateConstantLabels(); + tab.SetMaterialParameter(constant.Id, 0, new float[constant.ByteSize >> 2]); } return ret; @@ -336,7 +339,7 @@ public partial class ModEditWindow private static bool DrawMaterialSampler(MtrlTab tab, bool disabled, ref int idx) { - var (label, filename) = tab.Samplers[idx]; + var (label, filename, samplerCrc) = tab.Samplers[idx]; using var tree = ImRaii.TreeNode(label); if (!tree) return false; @@ -366,6 +369,7 @@ public partial class ModEditWindow { tab.Mtrl.ShaderPackage.Samplers[idx].Flags = (uint)samplerFlags; ret = true; + tab.SetSamplerFlags(samplerCrc, (uint)samplerFlags); } if (!disabled @@ -410,9 +414,10 @@ public partial class ModEditWindow if (!ImGui.Button("Add Sampler")) return false; + var newSamplerId = tab.NewSamplerId; tab.Mtrl.ShaderPackage.Samplers = tab.Mtrl.ShaderPackage.Samplers.AddItem(new Sampler { - SamplerId = tab.NewSamplerId, + SamplerId = newSamplerId, TextureIndex = (byte)tab.Mtrl.Textures.Length, Flags = 0, }); @@ -423,6 +428,7 @@ public partial class ModEditWindow }); tab.UpdateSamplers(); tab.UpdateTextureLabels(); + tab.SetSamplerFlags(newSamplerId, 0); return true; } @@ -467,7 +473,7 @@ public partial class ModEditWindow return ret; ret |= DrawPackageNameInput(tab, disabled); - ret |= DrawShaderFlagsInput(tab.Mtrl, disabled); + ret |= DrawShaderFlagsInput(tab, disabled); DrawCustomAssociations(tab); ret |= DrawMaterialShaderKeys(tab, disabled); DrawMaterialShaders(tab); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index d7e23ac3..e4de66a8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -15,13 +15,16 @@ public partial class ModEditWindow private bool DrawMaterialPanel( MtrlTab tab, bool disabled ) { + DrawMaterialLivePreviewRebind( tab, disabled ); + + ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); var ret = DrawMaterialTextureChange( tab, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawBackFaceAndTransparency( tab.Mtrl, disabled ); + ret |= DrawBackFaceAndTransparency( tab, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawMaterialColorSetChange( tab.Mtrl, disabled ); + ret |= DrawMaterialColorSetChange( tab, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); ret |= DrawMaterialShaderResources( tab, disabled ); @@ -32,6 +35,15 @@ public partial class ModEditWindow return !disabled && ret; } + private static void DrawMaterialLivePreviewRebind( MtrlTab tab, bool disabled ) + { + if (disabled) + return; + + if (ImGui.Button("Reload live-preview")) + tab.BindToMaterialInstances(); + } + private static bool DrawMaterialTextureChange( MtrlTab tab, bool disabled ) { var ret = false; @@ -62,7 +74,7 @@ public partial class ModEditWindow return ret; } - private static bool DrawBackFaceAndTransparency( MtrlFile file, bool disabled ) + private static bool DrawBackFaceAndTransparency( MtrlTab tab, bool disabled ) { const uint transparencyBit = 0x10; const uint backfaceBit = 0x01; @@ -71,19 +83,21 @@ public partial class ModEditWindow using var dis = ImRaii.Disabled( disabled ); - var tmp = ( file.ShaderPackage.Flags & transparencyBit ) != 0; + var tmp = ( tab.Mtrl.ShaderPackage.Flags & transparencyBit ) != 0; if( ImGui.Checkbox( "Enable Transparency", ref tmp ) ) { - file.ShaderPackage.Flags = tmp ? file.ShaderPackage.Flags | transparencyBit : file.ShaderPackage.Flags & ~transparencyBit; - ret = true; + tab.Mtrl.ShaderPackage.Flags = tmp ? tab.Mtrl.ShaderPackage.Flags | transparencyBit : tab.Mtrl.ShaderPackage.Flags & ~transparencyBit; + ret = true; + tab.SetShaderPackageFlags(tab.Mtrl.ShaderPackage.Flags); } ImGui.SameLine( 200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X ); - tmp = ( file.ShaderPackage.Flags & backfaceBit ) != 0; + tmp = ( tab.Mtrl.ShaderPackage.Flags & backfaceBit ) != 0; if( ImGui.Checkbox( "Hide Backfaces", ref tmp ) ) { - file.ShaderPackage.Flags = tmp ? file.ShaderPackage.Flags | backfaceBit : file.ShaderPackage.Flags & ~backfaceBit; - ret = true; + tab.Mtrl.ShaderPackage.Flags = tmp ? tab.Mtrl.ShaderPackage.Flags | backfaceBit : tab.Mtrl.ShaderPackage.Flags & ~backfaceBit; + ret = true; + tab.SetShaderPackageFlags(tab.Mtrl.ShaderPackage.Flags); } return ret; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 59cf8b80..a37363e3 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -137,6 +137,9 @@ public partial class ModEditWindow : Window, IDisposable { _left.Dispose(); _right.Dispose(); + _materialTab.Reset(); + _modelTab.Reset(); + _shaderPackageTab.Reset(); } public override void Draw() @@ -541,12 +544,12 @@ public partial class ModEditWindow : Window, IDisposable _fileDialog = fileDialog; _materialTab = new FileEditor(this, gameData, config, _fileDialog, "Materials", ".mtrl", () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, - bytes => new MtrlTab(this, new MtrlFile(bytes))); + (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _fileDialog, "Models", ".mdl", - () => _editor.Files.Mdl, DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, bytes => new MdlFile(bytes)); + () => _editor.Files.Mdl, DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlFile(bytes)); _shaderPackageTab = new FileEditor(this, gameData, config, _fileDialog, "Shaders", ".shpk", () => _editor.Files.Shpk, DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, - bytes => new ShpkTab(_fileDialog, bytes)); + (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, 2, OnQuickImportRefresh, DrawQuickImportActions); @@ -557,6 +560,9 @@ public partial class ModEditWindow : Window, IDisposable { _communicator.ModPathChanged.Unsubscribe(OnModPathChanged); _editor?.Dispose(); + _materialTab.Dispose(); + _modelTab.Dispose(); + _shaderPackageTab.Dispose(); _left.Dispose(); _right.Dispose(); _center.Dispose(); From b8d09ab6602d141b99b37e019da6ed50b54734dc Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 24 Aug 2023 05:51:21 +0200 Subject: [PATCH 0034/1381] Material editor 2099 --- OtterGui | 2 +- Penumbra.GameData | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 2 +- Penumbra/Interop/Structs/CharacterBaseExt.cs | 15 + Penumbra/Interop/Structs/HumanExt.cs | 3 + .../ModEditWindow.Materials.ColorSet.cs | 101 ++- .../ModEditWindow.Materials.ConstantEditor.cs | 235 +++++++ .../ModEditWindow.Materials.LivePreview.cs | 10 +- .../ModEditWindow.Materials.MtrlTab.cs | 622 +++++++++++------ .../ModEditWindow.Materials.Shpk.cs | 654 ++++++++---------- .../AdvancedWindow/ModEditWindow.Materials.cs | 90 ++- .../ModEditWindow.ShaderPackages.cs | 88 ++- .../AdvancedWindow/ModEditWindow.ShpkTab.cs | 12 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 20 + Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 16 +- 15 files changed, 1221 insertions(+), 651 deletions(-) create mode 100644 Penumbra/Interop/Structs/CharacterBaseExt.cs create mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs diff --git a/OtterGui b/OtterGui index 863d08bd..1e172ee9 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 863d08bd83381bb7fe4a8d5c514f0ba55379336f +Subproject commit 1e172ee9a0f5946d67b848a36b2be97f6541453f diff --git a/Penumbra.GameData b/Penumbra.GameData index 97643cad..07c001c5 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 97643cad67b6981c3ee510d1ca12c4321e6a80bf +Subproject commit 07c001c5b2b35b2dba2b8428389d3ed375728616 diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 6dc005ee..d14bd68b 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -190,7 +190,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (WithNames) { - var name = samplers != null && i < samplers.Count ? samplers[i].Item2?.Name : null; + var name = samplers != null && i < samplers.Length ? samplers[i].ShpkSampler?.Name : null; node.Children.Add(texNode.WithName(name ?? $"Texture #{i}")); } else diff --git a/Penumbra/Interop/Structs/CharacterBaseExt.cs b/Penumbra/Interop/Structs/CharacterBaseExt.cs new file mode 100644 index 00000000..3bbbeca9 --- /dev/null +++ b/Penumbra/Interop/Structs/CharacterBaseExt.cs @@ -0,0 +1,15 @@ +using System.Runtime.InteropServices; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; + +namespace Penumbra.Interop.Structs; + +[StructLayout( LayoutKind.Explicit )] +public unsafe struct CharacterBaseExt +{ + [FieldOffset( 0x0 )] + public CharacterBase CharacterBase; + + [FieldOffset( 0x258 )] + public Texture** ColorSetTextures; +} \ No newline at end of file diff --git a/Penumbra/Interop/Structs/HumanExt.cs b/Penumbra/Interop/Structs/HumanExt.cs index 7af5cee4..33d83b06 100644 --- a/Penumbra/Interop/Structs/HumanExt.cs +++ b/Penumbra/Interop/Structs/HumanExt.cs @@ -9,6 +9,9 @@ public unsafe struct HumanExt [FieldOffset( 0x0 )] public Human Human; + [FieldOffset( 0x0 )] + public CharacterBaseExt CharacterBase; + [FieldOffset( 0x9E8 )] public ResourceHandle* Decal; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs index 1d6c480a..798939ca 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs @@ -13,22 +13,44 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { + private static readonly float HalfMinValue = (float)Half.MinValue; + private static readonly float HalfMaxValue = (float)Half.MaxValue; + private static readonly float HalfEpsilon = (float)Half.Epsilon; + private bool DrawMaterialColorSetChange( MtrlTab tab, bool disabled ) { - if( !tab.Mtrl.ColorSets.Any( c => c.HasRows ) ) + if( !tab.SamplerIds.Contains( ShpkFile.TableSamplerId ) || !tab.Mtrl.ColorSets.Any( c => c.HasRows ) ) { return false; } + ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); + if( !ImGui.CollapsingHeader( "Color Set", ImGuiTreeNodeFlags.DefaultOpen ) ) + { + return false; + } + + var hasAnyDye = tab.UseColorDyeSet; + ColorSetCopyAllClipboardButton( tab.Mtrl, 0 ); ImGui.SameLine(); - var ret = ColorSetPasteAllClipboardButton( tab, 0 ); - ImGui.SameLine(); - ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); - ImGui.SameLine(); - ret |= DrawPreviewDye( tab, disabled ); + var ret = ColorSetPasteAllClipboardButton( tab, 0, disabled ); + if( !disabled ) + { + ImGui.SameLine(); + ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); + ImGui.SameLine(); + ret |= ColorSetDyeableCheckbox( tab, ref hasAnyDye ); + } + if( hasAnyDye ) + { + ImGui.SameLine(); + ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); + ImGui.SameLine(); + ret |= DrawPreviewDye( tab, disabled ); + } - using var table = ImRaii.Table( "##ColorSets", 11, + using var table = ImRaii.Table( "##ColorSets", hasAnyDye ? 11 : 9, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV ); if( !table ) { @@ -53,17 +75,20 @@ public partial class ModEditWindow ImGui.TableHeader( "Repeat" ); ImGui.TableNextColumn(); ImGui.TableHeader( "Skew" ); - ImGui.TableNextColumn(); - ImGui.TableHeader( "Dye" ); - ImGui.TableNextColumn(); - ImGui.TableHeader( "Dye Preview" ); + if( hasAnyDye ) + { + ImGui.TableNextColumn(); + ImGui.TableHeader("Dye"); + ImGui.TableNextColumn(); + ImGui.TableHeader("Dye Preview"); + } for( var j = 0; j < tab.Mtrl.ColorSets.Length; ++j ) { using var _ = ImRaii.PushId( j ); for( var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i ) { - ret |= DrawColorSetRow( tab, j, i, disabled ); + ret |= DrawColorSetRow( tab, j, i, disabled, hasAnyDye ); ImGui.TableNextRow(); } } @@ -122,9 +147,9 @@ public partial class ModEditWindow return false; } - private static unsafe bool ColorSetPasteAllClipboardButton( MtrlTab tab, int colorSetIdx ) + private static unsafe bool ColorSetPasteAllClipboardButton( MtrlTab tab, int colorSetIdx, bool disabled ) { - if( !ImGui.Button( "Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2( 200, 0 ) ) || tab.Mtrl.ColorSets.Length <= colorSetIdx ) + if( !ImGuiUtil.DrawDisabledButton( "Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2( 200, 0 ), string.Empty, disabled ) || tab.Mtrl.ColorSets.Length <= colorSetIdx ) { return false; } @@ -187,6 +212,21 @@ public partial class ModEditWindow } } + private static bool ColorSetDyeableCheckbox( MtrlTab tab, ref bool dyeable ) + { + var ret = ImGui.Checkbox( "Dyeable", ref dyeable ); + + if( ret ) + { + tab.UseColorDyeSet = dyeable; + if( dyeable ) + tab.Mtrl.FindOrAddColorDyeSet(); + tab.UpdateColorSetPreview(); + } + + return ret; + } + private static unsafe bool ColorSetPasteFromClipboardButton( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled ) { if( ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, @@ -235,7 +275,7 @@ public partial class ModEditWindow tab.CancelColorSetHighlight(); } - private bool DrawColorSetRow( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled ) + private bool DrawColorSetRow( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, bool hasAnyDye ) { static bool FixFloat( ref float val, float current ) { @@ -245,7 +285,7 @@ public partial class ModEditWindow using var id = ImRaii.PushId( rowIdx ); var row = tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ]; - var hasDye = tab.Mtrl.ColorDyeSets.Length > colorSetIdx; + var hasDye = hasAnyDye && tab.Mtrl.ColorDyeSets.Length > colorSetIdx; var dye = hasDye ? tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] : new MtrlFile.ColorDyeSet.Row(); var floatSize = 70 * UiHelpers.Scale; var intSize = 45 * UiHelpers.Scale; @@ -274,7 +314,7 @@ public partial class ModEditWindow ImGui.SameLine(); var tmpFloat = row.SpecularStrength; ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##SpecularStrength", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.SpecularStrength ) ) + if( ImGui.DragFloat( "##SpecularStrength", ref tmpFloat, 0.1f, 0f, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.SpecularStrength ) ) { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = tmpFloat; ret = true; @@ -305,9 +345,9 @@ public partial class ModEditWindow ImGui.TableNextColumn(); tmpFloat = row.GlossStrength; ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##GlossStrength", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.GlossStrength ) ) + if( ImGui.DragFloat( "##GlossStrength", ref tmpFloat, Math.Max( 0.1f, tmpFloat * 0.025f ), HalfEpsilon, HalfMaxValue, "%.1f" ) && FixFloat( ref tmpFloat, row.GlossStrength ) ) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].GlossStrength = tmpFloat; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].GlossStrength = Math.Max(tmpFloat, HalfEpsilon); ret = true; tab.UpdateColorSetRowPreview(rowIdx); } @@ -323,9 +363,9 @@ public partial class ModEditWindow ImGui.TableNextColumn(); int tmpInt = row.TileSet; ImGui.SetNextItemWidth( intSize ); - if( ImGui.InputInt( "##TileSet", ref tmpInt, 0, 0 ) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue ) + if( ImGui.DragInt( "##TileSet", ref tmpInt, 0.25f, 0, 63 ) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue ) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].TileSet = ( ushort )tmpInt; + tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].TileSet = ( ushort )Math.Clamp(tmpInt, 0, 63); ret = true; tab.UpdateColorSetRowPreview(rowIdx); } @@ -335,7 +375,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); tmpFloat = row.MaterialRepeat.X; ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##RepeatX", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialRepeat.X ) ) + if( ImGui.DragFloat( "##RepeatX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialRepeat.X ) ) { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; ret = true; @@ -346,7 +386,7 @@ public partial class ModEditWindow ImGui.SameLine(); tmpFloat = row.MaterialRepeat.Y; ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##RepeatY", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialRepeat.Y ) ) + if( ImGui.DragFloat( "##RepeatY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialRepeat.Y ) ) { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; ret = true; @@ -358,7 +398,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); tmpFloat = row.MaterialSkew.X; ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##SkewX", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialSkew.X ) ) + if( ImGui.DragFloat( "##SkewX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialSkew.X ) ) { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { X = tmpFloat }; ret = true; @@ -370,7 +410,7 @@ public partial class ModEditWindow ImGui.SameLine(); tmpFloat = row.MaterialSkew.Y; ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##SkewY", ref tmpFloat, 0.1f, 0f ) && FixFloat( ref tmpFloat, row.MaterialSkew.Y ) ) + if( ImGui.DragFloat( "##SkewY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialSkew.Y ) ) { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; ret = true; @@ -379,10 +419,10 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip( "Skew Y", ImGuiHoveredFlags.AllowWhenDisabled ); - ImGui.TableNextColumn(); if( hasDye ) { - if(_stainService.TemplateCombo.Draw( "##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + ImGui.TableNextColumn(); + if (_stainService.TemplateCombo.Draw( "##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton ) ) { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Template = _stainService.TemplateCombo.CurrentSelection; @@ -395,9 +435,10 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ret |= DrawDyePreview( tab, colorSetIdx, rowIdx, disabled, dye, floatSize ); } - else + else if ( hasAnyDye ) { ImGui.TableNextColumn(); + ImGui.TableNextColumn(); } @@ -431,10 +472,10 @@ public partial class ModEditWindow ImGui.SameLine(); using var dis = ImRaii.Disabled(); ImGui.SetNextItemWidth( floatSize ); - ImGui.DragFloat( "##gloss", ref values.Gloss, 0, 0, 0, "%.2f G" ); + ImGui.DragFloat( "##gloss", ref values.Gloss, 0, values.Gloss, values.Gloss, "%.1f G" ); ImGui.SameLine(); ImGui.SetNextItemWidth( floatSize ); - ImGui.DragFloat( "##specularStrength", ref values.SpecularPower, 0, 0, 0, "%.2f S" ); + ImGui.DragFloat( "##specularStrength", ref values.SpecularPower, 0, values.SpecularPower, values.SpecularPower, "%.2f S" ); return ret; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs new file mode 100644 index 00000000..5616425c --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui; +using Penumbra.GameData; + +namespace Penumbra.UI.AdvancedWindow; + +public partial class ModEditWindow +{ + private interface IConstantEditor + { + bool Draw(Span values, bool disabled, float editorWidth); + } + + private sealed class FloatConstantEditor : IConstantEditor + { + public static readonly FloatConstantEditor Default = new(null, null, 0.1f, 0.0f, 1.0f, 0.0f, 3, string.Empty); + + private readonly float? _minimum; + private readonly float? _maximum; + private readonly float _speed; + private readonly float _relativeSpeed; + private readonly float _factor; + private readonly float _bias; + private readonly string _format; + + public FloatConstantEditor(float? minimum, float? maximum, float speed, float relativeSpeed, float factor, float bias, byte precision, string unit) + { + _minimum = minimum; + _maximum = maximum; + _speed = speed; + _relativeSpeed = relativeSpeed; + _factor = factor; + _bias = bias; + _format = $"%.{Math.Min(precision, (byte)9)}f"; + if (unit.Length > 0) + _format = $"{_format} {unit.Replace("%", "%%")}"; + } + + public bool Draw(Span values, bool disabled, float editorWidth) + { + var fieldWidth = (editorWidth - (values.Length - 1) * ImGui.GetStyle().ItemSpacing.X) / values.Length; + + var ret = false; + + for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) + { + if (valueIdx > 0) + ImGui.SameLine(); + + ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); + + var value = (values[valueIdx] - _bias) / _factor; + if (disabled) + ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), value, value, _format); + else + { + if (ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0.0f, _maximum ?? 0.0f, _format)) + { + values[valueIdx] = Clamp(value) * _factor + _bias; + ret = true; + } + } + } + + return ret; + } + + private float Clamp(float value) + => Math.Clamp(value, _minimum ?? float.NegativeInfinity, _maximum ?? float.PositiveInfinity); + } + + private sealed class IntConstantEditor : IConstantEditor + { + private readonly int? _minimum; + private readonly int? _maximum; + private readonly float _speed; + private readonly float _relativeSpeed; + private readonly float _factor; + private readonly float _bias; + private readonly string _format; + + public IntConstantEditor(int? minimum, int? maximum, float speed, float relativeSpeed, float factor, float bias, string unit) + { + _minimum = minimum; + _maximum = maximum; + _speed = speed; + _relativeSpeed = relativeSpeed; + _factor = factor; + _bias = bias; + _format = "%d"; + if (unit.Length > 0) + _format = $"{_format} {unit.Replace("%", "%%")}"; + } + + public bool Draw(Span values, bool disabled, float editorWidth) + { + var fieldWidth = (editorWidth - (values.Length - 1) * ImGui.GetStyle().ItemSpacing.X) / values.Length; + + var ret = false; + + for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) + { + if (valueIdx > 0) + ImGui.SameLine(); + + ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); + + var value = (int)Math.Clamp(MathF.Round((values[valueIdx] - _bias) / _factor), int.MinValue, int.MaxValue); + if (disabled) + ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), value, value, _format); + else + { + if (ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0, _maximum ?? 0, _format)) + { + values[valueIdx] = Clamp(value) * _factor + _bias; + ret = true; + } + } + } + + return ret; + } + + private int Clamp(int value) + => Math.Clamp(value, _minimum ?? int.MinValue, _maximum ?? int.MaxValue); + } + + private sealed class ColorConstantEditor : IConstantEditor + { + private readonly bool _squaredRgb; + private readonly bool _clamped; + + public ColorConstantEditor(bool squaredRgb, bool clamped) + { + _squaredRgb = squaredRgb; + _clamped = clamped; + } + + public bool Draw(Span values, bool disabled, float editorWidth) + { + if (values.Length == 3) + { + ImGui.SetNextItemWidth(editorWidth); + var value = new Vector3(values); + if (_squaredRgb) + value = Vector3.SquareRoot(value); + if (ImGui.ColorEdit3("##0", ref value) && !disabled) + { + if (_squaredRgb) + value *= value; + if (_clamped) + value = Vector3.Clamp(value, Vector3.Zero, Vector3.One); + value.CopyTo(values); + return true; + } + + return false; + } + else if (values.Length == 4) + { + ImGui.SetNextItemWidth(editorWidth); + var value = new Vector4(values); + if (_squaredRgb) + value = new Vector4(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z), value.W); + if (ImGui.ColorEdit4("##0", ref value) && !disabled) + { + if (_squaredRgb) + value *= new Vector4(value.X, value.Y, value.Z, 1.0f); + if (_clamped) + value = Vector4.Clamp(value, Vector4.Zero, Vector4.One); + value.CopyTo(values); + return true; + } + + return false; + } + else + return FloatConstantEditor.Default.Draw(values, disabled, editorWidth); + } + } + + private sealed class EnumConstantEditor : IConstantEditor + { + private readonly IReadOnlyList<(string Label, float Value, string Description)> _values; + + public EnumConstantEditor(IReadOnlyList<(string Label, float Value, string Description)> values) + { + _values = values; + } + + public bool Draw(Span values, bool disabled, float editorWidth) + { + var fieldWidth = (editorWidth - (values.Length - 1) * ImGui.GetStyle().ItemSpacing.X) / values.Length; + + var ret = false; + + for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) + { + if (valueIdx > 0) + ImGui.SameLine(); + + ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); + + var currentValue = values[valueIdx]; + var (currentLabel, _, currentDescription) = _values.FirstOrNull(v => v.Value == currentValue) ?? (currentValue.ToString(), currentValue, string.Empty); + if (disabled) + ImGui.InputText($"##{valueIdx}", ref currentLabel, (uint)currentLabel.Length, ImGuiInputTextFlags.ReadOnly); + else + { + using var c = ImRaii.Combo($"##{valueIdx}", currentLabel); + { + if (c) + foreach (var (valueLabel, value, valueDescription) in _values) + { + if (ImGui.Selectable(valueLabel, value == currentValue)) + { + values[valueIdx] = value; + ret = true; + } + + if (valueDescription.Length > 0) + ImGuiUtil.SelectableHelpMarker(valueDescription); + } + } + } + } + + return ret; + } + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs index 376e656f..7d400a71 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs @@ -398,7 +398,7 @@ public partial class ModEditWindow if (mtrlHandle == null) throw new InvalidOperationException("Material doesn't have a resource handle"); - var colorSetTextures = *(Texture***)((nint)DrawObject + 0x258); + var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; if (colorSetTextures == null) throw new InvalidOperationException("Draw object doesn't have color set textures"); @@ -424,7 +424,8 @@ public partial class ModEditWindow if (reset) { var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)_originalColorSetTexture); - Structs.TextureUtility.DecRef(oldTexture); + if (oldTexture != null) + Structs.TextureUtility.DecRef(oldTexture); } else Structs.TextureUtility.DecRef(_originalColorSetTexture); @@ -460,7 +461,8 @@ public partial class ModEditWindow if (success) { var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)newTexture); - Structs.TextureUtility.DecRef(oldTexture); + if (oldTexture != null) + Structs.TextureUtility.DecRef(oldTexture); } else Structs.TextureUtility.DecRef(newTexture); @@ -471,7 +473,7 @@ public partial class ModEditWindow if (!base.IsStillValid()) return false; - var colorSetTextures = *(Texture***)((nint)DrawObject + 0x258); + var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; if (colorSetTextures == null) return false; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 9cff681a..17f34b64 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -8,6 +8,7 @@ using Dalamud.Interface.Internal.Notifications; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; @@ -16,6 +17,7 @@ using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; using Penumbra.Services; +using Penumbra.String; using Penumbra.String.Classes; using Penumbra.Util; using static Penumbra.GameData.Files.ShpkFile; @@ -26,49 +28,47 @@ public partial class ModEditWindow { private sealed class MtrlTab : IWritable, IDisposable { + private const int ShpkPrefixLength = 16; + + private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); + private readonly ModEditWindow _edit; public readonly MtrlFile Mtrl; public readonly string FilePath; public readonly bool Writable; - public uint NewKeyId; - public uint NewKeyDefault; - public uint NewConstantId; - public int NewConstantIdx; - public uint NewSamplerId; - public int NewSamplerIdx; + private string[]? _shpkNames; + public string ShaderHeader = "Shader###Shader"; + public FullPath LoadedShpkPath = FullPath.Empty; + public string LoadedShpkPathName = string.Empty; + public string LoadedShpkDevkitPathName = string.Empty; + public string ShaderComment = string.Empty; + public ShpkFile? AssociatedShpk; + public JObject? AssociatedShpkDevkit; - public ShpkFile? AssociatedShpk; - public readonly List< string > TextureLabels = new(4); - public FullPath LoadedShpkPath = FullPath.Empty; - public string LoadedShpkPathName = string.Empty; - public float TextureLabelWidth; + public readonly string LoadedBaseDevkitPathName = string.Empty; + public readonly JObject? AssociatedBaseDevkit; // Shader Key State - public readonly List< string > ShaderKeyLabels = new(16); - public readonly Dictionary< uint, uint > DefinedShaderKeys = new(16); - public readonly List< int > MissingShaderKeyIndices = new(16); - public readonly List< uint > AvailableKeyValues = new(16); - public string VertexShaders = "Vertex Shaders: ???"; - public string PixelShaders = "Pixel Shaders: ???"; + public readonly List< (string Label, int Index, string Description, bool MonoFont, IReadOnlyList< (string Label, uint Value, string Description) > Values) > ShaderKeys = new(16); + + public readonly HashSet< int > VertexShaders = new(16); + public readonly HashSet< int > PixelShaders = new(16); + public bool ShadersKnown = false; + public string VertexShadersString = "Vertex Shaders: ???"; + public string PixelShadersString = "Pixel Shaders: ???"; + + // Textures & Samplers + public readonly List< (string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont) > Textures = new(4); + + public readonly HashSet< int > UnfoldedTextures = new(4); + public readonly HashSet< uint > SamplerIds = new(16); + public float TextureLabelWidth; + public bool UseColorDyeSet; // Material Constants - public readonly List< (string Name, bool ComponentOnly, int ParamValueOffset) > MaterialConstants = new(16); - public readonly List< (string Name, uint Id, ushort ByteSize) > MissingMaterialConstants = new(16); - public readonly HashSet< uint > DefinedMaterialConstants = new(16); - - public string MaterialConstantLabel = "Constants###Constants"; - public IndexSet OrphanedMaterialValues = new(0, false); - public int AliasedMaterialValueCount; - public bool HasMalformedMaterialConstants; - - // Samplers - public readonly List< (string Label, string FileName, uint Id) > Samplers = new(4); - public readonly List< (string Name, uint Id) > MissingSamplers = new(4); - public readonly HashSet< uint > DefinedSamplers = new(4); - public IndexSet OrphanedSamplers = new(0, false); - public int AliasedSamplerCount; + public readonly List< (string Header, List< (string Label, int ConstantIndex, Range Slice, string Description, bool MonoFont, IConstantEditor Editor) > Constants) > Constants = new(16); // Live-Previewers public readonly List MaterialPreviewers = new(4); @@ -87,8 +87,24 @@ public partial class ModEditWindow return _edit.FindBestMatch( defaultGamePath ); } + public string[] GetShpkNames() + { + if (null != _shpkNames) + return _shpkNames; + + var names = new HashSet(StandardShaderPackages); + names.UnionWith(_edit.FindPathsStartingWith(ShpkPrefix).Select(path => path.ToString()[ShpkPrefixLength..])); + + _shpkNames = names.ToArray(); + Array.Sort(_shpkNames); + + return _shpkNames; + } + public void LoadShpk( FullPath path ) { + ShaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; + try { LoadedShpkPath = path; @@ -106,180 +122,314 @@ public partial class ModEditWindow Penumbra.Chat.NotificationMessage( $"Could not load {LoadedShpkPath.ToPath()}:\n{e}", "Penumbra Advanced Editing", NotificationType.Error ); } + if( LoadedShpkPath.InternalName.IsEmpty ) + { + AssociatedShpkDevkit = null; + LoadedShpkDevkitPathName = string.Empty; + } + else + AssociatedShpkDevkit = TryLoadShpkDevkit( Path.GetFileNameWithoutExtension( Mtrl.ShaderPackage.Name ), out LoadedShpkDevkitPathName ); + + UpdateShaderKeys(); Update(); } - public void UpdateTextureLabels() + private JObject? TryLoadShpkDevkit(string shpkBaseName, out string devkitPathName) { - var samplers = Mtrl.GetSamplersByTexture( AssociatedShpk ); - TextureLabels.Clear(); - TextureLabelWidth = 50f * UiHelpers.Scale; - using( var _ = ImRaii.PushFont( UiBuilder.MonoFont ) ) + try { - for( var i = 0; i < Mtrl.Textures.Length; ++i ) - { - var (sampler, shpkSampler) = samplers[ i ]; - var name = shpkSampler.HasValue ? shpkSampler.Value.Name : sampler.HasValue ? $"0x{sampler.Value.SamplerId:X8}" : $"#{i}"; - TextureLabels.Add( name ); - TextureLabelWidth = Math.Max( TextureLabelWidth, ImGui.CalcTextSize( name ).X ); - } - } + if (!Utf8GamePath.FromString("penumbra/shpk_devkit/" + shpkBaseName + ".json", out var devkitPath)) + throw new Exception("Could not assemble ShPk dev-kit path."); - TextureLabelWidth = TextureLabelWidth / UiHelpers.Scale + 4; + var devkitFullPath = _edit.FindBestMatch(devkitPath); + if (!devkitFullPath.IsRooted) + throw new Exception("Could not resolve ShPk dev-kit path."); + + devkitPathName = devkitFullPath.FullName; + return JObject.Parse(File.ReadAllText(devkitFullPath.FullName)); + } + catch + { + devkitPathName = string.Empty; + return null; + } } - public void UpdateShaderKeyLabels() + private T? TryGetShpkDevkitData(string category, uint? id, bool mayVary) where T : class { - ShaderKeyLabels.Clear(); - DefinedShaderKeys.Clear(); - foreach( var (key, idx) in Mtrl.ShaderPackage.ShaderKeys.WithIndex() ) - { - ShaderKeyLabels.Add( $"#{idx}: 0x{key.Category:X8} = 0x{key.Value:X8}###{idx}: 0x{key.Category:X8}" ); - DefinedShaderKeys.Add( key.Category, key.Value ); - } + return TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) + ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); + } - MissingShaderKeyIndices.Clear(); - AvailableKeyValues.Clear(); - var vertexShaders = new IndexSet( AssociatedShpk?.VertexShaders.Length ?? 0, false ); - var pixelShaders = new IndexSet( AssociatedShpk?.PixelShaders.Length ?? 0, false ); - if( AssociatedShpk != null ) - { - MissingShaderKeyIndices.AddRange( AssociatedShpk.MaterialKeys.WithIndex().Where( k => !DefinedShaderKeys.ContainsKey( k.Value.Id ) ).WithoutValue() ); + private T? TryGetShpkDevkitData(JObject? devkit, string devkitPathName, string category, uint? id, bool mayVary) where T : class + { + if (devkit == null) + return null; - if( MissingShaderKeyIndices.Count > 0 && MissingShaderKeyIndices.All( i => AssociatedShpk.MaterialKeys[ i ].Id != NewKeyId ) ) + try + { + var data = devkit[category]; + if (id.HasValue) + data = data?[id.Value.ToString()]; + + if (mayVary && (data as JObject)?["Vary"] != null) { - var key = AssociatedShpk.MaterialKeys[ MissingShaderKeyIndices[ 0 ] ]; - NewKeyId = key.Id; - NewKeyDefault = key.DefaultValue; + var selector = BuildSelector(data!["Vary"]! + .Select(key => (uint)key) + .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); + var index = (int)data["Selectors"]![selector.ToString()]!; + data = data["Items"]![index]; } - AvailableKeyValues.AddRange( AssociatedShpk.MaterialKeys.Select( k => DefinedShaderKeys.TryGetValue( k.Id, out var value ) ? value : k.DefaultValue ) ); - foreach( var node in AssociatedShpk.Nodes ) + return data?.ToObject(typeof(T)) as T; + } + catch (Exception e) + { + // Some element in the JSON was undefined or invalid (wrong type, key that doesn't exist in the ShPk, index out of range, …) + Penumbra.Log.Error($"Error while traversing the ShPk dev-kit file at {devkitPathName}: {e}"); + return null; + } + } + + public void UpdateShaderKeys() + { + ShaderKeys.Clear(); + if (AssociatedShpk != null) + { + foreach (var key in AssociatedShpk.MaterialKeys) { - if( node.MaterialKeys.WithIndex().All( key => key.Value == AvailableKeyValues[ key.Index ] ) ) + var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); + var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); + + var valueSet = new HashSet(key.Values); + if (dkData != null) + valueSet.UnionWith(dkData.Values.Keys); + + var mtrlKeyIndex = Mtrl.FindOrAddShaderKey(key.Id, key.DefaultValue); + var values = valueSet.Select(value => { - foreach( var pass in node.Passes ) + if (dkData != null && dkData.Values.TryGetValue(value, out var dkValue)) + return (dkValue.Label.Length > 0 ? dkValue.Label : $"0x{value:X8}", value, dkValue.Description); + else + return ($"0x{value:X8}", value, string.Empty); + }).ToArray(); + Array.Sort(values, (x, y) => + { + if (x.Value == key.DefaultValue) + return -1; + if (y.Value == key.DefaultValue) + return 1; + return x.Label.CompareTo(y.Label); + }); + ShaderKeys.Add((hasDkLabel ? dkData!.Label : $"0x{key.Id:X8}", mtrlKeyIndex, dkData?.Description ?? string.Empty, !hasDkLabel, values)); + } + } + else + { + foreach (var (key, index) in Mtrl.ShaderPackage.ShaderKeys.WithIndex()) + ShaderKeys.Add(($"0x{key.Category:X8}", index, string.Empty, true, Array.Empty<(string, uint, string)>())); + } + } + + public void UpdateShaders() + { + VertexShaders.Clear(); + PixelShaders.Clear(); + if (AssociatedShpk == null) + ShadersKnown = false; + else + { + ShadersKnown = true; + var systemKeySelectors = AllSelectors(AssociatedShpk.SystemKeys).ToArray(); + var sceneKeySelectors = AllSelectors(AssociatedShpk.SceneKeys).ToArray(); + var subViewKeySelectors = AllSelectors(AssociatedShpk.SubViewKeys).ToArray(); + var materialKeySelector = BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); + foreach (var systemKeySelector in systemKeySelectors) + { + foreach (var sceneKeySelector in sceneKeySelectors) + { + foreach (var subViewKeySelector in subViewKeySelectors) { - vertexShaders.Add( ( int )pass.VertexShader ); - pixelShaders.Add( ( int )pass.PixelShader ); + var selector = BuildSelector(systemKeySelector, sceneKeySelector, materialKeySelector, subViewKeySelector); + var node = AssociatedShpk.GetNodeBySelector(selector); + if (node.HasValue) + { + foreach (var pass in node.Value.Passes) + { + VertexShaders.Add((int)pass.VertexShader); + PixelShaders.Add((int)pass.PixelShader); + } + } + else + ShadersKnown = false; } } } } - VertexShaders = $"Vertex Shaders: {( vertexShaders.Count > 0 ? string.Join( ", ", vertexShaders.Select( i => $"#{i}" ) ) : "???" )}"; - PixelShaders = $"Pixel Shaders: {( pixelShaders.Count > 0 ? string.Join( ", ", pixelShaders.Select( i => $"#{i}" ) ) : "???" )}"; + var vertexShaders = VertexShaders.OrderBy(i => i).Select(i => $"#{i}"); + var pixelShaders = PixelShaders.OrderBy(i => i).Select(i => $"#{i}"); + + VertexShadersString = $"Vertex Shaders: {string.Join(", ", ShadersKnown ? vertexShaders : vertexShaders.Append("???"))}"; + PixelShadersString = $"Pixel Shaders: {string.Join(", ", ShadersKnown ? pixelShaders : pixelShaders.Append("???"))}"; + + ShaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; } - public void UpdateConstantLabels() + public void UpdateTextures() { - var prefix = AssociatedShpk?.GetConstantById( MaterialParamsConstantId )?.Name ?? string.Empty; - MaterialConstantLabel = prefix.Length == 0 ? "Constants###Constants" : prefix + "###Constants"; - - DefinedMaterialConstants.Clear(); - MaterialConstants.Clear(); - HasMalformedMaterialConstants = false; - AliasedMaterialValueCount = 0; - OrphanedMaterialValues = new IndexSet( Mtrl.ShaderPackage.ShaderValues.Length, true ); - foreach( var (constant, idx) in Mtrl.ShaderPackage.Constants.WithIndex() ) + Textures.Clear(); + SamplerIds.Clear(); + if (AssociatedShpk == null) { - DefinedMaterialConstants.Add( constant.Id ); - var values = Mtrl.GetConstantValues( constant ); - var paramValueOffset = -values.Length; - if( values.Length > 0 ) + SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); + if (Mtrl.ColorSets.Any(c => c.HasRows)) + SamplerIds.Add(TableSamplerId); + + foreach (var (sampler, index) in Mtrl.ShaderPackage.Samplers.WithIndex()) + Textures.Add(($"0x{sampler.SamplerId:X8}", sampler.TextureIndex, index, string.Empty, true)); + } + else + { + foreach (var index in VertexShaders) + SamplerIds.UnionWith(AssociatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); + foreach (var index in PixelShaders) + SamplerIds.UnionWith(AssociatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); + if (!ShadersKnown) { - var shpkParam = AssociatedShpk?.GetMaterialParamById( constant.Id ); - var paramByteOffset = shpkParam?.ByteOffset ?? -1; - if( ( paramByteOffset & 0x3 ) == 0 ) - { - paramValueOffset = paramByteOffset >> 2; - } - - var unique = OrphanedMaterialValues.RemoveRange( constant.ByteOffset >> 2, values.Length ); - AliasedMaterialValueCount += values.Length - unique; + SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); + if (Mtrl.ColorSets.Any(c => c.HasRows)) + SamplerIds.Add(TableSamplerId); } - else + foreach (var samplerId in SamplerIds) { - HasMalformedMaterialConstants = true; + var shpkSampler = AssociatedShpk.GetSamplerById(samplerId); + if (!shpkSampler.HasValue || shpkSampler.Value.Slot != 2) + continue; + + var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); + var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); + + var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); + Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, dkData?.Description ?? string.Empty, !hasDkLabel)); } + if (SamplerIds.Contains(TableSamplerId)) + Mtrl.FindOrAddColorSet(); + } + Textures.Sort((x, y) => string.CompareOrdinal(x.Label, y.Label)); - var (name, componentOnly) = MaterialParamRangeName( prefix, paramValueOffset, values.Length ); - var label = name == null - ? $"#{idx:D2} (ID: 0x{constant.Id:X8})###{constant.Id}" - : $"#{idx:D2}: {name} (ID: 0x{constant.Id:X8})###{constant.Id}"; + TextureLabelWidth = 50f * UiHelpers.Scale; - MaterialConstants.Add( ( label, componentOnly, paramValueOffset ) ); + float helpWidth; + using (var _ = ImRaii.PushFont(UiBuilder.IconFont)) + helpWidth = ImGui.GetStyle().ItemSpacing.X + ImGui.CalcTextSize(FontAwesomeIcon.InfoCircle.ToIconString()).X; + + foreach (var (label, _, _, description, monoFont) in Textures) + if (!monoFont) + TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); + + using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) + { + foreach (var (label, _, _, description, monoFont) in Textures) + if (monoFont) + TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); } - MissingMaterialConstants.Clear(); - if( AssociatedShpk != null ) - { - var setIdx = false; - foreach( var param in AssociatedShpk.MaterialParams.Where( m => !DefinedMaterialConstants.Contains( m.Id ) ) ) - { - var (name, _) = MaterialParamRangeName( prefix, param.ByteOffset >> 2, param.ByteSize >> 2 ); - var label = name == null - ? $"(ID: 0x{param.Id:X8})" - : $"{name} (ID: 0x{param.Id:X8})"; - if( NewConstantId == param.Id ) - { - setIdx = true; - NewConstantIdx = MissingMaterialConstants.Count; - } - - MissingMaterialConstants.Add( ( label, param.Id, param.ByteSize ) ); - } - - if( !setIdx && MissingMaterialConstants.Count > 0 ) - { - NewConstantIdx = 0; - NewConstantId = MissingMaterialConstants[ 0 ].Id; - } - } + TextureLabelWidth = TextureLabelWidth / UiHelpers.Scale + 4; } - public void UpdateSamplers() + public void UpdateConstants() { - Samplers.Clear(); - DefinedSamplers.Clear(); - OrphanedSamplers = new IndexSet( Mtrl.Textures.Length, true ); - foreach( var (sampler, idx) in Mtrl.ShaderPackage.Samplers.WithIndex() ) + static List FindOrAddGroup(List<(string, List)> groups, string name) { - DefinedSamplers.Add( sampler.SamplerId ); - if( !OrphanedSamplers.Remove( sampler.TextureIndex ) ) - { - ++AliasedSamplerCount; - } + foreach (var (groupName, group) in groups) + if (string.Equals(name, groupName, StringComparison.Ordinal)) + return group; - var shpk = AssociatedShpk?.GetSamplerById( sampler.SamplerId ); - var label = shpk.HasValue - ? $"#{idx}: {shpk.Value.Name} (ID: 0x{sampler.SamplerId:X8})##{sampler.SamplerId}" - : $"#{idx} (ID: 0x{sampler.SamplerId:X8})##{sampler.SamplerId}"; - var fileName = $"Texture #{sampler.TextureIndex} - {Path.GetFileName( Mtrl.Textures[ sampler.TextureIndex ].Path )}"; - Samplers.Add( ( label, fileName, sampler.SamplerId ) ); + var newGroup = new List(16); + groups.Add((name, newGroup)); + return newGroup; } - MissingSamplers.Clear(); - if( AssociatedShpk != null ) + Constants.Clear(); + if (AssociatedShpk == null) { - var setSampler = false; - foreach( var sampler in AssociatedShpk.Samplers.Where( s => s.Slot == 2 && !DefinedSamplers.Contains( s.Id ) ) ) + var fcGroup = FindOrAddGroup(Constants, "Further Constants"); + foreach (var (constant, index) in Mtrl.ShaderPackage.Constants.WithIndex()) { - if( sampler.Id == NewSamplerId ) + var values = Mtrl.GetConstantValues(constant); + for (var i = 0; i < values.Length; i += 4) + fcGroup.Add(($"0x{constant.Id:X8}", index, i..Math.Min(i + 4, values.Length), string.Empty, true, FloatConstantEditor.Default)); + } + } + else + { + var prefix = AssociatedShpk.GetConstantById(MaterialParamsConstantId)?.Name ?? string.Empty; + foreach (var shpkConstant in AssociatedShpk.MaterialParams) + { + if ((shpkConstant.ByteSize & 0x3) != 0) + continue; + + var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, shpkConstant.ByteSize >> 2, out var constantIndex); + var values = Mtrl.GetConstantValues(constant); + var handledElements = new IndexSet(values.Length, false); + + var dkData = TryGetShpkDevkitData("Constants", shpkConstant.Id, true); + if (dkData != null) { - setSampler = true; - NewSamplerIdx = MissingSamplers.Count; + foreach (var dkConstant in dkData) + { + var offset = (int)dkConstant.Offset; + var length = values.Length - offset; + if (dkConstant.Length.HasValue) + length = Math.Min(length, (int)dkConstant.Length.Value); + if (length <= 0) + continue; + var editor = dkConstant.CreateEditor(); + if (editor != null) + FindOrAddGroup(Constants, dkConstant.Group.Length > 0 ? dkConstant.Group : "Further Constants") + .Add((dkConstant.Label, constantIndex, offset..(offset + length), dkConstant.Description, false, editor)); + handledElements.AddRange(offset, length); + } } - MissingSamplers.Add( ( sampler.Name, sampler.Id ) ); - } - - if( !setSampler && MissingSamplers.Count > 0 ) - { - NewSamplerIdx = 0; - NewSamplerId = MissingSamplers[ 0 ].Id; + var fcGroup = FindOrAddGroup(Constants, "Further Constants"); + foreach (var (start, end) in handledElements.Ranges(true)) + { + if ((shpkConstant.ByteOffset & 0x3) == 0) + { + var offset = shpkConstant.ByteOffset >> 2; + for (int i = (start & ~0x3) - (offset & 0x3), j = offset >> 2; i < end; i += 4, ++j) + { + var rangeStart = Math.Max(i, start); + var rangeEnd = Math.Min(i + 4, end); + if (rangeEnd > rangeStart) + fcGroup.Add(($"{prefix}[{j:D2}]{VectorSwizzle((offset + rangeStart) & 0x3, (offset + rangeEnd - 1) & 0x3)} (0x{shpkConstant.Id:X8})", constantIndex, rangeStart..rangeEnd, string.Empty, true, FloatConstantEditor.Default)); + } + } + else + { + for (var i = start; i < end; i += 4) + fcGroup.Add(($"0x{shpkConstant.Id:X8}", constantIndex, i..Math.Min(i + 4, end), string.Empty, true, FloatConstantEditor.Default)); + } + } } } + + Constants.RemoveAll(group => group.Constants.Count == 0); + Constants.Sort((x, y) => + { + if (string.Equals(x.Header, "Further Constants", StringComparison.Ordinal)) + return 1; + if (string.Equals(y.Header, "Further Constants", StringComparison.Ordinal)) + return -1; + return string.Compare(x.Header, y.Header, StringComparison.Ordinal); + }); + // HACK the Replace makes w appear after xyz, for the cbuffer-location-based naming scheme + foreach (var (_, group) in Constants) + group.Sort((x, y) => string.CompareOrdinal( + x.MonoFont ? x.Label.Replace("].w", "].{") : x.Label, + y.MonoFont ? y.Label.Replace("].w", "].{") : y.Label)); } public unsafe void BindToMaterialInstances() @@ -329,6 +479,7 @@ public partial class ModEditWindow // Carry on without that previewer. } } + UpdateMaterialPreview(); var colorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); @@ -378,6 +529,19 @@ public partial class ModEditWindow previewer.SetSamplerFlags(samplerCrc, samplerFlags); } + public void UpdateMaterialPreview() + { + SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); + foreach (var constant in Mtrl.ShaderPackage.Constants) + { + var values = Mtrl.GetConstantValues(constant); + if (values != null) + SetMaterialParameter(constant.Id, 0, values); + } + foreach (var sampler in Mtrl.ShaderPackage.Samplers) + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + public void HighlightColorSetRow(int rowIdx) { var oldRowIdx = HighlightedColorSetRow; @@ -402,7 +566,7 @@ public partial class ModEditWindow UpdateColorSetRowPreview(rowIdx); } - public unsafe void UpdateColorSetRowPreview(int rowIdx) + public void UpdateColorSetRowPreview(int rowIdx) { if (ColorSetPreviewers.Count == 0) return; @@ -415,12 +579,12 @@ public partial class ModEditWindow var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); var row = colorSet.Rows[rowIdx]; - if (maybeColorDyeSet.HasValue) + if (maybeColorDyeSet.HasValue && UseColorDyeSet) { var stm = _edit._stainService.StmFile; var dye = maybeColorDyeSet.Value.Rows[rowIdx]; if (stm.TryGetValue(dye.Template, (StainId)_edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) - ApplyDye(ref row, dye, dyes); + row.ApplyDyeTemplate(dye, dyes); } if (HighlightedColorSetRow == rowIdx) @@ -428,13 +592,12 @@ public partial class ModEditWindow foreach (var previewer in ColorSetPreviewers) { - fixed (Half* pDest = previewer.ColorSet) - Buffer.MemoryCopy(&row, pDest + LiveColorSetPreviewer.TextureWidth * 4 * rowIdx, LiveColorSetPreviewer.TextureWidth * 4 * sizeof(Half), sizeof(MtrlFile.ColorSet.Row)); + row.AsHalves().CopyTo(previewer.ColorSet.AsSpan().Slice(LiveColorSetPreviewer.TextureWidth * 4 * rowIdx, LiveColorSetPreviewer.TextureWidth * 4)); previewer.ScheduleUpdate(); } } - public unsafe void UpdateColorSetPreview() + public void UpdateColorSetPreview() { if (ColorSetPreviewers.Count == 0) return; @@ -447,7 +610,7 @@ public partial class ModEditWindow var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); var rows = colorSet.Rows; - if (maybeColorDyeSet.HasValue) + if (maybeColorDyeSet.HasValue && UseColorDyeSet) { var stm = _edit._stainService.StmFile; var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; @@ -457,7 +620,7 @@ public partial class ModEditWindow ref var row = ref rows[i]; var dye = colorDyeSet.Rows[i]; if (stm.TryGetValue(dye.Template, stainId, out var dyes)) - ApplyDye(ref row, dye, dyes); + row.ApplyDyeTemplate(dye, dyes); } } @@ -466,26 +629,11 @@ public partial class ModEditWindow foreach (var previewer in ColorSetPreviewers) { - fixed (Half* pDest = previewer.ColorSet) - Buffer.MemoryCopy(&rows, pDest, LiveColorSetPreviewer.TextureLength * sizeof(Half), sizeof(MtrlFile.ColorSet.RowArray)); + rows.AsHalves().CopyTo(previewer.ColorSet); previewer.ScheduleUpdate(); } } - private static void ApplyDye(ref MtrlFile.ColorSet.Row row, MtrlFile.ColorDyeSet.Row dye, StmFile.DyePack dyes) - { - if (dye.Diffuse) - row.Diffuse = dyes.Diffuse; - if (dye.Specular) - row.Specular = dyes.Specular; - if (dye.SpecularStrength) - row.SpecularStrength = dyes.SpecularPower; - if (dye.Emissive) - row.Emissive = dyes.Emissive; - if (dye.Gloss) - row.GlossStrength = dyes.Gloss; - } - private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, int time) { var level = Math.Sin(time * Math.PI / 16) * 0.5 + 0.5; @@ -498,18 +646,19 @@ public partial class ModEditWindow public void Update() { - UpdateTextureLabels(); - UpdateShaderKeyLabels(); - UpdateConstantLabels(); - UpdateSamplers(); + UpdateShaders(); + UpdateTextures(); + UpdateConstants(); } public MtrlTab( ModEditWindow edit, MtrlFile file, string filePath, bool writable ) { - _edit = edit; - Mtrl = file; - FilePath = filePath; - Writable = writable; + _edit = edit; + Mtrl = file; + FilePath = filePath; + Writable = writable; + UseColorDyeSet = file.ColorDyeSets.Length > 0; + AssociatedBaseDevkit = TryLoadShpkDevkit( "_base", out LoadedBaseDevkitPathName ); LoadShpk( FindAssociatedShpk( out _, out _ ) ); if (writable) BindToMaterialInstances(); @@ -532,9 +681,96 @@ public partial class ModEditWindow } public bool Valid - => Mtrl.Valid; + => ShadersKnown && Mtrl.Valid; public byte[] Write() - => Mtrl.Write(); + { + var output = Mtrl.Clone(); + output.GarbageCollect(AssociatedShpk, SamplerIds, UseColorDyeSet); + + return output.Write(); + } + + private sealed class DevkitShaderKeyValue + { + public string Label = string.Empty; + public string Description = string.Empty; + } + + private sealed class DevkitShaderKey + { + public string Label = string.Empty; + public string Description = string.Empty; + public Dictionary Values = new(); + } + + private sealed class DevkitSampler + { + public string Label = string.Empty; + public string Description = string.Empty; + public string DefaultTexture = string.Empty; + } + + private enum DevkitConstantType + { + Hidden = -1, + Float = 0, + Integer = 1, + Color = 2, + Enum = 3, + } + + private sealed class DevkitConstantValue + { + public string Label = string.Empty; + public string Description = string.Empty; + public float Value = 0.0f; + } + + private sealed class DevkitConstant + { + public uint Offset = 0; + public uint? Length = null; + public string Group = string.Empty; + public string Label = string.Empty; + public string Description = string.Empty; + public DevkitConstantType Type = DevkitConstantType.Float; + + public float? Minimum = null; + public float? Maximum = null; + public float? Speed = null; + public float RelativeSpeed = 0.0f; + public float Factor = 1.0f; + public float Bias = 0.0f; + public byte Precision = 3; + public string Unit = string.Empty; + + public bool SquaredRgb = false; + public bool Clamped = false; + + public DevkitConstantValue[] Values = Array.Empty(); + + public IConstantEditor? CreateEditor() + { + switch (Type) + { + case DevkitConstantType.Hidden: + return null; + case DevkitConstantType.Float: + return new FloatConstantEditor(Minimum, Maximum, Speed ?? 0.1f, RelativeSpeed, Factor, Bias, Precision, Unit); + case DevkitConstantType.Integer: + return new IntConstantEditor(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, Factor, Bias, Unit); + case DevkitConstantType.Color: + return new ColorConstantEditor(SquaredRgb, Clamped); + case DevkitConstantType.Enum: + return new EnumConstantEditor(Array.ConvertAll(Values, value => (value.Label, value.Value, value.Description))); + default: + return FloatConstantEditor.Default; + } + } + + private int? ToInteger(float? value) + => value.HasValue ? (int)Math.Clamp(MathF.Round(value.Value), int.MinValue, int.MaxValue) : null; + } } -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 2d1859bd..d3bc826a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; @@ -7,6 +8,7 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiFileDialog; using ImGuiNET; using Lumina.Data.Parsing; +using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Raii; using Penumbra.GameData; @@ -19,20 +21,92 @@ public partial class ModEditWindow { private readonly FileDialogService _fileDialog; - private bool DrawPackageNameInput(MtrlTab tab, bool disabled) + // strings path/to/the.exe | grep --fixed-strings '.shpk' | sort -u | sed -e 's#^shader/sm5/shpk/##' + // Apricot shader packages are unlisted because + // 1. they cause performance/memory issues when calculating the effective shader set + // 2. they probably aren't intended for use with materials anyway + private static readonly IReadOnlyList StandardShaderPackages = new string[] { - var ret = false; - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); - if (ImGui.InputText("Shader Package Name", ref tab.Mtrl.ShaderPackage.Name, 63, - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None)) + "3dui.shpk", + // "apricot_decal_dummy.shpk", + // "apricot_decal_ring.shpk", + // "apricot_decal.shpk", + // "apricot_lightmodel.shpk", + // "apricot_model_dummy.shpk", + // "apricot_model_morph.shpk", + // "apricot_model.shpk", + // "apricot_powder_dummy.shpk", + // "apricot_powder.shpk", + // "apricot_shape_dummy.shpk", + // "apricot_shape.shpk", + "bgcolorchange.shpk", + "bgcrestchange.shpk", + "bgdecal.shpk", + "bg.shpk", + "bguvscroll.shpk", + "channeling.shpk", + "characterglass.shpk", + "character.shpk", + "cloud.shpk", + "createviewposition.shpk", + "crystal.shpk", + "directionallighting.shpk", + "directionalshadow.shpk", + "grass.shpk", + "hair.shpk", + "iris.shpk", + "lightshaft.shpk", + "linelighting.shpk", + "planelighting.shpk", + "pointlighting.shpk", + "river.shpk", + "shadowmask.shpk", + "skin.shpk", + "spotlighting.shpk", + "verticalfog.shpk", + "water.shpk", + "weather.shpk", + }; + + private enum TextureAddressMode : uint + { + Wrap = 0, + Mirror = 1, + Clamp = 2, + Border = 3, + } + + private static readonly IReadOnlyList TextureAddressModeTooltips = new string[] + { + "Tile the texture at every UV integer junction.\n\nFor example, for U values between 0 and 3, the texture is repeated three times.", + "Flip the texture at every UV integer junction.\n\nFor U values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is mirrored; between 2 and 3, the texture is normal again; and so on.", + "Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.", + "Texture coordinates outside the range [0.0, 1.0] are set to the border color (generally black).", + }; + + private static bool DrawPackageNameInput(MtrlTab tab, bool disabled) + { + if (disabled) { - ret = true; - tab.AssociatedShpk = null; - tab.LoadedShpkPath = FullPath.Empty; + ImGui.TextUnformatted("Shader Package: " + tab.Mtrl.ShaderPackage.Name); + return false; } - if (ImGui.IsItemDeactivatedAfterEdit()) - tab.LoadShpk(tab.FindAssociatedShpk(out _, out _)); + var ret = false; + ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); + using var c = ImRaii.Combo("Shader Package", tab.Mtrl.ShaderPackage.Name); + if (c) + foreach (var value in tab.GetShpkNames()) + { + if (ImGui.Selectable(value, value == tab.Mtrl.ShaderPackage.Name)) + { + tab.Mtrl.ShaderPackage.Name = value; + ret = true; + tab.AssociatedShpk = null; + tab.LoadedShpkPath = FullPath.Empty; + tab.LoadShpk(tab.FindAssociatedShpk(out _, out _)); + } + } return ret; } @@ -41,8 +115,8 @@ public partial class ModEditWindow { var ret = false; var shpkFlags = (int)tab.Mtrl.ShaderPackage.Flags; - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); - if (ImGui.InputInt("Shader Package Flags", ref shpkFlags, 0, 0, + ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); + if (ImGui.InputInt("Shader Flags", ref shpkFlags, 0, 0, ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) { tab.Mtrl.ShaderPackage.Flags = (uint)shpkFlags; @@ -62,6 +136,12 @@ public partial class ModEditWindow var text = tab.AssociatedShpk == null ? "Associated .shpk file: None" : $"Associated .shpk file: {tab.LoadedShpkPathName}"; + var devkitText = tab.AssociatedShpkDevkit == null + ? "Associated dev-kit file: None" + : $"Associated dev-kit file: {tab.LoadedShpkDevkitPathName}"; + var baseDevkitText = tab.AssociatedBaseDevkit == null + ? "Base dev-kit file: None" + : $"Base dev-kit file: {tab.LoadedBaseDevkitPathName}"; ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); @@ -70,6 +150,16 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip("Click to copy file path to clipboard."); + if (ImGui.Selectable(devkitText)) + ImGui.SetClipboardText(tab.LoadedShpkDevkitPathName); + + ImGuiUtil.HoverTooltip("Click to copy file path to clipboard."); + + if (ImGui.Selectable(baseDevkitText)) + ImGui.SetClipboardText(tab.LoadedBaseDevkitPathName); + + ImGuiUtil.HoverTooltip("Click to copy file path to clipboard."); + if (ImGui.Button("Associate Custom .shpk File")) _fileDialog.OpenFilePicker("Associate Custom .shpk File...", ".shpk", (success, name) => { @@ -94,94 +184,50 @@ public partial class ModEditWindow ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); } - - private static bool DrawShaderKey(MtrlTab tab, bool disabled, ref int idx) - { - var ret = false; - using var t2 = ImRaii.TreeNode(tab.ShaderKeyLabels[idx], disabled ? ImGuiTreeNodeFlags.Leaf : 0); - if (!t2 || disabled) - return ret; - - var key = tab.Mtrl.ShaderPackage.ShaderKeys[idx]; - var shpkKey = tab.AssociatedShpk?.GetMaterialKeyById(key.Category); - if (shpkKey.HasValue) - { - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); - using var c = ImRaii.Combo("Value", $"0x{key.Value:X8}"); - if (c) - foreach (var value in shpkKey.Value.Values) - { - if (ImGui.Selectable($"0x{value:X8}", value == key.Value)) - { - tab.Mtrl.ShaderPackage.ShaderKeys[idx].Value = value; - ret = true; - tab.UpdateShaderKeyLabels(); - } - } - } - - if (ImGui.Button("Remove Key")) - { - tab.Mtrl.ShaderPackage.ShaderKeys = tab.Mtrl.ShaderPackage.ShaderKeys.RemoveItems(idx--); - ret = true; - tab.UpdateShaderKeyLabels(); - } - - return ret; - } - - private static bool DrawNewShaderKey(MtrlTab tab) - { - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); - var ret = false; - using (var c = ImRaii.Combo("##NewConstantId", $"ID: 0x{tab.NewKeyId:X8}")) - { - if (c) - foreach (var idx in tab.MissingShaderKeyIndices) - { - var key = tab.AssociatedShpk!.MaterialKeys[idx]; - - if (ImGui.Selectable($"ID: 0x{key.Id:X8}", key.Id == tab.NewKeyId)) - { - tab.NewKeyDefault = key.DefaultValue; - tab.NewKeyId = key.Id; - ret = true; - tab.UpdateShaderKeyLabels(); - } - } - } - - ImGui.SameLine(); - if (ImGui.Button("Add Key")) - { - tab.Mtrl.ShaderPackage.ShaderKeys = tab.Mtrl.ShaderPackage.ShaderKeys.AddItem(new ShaderKey - { - Category = tab.NewKeyId, - Value = tab.NewKeyDefault, - }); - ret = true; - tab.UpdateShaderKeyLabels(); - } - - return ret; - } - private static bool DrawMaterialShaderKeys(MtrlTab tab, bool disabled) { - if (tab.Mtrl.ShaderPackage.ShaderKeys.Length <= 0 - && (disabled || tab.AssociatedShpk == null || tab.AssociatedShpk.MaterialKeys.Length <= 0)) - return false; - - using var t = ImRaii.TreeNode("Shader Keys"); - if (!t) + if (tab.ShaderKeys.Count == 0) return false; var ret = false; - for (var idx = 0; idx < tab.Mtrl.ShaderPackage.ShaderKeys.Length; ++idx) - ret |= DrawShaderKey(tab, disabled, ref idx); + foreach (var (label, index, description, monoFont, values) in tab.ShaderKeys) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); + ref var key = ref tab.Mtrl.ShaderPackage.ShaderKeys[index]; + var shpkKey = tab.AssociatedShpk?.GetMaterialKeyById(key.Category); + var currentValue = key.Value; + var (currentLabel, _, currentDescription) = values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); + if (!disabled && shpkKey.HasValue) + { + ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); + using (var c = ImRaii.Combo($"##{key.Category:X8}", currentLabel)) + { + if (c) + foreach (var (valueLabel, value, valueDescription) in values) + { + if (ImGui.Selectable(valueLabel, value == currentValue)) + { + key.Value = value; + ret = true; + tab.Update(); + } - if (!disabled && tab.AssociatedShpk != null && tab.MissingShaderKeyIndices.Count != 0) - ret |= DrawNewShaderKey(tab); + if (valueDescription.Length > 0) + ImGuiUtil.SelectableHelpMarker(valueDescription); + } + } + ImGui.SameLine(); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); + } + else if (description.Length > 0 || currentDescription.Length > 0) + ImGuiUtil.LabeledHelpMarker($"{label}: {currentLabel}", + description + ((description.Length > 0 && currentDescription.Length > 0) ? "\n\n" : string.Empty) + currentDescription); + else + ImGui.TextUnformatted($"{label}: {currentLabel}"); + } return ret; } @@ -191,162 +237,64 @@ public partial class ModEditWindow if (tab.AssociatedShpk == null) return; - ImRaii.TreeNode(tab.VertexShaders, ImGuiTreeNodeFlags.Leaf).Dispose(); - ImRaii.TreeNode(tab.PixelShaders, ImGuiTreeNodeFlags.Leaf).Dispose(); - } + ImRaii.TreeNode(tab.VertexShadersString, ImGuiTreeNodeFlags.Leaf).Dispose(); + ImRaii.TreeNode(tab.PixelShadersString, ImGuiTreeNodeFlags.Leaf).Dispose(); - - private static bool DrawMaterialConstantValues(MtrlTab tab, bool disabled, ref int idx) - { - var (name, componentOnly, paramValueOffset) = tab.MaterialConstants[idx]; - using var font = ImRaii.PushFont(UiBuilder.MonoFont); - using var t2 = ImRaii.TreeNode(name); - if (!t2) - return false; - - font.Dispose(); - - var constant = tab.Mtrl.ShaderPackage.Constants[idx]; - var ret = false; - var values = tab.Mtrl.GetConstantValues(constant); - if (values.Length > 0) + if (tab.ShaderComment.Length > 0) { - var valueOffset = constant.ByteOffset >> 2; - - for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) - { - var paramName = MaterialParamName(componentOnly, paramValueOffset + valueIdx) ?? $"#{valueIdx}"; - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); - if (ImGui.InputFloat($"{paramName} (at 0x{(valueOffset + valueIdx) << 2:X4})", ref values[valueIdx], 0.0f, 0.0f, "%.3f", - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None)) - { - ret = true; - tab.UpdateConstantLabels(); - tab.SetMaterialParameter(constant.Id, valueIdx, values.Slice(valueIdx, 1)); - } - } + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ImGui.TextUnformatted(tab.ShaderComment); } - else - { - ImRaii.TreeNode($"Offset: 0x{constant.ByteOffset:X4}", ImGuiTreeNodeFlags.Leaf).Dispose(); - ImRaii.TreeNode($"Size: 0x{constant.ByteSize:X4}", ImGuiTreeNodeFlags.Leaf).Dispose(); - } - - if (!disabled - && !tab.HasMalformedMaterialConstants - && tab.OrphanedMaterialValues.Count == 0 - && tab.AliasedMaterialValueCount == 0 - && ImGui.Button("Remove Constant")) - { - tab.Mtrl.ShaderPackage.ShaderValues = - tab.Mtrl.ShaderPackage.ShaderValues.RemoveItems(constant.ByteOffset >> 2, constant.ByteSize >> 2); - tab.Mtrl.ShaderPackage.Constants = tab.Mtrl.ShaderPackage.Constants.RemoveItems(idx--); - for (var i = 0; i < tab.Mtrl.ShaderPackage.Constants.Length; ++i) - { - if (tab.Mtrl.ShaderPackage.Constants[i].ByteOffset >= constant.ByteOffset) - tab.Mtrl.ShaderPackage.Constants[i].ByteOffset -= constant.ByteSize; - } - - ret = true; - tab.UpdateConstantLabels(); - tab.SetMaterialParameter(constant.Id, 0, new float[constant.ByteSize >> 2]); - } - - return ret; - } - - private static bool DrawMaterialOrphans(MtrlTab tab, bool disabled) - { - using var t2 = ImRaii.TreeNode($"Orphan Values ({tab.OrphanedMaterialValues.Count})"); - if (!t2) - return false; - - var ret = false; - foreach (var idx in tab.OrphanedMaterialValues) - { - ImGui.SetNextItemWidth(ImGui.GetFontSize() * 10.0f); - if (ImGui.InputFloat($"#{idx} (at 0x{idx << 2:X4})", - ref tab.Mtrl.ShaderPackage.ShaderValues[idx], 0.0f, 0.0f, "%.3f", - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None)) - { - ret = true; - tab.UpdateConstantLabels(); - } - } - - return ret; - } - - private static bool DrawNewMaterialParam(MtrlTab tab) - { - ImGui.SetNextItemWidth(UiHelpers.Scale * 450.0f); - using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) - { - using var c = ImRaii.Combo("##NewConstantId", tab.MissingMaterialConstants[tab.NewConstantIdx].Name); - if (c) - foreach (var (constant, idx) in tab.MissingMaterialConstants.WithIndex()) - { - if (ImGui.Selectable(constant.Name, constant.Id == tab.NewConstantId)) - { - tab.NewConstantIdx = idx; - tab.NewConstantId = constant.Id; - } - } - } - - ImGui.SameLine(); - if (ImGui.Button("Add Constant")) - { - var (_, _, byteSize) = tab.MissingMaterialConstants[tab.NewConstantIdx]; - tab.Mtrl.ShaderPackage.Constants = tab.Mtrl.ShaderPackage.Constants.AddItem(new MtrlFile.Constant - { - Id = tab.NewConstantId, - ByteOffset = (ushort)(tab.Mtrl.ShaderPackage.ShaderValues.Length << 2), - ByteSize = byteSize, - }); - tab.Mtrl.ShaderPackage.ShaderValues = tab.Mtrl.ShaderPackage.ShaderValues.AddItem(0.0f, byteSize >> 2); - tab.UpdateConstantLabels(); - return true; - } - - return false; } private static bool DrawMaterialConstants(MtrlTab tab, bool disabled) { - if (tab.Mtrl.ShaderPackage.Constants.Length == 0 - && tab.Mtrl.ShaderPackage.ShaderValues.Length == 0 - && (disabled || tab.AssociatedShpk == null || tab.AssociatedShpk.MaterialParams.Length == 0)) + if (tab.Constants.Count == 0) return false; - using var font = ImRaii.PushFont(UiBuilder.MonoFont); - using var t = ImRaii.TreeNode(tab.MaterialConstantLabel); - if (!t) + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + if (!ImGui.CollapsingHeader("Material Constants")) return false; - font.Dispose(); + using var _ = ImRaii.PushId("MaterialConstants"); + var ret = false; - for (var idx = 0; idx < tab.Mtrl.ShaderPackage.Constants.Length; ++idx) - ret |= DrawMaterialConstantValues(tab, disabled, ref idx); + foreach (var (header, group) in tab.Constants) + { + using var t = ImRaii.TreeNode(header, ImGuiTreeNodeFlags.DefaultOpen); + if (!t) + continue; - if (tab.OrphanedMaterialValues.Count > 0) - ret |= DrawMaterialOrphans(tab, disabled); - else if (!disabled && !tab.HasMalformedMaterialConstants && tab.MissingMaterialConstants.Count > 0) - ret |= DrawNewMaterialParam(tab); + foreach (var (label, constantIndex, slice, description, monoFont, editor) in group) + { + var constant = tab.Mtrl.ShaderPackage.Constants[constantIndex]; + var buffer = tab.Mtrl.GetConstantValues(constant); + if (buffer.Length > 0) + { + using var id = ImRaii.PushId($"##{constant.Id:X8}:{slice.Start}"); + if (editor.Draw(buffer[slice], disabled, 250.0f)) + { + ret = true; + tab.SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); + } + ImGui.SameLine(); + using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); + } + } + } return ret; } - private static bool DrawMaterialSampler(MtrlTab tab, bool disabled, ref int idx) + private static bool DrawMaterialSampler(MtrlTab tab, bool disabled, int textureIdx, int samplerIdx) { - var (label, filename, samplerCrc) = tab.Samplers[idx]; - using var tree = ImRaii.TreeNode(label); - if (!tree) - return false; - - ImRaii.TreeNode(filename, ImGuiTreeNodeFlags.Leaf).Dispose(); - var ret = false; - var sampler = tab.Mtrl.ShaderPackage.Samplers[idx]; + var ret = false; + ref var texture = ref tab.Mtrl.Textures[textureIdx]; + ref var sampler = ref tab.Mtrl.ShaderPackage.Samplers[samplerIdx]; // FIXME this probably doesn't belong here static unsafe bool InputHexUInt16(string label, ref ushort v, ImGuiInputTextFlags flags) @@ -357,128 +305,123 @@ public partial class ModEditWindow } } - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); - if (InputHexUInt16("Texture Flags", ref tab.Mtrl.Textures[sampler.TextureIndex].Flags, + static bool ComboTextureAddressMode(string label, ref uint samplerFlags, int bitOffset) + { + var current = (TextureAddressMode)((samplerFlags >> bitOffset) & 0x3u); + using var c = ImRaii.Combo(label, current.ToString()); + if (!c) + return false; + + var ret = false; + foreach (var value in Enum.GetValues()) + { + if (ImGui.Selectable(value.ToString(), value == current)) + { + samplerFlags = (samplerFlags & ~(0x3u << bitOffset)) | ((uint)value << bitOffset); + ret = true; + } + + ImGuiUtil.SelectableHelpMarker(TextureAddressModeTooltips[(int)value]); + } + return ret; + } + + var dx11 = texture.DX11; + if (ImGui.Checkbox("Prepend -- to the file name on DirectX 11", ref dx11)) + { + texture.DX11 = dx11; + ret = true; + } + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ComboTextureAddressMode("##UAddressMode", ref sampler.Flags, 2)) + { + ret = true; + tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker("U Address Mode", "Method to use for resolving a U texture coordinate that is outside the 0 to 1 range."); + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ComboTextureAddressMode("##VAddressMode", ref sampler.Flags, 0)) + { + ret = true; + tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker("V Address Mode", "Method to use for resolving a V texture coordinate that is outside the 0 to 1 range."); + + var lodBias = ((int)(sampler.Flags << 12) >> 22) / 64.0f; + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImGui.DragFloat("##LoDBias", ref lodBias, 0.1f, -8.0f, 7.984375f)) + { + sampler.Flags = (uint)((sampler.Flags & ~0x000FFC00) | (uint)((int)Math.Round(Math.Clamp(lodBias, -8.0f, 7.984375f) * 64.0f) & 0x3FF) << 10); + ret = true; + tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker("Level of Detail Bias", "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); + + var minLod = (int)((sampler.Flags >> 20) & 0xF); + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImGui.DragInt("##MinLoD", ref minLod, 0.1f, 0, 15)) + { + sampler.Flags = (uint)((sampler.Flags & ~0x00F00000) | ((uint)Math.Clamp(minLod, 0, 15) << 20)); + ret = true; + tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker("Minimum Level of Detail", "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); + + using var t = ImRaii.TreeNode("Advanced Settings"); + if (!t) + return ret; + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (InputHexUInt16("Texture Flags", ref texture.Flags, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None)) ret = true; var samplerFlags = (int)sampler.Flags; - ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); if (ImGui.InputInt("Sampler Flags", ref samplerFlags, 0, 0, ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) { - tab.Mtrl.ShaderPackage.Samplers[idx].Flags = (uint)samplerFlags; - ret = true; - tab.SetSamplerFlags(samplerCrc, (uint)samplerFlags); - } - - if (!disabled - && tab.OrphanedSamplers.Count == 0 - && tab.AliasedSamplerCount == 0 - && ImGui.Button("Remove Sampler")) - { - tab.Mtrl.Textures = tab.Mtrl.Textures.RemoveItems(sampler.TextureIndex); - tab.Mtrl.ShaderPackage.Samplers = tab.Mtrl.ShaderPackage.Samplers.RemoveItems(idx--); - for (var i = 0; i < tab.Mtrl.ShaderPackage.Samplers.Length; ++i) - { - if (tab.Mtrl.ShaderPackage.Samplers[i].TextureIndex >= sampler.TextureIndex) - --tab.Mtrl.ShaderPackage.Samplers[i].TextureIndex; - } - - ret = true; - tab.UpdateSamplers(); - tab.UpdateTextureLabels(); + sampler.Flags = (uint)samplerFlags; + ret = true; + tab.SetSamplerFlags(sampler.SamplerId, (uint)samplerFlags); } return ret; } - private static bool DrawMaterialNewSampler(MtrlTab tab) - { - var (name, id) = tab.MissingSamplers[tab.NewSamplerIdx]; - ImGui.SetNextItemWidth(UiHelpers.Scale * 450.0f); - using (var c = ImRaii.Combo("##NewSamplerId", $"{name} (ID: 0x{id:X8})")) - { - if (c) - foreach (var (sampler, idx) in tab.MissingSamplers.WithIndex()) - { - if (ImGui.Selectable($"{sampler.Name} (ID: 0x{sampler.Id:X8})", sampler.Id == tab.NewSamplerId)) - { - tab.NewSamplerIdx = idx; - tab.NewSamplerId = sampler.Id; - } - } - } - - ImGui.SameLine(); - if (!ImGui.Button("Add Sampler")) - return false; - - var newSamplerId = tab.NewSamplerId; - tab.Mtrl.ShaderPackage.Samplers = tab.Mtrl.ShaderPackage.Samplers.AddItem(new Sampler - { - SamplerId = newSamplerId, - TextureIndex = (byte)tab.Mtrl.Textures.Length, - Flags = 0, - }); - tab.Mtrl.Textures = tab.Mtrl.Textures.AddItem(new MtrlFile.Texture - { - Path = string.Empty, - Flags = 0, - }); - tab.UpdateSamplers(); - tab.UpdateTextureLabels(); - tab.SetSamplerFlags(newSamplerId, 0); - return true; - } - - private static bool DrawMaterialSamplers(MtrlTab tab, bool disabled) - { - if (tab.Mtrl.ShaderPackage.Samplers.Length == 0 - && tab.Mtrl.Textures.Length == 0 - && (disabled || (tab.AssociatedShpk?.Samplers.All(sampler => sampler.Slot != 2) ?? false))) - return false; - - using var t = ImRaii.TreeNode("Samplers"); - if (!t) - return false; - - var ret = false; - for (var idx = 0; idx < tab.Mtrl.ShaderPackage.Samplers.Length; ++idx) - ret |= DrawMaterialSampler(tab, disabled, ref idx); - - if (tab.OrphanedSamplers.Count > 0) - { - using var t2 = ImRaii.TreeNode($"Orphan Textures ({tab.OrphanedSamplers.Count})"); - if (t2) - foreach (var idx in tab.OrphanedSamplers) - { - ImRaii.TreeNode($"#{idx}: {Path.GetFileName(tab.Mtrl.Textures[idx].Path)} - {tab.Mtrl.Textures[idx].Flags:X4}", - ImGuiTreeNodeFlags.Leaf) - .Dispose(); - } - } - else if (!disabled && tab.MissingSamplers.Count > 0 && tab.AliasedSamplerCount == 0 && tab.Mtrl.Textures.Length < 255) - { - ret |= DrawMaterialNewSampler(tab); - } - - return ret; - } - - private bool DrawMaterialShaderResources(MtrlTab tab, bool disabled) + private bool DrawMaterialShader(MtrlTab tab, bool disabled) { var ret = false; - if (!ImGui.CollapsingHeader("Advanced Shader Resources")) - return ret; + if (ImGui.CollapsingHeader(tab.ShaderHeader)) + { + ret |= DrawPackageNameInput(tab, disabled); + ret |= DrawShaderFlagsInput(tab, disabled); + DrawCustomAssociations(tab); + ret |= DrawMaterialShaderKeys(tab, disabled); + DrawMaterialShaders(tab); + } + + if (tab.AssociatedShpkDevkit == null) + { + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + GC.KeepAlive(tab); + + var textColor = ImGui.GetColorU32(ImGuiCol.Text); + var textColorWarning = (textColor & 0xFF000000u) | ((textColor & 0x00FEFEFE) >> 1) | (tab.AssociatedShpk == null ? 0x80u : 0x8080u); // Half red or yellow + + using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); + + ImGui.TextUnformatted(tab.AssociatedShpk == null + ? "Unable to find a suitable .shpk file for cross-references. Some functionality will be missing." + : "No dev-kit file found for this material's shaders. Please install one for optimal editing experience, such as actual constant names instead of hexadecimal identifiers."); + } - ret |= DrawPackageNameInput(tab, disabled); - ret |= DrawShaderFlagsInput(tab, disabled); - DrawCustomAssociations(tab); - ret |= DrawMaterialShaderKeys(tab, disabled); - DrawMaterialShaders(tab); - ret |= DrawMaterialConstants(tab, disabled); - ret |= DrawMaterialSamplers(tab, disabled); return ret; } @@ -500,26 +443,25 @@ public partial class ModEditWindow _ => null, }; } + private static string VectorSwizzle(int firstComponent, int lastComponent) + => (firstComponent, lastComponent) switch + { + (0, 4) => " ", + (0, 0) => ".x ", + (0, 1) => ".xy ", + (0, 2) => ".xyz ", + (0, 3) => " ", + (1, 1) => ".y ", + (1, 2) => ".yz ", + (1, 3) => ".yzw ", + (2, 2) => ".z ", + (2, 3) => ".zw ", + (3, 3) => ".w ", + _ => string.Empty, + }; private static (string? Name, bool ComponentOnly) MaterialParamRangeName(string prefix, int valueOffset, int valueLength) { - static string VectorSwizzle(int firstComponent, int lastComponent) - => (firstComponent, lastComponent) switch - { - (0, 4) => " ", - (0, 0) => ".x ", - (0, 1) => ".xy ", - (0, 2) => ".xyz ", - (0, 3) => " ", - (1, 1) => ".y ", - (1, 2) => ".yz ", - (1, 3) => ".yzw ", - (2, 2) => ".z ", - (2, 3) => ".zw ", - (3, 3) => ".w ", - _ => string.Empty, - }; - if (valueLength == 0 || valueOffset < 0) return (null, false); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index e4de66a8..b89bab01 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -18,16 +18,14 @@ public partial class ModEditWindow DrawMaterialLivePreviewRebind( tab, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - var ret = DrawMaterialTextureChange( tab, disabled ); + var ret = DrawBackFaceAndTransparency( tab, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawBackFaceAndTransparency( tab, disabled ); + ret |= DrawMaterialShader( tab, disabled ); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); + ret |= DrawMaterialTextureChange( tab, disabled ); ret |= DrawMaterialColorSetChange( tab, disabled ); - - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawMaterialShaderResources( tab, disabled ); + ret |= DrawMaterialConstants( tab, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); DrawOtherMaterialDetails( tab.Mtrl, disabled ); @@ -40,35 +38,87 @@ public partial class ModEditWindow if (disabled) return; - if (ImGui.Button("Reload live-preview")) + if (ImGui.Button("Reload live preview")) tab.BindToMaterialInstances(); + + if (tab.MaterialPreviewers.Count == 0 && tab.ColorSetPreviewers.Count == 0) + { + ImGui.SameLine(); + + var textColor = ImGui.GetColorU32(ImGuiCol.Text); + var textColorWarning = (textColor & 0xFF000000u) | ((textColor & 0x00FEFEFE) >> 1) | 0x80u; // Half red + + using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); + + ImGui.TextUnformatted("The current material has not been found on your character. Please check the Import from Screen tab for more information."); + } } private static bool DrawMaterialTextureChange( MtrlTab tab, bool disabled ) { - var ret = false; - using var table = ImRaii.Table( "##Textures", 2 ); - ImGui.TableSetupColumn( "Path", ImGuiTableColumnFlags.WidthStretch ); - ImGui.TableSetupColumn( "Name", ImGuiTableColumnFlags.WidthFixed, tab.TextureLabelWidth * UiHelpers.Scale ); - for( var i = 0; i < tab.Mtrl.Textures.Length; ++i ) + if( tab.Textures.Count == 0 ) { - using var _ = ImRaii.PushId( i ); - var tmp = tab.Mtrl.Textures[ i ].Path; + return false; + } + + ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); + if( !ImGui.CollapsingHeader( "Textures and Samplers", ImGuiTreeNodeFlags.DefaultOpen ) ) + { + return false; + } + + var frameHeight = ImGui.GetFrameHeight(); + var ret = false; + using var table = ImRaii.Table( "##Textures", 3 ); + + ImGui.TableSetupColumn( string.Empty, ImGuiTableColumnFlags.WidthFixed, frameHeight ); + ImGui.TableSetupColumn( "Path" , ImGuiTableColumnFlags.WidthStretch ); + ImGui.TableSetupColumn( "Name" , ImGuiTableColumnFlags.WidthFixed, tab.TextureLabelWidth * UiHelpers.Scale ); + for( var i = 0; i < tab.Textures.Count; ++i ) + { + var (label, textureI, samplerI, description, monoFont) = tab.Textures[i]; + + using var _ = ImRaii.PushId( samplerI ); + var tmp = tab.Mtrl.Textures[ textureI ].Path; + var unfolded = tab.UnfoldedTextures.Contains( samplerI ); + ImGui.TableNextColumn(); + if( ImGuiUtil.DrawDisabledButton( ( unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight ).ToIconString(), new Vector2( frameHeight ), + "Settings for this texture and the associated sampler", false, true ) ) + { + unfolded = !unfolded; + if( unfolded ) + tab.UnfoldedTextures.Add( samplerI ); + else + tab.UnfoldedTextures.Remove( samplerI ); + } ImGui.TableNextColumn(); ImGui.SetNextItemWidth( ImGui.GetContentRegionAvail().X ); if( ImGui.InputText( string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None ) && tmp.Length > 0 - && tmp != tab.Mtrl.Textures[ i ].Path ) + && tmp != tab.Mtrl.Textures[ textureI ].Path ) { - ret = true; - tab.Mtrl.Textures[ i ].Path = tmp; + ret = true; + tab.Mtrl.Textures[ textureI ].Path = tmp; } ImGui.TableNextColumn(); - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted( tab.TextureLabels[ i ] ); + using( var font = ImRaii.PushFont( UiBuilder.MonoFont, monoFont ) ) + { + ImGui.AlignTextToFramePadding(); + if( description.Length > 0 ) + ImGuiUtil.LabeledHelpMarker( label, description ); + else + ImGui.TextUnformatted( label ); + } + + if( unfolded ) + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ret |= DrawMaterialSampler( tab, disabled, textureI, samplerI ); + ImGui.TableNextColumn(); + } } return ret; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 4e8a4f45..1b159efc 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -14,7 +14,6 @@ using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.String; -using Penumbra.UI.AdvancedWindow; using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.UI.AdvancedWindow; @@ -40,7 +39,13 @@ public partial class ModEditWindow ret |= DrawShaderPackageMaterialParamLayout( file, disabled ); ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawOtherShaderPackageDetails( file, disabled ); + ret |= DrawShaderPackageResources( file, disabled ); + + ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); + DrawShaderPackageSelection( file ); + + ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); + DrawOtherShaderPackageDetails( file ); file.FileDialog.Draw(); @@ -50,7 +55,18 @@ public partial class ModEditWindow } private static void DrawShaderPackageSummary( ShpkTab tab ) - => ImGui.TextUnformatted( tab.Header ); + { + ImGui.TextUnformatted( tab.Header ); + if( !tab.Shpk.Disassembled ) + { + var textColor = ImGui.GetColorU32( ImGuiCol.Text ); + var textColorWarning = ( textColor & 0xFF000000u ) | ( ( textColor & 0x00FEFEFE ) >> 1 ) | 0x80u; // Half red + + using var c = ImRaii.PushColor( ImGuiCol.Text, textColorWarning ); + + ImGui.TextUnformatted( "Your system doesn't support disassembling shaders. Some functionality will be missing." ); + } + } private static void DrawShaderExportButton( ShpkTab tab, string objectName, Shader shader, int idx ) { @@ -163,7 +179,7 @@ public partial class ModEditWindow } DrawShaderExportButton( tab, objectName, shader, idx ); - if( !disabled ) + if( !disabled && tab.Shpk.Disassembled ) { ImGui.SameLine(); DrawShaderImportButton( tab, objectName, shaders, idx ); @@ -182,7 +198,8 @@ public partial class ModEditWindow } } - DrawRawDisassembly( shader ); + if( tab.Shpk.Disassembled ) + DrawRawDisassembly( shader ); } return ret; @@ -276,7 +293,9 @@ public partial class ModEditWindow private static bool DrawShaderPackageMaterialMatrix( ShpkTab tab, bool disabled ) { - ImGui.TextUnformatted( "Parameter positions (continuations are grayed out, unused values are red):" ); + ImGui.TextUnformatted( tab.Shpk.Disassembled + ? "Parameter positions (continuations are grayed out, unused values are red):" + : "Parameter positions (continuations are grayed out):" ); using var table = ImRaii.Table( "##MaterialParamLayout", 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg ); @@ -471,6 +490,22 @@ public partial class ModEditWindow return ret; } + private static bool DrawShaderPackageResources( ShpkTab tab, bool disabled ) + { + var ret = false; + + if( !ImGui.CollapsingHeader( "Shader Resources" ) ) + { + return false; + } + + ret |= DrawShaderPackageResourceArray( "Constant Buffers", "type", true, tab.Shpk.Constants, disabled ); + ret |= DrawShaderPackageResourceArray( "Samplers", "type", false, tab.Shpk.Samplers, disabled ); + ret |= DrawShaderPackageResourceArray( "Unordered Access Views", "type", false, tab.Shpk.Uavs, disabled ); + + return ret; + } + private static void DrawKeyArray( string arrayName, bool withId, IReadOnlyCollection< Key > keys ) { if( keys.Count == 0 ) @@ -513,7 +548,7 @@ public partial class ModEditWindow foreach( var (node, idx) in tab.Shpk.Nodes.WithIndex() ) { using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - using var t2 = ImRaii.TreeNode( $"#{idx:D4}: ID: 0x{node.Id:X8}" ); + using var t2 = ImRaii.TreeNode( $"#{idx:D4}: Selector: 0x{node.Selector:X8}" ); if( !t2 ) { continue; @@ -549,39 +584,38 @@ public partial class ModEditWindow } } - private static bool DrawOtherShaderPackageDetails( ShpkTab tab, bool disabled ) + private static void DrawShaderPackageSelection( ShpkTab tab ) { - var ret = false; - - if( !ImGui.CollapsingHeader( "Further Content" ) ) + if( !ImGui.CollapsingHeader( "Shader Selection" ) ) { - return false; + return; } - ImRaii.TreeNode( $"Version: 0x{tab.Shpk.Version:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - - ret |= DrawShaderPackageResourceArray( "Constant Buffers", "type", true, tab.Shpk.Constants, disabled ); - ret |= DrawShaderPackageResourceArray( "Samplers", "type", false, tab.Shpk.Samplers, disabled ); - ret |= DrawShaderPackageResourceArray( "Unordered Access Views", "type", false, tab.Shpk.Uavs, disabled ); - DrawKeyArray( "System Keys", true, tab.Shpk.SystemKeys ); DrawKeyArray( "Scene Keys", true, tab.Shpk.SceneKeys ); DrawKeyArray( "Material Keys", true, tab.Shpk.MaterialKeys ); DrawKeyArray( "Sub-View Keys", false, tab.Shpk.SubViewKeys ); DrawShaderPackageNodes( tab ); - if( tab.Shpk.Items.Length > 0 ) + using var t = ImRaii.TreeNode( $"Node Selectors ({tab.Shpk.NodeSelectors.Count})###NodeSelectors" ); + if( t ) { - using var t = ImRaii.TreeNode( $"Items ({tab.Shpk.Items.Length})###Items" ); - if( t ) + using var font = ImRaii.PushFont( UiBuilder.MonoFont ); + foreach( var selector in tab.Shpk.NodeSelectors ) { - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - foreach( var (item, idx) in tab.Shpk.Items.WithIndex() ) - { - ImRaii.TreeNode( $"#{idx:D4}: ID: 0x{item.Id:X8}, node: {item.Node}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + ImRaii.TreeNode( $"#{selector.Value:D4}: Selector: 0x{selector.Key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); } } + } + + private static void DrawOtherShaderPackageDetails( ShpkTab tab ) + { + if( !ImGui.CollapsingHeader( "Further Content" ) ) + { + return; + } + + ImRaii.TreeNode( $"Version: 0x{tab.Shpk.Version:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); if( tab.Shpk.AdditionalData.Length > 0 ) { @@ -591,8 +625,6 @@ public partial class ModEditWindow ImGuiUtil.TextWrapped( string.Join( ' ', tab.Shpk.AdditionalData.Select( c => $"{c:X2}" ) ) ); } } - - return ret; } private static string UsedComponentString( bool withSize, in Resource resource ) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index 1720ec8c..2df52130 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -27,8 +27,16 @@ public partial class ModEditWindow public ShpkTab(FileDialogService fileDialog, byte[] bytes) { FileDialog = fileDialog; - Shpk = new ShpkFile(bytes, true); - Header = $"Shader Package for DirectX {(int)Shpk.DirectXVersion}"; + try + { + Shpk = new ShpkFile(bytes, true); + } + catch (NotImplementedException) + { + Shpk = new ShpkFile(bytes, false); + } + + Header = $"Shader Package for DirectX {(int)Shpk.DirectXVersion}"; Extension = Shpk.DirectXVersion switch { ShpkFile.DxVersion.DirectX9 => ".cso", diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index a37363e3..f1c78bf7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; @@ -21,6 +23,7 @@ using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; +using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI.Classes; using Penumbra.Util; @@ -523,6 +526,23 @@ public partial class ModEditWindow : Window, IDisposable return new FullPath(path); } + private HashSet FindPathsStartingWith(ByteString prefix) + { + var ret = new HashSet(); + + foreach (var path in _activeCollections.Current.ResolvedFiles.Keys) + if (path.Path.StartsWith(prefix)) + ret.Add(path); + + if (_mod != null) + foreach (var option in _mod.Groups.SelectMany(g => g).Append(_mod.Default)) + foreach (var path in option.Files.Keys) + if (path.Path.StartsWith(prefix)) + ret.Add(path); + + return ret; + } + public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 0378d620..ad0f2e40 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -195,21 +195,7 @@ public class ModPanelSettingsTab : ITab _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, (uint)idx2); if (option.Description.Length > 0) - { - var hovered = ImGui.IsItemHovered(); - ImGui.SameLine(); - using (var _ = ImRaii.PushFont(UiBuilder.IconFont)) - { - using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled)); - ImGuiUtil.RightAlign(FontAwesomeIcon.InfoCircle.ToIconString(), ImGui.GetStyle().ItemSpacing.X); - } - - if (hovered) - { - using var tt = ImRaii.Tooltip(); - ImGui.TextUnformatted(option.Description); - } - } + ImGuiUtil.SelectableHelpMarker(option.Description); id.Pop(); } From 9364ecccd22673bd54b3c63574992bdb81dba88b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 25 Aug 2023 06:17:54 +0200 Subject: [PATCH 0035/1381] Material editor: better color constants --- OtterGui | 2 +- .../AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index 1e172ee9..c8394607 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 1e172ee9a0f5946d67b848a36b2be97f6541453f +Subproject commit c8394607addd29cb7f8ae3257f635a4486c40a63 diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs index 5616425c..f7ea317d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -148,7 +148,7 @@ public partial class ModEditWindow var value = new Vector3(values); if (_squaredRgb) value = Vector3.SquareRoot(value); - if (ImGui.ColorEdit3("##0", ref value) && !disabled) + if (ImGui.ColorEdit3("##0", ref value, ImGuiColorEditFlags.Float | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) && !disabled) { if (_squaredRgb) value *= value; @@ -166,7 +166,7 @@ public partial class ModEditWindow var value = new Vector4(values); if (_squaredRgb) value = new Vector4(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z), value.W); - if (ImGui.ColorEdit4("##0", ref value) && !disabled) + if (ImGui.ColorEdit4("##0", ref value, ImGuiColorEditFlags.Float | ImGuiColorEditFlags.AlphaPreviewHalf | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) && !disabled) { if (_squaredRgb) value *= new Vector4(value.X, value.Y, value.Z, 1.0f); From 42b874413df85787af1b2acf8834b1dc6caa5153 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 25 Aug 2023 06:28:09 +0200 Subject: [PATCH 0036/1381] Add a few texture manipulation tools. --- OtterGui | 2 +- .../Textures/CombinedTexture.Manipulation.cs | 319 ++++++++++++++++-- Penumbra/Import/Textures/CombinedTexture.cs | 69 ++-- .../AdvancedWindow/ModEditWindow.Textures.cs | 100 +++--- 4 files changed, 381 insertions(+), 109 deletions(-) diff --git a/OtterGui b/OtterGui index 863d08bd..c8394607 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 863d08bd83381bb7fe4a8d5c514f0ba55379336f +Subproject commit c8394607addd29cb7f8ae3257f635a4486c40a63 diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index a32b9578..f8608071 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -6,23 +6,110 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; using SixLabors.ImageSharp.PixelFormats; +using Dalamud.Interface; +using Penumbra.UI; namespace Penumbra.Import.Textures; public partial class CombinedTexture { + private enum CombineOp + { + LeftCopy = -3, + RightCopy = -2, + Invalid = -1, + Over = 0, + Under = 1, + LeftMultiply = 2, + RightMultiply = 3, + CopyChannels = 4, + } + + [Flags] + private enum Channels + { + Red = 1, + Green = 2, + Blue = 4, + Alpha = 8, + } + private Matrix4x4 _multiplierLeft = Matrix4x4.Identity; + private Vector4 _constantLeft = Vector4.Zero; private Matrix4x4 _multiplierRight = Matrix4x4.Identity; - private bool _invertLeft = false; - private bool _invertRight = false; + private Vector4 _constantRight = Vector4.Zero; private int _offsetX = 0; - private int _offsetY = 0; + private int _offsetY = 0; + private CombineOp _combineOp = CombineOp.Over; + private Channels _copyChannels = Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha; + + private static readonly IReadOnlyList CombineOpLabels = new string[] + { + "Overlay over Input", + "Input over Overlay", + "Ignore Overlay", + "Replace Input", + "Copy Channels", + }; + + private static readonly IReadOnlyList CombineOpTooltips = new string[] + { + "Standard composition.\nApply the overlay over the input.", + "Standard composition, reversed.\nApply the input over the overlay.", + "Use only the input, and ignore the overlay.", + "Completely replace the input with the overlay.", + "Replace some input channels with those from the overlay.\nUseful for Multi maps.", + }; + + private const float OneThird = 1.0f / 3.0f; + private const float RWeight = 0.2126f; + private const float GWeight = 0.7152f; + private const float BWeight = 0.0722f; + + private static readonly IReadOnlyList<(string Label, Matrix4x4 Multiplier, Vector4 Constant)> PredefinedColorTransforms = new (string, Matrix4x4, Vector4)[] + { + ("No Transform (Identity)", Matrix4x4.Identity, Vector4.Zero), + ("Grayscale (Average)", new Matrix4x4(OneThird, OneThird, OneThird, 0.0f, OneThird, OneThird, OneThird, 0.0f, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero), + ("Grayscale (Weighted)", new Matrix4x4(RWeight, RWeight, RWeight, 0.0f, GWeight, GWeight, GWeight, 0.0f, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero), + ("Grayscale (Average) to Alpha", new Matrix4x4(OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero), + ("Grayscale (Weighted) to Alpha", new Matrix4x4(RWeight, RWeight, RWeight, RWeight, GWeight, GWeight, GWeight, GWeight, BWeight, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero), + ("Extract Red", new Matrix4x4(1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW), + ("Extract Green", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW), + ("Extract Blue", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW), + ("Extract Alpha", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f), Vector4.UnitW), + }; + + private CombineOp GetActualCombineOp() + { + var combineOp = (_left.IsLoaded, _right.IsLoaded) switch + { + (true, true) => _combineOp, + (true, false) => CombineOp.LeftMultiply, + (false, true) => CombineOp.RightMultiply, + (false, false) => CombineOp.Invalid, + }; + + if (combineOp == CombineOp.CopyChannels) + { + if (_copyChannels == 0) + combineOp = CombineOp.LeftMultiply; + else if (_copyChannels == (Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha)) + combineOp = CombineOp.RightMultiply; + } + + return combineOp switch + { + CombineOp.LeftMultiply => (_multiplierLeft.IsIdentity && _constantLeft == Vector4.Zero) ? CombineOp.LeftCopy : CombineOp.LeftMultiply, + CombineOp.RightMultiply => (_multiplierRight.IsIdentity && _constantRight == Vector4.Zero) ? CombineOp.RightCopy : CombineOp.RightMultiply, + _ => combineOp, + }; + } private Vector4 DataLeft( int offset ) - => CappedVector( _left.RgbaPixels, offset, _multiplierLeft, _invertLeft ); + => CappedVector( _left.RgbaPixels, offset, _multiplierLeft, _constantLeft ); private Vector4 DataRight( int offset ) - => CappedVector( _right.RgbaPixels, offset, _multiplierRight, _invertRight ); + => CappedVector( _right.RgbaPixels, offset, _multiplierRight, _constantRight ); private Vector4 DataRight( int x, int y ) { @@ -34,7 +121,7 @@ public partial class CombinedTexture } var offset = ( y * _right.TextureWrap!.Width + x ) * 4; - return CappedVector( _right.RgbaPixels, offset, _multiplierRight, _invertRight ); + return CappedVector( _right.RgbaPixels, offset, _multiplierRight, _constantRight ); } private void AddPixelsMultiplied( int y, ParallelLoopState _ ) @@ -55,6 +142,43 @@ public partial class CombinedTexture } } + private void ReverseAddPixelsMultiplied( int y, ParallelLoopState _ ) + { + for( var x = 0; x < _left.TextureWrap!.Width; ++x ) + { + var offset = ( _left.TextureWrap!.Width * y + x ) * 4; + var left = DataLeft( offset ); + var right = DataRight( x, y ); + var alpha = left.W + right.W * ( 1 - left.W ); + var rgba = alpha == 0 + ? new Rgba32() + : new Rgba32( ( ( left * left.W + right * right.W * ( 1 - left.W ) ) / alpha ) with { W = alpha } ); + _centerStorage.RgbaPixels[ offset ] = rgba.R; + _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; + _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; + _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + } + } + + private void ChannelMergePixelsMultiplied( int y, ParallelLoopState _ ) + { + var channels = _copyChannels; + for( var x = 0; x < _left.TextureWrap!.Width; ++x ) + { + var offset = ( _left.TextureWrap!.Width * y + x ) * 4; + var left = DataLeft( offset ); + var right = DataRight( x, y ); + var rgba = new Rgba32( ( channels & Channels.Red ) != 0 ? right.X : left.X, + ( channels & Channels.Green ) != 0 ? right.Y : left.Y, + ( channels & Channels.Blue ) != 0 ? right.Z : left.Z, + ( channels & Channels.Alpha ) != 0 ? right.W : left.W ); + _centerStorage.RgbaPixels[ offset ] = rgba.R; + _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; + _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; + _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + } + } + private void MultiplyPixelsLeft( int y, ParallelLoopState _ ) { for( var x = 0; x < _left.TextureWrap!.Width; ++x ) @@ -74,8 +198,8 @@ public partial class CombinedTexture for( var x = 0; x < _right.TextureWrap!.Width; ++x ) { var offset = ( _right.TextureWrap!.Width * y + x ) * 4; - var left = DataRight( offset ); - var rgba = new Rgba32( left ); + var right = DataRight( offset ); + var rgba = new Rgba32( right ); _centerStorage.RgbaPixels[ offset ] = rgba.R; _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; @@ -86,23 +210,25 @@ public partial class CombinedTexture private (int Width, int Height) CombineImage() { - var (width, height) = _left.IsLoaded + var combineOp = GetActualCombineOp(); + var (width, height) = combineOp is not CombineOp.Invalid or CombineOp.RightCopy or CombineOp.RightMultiply ? ( _left.TextureWrap!.Width, _left.TextureWrap!.Height ) : ( _right.TextureWrap!.Width, _right.TextureWrap!.Height ); _centerStorage.RgbaPixels = new byte[width * height * 4]; _centerStorage.Type = TextureType.Bitmap; - if( _left.IsLoaded ) + Parallel.For( 0, height, combineOp switch { - Parallel.For( 0, height, _right.IsLoaded ? AddPixelsMultiplied : MultiplyPixelsLeft ); - } - else - { - Parallel.For( 0, height, MultiplyPixelsRight ); - } + CombineOp.Over => AddPixelsMultiplied, + CombineOp.Under => ReverseAddPixelsMultiplied, + CombineOp.LeftMultiply => MultiplyPixelsLeft, + CombineOp.RightMultiply => MultiplyPixelsRight, + CombineOp.CopyChannels => ChannelMergePixelsMultiplied, + _ => throw new InvalidOperationException( $"Cannot combine images with operation {combineOp}" ), + } ); return ( width, height ); } - private static Vector4 CappedVector( IReadOnlyList< byte > bytes, int offset, Matrix4x4 transform, bool invert ) + private static Vector4 CappedVector( IReadOnlyList< byte > bytes, int offset, Matrix4x4 transform, Vector4 constant ) { if( bytes.Count == 0 ) { @@ -110,11 +236,7 @@ public partial class CombinedTexture } var rgba = new Rgba32( bytes[ offset ], bytes[ offset + 1 ], bytes[ offset + 2 ], bytes[ offset + 3 ] ); - var transformed = Vector4.Transform( rgba.ToVector4(), transform ); - if( invert ) - { - transformed = new Vector4( 1 - transformed.X, 1 - transformed.Y, 1 - transformed.Z, transformed.W ); - } + var transformed = Vector4.Transform( rgba.ToVector4(), transform ) + constant; transformed.X = Math.Clamp( transformed.X, 0, 1 ); transformed.Y = Math.Clamp( transformed.Y, 0, 1 ); @@ -138,8 +260,8 @@ public partial class CombinedTexture public void DrawMatrixInputLeft( float width ) { - var ret = DrawMatrixInput( ref _multiplierLeft, width ); - ret |= ImGui.Checkbox( "Invert Colors##Left", ref _invertLeft ); + var ret = DrawMatrixInput( ref _multiplierLeft, ref _constantLeft, width ); + ret |= DrawMatrixTools( ref _multiplierLeft, ref _constantLeft ); if( ret ) { Update(); @@ -148,23 +270,56 @@ public partial class CombinedTexture public void DrawMatrixInputRight( float width ) { - var ret = DrawMatrixInput( ref _multiplierRight, width ); - ret |= ImGui.Checkbox( "Invert Colors##Right", ref _invertRight ); - ImGui.SameLine(); - ImGui.SetNextItemWidth( 75 ); + var ret = DrawMatrixInput( ref _multiplierRight, ref _constantRight, width ); + ret |= DrawMatrixTools( ref _multiplierRight, ref _constantRight ); + ImGui.SetNextItemWidth( 75.0f * UiHelpers.Scale ); ImGui.DragInt( "##XOffset", ref _offsetX, 0.5f ); ret |= ImGui.IsItemDeactivatedAfterEdit(); ImGui.SameLine(); - ImGui.SetNextItemWidth( 75 ); + ImGui.SetNextItemWidth( 75.0f * UiHelpers.Scale ); ImGui.DragInt( "Offsets##YOffset", ref _offsetY, 0.5f ); ret |= ImGui.IsItemDeactivatedAfterEdit(); + ImGui.SetNextItemWidth( 200.0f * UiHelpers.Scale ); + using( var c = ImRaii.Combo( "Combine Operation", CombineOpLabels[ (int)_combineOp ] ) ) + { + if( c ) + { + foreach( var op in Enum.GetValues() ) + { + if ( (int)op < 0 ) // Negative codes are for internal use only. + continue; + + if( ImGui.Selectable( CombineOpLabels[ (int)op ], op == _combineOp ) ) + { + _combineOp = op; + ret = true; + } + + ImGuiUtil.SelectableHelpMarker( CombineOpTooltips[ (int)op ] ); + } + } + } + using( var dis = ImRaii.Disabled( _combineOp != CombineOp.CopyChannels )) + { + ImGui.TextUnformatted( "Copy" ); + foreach( var channel in Enum.GetValues() ) + { + ImGui.SameLine(); + var copy = ( _copyChannels & channel ) != 0; + if( ImGui.Checkbox( channel.ToString(), ref copy ) ) + { + _copyChannels = copy ? ( _copyChannels | channel ) : ( _copyChannels & ~channel ); + ret = true; + } + } + } if( ret ) { Update(); } } - private static bool DrawMatrixInput( ref Matrix4x4 multiplier, float width ) + private static bool DrawMatrixInput( ref Matrix4x4 multiplier, ref Vector4 constant, float width ) { using var table = ImRaii.Table( string.Empty, 5, ImGuiTableFlags.BordersInner | ImGuiTableFlags.SizingFixedFit ); if( !table ) @@ -217,6 +372,110 @@ public partial class CombinedTexture changes |= DragFloat( "##AB", inputWidth, ref multiplier.M43 ); changes |= DragFloat( "##AA", inputWidth, ref multiplier.M44 ); + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.Text( "1 " ); + changes |= DragFloat( "##1R", inputWidth, ref constant.X ); + changes |= DragFloat( "##1G", inputWidth, ref constant.Y ); + changes |= DragFloat( "##1B", inputWidth, ref constant.Z ); + changes |= DragFloat( "##1A", inputWidth, ref constant.W ); + return changes; } + + private static bool DrawMatrixTools( ref Matrix4x4 multiplier, ref Vector4 constant ) + { + var changes = false; + + using( var combo = ImRaii.Combo( "Presets", string.Empty, ImGuiComboFlags.NoPreview ) ) + { + if( combo ) + { + foreach( var (label, preMultiplier, preConstant) in PredefinedColorTransforms ) + { + if( ImGui.Selectable( label, multiplier == preMultiplier && constant == preConstant ) ) + { + multiplier = preMultiplier; + constant = preConstant; + changes = true; + } + } + } + } + + ImGui.SameLine(); + ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); + ImGui.SameLine(); + ImGui.TextUnformatted( "Invert" ); + ImGui.SameLine(); + if( ImGui.Button( "Colors" ) ) + { + InvertRed( ref multiplier, ref constant ); + InvertGreen( ref multiplier, ref constant ); + InvertBlue( ref multiplier, ref constant ); + changes = true; + } + ImGui.SameLine(); + if( ImGui.Button( "R" ) ) + { + InvertRed( ref multiplier, ref constant ); + changes = true; + } + ImGui.SameLine(); + if( ImGui.Button( "G" ) ) + { + InvertGreen( ref multiplier, ref constant ); + changes = true; + } + ImGui.SameLine(); + if( ImGui.Button( "B" ) ) + { + InvertBlue( ref multiplier, ref constant ); + changes = true; + } + ImGui.SameLine(); + if( ImGui.Button( "A" ) ) + { + InvertAlpha( ref multiplier, ref constant ); + changes = true; + } + + return changes; + } + + private static void InvertRed( ref Matrix4x4 multiplier, ref Vector4 constant ) + { + multiplier.M11 = -multiplier.M11; + multiplier.M21 = -multiplier.M21; + multiplier.M31 = -multiplier.M31; + multiplier.M41 = -multiplier.M41; + constant.X = 1.0f - constant.X; + } + + private static void InvertGreen( ref Matrix4x4 multiplier, ref Vector4 constant ) + { + multiplier.M12 = -multiplier.M12; + multiplier.M22 = -multiplier.M22; + multiplier.M32 = -multiplier.M32; + multiplier.M42 = -multiplier.M42; + constant.Y = 1.0f - constant.Y; + } + + private static void InvertBlue( ref Matrix4x4 multiplier, ref Vector4 constant ) + { + multiplier.M13 = -multiplier.M13; + multiplier.M23 = -multiplier.M23; + multiplier.M33 = -multiplier.M33; + multiplier.M43 = -multiplier.M43; + constant.Z = 1.0f - constant.Z; + } + + private static void InvertAlpha( ref Matrix4x4 multiplier, ref Vector4 constant ) + { + multiplier.M14 = -multiplier.M14; + multiplier.M24 = -multiplier.M24; + multiplier.M34 = -multiplier.M34; + multiplier.M44 = -multiplier.M44; + constant.W = 1.0f - constant.W; + } } \ No newline at end of file diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index c26cb900..14a8a41c 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Numerics; using System.Threading.Tasks; @@ -68,6 +69,38 @@ public partial class CombinedTexture : IDisposable _current.TextureWrap!.Height); } + public void SaveAs(TextureType? texType, TextureManager textures, string path, TextureSaveType type, bool mipMaps) + { + TextureType finalTexType; + if (texType.HasValue) + finalTexType = texType.Value; + else + { + finalTexType = Path.GetExtension(path).ToLowerInvariant() switch + { + ".tex" => TextureType.Tex, + ".dds" => TextureType.Dds, + ".png" => TextureType.Png, + _ => TextureType.Unknown, + }; + } + + switch (finalTexType) + { + case TextureType.Tex: + SaveAsTex(textures, path, type, mipMaps); + break; + case TextureType.Dds: + SaveAsDds(textures, path, type, mipMaps); + break; + case TextureType.Png: + SaveAsPng(textures, path); + break; + default: + throw new ArgumentException($"Cannot save texture as TextureType {finalTexType} with extension {Path.GetExtension(path).ToLowerInvariant()}"); + } + } + public void SaveAsTex(TextureManager textures, string path, TextureSaveType type, bool mipMaps) => SaveAs(textures, path, type, mipMaps, true); @@ -97,36 +130,22 @@ public partial class CombinedTexture : IDisposable public void Update() { Clean(); - if (_left.IsLoaded) + switch (GetActualCombineOp()) { - if (_right.IsLoaded) - { - _current = _centerStorage; - _mode = Mode.Custom; - } - else if (!_invertLeft && _multiplierLeft.IsIdentity) - { + case CombineOp.Invalid: + break; + case CombineOp.LeftCopy: _mode = Mode.LeftCopy; _current = _left; - } - else - { - _current = _centerStorage; - _mode = Mode.Custom; - } - } - else if (_right.IsLoaded) - { - if (!_invertRight && _multiplierRight.IsIdentity) - { - _current = _right; + break; + case CombineOp.RightCopy: _mode = Mode.RightCopy; - } - else - { - _current = _centerStorage; + _current = _right; + break; + default: _mode = Mode.Custom; - } + _current = _centerStorage; + break; } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 4d36ff8a..4cf3731d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -90,7 +90,7 @@ public partial class ModEditWindow if (ImGui.Selectable(newText, idx == _currentSaveAs)) _currentSaveAs = idx; - ImGuiUtil.HoverTooltip(newDesc); + ImGuiUtil.SelectableHelpMarker(newDesc); } } @@ -114,73 +114,65 @@ public partial class ModEditWindow SaveAsCombo(); ImGui.SameLine(); MipMapInput(); - if (ImGui.Button("Save as TEX", -Vector2.UnitX)) + + var canSaveInPlace = Path.IsPathRooted(_left.Path) && _left.Type is TextureType.Tex or TextureType.Dds or TextureType.Png; + + var buttonSize2 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); + if (ImGuiUtil.DrawDisabledButton("Save in place", buttonSize2, + "This saves the texture in place. This is not revertible.", + !canSaveInPlace || _center.IsLeftCopy && _currentSaveAs == (int)CombinedTexture.TextureSaveType.AsIs)) { - var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); - _fileDialog.OpenSavePicker("Save Texture as TEX...", ".tex", fileName, ".tex", (a, b) => - { - if (a) - _center.SaveAsTex(_textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); - }, _mod!.ModPath.FullName, _forceTextureStartPath); - _forceTextureStartPath = false; + _center.SaveAs(_left.Type, _textures, _left.Path, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + AddReloadTask(_left.Path, false); } - if (ImGui.Button("Save as DDS", -Vector2.UnitX)) + ImGui.SameLine(); + if (ImGui.Button("Save as TEX, DDS or PNG", buttonSize2)) { - var fileName = Path.GetFileNameWithoutExtension(_right.Path.Length > 0 ? _right.Path : _left.Path); - _fileDialog.OpenSavePicker("Save Texture as DDS...", ".dds", fileName, ".dds", (a, b) => + var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); + _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, ".tex", (a, b) => { if (a) - _center.SaveAsDds(_textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + { + _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + if (b == _left.Path) + AddReloadTask(_left.Path, false); + else if (b == _right.Path) + AddReloadTask(_right.Path, true); + } }, _mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } ImGui.NewLine(); - if (ImGui.Button("Save as PNG", -Vector2.UnitX)) + var canConvertInPlace = canSaveInPlace && _left.Type is TextureType.Tex && _center.IsLeftCopy; + + var buttonSize3 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X * 2) / 3, 0); + if (ImGuiUtil.DrawDisabledButton("Convert to BC7", buttonSize3, + "This converts the texture to BC7 format in place. This is not revertible.", + !canConvertInPlace || _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) { - var fileName = Path.GetFileNameWithoutExtension(_right.Path.Length > 0 ? _right.Path : _left.Path); - _fileDialog.OpenSavePicker("Save Texture as PNG...", ".png", fileName, ".png", (a, b) => - { - if (a) - _center.SaveAsPng(_textures, b); - }, _mod!.ModPath.FullName, _forceTextureStartPath); - _forceTextureStartPath = false; + _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); + AddReloadTask(_left.Path, false); } - if (_left.Type is TextureType.Tex && _center.IsLeftCopy) + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton("Convert to BC3", buttonSize3, + "This converts the texture to BC3 format in place. This is not revertible.", + !canConvertInPlace || _left.Format is DXGIFormat.BC3Typeless or DXGIFormat.BC3UNorm or DXGIFormat.BC3UNormSRGB)) { - var buttonSize = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X * 2) / 3, 0); - if (ImGuiUtil.DrawDisabledButton("Convert to BC7", buttonSize, - "This converts the texture to BC7 format in place. This is not revertible.", - _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) - { - _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); - AddReloadTask(_left.Path); - } - - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Convert to BC3", buttonSize, - "This converts the texture to BC3 format in place. This is not revertible.", - _left.Format is DXGIFormat.BC3Typeless or DXGIFormat.BC3UNorm or DXGIFormat.BC3UNormSRGB)) - { - _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); - AddReloadTask(_left.Path); - } - - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Convert to RGBA", buttonSize, - "This converts the texture to RGBA format in place. This is not revertible.", - _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) - { - _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); - AddReloadTask(_left.Path); - } + _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); + AddReloadTask(_left.Path, false); } - else + + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton("Convert to RGBA", buttonSize3, + "This converts the texture to RGBA format in place. This is not revertible.", + !canConvertInPlace || _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) { - ImGui.NewLine(); + _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); + AddReloadTask(_left.Path, false); } } @@ -212,17 +204,19 @@ public partial class ModEditWindow _center.Draw(_textures, imageSize); } - private void AddReloadTask(string path) + private void AddReloadTask(string path, bool right) { _center.SaveTask.ContinueWith(t => { if (!t.IsCompletedSuccessfully) return; - if (_left.Path != path) + var tex = right ? _right : _left; + + if (tex.Path != path) return; - _dalamud.Framework.RunOnFrameworkThread(() => _left.Reload(_textures)); + _dalamud.Framework.RunOnFrameworkThread(() => tex.Reload(_textures)); }); } From afd7aab37dcb3a2b0e8b4991367c26ad38890ce3 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 25 Aug 2023 17:46:53 +0200 Subject: [PATCH 0037/1381] Update GameData --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 07c001c5..1c68fd5e 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 07c001c5b2b35b2dba2b8428389d3ed375728616 +Subproject commit 1c68fd5efb23798d13154c1de0ad010db319abe2 From 87c5164367443dc43a9b1dc7ede61ca5b2c93f84 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 25 Aug 2023 17:56:48 +0200 Subject: [PATCH 0038/1381] Small cleanup, auto-formatting. --- .../Textures/CombinedTexture.Manipulation.cs | 380 +++++++++--------- Penumbra/Import/Textures/CombinedTexture.cs | 15 +- .../AdvancedWindow/ModEditWindow.Textures.cs | 24 +- 3 files changed, 205 insertions(+), 214 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index f8608071..2af2a8e4 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -66,25 +66,28 @@ public partial class CombinedTexture private const float GWeight = 0.7152f; private const float BWeight = 0.0722f; - private static readonly IReadOnlyList<(string Label, Matrix4x4 Multiplier, Vector4 Constant)> PredefinedColorTransforms = new (string, Matrix4x4, Vector4)[] - { - ("No Transform (Identity)", Matrix4x4.Identity, Vector4.Zero), - ("Grayscale (Average)", new Matrix4x4(OneThird, OneThird, OneThird, 0.0f, OneThird, OneThird, OneThird, 0.0f, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero), - ("Grayscale (Weighted)", new Matrix4x4(RWeight, RWeight, RWeight, 0.0f, GWeight, GWeight, GWeight, 0.0f, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero), - ("Grayscale (Average) to Alpha", new Matrix4x4(OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero), - ("Grayscale (Weighted) to Alpha", new Matrix4x4(RWeight, RWeight, RWeight, RWeight, GWeight, GWeight, GWeight, GWeight, BWeight, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero), - ("Extract Red", new Matrix4x4(1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW), - ("Extract Green", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW), - ("Extract Blue", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW), - ("Extract Alpha", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f), Vector4.UnitW), - }; + // @formatter:off + private static readonly IReadOnlyList<(string Label, Matrix4x4 Multiplier, Vector4 Constant)> PredefinedColorTransforms = + new[] + { + ("No Transform (Identity)", Matrix4x4.Identity, Vector4.Zero ), + ("Grayscale (Average)", new Matrix4x4(OneThird, OneThird, OneThird, 0.0f, OneThird, OneThird, OneThird, 0.0f, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero ), + ("Grayscale (Weighted)", new Matrix4x4(RWeight, RWeight, RWeight, 0.0f, GWeight, GWeight, GWeight, 0.0f, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero ), + ("Grayscale (Average) to Alpha", new Matrix4x4(OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero ), + ("Grayscale (Weighted) to Alpha", new Matrix4x4(RWeight, RWeight, RWeight, RWeight, GWeight, GWeight, GWeight, GWeight, BWeight, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero ), + ("Extract Red", new Matrix4x4(1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), + ("Extract Green", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), + ("Extract Blue", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), + ("Extract Alpha", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f), Vector4.UnitW ), + }; + // @formatter:on private CombineOp GetActualCombineOp() { var combineOp = (_left.IsLoaded, _right.IsLoaded) switch { - (true, true) => _combineOp, - (true, false) => CombineOp.LeftMultiply, + (true, true) => _combineOp, + (true, false) => CombineOp.LeftMultiply, (false, true) => CombineOp.RightMultiply, (false, false) => CombineOp.Invalid, }; @@ -99,111 +102,109 @@ public partial class CombinedTexture return combineOp switch { - CombineOp.LeftMultiply => (_multiplierLeft.IsIdentity && _constantLeft == Vector4.Zero) ? CombineOp.LeftCopy : CombineOp.LeftMultiply, - CombineOp.RightMultiply => (_multiplierRight.IsIdentity && _constantRight == Vector4.Zero) ? CombineOp.RightCopy : CombineOp.RightMultiply, - _ => combineOp, + CombineOp.LeftMultiply when _multiplierLeft.IsIdentity && _constantLeft == Vector4.Zero => CombineOp.LeftCopy, + CombineOp.RightMultiply when _multiplierRight.IsIdentity && _constantRight == Vector4.Zero => CombineOp.RightCopy, + _ => combineOp, }; } - private Vector4 DataLeft( int offset ) - => CappedVector( _left.RgbaPixels, offset, _multiplierLeft, _constantLeft ); + private Vector4 DataLeft(int offset) + => CappedVector(_left.RgbaPixels, offset, _multiplierLeft, _constantLeft); - private Vector4 DataRight( int offset ) - => CappedVector( _right.RgbaPixels, offset, _multiplierRight, _constantRight ); + private Vector4 DataRight(int offset) + => CappedVector(_right.RgbaPixels, offset, _multiplierRight, _constantRight); - private Vector4 DataRight( int x, int y ) + private Vector4 DataRight(int x, int y) { x += _offsetX; y += _offsetY; - if( x < 0 || x >= _right.TextureWrap!.Width || y < 0 || y >= _right.TextureWrap!.Height ) - { + if (x < 0 || x >= _right.TextureWrap!.Width || y < 0 || y >= _right.TextureWrap!.Height) return Vector4.Zero; - } - var offset = ( y * _right.TextureWrap!.Width + x ) * 4; - return CappedVector( _right.RgbaPixels, offset, _multiplierRight, _constantRight ); + var offset = (y * _right.TextureWrap!.Width + x) * 4; + return CappedVector(_right.RgbaPixels, offset, _multiplierRight, _constantRight); } - private void AddPixelsMultiplied( int y, ParallelLoopState _ ) + private void AddPixelsMultiplied(int y, ParallelLoopState _) { - for( var x = 0; x < _left.TextureWrap!.Width; ++x ) + for (var x = 0; x < _left.TextureWrap!.Width; ++x) { - var offset = ( _left.TextureWrap!.Width * y + x ) * 4; - var left = DataLeft( offset ); - var right = DataRight( x, y ); - var alpha = right.W + left.W * ( 1 - right.W ); + var offset = (_left.TextureWrap!.Width * y + x) * 4; + var left = DataLeft(offset); + var right = DataRight(x, y); + var alpha = right.W + left.W * (1 - right.W); var rgba = alpha == 0 ? new Rgba32() - : new Rgba32( ( ( right * right.W + left * left.W * ( 1 - right.W ) ) / alpha ) with { W = alpha } ); - _centerStorage.RgbaPixels[ offset ] = rgba.R; - _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; - _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; - _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + : new Rgba32(((right * right.W + left * left.W * (1 - right.W)) / alpha) with { W = alpha }); + _centerStorage.RgbaPixels[offset] = rgba.R; + _centerStorage.RgbaPixels[offset + 1] = rgba.G; + _centerStorage.RgbaPixels[offset + 2] = rgba.B; + _centerStorage.RgbaPixels[offset + 3] = rgba.A; } } - private void ReverseAddPixelsMultiplied( int y, ParallelLoopState _ ) + private void ReverseAddPixelsMultiplied(int y, ParallelLoopState _) { - for( var x = 0; x < _left.TextureWrap!.Width; ++x ) + for (var x = 0; x < _left.TextureWrap!.Width; ++x) { - var offset = ( _left.TextureWrap!.Width * y + x ) * 4; - var left = DataLeft( offset ); - var right = DataRight( x, y ); - var alpha = left.W + right.W * ( 1 - left.W ); + var offset = (_left.TextureWrap!.Width * y + x) * 4; + var left = DataLeft(offset); + var right = DataRight(x, y); + var alpha = left.W + right.W * (1 - left.W); var rgba = alpha == 0 ? new Rgba32() - : new Rgba32( ( ( left * left.W + right * right.W * ( 1 - left.W ) ) / alpha ) with { W = alpha } ); - _centerStorage.RgbaPixels[ offset ] = rgba.R; - _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; - _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; - _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + : new Rgba32(((left * left.W + right * right.W * (1 - left.W)) / alpha) with { W = alpha }); + _centerStorage.RgbaPixels[offset] = rgba.R; + _centerStorage.RgbaPixels[offset + 1] = rgba.G; + _centerStorage.RgbaPixels[offset + 2] = rgba.B; + _centerStorage.RgbaPixels[offset + 3] = rgba.A; } } - private void ChannelMergePixelsMultiplied( int y, ParallelLoopState _ ) + private void ChannelMergePixelsMultiplied(int y, ParallelLoopState _) { var channels = _copyChannels; - for( var x = 0; x < _left.TextureWrap!.Width; ++x ) + for (var x = 0; x < _left.TextureWrap!.Width; ++x) { - var offset = ( _left.TextureWrap!.Width * y + x ) * 4; - var left = DataLeft( offset ); - var right = DataRight( x, y ); - var rgba = new Rgba32( ( channels & Channels.Red ) != 0 ? right.X : left.X, - ( channels & Channels.Green ) != 0 ? right.Y : left.Y, - ( channels & Channels.Blue ) != 0 ? right.Z : left.Z, - ( channels & Channels.Alpha ) != 0 ? right.W : left.W ); - _centerStorage.RgbaPixels[ offset ] = rgba.R; - _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; - _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; - _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + var offset = (_left.TextureWrap!.Width * y + x) * 4; + var left = DataLeft(offset); + var right = DataRight(x, y); + var rgba = new Rgba32((channels & Channels.Red) != 0 ? right.X : left.X, + (channels & Channels.Green) != 0 ? right.Y : left.Y, + (channels & Channels.Blue) != 0 ? right.Z : left.Z, + (channels & Channels.Alpha) != 0 ? right.W : left.W); + _centerStorage.RgbaPixels[offset] = rgba.R; + _centerStorage.RgbaPixels[offset + 1] = rgba.G; + _centerStorage.RgbaPixels[offset + 2] = rgba.B; + _centerStorage.RgbaPixels[offset + 3] = rgba.A; } } - private void MultiplyPixelsLeft( int y, ParallelLoopState _ ) + private void MultiplyPixelsLeft(int y, ParallelLoopState _) { - for( var x = 0; x < _left.TextureWrap!.Width; ++x ) + for (var x = 0; x < _left.TextureWrap!.Width; ++x) { - var offset = ( _left.TextureWrap!.Width * y + x ) * 4; - var left = DataLeft( offset ); - var rgba = new Rgba32( left ); - _centerStorage.RgbaPixels[ offset ] = rgba.R; - _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; - _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; - _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + var offset = (_left.TextureWrap!.Width * y + x) * 4; + var left = DataLeft(offset); + var rgba = new Rgba32(left); + _centerStorage.RgbaPixels[offset] = rgba.R; + _centerStorage.RgbaPixels[offset + 1] = rgba.G; + _centerStorage.RgbaPixels[offset + 2] = rgba.B; + _centerStorage.RgbaPixels[offset + 3] = rgba.A; } } - private void MultiplyPixelsRight( int y, ParallelLoopState _ ) + private void MultiplyPixelsRight(int y, ParallelLoopState _) { - for( var x = 0; x < _right.TextureWrap!.Width; ++x ) + for (var x = 0; x < _right.TextureWrap!.Width; ++x) { - var offset = ( _right.TextureWrap!.Width * y + x ) * 4; - var right = DataRight( offset ); - var rgba = new Rgba32( right ); - _centerStorage.RgbaPixels[ offset ] = rgba.R; - _centerStorage.RgbaPixels[ offset + 1 ] = rgba.G; - _centerStorage.RgbaPixels[ offset + 2 ] = rgba.B; - _centerStorage.RgbaPixels[ offset + 3 ] = rgba.A; + var offset = (_right.TextureWrap!.Width * y + x) * 4; + var right = DataRight(offset); + var rgba = new Rgba32(right); + _centerStorage.RgbaPixels[offset] = rgba.R; + _centerStorage.RgbaPixels[offset + 1] = rgba.G; + _centerStorage.RgbaPixels[offset + 2] = rgba.B; + _centerStorage.RgbaPixels[offset + 3] = rgba.A; } } @@ -212,238 +213,231 @@ public partial class CombinedTexture { var combineOp = GetActualCombineOp(); var (width, height) = combineOp is not CombineOp.Invalid or CombineOp.RightCopy or CombineOp.RightMultiply - ? ( _left.TextureWrap!.Width, _left.TextureWrap!.Height ) - : ( _right.TextureWrap!.Width, _right.TextureWrap!.Height ); + ? (_left.TextureWrap!.Width, _left.TextureWrap!.Height) + : (_right.TextureWrap!.Width, _right.TextureWrap!.Height); _centerStorage.RgbaPixels = new byte[width * height * 4]; _centerStorage.Type = TextureType.Bitmap; - Parallel.For( 0, height, combineOp switch + Parallel.For(0, height, combineOp switch { CombineOp.Over => AddPixelsMultiplied, CombineOp.Under => ReverseAddPixelsMultiplied, CombineOp.LeftMultiply => MultiplyPixelsLeft, CombineOp.RightMultiply => MultiplyPixelsRight, CombineOp.CopyChannels => ChannelMergePixelsMultiplied, - _ => throw new InvalidOperationException( $"Cannot combine images with operation {combineOp}" ), - } ); + _ => throw new InvalidOperationException($"Cannot combine images with operation {combineOp}"), + }); - return ( width, height ); + return (width, height); } - private static Vector4 CappedVector( IReadOnlyList< byte > bytes, int offset, Matrix4x4 transform, Vector4 constant ) + + private static Vector4 CappedVector(IReadOnlyList bytes, int offset, Matrix4x4 transform, Vector4 constant) { - if( bytes.Count == 0 ) - { + if (bytes.Count == 0) return Vector4.Zero; - } - var rgba = new Rgba32( bytes[ offset ], bytes[ offset + 1 ], bytes[ offset + 2 ], bytes[ offset + 3 ] ); - var transformed = Vector4.Transform( rgba.ToVector4(), transform ) + constant; + var rgba = new Rgba32(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]); + var transformed = Vector4.Transform(rgba.ToVector4(), transform) + constant; - transformed.X = Math.Clamp( transformed.X, 0, 1 ); - transformed.Y = Math.Clamp( transformed.Y, 0, 1 ); - transformed.Z = Math.Clamp( transformed.Z, 0, 1 ); - transformed.W = Math.Clamp( transformed.W, 0, 1 ); + transformed.X = Math.Clamp(transformed.X, 0, 1); + transformed.Y = Math.Clamp(transformed.Y, 0, 1); + transformed.Z = Math.Clamp(transformed.Z, 0, 1); + transformed.W = Math.Clamp(transformed.W, 0, 1); return transformed; } - private static bool DragFloat( string label, float width, ref float value ) + private static bool DragFloat(string label, float width, ref float value) { var tmp = value; ImGui.TableNextColumn(); - ImGui.SetNextItemWidth( width ); - if( ImGui.DragFloat( label, ref tmp, 0.001f, -1f, 1f ) ) - { + ImGui.SetNextItemWidth(width); + if (ImGui.DragFloat(label, ref tmp, 0.001f, -1f, 1f)) value = tmp; - } return ImGui.IsItemDeactivatedAfterEdit(); } - public void DrawMatrixInputLeft( float width ) + public void DrawMatrixInputLeft(float width) { - var ret = DrawMatrixInput( ref _multiplierLeft, ref _constantLeft, width ); - ret |= DrawMatrixTools( ref _multiplierLeft, ref _constantLeft ); - if( ret ) - { + var ret = DrawMatrixInput(ref _multiplierLeft, ref _constantLeft, width); + ret |= DrawMatrixTools(ref _multiplierLeft, ref _constantLeft); + if (ret) Update(); - } } - public void DrawMatrixInputRight( float width ) + public void DrawMatrixInputRight(float width) { - var ret = DrawMatrixInput( ref _multiplierRight, ref _constantRight, width ); - ret |= DrawMatrixTools( ref _multiplierRight, ref _constantRight ); - ImGui.SetNextItemWidth( 75.0f * UiHelpers.Scale ); - ImGui.DragInt( "##XOffset", ref _offsetX, 0.5f ); + var ret = DrawMatrixInput(ref _multiplierRight, ref _constantRight, width); + ret |= DrawMatrixTools(ref _multiplierRight, ref _constantRight); + ImGui.SetNextItemWidth(75.0f * UiHelpers.Scale); + ImGui.DragInt("##XOffset", ref _offsetX, 0.5f); ret |= ImGui.IsItemDeactivatedAfterEdit(); ImGui.SameLine(); - ImGui.SetNextItemWidth( 75.0f * UiHelpers.Scale ); - ImGui.DragInt( "Offsets##YOffset", ref _offsetY, 0.5f ); + ImGui.SetNextItemWidth(75.0f * UiHelpers.Scale); + ImGui.DragInt("Offsets##YOffset", ref _offsetY, 0.5f); ret |= ImGui.IsItemDeactivatedAfterEdit(); - ImGui.SetNextItemWidth( 200.0f * UiHelpers.Scale ); - using( var c = ImRaii.Combo( "Combine Operation", CombineOpLabels[ (int)_combineOp ] ) ) + ImGui.SetNextItemWidth(200.0f * UiHelpers.Scale); + using (var c = ImRaii.Combo("Combine Operation", CombineOpLabels[(int)_combineOp])) { - if( c ) - { - foreach( var op in Enum.GetValues() ) + if (c) + foreach (var op in Enum.GetValues()) { - if ( (int)op < 0 ) // Negative codes are for internal use only. + if ((int)op < 0) // Negative codes are for internal use only. continue; - if( ImGui.Selectable( CombineOpLabels[ (int)op ], op == _combineOp ) ) + if (ImGui.Selectable(CombineOpLabels[(int)op], op == _combineOp)) { _combineOp = op; ret = true; } - ImGuiUtil.SelectableHelpMarker( CombineOpTooltips[ (int)op ] ); + ImGuiUtil.SelectableHelpMarker(CombineOpTooltips[(int)op]); } - } } - using( var dis = ImRaii.Disabled( _combineOp != CombineOp.CopyChannels )) + + using (var dis = ImRaii.Disabled(_combineOp != CombineOp.CopyChannels)) { - ImGui.TextUnformatted( "Copy" ); - foreach( var channel in Enum.GetValues() ) + ImGui.TextUnformatted("Copy"); + foreach (var channel in Enum.GetValues()) { ImGui.SameLine(); - var copy = ( _copyChannels & channel ) != 0; - if( ImGui.Checkbox( channel.ToString(), ref copy ) ) + var copy = (_copyChannels & channel) != 0; + if (ImGui.Checkbox(channel.ToString(), ref copy)) { - _copyChannels = copy ? ( _copyChannels | channel ) : ( _copyChannels & ~channel ); - ret = true; + _copyChannels = copy ? _copyChannels | channel : _copyChannels & ~channel; + ret = true; } } } - if( ret ) - { + + if (ret) Update(); - } } - private static bool DrawMatrixInput( ref Matrix4x4 multiplier, ref Vector4 constant, float width ) + private static bool DrawMatrixInput(ref Matrix4x4 multiplier, ref Vector4 constant, float width) { - using var table = ImRaii.Table( string.Empty, 5, ImGuiTableFlags.BordersInner | ImGuiTableFlags.SizingFixedFit ); - if( !table ) - { + using var table = ImRaii.Table(string.Empty, 5, ImGuiTableFlags.BordersInner | ImGuiTableFlags.SizingFixedFit); + if (!table) return false; - } var changes = false; ImGui.TableNextColumn(); ImGui.TableNextColumn(); - ImGuiUtil.Center( "R" ); + ImGuiUtil.Center("R"); ImGui.TableNextColumn(); - ImGuiUtil.Center( "G" ); + ImGuiUtil.Center("G"); ImGui.TableNextColumn(); - ImGuiUtil.Center( "B" ); + ImGuiUtil.Center("B"); ImGui.TableNextColumn(); - ImGuiUtil.Center( "A" ); + ImGuiUtil.Center("A"); var inputWidth = width / 6; ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); - ImGui.Text( "R " ); - changes |= DragFloat( "##RR", inputWidth, ref multiplier.M11 ); - changes |= DragFloat( "##RG", inputWidth, ref multiplier.M12 ); - changes |= DragFloat( "##RB", inputWidth, ref multiplier.M13 ); - changes |= DragFloat( "##RA", inputWidth, ref multiplier.M14 ); + ImGui.Text("R "); + changes |= DragFloat("##RR", inputWidth, ref multiplier.M11); + changes |= DragFloat("##RG", inputWidth, ref multiplier.M12); + changes |= DragFloat("##RB", inputWidth, ref multiplier.M13); + changes |= DragFloat("##RA", inputWidth, ref multiplier.M14); ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); - ImGui.Text( "G " ); - changes |= DragFloat( "##GR", inputWidth, ref multiplier.M21 ); - changes |= DragFloat( "##GG", inputWidth, ref multiplier.M22 ); - changes |= DragFloat( "##GB", inputWidth, ref multiplier.M23 ); - changes |= DragFloat( "##GA", inputWidth, ref multiplier.M24 ); + ImGui.Text("G "); + changes |= DragFloat("##GR", inputWidth, ref multiplier.M21); + changes |= DragFloat("##GG", inputWidth, ref multiplier.M22); + changes |= DragFloat("##GB", inputWidth, ref multiplier.M23); + changes |= DragFloat("##GA", inputWidth, ref multiplier.M24); ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); - ImGui.Text( "B " ); - changes |= DragFloat( "##BR", inputWidth, ref multiplier.M31 ); - changes |= DragFloat( "##BG", inputWidth, ref multiplier.M32 ); - changes |= DragFloat( "##BB", inputWidth, ref multiplier.M33 ); - changes |= DragFloat( "##BA", inputWidth, ref multiplier.M34 ); + ImGui.Text("B "); + changes |= DragFloat("##BR", inputWidth, ref multiplier.M31); + changes |= DragFloat("##BG", inputWidth, ref multiplier.M32); + changes |= DragFloat("##BB", inputWidth, ref multiplier.M33); + changes |= DragFloat("##BA", inputWidth, ref multiplier.M34); ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); - ImGui.Text( "A " ); - changes |= DragFloat( "##AR", inputWidth, ref multiplier.M41 ); - changes |= DragFloat( "##AG", inputWidth, ref multiplier.M42 ); - changes |= DragFloat( "##AB", inputWidth, ref multiplier.M43 ); - changes |= DragFloat( "##AA", inputWidth, ref multiplier.M44 ); + ImGui.Text("A "); + changes |= DragFloat("##AR", inputWidth, ref multiplier.M41); + changes |= DragFloat("##AG", inputWidth, ref multiplier.M42); + changes |= DragFloat("##AB", inputWidth, ref multiplier.M43); + changes |= DragFloat("##AA", inputWidth, ref multiplier.M44); ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); - ImGui.Text( "1 " ); - changes |= DragFloat( "##1R", inputWidth, ref constant.X ); - changes |= DragFloat( "##1G", inputWidth, ref constant.Y ); - changes |= DragFloat( "##1B", inputWidth, ref constant.Z ); - changes |= DragFloat( "##1A", inputWidth, ref constant.W ); + ImGui.Text("1 "); + changes |= DragFloat("##1R", inputWidth, ref constant.X); + changes |= DragFloat("##1G", inputWidth, ref constant.Y); + changes |= DragFloat("##1B", inputWidth, ref constant.Z); + changes |= DragFloat("##1A", inputWidth, ref constant.W); return changes; } - private static bool DrawMatrixTools( ref Matrix4x4 multiplier, ref Vector4 constant ) + private static bool DrawMatrixTools(ref Matrix4x4 multiplier, ref Vector4 constant) { var changes = false; - using( var combo = ImRaii.Combo( "Presets", string.Empty, ImGuiComboFlags.NoPreview ) ) + using (var combo = ImRaii.Combo("Presets", string.Empty, ImGuiComboFlags.NoPreview)) { - if( combo ) - { - foreach( var (label, preMultiplier, preConstant) in PredefinedColorTransforms ) + if (combo) + foreach (var (label, preMultiplier, preConstant) in PredefinedColorTransforms) { - if( ImGui.Selectable( label, multiplier == preMultiplier && constant == preConstant ) ) + if (ImGui.Selectable(label, multiplier == preMultiplier && constant == preConstant)) { multiplier = preMultiplier; constant = preConstant; changes = true; } } - } } ImGui.SameLine(); - ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); - ImGui.TextUnformatted( "Invert" ); + ImGui.TextUnformatted("Invert"); ImGui.SameLine(); - if( ImGui.Button( "Colors" ) ) + if (ImGui.Button("Colors")) { - InvertRed( ref multiplier, ref constant ); - InvertGreen( ref multiplier, ref constant ); - InvertBlue( ref multiplier, ref constant ); + InvertRed(ref multiplier, ref constant); + InvertGreen(ref multiplier, ref constant); + InvertBlue(ref multiplier, ref constant); changes = true; } + ImGui.SameLine(); - if( ImGui.Button( "R" ) ) + if (ImGui.Button("R")) { - InvertRed( ref multiplier, ref constant ); + InvertRed(ref multiplier, ref constant); changes = true; } + ImGui.SameLine(); - if( ImGui.Button( "G" ) ) + if (ImGui.Button("G")) { - InvertGreen( ref multiplier, ref constant ); + InvertGreen(ref multiplier, ref constant); changes = true; } + ImGui.SameLine(); - if( ImGui.Button( "B" ) ) + if (ImGui.Button("B")) { - InvertBlue( ref multiplier, ref constant ); + InvertBlue(ref multiplier, ref constant); changes = true; } + ImGui.SameLine(); - if( ImGui.Button( "A" ) ) + if (ImGui.Button("A")) { - InvertAlpha( ref multiplier, ref constant ); + InvertAlpha(ref multiplier, ref constant); changes = true; } return changes; } - private static void InvertRed( ref Matrix4x4 multiplier, ref Vector4 constant ) + private static void InvertRed(ref Matrix4x4 multiplier, ref Vector4 constant) { multiplier.M11 = -multiplier.M11; multiplier.M21 = -multiplier.M21; @@ -452,7 +446,7 @@ public partial class CombinedTexture constant.X = 1.0f - constant.X; } - private static void InvertGreen( ref Matrix4x4 multiplier, ref Vector4 constant ) + private static void InvertGreen(ref Matrix4x4 multiplier, ref Vector4 constant) { multiplier.M12 = -multiplier.M12; multiplier.M22 = -multiplier.M22; @@ -461,7 +455,7 @@ public partial class CombinedTexture constant.Y = 1.0f - constant.Y; } - private static void InvertBlue( ref Matrix4x4 multiplier, ref Vector4 constant ) + private static void InvertBlue(ref Matrix4x4 multiplier, ref Vector4 constant) { multiplier.M13 = -multiplier.M13; multiplier.M23 = -multiplier.M23; @@ -470,7 +464,7 @@ public partial class CombinedTexture constant.Z = 1.0f - constant.Z; } - private static void InvertAlpha( ref Matrix4x4 multiplier, ref Vector4 constant ) + private static void InvertAlpha(ref Matrix4x4 multiplier, ref Vector4 constant) { multiplier.M14 = -multiplier.M14; multiplier.M24 = -multiplier.M24; @@ -478,4 +472,4 @@ public partial class CombinedTexture multiplier.M44 = -multiplier.M44; constant.W = 1.0f - constant.W; } -} \ No newline at end of file +} diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index 14a8a41c..b7e2a90a 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -71,19 +71,14 @@ public partial class CombinedTexture : IDisposable public void SaveAs(TextureType? texType, TextureManager textures, string path, TextureSaveType type, bool mipMaps) { - TextureType finalTexType; - if (texType.HasValue) - finalTexType = texType.Value; - else - { - finalTexType = Path.GetExtension(path).ToLowerInvariant() switch + var finalTexType = texType + ?? Path.GetExtension(path).ToLowerInvariant() switch { ".tex" => TextureType.Tex, ".dds" => TextureType.Dds, ".png" => TextureType.Png, _ => TextureType.Unknown, }; - } switch (finalTexType) { @@ -97,7 +92,8 @@ public partial class CombinedTexture : IDisposable SaveAsPng(textures, path); break; default: - throw new ArgumentException($"Cannot save texture as TextureType {finalTexType} with extension {Path.GetExtension(path).ToLowerInvariant()}"); + throw new ArgumentException( + $"Cannot save texture as TextureType {finalTexType} with extension {Path.GetExtension(path).ToLowerInvariant()}"); } } @@ -132,8 +128,7 @@ public partial class CombinedTexture : IDisposable Clean(); switch (GetActualCombineOp()) { - case CombineOp.Invalid: - break; + case CombineOp.Invalid: break; case CombineOp.LeftCopy: _mode = Mode.LeftCopy; _current = _left; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 4cf3731d..af256f5c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -130,17 +130,18 @@ public partial class ModEditWindow if (ImGui.Button("Save as TEX, DDS or PNG", buttonSize2)) { var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); - _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, ".tex", (a, b) => - { - if (a) + _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, ".tex", + (a, b) => { - _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); - if (b == _left.Path) - AddReloadTask(_left.Path, false); - else if (b == _right.Path) - AddReloadTask(_right.Path, true); - } - }, _mod!.ModPath.FullName, _forceTextureStartPath); + if (a) + { + _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + if (b == _left.Path) + AddReloadTask(_left.Path, false); + else if (b == _right.Path) + AddReloadTask(_right.Path, true); + } + }, _mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } @@ -169,7 +170,8 @@ public partial class ModEditWindow ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Convert to RGBA", buttonSize3, "This converts the texture to RGBA format in place. This is not revertible.", - !canConvertInPlace || _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) + !canConvertInPlace + || _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); AddReloadTask(_left.Path, false); From 781bbb3d26ebaa0400b92d7996a8c0563a1d8ccd Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 25 Aug 2023 17:59:18 +0200 Subject: [PATCH 0039/1381] Textures: Un-merge save buttons, make ignore unselectable --- .../Textures/CombinedTexture.Manipulation.cs | 8 ++-- .../AdvancedWindow/ModEditWindow.Textures.cs | 41 +++++++++++-------- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index f8608071..3256836d 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -15,12 +15,12 @@ public partial class CombinedTexture { private enum CombineOp { + LeftMultiply = -4, LeftCopy = -3, RightCopy = -2, Invalid = -1, Over = 0, Under = 1, - LeftMultiply = 2, RightMultiply = 3, CopyChannels = 4, } @@ -47,7 +47,6 @@ public partial class CombinedTexture { "Overlay over Input", "Input over Overlay", - "Ignore Overlay", "Replace Input", "Copy Channels", }; @@ -55,9 +54,8 @@ public partial class CombinedTexture private static readonly IReadOnlyList CombineOpTooltips = new string[] { "Standard composition.\nApply the overlay over the input.", - "Standard composition, reversed.\nApply the input over the overlay.", - "Use only the input, and ignore the overlay.", - "Completely replace the input with the overlay.", + "Standard composition, reversed.\nApply the input over the overlay ; can be used to fix some wrong imports.", + "Completely replace the input with the overlay.\nCan be used to select the destination file as input and the source file as overlay.", "Replace some input channels with those from the overlay.\nUseful for Multi maps.", }; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 4cf3731d..3db2d407 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -127,22 +127,14 @@ public partial class ModEditWindow } ImGui.SameLine(); - if (ImGui.Button("Save as TEX, DDS or PNG", buttonSize2)) - { - var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); - _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, ".tex", (a, b) => - { - if (a) - { - _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); - if (b == _left.Path) - AddReloadTask(_left.Path, false); - else if (b == _right.Path) - AddReloadTask(_right.Path, true); - } - }, _mod!.ModPath.FullName, _forceTextureStartPath); - _forceTextureStartPath = false; - } + if (ImGui.Button("Save as TEX", buttonSize2)) + OpenSaveAsDialog(".tex"); + + if (ImGui.Button("Export as PNG", buttonSize2)) + OpenSaveAsDialog(".png"); + ImGui.SameLine(); + if (ImGui.Button("Export as DDS", buttonSize2)) + OpenSaveAsDialog(".dds"); ImGui.NewLine(); @@ -204,6 +196,23 @@ public partial class ModEditWindow _center.Draw(_textures, imageSize); } + private void OpenSaveAsDialog(string defaultExtension) + { + var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); + _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, defaultExtension, (a, b) => + { + if (a) + { + _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + if (b == _left.Path) + AddReloadTask(_left.Path, false); + else if (b == _right.Path) + AddReloadTask(_right.Path, true); + } + }, _mod!.ModPath.FullName, _forceTextureStartPath); + _forceTextureStartPath = false; + } + private void AddReloadTask(string path, bool right) { _center.SaveTask.ContinueWith(t => From 792707a6e3237e55d909ca05e0e58a7c4d736743 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 25 Aug 2023 18:24:21 +0200 Subject: [PATCH 0040/1381] Textures: Renumber CombineOps. Positive values in this enum also double as indices into the labels and tooltip arrays. (confirmed skill issue moment) --- Penumbra/Import/Textures/CombinedTexture.Manipulation.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index fed269da..057d0234 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -21,8 +21,8 @@ public partial class CombinedTexture Invalid = -1, Over = 0, Under = 1, - RightMultiply = 3, - CopyChannels = 4, + RightMultiply = 2, + CopyChannels = 3, } [Flags] From 99b43bf577d58744525264b9dcd3957cfb76dd5b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 25 Aug 2023 20:09:16 +0200 Subject: [PATCH 0041/1381] Textures: Automatic resizing --- .../Textures/CombinedTexture.Manipulation.cs | 131 ++++++++++++++---- 1 file changed, 105 insertions(+), 26 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 057d0234..b02ba7b7 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -8,6 +8,8 @@ using OtterGui; using SixLabors.ImageSharp.PixelFormats; using Dalamud.Interface; using Penumbra.UI; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Processing; namespace Penumbra.Import.Textures; @@ -25,6 +27,13 @@ public partial class CombinedTexture CopyChannels = 3, } + private enum ResizeOp + { + None = 0, + ToLeft = 1, + ToRight = 2, + } + [Flags] private enum Channels { @@ -41,8 +50,16 @@ public partial class CombinedTexture private int _offsetX = 0; private int _offsetY = 0; private CombineOp _combineOp = CombineOp.Over; + private ResizeOp _resizeOp = ResizeOp.None; private Channels _copyChannels = Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha; + private int _rightWidth = 0; + private int _rightHeight = 0; + private int _targetWidth = 0; + private int _targetHeight = 0; + private byte[] _leftPixels = Array.Empty(); + private byte[] _rightPixels = Array.Empty(); + private static readonly IReadOnlyList CombineOpLabels = new string[] { "Overlay over Input", @@ -59,6 +76,26 @@ public partial class CombinedTexture "Replace some input channels with those from the overlay.\nUseful for Multi maps.", }; + private static (bool UsesLeft, bool UsesRight) GetCombineOpFlags(CombineOp combineOp) + => combineOp switch + { + CombineOp.LeftCopy => (true, false), + CombineOp.LeftMultiply => (true, false), + CombineOp.RightCopy => (false, true), + CombineOp.RightMultiply => (false, true), + CombineOp.Over => (true, true), + CombineOp.Under => (true, true), + CombineOp.CopyChannels => (true, true), + _ => throw new ArgumentException($"Invalid combine operation {combineOp}"), + }; + + private static readonly IReadOnlyList ResizeOpLabels = new string[] + { + "No Resizing", + "Adjust Overlay to Input", + "Adjust Input to Overlay", + }; + private const float OneThird = 1.0f / 3.0f; private const float RWeight = 0.2126f; private const float GWeight = 0.7152f; @@ -107,27 +144,27 @@ public partial class CombinedTexture } private Vector4 DataLeft(int offset) - => CappedVector(_left.RgbaPixels, offset, _multiplierLeft, _constantLeft); + => CappedVector(_leftPixels, offset, _multiplierLeft, _constantLeft); private Vector4 DataRight(int offset) - => CappedVector(_right.RgbaPixels, offset, _multiplierRight, _constantRight); + => CappedVector(_rightPixels, offset, _multiplierRight, _constantRight); private Vector4 DataRight(int x, int y) { x += _offsetX; y += _offsetY; - if (x < 0 || x >= _right.TextureWrap!.Width || y < 0 || y >= _right.TextureWrap!.Height) + if (x < 0 || x >= _rightWidth || y < 0 || y >= _rightHeight) return Vector4.Zero; - var offset = (y * _right.TextureWrap!.Width + x) * 4; - return CappedVector(_right.RgbaPixels, offset, _multiplierRight, _constantRight); + var offset = (y * _rightWidth + x) * 4; + return CappedVector(_rightPixels, offset, _multiplierRight, _constantRight); } private void AddPixelsMultiplied(int y, ParallelLoopState _) { - for (var x = 0; x < _left.TextureWrap!.Width; ++x) + for (var x = 0; x < _targetWidth; ++x) { - var offset = (_left.TextureWrap!.Width * y + x) * 4; + var offset = (_targetWidth * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var alpha = right.W + left.W * (1 - right.W); @@ -143,9 +180,9 @@ public partial class CombinedTexture private void ReverseAddPixelsMultiplied(int y, ParallelLoopState _) { - for (var x = 0; x < _left.TextureWrap!.Width; ++x) + for (var x = 0; x < _targetWidth; ++x) { - var offset = (_left.TextureWrap!.Width * y + x) * 4; + var offset = (_targetWidth * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var alpha = left.W + right.W * (1 - left.W); @@ -162,9 +199,9 @@ public partial class CombinedTexture private void ChannelMergePixelsMultiplied(int y, ParallelLoopState _) { var channels = _copyChannels; - for (var x = 0; x < _left.TextureWrap!.Width; ++x) + for (var x = 0; x < _targetWidth; ++x) { - var offset = (_left.TextureWrap!.Width * y + x) * 4; + var offset = (_targetWidth * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var rgba = new Rgba32((channels & Channels.Red) != 0 ? right.X : left.X, @@ -180,9 +217,9 @@ public partial class CombinedTexture private void MultiplyPixelsLeft(int y, ParallelLoopState _) { - for (var x = 0; x < _left.TextureWrap!.Width; ++x) + for (var x = 0; x < _targetWidth; ++x) { - var offset = (_left.TextureWrap!.Width * y + x) * 4; + var offset = (_targetWidth * y + x) * 4; var left = DataLeft(offset); var rgba = new Rgba32(left); _centerStorage.RgbaPixels[offset] = rgba.R; @@ -194,9 +231,9 @@ public partial class CombinedTexture private void MultiplyPixelsRight(int y, ParallelLoopState _) { - for (var x = 0; x < _right.TextureWrap!.Width; ++x) + for (var x = 0; x < _targetWidth; ++x) { - var offset = (_right.TextureWrap!.Width * y + x) * 4; + var offset = (_targetWidth * y + x) * 4; var right = DataRight(offset); var rgba = new Rgba32(right); _centerStorage.RgbaPixels[offset] = rgba.R; @@ -206,26 +243,59 @@ public partial class CombinedTexture } } + private byte[] ResizePixels(byte[] rgbaPixels, int sourceWidth, int sourceHeight) + { + if (sourceWidth == _targetWidth && sourceHeight == _targetHeight) + return rgbaPixels; + + byte[] resizedPixels; + using (var image = Image.LoadPixelData(rgbaPixels, sourceWidth, sourceHeight)) + { + image.Mutate(ctx => ctx.Resize(_targetWidth, _targetHeight)); + + resizedPixels = new byte[_targetWidth * _targetHeight * 4]; + image.CopyPixelDataTo(resizedPixels); + } + + return resizedPixels; + } + private (int Width, int Height) CombineImage() { var combineOp = GetActualCombineOp(); - var (width, height) = combineOp is not CombineOp.Invalid or CombineOp.RightCopy or CombineOp.RightMultiply + var (usesLeft, usesRight) = GetCombineOpFlags(combineOp); + var resizeOp = usesLeft && usesRight ? _resizeOp : ResizeOp.None; + (_targetWidth, _targetHeight) = usesLeft && resizeOp != ResizeOp.ToRight ? (_left.TextureWrap!.Width, _left.TextureWrap!.Height) : (_right.TextureWrap!.Width, _right.TextureWrap!.Height); - _centerStorage.RgbaPixels = new byte[width * height * 4]; + _centerStorage.RgbaPixels = new byte[_targetWidth * _targetHeight * 4]; _centerStorage.Type = TextureType.Bitmap; - Parallel.For(0, height, combineOp switch + try { - CombineOp.Over => AddPixelsMultiplied, - CombineOp.Under => ReverseAddPixelsMultiplied, - CombineOp.LeftMultiply => MultiplyPixelsLeft, - CombineOp.RightMultiply => MultiplyPixelsRight, - CombineOp.CopyChannels => ChannelMergePixelsMultiplied, - _ => throw new InvalidOperationException($"Cannot combine images with operation {combineOp}"), - }); + if (usesLeft) + _leftPixels = (resizeOp == ResizeOp.ToRight) ? ResizePixels(_left.RgbaPixels, _left.TextureWrap!.Width, _left.TextureWrap!.Height) : _left.RgbaPixels; + if (usesRight) + (_rightWidth, _rightHeight, _rightPixels) = (resizeOp == ResizeOp.ToLeft) + ? (_targetWidth, _targetHeight, ResizePixels(_right.RgbaPixels, _right.TextureWrap!.Width, _right.TextureWrap!.Height)) + : (_right.TextureWrap!.Width, _right.TextureWrap!.Height, _right.RgbaPixels); + Parallel.For(0, _targetHeight, combineOp switch + { + CombineOp.Over => AddPixelsMultiplied, + CombineOp.Under => ReverseAddPixelsMultiplied, + CombineOp.LeftMultiply => MultiplyPixelsLeft, + CombineOp.RightMultiply => MultiplyPixelsRight, + CombineOp.CopyChannels => ChannelMergePixelsMultiplied, + _ => throw new InvalidOperationException($"Cannot combine images with operation {combineOp}"), + }); + } + finally + { + _leftPixels = Array.Empty(); + _rightPixels = Array.Empty(); + } - return (width, height); + return (_targetWidth, _targetHeight); } private static Vector4 CappedVector(IReadOnlyList bytes, int offset, Matrix4x4 transform, Vector4 constant) @@ -266,6 +336,7 @@ public partial class CombinedTexture { var ret = DrawMatrixInput(ref _multiplierRight, ref _constantRight, width); ret |= DrawMatrixTools(ref _multiplierRight, ref _constantRight); + ImGui.SetNextItemWidth(75.0f * UiHelpers.Scale); ImGui.DragInt("##XOffset", ref _offsetX, 0.5f); ret |= ImGui.IsItemDeactivatedAfterEdit(); @@ -273,6 +344,7 @@ public partial class CombinedTexture ImGui.SetNextItemWidth(75.0f * UiHelpers.Scale); ImGui.DragInt("Offsets##YOffset", ref _offsetY, 0.5f); ret |= ImGui.IsItemDeactivatedAfterEdit(); + ImGui.SetNextItemWidth(200.0f * UiHelpers.Scale); using (var c = ImRaii.Combo("Combine Operation", CombineOpLabels[(int)_combineOp])) { @@ -292,6 +364,13 @@ public partial class CombinedTexture } } + var (usesLeft, usesRight) = GetCombineOpFlags(_combineOp); + using (var dis = ImRaii.Disabled(!usesLeft || !usesRight)) + { + ret |= ImGuiUtil.GenericEnumCombo("Resizing Mode", 200.0f * UiHelpers.Scale, _resizeOp, out _resizeOp, + Enum.GetValues(), op => ResizeOpLabels[(int)op]); + } + using (var dis = ImRaii.Disabled(_combineOp != CombineOp.CopyChannels)) { ImGui.TextUnformatted("Copy"); From ead88f9fa6313ea83082b9c51d9ad4d886f1fd61 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 27 Aug 2023 03:42:34 +0200 Subject: [PATCH 0042/1381] Skin Fixer (fixes modding of skin.shpk) --- Penumbra/Interop/Services/CharacterUtility.cs | 12 +- Penumbra/Interop/Services/SkinFixer.cs | 161 ++++++++++++++++++ .../Interop/Structs/CharacterUtilityData.cs | 8 +- Penumbra/Interop/Structs/MtrlResource.cs | 22 ++- Penumbra/Interop/Structs/ResourceHandle.cs | 14 +- Penumbra/Penumbra.cs | 5 +- Penumbra/Services/ServiceManager.cs | 3 +- Penumbra/UI/Tabs/DebugTab.cs | 107 +++++++++--- 8 files changed, 302 insertions(+), 30 deletions(-) create mode 100644 Penumbra/Interop/Services/SkinFixer.cs diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index ef706f6d..00eab531 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -33,6 +33,7 @@ public unsafe partial class CharacterUtility : IDisposable public event Action LoadingFinished; public nint DefaultTransparentResource { get; private set; } public nint DefaultDecalResource { get; private set; } + public nint DefaultSkinShpkResource { get; private set; } /// /// The relevant indices depend on which meta manipulations we allow for. @@ -102,6 +103,12 @@ public unsafe partial class CharacterUtility : IDisposable anyMissing |= DefaultDecalResource == nint.Zero; } + if (DefaultSkinShpkResource == nint.Zero) + { + DefaultSkinShpkResource = (nint)Address->SkinShpkResource; + anyMissing |= DefaultSkinShpkResource == nint.Zero; + } + if (anyMissing) return; @@ -140,15 +147,16 @@ public unsafe partial class CharacterUtility : IDisposable /// Return all relevant resources to the default resource. public void ResetAll() - { + { if (!Ready) - return; + return; foreach (var list in _lists) list.Dispose(); Address->TransparentTexResource = (TextureResourceHandle*)DefaultTransparentResource; Address->DecalTexResource = (TextureResourceHandle*)DefaultDecalResource; + Address->SkinShpkResource = (ResourceHandle*)DefaultSkinShpkResource; } public void Dispose() diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs new file mode 100644 index 00000000..5ce35f29 --- /dev/null +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading; +using Dalamud.Hooking; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.System.Resource; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Penumbra.GameData; +using Penumbra.GameData.Enums; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.ResourceLoading; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Services; + +public unsafe class SkinFixer : IDisposable +{ + public static readonly Utf8GamePath SkinShpkPath = + Utf8GamePath.FromSpan("shader/sm5/shpk/skin.shpk"u8, out var p) ? p : Utf8GamePath.Empty; + + [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] + private readonly nint* _humanVTable = null!; + + private delegate nint OnRenderMaterialDelegate(nint drawObject, OnRenderMaterialParams* param); + + [StructLayout(LayoutKind.Explicit)] + private struct OnRenderMaterialParams + { + [FieldOffset(0x0)] + public Model* Model; + [FieldOffset(0x8)] + public uint MaterialIndex; + } + + private readonly Hook _onRenderMaterialHook; + + private readonly CollectionResolver _collectionResolver; + private readonly GameEventManager _gameEvents; + private readonly ResourceLoader _resources; + private readonly CharacterUtility _utility; + + private readonly ConcurrentDictionary _skinShpks = new(); + + private readonly object _lock = new(); + + private bool _enabled = true; + private int _moddedSkinShpkCount = 0; + private ulong _slowPathCallDelta = 0; + public bool Enabled + { + get => _enabled; + set => _enabled = value; + } + + public int ModdedSkinShpkCount + => _moddedSkinShpkCount; + + public SkinFixer(CollectionResolver collectionResolver, GameEventManager gameEvents, ResourceLoader resources, CharacterUtility utility, DrawObjectState _) + { + SignatureHelper.Initialise(this); + _collectionResolver = collectionResolver; + _gameEvents = gameEvents; + _resources = resources; + _utility = utility; + _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); + _gameEvents.CharacterBaseCreated += OnCharacterBaseCreated; // The dependency on DrawObjectState shall ensure that this handler is registered after its one. + _gameEvents.CharacterBaseDestructor += OnCharacterBaseDestructor; + _onRenderMaterialHook.Enable(); + } + + ~SkinFixer() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + protected virtual void Dispose(bool disposing) + { + _onRenderMaterialHook.Dispose(); + _gameEvents.CharacterBaseCreated -= OnCharacterBaseCreated; + _gameEvents.CharacterBaseDestructor -= OnCharacterBaseDestructor; + foreach (var skinShpk in _skinShpks.Values) + if (skinShpk != nint.Zero) + ((ResourceHandle*)skinShpk)->DecRef(); + _skinShpks.Clear(); + _moddedSkinShpkCount = 0; + } + + public ulong GetAndResetSlowPathCallDelta() + => Interlocked.Exchange(ref _slowPathCallDelta, 0); + + private void OnCharacterBaseCreated(uint modelCharaId, nint customize, nint equipment, nint drawObject) + { + if (((CharacterBase*)drawObject)->GetModelType() != CharacterBase.ModelType.Human) + return; + + nint skinShpk; + try + { + var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + skinShpk = data.Valid ? (nint)_resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data) : nint.Zero; + } + catch (Exception e) + { + Penumbra.Log.Error($"Error while resolving skin.shpk for human {drawObject:X}: {e}"); + skinShpk = nint.Zero; + } + + if (skinShpk != nint.Zero && _skinShpks.TryAdd(drawObject, skinShpk) && skinShpk != _utility.DefaultSkinShpkResource) + Interlocked.Increment(ref _moddedSkinShpkCount); + } + + private void OnCharacterBaseDestructor(nint characterBase) + { + if (_skinShpks.Remove(characterBase, out var skinShpk) && skinShpk != nint.Zero) + { + ((ResourceHandle*)skinShpk)->DecRef(); + if (skinShpk != _utility.DefaultSkinShpkResource) + Interlocked.Decrement(ref _moddedSkinShpkCount); + } + } + + private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) + { + if (!_enabled || // Can be toggled on the debug tab. + _moddedSkinShpkCount == 0 || // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. + !_skinShpks.TryGetValue(human, out var skinShpk) || skinShpk == nint.Zero) + return _onRenderMaterialHook!.Original(human, param); + + var material = param->Model->Materials[param->MaterialIndex]; + var shpkResource = ((Structs.MtrlResource*)material->MaterialResourceHandle)->ShpkResourceHandle; + if ((nint)shpkResource != skinShpk) + return _onRenderMaterialHook!.Original(human, param); + + Interlocked.Increment(ref _slowPathCallDelta); + + // Performance considerations: + // - This function is called from several threads simultaneously, hence the need for synchronization in the swapping path ; + // - Function is called each frame for each material on screen, after culling, i. e. up to thousands of times a frame in crowded areas ; + // - Swapping path is taken up to hundreds of times a frame. + // At the time of writing, the lock doesn't seem to have a noticeable impact in either framerate or CPU usage, but the swapping path shall still be avoided as much as possible. + lock (_lock) + try + { + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)skinShpk; + return _onRenderMaterialHook!.Original(human, param); + } + finally + { + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)_utility.DefaultSkinShpkResource; + } + } +} diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index b273091b..765ad25f 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -10,6 +10,7 @@ public unsafe struct CharacterUtilityData { public const int IndexTransparentTex = 72; public const int IndexDecalTex = 73; + public const int IndexSkinShpk = 76; public static readonly MetaIndex[] EqdpIndices = Enum.GetNames< MetaIndex >() .Zip( Enum.GetValues< MetaIndex >() ) @@ -17,8 +18,8 @@ public unsafe struct CharacterUtilityData .Select( n => n.Second ).ToArray(); public const int TotalNumResources = 87; - - /// Obtain the index for the eqdp file corresponding to the given race code and accessory. + + /// Obtain the index for the eqdp file corresponding to the given race code and accessory. public static MetaIndex EqdpIdx( GenderRace raceCode, bool accessory ) => +( int )raceCode switch { @@ -95,5 +96,8 @@ public unsafe struct CharacterUtilityData [FieldOffset( 8 + IndexDecalTex * 8 )] public TextureResourceHandle* DecalTexResource; + [FieldOffset( 8 + IndexSkinShpk * 8 )] + public ResourceHandle* SkinShpkResource; + // not included resources have no known use case. } \ No newline at end of file diff --git a/Penumbra/Interop/Structs/MtrlResource.cs b/Penumbra/Interop/Structs/MtrlResource.cs index 28756877..424adfe4 100644 --- a/Penumbra/Interop/Structs/MtrlResource.cs +++ b/Penumbra/Interop/Structs/MtrlResource.cs @@ -8,8 +8,11 @@ public unsafe struct MtrlResource [FieldOffset( 0x00 )] public ResourceHandle Handle; + [FieldOffset( 0xC8 )] + public ShaderPackageResourceHandle* ShpkResourceHandle; + [FieldOffset( 0xD0 )] - public ushort* TexSpace; // Contains the offsets for the tex files inside the string list. + public TextureEntry* TexSpace; // Contains the offsets for the tex files inside the string list. [FieldOffset( 0xE0 )] public byte* StringList; @@ -24,8 +27,21 @@ public unsafe struct MtrlResource => StringList + ShpkOffset; public byte* TexString( int idx ) - => StringList + *( TexSpace + 4 + idx * 8 ); + => StringList + TexSpace[idx].PathOffset; public bool TexIsDX11( int idx ) - => *(TexSpace + 5 + idx * 8) >= 0x8000; + => TexSpace[idx].Flags >= 0x8000; + + [StructLayout(LayoutKind.Explicit, Size = 0x10)] + public struct TextureEntry + { + [FieldOffset( 0x00 )] + public TextureResourceHandle* ResourceHandle; + + [FieldOffset( 0x08 )] + public ushort PathOffset; + + [FieldOffset( 0x0A )] + public ushort Flags; + } } \ No newline at end of file diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 4de81903..5db0f8e1 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -1,5 +1,7 @@ using System; using System.Runtime.InteropServices; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.GameData; using Penumbra.GameData.Enums; @@ -18,12 +20,22 @@ public unsafe struct TextureResourceHandle public IntPtr Unk; [FieldOffset( 0x118 )] - public IntPtr KernelTexture; + public Texture* KernelTexture; [FieldOffset( 0x20 )] public IntPtr NewKernelTexture; } +[StructLayout(LayoutKind.Explicit)] +public unsafe struct ShaderPackageResourceHandle +{ + [FieldOffset( 0x0 )] + public ResourceHandle Handle; + + [FieldOffset( 0xB0 )] + public ShaderPackage* ShaderPackage; +} + [StructLayout( LayoutKind.Explicit )] public unsafe struct ResourceHandle { diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b291e392..eeee8fd0 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -22,8 +22,8 @@ using Penumbra.Collections.Manager; using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; -using OtterGui.Tasks; - +using OtterGui.Tasks; + namespace Penumbra; public class Penumbra : IDalamudPlugin @@ -81,6 +81,7 @@ public class Penumbra : IDalamudPlugin { _services.GetRequiredService(); } + _services.GetRequiredService(); SetupInterface(); SetupApi(); diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 728585ae..8bea52e3 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -117,7 +117,8 @@ public static class ServiceManager => services.AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddResolvers(this IServiceCollection services) => services.AddSingleton() diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index a48fd714..1ee62c35 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -34,6 +34,9 @@ using CharacterBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBa using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using ObjectKind = Dalamud.Game.ClientState.Objects.Enums.ObjectKind; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; +using Penumbra.Interop.Services; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using static Lumina.Data.Parsing.Layer.LayerCommon; namespace Penumbra.UI.Tabs; @@ -63,6 +66,7 @@ public class DebugTab : Window, ITab private readonly ImportPopup _importPopup; private readonly FrameworkManager _framework; private readonly TextureManager _textureManager; + private readonly SkinFixer _skinFixer; public DebugTab(StartTracker timer, PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorService actorService, @@ -70,7 +74,7 @@ public class DebugTab : Window, ITab ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager) + TextureManager textureManager, SkinFixer skinFixer) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse, false) { IsOpen = true; @@ -103,6 +107,7 @@ public class DebugTab : Window, ITab _importPopup = importPopup; _framework = framework; _textureManager = textureManager; + _skinFixer = skinFixer; } public ReadOnlySpan Label @@ -144,6 +149,8 @@ public class DebugTab : Window, ITab ImGui.NewLine(); DrawPlayerModelInfo(); ImGui.NewLine(); + DrawGlobalVariableInfo(); + ImGui.NewLine(); DrawDebugTabIpc(); ImGui.NewLine(); } @@ -338,7 +345,7 @@ public class DebugTab : Window, ITab if (!ImGui.CollapsingHeader("Actors")) return; - using var table = Table("##actors", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + using var table = Table("##actors", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) return; @@ -350,6 +357,7 @@ public class DebugTab : Window, ITab ImGuiUtil.DrawTableColumn(name); ImGuiUtil.DrawTableColumn(string.Empty); + ImGuiUtil.DrawTableColumn(string.Empty); ImGuiUtil.DrawTableColumn(_actorService.AwaitedService.ToString(id)); ImGuiUtil.DrawTableColumn(string.Empty); } @@ -363,6 +371,7 @@ public class DebugTab : Window, ITab { ImGuiUtil.DrawTableColumn($"{((GameObject*)obj.Address)->ObjectIndex}"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); + ImGuiUtil.DrawTableColumn((obj.Address == nint.Zero) ? string.Empty : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); var identifier = _actorService.AwaitedService.FromObject(obj, false, true, false); ImGuiUtil.DrawTableColumn(_actorService.AwaitedService.ToString(identifier)); var id = obj.ObjectKind == ObjectKind.BattleNpc ? $"{identifier.DataId} | {obj.DataId}" : identifier.DataId.ToString(); @@ -582,45 +591,76 @@ public class DebugTab : Window, ITab if (!ImGui.CollapsingHeader("Character Utility")) return; - using var table = Table("##CharacterUtility", 6, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + var enableSkinFixer = _skinFixer.Enabled; + if (ImGui.Checkbox("Enable Skin Fixer", ref enableSkinFixer)) + _skinFixer.Enabled = enableSkinFixer; + + if (enableSkinFixer) + { + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImGui.SameLine(); + ImGui.TextUnformatted($"\u0394 Slow-Path Calls: {_skinFixer.GetAndResetSlowPathCallDelta()}"); + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImGui.SameLine(); + ImGui.TextUnformatted($"Draw Objects with Modded skin.shpk: {_skinFixer.ModdedSkinShpkCount}"); + } + + using var table = Table("##CharacterUtility", 7, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) return; - for (var i = 0; i < CharacterUtility.RelevantIndices.Length; ++i) + for (var idx = 0; idx < CharacterUtility.ReverseIndices.Length; ++idx) { - var idx = CharacterUtility.RelevantIndices[i]; - var intern = new CharacterUtility.InternalIndex(i); + var intern = CharacterUtility.ReverseIndices[idx]; var resource = _characterUtility.Address->Resource(idx); ImGui.TableNextColumn(); + ImGui.TextUnformatted($"[{idx}]"); + ImGui.TableNextColumn(); ImGui.TextUnformatted($"0x{(ulong)resource:X}"); ImGui.TableNextColumn(); + if (resource == null) + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + continue; + } UiHelpers.Text(resource); ImGui.TableNextColumn(); - ImGui.Selectable($"0x{resource->GetData().Data:X}"); + var data = (nint)ResourceHandle.GetData(resource); + var length = ResourceHandle.GetLength(resource); + ImGui.Selectable($"0x{data:X}"); if (ImGui.IsItemClicked()) { - var (data, length) = resource->GetData(); if (data != nint.Zero && length > 0) ImGui.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)data, length).ToArray().Select(b => b.ToString("X2")))); + new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); } ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{length}"); ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{resource->GetData().Length}"); - ImGui.TableNextColumn(); - ImGui.Selectable($"0x{_characterUtility.DefaultResource(intern).Address:X}"); - if (ImGui.IsItemClicked()) - ImGui.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)_characterUtility.DefaultResource(intern).Address, - _characterUtility.DefaultResource(intern).Size).ToArray().Select(b => b.ToString("X2")))); + if (intern.Value != -1) + { + ImGui.Selectable($"0x{_characterUtility.DefaultResource(intern).Address:X}"); + if (ImGui.IsItemClicked()) + ImGui.SetClipboardText(string.Join("\n", + new ReadOnlySpan((byte*)_characterUtility.DefaultResource(intern).Address, + _characterUtility.DefaultResource(intern).Size).ToArray().Select(b => b.ToString("X2")))); - ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); + ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{_characterUtility.DefaultResource(intern).Size}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_characterUtility.DefaultResource(intern).Size}"); + } + else + ImGui.TableNextColumn(); } } @@ -665,6 +705,18 @@ public class DebugTab : Window, ITab } } + private static void DrawCopyableAddress(string label, nint address) + { + using (var _ = PushFont(UiBuilder.MonoFont)) + if (ImGui.Selectable($"0x{address:X16} {label}")) + ImGui.SetClipboardText($"{address:X16}"); + + ImGuiUtil.HoverTooltip("Click to copy address to clipboard."); + } + + private static unsafe void DrawCopyableAddress(string label, void* address) + => DrawCopyableAddress(label, (nint)address); + /// Draw information about the models, materials and resources currently loaded by the local player. private unsafe void DrawPlayerModelInfo() { @@ -673,10 +725,14 @@ public class DebugTab : Window, ITab if (!ImGui.CollapsingHeader($"Player Model Info: {name}##Draw") || player == null) return; + DrawCopyableAddress("PlayerCharacter", player.Address); + var model = (CharacterBase*)((Character*)player.Address)->GameObject.GetDrawObject(); if (model == null) return; + DrawCopyableAddress("CharacterBase", model); + using (var t1 = Table("##table", 2, ImGuiTableFlags.SizingFixedFit)) { if (t1) @@ -730,6 +786,19 @@ public class DebugTab : Window, ITab } } + /// Draw information about some game global variables. + private unsafe void DrawGlobalVariableInfo() + { + var header = ImGui.CollapsingHeader("Global Variables"); + ImGuiUtil.HoverTooltip("Draw information about global variables. Can provide useful starting points for a memory viewer."); + if (!header) + return; + + DrawCopyableAddress("CharacterUtility", _characterUtility.Address); + DrawCopyableAddress("ResidentResourceManager", _residentResources.Address); + DrawCopyableAddress("Device", Device.Instance()); + } + /// Draw resources with unusual reference count. private unsafe void DrawResourceProblems() { From ec14efb789d28d2c8bdddf10e94ad474222d7c0d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 27 Aug 2023 04:04:14 +0200 Subject: [PATCH 0043/1381] Skin Fixer: Make resolving skin.shpk for new draw objects async --- Penumbra/Interop/Services/SkinFixer.cs | 28 +++++++++++++++----------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index 5ce35f29..479feafc 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; +using System.Threading.Tasks; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; @@ -102,20 +103,23 @@ public unsafe class SkinFixer : IDisposable if (((CharacterBase*)drawObject)->GetModelType() != CharacterBase.ModelType.Human) return; - nint skinShpk; - try + Task.Run(delegate { - var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - skinShpk = data.Valid ? (nint)_resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data) : nint.Zero; - } - catch (Exception e) - { - Penumbra.Log.Error($"Error while resolving skin.shpk for human {drawObject:X}: {e}"); - skinShpk = nint.Zero; - } + nint skinShpk; + try + { + var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + skinShpk = data.Valid ? (nint)_resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data) : nint.Zero; + } + catch (Exception e) + { + Penumbra.Log.Error($"Error while resolving skin.shpk for human {drawObject:X}: {e}"); + skinShpk = nint.Zero; + } - if (skinShpk != nint.Zero && _skinShpks.TryAdd(drawObject, skinShpk) && skinShpk != _utility.DefaultSkinShpkResource) - Interlocked.Increment(ref _moddedSkinShpkCount); + if (skinShpk != nint.Zero && _skinShpks.TryAdd(drawObject, skinShpk) && skinShpk != _utility.DefaultSkinShpkResource) + Interlocked.Increment(ref _moddedSkinShpkCount); + }); } private void OnCharacterBaseDestructor(nint characterBase) From 6c0864c8b9ae942566cc0d2f2368270c3eaeb98d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 28 Aug 2023 01:54:14 +0200 Subject: [PATCH 0044/1381] Textures: Add a matrix preset that drops alpha --- Penumbra/Import/Textures/CombinedTexture.Manipulation.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index b02ba7b7..c36c5065 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -110,6 +110,7 @@ public partial class CombinedTexture ("Grayscale (Weighted)", new Matrix4x4(RWeight, RWeight, RWeight, 0.0f, GWeight, GWeight, GWeight, 0.0f, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), Vector4.Zero ), ("Grayscale (Average) to Alpha", new Matrix4x4(OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, OneThird, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero ), ("Grayscale (Weighted) to Alpha", new Matrix4x4(RWeight, RWeight, RWeight, RWeight, GWeight, GWeight, GWeight, GWeight, BWeight, BWeight, BWeight, BWeight, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.Zero ), + ("Make Opaque (Drop Alpha)", new Matrix4x4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), ("Extract Red", new Matrix4x4(1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), ("Extract Green", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), ("Extract Blue", new Matrix4x4(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f), Vector4.UnitW ), From ffb8f0e8d3530e24a4406ebb44e459bb07cfc56e Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 28 Aug 2023 03:06:18 +0200 Subject: [PATCH 0045/1381] =?UTF-8?q?Material=20editor:=20Allow=20negative?= =?UTF-8?q?s=20again=20with=20R=C2=B2G=C2=B2B=C2=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit There seems to be people using it. --- .../ModEditWindow.Materials.ColorSet.cs | 26 ++++++++++++++++--- .../ModEditWindow.Materials.ConstantEditor.cs | 8 +++--- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs index 798939ca..daca1098 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs @@ -483,13 +483,13 @@ public partial class ModEditWindow private static bool ColorPicker( string label, string tooltip, Vector3 input, Action< Vector3 > setter, string letter = "" ) { var ret = false; - var inputSqrt = Vector3.SquareRoot( input ); + var inputSqrt = PseudoSqrtRgb( input ); var tmp = inputSqrt; if( ImGui.ColorEdit3( label, ref tmp, - ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.DisplayRGB | ImGuiColorEditFlags.InputRGB | ImGuiColorEditFlags.NoTooltip ) + ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.DisplayRGB | ImGuiColorEditFlags.InputRGB | ImGuiColorEditFlags.NoTooltip | ImGuiColorEditFlags.HDR ) && tmp != inputSqrt ) { - setter( tmp * tmp ); + setter( PseudoSquareRgb( tmp ) ); ret = true; } @@ -505,4 +505,24 @@ public partial class ModEditWindow return ret; } + + // Functions to deal with squared RGB values without making negatives useless. + + private static float PseudoSquareRgb(float x) + => x < 0.0f ? -(x * x) : (x * x); + + private static Vector3 PseudoSquareRgb(Vector3 vec) + => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z)); + + private static Vector4 PseudoSquareRgb(Vector4 vec) + => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z), vec.W); + + private static float PseudoSqrtRgb(float x) + => x < 0.0f ? -MathF.Sqrt(-x) : MathF.Sqrt(x); + + private static Vector3 PseudoSqrtRgb(Vector3 vec) + => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z)); + + private static Vector4 PseudoSqrtRgb(Vector4 vec) + => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z), vec.W); } \ No newline at end of file diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs index f7ea317d..8a104145 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -147,11 +147,11 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(editorWidth); var value = new Vector3(values); if (_squaredRgb) - value = Vector3.SquareRoot(value); + value = PseudoSqrtRgb(value); if (ImGui.ColorEdit3("##0", ref value, ImGuiColorEditFlags.Float | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) && !disabled) { if (_squaredRgb) - value *= value; + value = PseudoSquareRgb(value); if (_clamped) value = Vector3.Clamp(value, Vector3.Zero, Vector3.One); value.CopyTo(values); @@ -165,11 +165,11 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(editorWidth); var value = new Vector4(values); if (_squaredRgb) - value = new Vector4(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z), value.W); + value = PseudoSqrtRgb(value); if (ImGui.ColorEdit4("##0", ref value, ImGuiColorEditFlags.Float | ImGuiColorEditFlags.AlphaPreviewHalf | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) && !disabled) { if (_squaredRgb) - value *= new Vector4(value.X, value.Y, value.Z, 1.0f); + value = PseudoSquareRgb(value); if (_clamped) value = Vector4.Clamp(value, Vector4.Zero, Vector4.One); value.CopyTo(values); From f54146ada43d118c64392b83c77145659769574f Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 28 Aug 2023 03:30:21 +0200 Subject: [PATCH 0046/1381] Textures: PR #327 feedback --- .../Textures/CombinedTexture.Manipulation.cs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index c36c5065..57749471 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -249,12 +249,10 @@ public partial class CombinedTexture if (sourceWidth == _targetWidth && sourceHeight == _targetHeight) return rgbaPixels; - byte[] resizedPixels; + var resizedPixels = new byte[_targetWidth * _targetHeight * 4]; using (var image = Image.LoadPixelData(rgbaPixels, sourceWidth, sourceHeight)) { - image.Mutate(ctx => ctx.Resize(_targetWidth, _targetHeight)); - - resizedPixels = new byte[_targetWidth * _targetHeight * 4]; + image.Mutate(ctx => ctx.Resize(_targetWidth, _targetHeight, KnownResamplers.Lanczos3)); image.CopyPixelDataTo(resizedPixels); } @@ -267,9 +265,13 @@ public partial class CombinedTexture var combineOp = GetActualCombineOp(); var (usesLeft, usesRight) = GetCombineOpFlags(combineOp); var resizeOp = usesLeft && usesRight ? _resizeOp : ResizeOp.None; - (_targetWidth, _targetHeight) = usesLeft && resizeOp != ResizeOp.ToRight - ? (_left.TextureWrap!.Width, _left.TextureWrap!.Height) - : (_right.TextureWrap!.Width, _right.TextureWrap!.Height); + (_targetWidth, _targetHeight) = resizeOp switch + { + ResizeOp.ToLeft => (_left.TextureWrap!.Width, _left.TextureWrap!.Height), + ResizeOp.ToRight => (_right.TextureWrap!.Width, _right.TextureWrap!.Height), + ResizeOp.None when usesLeft => (_left.TextureWrap!.Width, _left.TextureWrap!.Height), + _ => (_right.TextureWrap!.Width, _right.TextureWrap!.Height), + }; _centerStorage.RgbaPixels = new byte[_targetWidth * _targetHeight * 4]; _centerStorage.Type = TextureType.Bitmap; try From 598f3db06aada150dad03ff61314538e8ef19646 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 29 Aug 2023 00:42:59 +0200 Subject: [PATCH 0047/1381] Textures: PR #327 feedback --- Penumbra/Import/Textures/CombinedTexture.Manipulation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 57749471..eb8db121 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -277,7 +277,7 @@ public partial class CombinedTexture try { if (usesLeft) - _leftPixels = (resizeOp == ResizeOp.ToRight) ? ResizePixels(_left.RgbaPixels, _left.TextureWrap!.Width, _left.TextureWrap!.Height) : _left.RgbaPixels; + _leftPixels = ResizePixels(_left.RgbaPixels, _left.TextureWrap!.Width, _left.TextureWrap!.Height); if (usesRight) (_rightWidth, _rightHeight, _rightPixels) = (resizeOp == ResizeOp.ToLeft) ? (_targetWidth, _targetHeight, ResizePixels(_right.RgbaPixels, _right.TextureWrap!.Width, _right.TextureWrap!.Height)) From 848e4ff8a649292656be3cad613713a20d8b03ef Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 29 Aug 2023 03:25:54 +0200 Subject: [PATCH 0048/1381] Textures: Refactor resizing code --- .../Textures/CombinedTexture.Manipulation.cs | 168 +++++++++++------- 1 file changed, 99 insertions(+), 69 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index eb8db121..3c0e8193 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -10,6 +10,7 @@ using Dalamud.Interface; using Penumbra.UI; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; +using System.Linq; namespace Penumbra.Import.Textures; @@ -29,9 +30,11 @@ public partial class CombinedTexture private enum ResizeOp { - None = 0, - ToLeft = 1, - ToRight = 2, + LeftOnly = -2, + RightOnly = -1, + None = 0, + ToLeft = 1, + ToRight = 2, } [Flags] @@ -43,6 +46,38 @@ public partial class CombinedTexture Alpha = 8, } + private readonly record struct RgbaPixelData(int Width, int Height, byte[] PixelData) + { + public static readonly RgbaPixelData Empty = new(0, 0, Array.Empty()); + + public (int Width, int Height) Size + => (Width, Height); + + public Image ToImage() + => Image.LoadPixelData(PixelData, Width, Height); + + public RgbaPixelData Resize((int Width, int Height) size) + { + if (Width == size.Width && Height == size.Height) + return this; + + var result = WithNewPixelData(size); + using (var image = ToImage()) + { + image.Mutate(ctx => ctx.Resize(size.Width, size.Height, KnownResamplers.Lanczos3)); + image.CopyPixelDataTo(result.PixelData); + } + + return result; + } + + public static RgbaPixelData WithNewPixelData((int Width, int Height) size) + => new(size.Width, size.Height, new byte[size.Width * size.Height * 4]); + + public static RgbaPixelData FromTexture(Texture texture) + => new(texture.TextureWrap!.Width, texture.TextureWrap!.Height, texture.RgbaPixels); + } + private Matrix4x4 _multiplierLeft = Matrix4x4.Identity; private Vector4 _constantLeft = Vector4.Zero; private Matrix4x4 _multiplierRight = Matrix4x4.Identity; @@ -53,12 +88,9 @@ public partial class CombinedTexture private ResizeOp _resizeOp = ResizeOp.None; private Channels _copyChannels = Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha; - private int _rightWidth = 0; - private int _rightHeight = 0; - private int _targetWidth = 0; - private int _targetHeight = 0; - private byte[] _leftPixels = Array.Empty(); - private byte[] _rightPixels = Array.Empty(); + private RgbaPixelData _targetPixels = RgbaPixelData.Empty; + private RgbaPixelData _leftPixels = RgbaPixelData.Empty; + private RgbaPixelData _rightPixels = RgbaPixelData.Empty; private static readonly IReadOnlyList CombineOpLabels = new string[] { @@ -76,16 +108,16 @@ public partial class CombinedTexture "Replace some input channels with those from the overlay.\nUseful for Multi maps.", }; - private static (bool UsesLeft, bool UsesRight) GetCombineOpFlags(CombineOp combineOp) + private static ResizeOp GetActualResizeOp(ResizeOp resizeOp, CombineOp combineOp) => combineOp switch { - CombineOp.LeftCopy => (true, false), - CombineOp.LeftMultiply => (true, false), - CombineOp.RightCopy => (false, true), - CombineOp.RightMultiply => (false, true), - CombineOp.Over => (true, true), - CombineOp.Under => (true, true), - CombineOp.CopyChannels => (true, true), + CombineOp.LeftCopy => ResizeOp.LeftOnly, + CombineOp.LeftMultiply => ResizeOp.LeftOnly, + CombineOp.RightCopy => ResizeOp.RightOnly, + CombineOp.RightMultiply => ResizeOp.RightOnly, + CombineOp.Over => resizeOp, + CombineOp.Under => resizeOp, + CombineOp.CopyChannels => resizeOp, _ => throw new ArgumentException($"Invalid combine operation {combineOp}"), }; @@ -145,27 +177,27 @@ public partial class CombinedTexture } private Vector4 DataLeft(int offset) - => CappedVector(_leftPixels, offset, _multiplierLeft, _constantLeft); + => CappedVector(_leftPixels.PixelData, offset, _multiplierLeft, _constantLeft); private Vector4 DataRight(int offset) - => CappedVector(_rightPixels, offset, _multiplierRight, _constantRight); + => CappedVector(_rightPixels.PixelData, offset, _multiplierRight, _constantRight); private Vector4 DataRight(int x, int y) { x += _offsetX; y += _offsetY; - if (x < 0 || x >= _rightWidth || y < 0 || y >= _rightHeight) + if (x < 0 || x >= _rightPixels.Width || y < 0 || y >= _rightPixels.Height) return Vector4.Zero; - var offset = (y * _rightWidth + x) * 4; - return CappedVector(_rightPixels, offset, _multiplierRight, _constantRight); + var offset = (y * _rightPixels.Width + x) * 4; + return CappedVector(_rightPixels.PixelData, offset, _multiplierRight, _constantRight); } private void AddPixelsMultiplied(int y, ParallelLoopState _) { - for (var x = 0; x < _targetWidth; ++x) + for (var x = 0; x < _targetPixels.Width; ++x) { - var offset = (_targetWidth * y + x) * 4; + var offset = (_targetPixels.Width * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var alpha = right.W + left.W * (1 - right.W); @@ -181,9 +213,9 @@ public partial class CombinedTexture private void ReverseAddPixelsMultiplied(int y, ParallelLoopState _) { - for (var x = 0; x < _targetWidth; ++x) + for (var x = 0; x < _targetPixels.Width; ++x) { - var offset = (_targetWidth * y + x) * 4; + var offset = (_targetPixels.Width * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var alpha = left.W + right.W * (1 - left.W); @@ -200,9 +232,9 @@ public partial class CombinedTexture private void ChannelMergePixelsMultiplied(int y, ParallelLoopState _) { var channels = _copyChannels; - for (var x = 0; x < _targetWidth; ++x) + for (var x = 0; x < _targetPixels.Width; ++x) { - var offset = (_targetWidth * y + x) * 4; + var offset = (_targetPixels.Width * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var rgba = new Rgba32((channels & Channels.Red) != 0 ? right.X : left.X, @@ -218,9 +250,9 @@ public partial class CombinedTexture private void MultiplyPixelsLeft(int y, ParallelLoopState _) { - for (var x = 0; x < _targetWidth; ++x) + for (var x = 0; x < _targetPixels.Width; ++x) { - var offset = (_targetWidth * y + x) * 4; + var offset = (_targetPixels.Width * y + x) * 4; var left = DataLeft(offset); var rgba = new Rgba32(left); _centerStorage.RgbaPixels[offset] = rgba.R; @@ -232,9 +264,9 @@ public partial class CombinedTexture private void MultiplyPixelsRight(int y, ParallelLoopState _) { - for (var x = 0; x < _targetWidth; ++x) + for (var x = 0; x < _targetPixels.Width; ++x) { - var offset = (_targetWidth * y + x) * 4; + var offset = (_targetPixels.Width * y + x) * 4; var right = DataRight(offset); var rgba = new Rgba32(right); _centerStorage.RgbaPixels[offset] = rgba.R; @@ -244,45 +276,42 @@ public partial class CombinedTexture } } - private byte[] ResizePixels(byte[] rgbaPixels, int sourceWidth, int sourceHeight) - { - if (sourceWidth == _targetWidth && sourceHeight == _targetHeight) - return rgbaPixels; - - var resizedPixels = new byte[_targetWidth * _targetHeight * 4]; - using (var image = Image.LoadPixelData(rgbaPixels, sourceWidth, sourceHeight)) - { - image.Mutate(ctx => ctx.Resize(_targetWidth, _targetHeight, KnownResamplers.Lanczos3)); - image.CopyPixelDataTo(resizedPixels); - } - - return resizedPixels; - } - private (int Width, int Height) CombineImage() { var combineOp = GetActualCombineOp(); - var (usesLeft, usesRight) = GetCombineOpFlags(combineOp); - var resizeOp = usesLeft && usesRight ? _resizeOp : ResizeOp.None; - (_targetWidth, _targetHeight) = resizeOp switch + var resizeOp = GetActualResizeOp(_resizeOp, combineOp); + + var left = resizeOp != ResizeOp.RightOnly ? RgbaPixelData.FromTexture(_left) : RgbaPixelData.Empty; + var right = resizeOp != ResizeOp.LeftOnly ? RgbaPixelData.FromTexture(_right) : RgbaPixelData.Empty; + + var targetSize = resizeOp switch { - ResizeOp.ToLeft => (_left.TextureWrap!.Width, _left.TextureWrap!.Height), - ResizeOp.ToRight => (_right.TextureWrap!.Width, _right.TextureWrap!.Height), - ResizeOp.None when usesLeft => (_left.TextureWrap!.Width, _left.TextureWrap!.Height), - _ => (_right.TextureWrap!.Width, _right.TextureWrap!.Height), + ResizeOp.RightOnly => right.Size, + ResizeOp.ToRight => right.Size, + _ => left.Size, }; - _centerStorage.RgbaPixels = new byte[_targetWidth * _targetHeight * 4]; - _centerStorage.Type = TextureType.Bitmap; + try { - if (usesLeft) - _leftPixels = ResizePixels(_left.RgbaPixels, _left.TextureWrap!.Width, _left.TextureWrap!.Height); - if (usesRight) - (_rightWidth, _rightHeight, _rightPixels) = (resizeOp == ResizeOp.ToLeft) - ? (_targetWidth, _targetHeight, ResizePixels(_right.RgbaPixels, _right.TextureWrap!.Width, _right.TextureWrap!.Height)) - : (_right.TextureWrap!.Width, _right.TextureWrap!.Height, _right.RgbaPixels); - Parallel.For(0, _targetHeight, combineOp switch + _targetPixels = RgbaPixelData.WithNewPixelData(targetSize); + + _centerStorage.RgbaPixels = _targetPixels.PixelData; + _centerStorage.Type = TextureType.Bitmap; + + _leftPixels = resizeOp switch + { + ResizeOp.RightOnly => RgbaPixelData.Empty, + _ => left.Resize(targetSize), + }; + _rightPixels = resizeOp switch + { + ResizeOp.LeftOnly => RgbaPixelData.Empty, + ResizeOp.None => right, + _ => right.Resize(targetSize), + }; + + Parallel.For(0, _targetPixels.Height, combineOp switch { CombineOp.Over => AddPixelsMultiplied, CombineOp.Under => ReverseAddPixelsMultiplied, @@ -294,11 +323,12 @@ public partial class CombinedTexture } finally { - _leftPixels = Array.Empty(); - _rightPixels = Array.Empty(); + _leftPixels = RgbaPixelData.Empty; + _rightPixels = RgbaPixelData.Empty; + _targetPixels = RgbaPixelData.Empty; } - return (_targetWidth, _targetHeight); + return targetSize; } private static Vector4 CappedVector(IReadOnlyList bytes, int offset, Matrix4x4 transform, Vector4 constant) @@ -367,11 +397,11 @@ public partial class CombinedTexture } } - var (usesLeft, usesRight) = GetCombineOpFlags(_combineOp); - using (var dis = ImRaii.Disabled(!usesLeft || !usesRight)) + var resizeOp = GetActualResizeOp(_resizeOp, _combineOp); + using (var dis = ImRaii.Disabled((int)resizeOp < 0)) { ret |= ImGuiUtil.GenericEnumCombo("Resizing Mode", 200.0f * UiHelpers.Scale, _resizeOp, out _resizeOp, - Enum.GetValues(), op => ResizeOpLabels[(int)op]); + Enum.GetValues().Where(op => (int)op >= 0), op => ResizeOpLabels[(int)op]); } using (var dis = ImRaii.Disabled(_combineOp != CombineOp.CopyChannels)) From bb8d9441f49ff69e190ae4a0708b37097aefe330 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 30 Aug 2023 01:14:20 +0200 Subject: [PATCH 0049/1381] Material editor: tweak colorset highlighting Make the frequency framerate-independent, set it to 1 Hz, and decrease the dynamic range. Thanks @StoiaCode for feedback! --- .../ModEditWindow.Materials.MtrlTab.cs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 17f34b64..9061cc98 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; @@ -74,7 +75,7 @@ public partial class ModEditWindow public readonly List MaterialPreviewers = new(4); public readonly List ColorSetPreviewers = new(4); public int HighlightedColorSetRow = -1; - public int HighlightTime = -1; + public readonly Stopwatch HighlightTime = new(); public FullPath FindAssociatedShpk( out string defaultPath, out Utf8GamePath defaultGamePath ) { @@ -546,8 +547,11 @@ public partial class ModEditWindow { var oldRowIdx = HighlightedColorSetRow; - HighlightedColorSetRow = rowIdx; - HighlightTime = (HighlightTime + 1) % 32; + if (HighlightedColorSetRow != rowIdx) + { + HighlightedColorSetRow = rowIdx; + HighlightTime.Restart(); + } if (oldRowIdx >= 0) UpdateColorSetRowPreview(oldRowIdx); @@ -560,7 +564,7 @@ public partial class ModEditWindow var rowIdx = HighlightedColorSetRow; HighlightedColorSetRow = -1; - HighlightTime = -1; + HighlightTime.Reset(); if (rowIdx >= 0) UpdateColorSetRowPreview(rowIdx); @@ -588,7 +592,7 @@ public partial class ModEditWindow } if (HighlightedColorSetRow == rowIdx) - ApplyHighlight(ref row, HighlightTime); + ApplyHighlight(ref row, (float)HighlightTime.Elapsed.TotalSeconds); foreach (var previewer in ColorSetPreviewers) { @@ -625,7 +629,7 @@ public partial class ModEditWindow } if (HighlightedColorSetRow >= 0) - ApplyHighlight(ref rows[HighlightedColorSetRow], HighlightTime); + ApplyHighlight(ref rows[HighlightedColorSetRow], (float)HighlightTime.Elapsed.TotalSeconds); foreach (var previewer in ColorSetPreviewers) { @@ -634,9 +638,9 @@ public partial class ModEditWindow } } - private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, int time) + private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, float time) { - var level = Math.Sin(time * Math.PI / 16) * 0.5 + 0.5; + var level = Math.Sin(time * 2.0 * Math.PI) * 0.25 + 0.5; var levelSq = (float)(level * level); row.Diffuse = Vector3.Zero; From 5346abaadf34171d81a0525f16e44d1437eb2a9b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 30 Aug 2023 01:51:43 +0200 Subject: [PATCH 0050/1381] Material editor: tear down previewers bound to a CharacterBase that goes away --- .../ModEditWindow.Materials.LivePreview.cs | 2 +- .../ModEditWindow.Materials.MtrlTab.cs | 28 +++++++++++++++++++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 5 +++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs index 7d400a71..76ac8915 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs @@ -154,7 +154,7 @@ public partial class ModEditWindow protected readonly int ModelSlot; protected readonly int MaterialSlot; - protected readonly CharacterBase* DrawObject; + public readonly CharacterBase* DrawObject; protected readonly Material* Material; protected bool Valid; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 9061cc98..6677db5b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -512,6 +512,29 @@ public partial class ModEditWindow ColorSetPreviewers.Clear(); } + public unsafe void UnbindFromDrawObjectMaterialInstances(nint characterBase) + { + for (var i = MaterialPreviewers.Count; i-- > 0; ) + { + var previewer = MaterialPreviewers[i]; + if ((nint)previewer.DrawObject != characterBase) + continue; + + previewer.Dispose(); + MaterialPreviewers.RemoveAt(i); + } + + for (var i = ColorSetPreviewers.Count; i-- > 0;) + { + var previewer = ColorSetPreviewers[i]; + if ((nint)previewer.DrawObject != characterBase) + continue; + + previewer.Dispose(); + ColorSetPreviewers.RemoveAt(i); + } + } + public void SetShaderPackageFlags(uint shPkFlags) { foreach (var previewer in MaterialPreviewers) @@ -665,7 +688,10 @@ public partial class ModEditWindow AssociatedBaseDevkit = TryLoadShpkDevkit( "_base", out LoadedBaseDevkitPathName ); LoadShpk( FindAssociatedShpk( out _, out _ ) ); if (writable) + { + _edit._gameEvents.CharacterBaseDestructor += UnbindFromDrawObjectMaterialInstances; BindToMaterialInstances(); + } } ~MtrlTab() @@ -682,6 +708,8 @@ public partial class ModEditWindow private void DoDispose() { UnbindFromMaterialInstances(); + if (Writable) + _edit._gameEvents.CharacterBaseDestructor -= UnbindFromDrawObjectMaterialInstances; } public bool Valid diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index f1c78bf7..e40a7915 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -19,6 +19,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.Import.Textures; using Penumbra.Interop.ResourceTree; +using Penumbra.Interop.Services; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -45,6 +46,7 @@ public partial class ModEditWindow : Window, IDisposable private readonly ModMergeTab _modMergeTab; private readonly CommunicatorService _communicator; private readonly IDragDropManager _dragDropManager; + private readonly GameEventManager _gameEvents; private Mod? _mod; private Vector2 _iconSize = Vector2.Zero; @@ -546,7 +548,7 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, - CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager) + CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, GameEventManager gameEvents) : base(WindowBaseLabel) { _performance = performance; @@ -562,6 +564,7 @@ public partial class ModEditWindow : Window, IDisposable _dragDropManager = dragDropManager; _textures = textures; _fileDialog = fileDialog; + _gameEvents = gameEvents; _materialTab = new FileEditor(this, gameData, config, _fileDialog, "Materials", ".mtrl", () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); From 38a22c5298865b44180a9a5d2f77809de5ae30ac Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 30 Aug 2023 02:51:36 +0200 Subject: [PATCH 0051/1381] Textures: Simplify away _targetPixels --- .../Textures/CombinedTexture.Manipulation.cs | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 3c0e8193..1633de62 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -53,6 +53,11 @@ public partial class CombinedTexture public (int Width, int Height) Size => (Width, Height); + public RgbaPixelData((int Width, int Height) size, byte[] pixelData) + : this(size.Width, size.Height, pixelData) + { + } + public Image ToImage() => Image.LoadPixelData(PixelData, Width, Height); @@ -61,7 +66,7 @@ public partial class CombinedTexture if (Width == size.Width && Height == size.Height) return this; - var result = WithNewPixelData(size); + var result = new RgbaPixelData(size, NewPixelData(size)); using (var image = ToImage()) { image.Mutate(ctx => ctx.Resize(size.Width, size.Height, KnownResamplers.Lanczos3)); @@ -71,8 +76,8 @@ public partial class CombinedTexture return result; } - public static RgbaPixelData WithNewPixelData((int Width, int Height) size) - => new(size.Width, size.Height, new byte[size.Width * size.Height * 4]); + public static byte[] NewPixelData((int Width, int Height) size) + => new byte[size.Width * size.Height * 4]; public static RgbaPixelData FromTexture(Texture texture) => new(texture.TextureWrap!.Width, texture.TextureWrap!.Height, texture.RgbaPixels); @@ -88,9 +93,8 @@ public partial class CombinedTexture private ResizeOp _resizeOp = ResizeOp.None; private Channels _copyChannels = Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha; - private RgbaPixelData _targetPixels = RgbaPixelData.Empty; - private RgbaPixelData _leftPixels = RgbaPixelData.Empty; - private RgbaPixelData _rightPixels = RgbaPixelData.Empty; + private RgbaPixelData _leftPixels = RgbaPixelData.Empty; + private RgbaPixelData _rightPixels = RgbaPixelData.Empty; private static readonly IReadOnlyList CombineOpLabels = new string[] { @@ -195,9 +199,9 @@ public partial class CombinedTexture private void AddPixelsMultiplied(int y, ParallelLoopState _) { - for (var x = 0; x < _targetPixels.Width; ++x) + for (var x = 0; x < _leftPixels.Width; ++x) { - var offset = (_targetPixels.Width * y + x) * 4; + var offset = (_leftPixels.Width * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var alpha = right.W + left.W * (1 - right.W); @@ -213,9 +217,9 @@ public partial class CombinedTexture private void ReverseAddPixelsMultiplied(int y, ParallelLoopState _) { - for (var x = 0; x < _targetPixels.Width; ++x) + for (var x = 0; x < _leftPixels.Width; ++x) { - var offset = (_targetPixels.Width * y + x) * 4; + var offset = (_leftPixels.Width * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var alpha = left.W + right.W * (1 - left.W); @@ -232,9 +236,9 @@ public partial class CombinedTexture private void ChannelMergePixelsMultiplied(int y, ParallelLoopState _) { var channels = _copyChannels; - for (var x = 0; x < _targetPixels.Width; ++x) + for (var x = 0; x < _leftPixels.Width; ++x) { - var offset = (_targetPixels.Width * y + x) * 4; + var offset = (_leftPixels.Width * y + x) * 4; var left = DataLeft(offset); var right = DataRight(x, y); var rgba = new Rgba32((channels & Channels.Red) != 0 ? right.X : left.X, @@ -250,9 +254,9 @@ public partial class CombinedTexture private void MultiplyPixelsLeft(int y, ParallelLoopState _) { - for (var x = 0; x < _targetPixels.Width; ++x) + for (var x = 0; x < _leftPixels.Width; ++x) { - var offset = (_targetPixels.Width * y + x) * 4; + var offset = (_leftPixels.Width * y + x) * 4; var left = DataLeft(offset); var rgba = new Rgba32(left); _centerStorage.RgbaPixels[offset] = rgba.R; @@ -264,9 +268,9 @@ public partial class CombinedTexture private void MultiplyPixelsRight(int y, ParallelLoopState _) { - for (var x = 0; x < _targetPixels.Width; ++x) + for (var x = 0; x < _rightPixels.Width; ++x) { - var offset = (_targetPixels.Width * y + x) * 4; + var offset = (_rightPixels.Width * y + x) * 4; var right = DataRight(offset); var rgba = new Rgba32(right); _centerStorage.RgbaPixels[offset] = rgba.R; @@ -294,9 +298,7 @@ public partial class CombinedTexture try { - _targetPixels = RgbaPixelData.WithNewPixelData(targetSize); - - _centerStorage.RgbaPixels = _targetPixels.PixelData; + _centerStorage.RgbaPixels = RgbaPixelData.NewPixelData(targetSize); _centerStorage.Type = TextureType.Bitmap; _leftPixels = resizeOp switch @@ -311,7 +313,7 @@ public partial class CombinedTexture _ => right.Resize(targetSize), }; - Parallel.For(0, _targetPixels.Height, combineOp switch + Parallel.For(0, targetSize.Height, combineOp switch { CombineOp.Over => AddPixelsMultiplied, CombineOp.Under => ReverseAddPixelsMultiplied, @@ -325,7 +327,6 @@ public partial class CombinedTexture { _leftPixels = RgbaPixelData.Empty; _rightPixels = RgbaPixelData.Empty; - _targetPixels = RgbaPixelData.Empty; } return targetSize; From 600f5987cda4f9e345fdb17830d500acffd52f93 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 30 Aug 2023 17:25:26 +0200 Subject: [PATCH 0052/1381] Slight restructuring. --- .../Textures/CombinedTexture.Manipulation.cs | 230 ++---------------- .../Textures/CombinedTexture.Operations.cs | 150 ++++++++++++ Penumbra/Import/Textures/RgbaPixelData.cs | 43 ++++ 3 files changed, 219 insertions(+), 204 deletions(-) create mode 100644 Penumbra/Import/Textures/CombinedTexture.Operations.cs create mode 100644 Penumbra/Import/Textures/RgbaPixelData.cs diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 1633de62..9bc4a2a5 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -8,81 +8,12 @@ using OtterGui; using SixLabors.ImageSharp.PixelFormats; using Dalamud.Interface; using Penumbra.UI; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Processing; using System.Linq; namespace Penumbra.Import.Textures; public partial class CombinedTexture { - private enum CombineOp - { - LeftMultiply = -4, - LeftCopy = -3, - RightCopy = -2, - Invalid = -1, - Over = 0, - Under = 1, - RightMultiply = 2, - CopyChannels = 3, - } - - private enum ResizeOp - { - LeftOnly = -2, - RightOnly = -1, - None = 0, - ToLeft = 1, - ToRight = 2, - } - - [Flags] - private enum Channels - { - Red = 1, - Green = 2, - Blue = 4, - Alpha = 8, - } - - private readonly record struct RgbaPixelData(int Width, int Height, byte[] PixelData) - { - public static readonly RgbaPixelData Empty = new(0, 0, Array.Empty()); - - public (int Width, int Height) Size - => (Width, Height); - - public RgbaPixelData((int Width, int Height) size, byte[] pixelData) - : this(size.Width, size.Height, pixelData) - { - } - - public Image ToImage() - => Image.LoadPixelData(PixelData, Width, Height); - - public RgbaPixelData Resize((int Width, int Height) size) - { - if (Width == size.Width && Height == size.Height) - return this; - - var result = new RgbaPixelData(size, NewPixelData(size)); - using (var image = ToImage()) - { - image.Mutate(ctx => ctx.Resize(size.Width, size.Height, KnownResamplers.Lanczos3)); - image.CopyPixelDataTo(result.PixelData); - } - - return result; - } - - public static byte[] NewPixelData((int Width, int Height) size) - => new byte[size.Width * size.Height * 4]; - - public static RgbaPixelData FromTexture(Texture texture) - => new(texture.TextureWrap!.Width, texture.TextureWrap!.Height, texture.RgbaPixels); - } - private Matrix4x4 _multiplierLeft = Matrix4x4.Identity; private Vector4 _constantLeft = Vector4.Zero; private Matrix4x4 _multiplierRight = Matrix4x4.Identity; @@ -96,42 +27,6 @@ public partial class CombinedTexture private RgbaPixelData _leftPixels = RgbaPixelData.Empty; private RgbaPixelData _rightPixels = RgbaPixelData.Empty; - private static readonly IReadOnlyList CombineOpLabels = new string[] - { - "Overlay over Input", - "Input over Overlay", - "Replace Input", - "Copy Channels", - }; - - private static readonly IReadOnlyList CombineOpTooltips = new string[] - { - "Standard composition.\nApply the overlay over the input.", - "Standard composition, reversed.\nApply the input over the overlay ; can be used to fix some wrong imports.", - "Completely replace the input with the overlay.\nCan be used to select the destination file as input and the source file as overlay.", - "Replace some input channels with those from the overlay.\nUseful for Multi maps.", - }; - - private static ResizeOp GetActualResizeOp(ResizeOp resizeOp, CombineOp combineOp) - => combineOp switch - { - CombineOp.LeftCopy => ResizeOp.LeftOnly, - CombineOp.LeftMultiply => ResizeOp.LeftOnly, - CombineOp.RightCopy => ResizeOp.RightOnly, - CombineOp.RightMultiply => ResizeOp.RightOnly, - CombineOp.Over => resizeOp, - CombineOp.Under => resizeOp, - CombineOp.CopyChannels => resizeOp, - _ => throw new ArgumentException($"Invalid combine operation {combineOp}"), - }; - - private static readonly IReadOnlyList ResizeOpLabels = new string[] - { - "No Resizing", - "Adjust Overlay to Input", - "Adjust Input to Overlay", - }; - private const float OneThird = 1.0f / 3.0f; private const float RWeight = 0.2126f; private const float GWeight = 0.7152f; @@ -154,32 +49,6 @@ public partial class CombinedTexture }; // @formatter:on - private CombineOp GetActualCombineOp() - { - var combineOp = (_left.IsLoaded, _right.IsLoaded) switch - { - (true, true) => _combineOp, - (true, false) => CombineOp.LeftMultiply, - (false, true) => CombineOp.RightMultiply, - (false, false) => CombineOp.Invalid, - }; - - if (combineOp == CombineOp.CopyChannels) - { - if (_copyChannels == 0) - combineOp = CombineOp.LeftMultiply; - else if (_copyChannels == (Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha)) - combineOp = CombineOp.RightMultiply; - } - - return combineOp switch - { - CombineOp.LeftMultiply when _multiplierLeft.IsIdentity && _constantLeft == Vector4.Zero => CombineOp.LeftCopy, - CombineOp.RightMultiply when _multiplierRight.IsIdentity && _constantRight == Vector4.Zero => CombineOp.RightCopy, - _ => combineOp, - }; - } - private Vector4 DataLeft(int offset) => CappedVector(_leftPixels.PixelData, offset, _multiplierLeft, _constantLeft); @@ -280,11 +149,10 @@ public partial class CombinedTexture } } - private (int Width, int Height) CombineImage() { var combineOp = GetActualCombineOp(); - var resizeOp = GetActualResizeOp(_resizeOp, combineOp); + var resizeOp = GetActualResizeOp(_resizeOp, combineOp); var left = resizeOp != ResizeOp.RightOnly ? RgbaPixelData.FromTexture(_left) : RgbaPixelData.Empty; var right = resizeOp != ResizeOp.LeftOnly ? RgbaPixelData.FromTexture(_right) : RgbaPixelData.Empty; @@ -325,8 +193,8 @@ public partial class CombinedTexture } finally { - _leftPixels = RgbaPixelData.Empty; - _rightPixels = RgbaPixelData.Empty; + _leftPixels = RgbaPixelData.Empty; + _rightPixels = RgbaPixelData.Empty; } return targetSize; @@ -488,99 +356,53 @@ public partial class CombinedTexture private static bool DrawMatrixTools(ref Matrix4x4 multiplier, ref Vector4 constant) { - var changes = false; - - using (var combo = ImRaii.Combo("Presets", string.Empty, ImGuiComboFlags.NoPreview)) - { - if (combo) - foreach (var (label, preMultiplier, preConstant) in PredefinedColorTransforms) - { - if (ImGui.Selectable(label, multiplier == preMultiplier && constant == preConstant)) - { - multiplier = preMultiplier; - constant = preConstant; - changes = true; - } - } - } - + var changes = PresetCombo(ref multiplier, ref constant); ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); ImGui.TextUnformatted("Invert"); ImGui.SameLine(); - if (ImGui.Button("Colors")) - { - InvertRed(ref multiplier, ref constant); - InvertGreen(ref multiplier, ref constant); - InvertBlue(ref multiplier, ref constant); - changes = true; - } + Channels channels = 0; + if (ImGui.Button("Colors")) + channels |= Channels.Red | Channels.Green | Channels.Blue; ImGui.SameLine(); if (ImGui.Button("R")) - { - InvertRed(ref multiplier, ref constant); - changes = true; - } + channels |= Channels.Red; ImGui.SameLine(); if (ImGui.Button("G")) - { - InvertGreen(ref multiplier, ref constant); - changes = true; - } + channels |= Channels.Green; ImGui.SameLine(); if (ImGui.Button("B")) - { - InvertBlue(ref multiplier, ref constant); - changes = true; - } + channels |= Channels.Blue; ImGui.SameLine(); if (ImGui.Button("A")) - { - InvertAlpha(ref multiplier, ref constant); - changes = true; - } + channels |= Channels.Alpha; + changes |= InvertChannels(channels, ref multiplier, ref constant); return changes; } - private static void InvertRed(ref Matrix4x4 multiplier, ref Vector4 constant) + private static bool PresetCombo(ref Matrix4x4 multiplier, ref Vector4 constant) { - multiplier.M11 = -multiplier.M11; - multiplier.M21 = -multiplier.M21; - multiplier.M31 = -multiplier.M31; - multiplier.M41 = -multiplier.M41; - constant.X = 1.0f - constant.X; - } + using var combo = ImRaii.Combo("Presets", string.Empty, ImGuiComboFlags.NoPreview); + if (!combo) + return false; - private static void InvertGreen(ref Matrix4x4 multiplier, ref Vector4 constant) - { - multiplier.M12 = -multiplier.M12; - multiplier.M22 = -multiplier.M22; - multiplier.M32 = -multiplier.M32; - multiplier.M42 = -multiplier.M42; - constant.Y = 1.0f - constant.Y; - } + var ret = false; + foreach (var (label, preMultiplier, preConstant) in PredefinedColorTransforms) + { + if (!ImGui.Selectable(label, multiplier == preMultiplier && constant == preConstant)) + continue; - private static void InvertBlue(ref Matrix4x4 multiplier, ref Vector4 constant) - { - multiplier.M13 = -multiplier.M13; - multiplier.M23 = -multiplier.M23; - multiplier.M33 = -multiplier.M33; - multiplier.M43 = -multiplier.M43; - constant.Z = 1.0f - constant.Z; - } + multiplier = preMultiplier; + constant = preConstant; + ret = true; + } - private static void InvertAlpha(ref Matrix4x4 multiplier, ref Vector4 constant) - { - multiplier.M14 = -multiplier.M14; - multiplier.M24 = -multiplier.M24; - multiplier.M34 = -multiplier.M34; - multiplier.M44 = -multiplier.M44; - constant.W = 1.0f - constant.W; + return ret; } } diff --git a/Penumbra/Import/Textures/CombinedTexture.Operations.cs b/Penumbra/Import/Textures/CombinedTexture.Operations.cs new file mode 100644 index 00000000..441cd3f0 --- /dev/null +++ b/Penumbra/Import/Textures/CombinedTexture.Operations.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +namespace Penumbra.Import.Textures; + +public partial class CombinedTexture +{ + private enum CombineOp + { + LeftMultiply = -4, + LeftCopy = -3, + RightCopy = -2, + Invalid = -1, + Over = 0, + Under = 1, + RightMultiply = 2, + CopyChannels = 3, + } + + private enum ResizeOp + { + LeftOnly = -2, + RightOnly = -1, + None = 0, + ToLeft = 1, + ToRight = 2, + } + + [Flags] + private enum Channels : byte + { + Red = 1, + Green = 2, + Blue = 4, + Alpha = 8, + } + + private static readonly IReadOnlyList CombineOpLabels = new[] + { + "Overlay over Input", + "Input over Overlay", + "Replace Input", + "Copy Channels", + }; + + private static readonly IReadOnlyList CombineOpTooltips = new[] + { + "Standard composition.\nApply the overlay over the input.", + "Standard composition, reversed.\nApply the input over the overlay ; can be used to fix some wrong imports.", + "Completely replace the input with the overlay.\nCan be used to select the destination file as input and the source file as overlay.", + "Replace some input channels with those from the overlay.\nUseful for Multi maps.", + }; + + private static readonly IReadOnlyList ResizeOpLabels = new string[] + { + "No Resizing", + "Adjust Overlay to Input", + "Adjust Input to Overlay", + }; + + private static ResizeOp GetActualResizeOp(ResizeOp resizeOp, CombineOp combineOp) + => combineOp switch + { + CombineOp.LeftCopy => ResizeOp.LeftOnly, + CombineOp.LeftMultiply => ResizeOp.LeftOnly, + CombineOp.RightCopy => ResizeOp.RightOnly, + CombineOp.RightMultiply => ResizeOp.RightOnly, + CombineOp.Over => resizeOp, + CombineOp.Under => resizeOp, + CombineOp.CopyChannels => resizeOp, + _ => throw new ArgumentException($"Invalid combine operation {combineOp}"), + }; + + private CombineOp GetActualCombineOp() + { + var combineOp = (_left.IsLoaded, _right.IsLoaded) switch + { + (true, true) => _combineOp, + (true, false) => CombineOp.LeftMultiply, + (false, true) => CombineOp.RightMultiply, + (false, false) => CombineOp.Invalid, + }; + + if (combineOp == CombineOp.CopyChannels) + { + if (_copyChannels == 0) + combineOp = CombineOp.LeftMultiply; + else if (_copyChannels == (Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha)) + combineOp = CombineOp.RightMultiply; + } + + return combineOp switch + { + CombineOp.LeftMultiply when _multiplierLeft.IsIdentity && _constantLeft == Vector4.Zero => CombineOp.LeftCopy, + CombineOp.RightMultiply when _multiplierRight.IsIdentity && _constantRight == Vector4.Zero => CombineOp.RightCopy, + _ => combineOp, + }; + } + + + private static bool InvertChannels(Channels channels, ref Matrix4x4 multiplier, ref Vector4 constant) + { + if (channels.HasFlag(Channels.Red)) + InvertRed(ref multiplier, ref constant); + if (channels.HasFlag(Channels.Green)) + InvertGreen(ref multiplier, ref constant); + if (channels.HasFlag(Channels.Blue)) + InvertBlue(ref multiplier, ref constant); + if (channels.HasFlag(Channels.Alpha)) + InvertAlpha(ref multiplier, ref constant); + return channels != 0; + } + + private static void InvertRed(ref Matrix4x4 multiplier, ref Vector4 constant) + { + multiplier.M11 = -multiplier.M11; + multiplier.M21 = -multiplier.M21; + multiplier.M31 = -multiplier.M31; + multiplier.M41 = -multiplier.M41; + constant.X = 1.0f - constant.X; + } + + private static void InvertGreen(ref Matrix4x4 multiplier, ref Vector4 constant) + { + multiplier.M12 = -multiplier.M12; + multiplier.M22 = -multiplier.M22; + multiplier.M32 = -multiplier.M32; + multiplier.M42 = -multiplier.M42; + constant.Y = 1.0f - constant.Y; + } + + private static void InvertBlue(ref Matrix4x4 multiplier, ref Vector4 constant) + { + multiplier.M13 = -multiplier.M13; + multiplier.M23 = -multiplier.M23; + multiplier.M33 = -multiplier.M33; + multiplier.M43 = -multiplier.M43; + constant.Z = 1.0f - constant.Z; + } + + private static void InvertAlpha(ref Matrix4x4 multiplier, ref Vector4 constant) + { + multiplier.M14 = -multiplier.M14; + multiplier.M24 = -multiplier.M24; + multiplier.M34 = -multiplier.M34; + multiplier.M44 = -multiplier.M44; + constant.W = 1.0f - constant.W; + } +} diff --git a/Penumbra/Import/Textures/RgbaPixelData.cs b/Penumbra/Import/Textures/RgbaPixelData.cs new file mode 100644 index 00000000..0314b104 --- /dev/null +++ b/Penumbra/Import/Textures/RgbaPixelData.cs @@ -0,0 +1,43 @@ +using System; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; + +namespace Penumbra.Import.Textures; + +public readonly record struct RgbaPixelData(int Width, int Height, byte[] PixelData) +{ + public static readonly RgbaPixelData Empty = new(0, 0, Array.Empty()); + + public (int Width, int Height) Size + => (Width, Height); + + public RgbaPixelData((int Width, int Height) size, byte[] pixelData) + : this(size.Width, size.Height, pixelData) + { + } + + public Image ToImage() + => Image.LoadPixelData(PixelData, Width, Height); + + public RgbaPixelData Resize((int Width, int Height) size) + { + if (Width == size.Width && Height == size.Height) + return this; + + var result = new RgbaPixelData(size, NewPixelData(size)); + using (var image = ToImage()) + { + image.Mutate(ctx => ctx.Resize(size.Width, size.Height, KnownResamplers.Lanczos3)); + image.CopyPixelDataTo(result.PixelData); + } + + return result; + } + + public static byte[] NewPixelData((int Width, int Height) size) + => new byte[size.Width * size.Height * 4]; + + public static RgbaPixelData FromTexture(Texture texture) + => new(texture.TextureWrap!.Width, texture.TextureWrap!.Height, texture.RgbaPixels); +} From f23804975004b9841e99a3f77aa8149425be9581 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 30 Aug 2023 19:16:22 +0200 Subject: [PATCH 0053/1381] Skin Fixer: Fix potential ref leak + add SRH `SafeResourceHandle` wraps a `ResourceHandle*` with auto `IncRef` / `DecRef`, to further help prevent leaks. --- .../Interop/SafeHandles/SafeResourceHandle.cs | 34 ++++++++++++++++ Penumbra/Interop/Services/SkinFixer.cs | 40 ++++++++++++------- 2 files changed, 60 insertions(+), 14 deletions(-) create mode 100644 Penumbra/Interop/SafeHandles/SafeResourceHandle.cs diff --git a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs new file mode 100644 index 00000000..7ec0f218 --- /dev/null +++ b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; + +namespace Penumbra.Interop.SafeHandles; + +public unsafe class SafeResourceHandle : SafeHandle +{ + public ResourceHandle* ResourceHandle => (ResourceHandle*)handle; + + public override bool IsInvalid => handle == 0; + + public SafeResourceHandle(ResourceHandle* handle, bool incRef, bool ownsHandle = true) : base(0, ownsHandle) + { + if (incRef && !ownsHandle) + throw new ArgumentException("Non-owning SafeResourceHandle with IncRef is unsupported"); + if (incRef && handle != null) + handle->IncRef(); + SetHandle((nint)handle); + } + + public static SafeResourceHandle CreateInvalid() + => new(null, incRef: false); + + protected override bool ReleaseHandle() + { + var handle = Interlocked.Exchange(ref this.handle, 0); + if (handle != 0) + ((ResourceHandle*)handle)->DecRef(); + + return true; + } +} diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index 479feafc..d72cedfb 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -14,6 +14,7 @@ using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.SafeHandles; using Penumbra.String.Classes; namespace Penumbra.Interop.Services; @@ -44,7 +45,7 @@ public unsafe class SkinFixer : IDisposable private readonly ResourceLoader _resources; private readonly CharacterUtility _utility; - private readonly ConcurrentDictionary _skinShpks = new(); + private readonly ConcurrentDictionary _skinShpks = new(); private readonly object _lock = new(); @@ -89,8 +90,7 @@ public unsafe class SkinFixer : IDisposable _gameEvents.CharacterBaseCreated -= OnCharacterBaseCreated; _gameEvents.CharacterBaseDestructor -= OnCharacterBaseDestructor; foreach (var skinShpk in _skinShpks.Values) - if (skinShpk != nint.Zero) - ((ResourceHandle*)skinShpk)->DecRef(); + skinShpk.Dispose(); _skinShpks.Clear(); _moddedSkinShpkCount = 0; } @@ -105,29 +105,41 @@ public unsafe class SkinFixer : IDisposable Task.Run(delegate { - nint skinShpk; + var skinShpk = SafeResourceHandle.CreateInvalid(); try { var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - skinShpk = data.Valid ? (nint)_resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data) : nint.Zero; + if (data.Valid) + { + var loadedShpk = _resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data); + skinShpk = new SafeResourceHandle((ResourceHandle*)loadedShpk, incRef: false); + } } catch (Exception e) { Penumbra.Log.Error($"Error while resolving skin.shpk for human {drawObject:X}: {e}"); - skinShpk = nint.Zero; } - if (skinShpk != nint.Zero && _skinShpks.TryAdd(drawObject, skinShpk) && skinShpk != _utility.DefaultSkinShpkResource) - Interlocked.Increment(ref _moddedSkinShpkCount); + if (!skinShpk.IsInvalid) + { + if (_skinShpks.TryAdd(drawObject, skinShpk)) + { + if ((nint)skinShpk.ResourceHandle != _utility.DefaultSkinShpkResource) + Interlocked.Increment(ref _moddedSkinShpkCount); + } + else + skinShpk.Dispose(); + } }); } private void OnCharacterBaseDestructor(nint characterBase) { - if (_skinShpks.Remove(characterBase, out var skinShpk) && skinShpk != nint.Zero) + if (_skinShpks.Remove(characterBase, out var skinShpk)) { - ((ResourceHandle*)skinShpk)->DecRef(); - if (skinShpk != _utility.DefaultSkinShpkResource) + var handle = skinShpk.ResourceHandle; + skinShpk.Dispose(); + if ((nint)handle != _utility.DefaultSkinShpkResource) Interlocked.Decrement(ref _moddedSkinShpkCount); } } @@ -136,12 +148,12 @@ public unsafe class SkinFixer : IDisposable { if (!_enabled || // Can be toggled on the debug tab. _moddedSkinShpkCount == 0 || // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. - !_skinShpks.TryGetValue(human, out var skinShpk) || skinShpk == nint.Zero) + !_skinShpks.TryGetValue(human, out var skinShpk)) return _onRenderMaterialHook!.Original(human, param); var material = param->Model->Materials[param->MaterialIndex]; var shpkResource = ((Structs.MtrlResource*)material->MaterialResourceHandle)->ShpkResourceHandle; - if ((nint)shpkResource != skinShpk) + if ((nint)shpkResource != (nint)skinShpk.ResourceHandle) return _onRenderMaterialHook!.Original(human, param); Interlocked.Increment(ref _slowPathCallDelta); @@ -154,7 +166,7 @@ public unsafe class SkinFixer : IDisposable lock (_lock) try { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)skinShpk; + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)skinShpk.ResourceHandle; return _onRenderMaterialHook!.Original(human, param); } finally From 6d3e93044072addf83169dde3f2c73433c5e2141 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 30 Aug 2023 20:52:21 +0200 Subject: [PATCH 0054/1381] Use better event in SkinFixer and some cleanup. --- Penumbra/Api/PenumbraApi.cs | 26 ++---- .../Communication/CreatedCharacterBase.cs | 14 ++-- Penumbra/Interop/PathResolving/MetaState.cs | 2 +- Penumbra/Interop/Services/SkinFixer.cs | 83 +++++++++---------- Penumbra/UI/Tabs/DebugTab.cs | 11 +-- 5 files changed, 57 insertions(+), 79 deletions(-) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 01078450..9d578190 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -85,26 +85,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi } } - public event CreatedCharacterBaseDelegate? CreatedCharacterBase - { - add - { - if (value == null) - return; - - CheckInitialized(); - _communicator.CreatedCharacterBase.Subscribe(new Action(value), - Communication.CreatedCharacterBase.Priority.Api); - } - remove - { - if (value == null) - return; - - CheckInitialized(); - _communicator.CreatedCharacterBase.Unsubscribe(new Action(value)); - } - } + public event CreatedCharacterBaseDelegate? CreatedCharacterBase; public bool Valid => _lumina != null; @@ -157,6 +138,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _resourceLoader.ResourceLoaded += OnResourceLoaded; _communicator.ModPathChanged.Subscribe(ModPathChangeSubscriber, ModPathChanged.Priority.Api); _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); + _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); } public unsafe void Dispose() @@ -167,6 +149,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _resourceLoader.ResourceLoaded -= OnResourceLoaded; _communicator.ModPathChanged.Unsubscribe(ModPathChangeSubscriber); _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); + _communicator.CreatedCharacterBase.Unsubscribe(OnCreatedCharacterBase); _lumina = null; _communicator = null!; _modManager = null!; @@ -1189,4 +1172,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, int _1, int _2, bool inherited) => ModSettingChanged?.Invoke(type, collection.Name, mod?.ModPath.Name ?? string.Empty, inherited); + + private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) + => CreatedCharacterBase?.Invoke(gameObject, collection.Name, drawObject); } diff --git a/Penumbra/Communication/CreatedCharacterBase.cs b/Penumbra/Communication/CreatedCharacterBase.cs index cbb86fc2..48ba86a5 100644 --- a/Penumbra/Communication/CreatedCharacterBase.cs +++ b/Penumbra/Communication/CreatedCharacterBase.cs @@ -1,26 +1,30 @@ using System; using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Collections; namespace Penumbra.Communication; /// /// Parameter is the game object for which a draw object is created. -/// Parameter is the name of the applied collection. +/// Parameter is the applied collection. /// Parameter is the created draw object. /// -public sealed class CreatedCharacterBase : EventWrapper, CreatedCharacterBase.Priority> +public sealed class CreatedCharacterBase : EventWrapper, CreatedCharacterBase.Priority> { public enum Priority { /// - Api = 0, + Api = int.MinValue, + + /// + SkinFixer = 0, } public CreatedCharacterBase() : base(nameof(CreatedCharacterBase)) { } - public void Invoke(nint gameObject, string appliedCollectionName, nint drawObject) - => Invoke(this, gameObject, appliedCollectionName, drawObject); + public void Invoke(nint gameObject, ModCollection appliedCollection, nint drawObject) + => Invoke(this, gameObject, appliedCollection, drawObject); } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index a4cbc967..1a257a96 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -142,7 +142,7 @@ public unsafe class MetaState : IDisposable _characterBaseCreateMetaChanges = DisposableContainer.Empty; if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero) _communicator.CreatedCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, - _lastCreatedCollection.ModCollection.Name, drawObject); + _lastCreatedCollection.ModCollection, drawObject); _lastCreatedCollection = ResolveData.Invalid; } diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index d72cedfb..be45708f 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -10,16 +10,18 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Penumbra.Collections; +using Penumbra.Communication; using Penumbra.GameData; using Penumbra.GameData.Enums; -using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.SafeHandles; +using Penumbra.Services; using Penumbra.String.Classes; namespace Penumbra.Interop.Services; -public unsafe class SkinFixer : IDisposable +public sealed unsafe class SkinFixer : IDisposable { public static readonly Utf8GamePath SkinShpkPath = Utf8GamePath.FromSpan("shader/sm5/shpk/skin.shpk"u8, out var p) ? p : Utf8GamePath.Empty; @@ -34,60 +36,48 @@ public unsafe class SkinFixer : IDisposable { [FieldOffset(0x0)] public Model* Model; + [FieldOffset(0x8)] public uint MaterialIndex; } private readonly Hook _onRenderMaterialHook; - private readonly CollectionResolver _collectionResolver; - private readonly GameEventManager _gameEvents; - private readonly ResourceLoader _resources; - private readonly CharacterUtility _utility; - - private readonly ConcurrentDictionary _skinShpks = new(); + private readonly GameEventManager _gameEvents; + private readonly CommunicatorService _communicator; + private readonly ResourceLoader _resources; + private readonly CharacterUtility _utility; + + // CharacterBase to ShpkHandle + private readonly ConcurrentDictionary _skinShpks = new(); private readonly object _lock = new(); - - private bool _enabled = true; + private int _moddedSkinShpkCount = 0; - private ulong _slowPathCallDelta = 0; - public bool Enabled - { - get => _enabled; - set => _enabled = value; - } + private ulong _slowPathCallDelta = 0; + + public bool Enabled { get; internal set; } = true; public int ModdedSkinShpkCount => _moddedSkinShpkCount; - public SkinFixer(CollectionResolver collectionResolver, GameEventManager gameEvents, ResourceLoader resources, CharacterUtility utility, DrawObjectState _) + public SkinFixer(GameEventManager gameEvents, ResourceLoader resources, CharacterUtility utility, CommunicatorService communicator) { SignatureHelper.Initialise(this); - _collectionResolver = collectionResolver; _gameEvents = gameEvents; _resources = resources; _utility = utility; + _communicator = communicator; _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); - _gameEvents.CharacterBaseCreated += OnCharacterBaseCreated; // The dependency on DrawObjectState shall ensure that this handler is registered after its one. + _communicator.CreatedCharacterBase.Subscribe(OnCharacterBaseCreated, CreatedCharacterBase.Priority.SkinFixer); _gameEvents.CharacterBaseDestructor += OnCharacterBaseDestructor; _onRenderMaterialHook.Enable(); } - ~SkinFixer() - { - Dispose(false); - } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - protected virtual void Dispose(bool disposing) { _onRenderMaterialHook.Dispose(); - _gameEvents.CharacterBaseCreated -= OnCharacterBaseCreated; + _communicator.CreatedCharacterBase.Unsubscribe(OnCharacterBaseCreated); _gameEvents.CharacterBaseDestructor -= OnCharacterBaseDestructor; foreach (var skinShpk in _skinShpks.Values) skinShpk.Dispose(); @@ -98,21 +88,21 @@ public unsafe class SkinFixer : IDisposable public ulong GetAndResetSlowPathCallDelta() => Interlocked.Exchange(ref _slowPathCallDelta, 0); - private void OnCharacterBaseCreated(uint modelCharaId, nint customize, nint equipment, nint drawObject) + private void OnCharacterBaseCreated(nint gameObject, ModCollection collection, nint drawObject) { if (((CharacterBase*)drawObject)->GetModelType() != CharacterBase.ModelType.Human) return; - Task.Run(delegate + Task.Run(() => { var skinShpk = SafeResourceHandle.CreateInvalid(); try { - var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + var data = collection.ToResolveData(gameObject); if (data.Valid) { var loadedShpk = _resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data); - skinShpk = new SafeResourceHandle((ResourceHandle*)loadedShpk, incRef: false); + skinShpk = new SafeResourceHandle((ResourceHandle*)loadedShpk, false); } } catch (Exception e) @@ -128,30 +118,31 @@ public unsafe class SkinFixer : IDisposable Interlocked.Increment(ref _moddedSkinShpkCount); } else + { skinShpk.Dispose(); + } } }); } private void OnCharacterBaseDestructor(nint characterBase) { - if (_skinShpks.Remove(characterBase, out var skinShpk)) - { - var handle = skinShpk.ResourceHandle; - skinShpk.Dispose(); - if ((nint)handle != _utility.DefaultSkinShpkResource) - Interlocked.Decrement(ref _moddedSkinShpkCount); - } + if (!_skinShpks.Remove(characterBase, out var skinShpk)) + return; + + var handle = skinShpk.ResourceHandle; + skinShpk.Dispose(); + if ((nint)handle != _utility.DefaultSkinShpkResource) + Interlocked.Decrement(ref _moddedSkinShpkCount); } private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) { - if (!_enabled || // Can be toggled on the debug tab. - _moddedSkinShpkCount == 0 || // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. - !_skinShpks.TryGetValue(human, out var skinShpk)) + // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. + if (!Enabled || _moddedSkinShpkCount == 0 || !_skinShpks.TryGetValue(human, out var skinShpk) || skinShpk.IsInvalid) return _onRenderMaterialHook!.Original(human, param); - var material = param->Model->Materials[param->MaterialIndex]; + var material = param->Model->Materials[param->MaterialIndex]; var shpkResource = ((Structs.MtrlResource*)material->MaterialResourceHandle)->ShpkResourceHandle; if ((nint)shpkResource != (nint)skinShpk.ResourceHandle) return _onRenderMaterialHook!.Original(human, param); @@ -164,6 +155,7 @@ public unsafe class SkinFixer : IDisposable // - Swapping path is taken up to hundreds of times a frame. // At the time of writing, the lock doesn't seem to have a noticeable impact in either framerate or CPU usage, but the swapping path shall still be avoided as much as possible. lock (_lock) + { try { _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)skinShpk.ResourceHandle; @@ -173,5 +165,6 @@ public unsafe class SkinFixer : IDisposable { _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)_utility.DefaultSkinShpkResource; } + } } } diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index 1ee62c35..c24d64fa 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -36,7 +36,6 @@ using ObjectKind = Dalamud.Game.ClientState.Objects.Enums.ObjectKind; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using Penumbra.Interop.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using static Lumina.Data.Parsing.Layer.LayerCommon; namespace Penumbra.UI.Tabs; @@ -623,18 +622,14 @@ public class DebugTab : Window, ITab ImGui.TableNextColumn(); if (resource == null) { - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); + ImGui.TableNextRow(); continue; } UiHelpers.Text(resource); ImGui.TableNextColumn(); var data = (nint)ResourceHandle.GetData(resource); var length = ResourceHandle.GetLength(resource); - ImGui.Selectable($"0x{data:X}"); - if (ImGui.IsItemClicked()) + if (ImGui.Selectable($"0x{data:X}")) { if (data != nint.Zero && length > 0) ImGui.SetClipboardText(string.Join("\n", @@ -643,7 +638,7 @@ public class DebugTab : Window, ITab ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{length}"); + ImGui.TextUnformatted(length.ToString()); ImGui.TableNextColumn(); if (intern.Value != -1) From 2ac997610d9b63366d5e964bfe971cd349b15ac3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 31 Aug 2023 01:00:46 +0200 Subject: [PATCH 0055/1381] Remove Finalize from FileEditor. --- Penumbra/UI/AdvancedWindow/FileEditor.cs | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index ac873ce2..d0e9504c 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -39,11 +39,6 @@ public class FileEditor : IDisposable where T : class, IWritable _combo = new Combo(config, getFiles); } - ~FileEditor() - { - DoDispose(); - } - public void Draw() { using var tab = ImRaii.TabItem(_tabName); @@ -66,15 +61,11 @@ public class FileEditor : IDisposable where T : class, IWritable } public void Dispose() - { - DoDispose(); - GC.SuppressFinalize(this); - } - - private void DoDispose() { (_currentFile as IDisposable)?.Dispose(); - _currentFile = null; + _currentFile = null; + (_defaultFile as IDisposable)?.Dispose(); + _defaultFile = null; } private readonly string _tabName; From 5023fafc19366ea5192f77831d00c05db61bee3c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 25 Aug 2023 18:45:13 +0200 Subject: [PATCH 0056/1381] Some formatting in Materials.Shpk. --- OtterGui | 2 +- .../ModEditWindow.Materials.Shpk.cs | 71 +++++++++++-------- 2 files changed, 41 insertions(+), 32 deletions(-) diff --git a/OtterGui b/OtterGui index c8394607..728dd8c3 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c8394607addd29cb7f8ae3257f635a4486c40a63 +Subproject commit 728dd8c33f8b43f7a2725ac7c8886fe7cb3f04a9 diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index d3bc826a..0f13f47e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -101,9 +101,9 @@ public partial class ModEditWindow if (ImGui.Selectable(value, value == tab.Mtrl.ShaderPackage.Name)) { tab.Mtrl.ShaderPackage.Name = value; - ret = true; - tab.AssociatedShpk = null; - tab.LoadedShpkPath = FullPath.Empty; + ret = true; + tab.AssociatedShpk = null; + tab.LoadedShpkPath = FullPath.Empty; tab.LoadShpk(tab.FindAssociatedShpk(out _, out _)); } } @@ -133,6 +133,7 @@ public partial class ModEditWindow /// private void DrawCustomAssociations(MtrlTab tab) { + const string tooltip = "Click to copy file path to clipboard."; var text = tab.AssociatedShpk == null ? "Associated .shpk file: None" : $"Associated .shpk file: {tab.LoadedShpkPathName}"; @@ -145,20 +146,9 @@ public partial class ModEditWindow ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (ImGui.Selectable(text)) - ImGui.SetClipboardText(tab.LoadedShpkPathName); - - ImGuiUtil.HoverTooltip("Click to copy file path to clipboard."); - - if (ImGui.Selectable(devkitText)) - ImGui.SetClipboardText(tab.LoadedShpkDevkitPathName); - - ImGuiUtil.HoverTooltip("Click to copy file path to clipboard."); - - if (ImGui.Selectable(baseDevkitText)) - ImGui.SetClipboardText(tab.LoadedBaseDevkitPathName); - - ImGuiUtil.HoverTooltip("Click to copy file path to clipboard."); + ImGuiUtil.CopyOnClickSelectable(text, tab.LoadedShpkPathName, tooltip); + ImGuiUtil.CopyOnClickSelectable(devkitText, tab.LoadedShpkDevkitPathName, tooltip); + ImGuiUtil.CopyOnClickSelectable(baseDevkitText, tab.LoadedBaseDevkitPathName, tooltip); if (ImGui.Button("Associate Custom .shpk File")) _fileDialog.OpenFilePicker("Associate Custom .shpk File...", ".shpk", (success, name) => @@ -192,11 +182,12 @@ public partial class ModEditWindow var ret = false; foreach (var (label, index, description, monoFont, values) in tab.ShaderKeys) { - using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); - ref var key = ref tab.Mtrl.ShaderPackage.ShaderKeys[index]; - var shpkKey = tab.AssociatedShpk?.GetMaterialKeyById(key.Category); - var currentValue = key.Value; - var (currentLabel, _, currentDescription) = values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); + using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); + ref var key = ref tab.Mtrl.ShaderPackage.ShaderKeys[index]; + var shpkKey = tab.AssociatedShpk?.GetMaterialKeyById(key.Category); + var currentValue = key.Value; + var (currentLabel, _, currentDescription) = + values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); if (!disabled && shpkKey.HasValue) { ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); @@ -216,6 +207,7 @@ public partial class ModEditWindow ImGuiUtil.SelectableHelpMarker(valueDescription); } } + ImGui.SameLine(); if (description.Length > 0) ImGuiUtil.LabeledHelpMarker(label, description); @@ -223,10 +215,14 @@ public partial class ModEditWindow ImGui.TextUnformatted(label); } else if (description.Length > 0 || currentDescription.Length > 0) + { ImGuiUtil.LabeledHelpMarker($"{label}: {currentLabel}", - description + ((description.Length > 0 && currentDescription.Length > 0) ? "\n\n" : string.Empty) + currentDescription); + description + (description.Length > 0 && currentDescription.Length > 0 ? "\n\n" : string.Empty) + currentDescription); + } else + { ImGui.TextUnformatted($"{label}: {currentLabel}"); + } } return ret; @@ -268,7 +264,7 @@ public partial class ModEditWindow foreach (var (label, constantIndex, slice, description, monoFont, editor) in group) { var constant = tab.Mtrl.ShaderPackage.Constants[constantIndex]; - var buffer = tab.Mtrl.GetConstantValues(constant); + var buffer = tab.Mtrl.GetConstantValues(constant); if (buffer.Length > 0) { using var id = ImRaii.PushId($"##{constant.Id:X8}:{slice.Start}"); @@ -277,6 +273,7 @@ public partial class ModEditWindow ret = true; tab.SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); } + ImGui.SameLine(); using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); if (description.Length > 0) @@ -307,8 +304,8 @@ public partial class ModEditWindow static bool ComboTextureAddressMode(string label, ref uint samplerFlags, int bitOffset) { - var current = (TextureAddressMode)((samplerFlags >> bitOffset) & 0x3u); - using var c = ImRaii.Combo(label, current.ToString()); + var current = (TextureAddressMode)((samplerFlags >> bitOffset) & 0x3u); + using var c = ImRaii.Combo(label, current.ToString()); if (!c) return false; @@ -323,6 +320,7 @@ public partial class ModEditWindow ImGuiUtil.SelectableHelpMarker(TextureAddressModeTooltips[(int)value]); } + return ret; } @@ -339,6 +337,7 @@ public partial class ModEditWindow ret = true; tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); } + ImGui.SameLine(); ImGuiUtil.LabeledHelpMarker("U Address Mode", "Method to use for resolving a U texture coordinate that is outside the 0 to 1 range."); @@ -348,6 +347,7 @@ public partial class ModEditWindow ret = true; tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); } + ImGui.SameLine(); ImGuiUtil.LabeledHelpMarker("V Address Mode", "Method to use for resolving a V texture coordinate that is outside the 0 to 1 range."); @@ -355,12 +355,15 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); if (ImGui.DragFloat("##LoDBias", ref lodBias, 0.1f, -8.0f, 7.984375f)) { - sampler.Flags = (uint)((sampler.Flags & ~0x000FFC00) | (uint)((int)Math.Round(Math.Clamp(lodBias, -8.0f, 7.984375f) * 64.0f) & 0x3FF) << 10); - ret = true; + sampler.Flags = (uint)((sampler.Flags & ~0x000FFC00) + | ((uint)((int)Math.Round(Math.Clamp(lodBias, -8.0f, 7.984375f) * 64.0f) & 0x3FF) << 10)); + ret = true; tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); } + ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Level of Detail Bias", "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); + ImGuiUtil.LabeledHelpMarker("Level of Detail Bias", + "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); var minLod = (int)((sampler.Flags >> 20) & 0xF); ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); @@ -370,8 +373,10 @@ public partial class ModEditWindow ret = true; tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); } + ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Minimum Level of Detail", "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); + ImGuiUtil.LabeledHelpMarker("Minimum Level of Detail", + "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); using var t = ImRaii.TreeNode("Advanced Settings"); if (!t) @@ -413,7 +418,10 @@ public partial class ModEditWindow GC.KeepAlive(tab); var textColor = ImGui.GetColorU32(ImGuiCol.Text); - var textColorWarning = (textColor & 0xFF000000u) | ((textColor & 0x00FEFEFE) >> 1) | (tab.AssociatedShpk == null ? 0x80u : 0x8080u); // Half red or yellow + var textColorWarning = + (textColor & 0xFF000000u) + | ((textColor & 0x00FEFEFE) >> 1) + | (tab.AssociatedShpk == null ? 0x80u : 0x8080u); // Half red or yellow using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); @@ -443,6 +451,7 @@ public partial class ModEditWindow _ => null, }; } + private static string VectorSwizzle(int firstComponent, int lastComponent) => (firstComponent, lastComponent) switch { From ff012768691892e06d9eda774a3306ba07d9145a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 31 Aug 2023 01:11:57 +0200 Subject: [PATCH 0057/1381] Small cleanup in ResolveContext. --- .../Interop/ResourceTree/ResolveContext.cs | 46 +++++++++---------- .../ModEditWindow.Materials.LivePreview.cs | 17 +++---- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index d14bd68b..0cb854f3 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -65,31 +65,10 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide private ResourceNode CreateNodeFromGamePath(ResourceType type, nint sourceAddress, Utf8GamePath gamePath, bool @internal) => new(null, type, sourceAddress, gamePath, FilterFullPath(Collection.ResolvePath(gamePath) ?? new FullPath(gamePath)), @internal); - public static unsafe FullPath GetResourceHandlePath(ResourceHandle* handle) - { - var name = handle->FileName(); - if (name.IsEmpty) - return FullPath.Empty; - - if (name[0] == (byte)'|') - { - var pos = name.IndexOf((byte)'|', 1); - if (pos < 0) - return FullPath.Empty; - - name = name.Substring(pos + 1); - } - - return new FullPath(Utf8GamePath.FromByteString(name, out var p) ? p : Utf8GamePath.Empty); - } - private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint sourceAddress, ResourceHandle* handle, bool @internal, bool withName) - { - if (handle == null) - return null; - - var fullPath = GetResourceHandlePath(handle); + { + var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(handle), out var p) ? new FullPath(p) : FullPath.Empty; if (fullPath.InternalName.IsEmpty) return null; @@ -294,4 +273,25 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide var i = index.GetOffset(array.Length); return i >= 0 && i < array.Length ? array[i] : null; } + + internal static unsafe ByteString GetResourceHandlePath(ResourceHandle* handle) + { + if (handle == null) + return ByteString.Empty; + + var name = handle->FileName(); + if (name.IsEmpty) + return ByteString.Empty; + + if (name[0] == (byte)'|') + { + var pos = name.IndexOf((byte)'|', 1); + if (pos < 0) + return ByteString.Empty; + + name = name.Substring(pos + 1); + } + + return name; + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs index 76ac8915..d2ce8796 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs @@ -9,6 +9,7 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; +using Penumbra.String; using Structs = Penumbra.Interop.Structs; namespace Penumbra.UI.AdvancedWindow; @@ -52,8 +53,8 @@ public partial class ModEditWindow private static unsafe List<(int SubActorType, int ChildObjectIndex, int ModelSlot, int MaterialSlot)> FindMaterial(CharacterBase* drawObject, int subActorType, string materialPath) { - static void CollectMaterials(List<(int, int, int, int)> result, int subActorType, int childObjectIndex, CharacterBase* drawObject, string materialPath) - { + static void CollectMaterials(List<(int, int, int, int)> result, int subActorType, int childObjectIndex, CharacterBase* drawObject, ByteString materialPath) + { for (var i = 0; i < drawObject->SlotCount; ++i) { var model = drawObject->Models[i]; @@ -67,11 +68,8 @@ public partial class ModEditWindow continue; var mtrlHandle = material->MaterialResourceHandle; - if (mtrlHandle == null) - continue; - var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); - if (path.ToString() == materialPath) + if (path == materialPath) result.Add((subActorType, childObjectIndex, i, j)); } } @@ -82,9 +80,8 @@ public partial class ModEditWindow if (drawObject == null) return result; - materialPath = materialPath.Replace('/', '\\').ToLowerInvariant(); - - CollectMaterials(result, subActorType, -1, drawObject, materialPath); + var path = ByteString.FromString(materialPath.Replace('/', '\\'), out var m, true) ? m : ByteString.Empty; + CollectMaterials(result, subActorType, -1, drawObject, path); var firstChildObject = (CharacterBase*)drawObject->DrawObject.Object.ChildObject; if (firstChildObject != null) @@ -93,7 +90,7 @@ public partial class ModEditWindow var childObjectIndex = 0; do { - CollectMaterials(result, subActorType, childObjectIndex, childObject, materialPath); + CollectMaterials(result, subActorType, childObjectIndex, childObject, path); childObject = (CharacterBase*)childObject->DrawObject.Object.NextSiblingObject; ++childObjectIndex; From e5e555b981a6afc2149c60cd581e1f8d41b68a93 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 31 Aug 2023 17:12:39 +0200 Subject: [PATCH 0058/1381] Auto-formatting and some cleanup. --- .../ModEditWindow.Materials.ColorSet.cs | 484 ++++++------ .../ModEditWindow.Materials.ConstantEditor.cs | 103 +-- .../ModEditWindow.Materials.MtrlTab.cs | 292 ++++---- .../ModEditWindow.Materials.Shpk.cs | 23 +- .../AdvancedWindow/ModEditWindow.Materials.cs | 236 +++--- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 1 - .../ModEditWindow.ShaderPackages.cs | 690 ++++++++---------- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 6 + 8 files changed, 876 insertions(+), 959 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs index daca1098..e1ba045d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs @@ -17,65 +17,60 @@ public partial class ModEditWindow private static readonly float HalfMaxValue = (float)Half.MaxValue; private static readonly float HalfEpsilon = (float)Half.Epsilon; - private bool DrawMaterialColorSetChange( MtrlTab tab, bool disabled ) + private bool DrawMaterialColorSetChange(MtrlTab tab, bool disabled) { - if( !tab.SamplerIds.Contains( ShpkFile.TableSamplerId ) || !tab.Mtrl.ColorSets.Any( c => c.HasRows ) ) - { + if (!tab.SamplerIds.Contains(ShpkFile.TableSamplerId) || !tab.Mtrl.ColorSets.Any(c => c.HasRows)) return false; - } - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - if( !ImGui.CollapsingHeader( "Color Set", ImGuiTreeNodeFlags.DefaultOpen ) ) - { + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + if (!ImGui.CollapsingHeader("Color Set", ImGuiTreeNodeFlags.DefaultOpen)) return false; - } var hasAnyDye = tab.UseColorDyeSet; - ColorSetCopyAllClipboardButton( tab.Mtrl, 0 ); + ColorSetCopyAllClipboardButton(tab.Mtrl, 0); ImGui.SameLine(); - var ret = ColorSetPasteAllClipboardButton( tab, 0, disabled ); - if( !disabled ) + var ret = ColorSetPasteAllClipboardButton(tab, 0, disabled); + if (!disabled) { ImGui.SameLine(); - ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); - ret |= ColorSetDyeableCheckbox( tab, ref hasAnyDye ); - } - if( hasAnyDye ) - { - ImGui.SameLine(); - ImGui.Dummy( ImGuiHelpers.ScaledVector2( 20, 0 ) ); - ImGui.SameLine(); - ret |= DrawPreviewDye( tab, disabled ); + ret |= ColorSetDyeableCheckbox(tab, ref hasAnyDye); } - using var table = ImRaii.Table( "##ColorSets", hasAnyDye ? 11 : 9, - ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV ); - if( !table ) + if (hasAnyDye) { + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImGui.SameLine(); + ret |= DrawPreviewDye(tab, disabled); + } + + using var table = ImRaii.Table("##ColorSets", hasAnyDye ? 11 : 9, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV); + if (!table) return false; - } ImGui.TableNextColumn(); - ImGui.TableHeader( string.Empty ); + ImGui.TableHeader(string.Empty); ImGui.TableNextColumn(); - ImGui.TableHeader( "Row" ); + ImGui.TableHeader("Row"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Diffuse" ); + ImGui.TableHeader("Diffuse"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Specular" ); + ImGui.TableHeader("Specular"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Emissive" ); + ImGui.TableHeader("Emissive"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Gloss" ); + ImGui.TableHeader("Gloss"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Tile" ); + ImGui.TableHeader("Tile"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Repeat" ); + ImGui.TableHeader("Repeat"); ImGui.TableNextColumn(); - ImGui.TableHeader( "Skew" ); - if( hasAnyDye ) + ImGui.TableHeader("Skew"); + if (hasAnyDye) { ImGui.TableNextColumn(); ImGui.TableHeader("Dye"); @@ -83,12 +78,12 @@ public partial class ModEditWindow ImGui.TableHeader("Dye Preview"); } - for( var j = 0; j < tab.Mtrl.ColorSets.Length; ++j ) + for (var j = 0; j < tab.Mtrl.ColorSets.Length; ++j) { - using var _ = ImRaii.PushId( j ); - for( var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i ) + using var _ = ImRaii.PushId(j); + for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) { - ret |= DrawColorSetRow( tab, j, i, disabled, hasAnyDye ); + ret |= DrawColorSetRow(tab, j, i, disabled, hasAnyDye); ImGui.TableNextRow(); } } @@ -97,22 +92,20 @@ public partial class ModEditWindow } - private static void ColorSetCopyAllClipboardButton( MtrlFile file, int colorSetIdx ) + private static void ColorSetCopyAllClipboardButton(MtrlFile file, int colorSetIdx) { - if( !ImGui.Button( "Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2( 200, 0 ) ) ) - { + if (!ImGui.Button("Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2(200, 0))) return; - } try { - var data1 = file.ColorSets[ colorSetIdx ].Rows.AsBytes(); - var data2 = file.ColorDyeSets.Length > colorSetIdx ? file.ColorDyeSets[ colorSetIdx ].Rows.AsBytes() : ReadOnlySpan< byte >.Empty; + var data1 = file.ColorSets[colorSetIdx].Rows.AsBytes(); + var data2 = file.ColorDyeSets.Length > colorSetIdx ? file.ColorDyeSets[colorSetIdx].Rows.AsBytes() : ReadOnlySpan.Empty; var array = new byte[data1.Length + data2.Length]; - data1.TryCopyTo( array ); - data2.TryCopyTo( array.AsSpan( data1.Length ) ); - var text = Convert.ToBase64String( array ); - ImGui.SetClipboardText( text ); + data1.TryCopyTo(array); + data2.TryCopyTo(array.AsSpan(data1.Length)); + var text = Convert.ToBase64String(array); + ImGui.SetClipboardText(text); } catch { @@ -120,19 +113,19 @@ public partial class ModEditWindow } } - private bool DrawPreviewDye( MtrlTab tab, bool disabled ) + private bool DrawPreviewDye(MtrlTab tab, bool disabled) { var (dyeId, (name, dyeColor, gloss)) = _stainService.StainCombo.CurrentSelection; - var tt = dyeId == 0 ? "Select a preview dye first." : "Apply all preview values corresponding to the dye template and chosen dye where dyeing is enabled."; - if( ImGuiUtil.DrawDisabledButton( "Apply Preview Dye", Vector2.Zero, tt, disabled || dyeId == 0 ) ) + var tt = dyeId == 0 + ? "Select a preview dye first." + : "Apply all preview values corresponding to the dye template and chosen dye where dyeing is enabled."; + if (ImGuiUtil.DrawDisabledButton("Apply Preview Dye", Vector2.Zero, tt, disabled || dyeId == 0)) { var ret = false; - for( var j = 0; j < tab.Mtrl.ColorDyeSets.Length; ++j ) + for (var j = 0; j < tab.Mtrl.ColorDyeSets.Length; ++j) { - for( var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i ) - { - ret |= tab.Mtrl.ApplyDyeTemplate( _stainService.StmFile, j, i, dyeId ); - } + for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) + ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, j, i, dyeId); } tab.UpdateColorSetPreview(); @@ -147,33 +140,31 @@ public partial class ModEditWindow return false; } - private static unsafe bool ColorSetPasteAllClipboardButton( MtrlTab tab, int colorSetIdx, bool disabled ) + private static unsafe bool ColorSetPasteAllClipboardButton(MtrlTab tab, int colorSetIdx, bool disabled) { - if( !ImGuiUtil.DrawDisabledButton( "Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2( 200, 0 ), string.Empty, disabled ) || tab.Mtrl.ColorSets.Length <= colorSetIdx ) - { + if (!ImGuiUtil.DrawDisabledButton("Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2(200, 0), string.Empty, disabled) + || tab.Mtrl.ColorSets.Length <= colorSetIdx) return false; - } try { var text = ImGui.GetClipboardText(); - var data = Convert.FromBase64String( text ); - if( data.Length < Marshal.SizeOf< MtrlFile.ColorSet.RowArray >() ) - { + var data = Convert.FromBase64String(text); + if (data.Length < Marshal.SizeOf()) return false; - } - ref var rows = ref tab.Mtrl.ColorSets[ colorSetIdx ].Rows; - fixed( void* ptr = data, output = &rows ) + ref var rows = ref tab.Mtrl.ColorSets[colorSetIdx].Rows; + fixed (void* ptr = data, output = &rows) { - MemoryUtility.MemCpyUnchecked( output, ptr, Marshal.SizeOf< MtrlFile.ColorSet.RowArray >() ); - if( data.Length >= Marshal.SizeOf< MtrlFile.ColorSet.RowArray >() + Marshal.SizeOf< MtrlFile.ColorDyeSet.RowArray >() - && tab.Mtrl.ColorDyeSets.Length > colorSetIdx ) + MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); + if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() + && tab.Mtrl.ColorDyeSets.Length > colorSetIdx) { - ref var dyeRows = ref tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows; - fixed( void* output2 = &dyeRows ) + ref var dyeRows = ref tab.Mtrl.ColorDyeSets[colorSetIdx].Rows; + fixed (void* output2 = &dyeRows) { - MemoryUtility.MemCpyUnchecked( output2, ( byte* )ptr + Marshal.SizeOf< MtrlFile.ColorSet.RowArray >(), Marshal.SizeOf< MtrlFile.ColorDyeSet.RowArray >() ); + MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), + Marshal.SizeOf()); } } } @@ -188,38 +179,38 @@ public partial class ModEditWindow } } - private static unsafe void ColorSetCopyClipboardButton( MtrlFile.ColorSet.Row row, MtrlFile.ColorDyeSet.Row dye ) + private static unsafe void ColorSetCopyClipboardButton(MtrlFile.ColorSet.Row row, MtrlFile.ColorDyeSet.Row dye) { - if( ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Export this row to your clipboard.", false, true ) ) - { - try - { - var data = new byte[MtrlFile.ColorSet.Row.Size + 2]; - fixed( byte* ptr = data ) - { - MemoryUtility.MemCpyUnchecked( ptr, &row, MtrlFile.ColorSet.Row.Size ); - MemoryUtility.MemCpyUnchecked( ptr + MtrlFile.ColorSet.Row.Size, &dye, 2 ); - } + if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, + "Export this row to your clipboard.", false, true)) + return; - var text = Convert.ToBase64String( data ); - ImGui.SetClipboardText( text ); - } - catch + try + { + var data = new byte[MtrlFile.ColorSet.Row.Size + 2]; + fixed (byte* ptr = data) { - // ignored + MemoryUtility.MemCpyUnchecked(ptr, &row, MtrlFile.ColorSet.Row.Size); + MemoryUtility.MemCpyUnchecked(ptr + MtrlFile.ColorSet.Row.Size, &dye, 2); } + + var text = Convert.ToBase64String(data); + ImGui.SetClipboardText(text); + } + catch + { + // ignored } } - private static bool ColorSetDyeableCheckbox( MtrlTab tab, ref bool dyeable ) + private static bool ColorSetDyeableCheckbox(MtrlTab tab, ref bool dyeable) { - var ret = ImGui.Checkbox( "Dyeable", ref dyeable ); + var ret = ImGui.Checkbox("Dyeable", ref dyeable); - if( ret ) + if (ret) { tab.UseColorDyeSet = dyeable; - if( dyeable ) + if (dyeable) tab.Mtrl.FindOrAddColorDyeSet(); tab.UpdateColorSetPreview(); } @@ -227,215 +218,244 @@ public partial class ModEditWindow return ret; } - private static unsafe bool ColorSetPasteFromClipboardButton( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled ) + private static unsafe bool ColorSetPasteFromClipboardButton(MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled) { - if( ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Import an exported row from your clipboard onto this row.", disabled, true ) ) + if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, + "Import an exported row from your clipboard onto this row.", disabled, true)) + return false; + + try { - try + var text = ImGui.GetClipboardText(); + var data = Convert.FromBase64String(text); + if (data.Length != MtrlFile.ColorSet.Row.Size + 2 + || tab.Mtrl.ColorSets.Length <= colorSetIdx) + return false; + + fixed (byte* ptr = data) { - var text = ImGui.GetClipboardText(); - var data = Convert.FromBase64String( text ); - if( data.Length != MtrlFile.ColorSet.Row.Size + 2 - || tab.Mtrl.ColorSets.Length <= colorSetIdx ) - { - return false; - } - - fixed( byte* ptr = data ) - { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ] = *( MtrlFile.ColorSet.Row* )ptr; - if( colorSetIdx < tab.Mtrl.ColorDyeSets.Length ) - { - tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] = *( MtrlFile.ColorDyeSet.Row* )( ptr + MtrlFile.ColorSet.Row.Size ); - } - } - - tab.UpdateColorSetRowPreview(rowIdx); - - return true; - } - catch - { - // ignored + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx] = *(MtrlFile.ColorSet.Row*)ptr; + if (colorSetIdx < tab.Mtrl.ColorDyeSets.Length) + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx] = *(MtrlFile.ColorDyeSet.Row*)(ptr + MtrlFile.ColorSet.Row.Size); } + + tab.UpdateColorSetRowPreview(rowIdx); + + return true; + } + catch + { + return false; } - - return false; } - private static void ColorSetHighlightButton( MtrlTab tab, int rowIdx, bool disabled ) + private static void ColorSetHighlightButton(MtrlTab tab, int rowIdx, bool disabled) { - ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Crosshairs.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Highlight this row on your character, if possible.", disabled || tab.ColorSetPreviewers.Count == 0, true ); + ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Crosshairs.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, + "Highlight this row on your character, if possible.", disabled || tab.ColorSetPreviewers.Count == 0, true); - if( ImGui.IsItemHovered() ) - tab.HighlightColorSetRow( rowIdx ); - else if( tab.HighlightedColorSetRow == rowIdx ) + if (ImGui.IsItemHovered()) + tab.HighlightColorSetRow(rowIdx); + else if (tab.HighlightedColorSetRow == rowIdx) tab.CancelColorSetHighlight(); } - private bool DrawColorSetRow( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, bool hasAnyDye ) + private bool DrawColorSetRow(MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, bool hasAnyDye) { - static bool FixFloat( ref float val, float current ) + static bool FixFloat(ref float val, float current) { - val = ( float )( Half )val; + val = (float)(Half)val; return val != current; } - using var id = ImRaii.PushId( rowIdx ); - var row = tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ]; + using var id = ImRaii.PushId(rowIdx); + var row = tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx]; var hasDye = hasAnyDye && tab.Mtrl.ColorDyeSets.Length > colorSetIdx; - var dye = hasDye ? tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ] : new MtrlFile.ColorDyeSet.Row(); + var dye = hasDye ? tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx] : new MtrlFile.ColorDyeSet.Row(); var floatSize = 70 * UiHelpers.Scale; var intSize = 45 * UiHelpers.Scale; ImGui.TableNextColumn(); - ColorSetCopyClipboardButton( row, dye ); + ColorSetCopyClipboardButton(row, dye); ImGui.SameLine(); - var ret = ColorSetPasteFromClipboardButton( tab, colorSetIdx, rowIdx, disabled ); + var ret = ColorSetPasteFromClipboardButton(tab, colorSetIdx, rowIdx, disabled); ImGui.SameLine(); - ColorSetHighlightButton( tab, rowIdx, disabled ); + ColorSetHighlightButton(tab, rowIdx, disabled); ImGui.TableNextColumn(); - ImGui.TextUnformatted( $"#{rowIdx + 1:D2}" ); + ImGui.TextUnformatted($"#{rowIdx + 1:D2}"); ImGui.TableNextColumn(); - using var dis = ImRaii.Disabled( disabled ); - ret |= ColorPicker( "##Diffuse", "Diffuse Color", row.Diffuse, c => { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Diffuse = c; tab.UpdateColorSetRowPreview(rowIdx); } ); - if( hasDye ) + using var dis = ImRaii.Disabled(disabled); + ret |= ColorPicker("##Diffuse", "Diffuse Color", row.Diffuse, c => + { + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].Diffuse = c; + tab.UpdateColorSetRowPreview(rowIdx); + }); + if (hasDye) { ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox( "##dyeDiffuse", "Apply Diffuse Color on Dye", dye.Diffuse, - b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Diffuse = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); + ret |= ImGuiUtil.Checkbox("##dyeDiffuse", "Apply Diffuse Color on Dye", dye.Diffuse, + b => + { + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Diffuse = b; + tab.UpdateColorSetRowPreview(rowIdx); + }, ImGuiHoveredFlags.AllowWhenDisabled); } ImGui.TableNextColumn(); - ret |= ColorPicker( "##Specular", "Specular Color", row.Specular, c => { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Specular = c; tab.UpdateColorSetRowPreview(rowIdx); } ); + ret |= ColorPicker("##Specular", "Specular Color", row.Specular, c => + { + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].Specular = c; + tab.UpdateColorSetRowPreview(rowIdx); + }); ImGui.SameLine(); var tmpFloat = row.SpecularStrength; - ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##SpecularStrength", ref tmpFloat, 0.1f, 0f, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.SpecularStrength ) ) + ImGui.SetNextItemWidth(floatSize); + if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.1f, 0f, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.SpecularStrength)) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = tmpFloat; - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].SpecularStrength = tmpFloat; + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Specular Strength", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Specular Strength", ImGuiHoveredFlags.AllowWhenDisabled); - if( hasDye ) + if (hasDye) { ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox( "##dyeSpecular", "Apply Specular Color on Dye", dye.Specular, - b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Specular = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); + ret |= ImGuiUtil.Checkbox("##dyeSpecular", "Apply Specular Color on Dye", dye.Specular, + b => + { + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Specular = b; + tab.UpdateColorSetRowPreview(rowIdx); + }, ImGuiHoveredFlags.AllowWhenDisabled); ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox( "##dyeSpecularStrength", "Apply Specular Strength on Dye", dye.SpecularStrength, - b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].SpecularStrength = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); + ret |= ImGuiUtil.Checkbox("##dyeSpecularStrength", "Apply Specular Strength on Dye", dye.SpecularStrength, + b => + { + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].SpecularStrength = b; + tab.UpdateColorSetRowPreview(rowIdx); + }, ImGuiHoveredFlags.AllowWhenDisabled); } ImGui.TableNextColumn(); - ret |= ColorPicker( "##Emissive", "Emissive Color", row.Emissive, c => { tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].Emissive = c; tab.UpdateColorSetRowPreview(rowIdx); } ); - if( hasDye ) + ret |= ColorPicker("##Emissive", "Emissive Color", row.Emissive, c => + { + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].Emissive = c; + tab.UpdateColorSetRowPreview(rowIdx); + }); + if (hasDye) { ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox( "##dyeEmissive", "Apply Emissive Color on Dye", dye.Emissive, - b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Emissive = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); + ret |= ImGuiUtil.Checkbox("##dyeEmissive", "Apply Emissive Color on Dye", dye.Emissive, + b => + { + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Emissive = b; + tab.UpdateColorSetRowPreview(rowIdx); + }, ImGuiHoveredFlags.AllowWhenDisabled); } ImGui.TableNextColumn(); tmpFloat = row.GlossStrength; - ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##GlossStrength", ref tmpFloat, Math.Max( 0.1f, tmpFloat * 0.025f ), HalfEpsilon, HalfMaxValue, "%.1f" ) && FixFloat( ref tmpFloat, row.GlossStrength ) ) + ImGui.SetNextItemWidth(floatSize); + if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), HalfEpsilon, HalfMaxValue, "%.1f") + && FixFloat(ref tmpFloat, row.GlossStrength)) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].GlossStrength = Math.Max(tmpFloat, HalfEpsilon); - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].GlossStrength = Math.Max(tmpFloat, HalfEpsilon); + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Gloss Strength", ImGuiHoveredFlags.AllowWhenDisabled ); - if( hasDye ) + ImGuiUtil.HoverTooltip("Gloss Strength", ImGuiHoveredFlags.AllowWhenDisabled); + if (hasDye) { ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox( "##dyeGloss", "Apply Gloss Strength on Dye", dye.Gloss, - b => { tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Gloss = b; tab.UpdateColorSetRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled ); + ret |= ImGuiUtil.Checkbox("##dyeGloss", "Apply Gloss Strength on Dye", dye.Gloss, + b => + { + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Gloss = b; + tab.UpdateColorSetRowPreview(rowIdx); + }, ImGuiHoveredFlags.AllowWhenDisabled); } ImGui.TableNextColumn(); int tmpInt = row.TileSet; - ImGui.SetNextItemWidth( intSize ); - if( ImGui.DragInt( "##TileSet", ref tmpInt, 0.25f, 0, 63 ) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue ) + ImGui.SetNextItemWidth(intSize); + if (ImGui.DragInt("##TileSet", ref tmpInt, 0.25f, 0, 63) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].TileSet = ( ushort )Math.Clamp(tmpInt, 0, 63); - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].TileSet = (ushort)Math.Clamp(tmpInt, 0, 63); + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Tile Set", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Tile Set", ImGuiHoveredFlags.AllowWhenDisabled); ImGui.TableNextColumn(); tmpFloat = row.MaterialRepeat.X; - ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##RepeatX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialRepeat.X ) ) + ImGui.SetNextItemWidth(floatSize); + if (ImGui.DragFloat("##RepeatX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") + && FixFloat(ref tmpFloat, row.MaterialRepeat.X)) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Repeat X", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Repeat X", ImGuiHoveredFlags.AllowWhenDisabled); ImGui.SameLine(); tmpFloat = row.MaterialRepeat.Y; - ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##RepeatY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialRepeat.Y ) ) + ImGui.SetNextItemWidth(floatSize); + if (ImGui.DragFloat("##RepeatY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") + && FixFloat(ref tmpFloat, row.MaterialRepeat.Y)) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Repeat Y", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Repeat Y", ImGuiHoveredFlags.AllowWhenDisabled); ImGui.TableNextColumn(); tmpFloat = row.MaterialSkew.X; - ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##SkewX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialSkew.X ) ) + ImGui.SetNextItemWidth(floatSize); + if (ImGui.DragFloat("##SkewX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.X)) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { X = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialSkew = row.MaterialSkew with { X = tmpFloat }; + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Skew X", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Skew X", ImGuiHoveredFlags.AllowWhenDisabled); ImGui.SameLine(); tmpFloat = row.MaterialSkew.Y; - ImGui.SetNextItemWidth( floatSize ); - if( ImGui.DragFloat( "##SkewY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f" ) && FixFloat( ref tmpFloat, row.MaterialSkew.Y ) ) + ImGui.SetNextItemWidth(floatSize); + if (ImGui.DragFloat("##SkewY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.Y)) { - tab.Mtrl.ColorSets[ colorSetIdx ].Rows[ rowIdx ].MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; - ret = true; + tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Skew Y", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Skew Y", ImGuiHoveredFlags.AllowWhenDisabled); - if( hasDye ) + if (hasDye) { ImGui.TableNextColumn(); - if (_stainService.TemplateCombo.Draw( "##dyeTemplate", dye.Template.ToString(), string.Empty, intSize - + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton ) ) + if (_stainService.TemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { - tab.Mtrl.ColorDyeSets[ colorSetIdx ].Rows[ rowIdx ].Template = _stainService.TemplateCombo.CurrentSelection; - ret = true; + tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Template = _stainService.TemplateCombo.CurrentSelection; + ret = true; tab.UpdateColorSetRowPreview(rowIdx); } - ImGuiUtil.HoverTooltip( "Dye Template", ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip("Dye Template", ImGuiHoveredFlags.AllowWhenDisabled); ImGui.TableNextColumn(); - ret |= DrawDyePreview( tab, colorSetIdx, rowIdx, disabled, dye, floatSize ); + ret |= DrawDyePreview(tab, colorSetIdx, rowIdx, disabled, dye, floatSize); } - else if ( hasAnyDye ) + else if (hasAnyDye) { ImGui.TableNextColumn(); ImGui.TableNextColumn(); @@ -445,63 +465,65 @@ public partial class ModEditWindow return ret; } - private bool DrawDyePreview( MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, MtrlFile.ColorDyeSet.Row dye, float floatSize ) + private bool DrawDyePreview(MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, MtrlFile.ColorDyeSet.Row dye, float floatSize) { var stain = _stainService.StainCombo.CurrentSelection.Key; - if( stain == 0 || !_stainService.StmFile.Entries.TryGetValue( dye.Template, out var entry ) ) - { + if (stain == 0 || !_stainService.StmFile.Entries.TryGetValue(dye.Template, out var entry)) return false; - } - var values = entry[ ( int )stain ]; - using var style = ImRaii.PushStyle( ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing / 2 ); + var values = entry[(int)stain]; + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing / 2); - var ret = ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2( ImGui.GetFrameHeight() ), - "Apply the selected dye to this row.", disabled, true ); + var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), + "Apply the selected dye to this row.", disabled, true); - ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, colorSetIdx, rowIdx, stain ); + ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, colorSetIdx, rowIdx, stain); if (ret) tab.UpdateColorSetRowPreview(rowIdx); ImGui.SameLine(); - ColorPicker( "##diffusePreview", string.Empty, values.Diffuse, _ => { }, "D" ); + ColorPicker("##diffusePreview", string.Empty, values.Diffuse, _ => { }, "D"); ImGui.SameLine(); - ColorPicker( "##specularPreview", string.Empty, values.Specular, _ => { }, "S" ); + ColorPicker("##specularPreview", string.Empty, values.Specular, _ => { }, "S"); ImGui.SameLine(); - ColorPicker( "##emissivePreview", string.Empty, values.Emissive, _ => { }, "E" ); + ColorPicker("##emissivePreview", string.Empty, values.Emissive, _ => { }, "E"); ImGui.SameLine(); using var dis = ImRaii.Disabled(); - ImGui.SetNextItemWidth( floatSize ); - ImGui.DragFloat( "##gloss", ref values.Gloss, 0, values.Gloss, values.Gloss, "%.1f G" ); + ImGui.SetNextItemWidth(floatSize); + ImGui.DragFloat("##gloss", ref values.Gloss, 0, values.Gloss, values.Gloss, "%.1f G"); ImGui.SameLine(); - ImGui.SetNextItemWidth( floatSize ); - ImGui.DragFloat( "##specularStrength", ref values.SpecularPower, 0, values.SpecularPower, values.SpecularPower, "%.2f S" ); + ImGui.SetNextItemWidth(floatSize); + ImGui.DragFloat("##specularStrength", ref values.SpecularPower, 0, values.SpecularPower, values.SpecularPower, "%.2f S"); return ret; } - private static bool ColorPicker( string label, string tooltip, Vector3 input, Action< Vector3 > setter, string letter = "" ) + private static bool ColorPicker(string label, string tooltip, Vector3 input, Action setter, string letter = "") { - var ret = false; - var inputSqrt = PseudoSqrtRgb( input ); - var tmp = inputSqrt; - if( ImGui.ColorEdit3( label, ref tmp, - ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.DisplayRGB | ImGuiColorEditFlags.InputRGB | ImGuiColorEditFlags.NoTooltip | ImGuiColorEditFlags.HDR ) - && tmp != inputSqrt ) + var ret = false; + var inputSqrt = PseudoSqrtRgb(input); + var tmp = inputSqrt; + if (ImGui.ColorEdit3(label, ref tmp, + ImGuiColorEditFlags.NoInputs + | ImGuiColorEditFlags.DisplayRGB + | ImGuiColorEditFlags.InputRGB + | ImGuiColorEditFlags.NoTooltip + | ImGuiColorEditFlags.HDR) + && tmp != inputSqrt) { - setter( PseudoSquareRgb( tmp ) ); + setter(PseudoSquareRgb(tmp)); ret = true; } - if( letter.Length > 0 && ImGui.IsItemVisible() ) + if (letter.Length > 0 && ImGui.IsItemVisible()) { - var textSize = ImGui.CalcTextSize( letter ); - var center = ImGui.GetItemRectMin() + ( ImGui.GetItemRectSize() - textSize ) / 2; + var textSize = ImGui.CalcTextSize(letter); + var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; var textColor = input.LengthSquared() < 0.25f ? 0x80FFFFFFu : 0x80000000u; - ImGui.GetWindowDrawList().AddText( center, textColor, letter ); + ImGui.GetWindowDrawList().AddText(center, textColor, letter); } - ImGuiUtil.HoverTooltip( tooltip, ImGuiHoveredFlags.AllowWhenDisabled ); + ImGuiUtil.HoverTooltip(tooltip, ImGuiHoveredFlags.AllowWhenDisabled); return ret; } @@ -509,7 +531,7 @@ public partial class ModEditWindow // Functions to deal with squared RGB values without making negatives useless. private static float PseudoSquareRgb(float x) - => x < 0.0f ? -(x * x) : (x * x); + => x < 0.0f ? -(x * x) : x * x; private static Vector3 PseudoSquareRgb(Vector3 vec) => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z)); @@ -525,4 +547,4 @@ public partial class ModEditWindow private static Vector4 PseudoSqrtRgb(Vector4 vec) => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z), vec.W); -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs index 8a104145..e5b16a47 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Numerics; using ImGuiNET; using OtterGui.Raii; @@ -27,7 +28,8 @@ public partial class ModEditWindow private readonly float _bias; private readonly string _format; - public FloatConstantEditor(float? minimum, float? maximum, float speed, float relativeSpeed, float factor, float bias, byte precision, string unit) + public FloatConstantEditor(float? minimum, float? maximum, float speed, float relativeSpeed, float factor, float bias, byte precision, + string unit) { _minimum = minimum; _maximum = maximum; @@ -55,10 +57,13 @@ public partial class ModEditWindow var value = (values[valueIdx] - _bias) / _factor; if (disabled) + { ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), value, value, _format); + } else { - if (ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0.0f, _maximum ?? 0.0f, _format)) + if (ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0.0f, + _maximum ?? 0.0f, _format)) { values[valueIdx] = Clamp(value) * _factor + _bias; ret = true; @@ -111,10 +116,13 @@ public partial class ModEditWindow var value = (int)Math.Clamp(MathF.Round((values[valueIdx] - _bias) / _factor), int.MinValue, int.MaxValue); if (disabled) + { ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), value, value, _format); + } else { - if (ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0, _maximum ?? 0, _format)) + if (ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0, _maximum ?? 0, + _format)) { values[valueIdx] = Clamp(value) * _factor + _bias; ret = true; @@ -142,14 +150,17 @@ public partial class ModEditWindow public bool Draw(Span values, bool disabled, float editorWidth) { - if (values.Length == 3) + switch (values.Length) { - ImGui.SetNextItemWidth(editorWidth); - var value = new Vector3(values); - if (_squaredRgb) - value = PseudoSqrtRgb(value); - if (ImGui.ColorEdit3("##0", ref value, ImGuiColorEditFlags.Float | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) && !disabled) + case 3: { + ImGui.SetNextItemWidth(editorWidth); + var value = new Vector3(values); + if (_squaredRgb) + value = PseudoSqrtRgb(value); + if (!ImGui.ColorEdit3("##0", ref value, ImGuiColorEditFlags.Float | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) || disabled) + return false; + if (_squaredRgb) value = PseudoSquareRgb(value); if (_clamped) @@ -157,17 +168,17 @@ public partial class ModEditWindow value.CopyTo(values); return true; } - - return false; - } - else if (values.Length == 4) - { - ImGui.SetNextItemWidth(editorWidth); - var value = new Vector4(values); - if (_squaredRgb) - value = PseudoSqrtRgb(value); - if (ImGui.ColorEdit4("##0", ref value, ImGuiColorEditFlags.Float | ImGuiColorEditFlags.AlphaPreviewHalf | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) && !disabled) + case 4: { + ImGui.SetNextItemWidth(editorWidth); + var value = new Vector4(values); + if (_squaredRgb) + value = PseudoSqrtRgb(value); + if (!ImGui.ColorEdit4("##0", ref value, + ImGuiColorEditFlags.Float | ImGuiColorEditFlags.AlphaPreviewHalf | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) + || disabled) + return false; + if (_squaredRgb) value = PseudoSquareRgb(value); if (_clamped) @@ -175,11 +186,8 @@ public partial class ModEditWindow value.CopyTo(values); return true; } - - return false; + default: return FloatConstantEditor.Default.Draw(values, disabled, editorWidth); } - else - return FloatConstantEditor.Default.Draw(values, disabled, editorWidth); } } @@ -188,9 +196,7 @@ public partial class ModEditWindow private readonly IReadOnlyList<(string Label, float Value, string Description)> _values; public EnumConstantEditor(IReadOnlyList<(string Label, float Value, string Description)> values) - { - _values = values; - } + => _values = values; public bool Draw(Span values, bool disabled, float editorWidth) { @@ -200,33 +206,40 @@ public partial class ModEditWindow for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) { + using var id = ImRaii.PushId(valueIdx); if (valueIdx > 0) ImGui.SameLine(); ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); var currentValue = values[valueIdx]; - var (currentLabel, _, currentDescription) = _values.FirstOrNull(v => v.Value == currentValue) ?? (currentValue.ToString(), currentValue, string.Empty); - if (disabled) - ImGui.InputText($"##{valueIdx}", ref currentLabel, (uint)currentLabel.Length, ImGuiInputTextFlags.ReadOnly); - else - { - using var c = ImRaii.Combo($"##{valueIdx}", currentLabel); - { - if (c) - foreach (var (valueLabel, value, valueDescription) in _values) - { - if (ImGui.Selectable(valueLabel, value == currentValue)) - { - values[valueIdx] = value; - ret = true; - } + var currentLabel = _values.FirstOrNull(v => v.Value == currentValue)?.Label + ?? currentValue.ToString(CultureInfo.CurrentCulture); + ret = disabled + ? ImGui.InputText(string.Empty, ref currentLabel, (uint)currentLabel.Length, ImGuiInputTextFlags.ReadOnly) + : DrawCombo(currentLabel, ref values[valueIdx]); + } - if (valueDescription.Length > 0) - ImGuiUtil.SelectableHelpMarker(valueDescription); - } - } + return ret; + } + + private bool DrawCombo(string label, ref float currentValue) + { + using var c = ImRaii.Combo(string.Empty, label); + if (!c) + return false; + + var ret = false; + foreach (var (valueLabel, value, valueDescription) in _values) + { + if (ImGui.Selectable(valueLabel, value == currentValue)) + { + currentValue = value; + ret = true; } + + if (valueDescription.Length > 0) + ImGuiUtil.SelectableHelpMarker(valueDescription); } return ret; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 6677db5b..12f7acd7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; -using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; using Newtonsoft.Json.Linq; @@ -17,10 +16,8 @@ using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; -using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; -using Penumbra.Util; using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.UI.AdvancedWindow; @@ -48,28 +45,32 @@ public partial class ModEditWindow public ShpkFile? AssociatedShpk; public JObject? AssociatedShpkDevkit; - public readonly string LoadedBaseDevkitPathName = string.Empty; + public readonly string LoadedBaseDevkitPathName; public readonly JObject? AssociatedBaseDevkit; // Shader Key State - public readonly List< (string Label, int Index, string Description, bool MonoFont, IReadOnlyList< (string Label, uint Value, string Description) > Values) > ShaderKeys = new(16); + public readonly + List<(string Label, int Index, string Description, bool MonoFont, IReadOnlyList<(string Label, uint Value, string Description)> + Values)> ShaderKeys = new(16); - public readonly HashSet< int > VertexShaders = new(16); - public readonly HashSet< int > PixelShaders = new(16); - public bool ShadersKnown = false; - public string VertexShadersString = "Vertex Shaders: ???"; - public string PixelShadersString = "Pixel Shaders: ???"; + public readonly HashSet VertexShaders = new(16); + public readonly HashSet PixelShaders = new(16); + public bool ShadersKnown; + public string VertexShadersString = "Vertex Shaders: ???"; + public string PixelShadersString = "Pixel Shaders: ???"; // Textures & Samplers - public readonly List< (string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont) > Textures = new(4); + public readonly List<(string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont)> Textures = new(4); - public readonly HashSet< int > UnfoldedTextures = new(4); - public readonly HashSet< uint > SamplerIds = new(16); - public float TextureLabelWidth; - public bool UseColorDyeSet; + public readonly HashSet UnfoldedTextures = new(4); + public readonly HashSet SamplerIds = new(16); + public float TextureLabelWidth; + public bool UseColorDyeSet; // Material Constants - public readonly List< (string Header, List< (string Label, int ConstantIndex, Range Slice, string Description, bool MonoFont, IConstantEditor Editor) > Constants) > Constants = new(16); + public readonly + List<(string Header, List<(string Label, int ConstantIndex, Range Slice, string Description, bool MonoFont, IConstantEditor Editor)> + Constants)> Constants = new(16); // Live-Previewers public readonly List MaterialPreviewers = new(4); @@ -77,15 +78,13 @@ public partial class ModEditWindow public int HighlightedColorSetRow = -1; public readonly Stopwatch HighlightTime = new(); - public FullPath FindAssociatedShpk( out string defaultPath, out Utf8GamePath defaultGamePath ) + public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) { - defaultPath = GamePaths.Shader.ShpkPath( Mtrl.ShaderPackage.Name ); - if( !Utf8GamePath.FromString( defaultPath, out defaultGamePath, true ) ) - { + defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); + if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath, true)) return FullPath.Empty; - } - return _edit.FindBestMatch( defaultGamePath ); + return _edit.FindBestMatch(defaultGamePath); } public string[] GetShpkNames() @@ -102,7 +101,7 @@ public partial class ModEditWindow return _shpkNames; } - public void LoadShpk( FullPath path ) + public void LoadShpk(FullPath path) { ShaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; @@ -110,26 +109,30 @@ public partial class ModEditWindow { LoadedShpkPath = path; var data = LoadedShpkPath.IsRooted - ? File.ReadAllBytes( LoadedShpkPath.FullName ) - : _edit._dalamud.GameData.GetFile( LoadedShpkPath.InternalName.ToString() )?.Data; - AssociatedShpk = data?.Length > 0 ? new ShpkFile( data ) : throw new Exception( "Failure to load file data." ); + ? File.ReadAllBytes(LoadedShpkPath.FullName) + : _edit._dalamud.GameData.GetFile(LoadedShpkPath.InternalName.ToString())?.Data; + AssociatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); LoadedShpkPathName = path.ToPath(); } - catch( Exception e ) + catch (Exception e) { LoadedShpkPath = FullPath.Empty; LoadedShpkPathName = string.Empty; AssociatedShpk = null; - Penumbra.Chat.NotificationMessage( $"Could not load {LoadedShpkPath.ToPath()}:\n{e}", "Penumbra Advanced Editing", NotificationType.Error ); + Penumbra.Chat.NotificationMessage($"Could not load {LoadedShpkPath.ToPath()}:\n{e}", "Penumbra Advanced Editing", + NotificationType.Error); } - if( LoadedShpkPath.InternalName.IsEmpty ) + if (LoadedShpkPath.InternalName.IsEmpty) { AssociatedShpkDevkit = null; LoadedShpkDevkitPathName = string.Empty; } else - AssociatedShpkDevkit = TryLoadShpkDevkit( Path.GetFileNameWithoutExtension( Mtrl.ShaderPackage.Name ), out LoadedShpkDevkitPathName ); + { + AssociatedShpkDevkit = + TryLoadShpkDevkit(Path.GetFileNameWithoutExtension(Mtrl.ShaderPackage.Name), out LoadedShpkDevkitPathName); + } UpdateShaderKeys(); Update(); @@ -157,10 +160,8 @@ public partial class ModEditWindow } private T? TryGetShpkDevkitData(string category, uint? id, bool mayVary) where T : class - { - return TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) - ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); - } + => TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) + ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); private T? TryGetShpkDevkitData(JObject? devkit, string devkitPathName, string category, uint? id, bool mayVary) where T : class { @@ -175,7 +176,7 @@ public partial class ModEditWindow if (mayVary && (data as JObject)?["Vary"] != null) { - var selector = BuildSelector(data!["Vary"]! + var selector = BuildSelector(data["Vary"]! .Select(key => (uint)key) .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); var index = (int)data["Selectors"]![selector.ToString()]!; @@ -192,14 +193,13 @@ public partial class ModEditWindow } } - public void UpdateShaderKeys() + private void UpdateShaderKeys() { ShaderKeys.Clear(); if (AssociatedShpk != null) - { foreach (var key in AssociatedShpk.MaterialKeys) { - var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); + var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); var valueSet = new HashSet(key.Values); @@ -211,8 +211,8 @@ public partial class ModEditWindow { if (dkData != null && dkData.Values.TryGetValue(value, out var dkValue)) return (dkValue.Label.Length > 0 ? dkValue.Label : $"0x{value:X8}", value, dkValue.Description); - else - return ($"0x{value:X8}", value, string.Empty); + + return ($"0x{value:X8}", value, string.Empty); }).ToArray(); Array.Sort(values, (x, y) => { @@ -220,31 +220,33 @@ public partial class ModEditWindow return -1; if (y.Value == key.DefaultValue) return 1; - return x.Label.CompareTo(y.Label); + + return string.Compare(x.Label, y.Label, StringComparison.Ordinal); }); - ShaderKeys.Add((hasDkLabel ? dkData!.Label : $"0x{key.Id:X8}", mtrlKeyIndex, dkData?.Description ?? string.Empty, !hasDkLabel, values)); + ShaderKeys.Add((hasDkLabel ? dkData!.Label : $"0x{key.Id:X8}", mtrlKeyIndex, dkData?.Description ?? string.Empty, + !hasDkLabel, values)); } - } else - { foreach (var (key, index) in Mtrl.ShaderPackage.ShaderKeys.WithIndex()) ShaderKeys.Add(($"0x{key.Category:X8}", index, string.Empty, true, Array.Empty<(string, uint, string)>())); - } } - public void UpdateShaders() + private void UpdateShaders() { VertexShaders.Clear(); PixelShaders.Clear(); if (AssociatedShpk == null) + { ShadersKnown = false; + } else { ShadersKnown = true; var systemKeySelectors = AllSelectors(AssociatedShpk.SystemKeys).ToArray(); var sceneKeySelectors = AllSelectors(AssociatedShpk.SceneKeys).ToArray(); var subViewKeySelectors = AllSelectors(AssociatedShpk.SubViewKeys).ToArray(); - var materialKeySelector = BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); + var materialKeySelector = + BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); foreach (var systemKeySelector in systemKeySelectors) { foreach (var sceneKeySelector in sceneKeySelectors) @@ -252,15 +254,13 @@ public partial class ModEditWindow foreach (var subViewKeySelector in subViewKeySelectors) { var selector = BuildSelector(systemKeySelector, sceneKeySelector, materialKeySelector, subViewKeySelector); - var node = AssociatedShpk.GetNodeBySelector(selector); + var node = AssociatedShpk.GetNodeBySelector(selector); if (node.HasValue) - { foreach (var pass in node.Value.Passes) { VertexShaders.Add((int)pass.VertexShader); PixelShaders.Add((int)pass.PixelShader); } - } else ShadersKnown = false; } @@ -272,12 +272,12 @@ public partial class ModEditWindow var pixelShaders = PixelShaders.OrderBy(i => i).Select(i => $"#{i}"); VertexShadersString = $"Vertex Shaders: {string.Join(", ", ShadersKnown ? vertexShaders : vertexShaders.Append("???"))}"; - PixelShadersString = $"Pixel Shaders: {string.Join(", ", ShadersKnown ? pixelShaders : pixelShaders.Append("???"))}"; + PixelShadersString = $"Pixel Shaders: {string.Join(", ", ShadersKnown ? pixelShaders : pixelShaders.Append("???"))}"; ShaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; } - public void UpdateTextures() + private void UpdateTextures() { Textures.Clear(); SamplerIds.Clear(); @@ -302,50 +302,63 @@ public partial class ModEditWindow if (Mtrl.ColorSets.Any(c => c.HasRows)) SamplerIds.Add(TableSamplerId); } + foreach (var samplerId in SamplerIds) { var shpkSampler = AssociatedShpk.GetSamplerById(samplerId); - if (!shpkSampler.HasValue || shpkSampler.Value.Slot != 2) + if (shpkSampler is not { Slot: 2 }) continue; - var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); + var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); - Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, dkData?.Description ?? string.Empty, !hasDkLabel)); + Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, + dkData?.Description ?? string.Empty, !hasDkLabel)); } + if (SamplerIds.Contains(TableSamplerId)) Mtrl.FindOrAddColorSet(); } + Textures.Sort((x, y) => string.CompareOrdinal(x.Label, y.Label)); TextureLabelWidth = 50f * UiHelpers.Scale; float helpWidth; using (var _ = ImRaii.PushFont(UiBuilder.IconFont)) + { helpWidth = ImGui.GetStyle().ItemSpacing.X + ImGui.CalcTextSize(FontAwesomeIcon.InfoCircle.ToIconString()).X; + } foreach (var (label, _, _, description, monoFont) in Textures) + { if (!monoFont) TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); + } using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) { foreach (var (label, _, _, description, monoFont) in Textures) + { if (monoFont) - TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); + TextureLabelWidth = Math.Max(TextureLabelWidth, + ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); + } } TextureLabelWidth = TextureLabelWidth / UiHelpers.Scale + 4; } - public void UpdateConstants() + private void UpdateConstants() { static List FindOrAddGroup(List<(string, List)> groups, string name) { foreach (var (groupName, group) in groups) + { if (string.Equals(name, groupName, StringComparison.Ordinal)) return group; + } var newGroup = new List(16); groups.Add((name, newGroup)); @@ -360,7 +373,10 @@ public partial class ModEditWindow { var values = Mtrl.GetConstantValues(constant); for (var i = 0; i < values.Length; i += 4) - fcGroup.Add(($"0x{constant.Id:X8}", index, i..Math.Min(i + 4, values.Length), string.Empty, true, FloatConstantEditor.Default)); + { + fcGroup.Add(($"0x{constant.Id:X8}", index, i..Math.Min(i + 4, values.Length), string.Empty, true, + FloatConstantEditor.Default)); + } } } else @@ -371,13 +387,12 @@ public partial class ModEditWindow if ((shpkConstant.ByteSize & 0x3) != 0) continue; - var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, shpkConstant.ByteSize >> 2, out var constantIndex); - var values = Mtrl.GetConstantValues(constant); + var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, shpkConstant.ByteSize >> 2, out var constantIndex); + var values = Mtrl.GetConstantValues(constant); var handledElements = new IndexSet(values.Length, false); var dkData = TryGetShpkDevkitData("Constants", shpkConstant.Id, true); if (dkData != null) - { foreach (var dkConstant in dkData) { var offset = (int)dkConstant.Offset; @@ -386,13 +401,13 @@ public partial class ModEditWindow length = Math.Min(length, (int)dkConstant.Length.Value); if (length <= 0) continue; + var editor = dkConstant.CreateEditor(); if (editor != null) FindOrAddGroup(Constants, dkConstant.Group.Length > 0 ? dkConstant.Group : "Further Constants") .Add((dkConstant.Label, constantIndex, offset..(offset + length), dkConstant.Description, false, editor)); handledElements.AddRange(offset, length); } - } var fcGroup = FindOrAddGroup(Constants, "Further Constants"); foreach (var (start, end) in handledElements.Ranges(true)) @@ -403,15 +418,20 @@ public partial class ModEditWindow for (int i = (start & ~0x3) - (offset & 0x3), j = offset >> 2; i < end; i += 4, ++j) { var rangeStart = Math.Max(i, start); - var rangeEnd = Math.Min(i + 4, end); + var rangeEnd = Math.Min(i + 4, end); if (rangeEnd > rangeStart) - fcGroup.Add(($"{prefix}[{j:D2}]{VectorSwizzle((offset + rangeStart) & 0x3, (offset + rangeEnd - 1) & 0x3)} (0x{shpkConstant.Id:X8})", constantIndex, rangeStart..rangeEnd, string.Empty, true, FloatConstantEditor.Default)); + fcGroup.Add(( + $"{prefix}[{j:D2}]{VectorSwizzle((offset + rangeStart) & 0x3, (offset + rangeEnd - 1) & 0x3)} (0x{shpkConstant.Id:X8})", + constantIndex, rangeStart..rangeEnd, string.Empty, true, FloatConstantEditor.Default)); } } else { for (var i = start; i < end; i += 4) - fcGroup.Add(($"0x{shpkConstant.Id:X8}", constantIndex, i..Math.Min(i + 4, end), string.Empty, true, FloatConstantEditor.Default)); + { + fcGroup.Add(($"0x{shpkConstant.Id:X8}", constantIndex, i..Math.Min(i + 4, end), string.Empty, true, + FloatConstantEditor.Default)); + } } } } @@ -424,20 +444,23 @@ public partial class ModEditWindow return 1; if (string.Equals(y.Header, "Further Constants", StringComparison.Ordinal)) return -1; + return string.Compare(x.Header, y.Header, StringComparison.Ordinal); }); // HACK the Replace makes w appear after xyz, for the cbuffer-location-based naming scheme foreach (var (_, group) in Constants) + { group.Sort((x, y) => string.CompareOrdinal( x.MonoFont ? x.Label.Replace("].w", "].{") : x.Label, y.MonoFont ? y.Label.Replace("].w", "].{") : y.Label)); + } } public unsafe void BindToMaterialInstances() { UnbindFromMaterialInstances(); - var localPlayer = FindLocalPlayer(_edit._dalamud.Objects); + var localPlayer = LocalPlayer(_edit._dalamud.Objects); if (null == localPlayer) return; @@ -449,7 +472,9 @@ public partial class ModEditWindow var drawObjects = stackalloc CharacterBase*[4]; drawObjects[0] = drawObject; - + drawObjects[1] = *((CharacterBase**)&localPlayer->DrawData.MainHand + 1); + drawObjects[2] = *((CharacterBase**)&localPlayer->DrawData.OffHand + 1); + drawObjects[3] = *((CharacterBase**)&localPlayer->DrawData.UnkF0 + 1); for (var i = 0; i < 3; ++i) { var subActor = FindSubActor(localPlayer, i); @@ -470,9 +495,11 @@ public partial class ModEditWindow var material = GetDrawObjectMaterial(drawObjects[subActorType + 1], modelSlot, materialSlot); if (foundMaterials.Contains((nint)material)) continue; + try { - MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._dalamud.Objects, subActorType, childObjectIndex, modelSlot, materialSlot)); + MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._dalamud.Objects, subActorType, childObjectIndex, modelSlot, + materialSlot)); foundMaterials.Add((nint)material); } catch (InvalidOperationException) @@ -480,28 +507,31 @@ public partial class ModEditWindow // Carry on without that previewer. } } + UpdateMaterialPreview(); var colorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); - if (colorSet.HasValue) + if (!colorSet.HasValue) + return; + + foreach (var (subActorType, childObjectIndex, modelSlot, materialSlot) in instances) { - foreach (var (subActorType, childObjectIndex, modelSlot, materialSlot) in instances) + try { - try - { - ColorSetPreviewers.Add(new LiveColorSetPreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, subActorType, childObjectIndex, modelSlot, materialSlot)); - } - catch (InvalidOperationException) - { - // Carry on without that previewer. - } + ColorSetPreviewers.Add(new LiveColorSetPreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, subActorType, + childObjectIndex, modelSlot, materialSlot)); + } + catch (InvalidOperationException) + { + // Carry on without that previewer. } - UpdateColorSetPreview(); } + + UpdateColorSetPreview(); } - public void UnbindFromMaterialInstances() + private void UnbindFromMaterialInstances() { foreach (var previewer in MaterialPreviewers) previewer.Dispose(); @@ -512,9 +542,9 @@ public partial class ModEditWindow ColorSetPreviewers.Clear(); } - public unsafe void UnbindFromDrawObjectMaterialInstances(nint characterBase) + private unsafe void UnbindFromDrawObjectMaterialInstances(nint characterBase) { - for (var i = MaterialPreviewers.Count; i-- > 0; ) + for (var i = MaterialPreviewers.Count; i-- > 0;) { var previewer = MaterialPreviewers[i]; if ((nint)previewer.DrawObject != characterBase) @@ -553,7 +583,7 @@ public partial class ModEditWindow previewer.SetSamplerFlags(samplerCrc, samplerFlags); } - public void UpdateMaterialPreview() + private void UpdateMaterialPreview() { SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); foreach (var constant in Mtrl.ShaderPackage.Constants) @@ -562,6 +592,7 @@ public partial class ModEditWindow if (values != null) SetMaterialParameter(constant.Id, 0, values); } + foreach (var sampler in Mtrl.ShaderPackage.Samplers) SetSamplerFlags(sampler.SamplerId, sampler.Flags); } @@ -602,7 +633,7 @@ public partial class ModEditWindow if (!maybeColorSet.HasValue) return; - var colorSet = maybeColorSet.Value; + var colorSet = maybeColorSet.Value; var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); var row = colorSet.Rows[rowIdx]; @@ -610,7 +641,7 @@ public partial class ModEditWindow { var stm = _edit._stainService.StmFile; var dye = maybeColorDyeSet.Value.Rows[rowIdx]; - if (stm.TryGetValue(dye.Template, (StainId)_edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) + if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) row.ApplyDyeTemplate(dye, dyes); } @@ -619,7 +650,8 @@ public partial class ModEditWindow foreach (var previewer in ColorSetPreviewers) { - row.AsHalves().CopyTo(previewer.ColorSet.AsSpan().Slice(LiveColorSetPreviewer.TextureWidth * 4 * rowIdx, LiveColorSetPreviewer.TextureWidth * 4)); + row.AsHalves().CopyTo(previewer.ColorSet.AsSpan() + .Slice(LiveColorSetPreviewer.TextureWidth * 4 * rowIdx, LiveColorSetPreviewer.TextureWidth * 4)); previewer.ScheduleUpdate(); } } @@ -633,19 +665,19 @@ public partial class ModEditWindow if (!maybeColorSet.HasValue) return; - var colorSet = maybeColorSet.Value; + var colorSet = maybeColorSet.Value; var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); var rows = colorSet.Rows; if (maybeColorDyeSet.HasValue && UseColorDyeSet) { - var stm = _edit._stainService.StmFile; - var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; + var stm = _edit._stainService.StmFile; + var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; var colorDyeSet = maybeColorDyeSet.Value; for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) { ref var row = ref rows[i]; - var dye = colorDyeSet.Rows[i]; + var dye = colorDyeSet.Rows[i]; if (stm.TryGetValue(dye.Template, stainId, out var dyes)) row.ApplyDyeTemplate(dye, dyes); } @@ -663,10 +695,10 @@ public partial class ModEditWindow private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, float time) { - var level = Math.Sin(time * 2.0 * Math.PI) * 0.25 + 0.5; + var level = Math.Sin(time * 2.0 * Math.PI) * 0.25 + 0.5; var levelSq = (float)(level * level); - row.Diffuse = Vector3.Zero; + row.Diffuse = Vector3.Zero; row.Specular = Vector3.Zero; row.Emissive = new Vector3(levelSq); } @@ -678,15 +710,15 @@ public partial class ModEditWindow UpdateConstants(); } - public MtrlTab( ModEditWindow edit, MtrlFile file, string filePath, bool writable ) + public MtrlTab(ModEditWindow edit, MtrlFile file, string filePath, bool writable) { - _edit = edit; - Mtrl = file; - FilePath = filePath; - Writable = writable; - UseColorDyeSet = file.ColorDyeSets.Length > 0; - AssociatedBaseDevkit = TryLoadShpkDevkit( "_base", out LoadedBaseDevkitPathName ); - LoadShpk( FindAssociatedShpk( out _, out _ ) ); + _edit = edit; + Mtrl = file; + FilePath = filePath; + Writable = writable; + UseColorDyeSet = file.ColorDyeSets.Length > 0; + AssociatedBaseDevkit = TryLoadShpkDevkit("_base", out LoadedBaseDevkitPathName); + LoadShpk(FindAssociatedShpk(out _, out _)); if (writable) { _edit._gameEvents.CharacterBaseDestructor += UnbindFromDrawObjectMaterialInstances; @@ -694,18 +726,7 @@ public partial class ModEditWindow } } - ~MtrlTab() - { - DoDispose(); - } - public void Dispose() - { - DoDispose(); - GC.SuppressFinalize(this); - } - - private void DoDispose() { UnbindFromMaterialInstances(); if (Writable) @@ -723,11 +744,7 @@ public partial class ModEditWindow return output.Write(); } - private sealed class DevkitShaderKeyValue - { - public string Label = string.Empty; - public string Description = string.Empty; - } + private sealed record DevkitShaderKeyValue(string Label = "", string Description = ""); private sealed class DevkitShaderKey { @@ -736,12 +753,7 @@ public partial class ModEditWindow public Dictionary Values = new(); } - private sealed class DevkitSampler - { - public string Label = string.Empty; - public string Description = string.Empty; - public string DefaultTexture = string.Empty; - } + private sealed record DevkitSampler(string Label = "", string Description = "", string DefaultTexture = ""); private enum DevkitConstantType { @@ -752,12 +764,7 @@ public partial class ModEditWindow Enum = 3, } - private sealed class DevkitConstantValue - { - public string Label = string.Empty; - public string Description = string.Empty; - public float Value = 0.0f; - } + private sealed record DevkitConstantValue(string Label = "", string Description = "", float Value = 0); private sealed class DevkitConstant { @@ -783,25 +790,20 @@ public partial class ModEditWindow public DevkitConstantValue[] Values = Array.Empty(); public IConstantEditor? CreateEditor() - { - switch (Type) + => Type switch { - case DevkitConstantType.Hidden: - return null; - case DevkitConstantType.Float: - return new FloatConstantEditor(Minimum, Maximum, Speed ?? 0.1f, RelativeSpeed, Factor, Bias, Precision, Unit); - case DevkitConstantType.Integer: - return new IntConstantEditor(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, Factor, Bias, Unit); - case DevkitConstantType.Color: - return new ColorConstantEditor(SquaredRgb, Clamped); - case DevkitConstantType.Enum: - return new EnumConstantEditor(Array.ConvertAll(Values, value => (value.Label, value.Value, value.Description))); - default: - return FloatConstantEditor.Default; - } - } + DevkitConstantType.Hidden => null, + DevkitConstantType.Float => new FloatConstantEditor(Minimum, Maximum, Speed ?? 0.1f, RelativeSpeed, Factor, Bias, Precision, + Unit), + DevkitConstantType.Integer => new IntConstantEditor(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, + Factor, Bias, Unit), + DevkitConstantType.Color => new ColorConstantEditor(SquaredRgb, Clamped), + DevkitConstantType.Enum => new EnumConstantEditor(Array.ConvertAll(Values, + value => (value.Label, value.Value, value.Description))), + _ => FloatConstantEditor.Default, + }; - private int? ToInteger(float? value) + private static int? ToInteger(float? value) => value.HasValue ? (int)Math.Clamp(MathF.Round(value.Value), int.MinValue, int.MaxValue) : null; } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 0f13f47e..8fca8aa6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -1,18 +1,12 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Numerics; using System.Text; using Dalamud.Interface; -using Dalamud.Interface.ImGuiFileDialog; using ImGuiNET; -using Lumina.Data.Parsing; -using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Raii; using Penumbra.GameData; -using Penumbra.GameData.Files; using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -25,7 +19,7 @@ public partial class ModEditWindow // Apricot shader packages are unlisted because // 1. they cause performance/memory issues when calculating the effective shader set // 2. they probably aren't intended for use with materials anyway - private static readonly IReadOnlyList StandardShaderPackages = new string[] + private static readonly IReadOnlyList StandardShaderPackages = new[] { "3dui.shpk", // "apricot_decal_dummy.shpk", @@ -76,7 +70,7 @@ public partial class ModEditWindow Border = 3, } - private static readonly IReadOnlyList TextureAddressModeTooltips = new string[] + private static readonly IReadOnlyList TextureAddressModeTooltips = new[] { "Tile the texture at every UV integer junction.\n\nFor example, for U values between 0 and 3, the texture is repeated three times.", "Flip the texture at every UV integer junction.\n\nFor U values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is mirrored; between 2 and 3, the texture is normal again; and so on.", @@ -113,18 +107,15 @@ public partial class ModEditWindow private static bool DrawShaderFlagsInput(MtrlTab tab, bool disabled) { - var ret = false; var shpkFlags = (int)tab.Mtrl.ShaderPackage.Flags; ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); - if (ImGui.InputInt("Shader Flags", ref shpkFlags, 0, 0, + if (!ImGui.InputInt("Shader Flags", ref shpkFlags, 0, 0, ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) - { - tab.Mtrl.ShaderPackage.Flags = (uint)shpkFlags; - ret = true; - tab.SetShaderPackageFlags((uint)shpkFlags); - } + return false; - return ret; + tab.Mtrl.ShaderPackage.Flags = (uint)shpkFlags; + tab.SetShaderPackageFlags((uint)shpkFlags); + return true; } /// diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index b89bab01..102a6778 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -6,34 +6,35 @@ using OtterGui; using OtterGui.Raii; using Penumbra.GameData.Files; using Penumbra.String.Classes; +using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private readonly FileEditor< MtrlTab > _materialTab; + private readonly FileEditor _materialTab; - private bool DrawMaterialPanel( MtrlTab tab, bool disabled ) + private bool DrawMaterialPanel(MtrlTab tab, bool disabled) { - DrawMaterialLivePreviewRebind( tab, disabled ); + DrawMaterialLivePreviewRebind(tab, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - var ret = DrawBackFaceAndTransparency( tab, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + var ret = DrawBackFaceAndTransparency(tab, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawMaterialShader( tab, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ret |= DrawMaterialShader(tab, disabled); - ret |= DrawMaterialTextureChange( tab, disabled ); - ret |= DrawMaterialColorSetChange( tab, disabled ); - ret |= DrawMaterialConstants( tab, disabled ); + ret |= DrawMaterialTextureChange(tab, disabled); + ret |= DrawMaterialColorSetChange(tab, disabled); + ret |= DrawMaterialConstants(tab, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - DrawOtherMaterialDetails( tab.Mtrl, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + DrawOtherMaterialDetails(tab.Mtrl, disabled); return !disabled && ret; } - private static void DrawMaterialLivePreviewRebind( MtrlTab tab, bool disabled ) + private static void DrawMaterialLivePreviewRebind(MtrlTab tab, bool disabled) { if (disabled) return; @@ -41,82 +42,74 @@ public partial class ModEditWindow if (ImGui.Button("Reload live preview")) tab.BindToMaterialInstances(); - if (tab.MaterialPreviewers.Count == 0 && tab.ColorSetPreviewers.Count == 0) - { - ImGui.SameLine(); + if (tab.MaterialPreviewers.Count != 0 || tab.ColorSetPreviewers.Count != 0) + return; - var textColor = ImGui.GetColorU32(ImGuiCol.Text); - var textColorWarning = (textColor & 0xFF000000u) | ((textColor & 0x00FEFEFE) >> 1) | 0x80u; // Half red - - using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); - - ImGui.TextUnformatted("The current material has not been found on your character. Please check the Import from Screen tab for more information."); - } + ImGui.SameLine(); + using var c = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); + ImGui.TextUnformatted( + "The current material has not been found on your character. Please check the Import from Screen tab for more information."); } - private static bool DrawMaterialTextureChange( MtrlTab tab, bool disabled ) + private static bool DrawMaterialTextureChange(MtrlTab tab, bool disabled) { - if( tab.Textures.Count == 0 ) - { + if (tab.Textures.Count == 0) return false; - } - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - if( !ImGui.CollapsingHeader( "Textures and Samplers", ImGuiTreeNodeFlags.DefaultOpen ) ) - { + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + if (!ImGui.CollapsingHeader("Textures and Samplers", ImGuiTreeNodeFlags.DefaultOpen)) return false; - } var frameHeight = ImGui.GetFrameHeight(); var ret = false; - using var table = ImRaii.Table( "##Textures", 3 ); + using var table = ImRaii.Table("##Textures", 3); - ImGui.TableSetupColumn( string.Empty, ImGuiTableColumnFlags.WidthFixed, frameHeight ); - ImGui.TableSetupColumn( "Path" , ImGuiTableColumnFlags.WidthStretch ); - ImGui.TableSetupColumn( "Name" , ImGuiTableColumnFlags.WidthFixed, tab.TextureLabelWidth * UiHelpers.Scale ); - for( var i = 0; i < tab.Textures.Count; ++i ) + ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, frameHeight); + ImGui.TableSetupColumn("Path", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthFixed, tab.TextureLabelWidth * UiHelpers.Scale); + foreach (var (label, textureI, samplerI, description, monoFont) in tab.Textures) { - var (label, textureI, samplerI, description, monoFont) = tab.Textures[i]; - - using var _ = ImRaii.PushId( samplerI ); - var tmp = tab.Mtrl.Textures[ textureI ].Path; - var unfolded = tab.UnfoldedTextures.Contains( samplerI ); + using var _ = ImRaii.PushId(samplerI); + var tmp = tab.Mtrl.Textures[textureI].Path; + var unfolded = tab.UnfoldedTextures.Contains(samplerI); ImGui.TableNextColumn(); - if( ImGuiUtil.DrawDisabledButton( ( unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight ).ToIconString(), new Vector2( frameHeight ), - "Settings for this texture and the associated sampler", false, true ) ) + if (ImGuiUtil.DrawDisabledButton((unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(), + new Vector2(frameHeight), + "Settings for this texture and the associated sampler", false, true)) { unfolded = !unfolded; - if( unfolded ) - tab.UnfoldedTextures.Add( samplerI ); + if (unfolded) + tab.UnfoldedTextures.Add(samplerI); else - tab.UnfoldedTextures.Remove( samplerI ); - } - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth( ImGui.GetContentRegionAvail().X ); - if( ImGui.InputText( string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None ) - && tmp.Length > 0 - && tmp != tab.Mtrl.Textures[ textureI ].Path ) - { - ret = true; - tab.Mtrl.Textures[ textureI ].Path = tmp; + tab.UnfoldedTextures.Remove(samplerI); } ImGui.TableNextColumn(); - using( var font = ImRaii.PushFont( UiBuilder.MonoFont, monoFont ) ) + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); + if (ImGui.InputText(string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, + disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) + && tmp.Length > 0 + && tmp != tab.Mtrl.Textures[textureI].Path) + { + ret = true; + tab.Mtrl.Textures[textureI].Path = tmp; + } + + ImGui.TableNextColumn(); + using (var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont)) { ImGui.AlignTextToFramePadding(); - if( description.Length > 0 ) - ImGuiUtil.LabeledHelpMarker( label, description ); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); else - ImGui.TextUnformatted( label ); + ImGui.TextUnformatted(label); } - if( unfolded ) + if (unfolded) { ImGui.TableNextColumn(); ImGui.TableNextColumn(); - ret |= DrawMaterialSampler( tab, disabled, textureI, samplerI ); + ret |= DrawMaterialSampler(tab, disabled, textureI, samplerI); ImGui.TableNextColumn(); } } @@ -124,26 +117,27 @@ public partial class ModEditWindow return ret; } - private static bool DrawBackFaceAndTransparency( MtrlTab tab, bool disabled ) + private static bool DrawBackFaceAndTransparency(MtrlTab tab, bool disabled) { const uint transparencyBit = 0x10; const uint backfaceBit = 0x01; var ret = false; - using var dis = ImRaii.Disabled( disabled ); + using var dis = ImRaii.Disabled(disabled); - var tmp = ( tab.Mtrl.ShaderPackage.Flags & transparencyBit ) != 0; - if( ImGui.Checkbox( "Enable Transparency", ref tmp ) ) + var tmp = (tab.Mtrl.ShaderPackage.Flags & transparencyBit) != 0; + if (ImGui.Checkbox("Enable Transparency", ref tmp)) { - tab.Mtrl.ShaderPackage.Flags = tmp ? tab.Mtrl.ShaderPackage.Flags | transparencyBit : tab.Mtrl.ShaderPackage.Flags & ~transparencyBit; - ret = true; + tab.Mtrl.ShaderPackage.Flags = + tmp ? tab.Mtrl.ShaderPackage.Flags | transparencyBit : tab.Mtrl.ShaderPackage.Flags & ~transparencyBit; + ret = true; tab.SetShaderPackageFlags(tab.Mtrl.ShaderPackage.Flags); } - ImGui.SameLine( 200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X ); - tmp = ( tab.Mtrl.ShaderPackage.Flags & backfaceBit ) != 0; - if( ImGui.Checkbox( "Hide Backfaces", ref tmp ) ) + ImGui.SameLine(200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); + tmp = (tab.Mtrl.ShaderPackage.Flags & backfaceBit) != 0; + if (ImGui.Checkbox("Hide Backfaces", ref tmp)) { tab.Mtrl.ShaderPackage.Flags = tmp ? tab.Mtrl.ShaderPackage.Flags | backfaceBit : tab.Mtrl.ShaderPackage.Flags & ~backfaceBit; ret = true; @@ -153,106 +147,80 @@ public partial class ModEditWindow return ret; } - private static void DrawOtherMaterialDetails( MtrlFile file, bool _ ) + private static void DrawOtherMaterialDetails(MtrlFile file, bool _) { - if( !ImGui.CollapsingHeader( "Further Content" ) ) - { + if (!ImGui.CollapsingHeader("Further Content")) return; + + using (var sets = ImRaii.TreeNode("UV Sets", ImGuiTreeNodeFlags.DefaultOpen)) + { + if (sets) + foreach (var set in file.UvSets) + ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); } - using( var sets = ImRaii.TreeNode( "UV Sets", ImGuiTreeNodeFlags.DefaultOpen ) ) - { - if( sets ) - { - foreach( var set in file.UvSets ) - { - ImRaii.TreeNode( $"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf ).Dispose(); - } - } - } - - if( file.AdditionalData.Length <= 0 ) - { + if (file.AdditionalData.Length <= 0) return; - } - using var t = ImRaii.TreeNode( $"Additional Data (Size: {file.AdditionalData.Length})###AdditionalData" ); - if( t ) - { - ImGuiUtil.TextWrapped( string.Join( ' ', file.AdditionalData.Select( c => $"{c:X2}" ) ) ); - } + using var t = ImRaii.TreeNode($"Additional Data (Size: {file.AdditionalData.Length})###AdditionalData"); + if (t) + ImGuiUtil.TextWrapped(string.Join(' ', file.AdditionalData.Select(c => $"{c:X2}"))); } private void DrawMaterialReassignmentTab() { - if( _editor.Files.Mdl.Count == 0 ) - { + if (_editor.Files.Mdl.Count == 0) return; - } - using var tab = ImRaii.TabItem( "Material Reassignment" ); - if( !tab ) - { + using var tab = ImRaii.TabItem("Material Reassignment"); + if (!tab) return; - } ImGui.NewLine(); - MaterialSuffix.Draw( _editor, ImGuiHelpers.ScaledVector2( 175, 0 ) ); + MaterialSuffix.Draw(_editor, ImGuiHelpers.ScaledVector2(175, 0)); ImGui.NewLine(); - using var child = ImRaii.Child( "##mdlFiles", -Vector2.One, true ); - if( !child ) - { + using var child = ImRaii.Child("##mdlFiles", -Vector2.One, true); + if (!child) return; - } - using var table = ImRaii.Table( "##files", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.One ); - if( !table ) - { + using var table = ImRaii.Table("##files", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.One); + if (!table) return; - } var iconSize = ImGui.GetFrameHeight() * Vector2.One; - foreach( var (info, idx) in _editor.MdlMaterialEditor.ModelFiles.WithIndex() ) + foreach (var (info, idx) in _editor.MdlMaterialEditor.ModelFiles.WithIndex()) { - using var id = ImRaii.PushId( idx ); + using var id = ImRaii.PushId(idx); ImGui.TableNextColumn(); - if( ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Save.ToIconString(), iconSize, - "Save the changed mdl file.\nUse at own risk!", !info.Changed, true ) ) - { + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), iconSize, + "Save the changed mdl file.\nUse at own risk!", !info.Changed, true)) info.Save(); - } ImGui.TableNextColumn(); - if( ImGuiUtil.DrawDisabledButton( FontAwesomeIcon.Recycle.ToIconString(), iconSize, - "Restore current changes to default.", !info.Changed, true ) ) - { + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), iconSize, + "Restore current changes to default.", !info.Changed, true)) info.Restore(); - } ImGui.TableNextColumn(); - ImGui.TextUnformatted( info.Path.FullName[ ( _mod!.ModPath.FullName.Length + 1 ).. ] ); + ImGui.TextUnformatted(info.Path.FullName[(_mod!.ModPath.FullName.Length + 1)..]); ImGui.TableNextColumn(); - ImGui.SetNextItemWidth( 400 * UiHelpers.Scale ); - var tmp = info.CurrentMaterials[ 0 ]; - if( ImGui.InputText( "##0", ref tmp, 64 ) ) - { - info.SetMaterial( tmp, 0 ); - } + ImGui.SetNextItemWidth(400 * UiHelpers.Scale); + var tmp = info.CurrentMaterials[0]; + if (ImGui.InputText("##0", ref tmp, 64)) + info.SetMaterial(tmp, 0); - for( var i = 1; i < info.Count; ++i ) + for (var i = 1; i < info.Count; ++i) { ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.TableNextColumn(); - ImGui.SetNextItemWidth( 400 * UiHelpers.Scale ); - tmp = info.CurrentMaterials[ i ]; - if( ImGui.InputText( $"##{i}", ref tmp, 64 ) ) - { - info.SetMaterial( tmp, i ); - } + ImGui.SetNextItemWidth(400 * UiHelpers.Scale); + tmp = info.CurrentMaterials[i]; + if (ImGui.InputText($"##{i}", ref tmp, 64)) + info.SetMaterial(tmp, i); } } } -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index b212e791..518566f5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -5,7 +5,6 @@ using Penumbra.GameData.Files; using Penumbra.String.Classes; using System.Globalization; using System.Linq; -using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 1b159efc..c0868b71 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -20,32 +20,32 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private static readonly ByteString DisassemblyLabel = ByteString.FromSpanUnsafe( "##disassembly"u8, true, true, true ); + private static readonly ByteString DisassemblyLabel = ByteString.FromSpanUnsafe("##disassembly"u8, true, true, true); - private readonly FileEditor< ShpkTab > _shaderPackageTab; + private readonly FileEditor _shaderPackageTab; - private static bool DrawShaderPackagePanel( ShpkTab file, bool disabled ) + private static bool DrawShaderPackagePanel(ShpkTab file, bool disabled) { - DrawShaderPackageSummary( file ); + DrawShaderPackageSummary(file); var ret = false; - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawShaderPackageShaderArray( file, "Vertex Shader", file.Shpk.VertexShaders, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ret |= DrawShaderPackageShaderArray(file, "Vertex Shader", file.Shpk.VertexShaders, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawShaderPackageShaderArray( file, "Pixel Shader", file.Shpk.PixelShaders, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ret |= DrawShaderPackageShaderArray(file, "Pixel Shader", file.Shpk.PixelShaders, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawShaderPackageMaterialParamLayout( file, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ret |= DrawShaderPackageMaterialParamLayout(file, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - ret |= DrawShaderPackageResources( file, disabled ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ret |= DrawShaderPackageResources(file, disabled); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - DrawShaderPackageSelection( file ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + DrawShaderPackageSelection(file); - ImGui.Dummy( new Vector2( ImGui.GetTextLineHeight() / 2 ) ); - DrawOtherShaderPackageDetails( file ); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + DrawOtherShaderPackageDetails(file); file.FileDialog.Draw(); @@ -54,28 +54,26 @@ public partial class ModEditWindow return !disabled && ret; } - private static void DrawShaderPackageSummary( ShpkTab tab ) + private static void DrawShaderPackageSummary(ShpkTab tab) { - ImGui.TextUnformatted( tab.Header ); - if( !tab.Shpk.Disassembled ) + ImGui.TextUnformatted(tab.Header); + if (!tab.Shpk.Disassembled) { - var textColor = ImGui.GetColorU32( ImGuiCol.Text ); - var textColorWarning = ( textColor & 0xFF000000u ) | ( ( textColor & 0x00FEFEFE ) >> 1 ) | 0x80u; // Half red + var textColor = ImGui.GetColorU32(ImGuiCol.Text); + var textColorWarning = (textColor & 0xFF000000u) | ((textColor & 0x00FEFEFE) >> 1) | 0x80u; // Half red - using var c = ImRaii.PushColor( ImGuiCol.Text, textColorWarning ); + using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); - ImGui.TextUnformatted( "Your system doesn't support disassembling shaders. Some functionality will be missing." ); + ImGui.TextUnformatted("Your system doesn't support disassembling shaders. Some functionality will be missing."); } } - private static void DrawShaderExportButton( ShpkTab tab, string objectName, Shader shader, int idx ) + private static void DrawShaderExportButton(ShpkTab tab, string objectName, Shader shader, int idx) { - if( !ImGui.Button( $"Export Shader Program Blob ({shader.Blob.Length} bytes)" ) ) - { + if (!ImGui.Button($"Export Shader Program Blob ({shader.Blob.Length} bytes)")) return; - } - var defaultName = objectName[ 0 ] switch + var defaultName = objectName[0] switch { 'V' => $"vs{idx}", 'P' => $"ps{idx}", @@ -83,247 +81,225 @@ public partial class ModEditWindow }; var blob = shader.Blob; - tab.FileDialog.OpenSavePicker( $"Export {objectName} #{idx} Program Blob to...", tab.Extension, defaultName, tab.Extension, ( success, name ) => - { - if( !success ) + tab.FileDialog.OpenSavePicker($"Export {objectName} #{idx} Program Blob to...", tab.Extension, defaultName, tab.Extension, + (success, name) => { - return; - } + if (!success) + return; - try - { - File.WriteAllBytes( name, blob ); - } - catch( Exception e ) - { - Penumbra.Chat.NotificationMessage( $"Could not export {defaultName}{tab.Extension} to {name}:\n{e.Message}", "Penumbra Advanced Editing", - NotificationType.Error ); - return; - } + try + { + File.WriteAllBytes(name, blob); + } + catch (Exception e) + { + Penumbra.Chat.NotificationMessage($"Could not export {defaultName}{tab.Extension} to {name}:\n{e.Message}", + "Penumbra Advanced Editing", + NotificationType.Error); + return; + } - Penumbra.Chat.NotificationMessage( $"Shader Program Blob {defaultName}{tab.Extension} exported successfully to {Path.GetFileName( name )}", - "Penumbra Advanced Editing", NotificationType.Success ); - }, null, false ); + Penumbra.Chat.NotificationMessage( + $"Shader Program Blob {defaultName}{tab.Extension} exported successfully to {Path.GetFileName(name)}", + "Penumbra Advanced Editing", NotificationType.Success); + }, null, false); } - private static void DrawShaderImportButton( ShpkTab tab, string objectName, Shader[] shaders, int idx ) + private static void DrawShaderImportButton(ShpkTab tab, string objectName, Shader[] shaders, int idx) { - if( !ImGui.Button( "Replace Shader Program Blob" ) ) - { + if (!ImGui.Button("Replace Shader Program Blob")) return; - } - tab.FileDialog.OpenFilePicker( $"Replace {objectName} #{idx} Program Blob...", "Shader Program Blobs{.o,.cso,.dxbc,.dxil}", ( success, name ) => - { - if( !success ) + tab.FileDialog.OpenFilePicker($"Replace {objectName} #{idx} Program Blob...", "Shader Program Blobs{.o,.cso,.dxbc,.dxil}", + (success, name) => { - return; - } + if (!success) + return; - try - { - shaders[ idx ].Blob = File.ReadAllBytes(name[0] ); - } - catch( Exception e ) - { - Penumbra.Chat.NotificationMessage( $"Could not import {name}:\n{e.Message}", "Penumbra Advanced Editing", NotificationType.Error ); - return; - } + try + { + shaders[idx].Blob = File.ReadAllBytes(name[0]); + } + catch (Exception e) + { + Penumbra.Chat.NotificationMessage($"Could not import {name}:\n{e.Message}", "Penumbra Advanced Editing", + NotificationType.Error); + return; + } - try - { - shaders[ idx ].UpdateResources( tab.Shpk ); - tab.Shpk.UpdateResources(); - } - catch( Exception e ) - { - tab.Shpk.SetInvalid(); - Penumbra.Chat.NotificationMessage( $"Failed to update resources after importing {name}:\n{e.Message}", "Penumbra Advanced Editing", - NotificationType.Error ); - return; - } + try + { + shaders[idx].UpdateResources(tab.Shpk); + tab.Shpk.UpdateResources(); + } + catch (Exception e) + { + tab.Shpk.SetInvalid(); + Penumbra.Chat.NotificationMessage($"Failed to update resources after importing {name}:\n{e.Message}", + "Penumbra Advanced Editing", + NotificationType.Error); + return; + } - tab.Shpk.SetChanged(); - }, 1, null, false ); + tab.Shpk.SetChanged(); + }, 1, null, false); } - private static unsafe void DrawRawDisassembly( Shader shader ) + private static unsafe void DrawRawDisassembly(Shader shader) { - using var t2 = ImRaii.TreeNode( "Raw Program Disassembly" ); - if( !t2 ) - { + using var t2 = ImRaii.TreeNode("Raw Program Disassembly"); + if (!t2) return; - } - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - var size = new Vector2( ImGui.GetContentRegionAvail().X, ImGui.GetTextLineHeight() * 20 ); - ImGuiNative.igInputTextMultiline( DisassemblyLabel.Path, shader.Disassembly!.RawDisassembly.Path, ( uint )shader.Disassembly!.RawDisassembly.Length + 1, size, - ImGuiInputTextFlags.ReadOnly, null, null ); + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + var size = new Vector2(ImGui.GetContentRegionAvail().X, ImGui.GetTextLineHeight() * 20); + ImGuiNative.igInputTextMultiline(DisassemblyLabel.Path, shader.Disassembly!.RawDisassembly.Path, + (uint)shader.Disassembly!.RawDisassembly.Length + 1, size, + ImGuiInputTextFlags.ReadOnly, null, null); } - private static bool DrawShaderPackageShaderArray( ShpkTab tab, string objectName, Shader[] shaders, bool disabled ) + private static bool DrawShaderPackageShaderArray(ShpkTab tab, string objectName, Shader[] shaders, bool disabled) { - if( shaders.Length == 0 || !ImGui.CollapsingHeader( $"{objectName}s" ) ) - { + if (shaders.Length == 0 || !ImGui.CollapsingHeader($"{objectName}s")) return false; - } var ret = false; - for( var idx = 0; idx < shaders.Length; ++idx ) + for (var idx = 0; idx < shaders.Length; ++idx) { - var shader = shaders[ idx ]; - using var t = ImRaii.TreeNode( $"{objectName} #{idx}" ); - if( !t ) - { + var shader = shaders[idx]; + using var t = ImRaii.TreeNode($"{objectName} #{idx}"); + if (!t) continue; - } - DrawShaderExportButton( tab, objectName, shader, idx ); - if( !disabled && tab.Shpk.Disassembled ) + DrawShaderExportButton(tab, objectName, shader, idx); + if (!disabled && tab.Shpk.Disassembled) { ImGui.SameLine(); - DrawShaderImportButton( tab, objectName, shaders, idx ); + DrawShaderImportButton(tab, objectName, shaders, idx); } - ret |= DrawShaderPackageResourceArray( "Constant Buffers", "slot", true, shader.Constants, true ); - ret |= DrawShaderPackageResourceArray( "Samplers", "slot", false, shader.Samplers, true ); - ret |= DrawShaderPackageResourceArray( "Unordered Access Views", "slot", true, shader.Uavs, true ); + ret |= DrawShaderPackageResourceArray("Constant Buffers", "slot", true, shader.Constants, true); + ret |= DrawShaderPackageResourceArray("Samplers", "slot", false, shader.Samplers, true); + ret |= DrawShaderPackageResourceArray("Unordered Access Views", "slot", true, shader.Uavs, true); - if( shader.AdditionalHeader.Length > 0 ) + if (shader.AdditionalHeader.Length > 0) { - using var t2 = ImRaii.TreeNode( $"Additional Header (Size: {shader.AdditionalHeader.Length})###AdditionalHeader" ); - if( t2 ) - { - ImGuiUtil.TextWrapped( string.Join( ' ', shader.AdditionalHeader.Select( c => $"{c:X2}" ) ) ); - } + using var t2 = ImRaii.TreeNode($"Additional Header (Size: {shader.AdditionalHeader.Length})###AdditionalHeader"); + if (t2) + ImGuiUtil.TextWrapped(string.Join(' ', shader.AdditionalHeader.Select(c => $"{c:X2}"))); } - if( tab.Shpk.Disassembled ) - DrawRawDisassembly( shader ); + if (tab.Shpk.Disassembled) + DrawRawDisassembly(shader); } return ret; } - private static bool DrawShaderPackageResource( string slotLabel, bool withSize, ref Resource resource, bool disabled ) + private static bool DrawShaderPackageResource(string slotLabel, bool withSize, ref Resource resource, bool disabled) { var ret = false; - if( !disabled ) + if (!disabled) { - ImGui.SetNextItemWidth( UiHelpers.Scale * 150.0f ); - if( ImGuiUtil.InputUInt16( $"{char.ToUpper( slotLabel[ 0 ] )}{slotLabel[ 1.. ].ToLower()}", ref resource.Slot, ImGuiInputTextFlags.None ) ) - { + ImGui.SetNextItemWidth(UiHelpers.Scale * 150.0f); + if (ImGuiUtil.InputUInt16($"{char.ToUpper(slotLabel[0])}{slotLabel[1..].ToLower()}", ref resource.Slot, ImGuiInputTextFlags.None)) ret = true; - } } - if( resource.Used == null ) - { + if (resource.Used == null) return ret; - } - var usedString = UsedComponentString( withSize, resource ); - if( usedString.Length > 0 ) - { - ImRaii.TreeNode( $"Used: {usedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + var usedString = UsedComponentString(withSize, resource); + if (usedString.Length > 0) + ImRaii.TreeNode($"Used: {usedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); else - { - ImRaii.TreeNode( "Unused", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + ImRaii.TreeNode("Unused", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); return ret; } - private static bool DrawShaderPackageResourceArray( string arrayName, string slotLabel, bool withSize, Resource[] resources, bool disabled ) + private static bool DrawShaderPackageResourceArray(string arrayName, string slotLabel, bool withSize, Resource[] resources, bool disabled) { - if( resources.Length == 0 ) - { + if (resources.Length == 0) return false; - } - using var t = ImRaii.TreeNode( arrayName ); - if( !t ) - { + using var t = ImRaii.TreeNode(arrayName); + if (!t) return false; - } var ret = false; - for( var idx = 0; idx < resources.Length; ++idx ) + for (var idx = 0; idx < resources.Length; ++idx) { - ref var buf = ref resources[ idx ]; + ref var buf = ref resources[idx]; var name = $"#{idx}: {buf.Name} (ID: 0x{buf.Id:X8}), {slotLabel}: {buf.Slot}" - + ( withSize ? $", size: {buf.Size} registers###{idx}: {buf.Name} (ID: 0x{buf.Id:X8})" : string.Empty ); - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - using var t2 = ImRaii.TreeNode( name, !disabled || buf.Used != null ? 0 : ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ); + + (withSize ? $", size: {buf.Size} registers###{idx}: {buf.Name} (ID: 0x{buf.Id:X8})" : string.Empty); + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var t2 = ImRaii.TreeNode(name, !disabled || buf.Used != null ? 0 : ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); font.Dispose(); - if( t2 ) - { - ret |= DrawShaderPackageResource( slotLabel, withSize, ref buf, disabled ); - } + if (t2) + ret |= DrawShaderPackageResource(slotLabel, withSize, ref buf, disabled); } return ret; } - private static bool DrawMaterialParamLayoutHeader( string label ) + private static bool DrawMaterialParamLayoutHeader(string label) { - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); + using var font = ImRaii.PushFont(UiBuilder.MonoFont); var pos = ImGui.GetCursorScreenPos() - + new Vector2( ImGui.CalcTextSize( label ).X + 3 * ImGui.GetStyle().ItemInnerSpacing.X + ImGui.GetFrameHeight(), ImGui.GetStyle().FramePadding.Y ); + + new Vector2(ImGui.CalcTextSize(label).X + 3 * ImGui.GetStyle().ItemInnerSpacing.X + ImGui.GetFrameHeight(), + ImGui.GetStyle().FramePadding.Y); - var ret = ImGui.CollapsingHeader( label ); - ImGui.GetWindowDrawList().AddText( UiBuilder.DefaultFont, UiBuilder.DefaultFont.FontSize, pos, ImGui.GetColorU32( ImGuiCol.Text ), "Layout" ); + var ret = ImGui.CollapsingHeader(label); + ImGui.GetWindowDrawList() + .AddText(UiBuilder.DefaultFont, UiBuilder.DefaultFont.FontSize, pos, ImGui.GetColorU32(ImGuiCol.Text), "Layout"); return ret; } - private static bool DrawMaterialParamLayoutBufferSize( ShpkFile file, Resource? materialParams ) + private static bool DrawMaterialParamLayoutBufferSize(ShpkFile file, Resource? materialParams) { - var isSizeWellDefined = ( file.MaterialParamsSize & 0xF ) == 0 && ( !materialParams.HasValue || file.MaterialParamsSize == materialParams.Value.Size << 4 ); - if( isSizeWellDefined ) - { + var isSizeWellDefined = (file.MaterialParamsSize & 0xF) == 0 + && (!materialParams.HasValue || file.MaterialParamsSize == materialParams.Value.Size << 4); + if (isSizeWellDefined) return true; - } - ImGui.TextUnformatted( materialParams.HasValue + ImGui.TextUnformatted(materialParams.HasValue ? $"Buffer size mismatch: {file.MaterialParamsSize} bytes ≠ {materialParams.Value.Size} registers ({materialParams.Value.Size << 4} bytes)" - : $"Buffer size mismatch: {file.MaterialParamsSize} bytes, not a multiple of 16" ); + : $"Buffer size mismatch: {file.MaterialParamsSize} bytes, not a multiple of 16"); return false; } - private static bool DrawShaderPackageMaterialMatrix( ShpkTab tab, bool disabled ) + private static bool DrawShaderPackageMaterialMatrix(ShpkTab tab, bool disabled) { - ImGui.TextUnformatted( tab.Shpk.Disassembled + ImGui.TextUnformatted(tab.Shpk.Disassembled ? "Parameter positions (continuations are grayed out, unused values are red):" - : "Parameter positions (continuations are grayed out):" ); + : "Parameter positions (continuations are grayed out):"); - using var table = ImRaii.Table( "##MaterialParamLayout", 5, - ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg ); - if( !table ) - { + using var table = ImRaii.Table("##MaterialParamLayout", 5, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); + if (!table) return false; - } - ImGui.TableSetupColumn( string.Empty, ImGuiTableColumnFlags.WidthFixed, 25 * UiHelpers.Scale ); - ImGui.TableSetupColumn( "x", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale ); - ImGui.TableSetupColumn( "y", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale ); - ImGui.TableSetupColumn( "z", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale ); - ImGui.TableSetupColumn( "w", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale ); + ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, 25 * UiHelpers.Scale); + ImGui.TableSetupColumn("x", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); + ImGui.TableSetupColumn("y", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); + ImGui.TableSetupColumn("z", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); + ImGui.TableSetupColumn("w", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); ImGui.TableHeadersRow(); - var textColorStart = ImGui.GetColorU32( ImGuiCol.Text ); - var textColorCont = ( textColorStart & 0x00FFFFFFu ) | ( ( textColorStart & 0xFE000000u ) >> 1 ); // Half opacity - var textColorUnusedStart = ( textColorStart & 0xFF000000u ) | ( ( textColorStart & 0x00FEFEFE ) >> 1 ) | 0x80u; // Half red - var textColorUnusedCont = ( textColorUnusedStart & 0x00FFFFFFu ) | ( ( textColorUnusedStart & 0xFE000000u ) >> 1 ); + var textColorStart = ImGui.GetColorU32(ImGuiCol.Text); + var textColorCont = (textColorStart & 0x00FFFFFFu) | ((textColorStart & 0xFE000000u) >> 1); // Half opacity + var textColorUnusedStart = (textColorStart & 0xFF000000u) | ((textColorStart & 0x00FEFEFE) >> 1) | 0x80u; // Half red + var textColorUnusedCont = (textColorUnusedStart & 0x00FFFFFFu) | ((textColorUnusedStart & 0xFE000000u) >> 1); var ret = false; - for( var i = 0; i < tab.Matrix.GetLength( 0 ); ++i ) + for (var i = 0; i < tab.Matrix.GetLength(0); ++i) { ImGui.TableNextColumn(); - ImGui.TableHeader( $" [{i}]" ); - for( var j = 0; j < 4; ++j ) + ImGui.TableHeader($" [{i}]"); + for (var j = 0; j < 4; ++j) { - var (name, tooltip, idx, colorType) = tab.Matrix[ i, j ]; + var (name, tooltip, idx, colorType) = tab.Matrix[i, j]; var color = colorType switch { ShpkTab.ColorType.Unused => textColorUnusedStart, @@ -332,367 +308,307 @@ public partial class ModEditWindow ShpkTab.ColorType.Continuation | ShpkTab.ColorType.Used => textColorCont, _ => textColorStart, }; - using var _ = ImRaii.PushId( i * 4 + j ); + using var _ = ImRaii.PushId(i * 4 + j); var deletable = !disabled && idx >= 0; - using( var font = ImRaii.PushFont( UiBuilder.MonoFont, tooltip.Length > 0 ) ) + using (var font = ImRaii.PushFont(UiBuilder.MonoFont, tooltip.Length > 0)) { - using( var c = ImRaii.PushColor( ImGuiCol.Text, color ) ) + using (var c = ImRaii.PushColor(ImGuiCol.Text, color)) { ImGui.TableNextColumn(); - ImGui.Selectable( name ); - if( deletable && ImGui.IsItemClicked( ImGuiMouseButton.Right ) && ImGui.GetIO().KeyCtrl ) + ImGui.Selectable(name); + if (deletable && ImGui.IsItemClicked(ImGuiMouseButton.Right) && ImGui.GetIO().KeyCtrl) { - tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.RemoveItems( idx ); + tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.RemoveItems(idx); ret = true; tab.Update(); } } - ImGuiUtil.HoverTooltip( tooltip ); + ImGuiUtil.HoverTooltip(tooltip); } - if( deletable ) - { - ImGuiUtil.HoverTooltip( "\nControl + Right-Click to remove." ); - } + if (deletable) + ImGuiUtil.HoverTooltip("\nControl + Right-Click to remove."); } } return ret; } - private static void DrawShaderPackageMisalignedParameters( ShpkTab tab ) + private static void DrawShaderPackageMisalignedParameters(ShpkTab tab) { - using var t = ImRaii.TreeNode( "Misaligned / Overflowing Parameters" ); - if( !t ) - { + using var t = ImRaii.TreeNode("Misaligned / Overflowing Parameters"); + if (!t) return; - } - using var _ = ImRaii.PushFont( UiBuilder.MonoFont ); - foreach( var name in tab.MalformedParameters ) - { - ImRaii.TreeNode( name, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + using var _ = ImRaii.PushFont(UiBuilder.MonoFont); + foreach (var name in tab.MalformedParameters) + ImRaii.TreeNode(name, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } - private static void DrawShaderPackageStartCombo( ShpkTab tab ) + private static void DrawShaderPackageStartCombo(ShpkTab tab) { - using var s = ImRaii.PushStyle( ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemInnerSpacing ); - using( var _ = ImRaii.PushFont( UiBuilder.MonoFont ) ) + using var s = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemInnerSpacing); + using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) { - ImGui.SetNextItemWidth( UiHelpers.Scale * 400 ); - using var c = ImRaii.Combo( "##Start", tab.Orphans[ tab.NewMaterialParamStart ].Name ); - if( c ) - { - foreach( var (start, idx) in tab.Orphans.WithIndex() ) + ImGui.SetNextItemWidth(UiHelpers.Scale * 400); + using var c = ImRaii.Combo("##Start", tab.Orphans[tab.NewMaterialParamStart].Name); + if (c) + foreach (var (start, idx) in tab.Orphans.WithIndex()) { - if( ImGui.Selectable( start.Name, idx == tab.NewMaterialParamStart ) ) - { - tab.UpdateOrphanStart( idx ); - } + if (ImGui.Selectable(start.Name, idx == tab.NewMaterialParamStart)) + tab.UpdateOrphanStart(idx); } - } } ImGui.SameLine(); - ImGui.TextUnformatted( "Start" ); + ImGui.TextUnformatted("Start"); } - private static void DrawShaderPackageEndCombo( ShpkTab tab ) + private static void DrawShaderPackageEndCombo(ShpkTab tab) { - using var s = ImRaii.PushStyle( ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemInnerSpacing ); - using( var _ = ImRaii.PushFont( UiBuilder.MonoFont ) ) + using var s = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemInnerSpacing); + using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) { - ImGui.SetNextItemWidth( UiHelpers.Scale * 400 ); - using var c = ImRaii.Combo( "##End", tab.Orphans[ tab.NewMaterialParamEnd ].Name ); - if( c ) + ImGui.SetNextItemWidth(UiHelpers.Scale * 400); + using var c = ImRaii.Combo("##End", tab.Orphans[tab.NewMaterialParamEnd].Name); + if (c) { - var current = tab.Orphans[ tab.NewMaterialParamStart ].Index; - for( var i = tab.NewMaterialParamStart; i < tab.Orphans.Count; ++i ) + var current = tab.Orphans[tab.NewMaterialParamStart].Index; + for (var i = tab.NewMaterialParamStart; i < tab.Orphans.Count; ++i) { - var next = tab.Orphans[ i ]; - if( current++ != next.Index ) - { + var next = tab.Orphans[i]; + if (current++ != next.Index) break; - } - if( ImGui.Selectable( next.Name, i == tab.NewMaterialParamEnd ) ) - { + if (ImGui.Selectable(next.Name, i == tab.NewMaterialParamEnd)) tab.NewMaterialParamEnd = i; - } } } } ImGui.SameLine(); - ImGui.TextUnformatted( "End" ); + ImGui.TextUnformatted("End"); } - private static bool DrawShaderPackageNewParameter( ShpkTab tab ) + private static bool DrawShaderPackageNewParameter(ShpkTab tab) { - if( tab.Orphans.Count == 0 ) - { + if (tab.Orphans.Count == 0) return false; - } - DrawShaderPackageStartCombo( tab ); - DrawShaderPackageEndCombo( tab ); + DrawShaderPackageStartCombo(tab); + DrawShaderPackageEndCombo(tab); - ImGui.SetNextItemWidth( UiHelpers.Scale * 400 ); - if( ImGui.InputText( "Name", ref tab.NewMaterialParamName, 63 ) ) - { - tab.NewMaterialParamId = Crc32.Get( tab.NewMaterialParamName, 0xFFFFFFFFu ); - } + ImGui.SetNextItemWidth(UiHelpers.Scale * 400); + if (ImGui.InputText("Name", ref tab.NewMaterialParamName, 63)) + tab.NewMaterialParamId = Crc32.Get(tab.NewMaterialParamName, 0xFFFFFFFFu); - var tooltip = tab.UsedIds.Contains( tab.NewMaterialParamId ) + var tooltip = tab.UsedIds.Contains(tab.NewMaterialParamId) ? "The ID is already in use. Please choose a different name." : string.Empty; - if( !ImGuiUtil.DrawDisabledButton( $"Add ID 0x{tab.NewMaterialParamId:X8}", new Vector2( 400 * UiHelpers.Scale, ImGui.GetFrameHeight() ), tooltip, - tooltip.Length > 0 ) ) - { + if (!ImGuiUtil.DrawDisabledButton($"Add ID 0x{tab.NewMaterialParamId:X8}", new Vector2(400 * UiHelpers.Scale, ImGui.GetFrameHeight()), + tooltip, + tooltip.Length > 0)) return false; - } - tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.AddItem( new MaterialParam + tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.AddItem(new MaterialParam { Id = tab.NewMaterialParamId, - ByteOffset = ( ushort )( tab.Orphans[ tab.NewMaterialParamStart ].Index << 2 ), - ByteSize = ( ushort )( ( tab.NewMaterialParamEnd - tab.NewMaterialParamStart + 1 ) << 2 ), - } ); + ByteOffset = (ushort)(tab.Orphans[tab.NewMaterialParamStart].Index << 2), + ByteSize = (ushort)((tab.NewMaterialParamEnd - tab.NewMaterialParamStart + 1) << 2), + }); tab.Update(); return true; } - private static bool DrawShaderPackageMaterialParamLayout( ShpkTab tab, bool disabled ) + private static bool DrawShaderPackageMaterialParamLayout(ShpkTab tab, bool disabled) { var ret = false; - var materialParams = tab.Shpk.GetConstantById( MaterialParamsConstantId ); - if( !DrawMaterialParamLayoutHeader( materialParams?.Name ?? "Material Parameter" ) ) - { + var materialParams = tab.Shpk.GetConstantById(MaterialParamsConstantId); + if (!DrawMaterialParamLayoutHeader(materialParams?.Name ?? "Material Parameter")) return false; - } - var sizeWellDefined = DrawMaterialParamLayoutBufferSize( tab.Shpk, materialParams ); + var sizeWellDefined = DrawMaterialParamLayoutBufferSize(tab.Shpk, materialParams); - ret |= DrawShaderPackageMaterialMatrix( tab, disabled ); + ret |= DrawShaderPackageMaterialMatrix(tab, disabled); - if( tab.MalformedParameters.Count > 0 ) - { - DrawShaderPackageMisalignedParameters( tab ); - } - else if( !disabled && sizeWellDefined ) - { - ret |= DrawShaderPackageNewParameter( tab ); - } + if (tab.MalformedParameters.Count > 0) + DrawShaderPackageMisalignedParameters(tab); + else if (!disabled && sizeWellDefined) + ret |= DrawShaderPackageNewParameter(tab); return ret; } - private static bool DrawShaderPackageResources( ShpkTab tab, bool disabled ) + private static bool DrawShaderPackageResources(ShpkTab tab, bool disabled) { var ret = false; - if( !ImGui.CollapsingHeader( "Shader Resources" ) ) - { + if (!ImGui.CollapsingHeader("Shader Resources")) return false; - } - ret |= DrawShaderPackageResourceArray( "Constant Buffers", "type", true, tab.Shpk.Constants, disabled ); - ret |= DrawShaderPackageResourceArray( "Samplers", "type", false, tab.Shpk.Samplers, disabled ); - ret |= DrawShaderPackageResourceArray( "Unordered Access Views", "type", false, tab.Shpk.Uavs, disabled ); + ret |= DrawShaderPackageResourceArray("Constant Buffers", "type", true, tab.Shpk.Constants, disabled); + ret |= DrawShaderPackageResourceArray("Samplers", "type", false, tab.Shpk.Samplers, disabled); + ret |= DrawShaderPackageResourceArray("Unordered Access Views", "type", false, tab.Shpk.Uavs, disabled); return ret; } - private static void DrawKeyArray( string arrayName, bool withId, IReadOnlyCollection< Key > keys ) + private static void DrawKeyArray(string arrayName, bool withId, IReadOnlyCollection keys) { - if( keys.Count == 0 ) - { + if (keys.Count == 0) return; - } - using var t = ImRaii.TreeNode( arrayName ); - if( !t ) - { + using var t = ImRaii.TreeNode(arrayName); + if (!t) return; - } - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - foreach( var (key, idx) in keys.WithIndex() ) + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + foreach (var (key, idx) in keys.WithIndex()) { - using var t2 = ImRaii.TreeNode( withId ? $"#{idx}: ID: 0x{key.Id:X8}" : $"#{idx}" ); - if( t2 ) + using var t2 = ImRaii.TreeNode(withId ? $"#{idx}: ID: 0x{key.Id:X8}" : $"#{idx}"); + if (t2) { - ImRaii.TreeNode( $"Default Value: 0x{key.DefaultValue:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - ImRaii.TreeNode( $"Known Values: {string.Join( ", ", Array.ConvertAll( key.Values, value => $"0x{value:X8}" ) )}", - ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); + ImRaii.TreeNode($"Default Value: 0x{key.DefaultValue:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImRaii.TreeNode($"Known Values: {string.Join(", ", Array.ConvertAll(key.Values, value => $"0x{value:X8}"))}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } } } - private static void DrawShaderPackageNodes( ShpkTab tab ) + private static void DrawShaderPackageNodes(ShpkTab tab) { - if( tab.Shpk.Nodes.Length <= 0 ) - { + if (tab.Shpk.Nodes.Length <= 0) return; - } - using var t = ImRaii.TreeNode( $"Nodes ({tab.Shpk.Nodes.Length})###Nodes" ); - if( !t ) - { + using var t = ImRaii.TreeNode($"Nodes ({tab.Shpk.Nodes.Length})###Nodes"); + if (!t) return; - } - foreach( var (node, idx) in tab.Shpk.Nodes.WithIndex() ) + foreach (var (node, idx) in tab.Shpk.Nodes.WithIndex()) { - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - using var t2 = ImRaii.TreeNode( $"#{idx:D4}: Selector: 0x{node.Selector:X8}" ); - if( !t2 ) - { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var t2 = ImRaii.TreeNode($"#{idx:D4}: Selector: 0x{node.Selector:X8}"); + if (!t2) continue; - } - foreach( var (key, keyIdx) in node.SystemKeys.WithIndex() ) - { - ImRaii.TreeNode( $"System Key 0x{tab.Shpk.SystemKeys[ keyIdx ].Id:X8} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + foreach (var (key, keyIdx) in node.SystemKeys.WithIndex()) + ImRaii.TreeNode($"System Key 0x{tab.Shpk.SystemKeys[keyIdx].Id:X8} = 0x{key:X8}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - foreach( var (key, keyIdx) in node.SceneKeys.WithIndex() ) - { - ImRaii.TreeNode( $"Scene Key 0x{tab.Shpk.SceneKeys[ keyIdx ].Id:X8} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + foreach (var (key, keyIdx) in node.SceneKeys.WithIndex()) + ImRaii.TreeNode($"Scene Key 0x{tab.Shpk.SceneKeys[keyIdx].Id:X8} = 0x{key:X8}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - foreach( var (key, keyIdx) in node.MaterialKeys.WithIndex() ) - { - ImRaii.TreeNode( $"Material Key 0x{tab.Shpk.MaterialKeys[ keyIdx ].Id:X8} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + foreach (var (key, keyIdx) in node.MaterialKeys.WithIndex()) + ImRaii.TreeNode($"Material Key 0x{tab.Shpk.MaterialKeys[keyIdx].Id:X8} = 0x{key:X8}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - foreach( var (key, keyIdx) in node.SubViewKeys.WithIndex() ) - { - ImRaii.TreeNode( $"Sub-View Key #{keyIdx} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + foreach (var (key, keyIdx) in node.SubViewKeys.WithIndex()) + ImRaii.TreeNode($"Sub-View Key #{keyIdx} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - ImRaii.TreeNode( $"Pass Indices: {string.Join( ' ', node.PassIndices.Select( c => $"{c:X2}" ) )}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - foreach( var (pass, passIdx) in node.Passes.WithIndex() ) + ImRaii.TreeNode($"Pass Indices: {string.Join(' ', node.PassIndices.Select(c => $"{c:X2}"))}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + foreach (var (pass, passIdx) in node.Passes.WithIndex()) { - ImRaii.TreeNode( $"Pass #{passIdx}: ID: 0x{pass.Id:X8}, Vertex Shader #{pass.VertexShader}, Pixel Shader #{pass.PixelShader}", - ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ) - .Dispose(); + ImRaii.TreeNode($"Pass #{passIdx}: ID: 0x{pass.Id:X8}, Vertex Shader #{pass.VertexShader}, Pixel Shader #{pass.PixelShader}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) + .Dispose(); } } } - private static void DrawShaderPackageSelection( ShpkTab tab ) + private static void DrawShaderPackageSelection(ShpkTab tab) { - if( !ImGui.CollapsingHeader( "Shader Selection" ) ) - { + if (!ImGui.CollapsingHeader("Shader Selection")) return; - } - DrawKeyArray( "System Keys", true, tab.Shpk.SystemKeys ); - DrawKeyArray( "Scene Keys", true, tab.Shpk.SceneKeys ); - DrawKeyArray( "Material Keys", true, tab.Shpk.MaterialKeys ); - DrawKeyArray( "Sub-View Keys", false, tab.Shpk.SubViewKeys ); + DrawKeyArray("System Keys", true, tab.Shpk.SystemKeys); + DrawKeyArray("Scene Keys", true, tab.Shpk.SceneKeys); + DrawKeyArray("Material Keys", true, tab.Shpk.MaterialKeys); + DrawKeyArray("Sub-View Keys", false, tab.Shpk.SubViewKeys); - DrawShaderPackageNodes( tab ); - using var t = ImRaii.TreeNode( $"Node Selectors ({tab.Shpk.NodeSelectors.Count})###NodeSelectors" ); - if( t ) + DrawShaderPackageNodes(tab); + using var t = ImRaii.TreeNode($"Node Selectors ({tab.Shpk.NodeSelectors.Count})###NodeSelectors"); + if (t) { - using var font = ImRaii.PushFont( UiBuilder.MonoFont ); - foreach( var selector in tab.Shpk.NodeSelectors ) - { - ImRaii.TreeNode( $"#{selector.Value:D4}: Selector: 0x{selector.Key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); - } + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + foreach (var selector in tab.Shpk.NodeSelectors) + ImRaii.TreeNode($"#{selector.Value:D4}: Selector: 0x{selector.Key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) + .Dispose(); } } - private static void DrawOtherShaderPackageDetails( ShpkTab tab ) + private static void DrawOtherShaderPackageDetails(ShpkTab tab) { - if( !ImGui.CollapsingHeader( "Further Content" ) ) - { + if (!ImGui.CollapsingHeader("Further Content")) return; - } - ImRaii.TreeNode( $"Version: 0x{tab.Shpk.Version:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet ).Dispose(); + ImRaii.TreeNode($"Version: 0x{tab.Shpk.Version:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - if( tab.Shpk.AdditionalData.Length > 0 ) + if (tab.Shpk.AdditionalData.Length > 0) { - using var t = ImRaii.TreeNode( $"Additional Data (Size: {tab.Shpk.AdditionalData.Length})###AdditionalData" ); - if( t ) - { - ImGuiUtil.TextWrapped( string.Join( ' ', tab.Shpk.AdditionalData.Select( c => $"{c:X2}" ) ) ); - } + using var t = ImRaii.TreeNode($"Additional Data (Size: {tab.Shpk.AdditionalData.Length})###AdditionalData"); + if (t) + ImGuiUtil.TextWrapped(string.Join(' ', tab.Shpk.AdditionalData.Select(c => $"{c:X2}"))); } } - private static string UsedComponentString( bool withSize, in Resource resource ) + private static string UsedComponentString(bool withSize, in Resource resource) { - var sb = new StringBuilder( 256 ); - if( withSize ) + var sb = new StringBuilder(256); + if (withSize) { - foreach( var (components, i) in ( resource.Used ?? Array.Empty< DisassembledShader.VectorComponents >() ).WithIndex() ) + foreach (var (components, i) in (resource.Used ?? Array.Empty()).WithIndex()) { - switch( components ) + switch (components) { case 0: break; case DisassembledShader.VectorComponents.All: - sb.Append( $"[{i}], " ); + sb.Append($"[{i}], "); break; default: - sb.Append( $"[{i}]." ); - foreach( var c in components.ToString().Where( char.IsUpper ) ) - { - sb.Append( char.ToLower( c ) ); - } + sb.Append($"[{i}]."); + foreach (var c in components.ToString().Where(char.IsUpper)) + sb.Append(char.ToLower(c)); - sb.Append( ", " ); + sb.Append(", "); break; } } - switch( resource.UsedDynamically ?? 0 ) + switch (resource.UsedDynamically ?? 0) { case 0: break; case DisassembledShader.VectorComponents.All: - sb.Append( "[*], " ); + sb.Append("[*], "); break; default: - sb.Append( "[*]." ); - foreach( var c in resource.UsedDynamically!.Value.ToString().Where( char.IsUpper ) ) - { - sb.Append( char.ToLower( c ) ); - } + sb.Append("[*]."); + foreach (var c in resource.UsedDynamically!.Value.ToString().Where(char.IsUpper)) + sb.Append(char.ToLower(c)); - sb.Append( ", " ); + sb.Append(", "); break; } } else { - var components = ( resource.Used is { Length: > 0 } ? resource.Used[ 0 ] : 0 ) | ( resource.UsedDynamically ?? 0 ); - if( ( components & DisassembledShader.VectorComponents.X ) != 0 ) - { - sb.Append( "Red, " ); - } + var components = (resource.Used is { Length: > 0 } ? resource.Used[0] : 0) | (resource.UsedDynamically ?? 0); + if ((components & DisassembledShader.VectorComponents.X) != 0) + sb.Append("Red, "); - if( ( components & DisassembledShader.VectorComponents.Y ) != 0 ) - { - sb.Append( "Green, " ); - } + if ((components & DisassembledShader.VectorComponents.Y) != 0) + sb.Append("Green, "); - if( ( components & DisassembledShader.VectorComponents.Z ) != 0 ) - { - sb.Append( "Blue, " ); - } + if ((components & DisassembledShader.VectorComponents.Z) != 0) + sb.Append("Blue, "); - if( ( components & DisassembledShader.VectorComponents.W ) != 0 ) - { - sb.Append( "Alpha, " ); - } + if ((components & DisassembledShader.VectorComponents.W) != 0) + sb.Append("Alpha, "); } - return sb.Length == 0 ? string.Empty : sb.ToString( 0, sb.Length - 2 ); + return sb.Length == 0 ? string.Empty : sb.ToString(0, sb.Length - 2); } -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index e40a7915..e90c148e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -533,14 +533,20 @@ public partial class ModEditWindow : Window, IDisposable var ret = new HashSet(); foreach (var path in _activeCollections.Current.ResolvedFiles.Keys) + { if (path.Path.StartsWith(prefix)) ret.Add(path); + } if (_mod != null) foreach (var option in _mod.Groups.SelectMany(g => g).Append(_mod.Default)) + { foreach (var path in option.Files.Keys) + { if (path.Path.StartsWith(prefix)) ret.Add(path); + } + } return ret; } From a768b039a8a7c0f98e54dc0872bca2615936aaea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 31 Aug 2023 18:25:29 +0200 Subject: [PATCH 0059/1381] Restructure Live Preview. --- .../MaterialPreview/LiveColorSetPreviewer.cs | 131 +++++ .../MaterialPreview/LiveMaterialPreviewer.cs | 149 ++++++ .../LiveMaterialPreviewerBase.cs | 70 +++ .../Interop/MaterialPreview/MaterialInfo.cs | 120 +++++ .../ModEditWindow.Materials.LivePreview.cs | 483 ------------------ .../ModEditWindow.Materials.MtrlTab.cs | 43 +- 6 files changed, 478 insertions(+), 518 deletions(-) create mode 100644 Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs create mode 100644 Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs create mode 100644 Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs create mode 100644 Penumbra/Interop/MaterialPreview/MaterialInfo.cs delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs diff --git a/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs new file mode 100644 index 00000000..18afa949 --- /dev/null +++ b/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs @@ -0,0 +1,131 @@ +using System; +using System.Threading; +using Dalamud.Game; +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using Penumbra.GameData.Files; + +namespace Penumbra.Interop.MaterialPreview; + +public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase +{ + public const int TextureWidth = 4; + public const int TextureHeight = MtrlFile.ColorSet.RowArray.NumRows; + public const int TextureLength = TextureWidth * TextureHeight * 4; + + private readonly Framework _framework; + + private readonly Texture** _colorSetTexture; + private readonly Texture* _originalColorSetTexture; + + private Half[] _colorSet; + private bool _updatePending; + + public Half[] ColorSet + => _colorSet; + + public LiveColorSetPreviewer(IObjectTable objects, Framework framework, MaterialInfo materialInfo) + : base(objects, materialInfo) + { + _framework = framework; + + var mtrlHandle = Material->MaterialResourceHandle; + if (mtrlHandle == null) + throw new InvalidOperationException("Material doesn't have a resource handle"); + + var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; + if (colorSetTextures == null) + throw new InvalidOperationException("Draw object doesn't have color set textures"); + + _colorSetTexture = colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); + + _originalColorSetTexture = *_colorSetTexture; + if (_originalColorSetTexture == null) + throw new InvalidOperationException("Material doesn't have a color set"); + + Structs.TextureUtility.IncRef(_originalColorSetTexture); + + _colorSet = new Half[TextureLength]; + _updatePending = true; + + framework.Update += OnFrameworkUpdate; + } + + protected override void Clear(bool disposing, bool reset) + { + _framework.Update -= OnFrameworkUpdate; + + base.Clear(disposing, reset); + + if (reset) + { + var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)_originalColorSetTexture); + if (oldTexture != null) + Structs.TextureUtility.DecRef(oldTexture); + } + else + { + Structs.TextureUtility.DecRef(_originalColorSetTexture); + } + } + + public void ScheduleUpdate() + { + _updatePending = true; + } + + private void OnFrameworkUpdate(Framework _) + { + if (!_updatePending) + return; + + _updatePending = false; + + if (!CheckValidity()) + return; + + var textureSize = stackalloc int[2]; + textureSize[0] = TextureWidth; + textureSize[1] = TextureHeight; + + var newTexture = Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7); + if (newTexture == null) + return; + + bool success; + lock (_colorSet) + { + fixed (Half* colorSet = _colorSet) + { + success = Structs.TextureUtility.InitializeContents(newTexture, colorSet); + } + } + + if (success) + { + var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)newTexture); + if (oldTexture != null) + Structs.TextureUtility.DecRef(oldTexture); + } + else + { + Structs.TextureUtility.DecRef(newTexture); + } + } + + protected override bool IsStillValid() + { + if (!base.IsStillValid()) + return false; + + var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; + if (colorSetTextures == null) + return false; + + if (_colorSetTexture != colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot)) + return false; + + return true; + } +} diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs new file mode 100644 index 00000000..1b280b20 --- /dev/null +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -0,0 +1,149 @@ +using System; +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; + +namespace Penumbra.Interop.MaterialPreview; + +public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase +{ + private readonly ShaderPackage* _shaderPackage; + + private readonly uint _originalShPkFlags; + private readonly float[] _originalMaterialParameter; + private readonly uint[] _originalSamplerFlags; + + public LiveMaterialPreviewer(IObjectTable objects, MaterialInfo materialInfo) + : base(objects, materialInfo) + { + var mtrlHandle = Material->MaterialResourceHandle; + if (mtrlHandle == null) + throw new InvalidOperationException("Material doesn't have a resource handle"); + + var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; + if (shpkHandle == null) + throw new InvalidOperationException("Material doesn't have a ShPk resource handle"); + + _shaderPackage = shpkHandle->ShaderPackage; + if (_shaderPackage == null) + throw new InvalidOperationException("Material doesn't have a shader package"); + + var material = (Structs.Material*)Material; + + _originalShPkFlags = material->ShaderPackageFlags; + + if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) + _originalMaterialParameter = materialParameter.ToArray(); + else + _originalMaterialParameter = Array.Empty(); + + _originalSamplerFlags = new uint[material->TextureCount]; + for (var i = 0; i < _originalSamplerFlags.Length; ++i) + _originalSamplerFlags[i] = material->Textures[i].SamplerFlags; + } + + protected override void Clear(bool disposing, bool reset) + { + base.Clear(disposing, reset); + + if (reset) + { + var material = (Structs.Material*)Material; + + material->ShaderPackageFlags = _originalShPkFlags; + + if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) + _originalMaterialParameter.AsSpan().CopyTo(materialParameter); + + for (var i = 0; i < _originalSamplerFlags.Length; ++i) + material->Textures[i].SamplerFlags = _originalSamplerFlags[i]; + } + } + + public void SetShaderPackageFlags(uint shPkFlags) + { + if (!CheckValidity()) + return; + + ((Structs.Material*)Material)->ShaderPackageFlags = shPkFlags; + } + + public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) + { + if (!CheckValidity()) + return; + + var constantBuffer = ((Structs.Material*)Material)->MaterialParameter; + if (constantBuffer == null) + return; + + if (!constantBuffer->TryGetBuffer(out var buffer)) + return; + + for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) + { + ref var parameter = ref _shaderPackage->MaterialElements[i]; + if (parameter.CRC == parameterCrc) + { + if ((parameter.Offset & 0x3) != 0 + || (parameter.Size & 0x3) != 0 + || (parameter.Offset + parameter.Size) >> 2 > buffer.Length) + return; + + value.TryCopyTo(buffer.Slice(parameter.Offset >> 2, parameter.Size >> 2)[offset..]); + return; + } + } + } + + public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) + { + if (!CheckValidity()) + return; + + var id = 0u; + var found = false; + + var samplers = (Structs.ShaderPackageUtility.Sampler*)_shaderPackage->Samplers; + for (var i = 0; i < _shaderPackage->SamplerCount; ++i) + { + if (samplers[i].Crc == samplerCrc) + { + id = samplers[i].Id; + found = true; + break; + } + } + + if (!found) + return; + + var material = (Structs.Material*)Material; + for (var i = 0; i < material->TextureCount; ++i) + { + if (material->Textures[i].Id == id) + { + material->Textures[i].SamplerFlags = (samplerFlags & 0xFFFFFDFF) | 0x000001C0; + break; + } + } + } + + protected override bool IsStillValid() + { + if (!base.IsStillValid()) + return false; + + var mtrlHandle = Material->MaterialResourceHandle; + if (mtrlHandle == null) + return false; + + var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; + if (shpkHandle == null) + return false; + + if (_shaderPackage != shpkHandle->ShaderPackage) + return false; + + return true; + } +} diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs new file mode 100644 index 00000000..88369725 --- /dev/null +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs @@ -0,0 +1,70 @@ +using System; +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; + +namespace Penumbra.Interop.MaterialPreview; + +public abstract unsafe class LiveMaterialPreviewerBase : IDisposable +{ + private readonly IObjectTable _objects; + + public readonly MaterialInfo MaterialInfo; + public readonly CharacterBase* DrawObject; + protected readonly Material* Material; + + protected bool Valid; + + public LiveMaterialPreviewerBase(IObjectTable objects, MaterialInfo materialInfo) + { + _objects = objects; + + MaterialInfo = materialInfo; + var gameObject = MaterialInfo.GetCharacter(objects); + if (gameObject == nint.Zero) + throw new InvalidOperationException("Cannot retrieve game object."); + + DrawObject = (CharacterBase*)MaterialInfo.GetDrawObject(gameObject); + if (DrawObject == null) + throw new InvalidOperationException("Cannot retrieve draw object."); + + Material = MaterialInfo.GetDrawObjectMaterial(DrawObject); + if (Material == null) + throw new InvalidOperationException("Cannot retrieve material."); + + Valid = true; + } + + public void Dispose() + { + if (Valid) + Clear(true, IsStillValid()); + } + + public bool CheckValidity() + { + if (Valid && !IsStillValid()) + Clear(false, false); + return Valid; + } + + protected virtual void Clear(bool disposing, bool reset) + { + Valid = false; + } + + protected virtual bool IsStillValid() + { + var gameObject = MaterialInfo.GetCharacter(_objects); + if (gameObject == nint.Zero) + return false; + + if ((nint)DrawObject != MaterialInfo.GetDrawObject(gameObject)) + return false; + + if (Material != MaterialInfo.GetDrawObjectMaterial(DrawObject)) + return false; + + return true; + } +} diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs new file mode 100644 index 00000000..f1c9c10e --- /dev/null +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.Interop.ResourceTree; +using Penumbra.String; + +namespace Penumbra.Interop.MaterialPreview; + +public enum DrawObjectType +{ + PlayerCharacter, + PlayerMainhand, + PlayerOffhand, + PlayerVfx, + MinionCharacter, + MinionUnk1, + MinionUnk2, + MinionUnk3, +}; + +public readonly record struct MaterialInfo(DrawObjectType Type, int ModelSlot, int MaterialSlot) +{ + public nint GetCharacter(IObjectTable objects) + => GetCharacter(Type, objects); + + public static nint GetCharacter(DrawObjectType type, IObjectTable objects) + => type switch + { + DrawObjectType.PlayerCharacter => objects.GetObjectAddress(0), + DrawObjectType.PlayerMainhand => objects.GetObjectAddress(0), + DrawObjectType.PlayerOffhand => objects.GetObjectAddress(0), + DrawObjectType.PlayerVfx => objects.GetObjectAddress(0), + DrawObjectType.MinionCharacter => objects.GetObjectAddress(1), + DrawObjectType.MinionUnk1 => objects.GetObjectAddress(1), + DrawObjectType.MinionUnk2 => objects.GetObjectAddress(1), + DrawObjectType.MinionUnk3 => objects.GetObjectAddress(1), + _ => nint.Zero, + }; + + public nint GetDrawObject(nint address) + => GetDrawObject(Type, address); + + public static nint GetDrawObject(DrawObjectType type, IObjectTable objects) + => GetDrawObject(type, GetCharacter(type, objects)); + + public static unsafe nint GetDrawObject(DrawObjectType type, nint address) + { + var gameObject = (Character*)address; + if (gameObject == null) + return nint.Zero; + + return type switch + { + DrawObjectType.PlayerCharacter => (nint)gameObject->GameObject.GetDrawObject(), + DrawObjectType.PlayerMainhand => *((nint*)&gameObject->DrawData.MainHand + 1), + DrawObjectType.PlayerOffhand => *((nint*)&gameObject->DrawData.OffHand + 1), + DrawObjectType.PlayerVfx => *((nint*)&gameObject->DrawData.UnkF0 + 1), + DrawObjectType.MinionCharacter => (nint)gameObject->GameObject.GetDrawObject(), + DrawObjectType.MinionUnk1 => *((nint*)&gameObject->DrawData.MainHand + 1), + DrawObjectType.MinionUnk2 => *((nint*)&gameObject->DrawData.OffHand + 1), + DrawObjectType.MinionUnk3 => *((nint*)&gameObject->DrawData.UnkF0 + 1), + _ => nint.Zero, + }; + } + + public unsafe Material* GetDrawObjectMaterial(CharacterBase* drawObject) + { + if (drawObject == null) + return null; + + if (ModelSlot < 0 || ModelSlot >= drawObject->SlotCount) + return null; + + var model = drawObject->Models[ModelSlot]; + if (model == null) + return null; + + if (MaterialSlot < 0 || MaterialSlot >= model->MaterialCount) + return null; + + return model->Materials[MaterialSlot]; + } + + public static unsafe List FindMaterials(IObjectTable objects, string materialPath) + { + var needle = ByteString.FromString(materialPath.Replace('/', '\\'), out var m, true) ? m : ByteString.Empty; + + var result = new List(Enum.GetValues().Length); + foreach (var type in Enum.GetValues()) + { + var drawObject = (CharacterBase*)GetDrawObject(type, objects); + if (drawObject == null) + continue; + + for (var i = 0; i < drawObject->SlotCount; ++i) + { + var model = drawObject->Models[i]; + if (model == null) + continue; + + for (var j = 0; j < model->MaterialCount; ++j) + { + var material = model->Materials[j]; + if (material == null) + continue; + + var mtrlHandle = material->MaterialResourceHandle; + var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); + if (path == needle) + result.Add(new MaterialInfo(type, i, j)); + } + } + } + + return result; + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs deleted file mode 100644 index d2ce8796..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.LivePreview.cs +++ /dev/null @@ -1,483 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using Dalamud.Game; -using Dalamud.Plugin.Services; -using FFXIVClientStructs.FFXIV.Client.Game.Character; -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using Penumbra.GameData.Files; -using Penumbra.Interop.ResourceTree; -using Penumbra.String; -using Structs = Penumbra.Interop.Structs; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private static unsafe Character* FindLocalPlayer(IObjectTable objects) - { - var localPlayer = objects[0]; - if (localPlayer is not Dalamud.Game.ClientState.Objects.Types.Character) - return null; - - return (Character*)localPlayer.Address; - } - - private static unsafe Character* FindSubActor(Character* character, int subActorType) - { - if (character == null) - return null; - - switch (subActorType) - { - case -1: - return character; - case 0: - return character->Mount.MountObject; - case 1: - var companion = character->Companion.CompanionObject; - if (companion == null) - return null; - return &companion->Character; - case 2: - var ornament = character->Ornament.OrnamentObject; - if (ornament == null) - return null; - return &ornament->Character; - default: - return null; - } - } - - private static unsafe List<(int SubActorType, int ChildObjectIndex, int ModelSlot, int MaterialSlot)> FindMaterial(CharacterBase* drawObject, int subActorType, string materialPath) - { - static void CollectMaterials(List<(int, int, int, int)> result, int subActorType, int childObjectIndex, CharacterBase* drawObject, ByteString materialPath) - { - for (var i = 0; i < drawObject->SlotCount; ++i) - { - var model = drawObject->Models[i]; - if (model == null) - continue; - - for (var j = 0; j < model->MaterialCount; ++j) - { - var material = model->Materials[j]; - if (material == null) - continue; - - var mtrlHandle = material->MaterialResourceHandle; - var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); - if (path == materialPath) - result.Add((subActorType, childObjectIndex, i, j)); - } - } - } - - var result = new List<(int, int, int, int)>(); - - if (drawObject == null) - return result; - - var path = ByteString.FromString(materialPath.Replace('/', '\\'), out var m, true) ? m : ByteString.Empty; - CollectMaterials(result, subActorType, -1, drawObject, path); - - var firstChildObject = (CharacterBase*)drawObject->DrawObject.Object.ChildObject; - if (firstChildObject != null) - { - var childObject = firstChildObject; - var childObjectIndex = 0; - do - { - CollectMaterials(result, subActorType, childObjectIndex, childObject, path); - - childObject = (CharacterBase*)childObject->DrawObject.Object.NextSiblingObject; - ++childObjectIndex; - } - while (childObject != null && childObject != firstChildObject); - } - - return result; - } - - private static unsafe CharacterBase* GetChildObject(CharacterBase* drawObject, int index) - { - if (drawObject == null) - return null; - - if (index >= 0) - { - drawObject = (CharacterBase*)drawObject->DrawObject.Object.ChildObject; - if (drawObject == null) - return null; - } - - var first = drawObject; - while (index-- > 0) - { - drawObject = (CharacterBase*)drawObject->DrawObject.Object.NextSiblingObject; - if (drawObject == null || drawObject == first) - return null; - } - - return drawObject; - } - - private static unsafe Material* GetDrawObjectMaterial(CharacterBase* drawObject, int modelSlot, int materialSlot) - { - if (drawObject == null) - return null; - - if (modelSlot < 0 || modelSlot >= drawObject->SlotCount) - return null; - - var model = drawObject->Models[modelSlot]; - if (model == null) - return null; - - if (materialSlot < 0 || materialSlot >= model->MaterialCount) - return null; - - return model->Materials[materialSlot]; - } - - private abstract unsafe class LiveMaterialPreviewerBase : IDisposable - { - private readonly IObjectTable _objects; - - protected readonly int SubActorType; - protected readonly int ChildObjectIndex; - protected readonly int ModelSlot; - protected readonly int MaterialSlot; - - public readonly CharacterBase* DrawObject; - protected readonly Material* Material; - - protected bool Valid; - - public LiveMaterialPreviewerBase(IObjectTable objects, int subActorType, int childObjectIndex, int modelSlot, int materialSlot) - { - _objects = objects; - - SubActorType = subActorType; - ChildObjectIndex = childObjectIndex; - ModelSlot = modelSlot; - MaterialSlot = materialSlot; - - var localPlayer = FindLocalPlayer(objects); - if (localPlayer == null) - throw new InvalidOperationException("Cannot retrieve local player object"); - - var subActor = FindSubActor(localPlayer, subActorType); - if (subActor == null) - throw new InvalidOperationException("Cannot retrieve sub-actor (mount, companion or ornament)"); - - DrawObject = GetChildObject((CharacterBase*)subActor->GameObject.GetDrawObject(), childObjectIndex); - if (DrawObject == null) - throw new InvalidOperationException("Cannot retrieve draw object"); - - Material = GetDrawObjectMaterial(DrawObject, modelSlot, materialSlot); - if (Material == null) - throw new InvalidOperationException("Cannot retrieve material"); - - Valid = true; - } - - ~LiveMaterialPreviewerBase() - { - if (Valid) - Dispose(false, IsStillValid()); - } - - public void Dispose() - { - if (Valid) - Dispose(true, IsStillValid()); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing, bool reset) - { - Valid = false; - } - - public bool CheckValidity() - { - if (Valid && !IsStillValid()) - Dispose(false, false); - - return Valid; - } - - protected virtual bool IsStillValid() - { - var localPlayer = FindLocalPlayer(_objects); - if (localPlayer == null) - return false; - - var subActor = FindSubActor(localPlayer, SubActorType); - if (subActor == null) - return false; - - if (DrawObject != GetChildObject((CharacterBase*)subActor->GameObject.GetDrawObject(), ChildObjectIndex)) - return false; - - if (Material != GetDrawObjectMaterial(DrawObject, ModelSlot, MaterialSlot)) - return false; - - return true; - } - } - - private sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase - { - private readonly ShaderPackage* _shaderPackage; - - private readonly uint _originalShPkFlags; - private readonly float[] _originalMaterialParameter; - private readonly uint[] _originalSamplerFlags; - - public LiveMaterialPreviewer(IObjectTable objects, int subActorType, int childObjectIndex, int modelSlot, int materialSlot) : base(objects, subActorType, childObjectIndex, modelSlot, materialSlot) - { - var mtrlHandle = Material->MaterialResourceHandle; - if (mtrlHandle == null) - throw new InvalidOperationException("Material doesn't have a resource handle"); - - var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; - if (shpkHandle == null) - throw new InvalidOperationException("Material doesn't have a ShPk resource handle"); - - _shaderPackage = shpkHandle->ShaderPackage; - if (_shaderPackage == null) - throw new InvalidOperationException("Material doesn't have a shader package"); - - var material = (Structs.Material*)Material; - - _originalShPkFlags = material->ShaderPackageFlags; - - if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) - _originalMaterialParameter = materialParameter.ToArray(); - else - _originalMaterialParameter = Array.Empty(); - - _originalSamplerFlags = new uint[material->TextureCount]; - for (var i = 0; i < _originalSamplerFlags.Length; ++i) - _originalSamplerFlags[i] = material->Textures[i].SamplerFlags; - } - - protected override void Dispose(bool disposing, bool reset) - { - base.Dispose(disposing, reset); - - if (reset) - { - var material = (Structs.Material*)Material; - - material->ShaderPackageFlags = _originalShPkFlags; - - if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) - _originalMaterialParameter.AsSpan().CopyTo(materialParameter); - - for (var i = 0; i < _originalSamplerFlags.Length; ++i) - material->Textures[i].SamplerFlags = _originalSamplerFlags[i]; - } - } - - public void SetShaderPackageFlags(uint shPkFlags) - { - if (!CheckValidity()) - return; - - ((Structs.Material*)Material)->ShaderPackageFlags = shPkFlags; - } - - public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) - { - if (!CheckValidity()) - return; - - var cbuffer = ((Structs.Material*)Material)->MaterialParameter; - if (cbuffer == null) - return; - - if (!cbuffer->TryGetBuffer(out var buffer)) - return; - - for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) - { - ref var parameter = ref _shaderPackage->MaterialElements[i]; - if (parameter.CRC == parameterCrc) - { - if ((parameter.Offset & 0x3) != 0 || (parameter.Size & 0x3) != 0 || (parameter.Offset + parameter.Size) >> 2 > buffer.Length) - return; - - value.TryCopyTo(buffer.Slice(parameter.Offset >> 2, parameter.Size >> 2)[offset..]); - return; - } - } - } - - public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) - { - if (!CheckValidity()) - return; - - var id = 0u; - var found = false; - - var samplers = (Structs.ShaderPackageUtility.Sampler*)_shaderPackage->Samplers; - for (var i = 0; i < _shaderPackage->SamplerCount; ++i) - { - if (samplers[i].Crc == samplerCrc) - { - id = samplers[i].Id; - found = true; - break; - } - } - - if (!found) - return; - - var material = (Structs.Material*)Material; - for (var i = 0; i < material->TextureCount; ++i) - { - if (material->Textures[i].Id == id) - { - material->Textures[i].SamplerFlags = (samplerFlags & 0xFFFFFDFF) | 0x000001C0; - break; - } - } - } - - protected override bool IsStillValid() - { - if (!base.IsStillValid()) - return false; - - var mtrlHandle = Material->MaterialResourceHandle; - if (mtrlHandle == null) - return false; - - var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; - if (shpkHandle == null) - return false; - - if (_shaderPackage != shpkHandle->ShaderPackage) - return false; - - return true; - } - } - - private sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase - { - public const int TextureWidth = 4; - public const int TextureHeight = MtrlFile.ColorSet.RowArray.NumRows; - public const int TextureLength = TextureWidth * TextureHeight * 4; - - private readonly Framework _framework; - - private readonly Texture** _colorSetTexture; - private readonly Texture* _originalColorSetTexture; - - private Half[] _colorSet; - private bool _updatePending; - - public Half[] ColorSet => _colorSet; - - public LiveColorSetPreviewer(IObjectTable objects, Framework framework, int subActorType, int childObjectIndex, int modelSlot, int materialSlot) : base(objects, subActorType, childObjectIndex, modelSlot, materialSlot) - { - _framework = framework; - - var mtrlHandle = Material->MaterialResourceHandle; - if (mtrlHandle == null) - throw new InvalidOperationException("Material doesn't have a resource handle"); - - var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; - if (colorSetTextures == null) - throw new InvalidOperationException("Draw object doesn't have color set textures"); - - _colorSetTexture = colorSetTextures + (modelSlot * 4 + materialSlot); - - _originalColorSetTexture = *_colorSetTexture; - if (_originalColorSetTexture == null) - throw new InvalidOperationException("Material doesn't have a color set"); - Structs.TextureUtility.IncRef(_originalColorSetTexture); - - _colorSet = new Half[TextureLength]; - _updatePending = true; - - framework.Update += OnFrameworkUpdate; - } - - protected override void Dispose(bool disposing, bool reset) - { - _framework.Update -= OnFrameworkUpdate; - - base.Dispose(disposing, reset); - - if (reset) - { - var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)_originalColorSetTexture); - if (oldTexture != null) - Structs.TextureUtility.DecRef(oldTexture); - } - else - Structs.TextureUtility.DecRef(_originalColorSetTexture); - } - - public void ScheduleUpdate() - { - _updatePending = true; - } - - private void OnFrameworkUpdate(Framework _) - { - if (!_updatePending) - return; - _updatePending = false; - - if (!CheckValidity()) - return; - - var textureSize = stackalloc int[2]; - textureSize[0] = TextureWidth; - textureSize[1] = TextureHeight; - - var newTexture = Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7); - if (newTexture == null) - return; - - bool success; - lock (_colorSet) - fixed (Half* colorSet = _colorSet) - success = Structs.TextureUtility.InitializeContents(newTexture, colorSet); - - if (success) - { - var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)newTexture); - if (oldTexture != null) - Structs.TextureUtility.DecRef(oldTexture); - } - else - Structs.TextureUtility.DecRef(newTexture); - } - - protected override bool IsStillValid() - { - if (!base.IsStillValid()) - return false; - - var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; - if (colorSetTextures == null) - return false; - - if (_colorSetTexture != colorSetTextures + (ModelSlot * 4 + MaterialSlot)) - return false; - - return true; - } - } -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 12f7acd7..6bb8b8c8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -16,6 +16,7 @@ using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; +using Penumbra.Interop.MaterialPreview; using Penumbra.String; using Penumbra.String.Classes; using static Penumbra.GameData.Files.ShpkFile; @@ -460,46 +461,19 @@ public partial class ModEditWindow { UnbindFromMaterialInstances(); - var localPlayer = LocalPlayer(_edit._dalamud.Objects); - if (null == localPlayer) - return; - - var drawObject = (CharacterBase*)localPlayer->GameObject.GetDrawObject(); - if (null == drawObject) - return; - - var instances = FindMaterial(drawObject, -1, FilePath); - - var drawObjects = stackalloc CharacterBase*[4]; - drawObjects[0] = drawObject; - drawObjects[1] = *((CharacterBase**)&localPlayer->DrawData.MainHand + 1); - drawObjects[2] = *((CharacterBase**)&localPlayer->DrawData.OffHand + 1); - drawObjects[3] = *((CharacterBase**)&localPlayer->DrawData.UnkF0 + 1); - for (var i = 0; i < 3; ++i) - { - var subActor = FindSubActor(localPlayer, i); - if (null == subActor) - continue; - - var subDrawObject = (CharacterBase*)subActor->GameObject.GetDrawObject(); - if (null == subDrawObject) - continue; - - instances.AddRange(FindMaterial(subDrawObject, i, FilePath)); - drawObjects[i + 1] = subDrawObject; - } + var instances = MaterialInfo.FindMaterials(_edit._dalamud.Objects, FilePath); var foundMaterials = new HashSet(); - foreach (var (subActorType, childObjectIndex, modelSlot, materialSlot) in instances) + foreach (var materialInfo in instances) { - var material = GetDrawObjectMaterial(drawObjects[subActorType + 1], modelSlot, materialSlot); + var drawObject = (CharacterBase*)MaterialInfo.GetDrawObject(materialInfo.Type, _edit._dalamud.Objects); + var material = materialInfo.GetDrawObjectMaterial(drawObject); if (foundMaterials.Contains((nint)material)) continue; try { - MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._dalamud.Objects, subActorType, childObjectIndex, modelSlot, - materialSlot)); + MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._dalamud.Objects, materialInfo)); foundMaterials.Add((nint)material); } catch (InvalidOperationException) @@ -515,12 +489,11 @@ public partial class ModEditWindow if (!colorSet.HasValue) return; - foreach (var (subActorType, childObjectIndex, modelSlot, materialSlot) in instances) + foreach (var materialInfo in instances) { try { - ColorSetPreviewers.Add(new LiveColorSetPreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, subActorType, - childObjectIndex, modelSlot, materialSlot)); + ColorSetPreviewers.Add(new LiveColorSetPreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, materialInfo)); } catch (InvalidOperationException) { From 616a4635d197d1e6eeb944c5bc892f1778722e38 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 31 Aug 2023 18:32:18 +0200 Subject: [PATCH 0060/1381] Fix slash direction in material path. --- Penumbra/Interop/MaterialPreview/MaterialInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index f1c9c10e..0146cf6f 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -86,7 +86,7 @@ public readonly record struct MaterialInfo(DrawObjectType Type, int ModelSlot, i public static unsafe List FindMaterials(IObjectTable objects, string materialPath) { - var needle = ByteString.FromString(materialPath.Replace('/', '\\'), out var m, true) ? m : ByteString.Empty; + var needle = ByteString.FromString(materialPath.Replace('\\', '/'), out var m, true) ? m : ByteString.Empty; var result = new List(Enum.GetValues().Length); foreach (var type in Enum.GetValues()) From af4373ce507b066a8c1ac7ab3767771e99766338 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 31 Aug 2023 16:36:03 +0000 Subject: [PATCH 0061/1381] [CI] Updating repo.json for testing_0.7.3.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 630dab0d..ccd0317b 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.2", + "TestingAssemblyVersion": "0.7.3.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 6f760426c783c2cf7b6b56bc9f9331b8ac2a8989 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 1 Sep 2023 17:27:28 +0200 Subject: [PATCH 0062/1381] Fix newtonsoft not playing well with records with strings. --- .../ModEditWindow.Materials.MtrlTab.cs | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 6bb8b8c8..d230950a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -717,7 +717,11 @@ public partial class ModEditWindow return output.Write(); } - private sealed record DevkitShaderKeyValue(string Label = "", string Description = ""); + private sealed class DevkitShaderKeyValue + { + public string Label = string.Empty; + public string Description = string.Empty; + } private sealed class DevkitShaderKey { @@ -726,7 +730,12 @@ public partial class ModEditWindow public Dictionary Values = new(); } - private sealed record DevkitSampler(string Label = "", string Description = "", string DefaultTexture = ""); + private sealed class DevkitSampler + { + public string Label = string.Empty; + public string Description = string.Empty; + public string DefaultTexture = string.Empty; + } private enum DevkitConstantType { @@ -737,7 +746,12 @@ public partial class ModEditWindow Enum = 3, } - private sealed record DevkitConstantValue(string Label = "", string Description = "", float Value = 0); + private sealed class DevkitConstantValue + { + public string Label = string.Empty; + public string Description = string.Empty; + public float Value = 0; + } private sealed class DevkitConstant { From 0dbe9b59c20beb3a2bedd0ba10c1e4c765bd4b7a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 1 Sep 2023 17:31:40 +0200 Subject: [PATCH 0063/1381] Cleanup --- Penumbra/Mods/Mod.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 6aac7e1e..4df41fb5 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -4,9 +4,6 @@ using System.IO; using System.Linq; using OtterGui; using OtterGui.Classes; -using Penumbra.Collections.Cache; -using Penumbra.Import; -using Penumbra.Meta; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; From 233a865c7837376ee5d558a2b3043bf1a2381f66 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 31 Aug 2023 20:05:39 +0200 Subject: [PATCH 0064/1381] Material editor: use a SafeHandle for texture swapping --- .../MaterialPreview/LiveColorSetPreviewer.cs | 37 +++++--------- .../Interop/SafeHandles/SafeTextureHandle.cs | 48 +++++++++++++++++++ 2 files changed, 59 insertions(+), 26 deletions(-) create mode 100644 Penumbra/Interop/SafeHandles/SafeTextureHandle.cs diff --git a/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs index 18afa949..f927aa43 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs @@ -5,6 +5,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using Penumbra.GameData.Files; +using Penumbra.Interop.SafeHandles; namespace Penumbra.Interop.MaterialPreview; @@ -16,8 +17,8 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase private readonly Framework _framework; - private readonly Texture** _colorSetTexture; - private readonly Texture* _originalColorSetTexture; + private readonly Texture** _colorSetTexture; + private readonly SafeTextureHandle _originalColorSetTexture; private Half[] _colorSet; private bool _updatePending; @@ -40,12 +41,10 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase _colorSetTexture = colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); - _originalColorSetTexture = *_colorSetTexture; + _originalColorSetTexture = new SafeTextureHandle(*_colorSetTexture, true); if (_originalColorSetTexture == null) throw new InvalidOperationException("Material doesn't have a color set"); - Structs.TextureUtility.IncRef(_originalColorSetTexture); - _colorSet = new Half[TextureLength]; _updatePending = true; @@ -59,15 +58,9 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase base.Clear(disposing, reset); if (reset) - { - var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)_originalColorSetTexture); - if (oldTexture != null) - Structs.TextureUtility.DecRef(oldTexture); - } - else - { - Structs.TextureUtility.DecRef(_originalColorSetTexture); - } + _originalColorSetTexture.Exchange(ref *(nint*)_colorSetTexture); + + _originalColorSetTexture.Dispose(); } public void ScheduleUpdate() @@ -89,8 +82,8 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase textureSize[0] = TextureWidth; textureSize[1] = TextureHeight; - var newTexture = Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7); - if (newTexture == null) + using var texture = new SafeTextureHandle(Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7), false); + if (texture.IsInvalid) return; bool success; @@ -98,20 +91,12 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase { fixed (Half* colorSet = _colorSet) { - success = Structs.TextureUtility.InitializeContents(newTexture, colorSet); + success = Structs.TextureUtility.InitializeContents(texture.Texture, colorSet); } } if (success) - { - var oldTexture = (Texture*)Interlocked.Exchange(ref *(nint*)_colorSetTexture, (nint)newTexture); - if (oldTexture != null) - Structs.TextureUtility.DecRef(oldTexture); - } - else - { - Structs.TextureUtility.DecRef(newTexture); - } + texture.Exchange(ref *(nint*)_colorSetTexture); } protected override bool IsStillValid() diff --git a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs new file mode 100644 index 00000000..36cd4612 --- /dev/null +++ b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using Penumbra.Interop.Structs; + +namespace Penumbra.Interop.SafeHandles; + +public unsafe class SafeTextureHandle : SafeHandle +{ + public Texture* Texture => (Texture*)handle; + + public override bool IsInvalid => handle == 0; + + public SafeTextureHandle(Texture* handle, bool incRef, bool ownsHandle = true) : base(0, ownsHandle) + { + if (incRef && !ownsHandle) + throw new ArgumentException("Non-owning SafeTextureHandle with IncRef is unsupported"); + if (incRef && handle != null) + TextureUtility.IncRef(handle); + SetHandle((nint)handle); + } + + public void Exchange(ref nint ppTexture) + { + lock (this) + { + handle = Interlocked.Exchange(ref ppTexture, handle); + } + } + + public static SafeTextureHandle CreateInvalid() + => new(null, incRef: false); + + protected override bool ReleaseHandle() + { + nint handle; + lock (this) + { + handle = this.handle; + this.handle = 0; + } + if (handle != 0) + TextureUtility.DecRef((Texture*)handle); + + return true; + } +} From 686c53d919681ee64f00c16a182ea9cc54e1c02b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 1 Sep 2023 18:46:31 +0200 Subject: [PATCH 0065/1381] Material editor: Customizable highlight color --- .../UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs | 8 +++++--- Penumbra/UI/Classes/Colors.cs | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index d230950a..f4ce3329 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -19,6 +19,7 @@ using Penumbra.GameData.Structs; using Penumbra.Interop.MaterialPreview; using Penumbra.String; using Penumbra.String.Classes; +using Penumbra.UI.Classes; using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.UI.AdvancedWindow; @@ -668,12 +669,13 @@ public partial class ModEditWindow private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, float time) { - var level = Math.Sin(time * 2.0 * Math.PI) * 0.25 + 0.5; - var levelSq = (float)(level * level); + var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; + var baseColor = ColorId.InGameHighlight.Value(); + var color = level * new Vector3(baseColor & 0xFF, (baseColor >> 8) & 0xFF, (baseColor >> 16) & 0xFF); row.Diffuse = Vector3.Zero; row.Specular = Vector3.Zero; - row.Emissive = new Vector3(levelSq); + row.Emissive = color * color; } public void Update() diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 450f3787..e2acc1a3 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -24,7 +24,8 @@ public enum ColorId RedundantAssignment, NoModsAssignment, NoAssignment, - SelectorPriority, + SelectorPriority, + InGameHighlight, } public static class Colors @@ -64,6 +65,7 @@ public static class Colors ColorId.NoModsAssignment => ( 0x50000080, "'Use No Mods' Collection Assignment", "A collection assignment set to not use any mods at all."), ColorId.NoAssignment => ( 0x00000000, "Unassigned Collection Assignment", "A collection assignment that is not configured to any collection and thus just has no specific treatment."), ColorId.SelectorPriority => ( 0xFF808080, "Mod Selector Priority", "The priority displayed for non-zero priority mods in the mod selector."), + ColorId.InGameHighlight => ( 0xFFEBCF89, "In-Game Highlight", "An in-game element that has been highlighted for ease of editing."), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; From 5899a59e065e6534d03601b1636823c4dfe0fd38 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 1 Sep 2023 18:46:40 +0200 Subject: [PATCH 0066/1381] Material editor: Vector field spacing --- .../ModEditWindow.Materials.ConstantEditor.cs | 31 ++++++++++--------- .../ModEditWindow.Materials.Shpk.cs | 3 +- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs index e5b16a47..19e96539 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -13,7 +13,7 @@ public partial class ModEditWindow { private interface IConstantEditor { - bool Draw(Span values, bool disabled, float editorWidth); + bool Draw(Span values, bool disabled); } private sealed class FloatConstantEditor : IConstantEditor @@ -42,16 +42,18 @@ public partial class ModEditWindow _format = $"{_format} {unit.Replace("%", "%%")}"; } - public bool Draw(Span values, bool disabled, float editorWidth) + public bool Draw(Span values, bool disabled) { - var fieldWidth = (editorWidth - (values.Length - 1) * ImGui.GetStyle().ItemSpacing.X) / values.Length; + var spacing = ImGui.GetStyle().ItemInnerSpacing.X; + var fieldWidth = (ImGui.CalcItemWidth() - (values.Length - 1) * spacing) / values.Length; var ret = false; + // Not using DragScalarN because of _relativeSpeed and other points of lost flexibility. for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) { if (valueIdx > 0) - ImGui.SameLine(); + ImGui.SameLine(0.0f, spacing); ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); @@ -101,16 +103,18 @@ public partial class ModEditWindow _format = $"{_format} {unit.Replace("%", "%%")}"; } - public bool Draw(Span values, bool disabled, float editorWidth) + public bool Draw(Span values, bool disabled) { - var fieldWidth = (editorWidth - (values.Length - 1) * ImGui.GetStyle().ItemSpacing.X) / values.Length; + var spacing = ImGui.GetStyle().ItemInnerSpacing.X; + var fieldWidth = (ImGui.CalcItemWidth() - (values.Length - 1) * spacing) / values.Length; var ret = false; + // Not using DragScalarN because of _relativeSpeed and other points of lost flexibility. for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) { if (valueIdx > 0) - ImGui.SameLine(); + ImGui.SameLine(0.0f, spacing); ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); @@ -148,13 +152,12 @@ public partial class ModEditWindow _clamped = clamped; } - public bool Draw(Span values, bool disabled, float editorWidth) + public bool Draw(Span values, bool disabled) { switch (values.Length) { case 3: { - ImGui.SetNextItemWidth(editorWidth); var value = new Vector3(values); if (_squaredRgb) value = PseudoSqrtRgb(value); @@ -170,7 +173,6 @@ public partial class ModEditWindow } case 4: { - ImGui.SetNextItemWidth(editorWidth); var value = new Vector4(values); if (_squaredRgb) value = PseudoSqrtRgb(value); @@ -186,7 +188,7 @@ public partial class ModEditWindow value.CopyTo(values); return true; } - default: return FloatConstantEditor.Default.Draw(values, disabled, editorWidth); + default: return FloatConstantEditor.Default.Draw(values, disabled); } } } @@ -198,9 +200,10 @@ public partial class ModEditWindow public EnumConstantEditor(IReadOnlyList<(string Label, float Value, string Description)> values) => _values = values; - public bool Draw(Span values, bool disabled, float editorWidth) + public bool Draw(Span values, bool disabled) { - var fieldWidth = (editorWidth - (values.Length - 1) * ImGui.GetStyle().ItemSpacing.X) / values.Length; + var spacing = ImGui.GetStyle().ItemInnerSpacing.X; + var fieldWidth = (ImGui.CalcItemWidth() - (values.Length - 1) * spacing) / values.Length; var ret = false; @@ -208,7 +211,7 @@ public partial class ModEditWindow { using var id = ImRaii.PushId(valueIdx); if (valueIdx > 0) - ImGui.SameLine(); + ImGui.SameLine(0.0f, spacing); ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 8fca8aa6..f6f480e7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -259,7 +259,8 @@ public partial class ModEditWindow if (buffer.Length > 0) { using var id = ImRaii.PushId($"##{constant.Id:X8}:{slice.Start}"); - if (editor.Draw(buffer[slice], disabled, 250.0f)) + ImGui.SetNextItemWidth(250.0f); + if (editor.Draw(buffer[slice], disabled)) { ret = true; tab.SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); From 1b490510c7f3165956a9b09eee22c4e656a47995 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 1 Sep 2023 19:09:38 +0200 Subject: [PATCH 0067/1381] Fix compiler warning --- Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index f4ce3329..aff30fb0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -178,7 +178,7 @@ public partial class ModEditWindow if (mayVary && (data as JObject)?["Vary"] != null) { - var selector = BuildSelector(data["Vary"]! + var selector = BuildSelector(data!["Vary"]! .Select(key => (uint)key) .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); var index = (int)data["Selectors"]![selector.ToString()]!; From b985833aaa144d6e2593067529f9a0dad70cb07b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Sep 2023 15:54:11 +0200 Subject: [PATCH 0068/1381] Check for drawObject != null before invoking draw object created event. --- Penumbra/Interop/PathResolving/MetaState.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 1a257a96..cdf28bbd 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -140,7 +140,7 @@ public unsafe class MetaState : IDisposable { _characterBaseCreateMetaChanges.Dispose(); _characterBaseCreateMetaChanges = DisposableContainer.Empty; - if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero) + if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero && drawObject != nint.Zero) _communicator.CreatedCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, _lastCreatedCollection.ModCollection, drawObject); _lastCreatedCollection = ResolveData.Invalid; From 0741ce0ce7179adba19055b599402ce10e30db65 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Sep 2023 15:55:06 +0200 Subject: [PATCH 0069/1381] Fix variant gamepath. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 1c68fd5e..43f6737d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1c68fd5efb23798d13154c1de0ad010db319abe2 +Subproject commit 43f6737d4baa7988a5fe23096f20827bc54e6812 From ecfe88faa681fc96f75312e206f9b9b257d677b2 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 2 Sep 2023 14:00:06 +0000 Subject: [PATCH 0070/1381] [CI] Updating repo.json for testing_0.7.3.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index ccd0317b..84db423d 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.3", + "TestingAssemblyVersion": "0.7.3.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From ccc0b51a999a6e3834d41620b827546875c784e1 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 1 Sep 2023 01:53:32 +0200 Subject: [PATCH 0071/1381] Resource Tree: Improve mtrl and sklb support --- .../Interop/ResourceTree/ResolveContext.cs | 107 ++++++++++++++---- Penumbra/Interop/ResourceTree/ResourceNode.cs | 28 +++-- Penumbra/Interop/ResourceTree/ResourceTree.cs | 30 +++-- .../Interop/ResourceTree/TreeBuildCache.cs | 5 - .../UI/AdvancedWindow/ResourceTreeViewer.cs | 2 +- 5 files changed, 129 insertions(+), 43 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 0cb854f3..8a27f02b 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Collections; using Penumbra.GameData; @@ -23,17 +24,17 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); - private ResourceNode? CreateNodeFromShpk(nint sourceAddress, ByteString gamePath, bool @internal) + private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath, bool @internal) { if (gamePath.IsEmpty) return null; if (!Utf8GamePath.FromByteString(ByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path, false)) return null; - return CreateNodeFromGamePath(ResourceType.Shpk, sourceAddress, path, @internal); + return CreateNodeFromGamePath(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->Handle, path, @internal); } - private ResourceNode? CreateNodeFromTex(nint sourceAddress, ByteString gamePath, bool @internal, bool dx11) + private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool @internal, bool dx11) { if (dx11) { @@ -59,13 +60,19 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (!Utf8GamePath.FromByteString(gamePath, out var path)) return null; - return CreateNodeFromGamePath(ResourceType.Tex, sourceAddress, path, @internal); + return CreateNodeFromGamePath(ResourceType.Tex, (nint)resourceHandle->KernelTexture, &resourceHandle->Handle, path, @internal); } - private ResourceNode CreateNodeFromGamePath(ResourceType type, nint sourceAddress, Utf8GamePath gamePath, bool @internal) - => new(null, type, sourceAddress, gamePath, FilterFullPath(Collection.ResolvePath(gamePath) ?? new FullPath(gamePath)), @internal); + private unsafe ResourceNode CreateNodeFromGamePath(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, Utf8GamePath gamePath, bool @internal) + { + var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(resourceHandle), out var p) ? new FullPath(p) : FullPath.Empty; + if (fullPath.InternalName.IsEmpty) + fullPath = Collection.ResolvePath(gamePath) ?? new FullPath(gamePath); - private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint sourceAddress, ResourceHandle* handle, bool @internal, + return new(null, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), GetResourceHandleLength(resourceHandle), @internal); + } + + private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal, bool withName) { var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(handle), out var p) ? new FullPath(p) : FullPath.Empty; @@ -79,13 +86,14 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide gamePaths = Filter(gamePaths); if (gamePaths.Count == 1) - return new ResourceNode(withName ? GuessNameFromPath(gamePaths[0]) : null, type, sourceAddress, gamePaths[0], fullPath, @internal); + return new ResourceNode(withName ? GuessNameFromPath(gamePaths[0]) : null, type, objectAddress, (nint)handle, gamePaths[0], fullPath, + GetResourceHandleLength(handle), @internal); Penumbra.Log.Information($"Found {gamePaths.Count} game paths while reverse-resolving {fullPath} in {Collection.Name}:"); foreach (var gamePath in gamePaths) Penumbra.Log.Information($"Game path: {gamePath}"); - return new ResourceNode(null, type, sourceAddress, gamePaths.ToArray(), fullPath, @internal); + return new ResourceNode(null, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), @internal); } public unsafe ResourceNode? CreateHumanSkeletonNode(GenderRace gr) { @@ -95,12 +103,12 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (!Utf8GamePath.FromString(path, out var gamePath)) return null; - return CreateNodeFromGamePath(ResourceType.Sklb, 0, gamePath, false); + return CreateNodeFromGamePath(ResourceType.Sklb, 0, null, gamePath, false); } public unsafe ResourceNode? CreateNodeFromImc(ResourceHandle* imc) { - var node = CreateNodeFromResourceHandle(ResourceType.Imc, (nint) imc, imc, true, false); + var node = CreateNodeFromResourceHandle(ResourceType.Imc, 0, imc, true, false); if (node == null) return null; @@ -113,8 +121,8 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return node; } - public unsafe ResourceNode? CreateNodeFromTex(ResourceHandle* tex) - => CreateNodeFromResourceHandle(ResourceType.Tex, (nint) tex, tex, false, WithNames); + public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex) + => CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithNames); public unsafe ResourceNode? CreateNodeFromRenderModel(RenderModel* mdl) { @@ -145,6 +153,38 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide private unsafe ResourceNode? CreateNodeFromMaterial(Material* mtrl) { + static ushort GetTextureIndex(ushort texFlags) + { + if ((texFlags & 0x001F) != 0x001F) + return (ushort)(texFlags & 0x001F); + else if ((texFlags & 0x03E0) != 0x03E0) + return (ushort)((texFlags >> 5) & 0x001F); + else + return (ushort)((texFlags >> 10) & 0x001F); + } + static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle) + { + var textures = mtrl->Textures; + for (var i = 0; i < mtrl->TextureCount; ++i) + { + if (textures[i].ResourceHandle == handle) + return textures[i].Id; + } + + return null; + } + static uint? GetSamplerCrcById(ShaderPackage* shpk, uint id) + { + var samplers = (ShaderPackageUtility.Sampler*)shpk->Samplers; + for (var i = 0; i < shpk->SamplerCount; ++i) + { + if (samplers[i].Id == id) + return samplers[i].Crc; + } + + return null; + } + if (mtrl == null) return null; @@ -153,23 +193,36 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (node == null) return null; - var mtrlFile = WithNames ? TreeBuildCache.ReadMaterial(node.FullPath) : null; - - var shpkNode = CreateNodeFromShpk(nint.Zero, new ByteString(resource->ShpkString), false); + var shpkNode = CreateNodeFromShpk(resource->ShpkResourceHandle, new ByteString(resource->ShpkString), false); if (shpkNode != null) node.Children.Add(WithNames ? shpkNode.WithName("Shader Package") : shpkNode); var shpkFile = WithNames && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; - var samplers = WithNames ? mtrlFile?.GetSamplersByTexture(shpkFile) : null; + var shpk = WithNames && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; for (var i = 0; i < resource->NumTex; i++) { - var texNode = CreateNodeFromTex(nint.Zero, new ByteString(resource->TexString(i)), false, resource->TexIsDX11(i)); + var texNode = CreateNodeFromTex(resource->TexSpace[i].ResourceHandle, new ByteString(resource->TexString(i)), false, resource->TexIsDX11(i)); if (texNode == null) continue; if (WithNames) { - var name = samplers != null && i < samplers.Length ? samplers[i].ShpkSampler?.Name : null; + string? name = null; + if (shpk != null) + { + var index = GetTextureIndex(resource->TexSpace[i].Flags); + uint? samplerId; + if (index != 0x001F) + samplerId = mtrl->Textures[index].Id; + else + samplerId = GetTextureSamplerId(mtrl, resource->TexSpace[i].ResourceHandle); + if (samplerId.HasValue) + { + var samplerCrc = GetSamplerCrcById(shpk, samplerId.Value); + if (samplerCrc.HasValue) + name = shpkFile?.GetSamplerById(samplerCrc.Value)?.Name ?? $"Texture 0x{samplerCrc.Value:X8}"; + } + } node.Children.Add(texNode.WithName(name ?? $"Texture #{i}")); } else @@ -181,6 +234,14 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return node; } + public unsafe ResourceNode? CreateNodeFromPartialSkeleton(FFXIVClientStructs.FFXIV.Client.Graphics.Render.PartialSkeleton* sklb) + { + if (sklb->SkeletonResourceHandle == null) + return null; + + return CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithNames); + } + private FullPath FilterFullPath(FullPath fullPath) { if (!fullPath.IsRooted) @@ -294,4 +355,12 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return name; } + + static unsafe ulong GetResourceHandleLength(ResourceHandle* handle) + { + if (handle == null) + return 0; + + return ResourceHandle.GetLength(handle); + } } diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index dc0c5fcb..bceda36c 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -9,37 +9,43 @@ public class ResourceNode { public readonly string? Name; public readonly ResourceType Type; - public readonly nint SourceAddress; + public readonly nint ObjectAddress; + public readonly nint ResourceHandle; public readonly Utf8GamePath GamePath; public readonly Utf8GamePath[] PossibleGamePaths; public readonly FullPath FullPath; + public readonly ulong Length; public readonly bool Internal; public readonly List Children; - public ResourceNode(string? name, ResourceType type, nint sourceAddress, Utf8GamePath gamePath, FullPath fullPath, bool @internal) + public ResourceNode(string? name, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath gamePath, FullPath fullPath, ulong length, bool @internal) { - Name = name; - Type = type; - SourceAddress = sourceAddress; - GamePath = gamePath; + Name = name; + Type = type; + ObjectAddress = objectAddress; + ResourceHandle = resourceHandle; + GamePath = gamePath; PossibleGamePaths = new[] { gamePath, }; FullPath = fullPath; + Length = length; Internal = @internal; Children = new List(); } - public ResourceNode(string? name, ResourceType type, nint sourceAddress, Utf8GamePath[] possibleGamePaths, FullPath fullPath, - bool @internal) + public ResourceNode(string? name, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath[] possibleGamePaths, FullPath fullPath, + ulong length, bool @internal) { Name = name; Type = type; - SourceAddress = sourceAddress; + ObjectAddress = objectAddress; + ResourceHandle = resourceHandle; GamePath = possibleGamePaths.Length == 1 ? possibleGamePaths[0] : Utf8GamePath.Empty; PossibleGamePaths = possibleGamePaths; FullPath = fullPath; + Length = length; Internal = @internal; Children = new List(); } @@ -48,10 +54,12 @@ public class ResourceNode { Name = name; Type = originalResourceNode.Type; - SourceAddress = originalResourceNode.SourceAddress; + ObjectAddress = originalResourceNode.ObjectAddress; + ResourceHandle = originalResourceNode.ResourceHandle; GamePath = originalResourceNode.GamePath; PossibleGamePaths = originalResourceNode.PossibleGamePaths; FullPath = originalResourceNode.FullPath; + Length = originalResourceNode.Length; Internal = originalResourceNode.Internal; Children = originalResourceNode.Children; } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 76d0c3f2..f14191c8 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -57,7 +58,9 @@ public class ResourceTree var mdlNode = context.CreateNodeFromRenderModel(mdl); if (mdlNode != null) Nodes.Add(globalContext.WithNames ? mdlNode.WithName(mdlNode.Name ?? $"Model #{i}") : mdlNode); - } + } + + AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); if (character->GameObject.GetObjectKind() == (byte)ObjectKind.Pc) AddHumanResources(globalContext, (HumanExt*)model); @@ -95,7 +98,9 @@ public class ResourceTree subObjectNodes.Add(globalContext.WithNames ? mdlNode.WithName(mdlNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}") : mdlNode); - } + } + + AddSkeleton(subObjectNodes, subObjectContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); subObject = (CharacterBase*)subObject->DrawObject.Object.NextSiblingObject; ++subObjectIndex; @@ -106,16 +111,25 @@ public class ResourceTree var context = globalContext.CreateContext(EquipSlot.Unknown, default); - var skeletonNode = context.CreateHumanSkeletonNode((GenderRace)human->Human.RaceSexId); - if (skeletonNode != null) - Nodes.Add(globalContext.WithNames ? skeletonNode.WithName(skeletonNode.Name ?? "Skeleton") : skeletonNode); - - var decalNode = context.CreateNodeFromTex(human->Decal); + var decalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->Decal); if (decalNode != null) Nodes.Add(globalContext.WithNames ? decalNode.WithName(decalNode.Name ?? "Face Decal") : decalNode); - var legacyDecalNode = context.CreateNodeFromTex(human->LegacyBodyDecal); + var legacyDecalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->LegacyBodyDecal); if (legacyDecalNode != null) Nodes.Add(globalContext.WithNames ? legacyDecalNode.WithName(legacyDecalNode.Name ?? "Legacy Body Decal") : legacyDecalNode); + } + + private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") + { + if (skeleton == null) + return; + + for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) + { + var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); + if (sklbNode != null) + nodes.Add(context.WithNames ? sklbNode.WithName($"{prefix}Skeleton #{i}") : sklbNode); + } } } diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index e9939496..d29916dd 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -12,7 +12,6 @@ namespace Penumbra.Interop.ResourceTree; internal class TreeBuildCache { private readonly IDataManager _dataManager; - private readonly Dictionary _materials = new(); private readonly Dictionary _shaderPackages = new(); public readonly List Characters; public readonly Dictionary CharactersById; @@ -27,10 +26,6 @@ internal class TreeBuildCache .ToDictionary(c => c.Key, c => c.First()); } - /// Try to read a material file from the given path and cache it on success. - public MtrlFile? ReadMaterial(FullPath path) - => ReadFile(_dataManager, path, _materials, bytes => new MtrlFile(bytes)); - /// Try to read a shpk file from the given path and cache it on success. public ShpkFile? ReadShaderPackage(FullPath path) => ReadFile(_dataManager, path, _shaderPackages, bytes => new ShpkFile(bytes)); diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 4d8c77a7..0d87215f 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -128,7 +128,7 @@ public class ResourceTreeViewer if (debugMode) ImGuiUtil.HoverTooltip( - $"Resource Type: {resourceNode.Type}\nSource Address: 0x{resourceNode.SourceAddress:X16}"); + $"Resource Type: {resourceNode.Type}\nObject Address: 0x{resourceNode.ObjectAddress:X16}\nResource Handle: 0x{resourceNode.ResourceHandle:X16}\nLength: 0x{resourceNode.Length:X}"); } ImGui.TableNextColumn(); From db521dd21cc8438308c2e2d983d7fbfb704211f0 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 1 Sep 2023 04:52:54 +0200 Subject: [PATCH 0072/1381] Resource Tree: Deduplicate nodes, add skp --- .../Interop/ResourceTree/ResolveContext.cs | 76 +++++++++++++++++-- Penumbra/Interop/ResourceTree/ResourceTree.cs | 34 +++++---- .../ResourceTree/ResourceTreeFactory.cs | 6 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 32 +++++--- 4 files changed, 114 insertions(+), 34 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 8a27f02b..a97ff726 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -11,21 +11,27 @@ using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; +using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.Interop.ResourceTree; internal record class GlobalResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithNames) { + public readonly Dictionary Nodes = new(128); + public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) - => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithNames, slot, equipment); + => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithNames, Nodes, slot, equipment); } -internal record class ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithNames, EquipSlot Slot, - CharacterArmor Equipment) +internal record class ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithNames, + Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath, bool @internal) { + if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) + return cached; + if (gamePath.IsEmpty) return null; if (!Utf8GamePath.FromByteString(ByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path, false)) @@ -36,6 +42,9 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool @internal, bool dx11) { + if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) + return cached; + if (dx11) { var lastDirectorySeparator = gamePath.LastIndexOf((byte)'/'); @@ -69,7 +78,11 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (fullPath.InternalName.IsEmpty) fullPath = Collection.ResolvePath(gamePath) ?? new FullPath(gamePath); - return new(null, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), GetResourceHandleLength(resourceHandle), @internal); + var node = new ResourceNode(null, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), GetResourceHandleLength(resourceHandle), @internal); + if (resourceHandle != null) + Nodes.Add((nint)resourceHandle, node); + + return node; } private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal, @@ -95,6 +108,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return new ResourceNode(null, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), @internal); } + public unsafe ResourceNode? CreateHumanSkeletonNode(GenderRace gr) { var raceSexIdStr = gr.ToRaceCode(); @@ -108,6 +122,9 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide public unsafe ResourceNode? CreateNodeFromImc(ResourceHandle* imc) { + if (Nodes.TryGetValue((nint)imc, out var cached)) + return cached; + var node = CreateNodeFromResourceHandle(ResourceType.Imc, 0, imc, true, false); if (node == null) return null; @@ -118,17 +135,31 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide node = node.WithName(name != null ? $"IMC: {name}" : null); } + Nodes.Add((nint)imc, node); + return node; } public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex) - => CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithNames); + { + if (Nodes.TryGetValue((nint)tex, out var cached)) + return cached; + + var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithNames); + if (node != null) + Nodes.Add((nint)tex, node); + + return node; + } public unsafe ResourceNode? CreateNodeFromRenderModel(RenderModel* mdl) { if (mdl == null || mdl->ResourceHandle == null || mdl->ResourceHandle->Category != ResourceCategory.Chara) return null; + if (Nodes.TryGetValue((nint)mdl->ResourceHandle, out var cached)) + return cached; + var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint) mdl, mdl->ResourceHandle, false, false); if (node == null) return null; @@ -148,6 +179,8 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide : mtrlNode); } + Nodes.Add((nint)mdl->ResourceHandle, node); + return node; } @@ -188,7 +221,10 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (mtrl == null) return null; - var resource = mtrl->ResourceHandle; + var resource = mtrl->ResourceHandle; + if (Nodes.TryGetValue((nint)resource, out var cached)) + return cached; + var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint) mtrl, &resource->Handle, false, WithNames); if (node == null) return null; @@ -231,6 +267,8 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide } } + Nodes.Add((nint)resource, node); + return node; } @@ -239,7 +277,29 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (sklb->SkeletonResourceHandle == null) return null; - return CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithNames); + if (Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) + return cached; + + var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithNames); + if (node != null) + Nodes.Add((nint)sklb->SkeletonResourceHandle, node); + + return node; + } + + public unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(FFXIVClientStructs.FFXIV.Client.Graphics.Render.PartialSkeleton* sklb) + { + if (sklb->SkeletonParameterResourceHandle == null) + return null; + + if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) + return cached; + + var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, WithNames); + if (node != null) + Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); + + return node; } private FullPath FilterFullPath(FullPath fullPath) @@ -356,7 +416,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return name; } - static unsafe ulong GetResourceHandleLength(ResourceHandle* handle) + private static unsafe ulong GetResourceHandleLength(ResourceHandle* handle) { if (handle == null) return 0; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index f14191c8..f3e6ca51 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -13,29 +13,33 @@ namespace Penumbra.Interop.ResourceTree; public class ResourceTree { - public readonly string Name; - public readonly nint SourceAddress; - public readonly bool PlayerRelated; - public readonly string CollectionName; - public readonly List Nodes; + public readonly string Name; + public readonly nint GameObjectAddress; + public readonly nint DrawObjectAddress; + public readonly bool PlayerRelated; + public readonly string CollectionName; + public readonly List Nodes; + public readonly HashSet FlatNodes; public int ModelId; public CustomizeData CustomizeData; public GenderRace RaceCode; - public ResourceTree(string name, nint sourceAddress, bool playerRelated, string collectionName) + public ResourceTree(string name, nint gameObjectAddress, nint drawObjectAddress, bool playerRelated, string collectionName) { - Name = name; - SourceAddress = sourceAddress; - PlayerRelated = playerRelated; - CollectionName = collectionName; - Nodes = new List(); + Name = name; + GameObjectAddress = gameObjectAddress; + DrawObjectAddress = drawObjectAddress; + PlayerRelated = playerRelated; + CollectionName = collectionName; + Nodes = new List(); + FlatNodes = new HashSet(); } internal unsafe void LoadResources(GlobalResolveContext globalContext) { - var character = (Character*)SourceAddress; - var model = (CharacterBase*)character->GameObject.GetDrawObject(); + var character = (Character*)GameObjectAddress; + var model = (CharacterBase*)DrawObjectAddress; var equipment = new ReadOnlySpan(&character->DrawData.Head, 10); // var customize = new ReadOnlySpan( character->CustomizeData, 26 ); ModelId = character->CharacterData.ModelCharaId; @@ -130,6 +134,10 @@ public class ResourceTree var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (sklbNode != null) nodes.Add(context.WithNames ? sklbNode.WithName($"{prefix}Skeleton #{i}") : sklbNode); + + var skpNode = context.CreateParameterNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); + if (skpNode != null) + nodes.Add(context.WithNames ? skpNode.WithName($"{prefix}Skeleton #{i} Parameters") : skpNode); } } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 98c1b305..f416dc12 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -62,7 +62,8 @@ public class ResourceTreeFactory return null; var gameObjStruct = (GameObject*)character.Address; - if (gameObjStruct->GetDrawObject() == null) + var drawObjStruct = gameObjStruct->GetDrawObject(); + if (drawObjStruct == null) return null; var collectionResolveData = _collectionResolver.IdentifyCollection(gameObjStruct, true); @@ -70,10 +71,11 @@ public class ResourceTreeFactory return null; var (name, related) = GetCharacterName(character, cache); - var tree = new ResourceTree(name, (nint)gameObjStruct, related, collectionResolveData.ModCollection.Name); + var tree = new ResourceTree(name, (nint)gameObjStruct, (nint)drawObjStruct, related, collectionResolveData.ModCollection.Name); var globalContext = new GlobalResolveContext(_config, _identifier.AwaitedService, cache, collectionResolveData.ModCollection, ((Character*)gameObjStruct)->CharacterData.ModelCharaId, withNames); tree.LoadResources(globalContext); + tree.FlatNodes.UnionWith(globalContext.Nodes.Values); return tree; } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 0d87215f..8e996eb7 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -18,7 +18,7 @@ public class ResourceTreeViewer private readonly int _actionCapacity; private readonly Action _onRefresh; private readonly Action _drawActions; - private readonly HashSet _unfolded; + private readonly HashSet _unfolded; private Task? _task; @@ -30,7 +30,7 @@ public class ResourceTreeViewer _actionCapacity = actionCapacity; _onRefresh = onRefresh; _drawActions = drawActions; - _unfolded = new HashSet(); + _unfolded = new HashSet(); } public void Draw() @@ -82,7 +82,7 @@ public class ResourceTreeViewer (_actionCapacity - 1) * 3 * ImGuiHelpers.GlobalScale + _actionCapacity * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); - DrawNodes(tree.Nodes, 0); + DrawNodes(tree.Nodes, 0, 0); } } } @@ -101,7 +101,7 @@ public class ResourceTreeViewer } }); - private void DrawNodes(IEnumerable resourceNodes, int level) + private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash) { var debugMode = _config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); @@ -109,26 +109,36 @@ public class ResourceTreeViewer foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { if (resourceNode.Internal && !debugMode) - continue; + continue; + + var textColor = ImGui.GetColorU32(ImGuiCol.Text); + var textColorInternal = (textColor & 0x00FFFFFFu) | ((textColor & 0xFE000000u) >> 1); // Half opacity + + using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, textColorInternal, resourceNode.Internal); + + var nodePathHash = unchecked(pathHash + resourceNode.ResourceHandle); using var id = ImRaii.PushId(index); ImGui.TableNextColumn(); - var unfolded = _unfolded.Contains(resourceNode); + var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) { ImGui.TableHeader((resourceNode.Children.Count > 0 ? unfolded ? "[-] " : "[+] " : string.Empty) + resourceNode.Name); if (ImGui.IsItemClicked() && resourceNode.Children.Count > 0) { if (unfolded) - _unfolded.Remove(resourceNode); + _unfolded.Remove(nodePathHash); else - _unfolded.Add(resourceNode); + _unfolded.Add(nodePathHash); unfolded = !unfolded; } - if (debugMode) + if (debugMode) + { + using var _ = ImRaii.PushFont(UiBuilder.MonoFont); ImGuiUtil.HoverTooltip( - $"Resource Type: {resourceNode.Type}\nObject Address: 0x{resourceNode.ObjectAddress:X16}\nResource Handle: 0x{resourceNode.ResourceHandle:X16}\nLength: 0x{resourceNode.Length:X}"); + $"Resource Type: {resourceNode.Type}\nObject Address: 0x{resourceNode.ObjectAddress:X16}\nResource Handle: 0x{resourceNode.ResourceHandle:X16}\nLength: 0x{resourceNode.Length:X16}"); + } } ImGui.TableNextColumn(); @@ -171,7 +181,7 @@ public class ResourceTreeViewer } if (unfolded) - DrawNodes(resourceNode.Children, level + 1); + DrawNodes(resourceNode.Children, level + 1, unchecked(nodePathHash * 31)); } } } From 30c622c085d658ca69bf980a707ab1860b9993f8 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 1 Sep 2023 06:06:42 +0200 Subject: [PATCH 0073/1381] Resource Tree: Add ChangedItem-like icons, make UI prettier --- .../Interop/ResourceTree/ResolveContext.cs | 72 ++++++++++--------- Penumbra/Interop/ResourceTree/ResourceNode.cs | 31 +++++--- Penumbra/Interop/ResourceTree/ResourceTree.cs | 20 +++--- .../ResourceTree/ResourceTreeFactory.cs | 17 ++--- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 5 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 44 ++++++++---- Penumbra/UI/ChangedItemDrawer.cs | 41 ++++++----- Penumbra/UI/Tabs/OnScreenTab.cs | 4 +- 8 files changed, 139 insertions(+), 95 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index a97ff726..72a5be69 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -11,20 +11,21 @@ using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; -using static Penumbra.GameData.Files.ShpkFile; +using Penumbra.UI; namespace Penumbra.Interop.ResourceTree; -internal record class GlobalResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithNames) +internal record class GlobalResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithUIData, + bool RedactExternalPaths) { public readonly Dictionary Nodes = new(128); public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) - => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithNames, Nodes, slot, equipment); + => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithUIData, RedactExternalPaths, Nodes, slot, equipment); } -internal record class ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithNames, - Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) +internal record class ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithUIData, + bool RedactExternalPaths, Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath, bool @internal) @@ -78,7 +79,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (fullPath.InternalName.IsEmpty) fullPath = Collection.ResolvePath(gamePath) ?? new FullPath(gamePath); - var node = new ResourceNode(null, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), GetResourceHandleLength(resourceHandle), @internal); + var node = new ResourceNode(default, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), GetResourceHandleLength(resourceHandle), @internal); if (resourceHandle != null) Nodes.Add((nint)resourceHandle, node); @@ -99,14 +100,14 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide gamePaths = Filter(gamePaths); if (gamePaths.Count == 1) - return new ResourceNode(withName ? GuessNameFromPath(gamePaths[0]) : null, type, objectAddress, (nint)handle, gamePaths[0], fullPath, + return new ResourceNode(withName ? GuessUIDataFromPath(gamePaths[0]) : default, type, objectAddress, (nint)handle, gamePaths[0], fullPath, GetResourceHandleLength(handle), @internal); Penumbra.Log.Information($"Found {gamePaths.Count} game paths while reverse-resolving {fullPath} in {Collection.Name}:"); foreach (var gamePath in gamePaths) Penumbra.Log.Information($"Game path: {gamePath}"); - return new ResourceNode(null, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), @internal); + return new ResourceNode(default, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), @internal); } public unsafe ResourceNode? CreateHumanSkeletonNode(GenderRace gr) @@ -129,10 +130,10 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (node == null) return null; - if (WithNames) + if (WithUIData) { - var name = GuessModelName(node.GamePath); - node = node.WithName(name != null ? $"IMC: {name}" : null); + var uiData = GuessModelUIData(node.GamePath); + node = node.WithUIData(uiData.PrependName("IMC: ")); } Nodes.Add((nint)imc, node); @@ -145,7 +146,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)tex, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithNames); + var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithUIData); if (node != null) Nodes.Add((nint)tex, node); @@ -164,8 +165,8 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (node == null) return null; - if (WithNames) - node = node.WithName(GuessModelName(node.GamePath)); + if (WithUIData) + node = node.WithUIData(GuessModelUIData(node.GamePath)); for (var i = 0; i < mdl->MaterialCount; i++) { @@ -173,9 +174,9 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide var mtrlNode = CreateNodeFromMaterial(mtrl); if (mtrlNode != null) // Don't keep the material's name if it's redundant with the model's name. - node.Children.Add(WithNames - ? mtrlNode.WithName((string.Equals(mtrlNode.Name, node.Name, StringComparison.Ordinal) ? null : mtrlNode.Name) - ?? $"Material #{i}") + node.Children.Add(WithUIData + ? mtrlNode.WithUIData((string.Equals(mtrlNode.Name, node.Name, StringComparison.Ordinal) ? null : mtrlNode.Name) + ?? $"Material #{i}", mtrlNode.Icon) : mtrlNode); } @@ -225,15 +226,15 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)resource, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint) mtrl, &resource->Handle, false, WithNames); + var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint) mtrl, &resource->Handle, false, WithUIData); if (node == null) return null; var shpkNode = CreateNodeFromShpk(resource->ShpkResourceHandle, new ByteString(resource->ShpkString), false); if (shpkNode != null) - node.Children.Add(WithNames ? shpkNode.WithName("Shader Package") : shpkNode); - var shpkFile = WithNames && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; - var shpk = WithNames && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; + node.Children.Add(WithUIData ? shpkNode.WithUIData("Shader Package", 0) : shpkNode); + var shpkFile = WithUIData && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; + var shpk = WithUIData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; for (var i = 0; i < resource->NumTex; i++) { @@ -241,7 +242,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (texNode == null) continue; - if (WithNames) + if (WithUIData) { string? name = null; if (shpk != null) @@ -259,7 +260,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide name = shpkFile?.GetSamplerById(samplerCrc.Value)?.Name ?? $"Texture 0x{samplerCrc.Value:X8}"; } } - node.Children.Add(texNode.WithName(name ?? $"Texture #{i}")); + node.Children.Add(texNode.WithUIData(name ?? $"Texture #{i}", 0)); } else { @@ -280,7 +281,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithNames); + var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithUIData); if (node != null) Nodes.Add((nint)sklb->SkeletonResourceHandle, node); @@ -295,7 +296,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, WithNames); + var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, WithUIData); if (node != null) Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); @@ -308,7 +309,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return fullPath; var relPath = Path.GetRelativePath(Config.ModDirectory, fullPath.FullName); - if (relPath == "." || !relPath.StartsWith('.') && !Path.IsPathRooted(relPath)) + if (!RedactExternalPaths || relPath == "." || !relPath.StartsWith('.') && !Path.IsPathRooted(relPath)) return fullPath.Exists ? fullPath : FullPath.Empty; return FullPath.Empty; @@ -351,7 +352,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide } : false; - private string? GuessModelName(Utf8GamePath gamePath) + private ResourceNode.UIData GuessModelUIData(Utf8GamePath gamePath) { var path = gamePath.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries); // Weapons intentionally left out. @@ -359,23 +360,24 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (isEquipment) foreach (var item in Identifier.Identify(Equipment.Set, Equipment.Variant, Slot.ToSlot())) { - return Slot switch + var name = Slot switch { EquipSlot.RFinger => "R: ", EquipSlot.LFinger => "L: ", _ => string.Empty, } + item.Name.ToString(); + return new(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); } - var nameFromPath = GuessNameFromPath(gamePath); - if (nameFromPath != null) - return nameFromPath; + var dataFromPath = GuessUIDataFromPath(gamePath); + if (dataFromPath.Name != null) + return dataFromPath; - return isEquipment ? Slot.ToName() : null; + return isEquipment ? new(Slot.ToName(), ChangedItemDrawer.GetCategoryIcon(Slot.ToSlot())) : new(null, ChangedItemDrawer.ChangedItemIcon.Unknown); } - private string? GuessNameFromPath(Utf8GamePath gamePath) + private ResourceNode.UIData GuessUIDataFromPath(Utf8GamePath gamePath) { foreach (var obj in Identifier.Identify(gamePath.ToString())) { @@ -383,10 +385,10 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (name.StartsWith("Customization:")) name = name[14..].Trim(); if (name != "Unknown") - return name; + return new(name, ChangedItemDrawer.GetCategoryIcon(obj.Key, obj.Value)); } - return null; + return new(null, ChangedItemDrawer.ChangedItemIcon.Unknown); } private static string? SafeGet(ReadOnlySpan array, Index index) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index bceda36c..17584787 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -2,12 +2,14 @@ using System; using System.Collections.Generic; using Penumbra.GameData.Enums; using Penumbra.String.Classes; +using ChangedItemIcon = Penumbra.UI.ChangedItemDrawer.ChangedItemIcon; namespace Penumbra.Interop.ResourceTree; public class ResourceNode { public readonly string? Name; + public readonly ChangedItemIcon Icon; public readonly ResourceType Type; public readonly nint ObjectAddress; public readonly nint ResourceHandle; @@ -18,9 +20,11 @@ public class ResourceNode public readonly bool Internal; public readonly List Children; - public ResourceNode(string? name, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath gamePath, FullPath fullPath, ulong length, bool @internal) + public ResourceNode(UIData uiData, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath gamePath, FullPath fullPath, + ulong length, bool @internal) { - Name = name; + Name = uiData.Name; + Icon = uiData.Icon; Type = type; ObjectAddress = objectAddress; ResourceHandle = resourceHandle; @@ -35,10 +39,11 @@ public class ResourceNode Children = new List(); } - public ResourceNode(string? name, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath[] possibleGamePaths, FullPath fullPath, + public ResourceNode(UIData uiData, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath[] possibleGamePaths, FullPath fullPath, ulong length, bool @internal) { - Name = name; + Name = uiData.Name; + Icon = uiData.Icon; Type = type; ObjectAddress = objectAddress; ResourceHandle = resourceHandle; @@ -50,9 +55,10 @@ public class ResourceNode Children = new List(); } - private ResourceNode(string? name, ResourceNode originalResourceNode) + private ResourceNode(UIData uiData, ResourceNode originalResourceNode) { - Name = name; + Name = uiData.Name; + Icon = uiData.Icon; Type = originalResourceNode.Type; ObjectAddress = originalResourceNode.ObjectAddress; ResourceHandle = originalResourceNode.ResourceHandle; @@ -64,6 +70,15 @@ public class ResourceNode Children = originalResourceNode.Children; } - public ResourceNode WithName(string? name) - => string.Equals(Name, name, StringComparison.Ordinal) ? this : new ResourceNode(name, this); + public ResourceNode WithUIData(string? name, ChangedItemIcon icon) + => string.Equals(Name, name, StringComparison.Ordinal) && Icon == icon ? this : new ResourceNode(new(name, icon), this); + + public ResourceNode WithUIData(UIData uiData) + => string.Equals(Name, uiData.Name, StringComparison.Ordinal) && Icon == uiData.Icon ? this : new ResourceNode(uiData, this); + + public readonly record struct UIData(string? Name, ChangedItemIcon Icon) + { + public readonly UIData PrependName(string prefix) + => Name == null ? this : new(prefix + Name, Icon); + } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index f3e6ca51..c6e90c6b 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -56,12 +56,12 @@ public class ResourceTree var imc = (ResourceHandle*)model->IMCArray[i]; var imcNode = context.CreateNodeFromImc(imc); if (imcNode != null) - Nodes.Add(globalContext.WithNames ? imcNode.WithName(imcNode.Name ?? $"IMC #{i}") : imcNode); + Nodes.Add(globalContext.WithUIData ? imcNode.WithUIData(imcNode.Name ?? $"IMC #{i}", imcNode.Icon) : imcNode); var mdl = (RenderModel*)model->Models[i]; var mdlNode = context.CreateNodeFromRenderModel(mdl); if (mdlNode != null) - Nodes.Add(globalContext.WithNames ? mdlNode.WithName(mdlNode.Name ?? $"Model #{i}") : mdlNode); + Nodes.Add(globalContext.WithUIData ? mdlNode.WithUIData(mdlNode.Name ?? $"Model #{i}", mdlNode.Icon) : mdlNode); } AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); @@ -92,15 +92,15 @@ public class ResourceTree var imc = (ResourceHandle*)subObject->IMCArray[i]; var imcNode = subObjectContext.CreateNodeFromImc(imc); if (imcNode != null) - subObjectNodes.Add(globalContext.WithNames - ? imcNode.WithName(imcNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}") + subObjectNodes.Add(globalContext.WithUIData + ? imcNode.WithUIData(imcNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}", imcNode.Icon) : imcNode); var mdl = (RenderModel*)subObject->Models[i]; var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); if (mdlNode != null) - subObjectNodes.Add(globalContext.WithNames - ? mdlNode.WithName(mdlNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}") + subObjectNodes.Add(globalContext.WithUIData + ? mdlNode.WithUIData(mdlNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}", mdlNode.Icon) : mdlNode); } @@ -117,11 +117,11 @@ public class ResourceTree var decalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->Decal); if (decalNode != null) - Nodes.Add(globalContext.WithNames ? decalNode.WithName(decalNode.Name ?? "Face Decal") : decalNode); + Nodes.Add(globalContext.WithUIData ? decalNode.WithUIData(decalNode.Name ?? "Face Decal", decalNode.Icon) : decalNode); var legacyDecalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->LegacyBodyDecal); if (legacyDecalNode != null) - Nodes.Add(globalContext.WithNames ? legacyDecalNode.WithName(legacyDecalNode.Name ?? "Legacy Body Decal") : legacyDecalNode); + Nodes.Add(globalContext.WithUIData ? legacyDecalNode.WithUIData(legacyDecalNode.Name ?? "Legacy Body Decal", legacyDecalNode.Icon) : legacyDecalNode); } private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") @@ -133,11 +133,11 @@ public class ResourceTree { var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (sklbNode != null) - nodes.Add(context.WithNames ? sklbNode.WithName($"{prefix}Skeleton #{i}") : sklbNode); + nodes.Add(context.WithUIData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); var skpNode = context.CreateParameterNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (skpNode != null) - nodes.Add(context.WithNames ? skpNode.WithName($"{prefix}Skeleton #{i} Parameters") : skpNode); + nodes.Add(context.WithUIData ? skpNode.WithUIData($"{prefix}Skeleton #{i} Parameters", skpNode.Icon) : skpNode); } } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index f416dc12..8d5318f2 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -29,34 +29,35 @@ public class ResourceTreeFactory _actors = actors; } - public ResourceTree[] FromObjectTable(bool withNames = true) + public ResourceTree[] FromObjectTable(bool withNames = true, bool redactExternalPaths = true) { var cache = new TreeBuildCache(_objects, _gameData); return cache.Characters - .Select(c => FromCharacter(c, cache, withNames)) + .Select(c => FromCharacter(c, cache, withNames, redactExternalPaths)) .OfType() .ToArray(); } public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromCharacters( IEnumerable characters, - bool withNames = true) + bool withUIData = true, bool redactExternalPaths = true) { var cache = new TreeBuildCache(_objects, _gameData); foreach (var character in characters) { - var tree = FromCharacter(character, cache, withNames); + var tree = FromCharacter(character, cache, withUIData, redactExternalPaths); if (tree != null) yield return (character, tree); } } - public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, bool withNames = true) - => FromCharacter(character, new TreeBuildCache(_objects, _gameData), withNames); + public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, bool withUIData = true, + bool redactExternalPaths = true) + => FromCharacter(character, new TreeBuildCache(_objects, _gameData), withUIData, redactExternalPaths); private unsafe ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache, - bool withNames = true) + bool withUIData = true, bool redactExternalPaths = true) { if (!character.IsValid()) return null; @@ -73,7 +74,7 @@ public class ResourceTreeFactory var (name, related) = GetCharacterName(character, cache); var tree = new ResourceTree(name, (nint)gameObjStruct, (nint)drawObjStruct, related, collectionResolveData.ModCollection.Name); var globalContext = new GlobalResolveContext(_config, _identifier.AwaitedService, cache, collectionResolveData.ModCollection, - ((Character*)gameObjStruct)->CharacterData.ModelCharaId, withNames); + ((Character*)gameObjStruct)->CharacterData.ModelCharaId, withUIData, redactExternalPaths); tree.LoadResources(globalContext); tree.FlatNodes.UnionWith(globalContext.Nodes.Values); return tree; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index e90c148e..890abfed 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -554,7 +554,8 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, - CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, GameEventManager gameEvents) + CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, GameEventManager gameEvents, + ChangedItemDrawer changedItemDrawer) : base(WindowBaseLabel) { _performance = performance; @@ -581,7 +582,7 @@ public partial class ModEditWindow : Window, IDisposable (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); - _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, 2, OnQuickImportRefresh, DrawQuickImportActions); + _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ModEditWindow); } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 8e996eb7..528f19c1 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -14,7 +14,8 @@ namespace Penumbra.UI.AdvancedWindow; public class ResourceTreeViewer { private readonly Configuration _config; - private readonly ResourceTreeFactory _treeFactory; + private readonly ResourceTreeFactory _treeFactory; + private readonly ChangedItemDrawer _changedItemDrawer; private readonly int _actionCapacity; private readonly Action _onRefresh; private readonly Action _drawActions; @@ -22,15 +23,16 @@ public class ResourceTreeViewer private Task? _task; - public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, int actionCapacity, Action onRefresh, - Action drawActions) + public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, + int actionCapacity, Action onRefresh, Action drawActions) { - _config = config; - _treeFactory = treeFactory; - _actionCapacity = actionCapacity; - _onRefresh = onRefresh; - _drawActions = drawActions; - _unfolded = new HashSet(); + _config = config; + _treeFactory = treeFactory; + _changedItemDrawer = changedItemDrawer; + _actionCapacity = actionCapacity; + _onRefresh = onRefresh; + _drawActions = drawActions; + _unfolded = new HashSet(); } public void Draw() @@ -122,8 +124,24 @@ public class ResourceTreeViewer ImGui.TableNextColumn(); var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) - { - ImGui.TableHeader((resourceNode.Children.Count > 0 ? unfolded ? "[-] " : "[+] " : string.Empty) + resourceNode.Name); + { + if (resourceNode.Children.Count > 0) + { + using var font = ImRaii.PushFont(UiBuilder.IconFont); + var icon = (unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(); + var offset = (ImGui.GetFrameHeight() - ImGui.CalcTextSize(icon).X) / 2; + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + offset); + ImGui.TextUnformatted(icon); + ImGui.SameLine(0f, offset + ImGui.GetStyle().ItemInnerSpacing.X); + } + else + { + ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); + ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); + } + _changedItemDrawer.DrawCategoryIcon(resourceNode.Icon); + ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); + ImGui.TableHeader(resourceNode.Name); if (ImGui.IsItemClicked() && resourceNode.Children.Count > 0) { if (unfolded) @@ -170,7 +188,9 @@ public class ResourceTreeViewer ImGui.Selectable("(unavailable)", false, ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); ImGuiUtil.HoverTooltip("The actual path to this file is unavailable.\nIt may be managed by another plug-in."); - } + } + + mutedColor.Dispose(); if (_actionCapacity > 0) { diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 7a81ec60..da4faa43 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -76,9 +76,11 @@ public class ChangedItemDrawer : IDisposable /// Draw the icon corresponding to the category of a changed item. public void DrawCategoryIcon(string name, object? data) + => DrawCategoryIcon(GetCategoryIcon(name, data)); + + public void DrawCategoryIcon(ChangedItemIcon iconType) { - var height = ImGui.GetFrameHeight(); - var iconType = GetCategoryIcon(name, data); + var height = ImGui.GetFrameHeight(); if (!_icons.TryGetValue(iconType, out var icon)) { ImGui.Dummy(new Vector2(height)); @@ -216,27 +218,13 @@ public class ChangedItemDrawer : IDisposable } /// Obtain the icon category corresponding to a changed item. - private static ChangedItemIcon GetCategoryIcon(string name, object? obj) + internal static ChangedItemIcon GetCategoryIcon(string name, object? obj) { var iconType = ChangedItemIcon.Unknown; switch (obj) { case EquipItem it: - iconType = it.Type.ToSlot() switch - { - EquipSlot.MainHand => ChangedItemIcon.Mainhand, - EquipSlot.OffHand => ChangedItemIcon.Offhand, - EquipSlot.Head => ChangedItemIcon.Head, - EquipSlot.Body => ChangedItemIcon.Body, - EquipSlot.Hands => ChangedItemIcon.Hands, - EquipSlot.Legs => ChangedItemIcon.Legs, - EquipSlot.Feet => ChangedItemIcon.Feet, - EquipSlot.Ears => ChangedItemIcon.Ears, - EquipSlot.Neck => ChangedItemIcon.Neck, - EquipSlot.Wrists => ChangedItemIcon.Wrists, - EquipSlot.RFinger => ChangedItemIcon.Finger, - _ => ChangedItemIcon.Unknown, - }; + iconType = GetCategoryIcon(it.Type.ToSlot()); break; case ModelChara m: iconType = (CharacterBase.ModelType)m.Type switch @@ -259,6 +247,23 @@ public class ChangedItemDrawer : IDisposable return iconType; } + internal static ChangedItemIcon GetCategoryIcon(EquipSlot slot) + => slot switch + { + EquipSlot.MainHand => ChangedItemIcon.Mainhand, + EquipSlot.OffHand => ChangedItemIcon.Offhand, + EquipSlot.Head => ChangedItemIcon.Head, + EquipSlot.Body => ChangedItemIcon.Body, + EquipSlot.Hands => ChangedItemIcon.Hands, + EquipSlot.Legs => ChangedItemIcon.Legs, + EquipSlot.Feet => ChangedItemIcon.Feet, + EquipSlot.Ears => ChangedItemIcon.Ears, + EquipSlot.Neck => ChangedItemIcon.Neck, + EquipSlot.Wrists => ChangedItemIcon.Wrists, + EquipSlot.RFinger => ChangedItemIcon.Finger, + _ => ChangedItemIcon.Unknown, + }; + /// Return more detailed object information in text, if it exists. private static bool GetChangedItemObject(object? obj, out string text) { diff --git a/Penumbra/UI/Tabs/OnScreenTab.cs b/Penumbra/UI/Tabs/OnScreenTab.cs index 0ebc7dbd..c8f86333 100644 --- a/Penumbra/UI/Tabs/OnScreenTab.cs +++ b/Penumbra/UI/Tabs/OnScreenTab.cs @@ -10,10 +10,10 @@ public class OnScreenTab : ITab private readonly Configuration _config; private ResourceTreeViewer _viewer; - public OnScreenTab(Configuration config, ResourceTreeFactory treeFactory) + public OnScreenTab(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer) { _config = config; - _viewer = new ResourceTreeViewer(_config, treeFactory, 0, delegate { }, delegate { }); + _viewer = new ResourceTreeViewer(_config, treeFactory, changedItemDrawer, 0, delegate { }, delegate { }); } public ReadOnlySpan Label From a17a1e9576dca2c2e5fa4e699759bf73e1995d07 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 2 Sep 2023 17:16:33 +0200 Subject: [PATCH 0074/1381] Resource Tree: Make skp child of sklb --- Penumbra/Interop/ResourceTree/ResolveContext.cs | 11 ++++++++++- Penumbra/Interop/ResourceTree/ResourceTree.cs | 4 ---- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 10 +++++++--- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 72a5be69..8e553091 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -283,12 +283,17 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithUIData); if (node != null) + { + var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); + if (skpNode != null) + node.Children.Add(skpNode); Nodes.Add((nint)sklb->SkeletonResourceHandle, node); + } return node; } - public unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(FFXIVClientStructs.FFXIV.Client.Graphics.Render.PartialSkeleton* sklb) + private unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(FFXIVClientStructs.FFXIV.Client.Graphics.Render.PartialSkeleton* sklb) { if (sklb->SkeletonParameterResourceHandle == null) return null; @@ -298,7 +303,11 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, WithUIData); if (node != null) + { + if (WithUIData) + node = node.WithUIData("Skeleton Parameters", node.Icon); Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); + } return node; } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index c6e90c6b..db3b287f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -134,10 +134,6 @@ public class ResourceTree var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (sklbNode != null) nodes.Add(context.WithUIData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); - - var skpNode = context.CreateParameterNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); - if (skpNode != null) - nodes.Add(context.WithUIData ? skpNode.WithUIData($"{prefix}Skeleton #{i} Parameters", skpNode.Icon) : skpNode); } } } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 528f19c1..f0cf6030 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -8,7 +8,8 @@ using OtterGui.Raii; using OtterGui; using Penumbra.Interop.ResourceTree; using Penumbra.UI.Classes; - +using System.Linq; + namespace Penumbra.UI.AdvancedWindow; public class ResourceTreeViewer @@ -125,7 +126,10 @@ public class ResourceTreeViewer var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) { - if (resourceNode.Children.Count > 0) + var unfoldable = debugMode + ? resourceNode.Children.Count > 0 + : resourceNode.Children.Any(child => !child.Internal); + if (unfoldable) { using var font = ImRaii.PushFont(UiBuilder.IconFont); var icon = (unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(); @@ -142,7 +146,7 @@ public class ResourceTreeViewer _changedItemDrawer.DrawCategoryIcon(resourceNode.Icon); ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); ImGui.TableHeader(resourceNode.Name); - if (ImGui.IsItemClicked() && resourceNode.Children.Count > 0) + if (ImGui.IsItemClicked() && unfoldable) { if (unfolded) _unfolded.Remove(nodePathHash); From cca626449d134ab1b459d7b2000cb88e3ac0843d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 3 Sep 2023 05:50:51 +0200 Subject: [PATCH 0075/1381] Resource Tree: Fix shared model fold state --- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index f0cf6030..90fcd820 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -85,7 +85,7 @@ public class ResourceTreeViewer (_actionCapacity - 1) * 3 * ImGuiHelpers.GlobalScale + _actionCapacity * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); - DrawNodes(tree.Nodes, 0, 0); + DrawNodes(tree.Nodes, 0, unchecked(tree.DrawObjectAddress * 31)); } } } From 2a2fa3bf1d00ed84086040b7e05a72ead2ae5318 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 3 Sep 2023 13:13:35 +0200 Subject: [PATCH 0076/1381] Some auto-formatting and ROS iteration for lookups. --- OtterGui | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 118 +++++++++--------- Penumbra/Interop/ResourceTree/ResourceTree.cs | 14 +-- Penumbra/Interop/Structs/Material.cs | 4 + 4 files changed, 71 insertions(+), 67 deletions(-) diff --git a/OtterGui b/OtterGui index 728dd8c3..8c7a309d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 728dd8c33f8b43f7a2725ac7c8886fe7cb3f04a9 +Subproject commit 8c7a309d039fdf008c85cf51923b4eac51b32428 diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 8e553091..24eea690 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using OtterGui; using Penumbra.Collections; using Penumbra.GameData; using Penumbra.GameData.Enums; @@ -15,19 +16,20 @@ using Penumbra.UI; namespace Penumbra.Interop.ResourceTree; -internal record class GlobalResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithUIData, - bool RedactExternalPaths) +internal record GlobalResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, + ModCollection Collection, int Skeleton, bool WithUiData, bool RedactExternalPaths) { public readonly Dictionary Nodes = new(128); public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) - => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithUIData, RedactExternalPaths, Nodes, slot, equipment); + => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithUiData, RedactExternalPaths, Nodes, slot, equipment); } -internal record class ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, int Skeleton, bool WithUIData, - bool RedactExternalPaths, Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) +internal record ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, + int Skeleton, bool WithUiData, bool RedactExternalPaths, Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); + private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath, bool @internal) { if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) @@ -73,26 +75,28 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide return CreateNodeFromGamePath(ResourceType.Tex, (nint)resourceHandle->KernelTexture, &resourceHandle->Handle, path, @internal); } - private unsafe ResourceNode CreateNodeFromGamePath(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, Utf8GamePath gamePath, bool @internal) + private unsafe ResourceNode CreateNodeFromGamePath(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, + Utf8GamePath gamePath, bool @internal) { - var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(resourceHandle), out var p) ? new FullPath(p) : FullPath.Empty; + var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(resourceHandle), out var p) ? new FullPath(p) : FullPath.Empty; if (fullPath.InternalName.IsEmpty) fullPath = Collection.ResolvePath(gamePath) ?? new FullPath(gamePath); - var node = new ResourceNode(default, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), GetResourceHandleLength(resourceHandle), @internal); + var node = new ResourceNode(default, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), + GetResourceHandleLength(resourceHandle), @internal); if (resourceHandle != null) Nodes.Add((nint)resourceHandle, node); return node; } - private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal, - bool withName) + private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal, + bool withName) { - var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(handle), out var p) ? new FullPath(p) : FullPath.Empty; - if (fullPath.InternalName.IsEmpty) - return null; - + var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(handle), out var p) ? new FullPath(p) : FullPath.Empty; + if (fullPath.InternalName.IsEmpty) + return null; + var gamePaths = Collection.ReverseResolvePath(fullPath).ToList(); fullPath = FilterFullPath(fullPath); @@ -100,14 +104,16 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide gamePaths = Filter(gamePaths); if (gamePaths.Count == 1) - return new ResourceNode(withName ? GuessUIDataFromPath(gamePaths[0]) : default, type, objectAddress, (nint)handle, gamePaths[0], fullPath, + return new ResourceNode(withName ? GuessUIDataFromPath(gamePaths[0]) : default, type, objectAddress, (nint)handle, gamePaths[0], + fullPath, GetResourceHandleLength(handle), @internal); Penumbra.Log.Information($"Found {gamePaths.Count} game paths while reverse-resolving {fullPath} in {Collection.Name}:"); foreach (var gamePath in gamePaths) Penumbra.Log.Information($"Game path: {gamePath}"); - return new ResourceNode(default, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), @internal); + return new ResourceNode(default, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), + @internal); } public unsafe ResourceNode? CreateHumanSkeletonNode(GenderRace gr) @@ -130,7 +136,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (node == null) return null; - if (WithUIData) + if (WithUiData) { var uiData = GuessModelUIData(node.GamePath); node = node.WithUIData(uiData.PrependName("IMC: ")); @@ -146,7 +152,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)tex, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithUIData); + var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithUiData); if (node != null) Nodes.Add((nint)tex, node); @@ -161,11 +167,11 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)mdl->ResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint) mdl, mdl->ResourceHandle, false, false); + var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint)mdl, mdl->ResourceHandle, false, false); if (node == null) return null; - if (WithUIData) + if (WithUiData) node = node.WithUIData(GuessModelUIData(node.GamePath)); for (var i = 0; i < mdl->MaterialCount; i++) @@ -174,7 +180,7 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide var mtrlNode = CreateNodeFromMaterial(mtrl); if (mtrlNode != null) // Don't keep the material's name if it's redundant with the model's name. - node.Children.Add(WithUIData + node.Children.Add(WithUiData ? mtrlNode.WithUIData((string.Equals(mtrlNode.Name, node.Name, StringComparison.Ordinal) ? null : mtrlNode.Name) ?? $"Material #{i}", mtrlNode.Icon) : mtrlNode); @@ -191,33 +197,21 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide { if ((texFlags & 0x001F) != 0x001F) return (ushort)(texFlags & 0x001F); - else if ((texFlags & 0x03E0) != 0x03E0) + if ((texFlags & 0x03E0) != 0x03E0) return (ushort)((texFlags >> 5) & 0x001F); - else - return (ushort)((texFlags >> 10) & 0x001F); + + return (ushort)((texFlags >> 10) & 0x001F); } + static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle) - { - var textures = mtrl->Textures; - for (var i = 0; i < mtrl->TextureCount; ++i) - { - if (textures[i].ResourceHandle == handle) - return textures[i].Id; - } + => mtrl->TextureSpan.FindFirst(p => p.ResourceHandle == handle, out var p) + ? p.Id + : null; - return null; - } static uint? GetSamplerCrcById(ShaderPackage* shpk, uint id) - { - var samplers = (ShaderPackageUtility.Sampler*)shpk->Samplers; - for (var i = 0; i < shpk->SamplerCount; ++i) - { - if (samplers[i].Id == id) - return samplers[i].Crc; - } - - return null; - } + => new ReadOnlySpan(shpk->Samplers, shpk->SamplerCount).FindFirst(s => s.Id == id, out var s) + ? s.Crc + : null; if (mtrl == null) return null; @@ -225,29 +219,30 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide var resource = mtrl->ResourceHandle; if (Nodes.TryGetValue((nint)resource, out var cached)) return cached; - - var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint) mtrl, &resource->Handle, false, WithUIData); + + var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint)mtrl, &resource->Handle, false, WithUiData); if (node == null) return null; var shpkNode = CreateNodeFromShpk(resource->ShpkResourceHandle, new ByteString(resource->ShpkString), false); if (shpkNode != null) - node.Children.Add(WithUIData ? shpkNode.WithUIData("Shader Package", 0) : shpkNode); - var shpkFile = WithUIData && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; - var shpk = WithUIData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; + node.Children.Add(WithUiData ? shpkNode.WithUIData("Shader Package", 0) : shpkNode); + var shpkFile = WithUiData && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; + var shpk = WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; for (var i = 0; i < resource->NumTex; i++) { - var texNode = CreateNodeFromTex(resource->TexSpace[i].ResourceHandle, new ByteString(resource->TexString(i)), false, resource->TexIsDX11(i)); + var texNode = CreateNodeFromTex(resource->TexSpace[i].ResourceHandle, new ByteString(resource->TexString(i)), false, + resource->TexIsDX11(i)); if (texNode == null) continue; - if (WithUIData) + if (WithUiData) { string? name = null; if (shpk != null) { - var index = GetTextureIndex(resource->TexSpace[i].Flags); + var index = GetTextureIndex(resource->TexSpace[i].Flags); uint? samplerId; if (index != 0x001F) samplerId = mtrl->Textures[index].Id; @@ -259,7 +254,8 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (samplerCrc.HasValue) name = shpkFile?.GetSamplerById(samplerCrc.Value)?.Name ?? $"Texture 0x{samplerCrc.Value:X8}"; } - } + } + node.Children.Add(texNode.WithUIData(name ?? $"Texture #{i}", 0)); } else @@ -281,7 +277,8 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, WithUIData); + var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, + WithUiData); if (node != null) { var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); @@ -301,10 +298,11 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, WithUIData); + var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, + WithUiData); if (node != null) { - if (WithUIData) + if (WithUiData) node = node.WithUIData("Skeleton Parameters", node.Icon); Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); } @@ -376,14 +374,16 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide _ => string.Empty, } + item.Name.ToString(); - return new(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); + return new ResourceNode.UIData(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); } var dataFromPath = GuessUIDataFromPath(gamePath); if (dataFromPath.Name != null) return dataFromPath; - return isEquipment ? new(Slot.ToName(), ChangedItemDrawer.GetCategoryIcon(Slot.ToSlot())) : new(null, ChangedItemDrawer.ChangedItemIcon.Unknown); + return isEquipment + ? new ResourceNode.UIData(Slot.ToName(), ChangedItemDrawer.GetCategoryIcon(Slot.ToSlot())) + : new ResourceNode.UIData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); } private ResourceNode.UIData GuessUIDataFromPath(Utf8GamePath gamePath) @@ -394,10 +394,10 @@ internal record class ResolveContext(Configuration Config, IObjectIdentifier Ide if (name.StartsWith("Customization:")) name = name[14..].Trim(); if (name != "Unknown") - return new(name, ChangedItemDrawer.GetCategoryIcon(obj.Key, obj.Value)); + return new ResourceNode.UIData(name, ChangedItemDrawer.GetCategoryIcon(obj.Key, obj.Value)); } - return new(null, ChangedItemDrawer.ChangedItemIcon.Unknown); + return new ResourceNode.UIData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); } private static string? SafeGet(ReadOnlySpan array, Index index) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index db3b287f..755103d7 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -56,12 +56,12 @@ public class ResourceTree var imc = (ResourceHandle*)model->IMCArray[i]; var imcNode = context.CreateNodeFromImc(imc); if (imcNode != null) - Nodes.Add(globalContext.WithUIData ? imcNode.WithUIData(imcNode.Name ?? $"IMC #{i}", imcNode.Icon) : imcNode); + Nodes.Add(globalContext.WithUiData ? imcNode.WithUIData(imcNode.Name ?? $"IMC #{i}", imcNode.Icon) : imcNode); var mdl = (RenderModel*)model->Models[i]; var mdlNode = context.CreateNodeFromRenderModel(mdl); if (mdlNode != null) - Nodes.Add(globalContext.WithUIData ? mdlNode.WithUIData(mdlNode.Name ?? $"Model #{i}", mdlNode.Icon) : mdlNode); + Nodes.Add(globalContext.WithUiData ? mdlNode.WithUIData(mdlNode.Name ?? $"Model #{i}", mdlNode.Icon) : mdlNode); } AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); @@ -92,14 +92,14 @@ public class ResourceTree var imc = (ResourceHandle*)subObject->IMCArray[i]; var imcNode = subObjectContext.CreateNodeFromImc(imc); if (imcNode != null) - subObjectNodes.Add(globalContext.WithUIData + subObjectNodes.Add(globalContext.WithUiData ? imcNode.WithUIData(imcNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}", imcNode.Icon) : imcNode); var mdl = (RenderModel*)subObject->Models[i]; var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); if (mdlNode != null) - subObjectNodes.Add(globalContext.WithUIData + subObjectNodes.Add(globalContext.WithUiData ? mdlNode.WithUIData(mdlNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}", mdlNode.Icon) : mdlNode); } @@ -117,11 +117,11 @@ public class ResourceTree var decalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->Decal); if (decalNode != null) - Nodes.Add(globalContext.WithUIData ? decalNode.WithUIData(decalNode.Name ?? "Face Decal", decalNode.Icon) : decalNode); + Nodes.Add(globalContext.WithUiData ? decalNode.WithUIData(decalNode.Name ?? "Face Decal", decalNode.Icon) : decalNode); var legacyDecalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->LegacyBodyDecal); if (legacyDecalNode != null) - Nodes.Add(globalContext.WithUIData ? legacyDecalNode.WithUIData(legacyDecalNode.Name ?? "Legacy Body Decal", legacyDecalNode.Icon) : legacyDecalNode); + Nodes.Add(globalContext.WithUiData ? legacyDecalNode.WithUIData(legacyDecalNode.Name ?? "Legacy Body Decal", legacyDecalNode.Icon) : legacyDecalNode); } private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") @@ -133,7 +133,7 @@ public class ResourceTree { var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (sklbNode != null) - nodes.Add(context.WithUIData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); + nodes.Add(context.WithUiData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); } } } diff --git a/Penumbra/Interop/Structs/Material.cs b/Penumbra/Interop/Structs/Material.cs index 7b66531c..3a204c75 100644 --- a/Penumbra/Interop/Structs/Material.cs +++ b/Penumbra/Interop/Structs/Material.cs @@ -1,3 +1,4 @@ +using System; using System.Runtime.InteropServices; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; @@ -41,4 +42,7 @@ public unsafe struct Material [FieldOffset( 0x10 )] public uint SamplerFlags; } + + public ReadOnlySpan TextureSpan + => new(Textures, TextureCount); } \ No newline at end of file From 94a0a3902c8c6b7e71b57b80355fb52a7e3c8f4c Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 3 Sep 2023 21:56:22 +0200 Subject: [PATCH 0077/1381] Resource Tree: Use `/`s for game actual paths --- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 90fcd820..7da0275b 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -182,9 +182,9 @@ public class ResourceTreeViewer ImGui.TableNextColumn(); if (resourceNode.FullPath.FullName.Length > 0) { - ImGui.Selectable(resourceNode.FullPath.ToString(), false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + ImGui.Selectable(resourceNode.FullPath.ToPath(), false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); if (ImGui.IsItemClicked()) - ImGui.SetClipboardText(resourceNode.FullPath.ToString()); + ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); ImGuiUtil.HoverTooltip($"{resourceNode.FullPath}\n\nClick to copy to clipboard."); } else From 32608ea45b1c51b8ebaf08d21fbbe2831a183022 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 5 Sep 2023 12:53:53 +0200 Subject: [PATCH 0078/1381] Skin Fixer: Switch to a passive approach. Do not load skin.shpk for ourselves as it causes a race condition. Instead, inspect the materials' ShPk names. --- .../Communication/CreatedCharacterBase.cs | 3 - Penumbra/Communication/MtrlShpkLoaded.cs | 24 +++ .../Interop/PathResolving/SubfileHelper.cs | 25 ++-- Penumbra/Interop/Services/SkinFixer.cs | 137 +++++++----------- Penumbra/Services/CommunicatorService.cs | 4 + Penumbra/UI/Tabs/DebugTab.cs | 2 +- Penumbra/Util/Unit.cs | 26 ++++ 7 files changed, 126 insertions(+), 95 deletions(-) create mode 100644 Penumbra/Communication/MtrlShpkLoaded.cs create mode 100644 Penumbra/Util/Unit.cs diff --git a/Penumbra/Communication/CreatedCharacterBase.cs b/Penumbra/Communication/CreatedCharacterBase.cs index 48ba86a5..69d84ce2 100644 --- a/Penumbra/Communication/CreatedCharacterBase.cs +++ b/Penumbra/Communication/CreatedCharacterBase.cs @@ -16,9 +16,6 @@ public sealed class CreatedCharacterBase : EventWrapper Api = int.MinValue, - - /// - SkinFixer = 0, } public CreatedCharacterBase() diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlShpkLoaded.cs new file mode 100644 index 00000000..4b5600c9 --- /dev/null +++ b/Penumbra/Communication/MtrlShpkLoaded.cs @@ -0,0 +1,24 @@ +using System; +using OtterGui.Classes; + +namespace Penumbra.Communication; + +/// +/// Parameter is the material resource handle for which the shader package has been loaded. +/// Parameter is the associated game object. +/// +public sealed class MtrlShpkLoaded : EventWrapper, MtrlShpkLoaded.Priority> +{ + public enum Priority + { + /// + SkinFixer = 0, + } + + public MtrlShpkLoaded() + : base(nameof(MtrlShpkLoaded)) + { } + + public void Invoke(nint mtrlResourceHandle, nint gameObject) + => Invoke(this, mtrlResourceHandle, gameObject); +} diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 05f42220..ffa3ac24 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -11,6 +11,7 @@ using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; +using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.Util; @@ -24,22 +25,24 @@ namespace Penumbra.Interop.PathResolving; /// public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection> { - private readonly PerformanceTracker _performance; - private readonly ResourceLoader _loader; - private readonly GameEventManager _events; + private readonly PerformanceTracker _performance; + private readonly ResourceLoader _loader; + private readonly GameEventManager _events; + private readonly CommunicatorService _communicator; private readonly ThreadLocal _mtrlData = new(() => ResolveData.Invalid); private readonly ThreadLocal _avfxData = new(() => ResolveData.Invalid); private readonly ConcurrentDictionary _subFileCollection = new(); - public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, GameEventManager events) + public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, GameEventManager events, CommunicatorService communicator) { SignatureHelper.Initialise(this); - _performance = performance; - _loader = loader; - _events = events; + _performance = performance; + _loader = loader; + _events = events; + _communicator = communicator; _loadMtrlShpkHook.Enable(); _loadMtrlTexHook.Enable(); @@ -150,10 +153,12 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection SkinShpkName + => "skin.shpk"u8; [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] private readonly nint* _humanVTable = null!; @@ -48,11 +40,12 @@ public sealed unsafe class SkinFixer : IDisposable private readonly ResourceLoader _resources; private readonly CharacterUtility _utility; - // CharacterBase to ShpkHandle - private readonly ConcurrentDictionary _skinShpks = new(); + // MaterialResourceHandle set + private readonly ConcurrentDictionary _moddedSkinShpkMaterials = new(); private readonly object _lock = new(); - + + // ConcurrentDictionary.Count uses a lock in its current implementation. private int _moddedSkinShpkCount = 0; private ulong _slowPathCallDelta = 0; @@ -68,83 +61,65 @@ public sealed unsafe class SkinFixer : IDisposable _resources = resources; _utility = utility; _communicator = communicator; - _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); - _communicator.CreatedCharacterBase.Subscribe(OnCharacterBaseCreated, CreatedCharacterBase.Priority.SkinFixer); - _gameEvents.CharacterBaseDestructor += OnCharacterBaseDestructor; + _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); + _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.SkinFixer); + _gameEvents.ResourceHandleDestructor += OnResourceHandleDestructor; _onRenderMaterialHook.Enable(); - } - + } + public void Dispose() { - _onRenderMaterialHook.Dispose(); - _communicator.CreatedCharacterBase.Unsubscribe(OnCharacterBaseCreated); - _gameEvents.CharacterBaseDestructor -= OnCharacterBaseDestructor; - foreach (var skinShpk in _skinShpks.Values) - skinShpk.Dispose(); - _skinShpks.Clear(); + _onRenderMaterialHook.Dispose(); + _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); + _gameEvents.ResourceHandleDestructor -= OnResourceHandleDestructor; + _moddedSkinShpkMaterials.Clear(); _moddedSkinShpkCount = 0; - } - + } + public ulong GetAndResetSlowPathCallDelta() - => Interlocked.Exchange(ref _slowPathCallDelta, 0); - - private void OnCharacterBaseCreated(nint gameObject, ModCollection collection, nint drawObject) - { - if (((CharacterBase*)drawObject)->GetModelType() != CharacterBase.ModelType.Human) - return; - - Task.Run(() => - { - var skinShpk = SafeResourceHandle.CreateInvalid(); - try - { - var data = collection.ToResolveData(gameObject); - if (data.Valid) - { - var loadedShpk = _resources.LoadResolvedResource(ResourceCategory.Shader, ResourceType.Shpk, SkinShpkPath.Path, data); - skinShpk = new SafeResourceHandle((ResourceHandle*)loadedShpk, false); - } - } - catch (Exception e) - { - Penumbra.Log.Error($"Error while resolving skin.shpk for human {drawObject:X}: {e}"); - } - - if (!skinShpk.IsInvalid) - { - if (_skinShpks.TryAdd(drawObject, skinShpk)) - { - if ((nint)skinShpk.ResourceHandle != _utility.DefaultSkinShpkResource) - Interlocked.Increment(ref _moddedSkinShpkCount); - } - else - { - skinShpk.Dispose(); - } - } - }); - } - - private void OnCharacterBaseDestructor(nint characterBase) - { - if (!_skinShpks.Remove(characterBase, out var skinShpk)) - return; - - var handle = skinShpk.ResourceHandle; - skinShpk.Dispose(); - if ((nint)handle != _utility.DefaultSkinShpkResource) - Interlocked.Decrement(ref _moddedSkinShpkCount); + => Interlocked.Exchange(ref _slowPathCallDelta, 0); + + private static bool IsSkinMaterial(Structs.MtrlResource* mtrlResource) + { + if (mtrlResource == null) + return false; + + var shpkName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlResource->ShpkString); + return SkinShpkName.SequenceEqual(shpkName); + } + + private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) + { + var mtrl = (Structs.MtrlResource*)mtrlResourceHandle; + var shpk = mtrl->ShpkResourceHandle; + if (shpk == null) + return; + + if (!IsSkinMaterial(mtrl)) + return; + + if ((nint)shpk != _utility.DefaultSkinShpkResource) + { + if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle, Unit.Instance)) + Interlocked.Increment(ref _moddedSkinShpkCount); + } + } + + private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) + { + if (_moddedSkinShpkMaterials.TryRemove((nint)handle, out _)) + Interlocked.Decrement(ref _moddedSkinShpkCount); } private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) { // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. - if (!Enabled || _moddedSkinShpkCount == 0 || !_skinShpks.TryGetValue(human, out var skinShpk) || skinShpk.IsInvalid) + if (!Enabled || _moddedSkinShpkCount == 0) return _onRenderMaterialHook!.Original(human, param); - var material = param->Model->Materials[param->MaterialIndex]; - var shpkResource = ((Structs.MtrlResource*)material->MaterialResourceHandle)->ShpkResourceHandle; - if ((nint)shpkResource != (nint)skinShpk.ResourceHandle) + var material = param->Model->Materials[param->MaterialIndex]; + var mtrlResource = (Structs.MtrlResource*)material->MaterialResourceHandle; + if (!IsSkinMaterial(mtrlResource)) return _onRenderMaterialHook!.Original(human, param); Interlocked.Increment(ref _slowPathCallDelta); @@ -158,7 +133,7 @@ public sealed unsafe class SkinFixer : IDisposable { try { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)skinShpk.ResourceHandle; + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShpkResourceHandle; return _onRenderMaterialHook!.Original(human, param); } finally diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index 728b391c..97340f6b 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -24,6 +24,9 @@ public class CommunicatorService : IDisposable /// public readonly CreatedCharacterBase CreatedCharacterBase = new(); + /// + public readonly MtrlShpkLoaded MtrlShpkLoaded = new(); + /// public readonly ModDataChanged ModDataChanged = new(); @@ -75,6 +78,7 @@ public class CommunicatorService : IDisposable TemporaryGlobalModChange.Dispose(); CreatingCharacterBase.Dispose(); CreatedCharacterBase.Dispose(); + MtrlShpkLoaded.Dispose(); ModDataChanged.Dispose(); ModOptionChanged.Dispose(); ModDiscoveryStarted.Dispose(); diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index c24d64fa..d02da883 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -603,7 +603,7 @@ public class DebugTab : Window, ITab ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); - ImGui.TextUnformatted($"Draw Objects with Modded skin.shpk: {_skinFixer.ModdedSkinShpkCount}"); + ImGui.TextUnformatted($"Materials with Modded skin.shpk: {_skinFixer.ModdedSkinShpkCount}"); } using var table = Table("##CharacterUtility", 7, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, diff --git a/Penumbra/Util/Unit.cs b/Penumbra/Util/Unit.cs new file mode 100644 index 00000000..9b8f4b1e --- /dev/null +++ b/Penumbra/Util/Unit.cs @@ -0,0 +1,26 @@ +using System; + +namespace Penumbra.Util; + +/// +/// An empty structure. Can be used as value of a concurrent dictionary, to use it as a set. +/// +public readonly struct Unit : IEquatable +{ + public static readonly Unit Instance = new(); + + public bool Equals(Unit other) + => true; + + public override bool Equals(object? obj) + => obj is Unit; + + public override int GetHashCode() + => 0; + + public static bool operator ==(Unit left, Unit right) + => true; + + public static bool operator !=(Unit left, Unit right) + => false; +} From 0e0733dab02b86db7e68cdec0612098fc3982df3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 5 Sep 2023 14:48:06 +0200 Subject: [PATCH 0079/1381] Some formatting, use ConcurrentSet explicitly for clarity. --- OtterGui | 2 +- .../Interop/PathResolving/SubfileHelper.cs | 14 +-- Penumbra/Interop/Services/SkinFixer.cs | 113 ++++++++---------- Penumbra/Util/Unit.cs | 26 ---- 4 files changed, 61 insertions(+), 94 deletions(-) delete mode 100644 Penumbra/Util/Unit.cs diff --git a/OtterGui b/OtterGui index 8c7a309d..86ec4d72 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 8c7a309d039fdf008c85cf51923b4eac51b32428 +Subproject commit 86ec4d72c9c9ed57aa7be4a7d0c81069c5b94ad7 diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index ffa3ac24..c0b8c5e3 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -11,7 +11,7 @@ using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; -using Penumbra.Services; +using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.Util; @@ -27,7 +27,7 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection _mtrlData = new(() => ResolveData.Invalid); @@ -41,7 +41,7 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollectionFileType) { case ResourceType.Mtrl: - case ResourceType.Avfx: + case ResourceType.Avfx: if (handle->FileSize == 0) _subFileCollection[(nint)handle] = resolveData; @@ -153,11 +153,11 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection SkinShpkName + public static ReadOnlySpan SkinShpkName => "skin.shpk"u8; [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] @@ -37,90 +35,85 @@ public sealed unsafe class SkinFixer : IDisposable private readonly GameEventManager _gameEvents; private readonly CommunicatorService _communicator; - private readonly ResourceLoader _resources; private readonly CharacterUtility _utility; - - // MaterialResourceHandle set - private readonly ConcurrentDictionary _moddedSkinShpkMaterials = new(); + + // MaterialResourceHandle set + private readonly ConcurrentSet _moddedSkinShpkMaterials = new(); private readonly object _lock = new(); - + // ConcurrentDictionary.Count uses a lock in its current implementation. - private int _moddedSkinShpkCount = 0; - private ulong _slowPathCallDelta = 0; + private int _moddedSkinShpkCount; + private ulong _slowPathCallDelta; public bool Enabled { get; internal set; } = true; public int ModdedSkinShpkCount => _moddedSkinShpkCount; - public SkinFixer(GameEventManager gameEvents, ResourceLoader resources, CharacterUtility utility, CommunicatorService communicator) + public SkinFixer(GameEventManager gameEvents, CharacterUtility utility, CommunicatorService communicator) { SignatureHelper.Initialise(this); _gameEvents = gameEvents; - _resources = resources; _utility = utility; - _communicator = communicator; - _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); + _communicator = communicator; + _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.SkinFixer); _gameEvents.ResourceHandleDestructor += OnResourceHandleDestructor; _onRenderMaterialHook.Enable(); - } - + } + public void Dispose() { - _onRenderMaterialHook.Dispose(); - _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); + _onRenderMaterialHook.Dispose(); + _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); _gameEvents.ResourceHandleDestructor -= OnResourceHandleDestructor; _moddedSkinShpkMaterials.Clear(); _moddedSkinShpkCount = 0; - } - + } + public ulong GetAndResetSlowPathCallDelta() - => Interlocked.Exchange(ref _slowPathCallDelta, 0); - - private static bool IsSkinMaterial(Structs.MtrlResource* mtrlResource) - { - if (mtrlResource == null) - return false; - - var shpkName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlResource->ShpkString); - return SkinShpkName.SequenceEqual(shpkName); - } - - private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) - { - var mtrl = (Structs.MtrlResource*)mtrlResourceHandle; - var shpk = mtrl->ShpkResourceHandle; - if (shpk == null) - return; - - if (!IsSkinMaterial(mtrl)) - return; - - if ((nint)shpk != _utility.DefaultSkinShpkResource) - { - if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle, Unit.Instance)) - Interlocked.Increment(ref _moddedSkinShpkCount); - } - } - - private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) - { - if (_moddedSkinShpkMaterials.TryRemove((nint)handle, out _)) - Interlocked.Decrement(ref _moddedSkinShpkCount); + => Interlocked.Exchange(ref _slowPathCallDelta, 0); + + private static bool IsSkinMaterial(Structs.MtrlResource* mtrlResource) + { + if (mtrlResource == null) + return false; + + var shpkName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlResource->ShpkString); + return SkinShpkName.SequenceEqual(shpkName); + } + + private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) + { + var mtrl = (Structs.MtrlResource*)mtrlResourceHandle; + var shpk = mtrl->ShpkResourceHandle; + if (shpk == null) + return; + + if (!IsSkinMaterial(mtrl) || (nint)shpk == _utility.DefaultSkinShpkResource) + return; + + if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle)) + Interlocked.Increment(ref _moddedSkinShpkCount); + } + + private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) + { + if (_moddedSkinShpkMaterials.TryRemove((nint)handle)) + Interlocked.Decrement(ref _moddedSkinShpkCount); } private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) { // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. if (!Enabled || _moddedSkinShpkCount == 0) - return _onRenderMaterialHook!.Original(human, param); + return _onRenderMaterialHook.Original(human, param); - var material = param->Model->Materials[param->MaterialIndex]; - var mtrlResource = (Structs.MtrlResource*)material->MaterialResourceHandle; - if (!IsSkinMaterial(mtrlResource)) - return _onRenderMaterialHook!.Original(human, param); + var material = param->Model->Materials[param->MaterialIndex]; + var mtrlResource = (Structs.MtrlResource*)material->MaterialResourceHandle; + if (!IsSkinMaterial(mtrlResource)) + return _onRenderMaterialHook.Original(human, param); Interlocked.Increment(ref _slowPathCallDelta); @@ -134,7 +127,7 @@ public sealed unsafe class SkinFixer : IDisposable try { _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShpkResourceHandle; - return _onRenderMaterialHook!.Original(human, param); + return _onRenderMaterialHook.Original(human, param); } finally { diff --git a/Penumbra/Util/Unit.cs b/Penumbra/Util/Unit.cs deleted file mode 100644 index 9b8f4b1e..00000000 --- a/Penumbra/Util/Unit.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace Penumbra.Util; - -/// -/// An empty structure. Can be used as value of a concurrent dictionary, to use it as a set. -/// -public readonly struct Unit : IEquatable -{ - public static readonly Unit Instance = new(); - - public bool Equals(Unit other) - => true; - - public override bool Equals(object? obj) - => obj is Unit; - - public override int GetHashCode() - => 0; - - public static bool operator ==(Unit left, Unit right) - => true; - - public static bool operator !=(Unit left, Unit right) - => false; -} From a890258cf5568f013fac1795dfa3af80a6efe0cc Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 5 Sep 2023 12:51:00 +0000 Subject: [PATCH 0080/1381] [CI] Updating repo.json for testing_0.7.3.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 84db423d..dd0b0d67 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.4", + "TestingAssemblyVersion": "0.7.3.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 6cc89f3e7c33143f950a877d8ac38e41a9ec47e2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 6 Sep 2023 21:15:05 +0200 Subject: [PATCH 0081/1381] Add Emotes to Changed Items. --- Penumbra.GameData | 2 +- Penumbra/UI/ChangedItemDrawer.cs | 78 ++++++++++++++++++++++---------- Penumbra/UI/Tabs/DebugTab.cs | 72 ++++++++++++++++++++++++----- 3 files changed, 115 insertions(+), 37 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 43f6737d..bd7e7926 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 43f6737d4baa7988a5fe23096f20827bc54e6812 +Subproject commit bd7e79262a0db06e27e61b98ab0a31ebb881be2a diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index da4faa43..529a6246 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -27,22 +27,23 @@ public class ChangedItemDrawer : IDisposable [Flags] public enum ChangedItemIcon : uint { - Head = 0x0001, - Body = 0x0002, - Hands = 0x0004, - Legs = 0x0008, - Feet = 0x0010, - Ears = 0x0020, - Neck = 0x0040, - Wrists = 0x0080, - Finger = 0x0100, - Monster = 0x0200, - Demihuman = 0x0400, - Customization = 0x0800, - Action = 0x1000, - Mainhand = 0x2000, - Offhand = 0x4000, - Unknown = 0x8000, + Head = 0x00_00_01, + Body = 0x00_00_02, + Hands = 0x00_00_04, + Legs = 0x00_00_08, + Feet = 0x00_00_10, + Ears = 0x00_00_20, + Neck = 0x00_00_40, + Wrists = 0x00_00_80, + Finger = 0x00_01_00, + Monster = 0x00_02_00, + Demihuman = 0x00_04_00, + Customization = 0x00_08_00, + Action = 0x00_10_00, + Mainhand = 0x00_20_00, + Offhand = 0x00_40_00, + Unknown = 0x00_80_00, + Emote = 0x01_00_00, } public const ChangedItemIcon AllFlags = (ChangedItemIcon)0xFFFF; @@ -51,10 +52,11 @@ public class ChangedItemDrawer : IDisposable private readonly Configuration _config; private readonly ExcelSheet _items; private readonly CommunicatorService _communicator; - private readonly Dictionary _icons = new(16); + private readonly Dictionary _icons = new(16); private float _smallestIconWidth; - public ChangedItemDrawer(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, Configuration config) + public ChangedItemDrawer(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, + Configuration config) { _items = gameData.GetExcelSheet()!; uiBuilder.RunWhenUiPrepared(() => CreateEquipSlotIcons(uiBuilder, gameData, textureProvider), true); @@ -164,6 +166,7 @@ public class ChangedItemDrawer : IDisposable ChangedItemIcon.Offhand, ChangedItemIcon.Customization, ChangedItemIcon.Action, + ChangedItemIcon.Emote, ChangedItemIcon.Monster, ChangedItemIcon.Demihuman, ChangedItemIcon.Unknown, @@ -182,14 +185,12 @@ public class ChangedItemDrawer : IDisposable using var popup = ImRaii.ContextPopupItem(type.ToString()); if (popup) - { if (ImGui.MenuItem("Enable Only This")) { _config.ChangedItemFilter = type; _config.Save(); ImGui.CloseCurrentPopup(); } - } if (ImGui.IsItemHovered()) { @@ -238,6 +239,8 @@ public class ChangedItemDrawer : IDisposable { if (name.StartsWith("Action: ")) iconType = ChangedItemIcon.Action; + else if (name.StartsWith("Emote: ")) + iconType = ChangedItemIcon.Emote; else if (name.StartsWith("Customization: ")) iconType = ChangedItemIcon.Customization; break; @@ -306,6 +309,7 @@ public class ChangedItemDrawer : IDisposable ChangedItemIcon.Demihuman => "Demi-Human", ChangedItemIcon.Customization => "Customization", ChangedItemIcon.Action => "Action", + ChangedItemIcon.Emote => "Emote", ChangedItemIcon.Mainhand => "Weapon (Mainhand)", ChangedItemIcon.Offhand => "Weapon (Offhand)", _ => "Other", @@ -354,21 +358,47 @@ public class ChangedItemDrawer : IDisposable Add(ChangedItemIcon.Demihuman, textureProvider.GetTextureFromGame("ui/icon/062000/062041_hr1.tex", true)); Add(ChangedItemIcon.Customization, textureProvider.GetTextureFromGame("ui/icon/062000/062043_hr1.tex", true)); Add(ChangedItemIcon.Action, textureProvider.GetTextureFromGame("ui/icon/062000/062001_hr1.tex", true)); + Add(ChangedItemIcon.Emote, LoadEmoteTexture(gameData, uiBuilder)); + Add(ChangedItemIcon.Unknown, LoadUnknownTexture(gameData, uiBuilder)); Add(AllFlags, textureProvider.GetTextureFromGame("ui/icon/114000/114052_hr1.tex", true)); + _smallestIconWidth = _icons.Values.Min(i => i.Width); + + return true; + } + + private static unsafe TextureWrap? LoadUnknownTexture(IDataManager gameData, UiBuilder uiBuilder) + { var unk = gameData.GetFile("ui/uld/levelup2_hr1.tex"); if (unk == null) - return true; + return null; var image = unk.GetRgbaImageData(); var bytes = new byte[unk.Header.Height * unk.Header.Height * 4]; var diff = 2 * (unk.Header.Height - unk.Header.Width); for (var y = 0; y < unk.Header.Height; ++y) image.AsSpan(4 * y * unk.Header.Width, 4 * unk.Header.Width).CopyTo(bytes.AsSpan(4 * y * unk.Header.Height + diff)); - Add(ChangedItemIcon.Unknown, uiBuilder.LoadImageRaw(bytes, unk.Header.Height, unk.Header.Height, 4)); - _smallestIconWidth = _icons.Values.Min(i => i.Width); + return uiBuilder.LoadImageRaw(bytes, unk.Header.Height, unk.Header.Height, 4); + } - return true; + private static unsafe TextureWrap? LoadEmoteTexture(IDataManager gameData, UiBuilder uiBuilder) + { + var emote = gameData.GetFile("ui/icon/000000/000019_hr1.tex"); + if (emote == null) + return null; + + var image2 = emote.GetRgbaImageData(); + fixed (byte* ptr = image2) + { + var color = (uint*)ptr; + for (var i = 0; i < image2.Length / 4; ++i) + { + if (color[i] == 0xFF000000) + image2[i * 4 + 3] = 0; + } + } + + return uiBuilder.LoadImageRaw(image2, emote.Header.Width, emote.Header.Height, 4); } } diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index d02da883..72122722 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Windowing; +using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Group; using FFXIVClientStructs.FFXIV.Client.Game.Object; @@ -66,6 +67,7 @@ public class DebugTab : Window, ITab private readonly FrameworkManager _framework; private readonly TextureManager _textureManager; private readonly SkinFixer _skinFixer; + private readonly IdentifierService _identifier; public DebugTab(StartTracker timer, PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorService actorService, @@ -73,7 +75,7 @@ public class DebugTab : Window, ITab ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager, SkinFixer skinFixer) + TextureManager textureManager, SkinFixer skinFixer, IdentifierService identifier) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse, false) { IsOpen = true; @@ -107,6 +109,7 @@ public class DebugTab : Window, ITab _framework = framework; _textureManager = textureManager; _skinFixer = skinFixer; + _identifier = identifier; } public ReadOnlySpan Label @@ -138,12 +141,10 @@ public class DebugTab : Window, ITab ImGui.NewLine(); DrawDebugCharacterUtility(); ImGui.NewLine(); - DrawStainTemplates(); + DrawData(); ImGui.NewLine(); DrawDebugTabMetaLists(); ImGui.NewLine(); - DrawDebugResidentResources(); - ImGui.NewLine(); DrawResourceProblems(); ImGui.NewLine(); DrawPlayerModelInfo(); @@ -370,7 +371,9 @@ public class DebugTab : Window, ITab { ImGuiUtil.DrawTableColumn($"{((GameObject*)obj.Address)->ObjectIndex}"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); - ImGuiUtil.DrawTableColumn((obj.Address == nint.Zero) ? string.Empty : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); + ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero + ? string.Empty + : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); var identifier = _actorService.AwaitedService.FromObject(obj, false, true, false); ImGuiUtil.DrawTableColumn(_actorService.AwaitedService.ToString(identifier)); var id = obj.ObjectKind == ObjectKind.BattleNpc ? $"{identifier.DataId} | {obj.DataId}" : identifier.DataId.ToString(); @@ -546,9 +549,49 @@ public class DebugTab : Window, ITab } } + private void DrawData() + { + if (!ImGui.CollapsingHeader("Game Data")) + return; + + DrawEmotes(); + DrawStainTemplates(); + } + + private string _emoteSearchFile = string.Empty; + private string _emoteSearchName = string.Empty; + + private void DrawEmotes() + { + using var mainTree = TreeNode("Emotes"); + if (!mainTree) + return; + + ImGui.InputText("File Name", ref _emoteSearchFile, 256); + ImGui.InputText("Emote Name", ref _emoteSearchName, 256); + using var table = Table("##table", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingFixedFit, new Vector2(-1, 12 * ImGui.GetTextLineHeightWithSpacing())); + if (!table) + return; + + var skips = ImGuiClip.GetNecessarySkips(ImGui.GetTextLineHeightWithSpacing()); + var dummy = ImGuiClip.FilteredClippedDraw(_identifier.AwaitedService.Emotes, skips, + p => p.Key.Contains(_emoteSearchFile, StringComparison.OrdinalIgnoreCase) + && (_emoteSearchName.Length == 0 + || p.Value.Any(s => s.Name.ToDalamudString().TextValue.Contains(_emoteSearchName, StringComparison.OrdinalIgnoreCase))), + p => + { + ImGui.TableNextColumn(); + ImGui.TextUnformatted(p.Key); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(string.Join(", ", p.Value.Select(v => v.Name.ToDalamudString().TextValue))); + }); + ImGuiClip.DrawEndDummy(dummy, ImGui.GetTextLineHeightWithSpacing()); + } + private void DrawStainTemplates() { - if (!ImGui.CollapsingHeader("Staining Templates")) + using var mainTree = TreeNode("Staining Templates"); + if (!mainTree) return; foreach (var (key, data) in _stains.StmFile.Entries) @@ -625,16 +668,15 @@ public class DebugTab : Window, ITab ImGui.TableNextRow(); continue; } + UiHelpers.Text(resource); ImGui.TableNextColumn(); - var data = (nint)ResourceHandle.GetData(resource); + var data = (nint)ResourceHandle.GetData(resource); var length = ResourceHandle.GetLength(resource); if (ImGui.Selectable($"0x{data:X}")) - { if (data != nint.Zero && length > 0) ImGui.SetClipboardText(string.Join("\n", new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); - } ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); ImGui.TableNextColumn(); @@ -655,7 +697,9 @@ public class DebugTab : Window, ITab ImGui.TextUnformatted($"{_characterUtility.DefaultResource(intern).Size}"); } else + { ImGui.TableNextColumn(); + } } } @@ -679,7 +723,8 @@ public class DebugTab : Window, ITab /// Draw information about the resident resource files. private unsafe void DrawDebugResidentResources() { - if (!ImGui.CollapsingHeader("Resident Resources")) + using var tree = TreeNode("Resident Resources"); + if (!tree) return; if (_residentResources.Address == null || _residentResources.Address->NumResources == 0) @@ -703,8 +748,10 @@ public class DebugTab : Window, ITab private static void DrawCopyableAddress(string label, nint address) { using (var _ = PushFont(UiBuilder.MonoFont)) + { if (ImGui.Selectable($"0x{address:X16} {label}")) ImGui.SetClipboardText($"{address:X16}"); + } ImGuiUtil.HoverTooltip("Click to copy address to clipboard."); } @@ -789,9 +836,10 @@ public class DebugTab : Window, ITab if (!header) return; - DrawCopyableAddress("CharacterUtility", _characterUtility.Address); + DrawCopyableAddress("CharacterUtility", _characterUtility.Address); DrawCopyableAddress("ResidentResourceManager", _residentResources.Address); - DrawCopyableAddress("Device", Device.Instance()); + DrawCopyableAddress("Device", Device.Instance()); + DrawDebugResidentResources(); } /// Draw resources with unusual reference count. From 4bd3fd357f1026f3b568f1c62f230af487e33464 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 6 Sep 2023 19:19:57 +0000 Subject: [PATCH 0082/1381] [CI] Updating repo.json for testing_0.7.3.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index dd0b0d67..185481f9 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.5", + "TestingAssemblyVersion": "0.7.3.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From ed243df4f34544f06444288b0d2d0309c5a2b77a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Sep 2023 13:59:36 +0200 Subject: [PATCH 0083/1381] Fix changed item flags for emotes. --- Penumbra/UI/ChangedItemDrawer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 529a6246..902f6671 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -46,7 +46,7 @@ public class ChangedItemDrawer : IDisposable Emote = 0x01_00_00, } - public const ChangedItemIcon AllFlags = (ChangedItemIcon)0xFFFF; + public const ChangedItemIcon AllFlags = (ChangedItemIcon)0x01FFFF; public const ChangedItemIcon DefaultFlags = AllFlags & ~ChangedItemIcon.Offhand; private readonly Configuration _config; From 40eb0c81b8a280287a1e4ab8ca938a65307e004a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Sep 2023 13:59:47 +0200 Subject: [PATCH 0084/1381] Update GameData for new parsing. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index bd7e7926..635d4c72 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit bd7e79262a0db06e27e61b98ab0a31ebb881be2a +Subproject commit 635d4c72e84da65a20a2d22d758dd8061bd8babf From 569fa06e183c299d3bc1c03636f5200a2d24eeee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Sep 2023 14:04:14 +0200 Subject: [PATCH 0085/1381] Fix CS update creating ambiguous reference. --- Penumbra/Interop/PathResolving/MetaState.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index cdf28bbd..f7a754fb 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -13,6 +13,7 @@ using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Util; using ObjectType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType; +using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using static Penumbra.GameData.Enums.GenderRace; namespace Penumbra.Interop.PathResolving; From 8eaf14d93247298b61b38445a9d94afaf472e812 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 11 Sep 2023 16:24:07 +0200 Subject: [PATCH 0086/1381] Add Player and Interface to quick select collections and rework their tooltips and names slightly. --- Penumbra/Api/IpcTester.cs | 1 - Penumbra/UI/Classes/CollectionSelectHeader.cs | 121 +++++++++++++----- 2 files changed, 92 insertions(+), 30 deletions(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index fea91b0e..cbd0cc8b 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -9,7 +9,6 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Numerics; -using System.Reflection.Metadata.Ecma335; using System.Threading.Tasks; using Dalamud.Utility; using Penumbra.Api.Enums; diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index 5c4570bf..f71ae323 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -1,3 +1,4 @@ +using System; using System.Linq; using System.Numerics; using ImGuiNET; @@ -5,6 +6,7 @@ using OtterGui.Raii; using OtterGui; using Penumbra.Collections; using Penumbra.Collections.Manager; +using Penumbra.Interop.PathResolving; using Penumbra.UI.CollectionTab; using Penumbra.UI.ModsTab; @@ -16,11 +18,14 @@ public class CollectionSelectHeader private readonly ActiveCollections _activeCollections; private readonly TutorialService _tutorial; private readonly ModFileSystemSelector _selector; + private readonly CollectionResolver _resolver; - public CollectionSelectHeader(CollectionManager collectionManager, TutorialService tutorial, ModFileSystemSelector selector) + public CollectionSelectHeader(CollectionManager collectionManager, TutorialService tutorial, ModFileSystemSelector selector, + CollectionResolver resolver) { _tutorial = tutorial; _selector = selector; + _resolver = resolver; _activeCollections = collectionManager.Active; _collectionCombo = new CollectionCombo(collectionManager, () => collectionManager.Storage.OrderBy(c => c.Name).ToList()); } @@ -28,16 +33,18 @@ public class CollectionSelectHeader /// Draw the header line that can quick switch between collections. public void Draw(bool spacing) { - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0).Push(ImGuiStyleVar.ItemSpacing, new Vector2(0, spacing ? ImGui.GetStyle().ItemSpacing.Y : 0)); - var buttonSize = new Vector2(ImGui.GetContentRegionAvail().X / 8f, 0); - + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0) + .Push(ImGuiStyleVar.ItemSpacing, new Vector2(0, spacing ? ImGui.GetStyle().ItemSpacing.Y : 0)); + var comboWidth = ImGui.GetContentRegionAvail().X / 4f; + var buttonSize = new Vector2(comboWidth * 3f / 4f, 0f); using (var _ = ImRaii.Group()) { - DrawDefaultCollectionButton(3 * buttonSize); - ImGui.SameLine(); - DrawInheritedCollectionButton(3 * buttonSize); - ImGui.SameLine(); - _collectionCombo.Draw("##collectionSelector", 2 * buttonSize.X, ColorId.SelectedCollection.Value()); + DrawCollectionButton(buttonSize, GetDefaultCollectionInfo()); + DrawCollectionButton(buttonSize, GetInterfaceCollectionInfo()); + DrawCollectionButton(buttonSize, GetPlayerCollectionInfo()); + DrawCollectionButton(buttonSize, GetInheritedCollectionInfo()); + + _collectionCombo.Draw("##collectionSelector", comboWidth, ColorId.SelectedCollection.Value()); } _tutorial.OpenTutorial(BasicTutorialSteps.CollectionSelectors); @@ -46,31 +53,87 @@ public class CollectionSelectHeader ImGuiUtil.DrawTextButton("The currently selected collection is not used in any way.", -Vector2.UnitX, Colors.PressEnterWarningBg); } - private void DrawDefaultCollectionButton(Vector2 width) + private enum CollectionState { - var name = $"{TutorialService.DefaultCollection} ({_activeCollections.Default.Name})"; - var isCurrent = _activeCollections.Default == _activeCollections.Current; - var isEmpty = _activeCollections.Default == ModCollection.Empty; - var tt = isCurrent ? $"The current collection is already the configured {TutorialService.DefaultCollection}." - : isEmpty ? $"The {TutorialService.DefaultCollection} is configured to be empty." - : $"Set the {TutorialService.SelectedCollection} to the configured {TutorialService.DefaultCollection}."; - if (ImGuiUtil.DrawDisabledButton(name, width, tt, isCurrent || isEmpty)) - _activeCollections.SetCollection(_activeCollections.Default, CollectionType.Current); + Empty, + Selected, + Unavailable, + Available, } - private void DrawInheritedCollectionButton(Vector2 width) + private CollectionState CheckCollection(ModCollection? collection, bool inheritance = false) { - var noModSelected = _selector.Selected == null; - var collection = _selector.SelectedSettingCollection; - var modInherited = collection != _activeCollections.Current; - var (name, tt) = (noModSelected, modInherited) switch + if (collection == null) + return CollectionState.Unavailable; + if (collection == ModCollection.Empty) + return CollectionState.Empty; + if (collection == _activeCollections.Current) + return inheritance ? CollectionState.Unavailable : CollectionState.Selected; + + return CollectionState.Available; + } + + private (ModCollection?, string, string, bool) GetDefaultCollectionInfo() + { + var collection = _activeCollections.Default; + return CheckCollection(collection) switch { - (true, _) => ("Inherited Collection", "No mod selected."), - (false, true) => ($"Inherited Collection ({collection.Name})", - "Set the current collection to the collection the selected mod inherits its settings from."), - (false, false) => ("Not Inherited", "The selected mod does not inherit its settings."), + CollectionState.Empty => (collection, "None", "The base collection is configured to use no mods.", true), + CollectionState.Selected => (collection, collection.Name, + "The configured base collection is already selected as the current collection.", true), + CollectionState.Available => (collection, collection.Name, + $"Select the configured base collection {collection.Name} as the current collection.", false), + _ => throw new Exception("Can not happen."), }; - if (ImGuiUtil.DrawDisabledButton(name, width, tt, noModSelected || !modInherited)) - _activeCollections.SetCollection(collection, CollectionType.Current); + } + + private (ModCollection?, string, string, bool) GetPlayerCollectionInfo() + { + var collection = _resolver.PlayerCollection(); + return CheckCollection(collection) switch + { + CollectionState.Empty => (collection, "None", "The base collection is configured to use no mods.", true), + CollectionState.Selected => (collection, collection.Name, + "The collection configured to apply to the loaded player character is already selected as the current collection.", true), + CollectionState.Available => (collection, collection.Name, + $"Select the collection {collection.Name} that applies to the loaded player character as the current collection.", false), + _ => throw new Exception("Can not happen."), + }; + } + + private (ModCollection?, string, string, bool) GetInterfaceCollectionInfo() + { + var collection = _activeCollections.Interface; + return CheckCollection(collection) switch + { + CollectionState.Empty => (collection, "None", "The interface collection is configured to use no mods.", true), + CollectionState.Selected => (collection, collection.Name, + "The configured interface collection is already selected as the current collection.", true), + CollectionState.Available => (collection, collection.Name, + $"Select the configured interface collection {collection.Name} as the current collection.", false), + _ => throw new Exception("Can not happen."), + }; + } + + private (ModCollection?, string, string, bool) GetInheritedCollectionInfo() + { + var collection = _selector.Selected == null ? null : _selector.SelectedSettingCollection; + return CheckCollection(collection, true) switch + { + CollectionState.Unavailable => (null, "Not Inherited", + "The settings of the selected mod are not inherited from another collection.", true), + CollectionState.Available => (collection, collection!.Name, + $"Select the collection {collection!.Name} from which the selected mod inherits its settings as the current collection.", + false), + _ => throw new Exception("Can not happen."), + }; + } + + private void DrawCollectionButton(Vector2 buttonWidth, (ModCollection?, string, string, bool) tuple) + { + var (collection, name, tooltip, disabled) = tuple; + if (ImGuiUtil.DrawDisabledButton(name, buttonWidth, tooltip, disabled)) + _activeCollections.SetCollection(collection!, CollectionType.Current); + ImGui.SameLine(); } } From 4fdb89ce625ff7c48460884e74ec5e5dfe44edbf Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 11 Sep 2023 14:26:51 +0000 Subject: [PATCH 0087/1381] [CI] Updating repo.json for testing_0.7.3.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 185481f9..21ff7756 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.6", + "TestingAssemblyVersion": "0.7.3.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From d21cba466933f2883148cf624ee2671604d074df Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 13 Sep 2023 17:06:29 +0200 Subject: [PATCH 0088/1381] Allow drag & drop of multiple mods or folders with Control. --- OtterGui | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 12 +++-- Penumbra/UI/ModsTab/ModPanel.cs | 56 ++++++++++++++++++-- 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/OtterGui b/OtterGui index 86ec4d72..9c7a3147 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 86ec4d72c9c9ed57aa7be4a7d0c81069c5b94ad7 +Subproject commit 9c7a3147f6e64e93074bc318a52b0723efc6ffff diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 6eecf36a..8d978413 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -42,7 +42,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector ImGui.GetStyle().ItemSpacing.X) ImGui.GetWindowDrawList().AddText(new Vector2(itemPos + offset, line), ColorId.SelectorPriority.Value(), priorityString); } @@ -341,7 +341,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector + ImGuiUtil.HelpPopup("ExtendedHelp", new Vector2(1000 * UiHelpers.Scale, 36.5f * ImGui.GetTextLineHeightWithSpacing()), () => { ImGui.Dummy(Vector2.UnitY * ImGui.GetTextLineHeight()); ImGui.TextUnformatted("Mod Management"); @@ -380,6 +380,10 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Lexicographical) .FirstOrDefault(l => l is ModFileSystem.Leaf m && m.Value.ModPath.FullName == _lastSelectedDirectory); - Select(leaf); + Select(leaf, AllowMultipleSelection); _lastSelectedDirectory = string.Empty; } diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index d85f77ff..f0d28dab 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -1,5 +1,11 @@ using System; +using System.Linq; +using System.Numerics; +using Dalamud.Interface; using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; using Penumbra.Mods; using Penumbra.UI.AdvancedWindow; @@ -7,10 +13,10 @@ namespace Penumbra.UI.ModsTab; public class ModPanel : IDisposable { - private readonly ModFileSystemSelector _selector; - private readonly ModEditWindow _editWindow; - private readonly ModPanelHeader _header; - private readonly ModPanelTabBar _tabs; + private readonly ModFileSystemSelector _selector; + private readonly ModEditWindow _editWindow; + private readonly ModPanelHeader _header; + private readonly ModPanelTabBar _tabs; public ModPanel(DalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs) { @@ -24,7 +30,10 @@ public class ModPanel : IDisposable public void Draw() { if (!_valid) + { + DrawMultiSelection(); return; + } _header.Draw(); _tabs.Draw(_mod); @@ -36,6 +45,45 @@ public class ModPanel : IDisposable _header.Dispose(); } + private void DrawMultiSelection() + { + if (_selector.SelectedPaths.Count == 0) + return; + + var sizeType = ImGui.GetFrameHeight(); + var availableSizePercent = (ImGui.GetContentRegionAvail().X - sizeType - 4 * ImGui.GetStyle().CellPadding.X) / 100; + var sizeMods = availableSizePercent * 35; + var sizeFolders = availableSizePercent * 65; + + ImGui.NewLine(); + ImGui.TextUnformatted("Currently Selected Objects"); + ImGui.Separator(); + using var table = ImRaii.Table("mods", 3, ImGuiTableFlags.RowBg); + ImGui.TableSetupColumn("type", ImGuiTableColumnFlags.WidthFixed, sizeType); + ImGui.TableSetupColumn("mod", ImGuiTableColumnFlags.WidthFixed, sizeMods); + ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthFixed, sizeFolders); + + var i = 0; + foreach (var (fullName, path) in _selector.SelectedPaths.Select(p => (p.FullName(), p)) + .OrderBy(p => p.Item1, StringComparer.OrdinalIgnoreCase)) + { + using var id = ImRaii.PushId(i++); + ImGui.TableNextColumn(); + var icon = (path is ModFileSystem.Leaf ? FontAwesomeIcon.FileCircleMinus : FontAwesomeIcon.FolderMinus).ToIconString(); + if (ImGuiUtil.DrawDisabledButton(icon, new Vector2(sizeType), "Remove from selection.", false, true)) + _selector.RemovePathFromMultiselection(path); + + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(path is ModFileSystem.Leaf l ? l.Value.Name : string.Empty); + + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(fullName); + } + } + + private bool _valid; private Mod _mod = null!; From b352373a52196e295b0825d419fbf213c95c4f96 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 13 Sep 2023 15:09:13 +0000 Subject: [PATCH 0089/1381] [CI] Updating repo.json for testing_0.7.3.8 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 21ff7756..cceb2f29 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.7", + "TestingAssemblyVersion": "0.7.3.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.8/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 7431db2a0816d6e22c0aa9f4788e2572d3ff7364 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 13 Sep 2023 20:09:00 +0200 Subject: [PATCH 0090/1381] Fix click check for selectables. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 9c7a3147..51ae6032 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9c7a3147f6e64e93074bc318a52b0723efc6ffff +Subproject commit 51ae60322c22c9d9b49365ad0b9fd60dc3d50296 From e26873934b77ef5477b19c3e9c7abf5ab1a0e833 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 13 Sep 2023 18:11:56 +0000 Subject: [PATCH 0091/1381] [CI] Updating repo.json for testing_0.7.3.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index cceb2f29..67cb1832 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.8", + "TestingAssemblyVersion": "0.7.3.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 4e704770cb2a4d6a15ad50445a9ac5972ca9af62 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 14 Sep 2023 17:23:54 +0200 Subject: [PATCH 0092/1381] Add Filesystem Compression as a toggle and button. Also some auto-formatting. --- OtterGui | 2 +- Penumbra/Configuration.cs | 1 + Penumbra/Import/TexToolsImport.cs | 146 ++++++------ Penumbra/Import/TexToolsImporter.Gui.cs | 1 - Penumbra/Import/TexToolsImporter.ModPack.cs | 215 +++++++++--------- Penumbra/Import/TexToolsMeta.Export.cs | 194 ++++++++-------- Penumbra/Import/Textures/TextureDrawer.cs | 2 +- Penumbra/Meta/MetaFileManager.cs | 8 +- Penumbra/Mods/Editor/MdlMaterialEditor.cs | 5 +- Penumbra/Mods/Editor/ModEditor.cs | 9 +- Penumbra/Mods/Editor/ModelMaterialInfo.cs | 7 +- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 3 +- Penumbra/Mods/Manager/ModImportManager.cs | 3 +- Penumbra/Services/ServiceManager.cs | 4 +- Penumbra/UI/AdvancedWindow/FileEditor.cs | 57 ++--- .../AdvancedWindow/ModEditWindow.Materials.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 1 + .../ModEditWindow.QuickImport.cs | 5 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 13 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 49 +++- 21 files changed, 385 insertions(+), 344 deletions(-) diff --git a/OtterGui b/OtterGui index 51ae6032..e3e3f42f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 51ae60322c22c9d9b49365ad0b9fd60dc3d50296 +Subproject commit e3e3f42f093b53ad02694810398df5736174d711 diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index cc7cc026..a80563c9 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -99,6 +99,7 @@ public class Configuration : IPluginConfiguration, ISavable public bool PrintSuccessfulCommandsToChat { get; set; } = true; public bool FixMainWindow { get; set; } = false; public bool AutoDeduplicateOnImport { get; set; } = true; + public bool UseFileSystemCompression { get; set; } = true; public bool EnableHttpApi { get; set; } = true; public string DefaultModImportPath { get; set; } = string.Empty; diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index dff1c921..49b344da 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; @@ -7,9 +6,10 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; -using Penumbra.Api; +using OtterGui.Compression; using Penumbra.Import.Structs; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using FileMode = System.IO.FileMode; using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; @@ -25,41 +25,41 @@ public partial class TexToolsImporter : IDisposable private readonly DirectoryInfo _baseDirectory; private readonly string _tmpFile; - private readonly IEnumerable< FileInfo > _modPackFiles; + private readonly IEnumerable _modPackFiles; private readonly int _modPackCount; private FileStream? _tmpFileStream; private StreamDisposer? _streamDisposer; private readonly CancellationTokenSource _cancellation = new(); private readonly CancellationToken _token; - public ImporterState State { get; private set; } - public readonly List< (FileInfo File, DirectoryInfo? Mod, Exception? Error) > ExtractedMods; + public ImporterState State { get; private set; } + public readonly List<(FileInfo File, DirectoryInfo? Mod, Exception? Error)> ExtractedMods; private readonly Configuration _config; private readonly ModEditor _editor; - private readonly ModManager _modManager; - - public TexToolsImporter( int count, IEnumerable< FileInfo > modPackFiles, - Action< FileInfo, DirectoryInfo?, Exception? > handler, Configuration config, ModEditor editor, ModManager modManager) + private readonly ModManager _modManager; + private readonly FileCompactor _compactor; + + public TexToolsImporter(int count, IEnumerable modPackFiles, Action handler, + Configuration config, ModEditor editor, ModManager modManager, FileCompactor compactor) { _baseDirectory = modManager.BasePath; - _tmpFile = Path.Combine( _baseDirectory.FullName, TempFileName ); + _tmpFile = Path.Combine(_baseDirectory.FullName, TempFileName); _modPackFiles = modPackFiles; _config = config; _editor = editor; - _modManager = modManager; + _modManager = modManager; + _compactor = compactor; _modPackCount = count; - ExtractedMods = new List< (FileInfo, DirectoryInfo?, Exception?) >( count ); + ExtractedMods = new List<(FileInfo, DirectoryInfo?, Exception?)>(count); _token = _cancellation.Token; - Task.Run( ImportFiles, _token ) - .ContinueWith( _ => CloseStreams() ) - .ContinueWith( _ => + Task.Run(ImportFiles, _token) + .ContinueWith(_ => CloseStreams()) + .ContinueWith(_ => { - foreach( var (file, dir, error) in ExtractedMods ) - { - handler( file, dir, error ); - } - } ); + foreach (var (file, dir, error) in ExtractedMods) + handler(file, dir, error); + }); } private void CloseStreams() @@ -71,45 +71,43 @@ public partial class TexToolsImporter : IDisposable public void Dispose() { - _cancellation.Cancel( true ); - if( State != ImporterState.WritingPackToDisk ) + _cancellation.Cancel(true); + if (State != ImporterState.WritingPackToDisk) { _tmpFileStream?.Dispose(); _tmpFileStream = null; } - if( State != ImporterState.ExtractingModFiles ) - { + if (State != ImporterState.ExtractingModFiles) ResetStreamDisposer(); - } } private void ImportFiles() { - State = ImporterState.None; - _currentModPackIdx = 0; - foreach( var file in _modPackFiles ) + State = ImporterState.None; + _currentModPackIdx = 0; + foreach (var file in _modPackFiles) { _currentModDirectory = null; - if( _token.IsCancellationRequested ) + if (_token.IsCancellationRequested) { - ExtractedMods.Add( ( file, null, new TaskCanceledException( "Task canceled by user." ) ) ); + ExtractedMods.Add((file, null, new TaskCanceledException("Task canceled by user."))); continue; } try { - var directory = VerifyVersionAndImport( file ); - ExtractedMods.Add( ( file, directory, null ) ); - if( _config.AutoDeduplicateOnImport ) + var directory = VerifyVersionAndImport(file); + ExtractedMods.Add((file, directory, null)); + if (_config.AutoDeduplicateOnImport) { State = ImporterState.DeduplicatingFiles; - _editor.Duplicates.DeduplicateMod( directory ); + _editor.Duplicates.DeduplicateMod(directory); } } - catch( Exception e ) + catch (Exception e) { - ExtractedMods.Add( ( file, _currentModDirectory, e ) ); + ExtractedMods.Add((file, _currentModDirectory, e)); _currentNumOptions = 0; _currentOptionIdx = 0; _currentFileIdx = 0; @@ -124,87 +122,75 @@ public partial class TexToolsImporter : IDisposable // Rudimentary analysis of a TTMP file by extension and version. // Puts out warnings if extension does not correspond to data. - private DirectoryInfo VerifyVersionAndImport( FileInfo modPackFile ) + private DirectoryInfo VerifyVersionAndImport(FileInfo modPackFile) { - if( modPackFile.Extension.ToLowerInvariant() is ".pmp" or ".zip" or ".7z" or ".rar" ) - { - return HandleRegularArchive( modPackFile ); - } + if (modPackFile.Extension.ToLowerInvariant() is ".pmp" or ".zip" or ".7z" or ".rar") + return HandleRegularArchive(modPackFile); using var zfs = modPackFile.OpenRead(); - using var extractedModPack = ZipArchive.Open( zfs ); + using var extractedModPack = ZipArchive.Open(zfs); - var mpl = FindZipEntry( extractedModPack, "TTMPL.mpl" ); - if( mpl == null ) - { - throw new FileNotFoundException( "ZIP does not contain a TTMPL.mpl file." ); - } + var mpl = FindZipEntry(extractedModPack, "TTMPL.mpl"); + if (mpl == null) + throw new FileNotFoundException("ZIP does not contain a TTMPL.mpl file."); - var modRaw = GetStringFromZipEntry( mpl, Encoding.UTF8 ); + var modRaw = GetStringFromZipEntry(mpl, Encoding.UTF8); // At least a better validation than going by the extension. - if( modRaw.Contains( "\"TTMPVersion\":" ) ) + if (modRaw.Contains("\"TTMPVersion\":")) { - if( modPackFile.Extension != ".ttmp2" ) - { - Penumbra.Log.Warning( $"File {modPackFile.FullName} seems to be a V2 TTMP, but has the wrong extension." ); - } + if (modPackFile.Extension != ".ttmp2") + Penumbra.Log.Warning($"File {modPackFile.FullName} seems to be a V2 TTMP, but has the wrong extension."); - return ImportV2ModPack( modPackFile, extractedModPack, modRaw ); + return ImportV2ModPack(modPackFile, extractedModPack, modRaw); } - if( modPackFile.Extension != ".ttmp" ) - { - Penumbra.Log.Warning( $"File {modPackFile.FullName} seems to be a V1 TTMP, but has the wrong extension." ); - } + if (modPackFile.Extension != ".ttmp") + Penumbra.Log.Warning($"File {modPackFile.FullName} seems to be a V1 TTMP, but has the wrong extension."); - return ImportV1ModPack( modPackFile, extractedModPack, modRaw ); + return ImportV1ModPack(modPackFile, extractedModPack, modRaw); } // You can in no way rely on any file paths in TTMPs so we need to just do this, sorry - private static ZipArchiveEntry? FindZipEntry( ZipArchive file, string fileName ) - => file.Entries.FirstOrDefault( e => !e.IsDirectory && e.Key.Contains( fileName ) ); + private static ZipArchiveEntry? FindZipEntry(ZipArchive file, string fileName) + => file.Entries.FirstOrDefault(e => !e.IsDirectory && e.Key.Contains(fileName)); - private static string GetStringFromZipEntry( ZipArchiveEntry entry, Encoding encoding ) + private static string GetStringFromZipEntry(ZipArchiveEntry entry, Encoding encoding) { using var ms = new MemoryStream(); using var s = entry.OpenEntryStream(); - s.CopyTo( ms ); - return encoding.GetString( ms.ToArray() ); + s.CopyTo(ms); + return encoding.GetString(ms.ToArray()); } - private void WriteZipEntryToTempFile( Stream s ) + private void WriteZipEntryToTempFile(Stream s) { _tmpFileStream?.Dispose(); // should not happen - _tmpFileStream = new FileStream( _tmpFile, FileMode.Create ); - if( _token.IsCancellationRequested ) - { + _tmpFileStream = new FileStream(_tmpFile, FileMode.Create); + if (_token.IsCancellationRequested) return; - } - s.CopyTo( _tmpFileStream ); + s.CopyTo(_tmpFileStream); _tmpFileStream.Dispose(); _tmpFileStream = null; } - private StreamDisposer GetSqPackStreamStream( ZipArchive file, string entryName ) + private StreamDisposer GetSqPackStreamStream(ZipArchive file, string entryName) { State = ImporterState.WritingPackToDisk; // write shitty zip garbage to disk - var entry = FindZipEntry( file, entryName ); - if( entry == null ) - { - throw new FileNotFoundException( $"ZIP does not contain a file named {entryName}." ); - } + var entry = FindZipEntry(file, entryName); + if (entry == null) + throw new FileNotFoundException($"ZIP does not contain a file named {entryName}."); using var s = entry.OpenEntryStream(); - WriteZipEntryToTempFile( s ); + WriteZipEntryToTempFile(s); _streamDisposer?.Dispose(); // Should not happen. - var fs = new FileStream( _tmpFile, FileMode.Open ); - return new StreamDisposer( fs ); + var fs = new FileStream(_tmpFile, FileMode.Open); + return new StreamDisposer(fs); } private void ResetStreamDisposer() @@ -212,4 +198,4 @@ public partial class TexToolsImporter : IDisposable _streamDisposer?.Dispose(); _streamDisposer = null; } -} \ No newline at end of file +} diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index 79cd728b..db818341 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -22,7 +22,6 @@ public partial class TexToolsImporter private string _currentOptionName = string.Empty; private string _currentFileName = string.Empty; - public void DrawProgressInfo( Vector2 size ) { if( _modPackCount == 0 ) diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 0776faea..32c9c0e1 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -17,7 +17,7 @@ public partial class TexToolsImporter private DirectoryInfo? _currentModDirectory; // Version 1 mod packs are a simple collection of files without much information. - private DirectoryInfo ImportV1ModPack( FileInfo modPackFile, ZipArchive extractedModPack, string modRaw ) + private DirectoryInfo ImportV1ModPack(FileInfo modPackFile, ZipArchive extractedModPack, string modRaw) { _currentOptionIdx = 0; _currentNumOptions = 1; @@ -25,174 +25,171 @@ public partial class TexToolsImporter _currentGroupName = string.Empty; _currentOptionName = DefaultTexToolsData.DefaultOption; - Penumbra.Log.Information( " -> Importing V1 ModPack" ); + Penumbra.Log.Information(" -> Importing V1 ModPack"); var modListRaw = modRaw.Split( - new[] { "\r\n", "\r", "\n" }, + new[] + { + "\r\n", + "\r", + "\n", + }, StringSplitOptions.RemoveEmptyEntries ); - var modList = modListRaw.Select( m => JsonConvert.DeserializeObject< SimpleMod >( m, JsonSettings )! ).ToList(); + var modList = modListRaw.Select(m => JsonConvert.DeserializeObject(m, JsonSettings)!).ToList(); - _currentModDirectory = ModCreator.CreateModFolder( _baseDirectory, Path.GetFileNameWithoutExtension( modPackFile.Name ) ); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetFileNameWithoutExtension(modPackFile.Name)); // Create a new ModMeta from the TTMP mod list info - _modManager.DataEditor.CreateMeta( _currentModDirectory, _currentModName, DefaultTexToolsData.Author, DefaultTexToolsData.Description, null, null ); + _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, DefaultTexToolsData.Author, DefaultTexToolsData.Description, + null, null); // Open the mod data file from the mod pack as a SqPackStream - _streamDisposer = GetSqPackStreamStream( extractedModPack, "TTMPD.mpd" ); - ExtractSimpleModList( _currentModDirectory, modList ); - _modManager.Creator.CreateDefaultFiles( _currentModDirectory ); + _streamDisposer = GetSqPackStreamStream(extractedModPack, "TTMPD.mpd"); + ExtractSimpleModList(_currentModDirectory, modList); + _modManager.Creator.CreateDefaultFiles(_currentModDirectory); ResetStreamDisposer(); return _currentModDirectory; } // Version 2 mod packs can either be simple or extended, import accordingly. - private DirectoryInfo ImportV2ModPack( FileInfo _, ZipArchive extractedModPack, string modRaw ) + private DirectoryInfo ImportV2ModPack(FileInfo _, ZipArchive extractedModPack, string modRaw) { - var modList = JsonConvert.DeserializeObject< SimpleModPack >( modRaw, JsonSettings )!; + var modList = JsonConvert.DeserializeObject(modRaw, JsonSettings)!; - if( modList.TtmpVersion.EndsWith( "s" ) ) - { - return ImportSimpleV2ModPack( extractedModPack, modList ); - } + if (modList.TtmpVersion.EndsWith("s")) + return ImportSimpleV2ModPack(extractedModPack, modList); - if( modList.TtmpVersion.EndsWith( "w" ) ) - { - return ImportExtendedV2ModPack( extractedModPack, modRaw ); - } + if (modList.TtmpVersion.EndsWith("w")) + return ImportExtendedV2ModPack(extractedModPack, modRaw); try { - Penumbra.Log.Warning( $"Unknown TTMPVersion <{modList.TtmpVersion}> given, trying to export as simple mod pack." ); - return ImportSimpleV2ModPack( extractedModPack, modList ); + Penumbra.Log.Warning($"Unknown TTMPVersion <{modList.TtmpVersion}> given, trying to export as simple mod pack."); + return ImportSimpleV2ModPack(extractedModPack, modList); } - catch( Exception e1 ) + catch (Exception e1) { - Penumbra.Log.Warning( $"Exporting as simple mod pack failed with following error, retrying as extended mod pack:\n{e1}" ); + Penumbra.Log.Warning($"Exporting as simple mod pack failed with following error, retrying as extended mod pack:\n{e1}"); try { - return ImportExtendedV2ModPack( extractedModPack, modRaw ); + return ImportExtendedV2ModPack(extractedModPack, modRaw); } - catch( Exception e2 ) + catch (Exception e2) { - throw new IOException( "Exporting as extended mod pack failed, too. Version unsupported or file defect.", e2 ); + throw new IOException("Exporting as extended mod pack failed, too. Version unsupported or file defect.", e2); } } } // Simple V2 mod packs are basically the same as V1 mod packs. - private DirectoryInfo ImportSimpleV2ModPack( ZipArchive extractedModPack, SimpleModPack modList ) + private DirectoryInfo ImportSimpleV2ModPack(ZipArchive extractedModPack, SimpleModPack modList) { _currentOptionIdx = 0; _currentNumOptions = 1; _currentModName = modList.Name; _currentGroupName = string.Empty; _currentOptionName = DefaultTexToolsData.DefaultOption; - Penumbra.Log.Information( " -> Importing Simple V2 ModPack" ); + Penumbra.Log.Information(" -> Importing Simple V2 ModPack"); - _currentModDirectory = ModCreator.CreateModFolder( _baseDirectory, _currentModName ); - _modManager.DataEditor.CreateMeta( _currentModDirectory, _currentModName, modList.Author, string.IsNullOrEmpty( modList.Description ) + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, _currentModName); + _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, modList.Author, string.IsNullOrEmpty(modList.Description) ? "Mod imported from TexTools mod pack" - : modList.Description, modList.Version, modList.Url ); + : modList.Description, modList.Version, modList.Url); // Open the mod data file from the mod pack as a SqPackStream - _streamDisposer = GetSqPackStreamStream( extractedModPack, "TTMPD.mpd" ); - ExtractSimpleModList( _currentModDirectory, modList.SimpleModsList ); - _modManager.Creator.CreateDefaultFiles( _currentModDirectory ); + _streamDisposer = GetSqPackStreamStream(extractedModPack, "TTMPD.mpd"); + ExtractSimpleModList(_currentModDirectory, modList.SimpleModsList); + _modManager.Creator.CreateDefaultFiles(_currentModDirectory); ResetStreamDisposer(); return _currentModDirectory; } // Obtain the number of relevant options to extract. - private static int GetOptionCount( ExtendedModPack pack ) - => ( pack.SimpleModsList.Length > 0 ? 1 : 0 ) + private static int GetOptionCount(ExtendedModPack pack) + => (pack.SimpleModsList.Length > 0 ? 1 : 0) + pack.ModPackPages - .Sum( page => page.ModGroups - .Where( g => g.GroupName.Length > 0 && g.OptionList.Length > 0 ) - .Sum( group => group.OptionList - .Count( o => o.Name.Length > 0 && o.ModsJsons.Length > 0 ) - + ( group.OptionList.Any( o => o.Name.Length > 0 && o.ModsJsons.Length == 0 ) ? 1 : 0 ) ) ); + .Sum(page => page.ModGroups + .Where(g => g.GroupName.Length > 0 && g.OptionList.Length > 0) + .Sum(group => group.OptionList + .Count(o => o.Name.Length > 0 && o.ModsJsons.Length > 0) + + (group.OptionList.Any(o => o.Name.Length > 0 && o.ModsJsons.Length == 0) ? 1 : 0))); - private static string GetGroupName( string groupName, ISet< string > names ) + private static string GetGroupName(string groupName, ISet names) { var baseName = groupName; var i = 2; - while( !names.Add( groupName ) ) - { + while (!names.Add(groupName)) groupName = $"{baseName} ({i++})"; - } return groupName; } // Extended V2 mod packs contain multiple options that need to be handled separately. - private DirectoryInfo ImportExtendedV2ModPack( ZipArchive extractedModPack, string modRaw ) + private DirectoryInfo ImportExtendedV2ModPack(ZipArchive extractedModPack, string modRaw) { _currentOptionIdx = 0; - Penumbra.Log.Information( " -> Importing Extended V2 ModPack" ); + Penumbra.Log.Information(" -> Importing Extended V2 ModPack"); - var modList = JsonConvert.DeserializeObject< ExtendedModPack >( modRaw, JsonSettings )!; - _currentNumOptions = GetOptionCount( modList ); + var modList = JsonConvert.DeserializeObject(modRaw, JsonSettings)!; + _currentNumOptions = GetOptionCount(modList); _currentModName = modList.Name; - _currentModDirectory = ModCreator.CreateModFolder( _baseDirectory, _currentModName ); - _modManager.DataEditor.CreateMeta( _currentModDirectory, _currentModName, modList.Author, modList.Description, modList.Version, modList.Url ); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, _currentModName); + _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, modList.Author, modList.Description, modList.Version, + modList.Url); - if( _currentNumOptions == 0 ) - { + if (_currentNumOptions == 0) return _currentModDirectory; - } // Open the mod data file from the mod pack as a SqPackStream - _streamDisposer = GetSqPackStreamStream( extractedModPack, "TTMPD.mpd" ); + _streamDisposer = GetSqPackStreamStream(extractedModPack, "TTMPD.mpd"); // It can contain a simple list, still. - if( modList.SimpleModsList.Length > 0 ) + if (modList.SimpleModsList.Length > 0) { _currentGroupName = string.Empty; _currentOptionName = "Default"; - ExtractSimpleModList( _currentModDirectory, modList.SimpleModsList ); + ExtractSimpleModList(_currentModDirectory, modList.SimpleModsList); } // Iterate through all pages - var options = new List< ISubMod >(); + var options = new List(); var groupPriority = 0; - var groupNames = new HashSet< string >(); - foreach( var page in modList.ModPackPages ) + var groupNames = new HashSet(); + foreach (var page in modList.ModPackPages) { - foreach( var group in page.ModGroups.Where( group => group.GroupName.Length > 0 && group.OptionList.Length > 0 ) ) + foreach (var group in page.ModGroups.Where(group => group.GroupName.Length > 0 && group.OptionList.Length > 0)) { - var allOptions = group.OptionList.Where( option => option.Name.Length > 0 && option.ModsJsons.Length > 0 ).ToList(); + var allOptions = group.OptionList.Where(option => option.Name.Length > 0 && option.ModsJsons.Length > 0).ToList(); var (numGroups, maxOptions) = group.SelectionType == GroupType.Single - ? ( 1, allOptions.Count ) - : ( 1 + allOptions.Count / IModGroup.MaxMultiOptions, IModGroup.MaxMultiOptions ); - _currentGroupName = GetGroupName( group.GroupName, groupNames ); + ? (1, allOptions.Count) + : (1 + allOptions.Count / IModGroup.MaxMultiOptions, IModGroup.MaxMultiOptions); + _currentGroupName = GetGroupName(group.GroupName, groupNames); - var optionIdx = 0; - for( var groupId = 0; groupId < numGroups; ++groupId ) + var optionIdx = 0; + for (var groupId = 0; groupId < numGroups; ++groupId) { - var name = numGroups == 1 ? _currentGroupName : $"{_currentGroupName}, Part {groupId + 1}"; + var name = numGroups == 1 ? _currentGroupName : $"{_currentGroupName}, Part {groupId + 1}"; options.Clear(); - var groupFolder = ModCreator.NewSubFolderName( _currentModDirectory, name ) - ?? new DirectoryInfo( Path.Combine( _currentModDirectory.FullName, - numGroups == 1 ? $"Group {groupPriority + 1}" : $"Group {groupPriority + 1}, Part {groupId + 1}" ) ); + var groupFolder = ModCreator.NewSubFolderName(_currentModDirectory, name) + ?? new DirectoryInfo(Path.Combine(_currentModDirectory.FullName, + numGroups == 1 ? $"Group {groupPriority + 1}" : $"Group {groupPriority + 1}, Part {groupId + 1}")); uint? defaultSettings = group.SelectionType == GroupType.Multi ? 0u : null; - for( var i = 0; i + optionIdx < allOptions.Count && i < maxOptions; ++i ) + for (var i = 0; i + optionIdx < allOptions.Count && i < maxOptions; ++i) { - var option = allOptions[ i + optionIdx ]; + var option = allOptions[i + optionIdx]; _token.ThrowIfCancellationRequested(); _currentOptionName = option.Name; - var optionFolder = ModCreator.NewSubFolderName( groupFolder, option.Name ) - ?? new DirectoryInfo( Path.Combine( groupFolder.FullName, $"Option {i + optionIdx + 1}" ) ); - ExtractSimpleModList( optionFolder, option.ModsJsons ); - options.Add( _modManager.Creator.CreateSubMod( _currentModDirectory, optionFolder, option ) ); - if( option.IsChecked ) - { + var optionFolder = ModCreator.NewSubFolderName(groupFolder, option.Name) + ?? new DirectoryInfo(Path.Combine(groupFolder.FullName, $"Option {i + optionIdx + 1}")); + ExtractSimpleModList(optionFolder, option.ModsJsons); + options.Add(_modManager.Creator.CreateSubMod(_currentModDirectory, optionFolder, option)); + if (option.IsChecked) defaultSettings = group.SelectionType == GroupType.Multi - ? ( defaultSettings!.Value | ( 1u << i ) ) - : ( uint )i; - } + ? defaultSettings!.Value | (1u << i) + : (uint)i; ++_currentOptionIdx; } @@ -201,30 +198,30 @@ public partial class TexToolsImporter // Handle empty options for single select groups without creating a folder for them. // We only want one of those at most, and it should usually be the first option. - if( group.SelectionType == GroupType.Single ) + if (group.SelectionType == GroupType.Single) { - var empty = group.OptionList.FirstOrDefault( o => o.Name.Length > 0 && o.ModsJsons.Length == 0 ); - if( empty != null ) + var empty = group.OptionList.FirstOrDefault(o => o.Name.Length > 0 && o.ModsJsons.Length == 0); + if (empty != null) { _currentOptionName = empty.Name; - options.Insert( 0, ModCreator.CreateEmptySubMod( empty.Name ) ); + options.Insert(0, ModCreator.CreateEmptySubMod(empty.Name)); defaultSettings = defaultSettings == null ? 0 : defaultSettings.Value + 1; } } - _modManager.Creator.CreateOptionGroup( _currentModDirectory, group.SelectionType, name, groupPriority, groupPriority, - defaultSettings ?? 0, group.Description, options ); + _modManager.Creator.CreateOptionGroup(_currentModDirectory, group.SelectionType, name, groupPriority, groupPriority, + defaultSettings ?? 0, group.Description, options); ++groupPriority; } } } ResetStreamDisposer(); - _modManager.Creator.CreateDefaultFiles( _currentModDirectory ); + _modManager.Creator.CreateDefaultFiles(_currentModDirectory); return _currentModDirectory; } - private void ExtractSimpleModList( DirectoryInfo outDirectory, ICollection< SimpleMod > mods ) + private void ExtractSimpleModList(DirectoryInfo outDirectory, ICollection mods) { State = ImporterState.ExtractingModFiles; @@ -232,51 +229,47 @@ public partial class TexToolsImporter _currentNumFiles = mods.Count(m => m.FullPath.Length > 0); // Extract each SimpleMod into the new mod folder - foreach( var simpleMod in mods.Where(m => m.FullPath.Length > 0 ) ) + foreach (var simpleMod in mods.Where(m => m.FullPath.Length > 0)) { - ExtractMod( outDirectory, simpleMod ); + ExtractMod(outDirectory, simpleMod); ++_currentFileIdx; } } - private void ExtractMod( DirectoryInfo outDirectory, SimpleMod mod ) + private void ExtractMod(DirectoryInfo outDirectory, SimpleMod mod) { - if( _streamDisposer is not PenumbraSqPackStream stream ) - { + if (_streamDisposer is not PenumbraSqPackStream stream) return; - } - Penumbra.Log.Information( $" -> Extracting {mod.FullPath} at {mod.ModOffset:X}" ); + Penumbra.Log.Information($" -> Extracting {mod.FullPath} at {mod.ModOffset:X}"); _token.ThrowIfCancellationRequested(); - var data = stream.ReadFile< PenumbraSqPackStream.PenumbraFileResource >( mod.ModOffset ); + var data = stream.ReadFile(mod.ModOffset); _currentFileName = mod.FullPath; - var extractedFile = new FileInfo( Path.Combine( outDirectory.FullName, mod.FullPath ) ); + var extractedFile = new FileInfo(Path.Combine(outDirectory.FullName, mod.FullPath)); extractedFile.Directory?.Create(); - if( extractedFile.FullName.EndsWith( ".mdl" ) ) - { - ProcessMdl( data.Data ); - } + if (extractedFile.FullName.EndsWith(".mdl")) + ProcessMdl(data.Data); - File.WriteAllBytes( extractedFile.FullName, data.Data ); + _compactor.WriteAllBytesAsync(extractedFile.FullName, data.Data, _token).Wait(_token); } - private static void ProcessMdl( byte[] mdl ) + private static void ProcessMdl(byte[] mdl) { const int modelHeaderLodOffset = 22; // Model file header LOD num - mdl[ 64 ] = 1; + mdl[64] = 1; // Model header LOD num - var stackSize = BitConverter.ToUInt32( mdl, 4 ); - var runtimeBegin = stackSize + 0x44; + var stackSize = BitConverter.ToUInt32(mdl, 4); + var runtimeBegin = stackSize + 0x44; var stringsLengthOffset = runtimeBegin + 4; - var stringsLength = BitConverter.ToUInt32( mdl, ( int )stringsLengthOffset ); + var stringsLength = BitConverter.ToUInt32(mdl, (int)stringsLengthOffset); var modelHeaderStart = stringsLengthOffset + stringsLength + 4; - mdl[ modelHeaderStart + modelHeaderLodOffset ] = 1; + mdl[modelHeaderStart + modelHeaderLodOffset] = 1; } -} \ No newline at end of file +} diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 7f455ab0..2eac8f59 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -12,7 +12,7 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Import; public partial class TexToolsMeta -{ +{ public static void WriteTexToolsMeta(MetaFileManager manager, IEnumerable manipulations, DirectoryInfo basePath) { var files = ConvertToTexTools(manager, manipulations); @@ -23,7 +23,7 @@ public partial class TexToolsMeta try { Directory.CreateDirectory(Path.GetDirectoryName(path)!); - File.WriteAllBytes(path, data); + manager.Compactor.WriteAllBytes(path, data); } catch (Exception e) { @@ -32,191 +32,187 @@ public partial class TexToolsMeta } } - public static Dictionary< string, byte[] > ConvertToTexTools( MetaFileManager manager, IEnumerable< MetaManipulation > manips ) + public static Dictionary ConvertToTexTools(MetaFileManager manager, IEnumerable manips) { - var ret = new Dictionary< string, byte[] >(); - foreach( var group in manips.GroupBy( ManipToPath ) ) + var ret = new Dictionary(); + foreach (var group in manips.GroupBy(ManipToPath)) { - if( group.Key.Length == 0 ) - { + if (group.Key.Length == 0) continue; - } - var bytes = group.Key.EndsWith( ".rgsp" ) - ? WriteRgspFile( manager, group.Key, group ) - : WriteMetaFile( manager, group.Key, group ); - if( bytes.Length == 0 ) - { + var bytes = group.Key.EndsWith(".rgsp") + ? WriteRgspFile(manager, group.Key, group) + : WriteMetaFile(manager, group.Key, group); + if (bytes.Length == 0) continue; - } - ret.Add( group.Key, bytes ); + ret.Add(group.Key, bytes); } return ret; } - private static byte[] WriteRgspFile( MetaFileManager manager, string path, IEnumerable< MetaManipulation > manips ) + private static byte[] WriteRgspFile(MetaFileManager manager, string path, IEnumerable manips) { - var list = manips.GroupBy( m => m.Rsp.Attribute ).ToDictionary( m => m.Key, m => m.Last().Rsp ); - using var m = new MemoryStream( 45 ); - using var b = new BinaryWriter( m ); + var list = manips.GroupBy(m => m.Rsp.Attribute).ToDictionary(m => m.Key, m => m.Last().Rsp); + using var m = new MemoryStream(45); + using var b = new BinaryWriter(m); // Version - b.Write( byte.MaxValue ); - b.Write( ( ushort )2 ); + b.Write(byte.MaxValue); + b.Write((ushort)2); var race = list.First().Value.SubRace; var gender = list.First().Value.Attribute.ToGender(); - b.Write( ( byte )(race - 1) ); // offset by one due to Unknown - b.Write( ( byte )(gender - 1) ); // offset by one due to Unknown + b.Write((byte)(race - 1)); // offset by one due to Unknown + b.Write((byte)(gender - 1)); // offset by one due to Unknown - void Add( params RspAttribute[] attributes ) + void Add(params RspAttribute[] attributes) { - foreach( var attribute in attributes ) + foreach (var attribute in attributes) { - var value = list.TryGetValue( attribute, out var tmp ) ? tmp.Entry : CmpFile.GetDefault( manager, race, attribute ); - b.Write( value ); + var value = list.TryGetValue(attribute, out var tmp) ? tmp.Entry : CmpFile.GetDefault(manager, race, attribute); + b.Write(value); } } - if( gender == Gender.Male ) + if (gender == Gender.Male) { - Add( RspAttribute.MaleMinSize, RspAttribute.MaleMaxSize, RspAttribute.MaleMinTail, RspAttribute.MaleMaxTail ); + Add(RspAttribute.MaleMinSize, RspAttribute.MaleMaxSize, RspAttribute.MaleMinTail, RspAttribute.MaleMaxTail); } else { - Add( RspAttribute.FemaleMinSize, RspAttribute.FemaleMaxSize, RspAttribute.FemaleMinTail, RspAttribute.FemaleMaxTail ); - Add( RspAttribute.BustMinX, RspAttribute.BustMinY, RspAttribute.BustMinZ, RspAttribute.BustMaxX, RspAttribute.BustMaxY, RspAttribute.BustMaxZ ); + Add(RspAttribute.FemaleMinSize, RspAttribute.FemaleMaxSize, RspAttribute.FemaleMinTail, RspAttribute.FemaleMaxTail); + Add(RspAttribute.BustMinX, RspAttribute.BustMinY, RspAttribute.BustMinZ, RspAttribute.BustMaxX, RspAttribute.BustMaxY, + RspAttribute.BustMaxZ); } return m.GetBuffer(); } - private static byte[] WriteMetaFile( MetaFileManager manager, string path, IEnumerable< MetaManipulation > manips ) + private static byte[] WriteMetaFile(MetaFileManager manager, string path, IEnumerable manips) { - var filteredManips = manips.GroupBy( m => m.ManipulationType ).ToDictionary( p => p.Key, p => p.Select( x => x ) ); + var filteredManips = manips.GroupBy(m => m.ManipulationType).ToDictionary(p => p.Key, p => p.Select(x => x)); using var m = new MemoryStream(); - using var b = new BinaryWriter( m ); + using var b = new BinaryWriter(m); // Header // Current TT Metadata version. - b.Write( 2u ); + b.Write(2u); // Null-terminated ASCII path. - var utf8Path = Encoding.ASCII.GetBytes( path ); - b.Write( utf8Path ); - b.Write( ( byte )0 ); + var utf8Path = Encoding.ASCII.GetBytes(path); + b.Write(utf8Path); + b.Write((byte)0); // Number of Headers - b.Write( ( uint )filteredManips.Count ); + b.Write((uint)filteredManips.Count); // Current TT Size of Headers - b.Write( ( uint )12 ); + b.Write((uint)12); // Start of Header Entries for some reason, which is absolutely useless. var headerStart = b.BaseStream.Position + 4; - b.Write( ( uint )headerStart ); + b.Write((uint)headerStart); - var offset = ( uint )( b.BaseStream.Position + 12 * filteredManips.Count ); - foreach( var (header, data) in filteredManips ) + var offset = (uint)(b.BaseStream.Position + 12 * filteredManips.Count); + foreach (var (header, data) in filteredManips) { - b.Write( ( uint )header ); - b.Write( offset ); + b.Write((uint)header); + b.Write(offset); - var size = WriteData( manager, b, offset, header, data ); - b.Write( size ); + var size = WriteData(manager, b, offset, header, data); + b.Write(size); offset += size; } return m.ToArray(); } - private static uint WriteData( MetaFileManager manager, BinaryWriter b, uint offset, MetaManipulation.Type type, IEnumerable< MetaManipulation > manips ) + private static uint WriteData(MetaFileManager manager, BinaryWriter b, uint offset, MetaManipulation.Type type, + IEnumerable manips) { var oldPos = b.BaseStream.Position; - b.Seek( ( int )offset, SeekOrigin.Begin ); + b.Seek((int)offset, SeekOrigin.Begin); - switch( type ) + switch (type) { case MetaManipulation.Type.Imc: var allManips = manips.ToList(); - var baseFile = new ImcFile( manager, allManips[ 0 ].Imc ); - foreach( var manip in allManips ) - { - manip.Imc.Apply( baseFile ); - } + var baseFile = new ImcFile(manager, allManips[0].Imc); + foreach (var manip in allManips) + manip.Imc.Apply(baseFile); - var partIdx = allManips[ 0 ].Imc.ObjectType is ObjectType.Equipment or ObjectType.Accessory - ? ImcFile.PartIndex( allManips[ 0 ].Imc.EquipSlot ) + var partIdx = allManips[0].Imc.ObjectType is ObjectType.Equipment or ObjectType.Accessory + ? ImcFile.PartIndex(allManips[0].Imc.EquipSlot) : 0; - for( var i = 0; i <= baseFile.Count; ++i ) + for (var i = 0; i <= baseFile.Count; ++i) { - var entry = baseFile.GetEntry( partIdx, (Variant)i ); - b.Write( entry.MaterialId ); - b.Write( entry.DecalId ); - b.Write( entry.AttributeAndSound ); - b.Write( entry.VfxId ); - b.Write( entry.MaterialAnimationId ); + var entry = baseFile.GetEntry(partIdx, (Variant)i); + b.Write(entry.MaterialId); + b.Write(entry.DecalId); + b.Write(entry.AttributeAndSound); + b.Write(entry.VfxId); + b.Write(entry.MaterialAnimationId); } break; case MetaManipulation.Type.Eqdp: - foreach( var manip in manips ) + foreach (var manip in manips) { - b.Write( ( uint )Names.CombinedRace( manip.Eqdp.Gender, manip.Eqdp.Race ) ); - var entry = ( byte )(( ( uint )manip.Eqdp.Entry >> Eqdp.Offset( manip.Eqdp.Slot ) ) & 0x03); - b.Write( entry ); + b.Write((uint)Names.CombinedRace(manip.Eqdp.Gender, manip.Eqdp.Race)); + var entry = (byte)(((uint)manip.Eqdp.Entry >> Eqdp.Offset(manip.Eqdp.Slot)) & 0x03); + b.Write(entry); } break; case MetaManipulation.Type.Eqp: - foreach( var manip in manips ) + foreach (var manip in manips) { - var bytes = BitConverter.GetBytes( (ulong) manip.Eqp.Entry ); - var (numBytes, byteOffset) = Eqp.BytesAndOffset( manip.Eqp.Slot ); - for( var i = byteOffset; i < numBytes + byteOffset; ++i ) - b.Write( bytes[ i ] ); + var bytes = BitConverter.GetBytes((ulong)manip.Eqp.Entry); + var (numBytes, byteOffset) = Eqp.BytesAndOffset(manip.Eqp.Slot); + for (var i = byteOffset; i < numBytes + byteOffset; ++i) + b.Write(bytes[i]); } break; case MetaManipulation.Type.Est: - foreach( var manip in manips ) + foreach (var manip in manips) { - b.Write( ( ushort )Names.CombinedRace( manip.Est.Gender, manip.Est.Race ) ); - b.Write( manip.Est.SetId.Id ); - b.Write( manip.Est.Entry ); + b.Write((ushort)Names.CombinedRace(manip.Est.Gender, manip.Est.Race)); + b.Write(manip.Est.SetId.Id); + b.Write(manip.Est.Entry); } break; case MetaManipulation.Type.Gmp: - foreach( var manip in manips ) + foreach (var manip in manips) { - b.Write( ( uint )manip.Gmp.Entry.Value ); - b.Write( manip.Gmp.Entry.UnknownTotal ); + b.Write((uint)manip.Gmp.Entry.Value); + b.Write(manip.Gmp.Entry.UnknownTotal); } break; } var size = b.BaseStream.Position - offset; - b.Seek( ( int )oldPos, SeekOrigin.Begin ); - return ( uint )size; + b.Seek((int)oldPos, SeekOrigin.Begin); + return (uint)size; } - private static string ManipToPath( MetaManipulation manip ) + private static string ManipToPath(MetaManipulation manip) => manip.ManipulationType switch { - MetaManipulation.Type.Imc => ManipToPath( manip.Imc ), - MetaManipulation.Type.Eqdp => ManipToPath( manip.Eqdp ), - MetaManipulation.Type.Eqp => ManipToPath( manip.Eqp ), - MetaManipulation.Type.Est => ManipToPath( manip.Est ), - MetaManipulation.Type.Gmp => ManipToPath( manip.Gmp ), - MetaManipulation.Type.Rsp => ManipToPath( manip.Rsp ), + MetaManipulation.Type.Imc => ManipToPath(manip.Imc), + MetaManipulation.Type.Eqdp => ManipToPath(manip.Eqdp), + MetaManipulation.Type.Eqp => ManipToPath(manip.Eqp), + MetaManipulation.Type.Est => ManipToPath(manip.Est), + MetaManipulation.Type.Gmp => ManipToPath(manip.Gmp), + MetaManipulation.Type.Rsp => ManipToPath(manip.Rsp), _ => string.Empty, }; - private static string ManipToPath( ImcManipulation manip ) + private static string ManipToPath(ImcManipulation manip) { var path = manip.GamePath().ToString(); var replacement = manip.ObjectType switch @@ -227,22 +223,22 @@ public partial class TexToolsMeta _ => ".meta", }; - return path.Replace( ".imc", replacement ); + return path.Replace(".imc", replacement); } - private static string ManipToPath( EqdpManipulation manip ) + private static string ManipToPath(EqdpManipulation manip) => manip.Slot.IsAccessory() ? $"chara/accessory/a{manip.SetId:D4}/a{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta" : $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta"; - private static string ManipToPath( EqpManipulation manip ) + private static string ManipToPath(EqpManipulation manip) => manip.Slot.IsAccessory() ? $"chara/accessory/a{manip.SetId:D4}/a{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta" : $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta"; - private static string ManipToPath( EstManipulation manip ) + private static string ManipToPath(EstManipulation manip) { - var raceCode = Names.CombinedRace( manip.Gender, manip.Race ).ToRaceCode(); + var raceCode = Names.CombinedRace(manip.Gender, manip.Race).ToRaceCode(); return manip.Slot switch { EstManipulation.EstType.Hair => $"chara/human/c{raceCode}/obj/hair/h{manip.SetId:D4}/c{raceCode}h{manip.SetId:D4}_hir.meta", @@ -253,10 +249,10 @@ public partial class TexToolsMeta }; } - private static string ManipToPath( GmpManipulation manip ) + private static string ManipToPath(GmpManipulation manip) => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Head.ToSuffix()}.meta"; - private static string ManipToPath( RspManipulation manip ) - => $"chara/xls/charamake/rgsp/{( int )manip.SubRace - 1}-{( int )manip.Attribute.ToGender() - 1}.rgsp"; -} \ No newline at end of file + private static string ManipToPath(RspManipulation manip) + => $"chara/xls/charamake/rgsp/{(int)manip.SubRace - 1}-{(int)manip.Attribute.ToGender() - 1}.rgsp"; +} diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index fead989e..d1b78268 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -10,7 +10,7 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; using OtterTex; -using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.UI; using Penumbra.UI.Classes; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 7287204c..171ea729 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Memory; +using OtterGui.Compression; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData; @@ -26,9 +27,11 @@ public unsafe class MetaFileManager internal readonly ActiveCollectionData ActiveCollections; internal readonly ValidityChecker ValidityChecker; internal readonly IdentifierService Identifier; + internal readonly FileCompactor Compactor; public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, - ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, IdentifierService identifier) + ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, IdentifierService identifier, + FileCompactor compactor) { CharacterUtility = characterUtility; ResidentResources = residentResources; @@ -37,6 +40,7 @@ public unsafe class MetaFileManager Config = config; ValidityChecker = validityChecker; Identifier = identifier; + Compactor = compactor; SignatureHelper.Initialise(this); } @@ -91,7 +95,7 @@ public unsafe class MetaFileManager ResidentResources.Reload(); if (collection?._cache == null) - CharacterUtility.ResetAll(); + CharacterUtility.ResetAll(); else collection._cache.Meta.SetFiles(); } diff --git a/Penumbra/Mods/Editor/MdlMaterialEditor.cs b/Penumbra/Mods/Editor/MdlMaterialEditor.cs index f616d128..0fe9ec46 100644 --- a/Penumbra/Mods/Editor/MdlMaterialEditor.cs +++ b/Penumbra/Mods/Editor/MdlMaterialEditor.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; using OtterGui; +using OtterGui.Compression; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.Mods.Editor; @@ -26,10 +27,10 @@ public partial class MdlMaterialEditor public MdlMaterialEditor(ModFileCollection files) => _files = files; - public void SaveAllModels() + public void SaveAllModels(FileCompactor compactor) { foreach (var info in _modelFiles) - info.Save(); + info.Save(compactor); } public void RestoreAllModels() diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index bd774607..f65ce280 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -1,10 +1,10 @@ using System; using System.IO; using OtterGui; -using Penumbra.Mods.Editor; +using OtterGui.Compression; using Penumbra.Mods.Subclasses; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; public class ModEditor : IDisposable { @@ -15,6 +15,7 @@ public class ModEditor : IDisposable public readonly ModFileCollection Files; public readonly ModSwapEditor SwapEditor; public readonly MdlMaterialEditor MdlMaterialEditor; + public readonly FileCompactor Compactor; public Mod? Mod { get; private set; } public int GroupIdx { get; private set; } @@ -24,7 +25,8 @@ public class ModEditor : IDisposable public ISubMod? Option { get; private set; } public ModEditor(ModNormalizer modNormalizer, ModMetaEditor metaEditor, ModFileCollection files, - ModFileEditor fileEditor, DuplicateManager duplicates, ModSwapEditor swapEditor, MdlMaterialEditor mdlMaterialEditor) + ModFileEditor fileEditor, DuplicateManager duplicates, ModSwapEditor swapEditor, MdlMaterialEditor mdlMaterialEditor, + FileCompactor compactor) { ModNormalizer = modNormalizer; MetaEditor = metaEditor; @@ -33,6 +35,7 @@ public class ModEditor : IDisposable Duplicates = duplicates; SwapEditor = swapEditor; MdlMaterialEditor = mdlMaterialEditor; + Compactor = compactor; } public void LoadMod(Mod mod) diff --git a/Penumbra/Mods/Editor/ModelMaterialInfo.cs b/Penumbra/Mods/Editor/ModelMaterialInfo.cs index dc01ae7d..38e76deb 100644 --- a/Penumbra/Mods/Editor/ModelMaterialInfo.cs +++ b/Penumbra/Mods/Editor/ModelMaterialInfo.cs @@ -2,10 +2,11 @@ using System; using System.Collections.Generic; using System.Linq; using OtterGui; +using OtterGui.Compression; using Penumbra.GameData.Files; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; /// A class that collects information about skin materials in a model file and handle changes on them. public class ModelMaterialInfo @@ -40,7 +41,7 @@ public class ModelMaterialInfo } // Save a changed .mdl file. - public void Save() + public void Save(FileCompactor compactor) { if (!Changed) return; @@ -50,7 +51,7 @@ public class ModelMaterialInfo try { - System.IO.File.WriteAllBytes(Path.FullName, File.Write()); + compactor.WriteAllBytes(Path.FullName, File.Write()); Changed = false; } catch (Exception e) diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 00bbaac8..d1af1d09 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -63,7 +63,6 @@ public class ItemSwapContainer continue; } - if( writeType == WriteType.UseSwaps && file.SwapToModdedExistsInGame && !file.DataWasChanged ) { convertedSwaps.TryAdd( file.SwapFromRequestPath, file.SwapToModded ); @@ -73,7 +72,7 @@ public class ItemSwapContainer var path = file.GetNewPath( directory.FullName ); var bytes = file.FileData.Write(); Directory.CreateDirectory( Path.GetDirectoryName( path )! ); - File.WriteAllBytes( path, bytes ); + _manager.Compactor.WriteAllBytes( path, bytes ); convertedFiles.TryAdd( file.SwapFromRequestPath, new FullPath( path ) ); } diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index bbe881b0..45b3f2ec 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -7,6 +7,7 @@ using System.IO; using System.Linq; using Dalamud.Interface.Internal.Notifications; using Penumbra.Import; +using Penumbra.Mods.Editor; namespace Penumbra.Mods.Manager; @@ -57,7 +58,7 @@ public class ModImportManager : IDisposable if (files.Length == 0) return; - _import = new TexToolsImporter(files.Length, files, AddNewMod, _config, _modEditor, _modManager); + _import = new TexToolsImporter(files.Length, files, AddNewMod, _config, _modEditor, _modManager, _modEditor.Compactor); } public bool Importing diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 8bea52e3..07c7394c 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin; using Microsoft.Extensions.DependencyInjection; using OtterGui.Classes; +using OtterGui.Compression; using OtterGui.Log; using Penumbra.Api; using Penumbra.Collections.Cache; @@ -62,7 +63,8 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddGameData(this IServiceCollection services) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index d0e9504c..8ed59fed 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -9,6 +9,7 @@ using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Classes; +using OtterGui.Compression; using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.GameData.Files; @@ -18,15 +19,16 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; -public class FileEditor : IDisposable where T : class, IWritable +public class FileEditor : IDisposable where T : class, IWritable { private readonly FileDialogService _fileDialog; - private readonly IDataManager _gameData; + private readonly IDataManager _gameData; private readonly ModEditWindow _owner; + private readonly FileCompactor _compactor; - public FileEditor(ModEditWindow owner, IDataManager gameData, Configuration config, FileDialogService fileDialog, string tabName, - string fileType, Func> getFiles, Func drawEdit, Func getInitialPath, - Func parseFile) + public FileEditor(ModEditWindow owner, IDataManager gameData, Configuration config, FileCompactor compactor, FileDialogService fileDialog, + string tabName, string fileType, Func> getFiles, Func drawEdit, Func getInitialPath, + Func parseFile) { _owner = owner; _gameData = gameData; @@ -36,6 +38,7 @@ public class FileEditor : IDisposable where T : class, IWritable _drawEdit = drawEdit; _getInitialPath = getInitialPath; _parseFile = parseFile; + _compactor = compactor; _combo = new Combo(config, getFiles); } @@ -60,19 +63,19 @@ public class FileEditor : IDisposable where T : class, IWritable DrawFilePanel(); } - public void Dispose() - { - (_currentFile as IDisposable)?.Dispose(); + public void Dispose() + { + (_currentFile as IDisposable)?.Dispose(); _currentFile = null; (_defaultFile as IDisposable)?.Dispose(); _defaultFile = null; - } - - private readonly string _tabName; - private readonly string _fileType; - private readonly Func _drawEdit; - private readonly Func _getInitialPath; - private readonly Func _parseFile; + } + + private readonly string _tabName; + private readonly string _fileType; + private readonly Func _drawEdit; + private readonly Func _getInitialPath; + private readonly Func _parseFile; private FileRegistry? _currentPath; private T? _currentFile; @@ -107,9 +110,9 @@ public class FileEditor : IDisposable where T : class, IWritable if (file != null) { _defaultException = null; - (_defaultFile as IDisposable)?.Dispose(); - _defaultFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. - _defaultFile = _parseFile(file.Data, _defaultPath, false); + (_defaultFile as IDisposable)?.Dispose(); + _defaultFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. + _defaultFile = _parseFile(file.Data, _defaultPath, false); } else { @@ -135,7 +138,7 @@ public class FileEditor : IDisposable where T : class, IWritable try { - File.WriteAllBytes(name, _defaultFile?.Write() ?? throw new Exception("File invalid.")); + _compactor.WriteAllBytes(name, _defaultFile?.Write() ?? throw new Exception("File invalid.")); } catch (Exception e) { @@ -168,9 +171,9 @@ public class FileEditor : IDisposable where T : class, IWritable { _currentException = null; _currentPath = null; - (_currentFile as IDisposable)?.Dispose(); - _currentFile = null; - _changed = false; + (_currentFile as IDisposable)?.Dispose(); + _currentFile = null; + _changed = false; } private void DrawFileSelectCombo() @@ -192,13 +195,13 @@ public class FileEditor : IDisposable where T : class, IWritable try { var bytes = File.ReadAllBytes(_currentPath.File.FullName); - (_currentFile as IDisposable)?.Dispose(); - _currentFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. - _currentFile = _parseFile(bytes, _currentPath.File.FullName, true); + (_currentFile as IDisposable)?.Dispose(); + _currentFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. + _currentFile = _parseFile(bytes, _currentPath.File.FullName, true); } catch (Exception e) { - (_currentFile as IDisposable)?.Dispose(); + (_currentFile as IDisposable)?.Dispose(); _currentFile = null; _currentException = e; } @@ -209,7 +212,7 @@ public class FileEditor : IDisposable where T : class, IWritable if (ImGuiUtil.DrawDisabledButton("Save to File", Vector2.Zero, $"Save the selected {_fileType} file with all changes applied. This is not revertible.", !_changed)) { - File.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); + _compactor.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); _changed = false; } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 102a6778..84779570 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -195,7 +195,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), iconSize, "Save the changed mdl file.\nUse at own risk!", !info.Changed, true)) - info.Save(); + info.Save(_editor.Compactor); ImGui.TableNextColumn(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), iconSize, diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 3e81901b..fd4c082e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -13,6 +13,7 @@ using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 29647c53..88ed10df 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -11,6 +11,7 @@ using OtterGui.Raii; using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -72,7 +73,7 @@ public partial class ModEditWindow try { - File.WriteAllBytes(name, writable!.Write()); + _editor.Compactor.WriteAllBytes(name, writable!.Write()); } catch (Exception e) { @@ -194,7 +195,7 @@ public partial class ModEditWindow var directory = Path.GetDirectoryName(_targetPath); if (directory != null) Directory.CreateDirectory(directory); - File.WriteAllBytes(_targetPath!, _file!.Write()); + _editor.Compactor.WriteAllBytes(_targetPath!, _file!.Write()); _editor.FileEditor.Revert(_editor.Mod!, _editor.Option!); var fileRegistry = _editor.Files.Available.First(file => file.File.FullName == _targetPath); _editor.FileEditor.AddPathsToSelected(_editor.Option!, new[] diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 890abfed..6e1b1d24 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -12,6 +12,7 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; +using OtterGui.Compression; using OtterGui.Raii; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -22,6 +23,7 @@ using Penumbra.Interop.ResourceTree; using Penumbra.Interop.Services; using Penumbra.Meta; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.String; @@ -236,7 +238,7 @@ public partial class ModEditWindow : Window, IDisposable var anyChanges = editor.MdlMaterialEditor.ModelFiles.Any(m => m.Changed); if (ImGuiUtil.DrawDisabledButton("Save All Changes", buttonSize, anyChanges ? "Irreversibly rewrites all currently applied changes to model files." : "No changes made yet.", !anyChanges)) - editor.MdlMaterialEditor.SaveAllModels(); + editor.MdlMaterialEditor.SaveAllModels(editor.Compactor); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Revert All Changes", buttonSize, @@ -572,17 +574,18 @@ public partial class ModEditWindow : Window, IDisposable _textures = textures; _fileDialog = fileDialog; _gameEvents = gameEvents; - _materialTab = new FileEditor(this, gameData, config, _fileDialog, "Materials", ".mtrl", + _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); - _modelTab = new FileEditor(this, gameData, config, _fileDialog, "Models", ".mdl", + _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", () => _editor.Files.Mdl, DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlFile(bytes)); - _shaderPackageTab = new FileEditor(this, gameData, config, _fileDialog, "Shaders", ".shpk", + _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => _editor.Files.Shpk, DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); - _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); + _quickImportViewer = + new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ModEditWindow); } diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index c629de5b..0e239b7f 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -138,7 +138,7 @@ public class ModPanelEditTab : ITab _editor.LoadMod(_mod); _editor.MdlMaterialEditor.ReplaceAllMaterials("bibo", "b"); _editor.MdlMaterialEditor.ReplaceAllMaterials("bibopube", "c"); - _editor.MdlMaterialEditor.SaveAllModels(); + _editor.MdlMaterialEditor.SaveAllModels(_editor.Compactor); _editWindow.UpdateModels(); } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index ac834e7c..7f27e6ee 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -7,6 +7,7 @@ using Dalamud.Interface.Components; using Dalamud.Utility; using ImGuiNET; using OtterGui; +using OtterGui.Compression; using OtterGui.Custom; using OtterGui.Raii; using OtterGui.Widgets; @@ -39,6 +40,7 @@ public class SettingsTab : ITab private readonly DalamudServices _dalamud; private readonly HttpApi _httpApi; private readonly DalamudSubstitutionProvider _dalamudSubstitutionProvider; + private readonly FileCompactor _compactor; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -46,7 +48,7 @@ public class SettingsTab : ITab public SettingsTab(Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, DalamudServices dalamud, ModExportManager modExportManager, HttpApi httpApi, - DalamudSubstitutionProvider dalamudSubstitutionProvider) + DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor) { _config = config; _fontReloader = fontReloader; @@ -61,6 +63,9 @@ public class SettingsTab : ITab _modExportManager = modExportManager; _httpApi = httpApi; _dalamudSubstitutionProvider = dalamudSubstitutionProvider; + _compactor = compactor; + if (_compactor.CanCompact) + _compactor.Enabled = _config.UseFileSystemCompression; } public void DrawHeader() @@ -661,6 +666,7 @@ public class SettingsTab : ITab Checkbox("Auto Deduplicate on Import", "Automatically deduplicate mod files on import. This will make mod file sizes smaller, but deletes (binary identical) files.", _config.AutoDeduplicateOnImport, v => _config.AutoDeduplicateOnImport = v); + DrawCompressionBox(); Checkbox("Keep Default Metadata Changes on Import", "Normally, metadata changes that equal their default values, which are sometimes exported by TexTools, are discarded. " + "Toggle this to keep them, for example if an option in a mod is supposed to disable a metadata change from a prior option.", @@ -673,6 +679,47 @@ public class SettingsTab : ITab ImGui.NewLine(); } + private void DrawCompressionBox() + { + if (!_compactor.CanCompact) + return; + + Checkbox("Use Filesystem Compression", + "Use Windows functionality to transparently reduce storage size of mod files on your computer. This might cost performance, but seems to generally be beneficial to performance by shifting more responsibility to the underused CPU and away from the overused hard drives.", + _config.UseFileSystemCompression, + v => + { + _config.UseFileSystemCompression = v; + _compactor.Enabled = v; + }); + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton("Compress Existing Files", Vector2.Zero, + "Try to compress all files in your root directory. This will take a while.", + _compactor.MassCompactRunning || !_modManager.Valid)) + _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K); + + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton("Decompress Existing Files", Vector2.Zero, + "Try to decompress all files in your root directory. This will take a while.", + _compactor.MassCompactRunning || !_modManager.Valid)) + _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.None); + + if (_compactor.MassCompactRunning) + { + ImGui.ProgressBar((float)_compactor.CurrentIndex / _compactor.TotalFiles, + new Vector2(ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - UiHelpers.IconButtonSize.X, ImGui.GetFrameHeight()), + _compactor.CurrentFile?.FullName[(_modManager.BasePath.FullName.Length + 1)..] ?? "Gathering Files..."); + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Ban.ToIconString(), UiHelpers.IconButtonSize, "Cancel the mass action.", + !_compactor.MassCompactRunning, true)) + _compactor.CancelMassCompact(); + } + else + { + ImGui.Dummy(UiHelpers.IconButtonSize); + } + } + /// Draw two integral inputs for minimum dimensions of this window. private void DrawMinimumDimensionConfig() { From 470c1317ed11d247a22db2ab77a4109b58aa5959 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 14 Sep 2023 15:26:36 +0000 Subject: [PATCH 0093/1381] [CI] Updating repo.json for testing_0.7.3.10 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 67cb1832..4eafa05f 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.9", + "TestingAssemblyVersion": "0.7.3.10", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.10/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From c5ef7bf46cd9ceb6288912b8c4c2a83627c0982f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 15 Sep 2023 01:06:38 +0200 Subject: [PATCH 0094/1381] Add Compacting to API AddMod. --- OtterGui | 2 +- Penumbra/Api/PenumbraApi.cs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index e3e3f42f..ee64ae2d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit e3e3f42f093b53ad02694810398df5736174d711 +Subproject commit ee64ae2d2710aea45365dafa3c91a721e59ae8fc diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 9d578190..5ac53210 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -15,6 +15,7 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Compression; using Penumbra.Api.Enums; using Penumbra.GameData.Actors; using Penumbra.Interop.ResourceLoading; @@ -637,6 +638,8 @@ public class PenumbraApi : IDisposable, IPenumbraApi return PenumbraApiEc.FileMissing; _modManager.AddMod(dir); + if (_config.UseFileSystemCompression) + new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K); return PenumbraApiEc.Success; } From 652b2e99d25239fe2fc0f6d0939531808d92cf8a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 15 Sep 2023 01:06:53 +0200 Subject: [PATCH 0095/1381] Add key checks to restoring from backup or deleting backups. --- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 0e239b7f..bd5a62c4 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -30,6 +30,7 @@ public class ModPanelEditTab : ITab private readonly ModFileSystemSelector _selector; private readonly ModEditWindow _editWindow; private readonly ModEditor _editor; + private readonly Configuration _config; private readonly TagButtons _modTags = new(); @@ -39,7 +40,7 @@ public class ModPanelEditTab : ITab private Mod _mod = null!; public ModPanelEditTab(ModManager modManager, ModFileSystemSelector selector, ModFileSystem fileSystem, ChatService chat, - ModEditWindow editWindow, ModEditor editor, FilenameService filenames, ModExportManager modExportManager) + ModEditWindow editWindow, ModEditor editor, FilenameService filenames, ModExportManager modExportManager, Configuration config) { _modManager = modManager; _selector = selector; @@ -49,6 +50,7 @@ public class ModPanelEditTab : ITab _editor = editor; _filenames = filenames; _modExportManager = modExportManager; + _config = config; } public ReadOnlySpan Label @@ -162,17 +164,27 @@ public class ModPanelEditTab : ITab ImGui.SameLine(); tt = backup.Exists - ? $"Delete existing mod export \"{backup.Name}\"." + ? $"Delete existing mod export \"{backup.Name}\" (hold {_config.DeleteModModifier} while clicking)." : $"Exported mod \"{backup.Name}\" does not exist."; - if (ImGuiUtil.DrawDisabledButton("Delete Export", buttonSize, tt, !backup.Exists)) + if (ImGuiUtil.DrawDisabledButton("Delete Export", buttonSize, tt, !backup.Exists || !_config.DeleteModModifier.IsActive())) backup.Delete(); tt = backup.Exists - ? $"Restore mod from exported file \"{backup.Name}\"." + ? $"Restore mod from exported file \"{backup.Name}\" (hold {_config.DeleteModModifier} while clicking)." : $"Exported mod \"{backup.Name}\" does not exist."; ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Restore From Export", buttonSize, tt, !backup.Exists)) + if (ImGuiUtil.DrawDisabledButton("Restore From Export", buttonSize, tt, !backup.Exists || !_config.DeleteModModifier.IsActive())) backup.Restore(_modManager); + if (backup.Exists) + { + ImGui.SameLine(); + using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + { + ImGui.TextUnformatted(FontAwesomeIcon.CheckCircle.ToIconString()); + } + + ImGuiUtil.HoverTooltip($"Export exists in \"{backup.Name}\"."); + } } /// Anything about editing the regular meta information about the mod. From 28c2af4266b90bab8d281b95d34fceb4d9682289 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 15 Sep 2023 13:38:47 +0200 Subject: [PATCH 0096/1381] Material Editor: Split ColorTable apart from ColorSet --- Penumbra.GameData | 2 +- ...reviewer.cs => LiveColorTablePreviewer.cs} | 47 ++-- Penumbra/Interop/Structs/CharacterBaseExt.cs | 2 +- ... => ModEditWindow.Materials.ColorTable.cs} | 226 +++++++++--------- .../ModEditWindow.Materials.MtrlTab.cs | 121 +++++----- .../AdvancedWindow/ModEditWindow.Materials.cs | 11 +- 6 files changed, 195 insertions(+), 214 deletions(-) rename Penumbra/Interop/MaterialPreview/{LiveColorSetPreviewer.cs => LiveColorTablePreviewer.cs} (62%) rename Penumbra/UI/AdvancedWindow/{ModEditWindow.Materials.ColorSet.cs => ModEditWindow.Materials.ColorTable.cs} (65%) diff --git a/Penumbra.GameData b/Penumbra.GameData index 635d4c72..862add38 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 635d4c72e84da65a20a2d22d758dd8061bd8babf +Subproject commit 862add38110116b9bb266b739489456a2dd699c0 diff --git a/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs similarity index 62% rename from Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs rename to Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index f927aa43..c9505091 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorSetPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -1,5 +1,4 @@ using System; -using System.Threading; using Dalamud.Game; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; @@ -9,24 +8,24 @@ using Penumbra.Interop.SafeHandles; namespace Penumbra.Interop.MaterialPreview; -public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase +public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase { public const int TextureWidth = 4; - public const int TextureHeight = MtrlFile.ColorSet.RowArray.NumRows; + public const int TextureHeight = MtrlFile.ColorTable.NumRows; public const int TextureLength = TextureWidth * TextureHeight * 4; private readonly Framework _framework; - private readonly Texture** _colorSetTexture; - private readonly SafeTextureHandle _originalColorSetTexture; + private readonly Texture** _colorTableTexture; + private readonly SafeTextureHandle _originalColorTableTexture; - private Half[] _colorSet; + private Half[] _colorTable; private bool _updatePending; - public Half[] ColorSet - => _colorSet; + public Half[] ColorTable + => _colorTable; - public LiveColorSetPreviewer(IObjectTable objects, Framework framework, MaterialInfo materialInfo) + public LiveColorTablePreviewer(IObjectTable objects, Framework framework, MaterialInfo materialInfo) : base(objects, materialInfo) { _framework = framework; @@ -35,17 +34,17 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase if (mtrlHandle == null) throw new InvalidOperationException("Material doesn't have a resource handle"); - var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; + var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorTableTextures; if (colorSetTextures == null) - throw new InvalidOperationException("Draw object doesn't have color set textures"); + throw new InvalidOperationException("Draw object doesn't have color table textures"); - _colorSetTexture = colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); + _colorTableTexture = colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); - _originalColorSetTexture = new SafeTextureHandle(*_colorSetTexture, true); - if (_originalColorSetTexture == null) - throw new InvalidOperationException("Material doesn't have a color set"); + _originalColorTableTexture = new SafeTextureHandle(*_colorTableTexture, true); + if (_originalColorTableTexture == null) + throw new InvalidOperationException("Material doesn't have a color table"); - _colorSet = new Half[TextureLength]; + _colorTable = new Half[TextureLength]; _updatePending = true; framework.Update += OnFrameworkUpdate; @@ -58,9 +57,9 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase base.Clear(disposing, reset); if (reset) - _originalColorSetTexture.Exchange(ref *(nint*)_colorSetTexture); + _originalColorTableTexture.Exchange(ref *(nint*)_colorTableTexture); - _originalColorSetTexture.Dispose(); + _originalColorTableTexture.Dispose(); } public void ScheduleUpdate() @@ -87,16 +86,16 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase return; bool success; - lock (_colorSet) + lock (_colorTable) { - fixed (Half* colorSet = _colorSet) + fixed (Half* colorTable = _colorTable) { - success = Structs.TextureUtility.InitializeContents(texture.Texture, colorSet); + success = Structs.TextureUtility.InitializeContents(texture.Texture, colorTable); } } if (success) - texture.Exchange(ref *(nint*)_colorSetTexture); + texture.Exchange(ref *(nint*)_colorTableTexture); } protected override bool IsStillValid() @@ -104,11 +103,11 @@ public sealed unsafe class LiveColorSetPreviewer : LiveMaterialPreviewerBase if (!base.IsStillValid()) return false; - var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorSetTextures; + var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorTableTextures; if (colorSetTextures == null) return false; - if (_colorSetTexture != colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot)) + if (_colorTableTexture != colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot)) return false; return true; diff --git a/Penumbra/Interop/Structs/CharacterBaseExt.cs b/Penumbra/Interop/Structs/CharacterBaseExt.cs index 3bbbeca9..1bc1c2f3 100644 --- a/Penumbra/Interop/Structs/CharacterBaseExt.cs +++ b/Penumbra/Interop/Structs/CharacterBaseExt.cs @@ -11,5 +11,5 @@ public unsafe struct CharacterBaseExt public CharacterBase CharacterBase; [FieldOffset( 0x258 )] - public Texture** ColorSetTextures; + public Texture** ColorTableTextures; } \ No newline at end of file diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs similarity index 65% rename from Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs rename to Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index e1ba045d..2d868a42 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorSet.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using System.Numerics; using System.Runtime.InteropServices; using Dalamud.Interface; @@ -17,29 +16,28 @@ public partial class ModEditWindow private static readonly float HalfMaxValue = (float)Half.MaxValue; private static readonly float HalfEpsilon = (float)Half.Epsilon; - private bool DrawMaterialColorSetChange(MtrlTab tab, bool disabled) + private bool DrawMaterialColorTableChange(MtrlTab tab, bool disabled) { - if (!tab.SamplerIds.Contains(ShpkFile.TableSamplerId) || !tab.Mtrl.ColorSets.Any(c => c.HasRows)) + if (!tab.SamplerIds.Contains(ShpkFile.TableSamplerId) || !tab.Mtrl.HasTable) return false; ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (!ImGui.CollapsingHeader("Color Set", ImGuiTreeNodeFlags.DefaultOpen)) + if (!ImGui.CollapsingHeader("Color Table", ImGuiTreeNodeFlags.DefaultOpen)) return false; - var hasAnyDye = tab.UseColorDyeSet; - - ColorSetCopyAllClipboardButton(tab.Mtrl, 0); + ColorTableCopyAllClipboardButton(tab.Mtrl); ImGui.SameLine(); - var ret = ColorSetPasteAllClipboardButton(tab, 0, disabled); + var ret = ColorTablePasteAllClipboardButton(tab, disabled); if (!disabled) { ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); - ret |= ColorSetDyeableCheckbox(tab, ref hasAnyDye); + ret |= ColorTableDyeableCheckbox(tab); } - - if (hasAnyDye) + + var hasDyeTable = tab.Mtrl.HasDyeTable; + if (hasDyeTable) { ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); @@ -47,7 +45,7 @@ public partial class ModEditWindow ret |= DrawPreviewDye(tab, disabled); } - using var table = ImRaii.Table("##ColorSets", hasAnyDye ? 11 : 9, + using var table = ImRaii.Table("##ColorTable", hasDyeTable ? 11 : 9, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV); if (!table) return false; @@ -70,7 +68,7 @@ public partial class ModEditWindow ImGui.TableHeader("Repeat"); ImGui.TableNextColumn(); ImGui.TableHeader("Skew"); - if (hasAnyDye) + if (hasDyeTable) { ImGui.TableNextColumn(); ImGui.TableHeader("Dye"); @@ -78,29 +76,25 @@ public partial class ModEditWindow ImGui.TableHeader("Dye Preview"); } - for (var j = 0; j < tab.Mtrl.ColorSets.Length; ++j) + for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) { - using var _ = ImRaii.PushId(j); - for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) - { - ret |= DrawColorSetRow(tab, j, i, disabled, hasAnyDye); - ImGui.TableNextRow(); - } + ret |= DrawColorTableRow(tab, i, disabled); + ImGui.TableNextRow(); } return ret; } - private static void ColorSetCopyAllClipboardButton(MtrlFile file, int colorSetIdx) + private static void ColorTableCopyAllClipboardButton(MtrlFile file) { if (!ImGui.Button("Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2(200, 0))) return; try { - var data1 = file.ColorSets[colorSetIdx].Rows.AsBytes(); - var data2 = file.ColorDyeSets.Length > colorSetIdx ? file.ColorDyeSets[colorSetIdx].Rows.AsBytes() : ReadOnlySpan.Empty; + var data1 = file.Table.AsBytes(); + var data2 = file.HasDyeTable ? file.DyeTable.AsBytes() : ReadOnlySpan.Empty; var array = new byte[data1.Length + data2.Length]; data1.TryCopyTo(array); data2.TryCopyTo(array.AsSpan(data1.Length)); @@ -122,13 +116,13 @@ public partial class ModEditWindow if (ImGuiUtil.DrawDisabledButton("Apply Preview Dye", Vector2.Zero, tt, disabled || dyeId == 0)) { var ret = false; - for (var j = 0; j < tab.Mtrl.ColorDyeSets.Length; ++j) + if (tab.Mtrl.HasDyeTable) { - for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) - ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, j, i, dyeId); + for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) + ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId); } - tab.UpdateColorSetPreview(); + tab.UpdateColorTablePreview(); return ret; } @@ -136,40 +130,40 @@ public partial class ModEditWindow ImGui.SameLine(); var label = dyeId == 0 ? "Preview Dye###previewDye" : $"{name} (Preview)###previewDye"; if (_stainService.StainCombo.Draw(label, dyeColor, string.Empty, true, gloss)) - tab.UpdateColorSetPreview(); + tab.UpdateColorTablePreview(); return false; } - private static unsafe bool ColorSetPasteAllClipboardButton(MtrlTab tab, int colorSetIdx, bool disabled) + private static unsafe bool ColorTablePasteAllClipboardButton(MtrlTab tab, bool disabled) { if (!ImGuiUtil.DrawDisabledButton("Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2(200, 0), string.Empty, disabled) - || tab.Mtrl.ColorSets.Length <= colorSetIdx) + || !tab.Mtrl.HasTable) return false; try { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - if (data.Length < Marshal.SizeOf()) + if (data.Length < Marshal.SizeOf()) return false; - ref var rows = ref tab.Mtrl.ColorSets[colorSetIdx].Rows; + ref var rows = ref tab.Mtrl.Table; fixed (void* ptr = data, output = &rows) { - MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); - if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() - && tab.Mtrl.ColorDyeSets.Length > colorSetIdx) + MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); + if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() + && tab.Mtrl.HasDyeTable) { - ref var dyeRows = ref tab.Mtrl.ColorDyeSets[colorSetIdx].Rows; + ref var dyeRows = ref tab.Mtrl.DyeTable; fixed (void* output2 = &dyeRows) { - MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), - Marshal.SizeOf()); + MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), + Marshal.SizeOf()); } } } - tab.UpdateColorSetPreview(); + tab.UpdateColorTablePreview(); return true; } @@ -179,7 +173,7 @@ public partial class ModEditWindow } } - private static unsafe void ColorSetCopyClipboardButton(MtrlFile.ColorSet.Row row, MtrlFile.ColorDyeSet.Row dye) + private static unsafe void ColorTableCopyClipboardButton(MtrlFile.ColorTable.Row row, MtrlFile.ColorDyeTable.Row dye) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, "Export this row to your clipboard.", false, true)) @@ -187,11 +181,11 @@ public partial class ModEditWindow try { - var data = new byte[MtrlFile.ColorSet.Row.Size + 2]; + var data = new byte[MtrlFile.ColorTable.Row.Size + 2]; fixed (byte* ptr = data) { - MemoryUtility.MemCpyUnchecked(ptr, &row, MtrlFile.ColorSet.Row.Size); - MemoryUtility.MemCpyUnchecked(ptr + MtrlFile.ColorSet.Row.Size, &dye, 2); + MemoryUtility.MemCpyUnchecked(ptr, &row, MtrlFile.ColorTable.Row.Size); + MemoryUtility.MemCpyUnchecked(ptr + MtrlFile.ColorTable.Row.Size, &dye, 2); } var text = Convert.ToBase64String(data); @@ -203,22 +197,21 @@ public partial class ModEditWindow } } - private static bool ColorSetDyeableCheckbox(MtrlTab tab, ref bool dyeable) - { - var ret = ImGui.Checkbox("Dyeable", ref dyeable); + private static bool ColorTableDyeableCheckbox(MtrlTab tab) + { + var dyeable = tab.Mtrl.HasDyeTable; + var ret = ImGui.Checkbox("Dyeable", ref dyeable); if (ret) { - tab.UseColorDyeSet = dyeable; - if (dyeable) - tab.Mtrl.FindOrAddColorDyeSet(); - tab.UpdateColorSetPreview(); + tab.Mtrl.HasDyeTable = dyeable; + tab.UpdateColorTablePreview(); } return ret; } - private static unsafe bool ColorSetPasteFromClipboardButton(MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled) + private static unsafe bool ColorTablePasteFromClipboardButton(MtrlTab tab, int rowIdx, bool disabled) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, "Import an exported row from your clipboard onto this row.", disabled, true)) @@ -228,18 +221,18 @@ public partial class ModEditWindow { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - if (data.Length != MtrlFile.ColorSet.Row.Size + 2 - || tab.Mtrl.ColorSets.Length <= colorSetIdx) + if (data.Length != MtrlFile.ColorTable.Row.Size + 2 + || !tab.Mtrl.HasTable) return false; fixed (byte* ptr = data) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx] = *(MtrlFile.ColorSet.Row*)ptr; - if (colorSetIdx < tab.Mtrl.ColorDyeSets.Length) - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx] = *(MtrlFile.ColorDyeSet.Row*)(ptr + MtrlFile.ColorSet.Row.Size); + tab.Mtrl.Table[rowIdx] = *(MtrlFile.ColorTable.Row*)ptr; + if (tab.Mtrl.HasDyeTable) + tab.Mtrl.DyeTable[rowIdx] = *(MtrlFile.ColorDyeTable.Row*)(ptr + MtrlFile.ColorTable.Row.Size); } - tab.UpdateColorSetRowPreview(rowIdx); + tab.UpdateColorTableRowPreview(rowIdx); return true; } @@ -249,18 +242,18 @@ public partial class ModEditWindow } } - private static void ColorSetHighlightButton(MtrlTab tab, int rowIdx, bool disabled) + private static void ColorTableHighlightButton(MtrlTab tab, int rowIdx, bool disabled) { ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Crosshairs.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Highlight this row on your character, if possible.", disabled || tab.ColorSetPreviewers.Count == 0, true); + "Highlight this row on your character, if possible.", disabled || tab.ColorTablePreviewers.Count == 0, true); if (ImGui.IsItemHovered()) - tab.HighlightColorSetRow(rowIdx); - else if (tab.HighlightedColorSetRow == rowIdx) - tab.CancelColorSetHighlight(); + tab.HighlightColorTableRow(rowIdx); + else if (tab.HighlightedColorTableRow == rowIdx) + tab.CancelColorTableHighlight(); } - private bool DrawColorSetRow(MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, bool hasAnyDye) + private bool DrawColorTableRow(MtrlTab tab, int rowIdx, bool disabled) { static bool FixFloat(ref float val, float current) { @@ -269,17 +262,17 @@ public partial class ModEditWindow } using var id = ImRaii.PushId(rowIdx); - var row = tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx]; - var hasDye = hasAnyDye && tab.Mtrl.ColorDyeSets.Length > colorSetIdx; - var dye = hasDye ? tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx] : new MtrlFile.ColorDyeSet.Row(); + ref var row = ref tab.Mtrl.Table[rowIdx]; + var hasDye = tab.Mtrl.HasDyeTable; + ref var dye = ref tab.Mtrl.DyeTable[rowIdx]; var floatSize = 70 * UiHelpers.Scale; var intSize = 45 * UiHelpers.Scale; ImGui.TableNextColumn(); - ColorSetCopyClipboardButton(row, dye); + ColorTableCopyClipboardButton(row, dye); ImGui.SameLine(); - var ret = ColorSetPasteFromClipboardButton(tab, colorSetIdx, rowIdx, disabled); + var ret = ColorTablePasteFromClipboardButton(tab, rowIdx, disabled); ImGui.SameLine(); - ColorSetHighlightButton(tab, rowIdx, disabled); + ColorTableHighlightButton(tab, rowIdx, disabled); ImGui.TableNextColumn(); ImGui.TextUnformatted($"#{rowIdx + 1:D2}"); @@ -288,8 +281,8 @@ public partial class ModEditWindow using var dis = ImRaii.Disabled(disabled); ret |= ColorPicker("##Diffuse", "Diffuse Color", row.Diffuse, c => { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].Diffuse = c; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.Table[rowIdx].Diffuse = c; + tab.UpdateColorTableRowPreview(rowIdx); }); if (hasDye) { @@ -297,25 +290,25 @@ public partial class ModEditWindow ret |= ImGuiUtil.Checkbox("##dyeDiffuse", "Apply Diffuse Color on Dye", dye.Diffuse, b => { - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Diffuse = b; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.DyeTable[rowIdx].Diffuse = b; + tab.UpdateColorTableRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled); } ImGui.TableNextColumn(); ret |= ColorPicker("##Specular", "Specular Color", row.Specular, c => { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].Specular = c; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.Table[rowIdx].Specular = c; + tab.UpdateColorTableRowPreview(rowIdx); }); ImGui.SameLine(); var tmpFloat = row.SpecularStrength; ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.1f, 0f, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.SpecularStrength)) + if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.01f, 0f, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.SpecularStrength)) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].SpecularStrength = tmpFloat; - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.SpecularStrength = tmpFloat; + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Specular Strength", ImGuiHoveredFlags.AllowWhenDisabled); @@ -326,23 +319,23 @@ public partial class ModEditWindow ret |= ImGuiUtil.Checkbox("##dyeSpecular", "Apply Specular Color on Dye", dye.Specular, b => { - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Specular = b; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.DyeTable[rowIdx].Specular = b; + tab.UpdateColorTableRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled); ImGui.SameLine(); ret |= ImGuiUtil.Checkbox("##dyeSpecularStrength", "Apply Specular Strength on Dye", dye.SpecularStrength, b => { - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].SpecularStrength = b; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.DyeTable[rowIdx].SpecularStrength = b; + tab.UpdateColorTableRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled); } ImGui.TableNextColumn(); ret |= ColorPicker("##Emissive", "Emissive Color", row.Emissive, c => { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].Emissive = c; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.Table[rowIdx].Emissive = c; + tab.UpdateColorTableRowPreview(rowIdx); }); if (hasDye) { @@ -350,8 +343,8 @@ public partial class ModEditWindow ret |= ImGuiUtil.Checkbox("##dyeEmissive", "Apply Emissive Color on Dye", dye.Emissive, b => { - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Emissive = b; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.DyeTable[rowIdx].Emissive = b; + tab.UpdateColorTableRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled); } @@ -361,9 +354,9 @@ public partial class ModEditWindow if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), HalfEpsilon, HalfMaxValue, "%.1f") && FixFloat(ref tmpFloat, row.GlossStrength)) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].GlossStrength = Math.Max(tmpFloat, HalfEpsilon); - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.GlossStrength = Math.Max(tmpFloat, HalfEpsilon); + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Gloss Strength", ImGuiHoveredFlags.AllowWhenDisabled); @@ -373,8 +366,8 @@ public partial class ModEditWindow ret |= ImGuiUtil.Checkbox("##dyeGloss", "Apply Gloss Strength on Dye", dye.Gloss, b => { - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Gloss = b; - tab.UpdateColorSetRowPreview(rowIdx); + tab.Mtrl.DyeTable[rowIdx].Gloss = b; + tab.UpdateColorTableRowPreview(rowIdx); }, ImGuiHoveredFlags.AllowWhenDisabled); } @@ -383,9 +376,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(intSize); if (ImGui.DragInt("##TileSet", ref tmpInt, 0.25f, 0, 63) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].TileSet = (ushort)Math.Clamp(tmpInt, 0, 63); - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.TileSet = (ushort)Math.Clamp(tmpInt, 0, 63); + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Tile Set", ImGuiHoveredFlags.AllowWhenDisabled); @@ -396,9 +389,9 @@ public partial class ModEditWindow if (ImGui.DragFloat("##RepeatX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialRepeat.X)) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Repeat X", ImGuiHoveredFlags.AllowWhenDisabled); @@ -408,9 +401,9 @@ public partial class ModEditWindow if (ImGui.DragFloat("##RepeatY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialRepeat.Y)) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Repeat Y", ImGuiHoveredFlags.AllowWhenDisabled); @@ -420,9 +413,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(floatSize); if (ImGui.DragFloat("##SkewX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.X)) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialSkew = row.MaterialSkew with { X = tmpFloat }; - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.MaterialSkew = row.MaterialSkew with { X = tmpFloat }; + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Skew X", ImGuiHoveredFlags.AllowWhenDisabled); @@ -432,9 +425,9 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(floatSize); if (ImGui.DragFloat("##SkewY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.Y)) { - tab.Mtrl.ColorSets[colorSetIdx].Rows[rowIdx].MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + row.MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Skew Y", ImGuiHoveredFlags.AllowWhenDisabled); @@ -445,27 +438,22 @@ public partial class ModEditWindow if (_stainService.TemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { - tab.Mtrl.ColorDyeSets[colorSetIdx].Rows[rowIdx].Template = _stainService.TemplateCombo.CurrentSelection; - ret = true; - tab.UpdateColorSetRowPreview(rowIdx); + dye.Template = _stainService.TemplateCombo.CurrentSelection; + ret = true; + tab.UpdateColorTableRowPreview(rowIdx); } ImGuiUtil.HoverTooltip("Dye Template", ImGuiHoveredFlags.AllowWhenDisabled); ImGui.TableNextColumn(); - ret |= DrawDyePreview(tab, colorSetIdx, rowIdx, disabled, dye, floatSize); - } - else if (hasAnyDye) - { - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); + ret |= DrawDyePreview(tab, rowIdx, disabled, dye, floatSize); } return ret; } - private bool DrawDyePreview(MtrlTab tab, int colorSetIdx, int rowIdx, bool disabled, MtrlFile.ColorDyeSet.Row dye, float floatSize) + private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, MtrlFile.ColorDyeTable.Row dye, float floatSize) { var stain = _stainService.StainCombo.CurrentSelection.Key; if (stain == 0 || !_stainService.StmFile.Entries.TryGetValue(dye.Template, out var entry)) @@ -477,9 +465,9 @@ public partial class ModEditWindow var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Apply the selected dye to this row.", disabled, true); - ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, colorSetIdx, rowIdx, stain); + ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, rowIdx, stain); if (ret) - tab.UpdateColorSetRowPreview(rowIdx); + tab.UpdateColorTableRowPreview(rowIdx); ImGui.SameLine(); ColorPicker("##diffusePreview", string.Empty, values.Diffuse, _ => { }, "D"); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index aff30fb0..12119742 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -67,7 +67,6 @@ public partial class ModEditWindow public readonly HashSet UnfoldedTextures = new(4); public readonly HashSet SamplerIds = new(16); public float TextureLabelWidth; - public bool UseColorDyeSet; // Material Constants public readonly @@ -75,10 +74,10 @@ public partial class ModEditWindow Constants)> Constants = new(16); // Live-Previewers - public readonly List MaterialPreviewers = new(4); - public readonly List ColorSetPreviewers = new(4); - public int HighlightedColorSetRow = -1; - public readonly Stopwatch HighlightTime = new(); + public readonly List MaterialPreviewers = new(4); + public readonly List ColorTablePreviewers = new(4); + public int HighlightedColorTableRow = -1; + public readonly Stopwatch HighlightTime = new(); public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) { @@ -286,7 +285,7 @@ public partial class ModEditWindow if (AssociatedShpk == null) { SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.ColorSets.Any(c => c.HasRows)) + if (Mtrl.HasTable) SamplerIds.Add(TableSamplerId); foreach (var (sampler, index) in Mtrl.ShaderPackage.Samplers.WithIndex()) @@ -301,7 +300,7 @@ public partial class ModEditWindow if (!ShadersKnown) { SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.ColorSets.Any(c => c.HasRows)) + if (Mtrl.HasTable) SamplerIds.Add(TableSamplerId); } @@ -320,7 +319,7 @@ public partial class ModEditWindow } if (SamplerIds.Contains(TableSamplerId)) - Mtrl.FindOrAddColorSet(); + Mtrl.HasTable = true; } Textures.Sort((x, y) => string.CompareOrdinal(x.Label, y.Label)); @@ -483,18 +482,16 @@ public partial class ModEditWindow } } - UpdateMaterialPreview(); - - var colorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); - - if (!colorSet.HasValue) + UpdateMaterialPreview(); + + if (!Mtrl.HasTable) return; foreach (var materialInfo in instances) { try { - ColorSetPreviewers.Add(new LiveColorSetPreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, materialInfo)); + ColorTablePreviewers.Add(new LiveColorTablePreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, materialInfo)); } catch (InvalidOperationException) { @@ -502,7 +499,7 @@ public partial class ModEditWindow } } - UpdateColorSetPreview(); + UpdateColorTablePreview(); } private void UnbindFromMaterialInstances() @@ -511,9 +508,9 @@ public partial class ModEditWindow previewer.Dispose(); MaterialPreviewers.Clear(); - foreach (var previewer in ColorSetPreviewers) + foreach (var previewer in ColorTablePreviewers) previewer.Dispose(); - ColorSetPreviewers.Clear(); + ColorTablePreviewers.Clear(); } private unsafe void UnbindFromDrawObjectMaterialInstances(nint characterBase) @@ -528,14 +525,14 @@ public partial class ModEditWindow MaterialPreviewers.RemoveAt(i); } - for (var i = ColorSetPreviewers.Count; i-- > 0;) + for (var i = ColorTablePreviewers.Count; i-- > 0;) { - var previewer = ColorSetPreviewers[i]; + var previewer = ColorTablePreviewers[i]; if ((nint)previewer.DrawObject != characterBase) continue; previewer.Dispose(); - ColorSetPreviewers.RemoveAt(i); + ColorTablePreviewers.RemoveAt(i); } } @@ -571,103 +568,94 @@ public partial class ModEditWindow SetSamplerFlags(sampler.SamplerId, sampler.Flags); } - public void HighlightColorSetRow(int rowIdx) + public void HighlightColorTableRow(int rowIdx) { - var oldRowIdx = HighlightedColorSetRow; + var oldRowIdx = HighlightedColorTableRow; - if (HighlightedColorSetRow != rowIdx) + if (HighlightedColorTableRow != rowIdx) { - HighlightedColorSetRow = rowIdx; + HighlightedColorTableRow = rowIdx; HighlightTime.Restart(); } if (oldRowIdx >= 0) - UpdateColorSetRowPreview(oldRowIdx); + UpdateColorTableRowPreview(oldRowIdx); if (rowIdx >= 0) - UpdateColorSetRowPreview(rowIdx); + UpdateColorTableRowPreview(rowIdx); } - public void CancelColorSetHighlight() + public void CancelColorTableHighlight() { - var rowIdx = HighlightedColorSetRow; + var rowIdx = HighlightedColorTableRow; - HighlightedColorSetRow = -1; + HighlightedColorTableRow = -1; HighlightTime.Reset(); if (rowIdx >= 0) - UpdateColorSetRowPreview(rowIdx); + UpdateColorTableRowPreview(rowIdx); } - public void UpdateColorSetRowPreview(int rowIdx) + public void UpdateColorTableRowPreview(int rowIdx) { - if (ColorSetPreviewers.Count == 0) + if (ColorTablePreviewers.Count == 0) + return; + + if (!Mtrl.HasTable) return; - var maybeColorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); - if (!maybeColorSet.HasValue) - return; - - var colorSet = maybeColorSet.Value; - var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); - - var row = colorSet.Rows[rowIdx]; - if (maybeColorDyeSet.HasValue && UseColorDyeSet) + var row = Mtrl.Table[rowIdx]; + if (Mtrl.HasDyeTable) { var stm = _edit._stainService.StmFile; - var dye = maybeColorDyeSet.Value.Rows[rowIdx]; + var dye = Mtrl.DyeTable[rowIdx]; if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) row.ApplyDyeTemplate(dye, dyes); } - if (HighlightedColorSetRow == rowIdx) + if (HighlightedColorTableRow == rowIdx) ApplyHighlight(ref row, (float)HighlightTime.Elapsed.TotalSeconds); - foreach (var previewer in ColorSetPreviewers) + foreach (var previewer in ColorTablePreviewers) { - row.AsHalves().CopyTo(previewer.ColorSet.AsSpan() - .Slice(LiveColorSetPreviewer.TextureWidth * 4 * rowIdx, LiveColorSetPreviewer.TextureWidth * 4)); + row.AsHalves().CopyTo(previewer.ColorTable.AsSpan() + .Slice(LiveColorTablePreviewer.TextureWidth * 4 * rowIdx, LiveColorTablePreviewer.TextureWidth * 4)); previewer.ScheduleUpdate(); } } - public void UpdateColorSetPreview() + public void UpdateColorTablePreview() { - if (ColorSetPreviewers.Count == 0) + if (ColorTablePreviewers.Count == 0) + return; + + if (!Mtrl.HasTable) return; - var maybeColorSet = Mtrl.ColorSets.FirstOrNull(colorSet => colorSet.HasRows); - if (!maybeColorSet.HasValue) - return; - - var colorSet = maybeColorSet.Value; - var maybeColorDyeSet = Mtrl.ColorDyeSets.FirstOrNull(colorDyeSet => colorDyeSet.Index == colorSet.Index); - - var rows = colorSet.Rows; - if (maybeColorDyeSet.HasValue && UseColorDyeSet) + var rows = Mtrl.Table; + if (Mtrl.HasDyeTable) { var stm = _edit._stainService.StmFile; var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; - var colorDyeSet = maybeColorDyeSet.Value; - for (var i = 0; i < MtrlFile.ColorSet.RowArray.NumRows; ++i) + for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) { ref var row = ref rows[i]; - var dye = colorDyeSet.Rows[i]; + var dye = Mtrl.DyeTable[i]; if (stm.TryGetValue(dye.Template, stainId, out var dyes)) row.ApplyDyeTemplate(dye, dyes); } } - if (HighlightedColorSetRow >= 0) - ApplyHighlight(ref rows[HighlightedColorSetRow], (float)HighlightTime.Elapsed.TotalSeconds); + if (HighlightedColorTableRow >= 0) + ApplyHighlight(ref rows[HighlightedColorTableRow], (float)HighlightTime.Elapsed.TotalSeconds); - foreach (var previewer in ColorSetPreviewers) + foreach (var previewer in ColorTablePreviewers) { - rows.AsHalves().CopyTo(previewer.ColorSet); + rows.AsHalves().CopyTo(previewer.ColorTable); previewer.ScheduleUpdate(); } } - private static void ApplyHighlight(ref MtrlFile.ColorSet.Row row, float time) + private static void ApplyHighlight(ref MtrlFile.ColorTable.Row row, float time) { var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; var baseColor = ColorId.InGameHighlight.Value(); @@ -691,7 +679,6 @@ public partial class ModEditWindow Mtrl = file; FilePath = filePath; Writable = writable; - UseColorDyeSet = file.ColorDyeSets.Length > 0; AssociatedBaseDevkit = TryLoadShpkDevkit("_base", out LoadedBaseDevkitPathName); LoadShpk(FindAssociatedShpk(out _, out _)); if (writable) @@ -714,7 +701,7 @@ public partial class ModEditWindow public byte[] Write() { var output = Mtrl.Clone(); - output.GarbageCollect(AssociatedShpk, SamplerIds, UseColorDyeSet); + output.GarbageCollect(AssociatedShpk, SamplerIds); return output.Write(); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 102a6778..02845362 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -25,7 +25,7 @@ public partial class ModEditWindow ret |= DrawMaterialShader(tab, disabled); ret |= DrawMaterialTextureChange(tab, disabled); - ret |= DrawMaterialColorSetChange(tab, disabled); + ret |= DrawMaterialColorTableChange(tab, disabled); ret |= DrawMaterialConstants(tab, disabled); ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); @@ -42,7 +42,7 @@ public partial class ModEditWindow if (ImGui.Button("Reload live preview")) tab.BindToMaterialInstances(); - if (tab.MaterialPreviewers.Count != 0 || tab.ColorSetPreviewers.Count != 0) + if (tab.MaterialPreviewers.Count != 0 || tab.ColorTablePreviewers.Count != 0) return; ImGui.SameLine(); @@ -159,6 +159,13 @@ public partial class ModEditWindow ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); } + using (var sets = ImRaii.TreeNode("Color Sets", ImGuiTreeNodeFlags.DefaultOpen)) + { + if (sets) + foreach (var set in file.ColorSets) + ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); + } + if (file.AdditionalData.Length <= 0) return; From 50d7619dde0641f08d52baf225b5bf37a533f518 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 15 Sep 2023 13:57:39 +0200 Subject: [PATCH 0097/1381] GameData Commit. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 862add38..3aab17bd 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 862add38110116b9bb266b739489456a2dd699c0 +Subproject commit 3aab17bd6a91146bb858cabee928ed214ec4e95c From 916ff0cbb234cb2d0fc88b1d7169aa1d6aba9a54 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 15 Sep 2023 14:00:30 +0200 Subject: [PATCH 0098/1381] Auto Formatting. --- Penumbra/Interop/Structs/CharacterBaseExt.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/Structs/CharacterBaseExt.cs b/Penumbra/Interop/Structs/CharacterBaseExt.cs index 1bc1c2f3..cfd43a21 100644 --- a/Penumbra/Interop/Structs/CharacterBaseExt.cs +++ b/Penumbra/Interop/Structs/CharacterBaseExt.cs @@ -4,12 +4,12 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct CharacterBaseExt { - [FieldOffset( 0x0 )] + [FieldOffset(0x0)] public CharacterBase CharacterBase; - [FieldOffset( 0x258 )] + [FieldOffset(0x258)] public Texture** ColorTableTextures; -} \ No newline at end of file +} From 53adb6fa548c7a687e602ca6fc5d382fac88636b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 15 Sep 2023 14:12:59 +0200 Subject: [PATCH 0099/1381] Use System global usings. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Api/DalamudSubstitutionProvider.cs | 3 --- Penumbra/Api/HttpApi.cs | 2 -- Penumbra/Api/IpcTester.cs | 5 ----- Penumbra/Api/PenumbraApi.cs | 6 ------ Penumbra/Api/PenumbraIpcProviders.cs | 3 --- Penumbra/Api/TempModManager.cs | 2 -- Penumbra/Collections/Cache/CmpCache.cs | 3 --- Penumbra/Collections/Cache/CollectionCache.cs | 6 ------ .../Collections/Cache/CollectionCacheManager.cs | 6 ------ Penumbra/Collections/Cache/CollectionModData.cs | 3 --- Penumbra/Collections/Cache/EqdpCache.cs | 4 ---- Penumbra/Collections/Cache/EqpCache.cs | 3 --- Penumbra/Collections/Cache/EstCache.cs | 2 -- Penumbra/Collections/Cache/GmpCache.cs | 3 --- Penumbra/Collections/Cache/ImcCache.cs | 3 --- Penumbra/Collections/Cache/MetaCache.cs | 3 --- .../Manager/ActiveCollectionMigration.cs | 4 ---- Penumbra/Collections/Manager/ActiveCollections.cs | 4 ---- Penumbra/Collections/Manager/CollectionEditor.cs | 4 ---- Penumbra/Collections/Manager/CollectionStorage.cs | 5 ----- Penumbra/Collections/Manager/CollectionType.cs | 3 --- .../Manager/IndividualCollections.Access.cs | 3 --- .../Manager/IndividualCollections.Files.cs | 3 --- .../Collections/Manager/IndividualCollections.cs | 3 --- Penumbra/Collections/Manager/InheritanceManager.cs | 3 --- .../Collections/Manager/ModCollectionMigration.cs | 2 -- .../Collections/Manager/TempCollectionManager.cs | 3 --- Penumbra/Collections/ModCollection.Cache.Access.cs | 3 --- Penumbra/Collections/ModCollection.cs | 4 ---- Penumbra/Collections/ModCollectionSave.cs | 4 ---- Penumbra/Collections/ResolveData.cs | 2 -- Penumbra/CommandHandler.cs | 3 --- Penumbra/Communication/ChangedItemClick.cs | 1 - Penumbra/Communication/ChangedItemHover.cs | 1 - Penumbra/Communication/CollectionChange.cs | 1 - .../Communication/CollectionInheritanceChanged.cs | 1 - Penumbra/Communication/CreatedCharacterBase.cs | 1 - Penumbra/Communication/CreatingCharacterBase.cs | 1 - Penumbra/Communication/EnabledChanged.cs | 1 - Penumbra/Communication/ModDataChanged.cs | 1 - Penumbra/Communication/ModDirectoryChanged.cs | 1 - Penumbra/Communication/ModDiscoveryFinished.cs | 1 - Penumbra/Communication/ModDiscoveryStarted.cs | 1 - Penumbra/Communication/ModOptionChanged.cs | 1 - Penumbra/Communication/ModPathChanged.cs | 2 -- Penumbra/Communication/ModSettingChanged.cs | 1 - Penumbra/Communication/MtrlShpkLoaded.cs | 3 +-- Penumbra/Communication/PostSettingsPanelDraw.cs | 1 - Penumbra/Communication/PreSettingsPanelDraw.cs | 1 - Penumbra/Communication/ResolvedFileChanged.cs | 1 - Penumbra/Communication/SelectTab.cs | 1 - Penumbra/Communication/TemporaryGlobalModChange.cs | 1 - Penumbra/Configuration.cs | 5 ----- Penumbra/GlobalUsings.cs | 14 ++++++++++++++ Penumbra/Import/Structs/StreamDisposer.cs | 2 -- Penumbra/Import/Structs/TexToolsStructs.cs | 1 - Penumbra/Import/TexToolsImport.cs | 6 ------ Penumbra/Import/TexToolsImporter.Archives.cs | 5 +---- Penumbra/Import/TexToolsImporter.Gui.cs | 2 -- Penumbra/Import/TexToolsImporter.ModPack.cs | 4 ---- Penumbra/Import/TexToolsMeta.Deserialization.cs | 2 -- Penumbra/Import/TexToolsMeta.Export.cs | 4 ---- Penumbra/Import/TexToolsMeta.Rgsp.cs | 2 -- Penumbra/Import/TexToolsMeta.cs | 3 --- Penumbra/Import/Textures/BaseImage.cs | 2 -- .../Textures/CombinedTexture.Manipulation.cs | 5 ----- .../Import/Textures/CombinedTexture.Operations.cs | 4 ---- Penumbra/Import/Textures/CombinedTexture.cs | 5 ----- Penumbra/Import/Textures/RgbaPixelData.cs | 1 - Penumbra/Import/Textures/TexFileParser.cs | 2 -- Penumbra/Import/Textures/Texture.cs | 1 - Penumbra/Import/Textures/TextureDrawer.cs | 5 ----- Penumbra/Import/Textures/TextureManager.cs | 7 ------- .../MaterialPreview/LiveColorTablePreviewer.cs | 1 - .../MaterialPreview/LiveMaterialPreviewer.cs | 1 - .../MaterialPreview/LiveMaterialPreviewerBase.cs | 1 - Penumbra/Interop/MaterialPreview/MaterialInfo.cs | 2 -- .../Interop/PathResolving/AnimationHookService.cs | 2 -- .../Interop/PathResolving/CollectionResolver.cs | 1 - Penumbra/Interop/PathResolving/CutsceneService.cs | 4 ---- Penumbra/Interop/PathResolving/DrawObjectState.cs | 4 ---- .../PathResolving/IdentifiedCollectionCache.cs | 3 --- Penumbra/Interop/PathResolving/MetaState.cs | 2 -- Penumbra/Interop/PathResolving/PathResolver.cs | 1 - Penumbra/Interop/PathResolving/PathState.cs | 4 ---- Penumbra/Interop/PathResolving/ResolvePathHooks.cs | 2 -- Penumbra/Interop/PathResolving/SubfileHelper.cs | 4 ---- .../Interop/ResourceLoading/CreateFileWHook.cs | 3 --- .../Interop/ResourceLoading/FileReadService.cs | 4 ---- Penumbra/Interop/ResourceLoading/ResourceLoader.cs | 4 +--- .../ResourceLoading/ResourceManagerService.cs | 2 -- .../Interop/ResourceLoading/ResourceService.cs | 1 - Penumbra/Interop/ResourceLoading/TexMdlService.cs | 2 -- Penumbra/Interop/ResourceTree/ResolveContext.cs | 4 ---- Penumbra/Interop/ResourceTree/ResourceNode.cs | 2 -- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 -- .../Interop/ResourceTree/ResourceTreeFactory.cs | 2 -- Penumbra/Interop/ResourceTree/TreeBuildCache.cs | 4 ---- Penumbra/Interop/SafeHandles/SafeResourceHandle.cs | 5 +---- Penumbra/Interop/SafeHandles/SafeTextureHandle.cs | 5 +---- Penumbra/Interop/Services/CharacterUtility.cs | 3 --- Penumbra/Interop/Services/DecalReverter.cs | 1 - Penumbra/Interop/Services/GameEventManager.cs | 1 - Penumbra/Interop/Services/MetaList.cs | 2 -- Penumbra/Interop/Services/RedrawService.cs | 3 --- Penumbra/Interop/Services/SkinFixer.cs | 3 --- Penumbra/Interop/Structs/CharacterBaseExt.cs | 1 - Penumbra/Interop/Structs/CharacterUtilityData.cs | 3 --- Penumbra/Interop/Structs/ClipScheduler.cs | 3 --- Penumbra/Interop/Structs/ConstantBuffer.cs | 3 --- Penumbra/Interop/Structs/DrawState.cs | 2 -- Penumbra/Interop/Structs/GetResourceParameters.cs | 2 -- Penumbra/Interop/Structs/HumanExt.cs | 1 - Penumbra/Interop/Structs/Material.cs | 2 -- Penumbra/Interop/Structs/MtrlResource.cs | 2 -- Penumbra/Interop/Structs/RenderModel.cs | 1 - .../Interop/Structs/ResidentResourceManager.cs | 2 -- Penumbra/Interop/Structs/ResourceHandle.cs | 2 -- Penumbra/Interop/Structs/SeFileDescriptor.cs | 2 -- Penumbra/Interop/Structs/ShaderPackageUtility.cs | 2 -- Penumbra/Interop/Structs/VfxParams.cs | 2 -- Penumbra/Meta/Files/CmpFile.cs | 2 -- Penumbra/Meta/Files/EqdpFile.cs | 2 -- Penumbra/Meta/Files/EqpGmpFile.cs | 4 ---- Penumbra/Meta/Files/EstFile.cs | 2 -- Penumbra/Meta/Files/EvpFile.cs | 1 - Penumbra/Meta/Files/ImcFile.cs | 2 -- Penumbra/Meta/Files/MetaBaseFile.cs | 1 - Penumbra/Meta/Manipulations/EqdpManipulation.cs | 2 -- Penumbra/Meta/Manipulations/EqpManipulation.cs | 2 -- Penumbra/Meta/Manipulations/EstManipulation.cs | 2 -- Penumbra/Meta/Manipulations/GmpManipulation.cs | 1 - Penumbra/Meta/Manipulations/ImcManipulation.cs | 2 -- Penumbra/Meta/Manipulations/MetaManipulation.cs | 2 -- Penumbra/Meta/Manipulations/RspManipulation.cs | 2 -- Penumbra/Meta/MetaFileManager.cs | 3 --- Penumbra/Mods/Editor/DuplicateManager.cs | 8 -------- Penumbra/Mods/Editor/FileRegistry.cs | 3 --- Penumbra/Mods/Editor/IMod.cs | 1 - Penumbra/Mods/Editor/MdlMaterialEditor.cs | 4 ---- Penumbra/Mods/Editor/ModBackup.cs | 4 ---- Penumbra/Mods/Editor/ModEditor.cs | 2 -- Penumbra/Mods/Editor/ModFileCollection.cs | 5 ----- Penumbra/Mods/Editor/ModFileEditor.cs | 4 ---- Penumbra/Mods/Editor/ModMerger.cs | 4 ---- Penumbra/Mods/Editor/ModMetaEditor.cs | 3 --- Penumbra/Mods/Editor/ModNormalizer.cs | 5 ----- Penumbra/Mods/Editor/ModSwapEditor.cs | 1 - Penumbra/Mods/Editor/ModelMaterialInfo.cs | 3 --- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 3 --- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 4 ---- Penumbra/Mods/ItemSwap/ItemSwap.cs | 2 -- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 4 ---- Penumbra/Mods/ItemSwap/Swaps.cs | 5 ----- Penumbra/Mods/Manager/ModCacheManager.cs | 5 ----- Penumbra/Mods/Manager/ModDataEditor.cs | 3 --- Penumbra/Mods/Manager/ModExportManager.cs | 2 -- Penumbra/Mods/Manager/ModFileSystem.cs | 4 ---- Penumbra/Mods/Manager/ModImportManager.cs | 5 ----- Penumbra/Mods/Manager/ModManager.cs | 4 ---- Penumbra/Mods/Manager/ModMigration.cs | 4 ---- Penumbra/Mods/Manager/ModOptionEditor.cs | 3 --- Penumbra/Mods/Manager/ModStorage.cs | 3 --- Penumbra/Mods/Mod.cs | 4 ---- Penumbra/Mods/ModCreator.cs | 4 ---- Penumbra/Mods/ModLocalData.cs | 3 --- Penumbra/Mods/ModMeta.cs | 1 - Penumbra/Mods/Subclasses/IModGroup.cs | 3 --- Penumbra/Mods/Subclasses/ISubMod.cs | 2 -- Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs | 5 ----- Penumbra/Mods/Subclasses/ModSettings.cs | 4 ---- Penumbra/Mods/Subclasses/MultiModGroup.cs | 5 ----- Penumbra/Mods/Subclasses/SingleModGroup.cs | 4 ---- Penumbra/Mods/TemporaryMod.cs | 4 ---- Penumbra/Penumbra.cs | 3 --- Penumbra/Services/BackupService.cs | 3 --- Penumbra/Services/ChatService.cs | 1 - Penumbra/Services/CommunicatorService.cs | 1 - Penumbra/Services/ConfigMigrationService.cs | 4 ---- Penumbra/Services/DalamudServices.cs | 2 -- Penumbra/Services/FilenameService.cs | 3 --- Penumbra/Services/SaveService.cs | 1 - Penumbra/Services/ServiceWrapper.cs | 2 -- Penumbra/Services/StainService.cs | 3 --- Penumbra/Services/ValidityChecker.cs | 4 ---- Penumbra/UI/AdvancedWindow/FileEditor.cs | 5 ----- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 5 ----- Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs | 4 ---- .../ModEditWindow.Materials.ColorTable.cs | 3 --- .../ModEditWindow.Materials.ConstantEditor.cs | 3 --- .../ModEditWindow.Materials.MtrlTab.cs | 7 ------- .../AdvancedWindow/ModEditWindow.Materials.Shpk.cs | 3 --- .../UI/AdvancedWindow/ModEditWindow.Materials.cs | 2 -- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 4 ---- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 1 - .../UI/AdvancedWindow/ModEditWindow.QuickImport.cs | 5 ----- .../AdvancedWindow/ModEditWindow.ShaderPackages.cs | 5 ----- .../UI/AdvancedWindow/ModEditWindow.ShpkTab.cs | 2 -- .../UI/AdvancedWindow/ModEditWindow.Textures.cs | 6 ------ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 6 ------ Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 3 --- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 7 +------ Penumbra/UI/ChangedItemDrawer.cs | 4 ---- Penumbra/UI/Changelog.cs | 1 - Penumbra/UI/Classes/CollectionSelectHeader.cs | 3 --- Penumbra/UI/Classes/Colors.cs | 2 -- Penumbra/UI/CollectionTab/CollectionCombo.cs | 2 -- Penumbra/UI/CollectionTab/CollectionPanel.cs | 4 ---- Penumbra/UI/CollectionTab/CollectionSelector.cs | 3 --- .../UI/CollectionTab/IndividualAssignmentUi.cs | 2 -- Penumbra/UI/CollectionTab/InheritanceUi.cs | 4 ---- Penumbra/UI/ConfigWindow.cs | 2 -- Penumbra/UI/FileDialogService.cs | 4 ---- Penumbra/UI/ImportPopup.cs | 2 -- Penumbra/UI/LaunchButton.cs | 2 -- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 5 ----- Penumbra/UI/ModsTab/ModFilter.cs | 2 -- Penumbra/UI/ModsTab/ModPanel.cs | 3 --- Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs | 4 ---- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 2 -- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 2 -- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 1 - Penumbra/UI/ModsTab/ModPanelEditTab.cs | 5 ----- Penumbra/UI/ModsTab/ModPanelHeader.cs | 3 --- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 3 --- Penumbra/UI/ModsTab/ModPanelTabBar.cs | 2 -- Penumbra/UI/ResourceWatcher/Record.cs | 1 - Penumbra/UI/ResourceWatcher/ResourceWatcher.cs | 3 --- .../UI/ResourceWatcher/ResourceWatcherTable.cs | 4 ---- Penumbra/UI/Tabs/ChangedItemsTab.cs | 4 ---- Penumbra/UI/Tabs/CollectionsTab.cs | 2 -- Penumbra/UI/Tabs/ConfigTabBar.cs | 1 - Penumbra/UI/Tabs/DebugTab.cs | 4 ---- Penumbra/UI/Tabs/EffectiveTab.cs | 4 ---- Penumbra/UI/Tabs/ModsTab.cs | 3 --- Penumbra/UI/Tabs/OnScreenTab.cs | 1 - Penumbra/UI/Tabs/ResourceTab.cs | 3 --- Penumbra/UI/Tabs/SettingsTab.cs | 4 ---- Penumbra/UI/TutorialService.cs | 2 -- Penumbra/UI/UiHelpers.cs | 3 --- Penumbra/UI/WindowSystem.cs | 1 - Penumbra/Util/DictionaryExtensions.cs | 4 ---- Penumbra/Util/FixedUlongStringEnumConverter.cs | 1 - Penumbra/Util/PenumbraSqPackStream.cs | 4 ---- 248 files changed, 24 insertions(+), 695 deletions(-) create mode 100644 Penumbra/GlobalUsings.cs diff --git a/OtterGui b/OtterGui index ee64ae2d..21333f3e 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit ee64ae2d2710aea45365dafa3c91a721e59ae8fc +Subproject commit 21333f3e2f3908d4f4c7dbb0b4bff5e5b7d1f64a diff --git a/Penumbra.Api b/Penumbra.Api index 97610e1c..316f3da4 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 97610e1c9d27d863ae8563bb9c8525cc6f8a3709 +Subproject commit 316f3da4a3ce246afe5b98c1568d73fcd7b6b22d diff --git a/Penumbra.GameData b/Penumbra.GameData index 3aab17bd..0507b1f0 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3aab17bd6a91146bb858cabee928ed214ec4e95c +Subproject commit 0507b1f093f5382e03242e5da991752361b70c6e diff --git a/Penumbra.String b/Penumbra.String index 5d9f36c5..0e0c1e1e 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 5d9f36c5b57685b07354460e225e65759ef9996e +Subproject commit 0e0c1e1ee116c259abd00e1d5c3450ad40f92a98 diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index 07da761f..fb966fe8 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Plugin.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index 0d9ef997..e23f8b4f 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading.Tasks; using EmbedIO; using EmbedIO.Routing; using EmbedIO.WebApi; diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index cbd0cc8b..69c2fd3d 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -4,12 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.Mods; -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Numerics; -using System.Threading.Tasks; using Dalamud.Utility; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 5ac53210..1dead7e5 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -7,13 +7,7 @@ using Penumbra.Interop.PathResolving; using Penumbra.Interop.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Compression; using Penumbra.Api.Enums; diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 73f87b94..2d3fcf97 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -1,9 +1,6 @@ using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin; using Penumbra.GameData.Enums; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; using Penumbra.Collections.Manager; diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index 1dd8331f..35aa1217 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -1,8 +1,6 @@ -using System; using Penumbra.Collections; using Penumbra.Meta.Manipulations; using Penumbra.Mods; -using System.Collections.Generic; using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Collections.Manager; diff --git a/Penumbra/Collections/Cache/CmpCache.cs b/Penumbra/Collections/Cache/CmpCache.cs index 9333501a..470cadd4 100644 --- a/Penumbra/Collections/Cache/CmpCache.cs +++ b/Penumbra/Collections/Cache/CmpCache.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using OtterGui.Filesystem; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 1f712124..6f3d59e9 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -2,12 +2,6 @@ using OtterGui; using OtterGui.Classes; using Penumbra.Meta.Manipulations; using Penumbra.Mods; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading; using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.String.Classes; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index abe5bfca..3a94bc89 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -1,10 +1,4 @@ -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Dalamud.Game; using OtterGui.Classes; using Penumbra.Api; diff --git a/Penumbra/Collections/Cache/CollectionModData.cs b/Penumbra/Collections/Cache/CollectionModData.cs index 24f8f297..fcbccc96 100644 --- a/Penumbra/Collections/Cache/CollectionModData.cs +++ b/Penumbra/Collections/Cache/CollectionModData.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.String.Classes; diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index 1b9c8156..a5232dbb 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; using OtterGui; using OtterGui.Filesystem; using Penumbra.GameData.Enums; diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 4e87a34a..9d63479a 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using OtterGui.Filesystem; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index d079a532..43ebcf56 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using OtterGui.Filesystem; using Penumbra.GameData.Enums; using Penumbra.Interop.Services; diff --git a/Penumbra/Collections/Cache/GmpCache.cs b/Penumbra/Collections/Cache/GmpCache.cs index 1c25b9e5..3287eb2d 100644 --- a/Penumbra/Collections/Cache/GmpCache.cs +++ b/Penumbra/Collections/Cache/GmpCache.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using OtterGui.Filesystem; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 28680d11..e226b409 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index ee589d1b..fa60993a 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Penumbra.GameData.Enums; using Penumbra.Interop.Services; diff --git a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs index 7ea52eb6..5fcfd2f9 100644 --- a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 69cd1239..58eb7517 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 5aad1595..3d0ef60e 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; using OtterGui; using Penumbra.Api.Enums; using Penumbra.Mods; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 0bee38cf..c172aeff 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Filesystem; diff --git a/Penumbra/Collections/Manager/CollectionType.cs b/Penumbra/Collections/Manager/CollectionType.cs index 40f0f488..8e2d1aed 100644 --- a/Penumbra/Collections/Manager/CollectionType.cs +++ b/Penumbra/Collections/Manager/CollectionType.cs @@ -1,7 +1,4 @@ using Penumbra.GameData.Enums; -using System; -using System.Collections.Generic; -using System.Linq; namespace Penumbra.Collections.Manager; diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index b1b0698a..ac4acb8e 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -1,7 +1,4 @@ -using System.Collections; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.Types; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index d670fc42..da403337 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json.Linq; diff --git a/Penumbra/Collections/Manager/IndividualCollections.cs b/Penumbra/Collections/Manager/IndividualCollections.cs index c4d9c516..e7547153 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Dalamud.Game.ClientState.Objects.Enums; using OtterGui.Filesystem; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index fef7bdbc..4c1bdc5a 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Filesystem; diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index c1f158ea..56135182 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -1,6 +1,4 @@ using Penumbra.Mods; -using System.Collections.Generic; -using System.Linq; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.Util; diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index 400bd2cf..133a0990 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Penumbra.Api; using Penumbra.Communication; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index a3e43afd..ae68a370 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -1,10 +1,7 @@ using OtterGui.Classes; using Penumbra.GameData.Enums; using Penumbra.Mods; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Penumbra.Interop.Structs; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index ca20f371..cb4aecc6 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -1,8 +1,4 @@ using Penumbra.Mods; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; using Penumbra.Mods.Manager; using Penumbra.Collections.Manager; using Penumbra.Services; diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index 72b2e94c..05a8d9b0 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -1,10 +1,6 @@ using Newtonsoft.Json.Linq; using Penumbra.Mods; using Penumbra.Services; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Newtonsoft.Json; using Penumbra.Mods.Manager; using Penumbra.Util; diff --git a/Penumbra/Collections/ResolveData.cs b/Penumbra/Collections/ResolveData.cs index e0901e98..0c7bc967 100644 --- a/Penumbra/Collections/ResolveData.cs +++ b/Penumbra/Collections/ResolveData.cs @@ -1,5 +1,3 @@ -using System; - namespace Penumbra.Collections; public readonly struct ResolveData diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index a78c4da7..d1830617 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Runtime.CompilerServices; using Dalamud.Game; using Dalamud.Game.Command; using Dalamud.Game.Gui; diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index 01a5fd56..1e5bc863 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api.Enums; diff --git a/Penumbra/Communication/ChangedItemHover.cs b/Penumbra/Communication/ChangedItemHover.cs index c0736256..cf270ba0 100644 --- a/Penumbra/Communication/ChangedItemHover.cs +++ b/Penumbra/Communication/ChangedItemHover.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/CollectionChange.cs b/Penumbra/Communication/CollectionChange.cs index 96dd61ab..b815c48e 100644 --- a/Penumbra/Communication/CollectionChange.cs +++ b/Penumbra/Communication/CollectionChange.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/Communication/CollectionInheritanceChanged.cs b/Penumbra/Communication/CollectionInheritanceChanged.cs index 00e90546..8288341d 100644 --- a/Penumbra/Communication/CollectionInheritanceChanged.cs +++ b/Penumbra/Communication/CollectionInheritanceChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Collections; diff --git a/Penumbra/Communication/CreatedCharacterBase.cs b/Penumbra/Communication/CreatedCharacterBase.cs index 69d84ce2..b1903e5b 100644 --- a/Penumbra/Communication/CreatedCharacterBase.cs +++ b/Penumbra/Communication/CreatedCharacterBase.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api; using Penumbra.Collections; diff --git a/Penumbra/Communication/CreatingCharacterBase.cs b/Penumbra/Communication/CreatingCharacterBase.cs index 6161a984..090ca40b 100644 --- a/Penumbra/Communication/CreatingCharacterBase.cs +++ b/Penumbra/Communication/CreatingCharacterBase.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api; diff --git a/Penumbra/Communication/EnabledChanged.cs b/Penumbra/Communication/EnabledChanged.cs index 38c6b387..fa768235 100644 --- a/Penumbra/Communication/EnabledChanged.cs +++ b/Penumbra/Communication/EnabledChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api; diff --git a/Penumbra/Communication/ModDataChanged.cs b/Penumbra/Communication/ModDataChanged.cs index 941ed4d5..cca546e0 100644 --- a/Penumbra/Communication/ModDataChanged.cs +++ b/Penumbra/Communication/ModDataChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Mods; using Penumbra.Mods.Manager; diff --git a/Penumbra/Communication/ModDirectoryChanged.cs b/Penumbra/Communication/ModDirectoryChanged.cs index 5a3fb473..9fdb261e 100644 --- a/Penumbra/Communication/ModDirectoryChanged.cs +++ b/Penumbra/Communication/ModDirectoryChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api; diff --git a/Penumbra/Communication/ModDiscoveryFinished.cs b/Penumbra/Communication/ModDiscoveryFinished.cs index b8e4e460..8f5d31d5 100644 --- a/Penumbra/Communication/ModDiscoveryFinished.cs +++ b/Penumbra/Communication/ModDiscoveryFinished.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/ModDiscoveryStarted.cs b/Penumbra/Communication/ModDiscoveryStarted.cs index ee193681..a2ff8633 100644 --- a/Penumbra/Communication/ModDiscoveryStarted.cs +++ b/Penumbra/Communication/ModDiscoveryStarted.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/ModOptionChanged.cs b/Penumbra/Communication/ModOptionChanged.cs index a86826a3..416cc8df 100644 --- a/Penumbra/Communication/ModOptionChanged.cs +++ b/Penumbra/Communication/ModOptionChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Mods; using Penumbra.Mods.Manager; diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index 675759dd..99ec9109 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using OtterGui.Classes; using Penumbra.Api; using Penumbra.Mods; diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index c3c9f671..65bcf3ed 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api; using Penumbra.Api.Enums; diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlShpkLoaded.cs index 4b5600c9..868692cd 100644 --- a/Penumbra/Communication/MtrlShpkLoaded.cs +++ b/Penumbra/Communication/MtrlShpkLoaded.cs @@ -1,5 +1,4 @@ -using System; -using OtterGui.Classes; +using OtterGui.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/PostSettingsPanelDraw.cs b/Penumbra/Communication/PostSettingsPanelDraw.cs index f653bd0b..b32b0dfa 100644 --- a/Penumbra/Communication/PostSettingsPanelDraw.cs +++ b/Penumbra/Communication/PostSettingsPanelDraw.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/PreSettingsPanelDraw.cs b/Penumbra/Communication/PreSettingsPanelDraw.cs index 1167e92f..e5857474 100644 --- a/Penumbra/Communication/PreSettingsPanelDraw.cs +++ b/Penumbra/Communication/PreSettingsPanelDraw.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/ResolvedFileChanged.cs b/Penumbra/Communication/ResolvedFileChanged.cs index 99cec829..55e95320 100644 --- a/Penumbra/Communication/ResolvedFileChanged.cs +++ b/Penumbra/Communication/ResolvedFileChanged.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Mods; diff --git a/Penumbra/Communication/SelectTab.cs b/Penumbra/Communication/SelectTab.cs index 3dcf6d1b..aaa362f6 100644 --- a/Penumbra/Communication/SelectTab.cs +++ b/Penumbra/Communication/SelectTab.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Mods; diff --git a/Penumbra/Communication/TemporaryGlobalModChange.cs b/Penumbra/Communication/TemporaryGlobalModChange.cs index 8906627b..12d42e48 100644 --- a/Penumbra/Communication/TemporaryGlobalModChange.cs +++ b/Penumbra/Communication/TemporaryGlobalModChange.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Mods; diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index a80563c9..72f8bb95 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Configuration; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; diff --git a/Penumbra/GlobalUsings.cs b/Penumbra/GlobalUsings.cs new file mode 100644 index 00000000..0f6538bb --- /dev/null +++ b/Penumbra/GlobalUsings.cs @@ -0,0 +1,14 @@ +// Global using directives + +global using System; +global using System.Collections; +global using System.Collections.Generic; +global using System.Diagnostics; +global using System.IO; +global using System.Linq; +global using System.Numerics; +global using System.Runtime.CompilerServices; +global using System.Runtime.InteropServices; +global using System.Security.Cryptography; +global using System.Threading; +global using System.Threading.Tasks; \ No newline at end of file diff --git a/Penumbra/Import/Structs/StreamDisposer.cs b/Penumbra/Import/Structs/StreamDisposer.cs index 65c67585..7a755c40 100644 --- a/Penumbra/Import/Structs/StreamDisposer.cs +++ b/Penumbra/Import/Structs/StreamDisposer.cs @@ -1,6 +1,4 @@ using Penumbra.Util; -using System; -using System.IO; namespace Penumbra.Import.Structs; diff --git a/Penumbra/Import/Structs/TexToolsStructs.cs b/Penumbra/Import/Structs/TexToolsStructs.cs index 2a160c62..bf3bccd8 100644 --- a/Penumbra/Import/Structs/TexToolsStructs.cs +++ b/Penumbra/Import/Structs/TexToolsStructs.cs @@ -1,4 +1,3 @@ -using System; using Penumbra.Api.Enums; namespace Penumbra.Import.Structs; diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index 49b344da..ad61398f 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; -using System.Threading; -using System.Threading.Tasks; using Newtonsoft.Json; using OtterGui.Compression; using Penumbra.Import.Structs; diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index 13200a9c..a41b9f24 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -2,7 +2,7 @@ using Dalamud.Utility; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui.Filesystem; -using Penumbra.Import.Structs; +using Penumbra.Import.Structs; using Penumbra.Mods; using SharpCompress.Archives; using SharpCompress.Archives.Rar; @@ -10,9 +10,6 @@ using SharpCompress.Archives.SevenZip; using SharpCompress.Archives.Zip; using SharpCompress.Common; using SharpCompress.Readers; -using System; -using System.IO; -using System.Linq; namespace Penumbra.Import; diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index db818341..0c3e084d 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -1,5 +1,3 @@ -using System.Linq; -using System.Numerics; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 32c9c0e1..73b5d976 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Newtonsoft.Json; using Penumbra.Api.Enums; using Penumbra.Import.Structs; diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index 49501d91..eea1d811 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using Lumina.Extensions; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 2eac8f59..46636362 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; diff --git a/Penumbra/Import/TexToolsMeta.Rgsp.cs b/Penumbra/Import/TexToolsMeta.Rgsp.cs index 7bb837ce..0fd94fb4 100644 --- a/Penumbra/Import/TexToolsMeta.Rgsp.cs +++ b/Penumbra/Import/TexToolsMeta.Rgsp.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using Penumbra.GameData.Enums; using Penumbra.Meta; using Penumbra.Meta.Files; diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index b07ac8ab..b44f99a8 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; using System.Text; using Penumbra.GameData; using Penumbra.Import.Structs; diff --git a/Penumbra/Import/Textures/BaseImage.cs b/Penumbra/Import/Textures/BaseImage.cs index f0f6a47e..4f8c5305 100644 --- a/Penumbra/Import/Textures/BaseImage.cs +++ b/Penumbra/Import/Textures/BaseImage.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using Lumina.Data.Files; using OtterTex; using SixLabors.ImageSharp; diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 9bc4a2a5..8bac0a3b 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -1,14 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Numerics; -using System.Threading.Tasks; using ImGuiNET; using OtterGui.Raii; using OtterGui; using SixLabors.ImageSharp.PixelFormats; using Dalamud.Interface; using Penumbra.UI; -using System.Linq; namespace Penumbra.Import.Textures; diff --git a/Penumbra/Import/Textures/CombinedTexture.Operations.cs b/Penumbra/Import/Textures/CombinedTexture.Operations.cs index 441cd3f0..8494f12b 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Operations.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Operations.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Numerics; - namespace Penumbra.Import.Textures; public partial class CombinedTexture diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index b7e2a90a..98b87ac3 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -1,8 +1,3 @@ -using System; -using System.IO; -using System.Numerics; -using System.Threading.Tasks; - namespace Penumbra.Import.Textures; public partial class CombinedTexture : IDisposable diff --git a/Penumbra/Import/Textures/RgbaPixelData.cs b/Penumbra/Import/Textures/RgbaPixelData.cs index 0314b104..32540f16 100644 --- a/Penumbra/Import/Textures/RgbaPixelData.cs +++ b/Penumbra/Import/Textures/RgbaPixelData.cs @@ -1,4 +1,3 @@ -using System; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index f84442c1..7f324601 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using Lumina.Data.Files; using Lumina.Extensions; using OtterTex; diff --git a/Penumbra/Import/Textures/Texture.cs b/Penumbra/Import/Textures/Texture.cs index aefe72b4..fe1d3371 100644 --- a/Penumbra/Import/Textures/Texture.cs +++ b/Penumbra/Import/Textures/Texture.cs @@ -1,4 +1,3 @@ -using System; using ImGuiScene; using OtterTex; diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index d1b78268..b94fdbf8 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using Lumina.Data.Files; diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 9e4890f2..90dfa3d0 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -1,11 +1,4 @@ -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Threading; -using System.Threading.Tasks; using Dalamud.Interface; using Dalamud.Plugin.Services; using ImGuiScene; diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index c9505091..f83b1531 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Game; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 1b280b20..9d2fc9eb 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs index 88369725..86fee976 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index 0146cf6f..3f02e7e8 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index b1efb1b9..cc679bfd 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading; using Dalamud.Game.ClientState.Conditions; using Dalamud.Hooking; using Dalamud.Plugin.Services; diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index a795b46b..3f73643b 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Collections; diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 4273ae01..add121b6 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using Penumbra.GameData.Actors; diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 12f867b4..512d370a 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -1,9 +1,5 @@ using Dalamud.Hooking; using Dalamud.Utility.Signatures; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Threading; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.GameData; diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 2bf165c1..546ffd92 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index f7a754fb..6afaf5d1 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index cc513a92..2176ebba 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics.CodeAnalysis; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Collections; diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index de9d65ee..0c6566a3 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading; using Dalamud.Utility.Signatures; using Penumbra.Collections; using Penumbra.GameData; diff --git a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs index 609c131d..6f8f93dd 100644 --- a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs +++ b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.CompilerServices; using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index c0b8c5e3..b1bc806d 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using Penumbra.Collections; diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs index 3f8c8d27..6b751db7 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; using System.Text; -using System.Threading; using Dalamud.Hooking; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/ResourceLoading/FileReadService.cs b/Penumbra/Interop/ResourceLoading/FileReadService.cs index b09d568e..6ca0efb4 100644 --- a/Penumbra/Interop/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/ResourceLoading/FileReadService.cs @@ -1,7 +1,3 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using Penumbra.GameData; diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index da50f26e..5d5e4590 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,12 +1,10 @@ -using System; -using System.Diagnostics; -using System.Threading; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Collections; using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; +using FileMode = Penumbra.Interop.Structs.FileMode; namespace Penumbra.Interop.ResourceLoading; diff --git a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs index 4458e699..0b29ee10 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 645596a3..8b4a5d15 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/ResourceLoading/TexMdlService.cs index e3d48cec..6dac0e6b 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/ResourceLoading/TexMdlService.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 24eea690..0bbe8e66 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui; diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 17584787..cae89c09 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Penumbra.GameData.Enums; using Penumbra.String.Classes; using ChangedItemIcon = Penumbra.UI.ChangedItemDrawer.ChangedItemIcon; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 755103d7..d2276291 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 8d5318f2..a2e29e48 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Linq; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index d29916dd..43b25476 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using Penumbra.GameData.Files; diff --git a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs index 7ec0f218..8dd1fb4a 100644 --- a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading; -using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; namespace Penumbra.Interop.SafeHandles; diff --git a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs index 36cd4612..88c97c54 100644 --- a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using Penumbra.Interop.Structs; namespace Penumbra.Interop.SafeHandles; diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 00eab531..48824888 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Game; using Dalamud.Utility.Signatures; using Penumbra.Collections.Manager; diff --git a/Penumbra/Interop/Services/DecalReverter.cs b/Penumbra/Interop/Services/DecalReverter.cs index a8aa3fa2..21fa87a1 100644 --- a/Penumbra/Interop/Services/DecalReverter.cs +++ b/Penumbra/Interop/Services/DecalReverter.cs @@ -1,4 +1,3 @@ -using System; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Collections; using Penumbra.GameData.Enums; diff --git a/Penumbra/Interop/Services/GameEventManager.cs b/Penumbra/Interop/Services/GameEventManager.cs index ea8d32d1..ca333ed4 100644 --- a/Penumbra/Interop/Services/GameEventManager.cs +++ b/Penumbra/Interop/Services/GameEventManager.cs @@ -1,7 +1,6 @@ using Dalamud.Hooking; using Dalamud.Utility.Signatures; using Penumbra.GameData; -using System; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Services/MetaList.cs b/Penumbra/Interop/Services/MetaList.cs index e2603f79..e956040b 100644 --- a/Penumbra/Interop/Services/MetaList.cs +++ b/Penumbra/Interop/Services/MetaList.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Penumbra.Interop.Structs; namespace Penumbra.Interop.Services; diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 38b7de1c..0b9c6c38 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Game; using Dalamud.Game.ClientState.Conditions; using Dalamud.Game.ClientState.Objects; diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index bb9e0983..211a062c 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -1,6 +1,3 @@ -using System; -using System.Runtime.InteropServices; -using System.Threading; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; diff --git a/Penumbra/Interop/Structs/CharacterBaseExt.cs b/Penumbra/Interop/Structs/CharacterBaseExt.cs index cfd43a21..7cdcc6fe 100644 --- a/Penumbra/Interop/Structs/CharacterBaseExt.cs +++ b/Penumbra/Interop/Structs/CharacterBaseExt.cs @@ -1,4 +1,3 @@ -using System.Runtime.InteropServices; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 765ad25f..87d9566c 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Runtime.InteropServices; using Penumbra.GameData.Enums; namespace Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Structs/ClipScheduler.cs b/Penumbra/Interop/Structs/ClipScheduler.cs index d968ffbe..c8fd082d 100644 --- a/Penumbra/Interop/Structs/ClipScheduler.cs +++ b/Penumbra/Interop/Structs/ClipScheduler.cs @@ -1,6 +1,3 @@ -using System; -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout( LayoutKind.Explicit )] diff --git a/Penumbra/Interop/Structs/ConstantBuffer.cs b/Penumbra/Interop/Structs/ConstantBuffer.cs index 52df6477..d61aaeea 100644 --- a/Penumbra/Interop/Structs/ConstantBuffer.cs +++ b/Penumbra/Interop/Structs/ConstantBuffer.cs @@ -1,6 +1,3 @@ -using System; -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit, Size = 0x70)] diff --git a/Penumbra/Interop/Structs/DrawState.cs b/Penumbra/Interop/Structs/DrawState.cs index b30d1a76..d0dfc22b 100644 --- a/Penumbra/Interop/Structs/DrawState.cs +++ b/Penumbra/Interop/Structs/DrawState.cs @@ -1,5 +1,3 @@ -using System; - namespace Penumbra.Interop.Structs; [Flags] diff --git a/Penumbra/Interop/Structs/GetResourceParameters.cs b/Penumbra/Interop/Structs/GetResourceParameters.cs index eb413ead..ef665b36 100644 --- a/Penumbra/Interop/Structs/GetResourceParameters.cs +++ b/Penumbra/Interop/Structs/GetResourceParameters.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] diff --git a/Penumbra/Interop/Structs/HumanExt.cs b/Penumbra/Interop/Structs/HumanExt.cs index 33d83b06..5eafa1f3 100644 --- a/Penumbra/Interop/Structs/HumanExt.cs +++ b/Penumbra/Interop/Structs/HumanExt.cs @@ -1,4 +1,3 @@ -using System.Runtime.InteropServices; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; namespace Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Structs/Material.cs b/Penumbra/Interop/Structs/Material.cs index 3a204c75..2bca832d 100644 --- a/Penumbra/Interop/Structs/Material.cs +++ b/Penumbra/Interop/Structs/Material.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Structs/MtrlResource.cs b/Penumbra/Interop/Structs/MtrlResource.cs index 424adfe4..55c7f8d8 100644 --- a/Penumbra/Interop/Structs/MtrlResource.cs +++ b/Penumbra/Interop/Structs/MtrlResource.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout( LayoutKind.Explicit )] diff --git a/Penumbra/Interop/Structs/RenderModel.cs b/Penumbra/Interop/Structs/RenderModel.cs index 9c8581b0..25e928be 100644 --- a/Penumbra/Interop/Structs/RenderModel.cs +++ b/Penumbra/Interop/Structs/RenderModel.cs @@ -1,4 +1,3 @@ -using System.Runtime.InteropServices; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Structs/ResidentResourceManager.cs b/Penumbra/Interop/Structs/ResidentResourceManager.cs index d5dd1715..08461b03 100644 --- a/Penumbra/Interop/Structs/ResidentResourceManager.cs +++ b/Penumbra/Interop/Structs/ResidentResourceManager.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 5db0f8e1..b23cf62f 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource; diff --git a/Penumbra/Interop/Structs/SeFileDescriptor.cs b/Penumbra/Interop/Structs/SeFileDescriptor.cs index 4e1a1f57..d4ca3afa 100644 --- a/Penumbra/Interop/Structs/SeFileDescriptor.cs +++ b/Penumbra/Interop/Structs/SeFileDescriptor.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout( LayoutKind.Explicit )] diff --git a/Penumbra/Interop/Structs/ShaderPackageUtility.cs b/Penumbra/Interop/Structs/ShaderPackageUtility.cs index 5bf95f5b..9f7ec1f5 100644 --- a/Penumbra/Interop/Structs/ShaderPackageUtility.cs +++ b/Penumbra/Interop/Structs/ShaderPackageUtility.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; public static class ShaderPackageUtility diff --git a/Penumbra/Interop/Structs/VfxParams.cs b/Penumbra/Interop/Structs/VfxParams.cs index 644d5a9a..76dbd3ed 100644 --- a/Penumbra/Interop/Structs/VfxParams.cs +++ b/Penumbra/Interop/Structs/VfxParams.cs @@ -1,5 +1,3 @@ -using System.Runtime.InteropServices; - namespace Penumbra.Interop.Structs; [StructLayout( LayoutKind.Explicit )] diff --git a/Penumbra/Meta/Files/CmpFile.cs b/Penumbra/Meta/Files/CmpFile.cs index e67c5efd..8a6040ec 100644 --- a/Penumbra/Meta/Files/CmpFile.cs +++ b/Penumbra/Meta/Files/CmpFile.cs @@ -1,8 +1,6 @@ -using System; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; -using System.Collections.Generic; using Penumbra.Interop.Services; using Penumbra.String.Functions; diff --git a/Penumbra/Meta/Files/EqdpFile.cs b/Penumbra/Meta/Files/EqdpFile.cs index 6d1b5476..8a99225f 100644 --- a/Penumbra/Meta/Files/EqdpFile.cs +++ b/Penumbra/Meta/Files/EqdpFile.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index 71563ef9..6e9fd010 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Numerics; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; diff --git a/Penumbra/Meta/Files/EstFile.cs b/Penumbra/Meta/Files/EstFile.cs index 81749d46..2c7409b4 100644 --- a/Penumbra/Meta/Files/EstFile.cs +++ b/Penumbra/Meta/Files/EstFile.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; diff --git a/Penumbra/Meta/Files/EvpFile.cs b/Penumbra/Meta/Files/EvpFile.cs index 0b64e1e8..3d0b4dbe 100644 --- a/Penumbra/Meta/Files/EvpFile.cs +++ b/Penumbra/Meta/Files/EvpFile.cs @@ -1,4 +1,3 @@ -using System; using Penumbra.Interop.Structs; namespace Penumbra.Meta.Files; diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 8c957bcc..94bc2428 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; diff --git a/Penumbra/Meta/Files/MetaBaseFile.cs b/Penumbra/Meta/Files/MetaBaseFile.cs index 46e87567..ab08efc2 100644 --- a/Penumbra/Meta/Files/MetaBaseFile.cs +++ b/Penumbra/Meta/Files/MetaBaseFile.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Memory; using Penumbra.Interop.Structs; using Penumbra.String.Functions; diff --git a/Penumbra/Meta/Manipulations/EqdpManipulation.cs b/Penumbra/Meta/Manipulations/EqdpManipulation.cs index 8524ab8c..1e0756f2 100644 --- a/Penumbra/Meta/Manipulations/EqdpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqdpManipulation.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Penumbra.GameData.Enums; diff --git a/Penumbra/Meta/Manipulations/EqpManipulation.cs b/Penumbra/Meta/Manipulations/EqpManipulation.cs index 91949ae4..8e1a2ded 100644 --- a/Penumbra/Meta/Manipulations/EqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqpManipulation.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Penumbra.GameData.Enums; diff --git a/Penumbra/Meta/Manipulations/EstManipulation.cs b/Penumbra/Meta/Manipulations/EstManipulation.cs index 3496c56c..da834b35 100644 --- a/Penumbra/Meta/Manipulations/EstManipulation.cs +++ b/Penumbra/Meta/Manipulations/EstManipulation.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Penumbra.GameData.Enums; diff --git a/Penumbra/Meta/Manipulations/GmpManipulation.cs b/Penumbra/Meta/Manipulations/GmpManipulation.cs index 6ce954fb..94f7f971 100644 --- a/Penumbra/Meta/Manipulations/GmpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GmpManipulation.cs @@ -1,4 +1,3 @@ -using System.Runtime.InteropServices; using Newtonsoft.Json; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs index 51ecd0fb..391daacc 100644 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ b/Penumbra/Meta/Manipulations/ImcManipulation.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Penumbra.GameData.Data; diff --git a/Penumbra/Meta/Manipulations/MetaManipulation.cs b/Penumbra/Meta/Manipulations/MetaManipulation.cs index 1e0760f1..94b45cdf 100644 --- a/Penumbra/Meta/Manipulations/MetaManipulation.cs +++ b/Penumbra/Meta/Manipulations/MetaManipulation.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Penumbra.Interop.Structs; diff --git a/Penumbra/Meta/Manipulations/RspManipulation.cs b/Penumbra/Meta/Manipulations/RspManipulation.cs index e61fafea..7e5e3fcb 100644 --- a/Penumbra/Meta/Manipulations/RspManipulation.cs +++ b/Penumbra/Meta/Manipulations/RspManipulation.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.InteropServices; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Penumbra.GameData.Enums; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 171ea729..2f19537b 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Runtime.CompilerServices; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Memory; diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 3a58d91a..12fb4f35 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -1,11 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Threading; -using System.Threading.Tasks; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 2ce22ec1..2100526a 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; using Penumbra.String.Classes; namespace Penumbra.Mods; diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index 88f04ef3..6fa645a9 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using OtterGui.Classes; using Penumbra.Mods.Subclasses; diff --git a/Penumbra/Mods/Editor/MdlMaterialEditor.cs b/Penumbra/Mods/Editor/MdlMaterialEditor.cs index 0fe9ec46..1c1a10b4 100644 --- a/Penumbra/Mods/Editor/MdlMaterialEditor.cs +++ b/Penumbra/Mods/Editor/MdlMaterialEditor.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using System.Text.RegularExpressions; using OtterGui; diff --git a/Penumbra/Mods/Editor/ModBackup.cs b/Penumbra/Mods/Editor/ModBackup.cs index eb15de87..f4904271 100644 --- a/Penumbra/Mods/Editor/ModBackup.cs +++ b/Penumbra/Mods/Editor/ModBackup.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; using System.IO.Compression; -using System.Threading.Tasks; using OtterGui.Tasks; using Penumbra.Mods.Manager; diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index f65ce280..2f39970d 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using OtterGui; using OtterGui.Compression; using Penumbra.Mods.Subclasses; diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 5ef290dc..85a7a544 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; using OtterGui; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 4f9d22b3..1ca3edd4 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 3b5babcc..5c9be2ac 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; using OtterGui; diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 4d845a7c..e389c86a 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 62d87815..9b17c390 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Tasks; diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index 58ef10a0..c00bb821 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/ModelMaterialInfo.cs b/Penumbra/Mods/Editor/ModelMaterialInfo.cs index 38e76deb..741c2388 100644 --- a/Penumbra/Mods/Editor/ModelMaterialInfo.cs +++ b/Penumbra/Mods/Editor/ModelMaterialInfo.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using OtterGui; using OtterGui.Compression; using Penumbra.GameData.Files; diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index 7fd77199..da56d204 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -1,6 +1,3 @@ -using System; -using System.IO; -using System.Linq; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 72cb9a03..188fc317 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 6ed2112a..02e02ccb 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -1,6 +1,4 @@ -using System; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Text.RegularExpressions; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index d1af1d09..8e6473cc 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -4,10 +4,6 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Penumbra.Meta; using Penumbra.Mods.Manager; using Penumbra.Services; diff --git a/Penumbra/Mods/ItemSwap/Swaps.cs b/Penumbra/Mods/ItemSwap/Swaps.cs index 36ca77cf..0fa81a52 100644 --- a/Penumbra/Mods/ItemSwap/Swaps.cs +++ b/Penumbra/Mods/ItemSwap/Swaps.cs @@ -1,11 +1,6 @@ -using System; using Penumbra.GameData.Files; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; using Penumbra.GameData.Enums; using Penumbra.Meta; using static Penumbra.Mods.ItemSwap.ItemSwap; diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 1ace9536..afd42f95 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using Penumbra.Communication; using Penumbra.GameData; using Penumbra.GameData.Data; diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 43175815..66101dcd 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -1,6 +1,3 @@ -using System; -using System.IO; -using System.Linq; using Dalamud.Utility; using Newtonsoft.Json.Linq; using OtterGui.Classes; diff --git a/Penumbra/Mods/Manager/ModExportManager.cs b/Penumbra/Mods/Manager/ModExportManager.cs index f2bfb9bc..7d79d3d4 100644 --- a/Penumbra/Mods/Manager/ModExportManager.cs +++ b/Penumbra/Mods/Manager/ModExportManager.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Services; diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index 8e6e729c..f7006c4c 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; using System.Text.RegularExpressions; using OtterGui.Filesystem; using Penumbra.Communication; diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index 45b3f2ec..6c49ccf8 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using Penumbra.Import; using Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index ac973be4..f8d293a2 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,8 +1,4 @@ -using System; using System.Collections.Concurrent; -using System.IO; -using System.Linq; -using System.Threading.Tasks; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Services; diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index d6c5e63f..3cfab943 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 4bf774fb..3eeb13c6 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Filesystem; diff --git a/Penumbra/Mods/Manager/ModStorage.cs b/Penumbra/Mods/Manager/ModStorage.cs index 8421d6e2..377bb4a7 100644 --- a/Penumbra/Mods/Manager/ModStorage.cs +++ b/Penumbra/Mods/Manager/ModStorage.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using OtterGui.Classes; using OtterGui.Widgets; diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 4df41fb5..4ce6da9a 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using OtterGui; using OtterGui.Classes; using Penumbra.Mods.Subclasses; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index d63627f5..b5462eee 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using System.Text.RegularExpressions; using Dalamud.Interface.Internal.Notifications; diff --git a/Penumbra/Mods/ModLocalData.cs b/Penumbra/Mods/ModLocalData.cs index 71aae013..56ee827b 100644 --- a/Penumbra/Mods/ModLocalData.cs +++ b/Penumbra/Mods/ModLocalData.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Mods.Manager; diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index 66979345..49094aa0 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -1,4 +1,3 @@ -using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Services; diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index f66f29ea..957fe21d 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; using Newtonsoft.Json; using Penumbra.Api.Enums; using Penumbra.Services; diff --git a/Penumbra/Mods/Subclasses/ISubMod.cs b/Penumbra/Mods/Subclasses/ISubMod.cs index bf11527f..ac92cd13 100644 --- a/Penumbra/Mods/Subclasses/ISubMod.cs +++ b/Penumbra/Mods/Subclasses/ISubMod.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.IO; using Newtonsoft.Json; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Subclasses; diff --git a/Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs b/Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs index aad74a13..7c43de86 100644 --- a/Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs +++ b/Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; using Newtonsoft.Json.Linq; using Penumbra.Import; using Penumbra.Meta; diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index ae06a082..537c989f 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index facbacdc..d40a79be 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index a67ee1e5..a69238f5 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index ef721414..fcd4a5f7 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index eeee8fd0..1402ef89 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -1,6 +1,3 @@ -using System; -using System.IO; -using System.Linq; using System.Text; using Dalamud.Plugin; using ImGuiNET; diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index 1acb5bdc..0c13217a 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; using OtterGui.Classes; using OtterGui.Log; using Penumbra.Util; diff --git a/Penumbra/Services/ChatService.cs b/Penumbra/Services/ChatService.cs index 9ea52cac..adb24618 100644 --- a/Penumbra/Services/ChatService.cs +++ b/Penumbra/Services/ChatService.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index 97340f6b..3e61e3c1 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using OtterGui.Log; using Penumbra.Communication; diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index b9e58deb..89f1063e 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui.Filesystem; diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudServices.cs index 03978566..6754d0bd 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudServices.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Game; using Dalamud.Game.ClientState.Conditions; using Dalamud.Game.ClientState.Keys; @@ -7,7 +6,6 @@ using Dalamud.Game.Gui; using Dalamud.Interface; using Dalamud.IoC; using Dalamud.Plugin; -using System.Linq; using System.Reflection; using Dalamud.Interface.DragDrop; using Dalamud.Plugin.Services; diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index b5fa5487..c7ed6061 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; using Dalamud.Plugin; using OtterGui.Filesystem; using Penumbra.Collections; diff --git a/Penumbra/Services/SaveService.cs b/Penumbra/Services/SaveService.cs index 8429863b..0e61c565 100644 --- a/Penumbra/Services/SaveService.cs +++ b/Penumbra/Services/SaveService.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using OtterGui.Log; using Penumbra.Mods; diff --git a/Penumbra/Services/ServiceWrapper.cs b/Penumbra/Services/ServiceWrapper.cs index ca1e3624..67ddb63d 100644 --- a/Penumbra/Services/ServiceWrapper.cs +++ b/Penumbra/Services/ServiceWrapper.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading.Tasks; using OtterGui.Tasks; using Penumbra.Util; diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 56893d70..1c6b3ef1 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Dalamud.Plugin; using Dalamud.Plugin.Services; using OtterGui.Widgets; diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index 3d09f097..e97a9a82 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; using Dalamud.Interface.Internal.Notifications; using Dalamud.Plugin; diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 8ed59fed..2591145f 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; using Dalamud.Plugin.Services; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index c7c09de2..87598f5a 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index fb1e59aa..d14c7125 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index 2d868a42..4f04150f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -1,6 +1,3 @@ -using System; -using System.Numerics; -using System.Runtime.InteropServices; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs index 19e96539..7b80920d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Globalization; -using System.Numerics; using ImGuiNET; using OtterGui.Raii; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 12119742..187d86c7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; @@ -12,7 +6,6 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index f6f480e7..a5746ec7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Numerics; using System.Text; using Dalamud.Interface; using ImGuiNET; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index ad5c806c..73aad323 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -1,5 +1,3 @@ -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index fd4c082e..a6a93a36 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 518566f5..c90eb2b4 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -4,7 +4,6 @@ using OtterGui.Raii; using Penumbra.GameData.Files; using Penumbra.String.Classes; using System.Globalization; -using System.Linq; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 88ed10df..43a1990e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using Lumina.Data; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index c0868b71..fb2b5128 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using System.Text; using Dalamud.Interface.Internal.Notifications; using Dalamud.Interface; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index 2df52130..58e2e0c1 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Dalamud.Utility; using Lumina.Misc; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 12f98ccb..20aea21e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Threading.Tasks; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 6e1b1d24..703329e6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Numerics; using System.Text; using Dalamud.Interface; using Dalamud.Interface.Components; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index f7490c93..75f75de0 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 7da0275b..f435cb98 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -1,15 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Numerics; -using System.Threading.Tasks; using Dalamud.Interface; using ImGuiNET; using OtterGui.Raii; using OtterGui; using Penumbra.Interop.ResourceTree; using Penumbra.UI.Classes; -using System.Linq; - + namespace Penumbra.UI.AdvancedWindow; public class ResourceTreeViewer diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 902f6671..91d81ea3 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Plugin.Services; using Dalamud.Utility; diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index a91c2150..d7845ab7 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -1,4 +1,3 @@ -using System.Runtime.CompilerServices; using OtterGui.Widgets; namespace Penumbra.UI; diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index f71ae323..f4fa1b68 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Numerics; using ImGuiNET; using OtterGui.Raii; using OtterGui; diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index e2acc1a3..eb4dec4c 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using OtterGui.Custom; namespace Penumbra.UI.Classes; diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index 94e6f6d2..fc37eaf2 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using ImGuiNET; using OtterGui.Raii; using OtterGui.Widgets; diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index b5e60380..fe248d99 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Game.ClientState.Objects; using Dalamud.Interface; using Dalamud.Interface.Components; diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index 746c2d5f..e568ecaf 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs index 376b7ad8..da011bde 100644 --- a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs +++ b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Dalamud.Game.ClientState.Objects.Enums; using ImGuiNET; using OtterGui.Custom; diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index 87c09917..4bcff426 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 6259ffe2..5cedd824 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using Dalamud.Interface.Windowing; using Dalamud.Plugin; using ImGuiNET; diff --git a/Penumbra/UI/FileDialogService.cs b/Penumbra/UI/FileDialogService.cs index c483c3b1..dc638ef5 100644 --- a/Penumbra/UI/FileDialogService.cs +++ b/Penumbra/UI/FileDialogService.cs @@ -1,8 +1,4 @@ -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; using Dalamud.Interface; using Dalamud.Interface.ImGuiFileDialog; diff --git a/Penumbra/UI/ImportPopup.cs b/Penumbra/UI/ImportPopup.cs index f97213c1..228cf4e1 100644 --- a/Penumbra/UI/ImportPopup.cs +++ b/Penumbra/UI/ImportPopup.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using Dalamud.Interface.Windowing; using ImGuiNET; using OtterGui.Raii; diff --git a/Penumbra/UI/LaunchButton.cs b/Penumbra/UI/LaunchButton.cs index 3aa470f5..5b9bf5a4 100644 --- a/Penumbra/UI/LaunchButton.cs +++ b/Penumbra/UI/LaunchButton.cs @@ -1,5 +1,3 @@ -using System; -using System.IO; using Dalamud.Interface; using Dalamud.Plugin; using ImGuiScene; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 8d978413..91da4da5 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -1,8 +1,3 @@ -using System; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Runtime.InteropServices; using Dalamud.Game.ClientState.Keys; using Dalamud.Interface; using Dalamud.Interface.DragDrop; diff --git a/Penumbra/UI/ModsTab/ModFilter.cs b/Penumbra/UI/ModsTab/ModFilter.cs index 03fdc177..4b2798f7 100644 --- a/Penumbra/UI/ModsTab/ModFilter.cs +++ b/Penumbra/UI/ModsTab/ModFilter.cs @@ -1,5 +1,3 @@ -using System; - namespace Penumbra.UI.ModsTab; [Flags] diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index f0d28dab..1866606a 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Plugin; using ImGuiNET; diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index df2c905e..e897f940 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using ImGuiNET; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs index 1bdb32c0..22f8022e 100644 --- a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 68a50123..83f79f56 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using ImGuiNET; using OtterGui.Raii; using OtterGui.Widgets; diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 9cb229d1..256be8d6 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Interface; using ImGuiNET; using OtterGui.Raii; diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index bd5a62c4..692cf8b7 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.Internal.Notifications; diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index e1da057f..2c71426f 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -1,6 +1,3 @@ -using System; -using System.Diagnostics; -using System.Numerics; using Dalamud.Interface.GameFonts; using Dalamud.Plugin; using ImGuiNET; diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index ad0f2e40..acfdcf28 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Numerics; using ImGuiNET; using OtterGui.Raii; using OtterGui; diff --git a/Penumbra/UI/ModsTab/ModPanelTabBar.cs b/Penumbra/UI/ModsTab/ModPanelTabBar.cs index 503e471f..3f1b0f77 100644 --- a/Penumbra/UI/ModsTab/ModPanelTabBar.cs +++ b/Penumbra/UI/ModsTab/ModPanelTabBar.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index e438be27..ec66ae08 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Classes; using Penumbra.Collections; using Penumbra.GameData.Enums; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index ec0274b6..e8031d4e 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -1,7 +1,4 @@ -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 0b2f2ae5..905307ba 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index f85387f8..4605527a 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using ImGuiNET; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index d0f227c8..4d6d2dd6 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -1,5 +1,3 @@ -using System; -using System.Numerics; using Dalamud.Game.ClientState.Objects; using Dalamud.Interface; using Dalamud.Plugin; diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index 49b6348a..60339893 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -1,4 +1,3 @@ -using System; using ImGuiNET; using OtterGui.Widgets; using Penumbra.Api.Enums; diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index 72122722..fc0168a0 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -1,7 +1,3 @@ -using System; -using System.IO; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Windowing; using Dalamud.Utility; diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index de9ad706..3c1d0801 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 10e4be1d..16f0180e 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -2,9 +2,6 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.UI.Classes; -using System; -using System.Linq; -using System.Numerics; using Dalamud.Interface; using Dalamud.Plugin.Services; using OtterGui.Widgets; diff --git a/Penumbra/UI/Tabs/OnScreenTab.cs b/Penumbra/UI/Tabs/OnScreenTab.cs index c8f86333..8d323baf 100644 --- a/Penumbra/UI/Tabs/OnScreenTab.cs +++ b/Penumbra/UI/Tabs/OnScreenTab.cs @@ -1,4 +1,3 @@ -using System; using OtterGui.Widgets; using Penumbra.Interop.ResourceTree; using Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index db1236bb..020493d1 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -1,6 +1,3 @@ -using System; -using System.Linq; -using System.Numerics; using Dalamud.Game; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 7f27e6ee..701d1ef6 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -1,7 +1,3 @@ -using System; -using System.IO; -using System.Numerics; -using System.Runtime.CompilerServices; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Utility; diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index 7f9b2ce3..87e709c3 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -1,5 +1,3 @@ -using System; -using System.Runtime.CompilerServices; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/UI/UiHelpers.cs b/Penumbra/UI/UiHelpers.cs index 8ae27dd6..7f4fc7cb 100644 --- a/Penumbra/UI/UiHelpers.cs +++ b/Penumbra/UI/UiHelpers.cs @@ -1,6 +1,3 @@ -using System.Diagnostics; -using System.IO; -using System.Numerics; using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; using ImGuiNET; diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index bde27bfc..f08b6de9 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Interface; using Dalamud.Interface.Windowing; using Dalamud.Plugin; diff --git a/Penumbra/Util/DictionaryExtensions.cs b/Penumbra/Util/DictionaryExtensions.cs index 31931fe7..74274c38 100644 --- a/Penumbra/Util/DictionaryExtensions.cs +++ b/Penumbra/Util/DictionaryExtensions.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace Penumbra.Util; public static class DictionaryExtensions diff --git a/Penumbra/Util/FixedUlongStringEnumConverter.cs b/Penumbra/Util/FixedUlongStringEnumConverter.cs index 750422b4..85c61837 100644 --- a/Penumbra/Util/FixedUlongStringEnumConverter.cs +++ b/Penumbra/Util/FixedUlongStringEnumConverter.cs @@ -1,4 +1,3 @@ -using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; diff --git a/Penumbra/Util/PenumbraSqPackStream.cs b/Penumbra/Util/PenumbraSqPackStream.cs index 0109ff35..d5b51433 100644 --- a/Penumbra/Util/PenumbraSqPackStream.cs +++ b/Penumbra/Util/PenumbraSqPackStream.cs @@ -1,8 +1,4 @@ -using System; -using System.Diagnostics; -using System.IO; using System.IO.Compression; -using System.Runtime.InteropServices; using Lumina.Data.Structs; using Lumina.Extensions; From 2b4a01df06fbc896789e12861891895b7a148f3d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 16:56:16 +0200 Subject: [PATCH 0100/1381] Make line endings explicit in editorconfig and share in sub projects, also apply editorconfig everywhere and move some namespaces. --- .editorconfig | 82 +++--- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Api/PenumbraApi.cs | 3 +- Penumbra/Api/TempModManager.cs | 6 +- Penumbra/Collections/Cache/CollectionCache.cs | 9 +- .../Cache/CollectionCacheManager.cs | 1 - Penumbra/Collections/Cache/EqdpCache.cs | 2 +- Penumbra/Collections/Cache/EqpCache.cs | 45 ++- Penumbra/Collections/Cache/GmpCache.cs | 32 +-- Penumbra/Collections/Cache/ImcCache.cs | 16 +- Penumbra/Collections/Cache/MetaCache.cs | 8 +- .../Manager/ActiveCollectionMigration.cs | 11 +- .../Collections/Manager/ActiveCollections.cs | 17 +- .../Collections/Manager/CollectionEditor.cs | 1 + .../Collections/Manager/CollectionStorage.cs | 3 +- .../Collections/Manager/CollectionType.cs | 14 +- .../Manager/IndividualCollections.Access.cs | 9 +- .../Manager/IndividualCollections.Files.cs | 5 +- .../Manager/IndividualCollections.cs | 3 +- .../Manager/ModCollectionMigration.cs | 1 + .../Collections/ModCollection.Cache.Access.cs | 4 +- Penumbra/Collections/ModCollection.cs | 18 +- Penumbra/Collections/ModCollectionSave.cs | 5 +- Penumbra/Collections/ResolveData.cs | 4 +- Penumbra/CommandHandler.cs | 3 +- Penumbra/Communication/CollectionChange.cs | 1 - Penumbra/Communication/ModDataChanged.cs | 2 +- .../Communication/ModDiscoveryFinished.cs | 3 +- Penumbra/Communication/ModDiscoveryStarted.cs | 1 + Penumbra/Communication/ModPathChanged.cs | 3 +- Penumbra/Configuration.cs | 3 +- Penumbra/GlobalUsings.cs | 4 +- Penumbra/Import/Structs/ImporterState.cs | 2 +- Penumbra/Import/Structs/StreamDisposer.cs | 2 +- Penumbra/Import/TexToolsImporter.Archives.cs | 99 ++++--- Penumbra/Import/TexToolsImporter.Gui.cs | 78 +++--- .../Import/TexToolsMeta.Deserialization.cs | 2 +- Penumbra/Import/TexToolsMeta.Rgsp.cs | 66 +++-- Penumbra/Import/TexToolsMeta.cs | 76 +++-- Penumbra/Import/Textures/RgbaPixelData.cs | 3 +- Penumbra/Import/Textures/TexFileParser.cs | 4 +- Penumbra/Import/Textures/TextureDrawer.cs | 2 +- Penumbra/Import/Textures/TextureManager.cs | 1 - .../LiveColorTablePreviewer.cs | 3 +- .../PathResolving/AnimationHookService.cs | 26 +- .../PathResolving/CollectionResolver.cs | 2 +- .../Interop/PathResolving/DrawObjectState.cs | 6 +- .../IdentifiedCollectionCache.cs | 8 +- .../Interop/PathResolving/PathResolver.cs | 1 + .../Interop/PathResolving/SubfileHelper.cs | 1 - .../ResourceLoading/FileReadService.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceNode.cs | 7 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 48 ++-- .../Interop/SafeHandles/SafeResourceHandle.cs | 12 +- .../Interop/SafeHandles/SafeTextureHandle.cs | 15 +- Penumbra/Interop/Services/DecalReverter.cs | 6 +- Penumbra/Interop/Services/GameEventManager.cs | 4 +- Penumbra/Interop/Services/RedrawService.cs | 6 +- .../Services/ResidentResourceManager.cs | 4 +- .../Interop/Structs/CharacterUtilityData.cs | 54 ++-- Penumbra/Interop/Structs/ClipScheduler.cs | 8 +- Penumbra/Interop/Structs/DrawState.cs | 2 +- Penumbra/Interop/Structs/FileMode.cs | 2 +- Penumbra/Interop/Structs/HumanExt.cs | 12 +- Penumbra/Interop/Structs/Material.cs | 29 +- Penumbra/Interop/Structs/MtrlResource.cs | 26 +- Penumbra/Interop/Structs/RenderModel.cs | 26 +- .../Structs/ResidentResourceManager.cs | 10 +- Penumbra/Interop/Structs/ResourceHandle.cs | 92 +++--- Penumbra/Interop/Structs/SeFileDescriptor.cs | 19 +- Penumbra/Interop/Structs/TextureUtility.cs | 5 +- Penumbra/Interop/Structs/VfxParams.cs | 12 +- .../Meta/Manipulations/EqdpManipulation.cs | 4 +- .../Meta/Manipulations/EqpManipulation.cs | 50 ++-- .../Meta/Manipulations/EstManipulation.cs | 57 ++-- .../Meta/Manipulations/GmpManipulation.cs | 36 ++- Penumbra/Meta/MetaFileManager.cs | 1 + Penumbra/Mods/Editor/DuplicateManager.cs | 2 +- Penumbra/Mods/Editor/FileRegistry.cs | 1 + Penumbra/Mods/Editor/IMod.cs | 14 +- Penumbra/Mods/Editor/ModBackup.cs | 19 +- Penumbra/Mods/Editor/ModFileCollection.cs | 1 + Penumbra/Mods/Editor/ModFileEditor.cs | 3 +- Penumbra/Mods/Editor/ModMerger.cs | 3 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 + Penumbra/Mods/Editor/ModNormalizer.cs | 1 + Penumbra/Mods/Editor/ModSwapEditor.cs | 3 +- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 94 ++++--- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 26 +- Penumbra/Mods/ItemSwap/ItemSwap.cs | 153 +++++----- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 114 ++++---- Penumbra/Mods/Manager/ModExportManager.cs | 2 +- Penumbra/Mods/Manager/ModFileSystem.cs | 4 +- Penumbra/Mods/Manager/ModImportManager.cs | 1 - Penumbra/Mods/Manager/ModManager.cs | 11 +- Penumbra/Mods/Manager/ModMigration.cs | 17 +- Penumbra/Mods/Mod.cs | 2 +- Penumbra/Mods/ModCreator.cs | 2 - Penumbra/Mods/ModLocalData.cs | 1 - Penumbra/Mods/ModMeta.cs | 1 - Penumbra/Mods/Subclasses/ISubMod.cs | 53 ++-- Penumbra/Mods/Subclasses/ModSettings.cs | 5 +- Penumbra/Mods/Subclasses/MultiModGroup.cs | 5 +- Penumbra/Mods/Subclasses/SingleModGroup.cs | 85 +++--- .../{Mod.Files.SubMod.cs => SubMod.cs} | 5 +- Penumbra/Mods/TemporaryMod.cs | 75 ++--- Penumbra/Penumbra.cs | 1 + Penumbra/Services/ConfigMigrationService.cs | 4 +- Penumbra/Services/DalamudServices.cs | 1 - Penumbra/Services/ServiceManager.cs | 1 + Penumbra/Services/StainService.cs | 13 +- Penumbra/Services/ValidityChecker.cs | 18 +- Penumbra/Services/Wrappers.cs | 5 +- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 7 +- .../ModEditWindow.Materials.ColorTable.cs | 13 +- .../ModEditWindow.Materials.MtrlTab.cs | 22 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 66 +++-- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 159 +++++------ .../ModEditWindow.QuickImport.cs | 1 + .../ModEditWindow.ShaderPackages.cs | 8 + .../AdvancedWindow/ModEditWindow.ShpkTab.cs | 2 +- .../AdvancedWindow/ModEditWindow.Textures.cs | 21 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 2 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 73 ++--- Penumbra/UI/Changelog.cs | 121 +++++--- Penumbra/UI/Classes/Colors.cs | 22 +- Penumbra/UI/Classes/Combos.cs | 53 ++-- Penumbra/UI/CollectionTab/CollectionPanel.cs | 2 +- Penumbra/UI/CollectionTab/InheritanceUi.cs | 84 +++--- Penumbra/UI/FileDialogService.cs | 2 - Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 7 +- Penumbra/UI/ModsTab/ModFilter.cs | 80 +++--- Penumbra/UI/ModsTab/ModPanel.cs | 1 + Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 4 +- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 4 +- Penumbra/UI/ModsTab/ModPanelTabBar.cs | 1 + Penumbra/UI/ResourceWatcher/Record.cs | 3 +- .../UI/ResourceWatcher/ResourceWatcher.cs | 7 +- .../ResourceWatcher/ResourceWatcherTable.cs | 3 +- Penumbra/UI/Tabs/ChangedItemsTab.cs | 4 +- Penumbra/UI/Tabs/CollectionsTab.cs | 7 +- Penumbra/UI/Tabs/DebugTab.cs | 5 +- Penumbra/UI/Tabs/EffectiveTab.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 5 +- Penumbra/UI/TutorialService.cs | 28 +- Penumbra/UI/UiHelpers.cs | 4 +- Penumbra/UI/WindowSystem.cs | 3 +- Penumbra/Util/DictionaryExtensions.cs | 70 ++--- .../Util/FixedUlongStringEnumConverter.cs | 66 ++--- Penumbra/Util/PenumbraSqPackStream.cs | 262 ++++++++---------- Penumbra/Util/PerformanceType.cs | 2 +- 155 files changed, 1620 insertions(+), 1614 deletions(-) rename Penumbra/Mods/Subclasses/{Mod.Files.SubMod.cs => SubMod.cs} (97%) diff --git a/.editorconfig b/.editorconfig index 0bbaa114..c645b573 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,21 +1,31 @@ - -[*.proto] -indent_style=tab -indent_size=tab -tab_width=4 - -[*.{asax,ascx,aspx,axaml,cs,cshtml,css,htm,html,js,jsx,master,paml,razor,skin,ts,tsx,vb,xaml,xamlx,xoml}] -indent_style=space -indent_size=4 -tab_width=4 - -[*.{appxmanifest,axml,build,config,csproj,dbml,discomap,dtd,json,jsproj,lsproj,njsproj,nuspec,proj,props,resjson,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}] -indent_style=space -indent_size=2 -tab_width=2 +# Standard properties +charset = utf-8 +end_of_line = lf +insert_final_newline = true +csharp_indent_labels = one_less_than_current +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_throw_expression = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_prefer_top_level_statements = true:silent [*] - # Microsoft .NET properties csharp_indent_braces=false csharp_indent_switch_labels=true @@ -3567,30 +3577,6 @@ resharper_xaml_x_key_attribute_disallowed_highlighting=error resharper_xml_doc_comment_syntax_problem_highlighting=warning resharper_xunit_xunit_test_with_console_output_highlighting=warning -# Standard properties -end_of_line= crlf -csharp_indent_labels = one_less_than_current -csharp_prefer_simple_using_statement = true:suggestion -csharp_prefer_braces = true:silent -csharp_style_prefer_method_group_conversion = true:silent -csharp_style_expression_bodied_methods = false:silent -csharp_style_expression_bodied_constructors = false:silent -csharp_style_expression_bodied_operators = false:silent -csharp_style_expression_bodied_properties = true:silent -csharp_style_expression_bodied_indexers = true:silent -csharp_style_expression_bodied_accessors = true:silent -csharp_style_expression_bodied_lambdas = true:silent -csharp_style_expression_bodied_local_functions = false:silent -csharp_style_throw_expression = true:suggestion -csharp_style_prefer_null_check_over_type_check = true:suggestion -csharp_prefer_simple_default_expression = true:suggestion -csharp_style_prefer_local_over_anonymous_function = true:suggestion -csharp_style_prefer_index_operator = true:suggestion -csharp_style_prefer_range_operator = true:suggestion -csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion -csharp_style_prefer_tuple_swap = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion - [*.{cshtml,htm,html,proto,razor}] indent_style=tab indent_size=tab @@ -3601,6 +3587,21 @@ indent_style=space indent_size=4 tab_width=4 +[ "*.proto" ] +indent_style=tab +indent_size=tab +tab_width=4 + +[*.{asax,ascx,aspx,axaml,cs,cshtml,css,htm,html,js,jsx,master,paml,razor,skin,ts,tsx,vb,xaml,xamlx,xoml}] +indent_style=space +indent_size=4 +tab_width=4 + +[*.{appxmanifest,axml,build,config,csproj,dbml,discomap,dtd,json,jsproj,lsproj,njsproj,nuspec,proj,props,resjson,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}] +indent_style=space +indent_size=2 +tab_width=2 + [*.{appxmanifest,asax,ascx,aspx,axaml,axml,build,c,c++,cc,cginc,compute,config,cp,cpp,cs,cshtml,csproj,css,cu,cuh,cxx,dbml,discomap,dtd,h,hh,hlsl,hlsli,hlslinc,hpp,htm,html,hxx,inc,inl,ino,ipp,js,json,jsproj,jsx,lsproj,master,mpp,mq4,mq5,mqh,njsproj,nuspec,paml,proj,props,proto,razor,resjson,resw,resx,skin,StyleCop,targets,tasks,tpp,ts,tsx,usf,ush,vb,vbproj,xaml,xamlx,xml,xoml,xsd}] indent_style=space indent_size= 4 @@ -3621,3 +3622,4 @@ dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion dotnet_style_prefer_compound_assignment = true:suggestion dotnet_style_prefer_simplified_interpolation = true:suggestion dotnet_style_namespace_match_folder = true:suggestion +insert_final_newline = true diff --git a/Penumbra.Api b/Penumbra.Api index 316f3da4..22846625 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 316f3da4a3ce246afe5b98c1568d73fcd7b6b22d +Subproject commit 22846625192884c6e9f5ec4429fb579875b519e9 diff --git a/Penumbra.GameData b/Penumbra.GameData index 0507b1f0..f004e069 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 0507b1f093f5382e03242e5da991752361b70c6e +Subproject commit f004e069824a1588244e06080b32bab170f78077 diff --git a/Penumbra.String b/Penumbra.String index 0e0c1e1e..620a7edf 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 0e0c1e1ee116c259abd00e1d5c3450ad40f92a98 +Subproject commit 620a7edf009b92288257ce7d64fffb8fba44d8b5 diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 1dead7e5..73a87fab 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -633,7 +633,8 @@ public class PenumbraApi : IDisposable, IPenumbraApi _modManager.AddMod(dir); if (_config.UseFileSystemCompression) - new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K); + new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), + CompressionAlgorithm.Xpress8K); return PenumbraApiEc.Success; } diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index 35aa1217..efbfd7f9 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -25,7 +25,7 @@ public class TempModManager : IDisposable public TempModManager(CommunicatorService communicator) { - _communicator = communicator; + _communicator = communicator; _communicator.CollectionChange.Subscribe(OnCollectionChange, CollectionChange.Priority.TempModManager); } @@ -43,7 +43,7 @@ public class TempModManager : IDisposable public RedirectResult Register(string tag, ModCollection? collection, Dictionary dict, HashSet manips, int priority) { - var mod = GetOrCreateMod(tag, collection, priority, out var created); + var mod = GetOrCreateMod(tag, collection, priority, out var created); Penumbra.Log.Verbose($"{(created ? "Created" : "Changed")} temporary Mod {mod.Name}."); mod.SetAll(dict, manips); ApplyModChange(mod, collection, created, false); @@ -56,7 +56,7 @@ public class TempModManager : IDisposable var list = collection == null ? _modsForAllCollections : _mods.TryGetValue(collection, out var l) ? l : null; if (list == null) return RedirectResult.NotRegistered; - + var removed = list.RemoveAll(m => { if (m.Name != tag || priority != null && m.Priority != priority.Value) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 6f3d59e9..80539d96 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -6,6 +6,7 @@ using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.String.Classes; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; namespace Penumbra.Collections.Cache; @@ -270,14 +271,14 @@ public class CollectionCache : IDisposable foreach (var manip in subMod.Manipulations) AddManipulation(manip, parentMod); } - - /// Invoke only if not in a full recalculation. + + /// Invoke only if not in a full recalculation. private void InvokeResolvedFileChange(ModCollection collection, ResolvedFileChanged.Type type, Utf8GamePath key, FullPath value, FullPath old, IMod? mod) { if (Calculating == -1) _manager.ResolvedFileChanged.Invoke(collection, type, key, value, old, mod); - } + } // Add a specific file redirection, handling potential conflicts. // For different mods, higher mod priority takes precedence before option group priority, @@ -292,7 +293,7 @@ public class CollectionCache : IDisposable { if (ResolvedFiles.TryAdd(path, new ModPath(mod, file))) { - ModData.AddPath(mod, path); + ModData.AddPath(mod, path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, file, FullPath.Empty, mod); return; } diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 3a94bc89..5daecaa9 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using Dalamud.Game; using OtterGui.Classes; using Penumbra.Api; diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index a5232dbb..3937fa72 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -45,7 +45,7 @@ public readonly struct EqdpCache : IDisposable foreach (var file in _eqdpFiles.OfType()) { var relevant = CharacterUtility.RelevantIndices[file.Index.Value]; - file.Reset(_eqdpManipulations.Where(m => m.FileIndex() == relevant).Select(m => (SetId) m.SetId)); + file.Reset(_eqdpManipulations.Where(m => m.FileIndex() == relevant).Select(m => (SetId)m.SetId)); } _eqdpManipulations.Clear(); diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 9d63479a..972ee5a5 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -9,20 +9,20 @@ namespace Penumbra.Collections.Cache; public struct EqpCache : IDisposable { - private ExpandedEqpFile? _eqpFile = null; - private readonly List< EqpManipulation > _eqpManipulations = new(); - - public EqpCache() - {} + private ExpandedEqpFile? _eqpFile = null; + private readonly List _eqpManipulations = new(); - public void SetFiles(MetaFileManager manager) - => manager.SetFile( _eqpFile, MetaIndex.Eqp ); + public EqpCache() + { } + + public void SetFiles(MetaFileManager manager) + => manager.SetFile(_eqpFile, MetaIndex.Eqp); public static void ResetFiles(MetaFileManager manager) - => manager.SetFile( null, MetaIndex.Eqp ); + => manager.SetFile(null, MetaIndex.Eqp); public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager) - => manager.TemporarilySetFile( _eqpFile, MetaIndex.Eqp ); + => manager.TemporarilySetFile(_eqpFile, MetaIndex.Eqp); public void Reset() { @@ -31,25 +31,24 @@ public struct EqpCache : IDisposable _eqpFile.Reset(_eqpManipulations.Select(m => m.SetId)); _eqpManipulations.Clear(); - } - - public bool ApplyMod( MetaFileManager manager, EqpManipulation manip ) - { - _eqpManipulations.AddOrReplace( manip ); - _eqpFile ??= new ExpandedEqpFile(manager); - return manip.Apply( _eqpFile ); } - public bool RevertMod( MetaFileManager manager, EqpManipulation manip ) + public bool ApplyMod(MetaFileManager manager, EqpManipulation manip) { - var idx = _eqpManipulations.FindIndex( manip.Equals ); + _eqpManipulations.AddOrReplace(manip); + _eqpFile ??= new ExpandedEqpFile(manager); + return manip.Apply(_eqpFile); + } + + public bool RevertMod(MetaFileManager manager, EqpManipulation manip) + { + var idx = _eqpManipulations.FindIndex(manip.Equals); if (idx < 0) return false; - var def = ExpandedEqpFile.GetDefault( manager, manip.SetId ); - manip = new EqpManipulation( def, manip.Slot, manip.SetId ); - return manip.Apply( _eqpFile! ); - + var def = ExpandedEqpFile.GetDefault(manager, manip.SetId); + manip = new EqpManipulation(def, manip.Slot, manip.SetId); + return manip.Apply(_eqpFile!); } public void Dispose() @@ -58,4 +57,4 @@ public struct EqpCache : IDisposable _eqpFile = null; _eqpManipulations.Clear(); } -} \ No newline at end of file +} diff --git a/Penumbra/Collections/Cache/GmpCache.cs b/Penumbra/Collections/Cache/GmpCache.cs index 3287eb2d..0a713867 100644 --- a/Penumbra/Collections/Cache/GmpCache.cs +++ b/Penumbra/Collections/Cache/GmpCache.cs @@ -9,42 +9,42 @@ namespace Penumbra.Collections.Cache; public struct GmpCache : IDisposable { - private ExpandedGmpFile? _gmpFile = null; - private readonly List< GmpManipulation > _gmpManipulations = new(); - + private ExpandedGmpFile? _gmpFile = null; + private readonly List _gmpManipulations = new(); + public GmpCache() - {} + { } public void SetFiles(MetaFileManager manager) - => manager.SetFile( _gmpFile, MetaIndex.Gmp ); + => manager.SetFile(_gmpFile, MetaIndex.Gmp); public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager) - => manager.TemporarilySetFile( _gmpFile, MetaIndex.Gmp ); + => manager.TemporarilySetFile(_gmpFile, MetaIndex.Gmp); public void Reset() { - if( _gmpFile == null ) + if (_gmpFile == null) return; - _gmpFile.Reset( _gmpManipulations.Select( m => m.SetId ) ); + _gmpFile.Reset(_gmpManipulations.Select(m => m.SetId)); _gmpManipulations.Clear(); } - public bool ApplyMod( MetaFileManager manager, GmpManipulation manip ) + public bool ApplyMod(MetaFileManager manager, GmpManipulation manip) { - _gmpManipulations.AddOrReplace( manip ); + _gmpManipulations.AddOrReplace(manip); _gmpFile ??= new ExpandedGmpFile(manager); - return manip.Apply( _gmpFile ); + return manip.Apply(_gmpFile); } - public bool RevertMod( MetaFileManager manager, GmpManipulation manip ) + public bool RevertMod(MetaFileManager manager, GmpManipulation manip) { if (!_gmpManipulations.Remove(manip)) return false; - var def = ExpandedGmpFile.GetDefault( manager, manip.SetId ); - manip = new GmpManipulation( def, manip.SetId ); - return manip.Apply( _gmpFile! ); + var def = ExpandedGmpFile.GetDefault(manager, manip.SetId); + manip = new GmpManipulation(def, manip.SetId); + return manip.Apply(_gmpFile!); } public void Dispose() @@ -53,4 +53,4 @@ public struct GmpCache : IDisposable _gmpFile = null; _gmpManipulations.Clear(); } -} \ No newline at end of file +} diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index e226b409..05756e12 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -44,9 +44,9 @@ public readonly struct ImcCache : IDisposable if (idx < 0) { idx = _imcManipulations.Count; - _imcManipulations.Add((manip, null!)); - } - + _imcManipulations.Add((manip, null!)); + } + var path = manip.GamePath(); try { @@ -79,13 +79,13 @@ public readonly struct ImcCache : IDisposable public bool RevertMod(MetaFileManager manager, ModCollection collection, ImcManipulation m) { if (!m.Validate()) - return false; - + return false; + var idx = _imcManipulations.FindIndex(p => p.Item1.Equals(m)); if (idx < 0) return false; - var (_, file) = _imcManipulations[idx]; + var (_, file) = _imcManipulations[idx]; _imcManipulations.RemoveAt(idx); if (_imcManipulations.All(p => !ReferenceEquals(p.Item2, file))) @@ -94,8 +94,8 @@ public readonly struct ImcCache : IDisposable collection._cache!.ForceFile(file.Path, FullPath.Empty); file.Dispose(); return true; - } - + } + var def = ImcFile.GetDefault(manager, file.Path, m.EquipSlot, m.Variant.Id, out _); var manip = m.Copy(def); if (!manip.Apply(file)) diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index fa60993a..d2dd48f8 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -136,7 +136,7 @@ public class MetaCache : IDisposable, IEnumerable false, }; } - + /// Set a single file. public void SetFile(MetaIndex metaIndex) { @@ -162,7 +162,7 @@ public class MetaCache : IDisposable, IEnumerable Set the currently relevant IMC files for the collection cache. public void SetImcFiles(bool fromFullCompute) => _imcCache.SetFiles(_collection, fromFullCompute); @@ -171,7 +171,7 @@ public class MetaCache : IDisposable, IEnumerable _eqpCache.TemporarilySetFiles(_manager); public MetaList.MetaReverter TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) - => _eqdpCache.TemporarilySetFiles(_manager, genderRace, accessory); + => _eqdpCache.TemporarilySetFiles(_manager, genderRace, accessory); public MetaList.MetaReverter TemporarilySetGmpFile() => _gmpCache.TemporarilySetFiles(_manager); @@ -180,7 +180,7 @@ public class MetaCache : IDisposable, IEnumerable _cmpCache.TemporarilySetFiles(_manager); public MetaList.MetaReverter TemporarilySetEstFile(EstManipulation.EstType type) - => _estCache.TemporarilySetFiles(_manager, type); + => _estCache.TemporarilySetFiles(_manager, type); /// Try to obtain a manipulated IMC file. diff --git a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs index 5fcfd2f9..5872dea1 100644 --- a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs @@ -16,18 +16,18 @@ public static class ActiveCollectionMigration foreach (var (type, _, _) in CollectionTypeExtensions.Special.Where(t => t.Item2.StartsWith("Male "))) { var oldName = type.ToString()[4..]; - var value = jObject[oldName]; + var value = jObject[oldName]; if (value == null) continue; jObject.Remove(oldName); - jObject.Add("Male" + oldName, value); + jObject.Add("Male" + oldName, value); jObject.Add("Female" + oldName, value); } using var stream = File.Open(fileNames.ActiveCollectionsFile, FileMode.Truncate); using var writer = new StreamWriter(stream); - using var j = new JsonTextWriter(writer); + using var j = new JsonTextWriter(writer); j.Formatting = Formatting.Indented; jObject.WriteTo(j); } @@ -41,13 +41,14 @@ public static class ActiveCollectionMigration // Load character collections. If a player name comes up multiple times, the last one is applied. var characters = jObject["Characters"]?.ToObject>() ?? new Dictionary(); - var dict = new Dictionary(characters.Count); + var dict = new Dictionary(characters.Count); foreach (var (player, collectionName) in characters) { if (!storage.ByName(collectionName, out var collection)) { Penumbra.Chat.NotificationMessage( - $"Last choice of <{player}>'s Collection {collectionName} is not available, reset to {ModCollection.Empty.Name}.", "Load Failure", + $"Last choice of <{player}>'s Collection {collectionName} is not available, reset to {ModCollection.Empty.Name}.", + "Load Failure", NotificationType.Warning); dict.Add(player, ModCollection.Empty); } diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 58eb7517..bae95885 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -442,6 +442,7 @@ public class ActiveCollections : ISavable, IDisposable var m = ByType(CollectionTypeExtensions.FromParts(race, Gender.Male, false)); if (m != null && m != yourself) return string.Empty; + var f = ByType(CollectionTypeExtensions.FromParts(race, Gender.Female, false)); if (f != null && f != yourself) return string.Empty; @@ -450,26 +451,28 @@ public class ActiveCollections : ISavable, IDisposable } var racialString = racial ? " and Racial Assignments" : string.Empty; - var @base = ByType(CollectionType.Default); - var male = ByType(CollectionType.MalePlayerCharacter); - var female = ByType(CollectionType.FemalePlayerCharacter); + var @base = ByType(CollectionType.Default); + var male = ByType(CollectionType.MalePlayerCharacter); + var female = ByType(CollectionType.FemalePlayerCharacter); if (male == yourself && female == yourself) return $"Assignment is redundant due to overwriting Male Players and Female Players{racialString} with an identical collection.\nYou can remove it."; - + if (male == null) { if (female == null && @base == yourself) - return $"Assignment is redundant due to overwriting Base{racialString} with an identical collection.\nYou can remove it."; + return + $"Assignment is redundant due to overwriting Base{racialString} with an identical collection.\nYou can remove it."; if (female == yourself && @base == yourself) return $"Assignment is redundant due to overwriting Base and Female Players{racialString} with an identical collection.\nYou can remove it."; } else if (male == yourself && female == null && @base == yourself) { - return $"Assignment is redundant due to overwriting Base and Male Players{racialString} with an identical collection.\nYou can remove it."; + return + $"Assignment is redundant due to overwriting Base and Male Players{racialString} with an identical collection.\nYou can remove it."; } - + break; // Check individual assignments. We can only be sure of redundancy for world-overlap or ownership overlap. case CollectionType.Individual: diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 3d0ef60e..f0b4d509 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -2,6 +2,7 @@ using OtterGui; using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; namespace Penumbra.Collections.Manager; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index c172aeff..eb230e9e 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -5,6 +5,7 @@ using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; namespace Penumbra.Collections.Manager; @@ -246,7 +247,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) { - switch (type) + switch (type) { case ModPathChangeType.Added: foreach (var collection in this) diff --git a/Penumbra/Collections/Manager/CollectionType.cs b/Penumbra/Collections/Manager/CollectionType.cs index 8e2d1aed..8c51fd90 100644 --- a/Penumbra/Collections/Manager/CollectionType.cs +++ b/Penumbra/Collections/Manager/CollectionType.cs @@ -427,13 +427,13 @@ public static class CollectionTypeExtensions public static string ToDescription(this CollectionType collectionType) => collectionType switch { - CollectionType.Default => "World, Music, Furniture, baseline for characters and monsters not specialized.", - CollectionType.Interface => "User Interface, Icons, Maps, Styles.", - CollectionType.Yourself => "Your characters, regardless of name, race or gender. Applies in the login screen.", - CollectionType.MalePlayerCharacter => "Baseline for male player characters.", - CollectionType.FemalePlayerCharacter => "Baseline for female player characters.", - CollectionType.MaleNonPlayerCharacter => "Baseline for humanoid male non-player characters.", + CollectionType.Default => "World, Music, Furniture, baseline for characters and monsters not specialized.", + CollectionType.Interface => "User Interface, Icons, Maps, Styles.", + CollectionType.Yourself => "Your characters, regardless of name, race or gender. Applies in the login screen.", + CollectionType.MalePlayerCharacter => "Baseline for male player characters.", + CollectionType.FemalePlayerCharacter => "Baseline for female player characters.", + CollectionType.MaleNonPlayerCharacter => "Baseline for humanoid male non-player characters.", CollectionType.FemaleNonPlayerCharacter => "Baseline for humanoid female non-player characters.", - _ => string.Empty, + _ => string.Empty, }; } diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index ac4acb8e..489e2f72 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -47,7 +47,8 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa return true; // Handle generic NPC - var npcIdentifier = _actorService.AwaitedService.CreateIndividualUnchecked(IdentifierType.Npc, ByteString.Empty, ushort.MaxValue, + var npcIdentifier = _actorService.AwaitedService.CreateIndividualUnchecked(IdentifierType.Npc, ByteString.Empty, + ushort.MaxValue, identifier.Kind, identifier.DataId); if (npcIdentifier.IsValid && _individuals.TryGetValue(npcIdentifier, out collection)) return true; @@ -56,7 +57,8 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa if (!_config.UseOwnerNameForCharacterCollection) return false; - identifier = _actorService.AwaitedService.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, + identifier = _actorService.AwaitedService.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, + identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); return CheckWorlds(identifier, out collection); } @@ -142,7 +144,8 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa if (_individuals.TryGetValue(identifier, out collection)) return true; - identifier = _actorService.AwaitedService.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, ushort.MaxValue, identifier.Kind, + identifier = _actorService.AwaitedService.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, ushort.MaxValue, + identifier.Kind, identifier.DataId); if (identifier.IsValid && _individuals.TryGetValue(identifier, out collection)) return true; diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index da403337..21a0c730 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -27,6 +27,7 @@ public partial class IndividualCollections { if (_actorService.Valid) return ReadJObjectInternal(obj, storage); + void Func() { if (ReadJObjectInternal(obj, storage)) @@ -35,9 +36,10 @@ public partial class IndividualCollections Loaded.Invoke(); _actorService.FinishedCreation -= Func; } + _actorService.FinishedCreation += Func; return false; - } + } private bool ReadJObjectInternal(JArray? obj, CollectionStorage storage) { @@ -85,6 +87,7 @@ public partial class IndividualCollections NotificationType.Error); } } + return changes; } diff --git a/Penumbra/Collections/Manager/IndividualCollections.cs b/Penumbra/Collections/Manager/IndividualCollections.cs index e7547153..ed3c3d4b 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.cs @@ -132,7 +132,8 @@ public sealed partial class IndividualCollections _ => throw new NotImplementedException(), }; return table.Where(kvp => kvp.Value == name) - .Select(kvp => manager.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, identifier.HomeWorld.Id, identifier.Kind, + .Select(kvp => manager.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, identifier.HomeWorld.Id, + identifier.Kind, kvp.Key)).ToArray(); } diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index 56135182..025df9ef 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -1,5 +1,6 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.Util; diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index ae68a370..d788d0bd 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -92,7 +92,7 @@ public partial class ModCollection // Used for short periods of changed files. public MetaList.MetaReverter TemporarilySetEqdpFile(CharacterUtility utility, GenderRace genderRace, bool accessory) => _cache?.Meta.TemporarilySetEqdpFile(genderRace, accessory) - ?? utility.TemporarilyResetResource(Interop.Structs.CharacterUtilityData.EqdpIdx(genderRace, accessory)); + ?? utility.TemporarilyResetResource(CharacterUtilityData.EqdpIdx(genderRace, accessory)); public MetaList.MetaReverter TemporarilySetEqpFile(CharacterUtility utility) => _cache?.Meta.TemporarilySetEqpFile() @@ -109,4 +109,4 @@ public partial class ModCollection public MetaList.MetaReverter TemporarilySetEstFile(CharacterUtility utility, EstManipulation.EstType type) => _cache?.Meta.TemporarilySetEstFile(type) ?? utility.TemporarilyResetResource((MetaIndex)type); -} \ No newline at end of file +} diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index cb4aecc6..a9f565c6 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -1,6 +1,7 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Collections.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; namespace Penumbra.Collections; @@ -44,10 +45,10 @@ public partial class ModCollection /// This is used for material and imc changes. /// public int ChangeCounter { get; private set; } - - /// Increment the number of changes in the effective file list. + + /// Increment the number of changes in the effective file list. public int IncrementCounter() - => ++ChangeCounter; + => ++ChangeCounter; /// /// If a ModSetting is null, it can be inherited from other collections. @@ -57,7 +58,7 @@ public partial class ModCollection /// Settings for deleted mods will be kept via the mods identifier (directory name). public readonly IReadOnlyDictionary UnusedSettings; - + /// Inheritances stored before they can be applied. public IReadOnlyList? InheritanceByName; @@ -118,7 +119,7 @@ public partial class ModCollection /// Constructor for reading from files. public static ModCollection CreateFromData(SaveService saver, ModStorage mods, string name, int version, int index, Dictionary allSettings, IReadOnlyList inheritances) - { + { Debug.Assert(index > 0, "Collection read with non-positive index."); var ret = new ModCollection(name, index, 0, version, new List(), new List(), allSettings) { @@ -130,7 +131,7 @@ public partial class ModCollection } /// Constructor for temporary collections. - public static ModCollection CreateTemporary(string name, int index, int changeCounter) + public static ModCollection CreateTemporary(string name, int index, int changeCounter) { Debug.Assert(index < 0, "Temporary collection created with non-negative index."); var ret = new ModCollection(name, index, changeCounter, CurrentVersion, new List(), new List(), @@ -142,9 +143,10 @@ public partial class ModCollection public static ModCollection CreateEmpty(string name, int index, int modCount) { Debug.Assert(index >= 0, "Empty collection created with negative index."); - return new ModCollection(name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?) null, modCount).ToList(), new List(), + return new ModCollection(name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?)null, modCount).ToList(), + new List(), new Dictionary()); - } + } /// Add settings for a new appended mod, by checking if the mod had settings from a previous deletion. internal bool AddMod(Mod mod) diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index 05a8d9b0..4cc7706e 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -3,6 +3,7 @@ using Penumbra.Mods; using Penumbra.Services; using Newtonsoft.Json; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Util; namespace Penumbra.Collections; @@ -53,7 +54,7 @@ internal readonly struct ModCollectionSave : ISavable } list.AddRange(_modCollection.UnusedSettings.Select(kvp => (kvp.Key, kvp.Value))); - list.Sort((a, b) => string.Compare(a.Item1, b.Item1, StringComparison.OrdinalIgnoreCase)); + list.Sort((a, b) => string.Compare(a.Item1, b.Item1, StringComparison.OrdinalIgnoreCase)); foreach (var (modDir, settings) in list) { @@ -64,7 +65,7 @@ internal readonly struct ModCollectionSave : ISavable j.WriteEndObject(); // Inherit by collection name. - j.WritePropertyName("Inheritance"); + j.WritePropertyName("Inheritance"); x.Serialize(j, _modCollection.InheritanceByName ?? _modCollection.DirectlyInheritsFrom.Select(c => c.Name)); j.WriteEndObject(); } diff --git a/Penumbra/Collections/ResolveData.cs b/Penumbra/Collections/ResolveData.cs index 0c7bc967..0f3a1155 100644 --- a/Penumbra/Collections/ResolveData.cs +++ b/Penumbra/Collections/ResolveData.cs @@ -14,8 +14,8 @@ public readonly struct ResolveData public bool Valid => _modCollection != null; - public ResolveData() - : this(null!, nint.Zero) + public ResolveData() + : this(null!, nint.Zero) { } public ResolveData(ModCollection collection, nint gameObject) diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index d1830617..920e9cef 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -207,7 +207,8 @@ public class CommandHandler : IDisposable private bool SetUiMinimumSize(string _) { if (_config.MinimumSize.X == Configuration.Constants.MinimumSizeX && _config.MinimumSize.Y == Configuration.Constants.MinimumSizeY) - return false; + return false; + _config.MinimumSize.X = Configuration.Constants.MinimumSizeX; _config.MinimumSize.Y = Configuration.Constants.MinimumSizeY; _config.Save(); diff --git a/Penumbra/Communication/CollectionChange.cs b/Penumbra/Communication/CollectionChange.cs index b815c48e..b713cc72 100644 --- a/Penumbra/Communication/CollectionChange.cs +++ b/Penumbra/Communication/CollectionChange.cs @@ -45,7 +45,6 @@ public sealed class CollectionChange : EventWrapper ModFileSystemSelector = 0, - } public CollectionChange() diff --git a/Penumbra/Communication/ModDataChanged.cs b/Penumbra/Communication/ModDataChanged.cs index cca546e0..9ec60aa3 100644 --- a/Penumbra/Communication/ModDataChanged.cs +++ b/Penumbra/Communication/ModDataChanged.cs @@ -21,7 +21,7 @@ public sealed class ModDataChanged : EventWrapper ModCacheManager = 0, - /// + /// ModFileSystem = 0, } diff --git a/Penumbra/Communication/ModDiscoveryFinished.cs b/Penumbra/Communication/ModDiscoveryFinished.cs index 8f5d31d5..04c13e95 100644 --- a/Penumbra/Communication/ModDiscoveryFinished.cs +++ b/Penumbra/Communication/ModDiscoveryFinished.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Mods.Manager; namespace Penumbra.Communication; @@ -19,7 +20,7 @@ public sealed class ModDiscoveryFinished : EventWrapper ModCacheManager = 0, - /// + /// ModFileSystem = 0, } diff --git a/Penumbra/Communication/ModDiscoveryStarted.cs b/Penumbra/Communication/ModDiscoveryStarted.cs index a2ff8633..cf45528d 100644 --- a/Penumbra/Communication/ModDiscoveryStarted.cs +++ b/Penumbra/Communication/ModDiscoveryStarted.cs @@ -16,6 +16,7 @@ public sealed class ModDiscoveryStarted : EventWrapper ModFileSystemSelector = 200, } + public ModDiscoveryStarted() : base(nameof(ModDiscoveryStarted)) { } diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index 99ec9109..83c3b5a5 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -30,7 +30,7 @@ public sealed class ModPathChanged : EventWrapper ModExportManager = 0, - /// + /// ModFileSystem = 0, /// @@ -48,6 +48,7 @@ public sealed class ModPathChanged : EventWrapper CollectionCacheManagerRemoval = 100, } + public ModPathChanged() : base(nameof(ModPathChanged)) { } diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 72f8bb95..63d58a16 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -6,13 +6,14 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Widgets; using Penumbra.Api.Enums; -using Penumbra.GameData.Enums; using Penumbra.Import.Structs; using Penumbra.Interop.Services; using Penumbra.Mods; +using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; using Penumbra.UI.Classes; +using Penumbra.UI.ResourceWatcher; using Penumbra.UI.Tabs; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; diff --git a/Penumbra/GlobalUsings.cs b/Penumbra/GlobalUsings.cs index 0f6538bb..b1e6218c 100644 --- a/Penumbra/GlobalUsings.cs +++ b/Penumbra/GlobalUsings.cs @@ -2,13 +2,15 @@ global using System; global using System.Collections; +global using System.Collections.Concurrent; global using System.Collections.Generic; global using System.Diagnostics; global using System.IO; global using System.Linq; global using System.Numerics; +global using System.Reflection; global using System.Runtime.CompilerServices; global using System.Runtime.InteropServices; global using System.Security.Cryptography; global using System.Threading; -global using System.Threading.Tasks; \ No newline at end of file +global using System.Threading.Tasks; diff --git a/Penumbra/Import/Structs/ImporterState.cs b/Penumbra/Import/Structs/ImporterState.cs index 9ab2ab9a..8c0ddb4e 100644 --- a/Penumbra/Import/Structs/ImporterState.cs +++ b/Penumbra/Import/Structs/ImporterState.cs @@ -7,4 +7,4 @@ public enum ImporterState ExtractingModFiles, DeduplicatingFiles, Done, -} \ No newline at end of file +} diff --git a/Penumbra/Import/Structs/StreamDisposer.cs b/Penumbra/Import/Structs/StreamDisposer.cs index 7a755c40..84719331 100644 --- a/Penumbra/Import/Structs/StreamDisposer.cs +++ b/Penumbra/Import/Structs/StreamDisposer.cs @@ -20,4 +20,4 @@ public class StreamDisposer : PenumbraSqPackStream, IDisposable File.Delete(filePath); } -} \ No newline at end of file +} diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index a41b9f24..3b67ac50 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -15,19 +15,19 @@ namespace Penumbra.Import; public partial class TexToolsImporter { - /// + /// /// Extract regular compressed archives that are folders containing penumbra-formatted mods. /// The mod has to either contain a meta.json at top level, or one folder deep. /// If the meta.json is one folder deep, all other files have to be in the same folder. /// The extracted folder gets its name either from that one top-level folder or from the mod name. - /// All data is extracted without manipulation of the files or metadata. - /// - private DirectoryInfo HandleRegularArchive( FileInfo modPackFile ) + /// All data is extracted without manipulation of the files or metadata. + /// + private DirectoryInfo HandleRegularArchive(FileInfo modPackFile) { using var zfs = modPackFile.OpenRead(); - using var archive = ArchiveFactory.Open( zfs ); + using var archive = ArchiveFactory.Open(zfs); - var baseName = FindArchiveModMeta( archive, out var leadDir ); + var baseName = FindArchiveModMeta(archive, out var leadDir); var name = string.Empty; _currentOptionIdx = 0; _currentNumOptions = 1; @@ -42,9 +42,9 @@ public partial class TexToolsImporter SevenZipArchive s => s.Entries.Count, _ => archive.Entries.Count(), }; - Penumbra.Log.Information( $" -> Importing {archive.Type} Archive." ); + Penumbra.Log.Information($" -> Importing {archive.Type} Archive."); - _currentModDirectory = ModCreator.CreateModFolder( _baseDirectory, Path.GetRandomFileName() ); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetRandomFileName()); var options = new ExtractionOptions() { ExtractFullPath = true, @@ -55,40 +55,38 @@ public partial class TexToolsImporter _currentFileIdx = 0; var reader = archive.ExtractAllEntries(); - while( reader.MoveToNextEntry() ) + while (reader.MoveToNextEntry()) { _token.ThrowIfCancellationRequested(); - if( reader.Entry.IsDirectory ) + if (reader.Entry.IsDirectory) { --_currentNumFiles; continue; } - Penumbra.Log.Information( $" -> Extracting {reader.Entry.Key}" ); + Penumbra.Log.Information($" -> Extracting {reader.Entry.Key}"); // Check that the mod has a valid name in the meta.json file. - if( Path.GetFileName( reader.Entry.Key ) == "meta.json" ) + if (Path.GetFileName(reader.Entry.Key) == "meta.json") { using var s = new MemoryStream(); using var e = reader.OpenEntryStream(); - e.CopyTo( s ); - s.Seek( 0, SeekOrigin.Begin ); - using var t = new StreamReader( s ); - using var j = new JsonTextReader( t ); - var obj = JObject.Load( j ); - name = obj[ nameof( Mod.Name ) ]?.Value< string >()?.RemoveInvalidPathSymbols() ?? string.Empty; - if( name.Length == 0 ) - { - throw new Exception( "Invalid mod archive: mod meta has no name." ); - } + e.CopyTo(s); + s.Seek(0, SeekOrigin.Begin); + using var t = new StreamReader(s); + using var j = new JsonTextReader(t); + var obj = JObject.Load(j); + name = obj[nameof(Mod.Name)]?.Value()?.RemoveInvalidPathSymbols() ?? string.Empty; + if (name.Length == 0) + throw new Exception("Invalid mod archive: mod meta has no name."); - using var f = File.OpenWrite( Path.Combine( _currentModDirectory.FullName, reader.Entry.Key ) ); - s.Seek( 0, SeekOrigin.Begin ); - s.WriteTo( f ); + using var f = File.OpenWrite(Path.Combine(_currentModDirectory.FullName, reader.Entry.Key)); + s.Seek(0, SeekOrigin.Begin); + s.WriteTo(f); } else { - reader.WriteEntryToDirectory( _currentModDirectory.FullName, options ); + reader.WriteEntryToDirectory(_currentModDirectory.FullName, options); } ++_currentFileIdx; @@ -97,60 +95,59 @@ public partial class TexToolsImporter _token.ThrowIfCancellationRequested(); var oldName = _currentModDirectory.FullName; // Use either the top-level directory as the mods base name, or the (fixed for path) name in the json. - if( leadDir ) + if (leadDir) { - _currentModDirectory = ModCreator.CreateModFolder( _baseDirectory, baseName, false ); - Directory.Move( Path.Combine( oldName, baseName ), _currentModDirectory.FullName ); - Directory.Delete( oldName ); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, baseName, false); + Directory.Move(Path.Combine(oldName, baseName), _currentModDirectory.FullName); + Directory.Delete(oldName); } else { - _currentModDirectory = ModCreator.CreateModFolder( _baseDirectory, name, false ); - Directory.Move( oldName, _currentModDirectory.FullName ); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, name, false); + Directory.Move(oldName, _currentModDirectory.FullName); } _currentModDirectory.Refresh(); - _modManager.Creator.SplitMultiGroups( _currentModDirectory ); + _modManager.Creator.SplitMultiGroups(_currentModDirectory); return _currentModDirectory; } // Search the archive for the meta.json file which needs to exist. - private static string FindArchiveModMeta( IArchive archive, out bool leadDir ) + private static string FindArchiveModMeta(IArchive archive, out bool leadDir) { - var entry = archive.Entries.FirstOrDefault( e => !e.IsDirectory && Path.GetFileName( e.Key ) == "meta.json" ); + var entry = archive.Entries.FirstOrDefault(e => !e.IsDirectory && Path.GetFileName(e.Key) == "meta.json"); // None found. - if( entry == null ) - { - throw new Exception( "Invalid mod archive: No meta.json contained." ); - } + if (entry == null) + throw new Exception("Invalid mod archive: No meta.json contained."); var ret = string.Empty; leadDir = false; // If the file is not at top-level. - if( entry.Key != "meta.json" ) + if (entry.Key != "meta.json") { leadDir = true; - var directory = Path.GetDirectoryName( entry.Key ); + var directory = Path.GetDirectoryName(entry.Key); // Should not happen. - if( directory.IsNullOrEmpty() ) - { - throw new Exception( "Invalid mod archive: Unknown error fetching meta.json." ); - } + if (directory.IsNullOrEmpty()) + throw new Exception("Invalid mod archive: Unknown error fetching meta.json."); ret = directory; // Check that all other files are also contained in the top-level directory. - if( ret.IndexOfAny( new[] { '/', '\\' } ) >= 0 - || !archive.Entries.All( e => e.Key.StartsWith( ret ) && ( e.Key.Length == ret.Length || e.Key[ ret.Length ] is '/' or '\\' ) ) ) - { + if (ret.IndexOfAny(new[] + { + '/', + '\\', + }) + >= 0 + || !archive.Entries.All(e => e.Key.StartsWith(ret) && (e.Key.Length == ret.Length || e.Key[ret.Length] is '/' or '\\'))) throw new Exception( - "Invalid mod archive: meta.json in wrong location. It needs to be either at root or one directory deep, in which all other files must be nested too." ); - } + "Invalid mod archive: meta.json in wrong location. It needs to be either at root or one directory deep, in which all other files must be nested too."); } return ret; } -} \ No newline at end of file +} diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index 0c3e084d..e150d10d 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -1,7 +1,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; -using Penumbra.Import.Structs; +using Penumbra.Import.Structs; using Penumbra.UI.Classes; namespace Penumbra.Import; @@ -20,89 +20,79 @@ public partial class TexToolsImporter private string _currentOptionName = string.Empty; private string _currentFileName = string.Empty; - public void DrawProgressInfo( Vector2 size ) + public void DrawProgressInfo(Vector2 size) { - if( _modPackCount == 0 ) + if (_modPackCount == 0) { - ImGuiUtil.Center( "Nothing to extract." ); + ImGuiUtil.Center("Nothing to extract."); } - else if( _modPackCount == _currentModPackIdx ) + else if (_modPackCount == _currentModPackIdx) { DrawEndState(); } else { ImGui.NewLine(); - var percentage = _modPackCount / ( float )_currentModPackIdx; - ImGui.ProgressBar( percentage, size, $"Mod {_currentModPackIdx + 1} / {_modPackCount}" ); + var percentage = _modPackCount / (float)_currentModPackIdx; + ImGui.ProgressBar(percentage, size, $"Mod {_currentModPackIdx + 1} / {_modPackCount}"); ImGui.NewLine(); - if( State == ImporterState.DeduplicatingFiles ) - { - ImGui.TextUnformatted( $"Deduplicating {_currentModName}..." ); - } + if (State == ImporterState.DeduplicatingFiles) + ImGui.TextUnformatted($"Deduplicating {_currentModName}..."); else - { - ImGui.TextUnformatted( $"Extracting {_currentModName}..." ); - } + ImGui.TextUnformatted($"Extracting {_currentModName}..."); - if( _currentNumOptions > 1 ) + if (_currentNumOptions > 1) { ImGui.NewLine(); ImGui.NewLine(); - percentage = _currentNumOptions == 0 ? 1f : _currentOptionIdx / ( float )_currentNumOptions; - ImGui.ProgressBar( percentage, size, $"Option {_currentOptionIdx + 1} / {_currentNumOptions}" ); + percentage = _currentNumOptions == 0 ? 1f : _currentOptionIdx / (float)_currentNumOptions; + ImGui.ProgressBar(percentage, size, $"Option {_currentOptionIdx + 1} / {_currentNumOptions}"); ImGui.NewLine(); - if( State != ImporterState.DeduplicatingFiles ) - { + if (State != ImporterState.DeduplicatingFiles) ImGui.TextUnformatted( - $"Extracting option {( _currentGroupName.Length == 0 ? string.Empty : $"{_currentGroupName} - " )}{_currentOptionName}..." ); - } + $"Extracting option {(_currentGroupName.Length == 0 ? string.Empty : $"{_currentGroupName} - ")}{_currentOptionName}..."); } ImGui.NewLine(); ImGui.NewLine(); - percentage = _currentNumFiles == 0 ? 1f : _currentFileIdx / ( float )_currentNumFiles; - ImGui.ProgressBar( percentage, size, $"File {_currentFileIdx + 1} / {_currentNumFiles}" ); + percentage = _currentNumFiles == 0 ? 1f : _currentFileIdx / (float)_currentNumFiles; + ImGui.ProgressBar(percentage, size, $"File {_currentFileIdx + 1} / {_currentNumFiles}"); ImGui.NewLine(); - if( State != ImporterState.DeduplicatingFiles ) - { - ImGui.TextUnformatted( $"Extracting file {_currentFileName}..." ); - } + if (State != ImporterState.DeduplicatingFiles) + ImGui.TextUnformatted($"Extracting file {_currentFileName}..."); } } private void DrawEndState() { - var success = ExtractedMods.Count( t => t.Error == null ); + var success = ExtractedMods.Count(t => t.Error == null); - ImGui.TextUnformatted( $"Successfully extracted {success} / {ExtractedMods.Count} files." ); + ImGui.TextUnformatted($"Successfully extracted {success} / {ExtractedMods.Count} files."); ImGui.NewLine(); - using var table = ImRaii.Table( "##files", 2 ); - if( !table ) - { + using var table = ImRaii.Table("##files", 2); + if (!table) return; - } - foreach( var (file, dir, ex) in ExtractedMods ) + foreach (var (file, dir, ex) in ExtractedMods) { ImGui.TableNextColumn(); - ImGui.TextUnformatted( file.Name ); + ImGui.TextUnformatted(file.Name); ImGui.TableNextColumn(); - if( ex == null ) + if (ex == null) { - using var color = ImRaii.PushColor( ImGuiCol.Text, ColorId.FolderExpanded.Value() ); - ImGui.TextUnformatted( dir?.FullName[ ( _baseDirectory.FullName.Length + 1 ).. ] ?? "Unknown Directory" ); + using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()); + ImGui.TextUnformatted(dir?.FullName[(_baseDirectory.FullName.Length + 1)..] ?? "Unknown Directory"); } else { - using var color = ImRaii.PushColor( ImGuiCol.Text, ColorId.ConflictingMod.Value() ); - ImGui.TextUnformatted( ex.Message ); - ImGuiUtil.HoverTooltip( ex.ToString() ); + using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ConflictingMod.Value()); + ImGui.TextUnformatted(ex.Message); + ImGuiUtil.HoverTooltip(ex.ToString()); } } } - public bool DrawCancelButton( Vector2 size ) - => ImGuiUtil.DrawDisabledButton( "Cancel", size, string.Empty, _token.IsCancellationRequested ); -} \ No newline at end of file + public bool DrawCancelButton(Vector2 size) + => ImGuiUtil.DrawDisabledButton("Cancel", size, string.Empty, _token.IsCancellationRequested); +} diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index eea1d811..64eff8ba 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -116,7 +116,7 @@ public partial class TexToolsMeta var partIdx = ImcFile.PartIndex(manip.EquipSlot); // Gets turned to unknown for things without equip, and unknown turns to 0. foreach (var value in values) { - if (_keepDefault || !value.Equals(def.GetEntry(partIdx, (Variant) i))) + if (_keepDefault || !value.Equals(def.GetEntry(partIdx, (Variant)i))) { var imc = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, i, manip.EquipSlot, value); diff --git a/Penumbra/Import/TexToolsMeta.Rgsp.cs b/Penumbra/Import/TexToolsMeta.Rgsp.cs index 0fd94fb4..51faa175 100644 --- a/Penumbra/Import/TexToolsMeta.Rgsp.cs +++ b/Penumbra/Import/TexToolsMeta.Rgsp.cs @@ -8,72 +8,70 @@ namespace Penumbra.Import; public partial class TexToolsMeta { // Parse a single rgsp file. - public static TexToolsMeta FromRgspFile( MetaFileManager manager, string filePath, byte[] data, bool keepDefault ) + public static TexToolsMeta FromRgspFile(MetaFileManager manager, string filePath, byte[] data, bool keepDefault) { - if( data.Length != 45 && data.Length != 42 ) + if (data.Length != 45 && data.Length != 42) { - Penumbra.Log.Error( "Error while parsing .rgsp file:\n\tInvalid number of bytes." ); + Penumbra.Log.Error("Error while parsing .rgsp file:\n\tInvalid number of bytes."); return Invalid; } - using var s = new MemoryStream( data ); - using var br = new BinaryReader( s ); + using var s = new MemoryStream(data); + using var br = new BinaryReader(s); // The first value is a flag that signifies version. // If it is byte.max, the following two bytes are the version, // otherwise it is version 1 and signifies the sub race instead. var flag = br.ReadByte(); - var version = flag != 255 ? ( uint )1 : br.ReadUInt16(); + var version = flag != 255 ? (uint)1 : br.ReadUInt16(); - var ret = new TexToolsMeta( manager, filePath, version ); + var ret = new TexToolsMeta(manager, filePath, version); // SubRace is offset by one due to Unknown. - var subRace = ( SubRace )( version == 1 ? flag + 1 : br.ReadByte() + 1 ); - if( !Enum.IsDefined( typeof( SubRace ), subRace ) || subRace == SubRace.Unknown ) + var subRace = (SubRace)(version == 1 ? flag + 1 : br.ReadByte() + 1); + if (!Enum.IsDefined(typeof(SubRace), subRace) || subRace == SubRace.Unknown) { - Penumbra.Log.Error( $"Error while parsing .rgsp file:\n\t{subRace} is not a valid SubRace." ); + Penumbra.Log.Error($"Error while parsing .rgsp file:\n\t{subRace} is not a valid SubRace."); return Invalid; } // Next byte is Gender. 1 is Female, 0 is Male. var gender = br.ReadByte(); - if( gender != 1 && gender != 0 ) + if (gender != 1 && gender != 0) { - Penumbra.Log.Error( $"Error while parsing .rgsp file:\n\t{gender} is neither Male nor Female." ); + Penumbra.Log.Error($"Error while parsing .rgsp file:\n\t{gender} is neither Male nor Female."); return Invalid; } // Add the given values to the manipulations if they are not default. - void Add( RspAttribute attribute, float value ) + void Add(RspAttribute attribute, float value) { - var def = CmpFile.GetDefault( manager, subRace, attribute ); - if( keepDefault || value != def ) - { - ret.MetaManipulations.Add( new RspManipulation( subRace, attribute, value ) ); - } + var def = CmpFile.GetDefault(manager, subRace, attribute); + if (keepDefault || value != def) + ret.MetaManipulations.Add(new RspManipulation(subRace, attribute, value)); } - if( gender == 1 ) + if (gender == 1) { - Add( RspAttribute.FemaleMinSize, br.ReadSingle() ); - Add( RspAttribute.FemaleMaxSize, br.ReadSingle() ); - Add( RspAttribute.FemaleMinTail, br.ReadSingle() ); - Add( RspAttribute.FemaleMaxTail, br.ReadSingle() ); + Add(RspAttribute.FemaleMinSize, br.ReadSingle()); + Add(RspAttribute.FemaleMaxSize, br.ReadSingle()); + Add(RspAttribute.FemaleMinTail, br.ReadSingle()); + Add(RspAttribute.FemaleMaxTail, br.ReadSingle()); - Add( RspAttribute.BustMinX, br.ReadSingle() ); - Add( RspAttribute.BustMinY, br.ReadSingle() ); - Add( RspAttribute.BustMinZ, br.ReadSingle() ); - Add( RspAttribute.BustMaxX, br.ReadSingle() ); - Add( RspAttribute.BustMaxY, br.ReadSingle() ); - Add( RspAttribute.BustMaxZ, br.ReadSingle() ); + Add(RspAttribute.BustMinX, br.ReadSingle()); + Add(RspAttribute.BustMinY, br.ReadSingle()); + Add(RspAttribute.BustMinZ, br.ReadSingle()); + Add(RspAttribute.BustMaxX, br.ReadSingle()); + Add(RspAttribute.BustMaxY, br.ReadSingle()); + Add(RspAttribute.BustMaxZ, br.ReadSingle()); } else { - Add( RspAttribute.MaleMinSize, br.ReadSingle() ); - Add( RspAttribute.MaleMaxSize, br.ReadSingle() ); - Add( RspAttribute.MaleMinTail, br.ReadSingle() ); - Add( RspAttribute.MaleMaxTail, br.ReadSingle() ); + Add(RspAttribute.MaleMinSize, br.ReadSingle()); + Add(RspAttribute.MaleMaxSize, br.ReadSingle()); + Add(RspAttribute.MaleMinTail, br.ReadSingle()); + Add(RspAttribute.MaleMaxTail, br.ReadSingle()); } return ret; } -} \ No newline at end of file +} diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index b44f99a8..a188975c 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -17,70 +17,68 @@ namespace Penumbra.Import; /// TexTools may also generate files that contain non-existing changes, e.g. *.imc files for weapon offhands, which will be ignored. /// TexTools also provides .rgsp files, that contain changes to the racial scaling parameters in the human.cmp file. public partial class TexToolsMeta -{ +{ /// An empty TexToolsMeta. public static readonly TexToolsMeta Invalid = new(null!, string.Empty, 0); // The info class determines the files or table locations the changes need to apply to from the filename. - public readonly uint Version; - public readonly string FilePath; - public readonly List< MetaManipulation > MetaManipulations = new(); - private readonly bool _keepDefault = false; - - private readonly MetaFileManager _metaFileManager; + public readonly uint Version; + public readonly string FilePath; + public readonly List MetaManipulations = new(); + private readonly bool _keepDefault = false; - public TexToolsMeta( MetaFileManager metaFileManager, IGamePathParser parser, byte[] data, bool keepDefault ) - { + private readonly MetaFileManager _metaFileManager; + + public TexToolsMeta(MetaFileManager metaFileManager, IGamePathParser parser, byte[] data, bool keepDefault) + { _metaFileManager = metaFileManager; - _keepDefault = keepDefault; + _keepDefault = keepDefault; try { - using var reader = new BinaryReader( new MemoryStream( data ) ); + using var reader = new BinaryReader(new MemoryStream(data)); Version = reader.ReadUInt32(); - FilePath = ReadNullTerminated( reader ); - var metaInfo = new MetaFileInfo( parser, FilePath ); + FilePath = ReadNullTerminated(reader); + var metaInfo = new MetaFileInfo(parser, FilePath); var numHeaders = reader.ReadUInt32(); var headerSize = reader.ReadUInt32(); var headerStart = reader.ReadUInt32(); - reader.BaseStream.Seek( headerStart, SeekOrigin.Begin ); + reader.BaseStream.Seek(headerStart, SeekOrigin.Begin); - List< (MetaManipulation.Type type, uint offset, int size) > entries = new(); - for( var i = 0; i < numHeaders; ++i ) + List<(MetaManipulation.Type type, uint offset, int size)> entries = new(); + for (var i = 0; i < numHeaders; ++i) { var currentOffset = reader.BaseStream.Position; - var type = ( MetaManipulation.Type )reader.ReadUInt32(); + var type = (MetaManipulation.Type)reader.ReadUInt32(); var offset = reader.ReadUInt32(); var size = reader.ReadInt32(); - entries.Add( ( type, offset, size ) ); - reader.BaseStream.Seek( currentOffset + headerSize, SeekOrigin.Begin ); + entries.Add((type, offset, size)); + reader.BaseStream.Seek(currentOffset + headerSize, SeekOrigin.Begin); } - byte[]? ReadEntry( MetaManipulation.Type type ) + byte[]? ReadEntry(MetaManipulation.Type type) { - var idx = entries.FindIndex( t => t.type == type ); - if( idx < 0 ) - { + var idx = entries.FindIndex(t => t.type == type); + if (idx < 0) return null; - } - reader.BaseStream.Seek( entries[ idx ].offset, SeekOrigin.Begin ); - return reader.ReadBytes( entries[ idx ].size ); + reader.BaseStream.Seek(entries[idx].offset, SeekOrigin.Begin); + return reader.ReadBytes(entries[idx].size); } - DeserializeEqpEntry( metaInfo, ReadEntry( MetaManipulation.Type.Eqp ) ); - DeserializeGmpEntry( metaInfo, ReadEntry( MetaManipulation.Type.Gmp ) ); - DeserializeEqdpEntries( metaInfo, ReadEntry( MetaManipulation.Type.Eqdp ) ); - DeserializeEstEntries( metaInfo, ReadEntry( MetaManipulation.Type.Est ) ); - DeserializeImcEntries( metaInfo, ReadEntry( MetaManipulation.Type.Imc ) ); + DeserializeEqpEntry(metaInfo, ReadEntry(MetaManipulation.Type.Eqp)); + DeserializeGmpEntry(metaInfo, ReadEntry(MetaManipulation.Type.Gmp)); + DeserializeEqdpEntries(metaInfo, ReadEntry(MetaManipulation.Type.Eqdp)); + DeserializeEstEntries(metaInfo, ReadEntry(MetaManipulation.Type.Est)); + DeserializeImcEntries(metaInfo, ReadEntry(MetaManipulation.Type.Imc)); } - catch( Exception e ) + catch (Exception e) { FilePath = ""; - Penumbra.Log.Error( $"Error while parsing .meta file:\n{e}" ); + Penumbra.Log.Error($"Error while parsing .meta file:\n{e}"); } } - private TexToolsMeta( MetaFileManager metaFileManager, string filePath, uint version ) + private TexToolsMeta(MetaFileManager metaFileManager, string filePath, uint version) { _metaFileManager = metaFileManager; FilePath = filePath; @@ -88,14 +86,12 @@ public partial class TexToolsMeta } // Read a null terminated string from a binary reader. - private static string ReadNullTerminated( BinaryReader reader ) + private static string ReadNullTerminated(BinaryReader reader) { var builder = new StringBuilder(); - for( var c = reader.ReadChar(); c != 0; c = reader.ReadChar() ) - { - builder.Append( c ); - } + for (var c = reader.ReadChar(); c != 0; c = reader.ReadChar()) + builder.Append(c); return builder.ToString(); } -} \ No newline at end of file +} diff --git a/Penumbra/Import/Textures/RgbaPixelData.cs b/Penumbra/Import/Textures/RgbaPixelData.cs index 32540f16..7c28b72b 100644 --- a/Penumbra/Import/Textures/RgbaPixelData.cs +++ b/Penumbra/Import/Textures/RgbaPixelData.cs @@ -13,8 +13,7 @@ public readonly record struct RgbaPixelData(int Width, int Height, byte[] PixelD public RgbaPixelData((int Width, int Height) size, byte[] pixelData) : this(size.Width, size.Height, pixelData) - { - } + { } public Image ToImage() => Image.LoadPixelData(PixelData, Width, Height); diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 7f324601..15d45be6 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -79,8 +79,8 @@ public static class TexFileParser w.Write(header.Width); w.Write(header.Height); w.Write(header.Depth); - w.Write((byte) header.MipLevels); - w.Write((byte) 0); // TODO Lumina Update + w.Write((byte)header.MipLevels); + w.Write((byte)0); // TODO Lumina Update unsafe { w.Write(header.LodOffset[0]); diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index b94fdbf8..a5692c23 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -103,7 +103,7 @@ public static class TextureDrawer public sealed class PathSelectCombo : FilterComboCache<(string, bool)> { - private int _skipPrefix = 0; + private int _skipPrefix = 0; public PathSelectCombo(TextureManager textures, ModEditor editor) : base(() => CreateFiles(textures, editor)) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 90dfa3d0..31c3275e 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using Dalamud.Interface; using Dalamud.Plugin.Services; using ImGuiScene; diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index f83b1531..e89f0d10 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -80,7 +80,8 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase textureSize[0] = TextureWidth; textureSize[1] = TextureHeight; - using var texture = new SafeTextureHandle(Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7), false); + using var texture = + new SafeTextureHandle(Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7), false); if (texture.IsInvalid) return; diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index cc679bfd..51612819 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -17,7 +17,7 @@ namespace Penumbra.Interop.PathResolving; public unsafe class AnimationHookService : IDisposable { private readonly PerformanceTracker _performance; - private readonly IObjectTable _objects; + private readonly IObjectTable _objects; private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; private readonly CollectionResolver _resolver; @@ -34,7 +34,7 @@ public unsafe class AnimationHookService : IDisposable _collectionResolver = collectionResolver; _drawObjectState = drawObjectState; _resolver = resolver; - _conditions = conditions; + _conditions = conditions; SignatureHelper.Initialise(this); @@ -122,7 +122,7 @@ public unsafe class AnimationHookService : IDisposable var last = _characterSoundData.Value; _characterSoundData.Value = _collectionResolver.IdentifyCollection((GameObject*)character, true); var ret = _loadCharacterSoundHook.Original(character, unk1, unk2, unk3, unk4, unk5, unk6, unk7); - _characterSoundData.Value = last; + _characterSoundData.Value = last; return ret; } @@ -140,15 +140,15 @@ public unsafe class AnimationHookService : IDisposable using var performance = _performance.Measure(PerformanceType.TimelineResources); // Do not check timeline loading in cutscenes. if (_conditions[ConditionFlag.OccupiedInCutSceneEvent] || _conditions[ConditionFlag.WatchingCutscene78]) - return _loadTimelineResourcesHook.Original(timeline); + return _loadTimelineResourcesHook.Original(timeline); - var last = _animationLoadData.Value; + var last = _animationLoadData.Value; _animationLoadData.Value = GetDataFromTimeline(timeline); var ret = _loadTimelineResourcesHook.Original(timeline); _animationLoadData.Value = last; return ret; } - + /// /// Probably used when the base idle animation gets loaded. /// Make it aware of the correct collection to load the correct pap files. @@ -297,12 +297,12 @@ public unsafe class AnimationHookService : IDisposable try { if (timeline != IntPtr.Zero) - { + { var getGameObjectIdx = ((delegate* unmanaged**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; var idx = getGameObjectIdx(timeline); if (idx >= 0 && idx < _objects.Length) { - var obj = (GameObject*)_objects.GetObjectAddress(idx); + var obj = (GameObject*)_objects.GetObjectAddress(idx); return obj != null ? _collectionResolver.IdentifyCollection(obj, true) : ResolveData.Invalid; } } @@ -378,17 +378,17 @@ public unsafe class AnimationHookService : IDisposable if (a6 == nint.Zero) return _apricotListenerSoundPlayHook!.Original(a1, a2, a3, a4, a5, a6); - var last = _animationLoadData.Value; - // a6 is some instance of Apricot.IInstanceListenner, in some cases we can obtain the associated caster via vfunc 1. + var last = _animationLoadData.Value; + // a6 is some instance of Apricot.IInstanceListenner, in some cases we can obtain the associated caster via vfunc 1. var gameObject = (*(delegate* unmanaged**)a6)[1](a6); if (gameObject != null) { _animationLoadData.Value = _collectionResolver.IdentifyCollection(gameObject, true); } else - { - // for VfxListenner we can obtain the associated draw object as its first member, - // if the object has different type, drawObject will contain other values or garbage, + { + // for VfxListenner we can obtain the associated draw object as its first member, + // if the object has different type, drawObject will contain other values or garbage, // but only be used in a dictionary pointer lookup, so this does not hurt. var drawObject = ((DrawObject**)a6)[1]; if (drawObject != null) diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 3f73643b..ecd4eb2e 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -20,7 +20,7 @@ public unsafe class CollectionResolver private readonly HumanModelList _humanModels; private readonly IClientState _clientState; - private readonly IGameGui _gameGui; + private readonly IGameGui _gameGui; private readonly ActorService _actors; private readonly CutsceneService _cutscenes; diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 512d370a..be1484db 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -10,7 +10,7 @@ namespace Penumbra.Interop.PathResolving; public class DrawObjectState : IDisposable, IReadOnlyDictionary { - private readonly IObjectTable _objects; + private readonly IObjectTable _objects; private readonly GameEventManager _gameEvents; private readonly Dictionary _drawObjectToGameObject = new(); @@ -71,8 +71,8 @@ public class DrawObjectState : IDisposable, IReadOnlyDictionaryDrawObject, gameObject, false, false); + _lastGameObject.Value!.Dequeue(); + IterateDrawObjectTree((Object*)((GameObject*)gameObject)->DrawObject, gameObject, false, false); } private void OnCharacterBaseDestructor(nint characterBase) diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 546ffd92..0b456b3c 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -25,8 +25,8 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A _events = events; _communicator.CollectionChange.Subscribe(CollectionChangeClear, CollectionChange.Priority.IdentifiedCollectionCache); - _clientState.TerritoryChanged += TerritoryClear; - _events.CharacterDestructor += OnCharacterDestruct; + _clientState.TerritoryChanged += TerritoryClear; + _events.CharacterDestructor += OnCharacterDestruct; } public ResolveData Set(ModCollection collection, ActorIdentifier identifier, GameObject* data) @@ -61,8 +61,8 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A public void Dispose() { _communicator.CollectionChange.Unsubscribe(CollectionChangeClear); - _clientState.TerritoryChanged -= TerritoryClear; - _events.CharacterDestructor -= OnCharacterDestruct; + _clientState.TerritoryChanged -= TerritoryClear; + _events.CharacterDestructor -= OnCharacterDestruct; } public IEnumerator<(nint Address, ActorIdentifier Identifier, ModCollection Collection)> GetEnumerator() diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 2176ebba..4494dc77 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,5 +1,6 @@ using System.Diagnostics.CodeAnalysis; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Enums; diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index b1bc806d..00b06963 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using Dalamud.Hooking; using Dalamud.Utility.Signatures; using Penumbra.Collections; diff --git a/Penumbra/Interop/ResourceLoading/FileReadService.cs b/Penumbra/Interop/ResourceLoading/FileReadService.cs index 6ca0efb4..9dc89ab2 100644 --- a/Penumbra/Interop/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/ResourceLoading/FileReadService.cs @@ -81,6 +81,6 @@ public unsafe class FileReadService : IDisposable /// private nint GetResourceManager() => !_lastFileThreadResourceManager.IsValueCreated || _lastFileThreadResourceManager.Value == IntPtr.Zero - ? (nint) _resourceManager.ResourceManager + ? (nint)_resourceManager.ResourceManager : _lastFileThreadResourceManager.Value; } diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index cae89c09..c3327a9e 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -37,7 +37,8 @@ public class ResourceNode Children = new List(); } - public ResourceNode(UIData uiData, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath[] possibleGamePaths, FullPath fullPath, + public ResourceNode(UIData uiData, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath[] possibleGamePaths, + FullPath fullPath, ulong length, bool @internal) { Name = uiData.Name; @@ -69,7 +70,7 @@ public class ResourceNode } public ResourceNode WithUIData(string? name, ChangedItemIcon icon) - => string.Equals(Name, name, StringComparison.Ordinal) && Icon == icon ? this : new ResourceNode(new(name, icon), this); + => string.Equals(Name, name, StringComparison.Ordinal) && Icon == icon ? this : new ResourceNode(new UIData(name, icon), this); public ResourceNode WithUIData(UIData uiData) => string.Equals(Name, uiData.Name, StringComparison.Ordinal) && Icon == uiData.Icon ? this : new ResourceNode(uiData, this); @@ -77,6 +78,6 @@ public class ResourceNode public readonly record struct UIData(string? Name, ChangedItemIcon Icon) { public readonly UIData PrependName(string prefix) - => Name == null ? this : new(prefix + Name, Icon); + => Name == null ? this : new UIData(prefix + Name, Icon); } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index d2276291..a8ad9d4f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,6 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -16,7 +16,7 @@ public class ResourceTree public readonly nint DrawObjectAddress; public readonly bool PlayerRelated; public readonly string CollectionName; - public readonly List Nodes; + public readonly List Nodes; public readonly HashSet FlatNodes; public int ModelId; @@ -26,11 +26,11 @@ public class ResourceTree public ResourceTree(string name, nint gameObjectAddress, nint drawObjectAddress, bool playerRelated, string collectionName) { Name = name; - GameObjectAddress = gameObjectAddress; + GameObjectAddress = gameObjectAddress; DrawObjectAddress = drawObjectAddress; PlayerRelated = playerRelated; CollectionName = collectionName; - Nodes = new List(); + Nodes = new List(); FlatNodes = new HashSet(); } @@ -42,7 +42,7 @@ public class ResourceTree // var customize = new ReadOnlySpan( character->CustomizeData, 26 ); ModelId = character->CharacterData.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; - RaceCode = model->GetModelType() == CharacterBase.ModelType.Human ? (GenderRace) ((Human*)model)->RaceSexId : GenderRace.Unknown; + RaceCode = model->GetModelType() == CharacterBase.ModelType.Human ? (GenderRace)((Human*)model)->RaceSexId : GenderRace.Unknown; for (var i = 0; i < model->SlotCount; ++i) { @@ -60,8 +60,8 @@ public class ResourceTree var mdlNode = context.CreateNodeFromRenderModel(mdl); if (mdlNode != null) Nodes.Add(globalContext.WithUiData ? mdlNode.WithUIData(mdlNode.Name ?? $"Model #{i}", mdlNode.Icon) : mdlNode); - } - + } + AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); if (character->GameObject.GetObjectKind() == (byte)ObjectKind.Pc) @@ -100,8 +100,8 @@ public class ResourceTree subObjectNodes.Add(globalContext.WithUiData ? mdlNode.WithUIData(mdlNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}", mdlNode.Icon) : mdlNode); - } - + } + AddSkeleton(subObjectNodes, subObjectContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); subObject = (CharacterBase*)subObject->DrawObject.Object.NextSiblingObject; @@ -119,19 +119,21 @@ public class ResourceTree var legacyDecalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->LegacyBodyDecal); if (legacyDecalNode != null) - Nodes.Add(globalContext.WithUiData ? legacyDecalNode.WithUIData(legacyDecalNode.Name ?? "Legacy Body Decal", legacyDecalNode.Icon) : legacyDecalNode); - } - - private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") - { - if (skeleton == null) - return; - - for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) - { - var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); - if (sklbNode != null) - nodes.Add(context.WithUiData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); - } + Nodes.Add(globalContext.WithUiData + ? legacyDecalNode.WithUIData(legacyDecalNode.Name ?? "Legacy Body Decal", legacyDecalNode.Icon) + : legacyDecalNode); + } + + private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") + { + if (skeleton == null) + return; + + for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) + { + var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); + if (sklbNode != null) + nodes.Add(context.WithUiData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); + } } } diff --git a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs index 8dd1fb4a..1f788a39 100644 --- a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs @@ -4,21 +4,25 @@ namespace Penumbra.Interop.SafeHandles; public unsafe class SafeResourceHandle : SafeHandle { - public ResourceHandle* ResourceHandle => (ResourceHandle*)handle; + public ResourceHandle* ResourceHandle + => (ResourceHandle*)handle; - public override bool IsInvalid => handle == 0; + public override bool IsInvalid + => handle == 0; - public SafeResourceHandle(ResourceHandle* handle, bool incRef, bool ownsHandle = true) : base(0, ownsHandle) + public SafeResourceHandle(ResourceHandle* handle, bool incRef, bool ownsHandle = true) + : base(0, ownsHandle) { if (incRef && !ownsHandle) throw new ArgumentException("Non-owning SafeResourceHandle with IncRef is unsupported"); + if (incRef && handle != null) handle->IncRef(); SetHandle((nint)handle); } public static SafeResourceHandle CreateInvalid() - => new(null, incRef: false); + => new(null, false); protected override bool ReleaseHandle() { diff --git a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs index 88c97c54..dee28797 100644 --- a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs @@ -5,14 +5,18 @@ namespace Penumbra.Interop.SafeHandles; public unsafe class SafeTextureHandle : SafeHandle { - public Texture* Texture => (Texture*)handle; + public Texture* Texture + => (Texture*)handle; - public override bool IsInvalid => handle == 0; + public override bool IsInvalid + => handle == 0; - public SafeTextureHandle(Texture* handle, bool incRef, bool ownsHandle = true) : base(0, ownsHandle) + public SafeTextureHandle(Texture* handle, bool incRef, bool ownsHandle = true) + : base(0, ownsHandle) { if (incRef && !ownsHandle) throw new ArgumentException("Non-owning SafeTextureHandle with IncRef is unsupported"); + if (incRef && handle != null) TextureUtility.IncRef(handle); SetHandle((nint)handle); @@ -27,16 +31,17 @@ public unsafe class SafeTextureHandle : SafeHandle } public static SafeTextureHandle CreateInvalid() - => new(null, incRef: false); + => new(null, false); protected override bool ReleaseHandle() { nint handle; lock (this) { - handle = this.handle; + handle = this.handle; this.handle = 0; } + if (handle != 0) TextureUtility.DecRef((Texture*)handle); diff --git a/Penumbra/Interop/Services/DecalReverter.cs b/Penumbra/Interop/Services/DecalReverter.cs index 21fa87a1..18c88766 100644 --- a/Penumbra/Interop/Services/DecalReverter.cs +++ b/Penumbra/Interop/Services/DecalReverter.cs @@ -14,7 +14,7 @@ public sealed unsafe class DecalReverter : IDisposable public static readonly Utf8GamePath TransparentPath = Utf8GamePath.FromSpan("chara/common/texture/transparent.tex"u8, out var p) ? p : Utf8GamePath.Empty; - private readonly CharacterUtility _utility; + private readonly CharacterUtility _utility; private readonly Structs.TextureResourceHandle* _decal; private readonly Structs.TextureResourceHandle* _transparent; @@ -22,10 +22,10 @@ public sealed unsafe class DecalReverter : IDisposable { _utility = utility; var ptr = _utility.Address; - _decal = null; + _decal = null; _transparent = null; if (!config.EnableMods) - return; + return; if (doDecal) { diff --git a/Penumbra/Interop/Services/GameEventManager.cs b/Penumbra/Interop/Services/GameEventManager.cs index ca333ed4..2e8a23f0 100644 --- a/Penumbra/Interop/Services/GameEventManager.cs +++ b/Penumbra/Interop/Services/GameEventManager.cs @@ -152,7 +152,7 @@ public unsafe class GameEventManager : IDisposable { try { - ((CreatingCharacterBaseEvent)subscriber).Invoke((nint) (&a), b, c); + ((CreatingCharacterBaseEvent)subscriber).Invoke((nint)(&a), b, c); } catch (Exception ex) { @@ -265,11 +265,13 @@ public unsafe class GameEventManager : IDisposable private readonly Hook? _testHook = null; private delegate void TestDelegate(nint a1, int a2); + private void TestDetour(nint a1, int a2) { Penumbra.Log.Information($"Test: {a1:X} {a2}"); _testHook!.Original(a1, a2); } + private void EnableDebugHook() => _testHook?.Enable(); diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 0b9c6c38..65d5b0c0 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -100,10 +100,10 @@ public unsafe partial class RedrawService public sealed unsafe partial class RedrawService : IDisposable { - private readonly Framework _framework; + private readonly Framework _framework; private readonly IObjectTable _objects; private readonly ITargetManager _targets; - private readonly Condition _conditions; + private readonly Condition _conditions; private readonly List _queue = new(100); private readonly List _afterGPoseQueue = new(GPoseSlots); @@ -207,7 +207,7 @@ public sealed unsafe partial class RedrawService : IDisposable return; _targets.Target = actor; - _target = -1; + _target = -1; } private void HandleRedraw() diff --git a/Penumbra/Interop/Services/ResidentResourceManager.cs b/Penumbra/Interop/Services/ResidentResourceManager.cs index cd20b889..ff7f95a5 100644 --- a/Penumbra/Interop/Services/ResidentResourceManager.cs +++ b/Penumbra/Interop/Services/ResidentResourceManager.cs @@ -1,6 +1,6 @@ using Dalamud.Utility.Signatures; using Penumbra.GameData; - + namespace Penumbra.Interop.Services; public unsafe class ResidentResourceManager @@ -36,4 +36,4 @@ public unsafe class ResidentResourceManager LoadPlayerResources.Invoke(Address); } } -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 87d9566c..08857292 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -2,23 +2,23 @@ using Penumbra.GameData.Enums; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct CharacterUtilityData { public const int IndexTransparentTex = 72; public const int IndexDecalTex = 73; public const int IndexSkinShpk = 76; - public static readonly MetaIndex[] EqdpIndices = Enum.GetNames< MetaIndex >() - .Zip( Enum.GetValues< MetaIndex >() ) - .Where( n => n.First.StartsWith( "Eqdp" ) ) - .Select( n => n.Second ).ToArray(); + public static readonly MetaIndex[] EqdpIndices = Enum.GetNames() + .Zip(Enum.GetValues()) + .Where(n => n.First.StartsWith("Eqdp")) + .Select(n => n.Second).ToArray(); public const int TotalNumResources = 87; /// Obtain the index for the eqdp file corresponding to the given race code and accessory. - public static MetaIndex EqdpIdx( GenderRace raceCode, bool accessory ) - => +( int )raceCode switch + public static MetaIndex EqdpIdx(GenderRace raceCode, bool accessory) + => +(int)raceCode switch { 0101 => accessory ? MetaIndex.Eqdp0101Acc : MetaIndex.Eqdp0101, 0201 => accessory ? MetaIndex.Eqdp0201Acc : MetaIndex.Eqdp0201, @@ -48,53 +48,53 @@ public unsafe struct CharacterUtilityData 1404 => accessory ? MetaIndex.Eqdp1404Acc : MetaIndex.Eqdp1404, 9104 => accessory ? MetaIndex.Eqdp9104Acc : MetaIndex.Eqdp9104, 9204 => accessory ? MetaIndex.Eqdp9204Acc : MetaIndex.Eqdp9204, - _ => ( MetaIndex )( -1 ), + _ => (MetaIndex)(-1), }; - [FieldOffset( 0 )] + [FieldOffset(0)] public void* VTable; - [FieldOffset( 8 )] + [FieldOffset(8)] public fixed ulong Resources[TotalNumResources]; - [FieldOffset( 8 + ( int )MetaIndex.Eqp * 8 )] + [FieldOffset(8 + (int)MetaIndex.Eqp * 8)] public ResourceHandle* EqpResource; - [FieldOffset( 8 + ( int )MetaIndex.Gmp * 8 )] + [FieldOffset(8 + (int)MetaIndex.Gmp * 8)] public ResourceHandle* GmpResource; - public ResourceHandle* Resource( int idx ) - => ( ResourceHandle* )Resources[ idx ]; + public ResourceHandle* Resource(int idx) + => (ResourceHandle*)Resources[idx]; - public ResourceHandle* Resource( MetaIndex idx ) - => Resource( ( int )idx ); + public ResourceHandle* Resource(MetaIndex idx) + => Resource((int)idx); - public ResourceHandle* EqdpResource( GenderRace raceCode, bool accessory ) - => Resource( ( int )EqdpIdx( raceCode, accessory ) ); + public ResourceHandle* EqdpResource(GenderRace raceCode, bool accessory) + => Resource((int)EqdpIdx(raceCode, accessory)); - [FieldOffset( 8 + ( int )MetaIndex.HumanCmp * 8 )] + [FieldOffset(8 + (int)MetaIndex.HumanCmp * 8)] public ResourceHandle* HumanCmpResource; - [FieldOffset( 8 + ( int )MetaIndex.FaceEst * 8 )] + [FieldOffset(8 + (int)MetaIndex.FaceEst * 8)] public ResourceHandle* FaceEstResource; - [FieldOffset( 8 + ( int )MetaIndex.HairEst * 8 )] + [FieldOffset(8 + (int)MetaIndex.HairEst * 8)] public ResourceHandle* HairEstResource; - [FieldOffset( 8 + ( int )MetaIndex.BodyEst * 8 )] + [FieldOffset(8 + (int)MetaIndex.BodyEst * 8)] public ResourceHandle* BodyEstResource; - [FieldOffset( 8 + ( int )MetaIndex.HeadEst * 8 )] + [FieldOffset(8 + (int)MetaIndex.HeadEst * 8)] public ResourceHandle* HeadEstResource; - [FieldOffset( 8 + IndexTransparentTex * 8 )] + [FieldOffset(8 + IndexTransparentTex * 8)] public TextureResourceHandle* TransparentTexResource; - [FieldOffset( 8 + IndexDecalTex * 8 )] + [FieldOffset(8 + IndexDecalTex * 8)] public TextureResourceHandle* DecalTexResource; - [FieldOffset( 8 + IndexSkinShpk * 8 )] + [FieldOffset(8 + IndexSkinShpk * 8)] public ResourceHandle* SkinShpkResource; // not included resources have no known use case. -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/ClipScheduler.cs b/Penumbra/Interop/Structs/ClipScheduler.cs index c8fd082d..3211c4f9 100644 --- a/Penumbra/Interop/Structs/ClipScheduler.cs +++ b/Penumbra/Interop/Structs/ClipScheduler.cs @@ -1,11 +1,11 @@ namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct ClipScheduler { - [FieldOffset( 0 )] + [FieldOffset(0)] public IntPtr* VTable; - [FieldOffset( 0x38 )] + [FieldOffset(0x38)] public IntPtr SchedulerTimeline; -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/DrawState.cs b/Penumbra/Interop/Structs/DrawState.cs index d0dfc22b..200e7952 100644 --- a/Penumbra/Interop/Structs/DrawState.cs +++ b/Penumbra/Interop/Structs/DrawState.cs @@ -9,4 +9,4 @@ public enum DrawState : uint MaybeCulled = 0x00_00_04_00, MaybeHiddenMinion = 0x00_00_80_00, MaybeHiddenSummon = 0x00_80_00_00, -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/FileMode.cs b/Penumbra/Interop/Structs/FileMode.cs index 1c1914b2..4e48b3c1 100644 --- a/Penumbra/Interop/Structs/FileMode.cs +++ b/Penumbra/Interop/Structs/FileMode.cs @@ -8,4 +8,4 @@ public enum FileMode : byte // Probably debug options only. LoadIndexResource = 0xA, // load index/index2 LoadSqPackResource = 0xB, -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/HumanExt.cs b/Penumbra/Interop/Structs/HumanExt.cs index 5eafa1f3..274b4fb2 100644 --- a/Penumbra/Interop/Structs/HumanExt.cs +++ b/Penumbra/Interop/Structs/HumanExt.cs @@ -2,18 +2,18 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct HumanExt { - [FieldOffset( 0x0 )] + [FieldOffset(0x0)] public Human Human; - [FieldOffset( 0x0 )] + [FieldOffset(0x0)] public CharacterBaseExt CharacterBase; - [FieldOffset( 0x9E8 )] + [FieldOffset(0x9E8)] public ResourceHandle* Decal; - [FieldOffset( 0x9F0 )] + [FieldOffset(0x9F0)] public ResourceHandle* LegacyBodyDecal; -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/Material.cs b/Penumbra/Interop/Structs/Material.cs index 2bca832d..0165a8ff 100644 --- a/Penumbra/Interop/Structs/Material.cs +++ b/Penumbra/Interop/Structs/Material.cs @@ -2,45 +2,46 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit, Size = 0x40 )] +[StructLayout(LayoutKind.Explicit, Size = 0x40)] public unsafe struct Material { - [FieldOffset( 0x10 )] + [FieldOffset(0x10)] public MtrlResource* ResourceHandle; - [FieldOffset( 0x18 )] + [FieldOffset(0x18)] public uint ShaderPackageFlags; - [FieldOffset( 0x20 )] + [FieldOffset(0x20)] public uint* ShaderKeys; public int ShaderKeyCount => (int)((uint*)Textures - ShaderKeys); - [FieldOffset( 0x28 )] + [FieldOffset(0x28)] public ConstantBuffer* MaterialParameter; - [FieldOffset( 0x30 )] + [FieldOffset(0x30)] public TextureEntry* Textures; - [FieldOffset( 0x38 )] + [FieldOffset(0x38)] public ushort TextureCount; - public Texture* Texture( int index ) => Textures[index].ResourceHandle->KernelTexture; + public Texture* Texture(int index) + => Textures[index].ResourceHandle->KernelTexture; - [StructLayout( LayoutKind.Explicit, Size = 0x18 )] + [StructLayout(LayoutKind.Explicit, Size = 0x18)] public struct TextureEntry { - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public uint Id; - [FieldOffset( 0x08 )] + [FieldOffset(0x08)] public TextureResourceHandle* ResourceHandle; - [FieldOffset( 0x10 )] + [FieldOffset(0x10)] public uint SamplerFlags; } public ReadOnlySpan TextureSpan - => new(Textures, TextureCount); -} \ No newline at end of file + => new(Textures, TextureCount); +} diff --git a/Penumbra/Interop/Structs/MtrlResource.cs b/Penumbra/Interop/Structs/MtrlResource.cs index 55c7f8d8..c3b86e14 100644 --- a/Penumbra/Interop/Structs/MtrlResource.cs +++ b/Penumbra/Interop/Structs/MtrlResource.cs @@ -1,45 +1,45 @@ namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct MtrlResource { - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public ResourceHandle Handle; - [FieldOffset( 0xC8 )] + [FieldOffset(0xC8)] public ShaderPackageResourceHandle* ShpkResourceHandle; - [FieldOffset( 0xD0 )] + [FieldOffset(0xD0)] public TextureEntry* TexSpace; // Contains the offsets for the tex files inside the string list. - [FieldOffset( 0xE0 )] + [FieldOffset(0xE0)] public byte* StringList; - [FieldOffset( 0xF8 )] + [FieldOffset(0xF8)] public ushort ShpkOffset; - [FieldOffset( 0xFA )] + [FieldOffset(0xFA)] public byte NumTex; public byte* ShpkString => StringList + ShpkOffset; - public byte* TexString( int idx ) + public byte* TexString(int idx) => StringList + TexSpace[idx].PathOffset; - public bool TexIsDX11( int idx ) + public bool TexIsDX11(int idx) => TexSpace[idx].Flags >= 0x8000; [StructLayout(LayoutKind.Explicit, Size = 0x10)] public struct TextureEntry { - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public TextureResourceHandle* ResourceHandle; - [FieldOffset( 0x08 )] + [FieldOffset(0x08)] public ushort PathOffset; - [FieldOffset( 0x0A )] + [FieldOffset(0x0A)] public ushort Flags; } -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/RenderModel.cs b/Penumbra/Interop/Structs/RenderModel.cs index 25e928be..f9cb2d56 100644 --- a/Penumbra/Interop/Structs/RenderModel.cs +++ b/Penumbra/Interop/Structs/RenderModel.cs @@ -2,39 +2,39 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct RenderModel { - [FieldOffset( 0x18 )] + [FieldOffset(0x18)] public RenderModel* PreviousModel; - [FieldOffset( 0x20 )] + [FieldOffset(0x20)] public RenderModel* NextModel; - [FieldOffset( 0x30 )] + [FieldOffset(0x30)] public ResourceHandle* ResourceHandle; - [FieldOffset( 0x40 )] + [FieldOffset(0x40)] public Skeleton* Skeleton; - [FieldOffset( 0x58 )] + [FieldOffset(0x58)] public void** BoneList; - [FieldOffset( 0x60 )] + [FieldOffset(0x60)] public int BoneListCount; - [FieldOffset( 0x70 )] + [FieldOffset(0x70)] private void* UnkDXBuffer1; - [FieldOffset( 0x78 )] + [FieldOffset(0x78)] private void* UnkDXBuffer2; - [FieldOffset( 0x80 )] + [FieldOffset(0x80)] private void* UnkDXBuffer3; - [FieldOffset( 0x98 )] + [FieldOffset(0x98)] public void** Materials; - [FieldOffset( 0xA0 )] + [FieldOffset(0xA0)] public int MaterialCount; -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/ResidentResourceManager.cs b/Penumbra/Interop/Structs/ResidentResourceManager.cs index 08461b03..131f2884 100644 --- a/Penumbra/Interop/Structs/ResidentResourceManager.cs +++ b/Penumbra/Interop/Structs/ResidentResourceManager.cs @@ -3,15 +3,15 @@ namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] public unsafe struct ResidentResourceManager { - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public void** VTable; - [FieldOffset( 0x08 )] + [FieldOffset(0x08)] public void** ResourceListVTable; - [FieldOffset( 0x14 )] + [FieldOffset(0x14)] public uint NumResources; - [FieldOffset( 0x18 )] + [FieldOffset(0x18)] public ResourceHandle** ResourceList; -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index b23cf62f..dba113f3 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -8,45 +8,45 @@ using Penumbra.String.Classes; namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct TextureResourceHandle { - [FieldOffset( 0x0 )] + [FieldOffset(0x0)] public ResourceHandle Handle; - [FieldOffset( 0x38 )] + [FieldOffset(0x38)] public IntPtr Unk; - [FieldOffset( 0x118 )] + [FieldOffset(0x118)] public Texture* KernelTexture; - [FieldOffset( 0x20 )] + [FieldOffset(0x20)] public IntPtr NewKernelTexture; } [StructLayout(LayoutKind.Explicit)] public unsafe struct ShaderPackageResourceHandle { - [FieldOffset( 0x0 )] + [FieldOffset(0x0)] public ResourceHandle Handle; - [FieldOffset( 0xB0 )] + [FieldOffset(0xB0)] public ShaderPackage* ShaderPackage; } -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct ResourceHandle { - [StructLayout( LayoutKind.Explicit )] + [StructLayout(LayoutKind.Explicit)] public struct DataIndirection { - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public void** VTable; - [FieldOffset( 0x10 )] + [FieldOffset(0x10)] public byte* DataPtr; - [FieldOffset( 0x28 )] + [FieldOffset(0x28)] public ulong DataLength; } @@ -54,87 +54,83 @@ public unsafe struct ResourceHandle public byte* FileNamePtr() { - if( FileNameLength > SsoSize ) - { + if (FileNameLength > SsoSize) return FileNameData; - } - fixed( byte** name = &FileNameData ) + fixed (byte** name = &FileNameData) { - return ( byte* )name; + return (byte*)name; } } public ByteString FileName() - => ByteString.FromByteStringUnsafe( FileNamePtr(), FileNameLength, true ); + => ByteString.FromByteStringUnsafe(FileNamePtr(), FileNameLength, true); - public ReadOnlySpan< byte > FileNameAsSpan() - => new( FileNamePtr(), FileNameLength ); + public ReadOnlySpan FileNameAsSpan() + => new(FileNamePtr(), FileNameLength); - public bool GamePath( out Utf8GamePath path ) - => Utf8GamePath.FromSpan( FileNameAsSpan(), out path ); + public bool GamePath(out Utf8GamePath path) + => Utf8GamePath.FromSpan(FileNameAsSpan(), out path); - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public void** VTable; - [FieldOffset( 0x08 )] + [FieldOffset(0x08)] public ResourceCategory Category; - [FieldOffset( 0x0C )] + [FieldOffset(0x0C)] public ResourceType FileType; - [FieldOffset( 0x10 )] + [FieldOffset(0x10)] public uint Id; - [FieldOffset( 0x28 )] + [FieldOffset(0x28)] public uint FileSize; - [FieldOffset( 0x2C )] + [FieldOffset(0x2C)] public uint FileSize2; - [FieldOffset( 0x34 )] + [FieldOffset(0x34)] public uint FileSize3; - [FieldOffset( 0x48 )] + [FieldOffset(0x48)] public byte* FileNameData; - [FieldOffset( 0x58 )] + [FieldOffset(0x58)] public int FileNameLength; - [FieldOffset( 0xAC )] + [FieldOffset(0xAC)] public uint RefCount; // May return null. - public static byte* GetData( ResourceHandle* handle ) - => ( ( delegate* unmanaged< ResourceHandle*, byte* > )handle->VTable[ Offsets.ResourceHandleGetDataVfunc ] )( handle ); + public static byte* GetData(ResourceHandle* handle) + => ((delegate* unmanaged< ResourceHandle*, byte* >)handle->VTable[Offsets.ResourceHandleGetDataVfunc])(handle); - public static ulong GetLength( ResourceHandle* handle ) - => ( ( delegate* unmanaged< ResourceHandle*, ulong > )handle->VTable[ Offsets.ResourceHandleGetLengthVfunc ] )( handle ); + public static ulong GetLength(ResourceHandle* handle) + => ((delegate* unmanaged< ResourceHandle*, ulong >)handle->VTable[Offsets.ResourceHandleGetLengthVfunc])(handle); // Only use these if you know what you are doing. // Those are actually only sure to be accessible for DefaultResourceHandles. - [FieldOffset( 0xB0 )] + [FieldOffset(0xB0)] public DataIndirection* Data; - [FieldOffset( 0xB8 )] + [FieldOffset(0xB8)] public uint DataLength; public (IntPtr Data, int Length) GetData() => Data != null - ? ( ( IntPtr )Data->DataPtr, ( int )Data->DataLength ) - : ( IntPtr.Zero, 0 ); + ? ((IntPtr)Data->DataPtr, (int)Data->DataLength) + : (IntPtr.Zero, 0); - public bool SetData( IntPtr data, int length ) + public bool SetData(IntPtr data, int length) { - if( Data == null ) - { + if (Data == null) return false; - } - Data->DataPtr = length != 0 ? ( byte* )data : null; - Data->DataLength = ( ulong )length; - DataLength = ( uint )length; + Data->DataPtr = length != 0 ? (byte*)data : null; + Data->DataLength = (ulong)length; + DataLength = (uint)length; return true; } -} \ No newline at end of file +} diff --git a/Penumbra/Interop/Structs/SeFileDescriptor.cs b/Penumbra/Interop/Structs/SeFileDescriptor.cs index d4ca3afa..67730799 100644 --- a/Penumbra/Interop/Structs/SeFileDescriptor.cs +++ b/Penumbra/Interop/Structs/SeFileDescriptor.cs @@ -1,18 +1,17 @@ namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct SeFileDescriptor { - [FieldOffset( 0x00 )] + [FieldOffset(0x00)] public FileMode FileMode; - [FieldOffset( 0x30 )] - public void* FileDescriptor; // + [FieldOffset(0x30)] + public void* FileDescriptor; - [FieldOffset( 0x50 )] - public ResourceHandle* ResourceHandle; // + [FieldOffset(0x50)] + public ResourceHandle* ResourceHandle; - - [FieldOffset( 0x70 )] - public char Utf16FileName; // -} \ No newline at end of file + [FieldOffset(0x70)] + public char Utf16FileName; +} diff --git a/Penumbra/Interop/Structs/TextureUtility.cs b/Penumbra/Interop/Structs/TextureUtility.cs index ec9c4b71..a81480fb 100644 --- a/Penumbra/Interop/Structs/TextureUtility.cs +++ b/Penumbra/Interop/Structs/TextureUtility.cs @@ -4,12 +4,13 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; -public unsafe static class TextureUtility +public static unsafe class TextureUtility { private static readonly Functions Funcs = new(); public static Texture* Create2D(Device* device, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk) - => ((delegate* unmanaged)Funcs.TextureCreate2D)(device, size, mipLevel, textureFormat, flags, unk); + => ((delegate* unmanaged)Funcs.TextureCreate2D)(device, size, mipLevel, textureFormat, + flags, unk); public static bool InitializeContents(Texture* texture, void* contents) => ((delegate* unmanaged)Funcs.TextureInitializeContents)(texture, contents); diff --git a/Penumbra/Interop/Structs/VfxParams.cs b/Penumbra/Interop/Structs/VfxParams.cs index 76dbd3ed..c3ae1751 100644 --- a/Penumbra/Interop/Structs/VfxParams.cs +++ b/Penumbra/Interop/Structs/VfxParams.cs @@ -1,17 +1,17 @@ namespace Penumbra.Interop.Structs; -[StructLayout( LayoutKind.Explicit )] +[StructLayout(LayoutKind.Explicit)] public unsafe struct VfxParams { - [FieldOffset( 0x118 )] + [FieldOffset(0x118)] public uint GameObjectId; - [FieldOffset( 0x11C )] + [FieldOffset(0x11C)] public byte GameObjectType; - [FieldOffset( 0xD0 )] + [FieldOffset(0xD0)] public ushort TargetCount; - [FieldOffset( 0x120 )] + [FieldOffset(0x120)] public fixed ulong Target[16]; -} \ No newline at end of file +} diff --git a/Penumbra/Meta/Manipulations/EqdpManipulation.cs b/Penumbra/Meta/Manipulations/EqdpManipulation.cs index 1e0756f2..df7ed2e4 100644 --- a/Penumbra/Meta/Manipulations/EqdpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqdpManipulation.cs @@ -101,8 +101,8 @@ public readonly struct EqdpManipulation : IMetaManipulation if (FileIndex() == (MetaIndex)(-1)) return false; - - // No check for set id. + + // No check for set id. return true; } } diff --git a/Penumbra/Meta/Manipulations/EqpManipulation.cs b/Penumbra/Meta/Manipulations/EqpManipulation.cs index 8e1a2ded..4373e8e9 100644 --- a/Penumbra/Meta/Manipulations/EqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqpManipulation.cs @@ -9,73 +9,71 @@ using SharpCompress.Common; namespace Penumbra.Meta.Manipulations; -[StructLayout( LayoutKind.Sequential, Pack = 1 )] -public readonly struct EqpManipulation : IMetaManipulation< EqpManipulation > +[StructLayout(LayoutKind.Sequential, Pack = 1)] +public readonly struct EqpManipulation : IMetaManipulation { - [JsonConverter( typeof( ForceNumericFlagEnumConverter ) )] + [JsonConverter(typeof(ForceNumericFlagEnumConverter))] public EqpEntry Entry { get; private init; } public SetId SetId { get; private init; } - [JsonConverter( typeof( StringEnumConverter ) )] + [JsonConverter(typeof(StringEnumConverter))] public EquipSlot Slot { get; private init; } [JsonConstructor] - public EqpManipulation( EqpEntry entry, EquipSlot slot, SetId setId ) + public EqpManipulation(EqpEntry entry, EquipSlot slot, SetId setId) { Slot = slot; SetId = setId; - Entry = Eqp.Mask( slot ) & entry; + Entry = Eqp.Mask(slot) & entry; } - public EqpManipulation Copy( EqpEntry entry ) + public EqpManipulation Copy(EqpEntry entry) => new(entry, Slot, SetId); public override string ToString() => $"Eqp - {SetId} - {Slot}"; - public bool Equals( EqpManipulation other ) - => Slot == other.Slot + public bool Equals(EqpManipulation other) + => Slot == other.Slot && SetId == other.SetId; - public override bool Equals( object? obj ) - => obj is EqpManipulation other && Equals( other ); + public override bool Equals(object? obj) + => obj is EqpManipulation other && Equals(other); public override int GetHashCode() - => HashCode.Combine( ( int )Slot, SetId ); + => HashCode.Combine((int)Slot, SetId); - public int CompareTo( EqpManipulation other ) + public int CompareTo(EqpManipulation other) { - var set = SetId.Id.CompareTo( other.SetId.Id ); - return set != 0 ? set : Slot.CompareTo( other.Slot ); + var set = SetId.Id.CompareTo(other.SetId.Id); + return set != 0 ? set : Slot.CompareTo(other.Slot); } public MetaIndex FileIndex() => MetaIndex.Eqp; - public bool Apply( ExpandedEqpFile file ) + public bool Apply(ExpandedEqpFile file) { - var entry = file[ SetId ]; - var mask = Eqp.Mask( Slot ); - if( ( entry & mask ) == Entry ) - { + var entry = file[SetId]; + var mask = Eqp.Mask(Slot); + if ((entry & mask) == Entry) return false; - } - file[ SetId ] = ( entry & ~mask ) | Entry; + file[SetId] = (entry & ~mask) | Entry; return true; } public bool Validate() - { + { var mask = Eqp.Mask(Slot); if (mask == 0) return false; if ((Entry & mask) != Entry) return false; - - // No check for set id. + + // No check for set id. return true; } -} \ No newline at end of file +} diff --git a/Penumbra/Meta/Manipulations/EstManipulation.cs b/Penumbra/Meta/Manipulations/EstManipulation.cs index da834b35..455c39ff 100644 --- a/Penumbra/Meta/Manipulations/EstManipulation.cs +++ b/Penumbra/Meta/Manipulations/EstManipulation.cs @@ -7,8 +7,8 @@ using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; -[StructLayout( LayoutKind.Sequential, Pack = 1 )] -public readonly struct EstManipulation : IMetaManipulation< EstManipulation > +[StructLayout(LayoutKind.Sequential, Pack = 1)] +public readonly struct EstManipulation : IMetaManipulation { public enum EstType : byte { @@ -18,7 +18,7 @@ public readonly struct EstManipulation : IMetaManipulation< EstManipulation > Head = MetaIndex.HeadEst, } - public static string ToName( EstType type ) + public static string ToName(EstType type) => type switch { EstType.Hair => "hair", @@ -30,19 +30,19 @@ public readonly struct EstManipulation : IMetaManipulation< EstManipulation > public ushort Entry { get; private init; } // SkeletonIdx. - [JsonConverter( typeof( StringEnumConverter ) )] + [JsonConverter(typeof(StringEnumConverter))] public Gender Gender { get; private init; } - [JsonConverter( typeof( StringEnumConverter ) )] + [JsonConverter(typeof(StringEnumConverter))] public ModelRace Race { get; private init; } public SetId SetId { get; private init; } - [JsonConverter( typeof( StringEnumConverter ) )] + [JsonConverter(typeof(StringEnumConverter))] public EstType Slot { get; private init; } [JsonConstructor] - public EstManipulation( Gender gender, ModelRace race, EstType slot, SetId setId, ushort entry ) + public EstManipulation(Gender gender, ModelRace race, EstType slot, SetId setId, ushort entry) { Entry = entry; Gender = gender; @@ -51,49 +51,45 @@ public readonly struct EstManipulation : IMetaManipulation< EstManipulation > Slot = slot; } - public EstManipulation Copy( ushort entry ) + public EstManipulation Copy(ushort entry) => new(Gender, Race, Slot, SetId, entry); public override string ToString() => $"Est - {SetId} - {Slot} - {Race.ToName()} {Gender.ToName()}"; - public bool Equals( EstManipulation other ) + public bool Equals(EstManipulation other) => Gender == other.Gender - && Race == other.Race + && Race == other.Race && SetId == other.SetId - && Slot == other.Slot; + && Slot == other.Slot; - public override bool Equals( object? obj ) - => obj is EstManipulation other && Equals( other ); + public override bool Equals(object? obj) + => obj is EstManipulation other && Equals(other); public override int GetHashCode() - => HashCode.Combine( ( int )Gender, ( int )Race, SetId, ( int )Slot ); + => HashCode.Combine((int)Gender, (int)Race, SetId, (int)Slot); - public int CompareTo( EstManipulation other ) + public int CompareTo(EstManipulation other) { - var r = Race.CompareTo( other.Race ); - if( r != 0 ) - { + var r = Race.CompareTo(other.Race); + if (r != 0) return r; - } - var g = Gender.CompareTo( other.Gender ); - if( g != 0 ) - { + var g = Gender.CompareTo(other.Gender); + if (g != 0) return g; - } - var s = Slot.CompareTo( other.Slot ); - return s != 0 ? s : SetId.Id.CompareTo( other.SetId.Id ); + var s = Slot.CompareTo(other.Slot); + return s != 0 ? s : SetId.Id.CompareTo(other.SetId.Id); } public MetaIndex FileIndex() - => ( MetaIndex )Slot; + => (MetaIndex)Slot; - public bool Apply( EstFile file ) + public bool Apply(EstFile file) { - return file.SetEntry( Names.CombinedRace( Gender, Race ), SetId.Id, Entry ) switch + return file.SetEntry(Names.CombinedRace(Gender, Race), SetId.Id, Entry) switch { EstFile.EstEntryChange.Unchanged => false, EstFile.EstEntryChange.Changed => true, @@ -109,7 +105,8 @@ public readonly struct EstManipulation : IMetaManipulation< EstManipulation > return false; if (Names.CombinedRace(Gender, Race) == GenderRace.Unknown) return false; - // No known check for set id or entry. + + // No known check for set id or entry. return true; } -} \ No newline at end of file +} diff --git a/Penumbra/Meta/Manipulations/GmpManipulation.cs b/Penumbra/Meta/Manipulations/GmpManipulation.cs index 94f7f971..928b6f55 100644 --- a/Penumbra/Meta/Manipulations/GmpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GmpManipulation.cs @@ -5,55 +5,51 @@ using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; -[StructLayout( LayoutKind.Sequential, Pack = 1 )] -public readonly struct GmpManipulation : IMetaManipulation< GmpManipulation > +[StructLayout(LayoutKind.Sequential, Pack = 1)] +public readonly struct GmpManipulation : IMetaManipulation { public GmpEntry Entry { get; private init; } - public SetId SetId { get; private init; } + public SetId SetId { get; private init; } [JsonConstructor] - public GmpManipulation( GmpEntry entry, SetId setId ) + public GmpManipulation(GmpEntry entry, SetId setId) { Entry = entry; SetId = setId; } - public GmpManipulation Copy( GmpEntry entry ) + public GmpManipulation Copy(GmpEntry entry) => new(entry, SetId); public override string ToString() => $"Gmp - {SetId}"; - public bool Equals( GmpManipulation other ) + public bool Equals(GmpManipulation other) => SetId == other.SetId; - public override bool Equals( object? obj ) - => obj is GmpManipulation other && Equals( other ); + public override bool Equals(object? obj) + => obj is GmpManipulation other && Equals(other); public override int GetHashCode() => SetId.GetHashCode(); - public int CompareTo( GmpManipulation other ) - => SetId.Id.CompareTo( other.SetId.Id ); + public int CompareTo(GmpManipulation other) + => SetId.Id.CompareTo(other.SetId.Id); public MetaIndex FileIndex() => MetaIndex.Gmp; - public bool Apply( ExpandedGmpFile file ) + public bool Apply(ExpandedGmpFile file) { - var entry = file[ SetId ]; - if( entry == Entry ) - { + var entry = file[SetId]; + if (entry == Entry) return false; - } - file[ SetId ] = Entry; + file[SetId] = Entry; return true; } public bool Validate() - { // No known conditions. - return true; - } -} \ No newline at end of file + => true; +} diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 2f19537b..3155e188 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -10,6 +10,7 @@ using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta.Files; using Penumbra.Mods; +using Penumbra.Mods.Subclasses; using Penumbra.Services; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 12fb4f35..488c1c91 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -59,7 +59,7 @@ public class DuplicateManager public void Clear() { _cancellationTokenSource.Cancel(); - Worker = Task.CompletedTask; + Worker = Task.CompletedTask; _duplicates.Clear(); SavedSpace = 0; } diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 2100526a..0aa70e61 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; namespace Penumbra.Mods; diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index 6fa645a9..cd8a9594 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -7,14 +7,14 @@ public interface IMod { LowerString Name { get; } - public int Index { get; } + public int Index { get; } public int Priority { get; } - public ISubMod Default { get; } - public IReadOnlyList< IModGroup > Groups { get; } + public ISubMod Default { get; } + public IReadOnlyList Groups { get; } - public IEnumerable< SubMod > AllSubMods { get; } - - // Cache + public IEnumerable AllSubMods { get; } + + // Cache public int TotalManipulations { get; } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/Editor/ModBackup.cs b/Penumbra/Mods/Editor/ModBackup.cs index f4904271..8de93bcc 100644 --- a/Penumbra/Mods/Editor/ModBackup.cs +++ b/Penumbra/Mods/Editor/ModBackup.cs @@ -1,25 +1,26 @@ using System.IO.Compression; -using OtterGui.Tasks; +using OtterGui.Tasks; using Penumbra.Mods.Manager; namespace Penumbra.Mods.Editor; /// Utility to create and apply a zipped backup of a mod. public class ModBackup -{ +{ /// Set when reading Config and migrating from v4 to v5. public static bool MigrateModBackups = false; + public static bool CreatingBackup { get; private set; } - private readonly Mod _mod; - public readonly string Name; - public readonly bool Exists; + private readonly Mod _mod; + public readonly string Name; + public readonly bool Exists; public ModBackup(ModExportManager modExportManager, Mod mod) - { - _mod = mod; - Name = Path.Combine(modExportManager.ExportDirectory.FullName, _mod.ModPath.Name) + ".pmp"; - Exists = File.Exists(Name); + { + _mod = mod; + Name = Path.Combine(modExportManager.ExportDirectory.FullName, _mod.ModPath.Name) + ".pmp"; + Exists = File.Exists(Name); } /// Migrate file extensions. diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 85a7a544..e3862c90 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -1,4 +1,5 @@ using OtterGui; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 1ca3edd4..82629971 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -1,5 +1,6 @@ using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; namespace Penumbra.Mods; @@ -7,7 +8,7 @@ namespace Penumbra.Mods; public class ModFileEditor { private readonly ModFileCollection _files; - private readonly ModManager _modManager; + private readonly ModManager _modManager; public bool Changes { get; private set; } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 5c9be2ac..f90f6c0a 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -5,6 +5,7 @@ using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.UI.ModsTab; @@ -174,7 +175,7 @@ public class ModMerger : IDisposable ret = new FullPath(MergeToMod!.ModPath, relPath); return true; } - + foreach (var originalOption in mergeOptions) { foreach (var manip in originalOption.Manipulations) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index e389c86a..09c5c77a 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,5 +1,6 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; namespace Penumbra.Mods; @@ -146,6 +147,7 @@ public class ModMetaEditor } } } + Split(currentOption.Manipulations); } diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 9b17c390..eebc8ab4 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Tasks; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; namespace Penumbra.Mods; diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index c00bb821..b9834da8 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -1,11 +1,12 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; using Penumbra.Util; public class ModSwapEditor { - private readonly ModManager _modManager; + private readonly ModManager _modManager; private readonly Dictionary _swaps = new(); public IReadOnlyDictionary Swaps diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index da56d204..b9200a24 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -10,27 +10,29 @@ namespace Penumbra.Mods.ItemSwap; public static class CustomizationSwap { /// The .mdl file for customizations is unique per racecode, slot and id, thus the .mdl redirection itself is independent of the mode. - public static FileSwap CreateMdl( MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, BodySlot slot, GenderRace race, SetId idFrom, SetId idTo ) + public static FileSwap CreateMdl(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, + SetId idFrom, SetId idTo) { - if( idFrom.Id > byte.MaxValue ) - { - throw new Exception( $"The Customization ID {idFrom} is too large for {slot}." ); - } + if (idFrom.Id > byte.MaxValue) + throw new Exception($"The Customization ID {idFrom} is too large for {slot}."); - var mdlPathFrom = GamePaths.Character.Mdl.Path( race, slot, idFrom, slot.ToCustomizationType() ); - var mdlPathTo = GamePaths.Character.Mdl.Path( race, slot, idTo, slot.ToCustomizationType() ); + var mdlPathFrom = GamePaths.Character.Mdl.Path(race, slot, idFrom, slot.ToCustomizationType()); + var mdlPathTo = GamePaths.Character.Mdl.Path(race, slot, idTo, slot.ToCustomizationType()); - var mdl = FileSwap.CreateSwap( manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo ); - var range = slot == BodySlot.Tail && race is GenderRace.HrothgarMale or GenderRace.HrothgarFemale or GenderRace.HrothgarMaleNpc or GenderRace.HrothgarMaleNpc ? 5 : 1; + var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); + var range = slot == BodySlot.Tail + && race is GenderRace.HrothgarMale or GenderRace.HrothgarFemale or GenderRace.HrothgarMaleNpc or GenderRace.HrothgarMaleNpc + ? 5 + : 1; - foreach( ref var materialFileName in mdl.AsMdl()!.Materials.AsSpan() ) + foreach (ref var materialFileName in mdl.AsMdl()!.Materials.AsSpan()) { var name = materialFileName; - foreach( var variant in Enumerable.Range( 1, range ) ) + foreach (var variant in Enumerable.Range(1, range)) { name = materialFileName; - var mtrl = CreateMtrl( manager, redirections, slot, race, idFrom, idTo, ( byte )variant, ref name, ref mdl.DataWasChanged ); - mdl.ChildSwaps.Add( mtrl ); + var mtrl = CreateMtrl(manager, redirections, slot, race, idFrom, idTo, (byte)variant, ref name, ref mdl.DataWasChanged); + mdl.ChildSwaps.Add(mtrl); } materialFileName = name; @@ -39,71 +41,75 @@ public static class CustomizationSwap return mdl; } - public static FileSwap CreateMtrl( MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, BodySlot slot, GenderRace race, SetId idFrom, SetId idTo, byte variant, - ref string fileName, ref bool dataWasChanged ) + public static FileSwap CreateMtrl(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, + SetId idFrom, SetId idTo, byte variant, + ref string fileName, ref bool dataWasChanged) { variant = slot is BodySlot.Face or BodySlot.Zear ? byte.MaxValue : variant; - var mtrlFromPath = GamePaths.Character.Mtrl.Path( race, slot, idFrom, fileName, out var gameRaceFrom, out var gameSetIdFrom, variant ); - var mtrlToPath = GamePaths.Character.Mtrl.Path( race, slot, idTo, fileName, out var gameRaceTo, out var gameSetIdTo, variant ); + var mtrlFromPath = GamePaths.Character.Mtrl.Path(race, slot, idFrom, fileName, out var gameRaceFrom, out var gameSetIdFrom, variant); + var mtrlToPath = GamePaths.Character.Mtrl.Path(race, slot, idTo, fileName, out var gameRaceTo, out var gameSetIdTo, variant); var newFileName = fileName; - newFileName = ItemSwap.ReplaceRace( newFileName, gameRaceTo, race, gameRaceTo != race ); - newFileName = ItemSwap.ReplaceBody( newFileName, slot, idTo, idFrom, idFrom != idTo ); - newFileName = ItemSwap.AddSuffix( newFileName, ".mtrl", $"_c{race.ToRaceCode()}", gameRaceFrom != race || MaterialHandling.IsSpecialCase( race, idFrom ) ); - newFileName = ItemSwap.AddSuffix( newFileName, ".mtrl", $"_{slot.ToAbbreviation()}{idFrom.Id:D4}", gameSetIdFrom != idFrom ); + newFileName = ItemSwap.ReplaceRace(newFileName, gameRaceTo, race, gameRaceTo != race); + newFileName = ItemSwap.ReplaceBody(newFileName, slot, idTo, idFrom, idFrom != idTo); + newFileName = ItemSwap.AddSuffix(newFileName, ".mtrl", $"_c{race.ToRaceCode()}", + gameRaceFrom != race || MaterialHandling.IsSpecialCase(race, idFrom)); + newFileName = ItemSwap.AddSuffix(newFileName, ".mtrl", $"_{slot.ToAbbreviation()}{idFrom.Id:D4}", gameSetIdFrom != idFrom); var actualMtrlFromPath = mtrlFromPath; - if( newFileName != fileName ) + if (newFileName != fileName) { - actualMtrlFromPath = GamePaths.Character.Mtrl.Path( race, slot, idFrom, newFileName, out _, out _, variant ); + actualMtrlFromPath = GamePaths.Character.Mtrl.Path(race, slot, idFrom, newFileName, out _, out _, variant); fileName = newFileName; dataWasChanged = true; } - var mtrl = FileSwap.CreateSwap( manager, ResourceType.Mtrl, redirections, actualMtrlFromPath, mtrlToPath, actualMtrlFromPath ); - var shpk = CreateShader( manager, redirections, ref mtrl.AsMtrl()!.ShaderPackage.Name, ref mtrl.DataWasChanged ); - mtrl.ChildSwaps.Add( shpk ); + var mtrl = FileSwap.CreateSwap(manager, ResourceType.Mtrl, redirections, actualMtrlFromPath, mtrlToPath, actualMtrlFromPath); + var shpk = CreateShader(manager, redirections, ref mtrl.AsMtrl()!.ShaderPackage.Name, ref mtrl.DataWasChanged); + mtrl.ChildSwaps.Add(shpk); - foreach( ref var texture in mtrl.AsMtrl()!.Textures.AsSpan() ) + foreach (ref var texture in mtrl.AsMtrl()!.Textures.AsSpan()) { - var tex = CreateTex( manager, redirections, slot, race, idFrom, ref texture, ref mtrl.DataWasChanged ); - mtrl.ChildSwaps.Add( tex ); + var tex = CreateTex(manager, redirections, slot, race, idFrom, ref texture, ref mtrl.DataWasChanged); + mtrl.ChildSwaps.Add(tex); } return mtrl; } - public static FileSwap CreateTex( MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, BodySlot slot, GenderRace race, SetId idFrom, ref MtrlFile.Texture texture, - ref bool dataWasChanged ) + public static FileSwap CreateTex(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, + SetId idFrom, ref MtrlFile.Texture texture, + ref bool dataWasChanged) { var path = texture.Path; var addedDashes = false; - if( texture.DX11 ) + if (texture.DX11) { - var fileName = Path.GetFileName( path ); - if( !fileName.StartsWith( "--" ) ) + var fileName = Path.GetFileName(path); + if (!fileName.StartsWith("--")) { - path = path.Replace( fileName, $"--{fileName}" ); + path = path.Replace(fileName, $"--{fileName}"); addedDashes = true; } } - var newPath = ItemSwap.ReplaceAnyRace( path, race ); - newPath = ItemSwap.ReplaceAnyBody( newPath, slot, idFrom ); - newPath = ItemSwap.AddSuffix( newPath, ".tex", $"_{Path.GetFileName( texture.Path ).GetStableHashCode():x8}", true ); - if( newPath != path ) + var newPath = ItemSwap.ReplaceAnyRace(path, race); + newPath = ItemSwap.ReplaceAnyBody(newPath, slot, idFrom); + newPath = ItemSwap.AddSuffix(newPath, ".tex", $"_{Path.GetFileName(texture.Path).GetStableHashCode():x8}", true); + if (newPath != path) { - texture.Path = addedDashes ? newPath.Replace( "--", string.Empty ) : newPath; + texture.Path = addedDashes ? newPath.Replace("--", string.Empty) : newPath; dataWasChanged = true; } - return FileSwap.CreateSwap( manager, ResourceType.Tex, redirections, newPath, path, path ); + return FileSwap.CreateSwap(manager, ResourceType.Tex, redirections, newPath, path, path); } - public static FileSwap CreateShader( MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, ref string shaderName, ref bool dataWasChanged ) + public static FileSwap CreateShader(MetaFileManager manager, Func redirections, ref string shaderName, + ref bool dataWasChanged) { var path = $"shader/sm5/shpk/{shaderName}"; - return FileSwap.CreateSwap( manager, ResourceType.Shpk, redirections, path, path ); + return FileSwap.CreateSwap(manager, ResourceType.Shpk, redirections, path, path); } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 188fc317..d95c8796 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -249,10 +249,10 @@ public static class EquipmentSwap private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, IObjectIdentifier identifier, EquipSlot slotFrom, SetId idFrom, SetId idTo, Variant variantFrom) { - var entry = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, default); - var imc = new ImcFile(manager, entry); + var entry = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, default); + var imc = new ImcFile(manager, entry); EquipItem[] items; - Variant[] variants; + Variant[] variants; if (idFrom == idTo) { items = identifier.Identify(idFrom, variantFrom, slotFrom).ToArray(); @@ -264,8 +264,9 @@ public static class EquipmentSwap else { items = identifier.Identify(slotFrom.IsEquipment() - ? GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom) - : GamePaths.Accessory.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom)).Select(kvp => kvp.Value).OfType().ToArray(); + ? GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom) + : GamePaths.Accessory.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom)).Select(kvp => kvp.Value).OfType() + .ToArray(); variants = Enumerable.Range(0, imc.Count + 1).Select(i => (Variant)i).ToArray(); } @@ -283,11 +284,13 @@ public static class EquipmentSwap return new MetaSwap(manips, manipFrom, manipTo); } - public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, Func manips, EquipSlot slot, + public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, + Func manips, EquipSlot slot, SetId idFrom, SetId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) => CreateImc(manager, redirections, manips, slot, slot, idFrom, idTo, variantFrom, variantTo, imcFileFrom, imcFileTo); - public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, Func manips, + public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, + Func manips, EquipSlot slotFrom, EquipSlot slotTo, SetId idFrom, SetId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) { @@ -401,7 +404,8 @@ public static class EquipmentSwap ref MtrlFile.Texture texture, ref bool dataWasChanged) => CreateTex(manager, redirections, prefix, EquipSlot.Unknown, EquipSlot.Unknown, idFrom, idTo, ref texture, ref dataWasChanged); - public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, EquipSlot slotFrom, EquipSlot slotTo, SetId idFrom, + public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, EquipSlot slotFrom, + EquipSlot slotTo, SetId idFrom, SetId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) { var path = texture.Path; @@ -428,13 +432,15 @@ public static class EquipmentSwap return FileSwap.CreateSwap(manager, ResourceType.Tex, redirections, newPath, path, path); } - public static FileSwap CreateShader(MetaFileManager manager, Func redirections, ref string shaderName, ref bool dataWasChanged) + public static FileSwap CreateShader(MetaFileManager manager, Func redirections, ref string shaderName, + ref bool dataWasChanged) { var path = $"shader/sm5/shpk/{shaderName}"; return FileSwap.CreateSwap(manager, ResourceType.Shpk, redirections, path, path); } - public static FileSwap CreateAtex(MetaFileManager manager, Func redirections, ref string filePath, ref bool dataWasChanged) + public static FileSwap CreateAtex(MetaFileManager manager, Func redirections, ref string filePath, + ref bool dataWasChanged) { var oldPath = filePath; filePath = ItemSwap.AddSuffix(filePath, ".atex", $"_{Path.GetFileName(filePath).GetStableHashCode():x8}"); diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 02e02ccb..0140d189 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -20,47 +20,45 @@ public static class ItemSwap { public readonly ResourceType Type; - public MissingFileException( ResourceType type, object path ) + public MissingFileException(ResourceType type, object path) : base($"Could not load {type} File Data for \"{path}\".") => Type = type; } - private static bool LoadFile( MetaFileManager manager, FullPath path, out byte[] data ) + private static bool LoadFile(MetaFileManager manager, FullPath path, out byte[] data) { - if( path.FullName.Length > 0 ) - { + if (path.FullName.Length > 0) try { - if( path.IsRooted ) + if (path.IsRooted) { - data = File.ReadAllBytes( path.FullName ); + data = File.ReadAllBytes(path.FullName); return true; } - var file = manager.GameData.GetFile( path.InternalName.ToString() ); - if( file != null ) + var file = manager.GameData.GetFile(path.InternalName.ToString()); + if (file != null) { data = file.Data; return true; } } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Debug( $"Could not load file {path}:\n{e}" ); + Penumbra.Log.Debug($"Could not load file {path}:\n{e}"); } - } - data = Array.Empty< byte >(); + data = Array.Empty(); return false; } public class GenericFile : IWritable { public readonly byte[] Data; - public bool Valid { get; } + public bool Valid { get; } - public GenericFile( MetaFileManager manager, FullPath path ) - => Valid = LoadFile( manager, path, out Data ); + public GenericFile(MetaFileManager manager, FullPath path) + => Valid = LoadFile(manager, path, out Data); public byte[] Write() => Data; @@ -68,69 +66,67 @@ public static class ItemSwap public static readonly GenericFile Invalid = new(null!, FullPath.Empty); } - public static bool LoadFile( MetaFileManager manager, FullPath path, [NotNullWhen( true )] out GenericFile? file ) + public static bool LoadFile(MetaFileManager manager, FullPath path, [NotNullWhen(true)] out GenericFile? file) { - file = new GenericFile( manager, path ); - if( file.Valid ) - { + file = new GenericFile(manager, path); + if (file.Valid) return true; - } file = null; return false; } - public static bool LoadMdl( MetaFileManager manager, FullPath path, [NotNullWhen( true )] out MdlFile? file ) + public static bool LoadMdl(MetaFileManager manager, FullPath path, [NotNullWhen(true)] out MdlFile? file) { try { - if( LoadFile( manager, path, out byte[] data ) ) + if (LoadFile(manager, path, out byte[] data)) { - file = new MdlFile( data ); + file = new MdlFile(data); return true; } } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Debug( $"Could not parse file {path} to Mdl:\n{e}" ); + Penumbra.Log.Debug($"Could not parse file {path} to Mdl:\n{e}"); } file = null; return false; } - public static bool LoadMtrl(MetaFileManager manager, FullPath path, [NotNullWhen( true )] out MtrlFile? file ) + public static bool LoadMtrl(MetaFileManager manager, FullPath path, [NotNullWhen(true)] out MtrlFile? file) { try { - if( LoadFile( manager, path, out byte[] data ) ) + if (LoadFile(manager, path, out byte[] data)) { - file = new MtrlFile( data ); + file = new MtrlFile(data); return true; } } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Debug( $"Could not parse file {path} to Mtrl:\n{e}" ); + Penumbra.Log.Debug($"Could not parse file {path} to Mtrl:\n{e}"); } file = null; return false; } - public static bool LoadAvfx( MetaFileManager manager, FullPath path, [NotNullWhen( true )] out AvfxFile? file ) + public static bool LoadAvfx(MetaFileManager manager, FullPath path, [NotNullWhen(true)] out AvfxFile? file) { try { - if( LoadFile( manager, path, out byte[] data ) ) + if (LoadFile(manager, path, out byte[] data)) { - file = new AvfxFile( data ); + file = new AvfxFile(data); return true; } } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Debug( $"Could not parse file {path} to Avfx:\n{e}" ); + Penumbra.Log.Debug($"Could not parse file {path} to Avfx:\n{e}"); } file = null; @@ -138,40 +134,41 @@ public static class ItemSwap } - public static FileSwap CreatePhyb(MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, EstManipulation.EstType type, GenderRace race, ushort estEntry ) + public static FileSwap CreatePhyb(MetaFileManager manager, Func redirections, EstManipulation.EstType type, + GenderRace race, ushort estEntry) { - var phybPath = GamePaths.Skeleton.Phyb.Path( race, EstManipulation.ToName( type ), estEntry ); - return FileSwap.CreateSwap( manager, ResourceType.Phyb, redirections, phybPath, phybPath ); + var phybPath = GamePaths.Skeleton.Phyb.Path(race, EstManipulation.ToName(type), estEntry); + return FileSwap.CreateSwap(manager, ResourceType.Phyb, redirections, phybPath, phybPath); } - public static FileSwap CreateSklb(MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, EstManipulation.EstType type, GenderRace race, ushort estEntry ) + public static FileSwap CreateSklb(MetaFileManager manager, Func redirections, EstManipulation.EstType type, + GenderRace race, ushort estEntry) { - var sklbPath = GamePaths.Skeleton.Sklb.Path( race, EstManipulation.ToName( type ), estEntry ); - return FileSwap.CreateSwap(manager, ResourceType.Sklb, redirections, sklbPath, sklbPath ); + var sklbPath = GamePaths.Skeleton.Sklb.Path(race, EstManipulation.ToName(type), estEntry); + return FileSwap.CreateSwap(manager, ResourceType.Sklb, redirections, sklbPath, sklbPath); } /// metaChanges is not manipulated, but IReadOnlySet does not support TryGetValue. - public static MetaSwap? CreateEst( MetaFileManager manager, Func< Utf8GamePath, FullPath > redirections, Func< MetaManipulation, MetaManipulation > manips, EstManipulation.EstType type, - GenderRace genderRace, SetId idFrom, SetId idTo, bool ownMdl ) + public static MetaSwap? CreateEst(MetaFileManager manager, Func redirections, + Func manips, EstManipulation.EstType type, + GenderRace genderRace, SetId idFrom, SetId idTo, bool ownMdl) { - if( type == 0 ) - { + if (type == 0) return null; - } var (gender, race) = genderRace.Split(); - var fromDefault = new EstManipulation( gender, race, type, idFrom, EstFile.GetDefault( manager, type, genderRace, idFrom ) ); - var toDefault = new EstManipulation( gender, race, type, idTo, EstFile.GetDefault( manager, type, genderRace, idTo ) ); - var est = new MetaSwap( manips, fromDefault, toDefault ); + var fromDefault = new EstManipulation(gender, race, type, idFrom, EstFile.GetDefault(manager, type, genderRace, idFrom)); + var toDefault = new EstManipulation(gender, race, type, idTo, EstFile.GetDefault(manager, type, genderRace, idTo)); + var est = new MetaSwap(manips, fromDefault, toDefault); - if( ownMdl && est.SwapApplied.Est.Entry >= 2 ) + if (ownMdl && est.SwapApplied.Est.Entry >= 2) { - var phyb = CreatePhyb( manager, redirections, type, genderRace, est.SwapApplied.Est.Entry ); - est.ChildSwaps.Add( phyb ); - var sklb = CreateSklb( manager, redirections, type, genderRace, est.SwapApplied.Est.Entry ); - est.ChildSwaps.Add( sklb ); + var phyb = CreatePhyb(manager, redirections, type, genderRace, est.SwapApplied.Est.Entry); + est.ChildSwaps.Add(phyb); + var sklb = CreateSklb(manager, redirections, type, genderRace, est.SwapApplied.Est.Entry); + est.ChildSwaps.Add(sklb); } - else if( est.SwapAppliedIsDefault ) + else if (est.SwapAppliedIsDefault) { return null; } @@ -179,57 +176,55 @@ public static class ItemSwap return est; } - public static int GetStableHashCode( this string str ) + public static int GetStableHashCode(this string str) { unchecked { var hash1 = 5381; var hash2 = hash1; - for( var i = 0; i < str.Length && str[ i ] != '\0'; i += 2 ) + for (var i = 0; i < str.Length && str[i] != '\0'; i += 2) { - hash1 = ( ( hash1 << 5 ) + hash1 ) ^ str[ i ]; - if( i == str.Length - 1 || str[ i + 1 ] == '\0' ) - { + hash1 = ((hash1 << 5) + hash1) ^ str[i]; + if (i == str.Length - 1 || str[i + 1] == '\0') break; - } - hash2 = ( ( hash2 << 5 ) + hash2 ) ^ str[ i + 1 ]; + hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; } return hash1 + hash2 * 1566083941; } } - public static string ReplaceAnyId( string path, char idType, SetId id, bool condition = true ) + public static string ReplaceAnyId(string path, char idType, SetId id, bool condition = true) => condition - ? Regex.Replace( path, $"{idType}\\d{{4}}", $"{idType}{id.Id:D4}" ) + ? Regex.Replace(path, $"{idType}\\d{{4}}", $"{idType}{id.Id:D4}") : path; - public static string ReplaceAnyRace( string path, GenderRace to, bool condition = true ) - => ReplaceAnyId( path, 'c', ( ushort )to, condition ); + public static string ReplaceAnyRace(string path, GenderRace to, bool condition = true) + => ReplaceAnyId(path, 'c', (ushort)to, condition); - public static string ReplaceAnyBody( string path, BodySlot slot, SetId to, bool condition = true ) - => ReplaceAnyId( path, slot.ToAbbreviation(), to, condition ); + public static string ReplaceAnyBody(string path, BodySlot slot, SetId to, bool condition = true) + => ReplaceAnyId(path, slot.ToAbbreviation(), to, condition); - public static string ReplaceId( string path, char type, SetId idFrom, SetId idTo, bool condition = true ) + public static string ReplaceId(string path, char type, SetId idFrom, SetId idTo, bool condition = true) => condition - ? path.Replace( $"{type}{idFrom.Id:D4}", $"{type}{idTo.Id:D4}" ) + ? path.Replace($"{type}{idFrom.Id:D4}", $"{type}{idTo.Id:D4}") : path; - public static string ReplaceSlot( string path, EquipSlot from, EquipSlot to, bool condition = true ) + public static string ReplaceSlot(string path, EquipSlot from, EquipSlot to, bool condition = true) => condition - ? path.Replace( $"_{from.ToSuffix()}_", $"_{to.ToSuffix()}_" ) + ? path.Replace($"_{from.ToSuffix()}_", $"_{to.ToSuffix()}_") : path; - public static string ReplaceRace( string path, GenderRace from, GenderRace to, bool condition = true ) - => ReplaceId( path, 'c', ( ushort )from, ( ushort )to, condition ); + public static string ReplaceRace(string path, GenderRace from, GenderRace to, bool condition = true) + => ReplaceId(path, 'c', (ushort)from, (ushort)to, condition); - public static string ReplaceBody( string path, BodySlot slot, SetId idFrom, SetId idTo, bool condition = true ) - => ReplaceId( path, slot.ToAbbreviation(), idFrom, idTo, condition ); + public static string ReplaceBody(string path, BodySlot slot, SetId idFrom, SetId idTo, bool condition = true) + => ReplaceId(path, slot.ToAbbreviation(), idFrom, idTo, condition); - public static string AddSuffix( string path, string ext, string suffix, bool condition = true ) + public static string AddSuffix(string path, string ext, string suffix, bool condition = true) => condition - ? path.Replace( ext, suffix + ext ) + ? path.Replace(ext, suffix + ext) : path; -} \ No newline at end of file +} diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 8e6473cc..1db890ed 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -6,6 +6,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; using Penumbra.Meta; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; namespace Penumbra.Mods.ItemSwap; @@ -13,18 +14,18 @@ namespace Penumbra.Mods.ItemSwap; public class ItemSwapContainer { private readonly MetaFileManager _manager; - private readonly IdentifierService _identifier; + private readonly IdentifierService _identifier; - private Dictionary< Utf8GamePath, FullPath > _modRedirections = new(); - private HashSet< MetaManipulation > _modManipulations = new(); + private Dictionary _modRedirections = new(); + private HashSet _modManipulations = new(); - public IReadOnlyDictionary< Utf8GamePath, FullPath > ModRedirections + public IReadOnlyDictionary ModRedirections => _modRedirections; - public IReadOnlySet< MetaManipulation > ModManipulations + public IReadOnlySet ModManipulations => _modManipulations; - public readonly List< Swap > Swaps = new(); + public readonly List Swaps = new(); public bool Loaded { get; private set; } @@ -40,72 +41,69 @@ public class ItemSwapContainer NoSwaps, } - public bool WriteMod( ModManager manager, Mod mod, WriteType writeType = WriteType.NoSwaps, DirectoryInfo? directory = null, int groupIndex = -1, int optionIndex = 0 ) + public bool WriteMod(ModManager manager, Mod mod, WriteType writeType = WriteType.NoSwaps, DirectoryInfo? directory = null, + int groupIndex = -1, int optionIndex = 0) { - var convertedManips = new HashSet< MetaManipulation >( Swaps.Count ); - var convertedFiles = new Dictionary< Utf8GamePath, FullPath >( Swaps.Count ); - var convertedSwaps = new Dictionary< Utf8GamePath, FullPath >( Swaps.Count ); + var convertedManips = new HashSet(Swaps.Count); + var convertedFiles = new Dictionary(Swaps.Count); + var convertedSwaps = new Dictionary(Swaps.Count); directory ??= mod.ModPath; try { - foreach( var swap in Swaps.SelectMany( s => s.WithChildren() ) ) + foreach (var swap in Swaps.SelectMany(s => s.WithChildren())) { - switch( swap ) + switch (swap) { case FileSwap file: // Skip, nothing to do - if( file.SwapToModdedEqualsOriginal ) - { + if (file.SwapToModdedEqualsOriginal) continue; - } - if( writeType == WriteType.UseSwaps && file.SwapToModdedExistsInGame && !file.DataWasChanged ) + if (writeType == WriteType.UseSwaps && file.SwapToModdedExistsInGame && !file.DataWasChanged) { - convertedSwaps.TryAdd( file.SwapFromRequestPath, file.SwapToModded ); + convertedSwaps.TryAdd(file.SwapFromRequestPath, file.SwapToModded); } else { - var path = file.GetNewPath( directory.FullName ); + var path = file.GetNewPath(directory.FullName); var bytes = file.FileData.Write(); - Directory.CreateDirectory( Path.GetDirectoryName( path )! ); - _manager.Compactor.WriteAllBytes( path, bytes ); - convertedFiles.TryAdd( file.SwapFromRequestPath, new FullPath( path ) ); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + _manager.Compactor.WriteAllBytes(path, bytes); + convertedFiles.TryAdd(file.SwapFromRequestPath, new FullPath(path)); } break; case MetaSwap meta: - if( !meta.SwapAppliedIsDefault ) - { - convertedManips.Add( meta.SwapApplied ); - } + if (!meta.SwapAppliedIsDefault) + convertedManips.Add(meta.SwapApplied); break; } } - manager.OptionEditor.OptionSetFiles( mod, groupIndex, optionIndex, convertedFiles ); - manager.OptionEditor.OptionSetFileSwaps( mod, groupIndex, optionIndex, convertedSwaps ); - manager.OptionEditor.OptionSetManipulations( mod, groupIndex, optionIndex, convertedManips ); + manager.OptionEditor.OptionSetFiles(mod, groupIndex, optionIndex, convertedFiles); + manager.OptionEditor.OptionSetFileSwaps(mod, groupIndex, optionIndex, convertedSwaps); + manager.OptionEditor.OptionSetManipulations(mod, groupIndex, optionIndex, convertedManips); return true; } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Error( $"Could not write FileSwapContainer to {mod.ModPath}:\n{e}" ); + Penumbra.Log.Error($"Could not write FileSwapContainer to {mod.ModPath}:\n{e}"); return false; } } - public void LoadMod( Mod? mod, ModSettings? settings ) + public void LoadMod(Mod? mod, ModSettings? settings) { Clear(); - if( mod == null ) + if (mod == null) { - _modRedirections = new Dictionary< Utf8GamePath, FullPath >(); - _modManipulations = new HashSet< MetaManipulation >(); + _modRedirections = new Dictionary(); + _modManipulations = new HashSet(); } else { - ( _modRedirections, _modManipulations ) = ModSettings.GetResolveData( mod, settings ); + (_modRedirections, _modManipulations) = ModSettings.GetResolveData(mod, settings); } } @@ -113,59 +111,61 @@ public class ItemSwapContainer { _manager = manager; _identifier = identifier; - LoadMod( null, null ); + LoadMod(null, null); } - private Func< Utf8GamePath, FullPath > PathResolver( ModCollection? collection ) + private Func PathResolver(ModCollection? collection) => collection != null - ? p => collection.ResolvePath( p ) ?? new FullPath( p ) - : p => ModRedirections.TryGetValue( p, out var path ) ? path : new FullPath( p ); + ? p => collection.ResolvePath(p) ?? new FullPath(p) + : p => ModRedirections.TryGetValue(p, out var path) ? path : new FullPath(p); - private Func< MetaManipulation, MetaManipulation > MetaResolver( ModCollection? collection ) + private Func MetaResolver(ModCollection? collection) { var set = collection?.MetaCache?.Manipulations.ToHashSet() ?? _modManipulations; - return m => set.TryGetValue( m, out var a ) ? a : m; + return m => set.TryGetValue(m, out var a) ? a : m; } - public EquipItem[] LoadEquipment( EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, bool useLeftRing = true ) + public EquipItem[] LoadEquipment(EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, + bool useLeftRing = true) { Swaps.Clear(); Loaded = false; - var ret = EquipmentSwap.CreateItemSwap( _manager, _identifier.AwaitedService, Swaps, PathResolver( collection ), MetaResolver( collection ), from, to, useRightRing, useLeftRing ); + var ret = EquipmentSwap.CreateItemSwap(_manager, _identifier.AwaitedService, Swaps, PathResolver(collection), MetaResolver(collection), + from, to, useRightRing, useLeftRing); Loaded = true; return ret; } - public EquipItem[] LoadTypeSwap( EquipSlot slotFrom, EquipItem from, EquipSlot slotTo, EquipItem to, ModCollection? collection = null ) + public EquipItem[] LoadTypeSwap(EquipSlot slotFrom, EquipItem from, EquipSlot slotTo, EquipItem to, ModCollection? collection = null) { Swaps.Clear(); Loaded = false; - var ret = EquipmentSwap.CreateTypeSwap( _manager, _identifier.AwaitedService, Swaps, PathResolver( collection ), MetaResolver( collection ), slotFrom, from, slotTo, to ); + var ret = EquipmentSwap.CreateTypeSwap(_manager, _identifier.AwaitedService, Swaps, PathResolver(collection), MetaResolver(collection), + slotFrom, from, slotTo, to); Loaded = true; return ret; } - public bool LoadCustomization( MetaFileManager manager, BodySlot slot, GenderRace race, SetId from, SetId to, ModCollection? collection = null ) + public bool LoadCustomization(MetaFileManager manager, BodySlot slot, GenderRace race, SetId from, SetId to, + ModCollection? collection = null) { - var pathResolver = PathResolver( collection ); - var mdl = CustomizationSwap.CreateMdl( manager, pathResolver, slot, race, from, to ); + var pathResolver = PathResolver(collection); + var mdl = CustomizationSwap.CreateMdl(manager, pathResolver, slot, race, from, to); var type = slot switch { BodySlot.Hair => EstManipulation.EstType.Hair, BodySlot.Face => EstManipulation.EstType.Face, - _ => ( EstManipulation.EstType )0, + _ => (EstManipulation.EstType)0, }; - var metaResolver = MetaResolver( collection ); - var est = ItemSwap.CreateEst( manager, pathResolver, metaResolver, type, race, from, to, true ); + var metaResolver = MetaResolver(collection); + var est = ItemSwap.CreateEst(manager, pathResolver, metaResolver, type, race, from, to, true); - Swaps.Add( mdl ); - if( est != null ) - { - Swaps.Add( est ); - } + Swaps.Add(mdl); + if (est != null) + Swaps.Add(est); Loaded = true; return true; } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/Manager/ModExportManager.cs b/Penumbra/Mods/Manager/ModExportManager.cs index 7d79d3d4..676018be 100644 --- a/Penumbra/Mods/Manager/ModExportManager.cs +++ b/Penumbra/Mods/Manager/ModExportManager.cs @@ -89,4 +89,4 @@ public class ModExportManager : IDisposable new ModBackup(this, mod).Move(null, newDirectory.Name); mod.ModPath = newDirectory; } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index f7006c4c..013d0e40 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -2,11 +2,9 @@ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using OtterGui.Filesystem; using Penumbra.Communication; -using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.Util; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Manager; public sealed class ModFileSystem : FileSystem, IDisposable, ISavable { diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index 6c49ccf8..cc91dfa6 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using Dalamud.Interface.Internal.Notifications; using Penumbra.Import; diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index f8d293a2..e258f996 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Services; @@ -16,7 +15,7 @@ public enum NewDirectoryState Identical, Empty, } - + /// Describes the state of a changed mod event. public enum ModPathChangeType { @@ -25,7 +24,7 @@ public enum ModPathChangeType Moved, Reloaded, StartingReload, -} +} public sealed class ModManager : ModStorage, IDisposable { @@ -46,8 +45,8 @@ public sealed class ModManager : ModStorage, IDisposable _communicator = communicator; DataEditor = dataEditor; OptionEditor = optionEditor; - Creator = creator; - SetBaseDirectory(config.ModDirectory, true); + Creator = creator; + SetBaseDirectory(config.ModDirectory, true); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModManager); DiscoverMods(); } @@ -242,7 +241,7 @@ public sealed class ModManager : ModStorage, IDisposable { switch (type) { - case ModPathChangeType.Added: + case ModPathChangeType.Added: SetNew(mod); break; case ModPathChangeType.Deleted: diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 3cfab943..ddd88a72 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -6,7 +6,6 @@ using Penumbra.Api.Enums; using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.String.Classes; -using Penumbra.Util; namespace Penumbra.Mods.Manager; @@ -19,7 +18,9 @@ public static partial class ModMigration private static partial Regex GroupStartRegex(); public static bool Migrate(ModCreator creator, SaveService saveService, Mod mod, JObject json, ref uint fileVersion) - => MigrateV0ToV1(creator, saveService, mod, json, ref fileVersion) || MigrateV1ToV2(saveService, mod, ref fileVersion) || MigrateV2ToV3(mod, ref fileVersion); + => MigrateV0ToV1(creator, saveService, mod, json, ref fileVersion) + || MigrateV1ToV2(saveService, mod, ref fileVersion) + || MigrateV2ToV3(mod, ref fileVersion); private static bool MigrateV2ToV3(Mod _, ref uint fileVersion) { @@ -63,8 +64,8 @@ public static partial class ModMigration var swaps = json["FileSwaps"]?.ToObject>() ?? new Dictionary(); - var groups = json["Groups"]?.ToObject>() ?? new Dictionary(); - var priority = 1; + var groups = json["Groups"]?.ToObject>() ?? new Dictionary(); + var priority = 1; var seenMetaFiles = new HashSet(); foreach (var group in groups.Values) ConvertGroup(creator, mod, group, ref priority, seenMetaFiles); @@ -128,8 +129,8 @@ public static partial class ModMigration var optionPriority = 0; var newMultiGroup = new MultiModGroup() { - Name = group.GroupName, - Priority = priority++, + Name = group.GroupName, + Priority = priority++, Description = string.Empty, }; mod.Groups.Add(newMultiGroup); @@ -146,8 +147,8 @@ public static partial class ModMigration var newSingleGroup = new SingleModGroup() { - Name = group.GroupName, - Priority = priority++, + Name = group.GroupName, + Priority = priority++, Description = string.Empty, }; mod.Groups.Add(newSingleGroup); diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 4ce6da9a..41cc023e 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -5,7 +5,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; -public sealed partial class Mod : IMod +public sealed class Mod : IMod { public static readonly TemporaryMod ForcedFiles = new() { diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index b5462eee..89d35cd2 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -113,9 +113,7 @@ public partial class ModCreator } if (changes) - { _saveService.SaveAllOptionGroups(mod, true); - } } /// Load the default option for a given mod. diff --git a/Penumbra/Mods/ModLocalData.cs b/Penumbra/Mods/ModLocalData.cs index 56ee827b..51fe8d58 100644 --- a/Penumbra/Mods/ModLocalData.cs +++ b/Penumbra/Mods/ModLocalData.cs @@ -2,7 +2,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.Util; namespace Penumbra.Mods; diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index 49094aa0..d29cdb9c 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -1,7 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Services; -using Penumbra.Util; namespace Penumbra.Mods; diff --git a/Penumbra/Mods/Subclasses/ISubMod.cs b/Penumbra/Mods/Subclasses/ISubMod.cs index ac92cd13..8c296f20 100644 --- a/Penumbra/Mods/Subclasses/ISubMod.cs +++ b/Penumbra/Mods/Subclasses/ISubMod.cs @@ -1,58 +1,57 @@ using Newtonsoft.Json; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Subclasses; public interface ISubMod { - public string Name { get; } - public string FullName { get; } + public string Name { get; } + public string FullName { get; } public string Description { get; } - public IReadOnlyDictionary< Utf8GamePath, FullPath > Files { get; } - public IReadOnlyDictionary< Utf8GamePath, FullPath > FileSwaps { get; } - public IReadOnlySet< MetaManipulation > Manipulations { get; } + public IReadOnlyDictionary Files { get; } + public IReadOnlyDictionary FileSwaps { get; } + public IReadOnlySet Manipulations { get; } public bool IsDefault { get; } - public static void WriteSubMod( JsonWriter j, JsonSerializer serializer, ISubMod mod, DirectoryInfo basePath, int? priority ) + public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, ISubMod mod, DirectoryInfo basePath, int? priority) { j.WriteStartObject(); - j.WritePropertyName( nameof( Name ) ); - j.WriteValue( mod.Name ); - j.WritePropertyName( nameof(Description) ); - j.WriteValue( mod.Description ); - if( priority != null ) + j.WritePropertyName(nameof(Name)); + j.WriteValue(mod.Name); + j.WritePropertyName(nameof(Description)); + j.WriteValue(mod.Description); + if (priority != null) { - j.WritePropertyName( nameof( IModGroup.Priority ) ); - j.WriteValue( priority.Value ); + j.WritePropertyName(nameof(IModGroup.Priority)); + j.WriteValue(priority.Value); } - j.WritePropertyName( nameof( mod.Files ) ); + j.WritePropertyName(nameof(mod.Files)); j.WriteStartObject(); - foreach( var (gamePath, file) in mod.Files ) + foreach (var (gamePath, file) in mod.Files) { - if( file.ToRelPath( basePath, out var relPath ) ) + if (file.ToRelPath(basePath, out var relPath)) { - j.WritePropertyName( gamePath.ToString() ); - j.WriteValue( relPath.ToString() ); + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(relPath.ToString()); } } j.WriteEndObject(); - j.WritePropertyName( nameof( mod.FileSwaps ) ); + j.WritePropertyName(nameof(mod.FileSwaps)); j.WriteStartObject(); - foreach( var (gamePath, file) in mod.FileSwaps ) + foreach (var (gamePath, file) in mod.FileSwaps) { - j.WritePropertyName( gamePath.ToString() ); - j.WriteValue( file.ToString() ); + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(file.ToString()); } j.WriteEndObject(); - j.WritePropertyName( nameof( mod.Manipulations ) ); - serializer.Serialize( j, mod.Manipulations ); + j.WritePropertyName(nameof(mod.Manipulations)); + serializer.Serialize(j, mod.Manipulations); j.WriteEndObject(); } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index 537c989f..122c6d29 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -3,10 +3,9 @@ using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Subclasses; /// Contains the settings for a given mod. public class ModSettings @@ -267,4 +266,4 @@ public class ModSettings return ( Enabled, Priority, dict ); } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index d40a79be..4d29c58d 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -4,10 +4,9 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; -using Penumbra.Mods.Subclasses; -namespace Penumbra.Mods; - +namespace Penumbra.Mods.Subclasses; + /// Groups that allow all available options to be selected at once. public sealed class MultiModGroup : IModGroup { diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index a69238f5..1184b6ed 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -3,9 +3,8 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; -using Penumbra.Mods.Subclasses; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Subclasses; /// Groups that allow only one of their available options to be selected. public sealed class SingleModGroup : IModGroup @@ -18,59 +17,55 @@ public sealed class SingleModGroup : IModGroup public int Priority { get; set; } public uint DefaultSettings { get; set; } - public readonly List< SubMod > OptionData = new(); + public readonly List OptionData = new(); - public int OptionPriority( Index _ ) + public int OptionPriority(Index _) => Priority; - public ISubMod this[ Index idx ] - => OptionData[ idx ]; + public ISubMod this[Index idx] + => OptionData[idx]; [JsonIgnore] public int Count => OptionData.Count; - public IEnumerator< ISubMod > GetEnumerator() + public IEnumerator GetEnumerator() => OptionData.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public static SingleModGroup? Load( Mod mod, JObject json, int groupIdx ) + public static SingleModGroup? Load(Mod mod, JObject json, int groupIdx) { - var options = json[ "Options" ]; + var options = json["Options"]; var ret = new SingleModGroup { - Name = json[ nameof( Name ) ]?.ToObject< string >() ?? string.Empty, - Description = json[ nameof( Description ) ]?.ToObject< string >() ?? string.Empty, - Priority = json[ nameof( Priority ) ]?.ToObject< int >() ?? 0, - DefaultSettings = json[ nameof( DefaultSettings ) ]?.ToObject< uint >() ?? 0u, + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? 0, + DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? 0u, }; - if( ret.Name.Length == 0 ) - { + if (ret.Name.Length == 0) return null; - } - if( options != null ) - { - foreach( var child in options.Children() ) + if (options != null) + foreach (var child in options.Children()) { - var subMod = new SubMod( mod ); - subMod.SetPosition( groupIdx, ret.OptionData.Count ); - subMod.Load( mod.ModPath, child, out _ ); - ret.OptionData.Add( subMod ); + var subMod = new SubMod(mod); + subMod.SetPosition(groupIdx, ret.OptionData.Count); + subMod.Load(mod.ModPath, child, out _); + ret.OptionData.Add(subMod); } - } - if( ( int )ret.DefaultSettings >= ret.Count ) + if ((int)ret.DefaultSettings >= ret.Count) ret.DefaultSettings = 0; return ret; } - public IModGroup Convert( GroupType type ) + public IModGroup Convert(GroupType type) { - switch( type ) + switch (type) { case GroupType.Single: return this; case GroupType.Multi: @@ -79,47 +74,41 @@ public sealed class SingleModGroup : IModGroup Name = Name, Description = Description, Priority = Priority, - DefaultSettings = 1u << ( int )DefaultSettings, + DefaultSettings = 1u << (int)DefaultSettings, }; - multi.PrioritizedOptions.AddRange( OptionData.Select( ( o, i ) => ( o, i ) ) ); + multi.PrioritizedOptions.AddRange(OptionData.Select((o, i) => (o, i))); return multi; - default: throw new ArgumentOutOfRangeException( nameof( type ), type, null ); + default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } } - public bool MoveOption( int optionIdxFrom, int optionIdxTo ) + public bool MoveOption(int optionIdxFrom, int optionIdxTo) { - if( !OptionData.Move( optionIdxFrom, optionIdxTo ) ) - { + if (!OptionData.Move(optionIdxFrom, optionIdxTo)) return false; - } // Update default settings with the move. - if( DefaultSettings == optionIdxFrom ) + if (DefaultSettings == optionIdxFrom) { - DefaultSettings = ( uint )optionIdxTo; + DefaultSettings = (uint)optionIdxTo; } - else if( optionIdxFrom < optionIdxTo ) + else if (optionIdxFrom < optionIdxTo) { - if( DefaultSettings > optionIdxFrom && DefaultSettings <= optionIdxTo ) - { + if (DefaultSettings > optionIdxFrom && DefaultSettings <= optionIdxTo) --DefaultSettings; - } } - else if( DefaultSettings < optionIdxFrom && DefaultSettings >= optionIdxTo ) + else if (DefaultSettings < optionIdxFrom && DefaultSettings >= optionIdxTo) { ++DefaultSettings; } - UpdatePositions( Math.Min( optionIdxFrom, optionIdxTo ) ); + UpdatePositions(Math.Min(optionIdxFrom, optionIdxTo)); return true; } - public void UpdatePositions( int from = 0 ) + public void UpdatePositions(int from = 0) { - foreach( var (o, i) in OptionData.WithIndex().Skip( from ) ) - { - o.SetPosition( o.GroupIdx, i ); - } + foreach (var (o, i) in OptionData.WithIndex().Skip(from)) + o.SetPosition(o.GroupIdx, i); } -} \ No newline at end of file +} diff --git a/Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs similarity index 97% rename from Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs rename to Penumbra/Mods/Subclasses/SubMod.cs index 7c43de86..542b14d2 100644 --- a/Penumbra/Mods/Subclasses/Mod.Files.SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -1,11 +1,8 @@ using Newtonsoft.Json.Linq; -using Penumbra.Import; -using Penumbra.Meta; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Subclasses; /// /// A sub mod is a collection of diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index fcd4a5f7..73273707 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -5,7 +5,6 @@ using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.String.Classes; -using Penumbra.Util; namespace Penumbra.Mods; @@ -21,80 +20,84 @@ public class TemporaryMod : IMod public readonly SubMod Default; ISubMod IMod.Default - => Default; + => Default; - public IReadOnlyList< IModGroup > Groups - => Array.Empty< IModGroup >(); + public IReadOnlyList Groups + => Array.Empty(); - public IEnumerable< SubMod > AllSubMods - => new[] { Default }; + public IEnumerable AllSubMods + => new[] + { + Default, + }; public TemporaryMod() - => Default = new SubMod( this ); + => Default = new SubMod(this); - public void SetFile( Utf8GamePath gamePath, FullPath fullPath ) - => Default.FileData[ gamePath ] = fullPath; + public void SetFile(Utf8GamePath gamePath, FullPath fullPath) + => Default.FileData[gamePath] = fullPath; - public bool SetManipulation( MetaManipulation manip ) - => Default.ManipulationData.Remove( manip ) | Default.ManipulationData.Add( manip ); + public bool SetManipulation(MetaManipulation manip) + => Default.ManipulationData.Remove(manip) | Default.ManipulationData.Add(manip); - public void SetAll( Dictionary< Utf8GamePath, FullPath > dict, HashSet< MetaManipulation > manips ) + public void SetAll(Dictionary dict, HashSet manips) { Default.FileData = dict; Default.ManipulationData = manips; } - public static void SaveTempCollection( Configuration config, SaveService saveService, ModManager modManager, ModCollection collection, string? character = null ) + public static void SaveTempCollection(Configuration config, SaveService saveService, ModManager modManager, ModCollection collection, + string? character = null) { DirectoryInfo? dir = null; try { - dir = ModCreator.CreateModFolder( modManager.BasePath, collection.Name ); - var fileDir = Directory.CreateDirectory( Path.Combine( dir.FullName, "files" ) ); - modManager.DataEditor.CreateMeta( dir, collection.Name, character ?? config.DefaultModAuthor, - $"Mod generated from temporary collection {collection.Name} for {character ?? "Unknown Character"}.", null, null ); - var mod = new Mod( dir ); + dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Name); + var fileDir = Directory.CreateDirectory(Path.Combine(dir.FullName, "files")); + modManager.DataEditor.CreateMeta(dir, collection.Name, character ?? config.DefaultModAuthor, + $"Mod generated from temporary collection {collection.Name} for {character ?? "Unknown Character"}.", null, null); + var mod = new Mod(dir); var defaultMod = mod.Default; - foreach( var (gamePath, fullPath) in collection.ResolvedFiles ) + foreach (var (gamePath, fullPath) in collection.ResolvedFiles) { - if( gamePath.Path.EndsWith( ".imc"u8 ) ) + if (gamePath.Path.EndsWith(".imc"u8)) { continue; } var targetPath = fullPath.Path.FullName; - if( fullPath.Path.Name.StartsWith( '|' ) ) + if (fullPath.Path.Name.StartsWith('|')) { - targetPath = targetPath.Split( '|', 3, StringSplitOptions.RemoveEmptyEntries ).Last(); + targetPath = targetPath.Split('|', 3, StringSplitOptions.RemoveEmptyEntries).Last(); } - if( Path.IsPathRooted(targetPath) ) + if (Path.IsPathRooted(targetPath)) { - var target = Path.Combine( fileDir.FullName, Path.GetFileName(targetPath) ); - File.Copy( targetPath, target, true ); - defaultMod.FileData[ gamePath ] = new FullPath( target ); + var target = Path.Combine(fileDir.FullName, Path.GetFileName(targetPath)); + File.Copy(targetPath, target, true); + defaultMod.FileData[gamePath] = new FullPath(target); } else { - defaultMod.FileSwapData[ gamePath ] = new FullPath(targetPath); + defaultMod.FileSwapData[gamePath] = new FullPath(targetPath); } } - foreach( var manip in collection.MetaCache?.Manipulations ?? Array.Empty< MetaManipulation >() ) - defaultMod.ManipulationData.Add( manip ); + foreach (var manip in collection.MetaCache?.Manipulations ?? Array.Empty()) + defaultMod.ManipulationData.Add(manip); saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod)); - modManager.AddMod( dir ); - Penumbra.Log.Information( $"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Name}." ); + modManager.AddMod(dir); + Penumbra.Log.Information($"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Name}."); } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Error( $"Could not save temporary collection {collection.Name} to permanent Mod:\n{e}" ); - if( dir != null && Directory.Exists( dir.FullName ) ) + Penumbra.Log.Error($"Could not save temporary collection {collection.Name} to permanent Mod:\n{e}"); + if (dir != null && Directory.Exists(dir.FullName)) { try { - Directory.Delete( dir.FullName, true ); + Directory.Delete(dir.FullName, true); } catch { @@ -103,4 +106,4 @@ public class TemporaryMod : IMod } } } -} \ No newline at end of file +} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 1402ef89..019355af 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -20,6 +20,7 @@ using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; +using Penumbra.UI; namespace Penumbra; diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index 89f1063e..d896e526 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -7,6 +7,7 @@ using Penumbra.Interop.Services; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.UI.Classes; namespace Penumbra.Services; @@ -331,7 +332,8 @@ public class ConfigMigrationService dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value with { Priority = maxPriority - kvp.Value.Priority }); var emptyStorage = new ModStorage(); - var collection = ModCollection.CreateFromData(_saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, Array.Empty()); + var collection = ModCollection.CreateFromData(_saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, + Array.Empty()); _saveService.ImmediateSave(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudServices.cs index 6754d0bd..0cd4c97a 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudServices.cs @@ -6,7 +6,6 @@ using Dalamud.Game.Gui; using Dalamud.Interface; using Dalamud.IoC; using Dalamud.Plugin; -using System.Reflection; using Dalamud.Interface.DragDrop; using Dalamud.Plugin.Services; using Microsoft.Extensions.DependencyInjection; diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 07c7394c..b76c39ef 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -21,6 +21,7 @@ using Penumbra.UI; using Penumbra.UI.AdvancedWindow; using Penumbra.UI.Classes; using Penumbra.UI.ModsTab; +using Penumbra.UI.ResourceWatcher; using Penumbra.UI.Tabs; namespace Penumbra.Services; diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 1c6b3ef1..30e22a7a 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -16,17 +16,18 @@ public class StainService : IDisposable { } } - public readonly StainData StainData; - public readonly FilterComboColors StainCombo; - public readonly StmFile StmFile; + public readonly StainData StainData; + public readonly FilterComboColors StainCombo; + public readonly StmFile StmFile; public readonly StainTemplateCombo TemplateCombo; public StainService(StartTracker timer, DalamudPluginInterface pluginInterface, IDataManager dataManager) { using var t = timer.Measure(StartTimeType.Stains); StainData = new StainData(pluginInterface, dataManager, dataManager.Language); - StainCombo = new FilterComboColors(140, StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false)))); - StmFile = new StmFile(dataManager); + StainCombo = new FilterComboColors(140, + StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false)))); + StmFile = new StmFile(dataManager); TemplateCombo = new StainTemplateCombo(StmFile.Entries.Keys.Prepend((ushort)0)); Penumbra.Log.Verbose($"[{nameof(StainService)}] Created."); } @@ -36,4 +37,4 @@ public class StainService : IDisposable StainData.Dispose(); Penumbra.Log.Verbose($"[{nameof(StainService)}] Disposed."); } -} \ No newline at end of file +} diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index e97a9a82..b8d9b30a 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -1,4 +1,3 @@ -using System.Reflection; using Dalamud.Interface.Internal.Notifications; using Dalamud.Plugin; @@ -25,20 +24,21 @@ public class ValidityChecker DevPenumbraExists = CheckDevPluginPenumbra(pi); IsNotInstalledPenumbra = CheckIsNotInstalled(pi); IsValidSourceRepo = CheckSourceRepo(pi); - + var assembly = Assembly.GetExecutingAssembly(); - Version = assembly.GetName().Version?.ToString() ?? string.Empty; + Version = assembly.GetName().Version?.ToString() ?? string.Empty; CommitHash = assembly.GetCustomAttribute()?.InformationalVersion ?? "Unknown"; } public void LogExceptions() { - if( ImcExceptions.Count > 0 ) - Penumbra.Chat.NotificationMessage( $"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", "Warning", NotificationType.Warning ); + if (ImcExceptions.Count > 0) + Penumbra.Chat.NotificationMessage($"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", + "Warning", NotificationType.Warning); } // Because remnants of penumbra in devPlugins cause issues, we check for them to warn users to remove them. - private static bool CheckDevPluginPenumbra( DalamudPluginInterface pi ) + private static bool CheckDevPluginPenumbra(DalamudPluginInterface pi) { #if !DEBUG var path = Path.Combine( pi.DalamudAssetDirectory.Parent?.FullName ?? "INVALIDPATH", "devPlugins", "Penumbra" ); @@ -59,7 +59,7 @@ public class ValidityChecker } // Check if the loaded version of Penumbra itself is in devPlugins. - private static bool CheckIsNotInstalled( DalamudPluginInterface pi ) + private static bool CheckIsNotInstalled(DalamudPluginInterface pi) { #if !DEBUG var checkedDirectory = pi.AssemblyLocation.Directory?.Parent?.Parent?.Name; @@ -76,7 +76,7 @@ public class ValidityChecker } // Check if the loaded version of Penumbra is installed from a valid source repo. - private static bool CheckSourceRepo( DalamudPluginInterface pi ) + private static bool CheckSourceRepo(DalamudPluginInterface pi) { #if !DEBUG return pi.SourceRepository?.Trim().ToLowerInvariant() switch @@ -90,4 +90,4 @@ public class ValidityChecker return true; #endif } -} \ No newline at end of file +} diff --git a/Penumbra/Services/Wrappers.cs b/Penumbra/Services/Wrappers.cs index d9bef172..69dbbeab 100644 --- a/Penumbra/Services/Wrappers.cs +++ b/Penumbra/Services/Wrappers.cs @@ -12,7 +12,8 @@ namespace Penumbra.Services; public sealed class IdentifierService : AsyncServiceWrapper { public IdentifierService(StartTracker tracker, DalamudPluginInterface pi, IDataManager data, ItemService items) - : base(nameof(IdentifierService), tracker, StartTimeType.Identifier, () => GameData.GameData.GetIdentifier(pi, data, items.AwaitedService)) + : base(nameof(IdentifierService), tracker, StartTimeType.Identifier, + () => GameData.GameData.GetIdentifier(pi, data, items.AwaitedService)) { } } @@ -30,4 +31,4 @@ public sealed class ActorService : AsyncServiceWrapper : base(nameof(ActorService), tracker, StartTimeType.Actors, () => new ActorManager(pi, objects, clientState, framework, gameData, gui, idx => (short)cutscene.GetParentIndex(idx))) { } -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index d14c7125..4a193591 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -4,6 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using Penumbra.Mods; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -289,14 +290,14 @@ public partial class ModEditWindow if (_selectedFiles.Count == 0) tt += "\n\nNo files selected."; else if (!active) - tt += $"\n\nHold {_config.DeleteModModifier} to delete."; - + tt += $"\n\nHold {_config.DeleteModModifier} to delete."; + if (ImGuiUtil.DrawDisabledButton("Delete Selected Files", Vector2.Zero, tt, _selectedFiles.Count == 0 || !active)) _editor.FileEditor.DeleteFiles(_editor.Mod!, _editor.Option!, _editor.Files.Available.Where(_selectedFiles.Contains)); ImGui.SameLine(); var changes = _editor.FileEditor.Changes; - tt = changes ? "Apply the current file setup to the currently selected option." : "No changes made."; + tt = changes ? "Apply the current file setup to the currently selected option." : "No changes made."; if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, !changes)) { var failedFiles = _editor.FileEditor.Apply(_editor.Mod!, (SubMod)_editor.Option!); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index 4f04150f..cccc43ee 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -32,7 +32,7 @@ public partial class ModEditWindow ImGui.SameLine(); ret |= ColorTableDyeableCheckbox(tab); } - + var hasDyeTable = tab.Mtrl.HasDyeTable; if (hasDyeTable) { @@ -114,10 +114,8 @@ public partial class ModEditWindow { var ret = false; if (tab.Mtrl.HasDyeTable) - { for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId); - } tab.UpdateColorTablePreview(); @@ -195,7 +193,7 @@ public partial class ModEditWindow } private static bool ColorTableDyeableCheckbox(MtrlTab tab) - { + { var dyeable = tab.Mtrl.HasDyeTable; var ret = ImGui.Checkbox("Dyeable", ref dyeable); @@ -259,9 +257,9 @@ public partial class ModEditWindow } using var id = ImRaii.PushId(rowIdx); - ref var row = ref tab.Mtrl.Table[rowIdx]; + ref var row = ref tab.Mtrl.Table[rowIdx]; var hasDye = tab.Mtrl.HasDyeTable; - ref var dye = ref tab.Mtrl.DyeTable[rowIdx]; + ref var dye = ref tab.Mtrl.DyeTable[rowIdx]; var floatSize = 70 * UiHelpers.Scale; var intSize = 45 * UiHelpers.Scale; ImGui.TableNextColumn(); @@ -301,7 +299,8 @@ public partial class ModEditWindow ImGui.SameLine(); var tmpFloat = row.SpecularStrength; ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.01f, 0f, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.SpecularStrength)) + if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.01f, 0f, HalfMaxValue, "%.2f") + && FixFloat(ref tmpFloat, row.SpecularStrength)) { row.SpecularStrength = tmpFloat; ret = true; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 187d86c7..ad83843d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -475,9 +475,9 @@ public partial class ModEditWindow } } - UpdateMaterialPreview(); - - if (!Mtrl.HasTable) + UpdateMaterialPreview(); + + if (!Mtrl.HasTable) return; foreach (var materialInfo in instances) @@ -591,9 +591,9 @@ public partial class ModEditWindow public void UpdateColorTableRowPreview(int rowIdx) { if (ColorTablePreviewers.Count == 0) - return; - - if (!Mtrl.HasTable) + return; + + if (!Mtrl.HasTable) return; var row = Mtrl.Table[rowIdx]; @@ -619,16 +619,16 @@ public partial class ModEditWindow public void UpdateColorTablePreview() { if (ColorTablePreviewers.Count == 0) - return; - - if (!Mtrl.HasTable) + return; + + if (!Mtrl.HasTable) return; var rows = Mtrl.Table; if (Mtrl.HasDyeTable) { - var stm = _edit._stainService.StmFile; - var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; + var stm = _edit._stainService.StmFile; + var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) { ref var row = ref rows[i]; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index a6a93a36..821f4454 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -8,7 +8,6 @@ using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.UI.Classes; @@ -66,20 +65,26 @@ public partial class ModEditWindow if (!child) return; - DrawEditHeader(_editor.MetaEditor.Eqp, "Equipment Parameter Edits (EQP)###EQP", 5, EqpRow.Draw, EqpRow.DrawNew , _editor.MetaEditor.OtherEqpCount); - DrawEditHeader(_editor.MetaEditor.Eqdp, "Racial Model Edits (EQDP)###EQDP", 7, EqdpRow.Draw, EqdpRow.DrawNew, _editor.MetaEditor.OtherEqdpCount); - DrawEditHeader(_editor.MetaEditor.Imc, "Variant Edits (IMC)###IMC", 10, ImcRow.Draw, ImcRow.DrawNew , _editor.MetaEditor.OtherImcCount); - DrawEditHeader(_editor.MetaEditor.Est, "Extra Skeleton Parameters (EST)###EST", 7, EstRow.Draw, EstRow.DrawNew , _editor.MetaEditor.OtherEstCount); - DrawEditHeader(_editor.MetaEditor.Gmp, "Visor/Gimmick Edits (GMP)###GMP", 7, GmpRow.Draw, GmpRow.DrawNew , _editor.MetaEditor.OtherGmpCount); - DrawEditHeader(_editor.MetaEditor.Rsp, "Racial Scaling Edits (RSP)###RSP", 5, RspRow.Draw, RspRow.DrawNew , _editor.MetaEditor.OtherRspCount); + DrawEditHeader(_editor.MetaEditor.Eqp, "Equipment Parameter Edits (EQP)###EQP", 5, EqpRow.Draw, EqpRow.DrawNew, + _editor.MetaEditor.OtherEqpCount); + DrawEditHeader(_editor.MetaEditor.Eqdp, "Racial Model Edits (EQDP)###EQDP", 7, EqdpRow.Draw, EqdpRow.DrawNew, + _editor.MetaEditor.OtherEqdpCount); + DrawEditHeader(_editor.MetaEditor.Imc, "Variant Edits (IMC)###IMC", 10, ImcRow.Draw, ImcRow.DrawNew, _editor.MetaEditor.OtherImcCount); + DrawEditHeader(_editor.MetaEditor.Est, "Extra Skeleton Parameters (EST)###EST", 7, EstRow.Draw, EstRow.DrawNew, + _editor.MetaEditor.OtherEstCount); + DrawEditHeader(_editor.MetaEditor.Gmp, "Visor/Gimmick Edits (GMP)###GMP", 7, GmpRow.Draw, GmpRow.DrawNew, + _editor.MetaEditor.OtherGmpCount); + DrawEditHeader(_editor.MetaEditor.Rsp, "Racial Scaling Edits (RSP)###RSP", 5, RspRow.Draw, RspRow.DrawNew, + _editor.MetaEditor.OtherRspCount); } - /// The headers for the different meta changes all have basically the same structure for different types. - private void DrawEditHeader(IReadOnlyCollection items, string label, int numColumns, Action draw, + /// The headers for the different meta changes all have basically the same structure for different types. + private void DrawEditHeader(IReadOnlyCollection items, string label, int numColumns, + Action draw, Action drawNew, int otherCount) - { - const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.BordersInnerV; + { + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.BordersInnerV; var oldPos = ImGui.GetCursorPosY(); var header = ImGui.CollapsingHeader($"{items.Count} {label}"); @@ -88,10 +93,11 @@ public partial class ModEditWindow { var text = $"{otherCount} Edits in other Options"; var size = ImGui.CalcTextSize(text).X; - ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionAvail().X - size, oldPos + ImGui.GetStyle().FramePadding.Y)); - ImGuiUtil.TextColored(ColorId.RedundantAssignment.Value() | 0xFF000000, text); + ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionAvail().X - size, oldPos + ImGui.GetStyle().FramePadding.Y)); + ImGuiUtil.TextColored(ColorId.RedundantAssignment.Value() | 0xFF000000, text); ImGui.SetCursorPos(newPos); - } + } + if (!header) return; @@ -223,7 +229,8 @@ public partial class ModEditWindow ImGui.TableNextColumn(); if (IdInput("##eqdpId", IdWidth, _new.SetId.Id, out var setId, 0, ExpandedEqpGmpBase.Count - 1, _new.SetId <= 1)) { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), _new.Slot.IsAccessory(), setId); + var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), + _new.Slot.IsAccessory(), setId); _new = new EqdpManipulation(newDefaultEntry, _new.Slot, _new.Gender, _new.Race, setId); } @@ -232,7 +239,8 @@ public partial class ModEditWindow ImGui.TableNextColumn(); if (Combos.Race("##eqdpRace", _new.Race, out var race)) { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, race), _new.Slot.IsAccessory(), _new.SetId); + var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, race), + _new.Slot.IsAccessory(), _new.SetId); _new = new EqdpManipulation(newDefaultEntry, _new.Slot, _new.Gender, race, _new.SetId); } @@ -241,7 +249,8 @@ public partial class ModEditWindow ImGui.TableNextColumn(); if (Combos.Gender("##eqdpGender", _new.Gender, out var gender)) { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(gender, _new.Race), _new.Slot.IsAccessory(), _new.SetId); + var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(gender, _new.Race), + _new.Slot.IsAccessory(), _new.SetId); _new = new EqdpManipulation(newDefaultEntry, _new.Slot, gender, _new.Race, _new.SetId); } @@ -250,7 +259,8 @@ public partial class ModEditWindow ImGui.TableNextColumn(); if (Combos.EqdpEquipSlot("##eqdpSlot", _new.Slot, out var slot)) { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), slot.IsAccessory(), _new.SetId); + var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), + slot.IsAccessory(), _new.SetId); _new = new EqdpManipulation(newDefaultEntry, slot, _new.Gender, _new.Race, _new.SetId); } @@ -288,7 +298,8 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip(EquipSlotTooltip); // Values - var defaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(meta.Gender, meta.Race), meta.Slot.IsAccessory(), meta.SetId); + var defaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(meta.Gender, meta.Race), meta.Slot.IsAccessory(), + meta.SetId); var (defaultBit1, defaultBit2) = defaultEntry.ToBits(meta.Slot); var (bit1, bit2) = meta.Entry.ToBits(meta.Slot); ImGui.TableNextColumn(); @@ -311,7 +322,7 @@ public partial class ModEditWindow private static float SmallIdWidth => 45 * UiHelpers.Scale; - /// Convert throwing to null-return if the file does not exist. + /// Convert throwing to null-return if the file does not exist. private static ImcEntry? GetDefault(MetaFileManager metaFileManager, ImcManipulation imc) { try @@ -370,7 +381,8 @@ public partial class ModEditWindow if (_new.ObjectType is ObjectType.Equipment) { if (Combos.EqpEquipSlot("##imcSlot", 100, _new.EquipSlot, out var slot)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, _new.Entry) + _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, + _new.Entry) .Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); @@ -379,7 +391,8 @@ public partial class ModEditWindow else if (_new.ObjectType is ObjectType.Accessory) { if (Combos.AccessorySlot("##imcSlot", _new.EquipSlot, out var slot)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, _new.Entry) + _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, + _new.Entry) .Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); @@ -388,7 +401,8 @@ public partial class ModEditWindow else { if (IdInput("##imcId2", 100 * UiHelpers.Scale, _new.SecondaryId.Id, out var setId2, 0, ushort.MaxValue, false)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, setId2, _new.Variant.Id, _new.EquipSlot, _new.Entry) + _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, setId2, _new.Variant.Id, _new.EquipSlot, + _new.Entry) .Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); @@ -405,7 +419,8 @@ public partial class ModEditWindow if (_new.ObjectType is ObjectType.DemiHuman) { if (Combos.EqpEquipSlot("##imcSlot", 70, _new.EquipSlot, out var slot)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, _new.Entry) + _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, + _new.Entry) .Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); @@ -787,7 +802,8 @@ public partial class ModEditWindow using var color = ImRaii.PushColor(ImGuiCol.FrameBg, def < value ? ColorId.IncreasedMetaValue.Value() : ColorId.DecreasedMetaValue.Value(), def != value); - if (ImGui.DragFloat("##rspValue", ref value, 0.001f, RspManipulation.MinValue, RspManipulation.MaxValue) && value is >= RspManipulation.MinValue and <= RspManipulation.MaxValue) + if (ImGui.DragFloat("##rspValue", ref value, 0.001f, RspManipulation.MinValue, RspManipulation.MaxValue) + && value is >= RspManipulation.MinValue and <= RspManipulation.MaxValue) editor.MetaEditor.Change(meta.Copy(value)); ImGuiUtil.HoverTooltip($"Default Value: {def:0.###}"); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index c90eb2b4..5d74dc33 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -9,125 +9,108 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private readonly FileEditor< MdlFile > _modelTab; + private readonly FileEditor _modelTab; - private static bool DrawModelPanel( MdlFile file, bool disabled ) + private static bool DrawModelPanel(MdlFile file, bool disabled) { var ret = false; - for( var i = 0; i < file.Materials.Length; ++i ) + for (var i = 0; i < file.Materials.Length; ++i) { - using var id = ImRaii.PushId( i ); - var tmp = file.Materials[ i ]; - if( ImGui.InputText( string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None ) - && tmp.Length > 0 - && tmp != file.Materials[ i ] ) + using var id = ImRaii.PushId(i); + var tmp = file.Materials[i]; + if (ImGui.InputText(string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, + disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) + && tmp.Length > 0 + && tmp != file.Materials[i]) { - file.Materials[ i ] = tmp; - ret = true; + file.Materials[i] = tmp; + ret = true; } } - ret |= DrawOtherModelDetails( file, disabled ); + ret |= DrawOtherModelDetails(file, disabled); return !disabled && ret; } - private static bool DrawOtherModelDetails( MdlFile file, bool _ ) + private static bool DrawOtherModelDetails(MdlFile file, bool _) { - if( !ImGui.CollapsingHeader( "Further Content" ) ) - { + if (!ImGui.CollapsingHeader("Further Content")) return false; - } - using( var table = ImRaii.Table( "##data", 2, ImGuiTableFlags.SizingFixedFit ) ) + using (var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit)) { - if( table ) + if (table) { - ImGuiUtil.DrawTableColumn( "Version" ); - ImGuiUtil.DrawTableColumn( file.Version.ToString() ); - ImGuiUtil.DrawTableColumn( "Radius" ); - ImGuiUtil.DrawTableColumn( file.Radius.ToString( CultureInfo.InvariantCulture ) ); - ImGuiUtil.DrawTableColumn( "Model Clip Out Distance" ); - ImGuiUtil.DrawTableColumn( file.ModelClipOutDistance.ToString( CultureInfo.InvariantCulture ) ); - ImGuiUtil.DrawTableColumn( "Shadow Clip Out Distance" ); - ImGuiUtil.DrawTableColumn( file.ShadowClipOutDistance.ToString( CultureInfo.InvariantCulture ) ); - ImGuiUtil.DrawTableColumn( "LOD Count" ); - ImGuiUtil.DrawTableColumn( file.LodCount.ToString() ); - ImGuiUtil.DrawTableColumn( "Enable Index Buffer Streaming" ); - ImGuiUtil.DrawTableColumn( file.EnableIndexBufferStreaming.ToString() ); - ImGuiUtil.DrawTableColumn( "Enable Edge Geometry" ); - ImGuiUtil.DrawTableColumn( file.EnableEdgeGeometry.ToString() ); - ImGuiUtil.DrawTableColumn( "Flags 1" ); - ImGuiUtil.DrawTableColumn( file.Flags1.ToString() ); - ImGuiUtil.DrawTableColumn( "Flags 2" ); - ImGuiUtil.DrawTableColumn( file.Flags2.ToString() ); - ImGuiUtil.DrawTableColumn( "Vertex Declarations" ); - ImGuiUtil.DrawTableColumn( file.VertexDeclarations.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Bone Bounding Boxes" ); - ImGuiUtil.DrawTableColumn( file.BoneBoundingBoxes.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Bone Tables" ); - ImGuiUtil.DrawTableColumn( file.BoneTables.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Element IDs" ); - ImGuiUtil.DrawTableColumn( file.ElementIds.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Extra LoDs" ); - ImGuiUtil.DrawTableColumn( file.ExtraLods.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Meshes" ); - ImGuiUtil.DrawTableColumn( file.Meshes.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Shape Meshes" ); - ImGuiUtil.DrawTableColumn( file.ShapeMeshes.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "LoDs" ); - ImGuiUtil.DrawTableColumn( file.Lods.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Vertex Declarations" ); - ImGuiUtil.DrawTableColumn( file.VertexDeclarations.Length.ToString() ); - ImGuiUtil.DrawTableColumn( "Stack Size" ); - ImGuiUtil.DrawTableColumn( file.StackSize.ToString() ); + ImGuiUtil.DrawTableColumn("Version"); + ImGuiUtil.DrawTableColumn(file.Version.ToString()); + ImGuiUtil.DrawTableColumn("Radius"); + ImGuiUtil.DrawTableColumn(file.Radius.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn("Model Clip Out Distance"); + ImGuiUtil.DrawTableColumn(file.ModelClipOutDistance.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn("Shadow Clip Out Distance"); + ImGuiUtil.DrawTableColumn(file.ShadowClipOutDistance.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn("LOD Count"); + ImGuiUtil.DrawTableColumn(file.LodCount.ToString()); + ImGuiUtil.DrawTableColumn("Enable Index Buffer Streaming"); + ImGuiUtil.DrawTableColumn(file.EnableIndexBufferStreaming.ToString()); + ImGuiUtil.DrawTableColumn("Enable Edge Geometry"); + ImGuiUtil.DrawTableColumn(file.EnableEdgeGeometry.ToString()); + ImGuiUtil.DrawTableColumn("Flags 1"); + ImGuiUtil.DrawTableColumn(file.Flags1.ToString()); + ImGuiUtil.DrawTableColumn("Flags 2"); + ImGuiUtil.DrawTableColumn(file.Flags2.ToString()); + ImGuiUtil.DrawTableColumn("Vertex Declarations"); + ImGuiUtil.DrawTableColumn(file.VertexDeclarations.Length.ToString()); + ImGuiUtil.DrawTableColumn("Bone Bounding Boxes"); + ImGuiUtil.DrawTableColumn(file.BoneBoundingBoxes.Length.ToString()); + ImGuiUtil.DrawTableColumn("Bone Tables"); + ImGuiUtil.DrawTableColumn(file.BoneTables.Length.ToString()); + ImGuiUtil.DrawTableColumn("Element IDs"); + ImGuiUtil.DrawTableColumn(file.ElementIds.Length.ToString()); + ImGuiUtil.DrawTableColumn("Extra LoDs"); + ImGuiUtil.DrawTableColumn(file.ExtraLods.Length.ToString()); + ImGuiUtil.DrawTableColumn("Meshes"); + ImGuiUtil.DrawTableColumn(file.Meshes.Length.ToString()); + ImGuiUtil.DrawTableColumn("Shape Meshes"); + ImGuiUtil.DrawTableColumn(file.ShapeMeshes.Length.ToString()); + ImGuiUtil.DrawTableColumn("LoDs"); + ImGuiUtil.DrawTableColumn(file.Lods.Length.ToString()); + ImGuiUtil.DrawTableColumn("Vertex Declarations"); + ImGuiUtil.DrawTableColumn(file.VertexDeclarations.Length.ToString()); + ImGuiUtil.DrawTableColumn("Stack Size"); + ImGuiUtil.DrawTableColumn(file.StackSize.ToString()); } } - using( var attributes = ImRaii.TreeNode( "Attributes", ImGuiTreeNodeFlags.DefaultOpen ) ) + using (var attributes = ImRaii.TreeNode("Attributes", ImGuiTreeNodeFlags.DefaultOpen)) { - if( attributes ) - { - foreach( var attribute in file.Attributes ) - { - ImRaii.TreeNode( attribute, ImGuiTreeNodeFlags.Leaf ).Dispose(); - } - } + if (attributes) + foreach (var attribute in file.Attributes) + ImRaii.TreeNode(attribute, ImGuiTreeNodeFlags.Leaf).Dispose(); } - using( var bones = ImRaii.TreeNode( "Bones", ImGuiTreeNodeFlags.DefaultOpen ) ) + using (var bones = ImRaii.TreeNode("Bones", ImGuiTreeNodeFlags.DefaultOpen)) { - if( bones ) - { - foreach( var bone in file.Bones ) - { - ImRaii.TreeNode( bone, ImGuiTreeNodeFlags.Leaf ).Dispose(); - } - } + if (bones) + foreach (var bone in file.Bones) + ImRaii.TreeNode(bone, ImGuiTreeNodeFlags.Leaf).Dispose(); } - using( var shapes = ImRaii.TreeNode( "Shapes", ImGuiTreeNodeFlags.DefaultOpen ) ) + using (var shapes = ImRaii.TreeNode("Shapes", ImGuiTreeNodeFlags.DefaultOpen)) { - if( shapes ) - { - foreach( var shape in file.Shapes ) - { - ImRaii.TreeNode( shape.ShapeName, ImGuiTreeNodeFlags.Leaf ).Dispose(); - } - } + if (shapes) + foreach (var shape in file.Shapes) + ImRaii.TreeNode(shape.ShapeName, ImGuiTreeNodeFlags.Leaf).Dispose(); } - if( file.RemainingData.Length > 0 ) + if (file.RemainingData.Length > 0) { - using var t = ImRaii.TreeNode( $"Additional Data (Size: {file.RemainingData.Length})###AdditionalData" ); - if( t ) - { - ImGuiUtil.TextWrapped( string.Join( ' ', file.RemainingData.Select( c => $"{c:X2}" ) ) ); - } + using var t = ImRaii.TreeNode($"Additional Data (Size: {file.RemainingData.Length})###AdditionalData"); + if (t) + ImGuiUtil.TextWrapped(string.Join(' ', file.RemainingData.Select(c => $"{c:X2}"))); } return false; } - -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 43a1990e..2f64f82a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -7,6 +7,7 @@ using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; using Penumbra.Mods; using Penumbra.Mods.Editor; +using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index fb2b5128..e475f47f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -489,16 +489,22 @@ public partial class ModEditWindow continue; foreach (var (key, keyIdx) in node.SystemKeys.WithIndex()) + { ImRaii.TreeNode($"System Key 0x{tab.Shpk.SystemKeys[keyIdx].Id:X8} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } foreach (var (key, keyIdx) in node.SceneKeys.WithIndex()) + { ImRaii.TreeNode($"Scene Key 0x{tab.Shpk.SceneKeys[keyIdx].Id:X8} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } foreach (var (key, keyIdx) in node.MaterialKeys.WithIndex()) + { ImRaii.TreeNode($"Material Key 0x{tab.Shpk.MaterialKeys[keyIdx].Id:X8} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } foreach (var (key, keyIdx) in node.SubViewKeys.WithIndex()) ImRaii.TreeNode($"Sub-View Key #{keyIdx} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); @@ -530,8 +536,10 @@ public partial class ModEditWindow { using var font = ImRaii.PushFont(UiBuilder.MonoFont); foreach (var selector in tab.Shpk.NodeSelectors) + { ImRaii.TreeNode($"#{selector.Value:D4}: Selector: 0x{selector.Key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) .Dispose(); + } } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index 58e2e0c1..7f14165c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -34,7 +34,7 @@ public partial class ModEditWindow Shpk = new ShpkFile(bytes, false); } - Header = $"Shader Package for DirectX {(int)Shpk.DirectXVersion}"; + Header = $"Shader Package for DirectX {(int)Shpk.DirectXVersion}"; Extension = Shpk.DirectXVersion switch { ShpkFile.DxVersion.DirectX9 => ".cso", diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 20aea21e..1ee0a128 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -193,17 +193,18 @@ public partial class ModEditWindow private void OpenSaveAsDialog(string defaultExtension) { var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); - _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, defaultExtension, (a, b) => - { - if (a) + _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, defaultExtension, + (a, b) => { - _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); - if (b == _left.Path) - AddReloadTask(_left.Path, false); - else if (b == _right.Path) - AddReloadTask(_right.Path, true); - } - }, _mod!.ModPath.FullName, _forceTextureStartPath); + if (a) + { + _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + if (b == _left.Path) + AddReloadTask(_left.Path, false); + else if (b == _right.Path) + AddReloadTask(_right.Path, true); + } + }, _mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 703329e6..745b412b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -6,7 +6,6 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; -using OtterGui.Compression; using OtterGui.Raii; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -19,6 +18,7 @@ using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index 75f75de0..60247d81 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -2,9 +2,9 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index f435cb98..5f09e584 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -10,20 +10,20 @@ namespace Penumbra.UI.AdvancedWindow; public class ResourceTreeViewer { private readonly Configuration _config; - private readonly ResourceTreeFactory _treeFactory; + private readonly ResourceTreeFactory _treeFactory; private readonly ChangedItemDrawer _changedItemDrawer; private readonly int _actionCapacity; private readonly Action _onRefresh; private readonly Action _drawActions; private readonly HashSet _unfolded; - private Task? _task; + private Task? _task; - public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, + public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, int actionCapacity, Action onRefresh, Action drawActions) { _config = config; - _treeFactory = treeFactory; + _treeFactory = treeFactory; _changedItemDrawer = changedItemDrawer; _actionCapacity = actionCapacity; _onRefresh = onRefresh; @@ -87,7 +87,7 @@ public class ResourceTreeViewer private Task RefreshCharacterList() => Task.Run(() => - { + { try { return _treeFactory.FromObjectTable(); @@ -107,38 +107,39 @@ public class ResourceTreeViewer foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { if (resourceNode.Internal && !debugMode) - continue; - - var textColor = ImGui.GetColorU32(ImGuiCol.Text); - var textColorInternal = (textColor & 0x00FFFFFFu) | ((textColor & 0xFE000000u) >> 1); // Half opacity - - using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, textColorInternal, resourceNode.Internal); - + continue; + + var textColor = ImGui.GetColorU32(ImGuiCol.Text); + var textColorInternal = (textColor & 0x00FFFFFFu) | ((textColor & 0xFE000000u) >> 1); // Half opacity + + using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, textColorInternal, resourceNode.Internal); + var nodePathHash = unchecked(pathHash + resourceNode.ResourceHandle); using var id = ImRaii.PushId(index); ImGui.TableNextColumn(); var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) - { - var unfoldable = debugMode - ? resourceNode.Children.Count > 0 - : resourceNode.Children.Any(child => !child.Internal); - if (unfoldable) - { - using var font = ImRaii.PushFont(UiBuilder.IconFont); - var icon = (unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(); - var offset = (ImGui.GetFrameHeight() - ImGui.CalcTextSize(icon).X) / 2; - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + offset); - ImGui.TextUnformatted(icon); - ImGui.SameLine(0f, offset + ImGui.GetStyle().ItemInnerSpacing.X); - } - else - { - ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); - ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); - } - _changedItemDrawer.DrawCategoryIcon(resourceNode.Icon); + { + var unfoldable = debugMode + ? resourceNode.Children.Count > 0 + : resourceNode.Children.Any(child => !child.Internal); + if (unfoldable) + { + using var font = ImRaii.PushFont(UiBuilder.IconFont); + var icon = (unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(); + var offset = (ImGui.GetFrameHeight() - ImGui.CalcTextSize(icon).X) / 2; + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + offset); + ImGui.TextUnformatted(icon); + ImGui.SameLine(0f, offset + ImGui.GetStyle().ItemInnerSpacing.X); + } + else + { + ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); + ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); + } + + _changedItemDrawer.DrawCategoryIcon(resourceNode.Icon); ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); ImGui.TableHeader(resourceNode.Name); if (ImGui.IsItemClicked() && unfoldable) @@ -150,11 +151,11 @@ public class ResourceTreeViewer unfolded = !unfolded; } - if (debugMode) - { + if (debugMode) + { using var _ = ImRaii.PushFont(UiBuilder.MonoFont); ImGuiUtil.HoverTooltip( - $"Resource Type: {resourceNode.Type}\nObject Address: 0x{resourceNode.ObjectAddress:X16}\nResource Handle: 0x{resourceNode.ResourceHandle:X16}\nLength: 0x{resourceNode.Length:X16}"); + $"Resource Type: {resourceNode.Type}\nObject Address: 0x{resourceNode.ObjectAddress:X16}\nResource Handle: 0x{resourceNode.ResourceHandle:X16}\nLength: 0x{resourceNode.Length:X16}"); } } @@ -187,8 +188,8 @@ public class ResourceTreeViewer ImGui.Selectable("(unavailable)", false, ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); ImGuiUtil.HoverTooltip("The actual path to this file is unavailable.\nIt may be managed by another plug-in."); - } - + } + mutedColor.Dispose(); if (_actionCapacity > 0) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index d7845ab7..ed62bf83 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -4,7 +4,7 @@ namespace Penumbra.UI; public class PenumbraChangelog { - public const int LastChangelogVersion = 0; + public const int LastChangelogVersion = 0; private readonly Configuration _config; public readonly Changelog Changelog; @@ -41,19 +41,23 @@ public class PenumbraChangelog Add7_1_2(Changelog); Add7_2_0(Changelog); Add7_3_0(Changelog); - } - + } + #region Changelogs private static void Add7_3_0(Changelog log) => log.NextVersion("Version 0.7.3.0") - .RegisterEntry("Added the ability to drag and drop mod files from external sources (like a file explorer or browser) into Penumbras mod selector to import them.") + .RegisterEntry( + "Added the ability to drag and drop mod files from external sources (like a file explorer or browser) into Penumbras mod selector to import them.") .RegisterEntry("You can also drag and drop texture files into the textures tab of the Advanced Editing Window.", 1) - .RegisterEntry("Added a priority display to the mod selector using the currently selected collections priorities. This can be hidden in settings.") + .RegisterEntry( + "Added a priority display to the mod selector using the currently selected collections priorities. This can be hidden in settings.") .RegisterEntry("Added IPC for texture conversion, improved texture handling backend and threading.") - .RegisterEntry("Added Dalamud Substitution so that other plugins can more easily use replaced icons from Penumbras Interface collection when using Dalamuds new Texture Provider.") + .RegisterEntry( + "Added Dalamud Substitution so that other plugins can more easily use replaced icons from Penumbras Interface collection when using Dalamuds new Texture Provider.") .RegisterEntry("Added a filter to texture selection combos in the textures tab of the Advanced Editing Window.") - .RegisterEntry("Changed behaviour when failing to load group JSON files for mods - the pre-existing but failing files are now backed up before being deleted or overwritten.") + .RegisterEntry( + "Changed behaviour when failing to load group JSON files for mods - the pre-existing but failing files are now backed up before being deleted or overwritten.") .RegisterEntry("Further backend changes, mostly relating to the Glamourer rework.") .RegisterEntry("Fixed an issue with modded decals not loading correctly when used with the Glamourer rework.") .RegisterEntry("Fixed missing scaling with UI Scale for some combos.") @@ -66,49 +70,67 @@ public class PenumbraChangelog private static void Add7_2_0(Changelog log) => log.NextVersion("Version 0.7.2.0") - .RegisterEntry("Added Changed Item Categories and icons that can filter for specific types of Changed Items, in the Changed Items Tab as well as in the Changed Items panel for specific mods..") - .RegisterEntry("Icons at the top can be clicked to filter, as well as right-clicked to open a context menu with the option to inverse-filter for them", 1) + .RegisterEntry( + "Added Changed Item Categories and icons that can filter for specific types of Changed Items, in the Changed Items Tab as well as in the Changed Items panel for specific mods..") + .RegisterEntry( + "Icons at the top can be clicked to filter, as well as right-clicked to open a context menu with the option to inverse-filter for them", + 1) .RegisterEntry("There is also an ALL button that can be toggled.", 1) - .RegisterEntry("Modded files in the Font category now resolve from the Interface assignment instead of the base assignment, despite not technically being in the UI category.") - .RegisterEntry("Timeline files will no longer be associated with specific characters in cutscenes, since there is no way to correctly do this, and it could cause crashes if IVCS-requiring animations were used on characters without IVCS.") + .RegisterEntry( + "Modded files in the Font category now resolve from the Interface assignment instead of the base assignment, despite not technically being in the UI category.") + .RegisterEntry( + "Timeline files will no longer be associated with specific characters in cutscenes, since there is no way to correctly do this, and it could cause crashes if IVCS-requiring animations were used on characters without IVCS.") .RegisterEntry("File deletion in the Advanced Editing Window now also checks for your configured deletion key combo.") - .RegisterEntry("The Texture tab in the Advanced Editing Window now has some quick convert buttons to just convert the selected texture to a different format in-place.") - .RegisterEntry("These buttons only appear if only one texture is selected on the left side, it is not otherwise manipulated, and the texture is a .tex file.", 1) + .RegisterEntry( + "The Texture tab in the Advanced Editing Window now has some quick convert buttons to just convert the selected texture to a different format in-place.") + .RegisterEntry( + "These buttons only appear if only one texture is selected on the left side, it is not otherwise manipulated, and the texture is a .tex file.", + 1) .RegisterEntry("The text part of the mod filter in the mod selector now also resets when right-clicking the drop-down arrow.") .RegisterEntry("The Dissolve Folder option in the mod selector context menu has been moved to the bottom.") .RegisterEntry("Somewhat improved IMC handling to prevent some issues.") - .RegisterEntry("Improved the handling of mod renames on mods with default-search names to correctly rename their search-name in (hopefully) all cases too.") + .RegisterEntry( + "Improved the handling of mod renames on mods with default-search names to correctly rename their search-name in (hopefully) all cases too.") .RegisterEntry("A lot of backend improvements and changes related to the pending Glamourer rework.") .RegisterEntry("Fixed an issue where the displayed active collection count in the support info was wrong.") - .RegisterEntry("Fixed an issue with created directories dealing badly with non-standard whitespace characters like half-width or non-breaking spaces.") + .RegisterEntry( + "Fixed an issue with created directories dealing badly with non-standard whitespace characters like half-width or non-breaking spaces.") .RegisterEntry("Fixed an issue with unknown animation and vfx edits not being recognized correctly.") .RegisterEntry("Fixed an issue where changing option descriptions to be empty was not working correctly.") .RegisterEntry("Fixed an issue with texture names in the resource tree of the On-Screen views.") .RegisterEntry("Fixed a bug where the game would crash when drawing folders in the mod selector that contained a '%' symbol.") .RegisterEntry("Fixed an issue with parallel algorithms obtaining the wrong number of available cores.") .RegisterEntry("Updated the available selection of Battle NPC names.") - .RegisterEntry("A typo in the 0.7.1.2 Changlog has been fixed.") - .RegisterEntry("Added the Sea of Stars as accepted repository. (0.7.1.4)") - .RegisterEntry("Fixed an issue with collections sometimes not loading correctly, and IMC files not applying correctly. (0.7.1.3)"); - - + .RegisterEntry("A typo in the 0.7.1.2 Changlog has been fixed.") + .RegisterEntry("Added the Sea of Stars as accepted repository. (0.7.1.4)") + .RegisterEntry("Fixed an issue with collections sometimes not loading correctly, and IMC files not applying correctly. (0.7.1.3)"); + + private static void Add7_1_2(Changelog log) => log.NextVersion("Version 0.7.1.2") - .RegisterEntry("Changed threaded handling of collection caches. Maybe this fixes the startup problems some people are experiencing.") - .RegisterEntry("This is just testing and may not be the solution, or may even make things worse. Sorry if I have to put out multiple small patches again to get this right.", 1) + .RegisterEntry( + "Changed threaded handling of collection caches. Maybe this fixes the startup problems some people are experiencing.") + .RegisterEntry( + "This is just testing and may not be the solution, or may even make things worse. Sorry if I have to put out multiple small patches again to get this right.", + 1) .RegisterEntry("Fixed Penumbra failing to load if the main configuration file is corrupted.") .RegisterEntry("Some miscellaneous small bug fixes.") .RegisterEntry("Slight changes in behaviour for deduplicator/normalizer, mostly backend.") .RegisterEntry("A typo in the 0.7.1.0 Changelog has been fixed.") .RegisterEntry("Fixed left rings not being valid for IMC entries after validation. (7.1.1)") - .RegisterEntry("Relaxed the scaling restrictions for RSP scaling values to go from 0.01 to 512.0 instead of the prior upper limit of 8.0, in interface as well as validation, to better support the fetish community. (7.1.1)"); + .RegisterEntry( + "Relaxed the scaling restrictions for RSP scaling values to go from 0.01 to 512.0 instead of the prior upper limit of 8.0, in interface as well as validation, to better support the fetish community. (7.1.1)"); private static void Add7_1_0(Changelog log) => log.NextVersion("Version 0.7.1.0") .RegisterEntry("Updated for patch 6.4 - there may be some oversights on edge cases, but I could not find any issues myself.") - .RegisterHighlight("This update changed some Dragoon skills that were moving the player character before to not do that anymore. If you have any mods that applied to those skills, please make sure that they do not contain any redirections for .tmb files. If skills that should no longer move your character still do that for some reason, this is detectable by the server.", 1) - .RegisterEntry("Added a Mod Merging tab in the Advanced Editing Window. This can help you merge multiple mods to one, or split off specific options from an existing mod into a new mod.") - .RegisterEntry("Added advanced options to configure the minimum allowed window size for the main window (to reduce it). This is not quite supported and may look bad, so only use it if you really need smaller windows.") + .RegisterHighlight( + "This update changed some Dragoon skills that were moving the player character before to not do that anymore. If you have any mods that applied to those skills, please make sure that they do not contain any redirections for .tmb files. If skills that should no longer move your character still do that for some reason, this is detectable by the server.", + 1) + .RegisterEntry( + "Added a Mod Merging tab in the Advanced Editing Window. This can help you merge multiple mods to one, or split off specific options from an existing mod into a new mod.") + .RegisterEntry( + "Added advanced options to configure the minimum allowed window size for the main window (to reduce it). This is not quite supported and may look bad, so only use it if you really need smaller windows.") .RegisterEntry("The last tab selected in the main window is now saved and re-used when relaunching Penumbra.") .RegisterEntry("Added a hook to correctly associate some sounds that are played while weapons are drawn.") .RegisterEntry("Added a hook to correctly associate sounds that are played while dismounting.") @@ -125,7 +147,8 @@ public class PenumbraChangelog .RegisterEntry("Fixed an issue with the file selectors not always opening at the expected locations. (0.7.0.7)") .RegisterEntry("Fixed some cache handling issues. (0.7.0.5 - 0.7.0.10)") .RegisterEntry("Fixed an issue with multiple collection context menus appearing for some identifiers (0.7.0.5)") - .RegisterEntry("Fixed an issue where the Update Bibo button did only work if the Advanced Editing window was opened before. (0.7.0.5)"); + .RegisterEntry( + "Fixed an issue where the Update Bibo button did only work if the Advanced Editing window was opened before. (0.7.0.5)"); private static void Add7_0_4(Changelog log) => log.NextVersion("Version 0.7.0.4") @@ -136,7 +159,7 @@ public class PenumbraChangelog .RegisterEntry("Reverted trimming of whitespace for relative paths to only trim the end, not the start. (0.7.0.3)") .RegisterEntry("Fixed a bug that caused an integer overflow on textures of high dimensions. (0.7.0.3)") .RegisterEntry("Fixed a bug that caused Penumbra to enter invalid state when deleting mods. (0.7.0.2)") - .RegisterEntry("Added Notification on invalid collection names. (0.7.0.2)"); + .RegisterEntry("Added Notification on invalid collection names. (0.7.0.2)"); private static void Add7_0_1(Changelog log) => log.NextVersion("Version 0.7.0.1") @@ -145,26 +168,36 @@ public class PenumbraChangelog .RegisterEntry("Fixed a bug that showed the Your Character collection as redundant even if it was not.") .RegisterEntry("Fixed a bug that caused some required collection caches to not be built on startup and thus mods not to apply.") .RegisterEntry("Fixed a bug that showed the current collection as unused even if it was used."); + private static void Add7_0_0(Changelog log) => log.NextVersion("Version 0.7.0.0") - .RegisterHighlight("The entire backend was reworked (this is still in progress). While this does not come with a lot of functionality changes, basically every file and functionality was touched.") - .RegisterEntry("This may have (re-)introduced some bugs that have not yet been noticed despite a long testing period - there are not many users of the testing branch.", 1) + .RegisterHighlight( + "The entire backend was reworked (this is still in progress). While this does not come with a lot of functionality changes, basically every file and functionality was touched.") + .RegisterEntry( + "This may have (re-)introduced some bugs that have not yet been noticed despite a long testing period - there are not many users of the testing branch.", + 1) .RegisterEntry("If you encounter any - but especially breaking or lossy - bugs, please report them immediately.", 1) - .RegisterEntry("This also fixed or improved numerous bugs and issues that will not be listed here.", 1) - .RegisterEntry("GitHub currently reports 321 changed files with 34541 additions and 28464 deletions.", 1) + .RegisterEntry("This also fixed or improved numerous bugs and issues that will not be listed here.", 1) + .RegisterEntry("GitHub currently reports 321 changed files with 34541 additions and 28464 deletions.", 1) .RegisterEntry("Added Notifications on many failures that previously only wrote to log.") .RegisterEntry("Reworked the Collections Tab to hopefully be much more intuitive. It should be self-explanatory now.") .RegisterEntry("The tutorial was adapted to the new window, if you are unsure, maybe try restarting it.", 1) - .RegisterEntry("You can now toggle an incognito mode in the collection window so it shows shortened names of collections and players.", 1) - .RegisterEntry("You can get an overview about the current usage of a selected collection and its active and unused mod settings in the Collection Details panel.", 1) + .RegisterEntry( + "You can now toggle an incognito mode in the collection window so it shows shortened names of collections and players.", 1) + .RegisterEntry( + "You can get an overview about the current usage of a selected collection and its active and unused mod settings in the Collection Details panel.", + 1) .RegisterEntry("The currently selected collection is now highlighted in green (default, configurable) in multiple places.", 1) - .RegisterEntry("Mods now have a 'Collections' panel in the Mod Panel containing an overview about usage of the mod in all collections.") + .RegisterEntry( + "Mods now have a 'Collections' panel in the Mod Panel containing an overview about usage of the mod in all collections.") .RegisterEntry("The 'Changed Items' and 'Effective Changes' tab now contain a collection selector.") .RegisterEntry("Added the On-Screen tab to find what files a specific character is actually using (by Ny).") .RegisterEntry("Added 3 Quick Move folders in the mod selector that can be setup in context menus for easier cleanup.") - .RegisterEntry("Added handling for certain animation files for mounts and fashion accessories to correctly associate them to players.") + .RegisterEntry( + "Added handling for certain animation files for mounts and fashion accessories to correctly associate them to players.") .RegisterEntry("The file selectors in the Advanced Mod Editing Window now use filterable combos.") - .RegisterEntry("The Advanced Mod Editing Window now shows the number of meta edits and file swaps in unselected options and highlights the option selector.") + .RegisterEntry( + "The Advanced Mod Editing Window now shows the number of meta edits and file swaps in unselected options and highlights the option selector.") .RegisterEntry("Added API/IPC to start unpacking and installing mods from external tools (by Sebastina).") .RegisterEntry("Hidden files and folders are now ignored for unused files in Advanced Mod Editing (by myr)") .RegisterEntry("Paths in mods are now automatically trimmed of whitespace on loading.") @@ -173,13 +206,13 @@ public class PenumbraChangelog .RegisterEntry("Fixed some issues with tutorial windows.") .RegisterEntry("Fixed some bugs in the Resource Logger.") .RegisterEntry("Fixed Button Sizing for collapsible groups and several related bugs.") - .RegisterEntry("Fixed issue with mods with default settings other than 0.") - .RegisterEntry("Fixed issue with commands not registering on startup. (0.6.6.5)") - .RegisterEntry("Improved Startup Times and Time Tracking. (0.6.6.4)") - .RegisterEntry("Add Item Swapping between different types of Accessories and Hats. (0.6.6.4)") - .RegisterEntry("Fixed bugs with assignment of temporary collections and their deletion. (0.6.6.4)") - .RegisterEntry("Fixed bugs with new file loading mechanism. (0.6.6.2, 0.6.6.3)") - .RegisterEntry("Added API/IPC to open and close the main window and select specific tabs and mods. (0.6.6.2)"); + .RegisterEntry("Fixed issue with mods with default settings other than 0.") + .RegisterEntry("Fixed issue with commands not registering on startup. (0.6.6.5)") + .RegisterEntry("Improved Startup Times and Time Tracking. (0.6.6.4)") + .RegisterEntry("Add Item Swapping between different types of Accessories and Hats. (0.6.6.4)") + .RegisterEntry("Fixed bugs with assignment of temporary collections and their deletion. (0.6.6.4)") + .RegisterEntry("Fixed bugs with new file loading mechanism. (0.6.6.2, 0.6.6.3)") + .RegisterEntry("Added API/IPC to open and close the main window and select specific tabs and mods. (0.6.6.2)"); private static void Add6_6_1(Changelog log) => log.NextVersion("Version 0.6.6.1") diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index eb4dec4c..ebcff821 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -17,12 +17,12 @@ public enum ColorId FolderLine, ItemId, IncreasedMetaValue, - DecreasedMetaValue, - SelectedCollection, - RedundantAssignment, - NoModsAssignment, - NoAssignment, - SelectorPriority, + DecreasedMetaValue, + SelectedCollection, + RedundantAssignment, + NoModsAssignment, + NoAssignment, + SelectorPriority, InGameHighlight, } @@ -38,7 +38,7 @@ public static class Colors public const uint TutorialBorder = 0xD00000FF; public const uint ReniColorButton = CustomGui.ReniColorButton; public const uint ReniColorHovered = CustomGui.ReniColorHovered; - public const uint ReniColorActive = CustomGui.ReniColorActive ; + public const uint ReniColorActive = CustomGui.ReniColorActive; public static (uint DefaultColor, string Name, string Description) Data(this ColorId color) => color switch @@ -69,12 +69,12 @@ public static class Colors }; private static IReadOnlyDictionary _colors = new Dictionary(); - - /// Obtain the configured value for a color. + + /// Obtain the configured value for a color. public static uint Value(this ColorId color) => _colors.TryGetValue(color, out var value) ? value : color.Data().DefaultColor; - - /// Set the configurable colors dictionary to a value. + + /// Set the configurable colors dictionary to a value. public static void SetColors(Configuration config) => _colors = config.Colors; } diff --git a/Penumbra/UI/Classes/Combos.cs b/Penumbra/UI/Classes/Combos.cs index 26f747b7..2cba7cf5 100644 --- a/Penumbra/UI/Classes/Combos.cs +++ b/Penumbra/UI/Classes/Combos.cs @@ -8,38 +8,41 @@ namespace Penumbra.UI.Classes; public static class Combos { // Different combos to use with enums. - public static bool Race( string label, ModelRace current, out ModelRace race ) - => Race( label, 100, current, out race ); + public static bool Race(string label, ModelRace current, out ModelRace race) + => Race(label, 100, current, out race); - public static bool Race( string label, float unscaledWidth, ModelRace current, out ModelRace race ) - => ImGuiUtil.GenericEnumCombo( label, unscaledWidth * UiHelpers.Scale, current, out race, RaceEnumExtensions.ToName, 1 ); + public static bool Race(string label, float unscaledWidth, ModelRace current, out ModelRace race) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out race, RaceEnumExtensions.ToName, 1); - public static bool Gender( string label, Gender current, out Gender gender ) - => Gender( label, 120, current, out gender ); + public static bool Gender(string label, Gender current, out Gender gender) + => Gender(label, 120, current, out gender); - public static bool Gender( string label, float unscaledWidth, Gender current, out Gender gender ) - => ImGuiUtil.GenericEnumCombo( label, unscaledWidth * UiHelpers.Scale, current, out gender, RaceEnumExtensions.ToName, 1 ); + public static bool Gender(string label, float unscaledWidth, Gender current, out Gender gender) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out gender, RaceEnumExtensions.ToName, 1); - public static bool EqdpEquipSlot( string label, EquipSlot current, out EquipSlot slot ) - => ImGuiUtil.GenericEnumCombo( label, 100 * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EqdpSlots, EquipSlotExtensions.ToName ); + public static bool EqdpEquipSlot(string label, EquipSlot current, out EquipSlot slot) + => ImGuiUtil.GenericEnumCombo(label, 100 * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EqdpSlots, + EquipSlotExtensions.ToName); - public static bool EqpEquipSlot( string label, float width, EquipSlot current, out EquipSlot slot ) - => ImGuiUtil.GenericEnumCombo( label, width * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EquipmentSlots, EquipSlotExtensions.ToName ); + public static bool EqpEquipSlot(string label, float width, EquipSlot current, out EquipSlot slot) + => ImGuiUtil.GenericEnumCombo(label, width * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EquipmentSlots, + EquipSlotExtensions.ToName); - public static bool AccessorySlot( string label, EquipSlot current, out EquipSlot slot ) - => ImGuiUtil.GenericEnumCombo( label, 100 * UiHelpers.Scale, current, out slot, EquipSlotExtensions.AccessorySlots, EquipSlotExtensions.ToName ); + public static bool AccessorySlot(string label, EquipSlot current, out EquipSlot slot) + => ImGuiUtil.GenericEnumCombo(label, 100 * UiHelpers.Scale, current, out slot, EquipSlotExtensions.AccessorySlots, + EquipSlotExtensions.ToName); - public static bool SubRace( string label, SubRace current, out SubRace subRace ) - => ImGuiUtil.GenericEnumCombo( label, 150 * UiHelpers.Scale, current, out subRace, RaceEnumExtensions.ToName, 1 ); + public static bool SubRace(string label, SubRace current, out SubRace subRace) + => ImGuiUtil.GenericEnumCombo(label, 150 * UiHelpers.Scale, current, out subRace, RaceEnumExtensions.ToName, 1); - public static bool RspAttribute( string label, RspAttribute current, out RspAttribute attribute ) - => ImGuiUtil.GenericEnumCombo( label, 200 * UiHelpers.Scale, current, out attribute, - RspAttributeExtensions.ToFullString, 0, 1 ); + public static bool RspAttribute(string label, RspAttribute current, out RspAttribute attribute) + => ImGuiUtil.GenericEnumCombo(label, 200 * UiHelpers.Scale, current, out attribute, + RspAttributeExtensions.ToFullString, 0, 1); - public static bool EstSlot( string label, EstManipulation.EstType current, out EstManipulation.EstType attribute ) - => ImGuiUtil.GenericEnumCombo( label, 200 * UiHelpers.Scale, current, out attribute ); + public static bool EstSlot(string label, EstManipulation.EstType current, out EstManipulation.EstType attribute) + => ImGuiUtil.GenericEnumCombo(label, 200 * UiHelpers.Scale, current, out attribute); - public static bool ImcType( string label, ObjectType current, out ObjectType type ) - => ImGuiUtil.GenericEnumCombo( label, 110 * UiHelpers.Scale, current, out type, ObjectTypeExtensions.ValidImcTypes, - ObjectTypeExtensions.ToName ); -} \ No newline at end of file + public static bool ImcType(string label, ObjectType current, out ObjectType type) + => ImGuiUtil.GenericEnumCombo(label, 110 * UiHelpers.Scale, current, out type, ObjectTypeExtensions.ValidImcTypes, + ObjectTypeExtensions.ToName); +} diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index fe248d99..3ebd3252 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -22,7 +22,7 @@ public sealed class CollectionPanel : IDisposable private readonly ActiveCollections _active; private readonly CollectionSelector _selector; private readonly ActorService _actors; - private readonly ITargetManager _targets; + private readonly ITargetManager _targets; private readonly IndividualAssignmentUi _individualAssignmentUi; private readonly InheritanceUi _inheritanceUi; private readonly ModStorage _mods; diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index 4bcff426..88344e6a 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -30,23 +30,24 @@ public class InheritanceUi /// Draw the whole inheritance block. public void Draw() { - using var id = ImRaii.PushId("##Inheritance"); - ImGuiUtil.DrawColoredText(($"The {TutorialService.SelectedCollection} ", 0), (Name(_active.Current), ColorId.SelectedCollection.Value() | 0xFF000000), (" inherits from:", 0)); - ImGui.Dummy(Vector2.One); + using var id = ImRaii.PushId("##Inheritance"); + ImGuiUtil.DrawColoredText(($"The {TutorialService.SelectedCollection} ", 0), + (Name(_active.Current), ColorId.SelectedCollection.Value() | 0xFF000000), (" inherits from:", 0)); + ImGui.Dummy(Vector2.One); - DrawCurrentCollectionInheritance(); + DrawCurrentCollectionInheritance(); ImGui.SameLine(); DrawInheritanceTrashButton(); ImGui.SameLine(); - DrawRightText(); + DrawRightText(); DrawNewInheritanceSelection(); ImGui.SameLine(); if (ImGui.Button("More Information about Inheritance", new Vector2(ImGui.GetContentRegionAvail().X, 0))) - ImGui.OpenPopup("InheritanceHelp"); - + ImGui.OpenPopup("InheritanceHelp"); + DrawHelpPopup(); - DelayedActions(); + DelayedActions(); } // Keep for reuse. @@ -56,44 +57,44 @@ public class InheritanceUi private ModCollection? _newInheritance; private ModCollection? _movedInheritance; private (int, int)? _inheritanceAction; - private ModCollection? _newCurrentCollection; - + private ModCollection? _newCurrentCollection; + private void DrawRightText() { using var group = ImRaii.Group(); ImGuiUtil.TextWrapped( "Inheritance is a way to use a baseline of mods across multiple collections, without needing to change all those collections if you want to add a single mod."); ImGuiUtil.TextWrapped( - "You can select inheritances from the combo below to add them.\nSince the order of inheritances is important, you can reorder them here via drag and drop.\nYou can also delete inheritances by dragging them onto the trash can."); - } - - private void DrawHelpPopup() - => ImGuiUtil.HelpPopup("InheritanceHelp", new Vector2(1000 * UiHelpers.Scale, 20 * ImGui.GetTextLineHeightWithSpacing()), () => - { - ImGui.NewLine(); - ImGui.TextUnformatted("Every mod in a collection can have three basic states: 'Enabled', 'Disabled' and 'Unconfigured'."); - ImGui.BulletText("If the mod is 'Enabled' or 'Disabled', it does not matter if the collection inherits from other collections."); - ImGui.BulletText( - "If the mod is unconfigured, those inherited-from collections are checked in the order displayed here, including sub-inheritances."); - ImGui.BulletText( - "If a collection is found in which the mod is either 'Enabled' or 'Disabled', the settings from this collection will be used."); - ImGui.BulletText("If no such collection is found, the mod will be treated as disabled."); - ImGui.BulletText( - "Highlighted collections in the left box are never reached because they are already checked in a sub-inheritance before."); - ImGui.NewLine(); - ImGui.TextUnformatted("Example"); - ImGui.BulletText("Collection A has the Bibo+ body and a Hempen Camise mod enabled."); - ImGui.BulletText( - "Collection B inherits from A, leaves Bibo+ unconfigured, but has the Hempen Camise enabled with different settings than A."); - ImGui.BulletText("Collection C also inherits from A, has Bibo+ explicitly disabled and the Hempen Camise unconfigured."); - ImGui.BulletText("Collection D inherits from C and then B and leaves everything unconfigured."); - using var indent = ImRaii.PushIndent(); - ImGui.BulletText("B uses Bibo+ settings from A and its own Hempen Camise settings."); - ImGui.BulletText("C has Bibo+ disabled and uses A's Hempen Camise settings."); - ImGui.BulletText( - "D has Bibo+ disabled and uses A's Hempen Camise settings, not B's. It traversed the collections in Order D -> (C -> A) -> (B -> A)."); - }); - + "You can select inheritances from the combo below to add them.\nSince the order of inheritances is important, you can reorder them here via drag and drop.\nYou can also delete inheritances by dragging them onto the trash can."); + } + + private void DrawHelpPopup() + => ImGuiUtil.HelpPopup("InheritanceHelp", new Vector2(1000 * UiHelpers.Scale, 20 * ImGui.GetTextLineHeightWithSpacing()), () => + { + ImGui.NewLine(); + ImGui.TextUnformatted("Every mod in a collection can have three basic states: 'Enabled', 'Disabled' and 'Unconfigured'."); + ImGui.BulletText("If the mod is 'Enabled' or 'Disabled', it does not matter if the collection inherits from other collections."); + ImGui.BulletText( + "If the mod is unconfigured, those inherited-from collections are checked in the order displayed here, including sub-inheritances."); + ImGui.BulletText( + "If a collection is found in which the mod is either 'Enabled' or 'Disabled', the settings from this collection will be used."); + ImGui.BulletText("If no such collection is found, the mod will be treated as disabled."); + ImGui.BulletText( + "Highlighted collections in the left box are never reached because they are already checked in a sub-inheritance before."); + ImGui.NewLine(); + ImGui.TextUnformatted("Example"); + ImGui.BulletText("Collection A has the Bibo+ body and a Hempen Camise mod enabled."); + ImGui.BulletText( + "Collection B inherits from A, leaves Bibo+ unconfigured, but has the Hempen Camise enabled with different settings than A."); + ImGui.BulletText("Collection C also inherits from A, has Bibo+ explicitly disabled and the Hempen Camise unconfigured."); + ImGui.BulletText("Collection D inherits from C and then B and leaves everything unconfigured."); + using var indent = ImRaii.PushIndent(); + ImGui.BulletText("B uses Bibo+ settings from A and its own Hempen Camise settings."); + ImGui.BulletText("C has Bibo+ disabled and uses A's Hempen Camise settings."); + ImGui.BulletText( + "D has Bibo+ disabled and uses A's Hempen Camise settings, not B's. It traversed the collections in Order D -> (C -> A) -> (B -> A)."); + }); + /// /// If an inherited collection is expanded, @@ -122,7 +123,8 @@ public class InheritanceUi _seenInheritedCollections.Contains(inheritance)); _seenInheritedCollections.Add(inheritance); - ImRaii.TreeNode($"{Name(inheritance)}###{inheritance.Name}", ImGuiTreeNodeFlags.NoTreePushOnOpen | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); + ImRaii.TreeNode($"{Name(inheritance)}###{inheritance.Name}", + ImGuiTreeNodeFlags.NoTreePushOnOpen | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); var (minRect, maxRect) = (ImGui.GetItemRectMin(), ImGui.GetItemRectMax()); DrawInheritanceTreeClicks(inheritance, false); diff --git a/Penumbra/UI/FileDialogService.cs b/Penumbra/UI/FileDialogService.cs index dc638ef5..e5b0fa19 100644 --- a/Penumbra/UI/FileDialogService.cs +++ b/Penumbra/UI/FileDialogService.cs @@ -1,5 +1,3 @@ -using System.Collections.Concurrent; -using System.Reflection; using Dalamud.Interface; using Dalamud.Interface.ImGuiFileDialog; using Dalamud.Utility; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 91da4da5..3a7a7343 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -14,6 +14,7 @@ using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.UI.Classes; using ChatService = Penumbra.Services.ChatService; @@ -376,8 +377,10 @@ public sealed class ModFileSystemSelector : FileSystemSelector filter switch { - ModFilter.Enabled => "Enabled", - ModFilter.Disabled => "Disabled", - ModFilter.Favorite => "Favorite", - ModFilter.NotFavorite => "No Favorite", - ModFilter.NoConflict => "No Conflicts", - ModFilter.SolvedConflict => "Solved Conflicts", - ModFilter.UnsolvedConflict => "Unsolved Conflicts", + ModFilter.Enabled => "Enabled", + ModFilter.Disabled => "Disabled", + ModFilter.Favorite => "Favorite", + ModFilter.NotFavorite => "No Favorite", + ModFilter.NoConflict => "No Conflicts", + ModFilter.SolvedConflict => "Solved Conflicts", + ModFilter.UnsolvedConflict => "Unsolved Conflicts", ModFilter.HasNoMetaManipulations => "No Meta Manipulations", - ModFilter.HasMetaManipulations => "Meta Manipulations", - ModFilter.HasNoFileSwaps => "No File Swaps", - ModFilter.HasFileSwaps => "File Swaps", - ModFilter.HasNoConfig => "No Configuration", - ModFilter.HasConfig => "Configuration", - ModFilter.HasNoFiles => "No Files", - ModFilter.HasFiles => "Files", - ModFilter.IsNew => "Newly Imported", - ModFilter.NotNew => "Not Newly Imported", - ModFilter.Inherited => "Inherited Configuration", - ModFilter.Uninherited => "Own Configuration", - ModFilter.Undefined => "Not Configured", - _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), + ModFilter.HasMetaManipulations => "Meta Manipulations", + ModFilter.HasNoFileSwaps => "No File Swaps", + ModFilter.HasFileSwaps => "File Swaps", + ModFilter.HasNoConfig => "No Configuration", + ModFilter.HasConfig => "Configuration", + ModFilter.HasNoFiles => "No Files", + ModFilter.HasFiles => "Files", + ModFilter.IsNew => "Newly Imported", + ModFilter.NotNew => "Not Newly Imported", + ModFilter.Inherited => "Inherited Configuration", + ModFilter.Uninherited => "Own Configuration", + ModFilter.Undefined => "Not Configured", + _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), }; -} \ No newline at end of file +} diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index 1866606a..59c9d279 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -4,6 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.Mods; +using Penumbra.Mods.Manager; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 83f79f56..38737274 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -12,7 +12,7 @@ namespace Penumbra.UI.ModsTab; public class ModPanelConflictsTab : ITab { private readonly ModFileSystemSelector _selector; - private readonly CollectionManager _collectionManager; + private readonly CollectionManager _collectionManager; public ModPanelConflictsTab(CollectionManager collectionManager, ModFileSystemSelector selector) { diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 256be8d6..790bc383 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -3,9 +3,7 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; using OtterGui.Widgets; -using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; @@ -13,7 +11,7 @@ public class ModPanelDescriptionTab : ITab { private readonly ModFileSystemSelector _selector; private readonly TutorialService _tutorial; - private readonly ModManager _modManager; + private readonly ModManager _modManager; private readonly TagButtons _localTags = new(); private readonly TagButtons _modTags = new(); diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index acfdcf28..d63e42ef 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -4,10 +4,8 @@ using OtterGui; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.Mods; using Penumbra.UI.Classes; using Dalamud.Interface.Components; -using Dalamud.Interface; using Penumbra.Collections.Manager; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; @@ -192,7 +190,7 @@ public class ModPanelSettingsTab : ITab _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, (uint)idx2); if (option.Description.Length > 0) - ImGuiUtil.SelectableHelpMarker(option.Description); + ImGuiUtil.SelectableHelpMarker(option.Description); id.Pop(); } diff --git a/Penumbra/UI/ModsTab/ModPanelTabBar.cs b/Penumbra/UI/ModsTab/ModPanelTabBar.cs index 3f1b0f77..02ec9a32 100644 --- a/Penumbra/UI/ModsTab/ModPanelTabBar.cs +++ b/Penumbra/UI/ModsTab/ModPanelTabBar.cs @@ -5,6 +5,7 @@ using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index ec66ae08..dea68955 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -1,10 +1,9 @@ using OtterGui.Classes; using Penumbra.Collections; -using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.String; -namespace Penumbra.UI; +namespace Penumbra.UI.ResourceWatcher; [Flags] public enum RecordType : byte diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index e8031d4e..781c5fc1 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -1,4 +1,3 @@ -using System.Collections.Concurrent; using System.Text.RegularExpressions; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; @@ -15,12 +14,12 @@ using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI.Classes; -namespace Penumbra.UI; +namespace Penumbra.UI.ResourceWatcher; public class ResourceWatcher : IDisposable, ITab { public const int DefaultMaxEntries = 1024; - public const RecordType AllRecords = RecordType.Request | RecordType.ResourceLoad | RecordType.FileLoad | RecordType.Destruction; + public const RecordType AllRecords = RecordType.Request | RecordType.ResourceLoad | RecordType.FileLoad | RecordType.Destruction; private readonly Configuration _config; private readonly ResourceService _resources; @@ -28,7 +27,7 @@ public class ResourceWatcher : IDisposable, ITab private readonly ActorService _actors; private readonly List _records = new(); private readonly ConcurrentQueue _newRecords = new(); - private readonly ResourceWatcherTable _table; + private readonly ResourceWatcherTable _table; private string _logFilter = string.Empty; private Regex? _logRegex; private int _newMaxEntries; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 905307ba..eb034459 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -4,10 +4,9 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Table; -using Penumbra.GameData.Enums; using Penumbra.String; -namespace Penumbra.UI; +namespace Penumbra.UI.ResourceWatcher; internal sealed class ResourceWatcherTable : Table { diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index 4605527a..f7e64125 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -35,9 +35,9 @@ public class ChangedItemsTab : ITab public void DrawContent() { - _collectionHeader.Draw(true); + _collectionHeader.Draw(true); _drawer.DrawTypeFilter(); - var varWidth = DrawFilters(); + var varWidth = DrawFilters(); using var child = ImRaii.Child("##changedItemsChild", -Vector2.One); if (!child) return; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 4d6d2dd6..5b51bd85 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -58,11 +58,12 @@ public class CollectionsTab : IDisposable, ITab public void DrawContent() { - var width = ImGui.CalcTextSize("nnnnnnnnnnnnnnnnnnnnnnnnnn").X; + var width = ImGui.CalcTextSize("nnnnnnnnnnnnnnnnnnnnnnnnnn").X; using (var group = ImRaii.Group()) { _selector.Draw(width); } + _tutorial.OpenTutorial(BasicTutorialSteps.EditingCollections); ImGui.SameLine(); @@ -91,7 +92,7 @@ public class CollectionsTab : IDisposable, ITab color.Pop(); _tutorial.OpenTutorial(BasicTutorialSteps.SimpleAssignments); ImGui.SameLine(); - + color.Push(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.TabActive), Mode is PanelMode.IndividualAssignment); if (ImGui.Button("Individual Assignments", buttonSize)) Mode = PanelMode.IndividualAssignment; @@ -112,7 +113,7 @@ public class CollectionsTab : IDisposable, ITab color.Pop(); _tutorial.OpenTutorial(BasicTutorialSteps.CollectionDetails); ImGui.SameLine(); - + style.Push(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); color.Push(ImGuiCol.Text, ColorId.FolderExpanded.Value()) .Push(ImGuiCol.Border, ColorId.FolderExpanded.Value()); diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index fc0168a0..8dae2caa 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -565,11 +565,12 @@ public class DebugTab : Window, ITab ImGui.InputText("File Name", ref _emoteSearchFile, 256); ImGui.InputText("Emote Name", ref _emoteSearchName, 256); - using var table = Table("##table", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingFixedFit, new Vector2(-1, 12 * ImGui.GetTextLineHeightWithSpacing())); + using var table = Table("##table", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingFixedFit, + new Vector2(-1, 12 * ImGui.GetTextLineHeightWithSpacing())); if (!table) return; - var skips = ImGuiClip.GetNecessarySkips(ImGui.GetTextLineHeightWithSpacing()); + var skips = ImGuiClip.GetNecessarySkips(ImGui.GetTextLineHeightWithSpacing()); var dummy = ImGuiClip.FilteredClippedDraw(_identifier.AwaitedService.Emotes, skips, p => p.Key.Contains(_emoteSearchFile, StringComparison.OrdinalIgnoreCase) && (_emoteSearchName.Length == 0 diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index 3c1d0801..0cc2e5c1 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -30,7 +30,7 @@ public class EffectiveTab : ITab public void DrawContent() { - SetupEffectiveSizes(); + SetupEffectiveSizes(); _collectionHeader.Draw(true); DrawFilters(); using var child = ImRaii.Child("##EffectiveChangesTab", -Vector2.One, false); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 701d1ef6..7c350106 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -703,12 +703,13 @@ public class SettingsTab : ITab if (_compactor.MassCompactRunning) { ImGui.ProgressBar((float)_compactor.CurrentIndex / _compactor.TotalFiles, - new Vector2(ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - UiHelpers.IconButtonSize.X, ImGui.GetFrameHeight()), + new Vector2(ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - UiHelpers.IconButtonSize.X, + ImGui.GetFrameHeight()), _compactor.CurrentFile?.FullName[(_modManager.BasePath.FullName.Length + 1)..] ?? "Gathering Files..."); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Ban.ToIconString(), UiHelpers.IconButtonSize, "Cancel the mass action.", !_compactor.MassCompactRunning, true)) - _compactor.CancelMassCompact(); + _compactor.CancelMassCompact(); } else { diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index 87e709c3..1a589c28 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -42,10 +42,10 @@ public enum BasicTutorialSteps /// Service for the in-game tutorial. public class TutorialService { - public const string SelectedCollection = "Selected Collection"; - public const string DefaultCollection = "Base Collection"; - public const string InterfaceCollection = "Interface Collection"; - public const string AssignedCollections = "Assigned Collections"; + public const string SelectedCollection = "Selected Collection"; + public const string DefaultCollection = "Base Collection"; + public const string InterfaceCollection = "Interface Collection"; + public const string AssignedCollections = "Assigned Collections"; public const string SupportedRedrawModifiers = " - nothing, to redraw all characters\n" + " - 'self' or '': your own character\n" @@ -79,20 +79,26 @@ public class TutorialService .Register("Initial Setup, Step 3: Collections", "Collections are lists of settings for your installed mods.\n\n" + "This is our next stop!\n\n" + "Go here after setting up your root folder to continue the tutorial!") - .Register("Initial Setup, Step 4: Managing Collections", "On the left, we have the collection selector. Here, we can create new collections - either empty ones or by duplicating existing ones - and delete any collections not needed anymore.\n" + .Register("Initial Setup, Step 4: Managing Collections", + "On the left, we have the collection selector. Here, we can create new collections - either empty ones or by duplicating existing ones - and delete any collections not needed anymore.\n" + $"There will always be one collection called {ModCollection.DefaultCollectionName} that can not be deleted.") .Register($"Initial Setup, Step 5: {SelectedCollection}", $"The {SelectedCollection} is the one we highlighted in the selector. It is the collection we are currently looking at and editing.\nAny changes we make in our mod settings later in the next tab will edit this collection.\n" + $"We should already have the collection named {ModCollection.DefaultCollectionName} selected, and for our simple setup, we do not need to do anything here.\n\n") - .Register("Initial Setup, Step 6: Simple Assignments", "Aside from being a collection of settings, we can also assign collections to different functions. This is used to make different mods apply to different characters.\n" + .Register("Initial Setup, Step 6: Simple Assignments", + "Aside from being a collection of settings, we can also assign collections to different functions. This is used to make different mods apply to different characters.\n" + "The Simple Assignments panel shows you the possible assignments that are enough for most people along with descriptions.\n" + $"If you are just starting, you can see that the {ModCollection.DefaultCollectionName} is currently assigned to {CollectionType.Default.ToName()} and {CollectionType.Interface.ToName()}.\n" + "You can also assign 'Use No Mods' instead of a collection by clicking on the function buttons.") - .Register("Individual Assignments", "In the Individual Assignments panel, you can manually create assignments for very specific characters or monsters, not just yourself or ones you can currently target.") - .Register("Group Assignments", "In the Group Assignments panel, you can create Assignments for more specific groups of characters based on race or age.") - .Register("Collection Details", "In the Collection Details panel, you can see a detailed overview over the usage of the currently selected collection, as well as remove outdated mod settings and setup inheritance.\n" + .Register("Individual Assignments", + "In the Individual Assignments panel, you can manually create assignments for very specific characters or monsters, not just yourself or ones you can currently target.") + .Register("Group Assignments", + "In the Group Assignments panel, you can create Assignments for more specific groups of characters based on race or age.") + .Register("Collection Details", + "In the Collection Details panel, you can see a detailed overview over the usage of the currently selected collection, as well as remove outdated mod settings and setup inheritance.\n" + "Inheritance can be used to make one collection take the settings of another as long as it does not setup the mod in question itself.") - .Register("Incognito Mode", "This button can toggle Incognito Mode, which shortens all collection names to two letters and a number,\n" + .Register("Incognito Mode", + "This button can toggle Incognito Mode, which shortens all collection names to two letters and a number,\n" + "and all displayed individual character names to their initials and world, in case you want to share screenshots.\n" + "It is strongly recommended to not show your characters name in public screenshots when using Penumbra.") .Deprecated() @@ -150,7 +156,7 @@ public class TutorialService _config.TutorialStep = v; _config.Save(); }); - + /// Update the current tutorial step if tutorials have changed since last update. public void UpdateTutorialStep() { diff --git a/Penumbra/UI/UiHelpers.cs b/Penumbra/UI/UiHelpers.cs index 7f4fc7cb..132dce86 100644 --- a/Penumbra/UI/UiHelpers.cs +++ b/Penumbra/UI/UiHelpers.cs @@ -114,8 +114,8 @@ public static class UiHelpers ScaleX5 = Scale * 5; } - IconButtonSize = new Vector2(ImGui.GetFrameHeight()); + IconButtonSize = new Vector2(ImGui.GetFrameHeight()); InputTextMinusButton3 = InputTextWidth.X - IconButtonSize.X - ScaleX3; - InputTextMinusButton = InputTextWidth.X - IconButtonSize.X - ImGui.GetStyle().ItemSpacing.X; + InputTextMinusButton = InputTextWidth.X - IconButtonSize.X - ImGui.GetStyle().ItemSpacing.X; } } diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index f08b6de9..25d91644 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -1,11 +1,10 @@ using Dalamud.Interface; using Dalamud.Interface.Windowing; using Dalamud.Plugin; -using Penumbra.UI; using Penumbra.UI.AdvancedWindow; using Penumbra.UI.Tabs; -namespace Penumbra; +namespace Penumbra.UI; public class PenumbraWindowSystem : IDisposable { diff --git a/Penumbra/Util/DictionaryExtensions.cs b/Penumbra/Util/DictionaryExtensions.cs index 74274c38..abf715e6 100644 --- a/Penumbra/Util/DictionaryExtensions.cs +++ b/Penumbra/Util/DictionaryExtensions.cs @@ -2,98 +2,84 @@ namespace Penumbra.Util; public static class DictionaryExtensions { - /// Returns whether two dictionaries contain equal keys and values. - public static bool SetEquals< TKey, TValue >( this IReadOnlyDictionary< TKey, TValue > lhs, IReadOnlyDictionary< TKey, TValue > rhs ) + /// Returns whether two dictionaries contain equal keys and values. + public static bool SetEquals(this IReadOnlyDictionary lhs, IReadOnlyDictionary rhs) { - if( ReferenceEquals( lhs, rhs ) ) - { + if (ReferenceEquals(lhs, rhs)) return true; - } - if( lhs.Count != rhs.Count ) - { + if (lhs.Count != rhs.Count) return false; - } - foreach( var (key, value) in lhs ) + foreach (var (key, value) in lhs) { - if( !rhs.TryGetValue( key, out var rhsValue ) ) - { + if (!rhs.TryGetValue(key, out var rhsValue)) return false; - } - if( value == null ) + if (value == null) { - if( rhsValue != null ) - { + if (rhsValue != null) return false; - } continue; } - if( !value.Equals( rhsValue ) ) - { + if (!value.Equals(rhsValue)) return false; - } } return true; } - /// Set one dictionary to the other, deleting previous entries and ensuring capacity beforehand. - public static void SetTo< TKey, TValue >( this Dictionary< TKey, TValue > lhs, IReadOnlyDictionary< TKey, TValue > rhs ) + /// Set one dictionary to the other, deleting previous entries and ensuring capacity beforehand. + public static void SetTo(this Dictionary lhs, IReadOnlyDictionary rhs) where TKey : notnull { - if( ReferenceEquals( lhs, rhs ) ) + if (ReferenceEquals(lhs, rhs)) return; lhs.Clear(); - lhs.EnsureCapacity( rhs.Count ); - foreach( var (key, value) in rhs ) - lhs.Add( key, value ); + lhs.EnsureCapacity(rhs.Count); + foreach (var (key, value) in rhs) + lhs.Add(key, value); } - /// Set one set to the other, deleting previous entries and ensuring capacity beforehand. + /// Set one set to the other, deleting previous entries and ensuring capacity beforehand. public static void SetTo(this HashSet lhs, IReadOnlySet rhs) { if (ReferenceEquals(lhs, rhs)) return; lhs.Clear(); - lhs.EnsureCapacity(rhs.Count); + lhs.EnsureCapacity(rhs.Count); foreach (var value in rhs) lhs.Add(value); } - /// Add all entries from the other dictionary that would not overwrite current keys. - public static void AddFrom< TKey, TValue >( this Dictionary< TKey, TValue > lhs, IReadOnlyDictionary< TKey, TValue > rhs ) + /// Add all entries from the other dictionary that would not overwrite current keys. + public static void AddFrom(this Dictionary lhs, IReadOnlyDictionary rhs) where TKey : notnull { - if( ReferenceEquals( lhs, rhs ) ) - { + if (ReferenceEquals(lhs, rhs)) return; - } - lhs.EnsureCapacity( lhs.Count + rhs.Count ); - foreach( var (key, value) in rhs ) - { - lhs.Add( key, value ); - } + lhs.EnsureCapacity(lhs.Count + rhs.Count); + foreach (var (key, value) in rhs) + lhs.Add(key, value); } - public static int ReplaceValue< TKey, TValue >( this Dictionary< TKey, TValue > dict, TValue from, TValue to ) + public static int ReplaceValue(this Dictionary dict, TValue from, TValue to) where TKey : notnull - where TValue : IEquatable< TValue > + where TValue : IEquatable { var count = 0; - foreach( var (key, _) in dict.ToArray().Where( kvp => kvp.Value.Equals( from ) ) ) + foreach (var (key, _) in dict.ToArray().Where(kvp => kvp.Value.Equals(from))) { - dict[ key ] = to; + dict[key] = to; ++count; } return count; } -} \ No newline at end of file +} diff --git a/Penumbra/Util/FixedUlongStringEnumConverter.cs b/Penumbra/Util/FixedUlongStringEnumConverter.cs index 85c61837..857d951d 100644 --- a/Penumbra/Util/FixedUlongStringEnumConverter.cs +++ b/Penumbra/Util/FixedUlongStringEnumConverter.cs @@ -8,84 +8,70 @@ namespace Penumbra.Util; // These converters fix this, taken from https://stackoverflow.com/questions/61740964/json-net-unable-to-deserialize-ulong-flag-type-enum/ public class ForceNumericFlagEnumConverter : FixedUlongStringEnumConverter { - private static bool HasFlagsAttribute( Type? objectType ) - => objectType != null && Attribute.IsDefined( Nullable.GetUnderlyingType( objectType ) ?? objectType, typeof( System.FlagsAttribute ) ); + private static bool HasFlagsAttribute(Type? objectType) + => objectType != null && Attribute.IsDefined(Nullable.GetUnderlyingType(objectType) ?? objectType, typeof(FlagsAttribute)); - public override void WriteJson( JsonWriter writer, object? value, JsonSerializer serializer ) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { var enumType = value?.GetType(); - if( HasFlagsAttribute( enumType ) ) + if (HasFlagsAttribute(enumType)) { - var underlyingType = Enum.GetUnderlyingType( enumType! ); - var underlyingValue = Convert.ChangeType( value, underlyingType ); - writer.WriteValue( underlyingValue ); + var underlyingType = Enum.GetUnderlyingType(enumType!); + var underlyingValue = Convert.ChangeType(value, underlyingType); + writer.WriteValue(underlyingValue); } else { - base.WriteJson( writer, value, serializer ); + base.WriteJson(writer, value, serializer); } } } public class FixedUlongStringEnumConverter : StringEnumConverter { - public override object? ReadJson( JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer ) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { - if( reader.MoveToContentAndAssert().TokenType != JsonToken.Integer || reader.ValueType != typeof( System.Numerics.BigInteger ) ) - { - return base.ReadJson( reader, objectType, existingValue, serializer ); - } + if (reader.MoveToContentAndAssert().TokenType != JsonToken.Integer || reader.ValueType != typeof(BigInteger)) + return base.ReadJson(reader, objectType, existingValue, serializer); // Todo: throw an exception if !this.AllowIntegerValues // https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Converters_StringEnumConverter_AllowIntegerValues.htm - var enumType = Nullable.GetUnderlyingType( objectType ) ?? objectType; - if( Enum.GetUnderlyingType( enumType ) == typeof( ulong ) ) + var enumType = Nullable.GetUnderlyingType(objectType) ?? objectType; + if (Enum.GetUnderlyingType(enumType) == typeof(ulong)) { - var bigInteger = ( System.Numerics.BigInteger )reader.Value!; - if( bigInteger >= ulong.MinValue && bigInteger <= ulong.MaxValue ) - { - return Enum.ToObject( enumType, checked( ( ulong )bigInteger ) ); - } + var bigInteger = (BigInteger)reader.Value!; + if (bigInteger >= ulong.MinValue && bigInteger <= ulong.MaxValue) + return Enum.ToObject(enumType, checked((ulong)bigInteger)); } - return base.ReadJson( reader, objectType, existingValue, serializer ); + return base.ReadJson(reader, objectType, existingValue, serializer); } } public static partial class JsonExtensions { - public static JsonReader MoveToContentAndAssert( this JsonReader reader ) + public static JsonReader MoveToContentAndAssert(this JsonReader reader) { - if( reader == null ) - { + if (reader == null) throw new ArgumentNullException(); - } - if( reader.TokenType == JsonToken.None ) // Skip past beginning of stream. - { + if (reader.TokenType == JsonToken.None) // Skip past beginning of stream. reader.ReadAndAssert(); - } - while( reader.TokenType == JsonToken.Comment ) // Skip past comments. - { + while (reader.TokenType == JsonToken.Comment) // Skip past comments. reader.ReadAndAssert(); - } return reader; } - private static JsonReader ReadAndAssert( this JsonReader reader ) + private static JsonReader ReadAndAssert(this JsonReader reader) { - if( reader == null ) - { + if (reader == null) throw new ArgumentNullException(); - } - if( !reader.Read() ) - { - throw new JsonReaderException( "Unexpected end of JSON stream." ); - } + if (!reader.Read()) + throw new JsonReaderException("Unexpected end of JSON stream."); return reader; } -} \ No newline at end of file +} diff --git a/Penumbra/Util/PenumbraSqPackStream.cs b/Penumbra/Util/PenumbraSqPackStream.cs index d5b51433..d913a019 100644 --- a/Penumbra/Util/PenumbraSqPackStream.cs +++ b/Penumbra/Util/PenumbraSqPackStream.cs @@ -10,45 +10,45 @@ public class PenumbraSqPackStream : IDisposable protected BinaryReader Reader { get; set; } - public PenumbraSqPackStream( FileInfo file ) - : this( file.OpenRead() ) + public PenumbraSqPackStream(FileInfo file) + : this(file.OpenRead()) { } - public PenumbraSqPackStream( Stream stream ) + public PenumbraSqPackStream(Stream stream) { BaseStream = stream; - Reader = new BinaryReader( BaseStream ); + Reader = new BinaryReader(BaseStream); } public SqPackHeader GetSqPackHeader() { BaseStream.Position = 0; - return Reader.ReadStructure< SqPackHeader >(); + return Reader.ReadStructure(); } - public SqPackFileInfo GetFileMetadata( long offset ) + public SqPackFileInfo GetFileMetadata(long offset) { BaseStream.Position = offset; - return Reader.ReadStructure< SqPackFileInfo >(); + return Reader.ReadStructure(); } - public T ReadFile< T >( long offset ) where T : PenumbraFileResource + public T ReadFile(long offset) where T : PenumbraFileResource { using var ms = new MemoryStream(); BaseStream.Position = offset; - var fileInfo = Reader.ReadStructure< SqPackFileInfo >(); - var file = Activator.CreateInstance< T >(); + var fileInfo = Reader.ReadStructure(); + var file = Activator.CreateInstance(); // check if we need to read the extended model header or just default to the standard file header - if( fileInfo.Type == FileType.Model ) + if (fileInfo.Type == FileType.Model) { BaseStream.Position = offset; - var modelFileInfo = Reader.ReadStructure< ModelBlock >(); + var modelFileInfo = Reader.ReadStructure(); file.FileInfo = new PenumbraFileInfo { @@ -74,33 +74,31 @@ public class PenumbraSqPackStream : IDisposable }; } - switch( fileInfo.Type ) + switch (fileInfo.Type) { - case FileType.Empty: throw new FileNotFoundException( $"The file located at 0x{offset:x} is empty." ); + case FileType.Empty: throw new FileNotFoundException($"The file located at 0x{offset:x} is empty."); case FileType.Standard: - ReadStandardFile( file, ms ); + ReadStandardFile(file, ms); break; case FileType.Model: - ReadModelFile( file, ms ); + ReadModelFile(file, ms); break; case FileType.Texture: - ReadTextureFile( file, ms ); + ReadTextureFile(file, ms); break; - default: throw new NotImplementedException( $"File Type {( uint )fileInfo.Type} is not implemented." ); + default: throw new NotImplementedException($"File Type {(uint)fileInfo.Type} is not implemented."); } file.Data = ms.ToArray(); - if( file.Data.Length != file.FileInfo.RawFileSize ) - { - Debug.WriteLine( "Read data size does not match file size." ); - } + if (file.Data.Length != file.FileInfo.RawFileSize) + Debug.WriteLine("Read data size does not match file size."); - file.FileStream = new MemoryStream( file.Data, false ); - file.Reader = new BinaryReader( file.FileStream ); + file.FileStream = new MemoryStream(file.Data, false); + file.Reader = new BinaryReader(file.FileStream); file.FileStream.Position = 0; file.LoadFile(); @@ -108,20 +106,18 @@ public class PenumbraSqPackStream : IDisposable return file; } - private void ReadStandardFile( PenumbraFileResource resource, MemoryStream ms ) + private void ReadStandardFile(PenumbraFileResource resource, MemoryStream ms) { - var blocks = Reader.ReadStructures< DatStdFileBlockInfos >( ( int )resource.FileInfo!.BlockCount ); + var blocks = Reader.ReadStructures((int)resource.FileInfo!.BlockCount); - foreach( var block in blocks ) - { - ReadFileBlock( resource.FileInfo.Offset + resource.FileInfo.HeaderSize + block.Offset, ms ); - } + foreach (var block in blocks) + ReadFileBlock(resource.FileInfo.Offset + resource.FileInfo.HeaderSize + block.Offset, ms); // reset position ready for reading ms.Position = 0; } - private unsafe void ReadModelFile( PenumbraFileResource resource, MemoryStream ms ) + private unsafe void ReadModelFile(PenumbraFileResource resource, MemoryStream ms) { var mdlBlock = resource.FileInfo!.ModelBlock; var baseOffset = resource.FileInfo.Offset + resource.FileInfo.HeaderSize; @@ -133,185 +129,165 @@ public class PenumbraSqPackStream : IDisposable // but it seems to work fine in explorer... int totalBlocks = mdlBlock.StackBlockNum; totalBlocks += mdlBlock.RuntimeBlockNum; - for( var i = 0; i < 3; i++ ) - { - totalBlocks += mdlBlock.VertexBufferBlockNum[ i ]; - } + for (var i = 0; i < 3; i++) + totalBlocks += mdlBlock.VertexBufferBlockNum[i]; - for( var i = 0; i < 3; i++ ) - { - totalBlocks += mdlBlock.EdgeGeometryVertexBufferBlockNum[ i ]; - } + for (var i = 0; i < 3; i++) + totalBlocks += mdlBlock.EdgeGeometryVertexBufferBlockNum[i]; - for( var i = 0; i < 3; i++ ) - { - totalBlocks += mdlBlock.IndexBufferBlockNum[ i ]; - } + for (var i = 0; i < 3; i++) + totalBlocks += mdlBlock.IndexBufferBlockNum[i]; - var compressedBlockSizes = Reader.ReadStructures< ushort >( totalBlocks ); + var compressedBlockSizes = Reader.ReadStructures(totalBlocks); var currentBlock = 0; var vertexDataOffsets = new int[3]; var indexDataOffsets = new int[3]; var vertexBufferSizes = new int[3]; var indexBufferSizes = new int[3]; - ms.Seek( 0x44, SeekOrigin.Begin ); + ms.Seek(0x44, SeekOrigin.Begin); - Reader.Seek( baseOffset + mdlBlock.StackOffset ); + Reader.Seek(baseOffset + mdlBlock.StackOffset); var stackStart = ms.Position; - for( var i = 0; i < mdlBlock.StackBlockNum; i++ ) + for (var i = 0; i < mdlBlock.StackBlockNum; i++) { var lastPos = Reader.BaseStream.Position; - ReadFileBlock( ms ); - Reader.Seek( lastPos + compressedBlockSizes[ currentBlock ] ); + ReadFileBlock(ms); + Reader.Seek(lastPos + compressedBlockSizes[currentBlock]); currentBlock++; } var stackEnd = ms.Position; - var stackSize = ( int )( stackEnd - stackStart ); + var stackSize = (int)(stackEnd - stackStart); - Reader.Seek( baseOffset + mdlBlock.RuntimeOffset ); + Reader.Seek(baseOffset + mdlBlock.RuntimeOffset); var runtimeStart = ms.Position; - for( var i = 0; i < mdlBlock.RuntimeBlockNum; i++ ) + for (var i = 0; i < mdlBlock.RuntimeBlockNum; i++) { var lastPos = Reader.BaseStream.Position; - ReadFileBlock( ms ); - Reader.Seek( lastPos + compressedBlockSizes[ currentBlock ] ); + ReadFileBlock(ms); + Reader.Seek(lastPos + compressedBlockSizes[currentBlock]); currentBlock++; } var runtimeEnd = ms.Position; - var runtimeSize = ( int )( runtimeEnd - runtimeStart ); + var runtimeSize = (int)(runtimeEnd - runtimeStart); - for( var i = 0; i < 3; i++ ) + for (var i = 0; i < 3; i++) { - if( mdlBlock.VertexBufferBlockNum[ i ] != 0 ) + if (mdlBlock.VertexBufferBlockNum[i] != 0) { - var currentVertexOffset = ( int )ms.Position; - if( i == 0 || currentVertexOffset != vertexDataOffsets[ i - 1 ] ) - { - vertexDataOffsets[ i ] = currentVertexOffset; - } + var currentVertexOffset = (int)ms.Position; + if (i == 0 || currentVertexOffset != vertexDataOffsets[i - 1]) + vertexDataOffsets[i] = currentVertexOffset; else - { - vertexDataOffsets[ i ] = 0; - } + vertexDataOffsets[i] = 0; - Reader.Seek( baseOffset + mdlBlock.VertexBufferOffset[ i ] ); + Reader.Seek(baseOffset + mdlBlock.VertexBufferOffset[i]); - for( var j = 0; j < mdlBlock.VertexBufferBlockNum[ i ]; j++ ) + for (var j = 0; j < mdlBlock.VertexBufferBlockNum[i]; j++) { var lastPos = Reader.BaseStream.Position; - vertexBufferSizes[ i ] += ( int )ReadFileBlock( ms ); - Reader.Seek( lastPos + compressedBlockSizes[ currentBlock ] ); + vertexBufferSizes[i] += (int)ReadFileBlock(ms); + Reader.Seek(lastPos + compressedBlockSizes[currentBlock]); currentBlock++; } } - if( mdlBlock.EdgeGeometryVertexBufferBlockNum[ i ] != 0 ) - { - for( var j = 0; j < mdlBlock.EdgeGeometryVertexBufferBlockNum[ i ]; j++ ) + if (mdlBlock.EdgeGeometryVertexBufferBlockNum[i] != 0) + for (var j = 0; j < mdlBlock.EdgeGeometryVertexBufferBlockNum[i]; j++) { var lastPos = Reader.BaseStream.Position; - ReadFileBlock( ms ); - Reader.Seek( lastPos + compressedBlockSizes[ currentBlock ] ); + ReadFileBlock(ms); + Reader.Seek(lastPos + compressedBlockSizes[currentBlock]); currentBlock++; } - } - if( mdlBlock.IndexBufferBlockNum[ i ] != 0 ) + if (mdlBlock.IndexBufferBlockNum[i] != 0) { - var currentIndexOffset = ( int )ms.Position; - if( i == 0 || currentIndexOffset != indexDataOffsets[ i - 1 ] ) - { - indexDataOffsets[ i ] = currentIndexOffset; - } + var currentIndexOffset = (int)ms.Position; + if (i == 0 || currentIndexOffset != indexDataOffsets[i - 1]) + indexDataOffsets[i] = currentIndexOffset; else - { - indexDataOffsets[ i ] = 0; - } + indexDataOffsets[i] = 0; // i guess this is only needed in the vertex area, for i = 0 // Reader.Seek( baseOffset + mdlBlock.IndexBufferOffset[ i ] ); - for( var j = 0; j < mdlBlock.IndexBufferBlockNum[ i ]; j++ ) + for (var j = 0; j < mdlBlock.IndexBufferBlockNum[i]; j++) { var lastPos = Reader.BaseStream.Position; - indexBufferSizes[ i ] += ( int )ReadFileBlock( ms ); - Reader.Seek( lastPos + compressedBlockSizes[ currentBlock ] ); + indexBufferSizes[i] += (int)ReadFileBlock(ms); + Reader.Seek(lastPos + compressedBlockSizes[currentBlock]); currentBlock++; } } } - ms.Seek( 0, SeekOrigin.Begin ); - ms.Write( BitConverter.GetBytes( mdlBlock.Version ) ); - ms.Write( BitConverter.GetBytes( stackSize ) ); - ms.Write( BitConverter.GetBytes( runtimeSize ) ); - ms.Write( BitConverter.GetBytes( mdlBlock.VertexDeclarationNum ) ); - ms.Write( BitConverter.GetBytes( mdlBlock.MaterialNum ) ); - for( var i = 0; i < 3; i++ ) - { - ms.Write( BitConverter.GetBytes( vertexDataOffsets[ i ] ) ); - } + ms.Seek(0, SeekOrigin.Begin); + ms.Write(BitConverter.GetBytes(mdlBlock.Version)); + ms.Write(BitConverter.GetBytes(stackSize)); + ms.Write(BitConverter.GetBytes(runtimeSize)); + ms.Write(BitConverter.GetBytes(mdlBlock.VertexDeclarationNum)); + ms.Write(BitConverter.GetBytes(mdlBlock.MaterialNum)); + for (var i = 0; i < 3; i++) + ms.Write(BitConverter.GetBytes(vertexDataOffsets[i])); - for( var i = 0; i < 3; i++ ) - { - ms.Write( BitConverter.GetBytes( indexDataOffsets[ i ] ) ); - } + for (var i = 0; i < 3; i++) + ms.Write(BitConverter.GetBytes(indexDataOffsets[i])); - for( var i = 0; i < 3; i++ ) - { - ms.Write( BitConverter.GetBytes( vertexBufferSizes[ i ] ) ); - } + for (var i = 0; i < 3; i++) + ms.Write(BitConverter.GetBytes(vertexBufferSizes[i])); - for( var i = 0; i < 3; i++ ) - { - ms.Write( BitConverter.GetBytes( indexBufferSizes[ i ] ) ); - } + for (var i = 0; i < 3; i++) + ms.Write(BitConverter.GetBytes(indexBufferSizes[i])); - ms.Write( new[] { mdlBlock.NumLods } ); - ms.Write( BitConverter.GetBytes( mdlBlock.IndexBufferStreamingEnabled ) ); - ms.Write( BitConverter.GetBytes( mdlBlock.EdgeGeometryEnabled ) ); - ms.Write( new byte[] { 0 } ); + ms.Write(new[] + { + mdlBlock.NumLods, + }); + ms.Write(BitConverter.GetBytes(mdlBlock.IndexBufferStreamingEnabled)); + ms.Write(BitConverter.GetBytes(mdlBlock.EdgeGeometryEnabled)); + ms.Write(new byte[] + { + 0, + }); } - private void ReadTextureFile( PenumbraFileResource resource, MemoryStream ms ) + private void ReadTextureFile(PenumbraFileResource resource, MemoryStream ms) { - if( resource.FileInfo!.BlockCount == 0 ) - { + if (resource.FileInfo!.BlockCount == 0) return; - } - var blocks = Reader.ReadStructures< LodBlock >( ( int )resource.FileInfo!.BlockCount ); + var blocks = Reader.ReadStructures((int)resource.FileInfo!.BlockCount); // if there is a mipmap header, the comp_offset // will not be 0 - var mipMapSize = blocks[ 0 ].CompressedOffset; - if( mipMapSize != 0 ) + var mipMapSize = blocks[0].CompressedOffset; + if (mipMapSize != 0) { var originalPos = BaseStream.Position; BaseStream.Position = resource.FileInfo.Offset + resource.FileInfo.HeaderSize; - ms.Write( Reader.ReadBytes( ( int )mipMapSize ) ); + ms.Write(Reader.ReadBytes((int)mipMapSize)); BaseStream.Position = originalPos; } // i is for texture blocks, j is 'data blocks'... - for( byte i = 0; i < blocks.Count; i++ ) + for (byte i = 0; i < blocks.Count; i++) { - if( blocks[ i ].CompressedSize == 0 ) + if (blocks[i].CompressedSize == 0) continue; // start from comp_offset - var runningBlockTotal = blocks[ i ].CompressedOffset + resource.FileInfo.Offset + resource.FileInfo.HeaderSize; - ReadFileBlock( runningBlockTotal, ms, true ); + var runningBlockTotal = blocks[i].CompressedOffset + resource.FileInfo.Offset + resource.FileInfo.HeaderSize; + ReadFileBlock(runningBlockTotal, ms, true); - for( var j = 1; j < blocks[ i ].BlockCount; j++ ) + for (var j = 1; j < blocks[i].BlockCount; j++) { - runningBlockTotal += ( uint )Reader.ReadInt16(); - ReadFileBlock( runningBlockTotal, ms, true ); + runningBlockTotal += (uint)Reader.ReadInt16(); + ReadFileBlock(runningBlockTotal, ms, true); } // unknown @@ -319,34 +295,32 @@ public class PenumbraSqPackStream : IDisposable } } - protected uint ReadFileBlock( MemoryStream dest, bool resetPosition = false ) - => ReadFileBlock( Reader.BaseStream.Position, dest, resetPosition ); + protected uint ReadFileBlock(MemoryStream dest, bool resetPosition = false) + => ReadFileBlock(Reader.BaseStream.Position, dest, resetPosition); - protected uint ReadFileBlock( long offset, MemoryStream dest, bool resetPosition = false ) + protected uint ReadFileBlock(long offset, MemoryStream dest, bool resetPosition = false) { var originalPosition = BaseStream.Position; BaseStream.Position = offset; - var blockHeader = Reader.ReadStructure< DatBlockHeader >(); + var blockHeader = Reader.ReadStructure(); // uncompressed block - if( blockHeader.CompressedSize == 32000 ) + if (blockHeader.CompressedSize == 32000) { - dest.Write( Reader.ReadBytes( ( int )blockHeader.UncompressedSize ) ); + dest.Write(Reader.ReadBytes((int)blockHeader.UncompressedSize)); } else { - var data = Reader.ReadBytes( ( int )blockHeader.CompressedSize ); + var data = Reader.ReadBytes((int)blockHeader.CompressedSize); - using var compressedStream = new MemoryStream( data ); - using var zlibStream = new DeflateStream( compressedStream, CompressionMode.Decompress ); - zlibStream.CopyTo( dest ); + using var compressedStream = new MemoryStream(data); + using var zlibStream = new DeflateStream(compressedStream, CompressionMode.Decompress); + zlibStream.CopyTo(dest); } - if( resetPosition ) - { + if (resetPosition) BaseStream.Position = originalPosition; - } return blockHeader.UncompressedSize; } @@ -390,7 +364,7 @@ public class PenumbraSqPackStream : IDisposable } } - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] private struct DatBlockHeader { public uint Size; @@ -399,7 +373,7 @@ public class PenumbraSqPackStream : IDisposable public uint UncompressedSize; }; - [StructLayout( LayoutKind.Sequential )] + [StructLayout(LayoutKind.Sequential)] private struct LodBlock { public uint CompressedOffset; @@ -408,4 +382,4 @@ public class PenumbraSqPackStream : IDisposable public uint BlockOffset; public uint BlockCount; } -} \ No newline at end of file +} diff --git a/Penumbra/Util/PerformanceType.cs b/Penumbra/Util/PerformanceType.cs index c0ad766d..932072f0 100644 --- a/Penumbra/Util/PerformanceType.cs +++ b/Penumbra/Util/PerformanceType.cs @@ -1,5 +1,5 @@ global using StartTracker = OtterGui.Classes.StartTimeTracker; -global using PerformanceTracker = OtterGui.Classes.PerformanceTracker; +global using PerformanceTracker = OtterGui.Classes.PerformanceTracker; namespace Penumbra.Util; From d7205344ebdde365f9c0c4990a1fbf1825775f49 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 17 Sep 2023 22:25:31 +0200 Subject: [PATCH 0101/1381] ResourceTree improvements + IPC - Moves ResourceType enum out of GameData as discussed on Discord ; - Adds new color coding for local player and non-networked objects on On-Screen ; - Adds ResourceTree-related IPC ; - Fixes #342. --- Penumbra/Api/IpcTester.cs | 223 +++++++++++++++ Penumbra/Api/PenumbraApi.cs | 115 +++++--- Penumbra/Api/PenumbraIpcProviders.cs | 18 ++ Penumbra/Configuration.cs | 1 + Penumbra/Enums/ResourceType.cs | 260 ++++++++++++++++++ .../PathResolving/AnimationHookService.cs | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 1 + .../Interop/PathResolving/PathResolver.cs | 1 - .../Interop/PathResolving/SubfileHelper.cs | 2 +- .../Interop/ResourceLoading/ResourceLoader.cs | 2 +- .../ResourceLoading/ResourceManagerService.cs | 2 +- .../ResourceLoading/ResourceService.cs | 2 +- .../Interop/ResourceLoading/TexMdlService.cs | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 1 + Penumbra/Interop/ResourceTree/ResourceNode.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 24 +- .../ResourceTree/ResourceTreeApiHelper.cs | 104 +++++++ .../ResourceTree/ResourceTreeFactory.cs | 38 ++- .../Interop/ResourceTree/TreeBuildCache.cs | 28 +- Penumbra/Interop/Services/DecalReverter.cs | 2 +- Penumbra/Interop/Structs/ResourceHandle.cs | 2 +- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 1 + Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 1 + Penumbra/Mods/ItemSwap/ItemSwap.cs | 3 +- Penumbra/Mods/ItemSwap/Swaps.cs | 2 +- Penumbra/Penumbra.csproj | 4 + .../UI/AdvancedWindow/ResourceTreeViewer.cs | 25 +- Penumbra/UI/ChangedItemDrawer.cs | 24 ++ Penumbra/UI/Classes/Colors.cs | 10 + Penumbra/UI/ResourceWatcher/Record.cs | 1 + .../UI/ResourceWatcher/ResourceWatcher.cs | 2 +- .../ResourceWatcher/ResourceWatcherTable.cs | 1 + 32 files changed, 826 insertions(+), 80 deletions(-) create mode 100644 Penumbra/Enums/ResourceType.cs create mode 100644 Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 69c2fd3d..fb8719f4 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -15,6 +15,8 @@ using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; using Penumbra.Collections.Manager; +using Dalamud.Plugin.Services; +using Penumbra.GameData.Enums; namespace Penumbra.Api; @@ -35,6 +37,7 @@ public class IpcTester : IDisposable private readonly ModSettings _modSettings; private readonly Editing _editing; private readonly Temporary _temporary; + private readonly ResourceTree _resourceTree; public IpcTester(Configuration config, DalamudServices dalamud, PenumbraIpcProviders ipcProviders, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService) @@ -52,6 +55,7 @@ public class IpcTester : IDisposable _modSettings = new ModSettings(dalamud.PluginInterface); _editing = new Editing(dalamud.PluginInterface); _temporary = new Temporary(dalamud.PluginInterface, modManager, collections, tempMods, tempCollections, saveService, config); + _resourceTree = new ResourceTree(dalamud.PluginInterface, dalamud.Objects); UnsubscribeEvents(); } @@ -75,6 +79,7 @@ public class IpcTester : IDisposable _temporary.Draw(); _temporary.DrawCollections(); _temporary.DrawMods(); + _resourceTree.Draw(); } catch (Exception e) { @@ -1397,4 +1402,222 @@ public class IpcTester : IDisposable } } } + + private class ResourceTree + { + private readonly DalamudPluginInterface _pi; + private readonly IObjectTable _objects; + + private string _gameObjectIndices = "0"; + private bool _mergeSameCollection = false; + private ResourceType _type = ResourceType.Mtrl; + private bool _withUIData = false; + + private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcePaths; + private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcePaths; + private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcesOfType; + private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcesOfType; + + public ResourceTree(DalamudPluginInterface pi, IObjectTable objects) + { + _pi = pi; + _objects = objects; + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("Resource Tree"); + if (!_) + return; + + ImGui.InputText("GameObject indices", ref _gameObjectIndices, 511); + ImGui.Checkbox("Merge entries that use the same collection", ref _mergeSameCollection); + ImGuiUtil.GenericEnumCombo("Resource type", ImGui.CalcItemWidth(), _type, out _type, Enum.GetValues()); + ImGui.Checkbox("Also get names and icons", ref _withUIData); + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + DrawIntro(Ipc.GetGameObjectResourcePaths.Label, "Get GameObject resource paths"); + if (ImGui.Button("Get##GameObjectResourcePaths")) + { + var gameObjects = GetSelectedGameObjects(); + var resourcePaths = Ipc.GetGameObjectResourcePaths.Subscriber(_pi).Invoke(gameObjects, _mergeSameCollection); + + _lastGameObjectResourcePaths = gameObjects + .Select(GameObjectToString) + .Zip(resourcePaths) + .ToArray(); + + ImGui.OpenPopup(nameof(Ipc.GetGameObjectResourcePaths)); + } + + DrawIntro(Ipc.GetPlayerResourcePaths.Label, "Get local player resource paths"); + if (ImGui.Button("Get##PlayerResourcePaths")) + { + _lastPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Subscriber(_pi).Invoke(_mergeSameCollection) + .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) + .ToArray(); + + ImGui.OpenPopup(nameof(Ipc.GetPlayerResourcePaths)); + } + + DrawIntro(Ipc.GetGameObjectResourcesOfType.Label, "Get GameObject resources of type"); + if (ImGui.Button("Get##GameObjectResourcesOfType")) + { + var gameObjects = GetSelectedGameObjects(); + var resourcesOfType = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi).Invoke(gameObjects, _type, _withUIData); + + _lastGameObjectResourcesOfType = gameObjects + .Select(GameObjectToString) + .Zip(resourcesOfType) + .ToArray(); + + ImGui.OpenPopup(nameof(Ipc.GetGameObjectResourcesOfType)); + } + + DrawIntro(Ipc.GetPlayerResourcesOfType.Label, "Get local player resources of type"); + if (ImGui.Button("Get##PlayerResourcesOfType")) + { + _lastPlayerResourcesOfType = Ipc.GetPlayerResourcesOfType.Subscriber(_pi).Invoke(_type, _withUIData) + .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) + .ToArray(); + + ImGui.OpenPopup(nameof(Ipc.GetPlayerResourcesOfType)); + } + + DrawPopup(nameof(Ipc.GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths); + DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths); + + DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType); + DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType); + } + + private static void DrawPopup(string popupId, ref T? result, Action drawResult) where T : class + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(1000, 500)); + using var popup = ImRaii.Popup(popupId); + if (!popup) + { + result = null; + return; + } + + if (result == null) + { + ImGui.CloseCurrentPopup(); + return; + } + + drawResult(result); + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + { + result = null; + ImGui.CloseCurrentPopup(); + } + } + + private static void DrawWithHeaders((string, T?)[] result, Action drawItem) where T : class + { + var firstSeen = new Dictionary(); + foreach (var (label, item) in result) + { + if (item == null) + { + ImRaii.TreeNode($"{label}: null", ImGuiTreeNodeFlags.Leaf).Dispose(); + continue; + } + + if (firstSeen.TryGetValue(item, out var firstLabel)) + { + ImRaii.TreeNode($"{label}: same as {firstLabel}", ImGuiTreeNodeFlags.Leaf).Dispose(); + continue; + } + + firstSeen.Add(item, label); + + using var header = ImRaii.TreeNode(label); + if (!header) + continue; + + drawItem(item); + } + } + + private static void DrawResourcePaths((string, IReadOnlyDictionary?)[] result) + { + DrawWithHeaders(result, paths => + { + using var table = ImRaii.Table(string.Empty, 2, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.6f); + ImGui.TableSetupColumn("Game Paths", ImGuiTableColumnFlags.WidthStretch, 0.4f); + ImGui.TableHeadersRow(); + + foreach (var (actualPath, gamePaths) in paths) + { + ImGui.TableNextColumn(); + ImGui.TextUnformatted(actualPath); + ImGui.TableNextColumn(); + foreach (var gamePath in gamePaths) + ImGui.TextUnformatted(gamePath); + } + }); + } + + private void DrawResourcesOfType((string, IReadOnlyDictionary?)[] result) + { + DrawWithHeaders(result, resources => + { + using var table = ImRaii.Table(string.Empty, _withUIData ? 3 : 2, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.15f); + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUIData ? 0.55f : 0.85f); + if (_withUIData) + ImGui.TableSetupColumn("Icon & Name", ImGuiTableColumnFlags.WidthStretch, 0.3f); + ImGui.TableHeadersRow(); + + foreach (var (resourceHandle, (actualPath, name, icon)) in resources) + { + ImGui.TableNextColumn(); + TextUnformattedMono($"0x{resourceHandle:X}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(actualPath); + if (_withUIData) + { + ImGui.TableNextColumn(); + TextUnformattedMono(icon.ToString()); + ImGui.SameLine(); + ImGui.TextUnformatted(name); + } + } + }); + } + + private static void TextUnformattedMono(string text) + { + using var _ = ImRaii.PushFont(UiBuilder.MonoFont); + ImGui.TextUnformatted(text); + } + + private ushort[] GetSelectedGameObjects() + => _gameObjectIndices.Split(',') + .SelectWhere(index => (ushort.TryParse(index.Trim(), out var i), i)) + .ToArray(); + + private unsafe string GameObjectToString(ushort gameObjectIndex) + { + var gameObject = _objects[gameObjectIndex]; + + return gameObject != null + ? $"[{gameObjectIndex}] {gameObject.Name} ({gameObject.ObjectKind})" + : $"[{gameObjectIndex}] null"; + } + } } diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 73a87fab..1c56b9df 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -23,13 +23,15 @@ using Penumbra.Import.Textures; using Penumbra.Interop.Services; using Penumbra.UI; using TextureType = Penumbra.Api.Enums.TextureType; +using Penumbra.Interop.ResourceTree; +using System.Collections.Immutable; namespace Penumbra.Api; public class PenumbraApi : IDisposable, IPenumbraApi { public (int, int) ApiVersion - => (4, 21); + => (4, 22); public event Action? PreSettingsPanelDraw { @@ -104,31 +106,33 @@ public class PenumbraApi : IDisposable, IPenumbraApi private ModFileSystem _modFileSystem; private ConfigWindow _configWindow; private TextureManager _textureManager; + private ResourceTreeFactory _resourceTreeFactory; public unsafe PenumbraApi(CommunicatorService communicator, ModManager modManager, ResourceLoader resourceLoader, Configuration config, CollectionManager collectionManager, DalamudServices dalamud, TempCollectionManager tempCollections, TempModManager tempMods, ActorService actors, CollectionResolver collectionResolver, CutsceneService cutsceneService, ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, ModFileSystem modFileSystem, - ConfigWindow configWindow, TextureManager textureManager) + ConfigWindow configWindow, TextureManager textureManager, ResourceTreeFactory resourceTreeFactory) { - _communicator = communicator; - _modManager = modManager; - _resourceLoader = resourceLoader; - _config = config; - _collectionManager = collectionManager; - _dalamud = dalamud; - _tempCollections = tempCollections; - _tempMods = tempMods; - _actors = actors; - _collectionResolver = collectionResolver; - _cutsceneService = cutsceneService; - _modImportManager = modImportManager; - _collectionEditor = collectionEditor; - _redrawService = redrawService; - _modFileSystem = modFileSystem; - _configWindow = configWindow; - _textureManager = textureManager; - _lumina = _dalamud.GameData.GameData; + _communicator = communicator; + _modManager = modManager; + _resourceLoader = resourceLoader; + _config = config; + _collectionManager = collectionManager; + _dalamud = dalamud; + _tempCollections = tempCollections; + _tempMods = tempMods; + _actors = actors; + _collectionResolver = collectionResolver; + _cutsceneService = cutsceneService; + _modImportManager = modImportManager; + _collectionEditor = collectionEditor; + _redrawService = redrawService; + _modFileSystem = modFileSystem; + _configWindow = configWindow; + _textureManager = textureManager; + _resourceTreeFactory = resourceTreeFactory; + _lumina = _dalamud.GameData.GameData; _resourceLoader.ResourceLoaded += OnResourceLoaded; _communicator.ModPathChanged.Subscribe(ModPathChangeSubscriber, ModPathChanged.Priority.Api); @@ -145,24 +149,25 @@ public class PenumbraApi : IDisposable, IPenumbraApi _communicator.ModPathChanged.Unsubscribe(ModPathChangeSubscriber); _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); _communicator.CreatedCharacterBase.Unsubscribe(OnCreatedCharacterBase); - _lumina = null; - _communicator = null!; - _modManager = null!; - _resourceLoader = null!; - _config = null!; - _collectionManager = null!; - _dalamud = null!; - _tempCollections = null!; - _tempMods = null!; - _actors = null!; - _collectionResolver = null!; - _cutsceneService = null!; - _modImportManager = null!; - _collectionEditor = null!; - _redrawService = null!; - _modFileSystem = null!; - _configWindow = null!; - _textureManager = null!; + _lumina = null; + _communicator = null!; + _modManager = null!; + _resourceLoader = null!; + _config = null!; + _collectionManager = null!; + _dalamud = null!; + _tempCollections = null!; + _tempMods = null!; + _actors = null!; + _collectionResolver = null!; + _cutsceneService = null!; + _modImportManager = null!; + _collectionEditor = null!; + _redrawService = null!; + _modFileSystem = null!; + _configWindow = null!; + _textureManager = null!; + _resourceTreeFactory = null!; } public event ChangedItemClick? ChangedItemClicked @@ -1011,6 +1016,40 @@ public class PenumbraApi : IDisposable, IPenumbraApi }; // @formatter:on + public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects, bool mergeSameCollection) + { + var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, false, false); + var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees, mergeSameCollection); + + return Array.ConvertAll(gameObjects, obj => pathDictionaries.TryGetValue(obj, out var pathDict) ? pathDict : null); + } + + public IReadOnlyDictionary> GetPlayerResourcePaths(bool mergeSameCollection) + { + var resourceTrees = _resourceTreeFactory.FromObjectTable(true, false, false); + var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees, mergeSameCollection); + + return pathDictionaries.AsReadOnly(); + } + + public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ushort[] gameObjects, ResourceType type, bool withUIData) + { + var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData, false); + var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); + + return Array.ConvertAll(gameObjects, obj => resDictionaries.TryGetValue(obj, out var resDict) ? resDict : null); + } + + public IReadOnlyDictionary> GetPlayerResourcesOfType(ResourceType type, bool withUIData) + { + var resourceTrees = _resourceTreeFactory.FromObjectTable(true, withUIData, false); + var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); + + return resDictionaries.AsReadOnly(); + } + // TODO: cleanup when incrementing API public string GetMetaManipulations(string characterName) diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 2d3fcf97..c05a7c47 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -118,6 +118,12 @@ public class PenumbraIpcProviders : IDisposable internal readonly FuncProvider RemoveTemporaryModAll; internal readonly FuncProvider RemoveTemporaryMod; + // Resource Tree + internal readonly FuncProvider?[]> GetGameObjectResourcePaths; + internal readonly FuncProvider>> GetPlayerResourcePaths; + internal readonly FuncProvider?[]> GetGameObjectResourcesOfType; + internal readonly FuncProvider>> GetPlayerResourcesOfType; + public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) { @@ -236,6 +242,12 @@ public class PenumbraIpcProviders : IDisposable RemoveTemporaryModAll = Ipc.RemoveTemporaryModAll.Provider(pi, Api.RemoveTemporaryModAll); RemoveTemporaryMod = Ipc.RemoveTemporaryMod.Provider(pi, Api.RemoveTemporaryMod); + // ResourceTree + GetGameObjectResourcePaths = Ipc.GetGameObjectResourcePaths.Provider(pi, Api.GetGameObjectResourcePaths); + GetPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Provider(pi, Api.GetPlayerResourcePaths); + GetGameObjectResourcesOfType = Ipc.GetGameObjectResourcesOfType.Provider(pi, Api.GetGameObjectResourcesOfType); + GetPlayerResourcesOfType = Ipc.GetPlayerResourcesOfType.Provider(pi, Api.GetPlayerResourcesOfType); + Tester = new IpcTester(config, dalamud, this, modManager, collections, tempMods, tempCollections, saveService); Initialized.Invoke(); @@ -345,6 +357,12 @@ public class PenumbraIpcProviders : IDisposable ConvertTextureFile.Dispose(); ConvertTextureData.Dispose(); + // Resource Tree + GetGameObjectResourcePaths.Dispose(); + GetPlayerResourcePaths.Dispose(); + GetGameObjectResourcesOfType.Dispose(); + GetPlayerResourcesOfType.Dispose(); + Disposed.Invoke(); Disposed.Dispose(); } diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 63d58a16..0206d0ae 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -6,6 +6,7 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Widgets; using Penumbra.Api.Enums; +using Penumbra.GameData.Enums; using Penumbra.Import.Structs; using Penumbra.Interop.Services; using Penumbra.Mods; diff --git a/Penumbra/Enums/ResourceType.cs b/Penumbra/Enums/ResourceType.cs new file mode 100644 index 00000000..0cfc5469 --- /dev/null +++ b/Penumbra/Enums/ResourceType.cs @@ -0,0 +1,260 @@ +using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; +using Penumbra.String; +using Penumbra.String.Functions; + +namespace Penumbra.Enums; + +[Flags] +public enum ResourceTypeFlag : ulong +{ + Aet = 0x0000_0000_0000_0001, + Amb = 0x0000_0000_0000_0002, + Atch = 0x0000_0000_0000_0004, + Atex = 0x0000_0000_0000_0008, + Avfx = 0x0000_0000_0000_0010, + Awt = 0x0000_0000_0000_0020, + Cmp = 0x0000_0000_0000_0040, + Dic = 0x0000_0000_0000_0080, + Eid = 0x0000_0000_0000_0100, + Envb = 0x0000_0000_0000_0200, + Eqdp = 0x0000_0000_0000_0400, + Eqp = 0x0000_0000_0000_0800, + Essb = 0x0000_0000_0000_1000, + Est = 0x0000_0000_0000_2000, + Evp = 0x0000_0000_0000_4000, + Exd = 0x0000_0000_0000_8000, + Exh = 0x0000_0000_0001_0000, + Exl = 0x0000_0000_0002_0000, + Fdt = 0x0000_0000_0004_0000, + Gfd = 0x0000_0000_0008_0000, + Ggd = 0x0000_0000_0010_0000, + Gmp = 0x0000_0000_0020_0000, + Gzd = 0x0000_0000_0040_0000, + Imc = 0x0000_0000_0080_0000, + Lcb = 0x0000_0000_0100_0000, + Lgb = 0x0000_0000_0200_0000, + Luab = 0x0000_0000_0400_0000, + Lvb = 0x0000_0000_0800_0000, + Mdl = 0x0000_0000_1000_0000, + Mlt = 0x0000_0000_2000_0000, + Mtrl = 0x0000_0000_4000_0000, + Obsb = 0x0000_0000_8000_0000, + Pap = 0x0000_0001_0000_0000, + Pbd = 0x0000_0002_0000_0000, + Pcb = 0x0000_0004_0000_0000, + Phyb = 0x0000_0008_0000_0000, + Plt = 0x0000_0010_0000_0000, + Scd = 0x0000_0020_0000_0000, + Sgb = 0x0000_0040_0000_0000, + Shcd = 0x0000_0080_0000_0000, + Shpk = 0x0000_0100_0000_0000, + Sklb = 0x0000_0200_0000_0000, + Skp = 0x0000_0400_0000_0000, + Stm = 0x0000_0800_0000_0000, + Svb = 0x0000_1000_0000_0000, + Tera = 0x0000_2000_0000_0000, + Tex = 0x0000_4000_0000_0000, + Tmb = 0x0000_8000_0000_0000, + Ugd = 0x0001_0000_0000_0000, + Uld = 0x0002_0000_0000_0000, + Waoe = 0x0004_0000_0000_0000, + Wtd = 0x0008_0000_0000_0000, +} + +[Flags] +public enum ResourceCategoryFlag : ushort +{ + Common = 0x0001, + BgCommon = 0x0002, + Bg = 0x0004, + Cut = 0x0008, + Chara = 0x0010, + Shader = 0x0020, + Ui = 0x0040, + Sound = 0x0080, + Vfx = 0x0100, + UiScript = 0x0200, + Exd = 0x0400, + GameScript = 0x0800, + Music = 0x1000, + SqpackTest = 0x2000, +} + +public static class ResourceExtensions +{ + public static readonly ResourceTypeFlag AllResourceTypes = Enum.GetValues().Aggregate((v, f) => v | f); + public static readonly ResourceCategoryFlag AllResourceCategories = Enum.GetValues().Aggregate((v, f) => v | f); + + public static ResourceTypeFlag ToFlag(this ResourceType type) + => type switch + { + ResourceType.Aet => ResourceTypeFlag.Aet, + ResourceType.Amb => ResourceTypeFlag.Amb, + ResourceType.Atch => ResourceTypeFlag.Atch, + ResourceType.Atex => ResourceTypeFlag.Atex, + ResourceType.Avfx => ResourceTypeFlag.Avfx, + ResourceType.Awt => ResourceTypeFlag.Awt, + ResourceType.Cmp => ResourceTypeFlag.Cmp, + ResourceType.Dic => ResourceTypeFlag.Dic, + ResourceType.Eid => ResourceTypeFlag.Eid, + ResourceType.Envb => ResourceTypeFlag.Envb, + ResourceType.Eqdp => ResourceTypeFlag.Eqdp, + ResourceType.Eqp => ResourceTypeFlag.Eqp, + ResourceType.Essb => ResourceTypeFlag.Essb, + ResourceType.Est => ResourceTypeFlag.Est, + ResourceType.Evp => ResourceTypeFlag.Evp, + ResourceType.Exd => ResourceTypeFlag.Exd, + ResourceType.Exh => ResourceTypeFlag.Exh, + ResourceType.Exl => ResourceTypeFlag.Exl, + ResourceType.Fdt => ResourceTypeFlag.Fdt, + ResourceType.Gfd => ResourceTypeFlag.Gfd, + ResourceType.Ggd => ResourceTypeFlag.Ggd, + ResourceType.Gmp => ResourceTypeFlag.Gmp, + ResourceType.Gzd => ResourceTypeFlag.Gzd, + ResourceType.Imc => ResourceTypeFlag.Imc, + ResourceType.Lcb => ResourceTypeFlag.Lcb, + ResourceType.Lgb => ResourceTypeFlag.Lgb, + ResourceType.Luab => ResourceTypeFlag.Luab, + ResourceType.Lvb => ResourceTypeFlag.Lvb, + ResourceType.Mdl => ResourceTypeFlag.Mdl, + ResourceType.Mlt => ResourceTypeFlag.Mlt, + ResourceType.Mtrl => ResourceTypeFlag.Mtrl, + ResourceType.Obsb => ResourceTypeFlag.Obsb, + ResourceType.Pap => ResourceTypeFlag.Pap, + ResourceType.Pbd => ResourceTypeFlag.Pbd, + ResourceType.Pcb => ResourceTypeFlag.Pcb, + ResourceType.Phyb => ResourceTypeFlag.Phyb, + ResourceType.Plt => ResourceTypeFlag.Plt, + ResourceType.Scd => ResourceTypeFlag.Scd, + ResourceType.Sgb => ResourceTypeFlag.Sgb, + ResourceType.Shcd => ResourceTypeFlag.Shcd, + ResourceType.Shpk => ResourceTypeFlag.Shpk, + ResourceType.Sklb => ResourceTypeFlag.Sklb, + ResourceType.Skp => ResourceTypeFlag.Skp, + ResourceType.Stm => ResourceTypeFlag.Stm, + ResourceType.Svb => ResourceTypeFlag.Svb, + ResourceType.Tera => ResourceTypeFlag.Tera, + ResourceType.Tex => ResourceTypeFlag.Tex, + ResourceType.Tmb => ResourceTypeFlag.Tmb, + ResourceType.Ugd => ResourceTypeFlag.Ugd, + ResourceType.Uld => ResourceTypeFlag.Uld, + ResourceType.Waoe => ResourceTypeFlag.Waoe, + ResourceType.Wtd => ResourceTypeFlag.Wtd, + _ => 0, + }; + + public static bool FitsFlag(this ResourceType type, ResourceTypeFlag flags) + => (type.ToFlag() & flags) != 0; + + public static ResourceCategoryFlag ToFlag(this ResourceCategory type) + => type switch + { + ResourceCategory.Common => ResourceCategoryFlag.Common, + ResourceCategory.BgCommon => ResourceCategoryFlag.BgCommon, + ResourceCategory.Bg => ResourceCategoryFlag.Bg, + ResourceCategory.Cut => ResourceCategoryFlag.Cut, + ResourceCategory.Chara => ResourceCategoryFlag.Chara, + ResourceCategory.Shader => ResourceCategoryFlag.Shader, + ResourceCategory.Ui => ResourceCategoryFlag.Ui, + ResourceCategory.Sound => ResourceCategoryFlag.Sound, + ResourceCategory.Vfx => ResourceCategoryFlag.Vfx, + ResourceCategory.UiScript => ResourceCategoryFlag.UiScript, + ResourceCategory.Exd => ResourceCategoryFlag.Exd, + ResourceCategory.GameScript => ResourceCategoryFlag.GameScript, + ResourceCategory.Music => ResourceCategoryFlag.Music, + ResourceCategory.SqpackTest => ResourceCategoryFlag.SqpackTest, + _ => 0, + }; + + public static bool FitsFlag(this ResourceCategory type, ResourceCategoryFlag flags) + => (type.ToFlag() & flags) != 0; + + public static ResourceType FromBytes(byte a1, byte a2, byte a3) + => (ResourceType)(((uint)ByteStringFunctions.AsciiToLower(a1) << 16) + | ((uint)ByteStringFunctions.AsciiToLower(a2) << 8) + | ByteStringFunctions.AsciiToLower(a3)); + + public static ResourceType FromBytes(byte a1, byte a2, byte a3, byte a4) + => (ResourceType)(((uint)ByteStringFunctions.AsciiToLower(a1) << 24) + | ((uint)ByteStringFunctions.AsciiToLower(a2) << 16) + | ((uint)ByteStringFunctions.AsciiToLower(a3) << 8) + | ByteStringFunctions.AsciiToLower(a4)); + + public static ResourceType FromBytes(char a1, char a2, char a3) + => FromBytes((byte)a1, (byte)a2, (byte)a3); + + public static ResourceType FromBytes(char a1, char a2, char a3, char a4) + => FromBytes((byte)a1, (byte)a2, (byte)a3, (byte)a4); + + public static ResourceType Type(string path) + { + var ext = Path.GetExtension(path.AsSpan()); + ext = ext.Length == 0 ? path.AsSpan() : ext[1..]; + + return ext.Length switch + { + 0 => 0, + 1 => (ResourceType)ext[^1], + 2 => FromBytes('\0', ext[^2], ext[^1]), + 3 => FromBytes(ext[^3], ext[^2], ext[^1]), + _ => FromBytes(ext[^4], ext[^3], ext[^2], ext[^1]), + }; + } + + public static ResourceType Type(ByteString path) + { + var extIdx = path.LastIndexOf((byte)'.'); + var ext = extIdx == -1 ? path : extIdx == path.Length - 1 ? ByteString.Empty : path.Substring(extIdx + 1); + + return ext.Length switch + { + 0 => 0, + 1 => (ResourceType)ext[^1], + 2 => FromBytes(0, ext[^2], ext[^1]), + 3 => FromBytes(ext[^3], ext[^2], ext[^1]), + _ => FromBytes(ext[^4], ext[^3], ext[^2], ext[^1]), + }; + } + + public static ResourceCategory Category(ByteString path) + { + if (path.Length < 3) + return ResourceCategory.Debug; + + return ByteStringFunctions.AsciiToUpper(path[0]) switch + { + (byte)'C' => ByteStringFunctions.AsciiToUpper(path[1]) switch + { + (byte)'O' => ResourceCategory.Common, + (byte)'U' => ResourceCategory.Cut, + (byte)'H' => ResourceCategory.Chara, + _ => ResourceCategory.Debug, + }, + (byte)'B' => ByteStringFunctions.AsciiToUpper(path[2]) switch + { + (byte)'C' => ResourceCategory.BgCommon, + (byte)'/' => ResourceCategory.Bg, + _ => ResourceCategory.Debug, + }, + (byte)'S' => ByteStringFunctions.AsciiToUpper(path[1]) switch + { + (byte)'H' => ResourceCategory.Shader, + (byte)'O' => ResourceCategory.Sound, + (byte)'Q' => ResourceCategory.SqpackTest, + _ => ResourceCategory.Debug, + }, + (byte)'U' => ByteStringFunctions.AsciiToUpper(path[2]) switch + { + (byte)'/' => ResourceCategory.Ui, + (byte)'S' => ResourceCategory.UiScript, + _ => ResourceCategory.Debug, + }, + (byte)'V' => ResourceCategory.Vfx, + (byte)'E' => ResourceCategory.Exd, + (byte)'G' => ResourceCategory.GameScript, + (byte)'M' => ResourceCategory.Music, + _ => ResourceCategory.Debug, + }; + } +} diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index 51612819..616cb2f6 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -4,8 +4,8 @@ using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Collections; +using Penumbra.Api.Enums; using Penumbra.GameData; -using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 6afaf5d1..40984c6a 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -3,6 +3,7 @@ using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using Penumbra.Collections; +using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 4494dc77..20713fe7 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -3,7 +3,6 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; -using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.String; diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 00b06963..a8fd816a 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,8 +1,8 @@ using Dalamud.Hooking; using Dalamud.Utility.Signatures; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData; -using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 5d5e4590..94fdcce4 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,6 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs index 0b29ee10..ce7d3d4c 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs @@ -3,8 +3,8 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; using FFXIVClientStructs.STD; +using Penumbra.Api.Enums; using Penumbra.GameData; -using Penumbra.GameData.Enums; namespace Penumbra.Interop.ResourceLoading; diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 8b4a5d15..5d060d85 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -1,9 +1,9 @@ using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData; -using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/ResourceLoading/TexMdlService.cs index 6dac0e6b..574da240 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/ResourceLoading/TexMdlService.cs @@ -1,8 +1,8 @@ using Dalamud.Hooking; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Penumbra.Api.Enums; using Penumbra.GameData; -using Penumbra.GameData.Enums; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceLoading; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 0bbe8e66..972e3c55 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -1,6 +1,7 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData; using Penumbra.GameData.Enums; diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index c3327a9e..2fffaedd 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -1,4 +1,4 @@ -using Penumbra.GameData.Enums; +using Penumbra.Api.Enums; using Penumbra.String.Classes; using ChangedItemIcon = Penumbra.UI.ChangedItemDrawer.ChangedItemIcon; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index a8ad9d4f..161e0368 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -12,9 +12,12 @@ namespace Penumbra.Interop.ResourceTree; public class ResourceTree { public readonly string Name; + public readonly int GameObjectIndex; public readonly nint GameObjectAddress; public readonly nint DrawObjectAddress; + public readonly bool LocalPlayerRelated; public readonly bool PlayerRelated; + public readonly bool Networked; public readonly string CollectionName; public readonly List Nodes; public readonly HashSet FlatNodes; @@ -23,15 +26,18 @@ public class ResourceTree public CustomizeData CustomizeData; public GenderRace RaceCode; - public ResourceTree(string name, nint gameObjectAddress, nint drawObjectAddress, bool playerRelated, string collectionName) + public ResourceTree(string name, int gameObjectIndex, nint gameObjectAddress, nint drawObjectAddress, bool localPlayerRelated, bool playerRelated, bool networked, string collectionName) { - Name = name; - GameObjectAddress = gameObjectAddress; - DrawObjectAddress = drawObjectAddress; - PlayerRelated = playerRelated; - CollectionName = collectionName; - Nodes = new List(); - FlatNodes = new HashSet(); + Name = name; + GameObjectIndex = gameObjectIndex; + GameObjectAddress = gameObjectAddress; + DrawObjectAddress = drawObjectAddress; + LocalPlayerRelated = localPlayerRelated; + Networked = networked; + PlayerRelated = playerRelated; + CollectionName = collectionName; + Nodes = new List(); + FlatNodes = new HashSet(); } internal unsafe void LoadResources(GlobalResolveContext globalContext) @@ -64,7 +70,7 @@ public class ResourceTree AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); - if (character->GameObject.GetObjectKind() == (byte)ObjectKind.Pc) + if (model->GetModelType() == CharacterBase.ModelType.Human) AddHumanResources(globalContext, (HumanExt*)model); } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs new file mode 100644 index 00000000..e7d9abc2 --- /dev/null +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -0,0 +1,104 @@ +using Dalamud.Game.ClientState.Objects.Types; +using Penumbra.Api.Enums; +using Penumbra.UI; + +namespace Penumbra.Interop.ResourceTree; + +internal static class ResourceTreeApiHelper +{ + public static Dictionary> GetResourcePathDictionaries(IEnumerable<(Character, ResourceTree)> resourceTrees, + bool mergeSameCollection) + => mergeSameCollection ? GetResourcePathDictionariesMerged(resourceTrees) : GetResourcePathDictionariesUnmerged(resourceTrees); + + private static Dictionary> GetResourcePathDictionariesMerged(IEnumerable<(Character, ResourceTree)> resourceTrees) + { + var collections = new Dictionary(4); + var pathDictionaries = new Dictionary>>(4); + + foreach (var (gameObject, resourceTree) in resourceTrees) + { + if (collections.ContainsKey(gameObject.ObjectIndex)) + continue; + + collections.Add(gameObject.ObjectIndex, resourceTree.CollectionName); + if (!pathDictionaries.TryGetValue(resourceTree.CollectionName, out var pathDictionary)) + { + pathDictionary = new(); + pathDictionaries.Add(resourceTree.CollectionName, pathDictionary); + } + + CollectResourcePaths(pathDictionary, resourceTree); + } + + var pathRODictionaries = pathDictionaries.ToDictionary(pair => pair.Key, + pair => (IReadOnlyDictionary)pair.Value.ToDictionary(pair => pair.Key, pair => pair.Value.ToArray()).AsReadOnly()); + + return collections.ToDictionary(pair => pair.Key, pair => pathRODictionaries[pair.Value]); + } + + private static Dictionary> GetResourcePathDictionariesUnmerged(IEnumerable<(Character, ResourceTree)> resourceTrees) + { + var pathDictionaries = new Dictionary>>(4); + + foreach (var (gameObject, resourceTree) in resourceTrees) + { + if (pathDictionaries.ContainsKey(gameObject.ObjectIndex)) + continue; + + var pathDictionary = new Dictionary>(); + pathDictionaries.Add(gameObject.ObjectIndex, pathDictionary); + + CollectResourcePaths(pathDictionary, resourceTree); + } + + return pathDictionaries.ToDictionary(pair => pair.Key, + pair => (IReadOnlyDictionary)pair.Value.ToDictionary(pair => pair.Key, pair => pair.Value.ToArray()).AsReadOnly()); + } + + private static void CollectResourcePaths(Dictionary> pathDictionary, ResourceTree resourceTree) + { + foreach (var node in resourceTree.FlatNodes) + { + if (node.PossibleGamePaths.Length == 0) + continue; + + var fullPath = node.FullPath.ToPath(); + if (!pathDictionary.TryGetValue(fullPath, out var gamePaths)) + { + gamePaths = new(); + pathDictionary.Add(fullPath, gamePaths); + } + + foreach (var gamePath in node.PossibleGamePaths) + gamePaths.Add(gamePath.ToString()); + } + } + + public static Dictionary> GetResourcesOfType(IEnumerable<(Character, ResourceTree)> resourceTrees, + ResourceType type) + { + var resDictionaries = new Dictionary>(4); + foreach (var (gameObject, resourceTree) in resourceTrees) + { + if (resDictionaries.ContainsKey(gameObject.ObjectIndex)) + continue; + + var resDictionary = new Dictionary(); + resDictionaries.Add(gameObject.ObjectIndex, resDictionary); + + foreach (var node in resourceTree.FlatNodes) + { + if (node.Type != type) + continue; + if (resDictionary.ContainsKey(node.ResourceHandle)) + continue; + + var fullPath = node.FullPath.ToPath(); + resDictionary.Add(node.ResourceHandle, (fullPath, node.Name ?? string.Empty, ChangedItemDrawer.ToApiIcon(node.Icon))); + } + } + + return resDictionaries.ToDictionary(pair => pair.Key, + pair => (IReadOnlyDictionary)pair.Value.AsReadOnly()); + } +} diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index a2e29e48..e3418e5b 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -27,21 +27,35 @@ public class ResourceTreeFactory _actors = actors; } - public ResourceTree[] FromObjectTable(bool withNames = true, bool redactExternalPaths = true) - { - var cache = new TreeBuildCache(_objects, _gameData); + private TreeBuildCache CreateTreeBuildCache() + => new(_objects, _gameData, _actors); - return cache.Characters - .Select(c => FromCharacter(c, cache, withNames, redactExternalPaths)) - .OfType() - .ToArray(); + public IEnumerable GetLocalPlayerRelatedCharacters() + { + var cache = CreateTreeBuildCache(); + + return cache.Characters.Where(cache.IsLocalPlayerRelated); + } + + public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromObjectTable( + bool localPlayerRelatedOnly = false, bool withUIData = true, bool redactExternalPaths = true) + { + var cache = CreateTreeBuildCache(); + var characters = localPlayerRelatedOnly ? cache.Characters.Where(cache.IsLocalPlayerRelated) : cache.Characters; + + foreach (var character in characters) + { + var tree = FromCharacter(character, cache, withUIData, redactExternalPaths); + if (tree != null) + yield return (character, tree); + } } public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromCharacters( IEnumerable characters, bool withUIData = true, bool redactExternalPaths = true) { - var cache = new TreeBuildCache(_objects, _gameData); + var cache = CreateTreeBuildCache(); foreach (var character in characters) { var tree = FromCharacter(character, cache, withUIData, redactExternalPaths); @@ -52,7 +66,7 @@ public class ResourceTreeFactory public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, bool withUIData = true, bool redactExternalPaths = true) - => FromCharacter(character, new TreeBuildCache(_objects, _gameData), withUIData, redactExternalPaths); + => FromCharacter(character, CreateTreeBuildCache(), withUIData, redactExternalPaths); private unsafe ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache, bool withUIData = true, bool redactExternalPaths = true) @@ -69,8 +83,10 @@ public class ResourceTreeFactory if (!collectionResolveData.Valid) return null; - var (name, related) = GetCharacterName(character, cache); - var tree = new ResourceTree(name, (nint)gameObjStruct, (nint)drawObjStruct, related, collectionResolveData.ModCollection.Name); + var localPlayerRelated = cache.IsLocalPlayerRelated(character); + var (name, related) = GetCharacterName(character, cache); + var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; + var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name); var globalContext = new GlobalResolveContext(_config, _identifier.AwaitedService, cache, collectionResolveData.ModCollection, ((Character*)gameObjStruct)->CharacterData.ModelCharaId, withUIData, redactExternalPaths); tree.LoadResources(globalContext); diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 43b25476..60714fbb 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -1,6 +1,8 @@ using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using Penumbra.GameData.Files; +using Penumbra.Interop.Services; +using Penumbra.Services; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; @@ -8,18 +10,38 @@ namespace Penumbra.Interop.ResourceTree; internal class TreeBuildCache { private readonly IDataManager _dataManager; + private readonly ActorService _actors; private readonly Dictionary _shaderPackages = new(); + private readonly uint _localPlayerId; public readonly List Characters; public readonly Dictionary CharactersById; - public TreeBuildCache(IObjectTable objects, IDataManager dataManager) + public TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorService actors) { - _dataManager = dataManager; - Characters = objects.Where(c => c is Character ch && ch.IsValid()).Cast().ToList(); + _dataManager = dataManager; + _actors = actors; + Characters = objects.OfType().Where(ch => ch.IsValid()).ToList(); CharactersById = Characters .Where(c => c.ObjectId != GameObject.InvalidGameObjectId) .GroupBy(c => c.ObjectId) .ToDictionary(c => c.Key, c => c.First()); + _localPlayerId = Characters.Count > 0 && Characters[0].ObjectIndex == 0 ? Characters[0].ObjectId : GameObject.InvalidGameObjectId; + } + + public unsafe bool IsLocalPlayerRelated(Character character) + { + if (_localPlayerId == GameObject.InvalidGameObjectId) + return false; + + // Index 0 is the local player, index 1 is the mount/minion/accessory. + if (character.ObjectIndex < 2 || character.ObjectIndex == RedrawService.GPosePlayerIdx) + return true; + + if (!_actors.AwaitedService.FromObject(character, out var owner, true, false, false).IsValid) + return false; + + // Check for SMN/SCH pet, chocobo and other owned NPCs. + return owner != null && owner->ObjectID == _localPlayerId; } /// Try to read a shpk file from the given path and cache it on success. diff --git a/Penumbra/Interop/Services/DecalReverter.cs b/Penumbra/Interop/Services/DecalReverter.cs index 18c88766..17d8d2e0 100644 --- a/Penumbra/Interop/Services/DecalReverter.cs +++ b/Penumbra/Interop/Services/DecalReverter.cs @@ -1,6 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index dba113f3..1b78e857 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -1,8 +1,8 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; using Penumbra.GameData; -using Penumbra.GameData.Enums; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index b9200a24..acd6eae9 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -1,3 +1,4 @@ +using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index d95c8796..3d8ab1b6 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -1,3 +1,4 @@ +using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 0140d189..7c2f50c4 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -1,5 +1,6 @@ using System.Diagnostics.CodeAnalysis; -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; +using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; diff --git a/Penumbra/Mods/ItemSwap/Swaps.cs b/Penumbra/Mods/ItemSwap/Swaps.cs index 0fa81a52..27935ffb 100644 --- a/Penumbra/Mods/ItemSwap/Swaps.cs +++ b/Penumbra/Mods/ItemSwap/Swaps.cs @@ -1,7 +1,7 @@ +using Penumbra.Api.Enums; using Penumbra.GameData.Files; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; -using Penumbra.GameData.Enums; using Penumbra.Meta; using static Penumbra.Mods.ItemSwap.ItemSwap; using Penumbra.Services; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index ec433113..0cda8f59 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -90,6 +90,10 @@ + + + + diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 5f09e584..2d474a83 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -40,8 +40,6 @@ public class ResourceTreeViewer if (!child) return; - var textColorNonPlayer = ImGui.GetColorU32(ImGuiCol.Text); - var textColorPlayer = (textColorNonPlayer & 0xFF000000u) | ((textColorNonPlayer & 0x00FEFEFE) >> 1) | 0x8000u; // Half green if (!_task.IsCompleted) { ImGui.NewLine(); @@ -55,17 +53,30 @@ public class ResourceTreeViewer } else if (_task.IsCompletedSuccessfully) { + var debugMode = _config.DebugMode; foreach (var (tree, index) in _task.Result.WithIndex()) { - using (var c = ImRaii.PushColor(ImGuiCol.Text, tree.PlayerRelated ? textColorPlayer : textColorNonPlayer)) + var headerColorId = + tree.LocalPlayerRelated ? ColorId.ResTreeLocalPlayer : + tree.PlayerRelated ? ColorId.ResTreePlayer : + tree.Networked ? ColorId.ResTreeNetworked : + ColorId.ResTreeNonNetworked; + using (var c = ImRaii.PushColor(ImGuiCol.Text, headerColorId.Value())) { - if (!ImGui.CollapsingHeader($"{tree.Name}##{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0)) + var isOpen = ImGui.CollapsingHeader($"{tree.Name}##{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); + if (debugMode) + { + using var _ = ImRaii.PushFont(UiBuilder.MonoFont); + ImGuiUtil.HoverTooltip( + $"Object Index: {tree.GameObjectIndex}\nObject Address: 0x{tree.GameObjectAddress:X16}\nDraw Object Address: 0x{tree.DrawObjectAddress:X16}"); + } + if (!isOpen) continue; } using var id = ImRaii.PushId(index); - ImGui.Text($"Collection: {tree.CollectionName}"); + ImGui.TextUnformatted($"Collection: {tree.CollectionName}"); using var table = ImRaii.Table("##ResourceTree", _actionCapacity > 0 ? 4 : 3, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); @@ -90,7 +101,9 @@ public class ResourceTreeViewer { try { - return _treeFactory.FromObjectTable(); + return _treeFactory.FromObjectTable() + .Select(entry => entry.ResourceTree) + .ToArray(); } finally { diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 91d81ea3..13a5787e 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -15,6 +15,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Services; using Penumbra.UI.Classes; +using ApiChangedItemIcon = Penumbra.Api.Enums.ChangedItemIcon; namespace Penumbra.UI; @@ -311,6 +312,29 @@ public class ChangedItemDrawer : IDisposable _ => "Other", }; + internal static ApiChangedItemIcon ToApiIcon(ChangedItemIcon icon) + => icon switch + { + ChangedItemIcon.Head => ApiChangedItemIcon.Head, + ChangedItemIcon.Body => ApiChangedItemIcon.Body, + ChangedItemIcon.Hands => ApiChangedItemIcon.Hands, + ChangedItemIcon.Legs => ApiChangedItemIcon.Legs, + ChangedItemIcon.Feet => ApiChangedItemIcon.Feet, + ChangedItemIcon.Ears => ApiChangedItemIcon.Ears, + ChangedItemIcon.Neck => ApiChangedItemIcon.Neck, + ChangedItemIcon.Wrists => ApiChangedItemIcon.Wrists, + ChangedItemIcon.Finger => ApiChangedItemIcon.Finger, + ChangedItemIcon.Monster => ApiChangedItemIcon.Monster, + ChangedItemIcon.Demihuman => ApiChangedItemIcon.Demihuman, + ChangedItemIcon.Customization => ApiChangedItemIcon.Customization, + ChangedItemIcon.Action => ApiChangedItemIcon.Action, + ChangedItemIcon.Emote => ApiChangedItemIcon.Emote, + ChangedItemIcon.Mainhand => ApiChangedItemIcon.Mainhand, + ChangedItemIcon.Offhand => ApiChangedItemIcon.Offhand, + ChangedItemIcon.Unknown => ApiChangedItemIcon.Unknown, + _ => ApiChangedItemIcon.None, + }; + /// Apply Changed Item Counters to the Name if necessary. private static string ChangedItemName(string name, object? data) => data is int counter ? $"{counter} Files Manipulating {name}s" : name; diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index ebcff821..0e3b9377 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -24,10 +24,16 @@ public enum ColorId NoAssignment, SelectorPriority, InGameHighlight, + ResTreeLocalPlayer, + ResTreePlayer, + ResTreeNetworked, + ResTreeNonNetworked, } public static class Colors { + // These are written as 0xAABBGGRR. + public const uint PressEnterWarningBg = 0xFF202080; public const uint RegexWarningBorder = 0xFF0000B0; public const uint MetaInfoText = 0xAAFFFFFF; @@ -64,6 +70,10 @@ public static class Colors ColorId.NoAssignment => ( 0x00000000, "Unassigned Collection Assignment", "A collection assignment that is not configured to any collection and thus just has no specific treatment."), ColorId.SelectorPriority => ( 0xFF808080, "Mod Selector Priority", "The priority displayed for non-zero priority mods in the mod selector."), ColorId.InGameHighlight => ( 0xFFEBCF89, "In-Game Highlight", "An in-game element that has been highlighted for ease of editing."), + ColorId.ResTreeLocalPlayer => ( 0xFFFFE0A0, "On-Screen: You", "You and what you own (mount, minion, accessory, pets and so on), in the On-Screen tab." ), + ColorId.ResTreePlayer => ( 0xFFC0FFC0, "On-Screen: Other Players", "Other players and what they own, in the On-Screen tab." ), + ColorId.ResTreeNetworked => ( 0xFFFFFFFF, "On-Screen: Non-Players (Networked)", "Non-player entities handled by the game server, in the On-Screen tab." ), + ColorId.ResTreeNonNetworked => ( 0xFFC0C0FF, "On-Screen: Non-Players (Local)", "Non-player entities handled locally, in the On-Screen tab." ), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index dea68955..1a25d722 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Collections; +using Penumbra.Enums; using Penumbra.Interop.Structs; using Penumbra.String; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 781c5fc1..de5a179d 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -4,9 +4,9 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using ImGuiNET; using OtterGui.Raii; using OtterGui.Widgets; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData.Actors; -using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.Services; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index eb034459..3789baf4 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -4,6 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Table; +using Penumbra.Enums; using Penumbra.String; namespace Penumbra.UI.ResourceWatcher; From 22966e648d84b26ce3ce39fefa2efde237044b04 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 18 Sep 2023 02:01:22 +0200 Subject: [PATCH 0102/1381] ResourceTree IPC: Remove mergeSameCollection. --- Penumbra/Api/IpcTester.cs | 12 +++---- Penumbra/Api/PenumbraApi.cs | 8 ++--- Penumbra/Api/PenumbraIpcProviders.cs | 4 +-- .../ResourceTree/ResourceTreeApiHelper.cs | 32 +------------------ 4 files changed, 12 insertions(+), 44 deletions(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index fb8719f4..86719160 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -1408,10 +1408,9 @@ public class IpcTester : IDisposable private readonly DalamudPluginInterface _pi; private readonly IObjectTable _objects; - private string _gameObjectIndices = "0"; - private bool _mergeSameCollection = false; - private ResourceType _type = ResourceType.Mtrl; - private bool _withUIData = false; + private string _gameObjectIndices = "0"; + private ResourceType _type = ResourceType.Mtrl; + private bool _withUIData = false; private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcePaths; private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcePaths; @@ -1431,7 +1430,6 @@ public class IpcTester : IDisposable return; ImGui.InputText("GameObject indices", ref _gameObjectIndices, 511); - ImGui.Checkbox("Merge entries that use the same collection", ref _mergeSameCollection); ImGuiUtil.GenericEnumCombo("Resource type", ImGui.CalcItemWidth(), _type, out _type, Enum.GetValues()); ImGui.Checkbox("Also get names and icons", ref _withUIData); @@ -1443,7 +1441,7 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourcePaths")) { var gameObjects = GetSelectedGameObjects(); - var resourcePaths = Ipc.GetGameObjectResourcePaths.Subscriber(_pi).Invoke(gameObjects, _mergeSameCollection); + var resourcePaths = Ipc.GetGameObjectResourcePaths.Subscriber(_pi).Invoke(gameObjects); _lastGameObjectResourcePaths = gameObjects .Select(GameObjectToString) @@ -1456,7 +1454,7 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcePaths.Label, "Get local player resource paths"); if (ImGui.Button("Get##PlayerResourcePaths")) { - _lastPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Subscriber(_pi).Invoke(_mergeSameCollection) + _lastPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Subscriber(_pi).Invoke() .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) .ToArray(); diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 1c56b9df..0572d868 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1016,19 +1016,19 @@ public class PenumbraApi : IDisposable, IPenumbraApi }; // @formatter:on - public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects, bool mergeSameCollection) + public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects) { var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, false, false); - var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees, mergeSameCollection); + var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); return Array.ConvertAll(gameObjects, obj => pathDictionaries.TryGetValue(obj, out var pathDict) ? pathDict : null); } - public IReadOnlyDictionary> GetPlayerResourcePaths(bool mergeSameCollection) + public IReadOnlyDictionary> GetPlayerResourcePaths() { var resourceTrees = _resourceTreeFactory.FromObjectTable(true, false, false); - var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees, mergeSameCollection); + var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); return pathDictionaries.AsReadOnly(); } diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index c05a7c47..aca57aac 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -119,8 +119,8 @@ public class PenumbraIpcProviders : IDisposable internal readonly FuncProvider RemoveTemporaryMod; // Resource Tree - internal readonly FuncProvider?[]> GetGameObjectResourcePaths; - internal readonly FuncProvider>> GetPlayerResourcePaths; + internal readonly FuncProvider?[]> GetGameObjectResourcePaths; + internal readonly FuncProvider>> GetPlayerResourcePaths; internal readonly FuncProvider?[]> GetGameObjectResourcesOfType; internal readonly FuncProvider>> GetPlayerResourcesOfType; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index e7d9abc2..6c1e4d1e 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -6,37 +6,7 @@ namespace Penumbra.Interop.ResourceTree; internal static class ResourceTreeApiHelper { - public static Dictionary> GetResourcePathDictionaries(IEnumerable<(Character, ResourceTree)> resourceTrees, - bool mergeSameCollection) - => mergeSameCollection ? GetResourcePathDictionariesMerged(resourceTrees) : GetResourcePathDictionariesUnmerged(resourceTrees); - - private static Dictionary> GetResourcePathDictionariesMerged(IEnumerable<(Character, ResourceTree)> resourceTrees) - { - var collections = new Dictionary(4); - var pathDictionaries = new Dictionary>>(4); - - foreach (var (gameObject, resourceTree) in resourceTrees) - { - if (collections.ContainsKey(gameObject.ObjectIndex)) - continue; - - collections.Add(gameObject.ObjectIndex, resourceTree.CollectionName); - if (!pathDictionaries.TryGetValue(resourceTree.CollectionName, out var pathDictionary)) - { - pathDictionary = new(); - pathDictionaries.Add(resourceTree.CollectionName, pathDictionary); - } - - CollectResourcePaths(pathDictionary, resourceTree); - } - - var pathRODictionaries = pathDictionaries.ToDictionary(pair => pair.Key, - pair => (IReadOnlyDictionary)pair.Value.ToDictionary(pair => pair.Key, pair => pair.Value.ToArray()).AsReadOnly()); - - return collections.ToDictionary(pair => pair.Key, pair => pathRODictionaries[pair.Value]); - } - - private static Dictionary> GetResourcePathDictionariesUnmerged(IEnumerable<(Character, ResourceTree)> resourceTrees) + public static Dictionary> GetResourcePathDictionaries(IEnumerable<(Character, ResourceTree)> resourceTrees) { var pathDictionaries = new Dictionary>>(4); From a241b933ca75424d8d99943b8ccd663d70f15f0d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 18 Sep 2023 12:35:41 +0200 Subject: [PATCH 0103/1381] ResourceTree: Avoid enumerating the whole object table in some cases --- Penumbra/Api/PenumbraApi.cs | 8 ++-- .../ResourceTree/ResourceTreeFactory.cs | 40 +++++++++++-------- .../Interop/ResourceTree/TreeBuildCache.cs | 22 ++++++---- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 7 +++- 4 files changed, 48 insertions(+), 29 deletions(-) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 0572d868..4a31199c 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1019,7 +1019,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects) { var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, false, false); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, 0); var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); return Array.ConvertAll(gameObjects, obj => pathDictionaries.TryGetValue(obj, out var pathDict) ? pathDict : null); @@ -1027,7 +1027,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary> GetPlayerResourcePaths() { - var resourceTrees = _resourceTreeFactory.FromObjectTable(true, false, false); + var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly); var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); return pathDictionaries.AsReadOnly(); @@ -1036,7 +1036,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ushort[] gameObjects, ResourceType type, bool withUIData) { var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData, false); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUIData : 0); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); return Array.ConvertAll(gameObjects, obj => resDictionaries.TryGetValue(obj, out var resDict) ? resDict : null); @@ -1044,7 +1044,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary> GetPlayerResourcesOfType(ResourceType type, bool withUIData) { - var resourceTrees = _resourceTreeFactory.FromObjectTable(true, withUIData, false); + var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly | (withUIData ? ResourceTreeFactory.Flags.WithUIData : 0)); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); return resDictionaries.AsReadOnly(); diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index e3418e5b..1d91948d 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -27,49 +27,46 @@ public class ResourceTreeFactory _actors = actors; } - private TreeBuildCache CreateTreeBuildCache() - => new(_objects, _gameData, _actors); + private TreeBuildCache CreateTreeBuildCache(bool withCharacters) + => new(_objects, _gameData, _actors, withCharacters); public IEnumerable GetLocalPlayerRelatedCharacters() { - var cache = CreateTreeBuildCache(); + var cache = CreateTreeBuildCache(true); return cache.Characters.Where(cache.IsLocalPlayerRelated); } public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromObjectTable( - bool localPlayerRelatedOnly = false, bool withUIData = true, bool redactExternalPaths = true) + Flags flags) { - var cache = CreateTreeBuildCache(); - var characters = localPlayerRelatedOnly ? cache.Characters.Where(cache.IsLocalPlayerRelated) : cache.Characters; + var cache = CreateTreeBuildCache(true); + var characters = (flags & Flags.LocalPlayerRelatedOnly) != 0 ? cache.Characters.Where(cache.IsLocalPlayerRelated) : cache.Characters; foreach (var character in characters) { - var tree = FromCharacter(character, cache, withUIData, redactExternalPaths); + var tree = FromCharacter(character, cache, flags); if (tree != null) yield return (character, tree); } } public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromCharacters( - IEnumerable characters, - bool withUIData = true, bool redactExternalPaths = true) + IEnumerable characters, Flags flags) { - var cache = CreateTreeBuildCache(); + var cache = CreateTreeBuildCache((flags & Flags.WithOwnership) != 0); foreach (var character in characters) { - var tree = FromCharacter(character, cache, withUIData, redactExternalPaths); + var tree = FromCharacter(character, cache, flags); if (tree != null) yield return (character, tree); } } - public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, bool withUIData = true, - bool redactExternalPaths = true) - => FromCharacter(character, CreateTreeBuildCache(), withUIData, redactExternalPaths); + public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, Flags flags) + => FromCharacter(character, CreateTreeBuildCache((flags & Flags.WithOwnership) != 0), flags); - private unsafe ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache, - bool withUIData = true, bool redactExternalPaths = true) + private unsafe ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache, Flags flags) { if (!character.IsValid()) return null; @@ -88,7 +85,7 @@ public class ResourceTreeFactory var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name); var globalContext = new GlobalResolveContext(_config, _identifier.AwaitedService, cache, collectionResolveData.ModCollection, - ((Character*)gameObjStruct)->CharacterData.ModelCharaId, withUIData, redactExternalPaths); + ((Character*)gameObjStruct)->CharacterData.ModelCharaId, (flags & Flags.WithUIData) != 0, (flags & Flags.RedactExternalPaths) != 0); tree.LoadResources(globalContext); tree.FlatNodes.UnionWith(globalContext.Nodes.Values); return tree; @@ -119,4 +116,13 @@ public class ResourceTreeFactory return (name, playerRelated); } + + [Flags] + public enum Flags + { + RedactExternalPaths = 1, + WithUIData = 2, + LocalPlayerRelatedOnly = 4, + WithOwnership = 8, + } } diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 60714fbb..d889cf5d 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -16,16 +16,24 @@ internal class TreeBuildCache public readonly List Characters; public readonly Dictionary CharactersById; - public TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorService actors) + public TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorService actors, bool withCharacters) { _dataManager = dataManager; _actors = actors; - Characters = objects.OfType().Where(ch => ch.IsValid()).ToList(); - CharactersById = Characters - .Where(c => c.ObjectId != GameObject.InvalidGameObjectId) - .GroupBy(c => c.ObjectId) - .ToDictionary(c => c.Key, c => c.First()); - _localPlayerId = Characters.Count > 0 && Characters[0].ObjectIndex == 0 ? Characters[0].ObjectId : GameObject.InvalidGameObjectId; + _localPlayerId = objects[0]?.ObjectId ?? GameObject.InvalidGameObjectId; + if (withCharacters) + { + Characters = objects.OfType().Where(ch => ch.IsValid()).ToList(); + CharactersById = Characters + .Where(c => c.ObjectId != GameObject.InvalidGameObjectId) + .GroupBy(c => c.ObjectId) + .ToDictionary(c => c.Key, c => c.First()); + } + else + { + Characters = new(); + CharactersById = new(); + } } public unsafe bool IsLocalPlayerRelated(Character character) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 2d474a83..3901b431 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -9,6 +9,11 @@ namespace Penumbra.UI.AdvancedWindow; public class ResourceTreeViewer { + private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = + ResourceTreeFactory.Flags.RedactExternalPaths | + ResourceTreeFactory.Flags.WithUIData | + ResourceTreeFactory.Flags.WithOwnership; + private readonly Configuration _config; private readonly ResourceTreeFactory _treeFactory; private readonly ChangedItemDrawer _changedItemDrawer; @@ -101,7 +106,7 @@ public class ResourceTreeViewer { try { - return _treeFactory.FromObjectTable() + return _treeFactory.FromObjectTable(ResourceTreeFactoryFlags) .Select(entry => entry.ResourceTree) .ToArray(); } From ea79469abde85a4d8f8ebfeda3ae9c7334f19bec Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 17:06:16 +0200 Subject: [PATCH 0104/1381] Move IPC Arguments around. --- Penumbra/Api/IpcTester.cs | 2 +- Penumbra/Api/PenumbraApi.cs | 10 ++++++---- Penumbra/Api/PenumbraIpcProviders.cs | 2 +- Penumbra/Configuration.cs | 2 +- Penumbra/UI/Tabs/ConfigTabBar.cs | 5 +++-- 5 files changed, 12 insertions(+), 9 deletions(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 86719160..0abf0cf5 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -1465,7 +1465,7 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourcesOfType")) { var gameObjects = GetSelectedGameObjects(); - var resourcesOfType = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi).Invoke(gameObjects, _type, _withUIData); + var resourcesOfType = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi).Invoke(_type, _withUIData, gameObjects); _lastGameObjectResourcesOfType = gameObjects .Select(GameObjectToString) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 4a31199c..49fa40db 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -24,7 +24,6 @@ using Penumbra.Interop.Services; using Penumbra.UI; using TextureType = Penumbra.Api.Enums.TextureType; using Penumbra.Interop.ResourceTree; -using System.Collections.Immutable; namespace Penumbra.Api; @@ -1033,7 +1032,8 @@ public class PenumbraApi : IDisposable, IPenumbraApi return pathDictionaries.AsReadOnly(); } - public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ushort[] gameObjects, ResourceType type, bool withUIData) + public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ResourceType type, bool withUIData, + params ushort[] gameObjects) { var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUIData : 0); @@ -1042,9 +1042,11 @@ public class PenumbraApi : IDisposable, IPenumbraApi return Array.ConvertAll(gameObjects, obj => resDictionaries.TryGetValue(obj, out var resDict) ? resDict : null); } - public IReadOnlyDictionary> GetPlayerResourcesOfType(ResourceType type, bool withUIData) + public IReadOnlyDictionary> GetPlayerResourcesOfType(ResourceType type, + bool withUIData) { - var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly | (withUIData ? ResourceTreeFactory.Flags.WithUIData : 0)); + var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly + | (withUIData ? ResourceTreeFactory.Flags.WithUIData : 0)); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); return resDictionaries.AsReadOnly(); diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index aca57aac..87de6a0c 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -121,7 +121,7 @@ public class PenumbraIpcProviders : IDisposable // Resource Tree internal readonly FuncProvider?[]> GetGameObjectResourcePaths; internal readonly FuncProvider>> GetPlayerResourcePaths; - internal readonly FuncProvider?[]> GetGameObjectResourcesOfType; + internal readonly FuncProvider?[]> GetGameObjectResourcesOfType; internal readonly FuncProvider>> GetPlayerResourcesOfType; public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 0206d0ae..7c9ae665 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -6,7 +6,7 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Widgets; using Penumbra.Api.Enums; -using Penumbra.GameData.Enums; +using Penumbra.Enums; using Penumbra.Import.Structs; using Penumbra.Interop.Services; using Penumbra.Mods; diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index 60339893..ee66ca86 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -3,6 +3,7 @@ using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Services; +using Watcher = Penumbra.UI.ResourceWatcher.ResourceWatcher; namespace Penumbra.UI.Tabs; @@ -17,7 +18,7 @@ public class ConfigTabBar : IDisposable public readonly EffectiveTab Effective; public readonly DebugTab Debug; public readonly ResourceTab Resource; - public readonly ResourceWatcher Watcher; + public readonly Watcher Watcher; public readonly OnScreenTab OnScreenTab; public readonly ITab[] Tabs; @@ -26,7 +27,7 @@ public class ConfigTabBar : IDisposable public TabType SelectTab = TabType.None; public ConfigTabBar(CommunicatorService communicator, SettingsTab settings, ModsTab mods, CollectionsTab collections, - ChangedItemsTab changedItems, EffectiveTab effective, DebugTab debug, ResourceTab resource, ResourceWatcher watcher, + ChangedItemsTab changedItems, EffectiveTab effective, DebugTab debug, ResourceTab resource, Watcher watcher, OnScreenTab onScreenTab) { _communicator = communicator; From 3905d5b9763ed77ddf05c61bb5b4807964c23fd8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 17:14:16 +0200 Subject: [PATCH 0105/1381] Rename ResourceType file. --- Penumbra/Enums/{ResourceType.cs => ResourceTypeFlag.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Penumbra/Enums/{ResourceType.cs => ResourceTypeFlag.cs} (100%) diff --git a/Penumbra/Enums/ResourceType.cs b/Penumbra/Enums/ResourceTypeFlag.cs similarity index 100% rename from Penumbra/Enums/ResourceType.cs rename to Penumbra/Enums/ResourceTypeFlag.cs From 4ffb69ea31fa84f3b238cb38e96046c17257bb9d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 17:14:42 +0200 Subject: [PATCH 0106/1381] Remove enums folder from csproj?! --- Penumbra/Penumbra.csproj | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 0cda8f59..ec433113 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -90,10 +90,6 @@ - - - - From fee99dd17e67a0b2a836d821eb96a1ce0ed71b63 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 17:18:11 +0200 Subject: [PATCH 0107/1381] Fix params bug. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 22846625..2d34adfb 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 22846625192884c6e9f5ec4429fb579875b519e9 +Subproject commit 2d34adfbd105b10ed456d40aebdd54ad7fc73df7 From 5506dcc3f317ebb09c7486471dbdc560047e07a8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 17:20:19 +0200 Subject: [PATCH 0108/1381] Api nuget version. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 2d34adfb..6cc41dc1 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 2d34adfbd105b10ed456d40aebdd54ad7fc73df7 +Subproject commit 6cc41dc15241417fd72dc46ebca48cf7d2092f53 From 5067ab2bb297f68aaaecff7e4255a60431eaeb04 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Sep 2023 18:18:23 +0200 Subject: [PATCH 0109/1381] Add load state to resource watcher. --- Penumbra/Interop/Structs/ResourceHandle.cs | 12 +++ Penumbra/UI/ResourceWatcher/Record.cs | 6 ++ .../ResourceWatcher/ResourceWatcherTable.cs | 89 +++++++++++++++++++ 3 files changed, 107 insertions(+) diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 1b78e857..3cceb949 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -34,6 +34,15 @@ public unsafe struct ShaderPackageResourceHandle public ShaderPackage* ShaderPackage; } +public enum LoadState : byte +{ + Success = 0x07, + Async = 0x03, + Failure = 0x09, + FailedSubResource = 0x0A, + None = 0xFF, +} + [StructLayout(LayoutKind.Explicit)] public unsafe struct ResourceHandle { @@ -99,6 +108,9 @@ public unsafe struct ResourceHandle [FieldOffset(0x58)] public int FileNameLength; + [FieldOffset(0xA9)] + public LoadState LoadState; + [FieldOffset(0xAC)] public uint RefCount; diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index 1a25d722..0fc51f26 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -30,6 +30,7 @@ internal unsafe struct Record public OptionalBool Synchronously; public OptionalBool ReturnValue; public OptionalBool CustomLoad; + public LoadState LoadState; public static Record CreateRequest(ByteString path, bool sync) => new() @@ -47,6 +48,7 @@ internal unsafe struct Record ReturnValue = OptionalBool.Null, CustomLoad = OptionalBool.Null, AssociatedGameObject = string.Empty, + LoadState = LoadState.None, }; public static Record CreateDefaultLoad(ByteString path, ResourceHandle* handle, ModCollection collection, string associatedGameObject) @@ -67,6 +69,7 @@ internal unsafe struct Record ReturnValue = OptionalBool.Null, CustomLoad = false, AssociatedGameObject = associatedGameObject, + LoadState = handle->LoadState, }; } @@ -87,6 +90,7 @@ internal unsafe struct Record ReturnValue = OptionalBool.Null, CustomLoad = true, AssociatedGameObject = associatedGameObject, + LoadState = handle->LoadState, }; public static Record CreateDestruction(ResourceHandle* handle) @@ -107,6 +111,7 @@ internal unsafe struct Record ReturnValue = OptionalBool.Null, CustomLoad = OptionalBool.Null, AssociatedGameObject = string.Empty, + LoadState = handle->LoadState, }; } @@ -126,5 +131,6 @@ internal unsafe struct Record ReturnValue = ret, CustomLoad = custom, AssociatedGameObject = string.Empty, + LoadState = handle->LoadState, }; } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 3789baf4..89dd42bb 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -5,7 +5,9 @@ using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Table; using Penumbra.Enums; +using Penumbra.Interop.Structs; using Penumbra.String; +using Penumbra.UI.Classes; namespace Penumbra.UI.ResourceWatcher; @@ -24,6 +26,7 @@ internal sealed class ResourceWatcherTable : Table new ResourceCategoryColumn(config) { Label = "Category" }, new ResourceTypeColumn(config) { Label = "Type" }, new HandleColumn { Label = "Resource" }, + new LoadStateColumn { Label = "State" }, new RefCountColumn { Label = "#Ref" }, new DateColumn { Label = "Time" } ) @@ -241,6 +244,92 @@ internal sealed class ResourceWatcherTable : Table } } + private sealed class LoadStateColumn : ColumnFlags + { + public override float Width + => 50 * UiHelpers.Scale; + + [Flags] + public enum LoadStateFlag : byte + { + Success = 0x01, + Async = 0x02, + Failed = 0x04, + FailedSub = 0x08, + Unknown = 0x10, + None = 0xFF, + } + + protected override string[] Names + => new[] + { + "Loaded", + "Loading", + "Failed", + "Dependency Failed", + "Unknown", + "None", + }; + + public LoadStateColumn() + { + AllFlags = Enum.GetValues().Aggregate((v, f) => v | f); + _filterValue = AllFlags; + } + + private LoadStateFlag _filterValue; + + public override LoadStateFlag FilterValue + => _filterValue; + + protected override void SetValue(LoadStateFlag value, bool enable) + { + if (enable) + _filterValue |= value; + else + _filterValue &= ~value; + } + + public override bool FilterFunc(Record item) + => item.LoadState switch + { + LoadState.None => FilterValue.HasFlag(LoadStateFlag.None), + LoadState.Success => FilterValue.HasFlag(LoadStateFlag.Success), + LoadState.Async => FilterValue.HasFlag(LoadStateFlag.Async), + LoadState.Failure => FilterValue.HasFlag(LoadStateFlag.Failed), + LoadState.FailedSubResource => FilterValue.HasFlag(LoadStateFlag.FailedSub), + _ => FilterValue.HasFlag(LoadStateFlag.Unknown), + }; + + public override void DrawColumn(Record item, int _) + { + if (item.LoadState == LoadState.None) + return; + + var (icon, color, tt) = item.LoadState switch + { + LoadState.Success => (FontAwesomeIcon.CheckCircle, ColorId.IncreasedMetaValue.Value(), + $"Successfully loaded ({(byte)item.LoadState})."), + LoadState.Async => (FontAwesomeIcon.Clock, ColorId.FolderLine.Value(), $"Loading asynchronously ({(byte)item.LoadState})."), + LoadState.Failure => (FontAwesomeIcon.Times, ColorId.DecreasedMetaValue.Value(), + $"Failed to load ({(byte)item.LoadState})."), + LoadState.FailedSubResource => (FontAwesomeIcon.ExclamationCircle, ColorId.DecreasedMetaValue.Value(), + $"Dependencies failed to load ({(byte)item.LoadState})."), + _ => (FontAwesomeIcon.QuestionCircle, ColorId.UndefinedMod.Value(), $"Unknown state ({(byte)item.LoadState})."), + }; + using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + { + using var c = ImRaii.PushColor(ImGuiCol.Text, color); + ImGui.TextUnformatted(icon.ToIconString()); + } + + ImGuiUtil.HoverTooltip(tt); + } + + public override int Compare(Record lhs, Record rhs) + => lhs.LoadState.CompareTo(rhs.LoadState); + } + private sealed class HandleColumn : ColumnString { public override float Width From 69012e5ecda8fcfd195f32d8ebedc211ab5ea1a7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 18 Sep 2023 17:51:30 +0000 Subject: [PATCH 0110/1381] [CI] Updating repo.json for testing_0.7.3.11 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 4eafa05f..386fb07a 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.10", + "TestingAssemblyVersion": "0.7.3.11", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.10/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.11/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From f02a37b939dd54d6dc62de544460d6f599204fff Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 19 Sep 2023 01:32:31 +0200 Subject: [PATCH 0111/1381] ResourceTree: Reverse-resolve in bulk --- Penumbra/Api/IpcTester.cs | 39 +++-- .../Interop/ResourceTree/ResolveContext.cs | 153 +++++++----------- Penumbra/Interop/ResourceTree/ResourceNode.cs | 105 ++++++------ Penumbra/Interop/ResourceTree/ResourceTree.cs | 64 ++++++-- .../ResourceTree/ResourceTreeFactory.cs | 120 +++++++++++++- 5 files changed, 311 insertions(+), 170 deletions(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 0abf0cf5..de9ab5a7 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -17,6 +17,7 @@ using Penumbra.UI; using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; using Penumbra.GameData.Enums; +using System.Diagnostics; namespace Penumbra.Api; @@ -1407,6 +1408,7 @@ public class IpcTester : IDisposable { private readonly DalamudPluginInterface _pi; private readonly IObjectTable _objects; + private readonly Stopwatch _stopwatch = new(); private string _gameObjectIndices = "0"; private ResourceType _type = ResourceType.Mtrl; @@ -1416,6 +1418,7 @@ public class IpcTester : IDisposable private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcePaths; private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcesOfType; private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcesOfType; + private TimeSpan _lastCallDuration; public ResourceTree(DalamudPluginInterface pi, IObjectTable objects) { @@ -1441,8 +1444,11 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourcePaths")) { var gameObjects = GetSelectedGameObjects(); - var resourcePaths = Ipc.GetGameObjectResourcePaths.Subscriber(_pi).Invoke(gameObjects); + var subscriber = Ipc.GetGameObjectResourcePaths.Subscriber(_pi); + _stopwatch.Restart(); + var resourcePaths = subscriber.Invoke(gameObjects); + _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcePaths = gameObjects .Select(GameObjectToString) .Zip(resourcePaths) @@ -1454,7 +1460,12 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcePaths.Label, "Get local player resource paths"); if (ImGui.Button("Get##PlayerResourcePaths")) { - _lastPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Subscriber(_pi).Invoke() + var subscriber = Ipc.GetPlayerResourcePaths.Subscriber(_pi); + _stopwatch.Restart(); + var resourcePaths = subscriber.Invoke(); + + _lastCallDuration = _stopwatch.Elapsed; + _lastPlayerResourcePaths = resourcePaths .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) .ToArray(); @@ -1465,8 +1476,11 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourcesOfType")) { var gameObjects = GetSelectedGameObjects(); - var resourcesOfType = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi).Invoke(_type, _withUIData, gameObjects); + var subscriber = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi); + _stopwatch.Restart(); + var resourcesOfType = subscriber.Invoke(_type, _withUIData, gameObjects); + _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcesOfType = gameObjects .Select(GameObjectToString) .Zip(resourcesOfType) @@ -1478,21 +1492,26 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcesOfType.Label, "Get local player resources of type"); if (ImGui.Button("Get##PlayerResourcesOfType")) { - _lastPlayerResourcesOfType = Ipc.GetPlayerResourcesOfType.Subscriber(_pi).Invoke(_type, _withUIData) + var subscriber = Ipc.GetPlayerResourcesOfType.Subscriber(_pi); + _stopwatch.Restart(); + var resourcesOfType = subscriber.Invoke(_type, _withUIData); + + _lastCallDuration = _stopwatch.Elapsed; + _lastPlayerResourcesOfType = resourcesOfType .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) .ToArray(); ImGui.OpenPopup(nameof(Ipc.GetPlayerResourcesOfType)); } - DrawPopup(nameof(Ipc.GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths); - DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths); + DrawPopup(nameof(Ipc.GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths, _lastCallDuration); + DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths, _lastCallDuration); - DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType); - DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType); + DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType, _lastCallDuration); + DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, _lastCallDuration); } - private static void DrawPopup(string popupId, ref T? result, Action drawResult) where T : class + private static void DrawPopup(string popupId, ref T? result, Action drawResult, TimeSpan duration) where T : class { ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(1000, 500)); using var popup = ImRaii.Popup(popupId); @@ -1510,6 +1529,8 @@ public class IpcTester : IDisposable drawResult(result); + ImGui.TextUnformatted($"Invoked in {duration.TotalMilliseconds} ms"); + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) { result = null; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 972e3c55..b6ce42d4 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -2,7 +2,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui; using Penumbra.Api.Enums; -using Penumbra.Collections; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -13,17 +12,17 @@ using Penumbra.UI; namespace Penumbra.Interop.ResourceTree; -internal record GlobalResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, - ModCollection Collection, int Skeleton, bool WithUiData, bool RedactExternalPaths) +internal record GlobalResolveContext(IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, + int Skeleton, bool WithUiData) { public readonly Dictionary Nodes = new(128); public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) - => new(Config, Identifier, TreeBuildCache, Collection, Skeleton, WithUiData, RedactExternalPaths, Nodes, slot, equipment); + => new(Identifier, TreeBuildCache, Skeleton, WithUiData, Nodes, slot, equipment); } -internal record ResolveContext(Configuration Config, IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, ModCollection Collection, - int Skeleton, bool WithUiData, bool RedactExternalPaths, Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) +internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, int Skeleton, bool WithUiData, + Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); @@ -76,52 +75,28 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie Utf8GamePath gamePath, bool @internal) { var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(resourceHandle), out var p) ? new FullPath(p) : FullPath.Empty; - if (fullPath.InternalName.IsEmpty) - fullPath = Collection.ResolvePath(gamePath) ?? new FullPath(gamePath); - var node = new ResourceNode(default, type, objectAddress, (nint)resourceHandle, gamePath, FilterFullPath(fullPath), - GetResourceHandleLength(resourceHandle), @internal); + var node = new ResourceNode(type, objectAddress, (nint)resourceHandle, GetResourceHandleLength(resourceHandle), @internal, this) + { + GamePath = gamePath, + FullPath = fullPath, + }; if (resourceHandle != null) Nodes.Add((nint)resourceHandle, node); return node; } - private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal, - bool withName) + private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal) { var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(handle), out var p) ? new FullPath(p) : FullPath.Empty; if (fullPath.InternalName.IsEmpty) return null; - var gamePaths = Collection.ReverseResolvePath(fullPath).ToList(); - fullPath = FilterFullPath(fullPath); - - if (gamePaths.Count > 1) - gamePaths = Filter(gamePaths); - - if (gamePaths.Count == 1) - return new ResourceNode(withName ? GuessUIDataFromPath(gamePaths[0]) : default, type, objectAddress, (nint)handle, gamePaths[0], - fullPath, - GetResourceHandleLength(handle), @internal); - - Penumbra.Log.Information($"Found {gamePaths.Count} game paths while reverse-resolving {fullPath} in {Collection.Name}:"); - foreach (var gamePath in gamePaths) - Penumbra.Log.Information($"Game path: {gamePath}"); - - return new ResourceNode(default, type, objectAddress, (nint)handle, gamePaths.ToArray(), fullPath, GetResourceHandleLength(handle), - @internal); - } - - public unsafe ResourceNode? CreateHumanSkeletonNode(GenderRace gr) - { - var raceSexIdStr = gr.ToRaceCode(); - var path = $"chara/human/c{raceSexIdStr}/skeleton/base/b0001/skl_c{raceSexIdStr}b0001.sklb"; - - if (!Utf8GamePath.FromString(path, out var gamePath)) - return null; - - return CreateNodeFromGamePath(ResourceType.Sklb, 0, null, gamePath, false); + return new ResourceNode(type, objectAddress, (nint)handle, GetResourceHandleLength(handle), @internal, this) + { + FullPath = fullPath, + }; } public unsafe ResourceNode? CreateNodeFromImc(ResourceHandle* imc) @@ -129,16 +104,10 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (Nodes.TryGetValue((nint)imc, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Imc, 0, imc, true, false); + var node = CreateNodeFromResourceHandle(ResourceType.Imc, 0, imc, true); if (node == null) return null; - if (WithUiData) - { - var uiData = GuessModelUIData(node.GamePath); - node = node.WithUIData(uiData.PrependName("IMC: ")); - } - Nodes.Add((nint)imc, node); return node; @@ -149,7 +118,7 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (Nodes.TryGetValue((nint)tex, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false, WithUiData); + var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false); if (node != null) Nodes.Add((nint)tex, node); @@ -164,23 +133,20 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (Nodes.TryGetValue((nint)mdl->ResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint)mdl, mdl->ResourceHandle, false, false); + var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint)mdl, mdl->ResourceHandle, false); if (node == null) return null; - if (WithUiData) - node = node.WithUIData(GuessModelUIData(node.GamePath)); - for (var i = 0; i < mdl->MaterialCount; i++) { var mtrl = (Material*)mdl->Materials[i]; var mtrlNode = CreateNodeFromMaterial(mtrl); if (mtrlNode != null) - // Don't keep the material's name if it's redundant with the model's name. - node.Children.Add(WithUiData - ? mtrlNode.WithUIData((string.Equals(mtrlNode.Name, node.Name, StringComparison.Ordinal) ? null : mtrlNode.Name) - ?? $"Material #{i}", mtrlNode.Icon) - : mtrlNode); + { + if (WithUiData) + mtrlNode.FallbackName = $"Material #{i}"; + node.Children.Add(mtrlNode); + } } Nodes.Add((nint)mdl->ResourceHandle, node); @@ -190,18 +156,20 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie private unsafe ResourceNode? CreateNodeFromMaterial(Material* mtrl) { - static ushort GetTextureIndex(ushort texFlags) + static ushort GetTextureIndex(Material* mtrl, ushort texFlags, HashSet alreadyVisitedSamplerIds) { - if ((texFlags & 0x001F) != 0x001F) + if ((texFlags & 0x001F) != 0x001F && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[texFlags & 0x001F].Id)) return (ushort)(texFlags & 0x001F); - if ((texFlags & 0x03E0) != 0x03E0) + if ((texFlags & 0x03E0) != 0x03E0 && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[(texFlags >> 5) & 0x001F].Id)) return (ushort)((texFlags >> 5) & 0x001F); + if ((texFlags & 0x7C00) != 0x7C00 && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[(texFlags >> 10) & 0x001F].Id)) + return (ushort)((texFlags >> 10) & 0x001F); - return (ushort)((texFlags >> 10) & 0x001F); + return 0x001F; } - static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle) - => mtrl->TextureSpan.FindFirst(p => p.ResourceHandle == handle, out var p) + static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle, HashSet alreadyVisitedSamplerIds) + => mtrl->TextureSpan.FindFirst(p => p.ResourceHandle == handle && !alreadyVisitedSamplerIds.Contains(p.Id), out var p) ? p.Id : null; @@ -217,16 +185,21 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (Nodes.TryGetValue((nint)resource, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint)mtrl, &resource->Handle, false, WithUiData); + var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint)mtrl, &resource->Handle, false); if (node == null) return null; var shpkNode = CreateNodeFromShpk(resource->ShpkResourceHandle, new ByteString(resource->ShpkString), false); if (shpkNode != null) - node.Children.Add(WithUiData ? shpkNode.WithUIData("Shader Package", 0) : shpkNode); + { + if (WithUiData) + shpkNode.Name = "Shader Package"; + node.Children.Add(shpkNode); + } var shpkFile = WithUiData && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; var shpk = WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; + var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->NumTex; i++) { var texNode = CreateNodeFromTex(resource->TexSpace[i].ResourceHandle, new ByteString(resource->TexString(i)), false, @@ -239,26 +212,26 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie string? name = null; if (shpk != null) { - var index = GetTextureIndex(resource->TexSpace[i].Flags); + var index = GetTextureIndex(mtrl, resource->TexSpace[i].Flags, alreadyProcessedSamplerIds); uint? samplerId; if (index != 0x001F) samplerId = mtrl->Textures[index].Id; else - samplerId = GetTextureSamplerId(mtrl, resource->TexSpace[i].ResourceHandle); + samplerId = GetTextureSamplerId(mtrl, resource->TexSpace[i].ResourceHandle, alreadyProcessedSamplerIds); if (samplerId.HasValue) { + alreadyProcessedSamplerIds.Add(samplerId.Value); var samplerCrc = GetSamplerCrcById(shpk, samplerId.Value); if (samplerCrc.HasValue) name = shpkFile?.GetSamplerById(samplerCrc.Value)?.Name ?? $"Texture 0x{samplerCrc.Value:X8}"; } } - node.Children.Add(texNode.WithUIData(name ?? $"Texture #{i}", 0)); - } - else - { - node.Children.Add(texNode); + texNode = texNode.Clone(); + texNode.Name = name ?? $"Texture #{i}"; } + + node.Children.Add(texNode); } Nodes.Add((nint)resource, node); @@ -274,8 +247,7 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false, - WithUiData); + var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false); if (node != null) { var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); @@ -295,31 +267,18 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true, - WithUiData); + var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true); if (node != null) { if (WithUiData) - node = node.WithUIData("Skeleton Parameters", node.Icon); + node.FallbackName = "Skeleton Parameters"; Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); } return node; } - private FullPath FilterFullPath(FullPath fullPath) - { - if (!fullPath.IsRooted) - return fullPath; - - var relPath = Path.GetRelativePath(Config.ModDirectory, fullPath.FullName); - if (!RedactExternalPaths || relPath == "." || !relPath.StartsWith('.') && !Path.IsPathRooted(relPath)) - return fullPath.Exists ? fullPath : FullPath.Empty; - - return FullPath.Empty; - } - - private List Filter(List gamePaths) + internal List FilterGamePaths(List gamePaths) { var filtered = new List(gamePaths.Count); foreach (var path in gamePaths) @@ -356,7 +315,7 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie } : false; - private ResourceNode.UIData GuessModelUIData(Utf8GamePath gamePath) + internal ResourceNode.UiData GuessModelUIData(Utf8GamePath gamePath) { var path = gamePath.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries); // Weapons intentionally left out. @@ -371,7 +330,7 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie _ => string.Empty, } + item.Name.ToString(); - return new ResourceNode.UIData(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); + return new ResourceNode.UiData(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); } var dataFromPath = GuessUIDataFromPath(gamePath); @@ -379,11 +338,11 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie return dataFromPath; return isEquipment - ? new ResourceNode.UIData(Slot.ToName(), ChangedItemDrawer.GetCategoryIcon(Slot.ToSlot())) - : new ResourceNode.UIData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); + ? new ResourceNode.UiData(Slot.ToName(), ChangedItemDrawer.GetCategoryIcon(Slot.ToSlot())) + : new ResourceNode.UiData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); } - private ResourceNode.UIData GuessUIDataFromPath(Utf8GamePath gamePath) + internal ResourceNode.UiData GuessUIDataFromPath(Utf8GamePath gamePath) { foreach (var obj in Identifier.Identify(gamePath.ToString())) { @@ -391,10 +350,10 @@ internal record ResolveContext(Configuration Config, IObjectIdentifier Identifie if (name.StartsWith("Customization:")) name = name[14..].Trim(); if (name != "Unknown") - return new ResourceNode.UIData(name, ChangedItemDrawer.GetCategoryIcon(obj.Key, obj.Value)); + return new ResourceNode.UiData(name, ChangedItemDrawer.GetCategoryIcon(obj.Key, obj.Value)); } - return new ResourceNode.UIData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); + return new ResourceNode.UiData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); } private static string? SafeGet(ReadOnlySpan array, Index index) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 2fffaedd..dfca5805 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -4,80 +4,89 @@ using ChangedItemIcon = Penumbra.UI.ChangedItemDrawer.ChangedItemIcon; namespace Penumbra.Interop.ResourceTree; -public class ResourceNode +public class ResourceNode : ICloneable { - public readonly string? Name; - public readonly ChangedItemIcon Icon; + public string? Name; + public string? FallbackName; + public ChangedItemIcon Icon; public readonly ResourceType Type; public readonly nint ObjectAddress; public readonly nint ResourceHandle; - public readonly Utf8GamePath GamePath; - public readonly Utf8GamePath[] PossibleGamePaths; - public readonly FullPath FullPath; + public Utf8GamePath[] PossibleGamePaths; + public FullPath FullPath; public readonly ulong Length; public readonly bool Internal; public readonly List Children; + internal ResolveContext? ResolveContext; - public ResourceNode(UIData uiData, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath gamePath, FullPath fullPath, - ulong length, bool @internal) + public Utf8GamePath GamePath { - Name = uiData.Name; - Icon = uiData.Icon; - Type = type; - ObjectAddress = objectAddress; - ResourceHandle = resourceHandle; - GamePath = gamePath; - PossibleGamePaths = new[] + get => PossibleGamePaths.Length == 1 ? PossibleGamePaths[0] : Utf8GamePath.Empty; + set { - gamePath, - }; - FullPath = fullPath; - Length = length; - Internal = @internal; - Children = new List(); + if (value.IsEmpty) + PossibleGamePaths = Array.Empty(); + else + PossibleGamePaths = new[] { value }; + } } - public ResourceNode(UIData uiData, ResourceType type, nint objectAddress, nint resourceHandle, Utf8GamePath[] possibleGamePaths, - FullPath fullPath, - ulong length, bool @internal) + internal ResourceNode(ResourceType type, nint objectAddress, nint resourceHandle, ulong length, bool @internal, ResolveContext? resolveContext) { - Name = uiData.Name; - Icon = uiData.Icon; Type = type; ObjectAddress = objectAddress; ResourceHandle = resourceHandle; - GamePath = possibleGamePaths.Length == 1 ? possibleGamePaths[0] : Utf8GamePath.Empty; - PossibleGamePaths = possibleGamePaths; - FullPath = fullPath; + PossibleGamePaths = Array.Empty(); Length = length; Internal = @internal; Children = new List(); + ResolveContext = resolveContext; } - private ResourceNode(UIData uiData, ResourceNode originalResourceNode) + private ResourceNode(ResourceNode other) { - Name = uiData.Name; - Icon = uiData.Icon; - Type = originalResourceNode.Type; - ObjectAddress = originalResourceNode.ObjectAddress; - ResourceHandle = originalResourceNode.ResourceHandle; - GamePath = originalResourceNode.GamePath; - PossibleGamePaths = originalResourceNode.PossibleGamePaths; - FullPath = originalResourceNode.FullPath; - Length = originalResourceNode.Length; - Internal = originalResourceNode.Internal; - Children = originalResourceNode.Children; + Name = other.Name; + FallbackName = other.FallbackName; + Icon = other.Icon; + Type = other.Type; + ObjectAddress = other.ObjectAddress; + ResourceHandle = other.ResourceHandle; + PossibleGamePaths = other.PossibleGamePaths; + FullPath = other.FullPath; + Length = other.Length; + Internal = other.Internal; + Children = other.Children; + ResolveContext = other.ResolveContext; } - public ResourceNode WithUIData(string? name, ChangedItemIcon icon) - => string.Equals(Name, name, StringComparison.Ordinal) && Icon == icon ? this : new ResourceNode(new UIData(name, icon), this); + public ResourceNode Clone() + => new(this); - public ResourceNode WithUIData(UIData uiData) - => string.Equals(Name, uiData.Name, StringComparison.Ordinal) && Icon == uiData.Icon ? this : new ResourceNode(uiData, this); + object ICloneable.Clone() + => Clone(); - public readonly record struct UIData(string? Name, ChangedItemIcon Icon) + public void ProcessPostfix(Action action, ResourceNode? parent) { - public readonly UIData PrependName(string prefix) - => Name == null ? this : new UIData(prefix + Name, Icon); + foreach (var child in Children) + child.ProcessPostfix(action, this); + action(this, parent); + } + + public void SetUiData(UiData uiData) + { + Name = uiData.Name; + Icon = uiData.Icon; + } + + public void PrependName(string prefix) + { + if (Name != null) + Name = prefix + Name; + } + + public readonly record struct UiData(string? Name, ChangedItemIcon Icon) + { + public readonly UiData PrependName(string prefix) + => Name == null ? this : new UiData(prefix + Name, Icon); } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 161e0368..bc2cca26 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,10 +1,10 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; -using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; +using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; namespace Penumbra.Interop.ResourceTree; @@ -40,6 +40,12 @@ public class ResourceTree FlatNodes = new HashSet(); } + public void ProcessPostfix(Action action) + { + foreach (var node in Nodes) + node.ProcessPostfix(action, null); + } + internal unsafe void LoadResources(GlobalResolveContext globalContext) { var character = (Character*)GameObjectAddress; @@ -60,12 +66,20 @@ public class ResourceTree var imc = (ResourceHandle*)model->IMCArray[i]; var imcNode = context.CreateNodeFromImc(imc); if (imcNode != null) - Nodes.Add(globalContext.WithUiData ? imcNode.WithUIData(imcNode.Name ?? $"IMC #{i}", imcNode.Icon) : imcNode); + { + if (globalContext.WithUiData) + imcNode.FallbackName = $"IMC #{i}"; + Nodes.Add(imcNode); + } var mdl = (RenderModel*)model->Models[i]; var mdlNode = context.CreateNodeFromRenderModel(mdl); if (mdlNode != null) - Nodes.Add(globalContext.WithUiData ? mdlNode.WithUIData(mdlNode.Name ?? $"Model #{i}", mdlNode.Icon) : mdlNode); + { + if (globalContext.WithUiData) + mdlNode.FallbackName = $"Model #{i}"; + Nodes.Add(mdlNode); + } } AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); @@ -96,16 +110,20 @@ public class ResourceTree var imc = (ResourceHandle*)subObject->IMCArray[i]; var imcNode = subObjectContext.CreateNodeFromImc(imc); if (imcNode != null) - subObjectNodes.Add(globalContext.WithUiData - ? imcNode.WithUIData(imcNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}", imcNode.Icon) - : imcNode); + { + if (globalContext.WithUiData) + imcNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}"; + subObjectNodes.Add(imcNode); + } var mdl = (RenderModel*)subObject->Models[i]; var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); if (mdlNode != null) - subObjectNodes.Add(globalContext.WithUiData - ? mdlNode.WithUIData(mdlNode.Name ?? $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}", mdlNode.Icon) - : mdlNode); + { + if (globalContext.WithUiData) + mdlNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}"; + subObjectNodes.Add(mdlNode); + } } AddSkeleton(subObjectNodes, subObjectContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); @@ -121,13 +139,27 @@ public class ResourceTree var decalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->Decal); if (decalNode != null) - Nodes.Add(globalContext.WithUiData ? decalNode.WithUIData(decalNode.Name ?? "Face Decal", decalNode.Icon) : decalNode); + { + if (globalContext.WithUiData) + { + decalNode = decalNode.Clone(); + decalNode.FallbackName = "Face Decal"; + decalNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + } + Nodes.Add(decalNode); + } var legacyDecalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->LegacyBodyDecal); if (legacyDecalNode != null) - Nodes.Add(globalContext.WithUiData - ? legacyDecalNode.WithUIData(legacyDecalNode.Name ?? "Legacy Body Decal", legacyDecalNode.Icon) - : legacyDecalNode); + { + if (globalContext.WithUiData) + { + legacyDecalNode = legacyDecalNode.Clone(); + legacyDecalNode.FallbackName = "Legacy Body Decal"; + legacyDecalNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + } + Nodes.Add(legacyDecalNode); + } } private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") @@ -139,7 +171,11 @@ public class ResourceTree { var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (sklbNode != null) - nodes.Add(context.WithUiData ? sklbNode.WithUIData($"{prefix}Skeleton #{i}", sklbNode.Icon) : sklbNode); + { + if (context.WithUiData) + sklbNode.FallbackName = $"{prefix}Skeleton #{i}"; + nodes.Add(sklbNode); + } } } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 1d91948d..33a8de0f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,9 +1,12 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using Penumbra.Api.Enums; +using Penumbra.Collections; using Penumbra.GameData.Actors; using Penumbra.Interop.PathResolving; using Penumbra.Services; +using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; @@ -84,13 +87,126 @@ public class ResourceTreeFactory var (name, related) = GetCharacterName(character, cache); var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name); - var globalContext = new GlobalResolveContext(_config, _identifier.AwaitedService, cache, collectionResolveData.ModCollection, - ((Character*)gameObjStruct)->CharacterData.ModelCharaId, (flags & Flags.WithUIData) != 0, (flags & Flags.RedactExternalPaths) != 0); + var globalContext = new GlobalResolveContext(_identifier.AwaitedService, cache, + ((Character*)gameObjStruct)->CharacterData.ModelCharaId, (flags & Flags.WithUIData) != 0); tree.LoadResources(globalContext); tree.FlatNodes.UnionWith(globalContext.Nodes.Values); + tree.ProcessPostfix((node, _) => tree.FlatNodes.Add(node)); + + ResolveGamePaths(tree, collectionResolveData.ModCollection); + if (globalContext.WithUiData) + ResolveUiData(tree); + FilterFullPaths(tree, (flags & Flags.RedactExternalPaths) != 0 ? _config.ModDirectory : null); + Cleanup(tree); + return tree; } + private static void ResolveGamePaths(ResourceTree tree, ModCollection collection) + { + var forwardSet = new HashSet(); + var reverseSet = new HashSet(); + foreach (var node in tree.FlatNodes) + { + if (node.PossibleGamePaths.Length == 0 && !node.FullPath.InternalName.IsEmpty) + reverseSet.Add(node.FullPath.ToPath()); + else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) + forwardSet.Add(node.GamePath); + } + + var forwardDictionary = forwardSet.ToDictionary(path => path, collection.ResolvePath); + var reverseArray = reverseSet.ToArray(); + var reverseResolvedArray = collection.ReverseResolvePaths(reverseArray); + var reverseDictionary = reverseArray.Zip(reverseResolvedArray).ToDictionary(pair => pair.First, pair => pair.Second); + + foreach (var node in tree.FlatNodes) + { + if (node.PossibleGamePaths.Length == 0 && !node.FullPath.InternalName.IsEmpty) + { + if (reverseDictionary.TryGetValue(node.FullPath.ToPath(), out var resolvedSet)) + { + var resolvedList = resolvedSet.ToList(); + if (resolvedList.Count > 1) + { + var filteredList = node.ResolveContext!.FilterGamePaths(resolvedList); + if (filteredList.Count > 0) + resolvedList = filteredList; + } + if (resolvedList.Count != 1) + { + Penumbra.Log.Information($"Found {resolvedList.Count} game paths while reverse-resolving {node.FullPath} in {collection.Name}:"); + foreach (var gamePath in resolvedList) + Penumbra.Log.Information($"Game path: {gamePath}"); + } + node.PossibleGamePaths = resolvedList.ToArray(); + } + } + else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) + { + if (forwardDictionary.TryGetValue(node.GamePath, out var resolved)) + node.FullPath = resolved ?? new FullPath(node.GamePath); + } + } + } + + private static void ResolveUiData(ResourceTree tree) + { + foreach (var node in tree.FlatNodes) + { + if (node.Name != null || node.PossibleGamePaths.Length == 0) + continue; + + var gamePath = node.PossibleGamePaths[0]; + node.SetUiData(node.Type switch + { + ResourceType.Imc => node.ResolveContext!.GuessModelUIData(gamePath).PrependName("IMC: "), + ResourceType.Mdl => node.ResolveContext!.GuessModelUIData(gamePath), + _ => node.ResolveContext!.GuessUIDataFromPath(gamePath), + }); + } + + tree.ProcessPostfix((node, parent) => + { + if (node.Name == parent?.Name) + node.Name = null; + }); + } + + private static void FilterFullPaths(ResourceTree tree, string? onlyWithinPath) + { + static bool ShallKeepPath(FullPath fullPath, string? onlyWithinPath) + { + if (!fullPath.IsRooted) + return true; + + if (onlyWithinPath != null) + { + var relPath = Path.GetRelativePath(onlyWithinPath, fullPath.FullName); + if (relPath != "." && (relPath.StartsWith('.') || Path.IsPathRooted(relPath))) + return false; + } + + return fullPath.Exists; + } + + foreach (var node in tree.FlatNodes) + { + if (!ShallKeepPath(node.FullPath, onlyWithinPath)) + node.FullPath = FullPath.Empty; + } + } + + private static void Cleanup(ResourceTree tree) + { + foreach (var node in tree.FlatNodes) + { + node.Name ??= node.FallbackName; + + node.FallbackName = null; + node.ResolveContext = null; + } + } + private unsafe (string Name, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache) { From 808d7ab017f26fe0de1711572be508495558a40b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Sep 2023 20:18:53 +0200 Subject: [PATCH 0112/1381] Add CalculateHeight Hook --- Penumbra.GameData | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index f004e069..7c483764 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f004e069824a1588244e06080b32bab170f78077 +Subproject commit 7c483764678c6edb5efd55f056aeaecae144d5fe diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 40984c6a..a68e376b 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -1,5 +1,7 @@ using Dalamud.Hooking; using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using Penumbra.Collections; @@ -36,7 +38,7 @@ namespace Penumbra.Interop.PathResolving; // RSP tail entries seem to be obtained by "E8 ?? ?? ?? ?? 0F 28 F0 48 8B 05" // RSP bust size entries seem to be obtained by "E8 ?? ?? ?? ?? F2 0F 10 44 24 ?? 8B 44 24 ?? F2 0F 11 45 ?? 89 45 ?? 83 FF" // they all are called by many functions, but the most relevant seem to be Human.SetupFromCharacterData, which is only called by CharacterBase.Create, -// ChangeCustomize and RspSetupCharacter, which is hooked here. +// ChangeCustomize and RspSetupCharacter, which is hooked here, as well as Character.CalculateHeight. // GMP Entries seem to be only used by "48 8B ?? 53 55 57 48 83 ?? ?? 48 8B", which has a DrawObject as its first parameter. public unsafe class MetaState : IDisposable @@ -74,6 +76,7 @@ public unsafe class MetaState : IDisposable _setupVisorHook.Enable(); _rspSetupCharacterHook.Enable(); _changeCustomize.Enable(); + _calculateHeightHook.Enable(); _gameEventManager.CreatingCharacterBase += OnCreatingCharacterBase; _gameEventManager.CharacterBaseCreated += OnCharacterBaseCreated; } @@ -118,6 +121,7 @@ public unsafe class MetaState : IDisposable _setupVisorHook.Dispose(); _rspSetupCharacterHook.Dispose(); _changeCustomize.Dispose(); + _calculateHeightHook.Dispose(); _gameEventManager.CreatingCharacterBase -= OnCreatingCharacterBase; _gameEventManager.CharacterBaseCreated -= OnCharacterBaseCreated; } @@ -242,6 +246,19 @@ public unsafe class MetaState : IDisposable } } + private delegate ulong CalculateHeightDelegate(Character* character); + + // TODO: use client structs + [Signature(Sigs.CalculateHeight, DetourName = nameof(CalculateHeightDetour))] + private readonly Hook _calculateHeightHook = null!; + + private ulong CalculateHeightDetour(Character* character) + { + var resolveData = _collectionResolver.IdentifyCollection((GameObject*)character, true); + using var cmp = resolveData.ModCollection.TemporarilySetCmpFile(_characterUtility); + return _calculateHeightHook.Original(character); + } + private delegate bool ChangeCustomizeDelegate(nint human, nint data, byte skipEquipment); [Signature(Sigs.ChangeCustomize, DetourName = nameof(ChangeCustomizeDetour))] From c29d0a5a4c5bdc837a65ba4e0e24f6768ff37e57 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Sep 2023 21:44:49 +0200 Subject: [PATCH 0113/1381] Remove some allocations from resource tree. --- Penumbra/Api/PenumbraApi.cs | 4 +- .../Collections/ModCollection.Cache.Access.cs | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 2 +- .../ResourceTree/ResourceTreeFactory.cs | 62 ++++++++++--------- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 2 +- 5 files changed, 39 insertions(+), 33 deletions(-) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 49fa40db..dabe4207 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1036,7 +1036,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi params ushort[] gameObjects) { var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUIData : 0); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); return Array.ConvertAll(gameObjects, obj => resDictionaries.TryGetValue(obj, out var resDict) ? resDict : null); @@ -1046,7 +1046,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi bool withUIData) { var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly - | (withUIData ? ResourceTreeFactory.Flags.WithUIData : 0)); + | (withUIData ? ResourceTreeFactory.Flags.WithUiData : 0)); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); return resDictionaries.AsReadOnly(); diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index d788d0bd..2d094970 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -37,7 +37,7 @@ public partial class ModCollection public IEnumerable ReverseResolvePath(FullPath path) => _cache?.ReverseResolvePath(path) ?? Array.Empty(); - public HashSet[] ReverseResolvePaths(string[] paths) + public HashSet[] ReverseResolvePaths(IReadOnlyCollection paths) => _cache?.ReverseResolvePaths(paths) ?? paths.Select(_ => new HashSet()).ToArray(); public FullPath? ResolvePath(Utf8GamePath path) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index b6ce42d4..55893cab 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -278,7 +278,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree return node; } - internal List FilterGamePaths(List gamePaths) + internal List FilterGamePaths(IReadOnlyCollection gamePaths) { var filtered = new List(gamePaths.Count); foreach (var path in gamePaths) diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 33a8de0f..bd0138c4 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -84,11 +84,12 @@ public class ResourceTreeFactory return null; var localPlayerRelated = cache.IsLocalPlayerRelated(character); - var (name, related) = GetCharacterName(character, cache); - var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; - var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name); + var (name, related) = GetCharacterName(character, cache); + var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; + var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, + networked, collectionResolveData.ModCollection.Name); var globalContext = new GlobalResolveContext(_identifier.AwaitedService, cache, - ((Character*)gameObjStruct)->CharacterData.ModelCharaId, (flags & Flags.WithUIData) != 0); + ((Character*)gameObjStruct)->CharacterData.ModelCharaId, (flags & Flags.WithUiData) != 0); tree.LoadResources(globalContext); tree.FlatNodes.UnionWith(globalContext.Nodes.Values); tree.ProcessPostfix((node, _) => tree.FlatNodes.Add(node)); @@ -104,42 +105,47 @@ public class ResourceTreeFactory private static void ResolveGamePaths(ResourceTree tree, ModCollection collection) { - var forwardSet = new HashSet(); - var reverseSet = new HashSet(); + var forwardDictionary = new Dictionary(); + var reverseDictionary = new Dictionary>(); foreach (var node in tree.FlatNodes) { if (node.PossibleGamePaths.Length == 0 && !node.FullPath.InternalName.IsEmpty) - reverseSet.Add(node.FullPath.ToPath()); + reverseDictionary.TryAdd(node.FullPath.ToPath(), null!); else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) - forwardSet.Add(node.GamePath); + forwardDictionary.TryAdd(node.GamePath, null); } - var forwardDictionary = forwardSet.ToDictionary(path => path, collection.ResolvePath); - var reverseArray = reverseSet.ToArray(); - var reverseResolvedArray = collection.ReverseResolvePaths(reverseArray); - var reverseDictionary = reverseArray.Zip(reverseResolvedArray).ToDictionary(pair => pair.First, pair => pair.Second); + foreach (var key in forwardDictionary.Keys) + forwardDictionary[key] = collection.ResolvePath(key); + + var reverseResolvedArray = collection.ReverseResolvePaths(reverseDictionary.Keys); + foreach (var (key, set) in reverseDictionary.Keys.Zip(reverseResolvedArray)) + reverseDictionary[key] = set; foreach (var node in tree.FlatNodes) { if (node.PossibleGamePaths.Length == 0 && !node.FullPath.InternalName.IsEmpty) { - if (reverseDictionary.TryGetValue(node.FullPath.ToPath(), out var resolvedSet)) + if (!reverseDictionary.TryGetValue(node.FullPath.ToPath(), out var resolvedSet)) + continue; + + IReadOnlyCollection resolvedList = resolvedSet; + if (resolvedList.Count > 1) { - var resolvedList = resolvedSet.ToList(); - if (resolvedList.Count > 1) - { - var filteredList = node.ResolveContext!.FilterGamePaths(resolvedList); - if (filteredList.Count > 0) - resolvedList = filteredList; - } - if (resolvedList.Count != 1) - { - Penumbra.Log.Information($"Found {resolvedList.Count} game paths while reverse-resolving {node.FullPath} in {collection.Name}:"); - foreach (var gamePath in resolvedList) - Penumbra.Log.Information($"Game path: {gamePath}"); - } - node.PossibleGamePaths = resolvedList.ToArray(); + var filteredList = node.ResolveContext!.FilterGamePaths(resolvedList); + if (filteredList.Count > 0) + resolvedList = filteredList; } + + if (resolvedList.Count != 1) + { + Penumbra.Log.Debug( + $"Found {resolvedList.Count} game paths while reverse-resolving {node.FullPath} in {collection.Name}:"); + foreach (var gamePath in resolvedList) + Penumbra.Log.Debug($"Game path: {gamePath}"); + } + + node.PossibleGamePaths = resolvedList.ToArray(); } else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) { @@ -237,7 +243,7 @@ public class ResourceTreeFactory public enum Flags { RedactExternalPaths = 1, - WithUIData = 2, + WithUiData = 2, LocalPlayerRelatedOnly = 4, WithOwnership = 8, } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 3901b431..39728cd4 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -11,7 +11,7 @@ public class ResourceTreeViewer { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = ResourceTreeFactory.Flags.RedactExternalPaths | - ResourceTreeFactory.Flags.WithUIData | + ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; private readonly Configuration _config; From 348480ed6846eb5e97e8b911c5244efd95bdddba Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Sep 2023 21:46:15 +0200 Subject: [PATCH 0114/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 21333f3e..4ea1eb7b 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 21333f3e2f3908d4f4c7dbb0b4bff5e5b7d1f64a +Subproject commit 4ea1eb7b7d39a74465291164563ad5d29fa038e4 From 1760efb4775f1ee38af709056be2f3cd22166c4a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Sep 2023 21:50:43 +0200 Subject: [PATCH 0115/1381] Fix ambiguous reference for no fucking reason. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 4ea1eb7b..6eb6ab15 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 4ea1eb7b7d39a74465291164563ad5d29fa038e4 +Subproject commit 6eb6ab156c1bc1cb61700f19768f3fa6c11e1e04 From 5a24d9155b1526e2c49d61e409dc7800df199a22 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 19 Sep 2023 19:52:53 +0000 Subject: [PATCH 0116/1381] [CI] Updating repo.json for testing_0.7.3.12 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 386fb07a..6eeaf412 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.11", + "TestingAssemblyVersion": "0.7.3.12", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.11/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.12/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 69388689ac20d92de722a328fc061d64a448e330 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 20 Sep 2023 01:53:10 +0200 Subject: [PATCH 0117/1381] Material Editor: Extend live preview. --- .../Interop/MaterialPreview/MaterialInfo.cs | 87 ++++++++----------- .../ModEditWindow.Materials.MtrlTab.cs | 5 +- .../ModEditWindow.QuickImport.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 7 +- 4 files changed, 44 insertions(+), 56 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index 3f02e7e8..26e809f9 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -9,41 +9,20 @@ namespace Penumbra.Interop.MaterialPreview; public enum DrawObjectType { - PlayerCharacter, - PlayerMainhand, - PlayerOffhand, - PlayerVfx, - MinionCharacter, - MinionUnk1, - MinionUnk2, - MinionUnk3, + Character, + Mainhand, + Offhand, + Vfx, }; -public readonly record struct MaterialInfo(DrawObjectType Type, int ModelSlot, int MaterialSlot) +public readonly record struct MaterialInfo(ushort ObjectIndex, DrawObjectType Type, int ModelSlot, int MaterialSlot) { public nint GetCharacter(IObjectTable objects) - => GetCharacter(Type, objects); - - public static nint GetCharacter(DrawObjectType type, IObjectTable objects) - => type switch - { - DrawObjectType.PlayerCharacter => objects.GetObjectAddress(0), - DrawObjectType.PlayerMainhand => objects.GetObjectAddress(0), - DrawObjectType.PlayerOffhand => objects.GetObjectAddress(0), - DrawObjectType.PlayerVfx => objects.GetObjectAddress(0), - DrawObjectType.MinionCharacter => objects.GetObjectAddress(1), - DrawObjectType.MinionUnk1 => objects.GetObjectAddress(1), - DrawObjectType.MinionUnk2 => objects.GetObjectAddress(1), - DrawObjectType.MinionUnk3 => objects.GetObjectAddress(1), - _ => nint.Zero, - }; + => objects.GetObjectAddress(ObjectIndex); public nint GetDrawObject(nint address) => GetDrawObject(Type, address); - public static nint GetDrawObject(DrawObjectType type, IObjectTable objects) - => GetDrawObject(type, GetCharacter(type, objects)); - public static unsafe nint GetDrawObject(DrawObjectType type, nint address) { var gameObject = (Character*)address; @@ -52,18 +31,17 @@ public readonly record struct MaterialInfo(DrawObjectType Type, int ModelSlot, i return type switch { - DrawObjectType.PlayerCharacter => (nint)gameObject->GameObject.GetDrawObject(), - DrawObjectType.PlayerMainhand => *((nint*)&gameObject->DrawData.MainHand + 1), - DrawObjectType.PlayerOffhand => *((nint*)&gameObject->DrawData.OffHand + 1), - DrawObjectType.PlayerVfx => *((nint*)&gameObject->DrawData.UnkF0 + 1), - DrawObjectType.MinionCharacter => (nint)gameObject->GameObject.GetDrawObject(), - DrawObjectType.MinionUnk1 => *((nint*)&gameObject->DrawData.MainHand + 1), - DrawObjectType.MinionUnk2 => *((nint*)&gameObject->DrawData.OffHand + 1), - DrawObjectType.MinionUnk3 => *((nint*)&gameObject->DrawData.UnkF0 + 1), - _ => nint.Zero, + DrawObjectType.Character => (nint)gameObject->GameObject.GetDrawObject(), + DrawObjectType.Mainhand => *((nint*)&gameObject->DrawData.MainHand + 1), + DrawObjectType.Offhand => *((nint*)&gameObject->DrawData.OffHand + 1), + DrawObjectType.Vfx => *((nint*)&gameObject->DrawData.UnkF0 + 1), + _ => nint.Zero, }; } + public unsafe Material* GetDrawObjectMaterial(IObjectTable objects) + => GetDrawObjectMaterial((CharacterBase*)GetDrawObject(GetCharacter(objects))); + public unsafe Material* GetDrawObjectMaterial(CharacterBase* drawObject) { if (drawObject == null) @@ -82,33 +60,42 @@ public readonly record struct MaterialInfo(DrawObjectType Type, int ModelSlot, i return model->Materials[MaterialSlot]; } - public static unsafe List FindMaterials(IObjectTable objects, string materialPath) + public static unsafe List FindMaterials(IEnumerable gameObjects, string materialPath) { var needle = ByteString.FromString(materialPath.Replace('\\', '/'), out var m, true) ? m : ByteString.Empty; var result = new List(Enum.GetValues().Length); - foreach (var type in Enum.GetValues()) + foreach (var objectPtr in gameObjects) { - var drawObject = (CharacterBase*)GetDrawObject(type, objects); - if (drawObject == null) + var gameObject = (Character*)objectPtr; + if (gameObject == null) continue; - for (var i = 0; i < drawObject->SlotCount; ++i) + var index = gameObject->GameObject.ObjectIndex; + + foreach (var type in Enum.GetValues()) { - var model = drawObject->Models[i]; - if (model == null) + var drawObject = (CharacterBase*)GetDrawObject(type, objectPtr); + if (drawObject == null) continue; - for (var j = 0; j < model->MaterialCount; ++j) + for (var i = 0; i < drawObject->SlotCount; ++i) { - var material = model->Materials[j]; - if (material == null) + var model = drawObject->Models[i]; + if (model == null) continue; - var mtrlHandle = material->MaterialResourceHandle; - var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); - if (path == needle) - result.Add(new MaterialInfo(type, i, j)); + for (var j = 0; j < model->MaterialCount; ++j) + { + var material = model->Materials[j]; + if (material == null) + continue; + + var mtrlHandle = material->MaterialResourceHandle; + var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); + if (path == needle) + result.Add(new MaterialInfo(index, type, i, j)); + } } } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index ad83843d..ebe980d7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -454,13 +454,12 @@ public partial class ModEditWindow { UnbindFromMaterialInstances(); - var instances = MaterialInfo.FindMaterials(_edit._dalamud.Objects, FilePath); + var instances = MaterialInfo.FindMaterials(_edit._resourceTreeFactory.GetLocalPlayerRelatedCharacters().Select(ch => ch.Address), FilePath); var foundMaterials = new HashSet(); foreach (var materialInfo in instances) { - var drawObject = (CharacterBase*)MaterialInfo.GetDrawObject(materialInfo.Type, _edit._dalamud.Objects); - var material = materialInfo.GetDrawObjectMaterial(drawObject); + var material = materialInfo.GetDrawObjectMaterial(_edit._dalamud.Objects); if (foundMaterials.Contains((nint)material)) continue; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 2f64f82a..48d617db 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -14,6 +14,7 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { + private readonly ResourceTreeFactory _resourceTreeFactory; private readonly ResourceTreeViewer _quickImportViewer; private readonly Dictionary _quickImportWritables = new(); private readonly Dictionary<(Utf8GamePath, IWritable?), QuickImportAction> _quickImportActions = new(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 745b412b..febb01cb 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -576,9 +576,10 @@ public partial class ModEditWindow : Window, IDisposable _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => _editor.Files.Shpk, DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); - _center = new CombinedTexture(_left, _right); - _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); - _quickImportViewer = + _center = new CombinedTexture(_left, _right); + _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); + _resourceTreeFactory = resourceTreeFactory; + _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ModEditWindow); } From 40b6c6022a23bf1365cf58f75f9d887d1cad9c2b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Sep 2023 18:51:07 +0200 Subject: [PATCH 0118/1381] Add automatic restore from backup for sort_order and active_collections for now. --- OtterGui | 2 +- .../Collections/Manager/ActiveCollections.cs | 20 +++++++--------- Penumbra/Mods/Manager/ModFileSystem.cs | 6 +++-- Penumbra/Services/BackupService.cs | 23 +++++++++++++++++++ 4 files changed, 36 insertions(+), 15 deletions(-) diff --git a/OtterGui b/OtterGui index 6eb6ab15..0f8a8664 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 6eb6ab156c1bc1cb61700f19768f3fa6c11e1e04 +Subproject commit 0f8a866491b246e819e0618a43078170686780ab diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index bae95885..7e6d691e 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -408,19 +408,15 @@ public class ActiveCollections : ISavable, IDisposable public static bool Load(FilenameService fileNames, out JObject ret) { var file = fileNames.ActiveCollectionsFile; - if (File.Exists(file)) - try - { - ret = JObject.Parse(File.ReadAllText(file)); - return true; - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not read active collections from file {file}:\n{e}"); - } + var jObj = BackupService.GetJObjectForFile(fileNames, file); + if (jObj == null) + { + ret = new JObject(); + return false; + } - ret = new JObject(); - return false; + ret = jObj; + return true; } public string RedundancyCheck(CollectionType type, ActorIdentifier id) diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index 013d0e40..2d8b90ab 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -1,5 +1,7 @@ using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; +using Newtonsoft.Json.Linq; +using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Services; @@ -60,8 +62,8 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable // Used on construction and on mod rediscoveries. private void Reload() { - // TODO - if (Load(new FileInfo(_saveService.FileNames.FilesystemFile), _modManager, ModToIdentifier, ModToName)) + var jObj = BackupService.GetJObjectForFile(_saveService.FileNames, _saveService.FileNames.FilesystemFile); + if (Load(jObj, _modManager, ModToIdentifier, ModToName)) _saveService.ImmediateSave(this); Penumbra.Log.Debug("Reloaded mod filesystem."); diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index 0c13217a..f6e2c3e4 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json.Linq; using OtterGui.Classes; using OtterGui.Log; using Penumbra.Util; @@ -23,4 +24,26 @@ public class BackupService list.Add(new FileInfo(fileNames.ActiveCollectionsFile)); return list; } + + /// Try to parse a file to JObject and check backups if this does not succeed. + public static JObject? GetJObjectForFile(FilenameService fileNames, string fileName) + { + JObject? ret = null; + if (!File.Exists(fileName)) + return ret; + + try + { + var text = File.ReadAllText(fileName); + ret = JObject.Parse(text); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Failed to load {fileName}, trying to restore from backup:\n{ex}"); + Backup.TryGetFile(new DirectoryInfo(fileNames.ConfigDirectory), fileName, out ret, out var messages, JObject.Parse); + Penumbra.Chat.NotificationMessage(messages); + } + + return ret; + } } From 11bf0d29987d2144c12aa740b9e75c5c6f69a24c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Sep 2023 02:05:52 +0200 Subject: [PATCH 0119/1381] Optimize ResourceTree somewhat. --- Penumbra.GameData | 2 +- Penumbra/Api/IpcTester.cs | 9 +- .../Interop/MaterialPreview/MaterialInfo.cs | 7 +- .../ResourceTree/ResourceTreeFactory.cs | 46 ++++---- .../Interop/ResourceTree/TreeBuildCache.cs | 107 +++++++++++++----- 5 files changed, 108 insertions(+), 63 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 7c483764..ef403be9 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 7c483764678c6edb5efd55f056aeaecae144d5fe +Subproject commit ef403be979bfac5ef805030ce76066151d36f112 diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index de9ab5a7..7766b5af 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -18,6 +18,7 @@ using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; using Penumbra.GameData.Enums; using System.Diagnostics; +using Penumbra.GameData.Structs; namespace Penumbra.Api; @@ -1450,7 +1451,7 @@ public class IpcTester : IDisposable _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcePaths = gameObjects - .Select(GameObjectToString) + .Select(i => GameObjectToString(i)) .Zip(resourcePaths) .ToArray(); @@ -1482,7 +1483,7 @@ public class IpcTester : IDisposable _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcesOfType = gameObjects - .Select(GameObjectToString) + .Select(i => GameObjectToString(i)) .Zip(resourcesOfType) .ToArray(); @@ -1630,9 +1631,9 @@ public class IpcTester : IDisposable .SelectWhere(index => (ushort.TryParse(index.Trim(), out var i), i)) .ToArray(); - private unsafe string GameObjectToString(ushort gameObjectIndex) + private unsafe string GameObjectToString(ObjectIndex gameObjectIndex) { - var gameObject = _objects[gameObjectIndex]; + var gameObject = _objects[gameObjectIndex.Index]; return gameObject != null ? $"[{gameObjectIndex}] {gameObject.Name} ({gameObject.ObjectKind})" diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index 26e809f9..7dd6f983 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -2,6 +2,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.GameData.Structs; using Penumbra.Interop.ResourceTree; using Penumbra.String; @@ -15,10 +16,10 @@ public enum DrawObjectType Vfx, }; -public readonly record struct MaterialInfo(ushort ObjectIndex, DrawObjectType Type, int ModelSlot, int MaterialSlot) +public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectType Type, int ModelSlot, int MaterialSlot) { public nint GetCharacter(IObjectTable objects) - => objects.GetObjectAddress(ObjectIndex); + => objects.GetObjectAddress(ObjectIndex.Index); public nint GetDrawObject(nint address) => GetDrawObject(Type, address); @@ -71,7 +72,7 @@ public readonly record struct MaterialInfo(ushort ObjectIndex, DrawObjectType Ty if (gameObject == null) continue; - var index = gameObject->GameObject.ObjectIndex; + var index = (ObjectIndex) gameObject->GameObject.ObjectIndex; foreach (var type in Enum.GetValues()) { diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index bd0138c4..6353d5b5 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -30,21 +30,20 @@ public class ResourceTreeFactory _actors = actors; } - private TreeBuildCache CreateTreeBuildCache(bool withCharacters) - => new(_objects, _gameData, _actors, withCharacters); + private TreeBuildCache CreateTreeBuildCache() + => new(_objects, _gameData, _actors); public IEnumerable GetLocalPlayerRelatedCharacters() { - var cache = CreateTreeBuildCache(true); - - return cache.Characters.Where(cache.IsLocalPlayerRelated); + var cache = CreateTreeBuildCache(); + return cache.GetLocalPlayerRelatedCharacters(); } public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromObjectTable( Flags flags) { - var cache = CreateTreeBuildCache(true); - var characters = (flags & Flags.LocalPlayerRelatedOnly) != 0 ? cache.Characters.Where(cache.IsLocalPlayerRelated) : cache.Characters; + var cache = CreateTreeBuildCache(); + var characters = (flags & Flags.LocalPlayerRelatedOnly) != 0 ? cache.GetLocalPlayerRelatedCharacters() : cache.GetCharacters(); foreach (var character in characters) { @@ -57,7 +56,7 @@ public class ResourceTreeFactory public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromCharacters( IEnumerable characters, Flags flags) { - var cache = CreateTreeBuildCache((flags & Flags.WithOwnership) != 0); + var cache = CreateTreeBuildCache(); foreach (var character in characters) { var tree = FromCharacter(character, cache, flags); @@ -67,7 +66,7 @@ public class ResourceTreeFactory } public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, Flags flags) - => FromCharacter(character, CreateTreeBuildCache((flags & Flags.WithOwnership) != 0), flags); + => FromCharacter(character, CreateTreeBuildCache(), flags); private unsafe ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache, Flags flags) { @@ -136,7 +135,7 @@ public class ResourceTreeFactory if (filteredList.Count > 0) resolvedList = filteredList; } - + if (resolvedList.Count != 1) { Penumbra.Log.Debug( @@ -216,27 +215,22 @@ public class ResourceTreeFactory private unsafe (string Name, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache) { - var identifier = _actors.AwaitedService.FromObject((GameObject*)character.Address, out var owner, true, false, false); - string name; - bool playerRelated; + var identifier = _actors.AwaitedService.FromObject((GameObject*)character.Address, out var owner, true, false, false); switch (identifier.Type) { - case IdentifierType.Player: - name = identifier.PlayerName.ToString(); - playerRelated = true; - break; - case IdentifierType.Owned when cache.CharactersById.TryGetValue(owner->ObjectID, out var ownerChara): - var ownerName = GetCharacterName(ownerChara, cache); - name = $"[{ownerName.Name}] {character.Name} ({identifier.Kind.ToName()})"; - playerRelated = ownerName.PlayerRelated; - break; - default: - name = $"{character.Name} ({identifier.Kind.ToName()})"; - playerRelated = false; + case IdentifierType.Player: return (identifier.PlayerName.ToString(), true); + case IdentifierType.Owned: + var ownerChara = _objects.CreateObjectReference((nint)owner) as Dalamud.Game.ClientState.Objects.Types.Character; + if (ownerChara != null) + { + var ownerName = GetCharacterName(ownerChara, cache); + return ($"[{ownerName.Name}] {character.Name} ({identifier.Kind.ToName()})", ownerName.PlayerRelated); + } + break; } - return (name, playerRelated); + return ($"{character.Name} ({identifier.Kind.ToName()})", false); } [Flags] diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index d889cf5d..5f724b14 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -1,55 +1,104 @@ +using System.Diagnostics.CodeAnalysis; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; +using Penumbra.GameData.Actors; using Penumbra.GameData.Files; -using Penumbra.Interop.Services; +using Penumbra.GameData.Structs; using Penumbra.Services; +using Penumbra.String; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; -internal class TreeBuildCache +internal readonly struct TreeBuildCache { private readonly IDataManager _dataManager; private readonly ActorService _actors; private readonly Dictionary _shaderPackages = new(); - private readonly uint _localPlayerId; - public readonly List Characters; - public readonly Dictionary CharactersById; + private readonly IObjectTable _objects; - public TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorService actors, bool withCharacters) + public TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorService actors) { - _dataManager = dataManager; - _actors = actors; - _localPlayerId = objects[0]?.ObjectId ?? GameObject.InvalidGameObjectId; - if (withCharacters) - { - Characters = objects.OfType().Where(ch => ch.IsValid()).ToList(); - CharactersById = Characters - .Where(c => c.ObjectId != GameObject.InvalidGameObjectId) - .GroupBy(c => c.ObjectId) - .ToDictionary(c => c.Key, c => c.First()); - } - else - { - Characters = new(); - CharactersById = new(); - } + _dataManager = dataManager; + _objects = objects; + _actors = actors; } public unsafe bool IsLocalPlayerRelated(Character character) { - if (_localPlayerId == GameObject.InvalidGameObjectId) + var player = _objects[0]; + if (player == null) return false; - // Index 0 is the local player, index 1 is the mount/minion/accessory. - if (character.ObjectIndex < 2 || character.ObjectIndex == RedrawService.GPosePlayerIdx) - return true; + var gameObject = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)character.Address; + var parent = _actors.AwaitedService.ToCutsceneParent(gameObject->ObjectIndex); + var actualIndex = parent >= 0 ? (ushort)parent : gameObject->ObjectIndex; + return actualIndex switch + { + < 2 => true, + < (int)ScreenActor.CutsceneStart => gameObject->OwnerID == player.ObjectId, + _ => false, + }; + } - if (!_actors.AwaitedService.FromObject(character, out var owner, true, false, false).IsValid) + public IEnumerable GetCharacters() + => _objects.OfType(); + + public IEnumerable GetLocalPlayerRelatedCharacters() + { + var player = _objects[0]; + if (player == null) + yield break; + + yield return (Character)player; + + var minion = _objects[1]; + if (minion != null) + yield return (Character)minion; + + var playerId = player.ObjectId; + for (var i = 2; i < ObjectIndex.CutsceneStart.Index; i += 2) + { + if (_objects[i] is Character owned && owned.OwnerId == playerId) + yield return owned; + } + + for (var i = ObjectIndex.CutsceneStart.Index; i < ObjectIndex.CharacterScreen.Index; ++i) + { + var character = _objects[i] as Character; + if (character == null) + continue; + + var parent = _actors.AwaitedService.ToCutsceneParent(i); + if (parent < 0) + continue; + + if (parent is 0 or 1 || _objects[parent]?.OwnerId == playerId) + yield return character; + } + } + + private unsafe ByteString GetPlayerName(GameObject player) + { + var gameObject = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)player.Address; + return new ByteString(gameObject->Name); + } + + private unsafe bool GetOwnedId(ByteString playerName, uint playerId, int idx, [NotNullWhen(true)] out Character? character) + { + character = _objects[idx] as Character; + if (character == null) return false; - // Check for SMN/SCH pet, chocobo and other owned NPCs. - return owner != null && owner->ObjectID == _localPlayerId; + var actorId = _actors.AwaitedService.FromObject(character, out var owner, true, true, true); + if (!actorId.IsValid) + return false; + if (owner != null && owner->OwnerID != playerId) + return false; + if (actorId.Type is not IdentifierType.Player || !actorId.PlayerName.Equals(playerName)) + return false; + + return true; } /// Try to read a shpk file from the given path and cache it on success. From 3f439bacb2264a72b1388bd1960333ad3fc7bd78 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Sep 2023 02:15:23 +0200 Subject: [PATCH 0120/1381] Extract remaining global usings for System libs. --- Penumbra/Api/IpcTester.cs | 2 -- Penumbra/Api/PenumbraApi.cs | 1 - Penumbra/Collections/Cache/ImcCache.cs | 1 - Penumbra/Collections/Cache/MetaCache.cs | 1 - Penumbra/Collections/Manager/CollectionStorage.cs | 1 - Penumbra/Collections/Manager/IndividualCollections.Access.cs | 1 - Penumbra/Collections/Manager/IndividualCollections.cs | 1 - Penumbra/Collections/Manager/TempCollectionManager.cs | 1 - Penumbra/Collections/ModCollection.Cache.Access.cs | 1 - Penumbra/GlobalUsings.cs | 5 +++++ Penumbra/Import/Structs/MetaFileInfo.cs | 1 - Penumbra/Import/TexToolsImport.cs | 2 -- Penumbra/Import/TexToolsImporter.Archives.cs | 2 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 2 +- Penumbra/Import/TexToolsMeta.Export.cs | 1 - Penumbra/Import/TexToolsMeta.cs | 1 - Penumbra/Interop/PathResolving/PathResolver.cs | 1 - Penumbra/Interop/ResourceLoading/CreateFileWHook.cs | 1 - Penumbra/Interop/ResourceTree/TreeBuildCache.cs | 1 - Penumbra/Mods/Editor/FileRegistry.cs | 1 - Penumbra/Mods/Editor/MdlMaterialEditor.cs | 2 -- Penumbra/Mods/Editor/ModBackup.cs | 1 - Penumbra/Mods/ItemSwap/ItemSwap.cs | 2 -- Penumbra/Mods/Manager/ModFileSystem.cs | 2 -- Penumbra/Mods/Manager/ModImportManager.cs | 1 - Penumbra/Mods/Manager/ModMigration.cs | 1 - Penumbra/Mods/Manager/ModStorage.cs | 1 - Penumbra/Mods/ModCreator.cs | 2 -- Penumbra/Penumbra.cs | 1 - .../AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs | 1 - Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs | 1 - Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 1 - Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs | 1 - Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs | 1 - Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 1 - Penumbra/UI/ResourceWatcher/ResourceWatcher.cs | 1 - Penumbra/Util/PenumbraSqPackStream.cs | 1 - 37 files changed, 7 insertions(+), 42 deletions(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 7766b5af..148d4481 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -4,7 +4,6 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.Mods; -using System.Globalization; using Dalamud.Utility; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; @@ -17,7 +16,6 @@ using Penumbra.UI; using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; using Penumbra.GameData.Enums; -using System.Diagnostics; using Penumbra.GameData.Structs; namespace Penumbra.Api; diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index dabe4207..10b5b6bd 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -7,7 +7,6 @@ using Penumbra.Interop.PathResolving; using Penumbra.Interop.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods; -using System.Diagnostics.CodeAnalysis; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Compression; using Penumbra.Api.Enums; diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 05756e12..3b865d4b 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index d2dd48f8..8eb7a5a0 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Penumbra.GameData.Enums; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index eb230e9e..e50b9bdb 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Filesystem; diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index 489e2f72..680f8b32 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.Types; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/Manager/IndividualCollections.cs b/Penumbra/Collections/Manager/IndividualCollections.cs index ed3c3d4b..4fe1e829 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Dalamud.Game.ClientState.Objects.Enums; using OtterGui.Filesystem; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index 133a0990..d0edf19b 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Penumbra.Api; using Penumbra.Communication; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 2d094970..36e0fd98 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -1,7 +1,6 @@ using OtterGui.Classes; using Penumbra.GameData.Enums; using Penumbra.Mods; -using System.Diagnostics.CodeAnalysis; using Penumbra.Interop.Structs; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/GlobalUsings.cs b/Penumbra/GlobalUsings.cs index b1e6218c..51ba9ce5 100644 --- a/Penumbra/GlobalUsings.cs +++ b/Penumbra/GlobalUsings.cs @@ -5,12 +5,17 @@ global using System.Collections; global using System.Collections.Concurrent; global using System.Collections.Generic; global using System.Diagnostics; +global using System.Diagnostics.CodeAnalysis; +global using System.Globalization; global using System.IO; +global using System.IO.Compression; global using System.Linq; global using System.Numerics; global using System.Reflection; global using System.Runtime.CompilerServices; global using System.Runtime.InteropServices; global using System.Security.Cryptography; +global using System.Text; +global using System.Text.RegularExpressions; global using System.Threading; global using System.Threading.Tasks; diff --git a/Penumbra/Import/Structs/MetaFileInfo.cs b/Penumbra/Import/Structs/MetaFileInfo.cs index 81b869d9..f7c9b419 100644 --- a/Penumbra/Import/Structs/MetaFileInfo.cs +++ b/Penumbra/Import/Structs/MetaFileInfo.cs @@ -1,5 +1,4 @@ using Penumbra.GameData.Enums; -using System.Text.RegularExpressions; using Penumbra.GameData; namespace Penumbra.Import.Structs; diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index ad61398f..3f3304b8 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -1,8 +1,6 @@ -using System.Text; using Newtonsoft.Json; using OtterGui.Compression; using Penumbra.Import.Structs; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using FileMode = System.IO.FileMode; diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index 3b67ac50..6ddafdd7 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -7,9 +7,9 @@ using Penumbra.Mods; using SharpCompress.Archives; using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; -using SharpCompress.Archives.Zip; using SharpCompress.Common; using SharpCompress.Readers; +using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; namespace Penumbra.Import; diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 73b5d976..dbe76ae3 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -4,7 +4,7 @@ using Penumbra.Import.Structs; using Penumbra.Mods; using Penumbra.Mods.Subclasses; using Penumbra.Util; -using SharpCompress.Archives.Zip; +using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; namespace Penumbra.Import; diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 46636362..90ffaf60 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -1,4 +1,3 @@ -using System.Text; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index a188975c..1108c965 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -1,4 +1,3 @@ -using System.Text; using Penumbra.GameData; using Penumbra.Import.Structs; using Penumbra.Meta; diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 20713fe7..12e5e280 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs index 6b751db7..ca9c2577 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs @@ -1,4 +1,3 @@ -using System.Text; using Dalamud.Hooking; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 5f724b14..9614e9aa 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using Penumbra.GameData.Actors; diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 0aa70e61..791778e3 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/MdlMaterialEditor.cs b/Penumbra/Mods/Editor/MdlMaterialEditor.cs index 1c1a10b4..8881ac4b 100644 --- a/Penumbra/Mods/Editor/MdlMaterialEditor.cs +++ b/Penumbra/Mods/Editor/MdlMaterialEditor.cs @@ -1,5 +1,3 @@ -using System.Text; -using System.Text.RegularExpressions; using OtterGui; using OtterGui.Compression; using Penumbra.GameData.Enums; diff --git a/Penumbra/Mods/Editor/ModBackup.cs b/Penumbra/Mods/Editor/ModBackup.cs index 8de93bcc..994ca0b5 100644 --- a/Penumbra/Mods/Editor/ModBackup.cs +++ b/Penumbra/Mods/Editor/ModBackup.cs @@ -1,4 +1,3 @@ -using System.IO.Compression; using OtterGui.Tasks; using Penumbra.Mods.Manager; diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 7c2f50c4..90bee553 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -1,5 +1,3 @@ -using System.Diagnostics.CodeAnalysis; -using System.Text.RegularExpressions; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index 013d0e40..73efe5d9 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -1,5 +1,3 @@ -using System.Diagnostics.CodeAnalysis; -using System.Text.RegularExpressions; using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Services; diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index cc91dfa6..96cf146b 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using Dalamud.Interface.Internal.Notifications; using Penumbra.Import; using Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index ddd88a72..452da366 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -1,4 +1,3 @@ -using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; diff --git a/Penumbra/Mods/Manager/ModStorage.cs b/Penumbra/Mods/Manager/ModStorage.cs index 377bb4a7..83d20969 100644 --- a/Penumbra/Mods/Manager/ModStorage.cs +++ b/Penumbra/Mods/Manager/ModStorage.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using OtterGui.Classes; using OtterGui.Widgets; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 89d35cd2..236f1539 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -1,5 +1,3 @@ -using System.Text; -using System.Text.RegularExpressions; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 019355af..2cca1789 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -1,4 +1,3 @@ -using System.Text; using Dalamud.Plugin; using ImGuiNET; using Lumina.Excel.GeneratedSheets; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs index 7b80920d..1f5db38e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs @@ -1,4 +1,3 @@ -using System.Globalization; using ImGuiNET; using OtterGui.Raii; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index a5746ec7..25869d9c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -1,4 +1,3 @@ -using System.Text; using Dalamud.Interface; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 5d74dc33..b95ba393 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -3,7 +3,6 @@ using OtterGui; using OtterGui.Raii; using Penumbra.GameData.Files; using Penumbra.String.Classes; -using System.Globalization; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index e475f47f..6b867b27 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -1,4 +1,3 @@ -using System.Text; using Dalamud.Interface.Internal.Notifications; using Dalamud.Interface; using ImGuiNET; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 1ee0a128..a3b17848 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index febb01cb..c659ada0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -1,4 +1,3 @@ -using System.Text; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.DragDrop; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index de5a179d..000e50db 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -1,4 +1,3 @@ -using System.Text.RegularExpressions; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; using ImGuiNET; diff --git a/Penumbra/Util/PenumbraSqPackStream.cs b/Penumbra/Util/PenumbraSqPackStream.cs index d913a019..562eca91 100644 --- a/Penumbra/Util/PenumbraSqPackStream.cs +++ b/Penumbra/Util/PenumbraSqPackStream.cs @@ -1,4 +1,3 @@ -using System.IO.Compression; using Lumina.Data.Structs; using Lumina.Extensions; From 8aebd441a1867e824acb029f0d8b6d42b923e3a9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 23 Sep 2023 14:25:32 +0200 Subject: [PATCH 0121/1381] Add option to disable conflicts from conflict panel. --- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 38737274..7fd0ae77 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -38,6 +38,8 @@ public class ModPanelConflictsTab : ITab { if (ImGui.Selectable(conflict.Mod2.Name) && conflict.Mod2 is Mod otherMod) _selector.SelectByValue(otherMod); + var hovered = ImGui.IsItemHovered(); + var rightClicked = ImGui.IsItemClicked(ImGuiMouseButton.Right); ImGui.SameLine(); using (var color = ImRaii.PushColor(ImGuiCol.Text, @@ -47,6 +49,16 @@ public class ModPanelConflictsTab : ITab ? conflict.Mod2.Priority : _collectionManager.Active.Current[conflict.Mod2.Index].Settings!.Priority; ImGui.TextUnformatted($"(Priority {priority})"); + hovered |= ImGui.IsItemHovered(); + rightClicked |= ImGui.IsItemClicked(ImGuiMouseButton.Right); + } + + if (conflict.Mod2 is Mod otherMod2) + { + if (hovered) + ImGui.SetTooltip("Click to jump to mod, Control + Right-Click to disable mod."); + if (rightClicked && ImGui.GetIO().KeyCtrl) + _collectionManager.Editor.SetModState(_collectionManager.Active.Current, otherMod2, false); } using var indent = ImRaii.PushIndent(30f); From 4c73453b4cd4ef7364674a5e5b879953166bab14 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 23 Sep 2023 12:30:49 +0000 Subject: [PATCH 0122/1381] [CI] Updating repo.json for testing_0.7.3.13 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 6eeaf412..60f0978a 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.12", + "TestingAssemblyVersion": "0.7.3.13", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.12/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.13/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 613092998532893cbe0291690d27ae7dfca2cd6a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 26 Sep 2023 14:16:09 +0200 Subject: [PATCH 0123/1381] Update API. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 6cc41dc1..9472b6e3 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 6cc41dc15241417fd72dc46ebca48cf7d2092f53 +Subproject commit 9472b6e327109216368c3dc1720159f5295bdb13 From 677d44442b8692d35160a5bbaa34a960d1cbeece Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 26 Sep 2023 14:18:45 +0200 Subject: [PATCH 0124/1381] Enable reset of substitutions. --- Penumbra/Api/DalamudSubstitutionProvider.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index fb966fe8..498c25e3 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -39,11 +39,10 @@ public class DalamudSubstitutionProvider : IDisposable public void ResetSubstitutions(IEnumerable paths) { - // TODO fix - //var transformed = paths - // .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) - // .Select(p => p.ToString()); - //_substitution.InvalidatePaths(transformed); + var transformed = paths + .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) + .Select(p => p.ToString()); + _substitution.InvalidatePaths(transformed); } public void Enable() From efdebeca54eb8f95b6020da0ceaa4f4a78382a69 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 26 Sep 2023 15:36:22 +0200 Subject: [PATCH 0125/1381] Add 0.8.0.0 Changelog --- OtterGui | 2 +- Penumbra/UI/Changelog.cs | 83 +++++++++++++++++++++++++++++++++------- 2 files changed, 71 insertions(+), 14 deletions(-) diff --git a/OtterGui b/OtterGui index 0f8a8664..05f7fba0 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 0f8a866491b246e819e0618a43078170686780ab +Subproject commit 05f7fba04156e81c099c87348632ecb03c877730 diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index ed62bf83..8a2b0fcb 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -41,10 +41,67 @@ public class PenumbraChangelog Add7_1_2(Changelog); Add7_2_0(Changelog); Add7_3_0(Changelog); + Add8_0_0(Changelog); } #region Changelogs + private static void Add8_0_0(Changelog log) + => log.NextVersion("Version 0.8.0.0") + .RegisterEntry( + "Penumbra now uses Windows' transparent file system compression by default (on Windows systems). You can disable this functionality in the settings.") + .RegisterImportant("You can retroactively compress your existing mods in the settings via the press of a button, too.", 1) + .RegisterEntry( + "In our tests, this not only was able to reduce storage space by 30-60%, it even decreased loading times since less I/O had to take place.", + 1) + .RegisterEntry("Added emotes to changed item identification.") + .RegisterEntry( + "Added quick select buttons to switch to the current interface collection or the collection applying to the current player character in the mods tab, reworked their text and tooltips slightly.") + .RegisterHighlight("Drag & Drop of multiple mods and folders at once is now supported by holding Control while clicking them.") + .RegisterEntry("You can now disable conflicting mods from the Conflicts panel via Control + Right-click.") + .RegisterEntry("Added checks for your deletion-modifiers for restoring mods from backups or deleting backups.") + .RegisterEntry( + "Penumbra now should automatically try to restore your custom sort order (mod folders) and your active collections from backups if they fail to load. No guarantees though.") + .RegisterEntry("The resource watcher now displays a column providing load state information of resources.") + .RegisterEntry( + "Custom RSP scaling outside of the collection assigned to Base should now be respected for emotes that adjust your stance on height differences.") + .RegisterEntry( + "Mods that replace the skin shaders will not cause visual glitches like loss of head shadows or Free Company crest tattoos anymore (by Ny).") + .RegisterEntry("The Material editor has been improved (by Ny):") + .RegisterHighlight( + "Live-Preview for materials yourself or entities owned by you are currently using, so you can see color set edits in real time.", + 1) + .RegisterEntry( + "Colors on the color table of a material can be highlighted on yourself or entities owned by you by hovering a button.", 1) + .RegisterEntry("The color table has improved color accuracy.", 1) + .RegisterEntry("Materials with non-dyable color tables can be made dyable, and vice-versa.", 1) + .RegisterEntry("The 'Advanced Shader Resources' section has been split apart into dedicated sections.", 1) + .RegisterEntry( + "Addition and removal of shader keys, textures, constants and a color table has been automated following shader requirements and can not be done manually anymore.", + 1) + .RegisterEntry("Plain English names and tooltips can now be displayed instead of hexadecimal identifiers or code names by providing dev-kit files installed via certain mods.", 1) + .RegisterEntry("The Texture editor has been improved (by Ny):") + .RegisterHighlight("The overlay texture can now be combined in several ways and automatically resized to match the input texture.", + 1) + .RegisterEntry("New color manipulation options have been added.", 1) + .RegisterEntry("Modifications to the selected texture can now be saved in-place.", 1) + .RegisterEntry("The On-Screen tab has been improved (by Ny):") + .RegisterEntry("The character list will load more quickly.", 1) + .RegisterEntry("It is now able to deal with characters under transformation effects.", 1) + .RegisterEntry( + "The headers are now color-coded to distinguish between you and other players, and between NPCs that are handled locally or on the server. Colors are customizable.", + 1) + .RegisterEntry("More file types will be recognized and shown.", 1) + .RegisterEntry("The actual paths for game files will be displayed and copied correctly.", 1) + .RegisterEntry("The Shader editor has been improved (by Ny):") + .RegisterEntry( + "New sections 'Shader Resources' and 'Shader Selection' have been added, expanding on some data that was in 'Further Content' before.", + 1) + .RegisterEntry("A fail-safe mode for shader decompilation on platforms that do not fully support it has been added.", 1) + .RegisterEntry("Fixed invalid game paths generated for variants of customizations.") + .RegisterEntry("Lots of minor improvements across the codebase.") + .RegisterEntry("Some unnamed mounts were made available for actor identification. (0.7.3.2)"); + private static void Add7_3_0(Changelog log) => log.NextVersion("Version 0.7.3.0") .RegisterEntry( @@ -124,7 +181,7 @@ public class PenumbraChangelog private static void Add7_1_0(Changelog log) => log.NextVersion("Version 0.7.1.0") .RegisterEntry("Updated for patch 6.4 - there may be some oversights on edge cases, but I could not find any issues myself.") - .RegisterHighlight( + .RegisterImportant( "This update changed some Dragoon skills that were moving the player character before to not do that anymore. If you have any mods that applied to those skills, please make sure that they do not contain any redirections for .tmb files. If skills that should no longer move your character still do that for some reason, this is detectable by the server.", 1) .RegisterEntry( @@ -171,7 +228,7 @@ public class PenumbraChangelog private static void Add7_0_0(Changelog log) => log.NextVersion("Version 0.7.0.0") - .RegisterHighlight( + .RegisterImportant( "The entire backend was reworked (this is still in progress). While this does not come with a lot of functionality changes, basically every file and functionality was touched.") .RegisterEntry( "This may have (re-)introduced some bugs that have not yet been noticed despite a long testing period - there are not many users of the testing branch.", @@ -375,10 +432,10 @@ public class PenumbraChangelog .RegisterEntry("You can now specify individual collections for players (by name) of specific worlds or any world.", 1) .RegisterEntry("You can also specify NPCs (by grouped name and type of NPC), and owned NPCs (by specifying an NPC and a Player).", 1) - .RegisterHighlight( + .RegisterImportant( "Migration should move all current names that correspond to NPCs to the appropriate NPC group and all names that can be valid Player names to a Player of any world.", 1) - .RegisterHighlight( + .RegisterImportant( "Please look through your Individual Collections to verify everything migrated correctly and corresponds to the game object you want. You might also want to change the 'Player (Any World)' collections to your specific homeworld.", 1) .RegisterEntry("You can also manually sort your Individual Collections by drag and drop now.", 1) @@ -424,7 +481,7 @@ public class PenumbraChangelog .RegisterEntry( "I believe the problem is fixed with 0.5.11.1, but I can not be sure since it would occur only rarely. For the same reason, a testing build would not help (as it also did not with 0.5.11.0 itself).", 1) - .RegisterHighlight( + .RegisterImportant( "If you do encounter this or similar problems in 0.5.11.1, please immediately let me know in Discord so I can revert the update again.", 1); @@ -472,7 +529,7 @@ public class PenumbraChangelog private static void Add5_8_7(Changelog log) => log.NextVersion("Version 0.5.8.7") .RegisterEntry("Fixed some problems with metadata reloading and reverting and IMC files. (5.8.1 to 5.8.7).") - .RegisterHighlight( + .RegisterImportant( "If you encounter any issues, please try completely restarting your game after updating (not just relogging), before reporting them.", 1); @@ -482,11 +539,11 @@ public class PenumbraChangelog .RegisterEntry("Added an Interface Collection assignment.") .RegisterEntry("All your UI mods will have to be in the interface collection.", 1) .RegisterEntry("Files that are categorized as UI files by the game will only check for redirections in this collection.", 1) - .RegisterHighlight( + .RegisterImportant( "Migration should have set your currently assigned Base Collection to the Interface Collection, please verify that.", 1) .RegisterEntry("New API / IPC for the Interface Collection added.", 1) - .RegisterHighlight("API / IPC consumers should verify whether they need to change resolving to the new collection.", 1) - .RegisterHighlight( + .RegisterImportant("API / IPC consumers should verify whether they need to change resolving to the new collection.", 1) + .RegisterImportant( "If other plugins are not using your interface collection yet, you can just keep Interface and Base the same collection for the time being.") .RegisterEntry( "Mods can now have default settings for each option group, that are shown while the mod is unconfigured and taken as initial values when configured.") @@ -499,7 +556,7 @@ public class PenumbraChangelog .RegisterEntry("Should work with lot more texture types for .dds and .tex files, most notably BC7 compression.", 1) .RegisterEntry("Supports saving .tex and .dds files in multiple texture types and generating MipMaps for them.", 1) .RegisterEntry("Interface reworked a bit, gives more information and the overlay side can be collapsed.", 1) - .RegisterHighlight( + .RegisterImportant( "May contain bugs or missing safeguards. Generally let me know what's missing, ugly, buggy, not working or could be improved. Not really feasible for me to test it all.", 1) .RegisterEntry( @@ -524,9 +581,9 @@ public class PenumbraChangelog => log.NextVersion("Version 0.5.7.0") .RegisterEntry("Added a Changelog!") .RegisterEntry("Files in the UI category will no longer be deduplicated for the moment.") - .RegisterHighlight("If you experience UI-related crashes, please re-import your UI mods.", 1) + .RegisterImportant("If you experience UI-related crashes, please re-import your UI mods.", 1) .RegisterEntry("This is a temporary fix against those not-yet fully understood crashes and may be reworked later.", 1) - .RegisterHighlight( + .RegisterImportant( "There is still a possibility of UI related mods crashing the game, we are still investigating - they behave very weirdly. If you continue to experience crashing, try disabling your UI mods.", 1) .RegisterEntry( @@ -534,7 +591,7 @@ public class PenumbraChangelog .RegisterEntry( "Penumbra Mod Pack ('.pmp') files are meant to be renames of any of the archive types that could already be imported that contain the necessary Penumbra meta files.", 1) - .RegisterHighlight( + .RegisterImportant( "If you distribute any mod as an archive specifically for Penumbra, you should change its extension to '.pmp'. Supported base archive types are ZIP, 7-Zip and RAR.", 1) .RegisterEntry("Penumbra will now save mod backups with the file extension '.pmp'. They still are regular ZIP files.", 1) From 6ca8ad2385d0b3eec2de35150a40657fe3343077 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 26 Sep 2023 13:46:33 +0000 Subject: [PATCH 0126/1381] [CI] Updating repo.json for 0.8.0.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 60f0978a..1fc24a13 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.7.3.2", - "TestingAssemblyVersion": "0.7.3.13", + "AssemblyVersion": "0.8.0.0", + "TestingAssemblyVersion": "0.8.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 8, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.7.3.13/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.7.3.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 6799bdbb0381dc4f473576ab9dec1a49f1c3cfe4 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 27 Sep 2023 03:15:18 +0200 Subject: [PATCH 0127/1381] Material Editor: Allow intentional 0 gloss --- .../UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index cccc43ee..f1e48200 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -347,10 +347,11 @@ public partial class ModEditWindow ImGui.TableNextColumn(); tmpFloat = row.GlossStrength; ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), HalfEpsilon, HalfMaxValue, "%.1f") + float glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; + if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), glossStrengthMin, HalfMaxValue, "%.1f") && FixFloat(ref tmpFloat, row.GlossStrength)) { - row.GlossStrength = Math.Max(tmpFloat, HalfEpsilon); + row.GlossStrength = Math.Max(tmpFloat, glossStrengthMin); ret = true; tab.UpdateColorTableRowPreview(rowIdx); } From 929db5c1a47d69c4a1966ddfe54bf7e107b97894 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Sep 2023 15:52:42 +0200 Subject: [PATCH 0128/1381] Make renaming search paths in context more clear. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 8 ++++++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 05f7fba0..45117034 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 05f7fba04156e81c099c87348632ecb03c877730 +Subproject commit 4511703462faa6d3126a52e29b1c509bd275599c diff --git a/Penumbra.GameData b/Penumbra.GameData index ef403be9..d400686c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ef403be979bfac5ef805030ce76066151d36f112 +Subproject commit d400686c8bfb0b9f72fa0c3301d1fe1df9be525b diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 3a7a7343..39fc7a0e 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -65,6 +65,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector ClearQuickMove(0, _config.QuickMoveFolder1, () => {_config.QuickMoveFolder1 = string.Empty; _config.Save();}), 110); SubscribeRightClickMain(() => ClearQuickMove(1, _config.QuickMoveFolder2, () => {_config.QuickMoveFolder2 = string.Empty; _config.Save();}), 120); SubscribeRightClickMain(() => ClearQuickMove(2, _config.QuickMoveFolder3, () => {_config.QuickMoveFolder3 = string.Empty; _config.Save();}), 130); + UnsubscribeRightClickLeaf(RenameLeaf); + SubscribeRightClickLeaf(RenameLeafMod, 1000); AddButton(AddNewModButton, 0); AddButton(AddImportModButton, 1); AddButton(AddHelpButton, 2); @@ -268,6 +270,12 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Wed, 27 Sep 2023 15:59:42 +0200 Subject: [PATCH 0129/1381] Oops. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 45117034..9b431c1f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 4511703462faa6d3126a52e29b1c509bd275599c +Subproject commit 9b431c1f491c0739132da65da08bc092d7ff79da From 50f6de78092e36f6ee6b7906cb06b362539a21d4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Sep 2023 17:26:39 +0200 Subject: [PATCH 0130/1381] Update API Level. --- Penumbra/Penumbra.json | 4 ++-- repo.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index cf7170d8..d1682985 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -7,9 +7,9 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], - "DalamudApiLevel": 8, + "DalamudApiLevel": 9, "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" -} \ No newline at end of file +} diff --git a/repo.json b/repo.json index 1fc24a13..639eb985 100644 --- a/repo.json +++ b/repo.json @@ -8,7 +8,7 @@ "TestingAssemblyVersion": "0.8.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 8, + "DalamudApiLevel": 9, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 21d503a8cdab3b5b267654d185bd616287f9751a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Sep 2023 18:12:27 +0200 Subject: [PATCH 0131/1381] Update for API 9 --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/IpcTester.cs | 2 +- .../Cache/CollectionCacheManager.cs | 4 +-- Penumbra/CommandHandler.cs | 6 ++-- Penumbra/Import/Textures/BaseImage.cs | 2 +- .../Textures/CombinedTexture.Manipulation.cs | 12 +++---- Penumbra/Import/Textures/TexFileParser.cs | 14 ++++---- Penumbra/Import/Textures/Texture.cs | 12 +++---- Penumbra/Import/Textures/TextureDrawer.cs | 4 +-- Penumbra/Import/Textures/TextureManager.cs | 10 +++--- .../LiveColorTablePreviewer.cs | 8 ++--- .../PathResolving/AnimationHookService.cs | 6 ++-- .../Interop/PathResolving/DrawObjectState.cs | 4 +-- .../IdentifiedCollectionCache.cs | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 7 ++-- Penumbra/Interop/PathResolving/PathState.cs | 13 +++---- .../Interop/PathResolving/ResolvePathHooks.cs | 35 ++++++++++--------- .../Interop/PathResolving/SubfileHelper.cs | 5 +-- .../ResourceLoading/CreateFileWHook.cs | 5 +-- .../ResourceLoading/FileReadService.cs | 5 +-- .../ResourceLoading/ResourceManagerService.cs | 5 +-- .../ResourceLoading/ResourceService.cs | 10 +++--- .../Interop/ResourceLoading/TexMdlService.cs | 5 +-- .../Interop/SafeHandles/SafeTextureHandle.cs | 2 +- Penumbra/Interop/Services/CharacterUtility.cs | 10 +++--- Penumbra/Interop/Services/FontReloader.cs | 3 +- Penumbra/Interop/Services/GameEventManager.cs | 5 +-- Penumbra/Interop/Services/RedrawService.cs | 6 ++-- .../Services/ResidentResourceManager.cs | 7 ++-- Penumbra/Interop/Services/SkinFixer.cs | 7 ++-- Penumbra/Interop/Structs/CharacterBaseExt.cs | 2 +- Penumbra/Interop/Structs/Material.cs | 2 +- Penumbra/Interop/Structs/TextureUtility.cs | 32 +++++++---------- Penumbra/Meta/MetaFileManager.cs | 4 +-- Penumbra/Mods/Manager/ModStorage.cs | 2 +- Penumbra/Penumbra.cs | 8 +++-- Penumbra/Services/ChatService.cs | 8 ++--- Penumbra/Services/DalamudServices.cs | 17 ++++----- Penumbra/Services/ServiceManager.cs | 5 ++- Penumbra/Services/StainService.cs | 8 ++--- Penumbra/Services/Wrappers.cs | 12 +++---- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 4 +-- .../ModEditWindow.Materials.ColorTable.cs | 1 + .../AdvancedWindow/ModEditWindow.Materials.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 1 + Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 2 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 1 + Penumbra/UI/ChangedItemDrawer.cs | 18 +++++----- Penumbra/UI/CollectionTab/CollectionCombo.cs | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 1 + .../CollectionTab/IndividualAssignmentUi.cs | 12 +++---- Penumbra/UI/LaunchButton.cs | 17 ++++----- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 7 ++-- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 1 + Penumbra/UI/Tabs/CollectionsTab.cs | 1 + Penumbra/UI/Tabs/DebugTab.cs | 5 +-- Penumbra/UI/UiHelpers.cs | 2 +- 61 files changed, 210 insertions(+), 192 deletions(-) diff --git a/OtterGui b/OtterGui index 9b431c1f..c70fcc06 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9b431c1f491c0739132da65da08bc092d7ff79da +Subproject commit c70fcc069ea44e1ffb8b33fc409c4ccfdef5e298 diff --git a/Penumbra.GameData b/Penumbra.GameData index d400686c..3c9e0d03 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d400686c8bfb0b9f72fa0c3301d1fe1df9be525b +Subproject commit 3c9e0d03281c350f8260debb0eab4059408cd0cd diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 148d4481..dd800f0a 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Utility; using Dalamud.Plugin; using ImGuiNET; using OtterGui; @@ -15,7 +16,6 @@ using Penumbra.Services; using Penumbra.UI; using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; -using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; namespace Penumbra.Api; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 5daecaa9..a24eb2fa 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -1,4 +1,4 @@ -using Dalamud.Game; +using Dalamud.Plugin.Services; using OtterGui.Classes; using Penumbra.Api; using Penumbra.Api.Enums; @@ -382,7 +382,7 @@ public class CollectionCacheManager : IDisposable /// /// Update forced files only on framework. /// - private void OnFramework(Framework _) + private void OnFramework(IFramework _) { while (_changeQueue.TryDequeue(out var changeData)) changeData.Apply(); diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 920e9cef..3249cc43 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -1,6 +1,4 @@ -using Dalamud.Game; using Dalamud.Game.Command; -using Dalamud.Game.Gui; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin.Services; using ImGuiNET; @@ -23,7 +21,7 @@ public class CommandHandler : IDisposable private readonly ICommandManager _commandManager; private readonly RedrawService _redrawService; - private readonly ChatGui _chat; + private readonly IChatGui _chat; private readonly Configuration _config; private readonly ConfigWindow _configWindow; private readonly ActorManager _actors; @@ -32,7 +30,7 @@ public class CommandHandler : IDisposable private readonly Penumbra _penumbra; private readonly CollectionEditor _collectionEditor; - public CommandHandler(Framework framework, ICommandManager commandManager, ChatGui chat, RedrawService redrawService, Configuration config, + public CommandHandler(IFramework framework, ICommandManager commandManager, IChatGui chat, RedrawService redrawService, Configuration config, ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorService actors, Penumbra penumbra, CollectionEditor collectionEditor) { diff --git a/Penumbra/Import/Textures/BaseImage.cs b/Penumbra/Import/Textures/BaseImage.cs index 4f8c5305..a4a0e203 100644 --- a/Penumbra/Import/Textures/BaseImage.cs +++ b/Penumbra/Import/Textures/BaseImage.cs @@ -103,7 +103,7 @@ public readonly struct BaseImage : IDisposable { null => 0, ScratchImage s => s.Meta.MipLevels, - TexFile t => t.Header.MipLevels, + TexFile t => t.Header.MipLevelsCount, _ => 1, }; } diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 8bac0a3b..2d131d71 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -2,7 +2,7 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; using SixLabors.ImageSharp.PixelFormats; -using Dalamud.Interface; +using Dalamud.Interface.Utility; using Penumbra.UI; namespace Penumbra.Import.Textures; @@ -13,11 +13,11 @@ public partial class CombinedTexture private Vector4 _constantLeft = Vector4.Zero; private Matrix4x4 _multiplierRight = Matrix4x4.Identity; private Vector4 _constantRight = Vector4.Zero; - private int _offsetX = 0; - private int _offsetY = 0; - private CombineOp _combineOp = CombineOp.Over; - private ResizeOp _resizeOp = ResizeOp.None; - private Channels _copyChannels = Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha; + private int _offsetX; + private int _offsetY; + private CombineOp _combineOp = CombineOp.Over; + private ResizeOp _resizeOp = ResizeOp.None; + private Channels _copyChannels = Channels.Red | Channels.Green | Channels.Blue | Channels.Alpha; private RgbaPixelData _leftPixels = RgbaPixelData.Empty; private RgbaPixelData _rightPixels = RgbaPixelData.Empty; diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 15d45be6..629cdff5 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -79,7 +79,7 @@ public static class TexFileParser w.Write(header.Width); w.Write(header.Height); w.Write(header.Depth); - w.Write((byte)header.MipLevels); + w.Write(header.MipLevelsCount); w.Write((byte)0); // TODO Lumina Update unsafe { @@ -96,11 +96,11 @@ public static class TexFileParser var meta = scratch.Meta; var ret = new TexFile.TexHeader() { - Height = (ushort)meta.Height, - Width = (ushort)meta.Width, - Depth = (ushort)Math.Max(meta.Depth, 1), - MipLevels = (byte)Math.Min(meta.MipLevels, 13), - Format = meta.Format.ToTexFormat(), + Height = (ushort)meta.Height, + Width = (ushort)meta.Width, + Depth = (ushort)Math.Max(meta.Depth, 1), + MipLevelsCount = (byte)Math.Min(meta.MipLevels, 13), + Format = meta.Format.ToTexFormat(), Type = meta.Dimension switch { _ when meta.IsCubeMap => TexFile.Attribute.TextureTypeCube, @@ -143,7 +143,7 @@ public static class TexFileParser Height = header.Height, Width = header.Width, Depth = Math.Max(header.Depth, (ushort)1), - MipLevels = header.MipLevels, + MipLevels = header.MipLevelsCount, ArraySize = 1, Format = header.Format.ToDXGI(), Dimension = header.Type.ToDimension(), diff --git a/Penumbra/Import/Textures/Texture.cs b/Penumbra/Import/Textures/Texture.cs index fe1d3371..c4d6dc56 100644 --- a/Penumbra/Import/Textures/Texture.cs +++ b/Penumbra/Import/Textures/Texture.cs @@ -1,4 +1,4 @@ -using ImGuiScene; +using Dalamud.Interface.Internal; using OtterTex; namespace Penumbra.Import.Textures; @@ -21,7 +21,7 @@ public sealed class Texture : IDisposable internal string? TmpPath; // If the load failed, an exception is stored. - public Exception? LoadError = null; + public Exception? LoadError; // The pixels of the main image in RGBA order. // Empty if LoadError != null or Path is empty. @@ -29,7 +29,7 @@ public sealed class Texture : IDisposable // The ImGui wrapper to load the image. // null if LoadError != null or Path is empty. - public TextureWrap? TextureWrap = null; + public IDalamudTextureWrap? TextureWrap; // The base image in whatever format it has. public BaseImage BaseImage; @@ -76,9 +76,9 @@ public sealed class Texture : IDisposable try { - (BaseImage, Type) = textures.Load(path); - (RgbaPixels, var width, var height) = BaseImage.GetPixelData(); - TextureWrap = textures.LoadTextureWrap(BaseImage, RgbaPixels); + (BaseImage, Type) = textures.Load(path); + (RgbaPixels, _, _) = BaseImage.GetPixelData(); + TextureWrap = textures.LoadTextureWrap(BaseImage, RgbaPixels); Loaded?.Invoke(true); } catch (Exception e) diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index a5692c23..bea28749 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -94,7 +94,7 @@ public static class TextureDrawer ImGuiUtil.DrawTableColumn("Format"); ImGuiUtil.DrawTableColumn(t.Header.Format.ToString()); ImGuiUtil.DrawTableColumn("Mip Levels"); - ImGuiUtil.DrawTableColumn(t.Header.MipLevels.ToString()); + ImGuiUtil.DrawTableColumn(t.Header.MipLevelsCount.ToString()); ImGuiUtil.DrawTableColumn("Data Size"); ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(t.ImageData.Length)} ({t.ImageData.Length} Bytes)"); break; @@ -106,7 +106,7 @@ public static class TextureDrawer private int _skipPrefix = 0; public PathSelectCombo(TextureManager textures, ModEditor editor) - : base(() => CreateFiles(textures, editor)) + : base(() => CreateFiles(textures, editor), Penumbra.Log) { } protected override string ToString((string, bool) obj) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 31c3275e..5653d760 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; +using Dalamud.Interface.Internal; using Dalamud.Plugin.Services; -using ImGuiScene; using Lumina.Data.Files; using OtterGui.Log; using OtterGui.Tasks; @@ -19,7 +19,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable private readonly IDataManager _gameData; private readonly ConcurrentDictionary _tasks = new(); - private bool _disposed = false; + private bool _disposed; public TextureManager(UiBuilder uiBuilder, IDataManager gameData, Logger logger) { @@ -209,14 +209,14 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable } /// Load a texture wrap for a given image. - public TextureWrap LoadTextureWrap(BaseImage image, byte[]? rgba = null, int width = 0, int height = 0) + public IDalamudTextureWrap LoadTextureWrap(BaseImage image, byte[]? rgba = null, int width = 0, int height = 0) { (rgba, width, height) = GetData(image, rgba, width, height); return LoadTextureWrap(rgba, width, height); } /// Load a texture wrap for a given image. - public TextureWrap LoadTextureWrap(byte[] rgba, int width, int height) + public IDalamudTextureWrap LoadTextureWrap(byte[] rgba, int width, int height) => _uiBuilder.LoadImageRaw(rgba, width, height, 4); /// Load any supported file from game data or drive depending on extension and if the path is rooted. @@ -335,7 +335,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable if (numMips == input.Meta.MipLevels) return input; - var flags = (Dalamud.Utility.Util.IsLinux() ? FilterFlags.ForceNonWIC : 0) | FilterFlags.SeparateAlpha; + var flags = (Dalamud.Utility.Util.IsWine() ? FilterFlags.ForceNonWIC : 0) | FilterFlags.SeparateAlpha; var ec = input.GenerateMipMaps(out var ret, numMips, flags); if (ec != ErrorCode.Ok) throw new Exception( diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index e89f0d10..bacc72fa 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -1,7 +1,5 @@ -using Dalamud.Game; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using Penumbra.GameData.Files; using Penumbra.Interop.SafeHandles; @@ -13,7 +11,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase public const int TextureHeight = MtrlFile.ColorTable.NumRows; public const int TextureLength = TextureWidth * TextureHeight * 4; - private readonly Framework _framework; + private readonly IFramework _framework; private readonly Texture** _colorTableTexture; private readonly SafeTextureHandle _originalColorTableTexture; @@ -24,7 +22,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase public Half[] ColorTable => _colorTable; - public LiveColorTablePreviewer(IObjectTable objects, Framework framework, MaterialInfo materialInfo) + public LiveColorTablePreviewer(IObjectTable objects, IFramework framework, MaterialInfo materialInfo) : base(objects, materialInfo) { _framework = framework; @@ -66,7 +64,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase _updatePending = true; } - private void OnFrameworkUpdate(Framework _) + private void OnFrameworkUpdate(IFramework _) { if (!_updatePending) return; diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index 616cb2f6..7f69ceef 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -21,13 +21,13 @@ public unsafe class AnimationHookService : IDisposable private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; private readonly CollectionResolver _resolver; - private readonly Condition _conditions; + private readonly ICondition _conditions; private readonly ThreadLocal _animationLoadData = new(() => ResolveData.Invalid, true); private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); public AnimationHookService(PerformanceTracker performance, IObjectTable objects, CollectionResolver collectionResolver, - DrawObjectState drawObjectState, CollectionResolver resolver, Condition conditions) + DrawObjectState drawObjectState, CollectionResolver resolver, ICondition conditions, IGameInteropProvider interop) { _performance = performance; _objects = objects; @@ -36,7 +36,7 @@ public unsafe class AnimationHookService : IDisposable _resolver = resolver; _conditions = conditions; - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _loadCharacterSoundHook.Enable(); _loadTimelineResourcesHook.Enable(); diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index be1484db..9726d84c 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -20,9 +20,9 @@ public class DrawObjectState : IDisposable, IReadOnlyDictionary _lastGameObject.IsValueCreated && _lastGameObject.Value!.Count > 0 ? _lastGameObject.Value.Peek() : nint.Zero; - public DrawObjectState(IObjectTable objects, GameEventManager gameEvents) + public DrawObjectState(IObjectTable objects, GameEventManager gameEvents, IGameInteropProvider interop) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _enableDrawHook.Enable(); _objects = objects; _gameEvents = gameEvents; diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 0b456b3c..73c20ab9 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -85,7 +85,7 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A _dirty = _cache.Count > 0; } - private void TerritoryClear(object? _1, ushort _2) + private void TerritoryClear(ushort _2) => _dirty = _cache.Count > 0; private void OnCharacterDestruct(Character* character) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index a68e376b..6defe78c 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; @@ -59,7 +60,7 @@ public unsafe class MetaState : IDisposable private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; public MetaState(PerformanceTracker performance, CommunicatorService communicator, CollectionResolver collectionResolver, - ResourceLoader resources, GameEventManager gameEventManager, CharacterUtility characterUtility, Configuration config) + ResourceLoader resources, GameEventManager gameEventManager, CharacterUtility characterUtility, Configuration config, IGameInteropProvider interop) { _performance = performance; _communicator = communicator; @@ -68,8 +69,8 @@ public unsafe class MetaState : IDisposable _gameEventManager = gameEventManager; _characterUtility = characterUtility; _config = config; - SignatureHelper.Initialise(this); - _onModelLoadCompleteHook = Hook.FromAddress(_humanVTable[58], OnModelLoadCompleteDetour); + interop.InitializeFromAttributes(this); + _onModelLoadCompleteHook = interop.HookFromAddress(_humanVTable[58], OnModelLoadCompleteDetour); _getEqpIndirectHook.Enable(); _updateModelsHook.Enable(); _onModelLoadCompleteHook.Enable(); diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index 0c6566a3..4fb3d31d 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using Penumbra.Collections; using Penumbra.GameData; @@ -34,16 +35,16 @@ public unsafe class PathState : IDisposable public IList CurrentData => _resolveData.Values; - public PathState(CollectionResolver collectionResolver, MetaState metaState, CharacterUtility characterUtility) + public PathState(CollectionResolver collectionResolver, MetaState metaState, CharacterUtility characterUtility, IGameInteropProvider interop) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); CollectionResolver = collectionResolver; MetaState = metaState; CharacterUtility = characterUtility; - _human = new ResolvePathHooks(this, _humanVTable, ResolvePathHooks.Type.Human); - _weapon = new ResolvePathHooks(this, _weaponVTable, ResolvePathHooks.Type.Weapon); - _demiHuman = new ResolvePathHooks(this, _demiHumanVTable, ResolvePathHooks.Type.Other); - _monster = new ResolvePathHooks(this, _monsterVTable, ResolvePathHooks.Type.Other); + _human = new ResolvePathHooks(interop, this, _humanVTable, ResolvePathHooks.Type.Human); + _weapon = new ResolvePathHooks(interop, this, _weaponVTable, ResolvePathHooks.Type.Weapon); + _demiHuman = new ResolvePathHooks(interop, this, _demiHumanVTable, ResolvePathHooks.Type.Other); + _monster = new ResolvePathHooks(interop, this, _monsterVTable, ResolvePathHooks.Type.Other); _human.Enable(); _weapon.Enable(); _demiHuman.Enable(); diff --git a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs index 6f8f93dd..f9a341b9 100644 --- a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs +++ b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using Penumbra.Collections; @@ -35,21 +36,21 @@ public unsafe class ResolvePathHooks : IDisposable private readonly PathState _parent; - public ResolvePathHooks(PathState parent, nint* vTable, Type type) + public ResolvePathHooks(IGameInteropProvider interop, PathState parent, nint* vTable, Type type) { _parent = parent; - _resolveDecalPathHook = Create(vTable[83], type, ResolveDecalWeapon, ResolveDecal); - _resolveEidPathHook = Create(vTable[85], type, ResolveEidWeapon, ResolveEid); - _resolveImcPathHook = Create(vTable[81], type, ResolveImcWeapon, ResolveImc); - _resolveMPapPathHook = Create(vTable[79], type, ResolveMPapWeapon, ResolveMPap); - _resolveMdlPathHook = Create(vTable[73], type, ResolveMdlWeapon, ResolveMdl, ResolveMdlHuman); - _resolveMtrlPathHook = Create(vTable[82], type, ResolveMtrlWeapon, ResolveMtrl); - _resolvePapPathHook = Create(vTable[76], type, ResolvePapWeapon, ResolvePap, ResolvePapHuman); - _resolvePhybPathHook = Create(vTable[75], type, ResolvePhybWeapon, ResolvePhyb, ResolvePhybHuman); - _resolveSklbPathHook = Create(vTable[72], type, ResolveSklbWeapon, ResolveSklb, ResolveSklbHuman); - _resolveSkpPathHook = Create(vTable[74], type, ResolveSkpWeapon, ResolveSkp, ResolveSkpHuman); - _resolveTmbPathHook = Create(vTable[77], type, ResolveTmbWeapon, ResolveTmb); - _resolveVfxPathHook = Create(vTable[84], type, ResolveVfxWeapon, ResolveVfx); + _resolveDecalPathHook = Create(interop, vTable[83], type, ResolveDecalWeapon, ResolveDecal); + _resolveEidPathHook = Create(interop, vTable[85], type, ResolveEidWeapon, ResolveEid); + _resolveImcPathHook = Create(interop, vTable[81], type, ResolveImcWeapon, ResolveImc); + _resolveMPapPathHook = Create(interop, vTable[79], type, ResolveMPapWeapon, ResolveMPap); + _resolveMdlPathHook = Create(interop, vTable[73], type, ResolveMdlWeapon, ResolveMdl, ResolveMdlHuman); + _resolveMtrlPathHook = Create(interop, vTable[82], type, ResolveMtrlWeapon, ResolveMtrl); + _resolvePapPathHook = Create(interop, vTable[76], type, ResolvePapWeapon, ResolvePap, ResolvePapHuman); + _resolvePhybPathHook = Create(interop, vTable[75], type, ResolvePhybWeapon, ResolvePhyb, ResolvePhybHuman); + _resolveSklbPathHook = Create(interop, vTable[72], type, ResolveSklbWeapon, ResolveSklb, ResolveSklbHuman); + _resolveSkpPathHook = Create(interop, vTable[74], type, ResolveSkpWeapon, ResolveSkp, ResolveSkpHuman); + _resolveTmbPathHook = Create(interop, vTable[77], type, ResolveTmbWeapon, ResolveTmb); + _resolveVfxPathHook = Create(interop, vTable[84], type, ResolveVfxWeapon, ResolveVfx); } public void Enable() @@ -217,7 +218,7 @@ public unsafe class ResolvePathHooks : IDisposable [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(nint address, Type type, T weapon, T other, T human) where T : Delegate + private static Hook Create(IGameInteropProvider interop, nint address, Type type, T weapon, T other, T human) where T : Delegate { var del = type switch { @@ -225,12 +226,12 @@ public unsafe class ResolvePathHooks : IDisposable Type.Weapon => weapon, _ => other, }; - return Hook.FromAddress(address, del); + return interop.HookFromAddress(address, del); } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(nint address, Type type, T weapon, T other) where T : Delegate - => Create(address, type, weapon, other, other); + private static Hook Create(IGameInteropProvider interop, nint address, Type type, T weapon, T other) where T : Delegate + => Create(interop, address, type, weapon, other, other); // Implementation diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index a8fd816a..3a60450d 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -30,9 +31,9 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection _subFileCollection = new(); - public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, GameEventManager events, CommunicatorService communicator) + public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, GameEventManager events, CommunicatorService communicator, IGameInteropProvider interop) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _performance = performance; _loader = loader; diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs index ca9c2577..b77ac1e0 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.String.Functions; @@ -14,9 +15,9 @@ public unsafe class CreateFileWHook : IDisposable { public const int RequiredSize = 28; - public CreateFileWHook() + public CreateFileWHook(IGameInteropProvider interop) { - _createFileWHook = Hook.FromImport(null, "KERNEL32.dll", "CreateFileW", 0, CreateFileWDetour); + _createFileWHook = interop.HookFromImport(null, "KERNEL32.dll", "CreateFileW", 0, CreateFileWDetour); _createFileWHook.Enable(); } diff --git a/Penumbra/Interop/ResourceLoading/FileReadService.cs b/Penumbra/Interop/ResourceLoading/FileReadService.cs index 9dc89ab2..64442771 100644 --- a/Penumbra/Interop/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/ResourceLoading/FileReadService.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using Penumbra.GameData; using Penumbra.Interop.Structs; @@ -8,11 +9,11 @@ namespace Penumbra.Interop.ResourceLoading; public unsafe class FileReadService : IDisposable { - public FileReadService(PerformanceTracker performance, ResourceManagerService resourceManager) + public FileReadService(PerformanceTracker performance, ResourceManagerService resourceManager, IGameInteropProvider interop) { _resourceManager = resourceManager; _performance = performance; - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _readSqPackHook.Enable(); } diff --git a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs index ce7d3d4c..a087a659 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; @@ -10,8 +11,8 @@ namespace Penumbra.Interop.ResourceLoading; public unsafe class ResourceManagerService { - public ResourceManagerService() - => SignatureHelper.Initialise(this); + public ResourceManagerService(IGameInteropProvider interop) + => interop.InitializeFromAttributes(this); /// The SE Resource Manager as pointer. public ResourceManager* ResourceManager diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 5d060d85..47107f44 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -1,8 +1,8 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; -using Penumbra.Collections; using Penumbra.GameData; using Penumbra.Interop.Structs; using Penumbra.String; @@ -16,19 +16,19 @@ public unsafe class ResourceService : IDisposable private readonly PerformanceTracker _performance; private readonly ResourceManagerService _resourceManager; - public ResourceService(PerformanceTracker performance, ResourceManagerService resourceManager) + public ResourceService(PerformanceTracker performance, ResourceManagerService resourceManager, IGameInteropProvider interop) { _performance = performance; _resourceManager = resourceManager; - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _getResourceSyncHook.Enable(); _getResourceAsyncHook.Enable(); _resourceHandleDestructorHook.Enable(); - _incRefHook = Hook.FromAddress( + _incRefHook = interop.HookFromAddress( (nint)FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle.MemberFunctionPointers.IncRef, ResourceHandleIncRefDetour); _incRefHook.Enable(); - _decRefHook = Hook.FromAddress( + _decRefHook = interop.HookFromAddress( (nint)FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle.MemberFunctionPointers.DecRef, ResourceHandleDecRefDetour); _decRefHook.Enable(); diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/ResourceLoading/TexMdlService.cs index 574da240..68ad518c 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/ResourceLoading/TexMdlService.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.Api.Enums; @@ -19,9 +20,9 @@ public unsafe class TexMdlService public IReadOnlySet CustomFileCrc => _customFileCrc; - public TexMdlService() + public TexMdlService(IGameInteropProvider interop) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _checkFileStateHook.Enable(); _loadTexFileExternHook.Enable(); _loadMdlFileExternHook.Enable(); diff --git a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs index dee28797..df97371b 100644 --- a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs @@ -1,4 +1,4 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using Penumbra.Interop.Structs; namespace Penumbra.Interop.SafeHandles; diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 48824888..699b59e0 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -1,4 +1,4 @@ -using Dalamud.Game; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using Penumbra.Collections.Manager; using Penumbra.GameData; @@ -6,7 +6,7 @@ using Penumbra.Interop.Structs; namespace Penumbra.Interop.Services; -public unsafe partial class CharacterUtility : IDisposable +public unsafe class CharacterUtility : IDisposable { public record struct InternalIndex(int Value); @@ -52,12 +52,12 @@ public unsafe partial class CharacterUtility : IDisposable public (nint Address, int Size) DefaultResource(InternalIndex idx) => _lists[idx.Value].DefaultResource; - private readonly Framework _framework; + private readonly IFramework _framework; public readonly ActiveCollectionData Active; - public CharacterUtility(Framework framework, ActiveCollectionData active) + public CharacterUtility(IFramework framework, IGameInteropProvider interop, ActiveCollectionData active) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _lists = Enumerable.Range(0, RelevantIndices.Length) .Select(idx => new MetaList(this, new InternalIndex(idx))) .ToArray(); diff --git a/Penumbra/Interop/Services/FontReloader.cs b/Penumbra/Interop/Services/FontReloader.cs index 76a205dc..2f4a3cfd 100644 --- a/Penumbra/Interop/Services/FontReloader.cs +++ b/Penumbra/Interop/Services/FontReloader.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.System.Framework; using FFXIVClientStructs.FFXIV.Component.GUI; using Penumbra.GameData; @@ -24,7 +25,7 @@ public unsafe class FontReloader private AtkModule* _atkModule = null!; private delegate* unmanaged _reloadFontsFunc = null!; - public FontReloader(Dalamud.Game.Framework dFramework) + public FontReloader(IFramework dFramework) { dFramework.RunOnFrameworkThread(() => { diff --git a/Penumbra/Interop/Services/GameEventManager.cs b/Penumbra/Interop/Services/GameEventManager.cs index 2e8a23f0..59714ff0 100644 --- a/Penumbra/Interop/Services/GameEventManager.cs +++ b/Penumbra/Interop/Services/GameEventManager.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using Penumbra.GameData; using FFXIVClientStructs.FFXIV.Client.Game.Character; @@ -20,9 +21,9 @@ public unsafe class GameEventManager : IDisposable public event WeaponReloadingEvent? WeaponReloading; public event WeaponReloadedEvent? WeaponReloaded; - public GameEventManager() + public GameEventManager(IGameInteropProvider interop) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _characterDtorHook.Enable(); _copyCharacterHook.Enable(); _resourceHandleDestructorHook.Enable(); diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 65d5b0c0..0864bb71 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -100,10 +100,10 @@ public unsafe partial class RedrawService public sealed unsafe partial class RedrawService : IDisposable { - private readonly Framework _framework; + private readonly IFramework _framework; private readonly IObjectTable _objects; private readonly ITargetManager _targets; - private readonly Condition _conditions; + private readonly ICondition _conditions; private readonly List _queue = new(100); private readonly List _afterGPoseQueue = new(GPoseSlots); @@ -111,7 +111,7 @@ public sealed unsafe partial class RedrawService : IDisposable public event GameObjectRedrawnDelegate? GameObjectRedrawn; - public RedrawService(Framework framework, IObjectTable objects, ITargetManager targets, Condition conditions) + public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions) { _framework = framework; _objects = objects; diff --git a/Penumbra/Interop/Services/ResidentResourceManager.cs b/Penumbra/Interop/Services/ResidentResourceManager.cs index ff7f95a5..72697185 100644 --- a/Penumbra/Interop/Services/ResidentResourceManager.cs +++ b/Penumbra/Interop/Services/ResidentResourceManager.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using Penumbra.GameData; @@ -21,10 +22,8 @@ public unsafe class ResidentResourceManager public Structs.ResidentResourceManager* Address => *_residentResourceManagerAddress; - public ResidentResourceManager() - { - SignatureHelper.Initialise(this); - } + public ResidentResourceManager(IGameInteropProvider interop) + => interop.InitializeFromAttributes(this); // Reload certain player resources by force. public void Reload() diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index 211a062c..be5b778e 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using OtterGui.Classes; @@ -48,13 +49,13 @@ public sealed unsafe class SkinFixer : IDisposable public int ModdedSkinShpkCount => _moddedSkinShpkCount; - public SkinFixer(GameEventManager gameEvents, CharacterUtility utility, CommunicatorService communicator) + public SkinFixer(GameEventManager gameEvents, CharacterUtility utility, CommunicatorService communicator, IGameInteropProvider interop) { - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); _gameEvents = gameEvents; _utility = utility; _communicator = communicator; - _onRenderMaterialHook = Hook.FromAddress(_humanVTable[62], OnRenderHumanMaterial); + _onRenderMaterialHook = interop.HookFromAddress(_humanVTable[62], OnRenderHumanMaterial); _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.SkinFixer); _gameEvents.ResourceHandleDestructor += OnResourceHandleDestructor; _onRenderMaterialHook.Enable(); diff --git a/Penumbra/Interop/Structs/CharacterBaseExt.cs b/Penumbra/Interop/Structs/CharacterBaseExt.cs index 7cdcc6fe..53fda2cd 100644 --- a/Penumbra/Interop/Structs/CharacterBaseExt.cs +++ b/Penumbra/Interop/Structs/CharacterBaseExt.cs @@ -1,4 +1,4 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; namespace Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Structs/Material.cs b/Penumbra/Interop/Structs/Material.cs index 0165a8ff..f7c8679e 100644 --- a/Penumbra/Interop/Structs/Material.cs +++ b/Penumbra/Interop/Structs/Material.cs @@ -1,4 +1,4 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; namespace Penumbra.Interop.Structs; diff --git a/Penumbra/Interop/Structs/TextureUtility.cs b/Penumbra/Interop/Structs/TextureUtility.cs index a81480fb..eeea4c33 100644 --- a/Penumbra/Interop/Structs/TextureUtility.cs +++ b/Penumbra/Interop/Structs/TextureUtility.cs @@ -1,37 +1,31 @@ +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; namespace Penumbra.Interop.Structs; -public static unsafe class TextureUtility +public unsafe class TextureUtility { - private static readonly Functions Funcs = new(); + public TextureUtility(IGameInteropProvider interop) + => interop.InitializeFromAttributes(this); + + + [Signature("E8 ?? ?? ?? ?? 8B 0F 48 8D 54 24")] + private static nint _textureCreate2D = nint.Zero; + + [Signature("E9 ?? ?? ?? ?? 8B 02 25")] + private static nint _textureInitializeContents = nint.Zero; public static Texture* Create2D(Device* device, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk) - => ((delegate* unmanaged)Funcs.TextureCreate2D)(device, size, mipLevel, textureFormat, + => ((delegate* unmanaged)_textureCreate2D)(device, size, mipLevel, textureFormat, flags, unk); public static bool InitializeContents(Texture* texture, void* contents) - => ((delegate* unmanaged)Funcs.TextureInitializeContents)(texture, contents); + => ((delegate* unmanaged)_textureInitializeContents)(texture, contents); public static void IncRef(Texture* texture) => ((delegate* unmanaged)(*(void***)texture)[2])(texture); public static void DecRef(Texture* texture) => ((delegate* unmanaged)(*(void***)texture)[3])(texture); - - private sealed class Functions - { - [Signature("E8 ?? ?? ?? ?? 8B 0F 48 8D 54 24")] - public nint TextureCreate2D = nint.Zero; - - [Signature("E9 ?? ?? ?? ?? 8B 02 25")] - public nint TextureInitializeContents = nint.Zero; - - public Functions() - { - SignatureHelper.Initialise(this); - } - } } diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 3155e188..d918bda2 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -29,7 +29,7 @@ public unsafe class MetaFileManager public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, IdentifierService identifier, - FileCompactor compactor) + FileCompactor compactor, IGameInteropProvider interop) { CharacterUtility = characterUtility; ResidentResources = residentResources; @@ -39,7 +39,7 @@ public unsafe class MetaFileManager ValidityChecker = validityChecker; Identifier = identifier; Compactor = compactor; - SignatureHelper.Initialise(this); + interop.InitializeFromAttributes(this); } public void WriteAllTexToolsMeta(Mod mod) diff --git a/Penumbra/Mods/Manager/ModStorage.cs b/Penumbra/Mods/Manager/ModStorage.cs index 83d20969..490381d6 100644 --- a/Penumbra/Mods/Manager/ModStorage.cs +++ b/Penumbra/Mods/Manager/ModStorage.cs @@ -12,7 +12,7 @@ public class ModCombo : FilterComboCache => obj.Name.Text; public ModCombo(Func> generator) - : base(generator) + : base(generator, Penumbra.Log) { } } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 2cca1789..0519baae 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -19,7 +19,9 @@ using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; +using Penumbra.Interop.Structs; using Penumbra.UI; +using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra; @@ -53,7 +55,7 @@ public class Penumbra : IDalamudPlugin var startTimer = new StartTracker(); using var timer = startTimer.Measure(StartTimeType.Total); _services = ServiceManager.CreateProvider(this, pluginInterface, Log, startTimer); - Chat = _services.GetRequiredService(); + Chat = _services.GetRequiredService(); _validityChecker = _services.GetRequiredService(); var startup = _services.GetRequiredService().GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool s) ? s.ToString() @@ -73,11 +75,13 @@ public class Penumbra : IDalamudPlugin _communicatorService = _services.GetRequiredService(); _services.GetRequiredService(); // Initialize because not required anywhere else. _services.GetRequiredService(); // Initialize because not required anywhere else. + _services.GetRequiredService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); using (var t = _services.GetRequiredService().Measure(StartTimeType.PathResolver)) { _services.GetRequiredService(); } + _services.GetRequiredService(); SetupInterface(); @@ -187,7 +191,7 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Commit Hash: `** {_validityChecker.CommitHash}\n"); sb.Append($"> **`Enable Mods: `** {_config.EnableMods}\n"); sb.Append($"> **`Enable HTTP API: `** {_config.EnableHttpApi}\n"); - sb.Append($"> **`Operating System: `** {(Dalamud.Utility.Util.IsLinux() ? "Mac/Linux (Wine)" : "Windows")}\n"); + sb.Append($"> **`Operating System: `** {(Dalamud.Utility.Util.IsWine() ? "Mac/Linux (Wine)" : "Windows")}\n"); sb.Append($"> **`Root Directory: `** `{_config.ModDirectory}`, {(exists ? "Exists" : "Not Existing")}\n"); sb.Append( $"> **`Free Drive Space: `** {(drive != null ? Functions.HumanReadableSize(drive.AvailableFreeSpace) : "Unknown")}\n"); diff --git a/Penumbra/Services/ChatService.cs b/Penumbra/Services/ChatService.cs index adb24618..3e715a4f 100644 --- a/Penumbra/Services/ChatService.cs +++ b/Penumbra/Services/ChatService.cs @@ -1,8 +1,8 @@ -using Dalamud.Game.Gui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Plugin; +using Dalamud.Plugin.Services; using Lumina.Excel.GeneratedSheets; using OtterGui.Log; @@ -10,9 +10,9 @@ namespace Penumbra.Services; public class ChatService : OtterGui.Classes.ChatService { - private readonly ChatGui _chat; + private readonly IChatGui _chat; - public ChatService(Logger log, DalamudPluginInterface pi, ChatGui chat) + public ChatService(Logger log, DalamudPluginInterface pi, IChatGui chat) : base(log, pi) => _chat = chat; @@ -37,7 +37,7 @@ public class ChatService : OtterGui.Classes.ChatService var payload = new SeString(payloadList); - _chat.PrintChat(new XivChatEntry + _chat.Print(new XivChatEntry { Message = payload, }); diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudServices.cs index 0cd4c97a..99539c39 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudServices.cs @@ -1,8 +1,5 @@ using Dalamud.Game; -using Dalamud.Game.ClientState.Conditions; -using Dalamud.Game.ClientState.Keys; using Dalamud.Game.ClientState.Objects; -using Dalamud.Game.Gui; using Dalamud.Interface; using Dalamud.IoC; using Dalamud.Plugin; @@ -75,6 +72,8 @@ public class DalamudServices services.AddSingleton(DragDropManager); services.AddSingleton(TextureProvider); services.AddSingleton(TextureSubstitutionProvider); + services.AddSingleton(Interop); + services.AddSingleton(Log); } // TODO remove static @@ -83,18 +82,20 @@ public class DalamudServices [PluginService][RequiredVersion("1.0")] public ICommandManager Commands { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public IDataManager GameData { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public IClientState ClientState { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ChatGui Chat { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public Framework Framework { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public Condition Conditions { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IChatGui Chat { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IFramework Framework { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ICondition Conditions { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ITargetManager Targets { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public IObjectTable Objects { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public TitleScreenMenu TitleScreenMenu { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public ITitleScreenMenu TitleScreenMenu { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public IGameGui GameGui { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public KeyState KeyState { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IKeyState KeyState { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ISigScanner SigScanner { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public IDragDropManager DragDropManager { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ITextureProvider TextureProvider { get; private set; } = null!; [PluginService][RequiredVersion("1.0")] public ITextureSubstitutionProvider TextureSubstitutionProvider { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IGameInteropProvider Interop { get; private set; } = null!; + [PluginService][RequiredVersion("1.0")] public IPluginLog Log { get; private set; } = null!; // @formatter:on public UiBuilder UiBuilder diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index b76c39ef..9e3b9b1a 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -13,6 +13,7 @@ using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.ResourceTree; using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -23,6 +24,7 @@ using Penumbra.UI.Classes; using Penumbra.UI.ModsTab; using Penumbra.UI.ResourceWatcher; using Penumbra.UI.Tabs; +using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra.Services; @@ -88,7 +90,8 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddConfiguration(this IServiceCollection services) => services.AddTransient() diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 30e22a7a..bbbfcc71 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -12,7 +12,7 @@ public class StainService : IDisposable public sealed class StainTemplateCombo : FilterComboCache { public StainTemplateCombo(IEnumerable items) - : base(items) + : base(items, Penumbra.Log) { } } @@ -21,12 +21,12 @@ public class StainService : IDisposable public readonly StmFile StmFile; public readonly StainTemplateCombo TemplateCombo; - public StainService(StartTracker timer, DalamudPluginInterface pluginInterface, IDataManager dataManager) + public StainService(StartTracker timer, DalamudPluginInterface pluginInterface, IDataManager dataManager, IPluginLog dalamudLog) { using var t = timer.Measure(StartTimeType.Stains); - StainData = new StainData(pluginInterface, dataManager, dataManager.Language); + StainData = new StainData(pluginInterface, dataManager, dataManager.Language, dalamudLog); StainCombo = new FilterComboColors(140, - StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false)))); + StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false))), Penumbra.Log); StmFile = new StmFile(dataManager); TemplateCombo = new StainTemplateCombo(StmFile.Entries.Keys.Prepend((ushort)0)); Penumbra.Log.Verbose($"[{nameof(StainService)}] Created."); diff --git a/Penumbra/Services/Wrappers.cs b/Penumbra/Services/Wrappers.cs index 69dbbeab..b1f17d4d 100644 --- a/Penumbra/Services/Wrappers.cs +++ b/Penumbra/Services/Wrappers.cs @@ -11,24 +11,24 @@ namespace Penumbra.Services; public sealed class IdentifierService : AsyncServiceWrapper { - public IdentifierService(StartTracker tracker, DalamudPluginInterface pi, IDataManager data, ItemService items) + public IdentifierService(StartTracker tracker, DalamudPluginInterface pi, IDataManager data, ItemService items, IPluginLog log) : base(nameof(IdentifierService), tracker, StartTimeType.Identifier, - () => GameData.GameData.GetIdentifier(pi, data, items.AwaitedService)) + () => GameData.GameData.GetIdentifier(pi, data, items.AwaitedService, log)) { } } public sealed class ItemService : AsyncServiceWrapper { - public ItemService(StartTracker tracker, DalamudPluginInterface pi, IDataManager gameData) - : base(nameof(ItemService), tracker, StartTimeType.Items, () => new ItemData(pi, gameData, gameData.Language)) + public ItemService(StartTracker tracker, DalamudPluginInterface pi, IDataManager gameData, IPluginLog log) + : base(nameof(ItemService), tracker, StartTimeType.Items, () => new ItemData(pi, gameData, gameData.Language, log)) { } } public sealed class ActorService : AsyncServiceWrapper { public ActorService(StartTracker tracker, DalamudPluginInterface pi, IObjectTable objects, IClientState clientState, - Framework framework, IDataManager gameData, IGameGui gui, CutsceneService cutscene) + IFramework framework, IDataManager gameData, IGameGui gui, CutsceneService cutscene, IPluginLog log, IGameInteropProvider interop) : base(nameof(ActorService), tracker, StartTimeType.Actors, - () => new ActorManager(pi, objects, clientState, framework, gameData, gui, idx => (short)cutscene.GetParentIndex(idx))) + () => new ActorManager(pi, objects, clientState, framework, interop, gameData, gui, idx => (short)cutscene.GetParentIndex(idx), log)) { } } diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 2591145f..9354afaf 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -279,7 +279,7 @@ public class FileEditor : IDisposable where T : class, IWritable private readonly Configuration _config; public Combo(Configuration config, Func> generator) - : base(generator) + : base(generator, Penumbra.Log) => _config = config; protected override bool DrawSelectable(int globalIdx, bool selected) diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 87598f5a..967e8d01 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -129,7 +129,7 @@ public class ItemSwapTab : IDisposable, ITab private class ItemSelector : FilterComboCache { public ItemSelector(ItemService data, FullEquipType type) - : base(() => data.AwaitedService[type]) + : base(() => data.AwaitedService[type], Penumbra.Log) { } protected override string ToString(EquipItem obj) @@ -139,7 +139,7 @@ public class ItemSwapTab : IDisposable, ITab private class WeaponSelector : FilterComboCache { public WeaponSelector() - : base(FullEquipTypeExtensions.WeaponTypes.Concat(FullEquipTypeExtensions.ToolTypes)) + : base(FullEquipTypeExtensions.WeaponTypes.Concat(FullEquipTypeExtensions.ToolTypes), Penumbra.Log) { } protected override string ToString(FullEquipType type) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index cccc43ee..447382cf 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 73aad323..df20d60f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index c659ada0..0f171e21 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.DragDrop; +using Dalamud.Interface.Utility; using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; using ImGuiNET; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index 60247d81..7d4fa96f 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface; +using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 39728cd4..ef847d8d 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui.Raii; using OtterGui; diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 13a5787e..324c354a 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -1,9 +1,9 @@ using Dalamud.Interface; +using Dalamud.Interface.Internal; using Dalamud.Plugin.Services; using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; -using ImGuiScene; using Lumina.Data.Files; using Lumina.Excel; using Lumina.Excel.GeneratedSheets; @@ -46,11 +46,11 @@ public class ChangedItemDrawer : IDisposable public const ChangedItemIcon AllFlags = (ChangedItemIcon)0x01FFFF; public const ChangedItemIcon DefaultFlags = AllFlags & ~ChangedItemIcon.Offhand; - private readonly Configuration _config; - private readonly ExcelSheet _items; - private readonly CommunicatorService _communicator; - private readonly Dictionary _icons = new(16); - private float _smallestIconWidth; + private readonly Configuration _config; + private readonly ExcelSheet _items; + private readonly CommunicatorService _communicator; + private readonly Dictionary _icons = new(16); + private float _smallestIconWidth; public ChangedItemDrawer(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, Configuration config) @@ -357,7 +357,7 @@ public class ChangedItemDrawer : IDisposable if (!equipTypeIcons.Valid) return false; - void Add(ChangedItemIcon icon, TextureWrap? tex) + void Add(ChangedItemIcon icon, IDalamudTextureWrap? tex) { if (tex != null) _icons.Add(icon, tex); @@ -387,7 +387,7 @@ public class ChangedItemDrawer : IDisposable return true; } - private static unsafe TextureWrap? LoadUnknownTexture(IDataManager gameData, UiBuilder uiBuilder) + private static unsafe IDalamudTextureWrap? LoadUnknownTexture(IDataManager gameData, UiBuilder uiBuilder) { var unk = gameData.GetFile("ui/uld/levelup2_hr1.tex"); if (unk == null) @@ -402,7 +402,7 @@ public class ChangedItemDrawer : IDisposable return uiBuilder.LoadImageRaw(bytes, unk.Header.Height, unk.Header.Height, 4); } - private static unsafe TextureWrap? LoadEmoteTexture(IDataManager gameData, UiBuilder uiBuilder) + private static unsafe IDalamudTextureWrap? LoadEmoteTexture(IDataManager gameData, UiBuilder uiBuilder) { var emote = gameData.GetFile("ui/icon/000000/000019_hr1.tex"); if (emote == null) diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index fc37eaf2..b2ee5c3b 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -13,7 +13,7 @@ public sealed class CollectionCombo : FilterComboCache private readonly ImRaii.Color _color = new(); public CollectionCombo(CollectionManager manager, Func> items) - : base(items) + : base(items, Penumbra.Log) => _collectionManager = manager; protected override void DrawFilter(int currentSelected, float width) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 3ebd3252..bd37a484 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -2,6 +2,7 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.GameFonts; +using Dalamud.Interface.Utility; using Dalamud.Plugin; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs index da011bde..5f463c43 100644 --- a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs +++ b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs @@ -126,12 +126,12 @@ public class IndividualAssignmentUi : IDisposable /// Create combos when ready. private void SetupCombos() { - _worldCombo = new WorldCombo(_actorService.AwaitedService.Data.Worlds); - _mountCombo = new NpcCombo("##mountCombo", _actorService.AwaitedService.Data.Mounts); - _companionCombo = new NpcCombo("##companionCombo", _actorService.AwaitedService.Data.Companions); - _ornamentCombo = new NpcCombo("##ornamentCombo", _actorService.AwaitedService.Data.Ornaments); - _bnpcCombo = new NpcCombo("##bnpcCombo", _actorService.AwaitedService.Data.BNpcs); - _enpcCombo = new NpcCombo("##enpcCombo", _actorService.AwaitedService.Data.ENpcs); + _worldCombo = new WorldCombo(_actorService.AwaitedService.Data.Worlds, Penumbra.Log); + _mountCombo = new NpcCombo("##mountCombo", _actorService.AwaitedService.Data.Mounts, Penumbra.Log); + _companionCombo = new NpcCombo("##companionCombo", _actorService.AwaitedService.Data.Companions, Penumbra.Log); + _ornamentCombo = new NpcCombo("##ornamentCombo", _actorService.AwaitedService.Data.Ornaments, Penumbra.Log); + _bnpcCombo = new NpcCombo("##bnpcCombo", _actorService.AwaitedService.Data.BNpcs, Penumbra.Log); + _enpcCombo = new NpcCombo("##enpcCombo", _actorService.AwaitedService.Data.ENpcs, Penumbra.Log); _ready = true; _actorService.FinishedCreation -= SetupCombos; } diff --git a/Penumbra/UI/LaunchButton.cs b/Penumbra/UI/LaunchButton.cs index 5b9bf5a4..9650ccf8 100644 --- a/Penumbra/UI/LaunchButton.cs +++ b/Penumbra/UI/LaunchButton.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; +using Dalamud.Interface.Internal; using Dalamud.Plugin; -using ImGuiScene; +using Dalamud.Plugin.Services; namespace Penumbra.UI; @@ -10,18 +11,18 @@ namespace Penumbra.UI; /// public class LaunchButton : IDisposable { - private readonly ConfigWindow _configWindow; - private readonly UiBuilder _uiBuilder; - private readonly TitleScreenMenu _title; - private readonly string _fileName; + private readonly ConfigWindow _configWindow; + private readonly UiBuilder _uiBuilder; + private readonly ITitleScreenMenu _title; + private readonly string _fileName; - private TextureWrap? _icon; - private TitleScreenMenu.TitleScreenMenuEntry? _entry; + private IDalamudTextureWrap? _icon; + private TitleScreenMenuEntry? _entry; /// /// Register the launch button to be created on the next draw event. /// - public LaunchButton(DalamudPluginInterface pi, TitleScreenMenu title, ConfigWindow ui) + public LaunchButton(DalamudPluginInterface pi, ITitleScreenMenu title, ConfigWindow ui) { _uiBuilder = pi.UiBuilder; _configWindow = ui; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 39fc7a0e..0d9b0a70 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -2,6 +2,7 @@ using Dalamud.Game.ClientState.Keys; using Dalamud.Interface; using Dalamud.Interface.DragDrop; using Dalamud.Interface.Internal.Notifications; +using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Classes; @@ -35,10 +36,10 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Fri, 29 Sep 2023 02:18:44 +0200 Subject: [PATCH 0132/1381] Add multi deletion to mod selector. --- OtterGui | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 14 +------------- 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/OtterGui b/OtterGui index c70fcc06..06a5ea00 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c70fcc069ea44e1ffb8b33fc409c4ccfdef5e298 +Subproject commit 06a5ea005d5a08febbbc2e45cffde7582ffa7607 diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 0d9b0a70..215a0269 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -279,19 +279,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector DeleteSelectionButton(size, _config.DeleteModModifier, "mod", "mods", _modManager.DeleteMod); private void AddHelpButton(Vector2 size) { From 8f16aa7ee91fd0d350616542fa288785dae3b94b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 2 Oct 2023 23:21:07 +0200 Subject: [PATCH 0133/1381] Fix collection button ids. --- Penumbra/UI/Classes/CollectionSelectHeader.cs | 11 ++++++----- Penumbra/UI/Tabs/ModsTab.cs | 1 + 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index f4fa1b68..de2b6a34 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -36,10 +36,10 @@ public class CollectionSelectHeader var buttonSize = new Vector2(comboWidth * 3f / 4f, 0f); using (var _ = ImRaii.Group()) { - DrawCollectionButton(buttonSize, GetDefaultCollectionInfo()); - DrawCollectionButton(buttonSize, GetInterfaceCollectionInfo()); - DrawCollectionButton(buttonSize, GetPlayerCollectionInfo()); - DrawCollectionButton(buttonSize, GetInheritedCollectionInfo()); + DrawCollectionButton(buttonSize, GetDefaultCollectionInfo(), 1); + DrawCollectionButton(buttonSize, GetInterfaceCollectionInfo(), 2); + DrawCollectionButton(buttonSize, GetPlayerCollectionInfo(), 3); + DrawCollectionButton(buttonSize, GetInheritedCollectionInfo(), 4); _collectionCombo.Draw("##collectionSelector", comboWidth, ColorId.SelectedCollection.Value()); } @@ -126,9 +126,10 @@ public class CollectionSelectHeader }; } - private void DrawCollectionButton(Vector2 buttonWidth, (ModCollection?, string, string, bool) tuple) + private void DrawCollectionButton(Vector2 buttonWidth, (ModCollection?, string, string, bool) tuple, int id) { var (collection, name, tooltip, disabled) = tuple; + using var _ = ImRaii.PushId(id); if (ImGuiUtil.DrawDisabledButton(name, buttonWidth, tooltip, disabled)) _activeCollections.SetCollection(collection!, CollectionType.Current); ImGui.SameLine(); diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 16f0180e..1e675036 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -146,6 +146,7 @@ public class ModsTab : ITab ImGuiUtil.HoverTooltip(lower.Length > 0 ? $"Execute '/penumbra redraw {lower}'." : $"Execute '/penumbra redraw'."); } + using var id = ImRaii.PushId("Redraw"); using var disabled = ImRaii.Disabled(_clientState.LocalPlayer == null); ImGui.SameLine(); var buttonWidth = frameHeight with { X = ImGui.GetContentRegionAvail().X / 4 }; From 5394bdc535b0e9adbb9679630aec40faa5077059 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 2 Oct 2023 23:23:26 +0200 Subject: [PATCH 0134/1381] Update Submodules. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index 06a5ea00..df07c4ed 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 06a5ea005d5a08febbbc2e45cffde7582ffa7607 +Subproject commit df07c4ed08e8e6c1188867c7863a19e02c8adb53 diff --git a/Penumbra.Api b/Penumbra.Api index 9472b6e3..bc9bd5f6 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 9472b6e327109216368c3dc1720159f5295bdb13 +Subproject commit bc9bd5f6bb06e61069704733841868307aed7a5c diff --git a/Penumbra.GameData b/Penumbra.GameData index 3c9e0d03..acf8cf68 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3c9e0d03281c350f8260debb0eab4059408cd0cd +Subproject commit acf8cf68f06e37bbe64f1100a68937da9efb762c From 3d2ce1f4bb0718660e3900efcd837cc7f030f957 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 2 Oct 2023 23:25:15 +0200 Subject: [PATCH 0135/1381] Use ClientStructs hook for CalculateHeight. --- Penumbra/Interop/PathResolving/MetaState.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 6defe78c..c41d651e 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -70,6 +70,8 @@ public unsafe class MetaState : IDisposable _characterUtility = characterUtility; _config = config; interop.InitializeFromAttributes(this); + _calculateHeightHook = + interop.HookFromAddress((nint)Character.MemberFunctionPointers.CalculateHeight, CalculateHeightDetour); _onModelLoadCompleteHook = interop.HookFromAddress(_humanVTable[58], OnModelLoadCompleteDetour); _getEqpIndirectHook.Enable(); _updateModelsHook.Enable(); @@ -249,8 +251,6 @@ public unsafe class MetaState : IDisposable private delegate ulong CalculateHeightDelegate(Character* character); - // TODO: use client structs - [Signature(Sigs.CalculateHeight, DetourName = nameof(CalculateHeightDetour))] private readonly Hook _calculateHeightHook = null!; private ulong CalculateHeightDetour(Character* character) From e5427858e0e91d7e590b74fa2843d474ab477df4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 3 Oct 2023 01:42:28 +0200 Subject: [PATCH 0136/1381] Add support for ActorIdentifier.FromUserString returning multiple identifiers. --- Penumbra/CommandHandler.cs | 113 +++++++++++--------- Penumbra/Interop/PathResolving/MetaState.cs | 3 +- 2 files changed, 64 insertions(+), 52 deletions(-) diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 3249cc43..71bd19c2 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -21,7 +21,7 @@ public class CommandHandler : IDisposable private readonly ICommandManager _commandManager; private readonly RedrawService _redrawService; - private readonly IChatGui _chat; + private readonly IChatGui _chat; private readonly Configuration _config; private readonly ConfigWindow _configWindow; private readonly ActorManager _actors; @@ -30,7 +30,8 @@ public class CommandHandler : IDisposable private readonly Penumbra _penumbra; private readonly CollectionEditor _collectionEditor; - public CommandHandler(IFramework framework, ICommandManager commandManager, IChatGui chat, RedrawService redrawService, Configuration config, + public CommandHandler(IFramework framework, ICommandManager commandManager, IChatGui chat, RedrawService redrawService, + Configuration config, ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorService actors, Penumbra penumbra, CollectionEditor collectionEditor) { @@ -270,7 +271,7 @@ public class CommandHandler : IDisposable if (!GetModCollection(split[1], out var collection)) return false; - var identifier = ActorIdentifier.Invalid; + var identifiers = Array.Empty(); if (type is CollectionType.Individual) { if (split.Length == 2) @@ -284,17 +285,22 @@ public class CommandHandler : IDisposable { if (_redrawService.GetName(split[2].ToLowerInvariant(), out var obj)) { - identifier = _actors.FromObject(obj, false, true, true); + var identifier = _actors.FromObject(obj, false, true, true); if (!identifier.IsValid) { _chat.Print(new SeStringBuilder().AddText("The placeholder ").AddGreen(split[2]) .AddText(" did not resolve to a game object with a valid identifier.").BuiltString); return false; } + + identifiers = new[] + { + identifier, + }; } else { - identifier = _actors.FromUserString(split[2]); + identifiers = _actors.FromUserString(split[2], false); } } catch (ActorManager.IdentifierParseError e) @@ -306,55 +312,60 @@ public class CommandHandler : IDisposable } } - var oldCollection = _collectionManager.Active.ByType(type, identifier); - if (collection == oldCollection) + var anySuccess = false; + foreach (var identifier in identifiers.Distinct()) { - _chat.Print(collection == null - ? $"The {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}" : string.Empty)} is already unassigned" - : $"{collection.Name} already is the {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); - return false; + var oldCollection = _collectionManager.Active.ByType(type, identifier); + if (collection == oldCollection) + { + _chat.Print(collection == null + ? $"The {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}" : string.Empty)} is already unassigned" + : $"{collection.Name} already is the {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); + continue; + } + + var individualIndex = _collectionManager.Active.Individuals.Index(identifier); + + if (oldCollection == null) + { + if (type.IsSpecial()) + { + _collectionManager.Active.CreateSpecialCollection(type); + } + else if (identifier.IsValid) + { + var identifierGroup = _collectionManager.Active.Individuals.GetGroup(identifier); + individualIndex = _collectionManager.Active.Individuals.Count; + _collectionManager.Active.CreateIndividualCollection(identifierGroup); + } + } + else if (collection == null) + { + if (type.IsSpecial()) + { + _collectionManager.Active.RemoveSpecialCollection(type); + } + else if (individualIndex >= 0) + { + _collectionManager.Active.RemoveIndividualCollection(individualIndex); + } + else + { + _chat.Print( + $"Can not remove the {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); + continue; + } + + Print( + $"Removed {oldCollection.Name} as {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); + anySuccess = true; + } + + _collectionManager.Active.SetCollection(collection!, type, individualIndex); + Print($"Assigned {collection!.Name} as {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); } - var individualIndex = _collectionManager.Active.Individuals.Index(identifier); - - if (oldCollection == null) - { - if (type.IsSpecial()) - { - _collectionManager.Active.CreateSpecialCollection(type); - } - else if (identifier.IsValid) - { - var identifiers = _collectionManager.Active.Individuals.GetGroup(identifier); - individualIndex = _collectionManager.Active.Individuals.Count; - _collectionManager.Active.CreateIndividualCollection(identifiers); - } - } - else if (collection == null) - { - if (type.IsSpecial()) - { - _collectionManager.Active.RemoveSpecialCollection(type); - } - else if (individualIndex >= 0) - { - _collectionManager.Active.RemoveIndividualCollection(individualIndex); - } - else - { - _chat.Print( - $"Can not remove the {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); - return false; - } - - Print( - $"Removed {oldCollection.Name} as {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); - return true; - } - - _collectionManager.Active.SetCollection(collection!, type, individualIndex); - Print($"Assigned {collection!.Name} as {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); - return true; + return anySuccess; } private bool SetMod(string arguments) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index c41d651e..0048dc8c 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -60,7 +60,8 @@ public unsafe class MetaState : IDisposable private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; public MetaState(PerformanceTracker performance, CommunicatorService communicator, CollectionResolver collectionResolver, - ResourceLoader resources, GameEventManager gameEventManager, CharacterUtility characterUtility, Configuration config, IGameInteropProvider interop) + ResourceLoader resources, GameEventManager gameEventManager, CharacterUtility characterUtility, Configuration config, + IGameInteropProvider interop) { _performance = performance; _communicator = communicator; From fb591429d60e6f6efa054be20dd9b70ffc1d0d59 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 03:19:05 +0200 Subject: [PATCH 0137/1381] Update Sigs. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index acf8cf68..5b23ba04 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit acf8cf68f06e37bbe64f1100a68937da9efb762c +Subproject commit 5b23ba04e5fd0e934c882c38024ab1b5661b44e1 From 5fefdfa33b7a2637e74d623ff437f4a5c23f1c49 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 14:03:51 +0200 Subject: [PATCH 0138/1381] Fix error in log about existing command. --- Penumbra/CommandHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 71bd19c2..11ccca71 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -47,7 +47,8 @@ public class CommandHandler : IDisposable _collectionEditor = collectionEditor; framework.RunOnFrameworkThread(() => { - _commandManager.RemoveHandler(CommandName); + if (_commandManager.Commands.ContainsKey(CommandName)) + _commandManager.RemoveHandler(CommandName); _commandManager.AddHandler(CommandName, new CommandInfo(OnCommand) { HelpMessage = "Without arguments, toggles the main window. Use /penumbra help to get further command help.", From 58b5c4415771535b4739891ac7dced328ea81ae5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 14:35:03 +0200 Subject: [PATCH 0139/1381] Fix an issue with memory locations that suddenly caused issues? --- .../Interop/ResourceLoading/ResourceLoader.cs | 7 +++--- .../ResourceLoading/ResourceService.cs | 22 +++++++++++++------ 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 94fdcce4..b8cc4742 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -76,8 +76,7 @@ public unsafe class ResourceLoader : IDisposable } private void ResourceHandler(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, - Utf8GamePath original, - GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue) + Utf8GamePath original, GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue) { if (returnValue != null) return; @@ -93,7 +92,7 @@ public unsafe class ResourceLoader : IDisposable if (resolvedPath == null || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var p)) { - returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); + returnValue = _resources.GetOriginalResource(sync, ref category, ref type, ref hash, path.Path, parameters); ResourceLoaded?.Invoke(returnValue, path, resolvedPath, data); return; } @@ -103,7 +102,7 @@ public unsafe class ResourceLoader : IDisposable hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; path = p; - returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); + returnValue = _resources.GetOriginalResource(sync, ref category, ref type, ref hash, path.Path, parameters); ResourceLoaded?.Invoke(returnValue, oldPath, resolvedPath.Value, data); } diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 47107f44..792f8a8e 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -110,18 +110,26 @@ public unsafe class ResourceService : IDisposable if (returnValue != null) return returnValue; - return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk); + return GetOriginalResource(isSync, categoryId, resourceType, resourceHash, gamePath.Path.Path, pGetResParams, isUnk); } - /// Call the original GetResource function. - public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, ByteString path, + private ResourceHandle* GetOriginalResource(bool sync, ResourceCategory* categoryId, ResourceType* type, int* hash, byte* path, GetResourceParameters* resourceParameters = null, bool unk = false) => sync - ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, + ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, categoryId, type, hash, path, resourceParameters) - : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, - resourceParameters, - unk); + : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, categoryId, type, hash, path, + resourceParameters, unk); + + /// Call the original GetResource function. + public ResourceHandle* GetOriginalResource(bool sync, ref ResourceCategory categoryId, ref ResourceType type, ref int hash, ByteString path, + GetResourceParameters* resourceParameters = null, bool unk = false) + { + var ptrCategory = (ResourceCategory*)Unsafe.AsPointer(ref categoryId); + var ptrType = (ResourceType*)Unsafe.AsPointer(ref type); + var ptrHash = (int*)Unsafe.AsPointer(ref hash); + return GetOriginalResource(sync, ptrCategory, ptrType, ptrHash, path.Path, resourceParameters, unk); + } #endregion From a18ace433abe08fa0d62b75700b42595942cae60 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 4 Oct 2023 12:37:47 +0000 Subject: [PATCH 0140/1381] [CI] Updating repo.json for testing_0.8.0.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 639eb985..65368656 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.0.0", - "TestingAssemblyVersion": "0.8.0.0", + "TestingAssemblyVersion": "0.8.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 83ab8e80033aff2fd02046f78f8365f505aeb32f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 16:16:08 +0200 Subject: [PATCH 0141/1381] Temporarily fix ShaderPackage.MaterialElement. --- Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 9d2fc9eb..3ef31382 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -80,7 +80,8 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) { - ref var parameter = ref _shaderPackage->MaterialElements[i]; + // TODO fix when CS updated + ref var parameter = ref ((ShaderPackage.MaterialElement*) ((byte*)_shaderPackage + 0xA0))[i]; if (parameter.CRC == parameterCrc) { if ((parameter.Offset & 0x3) != 0 From 8e0877659f009253c830e32391dc403dc0c4c664 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 16:17:03 +0200 Subject: [PATCH 0142/1381] Update LoadCharacterSound. --- .../PathResolving/AnimationHookService.cs | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index 7f69ceef..9b089658 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -21,7 +21,7 @@ public unsafe class AnimationHookService : IDisposable private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; private readonly CollectionResolver _resolver; - private readonly ICondition _conditions; + private readonly ICondition _conditions; private readonly ThreadLocal _animationLoadData = new(() => ResolveData.Invalid, true); private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); @@ -111,17 +111,19 @@ public unsafe class AnimationHookService : IDisposable } /// Characters load some of their voice lines or whatever with this function. - private delegate IntPtr LoadCharacterSound(IntPtr character, int unk1, int unk2, IntPtr unk3, ulong unk4, int unk5, int unk6, ulong unk7); + private delegate nint LoadCharacterSound(nint character, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); + // TODO: Use ClientStructs [Signature(Sigs.LoadCharacterSound, DetourName = nameof(LoadCharacterSoundDetour))] private readonly Hook _loadCharacterSoundHook = null!; - private IntPtr LoadCharacterSoundDetour(IntPtr character, int unk1, int unk2, IntPtr unk3, ulong unk4, int unk5, int unk6, ulong unk7) + private nint LoadCharacterSoundDetour(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7) { using var performance = _performance.Measure(PerformanceType.LoadSound); var last = _characterSoundData.Value; - _characterSoundData.Value = _collectionResolver.IdentifyCollection((GameObject*)character, true); - var ret = _loadCharacterSoundHook.Original(character, unk1, unk2, unk3, unk4, unk5, unk6, unk7); + var character = *(GameObject**)(container + 8); + _characterSoundData.Value = _collectionResolver.IdentifyCollection(character, true); + var ret = _loadCharacterSoundHook.Original(container, unk1, unk2, unk3, unk4, unk5, unk6, unk7); _characterSoundData.Value = last; return ret; } @@ -130,12 +132,12 @@ public unsafe class AnimationHookService : IDisposable /// The timeline object loads the requested .tmb and .pap files. The .tmb files load the respective .avfx files. /// We can obtain the associated game object from the timelines 28'th vfunc and use that to apply the correct collection. /// - private delegate ulong LoadTimelineResourcesDelegate(IntPtr timeline); + private delegate ulong LoadTimelineResourcesDelegate(nint timeline); [Signature(Sigs.LoadTimelineResources, DetourName = nameof(LoadTimelineResourcesDetour))] private readonly Hook _loadTimelineResourcesHook = null!; - private ulong LoadTimelineResourcesDetour(IntPtr timeline) + private ulong LoadTimelineResourcesDetour(nint timeline) { using var performance = _performance.Measure(PerformanceType.TimelineResources); // Do not check timeline loading in cutscenes. @@ -153,12 +155,12 @@ public unsafe class AnimationHookService : IDisposable /// Probably used when the base idle animation gets loaded. /// Make it aware of the correct collection to load the correct pap files. /// - private delegate void CharacterBaseNoArgumentDelegate(IntPtr drawBase); + private delegate void CharacterBaseNoArgumentDelegate(nint drawBase); [Signature(Sigs.CharacterBaseLoadAnimation, DetourName = nameof(CharacterBaseLoadAnimationDetour))] private readonly Hook _characterBaseLoadAnimationHook = null!; - private void CharacterBaseLoadAnimationDetour(IntPtr drawObject) + private void CharacterBaseLoadAnimationDetour(nint drawObject) { using var performance = _performance.Measure(PerformanceType.LoadCharacterBaseAnimation); var last = _animationLoadData.Value; @@ -171,17 +173,17 @@ public unsafe class AnimationHookService : IDisposable } /// Unknown what exactly this is but it seems to load a bunch of paps. - private delegate void LoadSomePap(IntPtr a1, int a2, IntPtr a3, int a4); + private delegate void LoadSomePap(nint a1, int a2, nint a3, int a4); [Signature(Sigs.LoadSomePap, DetourName = nameof(LoadSomePapDetour))] private readonly Hook _loadSomePapHook = null!; - private void LoadSomePapDetour(IntPtr a1, int a2, IntPtr a3, int a4) + private void LoadSomePapDetour(nint a1, int a2, nint a3, int a4) { using var performance = _performance.Measure(PerformanceType.LoadPap); var timelinePtr = a1 + Offsets.TimeLinePtr; var last = _animationLoadData.Value; - if (timelinePtr != IntPtr.Zero) + if (timelinePtr != nint.Zero) { var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); if (actorIdx >= 0 && actorIdx < _objects.Length) @@ -206,12 +208,12 @@ public unsafe class AnimationHookService : IDisposable } /// Load a VFX specifically for a character. - private delegate IntPtr LoadCharacterVfxDelegate(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4); + private delegate nint LoadCharacterVfxDelegate(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4); [Signature(Sigs.LoadCharacterVfx, DetourName = nameof(LoadCharacterVfxDetour))] private readonly Hook _loadCharacterVfxHook = null!; - private IntPtr LoadCharacterVfxDetour(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4) + private nint LoadCharacterVfxDetour(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4) { using var performance = _performance.Measure(PerformanceType.LoadCharacterVfx); var last = _animationLoadData.Value; @@ -296,7 +298,7 @@ public unsafe class AnimationHookService : IDisposable { try { - if (timeline != IntPtr.Zero) + if (timeline != nint.Zero) { var getGameObjectIdx = ((delegate* unmanaged**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; var idx = getGameObjectIdx(timeline); From c21cbcdcd36f7a5d6f724d2c5d722f0460ed3735 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 4 Oct 2023 14:20:40 +0000 Subject: [PATCH 0143/1381] [CI] Updating repo.json for testing_0.8.0.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 65368656..77bbc8c3 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.0.0", - "TestingAssemblyVersion": "0.8.0.1", + "TestingAssemblyVersion": "0.8.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 069929ce24feee1edfcaaeef4c7bbfaf35086a2d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 20:30:04 +0200 Subject: [PATCH 0144/1381] Some updates. --- .../MaterialPreview/LiveMaterialPreviewer.cs | 2 +- .../Interop/MaterialPreview/MaterialInfo.cs | 10 +++++----- .../PathResolving/AnimationHookService.cs | 19 ++++++++++++------- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 3ef31382..15989638 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -81,7 +81,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) { // TODO fix when CS updated - ref var parameter = ref ((ShaderPackage.MaterialElement*) ((byte*)_shaderPackage + 0xA0))[i]; + ref var parameter = ref ((ShaderPackage.MaterialElement*) ((byte*)_shaderPackage + 0x98))[i]; if (parameter.CRC == parameterCrc) { if ((parameter.Offset & 0x3) != 0 diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index 7dd6f983..c64e4d0b 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -33,9 +33,9 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy return type switch { DrawObjectType.Character => (nint)gameObject->GameObject.GetDrawObject(), - DrawObjectType.Mainhand => *((nint*)&gameObject->DrawData.MainHand + 1), - DrawObjectType.Offhand => *((nint*)&gameObject->DrawData.OffHand + 1), - DrawObjectType.Vfx => *((nint*)&gameObject->DrawData.UnkF0 + 1), + DrawObjectType.Mainhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.MainHand).DrawObject, + DrawObjectType.Offhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.OffHand).DrawObject, + DrawObjectType.Vfx => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.Unk).DrawObject, _ => nint.Zero, }; } @@ -72,7 +72,7 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy if (gameObject == null) continue; - var index = (ObjectIndex) gameObject->GameObject.ObjectIndex; + var index = (ObjectIndex)gameObject->GameObject.ObjectIndex; foreach (var type in Enum.GetValues()) { @@ -93,7 +93,7 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy continue; var mtrlHandle = material->MaterialResourceHandle; - var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); + var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); if (path == needle) result.Add(new MaterialInfo(index, type, i, j)); } diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index 9b089658..7fa0ed35 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -2,6 +2,7 @@ using Dalamud.Game.ClientState.Conditions; using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Game; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Collections; using Penumbra.Api.Enums; @@ -37,6 +38,10 @@ public unsafe class AnimationHookService : IDisposable _conditions = conditions; interop.InitializeFromAttributes(this); + _loadCharacterSoundHook = + interop.HookFromAddress( + (nint)FFXIVClientStructs.FFXIV.Client.Game.Character.Character.VfxContainer.MemberFunctionPointers.LoadCharacterSound, + LoadCharacterSoundDetour); _loadCharacterSoundHook.Enable(); _loadTimelineResourcesHook.Enable(); @@ -113,9 +118,7 @@ public unsafe class AnimationHookService : IDisposable /// Characters load some of their voice lines or whatever with this function. private delegate nint LoadCharacterSound(nint character, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); - // TODO: Use ClientStructs - [Signature(Sigs.LoadCharacterSound, DetourName = nameof(LoadCharacterSoundDetour))] - private readonly Hook _loadCharacterSoundHook = null!; + private readonly Hook _loadCharacterSoundHook; private nint LoadCharacterSoundDetour(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7) { @@ -194,16 +197,18 @@ public unsafe class AnimationHookService : IDisposable _animationLoadData.Value = last; } + private delegate void SomeActionLoadDelegate(ActionTimelineManager* timelineManager); + /// Seems to load character actions when zoning or changing class, maybe. [Signature(Sigs.LoadSomeAction, DetourName = nameof(SomeActionLoadDetour))] - private readonly Hook _someActionLoadHook = null!; + private readonly Hook _someActionLoadHook = null!; - private void SomeActionLoadDetour(nint gameObject) + private void SomeActionLoadDetour(ActionTimelineManager* timelineManager) { using var performance = _performance.Measure(PerformanceType.LoadAction); var last = _animationLoadData.Value; - _animationLoadData.Value = _collectionResolver.IdentifyCollection((GameObject*)gameObject, true); - _someActionLoadHook.Original(gameObject); + _animationLoadData.Value = _collectionResolver.IdentifyCollection((GameObject*)timelineManager->Parent, true); + _someActionLoadHook.Original(timelineManager); _animationLoadData.Value = last; } From 53f1efa88b13d91203ec44c17b62a00a2a873eec Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 4 Oct 2023 18:33:22 +0000 Subject: [PATCH 0145/1381] [CI] Updating repo.json for testing_0.8.0.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 77bbc8c3..e6c3ad8e 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.0.0", - "TestingAssemblyVersion": "0.8.0.2", + "TestingAssemblyVersion": "0.8.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0aeb407a012dec22d75ef40d0dcf585f965c3e3c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 4 Oct 2023 22:02:23 +0200 Subject: [PATCH 0146/1381] Update CopyCharacterEvent. --- Penumbra/Interop/Services/GameEventManager.cs | 15 ++++++++---- Penumbra/Interop/Services/RedrawService.cs | 24 +++++++++---------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/Penumbra/Interop/Services/GameEventManager.cs b/Penumbra/Interop/Services/GameEventManager.cs index 59714ff0..d11b7159 100644 --- a/Penumbra/Interop/Services/GameEventManager.cs +++ b/Penumbra/Interop/Services/GameEventManager.cs @@ -24,6 +24,10 @@ public unsafe class GameEventManager : IDisposable public GameEventManager(IGameInteropProvider interop) { interop.InitializeFromAttributes(this); + + _copyCharacterHook = + interop.HookFromAddress((nint)CharacterSetup.MemberFunctionPointers.CopyFromCharacter, CopyCharacterDetour); + _characterDtorHook.Enable(); _copyCharacterHook.Enable(); _resourceHandleDestructorHook.Enable(); @@ -78,19 +82,20 @@ public unsafe class GameEventManager : IDisposable #region Copy Character - private delegate ulong CopyCharacterDelegate(GameObject* target, GameObject* source, uint unk); + private delegate ulong CopyCharacterDelegate(CharacterSetup* target, GameObject* source, uint unk); - [Signature(Sigs.CopyCharacter, DetourName = nameof(CopyCharacterDetour))] - private readonly Hook _copyCharacterHook = null!; + private readonly Hook _copyCharacterHook; - private ulong CopyCharacterDetour(GameObject* target, GameObject* source, uint unk) + private ulong CopyCharacterDetour(CharacterSetup* target, GameObject* source, uint unk) { + // TODO: update when CS updated. + var character = ((Character**)target)[1]; if (CopyCharacter != null) foreach (var subscriber in CopyCharacter.GetInvocationList()) { try { - ((CopyCharacterEvent)subscriber).Invoke((Character*)target, (Character*)source); + ((CopyCharacterEvent)subscriber).Invoke(character, (Character*)source); } catch (Exception ex) { diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 0864bb71..5cc493ad 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -1,4 +1,3 @@ -using Dalamud.Game; using Dalamud.Game.ClientState.Conditions; using Dalamud.Game.ClientState.Objects; using Dalamud.Game.ClientState.Objects.Enums; @@ -20,8 +19,10 @@ public unsafe partial class RedrawService public const int GPoseEndIdx = GPosePlayerIdx + GPoseSlots; private readonly string?[] _gPoseNames = new string?[GPoseSlots]; - private int _gPoseNameCounter = 0; - private bool _inGPose = false; + private int _gPoseNameCounter; + + private bool InGPose + => _clientState.IsGPosing; // VFuncs that disable and enable draw, used only for GPose actors. private static void DisableDraw(GameObject actor) @@ -33,10 +34,7 @@ public unsafe partial class RedrawService // Check whether we currently are in GPose. // Also clear the name list. private void SetGPose() - { - _inGPose = _objects[GPosePlayerIdx] != null; - _gPoseNameCounter = 0; - } + => _gPoseNameCounter = 0; private static bool IsGPoseActor(int idx) => idx is >= GPosePlayerIdx and < GPoseEndIdx; @@ -50,7 +48,7 @@ public unsafe partial class RedrawService private bool FindCorrectActor(int idx, out GameObject? obj) { obj = _objects[idx]; - if (!_inGPose || obj == null || IsGPoseActor(idx)) + if (!InGPose || obj == null || IsGPoseActor(idx)) return false; var name = obj.Name.ToString(); @@ -100,10 +98,11 @@ public unsafe partial class RedrawService public sealed unsafe partial class RedrawService : IDisposable { - private readonly IFramework _framework; + private readonly IFramework _framework; private readonly IObjectTable _objects; private readonly ITargetManager _targets; - private readonly ICondition _conditions; + private readonly ICondition _conditions; + private readonly IClientState _clientState; private readonly List _queue = new(100); private readonly List _afterGPoseQueue = new(GPoseSlots); @@ -111,12 +110,13 @@ public sealed unsafe partial class RedrawService : IDisposable public event GameObjectRedrawnDelegate? GameObjectRedrawn; - public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions) + public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions, IClientState clientState) { _framework = framework; _objects = objects; _targets = targets; _conditions = conditions; + _clientState = clientState; _framework.Update += OnUpdateEvent; } @@ -241,7 +241,7 @@ public sealed unsafe partial class RedrawService : IDisposable private void HandleAfterGPose() { - if (_afterGPoseQueue.Count == 0 || _inGPose) + if (_afterGPoseQueue.Count == 0 || InGPose) return; var numKept = 0; From 30a55d401f111ecd0dbf973019cb4c850a2b0164 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 4 Oct 2023 20:06:28 +0000 Subject: [PATCH 0147/1381] [CI] Updating repo.json for testing_0.8.0.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e6c3ad8e..1c13cdab 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.0.0", - "TestingAssemblyVersion": "0.8.0.3", + "TestingAssemblyVersion": "0.8.0.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 73b4227310d59e81aa23081aae07c5cd69736bd8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 16:23:09 +0200 Subject: [PATCH 0148/1381] Fix slash commands. --- Penumbra/CommandHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 11ccca71..b6c675a2 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -314,7 +314,7 @@ public class CommandHandler : IDisposable } var anySuccess = false; - foreach (var identifier in identifiers.Distinct()) + foreach (var identifier in identifiers.Distinct().DefaultIfEmpty(ActorIdentifier.Invalid)) { var oldCollection = _collectionManager.Active.ByType(type, identifier); if (collection == oldCollection) @@ -360,6 +360,7 @@ public class CommandHandler : IDisposable Print( $"Removed {oldCollection.Name} as {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); anySuccess = true; + continue; } _collectionManager.Active.SetCollection(collection!, type, individualIndex); From 8b5437c2c70237b786716c1fd82cf89361de4442 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 17:39:38 +0200 Subject: [PATCH 0149/1381] Remove CS temp fix. --- Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 15989638..420e929f 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -80,8 +80,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) { - // TODO fix when CS updated - ref var parameter = ref ((ShaderPackage.MaterialElement*) ((byte*)_shaderPackage + 0x98))[i]; + ref var parameter = ref _shaderPackage->MaterialElementsSpan[i]; if (parameter.CRC == parameterCrc) { if ((parameter.Offset & 0x3) != 0 From c487fb12ec0eeeb1c023c26d26390aafe75c87a6 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 5 Oct 2023 17:50:38 +0200 Subject: [PATCH 0150/1381] CS-ify LiveMaterialPreviewer and add new shpk name --- .../MaterialPreview/LiveMaterialPreviewer.cs | 29 +++++++++---------- .../ModEditWindow.Materials.Shpk.cs | 1 + 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 420e929f..fa03ac49 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -26,14 +26,11 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (_shaderPackage == null) throw new InvalidOperationException("Material doesn't have a shader package"); - var material = (Structs.Material*)Material; + var material = Material; - _originalShPkFlags = material->ShaderPackageFlags; + _originalShPkFlags = material->ShaderFlags; - if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) - _originalMaterialParameter = materialParameter.ToArray(); - else - _originalMaterialParameter = Array.Empty(); + _originalMaterialParameter = material->MaterialParameterCBuffer->TryGetBuffer().ToArray(); _originalSamplerFlags = new uint[material->TextureCount]; for (var i = 0; i < _originalSamplerFlags.Length; ++i) @@ -46,11 +43,12 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (reset) { - var material = (Structs.Material*)Material; + var material = Material; - material->ShaderPackageFlags = _originalShPkFlags; + material->ShaderFlags = _originalShPkFlags; - if (material->MaterialParameter->TryGetBuffer(out var materialParameter)) + var materialParameter = material->MaterialParameterCBuffer->TryGetBuffer(); + if (!materialParameter.IsEmpty) _originalMaterialParameter.AsSpan().CopyTo(materialParameter); for (var i = 0; i < _originalSamplerFlags.Length; ++i) @@ -71,11 +69,12 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (!CheckValidity()) return; - var constantBuffer = ((Structs.Material*)Material)->MaterialParameter; + var constantBuffer = Material->MaterialParameterCBuffer; if (constantBuffer == null) return; - if (!constantBuffer->TryGetBuffer(out var buffer)) + var buffer = constantBuffer->TryGetBuffer(); + if (buffer.IsEmpty) return; for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) @@ -102,10 +101,10 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase var id = 0u; var found = false; - var samplers = (Structs.ShaderPackageUtility.Sampler*)_shaderPackage->Samplers; + var samplers = _shaderPackage->Samplers; for (var i = 0; i < _shaderPackage->SamplerCount; ++i) { - if (samplers[i].Crc == samplerCrc) + if (samplers[i].CRC == samplerCrc) { id = samplers[i].Id; found = true; @@ -116,7 +115,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (!found) return; - var material = (Structs.Material*)Material; + var material = Material; for (var i = 0; i < material->TextureCount; ++i) { if (material->Textures[i].Id == id) @@ -136,7 +135,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (mtrlHandle == null) return false; - var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; + var shpkHandle = mtrlHandle->ShaderPackageResourceHandle; if (shpkHandle == null) return false; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 25869d9c..9e9557d3 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -36,6 +36,7 @@ public partial class ModEditWindow "bguvscroll.shpk", "channeling.shpk", "characterglass.shpk", + "charactershadowoffset.shpk", "character.shpk", "cloud.shpk", "createviewposition.shpk", From 779d6b37a55c753e5a8ea8ae52adf971874ee9af Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 18:20:41 +0200 Subject: [PATCH 0151/1381] Improved messaging. --- OtterGui | 2 +- Penumbra.Api | 2 +- .../Manager/ActiveCollectionMigration.cs | 7 ++--- .../Collections/Manager/ActiveCollections.cs | 20 +++++-------- .../Collections/Manager/CollectionStorage.cs | 29 ++++++++----------- .../Manager/IndividualCollections.Files.cs | 24 +++++++-------- .../Collections/Manager/InheritanceManager.cs | 9 +++--- Penumbra/Configuration.cs | 4 +-- Penumbra/Mods/Editor/ModMerger.cs | 5 ++-- Penumbra/Mods/Editor/ModNormalizer.cs | 21 ++++++-------- Penumbra/Mods/Manager/ModImportManager.cs | 4 +-- Penumbra/Mods/Manager/ModOptionEditor.cs | 5 ++-- Penumbra/Mods/ModCreator.cs | 4 +-- Penumbra/Mods/Subclasses/MultiModGroup.cs | 6 ++-- Penumbra/Penumbra.cs | 6 ++-- Penumbra/Services/BackupService.cs | 2 +- .../{ChatService.cs => MessageService.cs} | 14 ++++----- Penumbra/Services/ServiceManager.cs | 3 +- Penumbra/Services/ValidityChecker.cs | 4 +-- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 3 +- .../ModEditWindow.Materials.MtrlTab.cs | 3 +- .../ModEditWindow.ShaderPackages.cs | 20 ++++++------- Penumbra/UI/ConfigWindow.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 14 ++++----- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 25 ++++++++-------- Penumbra/UI/Tabs/ConfigTabBar.cs | 17 +++++++---- Penumbra/UI/Tabs/MessagesTab.cs | 21 ++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 4 +-- Penumbra/UI/UiHelpers.cs | 3 +- 30 files changed, 146 insertions(+), 139 deletions(-) rename Penumbra/Services/{ChatService.cs => MessageService.cs} (80%) create mode 100644 Penumbra/UI/Tabs/MessagesTab.cs diff --git a/OtterGui b/OtterGui index df07c4ed..96c9055a 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit df07c4ed08e8e6c1188867c7863a19e02c8adb53 +Subproject commit 96c9055a1d8a19d9cdb61f41ddfb372871e204ac diff --git a/Penumbra.Api b/Penumbra.Api index bc9bd5f6..839cc8f2 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit bc9bd5f6bb06e61069704733841868307aed7a5c +Subproject commit 839cc8f270abb6a938d71596bef05b4a9b3ab0ea diff --git a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs index 5872dea1..2f9e9b15 100644 --- a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs @@ -1,6 +1,7 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using OtterGui.Classes; using Penumbra.Services; namespace Penumbra.Collections.Manager; @@ -46,10 +47,8 @@ public static class ActiveCollectionMigration { if (!storage.ByName(collectionName, out var collection)) { - Penumbra.Chat.NotificationMessage( - $"Last choice of <{player}>'s Collection {collectionName} is not available, reset to {ModCollection.Empty.Name}.", - "Load Failure", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"Last choice of <{player}>'s Collection {collectionName} is not available, reset to {ModCollection.Empty.Name}.", NotificationType.Warning); dict.Add(player, ModCollection.Empty); } else diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 7e6d691e..3da009a3 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; +using OtterGui.Classes; using Penumbra.Communication; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; @@ -331,10 +332,8 @@ public class ActiveCollections : ISavable, IDisposable ?? (configChanged ? ModCollection.DefaultCollectionName : ModCollection.Empty.Name); if (!_storage.ByName(defaultName, out var defaultCollection)) { - Penumbra.Chat.NotificationMessage( - $"Last choice of {TutorialService.DefaultCollection} {defaultName} is not available, reset to {ModCollection.Empty.Name}.", - "Load Failure", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"Last choice of {TutorialService.DefaultCollection} {defaultName} is not available, reset to {ModCollection.Empty.Name}.", NotificationType.Warning); Default = ModCollection.Empty; configChanged = true; } @@ -347,9 +346,8 @@ public class ActiveCollections : ISavable, IDisposable var interfaceName = jObject[nameof(Interface)]?.ToObject() ?? Default.Name; if (!_storage.ByName(interfaceName, out var interfaceCollection)) { - Penumbra.Chat.NotificationMessage( - $"Last choice of {TutorialService.InterfaceCollection} {interfaceName} is not available, reset to {ModCollection.Empty.Name}.", - "Load Failure", NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"Last choice of {TutorialService.InterfaceCollection} {interfaceName} is not available, reset to {ModCollection.Empty.Name}.", NotificationType.Warning); Interface = ModCollection.Empty; configChanged = true; } @@ -362,9 +360,8 @@ public class ActiveCollections : ISavable, IDisposable var currentName = jObject[nameof(Current)]?.ToObject() ?? Default.Name; if (!_storage.ByName(currentName, out var currentCollection)) { - Penumbra.Chat.NotificationMessage( - $"Last choice of {TutorialService.SelectedCollection} {currentName} is not available, reset to {ModCollection.DefaultCollectionName}.", - "Load Failure", NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"Last choice of {TutorialService.SelectedCollection} {currentName} is not available, reset to {ModCollection.DefaultCollectionName}.", NotificationType.Warning); Current = _storage.DefaultNamed; configChanged = true; } @@ -381,8 +378,7 @@ public class ActiveCollections : ISavable, IDisposable { if (!_storage.ByName(typeName, out var typeCollection)) { - Penumbra.Chat.NotificationMessage($"Last choice of {name} Collection {typeName} is not available, removed.", - "Load Failure", + Penumbra.Messager.NotificationMessage($"Last choice of {name} Collection {typeName} is not available, removed.", NotificationType.Warning); configChanged = true; } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index e50b9bdb..70b2cd13 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; +using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Mods; @@ -102,9 +103,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable { if (!CanAddCollection(name, out var fixedName)) { - Penumbra.Chat.NotificationMessage( - $"The new collection {name} would lead to the same path {fixedName} as one that already exists.", "Warning", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"The new collection {name} would lead to the same path {fixedName} as one that already exists.", NotificationType.Warning, false); return false; } @@ -113,8 +113,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable _collections.Add(newCollection); _saveService.ImmediateSave(new ModCollectionSave(_modStorage, newCollection)); - Penumbra.Chat.NotificationMessage($"Created new collection {newCollection.AnonymizedName}.", "Success", - NotificationType.Success); + Penumbra.Messager.NotificationMessage($"Created new collection {newCollection.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, null, newCollection, string.Empty); return true; } @@ -126,13 +125,13 @@ public class CollectionStorage : IReadOnlyList, IDisposable { if (collection.Index <= ModCollection.Empty.Index || collection.Index >= _collections.Count) { - Penumbra.Chat.NotificationMessage("Can not remove the empty collection.", "Error", NotificationType.Error); + Penumbra.Messager.NotificationMessage("Can not remove the empty collection.", NotificationType.Error, false); return false; } if (collection.Index == DefaultNamed.Index) { - Penumbra.Chat.NotificationMessage("Can not remove the default collection.", "Error", NotificationType.Error); + Penumbra.Messager.NotificationMessage("Can not remove the default collection.", NotificationType.Error, false); return false; } @@ -142,7 +141,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable for (var i = collection.Index; i < Count; ++i) _collections[i].Index = i; - Penumbra.Chat.NotificationMessage($"Deleted collection {collection.AnonymizedName}.", "Success", NotificationType.Success); + Penumbra.Messager.NotificationMessage($"Deleted collection {collection.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, collection, null, string.Empty); return true; } @@ -185,23 +184,20 @@ public class CollectionStorage : IReadOnlyList, IDisposable if (!IsValidName(name)) { // TODO: handle better. - Penumbra.Chat.NotificationMessage($"Collection of unsupported name found: {name} is not a valid collection name.", - "Warning", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Collection of unsupported name found: {name} is not a valid collection name.", NotificationType.Warning); continue; } if (ByName(name, out _)) { - Penumbra.Chat.NotificationMessage($"Duplicate collection found: {name} already exists. Import skipped.", - "Warning", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Duplicate collection found: {name} already exists. Import skipped.", NotificationType.Warning); continue; } var collection = ModCollection.CreateFromData(_saveService, _modStorage, name, version, Count, settings, inheritance); var correctName = _saveService.FileNames.CollectionFile(collection); if (file.FullName != correctName) - Penumbra.Chat.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Name}.", "Warning", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Name}.", NotificationType.Warning); _collections.Add(collection); } @@ -221,9 +217,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable if (AddCollection(ModCollection.DefaultCollectionName, null)) return _collections[^1]; - Penumbra.Chat.NotificationMessage( - $"Unknown problem creating a collection with the name {ModCollection.DefaultCollectionName}, which is required to exist.", "Error", - NotificationType.Error); + Penumbra.Messager.NotificationMessage( + $"Unknown problem creating a collection with the name {ModCollection.DefaultCollectionName}, which is required to exist.", NotificationType.Error); return Count > 1 ? _collections[1] : _collections[0]; } diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index 21a0c730..fa6019c6 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -1,6 +1,7 @@ using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json.Linq; +using OtterGui.Classes; using Penumbra.GameData.Actors; using Penumbra.Services; using Penumbra.String; @@ -56,7 +57,7 @@ public partial class IndividualCollections if (group.Length == 0 || group.Any(i => !i.IsValid)) { changes = true; - Penumbra.Chat.NotificationMessage("Could not load an unknown individual collection, removed.", "Load Failure", + Penumbra.Messager.NotificationMessage("Could not load an unknown individual collection, removed.", NotificationType.Warning); continue; } @@ -65,9 +66,8 @@ public partial class IndividualCollections if (collectionName.Length == 0 || !storage.ByName(collectionName, out var collection)) { changes = true; - Penumbra.Chat.NotificationMessage( + Penumbra.Messager.NotificationMessage( $"Could not load the collection \"{collectionName}\" as individual collection for {identifier}, set to None.", - "Load Failure", NotificationType.Warning); continue; } @@ -75,16 +75,14 @@ public partial class IndividualCollections if (!Add(group, collection)) { changes = true; - Penumbra.Chat.NotificationMessage($"Could not add an individual collection for {identifier}, removed.", - "Load Failure", + Penumbra.Messager.NotificationMessage($"Could not add an individual collection for {identifier}, removed.", NotificationType.Warning); } } catch (Exception e) { changes = true; - Penumbra.Chat.NotificationMessage($"Could not load an unknown individual collection, removed:\n{e}", "Load Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not load an unknown individual collection, removed.", NotificationType.Error); } } @@ -124,9 +122,9 @@ public partial class IndividualCollections if (Add($"{_actorService.AwaitedService.Data.ToName(kind, dataId)} ({kind.ToName()})", group, collection)) Penumbra.Log.Information($"Migrated {name} ({kind.ToName()}) to NPC Identifiers [{ids}]."); else - Penumbra.Chat.NotificationMessage( + Penumbra.Messager.NotificationMessage( $"Could not migrate {name} ({collection.AnonymizedName}) which was assumed to be a {kind.ToName()} with IDs [{ids}], please look through your individual collections.", - "Migration Failure", NotificationType.Error); + NotificationType.Error); } // If it is not a valid NPC name, check if it can be a player name. else if (ActorManager.VerifyPlayerName(name)) @@ -140,15 +138,15 @@ public partial class IndividualCollections }, collection)) Penumbra.Log.Information($"Migrated {shortName} ({collection.AnonymizedName}) to Player Identifier."); else - Penumbra.Chat.NotificationMessage( + Penumbra.Messager.NotificationMessage( $"Could not migrate {shortName} ({collection.AnonymizedName}), please look through your individual collections.", - "Migration Failure", NotificationType.Error); + NotificationType.Error); } else { - Penumbra.Chat.NotificationMessage( + Penumbra.Messager.NotificationMessage( $"Could not migrate {name} ({collection.AnonymizedName}), which can not be a player name nor is it a known NPC name, please look through your individual collections.", - "Migration Failure", NotificationType.Error); + NotificationType.Error); } } } diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index 4c1bdc5a..771f9463 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; +using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Mods.Manager; @@ -143,14 +144,12 @@ public class InheritanceManager : IDisposable continue; changes = true; - Penumbra.Chat.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", "Warning", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", NotificationType.Warning); } else { - Penumbra.Chat.NotificationMessage( - $"Inherited collection {subCollectionName} for {collection.AnonymizedName} does not exist, it was removed.", "Warning", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"Inherited collection {subCollectionName} for {collection.AnonymizedName} does not exist, it was removed.", NotificationType.Warning); changes = true; } } diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 7c9ae665..d221b4a2 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -137,9 +137,9 @@ public class Configuration : IPluginConfiguration, ISavable } catch (Exception ex) { - Penumbra.Chat.NotificationMessage(ex, + Penumbra.Messager.NotificationMessage(ex, "Error reading Configuration, reverting to default.\nYou may be able to restore your configuration using the rolling backups in the XIVLauncher/backups/Penumbra directory.", - "Error reading Configuration", "Error", NotificationType.Error); + "Error reading Configuration", NotificationType.Error); } migrator.Migrate(utility, this); diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index f90f6c0a..37ffdcfe 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -1,6 +1,7 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; using OtterGui; +using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Meta.Manipulations; @@ -81,9 +82,7 @@ public class ModMerger : IDisposable catch (Exception ex) { Error = ex; - Penumbra.Chat.NotificationMessage( - $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}, cleaning up changes.:\n{ex}", "Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(ex, $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}, cleaning up changes.", NotificationType.Error, false); FailureCleanup(); DataCleanup(); } diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index eebc8ab4..3610c99a 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; +using OtterGui.Classes; using OtterGui.Tasks; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; @@ -74,7 +75,7 @@ public class ModNormalizer } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not normalize mod:\n{e}", "Failure", NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not normalize mod {Mod.Name}.", NotificationType.Error, false); } finally { @@ -87,17 +88,15 @@ public class ModNormalizer { if (Directory.Exists(_normalizationDirName)) { - Penumbra.Chat.NotificationMessage("Could not normalize mod:\n" - + "The directory TmpNormalization may not already exist when normalizing a mod.", "Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage($"Could not normalize mod {Mod.Name}:\n" + + "The directory TmpNormalization may not already exist when normalizing a mod.", NotificationType.Error, false); return false; } if (Directory.Exists(_oldDirName)) { - Penumbra.Chat.NotificationMessage("Could not normalize mod:\n" - + "The directory TmpNormalizationOld may not already exist when normalizing a mod.", "Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage($"Could not normalize mod {Mod.Name}:\n" + + "The directory TmpNormalizationOld may not already exist when normalizing a mod.", NotificationType.Error, false); return false; } @@ -201,7 +200,7 @@ public class ModNormalizer } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not normalize mod:\n{e}", "Failure", NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not normalize mod {Mod.Name}.", NotificationType.Error, false); } return false; @@ -229,8 +228,7 @@ public class ModNormalizer } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not move old files out of the way while normalizing mod mod:\n{e}", "Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not move old files out of the way while normalizing mod {Mod.Name}.", NotificationType.Error, false); } return false; @@ -253,8 +251,7 @@ public class ModNormalizer } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not move new files into the mod while normalizing mod mod:\n{e}", "Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not move new files into the mod while normalizing mod {Mod.Name}.", NotificationType.Error, false); foreach (var dir in Mod.ModPath.EnumerateDirectories()) { if (dir.FullName.Equals(_oldDirName, StringComparison.OrdinalIgnoreCase) diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index 96cf146b..73571ea4 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -1,4 +1,5 @@ using Dalamud.Interface.Internal.Notifications; +using OtterGui.Classes; using Penumbra.Import; using Penumbra.Mods.Editor; @@ -42,8 +43,7 @@ public class ModImportManager : IDisposable if (File.Exists(s)) return true; - Penumbra.Chat.NotificationMessage($"Failed to import queued mod at {s}, the file does not exist.", "Warning", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Failed to import queued mod at {s}, the file does not exist.", NotificationType.Warning, false); return false; }).Select(s => new FileInfo(s)).ToArray(); diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 3eeb13c6..0a3034fc 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; +using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; @@ -395,9 +396,9 @@ public class ModOptionEditor return true; if (message) - Penumbra.Chat.NotificationMessage( + Penumbra.Messager.NotificationMessage( $"Could not name option {newName} because option with same filename {path} already exists.", - "Warning", NotificationType.Warning); + NotificationType.Warning, false); return false; } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 236f1539..98770edc 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; +using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.GameData; @@ -45,8 +46,7 @@ public partial class ModCreator } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not create directory for new Mod {newName}:\n{e}", "Failure", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not create directory for new Mod {newName}.", NotificationType.Error, false); return null; } } diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 4d29c58d..07f84722 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; +using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; @@ -54,9 +55,8 @@ public sealed class MultiModGroup : IModGroup { if (ret.PrioritizedOptions.Count == IModGroup.MaxMultiOptions) { - Penumbra.Chat.NotificationMessage( - $"Multi Group {ret.Name} has more than {IModGroup.MaxMultiOptions} options, ignoring excessive options.", "Warning", - NotificationType.Warning); + Penumbra.Messager.NotificationMessage( + $"Multi Group {ret.Name} in {mod.Name} has more than {IModGroup.MaxMultiOptions} options, ignoring excessive options.", NotificationType.Warning); break; } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 0519baae..73d1013e 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -31,7 +31,7 @@ public class Penumbra : IDalamudPlugin => "Penumbra"; public static readonly Logger Log = new(); - public static ChatService Chat { get; private set; } = null!; + public static MessageService Messager { get; private set; } = null!; private readonly ValidityChecker _validityChecker; private readonly ResidentResourceManager _residentResources; @@ -55,7 +55,7 @@ public class Penumbra : IDalamudPlugin var startTimer = new StartTracker(); using var timer = startTimer.Measure(StartTimeType.Total); _services = ServiceManager.CreateProvider(this, pluginInterface, Log, startTimer); - Chat = _services.GetRequiredService(); + Messager = _services.GetRequiredService(); _validityChecker = _services.GetRequiredService(); var startup = _services.GetRequiredService().GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool s) ? s.ToString() @@ -118,7 +118,7 @@ public class Penumbra : IDalamudPlugin _communicatorService.ChangedItemClick.Subscribe((button, it) => { if (button == MouseButton.Left && it is Item item) - Chat.LinkItem(item); + Messager.LinkItem(item); }, ChangedItemClick.Priority.Link); } diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index f6e2c3e4..e623be3e 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -41,7 +41,7 @@ public class BackupService { Penumbra.Log.Error($"Failed to load {fileName}, trying to restore from backup:\n{ex}"); Backup.TryGetFile(new DirectoryInfo(fileNames.ConfigDirectory), fileName, out ret, out var messages, JObject.Parse); - Penumbra.Chat.NotificationMessage(messages); + Penumbra.Messager.NotificationMessage(messages); } return ret; diff --git a/Penumbra/Services/ChatService.cs b/Penumbra/Services/MessageService.cs similarity index 80% rename from Penumbra/Services/ChatService.cs rename to Penumbra/Services/MessageService.cs index 3e715a4f..c893b00f 100644 --- a/Penumbra/Services/ChatService.cs +++ b/Penumbra/Services/MessageService.cs @@ -1,20 +1,18 @@ using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; -using Dalamud.Plugin; +using Dalamud.Interface; using Dalamud.Plugin.Services; using Lumina.Excel.GeneratedSheets; using OtterGui.Log; namespace Penumbra.Services; -public class ChatService : OtterGui.Classes.ChatService +public class MessageService : OtterGui.Classes.MessageService { - private readonly IChatGui _chat; - - public ChatService(Logger log, DalamudPluginInterface pi, IChatGui chat) - : base(log, pi) - => _chat = chat; + public MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat) + : base(log, uiBuilder, chat) + { } public void LinkItem(Item item) { @@ -37,7 +35,7 @@ public class ChatService : OtterGui.Classes.ChatService var payload = new SeString(payloadList); - _chat.Print(new XivChatEntry + Chat.Print(new XivChatEntry { Message = payload, }); diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 9e3b9b1a..84f89f6d 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -65,7 +65,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() + .AddSingleton() .AddSingleton() .AddSingleton(); @@ -165,6 +165,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() + .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index b8d9b30a..749da5b9 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Plugin; +using OtterGui.Classes; namespace Penumbra.Services; @@ -33,8 +34,7 @@ public class ValidityChecker public void LogExceptions() { if (ImcExceptions.Count > 0) - Penumbra.Chat.NotificationMessage($"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", - "Warning", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", NotificationType.Warning); } // Because remnants of penumbra in devPlugins cause issues, we check for them to warn users to remove them. diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 9354afaf..b84fa84c 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -137,7 +137,7 @@ public class FileEditor : IDisposable where T : class, IWritable } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not export {_defaultPath}:\n{e}", "Error", NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not export {_defaultPath}.", NotificationType.Error); } }, _getInitialPath(), false); diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 967e8d01..8597bc0c 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -4,6 +4,7 @@ using Dalamud.Utility; using ImGuiNET; using Lumina.Excel.GeneratedSheets; using OtterGui; +using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.Api.Enums; @@ -321,7 +322,7 @@ public class ItemSwapTab : IDisposable, ITab } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not create new Swap Option:\n{e}", "Error", NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, "Could not create new Swap Option.", NotificationType.Error, false); try { if (optionCreated && _selectedGroup != null) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index ebe980d7..20efe757 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -113,8 +113,7 @@ public partial class ModEditWindow LoadedShpkPath = FullPath.Empty; LoadedShpkPathName = string.Empty; AssociatedShpk = null; - Penumbra.Chat.NotificationMessage($"Could not load {LoadedShpkPath.ToPath()}:\n{e}", "Penumbra Advanced Editing", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not load {LoadedShpkPath.ToPath()}.", NotificationType.Error, false); } if (LoadedShpkPath.InternalName.IsEmpty) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 6b867b27..804feae1 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -4,6 +4,7 @@ using ImGuiNET; using Lumina.Misc; using OtterGui.Raii; using OtterGui; +using OtterGui.Classes; using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; @@ -87,15 +88,14 @@ public partial class ModEditWindow } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not export {defaultName}{tab.Extension} to {name}:\n{e.Message}", - "Penumbra Advanced Editing", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not export {defaultName}{tab.Extension} to {name}.", + NotificationType.Error, false); return; } - Penumbra.Chat.NotificationMessage( - $"Shader Program Blob {defaultName}{tab.Extension} exported successfully to {Path.GetFileName(name)}", - "Penumbra Advanced Editing", NotificationType.Success); + Penumbra.Messager.NotificationMessage( + $"Shader Program Blob {defaultName}{tab.Extension} exported successfully to {Path.GetFileName(name)}.", + NotificationType.Success, false); }, null, false); } @@ -116,8 +116,7 @@ public partial class ModEditWindow } catch (Exception e) { - Penumbra.Chat.NotificationMessage($"Could not import {name}:\n{e.Message}", "Penumbra Advanced Editing", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not import {name}.", NotificationType.Error, false); return; } @@ -129,9 +128,8 @@ public partial class ModEditWindow catch (Exception e) { tab.Shpk.SetInvalid(); - Penumbra.Chat.NotificationMessage($"Failed to update resources after importing {name}:\n{e.Message}", - "Penumbra Advanced Editing", - NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Failed to update resources after importing {name}.", NotificationType.Error, + false); return; } diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 5cedd824..0f209686 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -142,7 +142,7 @@ public sealed class ConfigWindow : Window ImGui.NewLine(); ImGui.NewLine(); - CustomGui.DrawDiscordButton(Penumbra.Chat, 0); + CustomGui.DrawDiscordButton(Penumbra.Messager, 0); ImGui.SameLine(); UiHelpers.DrawSupportButton(_penumbra!); ImGui.NewLine(); diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 215a0269..cc4ceb55 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -18,14 +18,14 @@ using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.UI.Classes; -using ChatService = Penumbra.Services.ChatService; +using MessageService = Penumbra.Services.MessageService; namespace Penumbra.UI.ModsTab; public sealed class ModFileSystemSelector : FileSystemSelector { private readonly CommunicatorService _communicator; - private readonly ChatService _chat; + private readonly MessageService _messager; private readonly Configuration _config; private readonly FileDialogService _fileDialog; private readonly ModManager _modManager; @@ -37,7 +37,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Penumbra.Chat.NotificationMessage(e.Message, "Failure", NotificationType.Warning); + => Penumbra.Messager.NotificationMessage(e, e.Message, NotificationType.Warning); #endregion diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 44c40247..18d0e613 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -6,6 +6,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; +using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -18,15 +19,15 @@ namespace Penumbra.UI.ModsTab; public class ModPanelEditTab : ITab { - private readonly ChatService _chat; - private readonly FilenameService _filenames; - private readonly ModManager _modManager; - private readonly ModExportManager _modExportManager; - private readonly ModFileSystem _fileSystem; - private readonly ModFileSystemSelector _selector; - private readonly ModEditWindow _editWindow; - private readonly ModEditor _editor; - private readonly Configuration _config; + private readonly Services.MessageService _messager; + private readonly FilenameService _filenames; + private readonly ModManager _modManager; + private readonly ModExportManager _modExportManager; + private readonly ModFileSystem _fileSystem; + private readonly ModFileSystemSelector _selector; + private readonly ModEditWindow _editWindow; + private readonly ModEditor _editor; + private readonly Configuration _config; private readonly TagButtons _modTags = new(); @@ -35,13 +36,13 @@ public class ModPanelEditTab : ITab private ModFileSystem.Leaf _leaf = null!; private Mod _mod = null!; - public ModPanelEditTab(ModManager modManager, ModFileSystemSelector selector, ModFileSystem fileSystem, ChatService chat, + public ModPanelEditTab(ModManager modManager, ModFileSystemSelector selector, ModFileSystem fileSystem, Services.MessageService messager, ModEditWindow editWindow, ModEditor editor, FilenameService filenames, ModExportManager modExportManager, Configuration config) { _modManager = modManager; _selector = selector; _fileSystem = fileSystem; - _chat = chat; + _messager = messager; _editWindow = editWindow; _editor = editor; _filenames = filenames; @@ -75,7 +76,7 @@ public class ModPanelEditTab : ITab } catch (Exception e) { - _chat.NotificationMessage(e.Message, "Warning", NotificationType.Warning); + _messager.NotificationMessage(e.Message, NotificationType.Warning, false); } UiHelpers.DefaultLineSpace(); diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index ee66ca86..1cc29d88 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -19,7 +19,8 @@ public class ConfigTabBar : IDisposable public readonly DebugTab Debug; public readonly ResourceTab Resource; public readonly Watcher Watcher; - public readonly OnScreenTab OnScreenTab; + public readonly OnScreenTab OnScreen; + public readonly MessagesTab Messages; public readonly ITab[] Tabs; @@ -28,7 +29,7 @@ public class ConfigTabBar : IDisposable public ConfigTabBar(CommunicatorService communicator, SettingsTab settings, ModsTab mods, CollectionsTab collections, ChangedItemsTab changedItems, EffectiveTab effective, DebugTab debug, ResourceTab resource, Watcher watcher, - OnScreenTab onScreenTab) + OnScreenTab onScreen, MessagesTab messages) { _communicator = communicator; @@ -40,7 +41,8 @@ public class ConfigTabBar : IDisposable Debug = debug; Resource = resource; Watcher = watcher; - OnScreenTab = onScreenTab; + OnScreen = onScreen; + Messages = messages; Tabs = new ITab[] { Settings, @@ -48,10 +50,11 @@ public class ConfigTabBar : IDisposable Mods, ChangedItems, Effective, - OnScreenTab, + OnScreen, Debug, Resource, Watcher, + Messages, }; _communicator.SelectTab.Subscribe(OnSelectTab, Communication.SelectTab.Priority.ConfigTabBar); } @@ -75,10 +78,11 @@ public class ConfigTabBar : IDisposable TabType.Collections => Collections.Label, TabType.ChangedItems => ChangedItems.Label, TabType.EffectiveChanges => Effective.Label, - TabType.OnScreen => OnScreenTab.Label, + TabType.OnScreen => OnScreen.Label, TabType.ResourceWatcher => Watcher.Label, TabType.Debug => Debug.Label, TabType.ResourceManager => Resource.Label, + TabType.Messages => Messages.Label, _ => ReadOnlySpan.Empty, }; @@ -90,7 +94,8 @@ public class ConfigTabBar : IDisposable if (label == Settings.Label) return TabType.Settings; if (label == ChangedItems.Label) return TabType.ChangedItems; if (label == Effective.Label) return TabType.EffectiveChanges; - if (label == OnScreenTab.Label) return TabType.OnScreen; + if (label == OnScreen.Label) return TabType.OnScreen; + if (label == Messages.Label) return TabType.Messages; if (label == Watcher.Label) return TabType.ResourceWatcher; if (label == Debug.Label) return TabType.Debug; if (label == Resource.Label) return TabType.ResourceManager; diff --git a/Penumbra/UI/Tabs/MessagesTab.cs b/Penumbra/UI/Tabs/MessagesTab.cs new file mode 100644 index 00000000..e834a4b4 --- /dev/null +++ b/Penumbra/UI/Tabs/MessagesTab.cs @@ -0,0 +1,21 @@ +using OtterGui.Widgets; +using Penumbra.Services; + +namespace Penumbra.UI.Tabs; + +public class MessagesTab : ITab +{ + public ReadOnlySpan Label + => "Messages"u8; + + private readonly MessageService _messages; + + public MessagesTab(MessageService messages) + => _messages = messages; + + public bool IsVisible + => _messages.Count > 0; + + public void DrawContent() + => _messages.Draw(); +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 7c350106..32bd6b8f 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -851,10 +851,10 @@ public class SettingsTab : ITab UiHelpers.DrawSupportButton(_penumbra); ImGui.SetCursorPos(new Vector2(xPos, 0)); - CustomGui.DrawDiscordButton(Penumbra.Chat, width); + CustomGui.DrawDiscordButton(Penumbra.Messager, width); ImGui.SetCursorPos(new Vector2(xPos, 2 * ImGui.GetFrameHeightWithSpacing())); - CustomGui.DrawGuideButton(Penumbra.Chat, width); + CustomGui.DrawGuideButton(Penumbra.Messager, width); ImGui.SetCursorPos(new Vector2(xPos, 3 * ImGui.GetFrameHeightWithSpacing())); if (ImGui.Button("Restart Tutorial", new Vector2(width, 0))) diff --git a/Penumbra/UI/UiHelpers.cs b/Penumbra/UI/UiHelpers.cs index a37d8e77..6c64bd55 100644 --- a/Penumbra/UI/UiHelpers.cs +++ b/Penumbra/UI/UiHelpers.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; +using OtterGui.Classes; using OtterGui.Raii; using Penumbra.Interop.Structs; using Penumbra.String; @@ -56,7 +57,7 @@ public static class UiHelpers var text = penumbra.GatherSupportInformation(); ImGui.SetClipboardText(text); - Penumbra.Chat.NotificationMessage($"Copied Support Info to Clipboard.", "Success", NotificationType.Success); + Penumbra.Messager.NotificationMessage($"Copied Support Info to Clipboard.", NotificationType.Success, false); } /// Draw a button to open a specific directory in a file explorer. From 52d38eda3a0617e6a2228561128e22238f22bb55 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 18:21:47 +0200 Subject: [PATCH 0152/1381] 0.8.1.0 Changelog --- Penumbra/UI/Changelog.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 8a2b0fcb..c1a2671c 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -42,10 +42,21 @@ public class PenumbraChangelog Add7_2_0(Changelog); Add7_3_0(Changelog); Add8_0_0(Changelog); + Add8_1_0(Changelog); } #region Changelogs + private static void Add8_1_0(Changelog log) + => log.NextVersion("Version 0.8.1.0") + .RegisterImportant( + "Updated for 6.5 - Square Enix shuffled around a lot of things this update, so some things still might not work but have not been noticed yet. Please report any issues.") + .RegisterEntry("Added support for chat commands to affect multiple individuals matching the supplied string at once.") + .RegisterEntry( + "Improved messaging: many warnings or errors appearing will stay a little longer and can now be looked at in a Messages tab (visible only if there have been any).") + .RegisterEntry("Fixed an issue with leading or trailing spaces when renaming mods."); + + private static void Add8_0_0(Changelog log) => log.NextVersion("Version 0.8.0.0") .RegisterEntry( @@ -79,7 +90,9 @@ public class PenumbraChangelog .RegisterEntry( "Addition and removal of shader keys, textures, constants and a color table has been automated following shader requirements and can not be done manually anymore.", 1) - .RegisterEntry("Plain English names and tooltips can now be displayed instead of hexadecimal identifiers or code names by providing dev-kit files installed via certain mods.", 1) + .RegisterEntry( + "Plain English names and tooltips can now be displayed instead of hexadecimal identifiers or code names by providing dev-kit files installed via certain mods.", + 1) .RegisterEntry("The Texture editor has been improved (by Ny):") .RegisterHighlight("The overlay texture can now be combined in several ways and automatically resized to match the input texture.", 1) From dd587350ea432990eee0d75b892d1af7caa3742e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 18:30:57 +0200 Subject: [PATCH 0153/1381] Update changelog discord export. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 96c9055a..44ec7c38 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 96c9055a1d8a19d9cdb61f41ddfb372871e204ac +Subproject commit 44ec7c38442dad765746abcc0dc838ad3936a0b7 diff --git a/Penumbra.GameData b/Penumbra.GameData index 5b23ba04..f97df642 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 5b23ba04e5fd0e934c882c38024ab1b5661b44e1 +Subproject commit f97df642999d4edc6dce7fac64903485b5a2fa11 From 3b593103ba5962c7ad3f46429637ef7fa088336f Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 5 Oct 2023 16:33:35 +0000 Subject: [PATCH 0154/1381] [CI] Updating repo.json for 0.8.1.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 1c13cdab..62c4be77 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.0.0", - "TestingAssemblyVersion": "0.8.0.4", + "AssemblyVersion": "0.8.1.0", + "TestingAssemblyVersion": "0.8.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.0.4/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.0.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From de3a74bbe88d17f3fadd6857ba0dbb36a1f750c9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 20:29:34 +0200 Subject: [PATCH 0155/1381] Change SubModules to https --- .gitmodules | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitmodules b/.gitmodules index c03525eb..ea1199ad 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,16 +1,16 @@ [submodule "OtterGui"] path = OtterGui - url = git@github.com:Ottermandias/OtterGui.git + url = https://github.com/Ottermandias/OtterGui.git branch = main [submodule "Penumbra.Api"] path = Penumbra.Api - url = git@github.com:Ottermandias/Penumbra.Api.git + url = https://github.com/Ottermandias/Penumbra.Api.git branch = main [submodule "Penumbra.String"] path = Penumbra.String - url = git@github.com:Ottermandias/Penumbra.String.git + url = https://github.com/Ottermandias/Penumbra.String.git branch = main [submodule "Penumbra.GameData"] path = Penumbra.GameData - url = git@github.com:Ottermandias/Penumbra.GameData.git + url = https://github.com/Ottermandias/Penumbra.GameData.git branch = main From 422324b6d7fc77d5991b6b02e5a76e584db68ef0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 21:22:09 +0200 Subject: [PATCH 0156/1381] Revert stupid changes due to ResourceCategory change. --- Penumbra.GameData | 2 +- .../Interop/ResourceLoading/ResourceLoader.cs | 4 ++-- .../ResourceLoading/ResourceService.cs | 23 ++++++------------- Penumbra/UI/Tabs/DebugTab.cs | 2 +- 4 files changed, 11 insertions(+), 20 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index f97df642..34e3299f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f97df642999d4edc6dce7fac64903485b5a2fa11 +Subproject commit 34e3299f28c5e1d2b7d071ba8a3f851f5d1fa057 diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index b8cc4742..8ccdfa80 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -92,7 +92,7 @@ public unsafe class ResourceLoader : IDisposable if (resolvedPath == null || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var p)) { - returnValue = _resources.GetOriginalResource(sync, ref category, ref type, ref hash, path.Path, parameters); + returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); ResourceLoaded?.Invoke(returnValue, path, resolvedPath, data); return; } @@ -102,7 +102,7 @@ public unsafe class ResourceLoader : IDisposable hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; path = p; - returnValue = _resources.GetOriginalResource(sync, ref category, ref type, ref hash, path.Path, parameters); + returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); ResourceLoaded?.Invoke(returnValue, oldPath, resolvedPath.Value, data); } diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 792f8a8e..6fb2e560 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -110,26 +110,17 @@ public unsafe class ResourceService : IDisposable if (returnValue != null) return returnValue; - return GetOriginalResource(isSync, categoryId, resourceType, resourceHash, gamePath.Path.Path, pGetResParams, isUnk); + return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk); } - private ResourceHandle* GetOriginalResource(bool sync, ResourceCategory* categoryId, ResourceType* type, int* hash, byte* path, - GetResourceParameters* resourceParameters = null, bool unk = false) - => sync - ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, categoryId, type, hash, path, - resourceParameters) - : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, categoryId, type, hash, path, - resourceParameters, unk); - /// Call the original GetResource function. - public ResourceHandle* GetOriginalResource(bool sync, ref ResourceCategory categoryId, ref ResourceType type, ref int hash, ByteString path, + public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, ByteString path, GetResourceParameters* resourceParameters = null, bool unk = false) - { - var ptrCategory = (ResourceCategory*)Unsafe.AsPointer(ref categoryId); - var ptrType = (ResourceType*)Unsafe.AsPointer(ref type); - var ptrHash = (int*)Unsafe.AsPointer(ref hash); - return GetOriginalResource(sync, ptrCategory, ptrType, ptrHash, path.Path, resourceParameters, unk); - } + => sync + ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, + resourceParameters) + : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, + resourceParameters, unk); #endregion diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index b0715da1..5abb3c2f 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -858,7 +858,7 @@ public class DebugTab : Window, ITab return; ImGui.TableNextColumn(); - ImGui.TextUnformatted(r->Category.ToString()); + ImGui.TextUnformatted(((ResourceCategory)r->Type.Value).ToString()); ImGui.TableNextColumn(); ImGui.TextUnformatted(r->FileType.ToString("X")); ImGui.TableNextColumn(); From 110298f280afe74bc9e7e016cfa31a09e1f7b427 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Oct 2023 21:23:02 +0200 Subject: [PATCH 0157/1381] Increment Changelog Version. --- Penumbra/UI/Changelog.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index c1a2671c..5540285b 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -42,13 +42,13 @@ public class PenumbraChangelog Add7_2_0(Changelog); Add7_3_0(Changelog); Add8_0_0(Changelog); - Add8_1_0(Changelog); + Add8_1_1(Changelog); } #region Changelogs - private static void Add8_1_0(Changelog log) - => log.NextVersion("Version 0.8.1.0") + private static void Add8_1_1(Changelog log) + => log.NextVersion("Version 0.8.1.1") .RegisterImportant( "Updated for 6.5 - Square Enix shuffled around a lot of things this update, so some things still might not work but have not been noticed yet. Please report any issues.") .RegisterEntry("Added support for chat commands to affect multiple individuals matching the supplied string at once.") From 9fda19d4c0621ca1676f03ea7d1533a7c8637b31 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 5 Oct 2023 19:25:42 +0000 Subject: [PATCH 0158/1381] [CI] Updating repo.json for 0.8.1.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 62c4be77..c8a04440 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.0", - "TestingAssemblyVersion": "0.8.1.0", + "AssemblyVersion": "0.8.1.1", + "TestingAssemblyVersion": "0.8.1.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 2d007c189fac933449b641d5d9869ffbd7749e37 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 6 Oct 2023 16:16:27 +0200 Subject: [PATCH 0159/1381] Fix deletion in selector. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 44ec7c38..c466bd33 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 44ec7c38442dad765746abcc0dc838ad3936a0b7 +Subproject commit c466bd33442dda3ade26f05c9e8d694443564118 From 7cdd8656eff237109c7ec4227ae98ddc4af8e5f8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 6 Oct 2023 16:21:33 +0200 Subject: [PATCH 0160/1381] Maybe fix issue with individual assignments sometimes getting eaten. --- Penumbra.GameData | 2 +- Penumbra/Collections/Manager/IndividualCollections.cs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 34e3299f..ac0710e9 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 34e3299f28c5e1d2b7d071ba8a3f851f5d1fa057 +Subproject commit ac0710e9a116bec8633f3dcde2c9b6e38dffaaa9 diff --git a/Penumbra/Collections/Manager/IndividualCollections.cs b/Penumbra/Collections/Manager/IndividualCollections.cs index 4fe1e829..31695a94 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.cs @@ -132,8 +132,7 @@ public sealed partial class IndividualCollections }; return table.Where(kvp => kvp.Value == name) .Select(kvp => manager.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, identifier.HomeWorld.Id, - identifier.Kind, - kvp.Key)).ToArray(); + identifier.Kind, kvp.Key)).ToArray(); } return identifier.Type switch From 987142163242e3443bbdc404dc3909f453a20032 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 7 Oct 2023 15:31:18 +0200 Subject: [PATCH 0161/1381] 0.8.1.2 --- Penumbra/UI/Changelog.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 5540285b..7589e6ec 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -43,10 +43,16 @@ public class PenumbraChangelog Add7_3_0(Changelog); Add8_0_0(Changelog); Add8_1_1(Changelog); + Add8_1_2(Changelog); } #region Changelogs + private static void Add8_1_2(Changelog log) + => log.NextVersion("Version 0.8.1.2") + .RegisterEntry("Fixed an issue keeping mods selected after their deletion.") + .RegisterEntry("Maybe fixed an issue causing individual assignments to get lost on game start."); + private static void Add8_1_1(Changelog log) => log.NextVersion("Version 0.8.1.1") .RegisterImportant( From 717ddba8d2d2df76ca6f48a04201d471671a379b Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 7 Oct 2023 13:34:11 +0000 Subject: [PATCH 0162/1381] [CI] Updating repo.json for 0.8.1.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index c8a04440..af898a90 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.1", - "TestingAssemblyVersion": "0.8.1.1", + "AssemblyVersion": "0.8.1.2", + "TestingAssemblyVersion": "0.8.1.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 4378c826f07bf6c1d9727c489ccfc133d448a874 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 8 Oct 2023 13:19:01 +0200 Subject: [PATCH 0163/1381] Add some log statements. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Collections/Manager/ActiveCollections.cs | 3 +++ Penumbra/Collections/Manager/CollectionStorage.cs | 2 ++ .../Manager/IndividualCollections.Files.cs | 14 ++++++++++++-- Penumbra/Import/Structs/StreamDisposer.cs | 7 ++----- Penumbra/Util/PenumbraSqPackStream.cs | 4 ++++ 7 files changed, 25 insertions(+), 9 deletions(-) diff --git a/OtterGui b/OtterGui index c466bd33..934e991f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c466bd33442dda3ade26f05c9e8d694443564118 +Subproject commit 934e991f9a39c7d864501532003b9548ef73f896 diff --git a/Penumbra.GameData b/Penumbra.GameData index ac0710e9..54b56ada 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ac0710e9a116bec8633f3dcde2c9b6e38dffaaa9 +Subproject commit 54b56ada57529221d3fc812193ffe65c424c1521 diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 3da009a3..0814da90 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -325,6 +325,7 @@ public class ActiveCollections : ISavable, IDisposable /// private void LoadCollections() { + Penumbra.Log.Debug("[Collections] Reading collection assignments..."); var configChanged = !Load(_saveService.FileNames, out var jObject); // Load the default collection. If the string does not exist take the Default name if no file existed or the Empty name if one existed. @@ -389,6 +390,8 @@ public class ActiveCollections : ISavable, IDisposable } } + Penumbra.Log.Debug("[Collections] Loaded non-individual collection assignments."); + configChanged |= ActiveCollectionMigration.MigrateIndividualCollections(_storage, Individuals, jObject); configChanged |= Individuals.ReadJObject(_saveService, this, jObject[nameof(Individuals)] as JArray, _storage); diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 70b2cd13..7c94d705 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -176,6 +176,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable /// private void ReadCollections(out ModCollection defaultNamedCollection) { + Penumbra.Log.Debug("[Collections] Reading saved collections..."); foreach (var file in _saveService.FileNames.CollectionFiles) { if (!ModCollectionSave.LoadFromFile(file, out var name, out var version, out var settings, out var inheritance)) @@ -202,6 +203,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable } defaultNamedCollection = SetDefaultNamedCollection(); + Penumbra.Log.Debug($"[Collections] Found {Count} saved collections."); } /// diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index fa6019c6..45a1d98c 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -27,7 +27,10 @@ public partial class IndividualCollections public bool ReadJObject(SaveService saver, ActiveCollections parent, JArray? obj, CollectionStorage storage) { if (_actorService.Valid) - return ReadJObjectInternal(obj, storage); + { + var ret = ReadJObjectInternal(obj, storage); + return ret; + } void Func() { @@ -38,14 +41,19 @@ public partial class IndividualCollections _actorService.FinishedCreation -= Func; } + Penumbra.Log.Debug("[Collections] Delayed reading individual assignments until actor service is ready..."); _actorService.FinishedCreation += Func; return false; } private bool ReadJObjectInternal(JArray? obj, CollectionStorage storage) { + Penumbra.Log.Debug("[Collections] Reading individual assignments..."); if (obj == null) + { + Penumbra.Log.Debug($"[Collections] Finished reading {Count} individual assignments..."); return true; + } var changes = false; foreach (var data in obj) @@ -58,7 +66,7 @@ public partial class IndividualCollections { changes = true; Penumbra.Messager.NotificationMessage("Could not load an unknown individual collection, removed.", - NotificationType.Warning); + NotificationType.Error); continue; } @@ -86,6 +94,8 @@ public partial class IndividualCollections } } + Penumbra.Log.Debug($"Finished reading {Count} individual assignments..."); + return changes; } diff --git a/Penumbra/Import/Structs/StreamDisposer.cs b/Penumbra/Import/Structs/StreamDisposer.cs index 84719331..c38362ce 100644 --- a/Penumbra/Import/Structs/StreamDisposer.cs +++ b/Penumbra/Import/Structs/StreamDisposer.cs @@ -3,7 +3,7 @@ using Penumbra.Util; namespace Penumbra.Import.Structs; // Create an automatically disposing SqPack stream. -public class StreamDisposer : PenumbraSqPackStream, IDisposable +public class StreamDisposer : PenumbraSqPackStream { private readonly FileStream _fileStream; @@ -11,13 +11,10 @@ public class StreamDisposer : PenumbraSqPackStream, IDisposable : base(stream) => _fileStream = stream; - public new void Dispose() + protected override void Dispose(bool _) { var filePath = _fileStream.Name; - - base.Dispose(); _fileStream.Dispose(); - File.Delete(filePath); } } diff --git a/Penumbra/Util/PenumbraSqPackStream.cs b/Penumbra/Util/PenumbraSqPackStream.cs index 562eca91..392730e2 100644 --- a/Penumbra/Util/PenumbraSqPackStream.cs +++ b/Penumbra/Util/PenumbraSqPackStream.cs @@ -327,8 +327,12 @@ public class PenumbraSqPackStream : IDisposable public void Dispose() { Reader.Dispose(); + Dispose(true); } + protected virtual void Dispose(bool _) + { } + public class PenumbraFileInfo { public uint HeaderSize; From 369992393802f8c42361d77e16f10d1e4e128ca4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 8 Oct 2023 15:03:24 +0200 Subject: [PATCH 0164/1381] Improve save logging. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 934e991f..a9dac59d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 934e991f9a39c7d864501532003b9548ef73f896 +Subproject commit a9dac59d36e25064ebd9cd17d519bfac91acc17e From 764ef76e1a9b80d362f8f2237c81422e54cc7170 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 8 Oct 2023 13:08:02 +0000 Subject: [PATCH 0165/1381] [CI] Updating repo.json for 0.8.1.3 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index af898a90..763f39ae 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.2", - "TestingAssemblyVersion": "0.8.1.2", + "AssemblyVersion": "0.8.1.3", + "TestingAssemblyVersion": "0.8.1.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.3/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 4bdc8f126d107da097c2f88e2badd3e23148cb3b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 9 Oct 2023 00:10:38 +0200 Subject: [PATCH 0166/1381] Make ActorData great again. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 54b56ada..8a343f78 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 54b56ada57529221d3fc812193ffe65c424c1521 +Subproject commit 8a343f78abc4ecb7485489cd13a313980227b47e From f5822cf2c8e5ebdfa62f0b4a8785f9d52498f379 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 9 Oct 2023 22:18:33 +0000 Subject: [PATCH 0167/1381] [CI] Updating repo.json for 0.8.1.4 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 763f39ae..14ee0e6c 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.3", - "TestingAssemblyVersion": "0.8.1.3", + "AssemblyVersion": "0.8.1.4", + "TestingAssemblyVersion": "0.8.1.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.3/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.4/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.4/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From c24a40fd9f67f0fceda9e64202ed0f0218c30166 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 10 Oct 2023 18:01:55 +0200 Subject: [PATCH 0168/1381] Add support for middle-clicking mods. --- OtterGui | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 35 ++++++++++++++++---- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/OtterGui b/OtterGui index a9dac59d..791a9c98 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit a9dac59d36e25064ebd9cd17d519bfac91acc17e +Subproject commit 791a9c98aa5a533f754f4e1085d1ae6f890717ac diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index cc4ceb55..bff021bc 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -1,4 +1,3 @@ -using Dalamud.Game.ClientState.Keys; using Dalamud.Interface; using Dalamud.Interface.DragDrop; using Dalamud.Interface.Internal.Notifications; @@ -25,7 +24,7 @@ namespace Penumbra.UI.ModsTab; public sealed class ModFileSystemSelector : FileSystemSelector { private readonly CommunicatorService _communicator; - private readonly MessageService _messager; + private readonly MessageService _messager; private readonly Configuration _config; private readonly FileDialogService _fileDialog; private readonly ModManager _modManager; @@ -37,7 +36,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector + ImGuiUtil.HelpPopup("ExtendedHelp", new Vector2(1000 * UiHelpers.Scale, 38.5f * ImGui.GetTextLineHeightWithSpacing()), () => { ImGui.Dummy(Vector2.UnitY * ImGui.GetTextLineHeight()); ImGui.TextUnformatted("Mod Management"); @@ -363,6 +381,11 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Tue, 10 Oct 2023 21:48:01 +0200 Subject: [PATCH 0169/1381] Disable window sounds in ImportPopup --- Penumbra/UI/ImportPopup.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/ImportPopup.cs b/Penumbra/UI/ImportPopup.cs index 228cf4e1..71164d1d 100644 --- a/Penumbra/UI/ImportPopup.cs +++ b/Penumbra/UI/ImportPopup.cs @@ -29,10 +29,11 @@ public sealed class ImportPopup : Window | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar, true) { - _modImportManager = modImportManager; - IsOpen = true; - RespectCloseHotkey = false; - Collapsed = false; + _modImportManager = modImportManager; + DisableWindowSounds = true; + IsOpen = true; + RespectCloseHotkey = false; + Collapsed = false; SizeConstraints = new WindowSizeConstraints { MinimumSize = Vector2.Zero, From 5d2fc72883f0c0c8b6db889106a01774ee895766 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 16 Oct 2023 15:06:31 +0200 Subject: [PATCH 0170/1381] Update submodules. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 791a9c98..a4f9b285 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 791a9c98aa5a533f754f4e1085d1ae6f890717ac +Subproject commit a4f9b285c82f84ff0841695c0787dbba93afc59b diff --git a/Penumbra.GameData b/Penumbra.GameData index 8a343f78..6a0daf2f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 8a343f78abc4ecb7485489cd13a313980227b47e +Subproject commit 6a0daf2f309c27c5a260825bce31094987fce3d1 From 5e79a137083253c1cf183f783a494de3a57653b2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 16 Oct 2023 15:10:41 +0200 Subject: [PATCH 0171/1381] Expand tooltip for Wait for Plugins on Startup. --- Penumbra/UI/Tabs/SettingsTab.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 32bd6b8f..ae3a939c 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -830,7 +830,8 @@ public class SettingsTab : ITab } else { - Checkbox("Wait for Plugins on Startup", "This changes a setting in the Dalamud Configuration found at /xlsettings -> General.", + Checkbox("Wait for Plugins on Startup", + "Some mods need to change files that are loaded once when the game starts and never afterwards.\nThis can cause issues with Penumbra loading after the files are already loaded.\nThis setting causes the game to wait until certain plugins have finished loading, making those mods work (in the base collection).\n\nThis changes a setting in the Dalamud Configuration found at /xlsettings -> General.", value, v => _dalamud.SetDalamudConfig(DalamudServices.WaitingForPluginsOption, v, "doWaitForPluginsOnStartup")); } From 23f46438a202b0d16427cdcb34c89c4fd20a72ea Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 16 Oct 2023 13:13:05 +0000 Subject: [PATCH 0172/1381] [CI] Updating repo.json for 0.8.1.5 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 14ee0e6c..2a299ae3 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.4", - "TestingAssemblyVersion": "0.8.1.4", + "AssemblyVersion": "0.8.1.5", + "TestingAssemblyVersion": "0.8.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.4/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.4/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.4/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.5/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.5/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From f2ef0e15d3fdce68c6f2dec0418fb45ad6ad06ed Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 17 Oct 2023 19:42:46 +0200 Subject: [PATCH 0173/1381] Draw associated BNPCs in debug tab. --- Penumbra.GameData | 2 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 208 ++++++++++++++++---- 2 files changed, 168 insertions(+), 42 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 6a0daf2f..4a639dbe 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 6a0daf2f309c27c5a260825bce31094987fce3d1 +Subproject commit 4a639dbeebc3cbbaf8518b7626892855689f7440 diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 7fd0ae77..926ba77b 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -1,6 +1,10 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility; using ImGuiNET; +using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; +using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.Meta.Manipulations; using Penumbra.Mods; @@ -20,60 +24,182 @@ public class ModPanelConflictsTab : ITab _selector = selector; } + private int? _currentPriority = null; + public ReadOnlySpan Label => "Conflicts"u8; public bool IsVisible => _collectionManager.Active.Current.Conflicts(_selector.Selected!).Count > 0; + private readonly ConditionalWeakTable _expandedMods = new(); + + private int GetPriority(ModConflicts conflicts) + { + if (conflicts.Mod2.Index < 0) + return conflicts.Mod2.Priority; + + return _collectionManager.Active.Current[conflicts.Mod2.Index].Settings?.Priority ?? 0; + } + public void DrawContent() { - using var box = ImRaii.ListBox("##conflicts", -Vector2.One); - if (!box) + using var table = ImRaii.Table("conflicts", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, ImGui.GetContentRegionAvail()); + if (!table) return; + var buttonSize = new Vector2(ImGui.GetFrameHeight()); + var spacing = ImGui.GetStyle().ItemInnerSpacing with { Y = ImGui.GetStyle().ItemSpacing.Y }; + var priorityRowWidth = ImGui.CalcTextSize("Priority").X + 20 * ImGuiHelpers.GlobalScale + 2 * buttonSize.X; + var priorityWidth = priorityRowWidth - 2 * (buttonSize.X + spacing.X); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, spacing); + ImGui.TableSetupColumn("Conflicting Mod", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Priority", ImGuiTableColumnFlags.WidthFixed, priorityRowWidth); + ImGui.TableSetupColumn("Files", ImGuiTableColumnFlags.WidthFixed, ImGui.CalcTextSize("Files").X + spacing.X); + + ImGui.TableSetupScrollFreeze(2, 2); + ImGui.TableHeadersRow(); + DrawCurrentRow(priorityWidth); + // Can not be null because otherwise the tab bar is never drawn. var mod = _selector.Selected!; - foreach (var conflict in _collectionManager.Active.Current.Conflicts(mod)) + foreach (var (conflict, index) in _collectionManager.Active.Current.Conflicts(mod).OrderByDescending(GetPriority) + .ThenBy(c => c.Mod2.Name.Lower).WithIndex()) { - if (ImGui.Selectable(conflict.Mod2.Name) && conflict.Mod2 is Mod otherMod) - _selector.SelectByValue(otherMod); - var hovered = ImGui.IsItemHovered(); - var rightClicked = ImGui.IsItemClicked(ImGuiMouseButton.Right); - - ImGui.SameLine(); - using (var color = ImRaii.PushColor(ImGuiCol.Text, - conflict.HasPriority ? ColorId.HandledConflictMod.Value() : ColorId.ConflictingMod.Value())) - { - var priority = conflict.Mod2.Index < 0 - ? conflict.Mod2.Priority - : _collectionManager.Active.Current[conflict.Mod2.Index].Settings!.Priority; - ImGui.TextUnformatted($"(Priority {priority})"); - hovered |= ImGui.IsItemHovered(); - rightClicked |= ImGui.IsItemClicked(ImGuiMouseButton.Right); - } - - if (conflict.Mod2 is Mod otherMod2) - { - if (hovered) - ImGui.SetTooltip("Click to jump to mod, Control + Right-Click to disable mod."); - if (rightClicked && ImGui.GetIO().KeyCtrl) - _collectionManager.Editor.SetModState(_collectionManager.Active.Current, otherMod2, false); - } - - using var indent = ImRaii.PushIndent(30f); - foreach (var data in conflict.Conflicts) - { - unsafe - { - var _ = data switch - { - Utf8GamePath p => ImGuiNative.igSelectable_Bool(p.Path.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) > 0, - MetaManipulation m => ImGui.Selectable(m.Manipulation?.ToString() ?? string.Empty), - _ => false, - }; - } - } + using var id = ImRaii.PushId(index); + DrawConflictRow(conflict, priorityWidth, buttonSize); } } + + private void DrawCurrentRow(float priorityWidth) + { + ImGui.TableNextColumn(); + using var c = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderLine.Value()); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(_selector.Selected!.Name); + ImGui.TableNextColumn(); + var priority = _collectionManager.Active.Current[_selector.Selected!.Index].Settings!.Priority; + ImGui.SetNextItemWidth(priorityWidth); + if (ImGui.InputInt("##priority", ref priority, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue)) + _currentPriority = priority; + + if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) + { + if (_currentPriority != _collectionManager.Active.Current[_selector.Selected!.Index].Settings!.Priority) + _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, (Mod)_selector.Selected!, + _currentPriority.Value); + + _currentPriority = null; + } + else if (ImGui.IsItemDeactivated()) + { + _currentPriority = null; + } + + ImGui.TableNextColumn(); + } + + private void DrawConflictSelectable(ModConflicts conflict) + { + ImGui.AlignTextToFramePadding(); + if (ImGui.Selectable(conflict.Mod2.Name) && conflict.Mod2 is Mod otherMod) + _selector.SelectByValue(otherMod); + var hovered = ImGui.IsItemHovered(); + var rightClicked = ImGui.IsItemClicked(ImGuiMouseButton.Right); + if (conflict.Mod2 is Mod otherMod2) + { + if (hovered) + ImGui.SetTooltip("Click to jump to mod, Control + Right-Click to disable mod."); + if (rightClicked && ImGui.GetIO().KeyCtrl) + _collectionManager.Editor.SetModState(_collectionManager.Active.Current, otherMod2, false); + } + } + + private bool DrawExpandedFiles(ModConflicts conflict) + { + if (!_expandedMods.TryGetValue(conflict.Mod2, out _)) + return false; + + using var indent = ImRaii.PushIndent(30f); + foreach (var data in conflict.Conflicts) + { + unsafe + { + var _ = data switch + { + Utf8GamePath p => ImGuiNative.igSelectable_Bool(p.Path.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) > 0, + MetaManipulation m => ImGui.Selectable(m.Manipulation?.ToString() ?? string.Empty), + _ => false, + }; + } + } + + return true; + } + + private void DrawConflictRow(ModConflicts conflict, float priorityWidth, Vector2 buttonSize) + { + ImGui.TableNextColumn(); + DrawConflictSelectable(conflict); + var expanded = DrawExpandedFiles(conflict); + ImGui.TableNextColumn(); + var conflictPriority = DrawPriorityInput(conflict, priorityWidth); + ImGui.SameLine(); + var selectedPriority = _collectionManager.Active.Current[_selector.Selected!.Index].Settings!.Priority; + DrawPriorityButtons(conflict.Mod2 as Mod, conflictPriority, selectedPriority, buttonSize); + ImGui.TableNextColumn(); + DrawExpandButton(conflict.Mod2, expanded, buttonSize); + } + + private void DrawExpandButton(IMod mod, bool expanded, Vector2 buttonSize) + { + var (icon, tt) = expanded + ? (FontAwesomeIcon.CaretUp.ToIconString(), "Hide the conflicting files for this mod.") + : (FontAwesomeIcon.CaretDown.ToIconString(), "Show the conflicting files for this mod."); + if (ImGuiUtil.DrawDisabledButton(icon, buttonSize, tt, false, true)) + { + if (expanded) + _expandedMods.Remove(mod); + else + _expandedMods.Add(mod, new object()); + } + } + + private int DrawPriorityInput(ModConflicts conflict, float priorityWidth) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, + conflict.HasPriority ? ColorId.HandledConflictMod.Value() : ColorId.ConflictingMod.Value()); + using var disabled = ImRaii.Disabled(conflict.Mod2.Index < 0); + var priority = _currentPriority ?? GetPriority(conflict); + + ImGui.SetNextItemWidth(priorityWidth); + if (ImGui.InputInt("##priority", ref priority, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue)) + _currentPriority = priority; + + if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) + { + if (_currentPriority != GetPriority(conflict)) + _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, (Mod)conflict.Mod2, _currentPriority.Value); + + _currentPriority = null; + } + else if (ImGui.IsItemDeactivated()) + { + _currentPriority = null; + } + + return priority; + } + + private void DrawPriorityButtons(Mod? conflict, int conflictPriority, int selectedPriority, Vector2 buttonSize) + { + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.SortNumericUpAlt.ToIconString(), buttonSize, + $"Set the priority of the currently selected mod to this mods priority plus one. ({selectedPriority} -> {conflictPriority + 1})", selectedPriority > conflictPriority, true)) + _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, _selector.Selected!, conflictPriority + 1); + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.SortNumericDownAlt.ToIconString(), buttonSize, + $"Set the priority of this mod to the currently selected mods priority minus one. ({conflictPriority} -> {selectedPriority - 1})", + selectedPriority > conflictPriority || conflict == null, true)) + _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, conflict!, selectedPriority - 1); + } } From f910dcf1e0c90b6eb330166416e1fcb3e353ea85 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 22 Oct 2023 15:36:47 +0200 Subject: [PATCH 0174/1381] Add ReverseResolvePlayerPathsAsync. --- Penumbra.Api | 2 +- Penumbra/Api/IpcTester.cs | 110 +++++++++++------- Penumbra/Api/PenumbraApi.cs | 24 ++++ Penumbra/Api/PenumbraIpcProviders.cs | 34 +++--- Penumbra/Collections/Cache/CollectionCache.cs | 6 +- .../Collections/ModCollection.Cache.Access.cs | 2 +- 6 files changed, 115 insertions(+), 63 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 839cc8f2..eb9e6d65 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 839cc8f270abb6a938d71596bef05b4a9b3ab0ea +Subproject commit eb9e6d65d51db9c8ed11d74332f8390d5d813727 diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index dd800f0a..675a61a3 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -16,6 +16,7 @@ using Penumbra.Services; using Penumbra.UI; using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; +using ImGuiScene; using Penumbra.GameData.Structs; namespace Penumbra.Api; @@ -566,10 +567,11 @@ public class IpcTester : IDisposable { private readonly DalamudPluginInterface _pi; - private string _currentResolvePath = string.Empty; - private string _currentResolveCharacter = string.Empty; - private string _currentReversePath = string.Empty; - private int _currentReverseIdx = 0; + private string _currentResolvePath = string.Empty; + private string _currentResolveCharacter = string.Empty; + private string _currentReversePath = string.Empty; + private int _currentReverseIdx = 0; + private Task<(string[], string[][])> _task = Task.FromException<(string[], string[][])>(new Exception()); public Resolve(DalamudPluginInterface pi) => _pi = pi; @@ -645,37 +647,55 @@ public class IpcTester : IDisposable } } - DrawIntro(Ipc.ResolvePlayerPaths.Label, "Resolved Paths (Player)"); - if (_currentResolvePath.Length > 0 || _currentReversePath.Length > 0) - { - var forwardArray = _currentResolvePath.Length > 0 - ? new[] - { - _currentResolvePath, - } - : Array.Empty(); - var reverseArray = _currentReversePath.Length > 0 - ? new[] - { - _currentReversePath, - } - : Array.Empty(); - var ret = Ipc.ResolvePlayerPaths.Subscriber(_pi).Invoke(forwardArray, reverseArray); - var text = string.Empty; - if (ret.Item1.Length > 0) + var forwardArray = _currentResolvePath.Length > 0 + ? new[] { - if (ret.Item2.Length > 0) - text = $"Forward: {ret.Item1[0]} | Reverse: {string.Join("; ", ret.Item2[0])}."; - else - text = $"Forward: {ret.Item1[0]}."; + _currentResolvePath, } - else if (ret.Item2.Length > 0) + : Array.Empty(); + var reverseArray = _currentReversePath.Length > 0 + ? new[] { - text = $"Reverse: {string.Join("; ", ret.Item2[0])}."; + _currentReversePath, + } + : Array.Empty(); + + string ConvertText((string[], string[][]) data) + { + var text = string.Empty; + if (data.Item1.Length > 0) + { + if (data.Item2.Length > 0) + text = $"Forward: {data.Item1[0]} | Reverse: {string.Join("; ", data.Item2[0])}."; + else + text = $"Forward: {data.Item1[0]}."; + } + else if (data.Item2.Length > 0) + { + text = $"Reverse: {string.Join("; ", data.Item2[0])}."; } - ImGui.TextUnformatted(text); + return text; } + + ; + + DrawIntro(Ipc.ResolvePlayerPaths.Label, "Resolved Paths (Player)"); + if (forwardArray.Length > 0 || reverseArray.Length > 0) + { + var ret = Ipc.ResolvePlayerPaths.Subscriber(_pi).Invoke(forwardArray, reverseArray); + ImGui.TextUnformatted(ConvertText(ret)); + } + + DrawIntro(Ipc.ResolvePlayerPathsAsync.Label, "Resolved Paths Async (Player)"); + if (ImGui.Button("Start")) + _task = Ipc.ResolvePlayerPathsAsync.Subscriber(_pi).Invoke(forwardArray, reverseArray); + var hovered = ImGui.IsItemHovered(); + ImGui.SameLine(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(_task.Status.ToString()); + if ((hovered || ImGui.IsItemHovered()) && _task.IsCompletedSuccessfully) + ImGui.SetTooltip(ConvertText(_task.Result)); } } @@ -1442,12 +1462,12 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetGameObjectResourcePaths.Label, "Get GameObject resource paths"); if (ImGui.Button("Get##GameObjectResourcePaths")) { - var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourcePaths.Subscriber(_pi); + var gameObjects = GetSelectedGameObjects(); + var subscriber = Ipc.GetGameObjectResourcePaths.Subscriber(_pi); _stopwatch.Restart(); var resourcePaths = subscriber.Invoke(gameObjects); - _lastCallDuration = _stopwatch.Elapsed; + _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcePaths = gameObjects .Select(i => GameObjectToString(i)) .Zip(resourcePaths) @@ -1459,11 +1479,11 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcePaths.Label, "Get local player resource paths"); if (ImGui.Button("Get##PlayerResourcePaths")) { - var subscriber = Ipc.GetPlayerResourcePaths.Subscriber(_pi); + var subscriber = Ipc.GetPlayerResourcePaths.Subscriber(_pi); _stopwatch.Restart(); var resourcePaths = subscriber.Invoke(); - _lastCallDuration = _stopwatch.Elapsed; + _lastCallDuration = _stopwatch.Elapsed; _lastPlayerResourcePaths = resourcePaths .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) .ToArray(); @@ -1474,12 +1494,12 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetGameObjectResourcesOfType.Label, "Get GameObject resources of type"); if (ImGui.Button("Get##GameObjectResourcesOfType")) { - var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi); + var gameObjects = GetSelectedGameObjects(); + var subscriber = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi); _stopwatch.Restart(); var resourcesOfType = subscriber.Invoke(_type, _withUIData, gameObjects); - _lastCallDuration = _stopwatch.Elapsed; + _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcesOfType = gameObjects .Select(i => GameObjectToString(i)) .Zip(resourcesOfType) @@ -1491,11 +1511,11 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcesOfType.Label, "Get local player resources of type"); if (ImGui.Button("Get##PlayerResourcesOfType")) { - var subscriber = Ipc.GetPlayerResourcesOfType.Subscriber(_pi); + var subscriber = Ipc.GetPlayerResourcesOfType.Subscriber(_pi); _stopwatch.Restart(); var resourcesOfType = subscriber.Invoke(_type, _withUIData); - _lastCallDuration = _stopwatch.Elapsed; + _lastCallDuration = _stopwatch.Elapsed; _lastPlayerResourcesOfType = resourcesOfType .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) .ToArray(); @@ -1504,10 +1524,10 @@ public class IpcTester : IDisposable } DrawPopup(nameof(Ipc.GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths, _lastCallDuration); - DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths, _lastCallDuration); + DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths, _lastCallDuration); DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType, _lastCallDuration); - DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, _lastCallDuration); + DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, _lastCallDuration); } private static void DrawPopup(string popupId, ref T? result, Action drawResult, TimeSpan duration) where T : class @@ -1573,7 +1593,7 @@ public class IpcTester : IDisposable return; ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.6f); - ImGui.TableSetupColumn("Game Paths", ImGuiTableColumnFlags.WidthStretch, 0.4f); + ImGui.TableSetupColumn("Game Paths", ImGuiTableColumnFlags.WidthStretch, 0.4f); ImGui.TableHeadersRow(); foreach (var (actualPath, gamePaths) in paths) @@ -1596,7 +1616,7 @@ public class IpcTester : IDisposable return; ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.15f); - ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUIData ? 0.55f : 0.85f); + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUIData ? 0.55f : 0.85f); if (_withUIData) ImGui.TableSetupColumn("Icon & Name", ImGuiTableColumnFlags.WidthStretch, 0.3f); ImGui.TableHeadersRow(); @@ -1626,8 +1646,8 @@ public class IpcTester : IDisposable private ushort[] GetSelectedGameObjects() => _gameObjectIndices.Split(',') - .SelectWhere(index => (ushort.TryParse(index.Trim(), out var i), i)) - .ToArray(); + .SelectWhere(index => (ushort.TryParse(index.Trim(), out var i), i)) + .ToArray(); private unsafe string GameObjectToString(ObjectIndex gameObjectIndex) { diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 10b5b6bd..0ae4fcca 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -388,6 +388,30 @@ public class PenumbraApi : IDisposable, IPenumbraApi return (resolved, reverseResolved.Select(a => a.Select(p => p.ToString()).ToArray()).ToArray()); } + public async Task<(string[], string[][])> ResolvePlayerPathsAsync(string[] forward, string[] reverse) + { + CheckInitialized(); + if (!_config.EnableMods) + return (forward, reverse.Select(p => new[] + { + p, + }).ToArray()); + + return await Task.Run(async () => + { + var playerCollection = await _dalamud.Framework.RunOnFrameworkThread(_collectionResolver.PlayerCollection).ConfigureAwait(false); + var forwardTask = Task.Run(() => + { + var forwardRet = new string[forward.Length]; + Parallel.For(0, forward.Length, idx => forwardRet[idx] = ResolvePath(forward[idx], _modManager, playerCollection)); + return forwardRet; + }).ConfigureAwait(false); + var reverseTask = Task.Run(() => playerCollection.ReverseResolvePaths(reverse)).ConfigureAwait(false); + var reverseResolved = (await reverseTask).Select(a => a.Select(p => p.ToString()).ToArray()).ToArray(); + return (await forwardTask, reverseResolved); + }); + } + public T? GetFile(string gamePath) where T : FileResource => GetFileIntern(ResolveDefaultPath(gamePath)); diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 87de6a0c..b72073fb 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -53,15 +53,16 @@ public class PenumbraIpcProviders : IDisposable internal readonly EventProvider GameObjectResourcePathResolved; // Resolve - internal readonly FuncProvider ResolveDefaultPath; - internal readonly FuncProvider ResolveInterfacePath; - internal readonly FuncProvider ResolvePlayerPath; - internal readonly FuncProvider ResolveGameObjectPath; - internal readonly FuncProvider ResolveCharacterPath; - internal readonly FuncProvider ReverseResolvePath; - internal readonly FuncProvider ReverseResolveGameObjectPath; - internal readonly FuncProvider ReverseResolvePlayerPath; - internal readonly FuncProvider ResolvePlayerPaths; + internal readonly FuncProvider ResolveDefaultPath; + internal readonly FuncProvider ResolveInterfacePath; + internal readonly FuncProvider ResolvePlayerPath; + internal readonly FuncProvider ResolveGameObjectPath; + internal readonly FuncProvider ResolveCharacterPath; + internal readonly FuncProvider ReverseResolvePath; + internal readonly FuncProvider ReverseResolveGameObjectPath; + internal readonly FuncProvider ReverseResolvePlayerPath; + internal readonly FuncProvider ResolvePlayerPaths; + internal readonly FuncProvider> ResolvePlayerPathsAsync; // Collections internal readonly FuncProvider> GetCollections; @@ -119,10 +120,15 @@ public class PenumbraIpcProviders : IDisposable internal readonly FuncProvider RemoveTemporaryMod; // Resource Tree - internal readonly FuncProvider?[]> GetGameObjectResourcePaths; - internal readonly FuncProvider>> GetPlayerResourcePaths; - internal readonly FuncProvider?[]> GetGameObjectResourcesOfType; - internal readonly FuncProvider>> GetPlayerResourcesOfType; + internal readonly FuncProvider?[]> GetGameObjectResourcePaths; + internal readonly FuncProvider>> GetPlayerResourcePaths; + + internal readonly FuncProvider?[]> + GetGameObjectResourcesOfType; + + internal readonly + FuncProvider>> + GetPlayerResourcesOfType; public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) @@ -184,6 +190,7 @@ public class PenumbraIpcProviders : IDisposable ReverseResolveGameObjectPath = Ipc.ReverseResolveGameObjectPath.Provider(pi, Api.ReverseResolveGameObjectPath); ReverseResolvePlayerPath = Ipc.ReverseResolvePlayerPath.Provider(pi, Api.ReverseResolvePlayerPath); ResolvePlayerPaths = Ipc.ResolvePlayerPaths.Provider(pi, Api.ResolvePlayerPaths); + ResolvePlayerPathsAsync = Ipc.ResolvePlayerPathsAsync.Provider(pi, Api.ResolvePlayerPathsAsync); // Collections GetCollections = Ipc.GetCollections.Provider(pi, Api.GetCollections); @@ -301,6 +308,7 @@ public class PenumbraIpcProviders : IDisposable ReverseResolveGameObjectPath.Dispose(); ReverseResolvePlayerPath.Dispose(); ResolvePlayerPaths.Dispose(); + ResolvePlayerPathsAsync.Dispose(); // Collections GetCollections.Dispose(); diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 80539d96..3761424a 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -23,7 +23,7 @@ public class CollectionCache : IDisposable private readonly ModCollection _collection; public readonly CollectionModData ModData = new(); public readonly SortedList, object?)> _changedItems = new(); - public readonly Dictionary ResolvedFiles = new(); + public readonly ConcurrentDictionary ResolvedFiles = new(); public readonly MetaCache Meta; public readonly Dictionary> _conflicts = new(); @@ -146,7 +146,7 @@ public class CollectionCache : IDisposable ModData.RemovePath(modPath.Mod, path); if (fullPath.FullName.Length > 0) { - ResolvedFiles.Add(path, new ModPath(Mod.ForcedFiles, fullPath)); + ResolvedFiles.TryAdd(path, new ModPath(Mod.ForcedFiles, fullPath)); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, fullPath, modPath.Path, Mod.ForcedFiles); } @@ -157,7 +157,7 @@ public class CollectionCache : IDisposable } else if (fullPath.FullName.Length > 0) { - ResolvedFiles.Add(path, new ModPath(Mod.ForcedFiles, fullPath)); + ResolvedFiles.TryAdd(path, new ModPath(Mod.ForcedFiles, fullPath)); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, fullPath, FullPath.Empty, Mod.ForcedFiles); } } diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 36e0fd98..a695c463 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -56,7 +56,7 @@ public partial class ModCollection } internal IReadOnlyDictionary ResolvedFiles - => _cache?.ResolvedFiles ?? new Dictionary(); + => _cache?.ResolvedFiles ?? new ConcurrentDictionary(); internal IReadOnlyDictionary, object?)> ChangedItems => _cache?.ChangedItems ?? new Dictionary, object?)>(); From 25e9a99799b956ee2be6bd2c886c0167ab3262a0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 22 Oct 2023 15:37:34 +0200 Subject: [PATCH 0175/1381] Fix portraits not respecting card settings. --- .../Collections/Manager/IndividualCollections.Access.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index 680f8b32..78eff98c 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -90,13 +90,13 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa return (identifier, SpecialResult.Invalid); if (_actorService.AwaitedService.ResolvePartyBannerPlayer(identifier.Special, out var id)) - return (id, SpecialResult.PartyBanner); + return _config.UseCharacterCollectionsInCards ? (id, SpecialResult.PartyBanner) : (identifier, SpecialResult.Invalid); if (_actorService.AwaitedService.ResolvePvPBannerPlayer(identifier.Special, out id)) - return (id, SpecialResult.PvPBanner); + return _config.UseCharacterCollectionsInCards ? (id, SpecialResult.PvPBanner) : (identifier, SpecialResult.Invalid); if (_actorService.AwaitedService.ResolveMahjongPlayer(identifier.Special, out id)) - return (id, SpecialResult.Mahjong); + return _config.UseCharacterCollectionsInCards ? (id, SpecialResult.Mahjong) : (identifier, SpecialResult.Invalid); switch (identifier.Special) { From 2cb92d817adc2e55143c401cecce1fc406bf2ce0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 22 Oct 2023 15:37:52 +0200 Subject: [PATCH 0176/1381] Fix directory rename not updating paths in advanced window. --- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 0f171e21..7171a0e2 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -598,7 +598,7 @@ public partial class ModEditWindow : Window, IDisposable private void OnModPathChanged(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) { - if (type is ModPathChangeType.Reloaded) + if (type is ModPathChangeType.Reloaded or ModPathChangeType.Moved) ChangeMod(mod); } } From 8fd755c5e6da50610581a7f25310929f4b2c3afe Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 22 Oct 2023 13:40:09 +0000 Subject: [PATCH 0177/1381] [CI] Updating repo.json for 0.8.1.6 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 2a299ae3..d264be81 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.5", - "TestingAssemblyVersion": "0.8.1.5", + "AssemblyVersion": "0.8.1.6", + "TestingAssemblyVersion": "0.8.1.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.5/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.5/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.5/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.6/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From c76a9ace24cb5b71f51ca3e7b6809e2c0e688af3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 22 Oct 2023 15:40:30 +0200 Subject: [PATCH 0178/1381] Update API Nuget. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index eb9e6d65..f9069dfd 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit eb9e6d65d51db9c8ed11d74332f8390d5d813727 +Subproject commit f9069dfdf1f0a7011c3b0ea7c0be5330c42959dd From 06e06b81e9e095d91ba7f05a3909fa62bf7e7731 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 28 Oct 2023 01:13:18 +0200 Subject: [PATCH 0179/1381] Support correct handling of offhands in changed items. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Communication/ChangedItemClick.cs | 3 ++- Penumbra/UI/ChangedItemDrawer.cs | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index f9069dfd..80f9793e 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit f9069dfdf1f0a7011c3b0ea7c0be5330c42959dd +Subproject commit 80f9793ef2ddaa50246b7112fde4d9b2098d8823 diff --git a/Penumbra.GameData b/Penumbra.GameData index 4a639dbe..e1a62d8e 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 4a639dbeebc3cbbaf8518b7626892855689f7440 +Subproject commit e1a62d8e6b4e1d8c482253ad14850fd3dc372d86 diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index 1e5bc863..ea389bb6 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api.Enums; +using Penumbra.GameData.Enums; namespace Penumbra.Communication; @@ -7,7 +8,7 @@ namespace Penumbra.Communication; /// Triggered when a Changed Item in Penumbra is clicked. /// /// Parameter is the clicked mouse button. -/// Parameter is the clicked object data if any.. +/// Parameter is the clicked object data if any. /// /// public sealed class ChangedItemClick : EventWrapper, ChangedItemClick.Priority> diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 324c354a..3c74aa20 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -285,7 +285,7 @@ public class ChangedItemDrawer : IDisposable private object? Convert(object? data) { if (data is EquipItem it) - return _items.GetRow(it.ItemId.Id); + return (_items.GetRow(it.ItemId.Id), it.Type); return data; } From 8e63452e84cd5b6decb57368fe49e434ca5fc1fa Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 31 Oct 2023 11:32:40 +0100 Subject: [PATCH 0180/1381] Use some CS sigs. --- Penumbra.GameData | 2 +- Penumbra/Interop/Services/GameEventManager.cs | 18 +++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index e1a62d8e..04ddadb4 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e1a62d8e6b4e1d8c482253ad14850fd3dc372d86 +Subproject commit 04ddadb44600a382e26661e1db08fd16c3b671d8 diff --git a/Penumbra/Interop/Services/GameEventManager.cs b/Penumbra/Interop/Services/GameEventManager.cs index d11b7159..30319060 100644 --- a/Penumbra/Interop/Services/GameEventManager.cs +++ b/Penumbra/Interop/Services/GameEventManager.cs @@ -4,6 +4,7 @@ using Dalamud.Utility.Signatures; using Penumbra.GameData; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Interop.Structs; namespace Penumbra.Interop.Services; @@ -27,7 +28,13 @@ public unsafe class GameEventManager : IDisposable _copyCharacterHook = interop.HookFromAddress((nint)CharacterSetup.MemberFunctionPointers.CopyFromCharacter, CopyCharacterDetour); - + _characterBaseCreateHook = + interop.HookFromAddress((nint)CharacterBase.MemberFunctionPointers.Create, CharacterBaseCreateDetour); + _characterBaseDestructorHook = + interop.HookFromAddress((nint)CharacterBase.MemberFunctionPointers.Destroy, + CharacterBaseDestructorDetour); + _weaponReloadHook = + interop.HookFromAddress((nint)DrawDataContainer.MemberFunctionPointers.LoadWeapon, WeaponReloadDetour); _characterDtorHook.Enable(); _copyCharacterHook.Enable(); _resourceHandleDestructorHook.Enable(); @@ -148,8 +155,7 @@ public unsafe class GameEventManager : IDisposable private delegate nint CharacterBaseCreateDelegate(uint a, nint b, nint c, byte d); - [Signature(Sigs.CharacterBaseCreate, DetourName = nameof(CharacterBaseCreateDetour))] - private readonly Hook _characterBaseCreateHook = null!; + private readonly Hook _characterBaseCreateHook; private nint CharacterBaseCreateDetour(uint a, nint b, nint c, byte d) { @@ -194,8 +200,7 @@ public unsafe class GameEventManager : IDisposable public delegate void CharacterBaseDestructorEvent(nint drawBase); - [Signature(Sigs.CharacterBaseDestructor, DetourName = nameof(CharacterBaseDestructorDetour))] - private readonly Hook _characterBaseDestructorHook = null!; + private readonly Hook _characterBaseDestructorHook; private void CharacterBaseDestructorDetour(IntPtr drawBase) { @@ -222,8 +227,7 @@ public unsafe class GameEventManager : IDisposable private delegate void WeaponReloadFunc(nint a1, uint a2, nint a3, byte a4, byte a5, byte a6, byte a7); - [Signature(Sigs.WeaponReload, DetourName = nameof(WeaponReloadDetour))] - private readonly Hook _weaponReloadHook = null!; + private readonly Hook _weaponReloadHook; private void WeaponReloadDetour(nint a1, uint a2, nint a3, byte a4, byte a5, byte a6, byte a7) { From 6375faa7586e6adccbb289bfcc599501cd2b8be3 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 31 Oct 2023 11:23:59 +0000 Subject: [PATCH 0181/1381] [CI] Updating repo.json for 0.8.1.7 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index d264be81..bc8d02d7 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.6", - "TestingAssemblyVersion": "0.8.1.6", + "AssemblyVersion": "0.8.1.7", + "TestingAssemblyVersion": "0.8.1.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.6/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.6/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.7/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.7/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 00dc5f48b1c32da73f4d8d10c60e9a9c698ff7d0 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 27 Oct 2023 01:52:16 +0200 Subject: [PATCH 0182/1381] ClientStructs-ify a few things --- OtterGui | 2 +- .../LiveColorTablePreviewer.cs | 8 +-- .../MaterialPreview/LiveMaterialPreviewer.cs | 4 +- .../Interop/MaterialPreview/MaterialInfo.cs | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 47 +++++++------- Penumbra/Interop/ResourceTree/ResourceTree.cs | 21 ++++--- .../Interop/SafeHandles/SafeTextureHandle.cs | 5 +- Penumbra/Interop/Services/SkinFixer.cs | 13 ++-- Penumbra/Interop/Structs/CharacterBaseExt.cs | 14 ----- Penumbra/Interop/Structs/ConstantBuffer.cs | 28 --------- Penumbra/Interop/Structs/HumanExt.cs | 19 ------ Penumbra/Interop/Structs/Material.cs | 47 -------------- Penumbra/Interop/Structs/MtrlResource.cs | 45 ------------- Penumbra/Interop/Structs/RenderModel.cs | 3 + Penumbra/Interop/Structs/ResourceHandle.cs | 63 +++---------------- .../Interop/Structs/ShaderPackageUtility.cs | 17 ----- Penumbra/Interop/Structs/StructExtensions.cs | 24 +++++++ Penumbra/Interop/Structs/TextureUtility.cs | 31 --------- Penumbra/Penumbra.cs | 1 - Penumbra/Services/ServiceManager.cs | 3 +- Penumbra/UI/Tabs/DebugTab.cs | 4 +- Penumbra/UI/Tabs/ResourceTab.cs | 4 +- Penumbra/UI/UiHelpers.cs | 11 +++- 23 files changed, 102 insertions(+), 314 deletions(-) delete mode 100644 Penumbra/Interop/Structs/CharacterBaseExt.cs delete mode 100644 Penumbra/Interop/Structs/ConstantBuffer.cs delete mode 100644 Penumbra/Interop/Structs/HumanExt.cs delete mode 100644 Penumbra/Interop/Structs/Material.cs delete mode 100644 Penumbra/Interop/Structs/MtrlResource.cs delete mode 100644 Penumbra/Interop/Structs/ShaderPackageUtility.cs create mode 100644 Penumbra/Interop/Structs/StructExtensions.cs delete mode 100644 Penumbra/Interop/Structs/TextureUtility.cs diff --git a/OtterGui b/OtterGui index a4f9b285..6f17ef70 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit a4f9b285c82f84ff0841695c0787dbba93afc59b +Subproject commit 6f17ef70c41f3b31a401fdc9d6e37087e64f2035 diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index bacc72fa..0b7bafe0 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -31,7 +31,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (mtrlHandle == null) throw new InvalidOperationException("Material doesn't have a resource handle"); - var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorTableTextures; + var colorSetTextures = DrawObject->ColorTableTextures; if (colorSetTextures == null) throw new InvalidOperationException("Draw object doesn't have color table textures"); @@ -79,7 +79,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase textureSize[1] = TextureHeight; using var texture = - new SafeTextureHandle(Structs.TextureUtility.Create2D(Device.Instance(), textureSize, 1, 0x2460, 0x80000804, 7), false); + new SafeTextureHandle(Device.Instance()->CreateTexture2D(textureSize, 1, 0x2460, 0x80000804, 7), false); if (texture.IsInvalid) return; @@ -88,7 +88,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase { fixed (Half* colorTable = _colorTable) { - success = Structs.TextureUtility.InitializeContents(texture.Texture, colorTable); + success = texture.Texture->InitializeContents(colorTable); } } @@ -101,7 +101,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (!base.IsStillValid()) return false; - var colorSetTextures = ((Structs.CharacterBaseExt*)DrawObject)->ColorTableTextures; + var colorSetTextures = DrawObject->ColorTableTextures; if (colorSetTextures == null) return false; diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index fa03ac49..972d81be 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -18,7 +18,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (mtrlHandle == null) throw new InvalidOperationException("Material doesn't have a resource handle"); - var shpkHandle = ((Structs.MtrlResource*)mtrlHandle)->ShpkResourceHandle; + var shpkHandle = mtrlHandle->ShaderPackageResourceHandle; if (shpkHandle == null) throw new InvalidOperationException("Material doesn't have a ShPk resource handle"); @@ -61,7 +61,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (!CheckValidity()) return; - ((Structs.Material*)Material)->ShaderPackageFlags = shPkFlags; + Material->ShaderFlags = shPkFlags; } public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index c64e4d0b..ec0ddd29 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -93,7 +93,7 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy continue; var mtrlHandle = material->MaterialResourceHandle; - var path = ResolveContext.GetResourceHandlePath((Structs.ResourceHandle*)mtrlHandle); + var path = ResolveContext.GetResourceHandlePath(&mtrlHandle->ResourceHandle); if (path == needle) result.Add(new MaterialInfo(index, type, i, j)); } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 55893cab..5e3970cc 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -1,14 +1,15 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using FFXIVClientStructs.FFXIV.Client.System.Resource; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui; using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; +using static Penumbra.Interop.Structs.StructExtensions; namespace Penumbra.Interop.ResourceTree; @@ -36,7 +37,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (!Utf8GamePath.FromByteString(ByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path, false)) return null; - return CreateNodeFromGamePath(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->Handle, path, @internal); + return CreateNodeFromGamePath(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path, @internal); } private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool @internal, bool dx11) @@ -68,7 +69,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (!Utf8GamePath.FromByteString(gamePath, out var path)) return null; - return CreateNodeFromGamePath(ResourceType.Tex, (nint)resourceHandle->KernelTexture, &resourceHandle->Handle, path, @internal); + return CreateNodeFromGamePath(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path, @internal); } private unsafe ResourceNode CreateNodeFromGamePath(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, @@ -118,22 +119,22 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (Nodes.TryGetValue((nint)tex, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->KernelTexture, &tex->Handle, false); + var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, false); if (node != null) Nodes.Add((nint)tex, node); return node; } - public unsafe ResourceNode? CreateNodeFromRenderModel(RenderModel* mdl) + public unsafe ResourceNode? CreateNodeFromRenderModel(Model* mdl) { - if (mdl == null || mdl->ResourceHandle == null || mdl->ResourceHandle->Category != ResourceCategory.Chara) + if (mdl == null || mdl->ModelResourceHandle == null || mdl->ModelResourceHandle->ResourceHandle.Type.Category != ResourceHandleType.HandleCategory.Chara) return null; - if (Nodes.TryGetValue((nint)mdl->ResourceHandle, out var cached)) + if (Nodes.TryGetValue((nint)mdl->ModelResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint)mdl, mdl->ResourceHandle, false); + var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, false); if (node == null) return null; @@ -149,7 +150,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree } } - Nodes.Add((nint)mdl->ResourceHandle, node); + Nodes.Add((nint)mdl->ModelResourceHandle, node); return node; } @@ -169,27 +170,27 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree } static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle, HashSet alreadyVisitedSamplerIds) - => mtrl->TextureSpan.FindFirst(p => p.ResourceHandle == handle && !alreadyVisitedSamplerIds.Contains(p.Id), out var p) + => mtrl->TexturesSpan.FindFirst(p => p.Texture == handle && !alreadyVisitedSamplerIds.Contains(p.Id), out var p) ? p.Id : null; static uint? GetSamplerCrcById(ShaderPackage* shpk, uint id) - => new ReadOnlySpan(shpk->Samplers, shpk->SamplerCount).FindFirst(s => s.Id == id, out var s) - ? s.Crc + => shpk->SamplersSpan.FindFirst(s => s.Id == id, out var s) + ? s.CRC : null; if (mtrl == null) return null; - var resource = mtrl->ResourceHandle; + var resource = mtrl->MaterialResourceHandle; if (Nodes.TryGetValue((nint)resource, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint)mtrl, &resource->Handle, false); + var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, false); if (node == null) return null; - var shpkNode = CreateNodeFromShpk(resource->ShpkResourceHandle, new ByteString(resource->ShpkString), false); + var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName), false); if (shpkNode != null) { if (WithUiData) @@ -200,10 +201,10 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree var shpk = WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; var alreadyProcessedSamplerIds = new HashSet(); - for (var i = 0; i < resource->NumTex; i++) + for (var i = 0; i < resource->TextureCount; i++) { - var texNode = CreateNodeFromTex(resource->TexSpace[i].ResourceHandle, new ByteString(resource->TexString(i)), false, - resource->TexIsDX11(i)); + var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new ByteString(resource->TexturePath(i)), false, + resource->Textures[i].IsDX11); if (texNode == null) continue; @@ -212,12 +213,12 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree string? name = null; if (shpk != null) { - var index = GetTextureIndex(mtrl, resource->TexSpace[i].Flags, alreadyProcessedSamplerIds); + var index = GetTextureIndex(mtrl, resource->Textures[i].Flags, alreadyProcessedSamplerIds); uint? samplerId; if (index != 0x001F) samplerId = mtrl->Textures[index].Id; else - samplerId = GetTextureSamplerId(mtrl, resource->TexSpace[i].ResourceHandle, alreadyProcessedSamplerIds); + samplerId = GetTextureSamplerId(mtrl, resource->Textures[i].TextureResourceHandle, alreadyProcessedSamplerIds); if (samplerId.HasValue) { alreadyProcessedSamplerIds.Add(samplerId.Value); @@ -367,7 +368,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (handle == null) return ByteString.Empty; - var name = handle->FileName(); + var name = handle->FileName.AsByteString(); if (name.IsEmpty) return ByteString.Empty; @@ -388,6 +389,6 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (handle == null) return 0; - return ResourceHandle.GetLength(handle); + return handle->GetLength(); } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index bc2cca26..53e7db35 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,9 +1,9 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; @@ -50,11 +50,12 @@ public class ResourceTree { var character = (Character*)GameObjectAddress; var model = (CharacterBase*)DrawObjectAddress; + var human = model->GetModelType() == CharacterBase.ModelType.Human ? (Human*)model : null; var equipment = new ReadOnlySpan(&character->DrawData.Head, 10); // var customize = new ReadOnlySpan( character->CustomizeData, 26 ); ModelId = character->CharacterData.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; - RaceCode = model->GetModelType() == CharacterBase.ModelType.Human ? (GenderRace)((Human*)model)->RaceSexId : GenderRace.Unknown; + RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; for (var i = 0; i < model->SlotCount; ++i) { @@ -72,7 +73,7 @@ public class ResourceTree Nodes.Add(imcNode); } - var mdl = (RenderModel*)model->Models[i]; + var mdl = model->Models[i]; var mdlNode = context.CreateNodeFromRenderModel(mdl); if (mdlNode != null) { @@ -84,13 +85,13 @@ public class ResourceTree AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); - if (model->GetModelType() == CharacterBase.ModelType.Human) - AddHumanResources(globalContext, (HumanExt*)model); + if (human != null) + AddHumanResources(globalContext, human); } - private unsafe void AddHumanResources(GlobalResolveContext globalContext, HumanExt* human) + private unsafe void AddHumanResources(GlobalResolveContext globalContext, Human* human) { - var firstSubObject = (CharacterBase*)human->Human.CharacterBase.DrawObject.Object.ChildObject; + var firstSubObject = (CharacterBase*)human->CharacterBase.DrawObject.Object.ChildObject; if (firstSubObject != null) { var subObjectNodes = new List(); @@ -116,7 +117,7 @@ public class ResourceTree subObjectNodes.Add(imcNode); } - var mdl = (RenderModel*)subObject->Models[i]; + var mdl = subObject->Models[i]; var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); if (mdlNode != null) { @@ -137,7 +138,7 @@ public class ResourceTree var context = globalContext.CreateContext(EquipSlot.Unknown, default); - var decalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->Decal); + var decalNode = context.CreateNodeFromTex(human->Decal); if (decalNode != null) { if (globalContext.WithUiData) @@ -149,7 +150,7 @@ public class ResourceTree Nodes.Add(decalNode); } - var legacyDecalNode = context.CreateNodeFromTex((TextureResourceHandle*)human->LegacyBodyDecal); + var legacyDecalNode = context.CreateNodeFromTex(human->LegacyBodyDecal); if (legacyDecalNode != null) { if (globalContext.WithUiData) diff --git a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs index df97371b..fd020804 100644 --- a/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeTextureHandle.cs @@ -1,5 +1,4 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using Penumbra.Interop.Structs; namespace Penumbra.Interop.SafeHandles; @@ -18,7 +17,7 @@ public unsafe class SafeTextureHandle : SafeHandle throw new ArgumentException("Non-owning SafeTextureHandle with IncRef is unsupported"); if (incRef && handle != null) - TextureUtility.IncRef(handle); + handle->IncRef(); SetHandle((nint)handle); } @@ -43,7 +42,7 @@ public unsafe class SafeTextureHandle : SafeHandle } if (handle != 0) - TextureUtility.DecRef((Texture*)handle); + ((Texture*)handle)->DecRef(); return true; } diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index be5b778e..d25a5638 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -2,6 +2,7 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Classes; using Penumbra.Communication; using Penumbra.GameData; @@ -73,19 +74,19 @@ public sealed unsafe class SkinFixer : IDisposable public ulong GetAndResetSlowPathCallDelta() => Interlocked.Exchange(ref _slowPathCallDelta, 0); - private static bool IsSkinMaterial(Structs.MtrlResource* mtrlResource) + private static bool IsSkinMaterial(MaterialResourceHandle* mtrlResource) { if (mtrlResource == null) return false; - var shpkName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlResource->ShpkString); + var shpkName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlResource->ShpkName); return SkinShpkName.SequenceEqual(shpkName); } private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) { - var mtrl = (Structs.MtrlResource*)mtrlResourceHandle; - var shpk = mtrl->ShpkResourceHandle; + var mtrl = (MaterialResourceHandle*)mtrlResourceHandle; + var shpk = mtrl->ShaderPackageResourceHandle; if (shpk == null) return; @@ -109,7 +110,7 @@ public sealed unsafe class SkinFixer : IDisposable return _onRenderMaterialHook.Original(human, param); var material = param->Model->Materials[param->MaterialIndex]; - var mtrlResource = (Structs.MtrlResource*)material->MaterialResourceHandle; + var mtrlResource = material->MaterialResourceHandle; if (!IsSkinMaterial(mtrlResource)) return _onRenderMaterialHook.Original(human, param); @@ -124,7 +125,7 @@ public sealed unsafe class SkinFixer : IDisposable { try { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShpkResourceHandle; + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShaderPackageResourceHandle; return _onRenderMaterialHook.Original(human, param); } finally diff --git a/Penumbra/Interop/Structs/CharacterBaseExt.cs b/Penumbra/Interop/Structs/CharacterBaseExt.cs deleted file mode 100644 index 53fda2cd..00000000 --- a/Penumbra/Interop/Structs/CharacterBaseExt.cs +++ /dev/null @@ -1,14 +0,0 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; - -namespace Penumbra.Interop.Structs; - -[StructLayout(LayoutKind.Explicit)] -public unsafe struct CharacterBaseExt -{ - [FieldOffset(0x0)] - public CharacterBase CharacterBase; - - [FieldOffset(0x258)] - public Texture** ColorTableTextures; -} diff --git a/Penumbra/Interop/Structs/ConstantBuffer.cs b/Penumbra/Interop/Structs/ConstantBuffer.cs deleted file mode 100644 index d61aaeea..00000000 --- a/Penumbra/Interop/Structs/ConstantBuffer.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Penumbra.Interop.Structs; - -[StructLayout(LayoutKind.Explicit, Size = 0x70)] -public unsafe struct ConstantBuffer -{ - [FieldOffset(0x20)] - public int Size; - - [FieldOffset(0x24)] - public int Flags; - - [FieldOffset(0x28)] - private void* _maybeSourcePointer; - - public bool TryGetBuffer(out Span buffer) - { - if ((Flags & 0x4003) == 0 && _maybeSourcePointer != null) - { - buffer = new Span(_maybeSourcePointer, Size >> 2); - return true; - } - else - { - buffer = null; - return false; - } - } -} diff --git a/Penumbra/Interop/Structs/HumanExt.cs b/Penumbra/Interop/Structs/HumanExt.cs deleted file mode 100644 index 274b4fb2..00000000 --- a/Penumbra/Interop/Structs/HumanExt.cs +++ /dev/null @@ -1,19 +0,0 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; - -namespace Penumbra.Interop.Structs; - -[StructLayout(LayoutKind.Explicit)] -public unsafe struct HumanExt -{ - [FieldOffset(0x0)] - public Human Human; - - [FieldOffset(0x0)] - public CharacterBaseExt CharacterBase; - - [FieldOffset(0x9E8)] - public ResourceHandle* Decal; - - [FieldOffset(0x9F0)] - public ResourceHandle* LegacyBodyDecal; -} diff --git a/Penumbra/Interop/Structs/Material.cs b/Penumbra/Interop/Structs/Material.cs deleted file mode 100644 index f7c8679e..00000000 --- a/Penumbra/Interop/Structs/Material.cs +++ /dev/null @@ -1,47 +0,0 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; - -namespace Penumbra.Interop.Structs; - -[StructLayout(LayoutKind.Explicit, Size = 0x40)] -public unsafe struct Material -{ - [FieldOffset(0x10)] - public MtrlResource* ResourceHandle; - - [FieldOffset(0x18)] - public uint ShaderPackageFlags; - - [FieldOffset(0x20)] - public uint* ShaderKeys; - - public int ShaderKeyCount - => (int)((uint*)Textures - ShaderKeys); - - [FieldOffset(0x28)] - public ConstantBuffer* MaterialParameter; - - [FieldOffset(0x30)] - public TextureEntry* Textures; - - [FieldOffset(0x38)] - public ushort TextureCount; - - public Texture* Texture(int index) - => Textures[index].ResourceHandle->KernelTexture; - - [StructLayout(LayoutKind.Explicit, Size = 0x18)] - public struct TextureEntry - { - [FieldOffset(0x00)] - public uint Id; - - [FieldOffset(0x08)] - public TextureResourceHandle* ResourceHandle; - - [FieldOffset(0x10)] - public uint SamplerFlags; - } - - public ReadOnlySpan TextureSpan - => new(Textures, TextureCount); -} diff --git a/Penumbra/Interop/Structs/MtrlResource.cs b/Penumbra/Interop/Structs/MtrlResource.cs deleted file mode 100644 index c3b86e14..00000000 --- a/Penumbra/Interop/Structs/MtrlResource.cs +++ /dev/null @@ -1,45 +0,0 @@ -namespace Penumbra.Interop.Structs; - -[StructLayout(LayoutKind.Explicit)] -public unsafe struct MtrlResource -{ - [FieldOffset(0x00)] - public ResourceHandle Handle; - - [FieldOffset(0xC8)] - public ShaderPackageResourceHandle* ShpkResourceHandle; - - [FieldOffset(0xD0)] - public TextureEntry* TexSpace; // Contains the offsets for the tex files inside the string list. - - [FieldOffset(0xE0)] - public byte* StringList; - - [FieldOffset(0xF8)] - public ushort ShpkOffset; - - [FieldOffset(0xFA)] - public byte NumTex; - - public byte* ShpkString - => StringList + ShpkOffset; - - public byte* TexString(int idx) - => StringList + TexSpace[idx].PathOffset; - - public bool TexIsDX11(int idx) - => TexSpace[idx].Flags >= 0x8000; - - [StructLayout(LayoutKind.Explicit, Size = 0x10)] - public struct TextureEntry - { - [FieldOffset(0x00)] - public TextureResourceHandle* ResourceHandle; - - [FieldOffset(0x08)] - public ushort PathOffset; - - [FieldOffset(0x0A)] - public ushort Flags; - } -} diff --git a/Penumbra/Interop/Structs/RenderModel.cs b/Penumbra/Interop/Structs/RenderModel.cs index f9cb2d56..86b09e8d 100644 --- a/Penumbra/Interop/Structs/RenderModel.cs +++ b/Penumbra/Interop/Structs/RenderModel.cs @@ -5,6 +5,9 @@ namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] public unsafe struct RenderModel { + [FieldOffset(0)] + public Model Model; + [FieldOffset(0x18)] public RenderModel* PreviousModel; diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 3cceb949..382368b4 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -1,10 +1,8 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; -using Penumbra.GameData; using Penumbra.String; using Penumbra.String.Classes; +using CsHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; namespace Penumbra.Interop.Structs; @@ -14,24 +12,8 @@ public unsafe struct TextureResourceHandle [FieldOffset(0x0)] public ResourceHandle Handle; - [FieldOffset(0x38)] - public IntPtr Unk; - - [FieldOffset(0x118)] - public Texture* KernelTexture; - - [FieldOffset(0x20)] - public IntPtr NewKernelTexture; -} - -[StructLayout(LayoutKind.Explicit)] -public unsafe struct ShaderPackageResourceHandle -{ [FieldOffset(0x0)] - public ResourceHandle Handle; - - [FieldOffset(0xB0)] - public ShaderPackage* ShaderPackage; + public CsHandle.TextureResourceHandle CsHandle; } public enum LoadState : byte @@ -59,27 +41,14 @@ public unsafe struct ResourceHandle public ulong DataLength; } - public const int SsoSize = 15; + public readonly ByteString FileName() + => CsHandle.FileName.AsByteString(); - public byte* FileNamePtr() - { - if (FileNameLength > SsoSize) - return FileNameData; + public readonly bool GamePath(out Utf8GamePath path) + => Utf8GamePath.FromSpan(CsHandle.FileName.AsSpan(), out path); - fixed (byte** name = &FileNameData) - { - return (byte*)name; - } - } - - public ByteString FileName() - => ByteString.FromByteStringUnsafe(FileNamePtr(), FileNameLength, true); - - public ReadOnlySpan FileNameAsSpan() - => new(FileNamePtr(), FileNameLength); - - public bool GamePath(out Utf8GamePath path) - => Utf8GamePath.FromSpan(FileNameAsSpan(), out path); + [FieldOffset(0x00)] + public CsHandle.ResourceHandle CsHandle; [FieldOffset(0x00)] public void** VTable; @@ -90,18 +59,9 @@ public unsafe struct ResourceHandle [FieldOffset(0x0C)] public ResourceType FileType; - [FieldOffset(0x10)] - public uint Id; - [FieldOffset(0x28)] public uint FileSize; - [FieldOffset(0x2C)] - public uint FileSize2; - - [FieldOffset(0x34)] - public uint FileSize3; - [FieldOffset(0x48)] public byte* FileNameData; @@ -114,13 +74,6 @@ public unsafe struct ResourceHandle [FieldOffset(0xAC)] public uint RefCount; - // May return null. - public static byte* GetData(ResourceHandle* handle) - => ((delegate* unmanaged< ResourceHandle*, byte* >)handle->VTable[Offsets.ResourceHandleGetDataVfunc])(handle); - - public static ulong GetLength(ResourceHandle* handle) - => ((delegate* unmanaged< ResourceHandle*, ulong >)handle->VTable[Offsets.ResourceHandleGetLengthVfunc])(handle); - // Only use these if you know what you are doing. // Those are actually only sure to be accessible for DefaultResourceHandles. diff --git a/Penumbra/Interop/Structs/ShaderPackageUtility.cs b/Penumbra/Interop/Structs/ShaderPackageUtility.cs deleted file mode 100644 index 9f7ec1f5..00000000 --- a/Penumbra/Interop/Structs/ShaderPackageUtility.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Penumbra.Interop.Structs; - -public static class ShaderPackageUtility -{ - [StructLayout(LayoutKind.Explicit, Size = 0xC)] - public unsafe struct Sampler - { - [FieldOffset(0x0)] - public uint Crc; - - [FieldOffset(0x4)] - public uint Id; - - [FieldOffset(0xA)] - public ushort Slot; - } -} diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs new file mode 100644 index 00000000..d1a38ae4 --- /dev/null +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -0,0 +1,24 @@ +using FFXIVClientStructs.STD; +using Penumbra.String; + +namespace Penumbra.Interop.Structs; + +internal static class StructExtensions +{ + // TODO submit this to ClientStructs + public static unsafe ReadOnlySpan AsSpan(in this StdString str) + { + if (str.Length < 16) + { + fixed (StdString* pStr = &str) + { + return new(pStr->Buffer, (int)str.Length); + } + } + else + return new(str.BufferPtr, (int)str.Length); + } + + public static unsafe ByteString AsByteString(in this StdString str) + => ByteString.FromSpanUnsafe(str.AsSpan(), true); +} diff --git a/Penumbra/Interop/Structs/TextureUtility.cs b/Penumbra/Interop/Structs/TextureUtility.cs deleted file mode 100644 index eeea4c33..00000000 --- a/Penumbra/Interop/Structs/TextureUtility.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; - -namespace Penumbra.Interop.Structs; - -public unsafe class TextureUtility -{ - public TextureUtility(IGameInteropProvider interop) - => interop.InitializeFromAttributes(this); - - - [Signature("E8 ?? ?? ?? ?? 8B 0F 48 8D 54 24")] - private static nint _textureCreate2D = nint.Zero; - - [Signature("E9 ?? ?? ?? ?? 8B 02 25")] - private static nint _textureInitializeContents = nint.Zero; - - public static Texture* Create2D(Device* device, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk) - => ((delegate* unmanaged)_textureCreate2D)(device, size, mipLevel, textureFormat, - flags, unk); - - public static bool InitializeContents(Texture* texture, void* contents) - => ((delegate* unmanaged)_textureInitializeContents)(texture, contents); - - public static void IncRef(Texture* texture) - => ((delegate* unmanaged)(*(void***)texture)[2])(texture); - - public static void DecRef(Texture* texture) - => ((delegate* unmanaged)(*(void***)texture)[3])(texture); -} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 73d1013e..ce1bdae5 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -75,7 +75,6 @@ public class Penumbra : IDalamudPlugin _communicatorService = _services.GetRequiredService(); _services.GetRequiredService(); // Initialize because not required anywhere else. _services.GetRequiredService(); // Initialize because not required anywhere else. - _services.GetRequiredService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); using (var t = _services.GetRequiredService().Measure(StartTimeType.PathResolver)) { diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 84f89f6d..6a522ca2 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -90,8 +90,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() - .AddSingleton(); + .AddSingleton(); private static IServiceCollection AddConfiguration(this IServiceCollection services) => services.AddTransient() diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index 5abb3c2f..1c5f7946 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -669,8 +669,8 @@ public class DebugTab : Window, ITab UiHelpers.Text(resource); ImGui.TableNextColumn(); - var data = (nint)ResourceHandle.GetData(resource); - var length = ResourceHandle.GetLength(resource); + var data = (nint)resource->CsHandle.GetData(); + var length = resource->CsHandle.GetLength(); if (ImGui.Selectable($"0x{data:X}")) if (data != nint.Zero && length > 0) ImGui.SetClipboardText(string.Join("\n", diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index 020493d1..6f3dec30 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -99,10 +99,10 @@ public class ResourceTab : ITab UiHelpers.Text(resource); if (ImGui.IsItemClicked()) { - var data = Interop.Structs.ResourceHandle.GetData(resource); + var data = resource->CsHandle.GetData(); if (data != null) { - var length = (int)Interop.Structs.ResourceHandle.GetLength(resource); + var length = (int)resource->CsHandle.GetLength(); ImGui.SetClipboardText(string.Join(" ", new ReadOnlySpan(data, length).ToArray().Select(b => b.ToString("X2")))); } diff --git a/Penumbra/UI/UiHelpers.cs b/Penumbra/UI/UiHelpers.cs index 6c64bd55..8fbce6d0 100644 --- a/Penumbra/UI/UiHelpers.cs +++ b/Penumbra/UI/UiHelpers.cs @@ -19,9 +19,18 @@ public static class UiHelpers public static unsafe void Text(byte* s, int length) => ImGuiNative.igTextUnformatted(s, s + length); + /// Draw text given by a byte span. + public static unsafe void Text(ReadOnlySpan s) + { + fixed (byte* pS = s) + { + Text(pS, s.Length); + } + } + /// Draw the name of a resource file. public static unsafe void Text(ResourceHandle* resource) - => Text(resource->FileName().Path, resource->FileNameLength); + => Text(resource->CsHandle.FileName.AsSpan()); /// Draw a ByteString as a selectable. public static unsafe bool Selectable(ByteString s, bool selected) From 5085aa500c167bba4853346a7e4a651129a7d54d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 27 Oct 2023 02:13:57 +0200 Subject: [PATCH 0183/1381] ResourceTree: Use DrawObject as equipment source + CS-ify a bit more --- Penumbra/Interop/ResourceTree/ResourceTree.cs | 84 ++++++++++--------- 1 file changed, 45 insertions(+), 39 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 53e7db35..836e79e2 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -50,9 +50,14 @@ public class ResourceTree { var character = (Character*)GameObjectAddress; var model = (CharacterBase*)DrawObjectAddress; - var human = model->GetModelType() == CharacterBase.ModelType.Human ? (Human*)model : null; - var equipment = new ReadOnlySpan(&character->DrawData.Head, 10); - // var customize = new ReadOnlySpan( character->CustomizeData, 26 ); + var modelType = model->GetModelType(); + var human = modelType == CharacterBase.ModelType.Human ? (Human*)model : null; + var equipment = modelType switch + { + CharacterBase.ModelType.Human => new ReadOnlySpan(&human->Head, 10), + CharacterBase.ModelType.DemiHuman => new ReadOnlySpan(&character->DrawData.Head, 10), + _ => ReadOnlySpan.Empty, + }; ModelId = character->CharacterData.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; @@ -91,50 +96,51 @@ public class ResourceTree private unsafe void AddHumanResources(GlobalResolveContext globalContext, Human* human) { - var firstSubObject = (CharacterBase*)human->CharacterBase.DrawObject.Object.ChildObject; - if (firstSubObject != null) + var subObjectIndex = 0; + var weaponIndex = 0; + var subObjectNodes = new List(); + foreach (var baseSubObject in human->CharacterBase.DrawObject.Object.ChildObjects) { - var subObjectNodes = new List(); - var subObject = firstSubObject; - var subObjectIndex = 0; - do + if (baseSubObject->GetObjectType() != FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType.CharacterBase) + continue; + var subObject = (CharacterBase*)baseSubObject; + + var weapon = subObject->GetModelType() == CharacterBase.ModelType.Weapon ? (Weapon*)subObject : null; + var subObjectNamePrefix = weapon != null ? "Weapon" : "Fashion Acc."; + // This way to tell apart MainHand and OffHand is not always accurate, but seems good enough for what we're doing with it. + var subObjectContext = globalContext.CreateContext( + weapon != null ? (weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand) : EquipSlot.Unknown, + weapon != null ? new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown) : default + ); + + for (var i = 0; i < subObject->SlotCount; ++i) { - var weapon = subObject->GetModelType() == CharacterBase.ModelType.Weapon ? (Weapon*)subObject : null; - var subObjectNamePrefix = weapon != null ? "Weapon" : "Fashion Acc."; - var subObjectContext = globalContext.CreateContext( - weapon != null ? EquipSlot.MainHand : EquipSlot.Unknown, - weapon != null ? new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown) : default - ); - - for (var i = 0; i < subObject->SlotCount; ++i) + var imc = (ResourceHandle*)subObject->IMCArray[i]; + var imcNode = subObjectContext.CreateNodeFromImc(imc); + if (imcNode != null) { - var imc = (ResourceHandle*)subObject->IMCArray[i]; - var imcNode = subObjectContext.CreateNodeFromImc(imc); - if (imcNode != null) - { - if (globalContext.WithUiData) - imcNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}"; - subObjectNodes.Add(imcNode); - } - - var mdl = subObject->Models[i]; - var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); - if (mdlNode != null) - { - if (globalContext.WithUiData) - mdlNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}"; - subObjectNodes.Add(mdlNode); - } + if (globalContext.WithUiData) + imcNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}"; + subObjectNodes.Add(imcNode); } - AddSkeleton(subObjectNodes, subObjectContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); + var mdl = subObject->Models[i]; + var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); + if (mdlNode != null) + { + if (globalContext.WithUiData) + mdlNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}"; + subObjectNodes.Add(mdlNode); + } + } - subObject = (CharacterBase*)subObject->DrawObject.Object.NextSiblingObject; - ++subObjectIndex; - } while (subObject != null && subObject != firstSubObject); + AddSkeleton(subObjectNodes, subObjectContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); - Nodes.InsertRange(0, subObjectNodes); + ++subObjectIndex; + if (weapon != null) + ++weaponIndex; } + Nodes.InsertRange(0, subObjectNodes); var context = globalContext.CreateContext(EquipSlot.Unknown, default); From db9bfb00a32cbac3fbae13460e7ba1f86559f39a Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 27 Oct 2023 02:17:41 +0200 Subject: [PATCH 0184/1381] ResourceTree: Show SKP files out of Debug --- Penumbra/Interop/ResourceTree/ResolveContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 5e3970cc..ade3ccd7 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -268,7 +268,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, true); + var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, false); if (node != null) { if (WithUiData) From 3da20f2d8971553050715bd94a046d0c1a839701 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 2 Nov 2023 01:08:02 +0100 Subject: [PATCH 0185/1381] ResourceTree: Rework Internal flag, improve null checks, simplify --- .../Interop/ResourceTree/ResolveContext.cs | 91 +++++++++---------- Penumbra/Interop/ResourceTree/ResourceNode.cs | 8 +- 2 files changed, 48 insertions(+), 51 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index ade3ccd7..8e286ad0 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -27,8 +27,11 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); - private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath, bool @internal) + private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath) { + if (resourceHandle == null) + return null; + if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) return cached; @@ -37,11 +40,14 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (!Utf8GamePath.FromByteString(ByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path, false)) return null; - return CreateNodeFromGamePath(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path, @internal); + return CreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); } - private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool @internal, bool dx11) + private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool dx11) { + if (resourceHandle == null) + return null; + if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) return cached; @@ -65,82 +71,73 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree gamePath = tmp.Path.Clone(); } } + else + { + // Make sure the game path is owned, otherwise stale trees could cause crashes (access violations) or other memory safety issues. + if (!gamePath.IsOwned) + gamePath = gamePath.Clone(); + } if (!Utf8GamePath.FromByteString(gamePath, out var path)) return null; - return CreateNodeFromGamePath(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path, @internal); + return CreateNode(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path); } - private unsafe ResourceNode CreateNodeFromGamePath(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, - Utf8GamePath gamePath, bool @internal) + private unsafe ResourceNode CreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, + Utf8GamePath gamePath, bool autoAdd = true) { + if (resourceHandle == null) + throw new ArgumentNullException(nameof(resourceHandle)); + var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(resourceHandle), out var p) ? new FullPath(p) : FullPath.Empty; - var node = new ResourceNode(type, objectAddress, (nint)resourceHandle, GetResourceHandleLength(resourceHandle), @internal, this) + var node = new ResourceNode(type, objectAddress, (nint)resourceHandle, GetResourceHandleLength(resourceHandle), this) { GamePath = gamePath, FullPath = fullPath, }; - if (resourceHandle != null) + if (autoAdd) Nodes.Add((nint)resourceHandle, node); return node; } - private unsafe ResourceNode? CreateNodeFromResourceHandle(ResourceType type, nint objectAddress, ResourceHandle* handle, bool @internal) - { - var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(handle), out var p) ? new FullPath(p) : FullPath.Empty; - if (fullPath.InternalName.IsEmpty) - return null; - - return new ResourceNode(type, objectAddress, (nint)handle, GetResourceHandleLength(handle), @internal, this) - { - FullPath = fullPath, - }; - } - public unsafe ResourceNode? CreateNodeFromImc(ResourceHandle* imc) { + if (imc == null) + return null; + if (Nodes.TryGetValue((nint)imc, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Imc, 0, imc, true); - if (node == null) - return null; - - Nodes.Add((nint)imc, node); - - return node; + return CreateNode(ResourceType.Imc, 0, imc, Utf8GamePath.Empty); } public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex) { + if (tex == null) + return null; + if (Nodes.TryGetValue((nint)tex, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, false); - if (node != null) - Nodes.Add((nint)tex, node); - - return node; + return CreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, Utf8GamePath.Empty); } public unsafe ResourceNode? CreateNodeFromRenderModel(Model* mdl) { - if (mdl == null || mdl->ModelResourceHandle == null || mdl->ModelResourceHandle->ResourceHandle.Type.Category != ResourceHandleType.HandleCategory.Chara) + if (mdl == null || mdl->ModelResourceHandle == null) return null; if (Nodes.TryGetValue((nint)mdl->ModelResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, false); - if (node == null) - return null; + var node = CreateNode(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, Utf8GamePath.Empty, false); for (var i = 0; i < mdl->MaterialCount; i++) { - var mtrl = (Material*)mdl->Materials[i]; + var mtrl = mdl->Materials[i]; var mtrlNode = CreateNodeFromMaterial(mtrl); if (mtrlNode != null) { @@ -179,18 +176,18 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree ? s.CRC : null; - if (mtrl == null) + if (mtrl == null || mtrl->MaterialResourceHandle == null) return null; var resource = mtrl->MaterialResourceHandle; if (Nodes.TryGetValue((nint)resource, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, false); + var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, Utf8GamePath.Empty, false); if (node == null) return null; - var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName), false); + var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName)); if (shpkNode != null) { if (WithUiData) @@ -203,7 +200,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->TextureCount; i++) { - var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new ByteString(resource->TexturePath(i)), false, + var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new ByteString(resource->TexturePath(i)), resource->Textures[i].IsDX11); if (texNode == null) continue; @@ -240,15 +237,15 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree return node; } - public unsafe ResourceNode? CreateNodeFromPartialSkeleton(FFXIVClientStructs.FFXIV.Client.Graphics.Render.PartialSkeleton* sklb) + public unsafe ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb) { - if (sklb->SkeletonResourceHandle == null) + if (sklb == null || sklb->SkeletonResourceHandle == null) return null; if (Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, false); + var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, Utf8GamePath.Empty, false); if (node != null) { var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); @@ -260,15 +257,15 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree return node; } - private unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(FFXIVClientStructs.FFXIV.Client.Graphics.Render.PartialSkeleton* sklb) + private unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb) { - if (sklb->SkeletonParameterResourceHandle == null) + if (sklb == null || sklb->SkeletonParameterResourceHandle == null) return null; if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) return cached; - var node = CreateNodeFromResourceHandle(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, false); + var node = CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, Utf8GamePath.Empty, false); if (node != null) { if (WithUiData) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index dfca5805..f520c83a 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -15,7 +15,6 @@ public class ResourceNode : ICloneable public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; public readonly ulong Length; - public readonly bool Internal; public readonly List Children; internal ResolveContext? ResolveContext; @@ -31,14 +30,16 @@ public class ResourceNode : ICloneable } } - internal ResourceNode(ResourceType type, nint objectAddress, nint resourceHandle, ulong length, bool @internal, ResolveContext? resolveContext) + public bool Internal + => Type is ResourceType.Imc; + + internal ResourceNode(ResourceType type, nint objectAddress, nint resourceHandle, ulong length, ResolveContext? resolveContext) { Type = type; ObjectAddress = objectAddress; ResourceHandle = resourceHandle; PossibleGamePaths = Array.Empty(); Length = length; - Internal = @internal; Children = new List(); ResolveContext = resolveContext; } @@ -54,7 +55,6 @@ public class ResourceNode : ICloneable PossibleGamePaths = other.PossibleGamePaths; FullPath = other.FullPath; Length = other.Length; - Internal = other.Internal; Children = other.Children; ResolveContext = other.ResolveContext; } From 28a396470baae8e2162b94d2e0126b1d4e6b914d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 2 Nov 2023 01:11:48 +0100 Subject: [PATCH 0186/1381] ResourceTree: De-inline GlobalResolveContext in ResolveContext --- .../Interop/ResourceTree/ResolveContext.cs | 49 +++++++++---------- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 8e286ad0..e5a122ac 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -19,11 +19,10 @@ internal record GlobalResolveContext(IObjectIdentifier Identifier, TreeBuildCach public readonly Dictionary Nodes = new(128); public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) - => new(Identifier, TreeBuildCache, Skeleton, WithUiData, Nodes, slot, equipment); + => new(this, slot, equipment); } -internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, int Skeleton, bool WithUiData, - Dictionary Nodes, EquipSlot Slot, CharacterArmor Equipment) +internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); @@ -32,7 +31,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (resourceHandle == null) return null; - if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) + if (Global.Nodes.TryGetValue((nint)resourceHandle, out var cached)) return cached; if (gamePath.IsEmpty) @@ -48,7 +47,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (resourceHandle == null) return null; - if (Nodes.TryGetValue((nint)resourceHandle, out var cached)) + if (Global.Nodes.TryGetValue((nint)resourceHandle, out var cached)) return cached; if (dx11) @@ -98,7 +97,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree FullPath = fullPath, }; if (autoAdd) - Nodes.Add((nint)resourceHandle, node); + Global.Nodes.Add((nint)resourceHandle, node); return node; } @@ -108,7 +107,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (imc == null) return null; - if (Nodes.TryGetValue((nint)imc, out var cached)) + if (Global.Nodes.TryGetValue((nint)imc, out var cached)) return cached; return CreateNode(ResourceType.Imc, 0, imc, Utf8GamePath.Empty); @@ -119,7 +118,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (tex == null) return null; - if (Nodes.TryGetValue((nint)tex, out var cached)) + if (Global.Nodes.TryGetValue((nint)tex, out var cached)) return cached; return CreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, Utf8GamePath.Empty); @@ -130,7 +129,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (mdl == null || mdl->ModelResourceHandle == null) return null; - if (Nodes.TryGetValue((nint)mdl->ModelResourceHandle, out var cached)) + if (Global.Nodes.TryGetValue((nint)mdl->ModelResourceHandle, out var cached)) return cached; var node = CreateNode(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, Utf8GamePath.Empty, false); @@ -141,13 +140,13 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree var mtrlNode = CreateNodeFromMaterial(mtrl); if (mtrlNode != null) { - if (WithUiData) + if (Global.WithUiData) mtrlNode.FallbackName = $"Material #{i}"; node.Children.Add(mtrlNode); } } - Nodes.Add((nint)mdl->ModelResourceHandle, node); + Global.Nodes.Add((nint)mdl->ModelResourceHandle, node); return node; } @@ -180,7 +179,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree return null; var resource = mtrl->MaterialResourceHandle; - if (Nodes.TryGetValue((nint)resource, out var cached)) + if (Global.Nodes.TryGetValue((nint)resource, out var cached)) return cached; var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, Utf8GamePath.Empty, false); @@ -190,12 +189,12 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName)); if (shpkNode != null) { - if (WithUiData) + if (Global.WithUiData) shpkNode.Name = "Shader Package"; node.Children.Add(shpkNode); } - var shpkFile = WithUiData && shpkNode != null ? TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; - var shpk = WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; + var shpkFile = Global.WithUiData && shpkNode != null ? Global.TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; + var shpk = Global.WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->TextureCount; i++) @@ -205,7 +204,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (texNode == null) continue; - if (WithUiData) + if (Global.WithUiData) { string? name = null; if (shpk != null) @@ -232,7 +231,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree node.Children.Add(texNode); } - Nodes.Add((nint)resource, node); + Global.Nodes.Add((nint)resource, node); return node; } @@ -242,7 +241,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (sklb == null || sklb->SkeletonResourceHandle == null) return null; - if (Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) + if (Global.Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) return cached; var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, Utf8GamePath.Empty, false); @@ -251,7 +250,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); if (skpNode != null) node.Children.Add(skpNode); - Nodes.Add((nint)sklb->SkeletonResourceHandle, node); + Global.Nodes.Add((nint)sklb->SkeletonResourceHandle, node); } return node; @@ -262,15 +261,15 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree if (sklb == null || sklb->SkeletonParameterResourceHandle == null) return null; - if (Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) + if (Global.Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) return cached; var node = CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, Utf8GamePath.Empty, false); if (node != null) { - if (WithUiData) + if (Global.WithUiData) node.FallbackName = "Skeleton Parameters"; - Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); + Global.Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); } return node; @@ -297,7 +296,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree { "accessory" => IsMatchEquipment(path[2..], $"a{Equipment.Set.Id:D4}"), "equipment" => IsMatchEquipment(path[2..], $"e{Equipment.Set.Id:D4}"), - "monster" => SafeGet(path, 2) == $"m{Skeleton:D4}", + "monster" => SafeGet(path, 2) == $"m{Global.Skeleton:D4}", "weapon" => IsMatchEquipment(path[2..], $"w{Equipment.Set.Id:D4}"), _ => null, }, @@ -319,7 +318,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree // Weapons intentionally left out. var isEquipment = SafeGet(path, 0) == "chara" && SafeGet(path, 1) is "accessory" or "equipment"; if (isEquipment) - foreach (var item in Identifier.Identify(Equipment.Set, Equipment.Variant, Slot.ToSlot())) + foreach (var item in Global.Identifier.Identify(Equipment.Set, Equipment.Variant, Slot.ToSlot())) { var name = Slot switch { @@ -342,7 +341,7 @@ internal record ResolveContext(IObjectIdentifier Identifier, TreeBuildCache Tree internal ResourceNode.UiData GuessUIDataFromPath(Utf8GamePath gamePath) { - foreach (var obj in Identifier.Identify(gamePath.ToString())) + foreach (var obj in Global.Identifier.Identify(gamePath.ToString())) { var name = obj.Key; if (name.StartsWith("Customization:")) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 836e79e2..38dae6b8 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -179,7 +179,7 @@ public class ResourceTree var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); if (sklbNode != null) { - if (context.WithUiData) + if (context.Global.WithUiData) sklbNode.FallbackName = $"{prefix}Skeleton #{i}"; nodes.Add(sklbNode); } From 57f8587a4358853f85be4a3d75a59f5df24e69c0 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 2 Nov 2023 01:18:20 +0100 Subject: [PATCH 0187/1381] ResourceTree: Use both game path and resource handle as keys for dedup --- .../Interop/ResourceTree/ResolveContext.cs | 69 +++++++++++-------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index e5a122ac..a359411b 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -16,7 +16,7 @@ namespace Penumbra.Interop.ResourceTree; internal record GlobalResolveContext(IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, int Skeleton, bool WithUiData) { - public readonly Dictionary Nodes = new(128); + public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) => new(this, slot, equipment); @@ -30,16 +30,12 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char { if (resourceHandle == null) return null; - - if (Global.Nodes.TryGetValue((nint)resourceHandle, out var cached)) - return cached; - if (gamePath.IsEmpty) return null; if (!Utf8GamePath.FromByteString(ByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path, false)) return null; - return CreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); + return GetOrCreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); } private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool dx11) @@ -47,9 +43,6 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (resourceHandle == null) return null; - if (Global.Nodes.TryGetValue((nint)resourceHandle, out var cached)) - return cached; - if (dx11) { var lastDirectorySeparator = gamePath.LastIndexOf((byte)'/'); @@ -80,7 +73,19 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (!Utf8GamePath.FromByteString(gamePath, out var path)) return null; - return CreateNode(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path); + return GetOrCreateNode(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path); + } + + private unsafe ResourceNode GetOrCreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, + Utf8GamePath gamePath) + { + if (resourceHandle == null) + throw new ArgumentNullException(nameof(resourceHandle)); + + if (Global.Nodes.TryGetValue((gamePath, (nint)resourceHandle), out var cached)) + return cached; + + return CreateNode(type, objectAddress, resourceHandle, gamePath); } private unsafe ResourceNode CreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, @@ -97,7 +102,7 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char FullPath = fullPath, }; if (autoAdd) - Global.Nodes.Add((nint)resourceHandle, node); + Global.Nodes.Add((gamePath, (nint)resourceHandle), node); return node; } @@ -107,10 +112,9 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (imc == null) return null; - if (Global.Nodes.TryGetValue((nint)imc, out var cached)) - return cached; + var path = Utf8GamePath.Empty; // TODO - return CreateNode(ResourceType.Imc, 0, imc, Utf8GamePath.Empty); + return GetOrCreateNode(ResourceType.Imc, 0, imc, path); } public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex) @@ -118,10 +122,9 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (tex == null) return null; - if (Global.Nodes.TryGetValue((nint)tex, out var cached)) - return cached; + var path = Utf8GamePath.Empty; // TODO - return CreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, Utf8GamePath.Empty); + return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, path); } public unsafe ResourceNode? CreateNodeFromRenderModel(Model* mdl) @@ -129,10 +132,12 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (mdl == null || mdl->ModelResourceHandle == null) return null; - if (Global.Nodes.TryGetValue((nint)mdl->ModelResourceHandle, out var cached)) + var path = Utf8GamePath.Empty; // TODO + + if (Global.Nodes.TryGetValue((path, (nint)mdl->ModelResourceHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, Utf8GamePath.Empty, false); + var node = CreateNode(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, path, false); for (var i = 0; i < mdl->MaterialCount; i++) { @@ -146,7 +151,7 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char } } - Global.Nodes.Add((nint)mdl->ModelResourceHandle, node); + Global.Nodes.Add((path, (nint)mdl->ModelResourceHandle), node); return node; } @@ -178,11 +183,13 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (mtrl == null || mtrl->MaterialResourceHandle == null) return null; + var path = Utf8GamePath.Empty; // TODO + var resource = mtrl->MaterialResourceHandle; - if (Global.Nodes.TryGetValue((nint)resource, out var cached)) + if (Global.Nodes.TryGetValue((path, (nint)resource), out var cached)) return cached; - var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, Utf8GamePath.Empty, false); + var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); if (node == null) return null; @@ -231,7 +238,7 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char node.Children.Add(texNode); } - Global.Nodes.Add((nint)resource, node); + Global.Nodes.Add((path, (nint)resource), node); return node; } @@ -241,16 +248,18 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (sklb == null || sklb->SkeletonResourceHandle == null) return null; - if (Global.Nodes.TryGetValue((nint)sklb->SkeletonResourceHandle, out var cached)) + var path = Utf8GamePath.Empty; // TODO + + if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonResourceHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, Utf8GamePath.Empty, false); + var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); if (node != null) { var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); if (skpNode != null) node.Children.Add(skpNode); - Global.Nodes.Add((nint)sklb->SkeletonResourceHandle, node); + Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); } return node; @@ -261,15 +270,17 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (sklb == null || sklb->SkeletonParameterResourceHandle == null) return null; - if (Global.Nodes.TryGetValue((nint)sklb->SkeletonParameterResourceHandle, out var cached)) + var path = Utf8GamePath.Empty; // TODO + + if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonParameterResourceHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, Utf8GamePath.Empty, false); + var node = CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, path, false); if (node != null) { if (Global.WithUiData) node.FallbackName = "Skeleton Parameters"; - Global.Nodes.Add((nint)sklb->SkeletonParameterResourceHandle, node); + Global.Nodes.Add((path, (nint)sklb->SkeletonParameterResourceHandle), node); } return node; From da54222bb1f66ce189b335a7cbf78521a5a1583d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 2 Nov 2023 20:59:09 +0100 Subject: [PATCH 0188/1381] ResourceTree: Add EID files --- .../Interop/ResourceTree/ResolveContext.cs | 10 ++++++++++ Penumbra/Interop/ResourceTree/ResourceNode.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index a359411b..26d64afe 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -107,6 +107,16 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char return node; } + public unsafe ResourceNode? CreateNodeFromEid(ResourceHandle* eid) + { + if (eid == null) + return null; + + var path = Utf8GamePath.Empty; // TODO + + return GetOrCreateNode(ResourceType.Eid, 0, eid, path); + } + public unsafe ResourceNode? CreateNodeFromImc(ResourceHandle* imc) { if (imc == null) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index f520c83a..53dedfa0 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -31,7 +31,7 @@ public class ResourceNode : ICloneable } public bool Internal - => Type is ResourceType.Imc; + => Type is ResourceType.Eid or ResourceType.Imc; internal ResourceNode(ResourceType type, nint objectAddress, nint resourceHandle, ulong length, ResolveContext? resolveContext) { diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 38dae6b8..687c14ec 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -62,6 +62,15 @@ public class ResourceTree CustomizeData = character->DrawData.CustomizeData; RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; + var eid = (ResourceHandle*)model->EID; + var eidNode = globalContext.CreateContext(EquipSlot.Unknown, default).CreateNodeFromEid(eid); + if (eidNode != null) + { + if (globalContext.WithUiData) + eidNode.FallbackName = "EID"; + Nodes.Add(eidNode); + } + for (var i = 0; i < model->SlotCount; ++i) { var context = globalContext.CreateContext( @@ -113,6 +122,15 @@ public class ResourceTree weapon != null ? new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown) : default ); + var eid = (ResourceHandle*)subObject->EID; + var eidNode = subObjectContext.CreateNodeFromEid(eid); + if (eidNode != null) + { + if (globalContext.WithUiData) + eidNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, EID"; + Nodes.Add(eidNode); + } + for (var i = 0; i < subObject->SlotCount; ++i) { var imc = (ResourceHandle*)subObject->IMCArray[i]; From 69a4e2b52ef7ce0485d9881ddc5007bd2edd8f29 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 3 Nov 2023 12:59:35 +0100 Subject: [PATCH 0189/1381] Fix Linking changed items not working. --- Penumbra/Penumbra.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 73d1013e..99a81fd1 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -19,6 +19,7 @@ using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; +using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; @@ -111,13 +112,13 @@ public class Penumbra : IDalamudPlugin _services.GetRequiredService(); _communicatorService.ChangedItemHover.Subscribe(it => { - if (it is Item) + if (it is (Item, FullEquipType)) ImGui.TextUnformatted("Left Click to create an item link in chat."); }, ChangedItemHover.Priority.Link); _communicatorService.ChangedItemClick.Subscribe((button, it) => { - if (button == MouseButton.Left && it is Item item) + if (button == MouseButton.Left && it is (Item item, FullEquipType type)) Messager.LinkItem(item); }, ChangedItemClick.Priority.Link); } From 79c43fe7b1edc00d1afb357f37e447ddfde35773 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 2 Nov 2023 21:01:40 +0100 Subject: [PATCH 0190/1381] PathResolving: Better function signatures? (names + types + TMB param count + dedupe) --- Penumbra/Interop/PathResolving/PathState.cs | 2 +- .../Interop/PathResolving/ResolvePathHooks.cs | 175 +++++++----------- 2 files changed, 71 insertions(+), 106 deletions(-) diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index 4fb3d31d..f300a666 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -42,7 +42,7 @@ public unsafe class PathState : IDisposable MetaState = metaState; CharacterUtility = characterUtility; _human = new ResolvePathHooks(interop, this, _humanVTable, ResolvePathHooks.Type.Human); - _weapon = new ResolvePathHooks(interop, this, _weaponVTable, ResolvePathHooks.Type.Weapon); + _weapon = new ResolvePathHooks(interop, this, _weaponVTable, ResolvePathHooks.Type.Other); _demiHuman = new ResolvePathHooks(interop, this, _demiHumanVTable, ResolvePathHooks.Type.Other); _monster = new ResolvePathHooks(interop, this, _monsterVTable, ResolvePathHooks.Type.Other); _human.Enable(); diff --git a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs index f9a341b9..9d010d64 100644 --- a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs +++ b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs @@ -12,45 +12,47 @@ public unsafe class ResolvePathHooks : IDisposable public enum Type { Human, - Weapon, Other, } - private delegate nint GeneralResolveDelegate(nint drawObject, nint path, nint unk3, uint unk4); - private delegate nint MPapResolveDelegate(nint drawObject, nint path, nint unk3, uint unk4, uint unk5); - private delegate nint MaterialResolveDelegate(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5); - private delegate nint EidResolveDelegate(nint drawObject, nint path, nint unk3); + private delegate nint MPapResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, uint sId); + private delegate nint NamedResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint name); + private delegate nint PerSlotResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex); + private delegate nint SingleResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize); + private delegate nint TmbResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, nint timelineName); + // Kept separate from NamedResolveDelegate because the 5th parameter has out semantics here, instead of in. + private delegate nint VfxResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam); - private readonly Hook _resolveDecalPathHook; - private readonly Hook _resolveEidPathHook; - private readonly Hook _resolveImcPathHook; - private readonly Hook _resolveMPapPathHook; - private readonly Hook _resolveMdlPathHook; - private readonly Hook _resolveMtrlPathHook; - private readonly Hook _resolvePapPathHook; - private readonly Hook _resolvePhybPathHook; - private readonly Hook _resolveSklbPathHook; - private readonly Hook _resolveSkpPathHook; - private readonly Hook _resolveTmbPathHook; - private readonly Hook _resolveVfxPathHook; + private readonly Hook _resolveDecalPathHook; + private readonly Hook _resolveEidPathHook; + private readonly Hook _resolveImcPathHook; + private readonly Hook _resolveMPapPathHook; + private readonly Hook _resolveMdlPathHook; + private readonly Hook _resolveMtrlPathHook; + private readonly Hook _resolvePapPathHook; + private readonly Hook _resolvePhybPathHook; + private readonly Hook _resolveSklbPathHook; + private readonly Hook _resolveSkpPathHook; + private readonly Hook _resolveTmbPathHook; + private readonly Hook _resolveVfxPathHook; private readonly PathState _parent; public ResolvePathHooks(IGameInteropProvider interop, PathState parent, nint* vTable, Type type) { _parent = parent; - _resolveDecalPathHook = Create(interop, vTable[83], type, ResolveDecalWeapon, ResolveDecal); - _resolveEidPathHook = Create(interop, vTable[85], type, ResolveEidWeapon, ResolveEid); - _resolveImcPathHook = Create(interop, vTable[81], type, ResolveImcWeapon, ResolveImc); - _resolveMPapPathHook = Create(interop, vTable[79], type, ResolveMPapWeapon, ResolveMPap); - _resolveMdlPathHook = Create(interop, vTable[73], type, ResolveMdlWeapon, ResolveMdl, ResolveMdlHuman); - _resolveMtrlPathHook = Create(interop, vTable[82], type, ResolveMtrlWeapon, ResolveMtrl); - _resolvePapPathHook = Create(interop, vTable[76], type, ResolvePapWeapon, ResolvePap, ResolvePapHuman); - _resolvePhybPathHook = Create(interop, vTable[75], type, ResolvePhybWeapon, ResolvePhyb, ResolvePhybHuman); - _resolveSklbPathHook = Create(interop, vTable[72], type, ResolveSklbWeapon, ResolveSklb, ResolveSklbHuman); - _resolveSkpPathHook = Create(interop, vTable[74], type, ResolveSkpWeapon, ResolveSkp, ResolveSkpHuman); - _resolveTmbPathHook = Create(interop, vTable[77], type, ResolveTmbWeapon, ResolveTmb); - _resolveVfxPathHook = Create(interop, vTable[84], type, ResolveVfxWeapon, ResolveVfx); + _resolveDecalPathHook = Create(interop, vTable[83], ResolveDecal); + _resolveEidPathHook = Create(interop, vTable[85], ResolveEid); + _resolveImcPathHook = Create(interop, vTable[81], ResolveImc); + _resolveMPapPathHook = Create(interop, vTable[79], ResolveMPap); + _resolveMdlPathHook = Create(interop, vTable[73], type, ResolveMdl, ResolveMdlHuman); + _resolveMtrlPathHook = Create(interop, vTable[82], ResolveMtrl); + _resolvePapPathHook = Create(interop, vTable[76], type, ResolvePap, ResolvePapHuman); + _resolvePhybPathHook = Create(interop, vTable[75], type, ResolvePhyb, ResolvePhybHuman); + _resolveSklbPathHook = Create(interop, vTable[72], type, ResolveSklb, ResolveSklbHuman); + _resolveSkpPathHook = Create(interop, vTable[74], type, ResolveSkp, ResolveSkpHuman); + _resolveTmbPathHook = Create(interop, vTable[77], ResolveTmb); + _resolveVfxPathHook = Create(interop, vTable[84], ResolveVfx); } public void Enable() @@ -101,74 +103,74 @@ public unsafe class ResolvePathHooks : IDisposable _resolveVfxPathHook.Dispose(); } - private nint ResolveDecal(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveDecalPathHook.Original(drawObject, path, unk3, unk4)); + private nint ResolveDecal(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) + => ResolvePath(drawObject, _resolveDecalPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); - private nint ResolveEid(nint drawObject, nint path, nint unk3) - => ResolvePath(drawObject, _resolveEidPathHook.Original(drawObject, path, unk3)); + private nint ResolveEid(nint drawObject, nint pathBuffer, nint pathBufferSize) + => ResolvePath(drawObject, _resolveEidPathHook.Original(drawObject, pathBuffer, pathBufferSize)); - private nint ResolveImc(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveImcPathHook.Original(drawObject, path, unk3, unk4)); + private nint ResolveImc(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) + => ResolvePath(drawObject, _resolveImcPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); - private nint ResolveMPap(nint drawObject, nint path, nint unk3, uint unk4, uint unk5) - => ResolvePath(drawObject, _resolveMPapPathHook.Original(drawObject, path, unk3, unk4, unk5)); + private nint ResolveMPap(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, uint unkSId) + => ResolvePath(drawObject, _resolveMPapPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex, unkSId)); - private nint ResolveMdl(nint drawObject, nint path, nint unk3, uint modelType) - => ResolvePath(drawObject, _resolveMdlPathHook.Original(drawObject, path, unk3, modelType)); + private nint ResolveMdl(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) + => ResolvePath(drawObject, _resolveMdlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); - private nint ResolveMtrl(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) - => ResolvePath(drawObject, _resolveMtrlPathHook.Original(drawObject, path, unk3, unk4, unk5)); + private nint ResolveMtrl(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint mtrlFileName) + => ResolvePath(drawObject, _resolveMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex, mtrlFileName)); - private nint ResolvePap(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) - => ResolvePath(drawObject, _resolvePapPathHook.Original(drawObject, path, unk3, unk4, unk5)); + private nint ResolvePap(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) + => ResolvePath(drawObject, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); - private nint ResolvePhyb(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolvePhybPathHook.Original(drawObject, path, unk3, unk4)); + private nint ResolvePhyb(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + => ResolvePath(drawObject, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); - private nint ResolveSklb(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveSklbPathHook.Original(drawObject, path, unk3, unk4)); + private nint ResolveSklb(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + => ResolvePath(drawObject, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); - private nint ResolveSkp(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveSkpPathHook.Original(drawObject, path, unk3, unk4)); + private nint ResolveSkp(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + => ResolvePath(drawObject, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); - private nint ResolveTmb(nint drawObject, nint path, nint unk3) - => ResolvePath(drawObject, _resolveTmbPathHook.Original(drawObject, path, unk3)); + private nint ResolveTmb(nint drawObject, nint pathBuffer, nint pathBufferSize, nint timelineName) + => ResolvePath(drawObject, _resolveTmbPathHook.Original(drawObject, pathBuffer, pathBufferSize, timelineName)); - private nint ResolveVfx(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) - => ResolvePath(drawObject, _resolveVfxPathHook.Original(drawObject, path, unk3, unk4, unk5)); + private nint ResolveVfx(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) + => ResolvePath(drawObject, _resolveVfxPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam)); - private nint ResolveMdlHuman(nint drawObject, nint path, nint unk3, uint modelType) + private nint ResolveMdlHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) { var data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var eqdp = modelType > 9 + using var eqdp = slotIndex > 9 ? DisposableContainer.Empty - : _parent.MetaState.ResolveEqdpData(data.ModCollection, MetaState.GetHumanGenderRace(drawObject), modelType < 5, modelType > 4); - return ResolvePath(data, _resolveMdlPathHook.Original(drawObject, path, unk3, modelType)); + : _parent.MetaState.ResolveEqdpData(data.ModCollection, MetaState.GetHumanGenderRace(drawObject), slotIndex < 5, slotIndex > 4); + return ResolvePath(data, _resolveMdlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); } - private nint ResolvePapHuman(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) + private nint ResolvePapHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) { using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolvePapPathHook.Original(drawObject, path, unk3, unk4, unk5)); + return ResolvePath(data, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); } - private nint ResolvePhybHuman(nint drawObject, nint path, nint unk3, uint unk4) + private nint ResolvePhybHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolvePhybPathHook.Original(drawObject, path, unk3, unk4)); + return ResolvePath(data, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } - private nint ResolveSklbHuman(nint drawObject, nint path, nint unk3, uint unk4) + private nint ResolveSklbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolveSklbPathHook.Original(drawObject, path, unk3, unk4)); + return ResolvePath(data, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } - private nint ResolveSkpHuman(nint drawObject, nint path, nint unk3, uint unk4) + private nint ResolveSkpHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolveSkpPathHook.Original(drawObject, path, unk3, unk4)); + return ResolvePath(data, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } private DisposableContainer GetEstChanges(nint drawObject, out ResolveData data) @@ -180,58 +182,21 @@ public unsafe class ResolvePathHooks : IDisposable data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Head)); } - private nint ResolveDecalWeapon(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveDecalPathHook.Original(drawObject, path, unk3, unk4)); - - private nint ResolveEidWeapon(nint drawObject, nint path, nint unk3) - => ResolvePath(drawObject, _resolveEidPathHook.Original(drawObject, path, unk3)); - - private nint ResolveImcWeapon(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveImcPathHook.Original(drawObject, path, unk3, unk4)); - - private nint ResolveMPapWeapon(nint drawObject, nint path, nint unk3, uint unk4, uint unk5) - => ResolvePath(drawObject, _resolveMPapPathHook.Original(drawObject, path, unk3, unk4, unk5)); - - private nint ResolveMdlWeapon(nint drawObject, nint path, nint unk3, uint modelType) - => ResolvePath(drawObject, _resolveMdlPathHook.Original(drawObject, path, unk3, modelType)); - - private nint ResolveMtrlWeapon(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) - => ResolvePath(drawObject, _resolveMtrlPathHook.Original(drawObject, path, unk3, unk4, unk5)); - - private nint ResolvePapWeapon(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) - => ResolvePath(drawObject, _resolvePapPathHook.Original(drawObject, path, unk3, unk4, unk5)); - - private nint ResolvePhybWeapon(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolvePhybPathHook.Original(drawObject, path, unk3, unk4)); - - private nint ResolveSklbWeapon(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveSklbPathHook.Original(drawObject, path, unk3, unk4)); - - private nint ResolveSkpWeapon(nint drawObject, nint path, nint unk3, uint unk4) - => ResolvePath(drawObject, _resolveSkpPathHook.Original(drawObject, path, unk3, unk4)); - - private nint ResolveTmbWeapon(nint drawObject, nint path, nint unk3) - => ResolvePath(drawObject, _resolveTmbPathHook.Original(drawObject, path, unk3)); - - private nint ResolveVfxWeapon(nint drawObject, nint path, nint unk3, uint unk4, ulong unk5) - => ResolvePath(drawObject, _resolveVfxPathHook.Original(drawObject, path, unk3, unk4, unk5)); - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(IGameInteropProvider interop, nint address, Type type, T weapon, T other, T human) where T : Delegate + private static Hook Create(IGameInteropProvider interop, nint address, Type type, T other, T human) where T : Delegate { var del = type switch { Type.Human => human, - Type.Weapon => weapon, _ => other, }; return interop.HookFromAddress(address, del); } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(IGameInteropProvider interop, nint address, Type type, T weapon, T other) where T : Delegate - => Create(interop, address, type, weapon, other, other); + private static Hook Create(IGameInteropProvider interop, nint address, T del) where T : Delegate + => interop.HookFromAddress(address, del); // Implementation From 7dabb3c647b08848dfa99915f2e46e1e746a7b29 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 3 Nov 2023 15:23:48 +0100 Subject: [PATCH 0191/1381] Add some Redrawing Debug UI. --- Penumbra/Interop/Services/RedrawService.cs | 16 +++++++- Penumbra/UI/Tabs/DebugTab.cs | 46 +++++++++++++++++++++- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 5cc493ad..ec858290 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -18,10 +18,13 @@ public unsafe partial class RedrawService public const int GPoseSlots = 42; public const int GPoseEndIdx = GPosePlayerIdx + GPoseSlots; - private readonly string?[] _gPoseNames = new string?[GPoseSlots]; + private readonly string?[] _gPoseNames = new string?[GPoseSlots]; private int _gPoseNameCounter; - private bool InGPose + internal IReadOnlyList GPoseNames + => _gPoseNames; + + internal bool InGPose => _clientState.IsGPosing; // VFuncs that disable and enable draw, used only for GPose actors. @@ -108,6 +111,15 @@ public sealed unsafe partial class RedrawService : IDisposable private readonly List _afterGPoseQueue = new(GPoseSlots); private int _target = -1; + internal IReadOnlyList Queue + => _queue; + + internal IReadOnlyList AfterGPoseQueue + => _afterGPoseQueue; + + internal int Target + => _target; + public event GameObjectRedrawnDelegate? GameObjectRedrawn; public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions, IClientState clientState) diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index 5abb3c2f..dc39707a 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -65,6 +65,7 @@ public class DebugTab : Window, ITab private readonly TextureManager _textureManager; private readonly SkinFixer _skinFixer; private readonly IdentifierService _identifier; + private readonly RedrawService _redraws; public DebugTab(StartTracker timer, PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorService actorService, @@ -72,7 +73,7 @@ public class DebugTab : Window, ITab ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager, SkinFixer skinFixer, IdentifierService identifier) + TextureManager textureManager, SkinFixer skinFixer, IdentifierService identifier, RedrawService redraws) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -107,6 +108,7 @@ public class DebugTab : Window, ITab _textureManager = textureManager; _skinFixer = skinFixer; _identifier = identifier; + _redraws = redraws; } public ReadOnlySpan Label @@ -317,6 +319,48 @@ public class DebugTab : Window, ITab } } } + + using (var tree = TreeNode("Redraw Service")) + { + if (tree) + { + using var table = Table("##redraws", 3, ImGuiTableFlags.RowBg); + if (table) + { + ImGuiUtil.DrawTableColumn("In GPose"); + ImGuiUtil.DrawTableColumn(_redraws.InGPose.ToString()); + ImGui.TableNextColumn(); + + ImGuiUtil.DrawTableColumn("Target"); + ImGuiUtil.DrawTableColumn(_redraws.Target.ToString()); + ImGui.TableNextColumn(); + + foreach (var (objectIdx, idx) in _redraws.Queue.WithIndex()) + { + var (actualIdx, state) = objectIdx < 0 ? (~objectIdx, "Queued") : (objectIdx, "Invisible"); + ImGuiUtil.DrawTableColumn($"Redraw Queue #{idx}"); + ImGuiUtil.DrawTableColumn(actualIdx.ToString()); + ImGuiUtil.DrawTableColumn(state); + } + + foreach (var (objectIdx, idx) in _redraws.AfterGPoseQueue.WithIndex()) + { + var (actualIdx, state) = objectIdx < 0 ? (~objectIdx, "Queued") : (objectIdx, "Invisible"); + ImGuiUtil.DrawTableColumn($"GPose Queue #{idx}"); + ImGuiUtil.DrawTableColumn(actualIdx.ToString()); + ImGuiUtil.DrawTableColumn(state); + } + + foreach (var (name, idx) in _redraws.GPoseNames.OfType().WithIndex()) + { + ImGuiUtil.DrawTableColumn($"GPose Name #{idx}"); + ImGuiUtil.DrawTableColumn(name); + ImGui.TableNextColumn(); + } + + } + } + } } private void DrawPerformanceTab() From 2852562a03d4a09043691eeb2f5dad28ba956c30 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 2 Nov 2023 22:41:20 +0100 Subject: [PATCH 0192/1381] ResourceTree: Use ResolveXXXPath where possible --- Penumbra.GameData | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 35 +++++++---- Penumbra/Interop/ResourceTree/ResourceTree.cs | 59 ++++++++++++------ .../Interop/Structs/CharacterBaseUtility.cs | 62 +++++++++++++++++++ 4 files changed, 125 insertions(+), 33 deletions(-) create mode 100644 Penumbra/Interop/Structs/CharacterBaseUtility.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 04ddadb4..b141301c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 04ddadb44600a382e26661e1db08fd16c3b671d8 +Subproject commit b141301c4ee65422d6802f3038c8f344911d4ae2 diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 26d64afe..d700131d 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -1,6 +1,8 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using FFXIVClientStructs.Interop; using OtterGui; using Penumbra.Api.Enums; using Penumbra.GameData; @@ -9,6 +11,7 @@ using Penumbra.GameData.Structs; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; +using static Penumbra.Interop.Structs.CharacterBaseUtility; using static Penumbra.Interop.Structs.StructExtensions; namespace Penumbra.Interop.ResourceTree; @@ -18,11 +21,11 @@ internal record GlobalResolveContext(IObjectIdentifier Identifier, TreeBuildCach { public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); - public ResolveContext CreateContext(EquipSlot slot, CharacterArmor equipment) - => new(this, slot, equipment); + public unsafe ResolveContext CreateContext(CharacterBase* characterBase, uint slotIndex, EquipSlot slot, CharacterArmor equipment) + => new(this, characterBase, slotIndex, slot, equipment); } -internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, CharacterArmor Equipment) +internal record ResolveContext(GlobalResolveContext Global, Pointer CharacterBase, uint SlotIndex, EquipSlot Slot, CharacterArmor Equipment) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); @@ -112,7 +115,8 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (eid == null) return null; - var path = Utf8GamePath.Empty; // TODO + if (!Utf8GamePath.FromByteString(ResolveEidPath(CharacterBase), out var path)) + return null; return GetOrCreateNode(ResourceType.Eid, 0, eid, path); } @@ -122,17 +126,19 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (imc == null) return null; - var path = Utf8GamePath.Empty; // TODO + if (!Utf8GamePath.FromByteString(ResolveImcPath(CharacterBase, SlotIndex), out var path)) + return null; return GetOrCreateNode(ResourceType.Imc, 0, imc, path); } - public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex) + public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, string gamePath) { if (tex == null) return null; - var path = Utf8GamePath.Empty; // TODO + if (!Utf8GamePath.FromString(gamePath, out var path)) + return null; return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, path); } @@ -142,7 +148,8 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char if (mdl == null || mdl->ModelResourceHandle == null) return null; - var path = Utf8GamePath.Empty; // TODO + if (!Utf8GamePath.FromByteString(ResolveMdlPath(CharacterBase, SlotIndex), out var path)) + return null; if (Global.Nodes.TryGetValue((path, (nint)mdl->ModelResourceHandle), out var cached)) return cached; @@ -253,12 +260,13 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char return node; } - public unsafe ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb) + public unsafe ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) { if (sklb == null || sklb->SkeletonResourceHandle == null) return null; - var path = Utf8GamePath.Empty; // TODO + if (!Utf8GamePath.FromByteString(ResolveSklbPath(CharacterBase, partialSkeletonIndex), out var path)) + return null; if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonResourceHandle), out var cached)) return cached; @@ -266,7 +274,7 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); if (node != null) { - var skpNode = CreateParameterNodeFromPartialSkeleton(sklb); + var skpNode = CreateParameterNodeFromPartialSkeleton(sklb, partialSkeletonIndex); if (skpNode != null) node.Children.Add(skpNode); Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); @@ -275,12 +283,13 @@ internal record ResolveContext(GlobalResolveContext Global, EquipSlot Slot, Char return node; } - private unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb) + private unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) { if (sklb == null || sklb->SkeletonParameterResourceHandle == null) return null; - var path = Utf8GamePath.Empty; // TODO + if (!Utf8GamePath.FromByteString(ResolveSkpPath(CharacterBase, partialSkeletonIndex), out var path)) + return null; if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonParameterResourceHandle), out var cached)) return cached; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 687c14ec..7c58d6a8 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,7 +1,9 @@ +using Dalamud.Game.ClientState.Objects.Enums; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.UI; @@ -62,8 +64,10 @@ public class ResourceTree CustomizeData = character->DrawData.CustomizeData; RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; + var genericContext = globalContext.CreateContext(model, 0xFFFFFFFFu, EquipSlot.Unknown, default); + var eid = (ResourceHandle*)model->EID; - var eidNode = globalContext.CreateContext(EquipSlot.Unknown, default).CreateNodeFromEid(eid); + var eidNode = genericContext.CreateNodeFromEid(eid); if (eidNode != null) { if (globalContext.WithUiData) @@ -73,13 +77,15 @@ public class ResourceTree for (var i = 0; i < model->SlotCount; ++i) { - var context = globalContext.CreateContext( + var slotContext = globalContext.CreateContext( + model, + (uint)i, i < equipment.Length ? ((uint)i).ToEquipSlot() : EquipSlot.Unknown, i < equipment.Length ? equipment[i] : default ); var imc = (ResourceHandle*)model->IMCArray[i]; - var imcNode = context.CreateNodeFromImc(imc); + var imcNode = slotContext.CreateNodeFromImc(imc); if (imcNode != null) { if (globalContext.WithUiData) @@ -88,7 +94,7 @@ public class ResourceTree } var mdl = model->Models[i]; - var mdlNode = context.CreateNodeFromRenderModel(mdl); + var mdlNode = slotContext.CreateNodeFromRenderModel(mdl); if (mdlNode != null) { if (globalContext.WithUiData) @@ -97,18 +103,20 @@ public class ResourceTree } } - AddSkeleton(Nodes, globalContext.CreateContext(EquipSlot.Unknown, default), model->Skeleton); + AddSkeleton(Nodes, genericContext, model->Skeleton); + + AddSubObjects(globalContext, model); if (human != null) AddHumanResources(globalContext, human); } - private unsafe void AddHumanResources(GlobalResolveContext globalContext, Human* human) + private unsafe void AddSubObjects(GlobalResolveContext globalContext, CharacterBase* model) { var subObjectIndex = 0; var weaponIndex = 0; var subObjectNodes = new List(); - foreach (var baseSubObject in human->CharacterBase.DrawObject.Object.ChildObjects) + foreach (var baseSubObject in model->DrawObject.Object.ChildObjects) { if (baseSubObject->GetObjectType() != FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType.CharacterBase) continue; @@ -117,13 +125,13 @@ public class ResourceTree var weapon = subObject->GetModelType() == CharacterBase.ModelType.Weapon ? (Weapon*)subObject : null; var subObjectNamePrefix = weapon != null ? "Weapon" : "Fashion Acc."; // This way to tell apart MainHand and OffHand is not always accurate, but seems good enough for what we're doing with it. - var subObjectContext = globalContext.CreateContext( - weapon != null ? (weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand) : EquipSlot.Unknown, - weapon != null ? new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown) : default - ); + var slot = weapon != null ? (weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand) : EquipSlot.Unknown; + var equipment = weapon != null ? new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown) : default; + + var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment); var eid = (ResourceHandle*)subObject->EID; - var eidNode = subObjectContext.CreateNodeFromEid(eid); + var eidNode = genericContext.CreateNodeFromEid(eid); if (eidNode != null) { if (globalContext.WithUiData) @@ -133,8 +141,10 @@ public class ResourceTree for (var i = 0; i < subObject->SlotCount; ++i) { + var slotContext = globalContext.CreateContext(subObject, (uint)i, slot, equipment); + var imc = (ResourceHandle*)subObject->IMCArray[i]; - var imcNode = subObjectContext.CreateNodeFromImc(imc); + var imcNode = slotContext.CreateNodeFromImc(imc); if (imcNode != null) { if (globalContext.WithUiData) @@ -143,7 +153,7 @@ public class ResourceTree } var mdl = subObject->Models[i]; - var mdlNode = subObjectContext.CreateNodeFromRenderModel(mdl); + var mdlNode = slotContext.CreateNodeFromRenderModel(mdl); if (mdlNode != null) { if (globalContext.WithUiData) @@ -152,17 +162,24 @@ public class ResourceTree } } - AddSkeleton(subObjectNodes, subObjectContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); + AddSkeleton(subObjectNodes, genericContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); ++subObjectIndex; if (weapon != null) ++weaponIndex; } Nodes.InsertRange(0, subObjectNodes); + } - var context = globalContext.CreateContext(EquipSlot.Unknown, default); + private unsafe void AddHumanResources(GlobalResolveContext globalContext, Human* human) + { + var genericContext = globalContext.CreateContext(&human->CharacterBase, 0xFFFFFFFFu, EquipSlot.Unknown, default); - var decalNode = context.CreateNodeFromTex(human->Decal); + var decalId = (byte)(human->Customize[(int)CustomizeIndex.Facepaint] & 0x7F); + var decalPath = decalId != 0 + ? GamePaths.Human.Decal.FaceDecalPath(decalId) + : GamePaths.Tex.TransparentPath; + var decalNode = genericContext.CreateNodeFromTex(human->Decal, decalPath); if (decalNode != null) { if (globalContext.WithUiData) @@ -174,7 +191,11 @@ public class ResourceTree Nodes.Add(decalNode); } - var legacyDecalNode = context.CreateNodeFromTex(human->LegacyBodyDecal); + var hasLegacyDecal = (human->Customize[(int)CustomizeIndex.FaceFeatures] & 0x80) != 0; + var legacyDecalPath = hasLegacyDecal + ? GamePaths.Human.Decal.LegacyDecalPath + : GamePaths.Tex.TransparentPath; + var legacyDecalNode = genericContext.CreateNodeFromTex(human->LegacyBodyDecal, legacyDecalPath); if (legacyDecalNode != null) { if (globalContext.WithUiData) @@ -194,7 +215,7 @@ public class ResourceTree for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) { - var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i]); + var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], (uint)i); if (sklbNode != null) { if (context.Global.WithUiData) diff --git a/Penumbra/Interop/Structs/CharacterBaseUtility.cs b/Penumbra/Interop/Structs/CharacterBaseUtility.cs new file mode 100644 index 00000000..c29f44a3 --- /dev/null +++ b/Penumbra/Interop/Structs/CharacterBaseUtility.cs @@ -0,0 +1,62 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.String; + +namespace Penumbra.Interop.Structs; + +// TODO submit these to ClientStructs +public static unsafe class CharacterBaseUtility +{ + private const int PathBufferSize = 260; + + private const uint ResolveSklbPathVf = 72; + private const uint ResolveMdlPathVf = 73; + private const uint ResolveSkpPathVf = 74; + private const uint ResolveImcPathVf = 81; + private const uint ResolveMtrlPathVf = 82; + private const uint ResolveEidPathVf = 85; + + private static void* GetVFunc(CharacterBase* characterBase, uint vfIndex) + => ((void**)characterBase->VTable)[vfIndex]; + + private static ByteString? ResolvePath(CharacterBase* characterBase, uint vfIndex) + { + var vFunc = (delegate* unmanaged)GetVFunc(characterBase, vfIndex); + var pathBuffer = stackalloc byte[PathBufferSize]; + var path = vFunc(characterBase, pathBuffer, PathBufferSize); + return path != null ? new ByteString(path).Clone() : null; + } + + private static ByteString? ResolvePath(CharacterBase* characterBase, uint vfIndex, uint slotIndex) + { + var vFunc = (delegate* unmanaged)GetVFunc(characterBase, vfIndex); + var pathBuffer = stackalloc byte[PathBufferSize]; + var path = vFunc(characterBase, pathBuffer, PathBufferSize, slotIndex); + return path != null ? new ByteString(path).Clone() : null; + } + + private static ByteString? ResolvePath(CharacterBase* characterBase, uint vfIndex, uint slotIndex, byte* name) + { + var vFunc = (delegate* unmanaged)GetVFunc(characterBase, vfIndex); + var pathBuffer = stackalloc byte[PathBufferSize]; + var path = vFunc(characterBase, pathBuffer, PathBufferSize, slotIndex, name); + return path != null ? new ByteString(path).Clone() : null; + } + + public static ByteString? ResolveEidPath(CharacterBase* characterBase) + => ResolvePath(characterBase, ResolveEidPathVf); + + public static ByteString? ResolveImcPath(CharacterBase* characterBase, uint slotIndex) + => ResolvePath(characterBase, ResolveImcPathVf, slotIndex); + + public static ByteString? ResolveMdlPath(CharacterBase* characterBase, uint slotIndex) + => ResolvePath(characterBase, ResolveMdlPathVf, slotIndex); + + public static ByteString? ResolveMtrlPath(CharacterBase* characterBase, uint slotIndex, byte* mtrlFileName) + => ResolvePath(characterBase, ResolveMtrlPathVf, slotIndex, mtrlFileName); + + public static ByteString? ResolveSklbPath(CharacterBase* characterBase, uint partialSkeletonIndex) + => ResolvePath(characterBase, ResolveSklbPathVf, partialSkeletonIndex); + + public static ByteString? ResolveSkpPath(CharacterBase* characterBase, uint partialSkeletonIndex) + => ResolvePath(characterBase, ResolveSkpPathVf, partialSkeletonIndex); +} From fd163f8f66b1bc6edaa9a0cb2a431dcb94eef29d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 4 Nov 2023 18:30:36 +0100 Subject: [PATCH 0193/1381] ResourceTree: WIP - Path resolution --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/EstCache.cs | 21 ++ Penumbra/Collections/Cache/MetaCache.cs | 18 ++ Penumbra/Interop/PathResolving/PathState.cs | 44 +++- .../Interop/PathResolving/ResolvePathHooks.cs | 6 +- .../ResolveContext.PathResolution.cs | 248 ++++++++++++++++++ .../Interop/ResourceTree/ResolveContext.cs | 105 +++----- Penumbra/Interop/ResourceTree/ResourceTree.cs | 88 +++---- .../ResourceTree/ResourceTreeFactory.cs | 33 ++- .../Structs/ModelResourceHandleUtility.cs | 18 ++ Penumbra/Meta/Files/ImcFile.cs | 7 + Penumbra/Penumbra.cs | 1 + Penumbra/Services/ServiceManager.cs | 3 +- 13 files changed, 452 insertions(+), 142 deletions(-) create mode 100644 Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs create mode 100644 Penumbra/Interop/Structs/ModelResourceHandleUtility.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index b141301c..1f274b41 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b141301c4ee65422d6802f3038c8f344911d4ae2 +Subproject commit 1f274b41e3e703712deb83f3abd8727e10614ebe diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 43ebcf56..9e2cdef9 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -1,5 +1,6 @@ using OtterGui.Filesystem; using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta; @@ -61,6 +62,26 @@ public struct EstCache : IDisposable return manager.TemporarilySetFile(file, idx); } + private readonly EstFile? GetEstFile(EstManipulation.EstType type) + { + return type switch + { + EstManipulation.EstType.Face => _estFaceFile, + EstManipulation.EstType.Hair => _estHairFile, + EstManipulation.EstType.Body => _estBodyFile, + EstManipulation.EstType.Head => _estHeadFile, + _ => null, + }; + } + + internal ushort GetEstEntry(MetaFileManager manager, EstManipulation.EstType type, GenderRace genderRace, SetId setId) + { + var file = GetEstFile(type); + return file != null + ? file[genderRace, setId.Id] + : EstFile.GetDefault(manager, type, genderRace, setId); + } + public void Reset() { _estFaceFile?.Reset(); diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 8eb7a5a0..0da11022 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,4 +1,5 @@ using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta; @@ -186,6 +187,23 @@ public class MetaCache : IDisposable, IEnumerable _imcCache.GetImcFile(path, out file); + public ImcEntry GetImcEntry(Utf8GamePath path, EquipSlot slot, Variant variantIdx, out bool exists) + => GetImcFile(path, out var file) + ? file.GetEntry(Meta.Files.ImcFile.PartIndex(slot), variantIdx, out exists) + : Meta.Files.ImcFile.GetDefault(_manager, path, slot, variantIdx, out exists); + + internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, SetId setId) + { + var eqdpFile = _eqdpCache.EqdpFile(race, accessory); + if (eqdpFile != null) + return setId.Id < eqdpFile.Count ? eqdpFile[setId] : default; + else + return Meta.Files.ExpandedEqdpFile.GetDefault(_manager, race, accessory, setId); + } + + internal ushort GetEstEntry(EstManipulation.EstType type, GenderRace genderRace, SetId setId) + => _estCache.GetEstEntry(_manager, type, genderRace, setId); + /// Use this when CharacterUtility becomes ready. private void ApplyStoredManipulations() { diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index f300a666..6d7840d8 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -30,11 +30,15 @@ public unsafe class PathState : IDisposable private readonly ResolvePathHooks _demiHuman; private readonly ResolvePathHooks _monster; - private readonly ThreadLocal _resolveData = new(() => ResolveData.Invalid, true); + private readonly ThreadLocal _resolveData = new(() => ResolveData.Invalid, true); + private readonly ThreadLocal _internalResolve = new(() => 0, false); public IList CurrentData => _resolveData.Values; + public bool InInternalResolve + => _internalResolve.Value != 0u; + public PathState(CollectionResolver collectionResolver, MetaState metaState, CharacterUtility characterUtility, IGameInteropProvider interop) { interop.InitializeFromAttributes(this); @@ -55,6 +59,7 @@ public unsafe class PathState : IDisposable public void Dispose() { _resolveData.Dispose(); + _internalResolve.Dispose(); _human.Dispose(); _weapon.Dispose(); _demiHuman.Dispose(); @@ -80,7 +85,10 @@ public unsafe class PathState : IDisposable if (path == nint.Zero) return path; - _resolveData.Value = collection.ToResolveData(gameObject); + if (!InInternalResolve) + { + _resolveData.Value = collection.ToResolveData(gameObject); + } return path; } @@ -90,7 +98,37 @@ public unsafe class PathState : IDisposable if (path == nint.Zero) return path; - _resolveData.Value = data; + if (!InInternalResolve) + { + _resolveData.Value = data; + } return path; } + + /// + /// Temporarily disables metadata mod application and resolve data capture on the current thread. + /// Must be called to prevent race conditions between Penumbra's internal path resolution (for example for Resource Trees) and the game's path resolution. + /// Please note that this will make path resolution cases that depend on metadata incorrect. + /// + /// A struct that will undo this operation when disposed. Best used with: using (var _ = pathState.EnterInternalResolve()) { ... } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public InternalResolveRaii EnterInternalResolve() + => new(this); + + public readonly ref struct InternalResolveRaii + { + private readonly ThreadLocal _internalResolve; + + public InternalResolveRaii(PathState parent) + { + _internalResolve = parent._internalResolve; + ++_internalResolve.Value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public readonly void Dispose() + { + --_internalResolve.Value; + } + } } diff --git a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs index 9d010d64..3be7ffdd 100644 --- a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs +++ b/Penumbra/Interop/PathResolving/ResolvePathHooks.cs @@ -143,7 +143,7 @@ public unsafe class ResolvePathHooks : IDisposable private nint ResolveMdlHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) { var data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var eqdp = slotIndex > 9 + using var eqdp = slotIndex > 9 || _parent.InInternalResolve ? DisposableContainer.Empty : _parent.MetaState.ResolveEqdpData(data.ModCollection, MetaState.GetHumanGenderRace(drawObject), slotIndex < 5, slotIndex > 4); return ResolvePath(data, _resolveMdlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); @@ -176,6 +176,10 @@ public unsafe class ResolvePathHooks : IDisposable private DisposableContainer GetEstChanges(nint drawObject, out ResolveData data) { data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + if (_parent.InInternalResolve) + { + return DisposableContainer.Empty; + } return new DisposableContainer(data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Face), data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Body), data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Hair), diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs new file mode 100644 index 00000000..bcc957df --- /dev/null +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -0,0 +1,248 @@ +using Dalamud.Game.ClientState.Objects.Enums; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta.Manipulations; +using Penumbra.String; +using Penumbra.String.Classes; +using static Penumbra.Interop.Structs.CharacterBaseUtility; +using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; + +namespace Penumbra.Interop.ResourceTree; + +internal partial record ResolveContext +{ + + private Utf8GamePath ResolveModelPath() + { + // Correctness: + // Resolving a model path through the game's code can use EQDP metadata for human equipment models. + return ModelType switch + { + ModelType.Human when SlotIndex < 10 => ResolveEquipmentModelPath(), + _ => ResolveModelPathNative(), + }; + } + + private Utf8GamePath ResolveEquipmentModelPath() + { + var path = SlotIndex < 5 + ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot) + : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot); + return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe GenderRace ResolveModelRaceCode() + => ResolveEqdpRaceCode(Slot, Equipment.Set); + + private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, SetId setId) + { + var slotIndex = slot.ToIndex(); + if (slotIndex >= 10 || ModelType != ModelType.Human) + return GenderRace.MidlanderMale; + + var characterRaceCode = (GenderRace)((Human*)CharacterBase.Value)->RaceSexId; + if (characterRaceCode == GenderRace.MidlanderMale) + return GenderRace.MidlanderMale; + + var accessory = slotIndex >= 5; + if ((ushort)characterRaceCode % 10 != 1 && accessory) + return GenderRace.MidlanderMale; + + var metaCache = Global.Collection.MetaCache; + if (metaCache == null) + return GenderRace.MidlanderMale; + + var entry = metaCache.GetEqdpEntry(characterRaceCode, accessory, setId); + if (entry.ToBits(slot).Item2) + return characterRaceCode; + + var fallbackRaceCode = characterRaceCode.Fallback(); + if (fallbackRaceCode == GenderRace.MidlanderMale) + return GenderRace.MidlanderMale; + + entry = metaCache.GetEqdpEntry(fallbackRaceCode, accessory, setId); + if (entry.ToBits(slot).Item2) + return fallbackRaceCode; + + return GenderRace.MidlanderMale; + } + + private unsafe Utf8GamePath ResolveModelPathNative() + { + var path = ResolveMdlPath(CharacterBase, SlotIndex); + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolveMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) + { + // Safety: + // Resolving a material path through the game's code can dereference null pointers for equipment materials. + return ModelType switch + { + ModelType.Human when SlotIndex < 10 && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), + ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), + ModelType.Weapon => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), + _ => ResolveMaterialPathNative(mtrlFileName), + }; + } + + private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) + { + var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); + var modelPathSpan = modelPath.Path.Span; + var baseDirectory = modelPathSpan[..modelPathSpan.IndexOf("/model/"u8)]; + + var variant = ResolveMaterialVariant(imcPath); + + Span pathBuffer = stackalloc byte[260]; + baseDirectory.CopyTo(pathBuffer); + "/material/v"u8.CopyTo(pathBuffer[baseDirectory.Length..]); + WriteZeroPaddedNumber(pathBuffer.Slice(baseDirectory.Length + 11, 4), variant); + pathBuffer[baseDirectory.Length + 15] = (byte)'/'; + fileName.CopyTo(pathBuffer[(baseDirectory.Length + 16)..]); + + return Utf8GamePath.FromSpan(pathBuffer[..(baseDirectory.Length + 16 + fileName.Length)], out var path) ? path.Clone() : Utf8GamePath.Empty; + } + + private byte ResolveMaterialVariant(Utf8GamePath imcPath) + { + var metaCache = Global.Collection.MetaCache; + if (metaCache == null) + return Equipment.Variant.Id; + + var entry = metaCache.GetImcEntry(imcPath, Slot, Equipment.Variant, out var exists); + if (!exists) + return Equipment.Variant.Id; + + return entry.MaterialId; + } + + private static void WriteZeroPaddedNumber(Span destination, ushort number) + { + for (var i = destination.Length; i-- > 0;) + { + destination[i] = (byte)('0' + number % 10); + number /= 10; + } + } + + private unsafe Utf8GamePath ResolveMaterialPathNative(byte* mtrlFileName) + { + ByteString? path; + try + { + path = ResolveMtrlPath(CharacterBase, SlotIndex, mtrlFileName); + } + catch (AccessViolationException) + { + Penumbra.Log.Error($"Access violation during attempt to resolve material path\nDraw object: {(nint)CharacterBase.Value:X} (of type {ModelType})\nSlot index: {SlotIndex}\nMaterial file name: {(nint)mtrlFileName:X} ({new string((sbyte*)mtrlFileName)})"); + return Utf8GamePath.Empty; + } + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private Utf8GamePath ResolveSkeletonPath(uint partialSkeletonIndex) + { + // Correctness and Safety: + // Resolving a skeleton path through the game's code can use EST metadata for human skeletons. + // Additionally, it can dereference null pointers for human equipment skeletons. + return ModelType switch + { + ModelType.Human => ResolveHumanSkeletonPath(partialSkeletonIndex), + _ => ResolveSkeletonPathNative(partialSkeletonIndex), + }; + } + + private unsafe Utf8GamePath ResolveHumanSkeletonPath(uint partialSkeletonIndex) + { + var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); + if (set == 0) + return Utf8GamePath.Empty; + + var path = GamePaths.Skeleton.Sklb.Path(raceCode, slot, set); + return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe (GenderRace RaceCode, string Slot, SetId Set) ResolveHumanSkeletonData(uint partialSkeletonIndex) + { + var human = (Human*)CharacterBase.Value; + var characterRaceCode = (GenderRace)human->RaceSexId; + switch (partialSkeletonIndex) + { + case 0: + return (characterRaceCode, "base", 1); + case 1: + var faceId = human->FaceId; + var tribe = human->Customize[(int)CustomizeIndex.Tribe]; + var modelType = human->Customize[(int)CustomizeIndex.ModelType]; + if (faceId < 201) + { + faceId -= tribe switch + { + 0xB when modelType == 4 => 100, + 0xE | 0xF => 100, + _ => 0, + }; + } + return ResolveHumanExtraSkeletonData(characterRaceCode, EstManipulation.EstType.Face, faceId); + case 2: + return ResolveHumanExtraSkeletonData(characterRaceCode, EstManipulation.EstType.Hair, human->HairId); + case 3: + return ResolveHumanEquipmentSkeletonData(EquipSlot.Head, EstManipulation.EstType.Head); + case 4: + return ResolveHumanEquipmentSkeletonData(EquipSlot.Body, EstManipulation.EstType.Body); + default: + return (0, string.Empty, 0); + } + } + + private unsafe (GenderRace RaceCode, string Slot, SetId Set) ResolveHumanEquipmentSkeletonData(EquipSlot slot, EstManipulation.EstType type) + { + var human = (Human*)CharacterBase.Value; + var equipment = ((CharacterArmor*)&human->Head)[slot.ToIndex()]; + return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot, equipment.Set), type, equipment.Set); + } + + private unsafe (GenderRace RaceCode, string Slot, SetId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstManipulation.EstType type, SetId set) + { + var metaCache = Global.Collection.MetaCache; + var skeletonSet = metaCache == null ? default : metaCache.GetEstEntry(type, raceCode, set); + return (raceCode, EstManipulation.ToName(type), skeletonSet); + } + + private unsafe Utf8GamePath ResolveSkeletonPathNative(uint partialSkeletonIndex) + { + var path = ResolveSklbPath(CharacterBase, partialSkeletonIndex); + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private Utf8GamePath ResolveSkeletonParameterPath(uint partialSkeletonIndex) + { + // Correctness and Safety: + // Resolving a skeleton parameter path through the game's code can use EST metadata for human skeletons. + // Additionally, it can dereference null pointers for human equipment skeletons. + return ModelType switch + { + ModelType.Human => ResolveHumanSkeletonParameterPath(partialSkeletonIndex), + _ => ResolveSkeletonParameterPathNative(partialSkeletonIndex), + }; + } + + private Utf8GamePath ResolveHumanSkeletonParameterPath(uint partialSkeletonIndex) + { + var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); + if (set == 0) + return Utf8GamePath.Empty; + + var path = GamePaths.Skeleton.Skp.Path(raceCode, slot, set); + return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolveSkeletonParameterPathNative(uint partialSkeletonIndex) + { + var path = ResolveSkpPath(CharacterBase, partialSkeletonIndex); + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } +} diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index d700131d..f34a6ae2 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -5,6 +5,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; using OtterGui; using Penumbra.Api.Enums; +using Penumbra.Collections; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -12,23 +13,29 @@ using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; using static Penumbra.Interop.Structs.CharacterBaseUtility; +using static Penumbra.Interop.Structs.ModelResourceHandleUtility; using static Penumbra.Interop.Structs.StructExtensions; +using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; namespace Penumbra.Interop.ResourceTree; -internal record GlobalResolveContext(IObjectIdentifier Identifier, TreeBuildCache TreeBuildCache, - int Skeleton, bool WithUiData) +internal record GlobalResolveContext(IObjectIdentifier Identifier, ModCollection Collection, TreeBuildCache TreeBuildCache, bool WithUiData) { public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); - public unsafe ResolveContext CreateContext(CharacterBase* characterBase, uint slotIndex, EquipSlot slot, CharacterArmor equipment) - => new(this, characterBase, slotIndex, slot, equipment); + public unsafe ResolveContext CreateContext(CharacterBase* characterBase, uint slotIndex = 0xFFFFFFFFu, + EquipSlot slot = EquipSlot.Unknown, CharacterArmor equipment = default, WeaponType weaponType = default) + => new(this, characterBase, slotIndex, slot, equipment, weaponType); } -internal record ResolveContext(GlobalResolveContext Global, Pointer CharacterBase, uint SlotIndex, EquipSlot Slot, CharacterArmor Equipment) +internal partial record ResolveContext(GlobalResolveContext Global, Pointer CharacterBase, uint SlotIndex, + EquipSlot Slot, CharacterArmor Equipment, WeaponType WeaponType) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); + private unsafe ModelType ModelType + => CharacterBase.Value->GetModelType(); + private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath) { if (resourceHandle == null) @@ -46,35 +53,33 @@ internal record ResolveContext(GlobalResolveContext Global, Pointer gamePath.Length - 3) return null; - if (gamePath[lastDirectorySeparator + 1] != (byte)'-' || gamePath[lastDirectorySeparator + 2] != (byte)'-') - { - Span prefixed = stackalloc byte[gamePath.Length + 2]; - gamePath.Span[..(lastDirectorySeparator + 1)].CopyTo(prefixed); - prefixed[lastDirectorySeparator + 1] = (byte)'-'; - prefixed[lastDirectorySeparator + 2] = (byte)'-'; - gamePath.Span[(lastDirectorySeparator + 1)..].CopyTo(prefixed[(lastDirectorySeparator + 3)..]); + Span prefixed = stackalloc byte[260]; + gamePath.Span[..(lastDirectorySeparator + 1)].CopyTo(prefixed); + prefixed[lastDirectorySeparator + 1] = (byte)'-'; + prefixed[lastDirectorySeparator + 2] = (byte)'-'; + gamePath.Span[(lastDirectorySeparator + 1)..].CopyTo(prefixed[(lastDirectorySeparator + 3)..]); - if (!Utf8GamePath.FromSpan(prefixed, out var tmp)) - return null; + if (!Utf8GamePath.FromSpan(prefixed[..(gamePath.Length + 2)], out var tmp)) + return null; - gamePath = tmp.Path.Clone(); - } + path = tmp.Clone(); } else { // Make sure the game path is owned, otherwise stale trees could cause crashes (access violations) or other memory safety issues. if (!gamePath.IsOwned) gamePath = gamePath.Clone(); - } - if (!Utf8GamePath.FromByteString(gamePath, out var path)) - return null; + if (!Utf8GamePath.FromByteString(gamePath, out path)) + return null; + } return GetOrCreateNode(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path); } @@ -143,23 +148,28 @@ internal record ResolveContext(GlobalResolveContext Global, PointerTexture, &tex->ResourceHandle, path); } - public unsafe ResourceNode? CreateNodeFromRenderModel(Model* mdl) + public unsafe ResourceNode? CreateNodeFromModel(Model* mdl, Utf8GamePath imcPath) { if (mdl == null || mdl->ModelResourceHandle == null) return null; + var mdlResource = mdl->ModelResourceHandle; if (!Utf8GamePath.FromByteString(ResolveMdlPath(CharacterBase, SlotIndex), out var path)) return null; - if (Global.Nodes.TryGetValue((path, (nint)mdl->ModelResourceHandle), out var cached)) + if (Global.Nodes.TryGetValue((path, (nint)mdlResource), out var cached)) return cached; - var node = CreateNode(ResourceType.Mdl, (nint)mdl, &mdl->ModelResourceHandle->ResourceHandle, path, false); + var node = CreateNode(ResourceType.Mdl, (nint)mdl, &mdlResource->ResourceHandle, path, false); for (var i = 0; i < mdl->MaterialCount; i++) { - var mtrl = mdl->Materials[i]; - var mtrlNode = CreateNodeFromMaterial(mtrl); + var mtrl = mdl->Materials[i]; + if (mtrl == null) + continue; + + var mtrlFileName = GetMaterialFileNameBySlot(mdlResource, (uint)i); + var mtrlNode = CreateNodeFromMaterial(mtrl, ResolveMaterialPath(path, imcPath, mtrlFileName)); if (mtrlNode != null) { if (Global.WithUiData) @@ -173,7 +183,7 @@ internal record ResolveContext(GlobalResolveContext Global, Pointer alreadyVisitedSamplerIds) { @@ -200,8 +210,6 @@ internal record ResolveContext(GlobalResolveContext Global, PointerMaterialResourceHandle == null) return null; - var path = Utf8GamePath.Empty; // TODO - var resource = mtrl->MaterialResourceHandle; if (Global.Nodes.TryGetValue((path, (nint)resource), out var cached)) return cached; @@ -265,8 +273,7 @@ internal record ResolveContext(GlobalResolveContext Global, PointerSkeletonResourceHandle == null) return null; - if (!Utf8GamePath.FromByteString(ResolveSklbPath(CharacterBase, partialSkeletonIndex), out var path)) - return null; + var path = ResolveSkeletonPath(partialSkeletonIndex); if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonResourceHandle), out var cached)) return cached; @@ -288,8 +295,7 @@ internal record ResolveContext(GlobalResolveContext Global, PointerSkeletonParameterResourceHandle == null) return null; - if (!Utf8GamePath.FromByteString(ResolveSkpPath(CharacterBase, partialSkeletonIndex), out var path)) - return null; + var path = ResolveSkeletonParameterPath(partialSkeletonIndex); if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonParameterResourceHandle), out var cached)) return cached; @@ -305,43 +311,6 @@ internal record ResolveContext(GlobalResolveContext Global, Pointer FilterGamePaths(IReadOnlyCollection gamePaths) - { - var filtered = new List(gamePaths.Count); - foreach (var path in gamePaths) - { - // In doubt, keep the paths. - if (IsMatch(path.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries)) - ?? true) - filtered.Add(path); - } - - return filtered; - } - - private bool? IsMatch(ReadOnlySpan path) - => SafeGet(path, 0) switch - { - "chara" => SafeGet(path, 1) switch - { - "accessory" => IsMatchEquipment(path[2..], $"a{Equipment.Set.Id:D4}"), - "equipment" => IsMatchEquipment(path[2..], $"e{Equipment.Set.Id:D4}"), - "monster" => SafeGet(path, 2) == $"m{Global.Skeleton:D4}", - "weapon" => IsMatchEquipment(path[2..], $"w{Equipment.Set.Id:D4}"), - _ => null, - }, - _ => null, - }; - - private bool? IsMatchEquipment(ReadOnlySpan path, string equipmentDir) - => SafeGet(path, 0) == equipmentDir - ? SafeGet(path, 1) switch - { - "material" => SafeGet(path, 2) == $"v{Equipment.Variant.Id:D4}", - _ => null, - } - : false; - internal ResourceNode.UiData GuessModelUIData(Utf8GamePath gamePath) { var path = gamePath.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries); diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 7c58d6a8..5e96d8bf 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -6,6 +6,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.String.Classes; using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; @@ -64,25 +65,13 @@ public class ResourceTree CustomizeData = character->DrawData.CustomizeData; RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; - var genericContext = globalContext.CreateContext(model, 0xFFFFFFFFu, EquipSlot.Unknown, default); - - var eid = (ResourceHandle*)model->EID; - var eidNode = genericContext.CreateNodeFromEid(eid); - if (eidNode != null) - { - if (globalContext.WithUiData) - eidNode.FallbackName = "EID"; - Nodes.Add(eidNode); - } + var genericContext = globalContext.CreateContext(model); for (var i = 0; i < model->SlotCount; ++i) { - var slotContext = globalContext.CreateContext( - model, - (uint)i, - i < equipment.Length ? ((uint)i).ToEquipSlot() : EquipSlot.Unknown, - i < equipment.Length ? equipment[i] : default - ); + var slotContext = i < equipment.Length + ? globalContext.CreateContext(model, (uint)i, ((uint)i).ToEquipSlot(), equipment[i]) + : globalContext.CreateContext(model, (uint)i); var imc = (ResourceHandle*)model->IMCArray[i]; var imcNode = slotContext.CreateNodeFromImc(imc); @@ -94,7 +83,7 @@ public class ResourceTree } var mdl = model->Models[i]; - var mdlNode = slotContext.CreateNodeFromRenderModel(mdl); + var mdlNode = slotContext.CreateNodeFromModel(mdl, imcNode?.GamePath ?? Utf8GamePath.Empty); if (mdlNode != null) { if (globalContext.WithUiData) @@ -103,77 +92,68 @@ public class ResourceTree } } - AddSkeleton(Nodes, genericContext, model->Skeleton); + AddSkeleton(Nodes, genericContext, model->EID, model->Skeleton); - AddSubObjects(globalContext, model); + AddWeapons(globalContext, model); if (human != null) AddHumanResources(globalContext, human); } - private unsafe void AddSubObjects(GlobalResolveContext globalContext, CharacterBase* model) + private unsafe void AddWeapons(GlobalResolveContext globalContext, CharacterBase* model) { - var subObjectIndex = 0; - var weaponIndex = 0; - var subObjectNodes = new List(); + var weaponIndex = 0; + var weaponNodes = new List(); foreach (var baseSubObject in model->DrawObject.Object.ChildObjects) { if (baseSubObject->GetObjectType() != FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType.CharacterBase) continue; var subObject = (CharacterBase*)baseSubObject; - var weapon = subObject->GetModelType() == CharacterBase.ModelType.Weapon ? (Weapon*)subObject : null; - var subObjectNamePrefix = weapon != null ? "Weapon" : "Fashion Acc."; + if (subObject->GetModelType() != CharacterBase.ModelType.Weapon) + continue; + var weapon = (Weapon*)subObject; + // This way to tell apart MainHand and OffHand is not always accurate, but seems good enough for what we're doing with it. - var slot = weapon != null ? (weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand) : EquipSlot.Unknown; - var equipment = weapon != null ? new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown) : default; + var slot = weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand; + var equipment = new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown); + var weaponType = weapon->SecondaryId; - var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment); - - var eid = (ResourceHandle*)subObject->EID; - var eidNode = genericContext.CreateNodeFromEid(eid); - if (eidNode != null) - { - if (globalContext.WithUiData) - eidNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, EID"; - Nodes.Add(eidNode); - } + var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment, weaponType); for (var i = 0; i < subObject->SlotCount; ++i) { - var slotContext = globalContext.CreateContext(subObject, (uint)i, slot, equipment); + var slotContext = globalContext.CreateContext(subObject, (uint)i, slot, equipment, weaponType); var imc = (ResourceHandle*)subObject->IMCArray[i]; var imcNode = slotContext.CreateNodeFromImc(imc); if (imcNode != null) { if (globalContext.WithUiData) - imcNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, IMC #{i}"; - subObjectNodes.Add(imcNode); + imcNode.FallbackName = $"Weapon #{weaponIndex}, IMC #{i}"; + weaponNodes.Add(imcNode); } var mdl = subObject->Models[i]; - var mdlNode = slotContext.CreateNodeFromRenderModel(mdl); + var mdlNode = slotContext.CreateNodeFromModel(mdl, imcNode?.GamePath ?? Utf8GamePath.Empty); if (mdlNode != null) { if (globalContext.WithUiData) - mdlNode.FallbackName = $"{subObjectNamePrefix} #{subObjectIndex}, Model #{i}"; - subObjectNodes.Add(mdlNode); + mdlNode.FallbackName = $"Weapon #{weaponIndex}, Model #{i}"; + weaponNodes.Add(mdlNode); } } - AddSkeleton(subObjectNodes, genericContext, subObject->Skeleton, $"{subObjectNamePrefix} #{subObjectIndex}, "); + AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, $"Weapon #{weaponIndex}, "); - ++subObjectIndex; - if (weapon != null) - ++weaponIndex; + ++weaponIndex; } - Nodes.InsertRange(0, subObjectNodes); + Nodes.InsertRange(0, weaponNodes); } private unsafe void AddHumanResources(GlobalResolveContext globalContext, Human* human) { - var genericContext = globalContext.CreateContext(&human->CharacterBase, 0xFFFFFFFFu, EquipSlot.Unknown, default); + var genericContext = globalContext.CreateContext(&human->CharacterBase); var decalId = (byte)(human->Customize[(int)CustomizeIndex.Facepaint] & 0x7F); var decalPath = decalId != 0 @@ -208,8 +188,16 @@ public class ResourceTree } } - private unsafe void AddSkeleton(List nodes, ResolveContext context, Skeleton* skeleton, string prefix = "") + private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, string prefix = "") { + var eidNode = context.CreateNodeFromEid((ResourceHandle*)eid); + if (eidNode != null) + { + if (context.Global.WithUiData) + eidNode.FallbackName = $"{prefix}EID"; + Nodes.Add(eidNode); + } + if (skeleton == null) return; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 6353d5b5..0e3a92e2 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,5 +1,4 @@ using Dalamud.Plugin.Services; -using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -18,9 +17,10 @@ public class ResourceTreeFactory private readonly IdentifierService _identifier; private readonly Configuration _config; private readonly ActorService _actors; + private readonly PathState _pathState; public ResourceTreeFactory(IDataManager gameData, IObjectTable objects, CollectionResolver resolver, IdentifierService identifier, - Configuration config, ActorService actors) + Configuration config, ActorService actors, PathState pathState) { _gameData = gameData; _objects = objects; @@ -28,6 +28,7 @@ public class ResourceTreeFactory _identifier = identifier; _config = config; _actors = actors; + _pathState = pathState; } private TreeBuildCache CreateTreeBuildCache() @@ -87,13 +88,17 @@ public class ResourceTreeFactory var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name); - var globalContext = new GlobalResolveContext(_identifier.AwaitedService, cache, - ((Character*)gameObjStruct)->CharacterData.ModelCharaId, (flags & Flags.WithUiData) != 0); - tree.LoadResources(globalContext); + var globalContext = new GlobalResolveContext(_identifier.AwaitedService, collectionResolveData.ModCollection, + cache, (flags & Flags.WithUiData) != 0); + using (var _ = _pathState.EnterInternalResolve()) + { + tree.LoadResources(globalContext); + } tree.FlatNodes.UnionWith(globalContext.Nodes.Values); tree.ProcessPostfix((node, _) => tree.FlatNodes.Add(node)); - ResolveGamePaths(tree, collectionResolveData.ModCollection); + // This is currently unneeded as we can resolve all paths by querying the draw object: + // ResolveGamePaths(tree, collectionResolveData.ModCollection); if (globalContext.WithUiData) ResolveUiData(tree); FilterFullPaths(tree, (flags & Flags.RedactExternalPaths) != 0 ? _config.ModDirectory : null); @@ -128,23 +133,15 @@ public class ResourceTreeFactory if (!reverseDictionary.TryGetValue(node.FullPath.ToPath(), out var resolvedSet)) continue; - IReadOnlyCollection resolvedList = resolvedSet; - if (resolvedList.Count > 1) - { - var filteredList = node.ResolveContext!.FilterGamePaths(resolvedList); - if (filteredList.Count > 0) - resolvedList = filteredList; - } - - if (resolvedList.Count != 1) + if (resolvedSet.Count != 1) { Penumbra.Log.Debug( - $"Found {resolvedList.Count} game paths while reverse-resolving {node.FullPath} in {collection.Name}:"); - foreach (var gamePath in resolvedList) + $"Found {resolvedSet.Count} game paths while reverse-resolving {node.FullPath} in {collection.Name}:"); + foreach (var gamePath in resolvedSet) Penumbra.Log.Debug($"Game path: {gamePath}"); } - node.PossibleGamePaths = resolvedList.ToArray(); + node.PossibleGamePaths = resolvedSet.ToArray(); } else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) { diff --git a/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs b/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs new file mode 100644 index 00000000..008cd59a --- /dev/null +++ b/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs @@ -0,0 +1,18 @@ +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; + +namespace Penumbra.Interop.Structs; + +// TODO submit this to ClientStructs +public class ModelResourceHandleUtility +{ + public ModelResourceHandleUtility(IGameInteropProvider interop) + => interop.InitializeFromAttributes(this); + + [Signature("E8 ?? ?? ?? ?? 44 8B CD 48 89 44 24")] + private static nint _getMaterialFileNameBySlot = nint.Zero; + + public static unsafe byte* GetMaterialFileNameBySlot(ModelResourceHandle* handle, uint slot) + => ((delegate* unmanaged)_getMaterialFileNameBySlot)(handle, slot); +} diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 94bc2428..e3c31a42 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -65,6 +65,13 @@ public unsafe class ImcFile : MetaBaseFile return ptr == null ? new ImcEntry() : *ptr; } + public ImcEntry GetEntry(int partIdx, Variant variantIdx, out bool exists) + { + var ptr = VariantPtr(Data, partIdx, variantIdx); + exists = ptr != null; + return exists ? *ptr : new ImcEntry(); + } + public static int PartIndex(EquipSlot slot) => slot switch { diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index df470d63..d7daaf70 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -76,6 +76,7 @@ public class Penumbra : IDalamudPlugin _communicatorService = _services.GetRequiredService(); _services.GetRequiredService(); // Initialize because not required anywhere else. _services.GetRequiredService(); // Initialize because not required anywhere else. + _services.GetRequiredService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); using (var t = _services.GetRequiredService().Measure(StartTimeType.PathResolver)) { diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 6a522ca2..2c4f385d 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -90,7 +90,8 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddConfiguration(this IServiceCollection services) => services.AddTransient() From 50a7015bc5a89d280c86ea4f3a73c683ecbc3128 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Nov 2023 13:58:14 +0100 Subject: [PATCH 0194/1381] Update BNPC Data. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 04ddadb4..545aab1f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 04ddadb44600a382e26661e1db08fd16c3b671d8 +Subproject commit 545aab1f007158a5d53bc6a7d73b6b2992deb9b3 From 5a64eadb5c2c5418f715027804a6135222e628d6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Nov 2023 13:59:59 +0100 Subject: [PATCH 0195/1381] Update Stain Data. --- OtterGui | 2 +- Penumbra/Services/StainService.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index a4f9b285..b09bbcc2 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit a4f9b285c82f84ff0841695c0787dbba93afc59b +Subproject commit b09bbcc276363bc994d90b641871e6280898b6e5 diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index bbbfcc71..4bec85db 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -26,7 +26,8 @@ public class StainService : IDisposable using var t = timer.Measure(StartTimeType.Stains); StainData = new StainData(pluginInterface, dataManager, dataManager.Language, dalamudLog); StainCombo = new FilterComboColors(140, - StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false))), Penumbra.Log); + () => StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), + Penumbra.Log); StmFile = new StmFile(dataManager); TemplateCombo = new StainTemplateCombo(StmFile.Entries.Keys.Prepend((ushort)0)); Penumbra.Log.Verbose($"[{nameof(StainService)}] Created."); From da880bd76cceb503cae0d997744a0ba5f57af915 Mon Sep 17 00:00:00 2001 From: HoloWise Date: Thu, 9 Nov 2023 21:10:22 +0100 Subject: [PATCH 0196/1381] Fix broken tooltips --- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 821f4454..20550a15 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -27,6 +27,7 @@ public partial class ModEditWindow private const string GenderTooltip = "Gender"; private const string ObjectTypeTooltip = "Object Type"; private const string SecondaryIdTooltip = "Secondary ID"; + private const string PrimaryIDTooltip = "Primary ID"; private const string VariantIdTooltip = "Variant ID"; private const string EstTypeTooltip = "EST Type"; private const string RacialTribeTooltip = "Racial Tribe"; @@ -415,6 +416,8 @@ public partial class ModEditWindow _new.Entry).Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); + ImGuiUtil.HoverTooltip(VariantIdTooltip); + ImGui.TableNextColumn(); if (_new.ObjectType is ObjectType.DemiHuman) { @@ -431,7 +434,6 @@ public partial class ModEditWindow ImGui.Dummy(new Vector2(70 * UiHelpers.Scale, 0)); } - ImGuiUtil.HoverTooltip(VariantIdTooltip); // Values using var disabled = ImRaii.Disabled(); @@ -475,7 +477,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); ImGui.TextUnformatted(meta.PrimaryId.ToString()); - ImGuiUtil.HoverTooltip("Primary ID"); + ImGuiUtil.HoverTooltip(PrimaryIDTooltip); ImGui.TableNextColumn(); ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); @@ -498,7 +500,10 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); if (meta.ObjectType is ObjectType.DemiHuman) + { ImGui.TextUnformatted(meta.EquipSlot.ToName()); + ImGuiUtil.HoverTooltip(EquipSlotTooltip); + } // Values using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, From b5377a961f9a4c61d794715cab0a05828cf8d51c Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 11 Nov 2023 13:18:07 +0000 Subject: [PATCH 0197/1381] [CI] Updating repo.json for 0.8.1.8 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index bc8d02d7..061eb283 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.7", - "TestingAssemblyVersion": "0.8.1.7", + "AssemblyVersion": "0.8.1.8", + "TestingAssemblyVersion": "0.8.1.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.7/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.7/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.7/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 51dba221c44a6ecc0717df4dd774dd72d301d9c2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Nov 2023 21:09:49 +0100 Subject: [PATCH 0198/1381] Add option to open window at game start instead of coupling it with debug mode --- Penumbra/Configuration.cs | 1 + Penumbra/UI/ConfigWindow.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 9 ++++++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index d221b4a2..a1cf6a72 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -35,6 +35,7 @@ public class Configuration : IPluginConfiguration, ISavable public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; + public bool OpenWindowAtStart { get; set; } = false; public bool HideUiInGPose { get; set; } = false; public bool HideUiInCutscenes { get; set; } = true; public bool HideUiWhenUiHidden { get; set; } = false; diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 0f209686..804a1d01 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -32,7 +32,7 @@ public sealed class ConfigWindow : Window RespectCloseHotkey = true; tutorial.UpdateTutorialStep(); - IsOpen = _config.DebugMode; + IsOpen = _config.OpenWindowAtStart; } public void Setup(Penumbra penumbra, ConfigTabBar configTabs) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index ae3a939c..6274f209 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -345,22 +345,25 @@ public class SettingsTab : ITab /// Draw the window hiding state checkboxes. private void DrawHidingSettings() { + Checkbox("Open Config Window at Game Start", "Whether the Penumbra main window should be open or closed after launching the game.", + _config.OpenWindowAtStart, v => _config.OpenWindowAtStart = v); + Checkbox("Hide Config Window when UI is Hidden", - "Hide the penumbra main window when you manually hide the in-game user interface.", _config.HideUiWhenUiHidden, + "Hide the Penumbra main window when you manually hide the in-game user interface.", _config.HideUiWhenUiHidden, v => { _config.HideUiWhenUiHidden = v; _dalamud.UiBuilder.DisableUserUiHide = !v; }); Checkbox("Hide Config Window when in Cutscenes", - "Hide the penumbra main window when you are currently watching a cutscene.", _config.HideUiInCutscenes, + "Hide the Penumbra main window when you are currently watching a cutscene.", _config.HideUiInCutscenes, v => { _config.HideUiInCutscenes = v; _dalamud.UiBuilder.DisableCutsceneUiHide = !v; }); Checkbox("Hide Config Window when in GPose", - "Hide the penumbra main window when you are currently in GPose mode.", _config.HideUiInGPose, + "Hide the Penumbra main window when you are currently in GPose mode.", _config.HideUiInGPose, v => { _config.HideUiInGPose = v; From b2bf6eb0f7615f54ac5f19b76b35555918987c76 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 13 Nov 2023 07:44:48 +0100 Subject: [PATCH 0199/1381] ResourceTree: Handle weapon MTRL special cases --- .../ResolveContext.PathResolution.cs | 72 +++++++++++++++---- 1 file changed, 59 insertions(+), 13 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index bcc957df..d7d80c21 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -13,7 +13,6 @@ namespace Penumbra.Interop.ResourceTree; internal partial record ResolveContext { - private Utf8GamePath ResolveModelPath() { // Correctness: @@ -83,27 +82,57 @@ internal partial record ResolveContext { ModelType.Human when SlotIndex < 10 && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), - ModelType.Weapon => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), + ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imcPath, mtrlFileName), _ => ResolveMaterialPathNative(mtrlFileName), }; } private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) { - var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); - var modelPathSpan = modelPath.Path.Span; - var baseDirectory = modelPathSpan[..modelPathSpan.IndexOf("/model/"u8)]; - - var variant = ResolveMaterialVariant(imcPath); + var variant = ResolveMaterialVariant(imcPath); + var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; - baseDirectory.CopyTo(pathBuffer); - "/material/v"u8.CopyTo(pathBuffer[baseDirectory.Length..]); - WriteZeroPaddedNumber(pathBuffer.Slice(baseDirectory.Length + 11, 4), variant); - pathBuffer[baseDirectory.Length + 15] = (byte)'/'; - fileName.CopyTo(pathBuffer[(baseDirectory.Length + 16)..]); + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); - return Utf8GamePath.FromSpan(pathBuffer[..(baseDirectory.Length + 16 + fileName.Length)], out var path) ? path.Clone() : Utf8GamePath.Empty; + return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolveWeaponMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) + { + var setIdHigh = Equipment.Set.Id / 100; + // All MCH (20??) weapons' materials C are one and the same + if (setIdHigh is 20 && mtrlFileName[14] == (byte)'c') + return Utf8GamePath.FromString(GamePaths.Weapon.Mtrl.Path(2001, 1, 1, "c"), out var path) ? path : Utf8GamePath.Empty; + + // MNK (03??, 16??), NIN (18??) and DNC (26??) offhands share materials with the corresponding mainhand + if (setIdHigh is 3 or 16 or 18 or 26) + { + var setIdLow = Equipment.Set.Id % 100; + if (setIdLow > 50) + { + var variant = ResolveMaterialVariant(imcPath); + var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); + + var mirroredSetId = (ushort)(Equipment.Set.Id - 50); + + Span mirroredFileName = stackalloc byte[32]; + mirroredFileName = mirroredFileName[..fileName.Length]; + fileName.CopyTo(mirroredFileName); + WriteZeroPaddedNumber(mirroredFileName[4..8], mirroredSetId); + + Span pathBuffer = stackalloc byte[260]; + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, mirroredFileName); + + var weaponPosition = pathBuffer.IndexOf("/weapon/w"u8); + if (weaponPosition >= 0) + WriteZeroPaddedNumber(pathBuffer[(weaponPosition + 9)..(weaponPosition + 13)], mirroredSetId); + + return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; + } + } + + return ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName); } private byte ResolveMaterialVariant(Utf8GamePath imcPath) @@ -119,6 +148,23 @@ internal partial record ResolveContext return entry.MaterialId; } + private static Span AssembleMaterialPath(Span materialPathBuffer, ReadOnlySpan modelPath, byte variant, ReadOnlySpan mtrlFileName) + { + var modelPosition = modelPath.IndexOf("/model/"u8); + if (modelPosition < 0) + return Span.Empty; + + var baseDirectory = modelPath[..modelPosition]; + + baseDirectory.CopyTo(materialPathBuffer); + "/material/v"u8.CopyTo(materialPathBuffer[baseDirectory.Length..]); + WriteZeroPaddedNumber(materialPathBuffer.Slice(baseDirectory.Length + 11, 4), variant); + materialPathBuffer[baseDirectory.Length + 15] = (byte)'/'; + mtrlFileName.CopyTo(materialPathBuffer[(baseDirectory.Length + 16)..]); + + return materialPathBuffer[..(baseDirectory.Length + 16 + mtrlFileName.Length)]; + } + private static void WriteZeroPaddedNumber(Span destination, ushort number) { for (var i = destination.Length; i-- > 0;) From 60551c87393e4a2b988852688040b7a4ba36f441 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 14 Nov 2023 20:38:21 +0100 Subject: [PATCH 0200/1381] ResourceTree: Are we fast yet? --- Penumbra/Collections/Cache/MetaCache.cs | 5 --- .../ResolveContext.PathResolution.cs | 31 +++++++++++-------- .../Interop/ResourceTree/ResolveContext.cs | 8 ++--- Penumbra/Interop/ResourceTree/ResourceTree.cs | 4 +-- Penumbra/Meta/Files/ImcFile.cs | 10 +++++- 5 files changed, 33 insertions(+), 25 deletions(-) diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 0da11022..d5acf249 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -187,11 +187,6 @@ public class MetaCache : IDisposable, IEnumerable _imcCache.GetImcFile(path, out file); - public ImcEntry GetImcEntry(Utf8GamePath path, EquipSlot slot, Variant variantIdx, out bool exists) - => GetImcFile(path, out var file) - ? file.GetEntry(Meta.Files.ImcFile.PartIndex(slot), variantIdx, out exists) - : Meta.Files.ImcFile.GetDefault(_manager, path, slot, variantIdx, out exists); - internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, SetId setId) { var eqdpFile = _eqdpCache.EqdpFile(race, accessory); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index d7d80c21..f4081de1 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -1,8 +1,10 @@ using Dalamud.Game.ClientState.Objects.Enums; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.String; using Penumbra.String.Classes; @@ -74,22 +76,22 @@ internal partial record ResolveContext return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } - private unsafe Utf8GamePath ResolveMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) + private unsafe Utf8GamePath ResolveMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { // Safety: // Resolving a material path through the game's code can dereference null pointers for equipment materials. return ModelType switch { - ModelType.Human when SlotIndex < 10 && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), - ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName), - ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imcPath, mtrlFileName), + ModelType.Human when SlotIndex < 10 && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), + ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), + ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imc, mtrlFileName), _ => ResolveMaterialPathNative(mtrlFileName), }; } - private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) + private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { - var variant = ResolveMaterialVariant(imcPath); + var variant = ResolveMaterialVariant(imc); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; @@ -98,7 +100,7 @@ internal partial record ResolveContext return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; } - private unsafe Utf8GamePath ResolveWeaponMaterialPath(Utf8GamePath modelPath, Utf8GamePath imcPath, byte* mtrlFileName) + private unsafe Utf8GamePath ResolveWeaponMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { var setIdHigh = Equipment.Set.Id / 100; // All MCH (20??) weapons' materials C are one and the same @@ -111,7 +113,7 @@ internal partial record ResolveContext var setIdLow = Equipment.Set.Id % 100; if (setIdLow > 50) { - var variant = ResolveMaterialVariant(imcPath); + var variant = ResolveMaterialVariant(imc); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); var mirroredSetId = (ushort)(Equipment.Set.Id - 50); @@ -132,16 +134,19 @@ internal partial record ResolveContext } } - return ResolveEquipmentMaterialPath(modelPath, imcPath, mtrlFileName); + return ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName); } - private byte ResolveMaterialVariant(Utf8GamePath imcPath) + private unsafe byte ResolveMaterialVariant(ResourceHandle* imc) { - var metaCache = Global.Collection.MetaCache; - if (metaCache == null) + var imcFileData = imc->GetDataSpan(); + if (imcFileData.IsEmpty) + { + Penumbra.Log.Warning($"IMC resource handle with path {GetResourceHandlePath(imc, false)} doesn't have a valid data span"); return Equipment.Variant.Id; + } - var entry = metaCache.GetImcEntry(imcPath, Slot, Equipment.Variant, out var exists); + var entry = ImcFile.GetEntry(imcFileData, Slot, Equipment.Variant, out var exists); if (!exists) return Equipment.Variant.Id; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index f34a6ae2..73abcb4d 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -148,7 +148,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, PointerTexture, &tex->ResourceHandle, path); } - public unsafe ResourceNode? CreateNodeFromModel(Model* mdl, Utf8GamePath imcPath) + public unsafe ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc) { if (mdl == null || mdl->ModelResourceHandle == null) return null; @@ -169,7 +169,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, Pointer= 0 && i < array.Length ? array[i] : null; } - internal static unsafe ByteString GetResourceHandlePath(ResourceHandle* handle) + internal static unsafe ByteString GetResourceHandlePath(ResourceHandle* handle, bool stripPrefix = true) { if (handle == null) return ByteString.Empty; @@ -367,7 +367,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, PointerModels[i]; - var mdlNode = slotContext.CreateNodeFromModel(mdl, imcNode?.GamePath ?? Utf8GamePath.Empty); + var mdlNode = slotContext.CreateNodeFromModel(mdl, imc); if (mdlNode != null) { if (globalContext.WithUiData) @@ -135,7 +135,7 @@ public class ResourceTree } var mdl = subObject->Models[i]; - var mdlNode = slotContext.CreateNodeFromModel(mdl, imcNode?.GamePath ?? Utf8GamePath.Empty); + var mdlNode = slotContext.CreateNodeFromModel(mdl, imc); if (mdlNode != null) { if (globalContext.WithUiData) diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index e3c31a42..68d3f5b3 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -168,11 +168,19 @@ public unsafe class ImcFile : MetaBaseFile if (file == null) throw new Exception(); - fixed (byte* ptr = file.Data) + return GetEntry(file.Data, slot, variantIdx, out exists); + } + + public static ImcEntry GetEntry(ReadOnlySpan imcFileData, EquipSlot slot, Variant variantIdx, out bool exists) + { + fixed (byte* ptr = imcFileData) { var entry = VariantPtr(ptr, PartIndex(slot), variantIdx); if (entry == null) + { + exists = false; return new ImcEntry(); + } exists = true; return *entry; From cb43fed9d3785674ef016f4f7b3cbf968ef89dd0 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 14 Nov 2023 21:13:54 +0100 Subject: [PATCH 0201/1381] ResourceTree: Handle monster MTRL --- .../ResolveContext.PathResolution.cs | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index f4081de1..1c9dfaa1 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -78,20 +78,21 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { - // Safety: - // Resolving a material path through the game's code can dereference null pointers for equipment materials. + // Safety and correctness: + // Resolving a material path through the game's code can dereference null pointers for materials that involve IMC metadata. return ModelType switch { ModelType.Human when SlotIndex < 10 && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imc, mtrlFileName), + ModelType.Monster => ResolveMonsterMaterialPath(modelPath, imc, mtrlFileName), _ => ResolveMaterialPathNative(mtrlFileName), }; } private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { - var variant = ResolveMaterialVariant(imc); + var variant = ResolveMaterialVariant(imc, Equipment.Variant); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; @@ -113,7 +114,7 @@ internal partial record ResolveContext var setIdLow = Equipment.Set.Id % 100; if (setIdLow > 50) { - var variant = ResolveMaterialVariant(imc); + var variant = ResolveMaterialVariant(imc, Equipment.Variant); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); var mirroredSetId = (ushort)(Equipment.Set.Id - 50); @@ -137,18 +138,30 @@ internal partial record ResolveContext return ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName); } - private unsafe byte ResolveMaterialVariant(ResourceHandle* imc) + private unsafe Utf8GamePath ResolveMonsterMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) + { + // TODO: Submit this (Monster->Variant) to ClientStructs + var variant = ResolveMaterialVariant(imc, ((byte*)CharacterBase.Value)[0x8F4]); + var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); + + Span pathBuffer = stackalloc byte[260]; + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); + + return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; + } + + private unsafe byte ResolveMaterialVariant(ResourceHandle* imc, Variant variant) { var imcFileData = imc->GetDataSpan(); if (imcFileData.IsEmpty) { Penumbra.Log.Warning($"IMC resource handle with path {GetResourceHandlePath(imc, false)} doesn't have a valid data span"); - return Equipment.Variant.Id; + return variant.Id; } - var entry = ImcFile.GetEntry(imcFileData, Slot, Equipment.Variant, out var exists); + var entry = ImcFile.GetEntry(imcFileData, Slot, variant, out var exists); if (!exists) - return Equipment.Variant.Id; + return variant.Id; return entry.MaterialId; } From 13044763cbfcd8d899a1f05a67c34c41959370cc Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 15 Nov 2023 01:10:35 +0100 Subject: [PATCH 0202/1381] Redraw player ornament, allow redrawing by index --- Penumbra/Interop/Services/RedrawService.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index ec858290..ee09ea6e 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -154,11 +154,11 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) DisableDraw(actor!); - if (actor is PlayerCharacter && _objects[tableIndex + 1] is { ObjectKind: ObjectKind.MountType } mount) + if (actor is PlayerCharacter && _objects[tableIndex + 1] is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { - *ActorDrawState(mount) |= DrawState.Invisibility; + *ActorDrawState(mountOrOrnament) |= DrawState.Invisibility; if (gPose) - DisableDraw(mount); + DisableDraw(mountOrOrnament); } } @@ -173,11 +173,11 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) EnableDraw(actor!); - if (actor is PlayerCharacter && _objects[tableIndex + 1] is { ObjectKind: ObjectKind.MountType } mount) + if (actor is PlayerCharacter && _objects[tableIndex + 1] is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { - *ActorDrawState(mount) &= ~DrawState.Invisibility; + *ActorDrawState(mountOrOrnament) &= ~DrawState.Invisibility; if (gPose) - EnableDraw(mount); + EnableDraw(mountOrOrnament); } GameObjectRedrawn?.Invoke(actor!.Address, tableIndex); @@ -323,6 +323,12 @@ public sealed unsafe partial class RedrawService : IDisposable "mouseover" => (_targets.MouseOverTarget, true), _ => (null, false), }; + if (!ret && lowerName.Length > 1 && lowerName[0] == '#' && ushort.TryParse(lowerName[1..], out var objectIndex)) + { + ret = true; + actor = _objects[objectIndex]; + } + return ret; } From ab902cbe9e784a80f7d0cf5cd77826333022c9fc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 15 Nov 2023 16:09:48 +0100 Subject: [PATCH 0203/1381] Fix issue with ring identification --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 545aab1f..f39a716a 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 545aab1f007158a5d53bc6a7d73b6b2992deb9b3 +Subproject commit f39a716ad4f908c301d497728ede047ee6bd61c0 From d026ca888fc41511770ecaab255c3587c2247865 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 15 Nov 2023 16:10:15 +0100 Subject: [PATCH 0204/1381] Add Furniture Redrawing despite crash. --- Penumbra/Interop/Services/RedrawService.cs | 58 +++++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index ee09ea6e..ddabacd0 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -4,6 +4,8 @@ using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Housing; +using FFXIVClientStructs.Interop; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.GameData; @@ -101,6 +103,8 @@ public unsafe partial class RedrawService public sealed unsafe partial class RedrawService : IDisposable { + private const int FurnitureIdx = 1337; + private readonly IFramework _framework; private readonly IObjectTable _objects; private readonly ITargetManager _targets; @@ -231,6 +235,18 @@ public sealed unsafe partial class RedrawService : IDisposable for (var i = 0; i < _queue.Count; ++i) { var idx = _queue[i]; + if (idx == FurnitureIdx) + { + EnableFurniture(); + continue; + } + + if (idx == ~FurnitureIdx) + { + DisableFurniture(); + continue; + } + if (FindCorrectActor(idx < 0 ? ~idx : idx, out var obj)) _afterGPoseQueue.Add(idx < 0 ? idx : ~idx); @@ -340,8 +356,10 @@ public sealed unsafe partial class RedrawService : IDisposable public void RedrawObject(string name, RedrawType settings) { - var lowerName = name.ToLowerInvariant(); - if (GetName(lowerName, out var target)) + var lowerName = name.ToLowerInvariant().Trim(); + if (lowerName == "furniture") + _queue.Add(~FurnitureIdx); + else if (GetName(lowerName, out var target)) RedrawObject(target, settings); else foreach (var actor in _objects.Where(a => a.Name.ToString().ToLowerInvariant() == lowerName)) @@ -353,4 +371,40 @@ public sealed unsafe partial class RedrawService : IDisposable foreach (var actor in _objects) RedrawObject(actor, settings); } + + private void DisableFurniture() + { + var housingManager = HousingManager.Instance(); + if (housingManager == null) + return; + var currentTerritory = housingManager->CurrentTerritory; + if (currentTerritory == null) + return; + + foreach (var f in currentTerritory->FurnitureSpan.PointerEnumerator()) + { + var gameObject = f->Index >= 0 ? currentTerritory->HousingObjectManager.ObjectsSpan[f->Index].Value : null; + if (gameObject == null) + continue; + gameObject->DisableDraw(); + } + } + + private void EnableFurniture() + { + var housingManager = HousingManager.Instance(); + if (housingManager == null) + return; + var currentTerritory = housingManager->CurrentTerritory; + if (currentTerritory == null) + return; + + foreach (var f in currentTerritory->FurnitureSpan.PointerEnumerator()) + { + var gameObject = f->Index >= 0 ? currentTerritory->HousingObjectManager.ObjectsSpan[f->Index].Value : null; + if (gameObject == null) + continue; + gameObject->EnableDraw(); + } + } } From aee942468ebb681e2fd153ffe2333d3ece597cb0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 15 Nov 2023 18:34:24 +0100 Subject: [PATCH 0205/1381] Only allow redrawing furniture inside. --- Penumbra/Interop/Services/RedrawService.cs | 26 ++-------------------- 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index ddabacd0..49d688af 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -235,12 +235,6 @@ public sealed unsafe partial class RedrawService : IDisposable for (var i = 0; i < _queue.Count; ++i) { var idx = _queue[i]; - if (idx == FurnitureIdx) - { - EnableFurniture(); - continue; - } - if (idx == ~FurnitureIdx) { DisableFurniture(); @@ -380,6 +374,8 @@ public sealed unsafe partial class RedrawService : IDisposable var currentTerritory = housingManager->CurrentTerritory; if (currentTerritory == null) return; + if (!housingManager->IsInside()) + return; foreach (var f in currentTerritory->FurnitureSpan.PointerEnumerator()) { @@ -389,22 +385,4 @@ public sealed unsafe partial class RedrawService : IDisposable gameObject->DisableDraw(); } } - - private void EnableFurniture() - { - var housingManager = HousingManager.Instance(); - if (housingManager == null) - return; - var currentTerritory = housingManager->CurrentTerritory; - if (currentTerritory == null) - return; - - foreach (var f in currentTerritory->FurnitureSpan.PointerEnumerator()) - { - var gameObject = f->Index >= 0 ? currentTerritory->HousingObjectManager.ObjectsSpan[f->Index].Value : null; - if (gameObject == null) - continue; - gameObject->EnableDraw(); - } - } } From acfd5d24848988ea0232bee49c49b9bec7fb9cc0 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 15 Nov 2023 20:04:30 +0100 Subject: [PATCH 0206/1381] Update Penumbra.GameData Also remove a check that, if it was still valid, would always be false with the new changes. --- Penumbra.GameData | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 20e8002b..a807e426 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 20e8002bfe701e54b05721c3b7b80c495a692adc +Subproject commit a807e426eed5b26a5d1043d5c47c98b28c93982e diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 0048dc8c..c1e0bb80 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -102,8 +102,6 @@ public unsafe class MetaState : IDisposable public DisposableContainer ResolveEqdpData(ModCollection collection, GenderRace race, bool equipment, bool accessory) { var races = race.Dependencies(); - if (races.Length == 0) - return DisposableContainer.Empty; var equipmentEnumerable = equipment ? races.Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, false)) From 63ca0445867656980b8280282ac1cb0f14fa61fe Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 16 Nov 2023 05:48:30 +0100 Subject: [PATCH 0207/1381] Update GameData --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2e3237c9..c5c3b027 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2e3237c9018f4531f8ecdc1783b4f00e5eba7f34 +Subproject commit c5c3b0272ee47462c20b692787f9748571eb01dc From 8caba8c339375849e78a6b406a97379826ab6d84 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 16 Nov 2023 21:16:38 +0100 Subject: [PATCH 0208/1381] Update GameData again. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c5c3b027..ffdb966f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c5c3b0272ee47462c20b692787f9748571eb01dc +Subproject commit ffdb966fec5a657893289e655c641ceb3af1d59f From 7e8cd719fd73408501211e590ddf080cda94e6c7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 17 Nov 2023 12:11:06 +0000 Subject: [PATCH 0209/1381] [CI] Updating repo.json for testing_0.8.1.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 061eb283..e804fb1e 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.1.8", - "TestingAssemblyVersion": "0.8.1.8", + "TestingAssemblyVersion": "0.8.1.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.1.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From c88f1a7b1cefd8985524f0a39210fcbabb0b7aed Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Nov 2023 15:25:03 +0100 Subject: [PATCH 0210/1381] Add color preview for dye template selection. --- Penumbra/Services/StainService.cs | 56 +++++++++++++++++-- .../ModEditWindow.Materials.MtrlTab.cs | 1 - 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 4bec85db..58d9af21 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -1,5 +1,8 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin; using Dalamud.Plugin.Services; +using ImGuiNET; using OtterGui.Widgets; using Penumbra.GameData.Data; using Penumbra.GameData.Files; @@ -11,9 +14,54 @@ public class StainService : IDisposable { public sealed class StainTemplateCombo : FilterComboCache { - public StainTemplateCombo(IEnumerable items) - : base(items, Penumbra.Log) - { } + private readonly StmFile _stmFile; + private readonly FilterComboColors _stainCombo; + + private float _rightOffset; + + public StainTemplateCombo(FilterComboColors stainCombo, StmFile stmFile) + : base(stmFile.Entries.Keys.Prepend((ushort)0), Penumbra.Log) + { + _stainCombo = stainCombo; + _stmFile = stmFile; + } + + protected override float GetFilterWidth() + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + var baseSize = ImGui.CalcTextSize("0000").X + ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X; + if (_stainCombo.CurrentSelection.Key == 0) + return baseSize; + return baseSize + ImGui.GetTextLineHeight() * 3 + ImGui.GetStyle().ItemInnerSpacing.X * 3; + } + + protected override string ToString(ushort obj) + => $"{obj,4}"; + + protected override void DrawList(float width, float itemHeight) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, + ImGui.GetStyle().ItemSpacing with { X = ImGui.GetStyle().ItemInnerSpacing.X }); + base.DrawList(width, itemHeight); + } + + protected override bool DrawSelectable(int globalIdx, bool selected) + { + var ret = base.DrawSelectable(globalIdx, selected); + var selection = _stainCombo.CurrentSelection.Key; + if (selection == 0 || !_stmFile.TryGetValue(Items[globalIdx], selection, out var colors)) + return ret; + + ImGui.SameLine(); + var frame = new Vector2(ImGui.GetTextLineHeight()); + ImGui.ColorButton("D", new Vector4(colors.Diffuse, 1), 0, frame); + ImGui.SameLine(); + ImGui.ColorButton("E", new Vector4(colors.Emissive, 1), 0, frame); + ImGui.SameLine(); + ImGui.ColorButton("S", new Vector4(colors.Specular, 1), 0, frame); + return ret; + } } public readonly StainData StainData; @@ -29,7 +77,7 @@ public class StainService : IDisposable () => StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), Penumbra.Log); StmFile = new StmFile(dataManager); - TemplateCombo = new StainTemplateCombo(StmFile.Entries.Keys.Prepend((ushort)0)); + TemplateCombo = new StainTemplateCombo(StainCombo, StmFile); Penumbra.Log.Verbose($"[{nameof(StainService)}] Created."); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 20efe757..954e9b0f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -1,6 +1,5 @@ using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; using Newtonsoft.Json.Linq; using OtterGui; From 2fd8c981472f1e584f1a4126d17dc04bfa163752 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Nov 2023 15:25:37 +0100 Subject: [PATCH 0211/1381] Add furniture to redraw bar and help, improve redraw bar slightly. --- Penumbra/UI/Tabs/ModsTab.cs | 57 ++++++++++++++++++++++++++-------- Penumbra/UI/TutorialService.cs | 1 + 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 1e675036..7b30f7fc 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -1,9 +1,11 @@ +using Dalamud.Game.ClientState.Objects; using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.UI.Classes; using Dalamud.Interface; using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Housing; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Interop.Services; @@ -26,10 +28,12 @@ public class ModsTab : ITab private readonly Configuration _config; private readonly IClientState _clientState; private readonly CollectionSelectHeader _collectionHeader; + private readonly ITargetManager _targets; + private readonly IObjectTable _objectTable; public ModsTab(ModManager modManager, CollectionManager collectionManager, ModFileSystemSelector selector, ModPanel panel, TutorialService tutorial, RedrawService redrawService, Configuration config, IClientState clientState, - CollectionSelectHeader collectionHeader) + CollectionSelectHeader collectionHeader, ITargetManager targets, IObjectTable objectTable) { _modManager = modManager; _activeCollections = collectionManager.Active; @@ -40,6 +44,8 @@ public class ModsTab : ITab _config = config; _clientState = clientState; _collectionHeader = collectionHeader; + _targets = targets; + _objectTable = objectTable; } public bool IsVisible @@ -133,29 +139,54 @@ public class ModsTab : ITab if (hovered) ImGui.SetTooltip($"The supported modifiers for '/penumbra redraw' are:\n{TutorialService.SupportedRedrawModifiers}"); - void DrawButton(Vector2 size, string label, string lower) + void DrawButton(Vector2 size, string label, string lower, string additionalTooltip) { - if (ImGui.Button(label, size)) + using (var disabled = ImRaii.Disabled(additionalTooltip.Length > 0)) { - if (lower.Length > 0) - _redrawService.RedrawObject(lower, RedrawType.Redraw); - else - _redrawService.RedrawAll(RedrawType.Redraw); + if (ImGui.Button(label, size)) + { + if (lower.Length > 0) + _redrawService.RedrawObject(lower, RedrawType.Redraw); + else + _redrawService.RedrawAll(RedrawType.Redraw); + } } - ImGuiUtil.HoverTooltip(lower.Length > 0 ? $"Execute '/penumbra redraw {lower}'." : $"Execute '/penumbra redraw'."); + ImGuiUtil.HoverTooltip(lower.Length > 0 + ? $"Execute '/penumbra redraw {lower}'.{additionalTooltip}" + : $"Execute '/penumbra redraw'.{additionalTooltip}", ImGuiHoveredFlags.AllowWhenDisabled); } using var id = ImRaii.PushId("Redraw"); using var disabled = ImRaii.Disabled(_clientState.LocalPlayer == null); ImGui.SameLine(); - var buttonWidth = frameHeight with { X = ImGui.GetContentRegionAvail().X / 4 }; - DrawButton(buttonWidth, "All", string.Empty); + var buttonWidth = frameHeight with { X = ImGui.GetContentRegionAvail().X / 5 }; + var tt = _objectTable.GetObjectAddress(0) == nint.Zero + ? "\nCan only be used when you are logged in and your character is available." + : string.Empty; + DrawButton(buttonWidth, "All", string.Empty, tt); ImGui.SameLine(); - DrawButton(buttonWidth, "Self", "self"); + DrawButton(buttonWidth, "Self", "self", tt); ImGui.SameLine(); - DrawButton(buttonWidth, "Target", "target"); + + tt = _targets.Target == null && _targets.GPoseTarget == null + ? "\nCan only be used when you have a target." + : string.Empty; + DrawButton(buttonWidth, "Target", "target", tt); ImGui.SameLine(); - DrawButton(frameHeight with { X = ImGui.GetContentRegionAvail().X - 1 }, "Focus", "focus"); + + tt = _targets.FocusTarget == null + ? "\nCan only be used when you have a focus target." + : string.Empty; + DrawButton(buttonWidth, "Focus", "focus", tt); + ImGui.SameLine(); + + tt = !IsIndoors() + ? "\nCan currently only be used for indoor furniture." + : string.Empty; + DrawButton(frameHeight with { X = ImGui.GetContentRegionAvail().X - 1 }, "Furniture", "furniture", tt); } + + private static unsafe bool IsIndoors() + => HousingManager.Instance()->IsInside(); } diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index 1a589c28..86c4dd46 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -52,6 +52,7 @@ public class TutorialService + " - 'target' or '': your target\n" + " - 'focus' or ': your focus target\n" + " - 'mouseover' or '': the actor you are currently hovering over\n" + + " - 'furniture': most indoor furniture, does not currently work outdoors\n" + " - any specific actor name to redraw all actors of that exactly matching name."; private readonly Configuration _config; From dc1c8f42c0d8a01aa9f6cc90ae63cde78369bbdd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Nov 2023 15:46:54 +0100 Subject: [PATCH 0212/1381] Improve Color Preview. --- Penumbra/Services/StainService.cs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 58d9af21..63f6d05e 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -17,8 +17,6 @@ public class StainService : IDisposable private readonly StmFile _stmFile; private readonly FilterComboColors _stainCombo; - private float _rightOffset; - public StainTemplateCombo(FilterComboColors stainCombo, StmFile stmFile) : base(stmFile.Entries.Keys.Prepend((ushort)0), Penumbra.Log) { @@ -28,7 +26,6 @@ public class StainService : IDisposable protected override float GetFilterWidth() { - using var font = ImRaii.PushFont(UiBuilder.MonoFont); var baseSize = ImGui.CalcTextSize("0000").X + ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X; if (_stainCombo.CurrentSelection.Key == 0) return baseSize; @@ -38,12 +35,21 @@ public class StainService : IDisposable protected override string ToString(ushort obj) => $"{obj,4}"; - protected override void DrawList(float width, float itemHeight) + protected override void DrawFilter(int currentSelected, float width) { - using var font = ImRaii.PushFont(UiBuilder.MonoFont); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - ImGui.GetStyle().ItemSpacing with { X = ImGui.GetStyle().ItemInnerSpacing.X }); - base.DrawList(width, itemHeight); + using var font = ImRaii.PushFont(UiBuilder.DefaultFont); + base.DrawFilter(currentSelected, width); + } + + public override bool Draw(string label, string preview, string tooltip, ref int currentSelection, float previewWidth, float itemHeight, + ImGuiComboFlags flags = ImGuiComboFlags.None) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(1, 0.5f)) + .Push(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing with { X = ImGui.GetStyle().ItemInnerSpacing.X }); + var spaceSize = ImGui.CalcTextSize(" ").X; + var spaces = (int) (previewWidth / spaceSize) - 1; + return base.Draw(label, preview.PadLeft(spaces), tooltip, ref currentSelection, previewWidth, itemHeight, flags); } protected override bool DrawSelectable(int globalIdx, bool selected) From ea65296ab771462fb4c6acc796b3f18ac7b4aeea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Nov 2023 16:51:09 +0100 Subject: [PATCH 0213/1381] Add EphemeralConfig. --- Penumbra/CommandHandler.cs | 8 +- Penumbra/Configuration.cs | 66 +++++--------- Penumbra/EphemeralConfig.cs | 86 +++++++++++++++++++ Penumbra/Penumbra.cs | 2 +- Penumbra/Services/BackupService.cs | 4 + Penumbra/Services/ConfigMigrationService.cs | 44 +++++++++- Penumbra/Services/FilenameService.cs | 10 ++- Penumbra/Services/ServiceManager.cs | 3 +- Penumbra/UI/ChangedItemDrawer.cs | 20 ++--- Penumbra/UI/Changelog.cs | 16 +++- Penumbra/UI/ConfigWindow.cs | 10 +-- .../UI/ResourceWatcher/ResourceWatcher.cs | 52 +++++------ .../ResourceWatcher/ResourceWatcherTable.cs | 14 +-- Penumbra/UI/Tabs/CollectionsTab.cs | 4 +- Penumbra/UI/Tabs/DebugTab.cs | 16 ++-- Penumbra/UI/Tabs/SettingsTab.cs | 28 ++++-- Penumbra/UI/TutorialService.cs | 6 +- 17 files changed, 264 insertions(+), 125 deletions(-) create mode 100644 Penumbra/EphemeralConfig.cs diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index b6c675a2..c151e7e4 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -184,8 +184,8 @@ public class CommandHandler : IDisposable private bool SetUiLockState(string arguments) { - var value = ParseTrueFalseToggle(arguments) ?? !_config.FixMainWindow; - if (value == _config.FixMainWindow) + var value = ParseTrueFalseToggle(arguments) ?? !_config.Ephemeral.FixMainWindow; + if (value == _config.Ephemeral.FixMainWindow) return false; if (value) @@ -199,8 +199,8 @@ public class CommandHandler : IDisposable _configWindow.Flags &= ~(ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoResize); } - _config.FixMainWindow = value; - _config.Save(); + _config.Ephemeral.FixMainWindow = value; + _config.Ephemeral.Save(); return true; } diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index a1cf6a72..8f21ee52 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -5,17 +5,13 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Widgets; -using Penumbra.Api.Enums; -using Penumbra.Enums; using Penumbra.Import.Structs; using Penumbra.Interop.Services; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.UI; using Penumbra.UI.Classes; using Penumbra.UI.ResourceWatcher; -using Penumbra.UI.Tabs; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra; @@ -26,9 +22,11 @@ public class Configuration : IPluginConfiguration, ISavable [JsonIgnore] private readonly SaveService _saveService; + [JsonIgnore] + public readonly EphemeralConfig Ephemeral; + public int Version { get; set; } = Constants.CurrentVersion; - public int LastSeenVersion { get; set; } = PenumbraChangelog.LastChangelogVersion; public ChangeLogDisplayType ChangeLogDisplayType { get; set; } = ChangeLogDisplayType.New; public bool EnableMods { get; set; } = true; @@ -53,52 +51,33 @@ public class Configuration : IPluginConfiguration, ISavable public bool HideRedrawBar { get; set; } = false; public int OptionGroupCollapsibleMin { get; set; } = 5; - public bool DebugSeparateWindow = false; - public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); + public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); #if DEBUG public bool DebugMode { get; set; } = true; #else public bool DebugMode { get; set; } = false; #endif - - public int TutorialStep { get; set; } = 0; - - public bool EnableResourceLogging { get; set; } = false; - public string ResourceLoggingFilter { get; set; } = string.Empty; - public bool EnableResourceWatcher { get; set; } = false; - public bool OnlyAddMatchingResources { get; set; } = true; - public int MaxResourceWatcherRecords { get; set; } = ResourceWatcher.DefaultMaxEntries; - - public ResourceTypeFlag ResourceWatcherResourceTypes { get; set; } = ResourceExtensions.AllResourceTypes; - public ResourceCategoryFlag ResourceWatcherResourceCategories { get; set; } = ResourceExtensions.AllResourceCategories; - public RecordType ResourceWatcherRecordTypes { get; set; } = ResourceWatcher.AllRecords; - + public int MaxResourceWatcherRecords { get; set; } = ResourceWatcher.DefaultMaxEntries; [JsonConverter(typeof(SortModeConverter))] [JsonProperty(Order = int.MaxValue)] public ISortMode SortMode = ISortMode.FoldersFirst; - public bool ScaleModSelector { get; set; } = false; - public float ModSelectorAbsoluteSize { get; set; } = Constants.DefaultAbsoluteSize; - public int ModSelectorScaledSize { get; set; } = Constants.DefaultScaledSize; - public bool OpenFoldersByDefault { get; set; } = false; - public int SingleGroupRadioMax { get; set; } = 2; - public string DefaultImportFolder { get; set; } = string.Empty; - public string QuickMoveFolder1 { get; set; } = string.Empty; - public string QuickMoveFolder2 { get; set; } = string.Empty; - public string QuickMoveFolder3 { get; set; } = string.Empty; - public DoubleModifier DeleteModModifier { get; set; } = new(ModifierHotkey.Control, ModifierHotkey.Shift); - public CollectionsTab.PanelMode CollectionPanel { get; set; } = CollectionsTab.PanelMode.SimpleAssignment; - public TabType SelectedTab { get; set; } = TabType.Settings; - - public ChangedItemDrawer.ChangedItemIcon ChangedItemFilter { get; set; } = ChangedItemDrawer.DefaultFlags; - - public bool PrintSuccessfulCommandsToChat { get; set; } = true; - public bool FixMainWindow { get; set; } = false; - public bool AutoDeduplicateOnImport { get; set; } = true; - public bool UseFileSystemCompression { get; set; } = true; - public bool EnableHttpApi { get; set; } = true; + public bool ScaleModSelector { get; set; } = false; + public float ModSelectorAbsoluteSize { get; set; } = Constants.DefaultAbsoluteSize; + public int ModSelectorScaledSize { get; set; } = Constants.DefaultScaledSize; + public bool OpenFoldersByDefault { get; set; } = false; + public int SingleGroupRadioMax { get; set; } = 2; + public string DefaultImportFolder { get; set; } = string.Empty; + public string QuickMoveFolder1 { get; set; } = string.Empty; + public string QuickMoveFolder2 { get; set; } = string.Empty; + public string QuickMoveFolder3 { get; set; } = string.Empty; + public DoubleModifier DeleteModModifier { get; set; } = new(ModifierHotkey.Control, ModifierHotkey.Shift); + public bool PrintSuccessfulCommandsToChat { get; set; } = true; + public bool AutoDeduplicateOnImport { get; set; } = true; + public bool UseFileSystemCompression { get; set; } = true; + public bool EnableHttpApi { get; set; } = true; public string DefaultModImportPath { get; set; } = string.Empty; public bool AlwaysOpenDefaultImport { get; set; } = false; @@ -112,9 +91,10 @@ public class Configuration : IPluginConfiguration, ISavable /// Load the current configuration. /// Includes adding new colors and migrating from old versions. /// - public Configuration(CharacterUtility utility, ConfigMigrationService migrator, SaveService saveService) + public Configuration(CharacterUtility utility, ConfigMigrationService migrator, SaveService saveService, EphemeralConfig ephemeral) { _saveService = saveService; + Ephemeral = ephemeral; Load(utility, migrator); } @@ -148,12 +128,12 @@ public class Configuration : IPluginConfiguration, ISavable /// Save the current configuration. public void Save() - => _saveService.DelaySave(this); + => _saveService.QueueSave(this); /// Contains some default values or boundaries for config values. public static class Constants { - public const int CurrentVersion = 7; + public const int CurrentVersion = 8; public const float MaxAbsoluteSize = 600; public const int DefaultAbsoluteSize = 250; public const float MinAbsoluteSize = 50; diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs new file mode 100644 index 00000000..8003629d --- /dev/null +++ b/Penumbra/EphemeralConfig.cs @@ -0,0 +1,86 @@ +using Dalamud.Interface.Internal.Notifications; +using Newtonsoft.Json; +using OtterGui.Classes; +using Penumbra.Api.Enums; +using Penumbra.Enums; +using Penumbra.Interop.Services; +using Penumbra.Services; +using Penumbra.UI; +using Penumbra.UI.ResourceWatcher; +using Penumbra.UI.Tabs; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; + +namespace Penumbra; + +public class EphemeralConfig : ISavable +{ + [JsonIgnore] + private readonly SaveService _saveService; + + public int Version { get; set; } = Configuration.Constants.CurrentVersion; + public int LastSeenVersion { get; set; } = PenumbraChangelog.LastChangelogVersion; + public bool DebugSeparateWindow { get; set; } = false; + public int TutorialStep { get; set; } = 0; + public bool EnableResourceLogging { get; set; } = false; + public string ResourceLoggingFilter { get; set; } = string.Empty; + public bool EnableResourceWatcher { get; set; } = false; + public bool OnlyAddMatchingResources { get; set; } = true; + public ResourceTypeFlag ResourceWatcherResourceTypes { get; set; } = ResourceExtensions.AllResourceTypes; + public ResourceCategoryFlag ResourceWatcherResourceCategories { get; set; } = ResourceExtensions.AllResourceCategories; + public RecordType ResourceWatcherRecordTypes { get; set; } = ResourceWatcher.AllRecords; + public CollectionsTab.PanelMode CollectionPanel { get; set; } = CollectionsTab.PanelMode.SimpleAssignment; + public TabType SelectedTab { get; set; } = TabType.Settings; + public ChangedItemDrawer.ChangedItemIcon ChangedItemFilter { get; set; } = ChangedItemDrawer.DefaultFlags; + public bool FixMainWindow { get; set; } = false; + + /// + /// Load the current configuration. + /// Includes adding new colors and migrating from old versions. + /// + public EphemeralConfig(SaveService saveService) + { + _saveService = saveService; + Load(); + } + + private void Load() + { + static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) + { + Penumbra.Log.Error( + $"Error parsing Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); + errorArgs.ErrorContext.Handled = true; + } + + if (File.Exists(_saveService.FileNames.EphemeralConfigFile)) + try + { + var text = File.ReadAllText(_saveService.FileNames.EphemeralConfigFile); + JsonConvert.PopulateObject(text, this, new JsonSerializerSettings + { + Error = HandleDeserializationError, + }); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, + "Error reading ephemeral Configuration, reverting to default.", + "Error reading ephemeral Configuration", NotificationType.Error); + } + } + + /// Save the current configuration. + public void Save() + => _saveService.DelaySave(this, TimeSpan.FromSeconds(5)); + + + public string ToFilename(FilenameService fileNames) + => fileNames.EphemeralConfigFile; + + public void Save(StreamWriter writer) + { + using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + serializer.Serialize(jWriter, this); + } +} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index d7daaf70..ef8a1a05 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -201,7 +201,7 @@ public class Penumbra : IDalamudPlugin sb.Append( $"> **`Synchronous Load (Dalamud): `** {(_services.GetRequiredService().GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")}\n"); sb.Append( - $"> **`Logging: `** Log: {_config.EnableResourceLogging}, Watcher: {_config.EnableResourceWatcher} ({_config.MaxResourceWatcherRecords})\n"); + $"> **`Logging: `** Log: {_config.Ephemeral.EnableResourceLogging}, Watcher: {_config.Ephemeral.EnableResourceWatcher} ({_config.MaxResourceWatcherRecords})\n"); sb.Append($"> **`Use Ownership: `** {_config.UseOwnerNameForCharacterCollection}\n"); sb.AppendLine("**Mods**"); sb.Append($"> **`Installed Mods: `** {_modManager.Count}\n"); diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index e623be3e..7b8ace29 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -14,6 +14,10 @@ public class BackupService Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), files); } + public static void CreatePermanentBackup(FilenameService fileNames) + => Backup.CreatePermanentBackup(Penumbra.Log, new DirectoryInfo(fileNames.ConfigDirectory), PenumbraFiles(fileNames), + "pre_ephemeral_config"); + // Collect all relevant files for penumbra configuration. private static IReadOnlyList PenumbraFiles(FilenameService fileNames) { diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index d896e526..03aedc57 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -1,14 +1,20 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using OtterGui.Classes; using OtterGui.Filesystem; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; +using Penumbra.Enums; using Penumbra.Interop.Services; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; +using Penumbra.UI; using Penumbra.UI.Classes; +using Penumbra.UI.ResourceWatcher; +using Penumbra.UI.Tabs; namespace Penumbra.Services; @@ -26,7 +32,7 @@ public class ConfigMigrationService public string CurrentCollection = ModCollection.DefaultCollectionName; public string DefaultCollection = ModCollection.DefaultCollectionName; public string ForcedCollection = string.Empty; - public Dictionary CharacterCollections = new(); + public Dictionary CharacterCollections = []; public Dictionary ModSortOrder = new(); public bool InvertModListOrder; public bool SortFoldersFirst; @@ -71,9 +77,41 @@ public class ConfigMigrationService Version4To5(); Version5To6(); Version6To7(); + Version7To8(); AddColors(config, true); } + // Migrate to ephemeral config. + private void Version7To8() + { + if (_config.Version != 7) + return; + + _config.Version = 8; + _config.Ephemeral.Version = 8; + + _config.Ephemeral.LastSeenVersion = _data["LastSeenVersion"]?.ToObject() ?? _config.Ephemeral.LastSeenVersion; + _config.Ephemeral.DebugSeparateWindow = _data["DebugSeparateWindow"]?.ToObject() ?? _config.Ephemeral.DebugSeparateWindow; + _config.Ephemeral.TutorialStep = _data["TutorialStep"]?.ToObject() ?? _config.Ephemeral.TutorialStep; + _config.Ephemeral.EnableResourceLogging = _data["EnableResourceLogging"]?.ToObject() ?? _config.Ephemeral.EnableResourceLogging; + _config.Ephemeral.ResourceLoggingFilter = _data["ResourceLoggingFilter"]?.ToObject() ?? _config.Ephemeral.ResourceLoggingFilter; + _config.Ephemeral.EnableResourceWatcher = _data["EnableResourceWatcher"]?.ToObject() ?? _config.Ephemeral.EnableResourceWatcher; + _config.Ephemeral.OnlyAddMatchingResources = + _data["OnlyAddMatchingResources"]?.ToObject() ?? _config.Ephemeral.OnlyAddMatchingResources; + _config.Ephemeral.ResourceWatcherResourceTypes = _data["ResourceWatcherResourceTypes"]?.ToObject() + ?? _config.Ephemeral.ResourceWatcherResourceTypes; + _config.Ephemeral.ResourceWatcherResourceCategories = _data["ResourceWatcherResourceCategories"]?.ToObject() + ?? _config.Ephemeral.ResourceWatcherResourceCategories; + _config.Ephemeral.ResourceWatcherRecordTypes = + _data["ResourceWatcherRecordTypes"]?.ToObject() ?? _config.Ephemeral.ResourceWatcherRecordTypes; + _config.Ephemeral.CollectionPanel = _data["CollectionPanel"]?.ToObject() ?? _config.Ephemeral.CollectionPanel; + _config.Ephemeral.SelectedTab = _data["SelectedTab"]?.ToObject() ?? _config.Ephemeral.SelectedTab; + _config.Ephemeral.ChangedItemFilter = _data["ChangedItemFilter"]?.ToObject() + ?? _config.Ephemeral.ChangedItemFilter; + _config.Ephemeral.FixMainWindow = _data["FixMainWindow"]?.ToObject() ?? _config.Ephemeral.FixMainWindow; + _config.Ephemeral.Save(); + } + // Gendered special collections were added. private void Version6To7() { @@ -93,8 +131,8 @@ public class ConfigMigrationService if (_config.Version != 5) return; - if (_config.TutorialStep == 25) - _config.TutorialStep = 27; + if (_config.Ephemeral.TutorialStep == 25) + _config.Ephemeral.TutorialStep = 27; _config.Version = 6; } diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index c7ed6061..e525c1f4 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -11,17 +11,19 @@ public class FilenameService public readonly string CollectionDirectory; public readonly string LocalDataDirectory; public readonly string ConfigFile; + public readonly string EphemeralConfigFile; public readonly string FilesystemFile; public readonly string ActiveCollectionsFile; public FilenameService(DalamudPluginInterface pi) { ConfigDirectory = pi.ConfigDirectory.FullName; - CollectionDirectory = Path.Combine(pi.GetPluginConfigDirectory(), "collections"); - LocalDataDirectory = Path.Combine(pi.ConfigDirectory.FullName, "mod_data"); + CollectionDirectory = Path.Combine(pi.ConfigDirectory.FullName, "collections"); + LocalDataDirectory = Path.Combine(pi.ConfigDirectory.FullName, "mod_data"); ConfigFile = pi.ConfigFile.FullName; - FilesystemFile = Path.Combine(pi.GetPluginConfigDirectory(), "sort_order.json"); - ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); + FilesystemFile = Path.Combine(pi.ConfigDirectory.FullName, "sort_order.json"); + ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); + EphemeralConfigFile = Path.Combine(pi.ConfigDirectory.FullName, "ephemeral_config.json"); } /// Obtain the path of a collection file given its name. diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 2c4f385d..227f65d7 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -95,7 +95,8 @@ public static class ServiceManager private static IServiceCollection AddConfiguration(this IServiceCollection services) => services.AddTransient() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddCollections(this IServiceCollection services) => services.AddSingleton() diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 3c74aa20..8916d365 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -70,7 +70,7 @@ public class ChangedItemDrawer : IDisposable /// Check if a changed item should be drawn based on its category. public bool FilterChangedItem(string name, object? data, LowerString filter) - => (_config.ChangedItemFilter == AllFlags || _config.ChangedItemFilter.HasFlag(GetCategoryIcon(name, data))) + => (_config.Ephemeral.ChangedItemFilter == AllFlags || _config.Ephemeral.ChangedItemFilter.HasFlag(GetCategoryIcon(name, data))) && (filter.IsEmpty || filter.IsContained(ChangedItemFilterName(name, data))); /// Draw the icon corresponding to the category of a changed item. @@ -172,20 +172,20 @@ public class ChangedItemDrawer : IDisposable void DrawIcon(ChangedItemIcon type) { var icon = _icons[type]; - var flag = _config.ChangedItemFilter.HasFlag(type); + var flag = _config.Ephemeral.ChangedItemFilter.HasFlag(type); ImGui.Image(icon.ImGuiHandle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); if (ImGui.IsItemClicked(ImGuiMouseButton.Left)) { - _config.ChangedItemFilter = flag ? _config.ChangedItemFilter & ~type : _config.ChangedItemFilter | type; - _config.Save(); + _config.Ephemeral.ChangedItemFilter = flag ? _config.Ephemeral.ChangedItemFilter & ~type : _config.Ephemeral.ChangedItemFilter | type; + _config.Ephemeral.Save(); } using var popup = ImRaii.ContextPopupItem(type.ToString()); if (popup) if (ImGui.MenuItem("Enable Only This")) { - _config.ChangedItemFilter = type; - _config.Save(); + _config.Ephemeral.ChangedItemFilter = type; + _config.Ephemeral.Save(); ImGui.CloseCurrentPopup(); } @@ -206,12 +206,12 @@ public class ChangedItemDrawer : IDisposable ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); ImGui.Image(_icons[AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, - _config.ChangedItemFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : - _config.ChangedItemFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); + _config.Ephemeral.ChangedItemFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : + _config.Ephemeral.ChangedItemFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); if (ImGui.IsItemClicked()) { - _config.ChangedItemFilter = _config.ChangedItemFilter == AllFlags ? 0 : AllFlags; - _config.Save(); + _config.Ephemeral.ChangedItemFilter = _config.Ephemeral.ChangedItemFilter == AllFlags ? 0 : AllFlags; + _config.Ephemeral.Save(); } } diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 7589e6ec..dac415d5 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -627,12 +627,20 @@ public class PenumbraChangelog #endregion private (int, ChangeLogDisplayType) ConfigData() - => (_config.LastSeenVersion, _config.ChangeLogDisplayType); + => (_config.Ephemeral.LastSeenVersion, _config.ChangeLogDisplayType); private void Save(int version, ChangeLogDisplayType type) { - _config.LastSeenVersion = version; - _config.ChangeLogDisplayType = type; - _config.Save(); + if (_config.Ephemeral.LastSeenVersion != version) + { + _config.Ephemeral.LastSeenVersion = version; + _config.Ephemeral.Save(); + } + + if (_config.ChangeLogDisplayType != type) + { + _config.ChangeLogDisplayType = type; + _config.Save(); + } } } diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 804a1d01..d52ebb99 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -39,7 +39,7 @@ public sealed class ConfigWindow : Window { _penumbra = penumbra; _configTabs = configTabs; - _configTabs.SelectTab = _config.SelectedTab; + _configTabs.SelectTab = _config.Ephemeral.SelectedTab; } public override bool DrawConditions() @@ -47,7 +47,7 @@ public sealed class ConfigWindow : Window public override void PreDraw() { - if (_config.FixMainWindow) + if (_config.Ephemeral.FixMainWindow) Flags |= ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove; else Flags &= ~(ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove); @@ -99,10 +99,10 @@ public sealed class ConfigWindow : Window else { var type = _configTabs.Draw(); - if (type != _config.SelectedTab) + if (type != _config.Ephemeral.SelectedTab) { - _config.SelectedTab = type; - _config.Save(); + _config.Ephemeral.SelectedTab = type; + _config.Ephemeral.Save(); } } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 000e50db..0ac3b9a0 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -21,6 +21,7 @@ public class ResourceWatcher : IDisposable, ITab public const RecordType AllRecords = RecordType.Request | RecordType.ResourceLoad | RecordType.FileLoad | RecordType.Destruction; private readonly Configuration _config; + private readonly EphemeralConfig _ephemeral; private readonly ResourceService _resources; private readonly ResourceLoader _loader; private readonly ActorService _actors; @@ -35,14 +36,15 @@ public class ResourceWatcher : IDisposable, ITab { _actors = actors; _config = config; + _ephemeral = config.Ephemeral; _resources = resources; _loader = loader; - _table = new ResourceWatcherTable(config, _records); + _table = new ResourceWatcherTable(config.Ephemeral, _records); _resources.ResourceRequested += OnResourceRequested; _resources.ResourceHandleDestructor += OnResourceDestroyed; _loader.ResourceLoaded += OnResourceLoaded; _loader.FileLoaded += OnFileLoaded; - UpdateFilter(_config.ResourceLoggingFilter, false); + UpdateFilter(_ephemeral.ResourceLoggingFilter, false); _newMaxEntries = _config.MaxResourceWatcherRecords; } @@ -71,11 +73,11 @@ public class ResourceWatcher : IDisposable, ITab UpdateRecords(); ImGui.SetCursorPosY(ImGui.GetCursorPosY() + ImGui.GetTextLineHeightWithSpacing() / 2); - var isEnabled = _config.EnableResourceWatcher; + var isEnabled = _ephemeral.EnableResourceWatcher; if (ImGui.Checkbox("Enable", ref isEnabled)) { - _config.EnableResourceWatcher = isEnabled; - _config.Save(); + _ephemeral.EnableResourceWatcher = isEnabled; + _ephemeral.Save(); } ImGui.SameLine(); @@ -85,19 +87,19 @@ public class ResourceWatcher : IDisposable, ITab Clear(); ImGui.SameLine(); - var onlyMatching = _config.OnlyAddMatchingResources; + var onlyMatching = _ephemeral.OnlyAddMatchingResources; if (ImGui.Checkbox("Store Only Matching", ref onlyMatching)) { - _config.OnlyAddMatchingResources = onlyMatching; - _config.Save(); + _ephemeral.OnlyAddMatchingResources = onlyMatching; + _ephemeral.Save(); } ImGui.SameLine(); - var writeToLog = _config.EnableResourceLogging; + var writeToLog = _ephemeral.EnableResourceLogging; if (ImGui.Checkbox("Write to Log", ref writeToLog)) { - _config.EnableResourceLogging = writeToLog; - _config.Save(); + _ephemeral.EnableResourceLogging = writeToLog; + _ephemeral.Save(); } ImGui.SameLine(); @@ -136,8 +138,8 @@ public class ResourceWatcher : IDisposable, ITab if (config) { - _config.ResourceLoggingFilter = newString; - _config.Save(); + _ephemeral.ResourceLoggingFilter = newString; + _ephemeral.Save(); } } @@ -196,20 +198,20 @@ public class ResourceWatcher : IDisposable, ITab Utf8GamePath original, GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue) { - if (_config.EnableResourceLogging && FilterMatch(original.Path, out var match)) + if (_ephemeral.EnableResourceLogging && FilterMatch(original.Path, out var match)) Penumbra.Log.Information($"[ResourceLoader] [REQ] {match} was requested {(sync ? "synchronously." : "asynchronously.")}"); - if (!_config.EnableResourceWatcher) + if (!_ephemeral.EnableResourceWatcher) return; var record = Record.CreateRequest(original.Path, sync); - if (!_config.OnlyAddMatchingResources || _table.WouldBeVisible(record)) + if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } private unsafe void OnResourceLoaded(ResourceHandle* handle, Utf8GamePath path, FullPath? manipulatedPath, ResolveData data) { - if (_config.EnableResourceLogging) + if (_ephemeral.EnableResourceLogging) { var log = FilterMatch(path.Path, out var name); var name2 = string.Empty; @@ -224,41 +226,41 @@ public class ResourceWatcher : IDisposable, ITab } } - if (!_config.EnableResourceWatcher) + if (!_ephemeral.EnableResourceWatcher) return; var record = manipulatedPath == null ? Record.CreateDefaultLoad(path.Path, handle, data.ModCollection, Name(data)) : Record.CreateLoad(manipulatedPath.Value.InternalName, path.Path, handle, data.ModCollection, Name(data)); - if (!_config.OnlyAddMatchingResources || _table.WouldBeVisible(record)) + if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } private unsafe void OnFileLoaded(ResourceHandle* resource, ByteString path, bool success, bool custom, ByteString _) { - if (_config.EnableResourceLogging && FilterMatch(path, out var match)) + if (_ephemeral.EnableResourceLogging && FilterMatch(path, out var match)) Penumbra.Log.Information( $"[ResourceLoader] [FILE] [{resource->FileType}] Loading {match} from {(custom ? "local files" : "SqPack")} into 0x{(ulong)resource:X} returned {success}."); - if (!_config.EnableResourceWatcher) + if (!_ephemeral.EnableResourceWatcher) return; var record = Record.CreateFileLoad(path, resource, success, custom); - if (!_config.OnlyAddMatchingResources || _table.WouldBeVisible(record)) + if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } private unsafe void OnResourceDestroyed(ResourceHandle* resource) { - if (_config.EnableResourceLogging && FilterMatch(resource->FileName(), out var match)) + if (_ephemeral.EnableResourceLogging && FilterMatch(resource->FileName(), out var match)) Penumbra.Log.Information( $"[ResourceLoader] [DEST] [{resource->FileType}] Destroyed {match} at 0x{(ulong)resource:X}."); - if (!_config.EnableResourceWatcher) + if (!_ephemeral.EnableResourceWatcher) return; var record = Record.CreateDestruction(resource); - if (!_config.OnlyAddMatchingResources || _table.WouldBeVisible(record)) + if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 89dd42bb..b47574d0 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -13,7 +13,7 @@ namespace Penumbra.UI.ResourceWatcher; internal sealed class ResourceWatcherTable : Table { - public ResourceWatcherTable(Configuration config, IReadOnlyCollection records) + public ResourceWatcherTable(EphemeralConfig config, IReadOnlyCollection records) : base("##records", records, new PathColumn { Label = "Path" }, @@ -86,9 +86,9 @@ internal sealed class ResourceWatcherTable : Table private sealed class RecordTypeColumn : ColumnFlags { - private readonly Configuration _config; + private readonly EphemeralConfig _config; - public RecordTypeColumn(Configuration config) + public RecordTypeColumn(EphemeralConfig config) { AllFlags = ResourceWatcher.AllRecords; _config = config; @@ -174,9 +174,9 @@ internal sealed class ResourceWatcherTable : Table private sealed class ResourceCategoryColumn : ColumnFlags { - private readonly Configuration _config; + private readonly EphemeralConfig _config; - public ResourceCategoryColumn(Configuration config) + public ResourceCategoryColumn(EphemeralConfig config) { _config = config; AllFlags = ResourceExtensions.AllResourceCategories; @@ -209,9 +209,9 @@ internal sealed class ResourceWatcherTable : Table private sealed class ResourceTypeColumn : ColumnFlags { - private readonly Configuration _config; + private readonly EphemeralConfig _config; - public ResourceTypeColumn(Configuration config) + public ResourceTypeColumn(EphemeralConfig config) { _config = config; AllFlags = Enum.GetValues().Aggregate((v, f) => v | f); diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 24aa933c..2d30f9cf 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -16,7 +16,7 @@ namespace Penumbra.UI.Tabs; public class CollectionsTab : IDisposable, ITab { - private readonly Configuration _config; + private readonly EphemeralConfig _config; private readonly CollectionSelector _selector; private readonly CollectionPanel _panel; private readonly TutorialService _tutorial; @@ -42,7 +42,7 @@ public class CollectionsTab : IDisposable, ITab public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, CollectionManager collectionManager, ModStorage modStorage, ActorService actors, ITargetManager targets, TutorialService tutorial) { - _config = configuration; + _config = configuration.Ephemeral; _tutorial = tutorial; _selector = new CollectionSelector(configuration, communicator, collectionManager.Storage, collectionManager.Active, _tutorial); _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage); diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/DebugTab.cs index c5811051..4f554ac5 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/DebugTab.cs @@ -115,7 +115,7 @@ public class DebugTab : Window, ITab => "Debug"u8; public bool IsVisible - => _config.DebugMode && !_config.DebugSeparateWindow; + => _config is { DebugMode: true, Ephemeral.DebugSeparateWindow: false }; #if DEBUG private const string DebugVersionString = "(Debug)"; @@ -201,12 +201,12 @@ public class DebugTab : Window, ITab if (!ImGui.CollapsingHeader("General")) return; - var separateWindow = _config.DebugSeparateWindow; + var separateWindow = _config.Ephemeral.DebugSeparateWindow; if (ImGui.Checkbox("Draw as Separate Window", ref separateWindow)) { - IsOpen = true; - _config.DebugSeparateWindow = separateWindow; - _config.Save(); + IsOpen = true; + _config.Ephemeral.DebugSeparateWindow = separateWindow; + _config.Ephemeral.Save(); } using (var table = Table("##DebugGeneralTable", 2, ImGuiTableFlags.SizingFixedFit)) @@ -949,11 +949,11 @@ public class DebugTab : Window, ITab => DrawContent(); public override bool DrawConditions() - => _config.DebugMode && _config.DebugSeparateWindow; + => _config.DebugMode && _config.Ephemeral.DebugSeparateWindow; public override void OnClose() { - _config.DebugSeparateWindow = false; - _config.Save(); + _config.Ephemeral.DebugSeparateWindow = false; + _config.Ephemeral.Save(); } } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 6274f209..70a94ecd 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -78,8 +78,8 @@ public class SettingsTab : ITab return; DrawEnabledBox(); - Checkbox("Lock Main Window", "Prevent the main window from being resized or moved.", _config.FixMainWindow, - v => _config.FixMainWindow = v); + EphemeralCheckbox("Lock Main Window", "Prevent the main window from being resized or moved.", _config.Ephemeral.FixMainWindow, + v => _config.Ephemeral.FixMainWindow = v); ImGui.NewLine(); DrawRootFolder(); @@ -107,6 +107,21 @@ public class SettingsTab : ITab ImGuiUtil.LabeledHelpMarker(label, tooltip); } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void EphemeralCheckbox(string label, string tooltip, bool current, Action setter) + { + using var id = ImRaii.PushId(label); + var tmp = current; + if (ImGui.Checkbox(string.Empty, ref tmp) && tmp != current) + { + setter(tmp); + _config.Ephemeral.Save(); + } + + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker(label, tooltip); + } + #region Main Settings /// @@ -384,7 +399,10 @@ public class SettingsTab : ITab { _config.HideChangedItemFilters = v; if (v) - _config.ChangedItemFilter = ChangedItemDrawer.AllFlags; + { + _config.Ephemeral.ChangedItemFilter = ChangedItemDrawer.AllFlags; + _config.Ephemeral.Save(); + } }); Checkbox("Hide Priority Numbers in Mod Selector", "Hides the bracketed non-zero priority numbers displayed in the mod selector when there is enough space for them.", @@ -863,8 +881,8 @@ public class SettingsTab : ITab ImGui.SetCursorPos(new Vector2(xPos, 3 * ImGui.GetFrameHeightWithSpacing())); if (ImGui.Button("Restart Tutorial", new Vector2(width, 0))) { - _config.TutorialStep = 0; - _config.Save(); + _config.Ephemeral.TutorialStep = 0; + _config.Ephemeral.Save(); } ImGui.SetCursorPos(new Vector2(xPos, 4 * ImGui.GetFrameHeightWithSpacing())); diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index 86c4dd46..6c6b0612 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -55,10 +55,10 @@ public class TutorialService + " - 'furniture': most indoor furniture, does not currently work outdoors\n" + " - any specific actor name to redraw all actors of that exactly matching name."; - private readonly Configuration _config; - private readonly Tutorial _tutorial; + private readonly EphemeralConfig _config; + private readonly Tutorial _tutorial; - public TutorialService(Configuration config) + public TutorialService(EphemeralConfig config) { _config = config; _tutorial = new Tutorial() From 908239bf13bef8c95edab99285d7bc3a93b6d42f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Nov 2023 16:53:42 +0100 Subject: [PATCH 0214/1381] Meep. --- Penumbra/EphemeralConfig.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 8003629d..b6a06100 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -48,7 +48,7 @@ public class EphemeralConfig : ISavable static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) { Penumbra.Log.Error( - $"Error parsing Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); + $"Error parsing ephemeral Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); errorArgs.ErrorContext.Handled = true; } From 69c493b9d6c734e867eca82cd00951002752fdce Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Nov 2023 17:09:11 +0100 Subject: [PATCH 0215/1381] Morp. --- Penumbra/EphemeralConfig.cs | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index b6a06100..bb4a5eb8 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -52,21 +52,23 @@ public class EphemeralConfig : ISavable errorArgs.ErrorContext.Handled = true; } - if (File.Exists(_saveService.FileNames.EphemeralConfigFile)) - try + if (!File.Exists(_saveService.FileNames.EphemeralConfigFile)) + return; + + try + { + var text = File.ReadAllText(_saveService.FileNames.EphemeralConfigFile); + JsonConvert.PopulateObject(text, this, new JsonSerializerSettings { - var text = File.ReadAllText(_saveService.FileNames.EphemeralConfigFile); - JsonConvert.PopulateObject(text, this, new JsonSerializerSettings - { - Error = HandleDeserializationError, - }); - } - catch (Exception ex) - { - Penumbra.Messager.NotificationMessage(ex, - "Error reading ephemeral Configuration, reverting to default.", - "Error reading ephemeral Configuration", NotificationType.Error); - } + Error = HandleDeserializationError, + }); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, + "Error reading ephemeral Configuration, reverting to default.", + "Error reading ephemeral Configuration", NotificationType.Error); + } } /// Save the current configuration. From d84715ad27372aae31b50958d655800066d79888 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 17 Nov 2023 23:51:42 +0100 Subject: [PATCH 0216/1381] =?UTF-8?q?Fix=20stain=20preview=20(=E2=88=9A=20?= =?UTF-8?q?+=20order)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Penumbra/Services/StainService.cs | 7 ++++--- .../AdvancedWindow/ModEditWindow.Materials.ColorTable.cs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 63f6d05e..a0bca570 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -6,6 +6,7 @@ using ImGuiNET; using OtterGui.Widgets; using Penumbra.GameData.Data; using Penumbra.GameData.Files; +using Penumbra.UI.AdvancedWindow; using Penumbra.Util; namespace Penumbra.Services; @@ -61,11 +62,11 @@ public class StainService : IDisposable ImGui.SameLine(); var frame = new Vector2(ImGui.GetTextLineHeight()); - ImGui.ColorButton("D", new Vector4(colors.Diffuse, 1), 0, frame); + ImGui.ColorButton("D", new Vector4(ModEditWindow.PseudoSqrtRgb(colors.Diffuse), 1), 0, frame); ImGui.SameLine(); - ImGui.ColorButton("E", new Vector4(colors.Emissive, 1), 0, frame); + ImGui.ColorButton("S", new Vector4(ModEditWindow.PseudoSqrtRgb(colors.Specular), 1), 0, frame); ImGui.SameLine(); - ImGui.ColorButton("S", new Vector4(colors.Specular, 1), 0, frame); + ImGui.ColorButton("E", new Vector4(ModEditWindow.PseudoSqrtRgb(colors.Emissive), 1), 0, frame); return ret; } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index d1cb4c94..a4e25f77 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -528,7 +528,7 @@ public partial class ModEditWindow private static float PseudoSqrtRgb(float x) => x < 0.0f ? -MathF.Sqrt(-x) : MathF.Sqrt(x); - private static Vector3 PseudoSqrtRgb(Vector3 vec) + internal static Vector3 PseudoSqrtRgb(Vector3 vec) => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z)); private static Vector4 PseudoSqrtRgb(Vector4 vec) From 3e6967002b95b1ffee3b4d0898ae28b618424533 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 18 Nov 2023 13:15:14 +0100 Subject: [PATCH 0217/1381] Allow filtering for none in certain cases. --- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 42 +++++++++++++------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index bff021bc..c307f6f4 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -517,7 +517,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector Appropriately identify and set the string filter and its type. @@ -531,12 +532,12 @@ public sealed class ModFileSystemSelector : FileSystemSelector filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 1), 'N' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 1), - 'a' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 2), - 'A' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 2), - 'c' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 3), - 'C' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 3), - 't' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 4), - 'T' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 4), + 'a' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 2), + 'A' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 2), + 'c' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 3), + 'C' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 3), + 't' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 4), + 'T' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 4), _ => (new LowerString(filterValue), 0), }, _ => (new LowerString(filterValue), 0), @@ -545,6 +546,16 @@ public sealed class ModFileSystemSelector : FileSystemSelector /// Check the state filter for a specific pair of has/has-not flags. /// Uses count == 0 to check for has-not and count != 0 for has. @@ -584,13 +595,16 @@ public sealed class ModFileSystemSelector : FileSystemSelector false, - 0 => !(leaf.FullName().Contains(_modFilter.Lower, IgnoreCase) || mod.Name.Contains(_modFilter)), - 1 => !mod.Name.Contains(_modFilter), - 2 => !mod.Author.Contains(_modFilter), - 3 => !mod.LowerChangedItemsString.Contains(_modFilter.Lower), - 4 => !mod.AllTagsLower.Contains(_modFilter.Lower), - _ => false, // Should never happen + -1 => false, + 0 => !(leaf.FullName().Contains(_modFilter.Lower, IgnoreCase) || mod.Name.Contains(_modFilter)), + 1 => !mod.Name.Contains(_modFilter), + 2 => !mod.Author.Contains(_modFilter), + 3 => !mod.LowerChangedItemsString.Contains(_modFilter.Lower), + 4 => !mod.AllTagsLower.Contains(_modFilter.Lower), + 2 + EmptyOffset => !mod.Author.IsEmpty, + 3 + EmptyOffset => mod.LowerChangedItemsString.Length > 0, + 4 + EmptyOffset => mod.AllTagsLower.Length > 0, + _ => false, // Should never happen }; } From 85500f0e9d89cda2e26e00730b28409a82d883db Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 18 Nov 2023 13:15:33 +0100 Subject: [PATCH 0218/1381] Improve Multi Mod selection. --- Penumbra/Services/FilenameService.cs | 28 ++---- Penumbra/Services/ServiceManager.cs | 1 + Penumbra/UI/ModsTab/ModPanel.cs | 51 ++--------- Penumbra/UI/ModsTab/MultiModPanel.cs | 125 +++++++++++++++++++++++++++ 4 files changed, 139 insertions(+), 66 deletions(-) create mode 100644 Penumbra/UI/ModsTab/MultiModPanel.cs diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index e525c1f4..cf99c6c8 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -5,26 +5,15 @@ using Penumbra.Mods; namespace Penumbra.Services; -public class FilenameService +public class FilenameService(DalamudPluginInterface pi) { - public readonly string ConfigDirectory; - public readonly string CollectionDirectory; - public readonly string LocalDataDirectory; - public readonly string ConfigFile; - public readonly string EphemeralConfigFile; - public readonly string FilesystemFile; - public readonly string ActiveCollectionsFile; - - public FilenameService(DalamudPluginInterface pi) - { - ConfigDirectory = pi.ConfigDirectory.FullName; - CollectionDirectory = Path.Combine(pi.ConfigDirectory.FullName, "collections"); - LocalDataDirectory = Path.Combine(pi.ConfigDirectory.FullName, "mod_data"); - ConfigFile = pi.ConfigFile.FullName; - FilesystemFile = Path.Combine(pi.ConfigDirectory.FullName, "sort_order.json"); - ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); - EphemeralConfigFile = Path.Combine(pi.ConfigDirectory.FullName, "ephemeral_config.json"); - } + public readonly string ConfigDirectory = pi.ConfigDirectory.FullName; + public readonly string CollectionDirectory = Path.Combine(pi.ConfigDirectory.FullName, "collections"); + public readonly string LocalDataDirectory = Path.Combine(pi.ConfigDirectory.FullName, "mod_data"); + public readonly string ConfigFile = pi.ConfigFile.FullName; + public readonly string EphemeralConfigFile = Path.Combine(pi.ConfigDirectory.FullName, "ephemeral_config.json"); + public readonly string FilesystemFile = Path.Combine(pi.ConfigDirectory.FullName, "sort_order.json"); + public readonly string ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); /// Obtain the path of a collection file given its name. public string CollectionFile(ModCollection collection) @@ -34,7 +23,6 @@ public class FilenameService public string CollectionFile(string collectionName) => Path.Combine(CollectionDirectory, $"{collectionName}.json"); - /// Obtain the path of the local data file given a mod directory. Returns an empty string if the mod is temporary. public string LocalDataFile(Mod mod) => LocalDataFile(mod.ModPath.FullName); diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 227f65d7..73be8834 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -149,6 +149,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() + .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index 59c9d279..15961ff3 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -1,26 +1,24 @@ -using Dalamud.Interface; using Dalamud.Plugin; -using ImGuiNET; -using OtterGui; -using OtterGui.Raii; using Penumbra.Mods; -using Penumbra.Mods.Manager; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; public class ModPanel : IDisposable { + private readonly MultiModPanel _multiModPanel; private readonly ModFileSystemSelector _selector; private readonly ModEditWindow _editWindow; private readonly ModPanelHeader _header; private readonly ModPanelTabBar _tabs; - public ModPanel(DalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs) + public ModPanel(DalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs, + MultiModPanel multiModPanel) { _selector = selector; _editWindow = editWindow; _tabs = tabs; + _multiModPanel = multiModPanel; _header = new ModPanelHeader(pi); _selector.SelectionChanged += OnSelectionChange; } @@ -29,7 +27,7 @@ public class ModPanel : IDisposable { if (!_valid) { - DrawMultiSelection(); + _multiModPanel.Draw(); return; } @@ -43,45 +41,6 @@ public class ModPanel : IDisposable _header.Dispose(); } - private void DrawMultiSelection() - { - if (_selector.SelectedPaths.Count == 0) - return; - - var sizeType = ImGui.GetFrameHeight(); - var availableSizePercent = (ImGui.GetContentRegionAvail().X - sizeType - 4 * ImGui.GetStyle().CellPadding.X) / 100; - var sizeMods = availableSizePercent * 35; - var sizeFolders = availableSizePercent * 65; - - ImGui.NewLine(); - ImGui.TextUnformatted("Currently Selected Objects"); - ImGui.Separator(); - using var table = ImRaii.Table("mods", 3, ImGuiTableFlags.RowBg); - ImGui.TableSetupColumn("type", ImGuiTableColumnFlags.WidthFixed, sizeType); - ImGui.TableSetupColumn("mod", ImGuiTableColumnFlags.WidthFixed, sizeMods); - ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthFixed, sizeFolders); - - var i = 0; - foreach (var (fullName, path) in _selector.SelectedPaths.Select(p => (p.FullName(), p)) - .OrderBy(p => p.Item1, StringComparer.OrdinalIgnoreCase)) - { - using var id = ImRaii.PushId(i++); - ImGui.TableNextColumn(); - var icon = (path is ModFileSystem.Leaf ? FontAwesomeIcon.FileCircleMinus : FontAwesomeIcon.FolderMinus).ToIconString(); - if (ImGuiUtil.DrawDisabledButton(icon, new Vector2(sizeType), "Remove from selection.", false, true)) - _selector.RemovePathFromMultiselection(path); - - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(path is ModFileSystem.Leaf l ? l.Value.Name : string.Empty); - - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(fullName); - } - } - - private bool _valid; private Mod _mod = null!; diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs new file mode 100644 index 00000000..1e4117ec --- /dev/null +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -0,0 +1,125 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using Penumbra.Mods; +using Penumbra.Mods.Manager; + +namespace Penumbra.UI.ModsTab; + +public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _editor) +{ + public void Draw() + { + if (_selector.SelectedPaths.Count == 0) + return; + + ImGui.NewLine(); + DrawModList(); + DrawMultiTagger(); + } + + private void DrawModList() + { + using var tree = ImRaii.TreeNode("Currently Selected Objects", ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.NoTreePushOnOpen); + ImGui.Separator(); + if (!tree) + return; + + var sizeType = ImGui.GetFrameHeight(); + var availableSizePercent = (ImGui.GetContentRegionAvail().X - sizeType - 4 * ImGui.GetStyle().CellPadding.X) / 100; + var sizeMods = availableSizePercent * 35; + var sizeFolders = availableSizePercent * 65; + + using (var table = ImRaii.Table("mods", 3, ImGuiTableFlags.RowBg)) + { + if (!table) + return; + + ImGui.TableSetupColumn("type", ImGuiTableColumnFlags.WidthFixed, sizeType); + ImGui.TableSetupColumn("mod", ImGuiTableColumnFlags.WidthFixed, sizeMods); + ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthFixed, sizeFolders); + + var i = 0; + foreach (var (fullName, path) in _selector.SelectedPaths.Select(p => (p.FullName(), p)) + .OrderBy(p => p.Item1, StringComparer.OrdinalIgnoreCase)) + { + using var id = ImRaii.PushId(i++); + ImGui.TableNextColumn(); + var icon = (path is ModFileSystem.Leaf ? FontAwesomeIcon.FileCircleMinus : FontAwesomeIcon.FolderMinus).ToIconString(); + if (ImGuiUtil.DrawDisabledButton(icon, new Vector2(sizeType), "Remove from selection.", false, true)) + _selector.RemovePathFromMultiselection(path); + + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(path is ModFileSystem.Leaf l ? l.Value.Name : string.Empty); + + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(fullName); + } + } + + ImGui.Separator(); + } + + private string _tag = string.Empty; + private readonly List _addMods = []; + private readonly List<(Mod, int)> _removeMods = []; + + private void DrawMultiTagger() + { + var width = ImGuiHelpers.ScaledVector2(150, 0); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("Multi Tagger:"); + ImGui.SameLine(); + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - 2 * (width.X + ImGui.GetStyle().ItemSpacing.X)); + ImGui.InputTextWithHint("##tag", "Local Tag Name...", ref _tag, 128); + + UpdateTagCache(); + var label = _addMods.Count > 0 + ? $"Add to {_addMods.Count} Mods" + : "Add"; + var tooltip = _addMods.Count == 0 + ? _tag.Length == 0 + ? "No tag specified." + : $"All mods selected already contain the tag \"{_tag}\", either locally or as mod data." + : $"Add the tag \"{_tag}\" to {_addMods.Count} mods as a local tag:\n\n\t{string.Join("\n\t", _addMods.Select(m => m.Name.Text))}"; + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton(label, width, tooltip, _addMods.Count == 0)) + foreach (var mod in _addMods) + _editor.ChangeLocalTag(mod, mod.LocalTags.Count, _tag); + + label = _removeMods.Count > 0 + ? $"Remove from {_removeMods.Count} Mods" + : "Remove"; + tooltip = _removeMods.Count == 0 + ? _tag.Length == 0 + ? "No tag specified." + : $"No selected mod contains the tag \"{_tag}\" locally." + : $"Remove the local tag \"{_tag}\" from {_removeMods.Count} mods:\n\n\t{string.Join("\n\t", _removeMods.Select(m => m.Item1.Name.Text))}"; + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton(label, width, tooltip, _removeMods.Count == 0)) + foreach (var (mod, index) in _removeMods) + _editor.ChangeLocalTag(mod, index, string.Empty); + ImGui.Separator(); + } + + private void UpdateTagCache() + { + _addMods.Clear(); + _removeMods.Clear(); + if (_tag.Length == 0) + return; + + foreach (var leaf in _selector.SelectedPaths.OfType()) + { + var index = leaf.Value.LocalTags.IndexOf(_tag); + if (index >= 0) + _removeMods.Add((leaf.Value, index)); + else if (!leaf.Value.ModTags.Contains(_tag)) + _addMods.Add(leaf.Value); + } + } +} From 357b11eb256d0ed8914ee313b5b7810756c613fb Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 18 Nov 2023 12:17:35 +0000 Subject: [PATCH 0219/1381] [CI] Updating repo.json for testing_0.8.1.10 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e804fb1e..ae281fee 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.1.8", - "TestingAssemblyVersion": "0.8.1.9", + "TestingAssemblyVersion": "0.8.1.10", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.1.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.1.10/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 55ddafea4bdb2257513ccd81f4602a5e7a5e356e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Nov 2023 15:16:05 +0100 Subject: [PATCH 0220/1381] 0.8.2.0 --- Penumbra/UI/Changelog.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index dac415d5..c9b3e96d 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -44,10 +44,38 @@ public class PenumbraChangelog Add8_0_0(Changelog); Add8_1_1(Changelog); Add8_1_2(Changelog); + Add8_2_0(Changelog); } #region Changelogs + private static void Add8_2_0(Changelog log) + => log.NextVersion("Version 0.8.2.0") + .RegisterHighlight( + "You can now redraw indoor furniture. This may not be entirely stable and might break some customizable decoration like wallpapered walls.") + .RegisterEntry("The redraw bar has been slightly improved and disables currently unavailable redraw commands now.") + .RegisterEntry("Redrawing players now also actively redraws any accessories they are using.") + .RegisterEntry("Power-users can now redraw game objects by index via chat command.") + .RegisterHighlight( + "You can now filter for the special case 'None' for filters where that makes sense (like Tags or Changed Items).") + .RegisterHighlight("When selecting multiple mods, you can now add or remove tags from them at once.") + .RegisterEntry( + "The dye template combo in advanced material editing now displays the currently selected dye as it would appear with the respective template.") + .RegisterEntry("Fixed an issue with the changed item identification for left rings.") + .RegisterEntry("Updated BNPC data.") + .RegisterEntry( + "Some configuration like the currently selected tab states are now stored in a separate file that is not backed up and saved less often.") + .RegisterEntry("Added option to open the Penumbra main window at game start independently of Debug Mode.") + .RegisterEntry("Fixed some tooltips in the advanced editing window. (0.8.1.8)") + .RegisterEntry("Fixed clicking to linked changed items not working. (0.8.1.8)") + .RegisterEntry("Support correct handling of offhand-parts for two-handed weapons for changed items. (0.8.1.7)") + .RegisterEntry("Fixed renaming the mod directory not updating paths in the advanced window. (0.8.1.6)") + .RegisterEntry("Fixed portraits not respecting your card settings. (0.8.1.6)") + .RegisterEntry("Added ReverseResolvePlayerPathsAsync for IPC. (0.8.1.6)") + .RegisterEntry("Expanded the tooltip for Wait for Plugins on Startup. (0.8.1.5)") + .RegisterEntry("Disabled window sounds for some popup windows. (0.8.1.5)") + .RegisterEntry("Added support for middle-clicking mods to enable/disable them. (0.8.1.5)"); + private static void Add8_1_2(Changelog log) => log.NextVersion("Version 0.8.1.2") .RegisterEntry("Fixed an issue keeping mods selected after their deletion.") From 8a675215119d91b4559579daae8c0ae7f9fc3388 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Nov 2023 15:16:05 +0100 Subject: [PATCH 0221/1381] 0.8.2.0 --- Penumbra/UI/Changelog.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index c9b3e96d..1cdb8ae4 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -61,6 +61,7 @@ public class PenumbraChangelog .RegisterHighlight("When selecting multiple mods, you can now add or remove tags from them at once.") .RegisterEntry( "The dye template combo in advanced material editing now displays the currently selected dye as it would appear with the respective template.") + .RegisterEntry("The On-Screen tab and associated functionality has been heavily improved by Ny.") .RegisterEntry("Fixed an issue with the changed item identification for left rings.") .RegisterEntry("Updated BNPC data.") .RegisterEntry( From 42042622368c9e0a1a8ac2cbd1a34efad73b35f6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 22 Nov 2023 14:20:25 +0000 Subject: [PATCH 0222/1381] [CI] Updating repo.json for 0.8.2.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index ae281fee..4f7947af 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.1.8", - "TestingAssemblyVersion": "0.8.1.10", + "AssemblyVersion": "0.8.2.0", + "TestingAssemblyVersion": "0.8.2.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.1.10/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.1.8/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a6f7fd623c7285dabf06dc2b3422a993dc7b3537 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 21 Nov 2023 19:14:01 +0100 Subject: [PATCH 0223/1381] ResourceTree: Fix model path resolving --- Penumbra/Interop/ResourceTree/ResolveContext.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 73abcb4d..5a5ecdd9 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -154,8 +154,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, PointerModelResourceHandle; - if (!Utf8GamePath.FromByteString(ResolveMdlPath(CharacterBase, SlotIndex), out var path)) - return null; + var path = ResolveModelPath(); if (Global.Nodes.TryGetValue((path, (nint)mdlResource), out var cached)) return cached; From 43c6b52d0bd779038d3c8371c1fabca98bf03360 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 22 Nov 2023 14:27:30 +0000 Subject: [PATCH 0224/1381] [CI] Updating repo.json for 0.8.2.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 4f7947af..741a93c3 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.2.0", - "TestingAssemblyVersion": "0.8.2.0", + "AssemblyVersion": "0.8.2.1", + "TestingAssemblyVersion": "0.8.2.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a408b8918ce91acd15513557202ce213b672a550 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 25 Nov 2023 18:30:43 +0100 Subject: [PATCH 0225/1381] Make hooks not leak. --- OtterGui | 2 +- Penumbra/Interop/ResourceLoading/TexMdlService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index b09bbcc2..3a1a3f1a 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit b09bbcc276363bc994d90b641871e6280898b6e5 +Subproject commit 3a1a3f1a1f2021b063617ac9b294b579a154706e diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/ResourceLoading/TexMdlService.cs index 68ad518c..b9279f54 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/ResourceLoading/TexMdlService.cs @@ -8,7 +8,7 @@ using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceLoading; -public unsafe class TexMdlService +public unsafe class TexMdlService : IDisposable { /// Custom ulong flag to signal our files as opposed to SE files. public static readonly IntPtr CustomFileFlag = new(0xDEADBEEF); From 5e76ab3b843a88f514f1a6f51b0d15464b496fff Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 26 Nov 2023 20:18:36 +0100 Subject: [PATCH 0226/1381] ResourceTree: Add filtering to the UI --- Penumbra/Interop/ResourceTree/ResourceNode.cs | 2 + .../ResourceTree/ResourceTreeFactory.cs | 3 + .../UI/AdvancedWindow/ResourceTreeViewer.cs | 123 ++++++++++++++++-- Penumbra/UI/ChangedItemDrawer.cs | 39 ++++-- 4 files changed, 145 insertions(+), 22 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 53dedfa0..7ec75893 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -9,6 +9,7 @@ public class ResourceNode : ICloneable public string? Name; public string? FallbackName; public ChangedItemIcon Icon; + public ChangedItemIcon DescendentIcons; public readonly ResourceType Type; public readonly nint ObjectAddress; public readonly nint ResourceHandle; @@ -49,6 +50,7 @@ public class ResourceNode : ICloneable Name = other.Name; FallbackName = other.FallbackName; Icon = other.Icon; + DescendentIcons = other.DescendentIcons; Type = other.Type; ObjectAddress = other.ObjectAddress; ResourceHandle = other.ResourceHandle; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 0e3a92e2..b3b62359 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -171,6 +171,9 @@ public class ResourceTreeFactory { if (node.Name == parent?.Name) node.Name = null; + + if (parent != null) + parent.DescendentIcons |= node.Icon | node.DescendentIcons; }); } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index ef847d8d..dc7fb55c 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -23,6 +23,10 @@ public class ResourceTreeViewer private readonly Action _drawActions; private readonly HashSet _unfolded; + private TreeCategory _categoryFilter; + private ChangedItemDrawer.ChangedItemIcon _typeFilter; + private string _nameFilter; + private Task? _task; public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, @@ -35,6 +39,10 @@ public class ResourceTreeViewer _onRefresh = onRefresh; _drawActions = drawActions; _unfolded = new HashSet(); + + _categoryFilter = AllCategories; + _typeFilter = ChangedItemDrawer.AllFlags; + _nameFilter = string.Empty; } public void Draw() @@ -42,6 +50,8 @@ public class ResourceTreeViewer if (ImGui.Button("Refresh Character List") || _task == null) _task = RefreshCharacterList(); + DrawFilters(); + using var child = ImRaii.Child("##Data"); if (!child) return; @@ -62,12 +72,11 @@ public class ResourceTreeViewer var debugMode = _config.DebugMode; foreach (var (tree, index) in _task.Result.WithIndex()) { - var headerColorId = - tree.LocalPlayerRelated ? ColorId.ResTreeLocalPlayer : - tree.PlayerRelated ? ColorId.ResTreePlayer : - tree.Networked ? ColorId.ResTreeNetworked : - ColorId.ResTreeNonNetworked; - using (var c = ImRaii.PushColor(ImGuiCol.Text, headerColorId.Value())) + var category = Classify(tree); + if (!_categoryFilter.HasFlag(category) || !tree.Name.Contains(_nameFilter)) + continue; + + using (var c = ImRaii.PushColor(ImGuiCol.Text, CategoryColor(category).Value())) { var isOpen = ImGui.CollapsingHeader($"{tree.Name}##{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); if (debugMode) @@ -102,6 +111,34 @@ public class ResourceTreeViewer } } + private void DrawFilters() + { + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + + using (var id = ImRaii.PushId("TreeCategoryFilter")) + { + var spacing = ImGui.GetStyle().ItemInnerSpacing.X; + var categoryFilter = (uint)_categoryFilter; + foreach (var category in Enum.GetValues()) + { + ImGui.SameLine(0.0f, spacing); + using var c = ImRaii.PushColor(ImGuiCol.CheckMark, CategoryColor(category).Value()); + ImGui.CheckboxFlags($"##{category}", ref categoryFilter, (uint)category); + ImGuiUtil.HoverTooltip(CategoryFilterDescription(category)); + } + _categoryFilter = (TreeCategory)categoryFilter; + } + + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + + ImGui.SameLine(); + _changedItemDrawer.DrawTypeFilter(ref _typeFilter); + + ImGui.InputTextWithHint("##TreeNameFilter", "Filter by Character/Entity Name...", ref _nameFilter, 128); + } + private Task RefreshCharacterList() => Task.Run(() => { @@ -120,12 +157,27 @@ public class ResourceTreeViewer private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash) { + var debugMode = _config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); var cellHeight = _actionCapacity > 0 ? frameHeight : 0.0f; + + NodeVisibility GetNodeVisibility(ResourceNode node) + { + if (node.Internal && !debugMode) + return NodeVisibility.Hidden; + + if (_typeFilter.HasFlag(node.Icon)) + return NodeVisibility.Visible; + if ((_typeFilter & node.DescendentIcons) != 0) + return NodeVisibility.DescendentsOnly; + return NodeVisibility.Hidden; + } + foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { - if (resourceNode.Internal && !debugMode) + var visibility = GetNodeVisibility(resourceNode); + if (visibility == NodeVisibility.Hidden) continue; var textColor = ImGui.GetColorU32(ImGuiCol.Text); @@ -140,9 +192,8 @@ public class ResourceTreeViewer var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) { - var unfoldable = debugMode - ? resourceNode.Children.Count > 0 - : resourceNode.Children.Any(child => !child.Internal); + var hasVisibleChildren = resourceNode.Children.Any(child => GetNodeVisibility(child) != NodeVisibility.Hidden); + var unfoldable = hasVisibleChildren && visibility != NodeVisibility.DescendentsOnly; if (unfoldable) { using var font = ImRaii.PushFont(UiBuilder.IconFont); @@ -154,6 +205,11 @@ public class ResourceTreeViewer } else { + if (hasVisibleChildren && !unfolded) + { + _unfolded.Add(nodePathHash); + unfolded = true; + } ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); } @@ -200,7 +256,7 @@ public class ResourceTreeViewer ImGui.Selectable(resourceNode.FullPath.ToPath(), false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); if (ImGui.IsItemClicked()) ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); - ImGuiUtil.HoverTooltip($"{resourceNode.FullPath}\n\nClick to copy to clipboard."); + ImGuiUtil.HoverTooltip($"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard."); } else { @@ -223,4 +279,49 @@ public class ResourceTreeViewer DrawNodes(resourceNode.Children, level + 1, unchecked(nodePathHash * 31)); } } + + [Flags] + private enum TreeCategory : uint + { + LocalPlayer = 1, + Player = 2, + Networked = 4, + NonNetworked = 8, + } + + private const TreeCategory AllCategories = (TreeCategory)(((uint)TreeCategory.NonNetworked << 1) - 1); + + private static TreeCategory Classify(ResourceTree tree) + => tree.LocalPlayerRelated ? TreeCategory.LocalPlayer : + tree.PlayerRelated ? TreeCategory.Player : + tree.Networked ? TreeCategory.Networked : + TreeCategory.NonNetworked; + + private static ColorId CategoryColor(TreeCategory category) + => category switch + { + TreeCategory.LocalPlayer => ColorId.ResTreeLocalPlayer, + TreeCategory.Player => ColorId.ResTreePlayer, + TreeCategory.Networked => ColorId.ResTreeNetworked, + TreeCategory.NonNetworked => ColorId.ResTreeNonNetworked, + _ => throw new ArgumentException(), + }; + + private static string CategoryFilterDescription(TreeCategory category) + => category switch + { + TreeCategory.LocalPlayer => "Show you and what you own (mount, minion, accessory, pets and so on).", + TreeCategory.Player => "Show other players and what they own.", + TreeCategory.Networked => "Show non-player entities handled by the game server.", + TreeCategory.NonNetworked => "Show non-player entities handled locally.", + _ => throw new ArgumentException(), + }; + + [Flags] + private enum NodeVisibility : uint + { + Hidden = 0, + Visible = 1, + DescendentsOnly = 2, + } } diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 8916d365..ddd58a8a 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -145,6 +145,18 @@ public class ChangedItemDrawer : IDisposable if (_config.HideChangedItemFilters) return; + var typeFilter = _config.Ephemeral.ChangedItemFilter; + if (DrawTypeFilter(ref typeFilter)) + { + _config.Ephemeral.ChangedItemFilter = typeFilter; + _config.Ephemeral.Save(); + } + } + + /// Draw a header line with the different icon types to filter them. + public bool DrawTypeFilter(ref ChangedItemIcon typeFilter) + { + var ret = false; using var _ = ImRaii.PushId("ChangedItemIconFilter"); var size = new Vector2(2 * ImGui.GetTextLineHeight()); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero); @@ -169,23 +181,24 @@ public class ChangedItemDrawer : IDisposable ChangedItemIcon.Unknown, }; - void DrawIcon(ChangedItemIcon type) + bool DrawIcon(ChangedItemIcon type, ref ChangedItemIcon typeFilter) { + var ret = false; var icon = _icons[type]; - var flag = _config.Ephemeral.ChangedItemFilter.HasFlag(type); + var flag = typeFilter.HasFlag(type); ImGui.Image(icon.ImGuiHandle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); if (ImGui.IsItemClicked(ImGuiMouseButton.Left)) { - _config.Ephemeral.ChangedItemFilter = flag ? _config.Ephemeral.ChangedItemFilter & ~type : _config.Ephemeral.ChangedItemFilter | type; - _config.Ephemeral.Save(); + typeFilter = flag ? typeFilter & ~type : typeFilter | type; + ret = true; } using var popup = ImRaii.ContextPopupItem(type.ToString()); if (popup) if (ImGui.MenuItem("Enable Only This")) { - _config.Ephemeral.ChangedItemFilter = type; - _config.Ephemeral.Save(); + typeFilter = type; + ret = true; ImGui.CloseCurrentPopup(); } @@ -196,23 +209,27 @@ public class ChangedItemDrawer : IDisposable ImGui.SameLine(); ImGuiUtil.DrawTextButton(ToDescription(type), new Vector2(0, _smallestIconWidth), 0); } + + return ret; } foreach (var iconType in order) { - DrawIcon(iconType); + ret |= DrawIcon(iconType, ref typeFilter); ImGui.SameLine(); } ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); ImGui.Image(_icons[AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, - _config.Ephemeral.ChangedItemFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : - _config.Ephemeral.ChangedItemFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); + typeFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : + typeFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); if (ImGui.IsItemClicked()) { - _config.Ephemeral.ChangedItemFilter = _config.Ephemeral.ChangedItemFilter == AllFlags ? 0 : AllFlags; - _config.Ephemeral.Save(); + typeFilter = typeFilter == AllFlags ? 0 : AllFlags; + ret = true; } + + return ret; } /// Obtain the icon category corresponding to a changed item. From d05f369a94636f911293b57487163ec49f84a056 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 26 Nov 2023 20:56:35 +0100 Subject: [PATCH 0227/1381] ResourceTree: Adjustments on filtering --- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 18 +++++++++++------- Penumbra/UI/ChangedItemDrawer.cs | 12 ++++++++---- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index dc7fb55c..75f5c5b5 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -47,10 +47,8 @@ public class ResourceTreeViewer public void Draw() { - if (ImGui.Button("Refresh Character List") || _task == null) - _task = RefreshCharacterList(); - - DrawFilters(); + DrawControls(); + _task ??= RefreshCharacterList(); using var child = ImRaii.Child("##Data"); if (!child) @@ -73,7 +71,7 @@ public class ResourceTreeViewer foreach (var (tree, index) in _task.Result.WithIndex()) { var category = Classify(tree); - if (!_categoryFilter.HasFlag(category) || !tree.Name.Contains(_nameFilter)) + if (!_categoryFilter.HasFlag(category) || !tree.Name.Contains(_nameFilter, StringComparison.OrdinalIgnoreCase)) continue; using (var c = ImRaii.PushColor(ImGuiCol.Text, CategoryColor(category).Value())) @@ -111,8 +109,14 @@ public class ResourceTreeViewer } } - private void DrawFilters() + private void DrawControls() { + var yOffset = (ChangedItemDrawer.TypeFilterIconSize.Y - ImGui.GetFrameHeight()) / 2f; + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + yOffset); + + if (ImGui.Button("Refresh Character List")) + _task = RefreshCharacterList(); + ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); @@ -134,7 +138,7 @@ public class ResourceTreeViewer ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); - _changedItemDrawer.DrawTypeFilter(ref _typeFilter); + _changedItemDrawer.DrawTypeFilter(ref _typeFilter, -yOffset); ImGui.InputTextWithHint("##TreeNameFilter", "Filter by Character/Entity Name...", ref _nameFilter, 128); } diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index ddd58a8a..0a1d58f9 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -52,6 +52,9 @@ public class ChangedItemDrawer : IDisposable private readonly Dictionary _icons = new(16); private float _smallestIconWidth; + public static Vector2 TypeFilterIconSize + => new(2 * ImGui.GetTextLineHeight()); + public ChangedItemDrawer(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, Configuration config) { @@ -146,7 +149,7 @@ public class ChangedItemDrawer : IDisposable return; var typeFilter = _config.Ephemeral.ChangedItemFilter; - if (DrawTypeFilter(ref typeFilter)) + if (DrawTypeFilter(ref typeFilter, 0.0f)) { _config.Ephemeral.ChangedItemFilter = typeFilter; _config.Ephemeral.Save(); @@ -154,11 +157,11 @@ public class ChangedItemDrawer : IDisposable } /// Draw a header line with the different icon types to filter them. - public bool DrawTypeFilter(ref ChangedItemIcon typeFilter) + public bool DrawTypeFilter(ref ChangedItemIcon typeFilter, float yOffset) { var ret = false; using var _ = ImRaii.PushId("ChangedItemIconFilter"); - var size = new Vector2(2 * ImGui.GetTextLineHeight()); + var size = TypeFilterIconSize; using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero); var order = new[] { @@ -186,6 +189,7 @@ public class ChangedItemDrawer : IDisposable var ret = false; var icon = _icons[type]; var flag = typeFilter.HasFlag(type); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + yOffset); ImGui.Image(icon.ImGuiHandle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); if (ImGui.IsItemClicked(ImGuiMouseButton.Left)) { @@ -219,7 +223,7 @@ public class ChangedItemDrawer : IDisposable ImGui.SameLine(); } - ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); + ImGui.SetCursorPos(new(ImGui.GetContentRegionMax().X - size.X, ImGui.GetCursorPosY() + yOffset)); ImGui.Image(_icons[AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, typeFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : typeFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); From 5ebab472b822fd46fcae9e8684c99f429d1aea39 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 26 Nov 2023 21:26:35 +0100 Subject: [PATCH 0228/1381] Import from Screen: Add option selector --- .../AdvancedWindow/ModEditWindow.QuickImport.cs | 2 ++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 48d617db..626b1161 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -28,6 +28,8 @@ public partial class ModEditWindow return; } + if (DrawOptionSelectHeader()) + _quickImportActions.Clear(); _quickImportViewer.Draw(); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 7171a0e2..6ca22976 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -380,18 +380,25 @@ public partial class ModEditWindow : Window, IDisposable } } - private void DrawOptionSelectHeader() + private bool DrawOptionSelectHeader() { const string defaultOption = "Default Option"; using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero).Push(ImGuiStyleVar.FrameRounding, 0); var width = new Vector2(ImGui.GetContentRegionAvail().X / 3, 0); + var ret = false; if (ImGuiUtil.DrawDisabledButton(defaultOption, width, "Switch to the default option for the mod.\nThis resets unsaved changes.", _editor.Option!.IsDefault)) + { _editor.LoadOption(-1, 0); + ret = true; + } ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Refresh Data", width, "Refresh data for the current option.\nThis resets unsaved changes.", false)) + { _editor.LoadMod(_editor.Mod!, _editor.GroupIdx, _editor.OptionIdx); + ret = true; + } ImGui.SameLine(); ImGui.SetNextItemWidth(width.X); @@ -399,14 +406,19 @@ public partial class ModEditWindow : Window, IDisposable using var color = ImRaii.PushColor(ImGuiCol.Border, ColorId.FolderLine.Value()); using var combo = ImRaii.Combo("##optionSelector", _editor.Option.FullName); if (!combo) - return; + return ret; foreach (var (option, idx) in _mod!.AllSubMods.WithIndex()) { using var id = ImRaii.PushId(idx); if (ImGui.Selectable(option.FullName, option == _editor.Option)) + { _editor.LoadOption(option.GroupIdx, option.OptionIdx); + ret = true; + } } + + return ret; } private string _newSwapKey = string.Empty; From 73af509885d1aa69086798bd35daff19384dd524 Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Tue, 28 Nov 2023 10:28:37 -0800 Subject: [PATCH 0229/1381] Add GetGameObjectResourceTrees ipc method --- Penumbra.Api | 2 +- Penumbra/Api/PenumbraApi.cs | 9 +++++ Penumbra/Api/PenumbraIpcProviders.cs | 3 ++ .../ResourceTree/ResourceTreeApiHelper.cs | 35 +++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 80f9793e..3f3af19d 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 80f9793ef2ddaa50246b7112fde4d9b2098d8823 +Subproject commit 3f3af19d11ec4d7a83ee6c17810eb55ec4237675 diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 0ae4fcca..7b2e09d0 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1075,6 +1075,15 @@ public class PenumbraApi : IDisposable, IPenumbraApi return resDictionaries.AsReadOnly(); } + public IEnumerable?[] GetGameObjectResourceTrees(bool withUIData, params ushort[] gameObjects) + { + var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); + var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); + + return Array.ConvertAll(gameObjects, obj => resDictionary.TryGetValue(obj, out var nodes) ? nodes : null); + } + // TODO: cleanup when incrementing API public string GetMetaManipulations(string characterName) diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index b72073fb..289fc38b 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -130,6 +130,8 @@ public class PenumbraIpcProviders : IDisposable FuncProvider>> GetPlayerResourcesOfType; + internal readonly FuncProvider?[]> GetGameObjectResourceTrees; + public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) { @@ -254,6 +256,7 @@ public class PenumbraIpcProviders : IDisposable GetPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Provider(pi, Api.GetPlayerResourcePaths); GetGameObjectResourcesOfType = Ipc.GetGameObjectResourcesOfType.Provider(pi, Api.GetGameObjectResourcesOfType); GetPlayerResourcesOfType = Ipc.GetPlayerResourcesOfType.Provider(pi, Api.GetPlayerResourcesOfType); + GetGameObjectResourceTrees = Ipc.GetGameObjectResourceTrees.Provider(pi, Api.GetGameObjectResourceTrees); Tester = new IpcTester(config, dalamud, this, modManager, collections, tempMods, tempCollections, saveService); diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index 6c1e4d1e..3df47086 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -1,5 +1,7 @@ using Dalamud.Game.ClientState.Objects.Types; +using Penumbra.Api; using Penumbra.Api.Enums; +using Penumbra.String.Classes; using Penumbra.UI; namespace Penumbra.Interop.ResourceTree; @@ -71,4 +73,37 @@ internal static class ResourceTreeApiHelper return resDictionaries.ToDictionary(pair => pair.Key, pair => (IReadOnlyDictionary)pair.Value.AsReadOnly()); } + + public static Dictionary> EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) + { + static Ipc.ResourceNode GetIpcNode(ResourceNode[] tree, ResourceNode node) => + new() + { + ChildrenIndices = node.Children.Select(c => Array.IndexOf(tree, c)).ToArray(), + Type = node.Type, + Icon = ChangedItemDrawer.ToApiIcon(node.Icon), + Name = node.Name, + GamePath = node.GamePath.Equals(Utf8GamePath.Empty) ? null : node.GamePath.ToString(), + ActualPath = node.FullPath.ToString(), + ObjectAddress = node.ObjectAddress, + ResourceHandle = node.ResourceHandle, + }; + + static IEnumerable GetIpcNodes(ResourceTree tree) + { + var nodes = tree.FlatNodes.ToArray(); + return nodes.Select(n => GetIpcNode(nodes, n)).ToArray(); + } + + var resDictionary = new Dictionary>(4); + foreach (var (gameObject, resourceTree) in resourceTrees) + { + if (resDictionary.ContainsKey(gameObject.ObjectIndex)) + continue; + + resDictionary.Add(gameObject.ObjectIndex, GetIpcNodes(resourceTree)); + } + + return resDictionary; + } } From 0f03e0484c33ee9c87d239c8f1fa097b43e2bdda Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Tue, 28 Nov 2023 10:46:03 -0800 Subject: [PATCH 0230/1381] Add ipc GetPlayerResourceTrees, change ipc resource node to be nested --- Penumbra.Api | 2 +- Penumbra/Api/PenumbraApi.cs | 8 ++++++++ Penumbra/Api/PenumbraIpcProviders.cs | 4 +++- .../Interop/ResourceTree/ResourceTreeApiHelper.cs | 11 ++++------- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 3f3af19d..1fa1839a 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 3f3af19d11ec4d7a83ee6c17810eb55ec4237675 +Subproject commit 1fa1839aef7ddd4a90f53e9642403f950579c2eb diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 7b2e09d0..1e79099c 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1084,6 +1084,14 @@ public class PenumbraApi : IDisposable, IPenumbraApi return Array.ConvertAll(gameObjects, obj => resDictionary.TryGetValue(obj, out var nodes) ? nodes : null); } + public IReadOnlyDictionary> GetPlayerResourceTrees(bool withUIData) + { + var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly + | (withUIData ? ResourceTreeFactory.Flags.WithUiData : 0)); + var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); + + return resDictionary.AsReadOnly(); + } // TODO: cleanup when incrementing API public string GetMetaManipulations(string characterName) diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 289fc38b..9f1e79b9 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -131,6 +131,7 @@ public class PenumbraIpcProviders : IDisposable GetPlayerResourcesOfType; internal readonly FuncProvider?[]> GetGameObjectResourceTrees; + internal readonly FuncProvider>> GetPlayerResourceTrees; public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) @@ -256,7 +257,8 @@ public class PenumbraIpcProviders : IDisposable GetPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Provider(pi, Api.GetPlayerResourcePaths); GetGameObjectResourcesOfType = Ipc.GetGameObjectResourcesOfType.Provider(pi, Api.GetGameObjectResourcesOfType); GetPlayerResourcesOfType = Ipc.GetPlayerResourcesOfType.Provider(pi, Api.GetPlayerResourcesOfType); - GetGameObjectResourceTrees = Ipc.GetGameObjectResourceTrees.Provider(pi, Api.GetGameObjectResourceTrees); + GetGameObjectResourceTrees = Ipc.GetGameObjectResourceTrees.Provider(pi, Api.GetGameObjectResourceTrees); + GetPlayerResourceTrees = Ipc.GetPlayerResourceTrees.Provider(pi, Api.GetPlayerResourceTrees); Tester = new IpcTester(config, dalamud, this, modManager, collections, tempMods, tempCollections, saveService); diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index 3df47086..02e0f380 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -76,10 +76,9 @@ internal static class ResourceTreeApiHelper public static Dictionary> EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) { - static Ipc.ResourceNode GetIpcNode(ResourceNode[] tree, ResourceNode node) => + static Ipc.ResourceNode GetIpcNode(ResourceNode node) => new() { - ChildrenIndices = node.Children.Select(c => Array.IndexOf(tree, c)).ToArray(), Type = node.Type, Icon = ChangedItemDrawer.ToApiIcon(node.Icon), Name = node.Name, @@ -87,13 +86,11 @@ internal static class ResourceTreeApiHelper ActualPath = node.FullPath.ToString(), ObjectAddress = node.ObjectAddress, ResourceHandle = node.ResourceHandle, + Children = node.Children.Select(GetIpcNode).ToArray(), }; - static IEnumerable GetIpcNodes(ResourceTree tree) - { - var nodes = tree.FlatNodes.ToArray(); - return nodes.Select(n => GetIpcNode(nodes, n)).ToArray(); - } + static IEnumerable GetIpcNodes(ResourceTree tree) => + tree.Nodes.Select(GetIpcNode).ToArray(); var resDictionary = new Dictionary>(4); foreach (var (gameObject, resourceTree) in resourceTrees) From d647a62e82fef780cfe36a63d457d260937475e8 Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Tue, 28 Nov 2023 12:33:19 -0800 Subject: [PATCH 0231/1381] Add ResourceTree ipc structure --- Penumbra.Api | 2 +- Penumbra/Api/PenumbraApi.cs | 4 ++-- Penumbra/Api/PenumbraIpcProviders.cs | 4 ++-- .../Interop/ResourceTree/ResourceTreeApiHelper.cs | 15 ++++++++++----- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 1fa1839a..3567cf22 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 1fa1839aef7ddd4a90f53e9642403f950579c2eb +Subproject commit 3567cf225b469dd5bb5f723e96e2abaaa4d16a1c diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 1e79099c..8974e823 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1075,7 +1075,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi return resDictionaries.AsReadOnly(); } - public IEnumerable?[] GetGameObjectResourceTrees(bool withUIData, params ushort[] gameObjects) + public Ipc.ResourceTree?[] GetGameObjectResourceTrees(bool withUIData, params ushort[] gameObjects) { var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); @@ -1084,7 +1084,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi return Array.ConvertAll(gameObjects, obj => resDictionary.TryGetValue(obj, out var nodes) ? nodes : null); } - public IReadOnlyDictionary> GetPlayerResourceTrees(bool withUIData) + public IReadOnlyDictionary GetPlayerResourceTrees(bool withUIData) { var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly | (withUIData ? ResourceTreeFactory.Flags.WithUiData : 0)); diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 9f1e79b9..10980f98 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -130,8 +130,8 @@ public class PenumbraIpcProviders : IDisposable FuncProvider>> GetPlayerResourcesOfType; - internal readonly FuncProvider?[]> GetGameObjectResourceTrees; - internal readonly FuncProvider>> GetPlayerResourceTrees; + internal readonly FuncProvider GetGameObjectResourceTrees; + internal readonly FuncProvider> GetPlayerResourceTrees; public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index 02e0f380..df34c51a 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -74,7 +74,7 @@ internal static class ResourceTreeApiHelper pair => (IReadOnlyDictionary)pair.Value.AsReadOnly()); } - public static Dictionary> EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) + public static Dictionary EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) { static Ipc.ResourceNode GetIpcNode(ResourceNode node) => new() @@ -89,16 +89,21 @@ internal static class ResourceTreeApiHelper Children = node.Children.Select(GetIpcNode).ToArray(), }; - static IEnumerable GetIpcNodes(ResourceTree tree) => - tree.Nodes.Select(GetIpcNode).ToArray(); + static Ipc.ResourceTree GetIpcTree(ResourceTree tree) => + new() + { + Name = tree.Name, + RaceCode = (ushort)tree.RaceCode, + Nodes = tree.Nodes.Select(GetIpcNode).ToArray(), + }; - var resDictionary = new Dictionary>(4); + var resDictionary = new Dictionary(4); foreach (var (gameObject, resourceTree) in resourceTrees) { if (resDictionary.ContainsKey(gameObject.ObjectIndex)) continue; - resDictionary.Add(gameObject.ObjectIndex, GetIpcNodes(resourceTree)); + resDictionary.Add(gameObject.ObjectIndex, GetIpcTree(resourceTree)); } return resDictionary; From bb3d3657ed7d487acb4e575a6f91b76051bfef00 Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Tue, 28 Nov 2023 12:33:37 -0800 Subject: [PATCH 0232/1381] Add ResourceTree ipc tests --- Penumbra/Api/IpcTester.cs | 103 +++++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 675a61a3..f7b740b9 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -16,8 +16,8 @@ using Penumbra.Services; using Penumbra.UI; using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; -using ImGuiScene; using Penumbra.GameData.Structs; +using Penumbra.GameData.Enums; namespace Penumbra.Api; @@ -1437,6 +1437,8 @@ public class IpcTester : IDisposable private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcePaths; private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcesOfType; private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcesOfType; + private (string, Ipc.ResourceTree?)[]? _lastGameObjectResourceTrees; + private (string, Ipc.ResourceTree)[]? _lastPlayerResourceTrees; private TimeSpan _lastCallDuration; public ResourceTree(DalamudPluginInterface pi, IObjectTable objects) @@ -1523,11 +1525,46 @@ public class IpcTester : IDisposable ImGui.OpenPopup(nameof(Ipc.GetPlayerResourcesOfType)); } + DrawIntro(Ipc.GetGameObjectResourceTrees.Label, "Get GameObject resource trees"); + if (ImGui.Button("Get##GameObjectResourceTrees")) + { + var gameObjects = GetSelectedGameObjects(); + var subscriber = Ipc.GetGameObjectResourceTrees.Subscriber(_pi); + _stopwatch.Restart(); + var trees = subscriber.Invoke(_withUIData, gameObjects); + + _lastCallDuration = _stopwatch.Elapsed; + _lastGameObjectResourceTrees = gameObjects + .Select(i => GameObjectToString(i)) + .Zip(trees) + .ToArray(); + + ImGui.OpenPopup(nameof(Ipc.GetGameObjectResourceTrees)); + } + + DrawIntro(Ipc.GetPlayerResourceTrees.Label, "Get local player resource trees"); + if (ImGui.Button("Get##PlayerResourceTrees")) + { + var subscriber = Ipc.GetPlayerResourceTrees.Subscriber(_pi); + _stopwatch.Restart(); + var trees = subscriber.Invoke(_withUIData); + + _lastCallDuration = _stopwatch.Elapsed; + _lastPlayerResourceTrees = trees + .Select(pair => (GameObjectToString(pair.Key), pair.Value)) + .ToArray(); + + ImGui.OpenPopup(nameof(Ipc.GetPlayerResourceTrees)); + } + DrawPopup(nameof(Ipc.GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths, _lastCallDuration); DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths, _lastCallDuration); DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType, _lastCallDuration); DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, _lastCallDuration); + + DrawPopup(nameof(Ipc.GetGameObjectResourceTrees), ref _lastGameObjectResourceTrees, DrawResourceTrees, _lastCallDuration); + DrawPopup(nameof(Ipc.GetPlayerResourceTrees), ref _lastPlayerResourceTrees, DrawResourceTrees!, _lastCallDuration); } private static void DrawPopup(string popupId, ref T? result, Action drawResult, TimeSpan duration) where T : class @@ -1638,6 +1675,70 @@ public class IpcTester : IDisposable }); } + private void DrawResourceTrees((string, Ipc.ResourceTree?)[] result) + { + DrawWithHeaders(result, tree => + { + ImGui.TextUnformatted($"Name: {tree.Name}\nRaceCode: {(GenderRace)tree.RaceCode}"); + + using var table = ImRaii.Table(string.Empty, _withUIData ? 7 : 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.Resizable); + if (!table) + return; + + if (_withUIData) + { + ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.1f); + ImGui.TableSetupColumn("Icon", ImGuiTableColumnFlags.WidthStretch, 0.15f); + } + else + { + ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.5f); + } + ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Object Address", ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImGui.TableHeadersRow(); + + void DrawNode(Ipc.ResourceNode node) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + var hasChildren = node.Children.Any(); + using var treeNode = ImRaii.TreeNode( + $"{(_withUIData ? (node.Name ?? "Unknown") : node.Type)}##{node.ObjectAddress:X8}", + hasChildren ? + ImGuiTreeNodeFlags.SpanFullWidth : + (ImGuiTreeNodeFlags.SpanFullWidth | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen)); + if (_withUIData) + { + ImGui.TableNextColumn(); + TextUnformattedMono(node.Type.ToString()); + ImGui.TableNextColumn(); + TextUnformattedMono(node.Icon.ToString()); + } + ImGui.TableNextColumn(); + ImGui.TextUnformatted(node.GamePath ?? "Unknown"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(node.ActualPath); + ImGui.TableNextColumn(); + TextUnformattedMono($"0x{node.ObjectAddress:X8}"); + ImGui.TableNextColumn(); + TextUnformattedMono($"0x{node.ResourceHandle:X8}"); + + if (treeNode) + { + foreach (var child in node.Children) + DrawNode(child); + } + } + + foreach (var node in tree.Nodes) + DrawNode(node); + }); + } + private static void TextUnformattedMono(string text) { using var _ = ImRaii.PushFont(UiBuilder.MonoFont); From 18d38a997445bbbabceea91f9e0ec60437b974ef Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 29 Nov 2023 14:31:47 +0100 Subject: [PATCH 0233/1381] Mod Edit Window: Highlight paths of files on player --- Penumbra/Import/Textures/TextureDrawer.cs | 24 ++++++++++++------- Penumbra/Mods/Editor/FileRegistry.cs | 2 ++ Penumbra/UI/AdvancedWindow/FileEditor.cs | 4 +++- .../ModEditWindow.QuickImport.cs | 20 ++++++++++++++++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 9 +++---- 5 files changed, 45 insertions(+), 14 deletions(-) diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index bea28749..6d68efbd 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -101,24 +101,25 @@ public static class TextureDrawer } } - public sealed class PathSelectCombo : FilterComboCache<(string, bool)> + public sealed class PathSelectCombo : FilterComboCache<(string Path, bool Game, bool IsOnPlayer)> { private int _skipPrefix = 0; - public PathSelectCombo(TextureManager textures, ModEditor editor) - : base(() => CreateFiles(textures, editor), Penumbra.Log) + public PathSelectCombo(TextureManager textures, ModEditor editor, Func> getPlayerResources) + : base(() => CreateFiles(textures, editor, getPlayerResources), Penumbra.Log) { } - protected override string ToString((string, bool) obj) - => obj.Item1; + protected override string ToString((string Path, bool Game, bool IsOnPlayer) obj) + => obj.Path; protected override bool DrawSelectable(int globalIdx, bool selected) { - var (path, game) = Items[globalIdx]; + var (path, game, isOnPlayer) = Items[globalIdx]; bool ret; using (var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value(), game)) { - var equals = string.Equals(CurrentSelection.Item1, path, StringComparison.OrdinalIgnoreCase); + color.Push(ImGuiCol.Text, ColorId.HandledConflictMod.Value(), isOnPlayer); + var equals = string.Equals(CurrentSelection.Path, path, StringComparison.OrdinalIgnoreCase); var p = game ? $"--> {path}" : path[_skipPrefix..]; ret = ImGui.Selectable(p, selected) && !equals; } @@ -129,11 +130,16 @@ public static class TextureDrawer return ret; } - private static IReadOnlyList<(string, bool)> CreateFiles(TextureManager textures, ModEditor editor) - => editor.Files.Tex.SelectMany(f => f.SubModUsage.Select(p => (p.Item2.ToString(), true)) + private static IReadOnlyList<(string Path, bool Game, bool IsOnPlayer)> CreateFiles(TextureManager textures, ModEditor editor, Func> getPlayerResources) + { + var playerResources = getPlayerResources(); + + return editor.Files.Tex.SelectMany(f => f.SubModUsage.Select(p => (p.Item2.ToString(), true)) .Prepend((f.File.FullName, false))) .Where(p => p.Item2 ? textures.GameFileExists(p.Item1) : File.Exists(p.Item1)) + .Select(p => (p.Item1, p.Item2, playerResources.Contains(p.Item1))) .ToList(); + } public bool Draw(string label, string tooltip, string current, int skipPrefix, out string newPath) { diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 791778e3..a223b51e 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -10,6 +10,7 @@ public class FileRegistry : IEquatable public Utf8RelPath RelPath { get; private init; } public long FileSize { get; private init; } public int CurrentUsage; + public bool IsOnPlayer; public static bool FromFile(DirectoryInfo modPath, FileInfo file, [NotNullWhen(true)] out FileRegistry? registry) { @@ -26,6 +27,7 @@ public class FileRegistry : IEquatable RelPath = relPath, FileSize = file.Length, CurrentUsage = 0, + IsOnPlayer = false, }; return true; } diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index b84fa84c..c3a1c0dc 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -285,7 +285,9 @@ public class FileEditor : IDisposable where T : class, IWritable protected override bool DrawSelectable(int globalIdx, bool selected) { var file = Items[globalIdx]; - var ret = ImGui.Selectable(file.RelPath.ToString(), selected); + bool ret; + using (var c = ImRaii.PushColor(ImGuiCol.Text, ColorId.HandledConflictMod.Value(), file.IsOnPlayer)) + ret = ImGui.Selectable(file.RelPath.ToString(), selected); if (ImGui.IsItemHovered()) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 48d617db..1ab1ed88 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -3,6 +3,7 @@ using ImGuiNET; using Lumina.Data; using OtterGui; using OtterGui.Raii; +using Penumbra.Api.Enums; using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; using Penumbra.Mods; @@ -19,6 +20,25 @@ public partial class ModEditWindow private readonly Dictionary _quickImportWritables = new(); private readonly Dictionary<(Utf8GamePath, IWritable?), QuickImportAction> _quickImportActions = new(); + private HashSet GetPlayerResourcesOfType(ResourceType type) + { + var resources = ResourceTreeApiHelper.GetResourcesOfType(_resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly), type) + .Values + .SelectMany(resources => resources.Values) + .Select(resource => resource.Item1); + + return new(resources, StringComparer.OrdinalIgnoreCase); + } + + private IReadOnlyList PopulateIsOnPlayer(IReadOnlyList files, ResourceType type) + { + var playerResources = GetPlayerResourcesOfType(type); + foreach (var file in files) + file.IsOnPlayer = playerResources.Contains(file.File.ToPath()); + + return files; + } + private void DrawQuickImportTab() { using var tab = ImRaii.TabItem("Import from Screen"); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 7171a0e2..ce2bb2a4 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -7,6 +7,7 @@ using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Enums; @@ -569,15 +570,15 @@ public partial class ModEditWindow : Window, IDisposable _fileDialog = fileDialog; _gameEvents = gameEvents; _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", - () => _editor.Files.Mtrl, DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, + () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => _editor.Files.Mdl, DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlFile(bytes)); + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlFile(bytes)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", - () => _editor.Files.Shpk, DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, + () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); - _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor); + _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); _resourceTreeFactory = resourceTreeFactory; _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); From 1101a7a98625e8d51e23473b64ca57e30246a8f7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 29 Nov 2023 17:23:37 +0100 Subject: [PATCH 0234/1381] Make sure the SubstitutionProvider is initialized before the interface. --- Penumbra/Penumbra.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index ef8a1a05..bcf94ed1 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -85,6 +85,7 @@ public class Penumbra : IDalamudPlugin _services.GetRequiredService(); + _services.GetRequiredService(); // Initialize before Interface. SetupInterface(); SetupApi(); From b7272207755d8f87d35bb1b2cba83eaba69255a0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 29 Nov 2023 17:27:09 +0100 Subject: [PATCH 0235/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 3a1a3f1a..3e2d4ae9 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3a1a3f1a1f2021b063617ac9b294b579a154706e +Subproject commit 3e2d4ae934694918d312280d62127cf1a55b03e4 From 4aa1388b344558df1dada39f8152004df79c5c6c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 29 Nov 2023 17:30:57 +0100 Subject: [PATCH 0236/1381] Update actions for recursive submodules. --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/test_release.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a317f236..3dd1d45b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v2 with: - submodules: true + submodules: recursive - name: Setup .NET uses: actions/setup-dotnet@v1 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 44f9fd2f..3141c6ed 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ jobs: steps: - uses: actions/checkout@v2 with: - submodules: true + submodules: recursive - name: Setup .NET uses: actions/setup-dotnet@v1 with: diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 80c0ce8f..2644974b 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -11,7 +11,7 @@ jobs: steps: - uses: actions/checkout@v2 with: - submodules: true + submodules: recursive - name: Setup .NET uses: actions/setup-dotnet@v1 with: From 3d9f8355d234272e1d75a071f231fc9002ef8edb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 29 Nov 2023 17:32:59 +0100 Subject: [PATCH 0237/1381] Make braces clear for scoped using. --- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index c3a1c0dc..336be1a4 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -287,7 +287,9 @@ public class FileEditor : IDisposable where T : class, IWritable var file = Items[globalIdx]; bool ret; using (var c = ImRaii.PushColor(ImGuiCol.Text, ColorId.HandledConflictMod.Value(), file.IsOnPlayer)) + { ret = ImGui.Selectable(file.RelPath.ToString(), selected); + } if (ImGui.IsItemHovered()) { From e497414cb7c30222a38d72695ed4976ba7f759d6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 29 Nov 2023 18:00:30 +0100 Subject: [PATCH 0238/1381] Auto-Formatting and some imgui layouting. --- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 75f5c5b5..d31f3e52 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -11,9 +11,7 @@ namespace Penumbra.UI.AdvancedWindow; public class ResourceTreeViewer { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = - ResourceTreeFactory.Flags.RedactExternalPaths | - ResourceTreeFactory.Flags.WithUiData | - ResourceTreeFactory.Flags.WithOwnership; + ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; private readonly Configuration _config; private readonly ResourceTreeFactory _treeFactory; @@ -83,6 +81,7 @@ public class ResourceTreeViewer ImGuiUtil.HoverTooltip( $"Object Index: {tree.GameObjectIndex}\nObject Address: 0x{tree.GameObjectAddress:X16}\nDraw Object Address: 0x{tree.DrawObjectAddress:X16}"); } + if (!isOpen) continue; } @@ -117,29 +116,29 @@ public class ResourceTreeViewer if (ImGui.Button("Refresh Character List")) _task = RefreshCharacterList(); - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + var checkSpacing = ImGui.GetStyle().ItemInnerSpacing.X; + var checkPadding = 10 * ImGuiHelpers.GlobalScale + ImGui.GetStyle().ItemSpacing.X; + ImGui.SameLine(0, checkPadding); using (var id = ImRaii.PushId("TreeCategoryFilter")) { - var spacing = ImGui.GetStyle().ItemInnerSpacing.X; var categoryFilter = (uint)_categoryFilter; foreach (var category in Enum.GetValues()) { - ImGui.SameLine(0.0f, spacing); using var c = ImRaii.PushColor(ImGuiCol.CheckMark, CategoryColor(category).Value()); ImGui.CheckboxFlags($"##{category}", ref categoryFilter, (uint)category); ImGuiUtil.HoverTooltip(CategoryFilterDescription(category)); + ImGui.SameLine(0.0f, checkSpacing); } + _categoryFilter = (TreeCategory)categoryFilter; } - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImGui.SameLine(0, checkPadding); - ImGui.SameLine(); _changedItemDrawer.DrawTypeFilter(ref _typeFilter, -yOffset); + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); ImGui.InputTextWithHint("##TreeNameFilter", "Filter by Character/Entity Name...", ref _nameFilter, 128); } @@ -161,7 +160,6 @@ public class ResourceTreeViewer private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash) { - var debugMode = _config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); var cellHeight = _actionCapacity > 0 ? frameHeight : 0.0f; @@ -175,6 +173,7 @@ public class ResourceTreeViewer return NodeVisibility.Visible; if ((_typeFilter & node.DescendentIcons) != 0) return NodeVisibility.DescendentsOnly; + return NodeVisibility.Hidden; } @@ -214,6 +213,7 @@ public class ResourceTreeViewer _unfolded.Add(nodePathHash); unfolded = true; } + ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); } @@ -297,9 +297,9 @@ public class ResourceTreeViewer private static TreeCategory Classify(ResourceTree tree) => tree.LocalPlayerRelated ? TreeCategory.LocalPlayer : - tree.PlayerRelated ? TreeCategory.Player : - tree.Networked ? TreeCategory.Networked : - TreeCategory.NonNetworked; + tree.PlayerRelated ? TreeCategory.Player : + tree.Networked ? TreeCategory.Networked : + TreeCategory.NonNetworked; private static ColorId CategoryColor(TreeCategory category) => category switch From eb0e334437e07c276c72bf0bab9aa7b758054b20 Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Thu, 30 Nov 2023 09:53:16 -0800 Subject: [PATCH 0239/1381] Add ResourceTree ipc disposes --- Penumbra/Api/PenumbraIpcProviders.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 10980f98..a564588b 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -375,6 +375,8 @@ public class PenumbraIpcProviders : IDisposable GetPlayerResourcePaths.Dispose(); GetGameObjectResourcesOfType.Dispose(); GetPlayerResourcesOfType.Dispose(); + GetGameObjectResourceTrees.Dispose(); + GetPlayerResourceTrees.Dispose(); Disposed.Invoke(); Disposed.Dispose(); From b595a0da0ff0ceb81e428b87518b2ab487293bf7 Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Thu, 30 Nov 2023 10:01:49 -0800 Subject: [PATCH 0240/1381] Replace ResourceTree IEnumerables with lists --- Penumbra.Api | 2 +- Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 3567cf22..e2f578a9 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 3567cf225b469dd5bb5f723e96e2abaaa4d16a1c +Subproject commit e2f578a903f4e2de6c5967eb92f1b5a0a413d287 diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index df34c51a..386caf9d 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -86,7 +86,7 @@ internal static class ResourceTreeApiHelper ActualPath = node.FullPath.ToString(), ObjectAddress = node.ObjectAddress, ResourceHandle = node.ResourceHandle, - Children = node.Children.Select(GetIpcNode).ToArray(), + Children = node.Children.Select(GetIpcNode).ToList(), }; static Ipc.ResourceTree GetIpcTree(ResourceTree tree) => @@ -94,7 +94,7 @@ internal static class ResourceTreeApiHelper { Name = tree.Name, RaceCode = (ushort)tree.RaceCode, - Nodes = tree.Nodes.Select(GetIpcNode).ToArray(), + Nodes = tree.Nodes.Select(GetIpcNode).ToList(), }; var resDictionary = new Dictionary(4); From 07e20fb6701087932930b98e2ae2c00e9e746ac7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 1 Dec 2023 13:49:29 +0100 Subject: [PATCH 0241/1381] Test not redrawing while the fishing rod is out. --- Penumbra/EphemeralConfig.cs | 1 - Penumbra/Interop/Services/RedrawService.cs | 44 +++++++++++++++++++--- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index bb4a5eb8..6c87d331 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -3,7 +3,6 @@ using Newtonsoft.Json; using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Enums; -using Penumbra.Interop.Services; using Penumbra.Services; using Penumbra.UI; using Penumbra.UI.ResourceWatcher; diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 49d688af..8e47fa0b 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -11,6 +11,7 @@ using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.GameData.Actors; using Penumbra.Interop.Structs; +using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; namespace Penumbra.Interop.Services; @@ -248,8 +249,15 @@ public sealed unsafe partial class RedrawService : IDisposable { if (idx < 0) { - WriteInvisible(obj); - _queue[numKept++] = ObjectTableIndex(obj); + if (DelayRedraw(obj)) + { + _queue[numKept++] = ~ObjectTableIndex(obj); + } + else + { + WriteInvisible(obj); + _queue[numKept++] = ObjectTableIndex(obj); + } } else { @@ -261,6 +269,30 @@ public sealed unsafe partial class RedrawService : IDisposable _queue.RemoveRange(numKept, _queue.Count - numKept); } + private static uint GetCurrentAnimationId(GameObject obj) + { + var gameObj = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)obj.Address; + if (gameObj == null || !gameObj->IsCharacter()) + return 0; + + var chara = (Character*)gameObj; + var ptr = (byte*)&chara->ActionTimelineManager + 0xF0; + return *(uint*)ptr; + } + + private static bool DelayRedraw(GameObject obj) + => ((Character*)obj.Address)->Mode switch + { + (Character.CharacterModes)6 => // fishing + GetCurrentAnimationId(obj) switch + { + 278 => true, // line out. + 283 => true, // reeling in + _ => false, + }, + _ => false, + }; + private void HandleAfterGPose() { if (_afterGPoseQueue.Count == 0 || InGPose) @@ -369,10 +401,11 @@ public sealed unsafe partial class RedrawService : IDisposable private void DisableFurniture() { var housingManager = HousingManager.Instance(); - if (housingManager == null) + if (housingManager == null) return; + var currentTerritory = housingManager->CurrentTerritory; - if (currentTerritory == null) + if (currentTerritory == null) return; if (!housingManager->IsInside()) return; @@ -380,8 +413,9 @@ public sealed unsafe partial class RedrawService : IDisposable foreach (var f in currentTerritory->FurnitureSpan.PointerEnumerator()) { var gameObject = f->Index >= 0 ? currentTerritory->HousingObjectManager.ObjectsSpan[f->Index].Value : null; - if (gameObject == null) + if (gameObject == null) continue; + gameObject->DisableDraw(); } } From 2c1ce660115be08312f175efefa12b78e210a2ac Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 1 Dec 2023 14:32:13 +0100 Subject: [PATCH 0242/1381] Update Penumbra.Api. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index e2f578a9..cfc51714 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit e2f578a903f4e2de6c5967eb92f1b5a0a413d287 +Subproject commit cfc51714f74cae93608bc507775a9580cd1801de From e0fa8c9285100df589b3067814575cd87f93a3a4 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 1 Dec 2023 13:35:51 +0000 Subject: [PATCH 0243/1381] [CI] Updating repo.json for testing_0.8.2.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 741a93c3..4f815483 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.2.1", - "TestingAssemblyVersion": "0.8.2.1", + "TestingAssemblyVersion": "0.8.2.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.2.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a0328aab35430d45f95b8f3fd2ca5284dc2bfc12 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 1 Dec 2023 16:29:36 +0100 Subject: [PATCH 0244/1381] Compile releases from release dalamud, not staging. --- .github/workflows/release.yml | 2 +- .github/workflows/test_release.yml | 2 +- Penumbra/Interop/Services/RedrawService.cs | 24 +++++++++++----------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3141c6ed..f3afe9c1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 2644974b..0968430d 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 8e47fa0b..7a73857a 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -245,25 +245,25 @@ public sealed unsafe partial class RedrawService : IDisposable if (FindCorrectActor(idx < 0 ? ~idx : idx, out var obj)) _afterGPoseQueue.Add(idx < 0 ? idx : ~idx); - if (obj != null) + if (obj == null) + continue; + + if (idx < 0) { - if (idx < 0) + if (DelayRedraw(obj)) { - if (DelayRedraw(obj)) - { - _queue[numKept++] = ~ObjectTableIndex(obj); - } - else - { - WriteInvisible(obj); - _queue[numKept++] = ObjectTableIndex(obj); - } + _queue[numKept++] = ~ObjectTableIndex(obj); } else { - WriteVisible(obj); + WriteInvisible(obj); + _queue[numKept++] = ObjectTableIndex(obj); } } + else + { + WriteVisible(obj); + } } _queue.RemoveRange(numKept, _queue.Count - numKept); From 7128f237da0b39490ecba7e67a9f9dc027983f7f Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 1 Dec 2023 15:31:41 +0000 Subject: [PATCH 0245/1381] [CI] Updating repo.json for testing_0.8.2.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 4f815483..af1104be 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.2.1", - "TestingAssemblyVersion": "0.8.2.2", + "TestingAssemblyVersion": "0.8.2.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.2.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.2.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a9f36c6aef01df1370d45a1fa34a211cc34282a6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 10 Dec 2023 15:09:37 +0100 Subject: [PATCH 0246/1381] Fix inverted percentage, skill. --- Penumbra/Import/TexToolsImporter.Gui.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index e150d10d..78665f30 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -33,7 +33,7 @@ public partial class TexToolsImporter else { ImGui.NewLine(); - var percentage = _modPackCount / (float)_currentModPackIdx; + var percentage = (float)_currentModPackIdx / _modPackCount; ImGui.ProgressBar(percentage, size, $"Mod {_currentModPackIdx + 1} / {_modPackCount}"); ImGui.NewLine(); if (State == ImporterState.DeduplicatingFiles) From bb742463e99ebdc5e3645a39f585646087801611 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 10 Dec 2023 15:10:43 +0100 Subject: [PATCH 0247/1381] Wait for saves to finish when the file might be read immediately after saving. --- OtterGui | 2 +- Penumbra/Collections/Manager/ModCollectionMigration.cs | 2 +- Penumbra/Mods/Editor/DuplicateManager.cs | 2 +- Penumbra/Mods/ModCreator.cs | 8 ++++---- Penumbra/Services/ConfigMigrationService.cs | 2 +- Penumbra/Services/SaveService.cs | 3 ++- 6 files changed, 10 insertions(+), 9 deletions(-) diff --git a/OtterGui b/OtterGui index 3e2d4ae9..7098e957 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3e2d4ae934694918d312280d62127cf1a55b03e4 +Subproject commit 7098e9577117a3555f5f6181edae6cd306a4b5d4 diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index 025df9ef..b2b8df0d 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -14,7 +14,7 @@ internal static class ModCollectionMigration { var changes = MigrateV0ToV1(collection, ref version); if (changes) - saver.ImmediateSave(new ModCollectionSave(mods, collection)); + saver.ImmediateSaveSync(new ModCollectionSave(mods, collection)); } /// Migrate a mod collection from Version 0 to Version 1, which introduced support for inheritance. diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 488c1c91..7df0389e 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -82,7 +82,7 @@ public class DuplicateManager { var sub = (SubMod)subMod; sub.FileData = dict; - _saveService.ImmediateSave(new ModSaveGroup(mod, groupIdx)); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx)); } } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 98770edc..383b6d2d 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -177,7 +177,7 @@ public partial class ModCreator return; _saveService.SaveAllOptionGroups(mod, false); - _saveService.ImmediateSave(new ModSaveGroup(mod.ModPath, mod.Default)); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default)); } @@ -261,7 +261,7 @@ public partial class ModCreator DefaultSettings = defaultSettings, }; group.PrioritizedOptions.AddRange(subMods.OfType().Select((s, idx) => (s, idx))); - _saveService.ImmediateSave(new ModSaveGroup(baseFolder, group, index)); + _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index)); break; } case GroupType.Single: @@ -274,7 +274,7 @@ public partial class ModCreator DefaultSettings = defaultSettings, }; group.OptionData.AddRange(subMods.OfType()); - _saveService.ImmediateSave(new ModSaveGroup(baseFolder, group, index)); + _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index)); break; } } @@ -321,7 +321,7 @@ public partial class ModCreator } IncorporateMetaChanges(mod.Default, directory, true); - _saveService.ImmediateSave(new ModSaveGroup(mod, -1)); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod, -1)); } /// Return the name of a new valid directory based on the base directory and the given name. diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index 03aedc57..beb23fa2 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -372,7 +372,7 @@ public class ConfigMigrationService var emptyStorage = new ModStorage(); var collection = ModCollection.CreateFromData(_saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, Array.Empty()); - _saveService.ImmediateSave(new ModCollectionSave(emptyStorage, collection)); + _saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) { diff --git a/Penumbra/Services/SaveService.cs b/Penumbra/Services/SaveService.cs index 0e61c565..3f54160d 100644 --- a/Penumbra/Services/SaveService.cs +++ b/Penumbra/Services/SaveService.cs @@ -36,7 +36,8 @@ public sealed class SaveService : SaveServiceBase } } - for (var i = 0; i < mod.Groups.Count; ++i) + for (var i = 0; i < mod.Groups.Count - 1; ++i) ImmediateSave(new ModSaveGroup(mod, i)); + ImmediateSaveSync(new ModSaveGroup(mod, mod.Groups.Count - 1)); } } From 59ea1f2dd637641a3aaf4164a1eb3e409bf03160 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 10 Dec 2023 15:41:26 +0100 Subject: [PATCH 0248/1381] Add option to clear non-ascii symbols from paths again. --- Penumbra/Api/PenumbraApi.cs | 2 +- Penumbra/Configuration.cs | 1 + Penumbra/Import/TexToolsImporter.Archives.cs | 6 +-- Penumbra/Import/TexToolsImporter.ModPack.cs | 10 ++--- Penumbra/Meta/MetaFileManager.cs | 4 +- Penumbra/Mods/Editor/ModMerger.cs | 12 +++--- Penumbra/Mods/Editor/ModNormalizer.cs | 18 ++++----- Penumbra/Mods/Manager/ModManager.cs | 2 +- Penumbra/Mods/ModCreator.cs | 37 ++++++------------- Penumbra/Mods/TemporaryMod.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 6 ++- .../ModEditWindow.QuickImport.cs | 15 ++++---- Penumbra/UI/Tabs/SettingsTab.cs | 3 ++ 13 files changed, 56 insertions(+), 62 deletions(-) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 8974e823..5ce28510 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -877,7 +877,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public PenumbraApiEc CreateNamedTemporaryCollection(string name) { CheckInitialized(); - if (name.Length == 0 || ModCreator.ReplaceBadXivSymbols(name) != name || name.Contains('|')) + if (name.Length == 0 || ModCreator.ReplaceBadXivSymbols(name, _config.ReplaceNonAsciiOnImport) != name || name.Contains('|')) return PenumbraApiEc.InvalidArgument; return _tempCollections.CreateTemporaryCollection(name).Length > 0 diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 8f21ee52..a5a615bd 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -46,6 +46,7 @@ public class Configuration : IPluginConfiguration, ISavable public bool UseOwnerNameForCharacterCollection { get; set; } = true; public bool UseNoModsInInspect { get; set; } = false; public bool HideChangedItemFilters { get; set; } = false; + public bool ReplaceNonAsciiOnImport { get; set; } = false; public bool HidePrioritiesInSelector { get; set; } = false; public bool HideRedrawBar { get; set; } = false; diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index 6ddafdd7..57313ab1 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -44,7 +44,7 @@ public partial class TexToolsImporter }; Penumbra.Log.Information($" -> Importing {archive.Type} Archive."); - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetRandomFileName()); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetRandomFileName(), _config.ReplaceNonAsciiOnImport, true); var options = new ExtractionOptions() { ExtractFullPath = true, @@ -97,13 +97,13 @@ public partial class TexToolsImporter // Use either the top-level directory as the mods base name, or the (fixed for path) name in the json. if (leadDir) { - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, baseName, false); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, baseName, _config.ReplaceNonAsciiOnImport, false); Directory.Move(Path.Combine(oldName, baseName), _currentModDirectory.FullName); Directory.Delete(oldName); } else { - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, name, false); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, name, _config.ReplaceNonAsciiOnImport, false); Directory.Move(oldName, _currentModDirectory.FullName); } diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index dbe76ae3..94a5e5ac 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -35,7 +35,7 @@ public partial class TexToolsImporter var modList = modListRaw.Select(m => JsonConvert.DeserializeObject(m, JsonSettings)!).ToList(); - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetFileNameWithoutExtension(modPackFile.Name)); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetFileNameWithoutExtension(modPackFile.Name), _config.ReplaceNonAsciiOnImport, true); // Create a new ModMeta from the TTMP mod list info _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, DefaultTexToolsData.Author, DefaultTexToolsData.Description, null, null); @@ -88,7 +88,7 @@ public partial class TexToolsImporter _currentOptionName = DefaultTexToolsData.DefaultOption; Penumbra.Log.Information(" -> Importing Simple V2 ModPack"); - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, _currentModName); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, _currentModName, _config.ReplaceNonAsciiOnImport, true); _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, modList.Author, string.IsNullOrEmpty(modList.Description) ? "Mod imported from TexTools mod pack" : modList.Description, modList.Version, modList.Url); @@ -131,7 +131,7 @@ public partial class TexToolsImporter _currentNumOptions = GetOptionCount(modList); _currentModName = modList.Name; - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, _currentModName); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, _currentModName, _config.ReplaceNonAsciiOnImport, true); _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, modList.Author, modList.Description, modList.Version, modList.Url); @@ -168,7 +168,7 @@ public partial class TexToolsImporter { var name = numGroups == 1 ? _currentGroupName : $"{_currentGroupName}, Part {groupId + 1}"; options.Clear(); - var groupFolder = ModCreator.NewSubFolderName(_currentModDirectory, name) + var groupFolder = ModCreator.NewSubFolderName(_currentModDirectory, name, _config.ReplaceNonAsciiOnImport) ?? new DirectoryInfo(Path.Combine(_currentModDirectory.FullName, numGroups == 1 ? $"Group {groupPriority + 1}" : $"Group {groupPriority + 1}, Part {groupId + 1}")); @@ -178,7 +178,7 @@ public partial class TexToolsImporter var option = allOptions[i + optionIdx]; _token.ThrowIfCancellationRequested(); _currentOptionName = option.Name; - var optionFolder = ModCreator.NewSubFolderName(groupFolder, option.Name) + var optionFolder = ModCreator.NewSubFolderName(groupFolder, option.Name, _config.ReplaceNonAsciiOnImport) ?? new DirectoryInfo(Path.Combine(groupFolder.FullName, $"Option {i + optionIdx + 1}")); ExtractSimpleModList(optionFolder, option.ModsJsons); options.Add(_modManager.Creator.CreateSubMod(_currentModDirectory, optionFolder, option)); diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index d918bda2..9c42b9fc 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -49,13 +49,13 @@ public unsafe class MetaFileManager TexToolsMeta.WriteTexToolsMeta(this, mod.Default.Manipulations, mod.ModPath); foreach (var group in mod.Groups) { - var dir = ModCreator.NewOptionDirectory(mod.ModPath, group.Name); + var dir = ModCreator.NewOptionDirectory(mod.ModPath, group.Name, Config.ReplaceNonAsciiOnImport); if (!dir.Exists) dir.Create(); foreach (var option in group.OfType()) { - var optionDir = ModCreator.NewOptionDirectory(dir, option.Name); + var optionDir = ModCreator.NewOptionDirectory(dir, option.Name, Config.ReplaceNonAsciiOnImport); if (!optionDir.Exists) optionDir.Create(); diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 37ffdcfe..1dfe9e76 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -4,7 +4,6 @@ using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Communication; -using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; @@ -15,6 +14,7 @@ namespace Penumbra.Mods.Editor; public class ModMerger : IDisposable { + private readonly Configuration _config; private readonly CommunicatorService _communicator; private readonly ModOptionEditor _editor; private readonly ModFileSystemSelector _selector; @@ -40,13 +40,14 @@ public class ModMerger : IDisposable public Exception? Error { get; private set; } public ModMerger(ModManager mods, ModOptionEditor editor, ModFileSystemSelector selector, DuplicateManager duplicates, - CommunicatorService communicator, ModCreator creator) + CommunicatorService communicator, ModCreator creator, Configuration config) { _editor = editor; _selector = selector; _duplicates = duplicates; _communicator = communicator; _creator = creator; + _config = config; _mods = mods; _selector.SelectionChanged += OnSelectionChange; _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModMerger); @@ -82,7 +83,8 @@ public class ModMerger : IDisposable catch (Exception ex) { Error = ex; - Penumbra.Messager.NotificationMessage(ex, $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}, cleaning up changes.", NotificationType.Error, false); + Penumbra.Messager.NotificationMessage(ex, $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}, cleaning up changes.", + NotificationType.Error, false); FailureCleanup(); DataCleanup(); } @@ -138,10 +140,10 @@ public class ModMerger : IDisposable var (option, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName); if (optionCreated) _createdOptions.Add(option); - var dir = ModCreator.NewOptionDirectory(MergeToMod!.ModPath, groupName); + var dir = ModCreator.NewOptionDirectory(MergeToMod!.ModPath, groupName, _config.ReplaceNonAsciiOnImport); if (!dir.Exists) _createdDirectories.Add(dir.FullName); - dir = ModCreator.NewOptionDirectory(dir, optionName); + dir = ModCreator.NewOptionDirectory(dir, optionName, _config.ReplaceNonAsciiOnImport); if (!dir.Exists) _createdDirectories.Add(dir.FullName); CopyFiles(dir); diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 3610c99a..c146b6f4 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -6,11 +6,10 @@ using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; -public class ModNormalizer +public class ModNormalizer(ModManager _modManager, Configuration _config) { - private readonly ModManager _modManager; private readonly List>> _redirections = new(); public Mod Mod { get; private set; } = null!; @@ -25,9 +24,6 @@ public class ModNormalizer public bool Running => !Worker.IsCompleted; - public ModNormalizer(ModManager modManager) - => _modManager = modManager; - public void Normalize(Mod mod) { if (Step < TotalSteps) @@ -175,10 +171,10 @@ public class ModNormalizer for (var i = _redirections[groupIdx + 1].Count; i < group.Count; ++i) _redirections[groupIdx + 1].Add(new Dictionary()); - var groupDir = ModCreator.CreateModFolder(directory, group.Name); + var groupDir = ModCreator.CreateModFolder(directory, group.Name, _config.ReplaceNonAsciiOnImport, true); foreach (var option in group.OfType()) { - var optionDir = ModCreator.CreateModFolder(groupDir, option.Name); + var optionDir = ModCreator.CreateModFolder(groupDir, option.Name, _config.ReplaceNonAsciiOnImport, true); newDict = _redirections[groupIdx + 1][option.OptionIdx]; newDict.Clear(); @@ -228,7 +224,8 @@ public class ModNormalizer } catch (Exception e) { - Penumbra.Messager.NotificationMessage(e, $"Could not move old files out of the way while normalizing mod {Mod.Name}.", NotificationType.Error, false); + Penumbra.Messager.NotificationMessage(e, $"Could not move old files out of the way while normalizing mod {Mod.Name}.", + NotificationType.Error, false); } return false; @@ -251,7 +248,8 @@ public class ModNormalizer } catch (Exception e) { - Penumbra.Messager.NotificationMessage(e, $"Could not move new files into the mod while normalizing mod {Mod.Name}.", NotificationType.Error, false); + Penumbra.Messager.NotificationMessage(e, $"Could not move new files into the mod while normalizing mod {Mod.Name}.", + NotificationType.Error, false); foreach (var dir in Mod.ModPath.EnumerateDirectories()) { if (dir.FullName.Equals(_oldDirName, StringComparison.OrdinalIgnoreCase) diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index e258f996..40585520 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -217,7 +217,7 @@ public sealed class ModManager : ModStorage, IDisposable if (oldName == newName) return NewDirectoryState.Identical; - var fixedNewName = ModCreator.ReplaceBadXivSymbols(newName); + var fixedNewName = ModCreator.ReplaceBadXivSymbols(newName, _config.ReplaceNonAsciiOnImport); if (fixedNewName != newName) return NewDirectoryState.ContainsInvalidSymbols; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 383b6d2d..31fa64ab 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -16,30 +16,15 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; -public partial class ModCreator +public partial class ModCreator(SaveService _saveService, Configuration _config, ModDataEditor _dataEditor, MetaFileManager _metaFileManager, + IGamePathParser _gamePathParser) { - private readonly Configuration _config; - private readonly SaveService _saveService; - private readonly ModDataEditor _dataEditor; - private readonly MetaFileManager _metaFileManager; - private readonly IGamePathParser _gamePathParser; - - public ModCreator(SaveService saveService, Configuration config, ModDataEditor dataEditor, MetaFileManager metaFileManager, - IGamePathParser gamePathParser) - { - _saveService = saveService; - _config = config; - _dataEditor = dataEditor; - _metaFileManager = metaFileManager; - _gamePathParser = gamePathParser; - } - /// Creates directory and files necessary for a new mod without adding it to the manager. public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "") { try { - var newDir = CreateModFolder(basePath, newName); + var newDir = CreateModFolder(basePath, newName, _config.ReplaceNonAsciiOnImport, true); _dataEditor.CreateMeta(newDir, newName, _config.DefaultModAuthor, description, "1.0", string.Empty); CreateDefaultFiles(newDir); return newDir; @@ -138,13 +123,13 @@ public partial class ModCreator /// - Unique, by appending (digit) for duplicates.
/// - Containing no symbols invalid for FFXIV or windows paths.
/// - public static DirectoryInfo CreateModFolder(DirectoryInfo outDirectory, string modListName, bool create = true) + public static DirectoryInfo CreateModFolder(DirectoryInfo outDirectory, string modListName, bool onlyAscii, bool create) { var name = modListName; if (name.Length == 0) name = "_"; - var newModFolderBase = NewOptionDirectory(outDirectory, name); + var newModFolderBase = NewOptionDirectory(outDirectory, name, onlyAscii); var newModFolder = newModFolderBase.FullName.ObtainUniqueFile(); if (newModFolder.Length == 0) throw new IOException("Could not create mod folder: too many folders of the same name exist."); @@ -238,9 +223,9 @@ public partial class ModCreator /// Create the name for a group or option subfolder based on its parent folder and given name. /// subFolderName should never be empty, and the result is unique and contains no invalid symbols. /// - public static DirectoryInfo? NewSubFolderName(DirectoryInfo parentFolder, string subFolderName) + public static DirectoryInfo? NewSubFolderName(DirectoryInfo parentFolder, string subFolderName, bool onlyAscii) { - var newModFolderBase = NewOptionDirectory(parentFolder, subFolderName); + var newModFolderBase = NewOptionDirectory(parentFolder, subFolderName, onlyAscii); var newModFolder = newModFolderBase.FullName.ObtainUniqueFile(); return newModFolder.Length == 0 ? null : new DirectoryInfo(newModFolder); } @@ -325,14 +310,14 @@ public partial class ModCreator } /// Return the name of a new valid directory based on the base directory and the given name. - public static DirectoryInfo NewOptionDirectory(DirectoryInfo baseDir, string optionName) + public static DirectoryInfo NewOptionDirectory(DirectoryInfo baseDir, string optionName, bool onlyAscii) { - var option = ReplaceBadXivSymbols(optionName); + var option = ReplaceBadXivSymbols(optionName, onlyAscii); return new DirectoryInfo(Path.Combine(baseDir.FullName, option.Length > 0 ? option : "_")); } /// Normalize for nicer names, and remove invalid symbols or invalid paths. - public static string ReplaceBadXivSymbols(string s, string replacement = "_") + public static string ReplaceBadXivSymbols(string s, bool onlyAscii, string replacement = "_") { switch (s) { @@ -345,6 +330,8 @@ public partial class ModCreator { if (c.IsInvalidInPath()) sb.Append(replacement); + else if (onlyAscii && c.IsInvalidAscii()) + sb.Append(replacement); else sb.Append(c); } diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 73273707..dc73b451 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -52,7 +52,7 @@ public class TemporaryMod : IMod DirectoryInfo? dir = null; try { - dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Name); + dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Name, config.ReplaceNonAsciiOnImport, true); var fileDir = Directory.CreateDirectory(Path.Combine(dir.FullName, "files")); modManager.DataEditor.CreateMeta(dir, collection.Name, character ?? config.DefaultModAuthor, $"Mod generated from temporary collection {collection.Name} for {character ?? "Unknown Character"}.", null, null); diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 8597bc0c..5347208e 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -25,6 +25,7 @@ namespace Penumbra.UI.AdvancedWindow; public class ItemSwapTab : IDisposable, ITab { + private readonly Configuration _config; private readonly CommunicatorService _communicator; private readonly ItemService _itemService; private readonly CollectionManager _collectionManager; @@ -32,13 +33,14 @@ public class ItemSwapTab : IDisposable, ITab private readonly MetaFileManager _metaFileManager; public ItemSwapTab(CommunicatorService communicator, ItemService itemService, CollectionManager collectionManager, - ModManager modManager, IdentifierService identifier, MetaFileManager metaFileManager) + ModManager modManager, IdentifierService identifier, MetaFileManager metaFileManager, Configuration config) { _communicator = communicator; _itemService = itemService; _collectionManager = collectionManager; _modManager = modManager; _metaFileManager = metaFileManager; + _config = config; _swapData = new ItemSwapContainer(metaFileManager, identifier); _selectors = new Dictionary @@ -296,7 +298,7 @@ public class ItemSwapTab : IDisposable, ITab { optionFolderName = ModCreator.NewSubFolderName(new DirectoryInfo(Path.Combine(_mod.ModPath.FullName, _selectedGroup?.Name ?? _newGroupName)), - _newOptionName); + _newOptionName, _config.ReplaceNonAsciiOnImport); if (optionFolderName?.Exists == true) throw new Exception($"The folder {optionFolderName.FullName} for the option already exists."); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 63ea8581..64457c25 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -22,12 +22,13 @@ public partial class ModEditWindow private HashSet GetPlayerResourcesOfType(ResourceType type) { - var resources = ResourceTreeApiHelper.GetResourcesOfType(_resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly), type) + var resources = ResourceTreeApiHelper + .GetResourcesOfType(_resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly), type) .Values .SelectMany(resources => resources.Values) .Select(resource => resource.Item1); - return new(resources, StringComparer.OrdinalIgnoreCase); + return new HashSet(resources, StringComparer.OrdinalIgnoreCase); } private IReadOnlyList PopulateIsOnPlayer(IReadOnlyList files, ResourceType type) @@ -198,7 +199,7 @@ public partial class ModEditWindow if (mod == null) return new QuickImportAction(editor, optionName, gamePath); - var (preferredPath, subDirs) = GetPreferredPath(mod, subMod); + var (preferredPath, subDirs) = GetPreferredPath(mod, subMod, owner._config.ReplaceNonAsciiOnImport); var targetPath = new FullPath(Path.Combine(preferredPath.FullName, gamePath.ToString())).FullName; if (File.Exists(targetPath)) return new QuickImportAction(editor, optionName, gamePath); @@ -226,7 +227,7 @@ public partial class ModEditWindow return fileRegistry; } - private static (DirectoryInfo, int) GetPreferredPath(Mod mod, ISubMod subMod) + private static (DirectoryInfo, int) GetPreferredPath(Mod mod, ISubMod subMod, bool replaceNonAscii) { var path = mod.ModPath; var subDirs = 0; @@ -237,13 +238,13 @@ public partial class ModEditWindow var fullName = subMod.FullName; if (fullName.EndsWith(": " + name)) { - path = ModCreator.NewOptionDirectory(path, fullName[..^(name.Length + 2)]); - path = ModCreator.NewOptionDirectory(path, name); + path = ModCreator.NewOptionDirectory(path, fullName[..^(name.Length + 2)], replaceNonAscii); + path = ModCreator.NewOptionDirectory(path, name, replaceNonAscii); subDirs = 2; } else { - path = ModCreator.NewOptionDirectory(path, fullName); + path = ModCreator.NewOptionDirectory(path, fullName, replaceNonAscii); subDirs = 1; } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 70a94ecd..104f8d91 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -535,6 +535,9 @@ public class SettingsTab : ITab /// Draw all settings pertaining to import and export of mods. private void DrawModHandlingSettings() { + Checkbox("Replace Non-Standard Symbols On Import", + "Replace all non-ASCII symbols in mod and option names with underscores when importing mods.", _config.ReplaceNonAsciiOnImport, + v => _config.ReplaceNonAsciiOnImport = v); Checkbox("Always Open Import at Default Directory", "Open the import window at the location specified here every time, forgetting your previous path.", _config.AlwaysOpenDefaultImport, v => _config.AlwaysOpenDefaultImport = v); From 54776c45ea5a86c0133322752055e1d4db2a8f74 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 10 Dec 2023 15:41:38 +0100 Subject: [PATCH 0249/1381] 0.8.3.0 --- Penumbra/UI/Changelog.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 1cdb8ae4..d172cfb9 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -45,10 +45,24 @@ public class PenumbraChangelog Add8_1_1(Changelog); Add8_1_2(Changelog); Add8_2_0(Changelog); + Add8_3_0(Changelog); } #region Changelogs + private static void Add8_3_0(Changelog log) + => log.NextVersion("Version 0.8.3.0") + .RegisterHighlight("Improved the UI for the On-Screen tabs with highlighting of used paths, filtering and more selections. (by Ny)") + .RegisterEntry("Added an option to replace non-ASCII symbols with underscores for folder paths on mod import since this causes problems on some WINE systems. This option is off by default.") + .RegisterEntry( + "Added support for the Changed Item Icons to load modded icons, but this depends on a not-yet-released Dalamud update.") + .RegisterEntry( + "Penumbra should no longer redraw characters while they are fishing, but wait for them to reel in, because that could cause soft-locks. This may cause other issues, but I have not found any.") + .RegisterEntry( + "Hopefully fixed a bug on mod import where files were being read while they were still saving, causing Penumbra to create wrong options.") + .RegisterEntry("Fixed a few display issues.") + .RegisterEntry("Added some IPC functionality for Xande. (by Asriel)"); + private static void Add8_2_0(Changelog log) => log.NextVersion("Version 0.8.2.0") .RegisterHighlight( From 76cb09b3b557093932348662c303e3d1f20fe476 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 10 Dec 2023 14:43:34 +0000 Subject: [PATCH 0250/1381] [CI] Updating repo.json for 0.8.3.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index af1104be..a04b35b5 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.2.1", - "TestingAssemblyVersion": "0.8.2.3", + "AssemblyVersion": "0.8.3.0", + "TestingAssemblyVersion": "0.8.3.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.2.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.2.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 173b4d7306b662ccbfae466ac50d488ebf0c700e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 12 Dec 2023 21:05:08 +0100 Subject: [PATCH 0251/1381] Respect ascii setting for group names. --- Penumbra/Mods/Editor/DuplicateManager.cs | 6 ++-- Penumbra/Mods/Manager/ModMigration.cs | 4 +-- Penumbra/Mods/Manager/ModOptionEditor.cs | 44 +++++++++++++----------- Penumbra/Mods/ModCreator.cs | 29 +++++++++------- Penumbra/Mods/Subclasses/IModGroup.cs | 18 ++++++---- Penumbra/Mods/TemporaryMod.cs | 2 +- Penumbra/Services/FilenameService.cs | 8 ++--- Penumbra/Services/SaveService.cs | 6 ++-- Penumbra/UI/Changelog.cs | 3 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 8 ++--- 10 files changed, 70 insertions(+), 58 deletions(-) diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 7df0389e..47c34ce5 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -7,15 +7,17 @@ namespace Penumbra.Mods.Editor; public class DuplicateManager { + private readonly Configuration _config; private readonly SaveService _saveService; private readonly ModManager _modManager; private readonly SHA256 _hasher = SHA256.Create(); private readonly List<(FullPath[] Paths, long Size, byte[] Hash)> _duplicates = new(); - public DuplicateManager(ModManager modManager, SaveService saveService) + public DuplicateManager(ModManager modManager, SaveService saveService, Configuration config) { _modManager = modManager; _saveService = saveService; + _config = config; } public IReadOnlyList<(FullPath[] Paths, long Size, byte[] Hash)> Duplicates @@ -82,7 +84,7 @@ public class DuplicateManager { var sub = (SubMod)subMod; sub.FileData = dict; - _saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx)); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); } } diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 452da366..8b73cae5 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -83,7 +83,7 @@ public static partial class ModMigration creator.IncorporateMetaChanges(mod.Default, mod.ModPath, true); foreach (var (_, index) in mod.Groups.WithIndex()) - saveService.ImmediateSave(new ModSaveGroup(mod, index)); + saveService.ImmediateSave(new ModSaveGroup(mod, index, creator.Config.ReplaceNonAsciiOnImport)); // Delete meta files. foreach (var file in seenMetaFiles.Where(f => f.Exists)) @@ -111,7 +111,7 @@ public static partial class ModMigration } fileVersion = 1; - saveService.ImmediateSave(new ModSaveGroup(mod, -1)); + saveService.ImmediateSave(new ModSaveGroup(mod, -1, creator.Config.ReplaceNonAsciiOnImport)); return true; } diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 0a3034fc..73cb80cc 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -33,13 +33,15 @@ public enum ModOptionChangeType public class ModOptionEditor { + private readonly Configuration _config; private readonly CommunicatorService _communicator; private readonly SaveService _saveService; - public ModOptionEditor(CommunicatorService communicator, SaveService saveService) + public ModOptionEditor(CommunicatorService communicator, SaveService saveService, Configuration config) { _communicator = communicator; _saveService = saveService; + _config = config; } /// Change the type of a group given by mod and index to type, if possible. @@ -50,7 +52,7 @@ public class ModOptionEditor return; mod.Groups[groupIdx] = group.Convert(type); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, mod, groupIdx, -1, -1); } @@ -62,7 +64,7 @@ public class ModOptionEditor return; group.DefaultSettings = defaultOption; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, mod, groupIdx, -1, -1); } @@ -74,7 +76,7 @@ public class ModOptionEditor if (oldName == newName || !VerifyFileName(mod, group, newName, true)) return; - _saveService.ImmediateDelete(new ModSaveGroup(mod, groupIdx)); + _saveService.ImmediateDelete(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); var _ = group switch { SingleModGroup s => s.Name = newName, @@ -82,7 +84,7 @@ public class ModOptionEditor _ => newName, }; - _saveService.ImmediateSave(new ModSaveGroup(mod, groupIdx)); + _saveService.ImmediateSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, mod, groupIdx, -1, -1); } @@ -105,7 +107,7 @@ public class ModOptionEditor Name = newName, Priority = maxPriority, }); - _saveService.ImmediateSave(new ModSaveGroup(mod, mod.Groups.Count - 1)); + _saveService.ImmediateSave(new ModSaveGroup(mod, mod.Groups.Count - 1, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, mod.Groups.Count - 1, -1, -1); } @@ -129,7 +131,7 @@ public class ModOptionEditor _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, -1, -1); mod.Groups.RemoveAt(groupIdx); UpdateSubModPositions(mod, groupIdx); - _saveService.SaveAllOptionGroups(mod, false); + _saveService.SaveAllOptionGroups(mod, false, _config.ReplaceNonAsciiOnImport); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, groupIdx, -1, -1); } @@ -140,7 +142,7 @@ public class ModOptionEditor return; UpdateSubModPositions(mod, Math.Min(groupIdxFrom, groupIdxTo)); - _saveService.SaveAllOptionGroups(mod, false); + _saveService.SaveAllOptionGroups(mod, false, _config.ReplaceNonAsciiOnImport); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, groupIdxFrom, -1, groupIdxTo); } @@ -157,7 +159,7 @@ public class ModOptionEditor MultiModGroup m => m.Description = newDescription, _ => newDescription, }; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, -1, -1); } @@ -170,7 +172,7 @@ public class ModOptionEditor return; s.Description = newDescription; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } @@ -187,7 +189,7 @@ public class ModOptionEditor MultiModGroup m => m.Priority = newPriority, _ => newPriority, }; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, -1, -1); } @@ -204,7 +206,7 @@ public class ModOptionEditor return; m.PrioritizedOptions[optionIdx] = (m.PrioritizedOptions[optionIdx].Mod, newPriority); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, optionIdx, -1); return; } @@ -230,7 +232,7 @@ public class ModOptionEditor break; } - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } @@ -250,7 +252,7 @@ public class ModOptionEditor break; } - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); } @@ -296,7 +298,7 @@ public class ModOptionEditor break; } - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); } @@ -317,7 +319,7 @@ public class ModOptionEditor } group.UpdatePositions(optionIdx); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionDeleted, mod, groupIdx, optionIdx, -1); } @@ -328,7 +330,7 @@ public class ModOptionEditor if (!group.MoveOption(optionIdxFrom, optionIdxTo)) return; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, mod, groupIdx, optionIdxFrom, optionIdxTo); } @@ -342,7 +344,7 @@ public class ModOptionEditor _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.ManipulationData.SetTo(manipulations); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, optionIdx, -1); } @@ -355,7 +357,7 @@ public class ModOptionEditor _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.FileData.SetTo(replacements); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, optionIdx, -1); } @@ -367,7 +369,7 @@ public class ModOptionEditor subMod.FileData.AddFrom(additions); if (oldCount != subMod.FileData.Count) { - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, mod, groupIdx, optionIdx, -1); } } @@ -381,7 +383,7 @@ public class ModOptionEditor _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.FileSwapData.SetTo(swaps); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx)); + _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, optionIdx, -1); } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 31fa64ab..9a31cf46 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -16,16 +16,18 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; -public partial class ModCreator(SaveService _saveService, Configuration _config, ModDataEditor _dataEditor, MetaFileManager _metaFileManager, +public partial class ModCreator(SaveService _saveService, Configuration config, ModDataEditor _dataEditor, MetaFileManager _metaFileManager, IGamePathParser _gamePathParser) { + public readonly Configuration Config = config; + /// Creates directory and files necessary for a new mod without adding it to the manager. public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "") { try { - var newDir = CreateModFolder(basePath, newName, _config.ReplaceNonAsciiOnImport, true); - _dataEditor.CreateMeta(newDir, newName, _config.DefaultModAuthor, description, "1.0", string.Empty); + var newDir = CreateModFolder(basePath, newName, Config.ReplaceNonAsciiOnImport, true); + _dataEditor.CreateMeta(newDir, newName, Config.DefaultModAuthor, description, "1.0", string.Empty); CreateDefaultFiles(newDir); return newDir; } @@ -86,7 +88,8 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, if (group != null && mod.Groups.All(g => g.Name != group.Name)) { changes = changes - || _saveService.FileNames.OptionGroupFile(mod.ModPath.FullName, mod.Groups.Count, group.Name) != file.FullName; + || _saveService.FileNames.OptionGroupFile(mod.ModPath.FullName, mod.Groups.Count, group.Name, true) + != Path.Combine(file.DirectoryName!, ReplaceBadXivSymbols(file.Name, true)); mod.Groups.Add(group); } else @@ -96,13 +99,13 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, } if (changes) - _saveService.SaveAllOptionGroups(mod, true); + _saveService.SaveAllOptionGroups(mod, true, Config.ReplaceNonAsciiOnImport); } /// Load the default option for a given mod. public void LoadDefaultOption(Mod mod) { - var defaultFile = _saveService.FileNames.OptionGroupFile(mod, -1); + var defaultFile = _saveService.FileNames.OptionGroupFile(mod, -1, Config.ReplaceNonAsciiOnImport); mod.Default.SetPosition(-1, 0); try { @@ -161,8 +164,8 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, if (!changes) return; - _saveService.SaveAllOptionGroups(mod, false); - _saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default)); + _saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); } @@ -188,7 +191,7 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, continue; var meta = new TexToolsMeta(_metaFileManager, _gamePathParser, File.ReadAllBytes(file.FullName), - _config.KeepDefaultMetaChanges); + Config.KeepDefaultMetaChanges); Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); @@ -201,7 +204,7 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, continue; var rgsp = TexToolsMeta.FromRgspFile(_metaFileManager, file.FullName, File.ReadAllBytes(file.FullName), - _config.KeepDefaultMetaChanges); + Config.KeepDefaultMetaChanges); Penumbra.Log.Verbose( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); @@ -246,7 +249,7 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, DefaultSettings = defaultSettings, }; group.PrioritizedOptions.AddRange(subMods.OfType().Select((s, idx) => (s, idx))); - _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index)); + _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } case GroupType.Single: @@ -259,7 +262,7 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, DefaultSettings = defaultSettings, }; group.OptionData.AddRange(subMods.OfType()); - _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index)); + _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } } @@ -306,7 +309,7 @@ public partial class ModCreator(SaveService _saveService, Configuration _config, } IncorporateMetaChanges(mod.Default, directory, true); - _saveService.ImmediateSaveSync(new ModSaveGroup(mod, -1)); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod, -1, Config.ReplaceNonAsciiOnImport)); } /// Return the name of a new valid directory based on the base directory and the given name. diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 957fe21d..ea5f176c 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -39,8 +39,9 @@ public readonly struct ModSaveGroup : ISavable private readonly IModGroup? _group; private readonly int _groupIdx; private readonly ISubMod? _defaultMod; + private readonly bool _onlyAscii; - public ModSaveGroup(Mod mod, int groupIdx) + public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) { _basePath = mod.ModPath; _groupIdx = groupIdx; @@ -48,24 +49,27 @@ public readonly struct ModSaveGroup : ISavable _defaultMod = mod.Default; else _group = mod.Groups[_groupIdx]; + _onlyAscii = onlyAscii; } - public ModSaveGroup(DirectoryInfo basePath, IModGroup group, int groupIdx) + public ModSaveGroup(DirectoryInfo basePath, IModGroup group, int groupIdx, bool onlyAscii) { - _basePath = basePath; - _group = group; - _groupIdx = groupIdx; + _basePath = basePath; + _group = group; + _groupIdx = groupIdx; + _onlyAscii = onlyAscii; } - public ModSaveGroup(DirectoryInfo basePath, ISubMod @default) + public ModSaveGroup(DirectoryInfo basePath, ISubMod @default, bool onlyAscii) { _basePath = basePath; _groupIdx = -1; _defaultMod = @default; + _onlyAscii = onlyAscii; } public string ToFilename(FilenameService fileNames) - => fileNames.OptionGroupFile(_basePath.FullName, _groupIdx, _group?.Name ?? string.Empty); + => fileNames.OptionGroupFile(_basePath.FullName, _groupIdx, _group?.Name ?? string.Empty, _onlyAscii); public void Save(StreamWriter writer) { diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index dc73b451..52159258 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -86,7 +86,7 @@ public class TemporaryMod : IMod foreach (var manip in collection.MetaCache?.Manipulations ?? Array.Empty()) defaultMod.ManipulationData.Add(manip); - saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod)); + saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir); Penumbra.Log.Information($"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Name}."); } diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index cf99c6c8..52881b9e 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -60,14 +60,14 @@ public class FilenameService(DalamudPluginInterface pi) => Path.Combine(modDirectory, "meta.json"); /// Obtain the path of the file describing a given option group by its index and the mod. If the index is < 0, return the path for the default mod file. - public string OptionGroupFile(Mod mod, int index) - => OptionGroupFile(mod.ModPath.FullName, index, index >= 0 ? mod.Groups[index].Name : string.Empty); + public string OptionGroupFile(Mod mod, int index, bool onlyAscii) + => OptionGroupFile(mod.ModPath.FullName, index, index >= 0 ? mod.Groups[index].Name : string.Empty, onlyAscii); /// Obtain the path of the file describing a given option group by its index, name and basepath. If the index is < 0, return the path for the default mod file. - public string OptionGroupFile(string basePath, int index, string name) + public string OptionGroupFile(string basePath, int index, string name, bool onlyAscii) { var fileName = index >= 0 - ? $"group_{index + 1:D3}_{name.RemoveInvalidPathSymbols().ToLowerInvariant()}.json" + ? $"group_{index + 1:D3}_{ModCreator.ReplaceBadXivSymbols(name.ToLowerInvariant(), onlyAscii)}.json" : "default_mod.json"; return Path.Combine(basePath, fileName); } diff --git a/Penumbra/Services/SaveService.cs b/Penumbra/Services/SaveService.cs index 3f54160d..40dc4107 100644 --- a/Penumbra/Services/SaveService.cs +++ b/Penumbra/Services/SaveService.cs @@ -18,7 +18,7 @@ public sealed class SaveService : SaveServiceBase { } /// Immediately delete all existing option group files for a mod and save them anew. - public void SaveAllOptionGroups(Mod mod, bool backup) + public void SaveAllOptionGroups(Mod mod, bool backup, bool onlyAscii) { foreach (var file in FileNames.GetOptionGroupFiles(mod)) { @@ -37,7 +37,7 @@ public sealed class SaveService : SaveServiceBase } for (var i = 0; i < mod.Groups.Count - 1; ++i) - ImmediateSave(new ModSaveGroup(mod, i)); - ImmediateSaveSync(new ModSaveGroup(mod, mod.Groups.Count - 1)); + ImmediateSave(new ModSaveGroup(mod, i, onlyAscii)); + ImmediateSaveSync(new ModSaveGroup(mod, mod.Groups.Count - 1, onlyAscii)); } } diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index d172cfb9..d5b77bf4 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -53,7 +53,8 @@ public class PenumbraChangelog private static void Add8_3_0(Changelog log) => log.NextVersion("Version 0.8.3.0") .RegisterHighlight("Improved the UI for the On-Screen tabs with highlighting of used paths, filtering and more selections. (by Ny)") - .RegisterEntry("Added an option to replace non-ASCII symbols with underscores for folder paths on mod import since this causes problems on some WINE systems. This option is off by default.") + .RegisterEntry( + "Added an option to replace non-ASCII symbols with underscores for folder paths on mod import since this causes problems on some WINE systems. This option is off by default.") .RegisterEntry( "Added support for the Changed Item Icons to load modded icons, but this depends on a not-yet-released Dalamud update.") .RegisterEntry( diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 18d0e613..ed7a6a67 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -86,7 +86,7 @@ public class ModPanelEditTab : ITab _modManager.DataEditor.ChangeModTag(_mod, tagIdx, editedTag); UiHelpers.DefaultLineSpace(); - AddOptionGroup.Draw(_filenames, _modManager, _mod); + AddOptionGroup.Draw(_filenames, _modManager, _mod, _config.ReplaceNonAsciiOnImport); UiHelpers.DefaultLineSpace(); for (var groupIdx = 0; groupIdx < _mod.Groups.Count; ++groupIdx) @@ -235,13 +235,13 @@ public class ModPanelEditTab : ITab public static void Reset() => _newGroupName = string.Empty; - public static void Draw(FilenameService filenames, ModManager modManager, Mod mod) + public static void Draw(FilenameService filenames, ModManager modManager, Mod mod, bool onlyAscii) { using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3)); ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); ImGui.InputTextWithHint("##newGroup", "Add new option group...", ref _newGroupName, 256); ImGui.SameLine(); - var defaultFile = filenames.OptionGroupFile(mod, -1); + var defaultFile = filenames.OptionGroupFile(mod, -1, onlyAscii); var fileExists = File.Exists(defaultFile); var tt = fileExists ? "Open the default option json file in the text editor of your choice." @@ -438,7 +438,7 @@ public class ModPanelEditTab : ITab _delayedActions.Enqueue(() => DescriptionEdit.OpenPopup(_mod, groupIdx)); ImGui.SameLine(); - var fileName = _filenames.OptionGroupFile(_mod, groupIdx); + var fileName = _filenames.OptionGroupFile(_mod, groupIdx, _config.ReplaceNonAsciiOnImport); var fileExists = File.Exists(fileName); tt = fileExists ? $"Open the {group.Name} json file in the text editor of your choice." From 0514e72d47a271892d9533f7e02eba4c3a076475 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 13 Dec 2023 20:47:18 +0100 Subject: [PATCH 0252/1381] Update sizing for option groups. --- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index ed7a6a67..20da8fde 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -475,10 +475,11 @@ public class ModPanelEditTab : ITab if (!table) return; - ImGui.TableSetupColumn("idx", ImGuiTableColumnFlags.WidthFixed, 60 * UiHelpers.Scale); + var maxWidth = ImGui.CalcTextSize("Option #88.").X; + ImGui.TableSetupColumn("idx", ImGuiTableColumnFlags.WidthFixed, maxWidth); ImGui.TableSetupColumn("default", ImGuiTableColumnFlags.WidthFixed, ImGui.GetFrameHeight()); ImGui.TableSetupColumn("name", ImGuiTableColumnFlags.WidthFixed, - UiHelpers.InputTextWidth.X - 72 * UiHelpers.Scale - ImGui.GetFrameHeight() - UiHelpers.IconButtonSize.X); + UiHelpers.InputTextWidth.X - maxWidth - 12 * UiHelpers.Scale - ImGui.GetFrameHeight() - UiHelpers.IconButtonSize.X); ImGui.TableSetupColumn("description", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); ImGui.TableSetupColumn("delete", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); ImGui.TableSetupColumn("priority", ImGuiTableColumnFlags.WidthFixed, 50 * UiHelpers.Scale); @@ -644,7 +645,7 @@ public class ModPanelEditTab : ITab _ => "Unknown", }; - ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X - 3 * (UiHelpers.IconButtonSize.X - 4 * UiHelpers.Scale)); + ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X - 2 * UiHelpers.IconButtonSize.X - 2 * ImGui.GetStyle().ItemSpacing.X); using var combo = ImRaii.Combo("##GroupType", GroupTypeName(group.Type)); if (!combo) return; From 330525048213693cf4d2ad578d2795619537b618 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 14 Dec 2023 14:24:05 +0100 Subject: [PATCH 0253/1381] Misc. --- OtterGui | 2 +- Penumbra/Services/BackupService.cs | 6 +----- Penumbra/Services/ValidityChecker.cs | 2 +- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/OtterGui b/OtterGui index 7098e957..5f0eec50 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 7098e9577117a3555f5f6181edae6cd306a4b5d4 +Subproject commit 5f0eec50ea7f7a4727ceab056bc3756f0ed58a30 diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index 7b8ace29..0059cf9f 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -14,11 +14,7 @@ public class BackupService Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), files); } - public static void CreatePermanentBackup(FilenameService fileNames) - => Backup.CreatePermanentBackup(Penumbra.Log, new DirectoryInfo(fileNames.ConfigDirectory), PenumbraFiles(fileNames), - "pre_ephemeral_config"); - - // Collect all relevant files for penumbra configuration. + /// Collect all relevant files for penumbra configuration. private static IReadOnlyList PenumbraFiles(FilenameService fileNames) { var list = fileNames.CollectionFiles.ToList(); diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index 749da5b9..0688850b 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -26,7 +26,7 @@ public class ValidityChecker IsNotInstalledPenumbra = CheckIsNotInstalled(pi); IsValidSourceRepo = CheckSourceRepo(pi); - var assembly = Assembly.GetExecutingAssembly(); + var assembly = GetType().Assembly; Version = assembly.GetName().Version?.ToString() ?? string.Empty; CommitHash = assembly.GetCustomAttribute()?.InformationalVersion ?? "Unknown"; } From 7d612df95156841dcfe0c780be246a9227a98a22 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Dec 2023 11:51:24 +0100 Subject: [PATCH 0254/1381] Update for changed GameData. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/PenumbraApi.cs | 18 ++-- Penumbra/Collections/Cache/CollectionCache.cs | 24 ++--- .../Cache/CollectionCacheManager.cs | 4 +- .../Collections/Manager/ActiveCollections.cs | 10 +- .../Manager/IndividualCollections.Access.cs | 33 +++---- .../Manager/IndividualCollections.Files.cs | 40 ++++---- .../Manager/IndividualCollections.cs | 81 +++++++--------- .../Manager/TempCollectionManager.cs | 8 +- Penumbra/CommandHandler.cs | 4 +- Penumbra/Import/Structs/MetaFileInfo.cs | 3 +- Penumbra/Import/TexToolsMeta.cs | 3 +- .../PathResolving/CollectionResolver.cs | 16 ++-- .../Interop/PathResolving/CutsceneService.cs | 5 +- .../Interop/ResourceTree/ResolveContext.cs | 26 +++-- .../ResourceTree/ResourceTreeFactory.cs | 32 ++++--- .../Interop/ResourceTree/TreeBuildCache.cs | 40 +++----- Penumbra/Interop/Services/RedrawService.cs | 2 +- Penumbra/Meta/MetaFileManager.cs | 5 +- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 14 +-- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 19 ++-- Penumbra/Mods/Manager/ModCacheManager.cs | 31 +++--- Penumbra/Mods/ModCreator.cs | 4 +- Penumbra/Penumbra.cs | 26 ++--- Penumbra/Services/BackupService.cs | 4 +- Penumbra/Services/ServiceManager.cs | 40 ++++++-- Penumbra/Services/ServiceWrapper.cs | 30 +----- Penumbra/Services/StainService.cs | 11 +-- Penumbra/Services/Wrappers.cs | 34 ------- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 32 +++---- .../ModEditWindow.ShaderPackages.cs | 1 + .../AdvancedWindow/ModEditWindow.ShpkTab.cs | 1 + Penumbra/UI/CollectionTab/CollectionPanel.cs | 8 +- .../CollectionTab/IndividualAssignmentUi.cs | 61 ++++++------ .../UI/ResourceWatcher/ResourceWatcher.cs | 16 ++-- Penumbra/UI/Tabs/CollectionsTab.cs | 5 +- Penumbra/UI/Tabs/ConfigTabBar.cs | 1 + Penumbra/UI/Tabs/{ => Debug}/DebugTab.cs | 95 ++++++++++++------- Penumbra/UI/WindowSystem.cs | 2 +- Penumbra/Util/PerformanceType.cs | 33 ------- Penumbra/packages.lock.json | 3 +- 42 files changed, 374 insertions(+), 455 deletions(-) delete mode 100644 Penumbra/Services/Wrappers.cs rename Penumbra/UI/Tabs/{ => Debug}/DebugTab.cs (94%) diff --git a/OtterGui b/OtterGui index 5f0eec50..bde59c34 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5f0eec50ea7f7a4727ceab056bc3756f0ed58a30 +Subproject commit bde59c34f7108520002c21cdbf21e8ee5b586944 diff --git a/Penumbra.GameData b/Penumbra.GameData index ffdb966f..afc56d9f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ffdb966fec5a657893289e655c641ceb3af1d59f +Subproject commit afc56d9f07a2a54ab791a4c85cf627b6f884aec2 diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 5ce28510..97e69089 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -95,7 +95,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi private DalamudServices _dalamud; private TempCollectionManager _tempCollections; private TempModManager _tempMods; - private ActorService _actors; + private ActorManager _actors; private CollectionResolver _collectionResolver; private CutsceneService _cutsceneService; private ModImportManager _modImportManager; @@ -108,7 +108,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public unsafe PenumbraApi(CommunicatorService communicator, ModManager modManager, ResourceLoader resourceLoader, Configuration config, CollectionManager collectionManager, DalamudServices dalamud, TempCollectionManager tempCollections, - TempModManager tempMods, ActorService actors, CollectionResolver collectionResolver, CutsceneService cutsceneService, + TempModManager tempMods, ActorManager actors, CollectionResolver collectionResolver, CutsceneService cutsceneService, ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, ModFileSystem modFileSystem, ConfigWindow configWindow, TextureManager textureManager, ResourceTreeFactory resourceTreeFactory) { @@ -889,13 +889,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); - if (!_actors.Valid) - return PenumbraApiEc.SystemDisposed; - if (actorIndex < 0 || actorIndex >= _dalamud.Objects.Length) return PenumbraApiEc.InvalidArgument; - var identifier = _actors.AwaitedService.FromObject(_dalamud.Objects[actorIndex], false, false, true); + var identifier = _actors.FromObject(_dalamud.Objects[actorIndex], false, false, true); if (!identifier.IsValid) return PenumbraApiEc.InvalidArgument; @@ -1143,11 +1140,11 @@ public class PenumbraApi : IDisposable, IPenumbraApi [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe ActorIdentifier AssociatedIdentifier(int gameObjectIdx) { - if (gameObjectIdx < 0 || gameObjectIdx >= _dalamud.Objects.Length || !_actors.Valid) + if (gameObjectIdx < 0 || gameObjectIdx >= _dalamud.Objects.Length) return ActorIdentifier.Invalid; var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_dalamud.Objects.GetObjectAddress(gameObjectIdx); - return _actors.AwaitedService.FromObject(ptr, out _, false, true, true); + return _actors.FromObject(ptr, out _, false, true, true); } // Resolve a path given by string for a specific collection. @@ -1241,12 +1238,9 @@ public class PenumbraApi : IDisposable, IPenumbraApi // TODO: replace all usages with ActorIdentifier stuff when incrementing API private ActorIdentifier NameToIdentifier(string name, ushort worldId) { - if (!_actors.Valid) - return ActorIdentifier.Invalid; - // Verified to be valid name beforehand. var b = ByteString.FromStringUnsafe(name, false); - return _actors.AwaitedService.CreatePlayer(b, worldId); + return _actors.CreatePlayer(b, worldId); } private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, int _1, int _2, bool inherited) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 3761424a..a6e5fef5 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -22,10 +22,10 @@ public class CollectionCache : IDisposable private readonly CollectionCacheManager _manager; private readonly ModCollection _collection; public readonly CollectionModData ModData = new(); - public readonly SortedList, object?)> _changedItems = new(); + private readonly SortedList, object?)> _changedItems = []; public readonly ConcurrentDictionary ResolvedFiles = new(); public readonly MetaCache Meta; - public readonly Dictionary> _conflicts = new(); + public readonly Dictionary> ConflictDict = []; public int Calculating = -1; @@ -33,10 +33,10 @@ public class CollectionCache : IDisposable => _collection.AnonymizedName; public IEnumerable> AllConflicts - => _conflicts.Values; + => ConflictDict.Values; public SingleArray Conflicts(IMod mod) - => _conflicts.TryGetValue(mod, out var c) ? c : new SingleArray(); + => ConflictDict.TryGetValue(mod, out SingleArray c) ? c : new SingleArray(); private int _changedItemsSaveCounter = -1; @@ -195,7 +195,7 @@ public class CollectionCache : IDisposable $"Invalid mod state, removing {mod.Name} and associated manipulation {manipulation} returned current mod {mp.Name}."); } - _conflicts.Remove(mod); + ConflictDict.Remove(mod); foreach (var conflict in conflicts) { if (conflict.HasPriority) @@ -206,9 +206,9 @@ public class CollectionCache : IDisposable { var newConflicts = Conflicts(conflict.Mod2).Remove(c => c.Mod2 == mod); if (newConflicts.Count > 0) - _conflicts[conflict.Mod2] = newConflicts; + ConflictDict[conflict.Mod2] = newConflicts; else - _conflicts.Remove(conflict.Mod2); + ConflictDict.Remove(conflict.Mod2); } } @@ -336,9 +336,9 @@ public class CollectionCache : IDisposable return false; }); if (changedConflicts.Count == 0) - _conflicts.Remove(mod); + ConflictDict.Remove(mod); else - _conflicts[mod] = changedConflicts; + ConflictDict[mod] = changedConflicts; } // Add a new conflict between the added mod and the existing mod. @@ -373,9 +373,9 @@ public class CollectionCache : IDisposable { // Add the same conflict list to both conflict directions. var conflictList = new List { data }; - _conflicts[addedMod] = addedConflicts.Append(new ModConflicts(existingMod, conflictList, existingPriority < addedPriority, + ConflictDict[addedMod] = addedConflicts.Append(new ModConflicts(existingMod, conflictList, existingPriority < addedPriority, existingPriority != addedPriority)); - _conflicts[existingMod] = existingConflicts.Append(new ModConflicts(addedMod, conflictList, + ConflictDict[existingMod] = existingConflicts.Append(new ModConflicts(addedMod, conflictList, existingPriority >= addedPriority, existingPriority != addedPriority)); } @@ -426,7 +426,7 @@ public class CollectionCache : IDisposable _changedItems.Clear(); // Skip IMCs because they would result in far too many false-positive items, // since they are per set instead of per item-slot/item/variant. - var identifier = _manager.MetaFileManager.Identifier.AwaitedService; + var identifier = _manager.MetaFileManager.Identifier; var items = new SortedList(512); void AddItems(IMod mod) diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index a24eb2fa..7d4a5722 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -159,7 +159,7 @@ public class CollectionCacheManager : IDisposable null); cache.ResolvedFiles.Clear(); cache.Meta.Reset(); - cache._conflicts.Clear(); + cache.ConflictDict.Clear(); // Add all forced redirects. foreach (var tempMod in _tempMods.ModsForAllCollections @@ -372,7 +372,7 @@ public class CollectionCacheManager : IDisposable { collection._cache!.ResolvedFiles.Clear(); collection._cache!.Meta.Reset(); - collection._cache!._conflicts.Clear(); + collection._cache!.ConflictDict.Clear(); } } diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 0814da90..38679612 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -28,9 +28,9 @@ public class ActiveCollections : ISavable, IDisposable private readonly CommunicatorService _communicator; private readonly SaveService _saveService; private readonly ActiveCollectionData _data; - private readonly ActorService _actors; + private readonly ActorManager _actors; - public ActiveCollections(Configuration config, CollectionStorage storage, ActorService actors, CommunicatorService communicator, + public ActiveCollections(Configuration config, CollectionStorage storage, ActorManager actors, CommunicatorService communicator, SaveService saveService, ActiveCollectionData data) { _storage = storage; @@ -475,7 +475,7 @@ public class ActiveCollections : ISavable, IDisposable { case IdentifierType.Player when id.HomeWorld != ushort.MaxValue: { - var global = ByType(CollectionType.Individual, _actors.AwaitedService.CreatePlayer(id.PlayerName, ushort.MaxValue)); + var global = ByType(CollectionType.Individual, _actors.CreatePlayer(id.PlayerName, ushort.MaxValue)); return global?.Index == checkAssignment.Index ? "Assignment is redundant due to an identical Any-World assignment existing.\nYou can remove it." : string.Empty; @@ -484,12 +484,12 @@ public class ActiveCollections : ISavable, IDisposable if (id.HomeWorld != ushort.MaxValue) { var global = ByType(CollectionType.Individual, - _actors.AwaitedService.CreateOwned(id.PlayerName, ushort.MaxValue, id.Kind, id.DataId)); + _actors.CreateOwned(id.PlayerName, ushort.MaxValue, id.Kind, id.DataId)); if (global?.Index == checkAssignment.Index) return "Assignment is redundant due to an identical Any-World assignment existing.\nYou can remove it."; } - var unowned = ByType(CollectionType.Individual, _actors.AwaitedService.CreateNpc(id.Kind, id.DataId)); + var unowned = ByType(CollectionType.Individual, _actors.CreateNpc(id.Kind, id.DataId)); return unowned?.Index == checkAssignment.Index ? "Assignment is redundant due to an identical unowned NPC assignment existing.\nYou can remove it." : string.Empty; diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index 78eff98c..785f0013 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -1,6 +1,7 @@ using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.Types; using Penumbra.GameData.Actors; +using Penumbra.GameData.Enums; using Penumbra.String; namespace Penumbra.Collections.Manager; @@ -36,7 +37,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa return true; if (identifier.Retainer is not ActorIdentifier.RetainerType.Mannequin && _config.UseOwnerNameForCharacterCollection) - return CheckWorlds(_actorService.AwaitedService.GetCurrentPlayer(), out collection); + return CheckWorlds(_actors.GetCurrentPlayer(), out collection); break; } @@ -46,7 +47,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa return true; // Handle generic NPC - var npcIdentifier = _actorService.AwaitedService.CreateIndividualUnchecked(IdentifierType.Npc, ByteString.Empty, + var npcIdentifier = _actors.CreateIndividualUnchecked(IdentifierType.Npc, ByteString.Empty, ushort.MaxValue, identifier.Kind, identifier.DataId); if (npcIdentifier.IsValid && _individuals.TryGetValue(npcIdentifier, out collection)) @@ -56,7 +57,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa if (!_config.UseOwnerNameForCharacterCollection) return false; - identifier = _actorService.AwaitedService.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, + identifier = _actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); return CheckWorlds(identifier, out collection); @@ -89,37 +90,37 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa if (identifier.Type != IdentifierType.Special) return (identifier, SpecialResult.Invalid); - if (_actorService.AwaitedService.ResolvePartyBannerPlayer(identifier.Special, out var id)) + if (_actors.ResolvePartyBannerPlayer(identifier.Special, out var id)) return _config.UseCharacterCollectionsInCards ? (id, SpecialResult.PartyBanner) : (identifier, SpecialResult.Invalid); - if (_actorService.AwaitedService.ResolvePvPBannerPlayer(identifier.Special, out id)) + if (_actors.ResolvePvPBannerPlayer(identifier.Special, out id)) return _config.UseCharacterCollectionsInCards ? (id, SpecialResult.PvPBanner) : (identifier, SpecialResult.Invalid); - if (_actorService.AwaitedService.ResolveMahjongPlayer(identifier.Special, out id)) + if (_actors.ResolveMahjongPlayer(identifier.Special, out id)) return _config.UseCharacterCollectionsInCards ? (id, SpecialResult.Mahjong) : (identifier, SpecialResult.Invalid); switch (identifier.Special) { case ScreenActor.CharacterScreen when _config.UseCharacterCollectionInMainWindow: - return (_actorService.AwaitedService.GetCurrentPlayer(), SpecialResult.CharacterScreen); + return (_actors.GetCurrentPlayer(), SpecialResult.CharacterScreen); case ScreenActor.FittingRoom when _config.UseCharacterCollectionInTryOn: - return (_actorService.AwaitedService.GetCurrentPlayer(), SpecialResult.FittingRoom); + return (_actors.GetCurrentPlayer(), SpecialResult.FittingRoom); case ScreenActor.DyePreview when _config.UseCharacterCollectionInTryOn: - return (_actorService.AwaitedService.GetCurrentPlayer(), SpecialResult.DyePreview); + return (_actors.GetCurrentPlayer(), SpecialResult.DyePreview); case ScreenActor.Portrait when _config.UseCharacterCollectionsInCards: - return (_actorService.AwaitedService.GetCurrentPlayer(), SpecialResult.Portrait); + return (_actors.GetCurrentPlayer(), SpecialResult.Portrait); case ScreenActor.ExamineScreen: { - identifier = _actorService.AwaitedService.GetInspectPlayer(); + identifier = _actors.GetInspectPlayer(); if (identifier.IsValid) return (_config.UseCharacterCollectionInInspect ? identifier : ActorIdentifier.Invalid, SpecialResult.Inspect); - identifier = _actorService.AwaitedService.GetCardPlayer(); + identifier = _actors.GetCardPlayer(); if (identifier.IsValid) return (_config.UseCharacterCollectionInInspect ? identifier : ActorIdentifier.Invalid, SpecialResult.Card); return _config.UseCharacterCollectionInTryOn - ? (_actorService.AwaitedService.GetGlamourPlayer(), SpecialResult.Glamour) + ? (_actors.GetGlamourPlayer(), SpecialResult.Glamour) : (identifier, SpecialResult.Invalid); } default: return (identifier, SpecialResult.Invalid); @@ -127,10 +128,10 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa } public bool TryGetCollection(GameObject? gameObject, out ModCollection? collection) - => TryGetCollection(_actorService.AwaitedService.FromObject(gameObject, true, false, false), out collection); + => TryGetCollection(_actors.FromObject(gameObject, true, false, false), out collection); public unsafe bool TryGetCollection(FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject* gameObject, out ModCollection? collection) - => TryGetCollection(_actorService.AwaitedService.FromObject(gameObject, out _, true, false, false), out collection); + => TryGetCollection(_actors.FromObject(gameObject, out _, true, false, false), out collection); private bool CheckWorlds(ActorIdentifier identifier, out ModCollection? collection) { @@ -143,7 +144,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa if (_individuals.TryGetValue(identifier, out collection)) return true; - identifier = _actorService.AwaitedService.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, ushort.MaxValue, + identifier = _actors.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, ushort.MaxValue, identifier.Kind, identifier.DataId); if (identifier.IsValid && _individuals.TryGetValue(identifier, out collection)) diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index 45a1d98c..dc20da1e 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -3,6 +3,8 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json.Linq; using OtterGui.Classes; using Penumbra.GameData.Actors; +using Penumbra.GameData.DataContainers.Bases; +using Penumbra.GameData.Structs; using Penumbra.Services; using Penumbra.String; @@ -26,23 +28,20 @@ public partial class IndividualCollections public bool ReadJObject(SaveService saver, ActiveCollections parent, JArray? obj, CollectionStorage storage) { - if (_actorService.Valid) + if (_actors.Awaiter.IsCompletedSuccessfully) { var ret = ReadJObjectInternal(obj, storage); return ret; } - void Func() + Penumbra.Log.Debug("[Collections] Delayed reading individual assignments until actor service is ready..."); + _actors.Awaiter.ContinueWith(_ => { if (ReadJObjectInternal(obj, storage)) saver.ImmediateSave(parent); IsLoaded = true; Loaded.Invoke(); - _actorService.FinishedCreation -= Func; - } - - Penumbra.Log.Debug("[Collections] Delayed reading individual assignments until actor service is ready..."); - _actorService.FinishedCreation += Func; + }); return false; } @@ -60,7 +59,7 @@ public partial class IndividualCollections { try { - var identifier = _actorService.AwaitedService.FromJson(data as JObject); + var identifier = _actors.FromJson(data as JObject); var group = GetGroup(identifier); if (group.Length == 0 || group.Any(i => !i.IsValid)) { @@ -101,10 +100,10 @@ public partial class IndividualCollections internal void Migrate0To1(Dictionary old) { - static bool FindDataId(string name, IReadOnlyDictionary data, out uint dataId) + static bool FindDataId(string name, NameDictionary data, out NpcId dataId) { var kvp = data.FirstOrDefault(kvp => kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase), - new KeyValuePair(uint.MaxValue, string.Empty)); + new KeyValuePair(uint.MaxValue, string.Empty)); dataId = kvp.Key; return kvp.Value.Length > 0; } @@ -114,22 +113,22 @@ public partial class IndividualCollections var kind = ObjectKind.None; var lowerName = name.ToLowerInvariant(); // Prefer matching NPC names, fewer false positives than preferring players. - if (FindDataId(lowerName, _actorService.AwaitedService.Data.Companions, out var dataId)) + if (FindDataId(lowerName, _actors.Data.Companions, out var dataId)) kind = ObjectKind.Companion; - else if (FindDataId(lowerName, _actorService.AwaitedService.Data.Mounts, out dataId)) + else if (FindDataId(lowerName, _actors.Data.Mounts, out dataId)) kind = ObjectKind.MountType; - else if (FindDataId(lowerName, _actorService.AwaitedService.Data.BNpcs, out dataId)) + else if (FindDataId(lowerName, _actors.Data.BNpcs, out dataId)) kind = ObjectKind.BattleNpc; - else if (FindDataId(lowerName, _actorService.AwaitedService.Data.ENpcs, out dataId)) + else if (FindDataId(lowerName, _actors.Data.ENpcs, out dataId)) kind = ObjectKind.EventNpc; - var identifier = _actorService.AwaitedService.CreateNpc(kind, dataId); + var identifier = _actors.CreateNpc(kind, dataId); if (identifier.IsValid) { // If the name corresponds to a valid npc, add it as a group. If this fails, notify users. var group = GetGroup(identifier); var ids = string.Join(", ", group.Select(i => i.DataId.ToString())); - if (Add($"{_actorService.AwaitedService.Data.ToName(kind, dataId)} ({kind.ToName()})", group, collection)) + if (Add($"{_actors.Data.ToName(kind, dataId)} ({kind.ToName()})", group, collection)) Penumbra.Log.Information($"Migrated {name} ({kind.ToName()}) to NPC Identifiers [{ids}]."); else Penumbra.Messager.NotificationMessage( @@ -137,15 +136,12 @@ public partial class IndividualCollections NotificationType.Error); } // If it is not a valid NPC name, check if it can be a player name. - else if (ActorManager.VerifyPlayerName(name)) + else if (ActorIdentifierFactory.VerifyPlayerName(name)) { - identifier = _actorService.AwaitedService.CreatePlayer(ByteString.FromStringUnsafe(name, false), ushort.MaxValue); + identifier = _actors.CreatePlayer(ByteString.FromStringUnsafe(name, false), ushort.MaxValue); var shortName = string.Join(" ", name.Split().Select(n => $"{n[0]}.")); // Try to migrate the player name without logging full names. - if (Add($"{name} ({_actorService.AwaitedService.Data.ToWorldName(identifier.HomeWorld)})", new[] - { - identifier, - }, collection)) + if (Add($"{name} ({_actors.Data.ToWorldName(identifier.HomeWorld)})", [identifier], collection)) Penumbra.Log.Information($"Migrated {shortName} ({collection.AnonymizedName}) to Player Identifier."); else Penumbra.Messager.NotificationMessage( diff --git a/Penumbra/Collections/Manager/IndividualCollections.cs b/Penumbra/Collections/Manager/IndividualCollections.cs index 31695a94..67ab0b21 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.cs @@ -1,7 +1,9 @@ using Dalamud.Game.ClientState.Objects.Enums; using OtterGui.Filesystem; using Penumbra.GameData.Actors; -using Penumbra.Services; +using Penumbra.GameData.DataContainers.Bases; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; using Penumbra.String; namespace Penumbra.Collections.Manager; @@ -11,9 +13,9 @@ public sealed partial class IndividualCollections public record struct IndividualAssignment(string DisplayName, IReadOnlyList Identifiers, ModCollection Collection); private readonly Configuration _config; - private readonly ActorService _actorService; - private readonly Dictionary _individuals = new(); - private readonly List _assignments = new(); + private readonly ActorManager _actors; + private readonly Dictionary _individuals = []; + private readonly List _assignments = []; public event Action Loaded; public bool IsLoaded { get; private set; } @@ -21,12 +23,12 @@ public sealed partial class IndividualCollections public IReadOnlyList Assignments => _assignments; - public IndividualCollections(ActorService actorService, Configuration config, bool temporary) + public IndividualCollections(ActorManager actors, Configuration config, bool temporary) { - _config = config; - _actorService = actorService; - IsLoaded = temporary; - Loaded += () => Penumbra.Log.Information($"{_assignments.Count} Individual Assignments loaded after delay."); + _config = config; + _actors = actors; + IsLoaded = temporary; + Loaded += () => Penumbra.Log.Information($"{_assignments.Count} Individual Assignments loaded after delay."); } public enum AddResult @@ -69,44 +71,34 @@ public sealed partial class IndividualCollections return set ? AddResult.AlreadySet : AddResult.Valid; } - public AddResult CanAdd(IdentifierType type, string name, ushort homeWorld, ObjectKind kind, IEnumerable dataIds, + public AddResult CanAdd(IdentifierType type, string name, WorldId homeWorld, ObjectKind kind, IEnumerable dataIds, out ActorIdentifier[] identifiers) { - identifiers = Array.Empty(); + identifiers = []; - var manager = _actorService.AwaitedService; switch (type) { case IdentifierType.Player: if (!ByteString.FromString(name, out var playerName)) return AddResult.Invalid; - identifiers = new[] - { - manager.CreatePlayer(playerName, homeWorld), - }; + identifiers = [_actors.CreatePlayer(playerName, homeWorld)]; break; case IdentifierType.Retainer: if (!ByteString.FromString(name, out var retainerName)) return AddResult.Invalid; - identifiers = new[] - { - manager.CreateRetainer(retainerName, ActorIdentifier.RetainerType.Both), - }; + identifiers = [_actors.CreateRetainer(retainerName, ActorIdentifier.RetainerType.Both)]; break; case IdentifierType.Owned: if (!ByteString.FromString(name, out var ownerName)) return AddResult.Invalid; - identifiers = dataIds.Select(id => manager.CreateOwned(ownerName, homeWorld, kind, id)).ToArray(); + identifiers = dataIds.Select(id => _actors.CreateOwned(ownerName, homeWorld, kind, id)).ToArray(); break; case IdentifierType.Npc: identifiers = dataIds - .Select(id => manager.CreateIndividual(IdentifierType.Npc, ByteString.Empty, ushort.MaxValue, kind, id)).ToArray(); - break; - default: - identifiers = Array.Empty(); + .Select(id => _actors.CreateIndividual(IdentifierType.Npc, ByteString.Empty, ushort.MaxValue, kind, id)).ToArray(); break; } @@ -116,12 +108,22 @@ public sealed partial class IndividualCollections public ActorIdentifier[] GetGroup(ActorIdentifier identifier) { if (!identifier.IsValid) - return Array.Empty(); + return []; + + return identifier.Type switch + { + IdentifierType.Player => [identifier.CreatePermanent()], + IdentifierType.Special => [identifier], + IdentifierType.Retainer => [identifier.CreatePermanent()], + IdentifierType.Owned => CreateNpcs(_actors, identifier.CreatePermanent()), + IdentifierType.Npc => CreateNpcs(_actors, identifier), + _ => [], + }; static ActorIdentifier[] CreateNpcs(ActorManager manager, ActorIdentifier identifier) { var name = manager.Data.ToName(identifier.Kind, identifier.DataId); - var table = identifier.Kind switch + NameDictionary table = identifier.Kind switch { ObjectKind.BattleNpc => manager.Data.BNpcs, ObjectKind.EventNpc => manager.Data.ENpcs, @@ -134,25 +136,6 @@ public sealed partial class IndividualCollections .Select(kvp => manager.CreateIndividualUnchecked(identifier.Type, identifier.PlayerName, identifier.HomeWorld.Id, identifier.Kind, kvp.Key)).ToArray(); } - - return identifier.Type switch - { - IdentifierType.Player => new[] - { - identifier.CreatePermanent(), - }, - IdentifierType.Special => new[] - { - identifier, - }, - IdentifierType.Retainer => new[] - { - identifier.CreatePermanent(), - }, - IdentifierType.Owned => CreateNpcs(_actorService.AwaitedService, identifier.CreatePermanent()), - IdentifierType.Npc => CreateNpcs(_actorService.AwaitedService, identifier), - _ => Array.Empty(), - }; } internal bool Add(ActorIdentifier[] identifiers, ModCollection collection) @@ -241,12 +224,12 @@ public sealed partial class IndividualCollections { return identifier.Type switch { - IdentifierType.Player => $"{identifier.PlayerName} ({_actorService.AwaitedService.Data.ToWorldName(identifier.HomeWorld)})", + IdentifierType.Player => $"{identifier.PlayerName} ({_actors.Data.ToWorldName(identifier.HomeWorld)})", IdentifierType.Retainer => $"{identifier.PlayerName} (Retainer)", IdentifierType.Owned => - $"{identifier.PlayerName} ({_actorService.AwaitedService.Data.ToWorldName(identifier.HomeWorld)})'s {_actorService.AwaitedService.Data.ToName(identifier.Kind, identifier.DataId)}", + $"{identifier.PlayerName} ({_actors.Data.ToWorldName(identifier.HomeWorld)})'s {_actors.Data.ToName(identifier.Kind, identifier.DataId)}", IdentifierType.Npc => - $"{_actorService.AwaitedService.Data.ToName(identifier.Kind, identifier.DataId)} ({identifier.Kind.ToName()})", + $"{_actors.Data.ToName(identifier.Kind, identifier.DataId)} ({identifier.Kind.ToName()})", _ => string.Empty, }; } diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index d0edf19b..5d9de13d 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -14,10 +14,10 @@ public class TempCollectionManager : IDisposable private readonly CommunicatorService _communicator; private readonly CollectionStorage _storage; - private readonly ActorService _actors; + private readonly ActorManager _actors; private readonly Dictionary _customCollections = new(); - public TempCollectionManager(Configuration config, CommunicatorService communicator, ActorService actors, CollectionStorage storage) + public TempCollectionManager(Configuration config, CommunicatorService communicator, ActorManager actors, CollectionStorage storage) { _communicator = communicator; _actors = actors; @@ -111,7 +111,7 @@ public class TempCollectionManager : IDisposable if (!ByteString.FromString(characterName, out var byteString, false)) return false; - var identifier = _actors.AwaitedService.CreatePlayer(byteString, worldId); + var identifier = _actors.CreatePlayer(byteString, worldId); if (!identifier.IsValid) return false; @@ -123,7 +123,7 @@ public class TempCollectionManager : IDisposable if (!ByteString.FromString(characterName, out var byteString, false)) return false; - var identifier = _actors.AwaitedService.CreatePlayer(byteString, worldId); + var identifier = _actors.CreatePlayer(byteString, worldId); return Collections.TryGetValue(identifier, out var collection) && RemoveTemporaryCollection(collection.Name); } } diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index c151e7e4..537b08da 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -32,7 +32,7 @@ public class CommandHandler : IDisposable public CommandHandler(IFramework framework, ICommandManager commandManager, IChatGui chat, RedrawService redrawService, Configuration config, - ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorService actors, Penumbra penumbra, + ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorManager actors, Penumbra penumbra, CollectionEditor collectionEditor) { _commandManager = commandManager; @@ -41,7 +41,7 @@ public class CommandHandler : IDisposable _configWindow = configWindow; _modManager = modManager; _collectionManager = collectionManager; - _actors = actors.AwaitedService; + _actors = actors; _chat = chat; _penumbra = penumbra; _collectionEditor = collectionEditor; diff --git a/Penumbra/Import/Structs/MetaFileInfo.cs b/Penumbra/Import/Structs/MetaFileInfo.cs index f7c9b419..693c77b1 100644 --- a/Penumbra/Import/Structs/MetaFileInfo.cs +++ b/Penumbra/Import/Structs/MetaFileInfo.cs @@ -1,5 +1,6 @@ using Penumbra.GameData.Enums; using Penumbra.GameData; +using Penumbra.GameData.Data; namespace Penumbra.Import.Structs; @@ -47,7 +48,7 @@ public partial struct MetaFileInfo _ => false, }; - public MetaFileInfo(IGamePathParser parser, string fileName) + public MetaFileInfo(GamePathParser parser, string fileName) { // Set the primary type from the gamePath start. PrimaryType = parser.PathToObjectType(fileName); diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index 1108c965..83b430fb 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -1,4 +1,5 @@ using Penumbra.GameData; +using Penumbra.GameData.Data; using Penumbra.Import.Structs; using Penumbra.Meta; using Penumbra.Meta.Manipulations; @@ -28,7 +29,7 @@ public partial class TexToolsMeta private readonly MetaFileManager _metaFileManager; - public TexToolsMeta(MetaFileManager metaFileManager, IGamePathParser parser, byte[] data, bool keepDefault) + public TexToolsMeta(MetaFileManager metaFileManager, GamePathParser parser, byte[] data, bool keepDefault) { _metaFileManager = metaFileManager; _keepDefault = keepDefault; diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index ecd4eb2e..fe51a5cd 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -3,7 +3,7 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; -using Penumbra.GameData.Data; +using Penumbra.GameData.DataContainers; using Penumbra.GameData.Enums; using Penumbra.Services; using Penumbra.Util; @@ -21,7 +21,7 @@ public unsafe class CollectionResolver private readonly IClientState _clientState; private readonly IGameGui _gameGui; - private readonly ActorService _actors; + private readonly ActorManager _actors; private readonly CutsceneService _cutscenes; private readonly Configuration _config; @@ -30,7 +30,7 @@ public unsafe class CollectionResolver private readonly DrawObjectState _drawObjectState; public CollectionResolver(PerformanceTracker performance, IdentifiedCollectionCache cache, IClientState clientState, IGameGui gameGui, - ActorService actors, CutsceneService cutscenes, Configuration config, CollectionManager collectionManager, + ActorManager actors, CutsceneService cutscenes, Configuration config, CollectionManager collectionManager, TempCollectionManager tempCollections, DrawObjectState drawObjectState, HumanModelList humanModels) { _performance = performance; @@ -58,7 +58,7 @@ public unsafe class CollectionResolver return _collectionManager.Active.ByType(CollectionType.Yourself) ?? _collectionManager.Active.Default; - var player = _actors.AwaitedService.GetCurrentPlayer(); + var player = _actors.GetCurrentPlayer(); var _ = false; return CollectionByIdentifier(player) ?? CheckYourself(player, gameObject) @@ -147,7 +147,7 @@ public unsafe class CollectionResolver return false; } - var player = _actors.AwaitedService.GetCurrentPlayer(); + var player = _actors.GetCurrentPlayer(); var notYetReady = false; var collection = (player.IsValid ? CollectionByIdentifier(player) : null) ?? _collectionManager.Active.ByType(CollectionType.Yourself) @@ -163,7 +163,7 @@ public unsafe class CollectionResolver /// private ResolveData DefaultState(GameObject* gameObject) { - var identifier = _actors.AwaitedService.FromObject(gameObject, out var owner, true, false, false); + var identifier = _actors.FromObject(gameObject, out var owner, true, false, false); if (identifier.Type is IdentifierType.Special) { (identifier, var type) = _collectionManager.Active.Individuals.ConvertSpecialIdentifier(identifier); @@ -193,7 +193,7 @@ public unsafe class CollectionResolver { if (actor->ObjectIndex == 0 || _cutscenes.GetParentIndex(actor->ObjectIndex) == 0 - || identifier.Equals(_actors.AwaitedService.GetCurrentPlayer())) + || identifier.Equals(_actors.GetCurrentPlayer())) return _collectionManager.Active.ByType(CollectionType.Yourself); return null; @@ -242,7 +242,7 @@ public unsafe class CollectionResolver if (identifier.Type != IdentifierType.Owned || !_config.UseOwnerNameForCharacterCollection || owner == null) return null; - var id = _actors.AwaitedService.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, + var id = _actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); return CheckYourself(id, owner) diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index add121b6..18c016b9 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -1,6 +1,6 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; -using Penumbra.GameData.Actors; +using Penumbra.GameData.Enums; using Penumbra.Interop.Services; namespace Penumbra.Interop.PathResolving; @@ -45,6 +45,9 @@ public class CutsceneService : IDisposable /// Return the currently set index of a parent or -1 if none is set or the index is invalid. public int GetParentIndex(int idx) + => GetParentIndex((ushort)idx); + + public short GetParentIndex(ushort idx) { if (idx is >= CutsceneStartIdx and < CutsceneEndIdx) return _copiedCharacters[idx - CutsceneStartIdx]; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 5a5ecdd9..d03ee508 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -7,6 +7,7 @@ using OtterGui; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.String; @@ -19,7 +20,7 @@ using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.M namespace Penumbra.Interop.ResourceTree; -internal record GlobalResolveContext(IObjectIdentifier Identifier, ModCollection Collection, TreeBuildCache TreeBuildCache, bool WithUiData) +internal record GlobalResolveContext(ObjectIdentification Identifier, ModCollection Collection, TreeBuildCache TreeBuildCache, bool WithUiData) { public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); @@ -28,8 +29,13 @@ internal record GlobalResolveContext(IObjectIdentifier Identifier, ModCollection => new(this, characterBase, slotIndex, slot, equipment, weaponType); } -internal partial record ResolveContext(GlobalResolveContext Global, Pointer CharacterBase, uint SlotIndex, - EquipSlot Slot, CharacterArmor Equipment, WeaponType WeaponType) +internal partial record ResolveContext( + GlobalResolveContext Global, + Pointer CharacterBase, + uint SlotIndex, + EquipSlot Slot, + CharacterArmor Equipment, + WeaponType WeaponType) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); @@ -152,6 +158,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, PointerModelResourceHandle == null) return null; + var mdlResource = mdl->ModelResourceHandle; var path = ResolveModelPath(); @@ -224,6 +231,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, Pointer "L: ", _ => string.Empty, } - + item.Name.ToString(); + + item.Name; return new ResourceNode.UiData(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); } - var dataFromPath = GuessUIDataFromPath(gamePath); + var dataFromPath = GuessUiDataFromPath(gamePath); if (dataFromPath.Name != null) return dataFromPath; @@ -337,7 +345,7 @@ internal partial record ResolveContext(GlobalResolveContext Global, Pointer tree.FlatNodes.Add(node)); @@ -161,9 +163,9 @@ public class ResourceTreeFactory var gamePath = node.PossibleGamePaths[0]; node.SetUiData(node.Type switch { - ResourceType.Imc => node.ResolveContext!.GuessModelUIData(gamePath).PrependName("IMC: "), - ResourceType.Mdl => node.ResolveContext!.GuessModelUIData(gamePath), - _ => node.ResolveContext!.GuessUIDataFromPath(gamePath), + ResourceType.Imc => node.ResolveContext!.GuessModelUiData(gamePath).PrependName("IMC: "), + ResourceType.Mdl => node.ResolveContext!.GuessModelUiData(gamePath), + _ => node.ResolveContext!.GuessUiDataFromPath(gamePath), }); } @@ -215,7 +217,7 @@ public class ResourceTreeFactory private unsafe (string Name, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache) { - var identifier = _actors.AwaitedService.FromObject((GameObject*)character.Address, out var owner, true, false, false); + var identifier = _actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); switch (identifier.Type) { case IdentifierType.Player: return (identifier.PlayerName.ToString(), true); diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 9614e9aa..7582c753 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -1,36 +1,26 @@ using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using Penumbra.GameData.Actors; +using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; -using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; -internal readonly struct TreeBuildCache +internal readonly struct TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorManager actors) { - private readonly IDataManager _dataManager; - private readonly ActorService _actors; - private readonly Dictionary _shaderPackages = new(); - private readonly IObjectTable _objects; - - public TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorService actors) - { - _dataManager = dataManager; - _objects = objects; - _actors = actors; - } + private readonly Dictionary _shaderPackages = []; public unsafe bool IsLocalPlayerRelated(Character character) { - var player = _objects[0]; + var player = objects[0]; if (player == null) return false; var gameObject = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)character.Address; - var parent = _actors.AwaitedService.ToCutsceneParent(gameObject->ObjectIndex); + var parent = actors.ToCutsceneParent(gameObject->ObjectIndex); var actualIndex = parent >= 0 ? (ushort)parent : gameObject->ObjectIndex; return actualIndex switch { @@ -41,38 +31,38 @@ internal readonly struct TreeBuildCache } public IEnumerable GetCharacters() - => _objects.OfType(); + => objects.OfType(); public IEnumerable GetLocalPlayerRelatedCharacters() { - var player = _objects[0]; + var player = objects[0]; if (player == null) yield break; yield return (Character)player; - var minion = _objects[1]; + var minion = objects[1]; if (minion != null) yield return (Character)minion; var playerId = player.ObjectId; for (var i = 2; i < ObjectIndex.CutsceneStart.Index; i += 2) { - if (_objects[i] is Character owned && owned.OwnerId == playerId) + if (objects[i] is Character owned && owned.OwnerId == playerId) yield return owned; } for (var i = ObjectIndex.CutsceneStart.Index; i < ObjectIndex.CharacterScreen.Index; ++i) { - var character = _objects[i] as Character; + var character = objects[i] as Character; if (character == null) continue; - var parent = _actors.AwaitedService.ToCutsceneParent(i); + var parent = actors.ToCutsceneParent(i); if (parent < 0) continue; - if (parent is 0 or 1 || _objects[parent]?.OwnerId == playerId) + if (parent is 0 or 1 || objects[parent]?.OwnerId == playerId) yield return character; } } @@ -85,11 +75,11 @@ internal readonly struct TreeBuildCache private unsafe bool GetOwnedId(ByteString playerName, uint playerId, int idx, [NotNullWhen(true)] out Character? character) { - character = _objects[idx] as Character; + character = objects[idx] as Character; if (character == null) return false; - var actorId = _actors.AwaitedService.FromObject(character, out var owner, true, true, true); + var actorId = actors.FromObject(character, out var owner, true, true, true); if (!actorId.IsValid) return false; if (owner != null && owner->OwnerID != playerId) @@ -102,7 +92,7 @@ internal readonly struct TreeBuildCache /// Try to read a shpk file from the given path and cache it on success. public ShpkFile? ReadShaderPackage(FullPath path) - => ReadFile(_dataManager, path, _shaderPackages, bytes => new ShpkFile(bytes)); + => ReadFile(dataManager, path, _shaderPackages, bytes => new ShpkFile(bytes)); private static T? ReadFile(IDataManager dataManager, FullPath path, Dictionary cache, Func parseFile) where T : class diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 7a73857a..e2e57b1c 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -9,7 +9,7 @@ using FFXIVClientStructs.Interop; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.GameData; -using Penumbra.GameData.Actors; +using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 9c42b9fc..5283f77e 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -5,6 +5,7 @@ using OtterGui.Compression; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData; +using Penumbra.GameData.Data; using Penumbra.Import; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; @@ -24,11 +25,11 @@ public unsafe class MetaFileManager internal readonly IDataManager GameData; internal readonly ActiveCollectionData ActiveCollections; internal readonly ValidityChecker ValidityChecker; - internal readonly IdentifierService Identifier; + internal readonly ObjectIdentification Identifier; internal readonly FileCompactor Compactor; public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, - ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, IdentifierService identifier, + ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, ObjectIdentification identifier, FileCompactor compactor, IGameInteropProvider interop) { CharacterUtility = characterUtility; diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 3d8ab1b6..d634349e 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -1,5 +1,4 @@ using Penumbra.Api.Enums; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; @@ -41,7 +40,7 @@ public static class EquipmentSwap : Array.Empty(); } - public static EquipItem[] CreateTypeSwap(MetaFileManager manager, IObjectIdentifier identifier, List swaps, + public static EquipItem[] CreateTypeSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, Func redirections, Func manips, EquipSlot slotFrom, EquipItem itemFrom, EquipSlot slotTo, EquipItem itemTo) { @@ -99,7 +98,7 @@ public static class EquipmentSwap return affectedItems; } - public static EquipItem[] CreateItemSwap(MetaFileManager manager, IObjectIdentifier identifier, List swaps, + public static EquipItem[] CreateItemSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, Func redirections, Func manips, EquipItem itemFrom, EquipItem itemTo, bool rFinger = true, bool lFinger = true) { @@ -247,7 +246,7 @@ public static class EquipmentSwap variant = i.Variant; } - private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, IObjectIdentifier identifier, EquipSlot slotFrom, + private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, ObjectIdentification identifier, EquipSlot slotFrom, SetId idFrom, SetId idTo, Variant variantFrom) { var entry = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, default); @@ -256,11 +255,8 @@ public static class EquipmentSwap Variant[] variants; if (idFrom == idTo) { - items = identifier.Identify(idFrom, variantFrom, slotFrom).ToArray(); - variants = new[] - { - variantFrom, - }; + items = identifier.Identify(idFrom, 0, variantFrom, slotFrom).ToArray(); + variants = [variantFrom]; } else { diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 1db890ed..9ca02c4e 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -1,5 +1,5 @@ -using Lumina.Excel.GeneratedSheets; using Penumbra.Collections; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; @@ -7,17 +7,16 @@ using Penumbra.String.Classes; using Penumbra.Meta; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; -using Penumbra.Services; namespace Penumbra.Mods.ItemSwap; public class ItemSwapContainer { - private readonly MetaFileManager _manager; - private readonly IdentifierService _identifier; + private readonly MetaFileManager _manager; + private readonly ObjectIdentification _identifier; - private Dictionary _modRedirections = new(); - private HashSet _modManipulations = new(); + private Dictionary _modRedirections = []; + private HashSet _modManipulations = []; public IReadOnlyDictionary ModRedirections => _modRedirections; @@ -25,7 +24,7 @@ public class ItemSwapContainer public IReadOnlySet ModManipulations => _modManipulations; - public readonly List Swaps = new(); + public readonly List Swaps = []; public bool Loaded { get; private set; } @@ -107,7 +106,7 @@ public class ItemSwapContainer } } - public ItemSwapContainer(MetaFileManager manager, IdentifierService identifier) + public ItemSwapContainer(MetaFileManager manager, ObjectIdentification identifier) { _manager = manager; _identifier = identifier; @@ -130,7 +129,7 @@ public class ItemSwapContainer { Swaps.Clear(); Loaded = false; - var ret = EquipmentSwap.CreateItemSwap(_manager, _identifier.AwaitedService, Swaps, PathResolver(collection), MetaResolver(collection), + var ret = EquipmentSwap.CreateItemSwap(_manager, _identifier, Swaps, PathResolver(collection), MetaResolver(collection), from, to, useRightRing, useLeftRing); Loaded = true; return ret; @@ -140,7 +139,7 @@ public class ItemSwapContainer { Swaps.Clear(); Loaded = false; - var ret = EquipmentSwap.CreateTypeSwap(_manager, _identifier.AwaitedService, Swaps, PathResolver(collection), MetaResolver(collection), + var ret = EquipmentSwap.CreateTypeSwap(_manager, _identifier, Swaps, PathResolver(collection), MetaResolver(collection), slotFrom, from, slotTo, to); Loaded = true; return ret; diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index afd42f95..0af78431 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -1,5 +1,4 @@ using Penumbra.Communication; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Meta.Manipulations; @@ -9,11 +8,12 @@ namespace Penumbra.Mods.Manager; public class ModCacheManager : IDisposable { - private readonly CommunicatorService _communicator; - private readonly IdentifierService _identifier; - private readonly ModStorage _modManager; + private readonly CommunicatorService _communicator; + private readonly ObjectIdentification _identifier; + private readonly ModStorage _modManager; + private bool _updatingItems = false; - public ModCacheManager(CommunicatorService communicator, IdentifierService identifier, ModStorage modStorage) + public ModCacheManager(CommunicatorService communicator, ObjectIdentification identifier, ModStorage modStorage) { _communicator = communicator; _identifier = identifier; @@ -23,8 +23,7 @@ public class ModCacheManager : IDisposable _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModCacheManager); _communicator.ModDataChanged.Subscribe(OnModDataChange, ModDataChanged.Priority.ModCacheManager); _communicator.ModDiscoveryFinished.Subscribe(OnModDiscoveryFinished, ModDiscoveryFinished.Priority.ModCacheManager); - if (!identifier.Valid) - identifier.FinishedCreation += OnIdentifierCreation; + identifier.Awaiter.ContinueWith(_ => OnIdentifierCreation()); OnModDiscoveryFinished(); } @@ -37,7 +36,7 @@ public class ModCacheManager : IDisposable } /// Compute the items changed by a given meta manipulation and put them into the changedItems dictionary. - public static void ComputeChangedItems(IObjectIdentifier identifier, IDictionary changedItems, MetaManipulation manip) + public static void ComputeChangedItems(ObjectIdentification identifier, IDictionary changedItems, MetaManipulation manip) { switch (manip.ManipulationType) { @@ -155,10 +154,7 @@ public class ModCacheManager : IDisposable => Parallel.ForEach(_modManager, Refresh); private void OnIdentifierCreation() - { - Parallel.ForEach(_modManager, UpdateChangedItems); - _identifier.FinishedCreation -= OnIdentifierCreation; - } + => Parallel.ForEach(_modManager, UpdateChangedItems); private static void UpdateFileCount(Mod mod) => mod.TotalFileCount = mod.AllSubMods.Sum(s => s.Files.Count); @@ -177,18 +173,23 @@ public class ModCacheManager : IDisposable private void UpdateChangedItems(Mod mod) { + if (_updatingItems) + return; + + _updatingItems = true; var changedItems = (SortedList)mod.ChangedItems; changedItems.Clear(); - if (!_identifier.Valid) + if (!_identifier.Awaiter.IsCompletedSuccessfully) return; foreach (var gamePath in mod.AllSubMods.SelectMany(m => m.Files.Keys.Concat(m.FileSwaps.Keys))) - _identifier.AwaitedService.Identify(changedItems, gamePath.ToString()); + _identifier.Identify(changedItems, gamePath.ToString()); foreach (var manip in mod.AllSubMods.SelectMany(m => m.Manipulations)) - ComputeChangedItems(_identifier.AwaitedService, changedItems, manip); + ComputeChangedItems(_identifier, changedItems, manip); mod.LowerChangedItemsString = string.Join("\0", mod.ChangedItems.Keys.Select(k => k.ToLowerInvariant())); + _updatingItems = false; } private static void UpdateCounts(Mod mod) diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 9a31cf46..042c98b4 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -5,7 +5,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; -using Penumbra.GameData; +using Penumbra.GameData.Data; using Penumbra.Import; using Penumbra.Import.Structs; using Penumbra.Meta; @@ -17,7 +17,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; public partial class ModCreator(SaveService _saveService, Configuration config, ModDataEditor _dataEditor, MetaFileManager _metaFileManager, - IGamePathParser _gamePathParser) + GamePathParser _gamePathParser) { public readonly Configuration Config = config; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index bcf94ed1..9be40e66 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -1,4 +1,5 @@ using Dalamud.Plugin; +using Dalamud.Plugin.Services; using ImGuiNET; using Lumina.Excel.GeneratedSheets; using Microsoft.Extensions.DependencyInjection; @@ -6,7 +7,6 @@ using OtterGui; using OtterGui.Log; using Penumbra.Api; using Penumbra.Api.Enums; -using Penumbra.Util; using Penumbra.Collections; using Penumbra.Collections.Cache; using Penumbra.Interop.ResourceLoading; @@ -19,6 +19,7 @@ using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.UI; @@ -31,7 +32,7 @@ public class Penumbra : IDalamudPlugin public string Name => "Penumbra"; - public static readonly Logger Log = new(); + public static readonly Logger Log = new(); public static MessageService Messager { get; private set; } = null!; private readonly ValidityChecker _validityChecker; @@ -53,10 +54,8 @@ public class Penumbra : IDalamudPlugin { try { - var startTimer = new StartTracker(); - using var timer = startTimer.Measure(StartTimeType.Total); - _services = ServiceManager.CreateProvider(this, pluginInterface, Log, startTimer); - Messager = _services.GetRequiredService(); + _services = ServiceManager.CreateProvider(this, pluginInterface, Log); + Messager = _services.GetRequiredService(); _validityChecker = _services.GetRequiredService(); var startup = _services.GetRequiredService().GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool s) ? s.ToString() @@ -74,14 +73,11 @@ public class Penumbra : IDalamudPlugin _tempCollections = _services.GetRequiredService(); _redrawService = _services.GetRequiredService(); _communicatorService = _services.GetRequiredService(); - _services.GetRequiredService(); // Initialize because not required anywhere else. - _services.GetRequiredService(); // Initialize because not required anywhere else. + _services.GetRequiredService(); // Initialize because not required anywhere else. + _services.GetRequiredService(); // Initialize because not required anywhere else. _services.GetRequiredService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); - using (var t = _services.GetRequiredService().Measure(StartTimeType.PathResolver)) - { - _services.GetRequiredService(); - } + _services.GetRequiredService(); _services.GetRequiredService(); @@ -108,8 +104,7 @@ public class Penumbra : IDalamudPlugin private void SetupApi() { - using var timer = _services.GetRequiredService().Measure(StartTimeType.Api); - var api = _services.GetRequiredService(); + var api = _services.GetRequiredService(); _services.GetRequiredService(); _communicatorService.ChangedItemHover.Subscribe(it => { @@ -128,8 +123,7 @@ public class Penumbra : IDalamudPlugin { AsyncTask.Run(() => { - using var tInterface = _services.GetRequiredService().Measure(StartTimeType.Interface); - var system = _services.GetRequiredService(); + var system = _services.GetRequiredService(); system.Window.Setup(this, _services.GetRequiredService()); _services.GetRequiredService(); if (!_disposed) diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index 0059cf9f..e8684f9d 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -1,15 +1,13 @@ using Newtonsoft.Json.Linq; using OtterGui.Classes; using OtterGui.Log; -using Penumbra.Util; namespace Penumbra.Services; public class BackupService { - public BackupService(Logger logger, StartTracker timer, FilenameService fileNames) + public BackupService(Logger logger, FilenameService fileNames) { - using var t = timer.Measure(StartTimeType.Backup); var files = PenumbraFiles(fileNames); Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), files); } diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 73be8834..049ab328 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -7,7 +7,10 @@ using Penumbra.Api; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.GameData; +using Penumbra.GameData.Actors; using Penumbra.GameData.Data; +using Penumbra.GameData.DataContainers; +using Penumbra.GameData.DataContainers.Bases; using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; @@ -24,17 +27,17 @@ using Penumbra.UI.Classes; using Penumbra.UI.ModsTab; using Penumbra.UI.ResourceWatcher; using Penumbra.UI.Tabs; +using Penumbra.UI.Tabs.Debug; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra.Services; public static class ServiceManager { - public static ServiceProvider CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log, StartTracker startTimer) + public static ServiceProvider CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log) { var services = new ServiceCollection() .AddSingleton(log) - .AddSingleton(startTimer) .AddSingleton(penumbra) .AddDalamud(pi) .AddMeta() @@ -47,7 +50,9 @@ public static class ServiceManager .AddResolvers() .AddInterface() .AddModEditor() - .AddApi(); + .AddApi() + .AddDataContainers() + .AddAsyncServices(); return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); } @@ -59,6 +64,22 @@ public static class ServiceManager return services; } + private static IServiceCollection AddDataContainers(this IServiceCollection services) + { + foreach (var type in typeof(IDataContainer).Assembly.GetExportedTypes() + .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IDataContainer)))) + services.AddSingleton(type); + return services; + } + + private static IServiceCollection AddAsyncServices(this IServiceCollection services) + { + foreach (var type in typeof(IDataContainer).Assembly.GetExportedTypes() + .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncService)))) + services.AddSingleton(type); + return services; + } + private static IServiceCollection AddMeta(this IServiceCollection services) => services.AddSingleton() .AddSingleton() @@ -71,17 +92,19 @@ public static class ServiceManager private static IServiceCollection AddGameData(this IServiceCollection services) - => services.AddSingleton() - .AddSingleton() + => services.AddSingleton() .AddSingleton() - .AddSingleton() - .AddSingleton() .AddSingleton(); private static IServiceCollection AddInterop(this IServiceCollection services) => services.AddSingleton() .AddSingleton() .AddSingleton() + .AddSingleton(p => + { + var cutsceneService = p.GetRequiredService(); + return new CutsceneResolver(cutsceneService.GetParentIndex); + }) .AddSingleton() .AddSingleton() .AddSingleton() @@ -173,7 +196,8 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(p => new Diagnostics(p)); private static IServiceCollection AddModEditor(this IServiceCollection services) => services.AddSingleton() diff --git a/Penumbra/Services/ServiceWrapper.cs b/Penumbra/Services/ServiceWrapper.cs index 67ddb63d..37acdfd0 100644 --- a/Penumbra/Services/ServiceWrapper.cs +++ b/Penumbra/Services/ServiceWrapper.cs @@ -1,5 +1,4 @@ using OtterGui.Tasks; -using Penumbra.Util; namespace Penumbra.Services; @@ -12,10 +11,9 @@ public abstract class SyncServiceWrapper : IDisposable public bool Valid => !_isDisposed; - protected SyncServiceWrapper(string name, StartTracker tracker, StartTimeType type, Func factory) + protected SyncServiceWrapper(string name, Func factory) { Name = name; - using var timer = tracker.Measure(type); Service = factory(); Penumbra.Log.Verbose($"[{Name}] Created."); } @@ -54,32 +52,6 @@ public abstract class AsyncServiceWrapper : IDisposable private bool _isDisposed; - protected AsyncServiceWrapper(string name, StartTracker tracker, StartTimeType type, Func factory) - { - Name = name; - _task = TrackedTask.Run(() => - { - using var timer = tracker.Measure(type); - var service = factory(); - if (_isDisposed) - { - if (service is IDisposable d) - d.Dispose(); - } - else - { - Service = service; - Penumbra.Log.Verbose($"[{Name}] Created."); - _task = null; - } - }); - _task.ContinueWith((t, x) => - { - if (!_isDisposed) - FinishedCreation?.Invoke(); - }, null); - } - protected AsyncServiceWrapper(string name, Func factory) { Name = name; diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index a0bca570..d11e4d64 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -4,7 +4,7 @@ using Dalamud.Plugin; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui.Widgets; -using Penumbra.GameData.Data; +using Penumbra.GameData.DataContainers; using Penumbra.GameData.Files; using Penumbra.UI.AdvancedWindow; using Penumbra.Util; @@ -71,17 +71,16 @@ public class StainService : IDisposable } } - public readonly StainData StainData; + public readonly DictStains StainData; public readonly FilterComboColors StainCombo; public readonly StmFile StmFile; public readonly StainTemplateCombo TemplateCombo; - public StainService(StartTracker timer, DalamudPluginInterface pluginInterface, IDataManager dataManager, IPluginLog dalamudLog) + public StainService(DalamudPluginInterface pluginInterface, IDataManager dataManager, IPluginLog dalamudLog) { - using var t = timer.Measure(StartTimeType.Stains); - StainData = new StainData(pluginInterface, dataManager, dataManager.Language, dalamudLog); + StainData = new DictStains(pluginInterface, dalamudLog, dataManager); StainCombo = new FilterComboColors(140, - () => StainData.Data.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), + () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), Penumbra.Log); StmFile = new StmFile(dataManager); TemplateCombo = new StainTemplateCombo(StainCombo, StmFile); diff --git a/Penumbra/Services/Wrappers.cs b/Penumbra/Services/Wrappers.cs deleted file mode 100644 index b1f17d4d..00000000 --- a/Penumbra/Services/Wrappers.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Dalamud.Game; -using Dalamud.Plugin; -using Dalamud.Plugin.Services; -using Penumbra.GameData; -using Penumbra.GameData.Actors; -using Penumbra.GameData.Data; -using Penumbra.Interop.PathResolving; -using Penumbra.Util; - -namespace Penumbra.Services; - -public sealed class IdentifierService : AsyncServiceWrapper -{ - public IdentifierService(StartTracker tracker, DalamudPluginInterface pi, IDataManager data, ItemService items, IPluginLog log) - : base(nameof(IdentifierService), tracker, StartTimeType.Identifier, - () => GameData.GameData.GetIdentifier(pi, data, items.AwaitedService, log)) - { } -} - -public sealed class ItemService : AsyncServiceWrapper -{ - public ItemService(StartTracker tracker, DalamudPluginInterface pi, IDataManager gameData, IPluginLog log) - : base(nameof(ItemService), tracker, StartTimeType.Items, () => new ItemData(pi, gameData, gameData.Language, log)) - { } -} - -public sealed class ActorService : AsyncServiceWrapper -{ - public ActorService(StartTracker tracker, DalamudPluginInterface pi, IObjectTable objects, IClientState clientState, - IFramework framework, IDataManager gameData, IGameGui gui, CutsceneService cutscene, IPluginLog log, IGameInteropProvider interop) - : base(nameof(ActorService), tracker, StartTimeType.Actors, - () => new ActorManager(pi, objects, clientState, framework, interop, gameData, gui, idx => (short)cutscene.GetParentIndex(idx), log)) - { } -} diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 5347208e..0ec11542 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -1,8 +1,5 @@ -using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; -using Dalamud.Utility; using ImGuiNET; -using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; @@ -11,6 +8,7 @@ using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; @@ -27,16 +25,14 @@ public class ItemSwapTab : IDisposable, ITab { private readonly Configuration _config; private readonly CommunicatorService _communicator; - private readonly ItemService _itemService; private readonly CollectionManager _collectionManager; private readonly ModManager _modManager; private readonly MetaFileManager _metaFileManager; - public ItemSwapTab(CommunicatorService communicator, ItemService itemService, CollectionManager collectionManager, - ModManager modManager, IdentifierService identifier, MetaFileManager metaFileManager, Configuration config) + public ItemSwapTab(CommunicatorService communicator, ItemData itemService, CollectionManager collectionManager, + ModManager modManager, ObjectIdentification identifier, MetaFileManager metaFileManager, Configuration config) { _communicator = communicator; - _itemService = itemService; _collectionManager = collectionManager; _modManager = modManager; _metaFileManager = metaFileManager; @@ -46,15 +42,15 @@ public class ItemSwapTab : IDisposable, ITab _selectors = new Dictionary { // @formatter:off - [SwapType.Hat] = (new ItemSelector(_itemService, FullEquipType.Head), new ItemSelector(_itemService, FullEquipType.Head), "Take this Hat", "and put it on this one" ), - [SwapType.Top] = (new ItemSelector(_itemService, FullEquipType.Body), new ItemSelector(_itemService, FullEquipType.Body), "Take this Top", "and put it on this one" ), - [SwapType.Gloves] = (new ItemSelector(_itemService, FullEquipType.Hands), new ItemSelector(_itemService, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), - [SwapType.Pants] = (new ItemSelector(_itemService, FullEquipType.Legs), new ItemSelector(_itemService, FullEquipType.Legs), "Take these Pants", "and put them on these" ), - [SwapType.Shoes] = (new ItemSelector(_itemService, FullEquipType.Feet), new ItemSelector(_itemService, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), - [SwapType.Earrings] = (new ItemSelector(_itemService, FullEquipType.Ears), new ItemSelector(_itemService, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), - [SwapType.Necklace] = (new ItemSelector(_itemService, FullEquipType.Neck), new ItemSelector(_itemService, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), - [SwapType.Bracelet] = (new ItemSelector(_itemService, FullEquipType.Wrists), new ItemSelector(_itemService, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), - [SwapType.Ring] = (new ItemSelector(_itemService, FullEquipType.Finger), new ItemSelector(_itemService, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), + [SwapType.Hat] = (new ItemSelector(itemService, FullEquipType.Head), new ItemSelector(itemService, FullEquipType.Head), "Take this Hat", "and put it on this one" ), + [SwapType.Top] = (new ItemSelector(itemService, FullEquipType.Body), new ItemSelector(itemService, FullEquipType.Body), "Take this Top", "and put it on this one" ), + [SwapType.Gloves] = (new ItemSelector(itemService, FullEquipType.Hands), new ItemSelector(itemService, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), + [SwapType.Pants] = (new ItemSelector(itemService, FullEquipType.Legs), new ItemSelector(itemService, FullEquipType.Legs), "Take these Pants", "and put them on these" ), + [SwapType.Shoes] = (new ItemSelector(itemService, FullEquipType.Feet), new ItemSelector(itemService, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), + [SwapType.Earrings] = (new ItemSelector(itemService, FullEquipType.Ears), new ItemSelector(itemService, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), + [SwapType.Necklace] = (new ItemSelector(itemService, FullEquipType.Neck), new ItemSelector(itemService, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), + [SwapType.Bracelet] = (new ItemSelector(itemService, FullEquipType.Wrists), new ItemSelector(itemService, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), + [SwapType.Ring] = (new ItemSelector(itemService, FullEquipType.Finger), new ItemSelector(itemService, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), // @formatter:on }; @@ -131,8 +127,8 @@ public class ItemSwapTab : IDisposable, ITab private class ItemSelector : FilterComboCache { - public ItemSelector(ItemService data, FullEquipType type) - : base(() => data.AwaitedService[type], Penumbra.Log) + public ItemSelector(ItemData data, FullEquipType type) + : base(() => data.ByType[type], Penumbra.Log) { } protected override string ToString(EquipItem obj) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 804feae1..82fc78c0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -8,6 +8,7 @@ using OtterGui.Classes; using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; using Penumbra.String; using static Penumbra.GameData.Files.ShpkFile; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index 7f14165c..12b8d761 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -3,6 +3,7 @@ using Lumina.Misc; using OtterGui; using Penumbra.GameData.Data; using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index bd37a484..8f90750f 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -22,7 +22,7 @@ public sealed class CollectionPanel : IDisposable private readonly CollectionStorage _collections; private readonly ActiveCollections _active; private readonly CollectionSelector _selector; - private readonly ActorService _actors; + private readonly ActorManager _actors; private readonly ITargetManager _targets; private readonly IndividualAssignmentUi _individualAssignmentUi; private readonly InheritanceUi _inheritanceUi; @@ -37,7 +37,7 @@ public sealed class CollectionPanel : IDisposable private int _draggedIndividualAssignment = -1; public CollectionPanel(DalamudPluginInterface pi, CommunicatorService communicator, CollectionManager manager, - CollectionSelector selector, ActorService actors, ITargetManager targets, ModStorage mods) + CollectionSelector selector, ActorManager actors, ITargetManager targets, ModStorage mods) { _collections = manager.Storage; _active = manager.Active; @@ -382,11 +382,11 @@ public sealed class CollectionPanel : IDisposable } private void DrawCurrentCharacter(Vector2 width) - => DrawIndividualButton("Current Character", width, string.Empty, 'c', _actors.AwaitedService.GetCurrentPlayer()); + => DrawIndividualButton("Current Character", width, string.Empty, 'c', _actors.GetCurrentPlayer()); private void DrawCurrentTarget(Vector2 width) => DrawIndividualButton("Current Target", width, string.Empty, 't', - _actors.AwaitedService.FromObject(_targets.Target, false, true, true)); + _actors.FromObject(_targets.Target, false, true, true)); private void DrawNewPlayer(Vector2 width) => DrawIndividualButton("New Player", width, _individualAssignmentUi.PlayerTooltip, 'p', diff --git a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs index 5f463c43..d3e4ab5e 100644 --- a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs +++ b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs @@ -5,6 +5,9 @@ using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Actors; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Gui; +using Penumbra.GameData.Structs; using Penumbra.Services; namespace Penumbra.UI.CollectionTab; @@ -12,7 +15,7 @@ namespace Penumbra.UI.CollectionTab; public class IndividualAssignmentUi : IDisposable { private readonly CommunicatorService _communicator; - private readonly ActorService _actorService; + private readonly ActorManager _actors; private readonly CollectionManager _collectionManager; private WorldCombo _worldCombo = null!; @@ -24,16 +27,13 @@ public class IndividualAssignmentUi : IDisposable private bool _ready; - public IndividualAssignmentUi(CommunicatorService communicator, ActorService actors, CollectionManager collectionManager) + public IndividualAssignmentUi(CommunicatorService communicator, ActorManager actors, CollectionManager collectionManager) { _communicator = communicator; - _actorService = actors; + _actors = actors; _collectionManager = collectionManager; _communicator.CollectionChange.Subscribe(UpdateIdentifiers, CollectionChange.Priority.IndividualAssignmentUi); - if (_actorService.Valid) - SetupCombos(); - else - _actorService.FinishedCreation += SetupCombos; + _actors.Awaiter.ContinueWith(_ => SetupCombos()); } public string PlayerTooltip { get; private set; } = NewPlayerTooltipEmpty; @@ -91,10 +91,10 @@ public class IndividualAssignmentUi : IDisposable // Input Selections. private string _newCharacterName = string.Empty; private ObjectKind _newKind = ObjectKind.BattleNpc; - private ActorIdentifier[] _playerIdentifiers = Array.Empty(); - private ActorIdentifier[] _retainerIdentifiers = Array.Empty(); - private ActorIdentifier[] _npcIdentifiers = Array.Empty(); - private ActorIdentifier[] _ownedIdentifiers = Array.Empty(); + private ActorIdentifier[] _playerIdentifiers = []; + private ActorIdentifier[] _retainerIdentifiers = []; + private ActorIdentifier[] _npcIdentifiers = []; + private ActorIdentifier[] _ownedIdentifiers = []; private const string NewPlayerTooltipEmpty = "Please enter a valid player name and choose an available world or 'Any World'."; private const string NewRetainerTooltipEmpty = "Please enter a valid retainer name."; @@ -126,14 +126,13 @@ public class IndividualAssignmentUi : IDisposable /// Create combos when ready. private void SetupCombos() { - _worldCombo = new WorldCombo(_actorService.AwaitedService.Data.Worlds, Penumbra.Log); - _mountCombo = new NpcCombo("##mountCombo", _actorService.AwaitedService.Data.Mounts, Penumbra.Log); - _companionCombo = new NpcCombo("##companionCombo", _actorService.AwaitedService.Data.Companions, Penumbra.Log); - _ornamentCombo = new NpcCombo("##ornamentCombo", _actorService.AwaitedService.Data.Ornaments, Penumbra.Log); - _bnpcCombo = new NpcCombo("##bnpcCombo", _actorService.AwaitedService.Data.BNpcs, Penumbra.Log); - _enpcCombo = new NpcCombo("##enpcCombo", _actorService.AwaitedService.Data.ENpcs, Penumbra.Log); - _ready = true; - _actorService.FinishedCreation -= SetupCombos; + _worldCombo = new WorldCombo(_actors.Data.Worlds, Penumbra.Log, WorldId.AnyWorld); + _mountCombo = new NpcCombo("##mountCombo", _actors.Data.Mounts, Penumbra.Log); + _companionCombo = new NpcCombo("##companionCombo", _actors.Data.Companions, Penumbra.Log); + _ornamentCombo = new NpcCombo("##ornamentCombo", _actors.Data.Ornaments, Penumbra.Log); + _bnpcCombo = new NpcCombo("##bnpcCombo", _actors.Data.BNpcs, Penumbra.Log); + _enpcCombo = new NpcCombo("##enpcCombo", _actors.Data.ENpcs, Penumbra.Log); + _ready = true; } private void UpdateIdentifiers(CollectionType type, ModCollection? _1, ModCollection? _2, string _3) @@ -146,22 +145,22 @@ public class IndividualAssignmentUi : IDisposable { var combo = GetNpcCombo(_newKind); PlayerTooltip = _collectionManager.Active.Individuals.CanAdd(IdentifierType.Player, _newCharacterName, - _worldCombo.CurrentSelection.Key, ObjectKind.None, - Array.Empty(), out _playerIdentifiers) switch + _worldCombo.CurrentSelection.Key, ObjectKind.None, [], out _playerIdentifiers) switch { _ when _newCharacterName.Length == 0 => NewPlayerTooltipEmpty, IndividualCollections.AddResult.Invalid => NewPlayerTooltipInvalid, IndividualCollections.AddResult.AlreadySet => AlreadyAssigned, _ => string.Empty, }; - RetainerTooltip = _collectionManager.Active.Individuals.CanAdd(IdentifierType.Retainer, _newCharacterName, 0, ObjectKind.None, - Array.Empty(), out _retainerIdentifiers) switch - { - _ when _newCharacterName.Length == 0 => NewRetainerTooltipEmpty, - IndividualCollections.AddResult.Invalid => NewRetainerTooltipInvalid, - IndividualCollections.AddResult.AlreadySet => AlreadyAssigned, - _ => string.Empty, - }; + RetainerTooltip = + _collectionManager.Active.Individuals.CanAdd(IdentifierType.Retainer, _newCharacterName, 0, ObjectKind.None, [], + out _retainerIdentifiers) switch + { + _ when _newCharacterName.Length == 0 => NewRetainerTooltipEmpty, + IndividualCollections.AddResult.Invalid => NewRetainerTooltipInvalid, + IndividualCollections.AddResult.AlreadySet => AlreadyAssigned, + _ => string.Empty, + }; if (combo.CurrentSelection.Ids != null) { NpcTooltip = _collectionManager.Active.Individuals.CanAdd(IdentifierType.Npc, string.Empty, ushort.MaxValue, _newKind, @@ -184,8 +183,8 @@ public class IndividualAssignmentUi : IDisposable { NpcTooltip = NewNpcTooltipEmpty; OwnedTooltip = NewNpcTooltipEmpty; - _npcIdentifiers = Array.Empty(); - _ownedIdentifiers = Array.Empty(); + _npcIdentifiers = []; + _ownedIdentifiers = []; } } } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 0ac3b9a0..d5ff1abd 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -6,16 +6,16 @@ using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData.Actors; +using Penumbra.GameData.Enums; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; -using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI.Classes; namespace Penumbra.UI.ResourceWatcher; -public class ResourceWatcher : IDisposable, ITab +public sealed class ResourceWatcher : IDisposable, ITab { public const int DefaultMaxEntries = 1024; public const RecordType AllRecords = RecordType.Request | RecordType.ResourceLoad | RecordType.FileLoad | RecordType.Destruction; @@ -24,15 +24,15 @@ public class ResourceWatcher : IDisposable, ITab private readonly EphemeralConfig _ephemeral; private readonly ResourceService _resources; private readonly ResourceLoader _loader; - private readonly ActorService _actors; - private readonly List _records = new(); - private readonly ConcurrentQueue _newRecords = new(); + private readonly ActorManager _actors; + private readonly List _records = []; + private readonly ConcurrentQueue _newRecords = []; private readonly ResourceWatcherTable _table; private string _logFilter = string.Empty; private Regex? _logRegex; private int _newMaxEntries; - public unsafe ResourceWatcher(ActorService actors, Configuration config, ResourceService resources, ResourceLoader loader) + public unsafe ResourceWatcher(ActorManager actors, Configuration config, ResourceService resources, ResourceLoader loader) { _actors = actors; _config = config; @@ -266,12 +266,12 @@ public class ResourceWatcher : IDisposable, ITab public unsafe string Name(ResolveData resolve, string none = "") { - if (resolve.AssociatedGameObject == IntPtr.Zero || !_actors.Valid) + if (resolve.AssociatedGameObject == IntPtr.Zero || !_actors.Awaiter.IsCompletedSuccessfully) return none; try { - var id = _actors.AwaitedService.FromObject((GameObject*)resolve.AssociatedGameObject, out _, false, true, true); + var id = _actors.FromObject((GameObject*)resolve.AssociatedGameObject, out _, false, true, true); if (id.IsValid) { if (id.Type is not (IdentifierType.Player or IdentifierType.Owned)) diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 2d30f9cf..3c6a3ed9 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -7,6 +7,7 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.Collections.Manager; +using Penumbra.GameData.Actors; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.Classes; @@ -14,7 +15,7 @@ using Penumbra.UI.CollectionTab; namespace Penumbra.UI.Tabs; -public class CollectionsTab : IDisposable, ITab +public sealed class CollectionsTab : IDisposable, ITab { private readonly EphemeralConfig _config; private readonly CollectionSelector _selector; @@ -40,7 +41,7 @@ public class CollectionsTab : IDisposable, ITab } public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, - CollectionManager collectionManager, ModStorage modStorage, ActorService actors, ITargetManager targets, TutorialService tutorial) + CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial) { _config = configuration.Ephemeral; _tutorial = tutorial; diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index 1cc29d88..ad3fdb3d 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -3,6 +3,7 @@ using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Services; +using Penumbra.UI.Tabs.Debug; using Watcher = Penumbra.UI.ResourceWatcher.ResourceWatcher; namespace Penumbra.UI.Tabs; diff --git a/Penumbra/UI/Tabs/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs similarity index 94% rename from Penumbra/UI/Tabs/DebugTab.cs rename to Penumbra/UI/Tabs/Debug/DebugTab.cs index 4f554ac5..57ca68fc 100644 --- a/Penumbra/UI/Tabs/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -1,24 +1,30 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; +using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Group; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.UI.Agent; using ImGuiNET; +using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; +using Penumbra.GameData.DataContainers; +using Penumbra.GameData.DataContainers.Bases; using Penumbra.GameData.Files; using Penumbra.Import.Structs; using Penumbra.Import.Textures; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.PathResolving; +using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -31,22 +37,39 @@ using CharacterBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBa using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using ObjectKind = Dalamud.Game.ClientState.Objects.Enums.ObjectKind; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; -using Penumbra.Interop.Services; -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using ImGuiClip = OtterGui.ImGuiClip; -namespace Penumbra.UI.Tabs; +namespace Penumbra.UI.Tabs.Debug; + +public class Diagnostics(IServiceProvider provider) +{ + public void DrawDiagnostics() + { + if (!ImGui.CollapsingHeader("Diagnostics")) + return; + + using var table = ImRaii.Table("##data", 4, ImGuiTableFlags.RowBg); + foreach (var type in typeof(IAsyncDataContainer).Assembly.GetTypes() + .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncDataContainer)))) + { + var container = (IAsyncDataContainer) provider.GetRequiredService(type); + ImGuiUtil.DrawTableColumn(container.Name); + ImGuiUtil.DrawTableColumn(container.Time.ToString()); + ImGuiUtil.DrawTableColumn(Functions.HumanReadableSize(container.Memory)); + ImGuiUtil.DrawTableColumn(container.TotalCount.ToString()); + } + } +} public class DebugTab : Window, ITab { - private readonly StartTracker _timer; private readonly PerformanceTracker _performance; private readonly Configuration _config; private readonly CollectionManager _collectionManager; private readonly ModManager _modManager; private readonly ValidityChecker _validityChecker; private readonly HttpApi _httpApi; - private readonly ActorService _actorService; + private readonly ActorManager _actors; private readonly DalamudServices _dalamud; private readonly StainService _stains; private readonly CharacterUtility _characterUtility; @@ -64,16 +87,17 @@ public class DebugTab : Window, ITab private readonly FrameworkManager _framework; private readonly TextureManager _textureManager; private readonly SkinFixer _skinFixer; - private readonly IdentifierService _identifier; private readonly RedrawService _redraws; + private readonly DictEmotes _emotes; + private readonly Diagnostics _diagnostics; - public DebugTab(StartTracker timer, PerformanceTracker performance, Configuration config, CollectionManager collectionManager, - ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorService actorService, + public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, + ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, DalamudServices dalamud, StainService stains, CharacterUtility characterUtility, ResidentResourceManager residentResources, ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager, SkinFixer skinFixer, IdentifierService identifier, RedrawService redraws) + TextureManager textureManager, SkinFixer skinFixer, RedrawService redraws, DictEmotes emotes, Diagnostics diagnostics) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -82,14 +106,13 @@ public class DebugTab : Window, ITab MinimumSize = new Vector2(200, 200), MaximumSize = new Vector2(2000, 2000), }; - _timer = timer; _performance = performance; _config = config; _collectionManager = collectionManager; _validityChecker = validityChecker; _modManager = modManager; _httpApi = httpApi; - _actorService = actorService; + _actors = actors; _dalamud = dalamud; _stains = stains; _characterUtility = characterUtility; @@ -107,8 +130,9 @@ public class DebugTab : Window, ITab _framework = framework; _textureManager = textureManager; _skinFixer = skinFixer; - _identifier = identifier; _redraws = redraws; + _emotes = emotes; + _diagnostics = diagnostics; } public ReadOnlySpan Label @@ -130,6 +154,7 @@ public class DebugTab : Window, ITab return; DrawDebugTabGeneral(); + _diagnostics.DrawDiagnostics(); DrawPerformanceTab(); ImGui.NewLine(); DrawPathResolverDebug(); @@ -357,7 +382,6 @@ public class DebugTab : Window, ITab ImGuiUtil.DrawTableColumn(name); ImGui.TableNextColumn(); } - } } } @@ -372,10 +396,7 @@ public class DebugTab : Window, ITab using (var start = TreeNode("Startup Performance", ImGuiTreeNodeFlags.DefaultOpen)) { if (start) - { - _timer.Draw("##startTimer", TimingExtensions.ToName); ImGui.NewLine(); - } } _performance.Draw("##performance", "Enable Runtime Performance Tracking", TimingExtensions.ToName); @@ -391,22 +412,10 @@ public class DebugTab : Window, ITab if (!table) return; - void DrawSpecial(string name, ActorIdentifier id) - { - if (!id.IsValid) - return; - - ImGuiUtil.DrawTableColumn(name); - ImGuiUtil.DrawTableColumn(string.Empty); - ImGuiUtil.DrawTableColumn(string.Empty); - ImGuiUtil.DrawTableColumn(_actorService.AwaitedService.ToString(id)); - ImGuiUtil.DrawTableColumn(string.Empty); - } - - DrawSpecial("Current Player", _actorService.AwaitedService.GetCurrentPlayer()); - DrawSpecial("Current Inspect", _actorService.AwaitedService.GetInspectPlayer()); - DrawSpecial("Current Card", _actorService.AwaitedService.GetCardPlayer()); - DrawSpecial("Current Glamour", _actorService.AwaitedService.GetGlamourPlayer()); + DrawSpecial("Current Player", _actors.GetCurrentPlayer()); + DrawSpecial("Current Inspect", _actors.GetInspectPlayer()); + DrawSpecial("Current Card", _actors.GetCardPlayer()); + DrawSpecial("Current Glamour", _actors.GetGlamourPlayer()); foreach (var obj in _dalamud.Objects) { @@ -415,11 +424,25 @@ public class DebugTab : Window, ITab ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero ? string.Empty : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); - var identifier = _actorService.AwaitedService.FromObject(obj, false, true, false); - ImGuiUtil.DrawTableColumn(_actorService.AwaitedService.ToString(identifier)); + var identifier = _actors.FromObject(obj, false, true, false); + ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); var id = obj.ObjectKind == ObjectKind.BattleNpc ? $"{identifier.DataId} | {obj.DataId}" : identifier.DataId.ToString(); ImGuiUtil.DrawTableColumn(id); } + + return; + + void DrawSpecial(string name, ActorIdentifier id) + { + if (!id.IsValid) + return; + + ImGuiUtil.DrawTableColumn(name); + ImGuiUtil.DrawTableColumn(string.Empty); + ImGuiUtil.DrawTableColumn(string.Empty); + ImGuiUtil.DrawTableColumn(_actors.ToString(id)); + ImGuiUtil.DrawTableColumn(string.Empty); + } } /// @@ -616,7 +639,7 @@ public class DebugTab : Window, ITab return; var skips = ImGuiClip.GetNecessarySkips(ImGui.GetTextLineHeightWithSpacing()); - var dummy = ImGuiClip.FilteredClippedDraw(_identifier.AwaitedService.Emotes, skips, + var dummy = ImGuiClip.FilteredClippedDraw(_emotes, skips, p => p.Key.Contains(_emoteSearchFile, StringComparison.OrdinalIgnoreCase) && (_emoteSearchName.Length == 0 || p.Value.Any(s => s.Name.ToDalamudString().TextValue.Contains(_emoteSearchName, StringComparison.OrdinalIgnoreCase))), diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index 25d91644..62ad5a6e 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -2,7 +2,7 @@ using Dalamud.Interface; using Dalamud.Interface.Windowing; using Dalamud.Plugin; using Penumbra.UI.AdvancedWindow; -using Penumbra.UI.Tabs; +using Penumbra.UI.Tabs.Debug; namespace Penumbra.UI; diff --git a/Penumbra/Util/PerformanceType.cs b/Penumbra/Util/PerformanceType.cs index 932072f0..b84813cc 100644 --- a/Penumbra/Util/PerformanceType.cs +++ b/Penumbra/Util/PerformanceType.cs @@ -1,23 +1,7 @@ -global using StartTracker = OtterGui.Classes.StartTimeTracker; global using PerformanceTracker = OtterGui.Classes.PerformanceTracker; namespace Penumbra.Util; -public enum StartTimeType -{ - Total, - Identifier, - Stains, - Items, - Actors, - Backup, - Mods, - Collections, - PathResolver, - Interface, - Api, -} - public enum PerformanceType { UiMainWindow, @@ -48,23 +32,6 @@ public enum PerformanceType public static class TimingExtensions { - public static string ToName(this StartTimeType type) - => type switch - { - StartTimeType.Total => "Total Construction", - StartTimeType.Identifier => "Identification Data", - StartTimeType.Stains => "Stain Data", - StartTimeType.Items => "Item Data", - StartTimeType.Actors => "Actor Data", - StartTimeType.Backup => "Checking Backups", - StartTimeType.Mods => "Loading Mods", - StartTimeType.Collections => "Loading Collections", - StartTimeType.Api => "Setting Up API", - StartTimeType.Interface => "Setting Up Interface", - StartTimeType.PathResolver => "Setting Up Path Resolver", - _ => $"Unknown {(int)type}", - }; - public static string ToName(this PerformanceType type) => type switch { diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index eed5d7c8..9172bb60 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -81,7 +81,8 @@ "penumbra.gamedata": { "type": "Project", "dependencies": { - "Penumbra.Api": "[1.0.8, )", + "OtterGui": "[1.0.0, )", + "Penumbra.Api": "[1.0.13, )", "Penumbra.String": "[1.0.4, )" } }, From b494892d62630f1e446c255d5b19abbce0dd64fb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Dec 2023 16:50:52 +0100 Subject: [PATCH 0255/1381] Update for changed GameData. --- Penumbra.GameData | 2 +- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index afc56d9f..0cb10c3d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit afc56d9f07a2a54ab791a4c85cf627b6f884aec2 +Subproject commit 0cb10c3d915fd9c589195e24d44db3e2ca57841a diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index acd6eae9..36237e47 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -46,7 +46,7 @@ public static class CustomizationSwap SetId idFrom, SetId idTo, byte variant, ref string fileName, ref bool dataWasChanged) { - variant = slot is BodySlot.Face or BodySlot.Zear ? byte.MaxValue : variant; + variant = slot is BodySlot.Face or BodySlot.Ear ? byte.MaxValue : variant; var mtrlFromPath = GamePaths.Character.Mtrl.Path(race, slot, idFrom, fileName, out var gameRaceFrom, out var gameSetIdFrom, variant); var mtrlToPath = GamePaths.Character.Mtrl.Path(race, slot, idTo, fileName, out var gameRaceTo, out var gameSetIdTo, variant); diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 0ec11542..c2910b51 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -221,7 +221,7 @@ public class ItemSwapTab : IDisposable, ITab _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Ears when _targetId > 0 && _sourceId > 0: - _swapData.LoadCustomization(_metaFileManager, BodySlot.Zear, Names.CombinedRace(_currentGender, ModelRace.Viera), + _swapData.LoadCustomization(_metaFileManager, BodySlot.Ear, Names.CombinedRace(_currentGender, ModelRace.Viera), (SetId)_sourceId, (SetId)_targetId, _useCurrentCollection ? _collectionManager.Active.Current : null); From 6dc5916f2b711faa489ac00fe67c352c923c9d61 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Dec 2023 17:02:08 +0100 Subject: [PATCH 0256/1381] Fix some issues. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Services/ServiceManager.cs | 5 +++-- Penumbra/Services/StainService.cs | 5 +++-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 4 ++-- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/OtterGui b/OtterGui index bde59c34..ac88abfe 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit bde59c34f7108520002c21cdbf21e8ee5b586944 +Subproject commit ac88abfe9eb0bb5d03aec092dc8f4db642ecbd6a diff --git a/Penumbra.GameData b/Penumbra.GameData index 0cb10c3d..c53e578e 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 0cb10c3d915fd9c589195e24d44db3e2ca57841a +Subproject commit c53e578e750d26f83a4e81aca1681c5b01d25a5a diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 049ab328..30f58701 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection; using OtterGui.Classes; using OtterGui.Compression; using OtterGui.Log; +using OtterGui.Services; using Penumbra.Api; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; @@ -74,8 +75,8 @@ public static class ServiceManager private static IServiceCollection AddAsyncServices(this IServiceCollection services) { - foreach (var type in typeof(IDataContainer).Assembly.GetExportedTypes() - .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncService)))) + foreach (var type in typeof(ActorManager).Assembly.GetExportedTypes() + .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IService)))) services.AddSingleton(type); return services; } diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index d11e4d64..714576b2 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin; using Dalamud.Plugin.Services; using ImGuiNET; +using OtterGui.Log; using OtterGui.Widgets; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Files; @@ -76,9 +77,9 @@ public class StainService : IDisposable public readonly StmFile StmFile; public readonly StainTemplateCombo TemplateCombo; - public StainService(DalamudPluginInterface pluginInterface, IDataManager dataManager, IPluginLog dalamudLog) + public StainService(DalamudPluginInterface pluginInterface, IDataManager dataManager, Logger logger) { - StainData = new DictStains(pluginInterface, dalamudLog, dataManager); + StainData = new DictStains(pluginInterface, logger, dataManager); StainCombo = new FilterComboColors(140, () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), Penumbra.Log); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 57ca68fc..34628c60 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -13,12 +13,12 @@ using ImGuiNET; using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.DataContainers; -using Penumbra.GameData.DataContainers.Bases; using Penumbra.GameData.Files; using Penumbra.Import.Structs; using Penumbra.Import.Textures; @@ -49,7 +49,7 @@ public class Diagnostics(IServiceProvider provider) return; using var table = ImRaii.Table("##data", 4, ImGuiTableFlags.RowBg); - foreach (var type in typeof(IAsyncDataContainer).Assembly.GetTypes() + foreach (var type in typeof(ActorManager).Assembly.GetTypes() .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncDataContainer)))) { var container = (IAsyncDataContainer) provider.GetRequiredService(type); From 5d28904bdf7e343f9df883c205cfcd2b10ec8ed3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Dec 2023 16:39:26 +0100 Subject: [PATCH 0257/1381] Update for GameData changes. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/EqdpCache.cs | 2 +- Penumbra/Collections/Cache/EstCache.cs | 6 +-- Penumbra/Collections/Cache/MetaCache.cs | 10 ++--- .../ResolveContext.PathResolution.cs | 14 +++---- .../Interop/ResourceTree/ResolveContext.cs | 6 +-- Penumbra/Meta/Files/EqdpFile.cs | 22 +++++----- Penumbra/Meta/Files/EqpGmpFile.cs | 30 ++++++------- Penumbra/Meta/Files/EstFile.cs | 12 +++--- .../Meta/Manipulations/EqdpManipulation.cs | 4 +- .../Meta/Manipulations/EqpManipulation.cs | 4 +- .../Meta/Manipulations/EstManipulation.cs | 5 ++- .../Meta/Manipulations/GmpManipulation.cs | 6 +-- .../Meta/Manipulations/ImcManipulation.cs | 12 +++--- .../Meta/Manipulations/MetaManipulation.cs | 20 ++++++++- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 6 +-- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 42 +++++++++---------- Penumbra/Mods/ItemSwap/ItemSwap.cs | 10 ++--- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 2 +- Penumbra/Mods/Manager/ModCacheManager.cs | 40 ++++++++++++------ Penumbra/Mods/Subclasses/SubMod.cs | 6 +-- Penumbra/Penumbra.csproj | 5 ++- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 16 +++---- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 1 + 24 files changed, 160 insertions(+), 123 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c53e578e..bee73fbe 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c53e578e750d26f83a4e81aca1681c5b01d25a5a +Subproject commit bee73fbe1e263d81067029ad97c8e4a263c88147 diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index 3937fa72..6b4982a7 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -45,7 +45,7 @@ public readonly struct EqdpCache : IDisposable foreach (var file in _eqdpFiles.OfType()) { var relevant = CharacterUtility.RelevantIndices[file.Index.Value]; - file.Reset(_eqdpManipulations.Where(m => m.FileIndex() == relevant).Select(m => (SetId)m.SetId)); + file.Reset(_eqdpManipulations.Where(m => m.FileIndex() == relevant).Select(m => (PrimaryId)m.SetId)); } _eqdpManipulations.Clear(); diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 9e2cdef9..2552cd4a 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -74,12 +74,12 @@ public struct EstCache : IDisposable }; } - internal ushort GetEstEntry(MetaFileManager manager, EstManipulation.EstType type, GenderRace genderRace, SetId setId) + internal ushort GetEstEntry(MetaFileManager manager, EstManipulation.EstType type, GenderRace genderRace, PrimaryId primaryId) { var file = GetEstFile(type); return file != null - ? file[genderRace, setId.Id] - : EstFile.GetDefault(manager, type, genderRace, setId); + ? file[genderRace, primaryId.Id] + : EstFile.GetDefault(manager, type, genderRace, primaryId); } public void Reset() diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index d5acf249..650bd536 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -187,17 +187,17 @@ public class MetaCache : IDisposable, IEnumerable _imcCache.GetImcFile(path, out file); - internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, SetId setId) + internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, PrimaryId primaryId) { var eqdpFile = _eqdpCache.EqdpFile(race, accessory); if (eqdpFile != null) - return setId.Id < eqdpFile.Count ? eqdpFile[setId] : default; + return primaryId.Id < eqdpFile.Count ? eqdpFile[primaryId] : default; else - return Meta.Files.ExpandedEqdpFile.GetDefault(_manager, race, accessory, setId); + return Meta.Files.ExpandedEqdpFile.GetDefault(_manager, race, accessory, primaryId); } - internal ushort GetEstEntry(EstManipulation.EstType type, GenderRace genderRace, SetId setId) - => _estCache.GetEstEntry(_manager, type, genderRace, setId); + internal ushort GetEstEntry(EstManipulation.EstType type, GenderRace genderRace, PrimaryId primaryId) + => _estCache.GetEstEntry(_manager, type, genderRace, primaryId); /// Use this when CharacterUtility becomes ready. private void ApplyStoredManipulations() diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 1c9dfaa1..f2059253 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -37,7 +37,7 @@ internal partial record ResolveContext private unsafe GenderRace ResolveModelRaceCode() => ResolveEqdpRaceCode(Slot, Equipment.Set); - private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, SetId setId) + private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, PrimaryId primaryId) { var slotIndex = slot.ToIndex(); if (slotIndex >= 10 || ModelType != ModelType.Human) @@ -55,7 +55,7 @@ internal partial record ResolveContext if (metaCache == null) return GenderRace.MidlanderMale; - var entry = metaCache.GetEqdpEntry(characterRaceCode, accessory, setId); + var entry = metaCache.GetEqdpEntry(characterRaceCode, accessory, primaryId); if (entry.ToBits(slot).Item2) return characterRaceCode; @@ -63,7 +63,7 @@ internal partial record ResolveContext if (fallbackRaceCode == GenderRace.MidlanderMale) return GenderRace.MidlanderMale; - entry = metaCache.GetEqdpEntry(fallbackRaceCode, accessory, setId); + entry = metaCache.GetEqdpEntry(fallbackRaceCode, accessory, primaryId); if (entry.ToBits(slot).Item2) return fallbackRaceCode; @@ -229,7 +229,7 @@ internal partial record ResolveContext return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } - private unsafe (GenderRace RaceCode, string Slot, SetId Set) ResolveHumanSkeletonData(uint partialSkeletonIndex) + private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanSkeletonData(uint partialSkeletonIndex) { var human = (Human*)CharacterBase.Value; var characterRaceCode = (GenderRace)human->RaceSexId; @@ -262,17 +262,17 @@ internal partial record ResolveContext } } - private unsafe (GenderRace RaceCode, string Slot, SetId Set) ResolveHumanEquipmentSkeletonData(EquipSlot slot, EstManipulation.EstType type) + private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanEquipmentSkeletonData(EquipSlot slot, EstManipulation.EstType type) { var human = (Human*)CharacterBase.Value; var equipment = ((CharacterArmor*)&human->Head)[slot.ToIndex()]; return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot, equipment.Set), type, equipment.Set); } - private unsafe (GenderRace RaceCode, string Slot, SetId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstManipulation.EstType type, SetId set) + private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstManipulation.EstType type, PrimaryId primary) { var metaCache = Global.Collection.MetaCache; - var skeletonSet = metaCache == null ? default : metaCache.GetEstEntry(type, raceCode, set); + var skeletonSet = metaCache == null ? default : metaCache.GetEstEntry(type, raceCode, primary); return (raceCode, EstManipulation.ToName(type), skeletonSet); } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index d03ee508..431f1ac0 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -25,8 +25,8 @@ internal record GlobalResolveContext(ObjectIdentification Identifier, ModCollect public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); public unsafe ResolveContext CreateContext(CharacterBase* characterBase, uint slotIndex = 0xFFFFFFFFu, - EquipSlot slot = EquipSlot.Unknown, CharacterArmor equipment = default, WeaponType weaponType = default) - => new(this, characterBase, slotIndex, slot, equipment, weaponType); + EquipSlot slot = EquipSlot.Unknown, CharacterArmor equipment = default, SecondaryId secondaryId = default) + => new(this, characterBase, slotIndex, slot, equipment, secondaryId); } internal partial record ResolveContext( @@ -35,7 +35,7 @@ internal partial record ResolveContext( uint SlotIndex, EquipSlot Slot, CharacterArmor Equipment, - WeaponType WeaponType) + SecondaryId SecondaryId) { private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); diff --git a/Penumbra/Meta/Files/EqdpFile.cs b/Penumbra/Meta/Files/EqdpFile.cs index 8a99225f..c76c4efd 100644 --- a/Penumbra/Meta/Files/EqdpFile.cs +++ b/Penumbra/Meta/Files/EqdpFile.cs @@ -38,7 +38,7 @@ public sealed unsafe class ExpandedEqdpFile : MetaBaseFile public int Count => (Length - DataOffset) / EqdpEntrySize; - public EqdpEntry this[SetId id] + public EqdpEntry this[PrimaryId id] { get { @@ -79,7 +79,7 @@ public sealed unsafe class ExpandedEqdpFile : MetaBaseFile MemoryUtility.MemSet(myDataPtr, 0, Length - (int)((byte*)myDataPtr - Data)); } - public void Reset(IEnumerable entries) + public void Reset(IEnumerable entries) { foreach (var entry in entries) this[entry] = GetDefault(entry); @@ -101,18 +101,18 @@ public sealed unsafe class ExpandedEqdpFile : MetaBaseFile Reset(); } - public EqdpEntry GetDefault(SetId setId) - => GetDefault(Manager, Index, setId); + public EqdpEntry GetDefault(PrimaryId primaryId) + => GetDefault(Manager, Index, primaryId); - public static EqdpEntry GetDefault(MetaFileManager manager, CharacterUtility.InternalIndex idx, SetId setId) - => GetDefault((byte*)manager.CharacterUtility.DefaultResource(idx).Address, setId); + public static EqdpEntry GetDefault(MetaFileManager manager, CharacterUtility.InternalIndex idx, PrimaryId primaryId) + => GetDefault((byte*)manager.CharacterUtility.DefaultResource(idx).Address, primaryId); - public static EqdpEntry GetDefault(byte* data, SetId setId) + public static EqdpEntry GetDefault(byte* data, PrimaryId primaryId) { var blockSize = *(ushort*)(data + IdentifierSize); var totalBlockCount = *(ushort*)(data + IdentifierSize + 2); - var blockIdx = setId.Id / blockSize; + var blockIdx = primaryId.Id / blockSize; if (blockIdx >= totalBlockCount) return 0; @@ -121,9 +121,9 @@ public sealed unsafe class ExpandedEqdpFile : MetaBaseFile return 0; var blockData = (ushort*)(data + IdentifierSize + PreambleSize + totalBlockCount * 2 + block * 2); - return (EqdpEntry)(*(blockData + setId.Id % blockSize)); + return (EqdpEntry)(*(blockData + primaryId.Id % blockSize)); } - public static EqdpEntry GetDefault(MetaFileManager manager, GenderRace raceCode, bool accessory, SetId setId) - => GetDefault(manager, CharacterUtility.ReverseIndices[(int)CharacterUtilityData.EqdpIdx(raceCode, accessory)], setId); + public static EqdpEntry GetDefault(MetaFileManager manager, GenderRace raceCode, bool accessory, PrimaryId primaryId) + => GetDefault(manager, CharacterUtility.ReverseIndices[(int)CharacterUtilityData.EqdpIdx(raceCode, accessory)], primaryId); } diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index 6e9fd010..97f57703 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -24,7 +24,7 @@ public unsafe class ExpandedEqpGmpBase : MetaBaseFile public ulong ControlBlock => *(ulong*)Data; - protected ulong GetInternal(SetId idx) + protected ulong GetInternal(PrimaryId idx) { return idx.Id switch { @@ -34,7 +34,7 @@ public unsafe class ExpandedEqpGmpBase : MetaBaseFile }; } - protected void SetInternal(SetId idx, ulong value) + protected void SetInternal(PrimaryId idx, ulong value) { idx = idx.Id switch { @@ -81,13 +81,13 @@ public unsafe class ExpandedEqpGmpBase : MetaBaseFile Reset(); } - protected static ulong GetDefaultInternal(MetaFileManager manager, CharacterUtility.InternalIndex fileIndex, SetId setId, ulong def) + protected static ulong GetDefaultInternal(MetaFileManager manager, CharacterUtility.InternalIndex fileIndex, PrimaryId primaryId, ulong def) { var data = (byte*)manager.CharacterUtility.DefaultResource(fileIndex).Address; - if (setId == 0) - setId = 1; + if (primaryId == 0) + primaryId = 1; - var blockIdx = setId.Id / BlockSize; + var blockIdx = primaryId.Id / BlockSize; if (blockIdx >= NumBlocks) return def; @@ -97,7 +97,7 @@ public unsafe class ExpandedEqpGmpBase : MetaBaseFile return def; var count = BitOperations.PopCount(control & (blockBit - 1)); - var idx = setId.Id % BlockSize; + var idx = primaryId.Id % BlockSize; var ptr = (ulong*)data + BlockSize * count + idx; return *ptr; } @@ -112,15 +112,15 @@ public sealed class ExpandedEqpFile : ExpandedEqpGmpBase, IEnumerable : base(manager, false) { } - public EqpEntry this[SetId idx] + public EqpEntry this[PrimaryId idx] { get => (EqpEntry)GetInternal(idx); set => SetInternal(idx, (ulong)value); } - public static EqpEntry GetDefault(MetaFileManager manager, SetId setIdx) - => (EqpEntry)GetDefaultInternal(manager, InternalIndex, setIdx, (ulong)Eqp.DefaultEntry); + public static EqpEntry GetDefault(MetaFileManager manager, PrimaryId primaryIdx) + => (EqpEntry)GetDefaultInternal(manager, InternalIndex, primaryIdx, (ulong)Eqp.DefaultEntry); protected override unsafe void SetEmptyBlock(int idx) { @@ -130,7 +130,7 @@ public sealed class ExpandedEqpFile : ExpandedEqpGmpBase, IEnumerable *ptr = (ulong)Eqp.DefaultEntry; } - public void Reset(IEnumerable entries) + public void Reset(IEnumerable entries) { foreach (var entry in entries) this[entry] = GetDefault(Manager, entry); @@ -155,16 +155,16 @@ public sealed class ExpandedGmpFile : ExpandedEqpGmpBase, IEnumerable : base(manager, true) { } - public GmpEntry this[SetId idx] + public GmpEntry this[PrimaryId idx] { get => (GmpEntry)GetInternal(idx); set => SetInternal(idx, (ulong)value); } - public static GmpEntry GetDefault(MetaFileManager manager, SetId setIdx) - => (GmpEntry)GetDefaultInternal(manager, InternalIndex, setIdx, (ulong)GmpEntry.Default); + public static GmpEntry GetDefault(MetaFileManager manager, PrimaryId primaryIdx) + => (GmpEntry)GetDefaultInternal(manager, InternalIndex, primaryIdx, (ulong)GmpEntry.Default); - public void Reset(IEnumerable entries) + public void Reset(IEnumerable entries) { foreach (var entry in entries) this[entry] = GetDefault(Manager, entry); diff --git a/Penumbra/Meta/Files/EstFile.cs b/Penumbra/Meta/Files/EstFile.cs index 2c7409b4..af441b22 100644 --- a/Penumbra/Meta/Files/EstFile.cs +++ b/Penumbra/Meta/Files/EstFile.cs @@ -167,21 +167,21 @@ public sealed unsafe class EstFile : MetaBaseFile public ushort GetDefault(GenderRace genderRace, ushort setId) => GetDefault(Manager, Index, genderRace, setId); - public static ushort GetDefault(MetaFileManager manager, CharacterUtility.InternalIndex index, GenderRace genderRace, SetId setId) + public static ushort GetDefault(MetaFileManager manager, CharacterUtility.InternalIndex index, GenderRace genderRace, PrimaryId primaryId) { var data = (byte*)manager.CharacterUtility.DefaultResource(index).Address; var count = *(int*)data; var span = new ReadOnlySpan(data + 4, count); - var (idx, found) = FindEntry(span, genderRace, setId.Id); + var (idx, found) = FindEntry(span, genderRace, primaryId.Id); if (!found) return 0; return *(ushort*)(data + 4 + count * EntryDescSize + idx * EntrySize); } - public static ushort GetDefault(MetaFileManager manager, MetaIndex metaIndex, GenderRace genderRace, SetId setId) - => GetDefault(manager, CharacterUtility.ReverseIndices[(int)metaIndex], genderRace, setId); + public static ushort GetDefault(MetaFileManager manager, MetaIndex metaIndex, GenderRace genderRace, PrimaryId primaryId) + => GetDefault(manager, CharacterUtility.ReverseIndices[(int)metaIndex], genderRace, primaryId); - public static ushort GetDefault(MetaFileManager manager, EstManipulation.EstType estType, GenderRace genderRace, SetId setId) - => GetDefault(manager, (MetaIndex)estType, genderRace, setId); + public static ushort GetDefault(MetaFileManager manager, EstManipulation.EstType estType, GenderRace genderRace, PrimaryId primaryId) + => GetDefault(manager, (MetaIndex)estType, genderRace, primaryId); } diff --git a/Penumbra/Meta/Manipulations/EqdpManipulation.cs b/Penumbra/Meta/Manipulations/EqdpManipulation.cs index df7ed2e4..0426dfce 100644 --- a/Penumbra/Meta/Manipulations/EqdpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqdpManipulation.cs @@ -18,13 +18,13 @@ public readonly struct EqdpManipulation : IMetaManipulation [JsonConverter(typeof(StringEnumConverter))] public ModelRace Race { get; private init; } - public SetId SetId { get; private init; } + public PrimaryId SetId { get; private init; } [JsonConverter(typeof(StringEnumConverter))] public EquipSlot Slot { get; private init; } [JsonConstructor] - public EqdpManipulation(EqdpEntry entry, EquipSlot slot, Gender gender, ModelRace race, SetId setId) + public EqdpManipulation(EqdpEntry entry, EquipSlot slot, Gender gender, ModelRace race, PrimaryId setId) { Gender = gender; Race = race; diff --git a/Penumbra/Meta/Manipulations/EqpManipulation.cs b/Penumbra/Meta/Manipulations/EqpManipulation.cs index 4373e8e9..d59938b6 100644 --- a/Penumbra/Meta/Manipulations/EqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqpManipulation.cs @@ -15,13 +15,13 @@ public readonly struct EqpManipulation : IMetaManipulation [JsonConverter(typeof(ForceNumericFlagEnumConverter))] public EqpEntry Entry { get; private init; } - public SetId SetId { get; private init; } + public PrimaryId SetId { get; private init; } [JsonConverter(typeof(StringEnumConverter))] public EquipSlot Slot { get; private init; } [JsonConstructor] - public EqpManipulation(EqpEntry entry, EquipSlot slot, SetId setId) + public EqpManipulation(EqpEntry entry, EquipSlot slot, PrimaryId setId) { Slot = slot; SetId = setId; diff --git a/Penumbra/Meta/Manipulations/EstManipulation.cs b/Penumbra/Meta/Manipulations/EstManipulation.cs index 455c39ff..d3c92ad3 100644 --- a/Penumbra/Meta/Manipulations/EstManipulation.cs +++ b/Penumbra/Meta/Manipulations/EstManipulation.cs @@ -36,13 +36,14 @@ public readonly struct EstManipulation : IMetaManipulation [JsonConverter(typeof(StringEnumConverter))] public ModelRace Race { get; private init; } - public SetId SetId { get; private init; } + public PrimaryId SetId { get; private init; } [JsonConverter(typeof(StringEnumConverter))] public EstType Slot { get; private init; } + [JsonConstructor] - public EstManipulation(Gender gender, ModelRace race, EstType slot, SetId setId, ushort entry) + public EstManipulation(Gender gender, ModelRace race, EstType slot, PrimaryId setId, ushort entry) { Entry = entry; Gender = gender; diff --git a/Penumbra/Meta/Manipulations/GmpManipulation.cs b/Penumbra/Meta/Manipulations/GmpManipulation.cs index 928b6f55..ee58295d 100644 --- a/Penumbra/Meta/Manipulations/GmpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GmpManipulation.cs @@ -8,11 +8,11 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct GmpManipulation : IMetaManipulation { - public GmpEntry Entry { get; private init; } - public SetId SetId { get; private init; } + public GmpEntry Entry { get; private init; } + public PrimaryId SetId { get; private init; } [JsonConstructor] - public GmpManipulation(GmpEntry entry, SetId setId) + public GmpManipulation(GmpEntry entry, PrimaryId setId) { Entry = entry; SetId = setId; diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs index 391daacc..a1c4b5bf 100644 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ b/Penumbra/Meta/Manipulations/ImcManipulation.cs @@ -12,10 +12,10 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct ImcManipulation : IMetaManipulation { - public ImcEntry Entry { get; private init; } - public SetId PrimaryId { get; private init; } - public SetId SecondaryId { get; private init; } - public Variant Variant { get; private init; } + public ImcEntry Entry { get; private init; } + public PrimaryId PrimaryId { get; private init; } + public PrimaryId SecondaryId { get; private init; } + public Variant Variant { get; private init; } [JsonConverter(typeof(StringEnumConverter))] public ObjectType ObjectType { get; private init; } @@ -26,7 +26,7 @@ public readonly struct ImcManipulation : IMetaManipulation [JsonConverter(typeof(StringEnumConverter))] public BodySlot BodySlot { get; private init; } - public ImcManipulation(EquipSlot equipSlot, ushort variant, SetId primaryId, ImcEntry entry) + public ImcManipulation(EquipSlot equipSlot, ushort variant, PrimaryId primaryId, ImcEntry entry) { Entry = entry; PrimaryId = primaryId; @@ -42,7 +42,7 @@ public readonly struct ImcManipulation : IMetaManipulation // so we change the unused value to something nonsensical in that case, just so they do not compare equal, // and clamp the variant to 255. [JsonConstructor] - internal ImcManipulation(ObjectType objectType, BodySlot bodySlot, SetId primaryId, SetId secondaryId, ushort variant, + internal ImcManipulation(ObjectType objectType, BodySlot bodySlot, PrimaryId primaryId, PrimaryId secondaryId, ushort variant, EquipSlot equipSlot, ImcEntry entry) { Entry = entry; diff --git a/Penumbra/Meta/Manipulations/MetaManipulation.cs b/Penumbra/Meta/Manipulations/MetaManipulation.cs index 94b45cdf..e057d1a4 100644 --- a/Penumbra/Meta/Manipulations/MetaManipulation.cs +++ b/Penumbra/Meta/Manipulations/MetaManipulation.cs @@ -269,5 +269,23 @@ public readonly struct MetaManipulation : IEquatable, ICompara Type.Gmp => $"{Gmp.Entry.Value}", Type.Rsp => $"{Rsp.Entry}", _ => string.Empty, - }; + }; + + public static bool operator ==(MetaManipulation left, MetaManipulation right) + => left.Equals(right); + + public static bool operator !=(MetaManipulation left, MetaManipulation right) + => !(left == right); + + public static bool operator <(MetaManipulation left, MetaManipulation right) + => left.CompareTo(right) < 0; + + public static bool operator <=(MetaManipulation left, MetaManipulation right) + => left.CompareTo(right) <= 0; + + public static bool operator >(MetaManipulation left, MetaManipulation right) + => left.CompareTo(right) > 0; + + public static bool operator >=(MetaManipulation left, MetaManipulation right) + => left.CompareTo(right) >= 0; } diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index 36237e47..fc32df0c 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -12,7 +12,7 @@ public static class CustomizationSwap { /// The .mdl file for customizations is unique per racecode, slot and id, thus the .mdl redirection itself is independent of the mode. public static FileSwap CreateMdl(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, - SetId idFrom, SetId idTo) + PrimaryId idFrom, PrimaryId idTo) { if (idFrom.Id > byte.MaxValue) throw new Exception($"The Customization ID {idFrom} is too large for {slot}."); @@ -43,7 +43,7 @@ public static class CustomizationSwap } public static FileSwap CreateMtrl(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, - SetId idFrom, SetId idTo, byte variant, + PrimaryId idFrom, PrimaryId idTo, byte variant, ref string fileName, ref bool dataWasChanged) { variant = slot is BodySlot.Face or BodySlot.Ear ? byte.MaxValue : variant; @@ -79,7 +79,7 @@ public static class CustomizationSwap } public static FileSwap CreateTex(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, - SetId idFrom, ref MtrlFile.Texture texture, + PrimaryId idFrom, ref MtrlFile.Texture texture, ref bool dataWasChanged) { var path = texture.Path; diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index d634349e..f7f82a59 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -185,13 +185,13 @@ public static class EquipmentSwap } public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, - Func manips, EquipSlot slot, GenderRace gr, SetId idFrom, - SetId idTo, byte mtrlTo) + Func manips, EquipSlot slot, GenderRace gr, PrimaryId idFrom, + PrimaryId idTo, byte mtrlTo) => CreateEqdp(manager, redirections, manips, slot, slot, gr, idFrom, idTo, mtrlTo); public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, - Func manips, EquipSlot slotFrom, EquipSlot slotTo, GenderRace gr, SetId idFrom, - SetId idTo, byte mtrlTo) + Func manips, EquipSlot slotFrom, EquipSlot slotTo, GenderRace gr, PrimaryId idFrom, + PrimaryId idTo, byte mtrlTo) { var (gender, race) = gr.Split(); var eqdpFrom = new EqdpManipulation(ExpandedEqdpFile.GetDefault(manager, gr, slotFrom.IsAccessory(), idFrom), slotFrom, gender, @@ -214,11 +214,11 @@ public static class EquipmentSwap } public static FileSwap CreateMdl(MetaFileManager manager, Func redirections, EquipSlot slot, GenderRace gr, - SetId idFrom, SetId idTo, byte mtrlTo) + PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) => CreateMdl(manager, redirections, slot, slot, gr, idFrom, idTo, mtrlTo); public static FileSwap CreateMdl(MetaFileManager manager, Func redirections, EquipSlot slotFrom, EquipSlot slotTo, - GenderRace gr, SetId idFrom, SetId idTo, byte mtrlTo) + GenderRace gr, PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) { var mdlPathFrom = slotFrom.IsAccessory() ? GamePaths.Accessory.Mdl.Path(idFrom, gr, slotFrom) @@ -236,7 +236,7 @@ public static class EquipmentSwap return mdl; } - private static void LookupItem(EquipItem i, out EquipSlot slot, out SetId modelId, out Variant variant) + private static void LookupItem(EquipItem i, out EquipSlot slot, out PrimaryId modelId, out Variant variant) { slot = i.Type.ToSlot(); if (!slot.IsEquipmentPiece()) @@ -247,7 +247,7 @@ public static class EquipmentSwap } private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, ObjectIdentification identifier, EquipSlot slotFrom, - SetId idFrom, SetId idTo, Variant variantFrom) + PrimaryId idFrom, PrimaryId idTo, Variant variantFrom) { var entry = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, default); var imc = new ImcFile(manager, entry); @@ -270,8 +270,8 @@ public static class EquipmentSwap return (imc, variants, items); } - public static MetaSwap? CreateGmp(MetaFileManager manager, Func manips, EquipSlot slot, SetId idFrom, - SetId idTo) + public static MetaSwap? CreateGmp(MetaFileManager manager, Func manips, EquipSlot slot, PrimaryId idFrom, + PrimaryId idTo) { if (slot is not EquipSlot.Head) return null; @@ -283,12 +283,12 @@ public static class EquipmentSwap public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, Func manips, EquipSlot slot, - SetId idFrom, SetId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) + PrimaryId idFrom, PrimaryId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) => CreateImc(manager, redirections, manips, slot, slot, idFrom, idTo, variantFrom, variantTo, imcFileFrom, imcFileTo); public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, Func manips, - EquipSlot slotFrom, EquipSlot slotTo, SetId idFrom, SetId idTo, + EquipSlot slotFrom, EquipSlot slotTo, PrimaryId idFrom, PrimaryId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) { var entryFrom = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); @@ -322,7 +322,7 @@ public static class EquipmentSwap // Example: Abyssos Helm / Body - public static FileSwap? CreateAvfx(MetaFileManager manager, Func redirections, SetId idFrom, SetId idTo, byte vfxId) + public static FileSwap? CreateAvfx(MetaFileManager manager, Func redirections, PrimaryId idFrom, PrimaryId idTo, byte vfxId) { if (vfxId == 0) return null; @@ -340,8 +340,8 @@ public static class EquipmentSwap return avfx; } - public static MetaSwap? CreateEqp(MetaFileManager manager, Func manips, EquipSlot slot, SetId idFrom, - SetId idTo) + public static MetaSwap? CreateEqp(MetaFileManager manager, Func manips, EquipSlot slot, PrimaryId idFrom, + PrimaryId idTo) { if (slot.IsAccessory()) return null; @@ -353,13 +353,13 @@ public static class EquipmentSwap return new MetaSwap(manips, eqpFrom, eqpTo); } - public static FileSwap? CreateMtrl(MetaFileManager manager, Func redirections, EquipSlot slot, SetId idFrom, - SetId idTo, byte variantTo, ref string fileName, + public static FileSwap? CreateMtrl(MetaFileManager manager, Func redirections, EquipSlot slot, PrimaryId idFrom, + PrimaryId idTo, byte variantTo, ref string fileName, ref bool dataWasChanged) => CreateMtrl(manager, redirections, slot, slot, idFrom, idTo, variantTo, ref fileName, ref dataWasChanged); public static FileSwap? CreateMtrl(MetaFileManager manager, Func redirections, EquipSlot slotFrom, EquipSlot slotTo, - SetId idFrom, SetId idTo, byte variantTo, ref string fileName, + PrimaryId idFrom, PrimaryId idTo, byte variantTo, ref string fileName, ref bool dataWasChanged) { var prefix = slotTo.IsAccessory() ? 'a' : 'e'; @@ -397,13 +397,13 @@ public static class EquipmentSwap return mtrl; } - public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, SetId idFrom, SetId idTo, + public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, PrimaryId idFrom, PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) => CreateTex(manager, redirections, prefix, EquipSlot.Unknown, EquipSlot.Unknown, idFrom, idTo, ref texture, ref dataWasChanged); public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, EquipSlot slotFrom, - EquipSlot slotTo, SetId idFrom, - SetId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) + EquipSlot slotTo, PrimaryId idFrom, + PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) { var path = texture.Path; var addedDashes = false; diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 90bee553..b269d89c 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -150,7 +150,7 @@ public static class ItemSwap /// metaChanges is not manipulated, but IReadOnlySet does not support TryGetValue. public static MetaSwap? CreateEst(MetaFileManager manager, Func redirections, Func manips, EstManipulation.EstType type, - GenderRace genderRace, SetId idFrom, SetId idTo, bool ownMdl) + GenderRace genderRace, PrimaryId idFrom, PrimaryId idTo, bool ownMdl) { if (type == 0) return null; @@ -195,7 +195,7 @@ public static class ItemSwap } } - public static string ReplaceAnyId(string path, char idType, SetId id, bool condition = true) + public static string ReplaceAnyId(string path, char idType, PrimaryId id, bool condition = true) => condition ? Regex.Replace(path, $"{idType}\\d{{4}}", $"{idType}{id.Id:D4}") : path; @@ -203,10 +203,10 @@ public static class ItemSwap public static string ReplaceAnyRace(string path, GenderRace to, bool condition = true) => ReplaceAnyId(path, 'c', (ushort)to, condition); - public static string ReplaceAnyBody(string path, BodySlot slot, SetId to, bool condition = true) + public static string ReplaceAnyBody(string path, BodySlot slot, PrimaryId to, bool condition = true) => ReplaceAnyId(path, slot.ToAbbreviation(), to, condition); - public static string ReplaceId(string path, char type, SetId idFrom, SetId idTo, bool condition = true) + public static string ReplaceId(string path, char type, PrimaryId idFrom, PrimaryId idTo, bool condition = true) => condition ? path.Replace($"{type}{idFrom.Id:D4}", $"{type}{idTo.Id:D4}") : path; @@ -219,7 +219,7 @@ public static class ItemSwap public static string ReplaceRace(string path, GenderRace from, GenderRace to, bool condition = true) => ReplaceId(path, 'c', (ushort)from, (ushort)to, condition); - public static string ReplaceBody(string path, BodySlot slot, SetId idFrom, SetId idTo, bool condition = true) + public static string ReplaceBody(string path, BodySlot slot, PrimaryId idFrom, PrimaryId idTo, bool condition = true) => ReplaceId(path, slot.ToAbbreviation(), idFrom, idTo, condition); public static string AddSuffix(string path, string ext, string suffix, bool condition = true) diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 9ca02c4e..ff722945 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -145,7 +145,7 @@ public class ItemSwapContainer return ret; } - public bool LoadCustomization(MetaFileManager manager, BodySlot slot, GenderRace race, SetId from, SetId to, + public bool LoadCustomization(MetaFileManager manager, BodySlot slot, GenderRace race, PrimaryId from, PrimaryId to, ModCollection? collection = null) { var pathResolver = PathResolver(collection); diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 0af78431..a95567ce 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -139,7 +139,7 @@ public class ModCacheManager : IDisposable { case ModPathChangeType.Added: case ModPathChangeType.Reloaded: - Refresh(mod); + RefreshWithChangedItems(mod); break; } } @@ -151,10 +151,28 @@ public class ModCacheManager : IDisposable } private void OnModDiscoveryFinished() - => Parallel.ForEach(_modManager, Refresh); + { + if (!_identifier.Awaiter.IsCompletedSuccessfully || _updatingItems) + { + Parallel.ForEach(_modManager, RefreshWithoutChangedItems); + } + else + { + _updatingItems = true; + Parallel.ForEach(_modManager, RefreshWithChangedItems); + _updatingItems = false; + } + } private void OnIdentifierCreation() - => Parallel.ForEach(_modManager, UpdateChangedItems); + { + if (_updatingItems) + return; + + _updatingItems = true; + Parallel.ForEach(_modManager, UpdateChangedItems); + _updatingItems = false; + } private static void UpdateFileCount(Mod mod) => mod.TotalFileCount = mod.AllSubMods.Sum(s => s.Files.Count); @@ -173,15 +191,8 @@ public class ModCacheManager : IDisposable private void UpdateChangedItems(Mod mod) { - if (_updatingItems) - return; - - _updatingItems = true; var changedItems = (SortedList)mod.ChangedItems; changedItems.Clear(); - if (!_identifier.Awaiter.IsCompletedSuccessfully) - return; - foreach (var gamePath in mod.AllSubMods.SelectMany(m => m.Files.Keys.Concat(m.FileSwaps.Keys))) _identifier.Identify(changedItems, gamePath.ToString()); @@ -189,7 +200,6 @@ public class ModCacheManager : IDisposable ComputeChangedItems(_identifier, changedItems, manip); mod.LowerChangedItemsString = string.Join("\0", mod.ChangedItems.Keys.Select(k => k.ToLowerInvariant())); - _updatingItems = false; } private static void UpdateCounts(Mod mod) @@ -210,10 +220,16 @@ public class ModCacheManager : IDisposable } } - private void Refresh(Mod mod) + private void RefreshWithChangedItems(Mod mod) { UpdateTags(mod); UpdateCounts(mod); UpdateChangedItems(mod); } + + private void RefreshWithoutChangedItems(Mod mod) + { + UpdateTags(mod); + UpdateCounts(mod); + } } diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs index 542b14d2..a081f7bc 100644 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -30,9 +30,9 @@ public sealed class SubMod : ISubMod public bool IsDefault => GroupIdx < 0; - public Dictionary FileData = new(); - public Dictionary FileSwapData = new(); - public HashSet ManipulationData = new(); + public Dictionary FileData = []; + public Dictionary FileSwapData = []; + public HashSet ManipulationData = []; public SubMod(IMod parentMod) => ParentMod = parentMod; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index ec433113..54f7a16f 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -91,8 +91,9 @@ - - + + + diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index c2910b51..d31a08ae 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -210,26 +210,26 @@ public class ItemSwapTab : IDisposable, ITab break; case SwapType.Hair when _targetId > 0 && _sourceId > 0: _swapData.LoadCustomization(_metaFileManager, BodySlot.Hair, Names.CombinedRace(_currentGender, _currentRace), - (SetId)_sourceId, - (SetId)_targetId, + (PrimaryId)_sourceId, + (PrimaryId)_targetId, _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Face when _targetId > 0 && _sourceId > 0: _swapData.LoadCustomization(_metaFileManager, BodySlot.Face, Names.CombinedRace(_currentGender, _currentRace), - (SetId)_sourceId, - (SetId)_targetId, + (PrimaryId)_sourceId, + (PrimaryId)_targetId, _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Ears when _targetId > 0 && _sourceId > 0: _swapData.LoadCustomization(_metaFileManager, BodySlot.Ear, Names.CombinedRace(_currentGender, ModelRace.Viera), - (SetId)_sourceId, - (SetId)_targetId, + (PrimaryId)_sourceId, + (PrimaryId)_targetId, _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Tail when _targetId > 0 && _sourceId > 0: _swapData.LoadCustomization(_metaFileManager, BodySlot.Tail, Names.CombinedRace(_currentGender, _currentRace), - (SetId)_sourceId, - (SetId)_targetId, + (PrimaryId)_sourceId, + (PrimaryId)_targetId, _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Weapon: break; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index c307f6f4..cf65901e 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -169,6 +169,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Wed, 20 Dec 2023 16:43:30 +0100 Subject: [PATCH 0258/1381] Move signatures and add Footsteps. --- Penumbra.GameData | 2 +- .../PathResolving/AnimationHookService.cs | 26 ++++++++++++++----- .../Structs/ModelResourceHandleUtility.cs | 3 ++- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index bee73fbe..4d3570fd 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit bee73fbe1e263d81067029ad97c8e4a263c88147 +Subproject commit 4d3570fd47d78dbc49cf5e41fd3545a533ef9e81 diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs index 7fa0ed35..d13ef7f2 100644 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ b/Penumbra/Interop/PathResolving/AnimationHookService.cs @@ -55,6 +55,7 @@ public unsafe class AnimationHookService : IDisposable _unkParasolAnimationHook.Enable(); _dismountHook.Enable(); _apricotListenerSoundPlayHook.Enable(); + _footStepHook.Enable(); } public bool HandleFiles(ResourceType type, Utf8GamePath _, out ResolveData resolveData) @@ -113,6 +114,7 @@ public unsafe class AnimationHookService : IDisposable _unkParasolAnimationHook.Dispose(); _dismountHook.Dispose(); _apricotListenerSoundPlayHook.Dispose(); + _footStepHook.Dispose(); } /// Characters load some of their voice lines or whatever with this function. @@ -324,7 +326,7 @@ public unsafe class AnimationHookService : IDisposable private delegate void UnkMountAnimationDelegate(DrawObject* drawObject, uint unk1, byte unk2, uint unk3); - [Signature("48 89 5C 24 ?? 48 89 6C 24 ?? 89 54 24", DetourName = nameof(UnkMountAnimationDetour))] + [Signature(Sigs.UnkMountAnimation, DetourName = nameof(UnkMountAnimationDetour))] private readonly Hook _unkMountAnimationHook = null!; private void UnkMountAnimationDetour(DrawObject* drawObject, uint unk1, byte unk2, uint unk3) @@ -335,10 +337,9 @@ public unsafe class AnimationHookService : IDisposable _animationLoadData.Value = last; } - private delegate void UnkParasolAnimationDelegate(DrawObject* drawObject, int unk1); - [Signature("48 89 5C 24 ?? 48 89 74 24 ?? 89 54 24 ?? 57 48 83 EC ?? 48 8B F9", DetourName = nameof(UnkParasolAnimationDetour))] + [Signature(Sigs.UnkParasolAnimation, DetourName = nameof(UnkParasolAnimationDetour))] private readonly Hook _unkParasolAnimationHook = null!; private void UnkParasolAnimationDetour(DrawObject* drawObject, int unk1) @@ -347,9 +348,9 @@ public unsafe class AnimationHookService : IDisposable _animationLoadData.Value = _collectionResolver.IdentifyCollection(drawObject, true); _unkParasolAnimationHook.Original(drawObject, unk1); _animationLoadData.Value = last; - } + } - [Signature("E8 ?? ?? ?? ?? F6 43 ?? ?? 74 ?? 48 8B CB", DetourName = nameof(DismountDetour))] + [Signature(Sigs.Dismount, DetourName = nameof(DismountDetour))] private readonly Hook _dismountHook = null!; private delegate void DismountDelegate(nint a1, nint a2); @@ -375,7 +376,7 @@ public unsafe class AnimationHookService : IDisposable _animationLoadData.Value = last; } - [Signature("48 89 6C 24 ?? 41 54 41 56 41 57 48 81 EC", DetourName = nameof(ApricotListenerSoundPlayDetour))] + [Signature(Sigs.ApricotListenerSoundPlay, DetourName = nameof(ApricotListenerSoundPlayDetour))] private readonly Hook _apricotListenerSoundPlayHook = null!; private delegate nint ApricotListenerSoundPlayDelegate(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6); @@ -406,4 +407,17 @@ public unsafe class AnimationHookService : IDisposable _animationLoadData.Value = last; return ret; } + + private delegate void FootStepDelegate(GameObject* gameObject, int id, int unk); + + [Signature(Sigs.FootStepSound, DetourName = nameof(FootStepDetour))] + private readonly Hook _footStepHook = null!; + + private void FootStepDetour(GameObject* gameObject, int id, int unk) + { + var last = _animationLoadData.Value; + _animationLoadData.Value = _collectionResolver.IdentifyCollection(gameObject, true); + _footStepHook.Original(gameObject, id, unk); + _animationLoadData.Value = last; + } } diff --git a/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs b/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs index 008cd59a..bcfa2fa2 100644 --- a/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs +++ b/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Penumbra.GameData; namespace Penumbra.Interop.Structs; @@ -10,7 +11,7 @@ public class ModelResourceHandleUtility public ModelResourceHandleUtility(IGameInteropProvider interop) => interop.InitializeFromAttributes(this); - [Signature("E8 ?? ?? ?? ?? 44 8B CD 48 89 44 24")] + [Signature(Sigs.GetMaterialFileNameBySlot)] private static nint _getMaterialFileNameBySlot = nint.Zero; public static unsafe byte* GetMaterialFileNameBySlot(ModelResourceHandle* handle, uint slot) From f022d2be6480f459e2163f8dc8bfff50c288636f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Dec 2023 18:47:30 +0100 Subject: [PATCH 0259/1381] Rework DalamudServices, --- OtterGui | 2 +- Penumbra/Api/IpcTester.cs | 85 ++++++++++--------- Penumbra/Api/PenumbraApi.cs | 47 +++++----- Penumbra/Api/PenumbraIpcProviders.cs | 8 +- Penumbra/Import/Textures/TexFileParser.cs | 6 +- .../ResourceLoading/CreateFileWHook.cs | 6 +- Penumbra/Penumbra.cs | 60 +++++++------ Penumbra/Penumbra.json | 2 +- Penumbra/Services/DalamudServices.cs | 81 +++++++----------- .../{ServiceManager.cs => ServiceManagerA.cs} | 74 ++++++---------- Penumbra/Services/ValidityChecker.cs | 2 +- .../ModEditWindow.Materials.MtrlTab.cs | 8 +- .../ModEditWindow.QuickImport.cs | 2 +- .../AdvancedWindow/ModEditWindow.Textures.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 20 +++-- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 4 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 24 +++--- Penumbra/UI/Tabs/SettingsTab.cs | 42 +++++---- Penumbra/packages.lock.json | 5 +- 19 files changed, 230 insertions(+), 250 deletions(-) rename Penumbra/Services/{ServiceManager.cs => ServiceManagerA.cs} (72%) diff --git a/OtterGui b/OtterGui index ac88abfe..197d23ee 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit ac88abfe9eb0bb5d03aec092dc8f4db642ecbd6a +Subproject commit 197d23eee167c232000f22ef40a7a2bded913b6c diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index f7b740b9..aea95156 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -40,23 +40,24 @@ public class IpcTester : IDisposable private readonly Temporary _temporary; private readonly ResourceTree _resourceTree; - public IpcTester(Configuration config, DalamudServices dalamud, PenumbraIpcProviders ipcProviders, ModManager modManager, - CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService) + public IpcTester(Configuration config, DalamudPluginInterface pi, IObjectTable objects, IClientState clientState, + PenumbraIpcProviders ipcProviders, ModManager modManager, CollectionManager collections, TempModManager tempMods, + TempCollectionManager tempCollections, SaveService saveService) { _ipcProviders = ipcProviders; - _pluginState = new PluginState(dalamud.PluginInterface); - _ipcConfiguration = new IpcConfiguration(dalamud.PluginInterface); - _ui = new Ui(dalamud.PluginInterface); - _redrawing = new Redrawing(dalamud); - _gameState = new GameState(dalamud.PluginInterface); - _resolve = new Resolve(dalamud.PluginInterface); - _collections = new Collections(dalamud.PluginInterface); - _meta = new Meta(dalamud.PluginInterface); - _mods = new Mods(dalamud.PluginInterface); - _modSettings = new ModSettings(dalamud.PluginInterface); - _editing = new Editing(dalamud.PluginInterface); - _temporary = new Temporary(dalamud.PluginInterface, modManager, collections, tempMods, tempCollections, saveService, config); - _resourceTree = new ResourceTree(dalamud.PluginInterface, dalamud.Objects); + _pluginState = new PluginState(pi); + _ipcConfiguration = new IpcConfiguration(pi); + _ui = new Ui(pi); + _redrawing = new Redrawing(pi, objects, clientState); + _gameState = new GameState(pi); + _resolve = new Resolve(pi); + _collections = new Collections(pi); + _meta = new Meta(pi); + _mods = new Mods(pi); + _modSettings = new ModSettings(pi); + _editing = new Editing(pi); + _temporary = new Temporary(pi, modManager, collections, tempMods, tempCollections, saveService, config); + _resourceTree = new ResourceTree(pi, objects); UnsubscribeEvents(); } @@ -398,17 +399,21 @@ public class IpcTester : IDisposable private class Redrawing { - private readonly DalamudServices _dalamud; + private readonly DalamudPluginInterface _pi; + private readonly IClientState _clientState; + private readonly IObjectTable _objects; public readonly EventSubscriber Redrawn; private string _redrawName = string.Empty; private int _redrawIndex = 0; private string _lastRedrawnString = "None"; - public Redrawing(DalamudServices dalamud) + public Redrawing(DalamudPluginInterface pi, IObjectTable objects, IClientState clientState) { - _dalamud = dalamud; - Redrawn = Ipc.GameObjectRedrawn.Subscriber(_dalamud.PluginInterface, SetLastRedrawn); + _pi = pi; + _objects = objects; + _clientState = clientState; + Redrawn = Ipc.GameObjectRedrawn.Subscriber(_pi, SetLastRedrawn); } public void Draw() @@ -426,25 +431,25 @@ public class IpcTester : IDisposable ImGui.InputTextWithHint("##redrawName", "Name...", ref _redrawName, 32); ImGui.SameLine(); if (ImGui.Button("Redraw##Name")) - Ipc.RedrawObjectByName.Subscriber(_dalamud.PluginInterface).Invoke(_redrawName, RedrawType.Redraw); + Ipc.RedrawObjectByName.Subscriber(_pi).Invoke(_redrawName, RedrawType.Redraw); DrawIntro(Ipc.RedrawObject.Label, "Redraw Player Character"); - if (ImGui.Button("Redraw##pc") && _dalamud.ClientState.LocalPlayer != null) - Ipc.RedrawObject.Subscriber(_dalamud.PluginInterface).Invoke(_dalamud.ClientState.LocalPlayer, RedrawType.Redraw); + if (ImGui.Button("Redraw##pc") && _clientState.LocalPlayer != null) + Ipc.RedrawObject.Subscriber(_pi).Invoke(_clientState.LocalPlayer, RedrawType.Redraw); DrawIntro(Ipc.RedrawObjectByIndex.Label, "Redraw by Index"); var tmp = _redrawIndex; ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _dalamud.Objects.Length)) - _redrawIndex = Math.Clamp(tmp, 0, _dalamud.Objects.Length); + if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.Length)) + _redrawIndex = Math.Clamp(tmp, 0, _objects.Length); ImGui.SameLine(); if (ImGui.Button("Redraw##Index")) - Ipc.RedrawObjectByIndex.Subscriber(_dalamud.PluginInterface).Invoke(_redrawIndex, RedrawType.Redraw); + Ipc.RedrawObjectByIndex.Subscriber(_pi).Invoke(_redrawIndex, RedrawType.Redraw); DrawIntro(Ipc.RedrawAll.Label, "Redraw All"); if (ImGui.Button("Redraw##All")) - Ipc.RedrawAll.Subscriber(_dalamud.PluginInterface).Invoke(RedrawType.Redraw); + Ipc.RedrawAll.Subscriber(_pi).Invoke(RedrawType.Redraw); DrawIntro(Ipc.GameObjectRedrawn.Label, "Last Redrawn Object:"); ImGui.TextUnformatted(_lastRedrawnString); @@ -453,12 +458,12 @@ public class IpcTester : IDisposable private void SetLastRedrawn(IntPtr address, int index) { if (index < 0 - || index > _dalamud.Objects.Length + || index > _objects.Length || address == IntPtr.Zero - || _dalamud.Objects[index]?.Address != address) + || _objects[index]?.Address != address) _lastRedrawnString = "Invalid"; - _lastRedrawnString = $"{_dalamud.Objects[index]!.Name} (0x{address:X}, {index})"; + _lastRedrawnString = $"{_objects[index]!.Name} (0x{address:X}, {index})"; } } @@ -1529,7 +1534,7 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourceTrees")) { var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourceTrees.Subscriber(_pi); + var subscriber = Ipc.GetGameObjectResourceTrees.Subscriber(_pi); _stopwatch.Restart(); var trees = subscriber.Invoke(_withUIData, gameObjects); @@ -1563,7 +1568,7 @@ public class IpcTester : IDisposable DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType, _lastCallDuration); DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, _lastCallDuration); - DrawPopup(nameof(Ipc.GetGameObjectResourceTrees), ref _lastGameObjectResourceTrees, DrawResourceTrees, _lastCallDuration); + DrawPopup(nameof(Ipc.GetGameObjectResourceTrees), ref _lastGameObjectResourceTrees, DrawResourceTrees, _lastCallDuration); DrawPopup(nameof(Ipc.GetPlayerResourceTrees), ref _lastPlayerResourceTrees, DrawResourceTrees!, _lastCallDuration); } @@ -1695,9 +1700,10 @@ public class IpcTester : IDisposable { ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.5f); } - ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); - ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); - ImGui.TableSetupColumn("Object Address", ImGuiTableColumnFlags.WidthStretch, 0.2f); + + ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Object Address", ImGuiTableColumnFlags.WidthStretch, 0.2f); ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.2f); ImGui.TableHeadersRow(); @@ -1707,10 +1713,10 @@ public class IpcTester : IDisposable ImGui.TableNextColumn(); var hasChildren = node.Children.Any(); using var treeNode = ImRaii.TreeNode( - $"{(_withUIData ? (node.Name ?? "Unknown") : node.Type)}##{node.ObjectAddress:X8}", - hasChildren ? - ImGuiTreeNodeFlags.SpanFullWidth : - (ImGuiTreeNodeFlags.SpanFullWidth | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen)); + $"{(_withUIData ? node.Name ?? "Unknown" : node.Type)}##{node.ObjectAddress:X8}", + hasChildren + ? ImGuiTreeNodeFlags.SpanFullWidth + : ImGuiTreeNodeFlags.SpanFullWidth | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen); if (_withUIData) { ImGui.TableNextColumn(); @@ -1718,6 +1724,7 @@ public class IpcTester : IDisposable ImGui.TableNextColumn(); TextUnformattedMono(node.Icon.ToString()); } + ImGui.TableNextColumn(); ImGui.TextUnformatted(node.GamePath ?? "Unknown"); ImGui.TableNextColumn(); @@ -1728,10 +1735,8 @@ public class IpcTester : IDisposable TextUnformattedMono($"0x{node.ResourceHandle:X8}"); if (treeNode) - { foreach (var child in node.Children) DrawNode(child); - } } foreach (var node in tree.Nodes) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 97e69089..b7a46ae2 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -1,4 +1,5 @@ using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.Plugin.Services; using Lumina.Data; using Newtonsoft.Json; using OtterGui; @@ -88,11 +89,13 @@ public class PenumbraApi : IDisposable, IPenumbraApi private CommunicatorService _communicator; private Lumina.GameData? _lumina; + private IDataManager _gameData; + private IFramework _framework; + private IObjectTable _objects; private ModManager _modManager; private ResourceLoader _resourceLoader; private Configuration _config; private CollectionManager _collectionManager; - private DalamudServices _dalamud; private TempCollectionManager _tempCollections; private TempModManager _tempMods; private ActorManager _actors; @@ -106,18 +109,20 @@ public class PenumbraApi : IDisposable, IPenumbraApi private TextureManager _textureManager; private ResourceTreeFactory _resourceTreeFactory; - public unsafe PenumbraApi(CommunicatorService communicator, ModManager modManager, ResourceLoader resourceLoader, - Configuration config, CollectionManager collectionManager, DalamudServices dalamud, TempCollectionManager tempCollections, - TempModManager tempMods, ActorManager actors, CollectionResolver collectionResolver, CutsceneService cutsceneService, - ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, ModFileSystem modFileSystem, - ConfigWindow configWindow, TextureManager textureManager, ResourceTreeFactory resourceTreeFactory) + public unsafe PenumbraApi(CommunicatorService communicator, IDataManager gameData, IFramework framework, IObjectTable objects, + ModManager modManager, ResourceLoader resourceLoader, Configuration config, CollectionManager collectionManager, + TempCollectionManager tempCollections, TempModManager tempMods, ActorManager actors, CollectionResolver collectionResolver, + CutsceneService cutsceneService, ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, + ModFileSystem modFileSystem, ConfigWindow configWindow, TextureManager textureManager, ResourceTreeFactory resourceTreeFactory) { _communicator = communicator; + _gameData = gameData; + _framework = framework; + _objects = objects; _modManager = modManager; _resourceLoader = resourceLoader; _config = config; _collectionManager = collectionManager; - _dalamud = dalamud; _tempCollections = tempCollections; _tempMods = tempMods; _actors = actors; @@ -130,7 +135,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _configWindow = configWindow; _textureManager = textureManager; _resourceTreeFactory = resourceTreeFactory; - _lumina = _dalamud.GameData.GameData; + _lumina = gameData.GameData; _resourceLoader.ResourceLoaded += OnResourceLoaded; _communicator.ModPathChanged.Subscribe(ModPathChangeSubscriber, ModPathChanged.Priority.Api); @@ -153,7 +158,6 @@ public class PenumbraApi : IDisposable, IPenumbraApi _resourceLoader = null!; _config = null!; _collectionManager = null!; - _dalamud = null!; _tempCollections = null!; _tempMods = null!; _actors = null!; @@ -166,6 +170,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _configWindow = null!; _textureManager = null!; _resourceTreeFactory = null!; + _framework = null!; } public event ChangedItemClick? ChangedItemClicked @@ -399,7 +404,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi return await Task.Run(async () => { - var playerCollection = await _dalamud.Framework.RunOnFrameworkThread(_collectionResolver.PlayerCollection).ConfigureAwait(false); + var playerCollection = await _framework.RunOnFrameworkThread(_collectionResolver.PlayerCollection).ConfigureAwait(false); var forwardTask = Task.Run(() => { var forwardRet = new string[forward.Length]; @@ -851,7 +856,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); - if (!ActorManager.VerifyPlayerName(character.AsSpan()) || tag.Length == 0) + if (!ActorIdentifierFactory.VerifyPlayerName(character.AsSpan()) || tag.Length == 0) return (PenumbraApiEc.InvalidArgument, string.Empty); var identifier = NameToIdentifier(character, ushort.MaxValue); @@ -889,10 +894,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); - if (actorIndex < 0 || actorIndex >= _dalamud.Objects.Length) + if (actorIndex < 0 || actorIndex >= _objects.Length) return PenumbraApiEc.InvalidArgument; - var identifier = _actors.FromObject(_dalamud.Objects[actorIndex], false, false, true); + var identifier = _actors.FromObject(_objects[actorIndex], false, false, true); if (!identifier.IsValid) return PenumbraApiEc.InvalidArgument; @@ -1037,7 +1042,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects) { - var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); + var characters = gameObjects.Select(index => _objects[index]).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, 0); var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); @@ -1055,7 +1060,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ResourceType type, bool withUIData, params ushort[] gameObjects) { - var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); + var characters = gameObjects.Select(index => _objects[index]).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); @@ -1074,7 +1079,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public Ipc.ResourceTree?[] GetGameObjectResourceTrees(bool withUIData, params ushort[] gameObjects) { - var characters = gameObjects.Select(index => _dalamud.Objects[index]).OfType(); + var characters = gameObjects.Select(index => _objects[index]).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); @@ -1126,10 +1131,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi private unsafe bool AssociatedCollection(int gameObjectIdx, out ModCollection collection) { collection = _collectionManager.Active.Default; - if (gameObjectIdx < 0 || gameObjectIdx >= _dalamud.Objects.Length) + if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Length) return false; - var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_dalamud.Objects.GetObjectAddress(gameObjectIdx); + var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_objects.GetObjectAddress(gameObjectIdx); var data = _collectionResolver.IdentifyCollection(ptr, false); if (data.Valid) collection = data.ModCollection; @@ -1140,10 +1145,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe ActorIdentifier AssociatedIdentifier(int gameObjectIdx) { - if (gameObjectIdx < 0 || gameObjectIdx >= _dalamud.Objects.Length) + if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Length) return ActorIdentifier.Invalid; - var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_dalamud.Objects.GetObjectAddress(gameObjectIdx); + var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_objects.GetObjectAddress(gameObjectIdx); return _actors.FromObject(ptr, out _, false, true, true); } @@ -1168,7 +1173,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi if (Path.IsPathRooted(resolvedPath)) return _lumina?.GetFileFromDisk(resolvedPath); - return _dalamud.GameData.GetFile(resolvedPath); + return _gameData.GetFile(resolvedPath); } catch (Exception e) { diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index a564588b..1df90dd9 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -15,7 +15,6 @@ using CurrentSettings = ValueTuple GetGameObjectResourceTrees; internal readonly FuncProvider> GetPlayerResourceTrees; - public PenumbraIpcProviders(DalamudServices dalamud, IPenumbraApi api, ModManager modManager, CollectionManager collections, + public PenumbraIpcProviders(DalamudPluginInterface pi, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) { - var pi = dalamud.PluginInterface; Api = api; // Plugin State @@ -260,15 +258,11 @@ public class PenumbraIpcProviders : IDisposable GetGameObjectResourceTrees = Ipc.GetGameObjectResourceTrees.Provider(pi, Api.GetGameObjectResourceTrees); GetPlayerResourceTrees = Ipc.GetPlayerResourceTrees.Provider(pi, Api.GetPlayerResourceTrees); - Tester = new IpcTester(config, dalamud, this, modManager, collections, tempMods, tempCollections, saveService); - Initialized.Invoke(); } public void Dispose() { - Tester.Dispose(); - // Plugin State Initialized.Dispose(); ApiVersion.Dispose(); diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 629cdff5..6f854022 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -44,8 +44,8 @@ public static class TexFileParser if (offset == 0) return i; - var requiredSize = width * height * bits / 8; - if (offset + requiredSize > data.Length) + var Size = width * height * bits / 8; + if (offset + Size > data.Length) return i; var diff = offset - lastOffset; @@ -55,7 +55,7 @@ public static class TexFileParser width = Math.Max(width / 2, minSize); height = Math.Max(height / 2, minSize); lastOffset = offset; - lastSize = requiredSize; + lastSize = Size; } return 13; diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs index b77ac1e0..7d94b1d5 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs @@ -13,7 +13,7 @@ namespace Penumbra.Interop.ResourceLoading; /// public unsafe class CreateFileWHook : IDisposable { - public const int RequiredSize = 28; + public const int Size = 28; public CreateFileWHook(IGameInteropProvider interop) { @@ -57,8 +57,8 @@ public unsafe class CreateFileWHook : IDisposable ptr[22] = (byte)(l >> 16); ptr[24] = (byte)(l >> 24); - ptr[RequiredSize - 2] = 0; - ptr[RequiredSize - 1] = 0; + ptr[Size - 2] = 0; + ptr[Size - 1] = 0; } public void Dispose() diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 9be40e66..900d2770 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -1,10 +1,9 @@ using Dalamud.Plugin; -using Dalamud.Plugin.Services; using ImGuiNET; using Lumina.Excel.GeneratedSheets; -using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Log; +using OtterGui.Services; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -19,7 +18,6 @@ using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; -using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; using Penumbra.UI; @@ -48,40 +46,40 @@ public class Penumbra : IDalamudPlugin private PenumbraWindowSystem? _windowSystem; private bool _disposed; - private readonly ServiceProvider _services; + private readonly ServiceManager _services; public Penumbra(DalamudPluginInterface pluginInterface) { try { - _services = ServiceManager.CreateProvider(this, pluginInterface, Log); - Messager = _services.GetRequiredService(); - _validityChecker = _services.GetRequiredService(); - var startup = _services.GetRequiredService().GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool s) + _services = ServiceManagerA.CreateProvider(this, pluginInterface, Log); + Messager = _services.GetService(); + _validityChecker = _services.GetService(); + var startup = _services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool s) ? s.ToString() : "Unknown"; Log.Information( $"Loading Penumbra Version {_validityChecker.Version}, Commit #{_validityChecker.CommitHash} with Waiting For Plugins: {startup}..."); - _services.GetRequiredService(); // Initialize because not required anywhere else. - _config = _services.GetRequiredService(); - _characterUtility = _services.GetRequiredService(); - _tempMods = _services.GetRequiredService(); - _residentResources = _services.GetRequiredService(); - _services.GetRequiredService(); // Initialize because not required anywhere else. - _modManager = _services.GetRequiredService(); - _collectionManager = _services.GetRequiredService(); - _tempCollections = _services.GetRequiredService(); - _redrawService = _services.GetRequiredService(); - _communicatorService = _services.GetRequiredService(); - _services.GetRequiredService(); // Initialize because not required anywhere else. - _services.GetRequiredService(); // Initialize because not required anywhere else. - _services.GetRequiredService(); // Initialize because not required anywhere else. + _services.GetService(); // Initialize because not required anywhere else. + _config = _services.GetService(); + _characterUtility = _services.GetService(); + _tempMods = _services.GetService(); + _residentResources = _services.GetService(); + _services.GetService(); // Initialize because not required anywhere else. + _modManager = _services.GetService(); + _collectionManager = _services.GetService(); + _tempCollections = _services.GetService(); + _redrawService = _services.GetService(); + _communicatorService = _services.GetService(); + _services.GetService(); // Initialize because not required anywhere else. + _services.GetService(); // Initialize because not required anywhere else. + _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); - _services.GetRequiredService(); + _services.GetService(); - _services.GetRequiredService(); + _services.GetService(); - _services.GetRequiredService(); // Initialize before Interface. + _services.GetService(); // Initialize before Interface. SetupInterface(); SetupApi(); @@ -104,8 +102,8 @@ public class Penumbra : IDalamudPlugin private void SetupApi() { - var api = _services.GetRequiredService(); - _services.GetRequiredService(); + var api = _services.GetService(); + _services.GetService(); _communicatorService.ChangedItemHover.Subscribe(it => { if (it is (Item, FullEquipType)) @@ -123,9 +121,9 @@ public class Penumbra : IDalamudPlugin { AsyncTask.Run(() => { - var system = _services.GetRequiredService(); - system.Window.Setup(this, _services.GetRequiredService()); - _services.GetRequiredService(); + var system = _services.GetService(); + system.Window.Setup(this, _services.GetService()); + _services.GetService(); if (!_disposed) _windowSystem = system; else @@ -194,7 +192,7 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Auto-Deduplication: `** {_config.AutoDeduplicateOnImport}\n"); sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); sb.Append( - $"> **`Synchronous Load (Dalamud): `** {(_services.GetRequiredService().GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")}\n"); + $"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")}\n"); sb.Append( $"> **`Logging: `** Log: {_config.Ephemeral.EnableResourceLogging}, Watcher: {_config.Ephemeral.EnableResourceWatcher} ({_config.MaxResourceWatcherRecords})\n"); sb.Append($"> **`Use Ownership: `** {_config.UseOwnerNameForCharacterCollection}\n"); diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index d1682985..28dbc90d 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -9,7 +9,7 @@ "Tags": [ "modding" ], "DalamudApiLevel": 9, "LoadPriority": 69420, - "LoadRequiredState": 2, + "LoadState": 2, "LoadSync": true, "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudServices.cs index 99539c39..51fb1192 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudServices.cs @@ -5,15 +5,15 @@ using Dalamud.IoC; using Dalamud.Plugin; using Dalamud.Interface.DragDrop; using Dalamud.Plugin.Services; -using Microsoft.Extensions.DependencyInjection; +using OtterGui.Services; // ReSharper disable AutoPropertyCanBeMadeGetOnly.Local namespace Penumbra.Services; -public class DalamudServices +public class DalamudConfigService { - public DalamudServices(DalamudPluginInterface pluginInterface) + public DalamudConfigService(DalamudPluginInterface pluginInterface) { pluginInterface.Inject(this); try @@ -52,55 +52,6 @@ public class DalamudServices } } - public void AddServices(IServiceCollection services) - { - services.AddSingleton(PluginInterface); - services.AddSingleton(Commands); - services.AddSingleton(GameData); - services.AddSingleton(ClientState); - services.AddSingleton(Chat); - services.AddSingleton(Framework); - services.AddSingleton(Conditions); - services.AddSingleton(Targets); - services.AddSingleton(Objects); - services.AddSingleton(TitleScreenMenu); - services.AddSingleton(GameGui); - services.AddSingleton(KeyState); - services.AddSingleton(SigScanner); - services.AddSingleton(this); - services.AddSingleton(UiBuilder); - services.AddSingleton(DragDropManager); - services.AddSingleton(TextureProvider); - services.AddSingleton(TextureSubstitutionProvider); - services.AddSingleton(Interop); - services.AddSingleton(Log); - } - - // TODO remove static - // @formatter:off - [PluginService][RequiredVersion("1.0")] public DalamudPluginInterface PluginInterface { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ICommandManager Commands { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IDataManager GameData { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IClientState ClientState { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IChatGui Chat { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IFramework Framework { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ICondition Conditions { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ITargetManager Targets { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IObjectTable Objects { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ITitleScreenMenu TitleScreenMenu { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IGameGui GameGui { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IKeyState KeyState { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ISigScanner SigScanner { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IDragDropManager DragDropManager { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ITextureProvider TextureProvider { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public ITextureSubstitutionProvider TextureSubstitutionProvider { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IGameInteropProvider Interop { get; private set; } = null!; - [PluginService][RequiredVersion("1.0")] public IPluginLog Log { get; private set; } = null!; - // @formatter:on - - public UiBuilder UiBuilder - => PluginInterface.UiBuilder; - public const string WaitingForPluginsOption = "IsResumeGameAfterPluginLoad"; private readonly object? _dalamudConfig; @@ -164,3 +115,29 @@ public class DalamudServices } } } + +public static class DalamudServices +{ + public static void AddServices(ServiceManager services, DalamudPluginInterface pi) + { + services.AddExistingService(pi); + services.AddExistingService(pi.UiBuilder); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + services.AddDalamudService(pi); + } +} diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManagerA.cs similarity index 72% rename from Penumbra/Services/ServiceManager.cs rename to Penumbra/Services/ServiceManagerA.cs index 30f58701..410acfb9 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -7,11 +7,10 @@ using OtterGui.Services; using Penumbra.Api; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; -using Penumbra.GameData; using Penumbra.GameData.Actors; using Penumbra.GameData.Data; using Penumbra.GameData.DataContainers; -using Penumbra.GameData.DataContainers.Bases; +using Penumbra.GameData.Structs; using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; @@ -33,14 +32,13 @@ using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManage namespace Penumbra.Services; -public static class ServiceManager +public static class ServiceManagerA { - public static ServiceProvider CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log) + public static ServiceManager CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log) { - var services = new ServiceCollection() - .AddSingleton(log) - .AddSingleton(penumbra) - .AddDalamud(pi) + var services = new ServiceManager(log) + .AddExistingService(log) + .AddExistingService(penumbra) .AddMeta() .AddGameData() .AddInterop() @@ -51,37 +49,15 @@ public static class ServiceManager .AddResolvers() .AddInterface() .AddModEditor() - .AddApi() - .AddDataContainers() - .AddAsyncServices(); - - return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); - } - - private static IServiceCollection AddDalamud(this IServiceCollection services, DalamudPluginInterface pi) - { - var dalamud = new DalamudServices(pi); - dalamud.AddServices(services); + .AddApi(); + services.AddIServices(typeof(EquipItem).Assembly); + services.AddIServices(typeof(Penumbra).Assembly); + DalamudServices.AddServices(services, pi); + services.CreateProvider(); return services; } - private static IServiceCollection AddDataContainers(this IServiceCollection services) - { - foreach (var type in typeof(IDataContainer).Assembly.GetExportedTypes() - .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IDataContainer)))) - services.AddSingleton(type); - return services; - } - - private static IServiceCollection AddAsyncServices(this IServiceCollection services) - { - foreach (var type in typeof(ActorManager).Assembly.GetExportedTypes() - .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IService)))) - services.AddSingleton(type); - return services; - } - - private static IServiceCollection AddMeta(this IServiceCollection services) + private static ServiceManager AddMeta(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -89,15 +65,16 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); - private static IServiceCollection AddGameData(this IServiceCollection services) + private static ServiceManager AddGameData(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton(); - private static IServiceCollection AddInterop(this IServiceCollection services) + private static ServiceManager AddInterop(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -117,12 +94,12 @@ public static class ServiceManager .AddSingleton() .AddSingleton(); - private static IServiceCollection AddConfiguration(this IServiceCollection services) - => services.AddTransient() + private static ServiceManager AddConfiguration(this ServiceManager services) + => services.AddSingleton() .AddSingleton() .AddSingleton(); - private static IServiceCollection AddCollections(this IServiceCollection services) + private static ServiceManager AddCollections(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -132,7 +109,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton(); - private static IServiceCollection AddMods(this IServiceCollection services) + private static ServiceManager AddMods(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -144,14 +121,14 @@ public static class ServiceManager .AddSingleton() .AddSingleton(s => (ModStorage)s.GetRequiredService()); - private static IServiceCollection AddResources(this IServiceCollection services) + private static ServiceManager AddResources(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton(); - private static IServiceCollection AddResolvers(this IServiceCollection services) + private static ServiceManager AddResolvers(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -162,7 +139,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton(); - private static IServiceCollection AddInterface(this IServiceCollection services) + private static ServiceManager AddInterface(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -200,7 +177,7 @@ public static class ServiceManager .AddSingleton() .AddSingleton(p => new Diagnostics(p)); - private static IServiceCollection AddModEditor(this IServiceCollection services) + private static ServiceManager AddModEditor(this ServiceManager services) => services.AddSingleton() .AddSingleton() .AddSingleton() @@ -212,10 +189,11 @@ public static class ServiceManager .AddSingleton() .AddSingleton(); - private static IServiceCollection AddApi(this IServiceCollection services) + private static ServiceManager AddApi(this ServiceManager services) => services.AddSingleton() .AddSingleton(x => x.GetRequiredService()) .AddSingleton() .AddSingleton() + .AddSingleton() .AddSingleton(); } diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index 0688850b..7287938c 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -15,7 +15,7 @@ public class ValidityChecker public readonly bool IsNotInstalledPenumbra; public readonly bool IsValidSourceRepo; - public readonly List ImcExceptions = new(); + public readonly List ImcExceptions = []; public readonly string Version; public readonly string CommitHash; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 954e9b0f..09e22d67 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -103,7 +103,7 @@ public partial class ModEditWindow LoadedShpkPath = path; var data = LoadedShpkPath.IsRooted ? File.ReadAllBytes(LoadedShpkPath.FullName) - : _edit._dalamud.GameData.GetFile(LoadedShpkPath.InternalName.ToString())?.Data; + : _edit._gameData.GetFile(LoadedShpkPath.InternalName.ToString())?.Data; AssociatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); LoadedShpkPathName = path.ToPath(); } @@ -457,13 +457,13 @@ public partial class ModEditWindow var foundMaterials = new HashSet(); foreach (var materialInfo in instances) { - var material = materialInfo.GetDrawObjectMaterial(_edit._dalamud.Objects); + var material = materialInfo.GetDrawObjectMaterial(_edit._objects); if (foundMaterials.Contains((nint)material)) continue; try { - MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._dalamud.Objects, materialInfo)); + MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._objects, materialInfo)); foundMaterials.Add((nint)material); } catch (InvalidOperationException) @@ -481,7 +481,7 @@ public partial class ModEditWindow { try { - ColorTablePreviewers.Add(new LiveColorTablePreviewer(_edit._dalamud.Objects, _edit._dalamud.Framework, materialInfo)); + ColorTablePreviewers.Add(new LiveColorTablePreviewer(_edit._objects, _edit._framework, materialInfo)); } catch (InvalidOperationException) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 64457c25..c9cd3d06 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -71,7 +71,7 @@ public partial class ModEditWindow } else { - var file = _dalamud.GameData.GetFile(path); + var file = _gameData.GetFile(path); writable = file == null ? null : new RawGameFileWritable(file); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index a3b17848..e9facdf4 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -219,7 +219,7 @@ public partial class ModEditWindow if (tex.Path != path) return; - _dalamud.Framework.RunOnFrameworkThread(() => tex.Reload(_textures)); + _framework.RunOnFrameworkThread(() => tex.Reload(_textures)); }); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index db9201ca..9b127fe4 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -36,7 +36,6 @@ public partial class ModEditWindow : Window, IDisposable private readonly ModEditor _editor; private readonly Configuration _config; private readonly ItemSwapTab _itemSwapTab; - private readonly DalamudServices _dalamud; private readonly MetaFileManager _metaFileManager; private readonly ActiveCollections _activeCollections; private readonly StainService _stainService; @@ -44,6 +43,9 @@ public partial class ModEditWindow : Window, IDisposable private readonly CommunicatorService _communicator; private readonly IDragDropManager _dragDropManager; private readonly GameEventManager _gameEvents; + private readonly IDataManager _gameData; + private readonly IFramework _framework; + private readonly IObjectTable _objects; private Mod? _mod; private Vector2 _iconSize = Vector2.Zero; @@ -562,37 +564,41 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, - StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, + StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, GameEventManager gameEvents, - ChangedItemDrawer changedItemDrawer) + ChangedItemDrawer changedItemDrawer, IObjectTable objects, IFramework framework) : base(WindowBaseLabel) { _performance = performance; _itemSwapTab = itemSwapTab; + _gameData = gameData; _config = config; _editor = editor; _metaFileManager = metaFileManager; _stainService = stainService; _activeCollections = activeCollections; - _dalamud = dalamud; _modMergeTab = modMergeTab; _communicator = communicator; _dragDropManager = dragDropManager; _textures = textures; _fileDialog = fileDialog; _gameEvents = gameEvents; + _objects = objects; + _framework = framework; _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlFile(bytes)); + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, + (bytes, _, _) => new MdlFile(bytes)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", - () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, + () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, + () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); _resourceTreeFactory = resourceTreeFactory; - _quickImportViewer = + _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ModEditWindow); } diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index cf65901e..8f12afbb 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -190,9 +190,9 @@ public sealed class ModFileSystemSelector : FileSystemSelector Label @@ -417,7 +421,7 @@ public class DebugTab : Window, ITab DrawSpecial("Current Card", _actors.GetCardPlayer()); DrawSpecial("Current Glamour", _actors.GetGlamourPlayer()); - foreach (var obj in _dalamud.Objects) + foreach (var obj in _objects) { ImGuiUtil.DrawTableColumn($"{((GameObject*)obj.Address)->ObjectIndex}"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); @@ -827,7 +831,7 @@ public class DebugTab : Window, ITab /// Draw information about the models, materials and resources currently loaded by the local player. private unsafe void DrawPlayerModelInfo() { - var player = _dalamud.ClientState.LocalPlayer; + var player = _clientState.LocalPlayer; var name = player?.Name.ToString() ?? "NULL"; if (!ImGui.CollapsingHeader($"Player Model Info: {name}##Draw") || player == null) return; @@ -952,11 +956,11 @@ public class DebugTab : Window, ITab { if (!ImGui.CollapsingHeader("IPC")) { - _ipc.Tester.UnsubscribeEvents(); + _ipcTester.UnsubscribeEvents(); return; } - _ipc.Tester.Draw(); + _ipcTester.Draw(); } /// Helper to print a property and its value in a 2-column table. diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 104f8d91..a03e7b87 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -1,5 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Components; +using Dalamud.Plugin; +using Dalamud.Plugin.Services; using Dalamud.Utility; using ImGuiNET; using OtterGui; @@ -33,19 +35,23 @@ public class SettingsTab : ITab private readonly ModFileSystemSelector _selector; private readonly CharacterUtility _characterUtility; private readonly ResidentResourceManager _residentResources; - private readonly DalamudServices _dalamud; private readonly HttpApi _httpApi; private readonly DalamudSubstitutionProvider _dalamudSubstitutionProvider; private readonly FileCompactor _compactor; + private readonly DalamudConfigService _dalamudConfig; + private readonly DalamudPluginInterface _pluginInterface; + private readonly IDataManager _gameData; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; - public SettingsTab(Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, - FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, - ResidentResourceManager residentResources, DalamudServices dalamud, ModExportManager modExportManager, HttpApi httpApi, - DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor) + public SettingsTab(DalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, + Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, + CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, + DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, + IDataManager gameData) { + _pluginInterface = pluginInterface; _config = config; _fontReloader = fontReloader; _tutorial = tutorial; @@ -55,11 +61,12 @@ public class SettingsTab : ITab _selector = selector; _characterUtility = characterUtility; _residentResources = residentResources; - _dalamud = dalamud; _modExportManager = modExportManager; _httpApi = httpApi; _dalamudSubstitutionProvider = dalamudSubstitutionProvider; _compactor = compactor; + _dalamudConfig = dalamudConfig; + _gameData = gameData; if (_compactor.CanCompact) _compactor.Enabled = _config.UseFileSystemCompression; } @@ -164,14 +171,14 @@ public class SettingsTab : ITab if (IsSubPathOf(programFiles, newName) || IsSubPathOf(programFilesX86, newName)) return ("Path is not allowed to be in ProgramFiles.", false); - var dalamud = _dalamud.PluginInterface.ConfigDirectory.Parent!.Parent!; + var dalamud = _pluginInterface.ConfigDirectory.Parent!.Parent!; if (IsSubPathOf(dalamud.FullName, newName)) return ("Path is not allowed to be inside your Dalamud directories.", false); if (Functions.GetDownloadsFolder(out var downloads) && IsSubPathOf(downloads, newName)) return ("Path is not allowed to be inside your Downloads folder.", false); - var gameDir = _dalamud.GameData.GameData.DataPath.Parent!.Parent!.FullName; + var gameDir = _gameData.GameData.DataPath.Parent!.Parent!.FullName; if (IsSubPathOf(gameDir, newName)) return ("Path is not allowed to be inside your game folder.", false); @@ -368,21 +375,21 @@ public class SettingsTab : ITab v => { _config.HideUiWhenUiHidden = v; - _dalamud.UiBuilder.DisableUserUiHide = !v; + _pluginInterface.UiBuilder.DisableUserUiHide = !v; }); Checkbox("Hide Config Window when in Cutscenes", "Hide the Penumbra main window when you are currently watching a cutscene.", _config.HideUiInCutscenes, v => { - _config.HideUiInCutscenes = v; - _dalamud.UiBuilder.DisableCutsceneUiHide = !v; + _config.HideUiInCutscenes = v; + _pluginInterface.UiBuilder.DisableCutsceneUiHide = !v; }); Checkbox("Hide Config Window when in GPose", "Hide the Penumbra main window when you are currently in GPose mode.", _config.HideUiInGPose, v => { - _config.HideUiInGPose = v; - _dalamud.UiBuilder.DisableGposeUiHide = !v; + _config.HideUiInGPose = v; + _pluginInterface.UiBuilder.DisableGposeUiHide = !v; }); } @@ -847,7 +854,7 @@ public class SettingsTab : ITab /// Draw a checkbox that toggles the dalamud setting to wait for plugins on open. private void DrawWaitForPluginsReflection() { - if (!_dalamud.GetDalamudConfig(DalamudServices.WaitingForPluginsOption, out bool value)) + if (!_dalamudConfig.GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool value)) { using var disabled = ImRaii.Disabled(); Checkbox("Wait for Plugins on Startup (Disabled, can not access Dalamud Configuration)", string.Empty, false, v => { }); @@ -855,9 +862,12 @@ public class SettingsTab : ITab else { Checkbox("Wait for Plugins on Startup", - "Some mods need to change files that are loaded once when the game starts and never afterwards.\nThis can cause issues with Penumbra loading after the files are already loaded.\nThis setting causes the game to wait until certain plugins have finished loading, making those mods work (in the base collection).\n\nThis changes a setting in the Dalamud Configuration found at /xlsettings -> General.", + "Some mods need to change files that are loaded once when the game starts and never afterwards.\n" + + "This can cause issues with Penumbra loading after the files are already loaded.\n" + + "This setting causes the game to wait until certain plugins have finished loading, making those mods work (in the base collection).\n\n" + + "This changes a setting in the Dalamud Configuration found at /xlsettings -> General.", value, - v => _dalamud.SetDalamudConfig(DalamudServices.WaitingForPluginsOption, v, "doWaitForPluginsOnStartup")); + v => _dalamudConfig.SetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, v, "doWaitForPluginsOnStartup")); } } diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 9172bb60..16353828 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -73,7 +73,10 @@ } }, "ottergui": { - "type": "Project" + "type": "Project", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "[7.0.0, )" + } }, "penumbra.api": { "type": "Project" From 969ba38ffe01578472547430aeff6427b2291130 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Dec 2023 10:40:31 +0100 Subject: [PATCH 0260/1381] Prevent layer editing. --- Penumbra/Interop/PathResolving/PathResolver.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 12e5e280..6db97b63 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -51,6 +51,10 @@ public class PathResolver : IDisposable if (!_config.EnableMods) return (null, ResolveData.Invalid); + // Do not allow manipulating layers to prevent very obvious cheating and softlocks. + if (resourceType is ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb) + return (null, ResolveData.Invalid); + path = path.ToLower(); return category switch { From 6d89ea5a712c04b01de80ebdbec560eaeb599aa1 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 21 Dec 2023 09:43:40 +0000 Subject: [PATCH 0261/1381] [CI] Updating repo.json for 0.8.3.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index a04b35b5..173f6592 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.3.0", - "TestingAssemblyVersion": "0.8.3.0", + "AssemblyVersion": "0.8.3.1", + "TestingAssemblyVersion": "0.8.3.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 2a0e6ce1aa61b8d882364812b3a929cc50697fa3 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 02:48:11 +1100 Subject: [PATCH 0262/1381] WIP .mdl updates --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 113 ++++++++++++++++-- 1 file changed, 101 insertions(+), 12 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index b95ba393..001e1c78 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,6 +1,8 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Widgets; +using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.String.Classes; @@ -10,28 +12,115 @@ public partial class ModEditWindow { private readonly FileEditor _modelTab; + private static List _submeshAttributeTagWidgets = new(); + private static bool DrawModelPanel(MdlFile file, bool disabled) { - var ret = false; - for (var i = 0; i < file.Materials.Length; ++i) + var submeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); + if (_submeshAttributeTagWidgets.Count != submeshTotal) { - using var id = ImRaii.PushId(i); - var tmp = file.Materials[i]; - if (ImGui.InputText(string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) - && tmp.Length > 0 - && tmp != file.Materials[i]) - { - file.Materials[i] = tmp; - ret = true; - } + _submeshAttributeTagWidgets.Clear(); + _submeshAttributeTagWidgets.AddRange( + Enumerable.Range(0, submeshTotal).Select(_ => new TagButtons()) + ); } + var ret = false; + + for (var i = 0; i < file.Meshes.Length; ++i) + ret |= DrawMeshDetails(file, i, disabled); + ret |= DrawOtherModelDetails(file, disabled); return !disabled && ret; } + private static bool DrawMeshDetails(MdlFile file, int meshIndex, bool disabled) + { + if (!ImGui.CollapsingHeader($"Mesh {meshIndex}")) + return false; + + using var id = ImRaii.PushId(meshIndex); + + var mesh = file.Meshes[meshIndex]; + + var ret = false; + + // Mesh material. + var temp = file.Materials[mesh.MaterialIndex]; + if ( + ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) + && temp.Length > 0 + && temp != file.Materials[mesh.MaterialIndex] + ) { + file.Materials[mesh.MaterialIndex] = temp; + ret = true; + } + + // Submeshes. + for (var submeshOffset = 0; submeshOffset < mesh.SubMeshCount; submeshOffset++) + ret |= DrawSubMeshDetails(file, mesh.SubMeshIndex + submeshOffset, disabled); + + return ret; + } + + private static bool DrawSubMeshDetails(MdlFile file, int submeshIndex, bool disabled) + { + using var id = ImRaii.PushId(submeshIndex); + + var submesh = file.SubMeshes[submeshIndex]; + var widget = _submeshAttributeTagWidgets[submeshIndex]; + + var attributes = Enumerable + .Range(0, 32) + .Where(index => ((submesh.AttributeIndexMask >> index) & 1) == 1) + .Select(index => file.Attributes[index]) + .ToArray(); + + UiHelpers.DefaultLineSpace(); + var tagIndex = widget.Draw($"Submesh {submeshIndex} Attributes", "", attributes, out var editedAttribute, !disabled); + if (tagIndex >= 0) + { + // Eagerly remove the edited attribute from the attribute mask. + if (tagIndex < attributes.Length) + { + var previousAttributeIndex = file.Attributes.IndexOf(attributes[tagIndex]); + submesh.AttributeIndexMask &= ~(1u << previousAttributeIndex); + + // If no other submeshes use this attribute, remove it. + var usages = file.SubMeshes + .Where(submesh => ((submesh.AttributeIndexMask >> previousAttributeIndex) & 1) == 1) + .Count(); + if (usages <= 1) + { + // TODO THIS BLOWS UP ALL OTHER INDICES BEYOND WHAT WE JUST REMOVED - I NEED TO VIRTUALISE THIS SHIT + // file.Attributes = file.Attributes.RemoveItems(previousAttributeIndex); + } + } + + // If there's a new or edited name, add it to the mask, and the attribute list if it's not already known. + if (editedAttribute != "") + { + var attributeIndex = file.Attributes.IndexOf(editedAttribute); + if (attributeIndex == -1) + { + file.Attributes.AddItem(editedAttribute); + attributeIndex = file.Attributes.Length - 1; + } + submesh.AttributeIndexMask |= 1u << attributeIndex; + } + + file.SubMeshes[submeshIndex] = submesh; + + return true; + } + + ImGui.SameLine(); + ImGui.Text($"{Convert.ToString(submesh.AttributeIndexMask, 2)}"); + + return false; + } + private static bool DrawOtherModelDetails(MdlFile file, bool _) { if (!ImGui.CollapsingHeader("Further Content")) From 49b63d2208bf8b4c62bc02f83a7b447c951d8410 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 03:32:44 +1100 Subject: [PATCH 0263/1381] Draw the rest of the owl --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 94 +++++++++++-------- 1 file changed, 56 insertions(+), 38 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 001e1c78..8edc4082 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,4 +1,5 @@ using ImGuiNET; +using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; @@ -71,56 +72,73 @@ public partial class ModEditWindow var submesh = file.SubMeshes[submeshIndex]; var widget = _submeshAttributeTagWidgets[submeshIndex]; - var attributes = Enumerable - .Range(0, 32) - .Where(index => ((submesh.AttributeIndexMask >> index) & 1) == 1) - .Select(index => file.Attributes[index]) - .ToArray(); + var attributes = HydrateAttributes(file, submesh.AttributeIndexMask).ToArray(); UiHelpers.DefaultLineSpace(); var tagIndex = widget.Draw($"Submesh {submeshIndex} Attributes", "", attributes, out var editedAttribute, !disabled); if (tagIndex >= 0) { - // Eagerly remove the edited attribute from the attribute mask. - if (tagIndex < attributes.Length) - { - var previousAttributeIndex = file.Attributes.IndexOf(attributes[tagIndex]); - submesh.AttributeIndexMask &= ~(1u << previousAttributeIndex); - - // If no other submeshes use this attribute, remove it. - var usages = file.SubMeshes - .Where(submesh => ((submesh.AttributeIndexMask >> previousAttributeIndex) & 1) == 1) - .Count(); - if (usages <= 1) - { - // TODO THIS BLOWS UP ALL OTHER INDICES BEYOND WHAT WE JUST REMOVED - I NEED TO VIRTUALISE THIS SHIT - // file.Attributes = file.Attributes.RemoveItems(previousAttributeIndex); - } - } - - // If there's a new or edited name, add it to the mask, and the attribute list if it's not already known. - if (editedAttribute != "") - { - var attributeIndex = file.Attributes.IndexOf(editedAttribute); - if (attributeIndex == -1) - { - file.Attributes.AddItem(editedAttribute); - attributeIndex = file.Attributes.Length - 1; - } - submesh.AttributeIndexMask |= 1u << attributeIndex; - } - - file.SubMeshes[submeshIndex] = submesh; + EditSubmeshAttribute( + file, + submeshIndex, + tagIndex < attributes.Length ? attributes[tagIndex] : null, + editedAttribute != "" ? editedAttribute : null + ); return true; } - ImGui.SameLine(); - ImGui.Text($"{Convert.ToString(submesh.AttributeIndexMask, 2)}"); - return false; } + private static void EditSubmeshAttribute(MdlFile file, int changedSubmeshIndex, string? old, string? new_) + { + // Build a hydrated view of all attributes in the model + var submeshAttributes = file.SubMeshes + .Select(submesh => HydrateAttributes(file, submesh.AttributeIndexMask).ToList()) + .ToArray(); + + // Make changes to the submesh we're actually editing here. + var changedSubmesh = submeshAttributes[changedSubmeshIndex]; + + if (old != null) + changedSubmesh.Remove(old); + + if (new_ != null) + changedSubmesh.Add(new_); + + // Re-serialize all the attributes. + var allAttributes = new List(); + foreach (var (attributes, submeshIndex) in submeshAttributes.WithIndex()) + { + var mask = 0u; + + foreach (var attribute in attributes) + { + var attributeIndex = allAttributes.IndexOf(attribute); + if (attributeIndex == -1) + { + allAttributes.Add(attribute); + attributeIndex = allAttributes.Count() - 1; + } + + mask |= 1u << attributeIndex; + } + + file.SubMeshes[submeshIndex].AttributeIndexMask = mask; + } + + file.Attributes = allAttributes.ToArray(); + } + + private static IEnumerable HydrateAttributes(MdlFile file, uint mask) + { + return Enumerable + .Range(0, 32) + .Where(index => ((mask >> index) & 1) == 1) + .Select(index => file.Attributes[index]); + } + private static bool DrawOtherModelDetails(MdlFile file, bool _) { if (!ImGui.CollapsingHeader("Further Content")) From 8ba20218c620cef270d4cfcdf0ccb1591d5b5ef0 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 03:35:17 +1100 Subject: [PATCH 0264/1381] whoops --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 8edc4082..b41dbf0c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,9 +1,7 @@ using ImGuiNET; -using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; -using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.String.Classes; From 27123f2a640ee93908344e0351b3080a2808ca42 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 19:00:06 +1100 Subject: [PATCH 0265/1381] Inline submesh UI, fix visual offset --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 47 +++++++++---------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index b41dbf0c..d43ae55b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -58,35 +58,32 @@ public partial class ModEditWindow // Submeshes. for (var submeshOffset = 0; submeshOffset < mesh.SubMeshCount; submeshOffset++) - ret |= DrawSubMeshDetails(file, mesh.SubMeshIndex + submeshOffset, disabled); - - return ret; - } - - private static bool DrawSubMeshDetails(MdlFile file, int submeshIndex, bool disabled) - { - using var id = ImRaii.PushId(submeshIndex); - - var submesh = file.SubMeshes[submeshIndex]; - var widget = _submeshAttributeTagWidgets[submeshIndex]; - - var attributes = HydrateAttributes(file, submesh.AttributeIndexMask).ToArray(); - - UiHelpers.DefaultLineSpace(); - var tagIndex = widget.Draw($"Submesh {submeshIndex} Attributes", "", attributes, out var editedAttribute, !disabled); - if (tagIndex >= 0) { - EditSubmeshAttribute( - file, - submeshIndex, - tagIndex < attributes.Length ? attributes[tagIndex] : null, - editedAttribute != "" ? editedAttribute : null - ); + using var submeshId = ImRaii.PushId(submeshOffset); - return true; + var submeshIndex = mesh.SubMeshIndex + submeshOffset; + + var submesh = file.SubMeshes[submeshIndex]; + var widget = _submeshAttributeTagWidgets[submeshIndex]; + + var attributes = HydrateAttributes(file, submesh.AttributeIndexMask).ToArray(); + + UiHelpers.DefaultLineSpace(); + var tagIndex = widget.Draw($"Submesh {submeshOffset} Attributes", "", attributes, out var editedAttribute, !disabled); + if (tagIndex >= 0) + { + EditSubmeshAttribute( + file, + submeshIndex, + tagIndex < attributes.Length ? attributes[tagIndex] : null, + editedAttribute != "" ? editedAttribute : null + ); + + ret = true; + } } - return false; + return ret; } private static void EditSubmeshAttribute(MdlFile file, int changedSubmeshIndex, string? old, string? new_) From f04b2959891252453310a1eb9bec5c80ac7dba3a Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 19:06:55 +1100 Subject: [PATCH 0266/1381] Scaffold tab file --- .../ModEditWindow.Models.MdlTab.cs | 20 +++++++++++++++++++ .../UI/AdvancedWindow/ModEditWindow.Models.cs | 6 ++++-- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 4 ++-- 3 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs new file mode 100644 index 00000000..aeae20cc --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -0,0 +1,20 @@ +using Penumbra.GameData.Files; + +namespace Penumbra.UI.AdvancedWindow; + +public partial class ModEditWindow +{ + private class MdlTab : IWritable + { + public readonly MdlFile Mdl; + + public MdlTab(byte[] bytes) + { + Mdl = new MdlFile(bytes); + } + + public bool Valid => Mdl.Valid; + + public byte[] Write() => Mdl.Write(); + } +} \ No newline at end of file diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index d43ae55b..bcfc77ad 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -9,12 +9,14 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private readonly FileEditor _modelTab; + private readonly FileEditor _modelTab; private static List _submeshAttributeTagWidgets = new(); - private static bool DrawModelPanel(MdlFile file, bool disabled) + private static bool DrawModelPanel(MdlTab tab, bool disabled) { + var file = tab.Mdl; + var submeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); if (_submeshAttributeTagWidgets.Count != submeshTotal) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index db9201ca..365c4a4a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -584,8 +584,8 @@ public partial class ModEditWindow : Window, IDisposable _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); - _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlFile(bytes)); + _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlTab(bytes)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); From 28246244cd04c37689278a2c13259fc17508bf68 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 20:25:01 +1100 Subject: [PATCH 0267/1381] Move persitence logic to tab file --- .../ModEditWindow.Models.MdlTab.cs | 87 +++++++++++++++++++ .../UI/AdvancedWindow/ModEditWindow.Models.cs | 69 ++------------- 2 files changed, 96 insertions(+), 60 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index aeae20cc..3ba39543 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,3 +1,5 @@ +using System.Collections.ObjectModel; +using OtterGui; using Penumbra.GameData.Files; namespace Penumbra.UI.AdvancedWindow; @@ -8,9 +10,94 @@ public partial class ModEditWindow { public readonly MdlFile Mdl; + private List _materials; + private List[] _attributes; + public MdlTab(byte[] bytes) { Mdl = new MdlFile(bytes); + + _materials = Mdl.Meshes.Select(mesh => Mdl.Materials[mesh.MaterialIndex]).ToList(); + _attributes = HydrateAttributes(Mdl); + } + + private List[] HydrateAttributes(MdlFile mdl) + { + return mdl.SubMeshes.Select(submesh => + Enumerable.Range(0,32) + .Where(index => ((submesh.AttributeIndexMask >> index) & 1) == 1) + .Select(index => mdl.Attributes[index]) + .ToList() + ).ToArray(); + } + + public string GetMeshMaterial(int meshIndex) => _materials[meshIndex]; + + public void SetMeshMaterial(int meshIndex, string materialPath) + { + _materials[meshIndex] = materialPath; + + PersistMaterials(); + } + + private void PersistMaterials() + { + var allMaterials = new List(); + + foreach (var (material, meshIndex) in _materials.WithIndex()) + { + var materialIndex = allMaterials.IndexOf(material); + if (materialIndex == -1) + { + allMaterials.Add(material); + materialIndex = allMaterials.Count() - 1; + } + + Mdl.Meshes[meshIndex].MaterialIndex = (ushort)materialIndex; + } + + Mdl.Materials = allMaterials.ToArray(); + } + + public IReadOnlyCollection GetSubmeshAttributes(int submeshIndex) => _attributes[submeshIndex]; + + public void UpdateSubmeshAttribute(int submeshIndex, string? old, string? new_) + { + var attributes = _attributes[submeshIndex]; + + if (old != null) + attributes.Remove(old); + + if (new_ != null) + attributes.Add(new_); + + PersistAttributes(); + } + + private void PersistAttributes() + { + var allAttributes = new List(); + + foreach (var (attributes, submeshIndex) in _attributes.WithIndex()) + { + var mask = 0u; + + foreach (var attribute in attributes) + { + var attributeIndex = allAttributes.IndexOf(attribute); + if (attributeIndex == -1) + { + allAttributes.Add(attribute); + attributeIndex = allAttributes.Count() - 1; + } + + mask |= 1u << attributeIndex; + } + + Mdl.SubMeshes[submeshIndex].AttributeIndexMask = mask; + } + + Mdl.Attributes = allAttributes.ToArray(); } public bool Valid => Mdl.Valid; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index bcfc77ad..0a4c9c1b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -29,32 +29,33 @@ public partial class ModEditWindow var ret = false; for (var i = 0; i < file.Meshes.Length; ++i) - ret |= DrawMeshDetails(file, i, disabled); + ret |= DrawMeshDetails(tab, i, disabled); ret |= DrawOtherModelDetails(file, disabled); return !disabled && ret; } - private static bool DrawMeshDetails(MdlFile file, int meshIndex, bool disabled) + private static bool DrawMeshDetails(MdlTab tab, int meshIndex, bool disabled) { if (!ImGui.CollapsingHeader($"Mesh {meshIndex}")) return false; using var id = ImRaii.PushId(meshIndex); + var file = tab.Mdl; var mesh = file.Meshes[meshIndex]; var ret = false; // Mesh material. - var temp = file.Materials[mesh.MaterialIndex]; + var temp = tab.GetMeshMaterial(meshIndex); if ( ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) && temp.Length > 0 - && temp != file.Materials[mesh.MaterialIndex] + && temp != tab.GetMeshMaterial(meshIndex) ) { - file.Materials[mesh.MaterialIndex] = temp; + tab.SetMeshMaterial(meshIndex, temp); ret = true; } @@ -64,20 +65,16 @@ public partial class ModEditWindow using var submeshId = ImRaii.PushId(submeshOffset); var submeshIndex = mesh.SubMeshIndex + submeshOffset; - - var submesh = file.SubMeshes[submeshIndex]; var widget = _submeshAttributeTagWidgets[submeshIndex]; - - var attributes = HydrateAttributes(file, submesh.AttributeIndexMask).ToArray(); + var attributes = tab.GetSubmeshAttributes(submeshIndex); UiHelpers.DefaultLineSpace(); var tagIndex = widget.Draw($"Submesh {submeshOffset} Attributes", "", attributes, out var editedAttribute, !disabled); if (tagIndex >= 0) { - EditSubmeshAttribute( - file, + tab.UpdateSubmeshAttribute( submeshIndex, - tagIndex < attributes.Length ? attributes[tagIndex] : null, + tagIndex < attributes.Count() ? attributes.ElementAt(tagIndex) : null, editedAttribute != "" ? editedAttribute : null ); @@ -88,54 +85,6 @@ public partial class ModEditWindow return ret; } - private static void EditSubmeshAttribute(MdlFile file, int changedSubmeshIndex, string? old, string? new_) - { - // Build a hydrated view of all attributes in the model - var submeshAttributes = file.SubMeshes - .Select(submesh => HydrateAttributes(file, submesh.AttributeIndexMask).ToList()) - .ToArray(); - - // Make changes to the submesh we're actually editing here. - var changedSubmesh = submeshAttributes[changedSubmeshIndex]; - - if (old != null) - changedSubmesh.Remove(old); - - if (new_ != null) - changedSubmesh.Add(new_); - - // Re-serialize all the attributes. - var allAttributes = new List(); - foreach (var (attributes, submeshIndex) in submeshAttributes.WithIndex()) - { - var mask = 0u; - - foreach (var attribute in attributes) - { - var attributeIndex = allAttributes.IndexOf(attribute); - if (attributeIndex == -1) - { - allAttributes.Add(attribute); - attributeIndex = allAttributes.Count() - 1; - } - - mask |= 1u << attributeIndex; - } - - file.SubMeshes[submeshIndex].AttributeIndexMask = mask; - } - - file.Attributes = allAttributes.ToArray(); - } - - private static IEnumerable HydrateAttributes(MdlFile file, uint mask) - { - return Enumerable - .Range(0, 32) - .Where(index => ((mask >> index) & 1) == 1) - .Select(index => file.Attributes[index]); - } - private static bool DrawOtherModelDetails(MdlFile file, bool _) { if (!ImGui.CollapsingHeader("Further Content")) From 7ef50f7bb4767441387db5c9af1c71ac30511c28 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 20:28:29 +1100 Subject: [PATCH 0268/1381] Add material list to further content --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 0a4c9c1b..1960614a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -135,6 +135,13 @@ public partial class ModEditWindow } } + using (var materials = ImRaii.TreeNode("Materials", ImGuiTreeNodeFlags.DefaultOpen)) + { + if (materials) + foreach (var material in file.Materials) + ImRaii.TreeNode(material, ImGuiTreeNodeFlags.Leaf).Dispose(); + } + using (var attributes = ImRaii.TreeNode("Attributes", ImGuiTreeNodeFlags.DefaultOpen)) { if (attributes) From 17e6838422965a83056726a1388cdaaacc1f12a8 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 21 Dec 2023 20:52:14 +1100 Subject: [PATCH 0269/1381] Swap to tree nodes for more compact UX --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 1960614a..7e2f8f5f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -28,8 +28,9 @@ public partial class ModEditWindow var ret = false; - for (var i = 0; i < file.Meshes.Length; ++i) - ret |= DrawMeshDetails(tab, i, disabled); + if (ImGui.CollapsingHeader($"{file.Meshes.Length} Meshes###meshes")) + for (var i = 0; i < file.Meshes.Length; ++i) + ret |= DrawMeshDetails(tab, i, disabled); ret |= DrawOtherModelDetails(file, disabled); @@ -38,7 +39,8 @@ public partial class ModEditWindow private static bool DrawMeshDetails(MdlTab tab, int meshIndex, bool disabled) { - if (!ImGui.CollapsingHeader($"Mesh {meshIndex}")) + using var meshNode = ImRaii.TreeNode($"Mesh {meshIndex}", ImGuiTreeNodeFlags.DefaultOpen); + if (!meshNode) return false; using var id = ImRaii.PushId(meshIndex); From c138c39c068ef8eb10da401d73583db3995bf223 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Dec 2023 15:12:41 +0100 Subject: [PATCH 0270/1381] Change CharacterWeapon names. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 4d3570fd..fe0bf13f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 4d3570fd47d78dbc49cf5e41fd3545a533ef9e81 +Subproject commit fe0bf13f1ae47b77684ccb4bb9e9f44e430acfbf From 2051197c65e823142bfa31667120cbf0984f0241 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Dec 2023 15:20:39 +0100 Subject: [PATCH 0271/1381] Change again. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fe0bf13f..3787e82d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fe0bf13f1ae47b77684ccb4bb9e9f44e430acfbf +Subproject commit 3787e82d1b84d2542b6e4238060d75383a4b12a1 From 72f57d292b074d710f7c3325773669a1e6b1f6c7 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 22 Dec 2023 03:34:20 +1100 Subject: [PATCH 0272/1381] group meshes by lod --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 7e2f8f5f..c4c86e24 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -28,15 +28,31 @@ public partial class ModEditWindow var ret = false; - if (ImGui.CollapsingHeader($"{file.Meshes.Length} Meshes###meshes")) - for (var i = 0; i < file.Meshes.Length; ++i) - ret |= DrawMeshDetails(tab, i, disabled); + if (ImGui.CollapsingHeader($"Meshes ({file.Meshes.Length})###meshes")) + for (var i = 0; i < file.LodCount; ++i) + ret |= DrawLodDetails(tab, i, disabled); ret |= DrawOtherModelDetails(file, disabled); return !disabled && ret; } + private static bool DrawLodDetails(MdlTab tab, int lodIndex, bool disabled) + { + using var lodNode = ImRaii.TreeNode($"LOD {lodIndex}", ImGuiTreeNodeFlags.DefaultOpen); + if (!lodNode) + return false; + + var lod = tab.Mdl.Lods[lodIndex]; + + var ret = false; + + for (var meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) + ret |= DrawMeshDetails(tab, lod.MeshIndex + meshOffset, disabled); + + return ret; + } + private static bool DrawMeshDetails(MdlTab tab, int meshIndex, bool disabled) { using var meshNode = ImRaii.TreeNode($"Mesh {meshIndex}", ImGuiTreeNodeFlags.DefaultOpen); From 829016a1c4b236b5516e92f84101a6ea3ade3a5a Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 22 Dec 2023 23:16:23 +1100 Subject: [PATCH 0273/1381] Spike improved UI --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 124 +++++++++++++++--- 1 file changed, 108 insertions(+), 16 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index c4c86e24..0095ece8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,3 +1,4 @@ +using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; @@ -9,6 +10,8 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { + private const int MdlMaterialMaximum = 4; + private readonly FileEditor _modelTab; private static List _submeshAttributeTagWidgets = new(); @@ -28,18 +31,88 @@ public partial class ModEditWindow var ret = false; + ret |= DrawModelMaterialDetails(tab, disabled); + if (ImGui.CollapsingHeader($"Meshes ({file.Meshes.Length})###meshes")) for (var i = 0; i < file.LodCount; ++i) - ret |= DrawLodDetails(tab, i, disabled); + ret |= DrawModelLodDetails(tab, i, disabled); ret |= DrawOtherModelDetails(file, disabled); return !disabled && ret; } - private static bool DrawLodDetails(MdlTab tab, int lodIndex, bool disabled) + private static bool DrawModelMaterialDetails(MdlTab tab, bool disabled) { - using var lodNode = ImRaii.TreeNode($"LOD {lodIndex}", ImGuiTreeNodeFlags.DefaultOpen); + if (!ImGui.CollapsingHeader("Materials")) + return false; + + var materials = tab.Mdl.Materials; + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return false; + + ImGui.TableSetupColumn("index", ImGuiTableColumnFlags.WidthFixed, 80 * UiHelpers.Scale); + ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthStretch, 1); + ImGui.TableSetupColumn("actions", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); + + var inputFlags = ImGuiInputTextFlags.None; + if (disabled) + inputFlags |= ImGuiInputTextFlags.ReadOnly; + + for (var materialIndex = 0; materialIndex < materials.Length; materialIndex++) + { + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.Text($"Material #{materialIndex + 1}"); + + var temp = materials[materialIndex]; + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + ImGui.InputText($"##material{materialIndex}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags); + + ImGui.TableNextColumn(); + var todoDelete = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, "description", disabled || !ImGui.GetIO().KeyCtrl, true); + } + + if (materials.Length < MdlMaterialMaximum) + { + ImGui.TableNextColumn(); + + // todo: persist + var temp = ""; + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + ImGui.InputTextWithHint($"##newMaterial", "Add new material...", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags); + + // todo: flesh out this validation + var validName = temp != ""; + ImGui.TableNextColumn(); + var todoAdd = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, "description", disabled || !validName, true); + } + + // for (var index = 0; index < MdlMaterialMaximum; index++) + // { + // var temp = ""; + // ImGui.InputText($"Material {index}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags); + // } + + // var temp = tab.GetMeshMaterial(meshIndex); + // if ( + // ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) + // && temp.Length > 0 + // && temp != tab.GetMeshMaterial(meshIndex) + // ) { + // tab.SetMeshMaterial(meshIndex, temp); + // ret = true; + // } + return false; + } + + private static bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) + { + using var lodNode = ImRaii.TreeNode($"Level of Detail #{lodIndex}", ImGuiTreeNodeFlags.DefaultOpen); if (!lodNode) return false; @@ -48,18 +121,24 @@ public partial class ModEditWindow var ret = false; for (var meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) - ret |= DrawMeshDetails(tab, lod.MeshIndex + meshOffset, disabled); + ret |= DrawModelMeshDetails(tab, lod.MeshIndex + meshOffset, disabled); return ret; } - private static bool DrawMeshDetails(MdlTab tab, int meshIndex, bool disabled) + private static bool DrawModelMeshDetails(MdlTab tab, int meshIndex, bool disabled) { - using var meshNode = ImRaii.TreeNode($"Mesh {meshIndex}", ImGuiTreeNodeFlags.DefaultOpen); + using var meshNode = ImRaii.TreeNode($"Mesh #{meshIndex}", ImGuiTreeNodeFlags.DefaultOpen); if (!meshNode) return false; using var id = ImRaii.PushId(meshIndex); + using var table = ImRaii.Table(string.Empty, 2, ImGuiTableFlags.SizingFixedFit); + if (!table) + return false; + + ImGui.TableSetupColumn("name", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); + ImGui.TableSetupColumn("field", ImGuiTableColumnFlags.WidthStretch, 1); var file = tab.Mdl; var mesh = file.Meshes[meshIndex]; @@ -67,14 +146,23 @@ public partial class ModEditWindow var ret = false; // Mesh material. - var temp = tab.GetMeshMaterial(meshIndex); - if ( - ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) - && temp.Length > 0 - && temp != tab.GetMeshMaterial(meshIndex) - ) { - tab.SetMeshMaterial(meshIndex, temp); - ret = true; + // var temp = tab.GetMeshMaterial(meshIndex); + // if ( + // ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) + // && temp.Length > 0 + // && temp != tab.GetMeshMaterial(meshIndex) + // ) { + // tab.SetMeshMaterial(meshIndex, temp); + // ret = true; + // } + ImGui.TableNextColumn(); + ImGui.Text("Material"); + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + using (var materialCombo = ImRaii.Combo("##material", tab.GetMeshMaterial(meshIndex))) + { + // todo } // Submeshes. @@ -83,11 +171,15 @@ public partial class ModEditWindow using var submeshId = ImRaii.PushId(submeshOffset); var submeshIndex = mesh.SubMeshIndex + submeshOffset; + + ImGui.TableNextColumn(); + ImGui.Text($"Attributes #{submeshOffset}"); + + ImGui.TableNextColumn(); var widget = _submeshAttributeTagWidgets[submeshIndex]; var attributes = tab.GetSubmeshAttributes(submeshIndex); - UiHelpers.DefaultLineSpace(); - var tagIndex = widget.Draw($"Submesh {submeshOffset} Attributes", "", attributes, out var editedAttribute, !disabled); + var tagIndex = widget.Draw("", "", attributes, out var editedAttribute, !disabled); if (tagIndex >= 0) { tab.UpdateSubmeshAttribute( From a581495c7ea15058779c578acc51e12f247d1515 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 22 Dec 2023 23:49:50 +1100 Subject: [PATCH 0274/1381] Flesh out material wiring --- .../ModEditWindow.Models.MdlTab.cs | 57 ++++++--------- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 69 +++++++++++-------- 2 files changed, 62 insertions(+), 64 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 3ba39543..5fac4f5e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,5 +1,6 @@ using System.Collections.ObjectModel; using OtterGui; +using Penumbra.GameData; using Penumbra.GameData.Files; namespace Penumbra.UI.AdvancedWindow; @@ -10,53 +11,37 @@ public partial class ModEditWindow { public readonly MdlFile Mdl; - private List _materials; private List[] _attributes; public MdlTab(byte[] bytes) { Mdl = new MdlFile(bytes); - - _materials = Mdl.Meshes.Select(mesh => Mdl.Materials[mesh.MaterialIndex]).ToList(); - _attributes = HydrateAttributes(Mdl); + _attributes = PopulateAttributes(); } - private List[] HydrateAttributes(MdlFile mdl) + public void RemoveMaterial(int materialIndex) { - return mdl.SubMeshes.Select(submesh => - Enumerable.Range(0,32) - .Where(index => ((submesh.AttributeIndexMask >> index) & 1) == 1) - .Select(index => mdl.Attributes[index]) - .ToList() - ).ToArray(); - } - - public string GetMeshMaterial(int meshIndex) => _materials[meshIndex]; - - public void SetMeshMaterial(int meshIndex, string materialPath) - { - _materials[meshIndex] = materialPath; - - PersistMaterials(); - } - - private void PersistMaterials() - { - var allMaterials = new List(); - - foreach (var (material, meshIndex) in _materials.WithIndex()) + // Meshes using the removed material are redirected to material 0, and those after the index are corrected. + for (var meshIndex = 0; meshIndex < Mdl.Meshes.Length; meshIndex++) { - var materialIndex = allMaterials.IndexOf(material); - if (materialIndex == -1) - { - allMaterials.Add(material); - materialIndex = allMaterials.Count() - 1; - } - - Mdl.Meshes[meshIndex].MaterialIndex = (ushort)materialIndex; + var mesh = Mdl.Meshes[meshIndex]; + if (mesh.MaterialIndex == materialIndex) + mesh.MaterialIndex = 0; + else if (mesh.MaterialIndex > materialIndex) + mesh.MaterialIndex -= 1; } - Mdl.Materials = allMaterials.ToArray(); + Mdl.Materials = Mdl.Materials.RemoveItems(materialIndex); + } + + private List[] PopulateAttributes() + { + return Mdl.SubMeshes.Select(submesh => + Enumerable.Range(0,32) + .Where(index => ((submesh.AttributeIndexMask >> index) & 1) == 1) + .Select(index => Mdl.Attributes[index]) + .ToList() + ).ToArray(); } public IReadOnlyCollection GetSubmeshAttributes(int submeshIndex) => _attributes[submeshIndex]; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 0095ece8..fe3ca644 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; +using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.String.Classes; @@ -14,6 +15,7 @@ public partial class ModEditWindow private readonly FileEditor _modelTab; + private static string _modelNewMaterial = string.Empty; private static List _submeshAttributeTagWidgets = new(); private static bool DrawModelPanel(MdlTab tab, bool disabled) @@ -47,12 +49,13 @@ public partial class ModEditWindow if (!ImGui.CollapsingHeader("Materials")) return false; - var materials = tab.Mdl.Materials; - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); if (!table) return false; + var ret = false; + var materials = tab.Mdl.Materials; + ImGui.TableSetupColumn("index", ImGuiTableColumnFlags.WidthFixed, 80 * UiHelpers.Scale); ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthStretch, 1); ImGui.TableSetupColumn("actions", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); @@ -63,6 +66,8 @@ public partial class ModEditWindow for (var materialIndex = 0; materialIndex < materials.Length; materialIndex++) { + using var id = ImRaii.PushId(materialIndex); + ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); ImGui.Text($"Material #{materialIndex + 1}"); @@ -70,44 +75,52 @@ public partial class ModEditWindow var temp = materials[materialIndex]; ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); - ImGui.InputText($"##material{materialIndex}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags); - + if ( + ImGui.InputText($"##material{materialIndex}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags) + && temp.Length > 0 + && temp != materials[materialIndex] + ) { + materials[materialIndex] = temp; + ret = true; + } + ImGui.TableNextColumn(); - var todoDelete = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, "description", disabled || !ImGui.GetIO().KeyCtrl, true); + + // Need to have at least one material. + if (materials.Length <= 1) + continue; + + if (ImGuiUtil.DrawDisabledButton( + FontAwesomeIcon.Trash.ToIconString(), + UiHelpers.IconButtonSize, + "Delete this material.\nAny meshes targeting this material will be updated to use material #1.\nHold Control while clicking to delete.", + disabled || !ImGui.GetIO().KeyCtrl, + true + )) { + tab.RemoveMaterial(materialIndex); + ret = true; + } } if (materials.Length < MdlMaterialMaximum) { ImGui.TableNextColumn(); - // todo: persist - var temp = ""; ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); - ImGui.InputTextWithHint($"##newMaterial", "Add new material...", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags); + ImGui.InputTextWithHint($"##newMaterial", "Add new material...", ref _modelNewMaterial, Utf8GamePath.MaxGamePathLength, inputFlags); - // todo: flesh out this validation - var validName = temp != ""; + var validName = _modelNewMaterial != ""; ImGui.TableNextColumn(); - var todoAdd = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, "description", disabled || !validName, true); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, "description", disabled || !validName, true)) + { + tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); + _modelNewMaterial = string.Empty; + ret = true; + } } - // for (var index = 0; index < MdlMaterialMaximum; index++) - // { - // var temp = ""; - // ImGui.InputText($"Material {index}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags); - // } - - // var temp = tab.GetMeshMaterial(meshIndex); - // if ( - // ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) - // && temp.Length > 0 - // && temp != tab.GetMeshMaterial(meshIndex) - // ) { - // tab.SetMeshMaterial(meshIndex, temp); - // ret = true; - // } - return false; + return ret; } private static bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) @@ -160,7 +173,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); - using (var materialCombo = ImRaii.Combo("##material", tab.GetMeshMaterial(meshIndex))) + using (var materialCombo = ImRaii.Combo("##material", "TODO material")) { // todo } From b22470ac79bf3f89bf3a4d671427d3aada448588 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 23 Dec 2023 00:12:59 +1100 Subject: [PATCH 0275/1381] Finish up mesh material combos --- .../ModEditWindow.Models.MdlTab.cs | 13 ++++----- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 27 ++++++++++--------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 5fac4f5e..f488c987 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,4 +1,3 @@ -using System.Collections.ObjectModel; using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; @@ -24,11 +23,13 @@ public partial class ModEditWindow // Meshes using the removed material are redirected to material 0, and those after the index are corrected. for (var meshIndex = 0; meshIndex < Mdl.Meshes.Length; meshIndex++) { - var mesh = Mdl.Meshes[meshIndex]; - if (mesh.MaterialIndex == materialIndex) - mesh.MaterialIndex = 0; - else if (mesh.MaterialIndex > materialIndex) - mesh.MaterialIndex -= 1; + var newIndex = Mdl.Meshes[meshIndex].MaterialIndex; + if (newIndex == materialIndex) + newIndex = 0; + else if (newIndex > materialIndex) + newIndex -= 1; + + Mdl.Meshes[meshIndex].MaterialIndex = newIndex; } Mdl.Materials = Mdl.Materials.RemoveItems(materialIndex); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index fe3ca644..92953ae4 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -158,27 +158,28 @@ public partial class ModEditWindow var ret = false; - // Mesh material. - // var temp = tab.GetMeshMaterial(meshIndex); - // if ( - // ImGui.InputText("Material", ref temp, Utf8GamePath.MaxGamePathLength, disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) - // && temp.Length > 0 - // && temp != tab.GetMeshMaterial(meshIndex) - // ) { - // tab.SetMeshMaterial(meshIndex, temp); - // ret = true; - // } + // Mesh material ImGui.TableNextColumn(); ImGui.Text("Material"); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); - using (var materialCombo = ImRaii.Combo("##material", "TODO material")) + using (var materialCombo = ImRaii.Combo("##material", tab.Mdl.Materials[mesh.MaterialIndex])) { - // todo + if (materialCombo) + { + foreach (var (material, materialIndex) in tab.Mdl.Materials.WithIndex()) + { + if (ImGui.Selectable(material, mesh.MaterialIndex == materialIndex)) + { + file.Meshes[meshIndex].MaterialIndex = (ushort)materialIndex; + ret = true; + } + } + } } - // Submeshes. + // Submeshes for (var submeshOffset = 0; submeshOffset < mesh.SubMeshCount; submeshOffset++) { using var submeshId = ImRaii.PushId(submeshOffset); From 4aa19e49d59ac3a31f9ba05d7ba37243f8fb2d0f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Dec 2023 14:22:03 +0100 Subject: [PATCH 0276/1381] Add filtering mods by changed item categories. --- Penumbra.GameData | 2 +- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 2 +- Penumbra/UI/ChangedItemDrawer.cs | 92 ++++++++++++++----- .../CollectionTab/IndividualAssignmentUi.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 25 +++-- 5 files changed, 89 insertions(+), 34 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 3787e82d..58a3e794 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3787e82d1b84d2542b6e4238060d75383a4b12a1 +Subproject commit 58a3e7947c207452f5fa0d328c47c5ed6bdd9a0f diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index f7f82a59..516df251 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -242,7 +242,7 @@ public static class EquipmentSwap if (!slot.IsEquipmentPiece()) throw new ItemSwap.InvalidItemTypeException(); - modelId = i.ModelId; + modelId = i.PrimaryId; variant = i.Variant; } diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 0a1d58f9..638afef0 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -43,8 +43,71 @@ public class ChangedItemDrawer : IDisposable Emote = 0x01_00_00, } - public const ChangedItemIcon AllFlags = (ChangedItemIcon)0x01FFFF; - public const ChangedItemIcon DefaultFlags = AllFlags & ~ChangedItemIcon.Offhand; + private static readonly ChangedItemIcon[] Order = + [ + ChangedItemIcon.Head, + ChangedItemIcon.Body, + ChangedItemIcon.Hands, + ChangedItemIcon.Legs, + ChangedItemIcon.Feet, + ChangedItemIcon.Ears, + ChangedItemIcon.Neck, + ChangedItemIcon.Wrists, + ChangedItemIcon.Finger, + ChangedItemIcon.Mainhand, + ChangedItemIcon.Offhand, + ChangedItemIcon.Customization, + ChangedItemIcon.Action, + ChangedItemIcon.Emote, + ChangedItemIcon.Monster, + ChangedItemIcon.Demihuman, + ChangedItemIcon.Unknown, + ]; + + private static readonly string[] LowerNames = Order.Select(f => ToDescription(f).ToLowerInvariant()).ToArray(); + + public static bool TryParseIndex(ReadOnlySpan input, out ChangedItemIcon slot) + { + // Handle numeric cases before TryParse because numbers + // are not logical otherwise. + if (int.TryParse(input, out var idx)) + { + // We assume users will use 1-based index, but if they enter 0, just use the first. + if (idx == 0) + { + slot = Order[0]; + return true; + } + + // Use 1-based index. + --idx; + if (idx >= 0 && idx < Order.Length) + { + slot = Order[idx]; + return true; + } + } + + slot = 0; + return false; + } + + public static bool TryParsePartial(string lowerInput, out ChangedItemIcon slot) + { + if (TryParseIndex(lowerInput, out slot)) + return true; + + slot = 0; + foreach (var (item, flag) in LowerNames.Zip(Order)) + if (item.Contains(lowerInput, StringComparison.Ordinal)) + slot |= flag; + + return slot != 0; + } + + public const ChangedItemIcon AllFlags = (ChangedItemIcon)0x01FFFF; + public static readonly int NumCategories = Order.Length; + public const ChangedItemIcon DefaultFlags = AllFlags & ~ChangedItemIcon.Offhand; private readonly Configuration _config; private readonly ExcelSheet _items; @@ -163,26 +226,7 @@ public class ChangedItemDrawer : IDisposable using var _ = ImRaii.PushId("ChangedItemIconFilter"); var size = TypeFilterIconSize; using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero); - var order = new[] - { - ChangedItemIcon.Head, - ChangedItemIcon.Body, - ChangedItemIcon.Hands, - ChangedItemIcon.Legs, - ChangedItemIcon.Feet, - ChangedItemIcon.Ears, - ChangedItemIcon.Neck, - ChangedItemIcon.Wrists, - ChangedItemIcon.Finger, - ChangedItemIcon.Mainhand, - ChangedItemIcon.Offhand, - ChangedItemIcon.Customization, - ChangedItemIcon.Action, - ChangedItemIcon.Emote, - ChangedItemIcon.Monster, - ChangedItemIcon.Demihuman, - ChangedItemIcon.Unknown, - }; + bool DrawIcon(ChangedItemIcon type, ref ChangedItemIcon typeFilter) { @@ -217,13 +261,13 @@ public class ChangedItemDrawer : IDisposable return ret; } - foreach (var iconType in order) + foreach (var iconType in Order) { ret |= DrawIcon(iconType, ref typeFilter); ImGui.SameLine(); } - ImGui.SetCursorPos(new(ImGui.GetContentRegionMax().X - size.X, ImGui.GetCursorPosY() + yOffset)); + ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionMax().X - size.X, ImGui.GetCursorPosY() + yOffset)); ImGui.Image(_icons[AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, typeFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : typeFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); diff --git a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs index d3e4ab5e..a0e35cff 100644 --- a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs +++ b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs @@ -126,7 +126,7 @@ public class IndividualAssignmentUi : IDisposable /// Create combos when ready. private void SetupCombos() { - _worldCombo = new WorldCombo(_actors.Data.Worlds, Penumbra.Log, WorldId.AnyWorld); + _worldCombo = new WorldCombo(_actors.Data.Worlds, Penumbra.Log); _mountCombo = new NpcCombo("##mountCombo", _actors.Data.Mounts, Penumbra.Log); _companionCombo = new NpcCombo("##companionCombo", _actors.Data.Companions, Penumbra.Log); _ornamentCombo = new NpcCombo("##ornamentCombo", _actors.Data.Ornaments, Penumbra.Log); diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 8f12afbb..c42b1018 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -12,6 +12,8 @@ using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; @@ -190,7 +192,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 3), 't' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 4), 'T' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 4), + 's' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 5), + 'S' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 5), _ => (new LowerString(filterValue), 0), }, _ => (new LowerString(filterValue), 0), @@ -549,10 +555,13 @@ public sealed class ModFileSystemSelector : FileSystemSelector !mod.Author.Contains(_modFilter), 3 => !mod.LowerChangedItemsString.Contains(_modFilter.Lower), 4 => !mod.AllTagsLower.Contains(_modFilter.Lower), + 5 => mod.ChangedItems.All(p => (ChangedItemDrawer.GetCategoryIcon(p.Key, p.Value) & _slotFilter) == 0), 2 + EmptyOffset => !mod.Author.IsEmpty, 3 + EmptyOffset => mod.LowerChangedItemsString.Length > 0, 4 + EmptyOffset => mod.AllTagsLower.Length > 0, + 5 + EmptyOffset => mod.ChangedItems.Count == 0, _ => false, // Should never happen }; } From dc583cb8e24338e9370ee1caab1875edffd65a17 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Dec 2023 14:24:41 +0100 Subject: [PATCH 0277/1381] Update gamedata. --- Penumbra.GameData | 2 +- .../Interop/ResourceTree/ResolveContext.PathResolution.cs | 5 ++--- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 4 ++-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 58a3e794..ed37f834 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 58a3e7947c207452f5fa0d328c47c5ed6bdd9a0f +Subproject commit ed37f83424c11a5a601e74f4660cd52ebd68a7b3 diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index f2059253..0ab1e0e3 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -1,4 +1,3 @@ -using Dalamud.Game.ClientState.Objects.Enums; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; @@ -239,8 +238,8 @@ internal partial record ResolveContext return (characterRaceCode, "base", 1); case 1: var faceId = human->FaceId; - var tribe = human->Customize[(int)CustomizeIndex.Tribe]; - var modelType = human->Customize[(int)CustomizeIndex.ModelType]; + var tribe = human->Customize[(int)Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex.Tribe]; + var modelType = human->Customize[(int)Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex.ModelType]; if (faceId < 201) { faceId -= tribe switch diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index bd994242..24112a9f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -6,9 +6,9 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.String.Classes; using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; +using CustomizeIndex = Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex; namespace Penumbra.Interop.ResourceTree; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 599832f4..66b93b04 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -88,7 +88,7 @@ public class DebugTab : Window, ITab private readonly TextureManager _textureManager; private readonly SkinFixer _skinFixer; private readonly RedrawService _redraws; - private readonly DictEmotes _emotes; + private readonly DictEmote _emotes; private readonly Diagnostics _diagnostics; private readonly IObjectTable _objects; private readonly IClientState _clientState; @@ -99,7 +99,7 @@ public class DebugTab : Window, ITab ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager, SkinFixer skinFixer, RedrawService redraws, DictEmotes emotes, Diagnostics diagnostics, IpcTester ipcTester) + TextureManager textureManager, SkinFixer skinFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; From a001fcf24ff4333dbdd1bb496caa8f4b4d28ec7a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Dec 2023 15:18:43 +0100 Subject: [PATCH 0278/1381] Some cleanup. --- .../ModEditWindow.Models.MdlTab.cs | 64 +++-- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 246 +++++++++--------- 2 files changed, 166 insertions(+), 144 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index f488c987..4986963f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -10,24 +10,33 @@ public partial class ModEditWindow { public readonly MdlFile Mdl; - private List[] _attributes; + private readonly List[] _attributes; public MdlTab(byte[] bytes) { - Mdl = new MdlFile(bytes); - _attributes = PopulateAttributes(); + Mdl = new MdlFile(bytes); + _attributes = CreateAttributes(Mdl); } + /// + public bool Valid + => Mdl.Valid; + + /// + public byte[] Write() + => Mdl.Write(); + + /// Remove the material given by the index. + /// Meshes using the removed material are redirected to material 0, and those after the index are corrected. public void RemoveMaterial(int materialIndex) { - // Meshes using the removed material are redirected to material 0, and those after the index are corrected. for (var meshIndex = 0; meshIndex < Mdl.Meshes.Length; meshIndex++) { var newIndex = Mdl.Meshes[meshIndex].MaterialIndex; if (newIndex == materialIndex) newIndex = 0; else if (newIndex > materialIndex) - newIndex -= 1; + --newIndex; Mdl.Meshes[meshIndex].MaterialIndex = newIndex; } @@ -35,36 +44,41 @@ public partial class ModEditWindow Mdl.Materials = Mdl.Materials.RemoveItems(materialIndex); } - private List[] PopulateAttributes() - { - return Mdl.SubMeshes.Select(submesh => - Enumerable.Range(0,32) - .Where(index => ((submesh.AttributeIndexMask >> index) & 1) == 1) - .Select(index => Mdl.Attributes[index]) - .ToList() + /// Create a list of attributes per sub mesh. + private static List[] CreateAttributes(MdlFile mdl) + => mdl.SubMeshes.Select(s => Enumerable.Range(0, 32) + .Where(idx => ((s.AttributeIndexMask >> idx) & 1) == 1) + .Select(idx => mdl.Attributes[idx]) + .ToList() ).ToArray(); - } - public IReadOnlyCollection GetSubmeshAttributes(int submeshIndex) => _attributes[submeshIndex]; + /// Obtain the attributes associated with a sub mesh by its index. + public IReadOnlyList GetSubMeshAttributes(int subMeshIndex) + => _attributes[subMeshIndex]; - public void UpdateSubmeshAttribute(int submeshIndex, string? old, string? new_) + /// Remove or add attributes from a sub mesh by its index. + /// The index of the sub mesh to update. + /// If non-null, remove this attribute. + /// If non-null, add this attribute. + public void UpdateSubMeshAttribute(int subMeshIndex, string? old, string? @new) { - var attributes = _attributes[submeshIndex]; + var attributes = _attributes[subMeshIndex]; if (old != null) attributes.Remove(old); - if (new_ != null) - attributes.Add(new_); + if (@new != null) + attributes.Add(@new); PersistAttributes(); } + /// Apply changes to attributes to the file in memory. private void PersistAttributes() { var allAttributes = new List(); - foreach (var (attributes, submeshIndex) in _attributes.WithIndex()) + foreach (var (attributes, subMeshIndex) in _attributes.WithIndex()) { var mask = 0u; @@ -74,20 +88,16 @@ public partial class ModEditWindow if (attributeIndex == -1) { allAttributes.Add(attribute); - attributeIndex = allAttributes.Count() - 1; + attributeIndex = allAttributes.Count - 1; } mask |= 1u << attributeIndex; } - Mdl.SubMeshes[submeshIndex].AttributeIndexMask = mask; + Mdl.SubMeshes[subMeshIndex].AttributeIndexMask = mask; } - Mdl.Attributes = allAttributes.ToArray(); + Mdl.Attributes = [.. allAttributes]; } - - public bool Valid => Mdl.Valid; - - public byte[] Write() => Mdl.Write(); } -} \ No newline at end of file +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 92953ae4..25bb012a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -15,19 +15,19 @@ public partial class ModEditWindow private readonly FileEditor _modelTab; - private static string _modelNewMaterial = string.Empty; - private static List _submeshAttributeTagWidgets = new(); + private string _modelNewMaterial = string.Empty; + private readonly List _subMeshAttributeTagWidgets = []; - private static bool DrawModelPanel(MdlTab tab, bool disabled) + private bool DrawModelPanel(MdlTab tab, bool disabled) { var file = tab.Mdl; - var submeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); - if (_submeshAttributeTagWidgets.Count != submeshTotal) + var subMeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); + if (_subMeshAttributeTagWidgets.Count != subMeshTotal) { - _submeshAttributeTagWidgets.Clear(); - _submeshAttributeTagWidgets.AddRange( - Enumerable.Range(0, submeshTotal).Select(_ => new TagButtons()) + _subMeshAttributeTagWidgets.Clear(); + _subMeshAttributeTagWidgets.AddRange( + Enumerable.Range(0, subMeshTotal).Select(_ => new TagButtons()) ); } @@ -44,93 +44,92 @@ public partial class ModEditWindow return !disabled && ret; } - private static bool DrawModelMaterialDetails(MdlTab tab, bool disabled) + private bool DrawModelMaterialDetails(MdlTab tab, bool disabled) { if (!ImGui.CollapsingHeader("Materials")) return false; - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + using var table = ImRaii.Table(string.Empty, disabled ? 2 : 3, ImGuiTableFlags.SizingFixedFit); if (!table) return false; - var ret = false; + var ret = false; var materials = tab.Mdl.Materials; - ImGui.TableSetupColumn("index", ImGuiTableColumnFlags.WidthFixed, 80 * UiHelpers.Scale); - ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthStretch, 1); - ImGui.TableSetupColumn("actions", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); - - var inputFlags = ImGuiInputTextFlags.None; - if (disabled) - inputFlags |= ImGuiInputTextFlags.ReadOnly; + ImGui.TableSetupColumn("index", ImGuiTableColumnFlags.WidthFixed, 80 * UiHelpers.Scale); + ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthStretch, 1); + if (!disabled) + ImGui.TableSetupColumn("actions", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); + var inputFlags = disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None; for (var materialIndex = 0; materialIndex < materials.Length; materialIndex++) - { - using var id = ImRaii.PushId(materialIndex); + ret |= DrawMaterialRow(tab, disabled, materials, materialIndex, inputFlags); - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.Text($"Material #{materialIndex + 1}"); + if (materials.Length >= MdlMaterialMaximum || disabled) + return ret; - var temp = materials[materialIndex]; - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(-1); - if ( - ImGui.InputText($"##material{materialIndex}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags) - && temp.Length > 0 - && temp != materials[materialIndex] - ) { - materials[materialIndex] = temp; - ret = true; - } + ImGui.TableNextColumn(); - ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + ImGui.InputTextWithHint("##newMaterial", "Add new material...", ref _modelNewMaterial, Utf8GamePath.MaxGamePathLength, inputFlags); + var validName = _modelNewMaterial.Length > 0 && _modelNewMaterial[0] == '/'; + ImGui.TableNextColumn(); + if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, string.Empty, !validName, true)) + return ret; - // Need to have at least one material. - if (materials.Length <= 1) - continue; - - if (ImGuiUtil.DrawDisabledButton( - FontAwesomeIcon.Trash.ToIconString(), - UiHelpers.IconButtonSize, - "Delete this material.\nAny meshes targeting this material will be updated to use material #1.\nHold Control while clicking to delete.", - disabled || !ImGui.GetIO().KeyCtrl, - true - )) { - tab.RemoveMaterial(materialIndex); - ret = true; - } - } - - if (materials.Length < MdlMaterialMaximum) - { - ImGui.TableNextColumn(); - - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(-1); - ImGui.InputTextWithHint($"##newMaterial", "Add new material...", ref _modelNewMaterial, Utf8GamePath.MaxGamePathLength, inputFlags); - - var validName = _modelNewMaterial != ""; - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, "description", disabled || !validName, true)) - { - tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); - _modelNewMaterial = string.Empty; - ret = true; - } - } - - return ret; + tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); + _modelNewMaterial = string.Empty; + return true; } - private static bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) + private bool DrawMaterialRow(MdlTab tab, bool disabled, string[] materials, int materialIndex, ImGuiInputTextFlags inputFlags) { - using var lodNode = ImRaii.TreeNode($"Level of Detail #{lodIndex}", ImGuiTreeNodeFlags.DefaultOpen); + using var id = ImRaii.PushId(materialIndex); + var ret = false; + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted($"Material #{materialIndex + 1}"); + + var temp = materials[materialIndex]; + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(-1); + if (ImGui.InputText($"##material{materialIndex}", ref temp, Utf8GamePath.MaxGamePathLength, inputFlags) + && temp.Length > 0 + && temp != materials[materialIndex] + ) + { + materials[materialIndex] = temp; + ret = true; + } + + if (disabled) + return ret; + + ImGui.TableNextColumn(); + + // Need to have at least one material. + if (materials.Length <= 1) + return ret; + + var tt = "Delete this material.\nAny meshes targeting this material will be updated to use material #1."; + var modifierActive = _config.DeleteModModifier.IsActive(); + if (!modifierActive) + tt += $"\nHold {_config.DeleteModModifier} to delete."; + if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, tt, !modifierActive, true)) + return ret; + + tab.RemoveMaterial(materialIndex); + return true; + } + + private bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) + { + using var lodNode = ImRaii.TreeNode($"Level of Detail #{lodIndex + 1}", ImGuiTreeNodeFlags.DefaultOpen); if (!lodNode) return false; var lod = tab.Mdl.Lods[lodIndex]; - var ret = false; for (var meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) @@ -139,76 +138,89 @@ public partial class ModEditWindow return ret; } - private static bool DrawModelMeshDetails(MdlTab tab, int meshIndex, bool disabled) + private bool DrawModelMeshDetails(MdlTab tab, int meshIndex, bool disabled) { - using var meshNode = ImRaii.TreeNode($"Mesh #{meshIndex}", ImGuiTreeNodeFlags.DefaultOpen); + using var meshNode = ImRaii.TreeNode($"Mesh #{meshIndex + 1}", ImGuiTreeNodeFlags.DefaultOpen); if (!meshNode) return false; - using var id = ImRaii.PushId(meshIndex); + using var id = ImRaii.PushId(meshIndex); using var table = ImRaii.Table(string.Empty, 2, ImGuiTableFlags.SizingFixedFit); if (!table) return false; - ImGui.TableSetupColumn("name", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); + ImGui.TableSetupColumn("name", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); ImGui.TableSetupColumn("field", ImGuiTableColumnFlags.WidthStretch, 1); var file = tab.Mdl; var mesh = file.Meshes[meshIndex]; - var ret = false; // Mesh material ImGui.TableNextColumn(); - ImGui.Text("Material"); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("Material"); ImGui.TableNextColumn(); + var ret = DrawMaterialCombo(tab, meshIndex, disabled); + + // Sub meshes + for (var subMeshOffset = 0; subMeshOffset < mesh.SubMeshCount; subMeshOffset++) + ret |= DrawSubMeshAttributes(tab, meshIndex, disabled, subMeshOffset); + + return ret; + } + + private bool DrawMaterialCombo(MdlTab tab, int meshIndex, bool disabled) + { + var mesh = tab.Mdl.Meshes[meshIndex]; + using var _ = ImRaii.Disabled(disabled); ImGui.SetNextItemWidth(-1); - using (var materialCombo = ImRaii.Combo("##material", tab.Mdl.Materials[mesh.MaterialIndex])) + using var materialCombo = ImRaii.Combo("##material", tab.Mdl.Materials[mesh.MaterialIndex]); + + if (!materialCombo) + return false; + + var ret = false; + foreach (var (material, materialIndex) in tab.Mdl.Materials.WithIndex()) { - if (materialCombo) - { - foreach (var (material, materialIndex) in tab.Mdl.Materials.WithIndex()) - { - if (ImGui.Selectable(material, mesh.MaterialIndex == materialIndex)) - { - file.Meshes[meshIndex].MaterialIndex = (ushort)materialIndex; - ret = true; - } - } - } - } + if (!ImGui.Selectable(material, mesh.MaterialIndex == materialIndex)) + continue; - // Submeshes - for (var submeshOffset = 0; submeshOffset < mesh.SubMeshCount; submeshOffset++) - { - using var submeshId = ImRaii.PushId(submeshOffset); - - var submeshIndex = mesh.SubMeshIndex + submeshOffset; - - ImGui.TableNextColumn(); - ImGui.Text($"Attributes #{submeshOffset}"); - - ImGui.TableNextColumn(); - var widget = _submeshAttributeTagWidgets[submeshIndex]; - var attributes = tab.GetSubmeshAttributes(submeshIndex); - - var tagIndex = widget.Draw("", "", attributes, out var editedAttribute, !disabled); - if (tagIndex >= 0) - { - tab.UpdateSubmeshAttribute( - submeshIndex, - tagIndex < attributes.Count() ? attributes.ElementAt(tagIndex) : null, - editedAttribute != "" ? editedAttribute : null - ); - - ret = true; - } + tab.Mdl.Meshes[meshIndex].MaterialIndex = (ushort)materialIndex; + ret = true; } return ret; } + private bool DrawSubMeshAttributes(MdlTab tab, int meshIndex, bool disabled, int subMeshOffset) + { + using var _ = ImRaii.PushId(subMeshOffset); + + var mesh = tab.Mdl.Meshes[meshIndex]; + var subMeshIndex = mesh.SubMeshIndex + subMeshOffset; + + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted($"Attributes #{subMeshOffset + 1}"); + + ImGui.TableNextColumn(); + var widget = _subMeshAttributeTagWidgets[subMeshIndex]; + var attributes = tab.GetSubMeshAttributes(subMeshIndex); + + var tagIndex = widget.Draw(string.Empty, string.Empty, attributes, + out var editedAttribute, !disabled); + if (tagIndex < 0) + return false; + + var oldName = tagIndex < attributes.Count ? attributes[tagIndex] : null; + var newName = editedAttribute.Length > 0 ? editedAttribute : null; + tab.UpdateSubMeshAttribute(subMeshIndex, oldName, newName); + + return true; + } + private static bool DrawOtherModelDetails(MdlFile file, bool _) { if (!ImGui.CollapsingHeader("Further Content")) From 28752e2630869929944657287b2ad5aa1a6bbbb3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 24 Dec 2023 14:35:59 +0100 Subject: [PATCH 0279/1381] Fix issues with EQDP files for invalid characters. --- Penumbra/Collections/Cache/EqdpCache.cs | 16 +++++++++++++--- Penumbra/Collections/Cache/MetaCache.cs | 2 +- .../Collections/ModCollection.Cache.Access.cs | 11 ++++++++--- Penumbra/Collections/ModCollection.cs | 4 ++-- 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index 3937fa72..ddc161cd 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -31,12 +31,22 @@ public readonly struct EqdpCache : IDisposable manager.SetFile(_eqdpFiles[i], index); } - public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager, GenderRace genderRace, bool accessory) + public MetaList.MetaReverter? TemporarilySetFiles(MetaFileManager manager, GenderRace genderRace, bool accessory) { var idx = CharacterUtilityData.EqdpIdx(genderRace, accessory); - Debug.Assert(idx >= 0, $"Invalid Gender, Race or Accessory for EQDP file {genderRace}, {accessory}."); + if (idx < 0) + { + Penumbra.Log.Warning($"Invalid Gender, Race or Accessory for EQDP file {genderRace}, {accessory}."); + return null; + } + var i = CharacterUtilityData.EqdpIndices.IndexOf(idx); - Debug.Assert(i >= 0, $"Invalid Gender, Race or Accessory for EQDP file {genderRace}, {accessory}."); + if (i < 0) + { + Penumbra.Log.Warning($"Invalid Gender, Race or Accessory for EQDP file {genderRace}, {accessory}."); + return null; + } + return manager.TemporarilySetFile(_eqdpFiles[i], idx); } diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index d5acf249..0fc665ed 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -170,7 +170,7 @@ public class MetaCache : IDisposable, IEnumerable _eqpCache.TemporarilySetFiles(_manager); - public MetaList.MetaReverter TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) + public MetaList.MetaReverter? TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) => _eqdpCache.TemporarilySetFiles(_manager, genderRace, accessory); public MetaList.MetaReverter TemporarilySetGmpFile() diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index a695c463..5d1d10e2 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -89,9 +89,14 @@ public partial class ModCollection } // Used for short periods of changed files. - public MetaList.MetaReverter TemporarilySetEqdpFile(CharacterUtility utility, GenderRace genderRace, bool accessory) - => _cache?.Meta.TemporarilySetEqdpFile(genderRace, accessory) - ?? utility.TemporarilyResetResource(CharacterUtilityData.EqdpIdx(genderRace, accessory)); + public MetaList.MetaReverter? TemporarilySetEqdpFile(CharacterUtility utility, GenderRace genderRace, bool accessory) + { + if (_cache != null) + return _cache?.Meta.TemporarilySetEqdpFile(genderRace, accessory); + + var idx = CharacterUtilityData.EqdpIdx(genderRace, accessory); + return idx >= 0 ? utility.TemporarilyResetResource(idx) : null; + } public MetaList.MetaReverter TemporarilySetEqpFile(CharacterUtility utility) => _cache?.Meta.TemporarilySetEqpFile() diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index a9f565c6..b63be6cd 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -7,7 +7,7 @@ using Penumbra.Services; namespace Penumbra.Collections; /// -/// A ModCollection is a named set of ModSettings to all of the users' installed mods. +/// A ModCollection is a named set of ModSettings to all the users' installed mods. /// Settings to mods that are not installed anymore are kept as long as no call to CleanUnavailableSettings is made. /// Invariants: /// - Index is the collections index in the ModCollection.Manager @@ -113,7 +113,7 @@ public partial class ModCollection { Debug.Assert(index > 0, "Collection duplicated with non-positive index."); return new ModCollection(name, index, 0, CurrentVersion, Settings.Select(s => s?.DeepCopy()).ToList(), - DirectlyInheritsFrom.ToList(), UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); + [.. DirectlyInheritsFrom], UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); } /// Constructor for reading from files. From f8331bc4d818454e48f225257668f20e1c411b75 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 24 Dec 2023 14:36:21 +0100 Subject: [PATCH 0280/1381] Fix the mod panels header not resetting data when a selected mod updates. --- Penumbra/Communication/ModDataChanged.cs | 5 +++- Penumbra/Mods/Manager/ModFileSystem.cs | 6 ++--- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 3 +-- Penumbra/UI/ModsTab/ModPanel.cs | 5 ++-- Penumbra/UI/ModsTab/ModPanelHeader.cs | 23 +++++++++++++++++-- 5 files changed, 32 insertions(+), 10 deletions(-) diff --git a/Penumbra/Communication/ModDataChanged.cs b/Penumbra/Communication/ModDataChanged.cs index 9ec60aa3..2f50f005 100644 --- a/Penumbra/Communication/ModDataChanged.cs +++ b/Penumbra/Communication/ModDataChanged.cs @@ -21,8 +21,11 @@ public sealed class ModDataChanged : EventWrapper ModCacheManager = 0, - /// + /// ModFileSystem = 0, + + /// + ModPanelHeader = 0, } public ModDataChanged() diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index 1851399d..c8a0a5db 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -21,7 +21,7 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable Reload(); Changed += OnChange; _communicator.ModDiscoveryFinished.Subscribe(Reload, ModDiscoveryFinished.Priority.ModFileSystem); - _communicator.ModDataChanged.Subscribe(OnDataChange, ModDataChanged.Priority.ModFileSystem); + _communicator.ModDataChanged.Subscribe(OnModDataChange, ModDataChanged.Priority.ModFileSystem); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModFileSystem); } @@ -29,7 +29,7 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable { _communicator.ModPathChanged.Unsubscribe(OnModPathChange); _communicator.ModDiscoveryFinished.Unsubscribe(Reload); - _communicator.ModDataChanged.Unsubscribe(OnDataChange); + _communicator.ModDataChanged.Unsubscribe(OnModDataChange); } public struct ImportDate : ISortMode @@ -75,7 +75,7 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable } // Update sort order when defaulted mod names change. - private void OnDataChange(ModDataChangeType type, Mod mod, string? oldName) + private void OnModDataChange(ModDataChangeType type, Mod mod, string? oldName) { if (!type.HasFlag(ModDataChangeType.Name) || oldName == null || !FindLeaf(mod, out var leaf)) return; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 25bb012a..e4646d07 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -155,7 +155,6 @@ public partial class ModEditWindow var file = tab.Mdl; var mesh = file.Meshes[meshIndex]; - // Mesh material ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); @@ -171,7 +170,7 @@ public partial class ModEditWindow return ret; } - private bool DrawMaterialCombo(MdlTab tab, int meshIndex, bool disabled) + private static bool DrawMaterialCombo(MdlTab tab, int meshIndex, bool disabled) { var mesh = tab.Mdl.Meshes[meshIndex]; using var _ = ImRaii.Disabled(disabled); diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index 15961ff3..f9a3262f 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin; using Penumbra.Mods; +using Penumbra.Services; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; @@ -13,13 +14,13 @@ public class ModPanel : IDisposable private readonly ModPanelTabBar _tabs; public ModPanel(DalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs, - MultiModPanel multiModPanel) + MultiModPanel multiModPanel, CommunicatorService communicator) { _selector = selector; _editWindow = editWindow; _tabs = tabs; _multiModPanel = multiModPanel; - _header = new ModPanelHeader(pi); + _header = new ModPanelHeader(pi, communicator); _selector.SelectionChanged += OnSelectionChange; } diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index 2c71426f..4b127059 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -3,7 +3,10 @@ using Dalamud.Plugin; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using Penumbra.Communication; using Penumbra.Mods; +using Penumbra.Mods.Manager; +using Penumbra.Services; using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; @@ -13,8 +16,14 @@ public class ModPanelHeader : IDisposable /// We use a big, nice game font for the title. private readonly GameFontHandle _nameFont; - public ModPanelHeader(DalamudPluginInterface pi) - => _nameFont = pi.UiBuilder.GetGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); + private readonly CommunicatorService _communicator; + + public ModPanelHeader(DalamudPluginInterface pi, CommunicatorService communicator) + { + _communicator = communicator; + _nameFont = pi.UiBuilder.GetGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); + _communicator.ModDataChanged.Subscribe(OnModDataChange, ModDataChanged.Priority.ModPanelHeader); + } /// /// Draw the header for the current mod, @@ -76,6 +85,7 @@ public class ModPanelHeader : IDisposable public void Dispose() { _nameFont.Dispose(); + _communicator.ModDataChanged.Unsubscribe(OnModDataChange); } // Header data. @@ -218,4 +228,13 @@ public class ModPanelHeader : IDisposable ImGui.TextUnformatted(_modWebsite); } } + + /// Just update the data when any relevant field changes. + private void OnModDataChange(ModDataChangeType changeType, Mod mod, string? _2) + { + const ModDataChangeType relevantChanges = + ModDataChangeType.Author | ModDataChangeType.Name | ModDataChangeType.Website | ModDataChangeType.Version; + if ((changeType & relevantChanges) != 0) + UpdateModData(mod); + } } From df430831010f85b7970b5ec790107ef4ee726f81 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 27 Dec 2023 01:21:26 +1100 Subject: [PATCH 0281/1381] export per example --- Penumbra/Import/Models/ModelManager.cs | 45 +++++++++++++++++++ Penumbra/Penumbra.csproj | 2 + Penumbra/Services/ServiceManager.cs | 4 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 8 ++++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 4 +- Penumbra/packages.lock.json | 23 ++++++++++ 6 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 Penumbra/Import/Models/ModelManager.cs diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs new file mode 100644 index 00000000..33ad9249 --- /dev/null +++ b/Penumbra/Import/Models/ModelManager.cs @@ -0,0 +1,45 @@ +using Penumbra.GameData.Files; +using SharpGLTF.Geometry; +using SharpGLTF.Geometry.VertexTypes; +using SharpGLTF.Materials; +using SharpGLTF.Scenes; + +namespace Penumbra.Import.Models; + +public sealed class ModelManager +{ + public ModelManager() + { + // + } + + // TODO: Consider moving import/export onto an async queue, check ../textures/texturemanager + + public void ExportToGltf(/* MdlFile mdl, */string path) + { + var mesh = new MeshBuilder("mesh"); + + var material1 = new MaterialBuilder() + .WithDoubleSide(true) + .WithMetallicRoughnessShader() + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 0, 1)); + var primitive1 = mesh.UsePrimitive(material1); + primitive1.AddTriangle(new VertexPosition(-10, 0, 0), new VertexPosition(10, 0, 0), new VertexPosition(0, 10, 0)); + primitive1.AddTriangle(new VertexPosition(10, 0, 0), new VertexPosition(-10, 0, 0), new VertexPosition(0, -10, 0)); + + var material2 = new MaterialBuilder() + .WithDoubleSide(true) + .WithMetallicRoughnessShader() + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 1, 1)); + var primitive2 = mesh.UsePrimitive(material2); + primitive2.AddQuadrangle(new VertexPosition(-5, 0, 3), new VertexPosition(0, -5, 3), new VertexPosition(5, 0, 3), new VertexPosition(0, 5, 3)); + + var scene = new SceneBuilder(); + scene.AddRigidMesh(mesh, Matrix4x4.Identity); + + var model = scene.ToGltf2(); + model.SaveGLTF(path); + + // TODO: Draw the rest of the owl. + } +} diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index ec433113..122e17b5 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -72,6 +72,8 @@ + + diff --git a/Penumbra/Services/ServiceManager.cs b/Penumbra/Services/ServiceManager.cs index 73be8834..5a107060 100644 --- a/Penumbra/Services/ServiceManager.cs +++ b/Penumbra/Services/ServiceManager.cs @@ -8,6 +8,7 @@ using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.GameData; using Penumbra.GameData.Data; +using Penumbra.Import.Models; using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; @@ -185,7 +186,8 @@ public static class ServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static IServiceCollection AddApi(this IServiceCollection services) => services.AddSingleton() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index e4646d07..80831dab 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -5,6 +5,7 @@ using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.GameData; using Penumbra.GameData.Files; +using Penumbra.Import.Models; using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -13,6 +14,8 @@ public partial class ModEditWindow { private const int MdlMaterialMaximum = 4; + private readonly ModelManager _models; + private readonly FileEditor _modelTab; private string _modelNewMaterial = string.Empty; @@ -31,6 +34,11 @@ public partial class ModEditWindow ); } + if (ImGui.Button("bingo bango")) + { + _models.ExportToGltf("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); + } + var ret = false; ret |= DrawModelMaterialDetails(tab, disabled); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 365c4a4a..1a3d9182 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -12,6 +12,7 @@ using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; +using Penumbra.Import.Models; using Penumbra.Import.Textures; using Penumbra.Interop.ResourceTree; using Penumbra.Interop.Services; @@ -563,7 +564,7 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, DalamudServices dalamud, ModMergeTab modMergeTab, - CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, GameEventManager gameEvents, + CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, GameEventManager gameEvents, ChangedItemDrawer changedItemDrawer) : base(WindowBaseLabel) { @@ -579,6 +580,7 @@ public partial class ModEditWindow : Window, IDisposable _communicator = communicator; _dragDropManager = dragDropManager; _textures = textures; + _models = models; _fileDialog = fileDialog; _gameEvents = gameEvents; _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index eed5d7c8..cef49e9c 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -26,6 +26,21 @@ "resolved": "0.33.0", "contentHash": "FlHfpTAADzaSlVCBF33iKJk9UhOr3Xj+r5LXbW2GzqYr0SrhiOf6shLX2LC2fqs7g7d+YlwKbBXqWFtb+e7icw==" }, + "SharpGLTF.Core": { + "type": "Direct", + "requested": "[1.0.0-alpha0030, )", + "resolved": "1.0.0-alpha0030", + "contentHash": "HVL6PcrM0H/uEk96nRZfhtPeYvSFGHnni3g1aIckot2IWVp0jLMH5KWgaWfsatEz4Yds3XcdSLUWmJZivDBUPA==" + }, + "SharpGLTF.Toolkit": { + "type": "Direct", + "requested": "[1.0.0-alpha0030, )", + "resolved": "1.0.0-alpha0030", + "contentHash": "nsoJWAFhXgEky9bVCY0zLeZVDx+S88u7VjvuebvMb6dJiNyFOGF6FrrMHiJe+x5pcVBxxlc3VoXliBF7r/EqYA==", + "dependencies": { + "SharpGLTF.Runtime": "1.0.0-alpha0030" + } + }, "SixLabors.ImageSharp": { "type": "Direct", "requested": "[2.1.2, )", @@ -46,6 +61,14 @@ "resolved": "5.0.0", "contentHash": "VyPlqzH2wavqquTcYpkIIAQ6WdenuKoFN0BdYBbCWsclXacSOHNQn66Gt4z5NBqEYW0FAPm5rlvki9ZiCij5xQ==" }, + "SharpGLTF.Runtime": { + "type": "Transitive", + "resolved": "1.0.0-alpha0030", + "contentHash": "Ysn+fyj9EVXj6mfG0BmzSTBGNi/QvcnTrMd54dBMOlI/TsMRvnOY3JjTn0MpeH2CgHXX4qogzlDt4m+rb3n4Og==", + "dependencies": { + "SharpGLTF.Core": "1.0.0-alpha0030" + } + }, "System.Runtime.CompilerServices.Unsafe": { "type": "Transitive", "resolved": "5.0.0", From ed283afe2caa835cdbe6994c31852ff25510481d Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 27 Dec 2023 01:44:24 +1100 Subject: [PATCH 0282/1381] async is a great idea lets do more of that --- Penumbra/Import/Models/ModelManager.cs | 98 ++++++++++++++----- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 11 ++- 2 files changed, 81 insertions(+), 28 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 33ad9249..fbccf4b7 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Tasks; using Penumbra.GameData.Files; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; @@ -6,40 +7,89 @@ using SharpGLTF.Scenes; namespace Penumbra.Import.Models; -public sealed class ModelManager +public sealed class ModelManager : SingleTaskQueue, IDisposable { + private readonly ConcurrentDictionary _tasks = new(); + private bool _disposed = false; + public ModelManager() { // } - // TODO: Consider moving import/export onto an async queue, check ../textures/texturemanager - - public void ExportToGltf(/* MdlFile mdl, */string path) + public void Dispose() { - var mesh = new MeshBuilder("mesh"); + _disposed = true; + foreach (var (_, cancel) in _tasks.Values.ToArray()) + cancel.Cancel(); + _tasks.Clear(); + } - var material1 = new MaterialBuilder() - .WithDoubleSide(true) - .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 0, 1)); - var primitive1 = mesh.UsePrimitive(material1); - primitive1.AddTriangle(new VertexPosition(-10, 0, 0), new VertexPosition(10, 0, 0), new VertexPosition(0, 10, 0)); - primitive1.AddTriangle(new VertexPosition(10, 0, 0), new VertexPosition(-10, 0, 0), new VertexPosition(0, -10, 0)); - - var material2 = new MaterialBuilder() - .WithDoubleSide(true) - .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 1, 1)); - var primitive2 = mesh.UsePrimitive(material2); - primitive2.AddQuadrangle(new VertexPosition(-5, 0, 3), new VertexPosition(0, -5, 3), new VertexPosition(5, 0, 3), new VertexPosition(0, 5, 3)); + private Task Enqueue(IAction action) + { + if (_disposed) + return Task.FromException(new ObjectDisposedException(nameof(ModelManager))); - var scene = new SceneBuilder(); - scene.AddRigidMesh(mesh, Matrix4x4.Identity); + Task task; + lock (_tasks) + { + task = _tasks.GetOrAdd(action, action => + { + var token = new CancellationTokenSource(); + var task = Enqueue(action, token.Token); + task.ContinueWith(_ => _tasks.TryRemove(action, out var unused), CancellationToken.None); + return (task, token); + }).Item1; + } - var model = scene.ToGltf2(); - model.SaveGLTF(path); + return task; + } - // TODO: Draw the rest of the owl. + public Task ExportToGltf(/* MdlFile mdl, */string path) + => Enqueue(new ExportToGltfAction(path)); + + private class ExportToGltfAction : IAction + { + private readonly string _path; + + public ExportToGltfAction(string path) + { + _path = path; + } + + public void Execute(CancellationToken token) + { + var mesh = new MeshBuilder("mesh"); + + var material1 = new MaterialBuilder() + .WithDoubleSide(true) + .WithMetallicRoughnessShader() + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 0, 1)); + var primitive1 = mesh.UsePrimitive(material1); + primitive1.AddTriangle(new VertexPosition(-10, 0, 0), new VertexPosition(10, 0, 0), new VertexPosition(0, 10, 0)); + primitive1.AddTriangle(new VertexPosition(10, 0, 0), new VertexPosition(-10, 0, 0), new VertexPosition(0, -10, 0)); + + var material2 = new MaterialBuilder() + .WithDoubleSide(true) + .WithMetallicRoughnessShader() + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 1, 1)); + var primitive2 = mesh.UsePrimitive(material2); + primitive2.AddQuadrangle(new VertexPosition(-5, 0, 3), new VertexPosition(0, -5, 3), new VertexPosition(5, 0, 3), new VertexPosition(0, 5, 3)); + + var scene = new SceneBuilder(); + scene.AddRigidMesh(mesh, Matrix4x4.Identity); + + var model = scene.ToGltf2(); + model.SaveGLTF(_path); + } + + public bool Equals(IAction? other) + { + if (other is not ExportToGltfAction rhs) + return false; + + // TODO: compare configuration + return true; + } } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 80831dab..89497cfd 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -14,10 +14,11 @@ public partial class ModEditWindow { private const int MdlMaterialMaximum = 4; - private readonly ModelManager _models; - private readonly FileEditor _modelTab; + private readonly ModelManager _models; + private bool _pendingIo = false; + private string _modelNewMaterial = string.Empty; private readonly List _subMeshAttributeTagWidgets = []; @@ -34,9 +35,11 @@ public partial class ModEditWindow ); } - if (ImGui.Button("bingo bango")) + if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", _pendingIo)) { - _models.ExportToGltf("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); + _pendingIo = true; + var task = _models.ExportToGltf("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); + task.ContinueWith(_ => _pendingIo = false); } var ret = false; From b7472f722ee991166fb5d874419d3e25cbfb97fa Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 27 Dec 2023 16:17:39 +1100 Subject: [PATCH 0283/1381] poc submesh position export --- Penumbra/Import/Models/ModelManager.cs | 71 ++++++++++++++----- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 2 +- 2 files changed, 55 insertions(+), 18 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index fbccf4b7..bded3b0c 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,3 +1,4 @@ +using Lumina.Extensions; using OtterGui.Tasks; using Penumbra.GameData.Files; using SharpGLTF.Geometry; @@ -45,39 +46,75 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable return task; } - public Task ExportToGltf(/* MdlFile mdl, */string path) - => Enqueue(new ExportToGltfAction(path)); + public Task ExportToGltf(MdlFile mdl, string path) + => Enqueue(new ExportToGltfAction(mdl, path)); private class ExportToGltfAction : IAction { + private readonly MdlFile _mdl; private readonly string _path; - public ExportToGltfAction(string path) + public ExportToGltfAction(MdlFile mdl, string path) { + _mdl = mdl; _path = path; } public void Execute(CancellationToken token) { - var mesh = new MeshBuilder("mesh"); + var meshBuilder = new MeshBuilder("mesh"); - var material1 = new MaterialBuilder() + var material = new MaterialBuilder() .WithDoubleSide(true) .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 0, 1)); - var primitive1 = mesh.UsePrimitive(material1); - primitive1.AddTriangle(new VertexPosition(-10, 0, 0), new VertexPosition(10, 0, 0), new VertexPosition(0, 10, 0)); - primitive1.AddTriangle(new VertexPosition(10, 0, 0), new VertexPosition(-10, 0, 0), new VertexPosition(0, -10, 0)); - - var material2 = new MaterialBuilder() - .WithDoubleSide(true) - .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 0, 1, 1)); - var primitive2 = mesh.UsePrimitive(material2); - primitive2.AddQuadrangle(new VertexPosition(-5, 0, 3), new VertexPosition(0, -5, 3), new VertexPosition(5, 0, 3), new VertexPosition(0, 5, 3)); + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 1, 1, 1)); + + // lol, lmao even + var meshIndex = 2; + var lod = 0; + + var mesh = _mdl.Meshes[meshIndex]; + var submesh = _mdl.SubMeshes[mesh.SubMeshIndex]; // just first for now + + var positionVertexElement = _mdl.VertexDeclarations[meshIndex].VertexElements + .Where(decl => decl.Usage == 0 /* POSITION */) + .First(); + + // reading in the entire indices list + var dataReader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); + dataReader.Seek(_mdl.IndexOffset[lod]); + var indices = dataReader.ReadStructuresAsArray((int)_mdl.IndexBufferSize[lod] / sizeof(ushort)); + + // read in verts for this mesh + var baseOffset = _mdl.VertexOffset[lod] + mesh.VertexBufferOffset[positionVertexElement.Stream] + positionVertexElement.Offset; + var vertices = new List(); + for (var vertexIndex = 0; vertexIndex < mesh.VertexCount; vertexIndex++) + { + dataReader.Seek(baseOffset + vertexIndex * mesh.VertexBufferStride[positionVertexElement.Stream]); + // todo handle type + vertices.Add(new VertexPosition( + dataReader.ReadSingle(), + dataReader.ReadSingle(), + dataReader.ReadSingle() + )); + } + + // build a primitive for the submesh + var primitiveBuilder = meshBuilder.UsePrimitive(material); + // they're all tri list + for (var indexOffset = 0; indexOffset < submesh.IndexCount; indexOffset += 3) + { + var index = indexOffset + submesh.IndexOffset; + + primitiveBuilder.AddTriangle( + vertices[indices[index + 0]], + vertices[indices[index + 1]], + vertices[indices[index + 2]] + ); + } var scene = new SceneBuilder(); - scene.AddRigidMesh(mesh, Matrix4x4.Identity); + scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); var model = scene.ToGltf2(); model.SaveGLTF(_path); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 89497cfd..b64b4f40 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -38,7 +38,7 @@ public partial class ModEditWindow if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", _pendingIo)) { _pendingIo = true; - var task = _models.ExportToGltf("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); + var task = _models.ExportToGltf(file, "C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); task.ContinueWith(_ => _pendingIo = false); } From 81425b458e043ae98c25c0cddbf1e53de3a94c35 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 27 Dec 2023 17:25:14 +1100 Subject: [PATCH 0284/1381] Use vertex element enums --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ffdb966f..0dc4c892 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ffdb966fec5a657893289e655c641ceb3af1d59f +Subproject commit 0dc4c892308aea30314d118362b3ebab7706f4e5 diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index bded3b0c..5e931b36 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -77,7 +77,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var submesh = _mdl.SubMeshes[mesh.SubMeshIndex]; // just first for now var positionVertexElement = _mdl.VertexDeclarations[meshIndex].VertexElements - .Where(decl => decl.Usage == 0 /* POSITION */) + .Where(decl => (MdlFile.VertexUsage)decl.Usage == MdlFile.VertexUsage.Position) .First(); // reading in the entire indices list From ca46e7482f5dd2eeba323bd082a8d5d67b05d826 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 28 Dec 2023 00:44:19 +1100 Subject: [PATCH 0285/1381] Flesh out geometry handling --- Penumbra/Import/Models/ModelManager.cs | 149 ++++++++++++++++++++++--- 1 file changed, 131 insertions(+), 18 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 5e931b36..af285cbb 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,3 +1,5 @@ +using System.Collections.Immutable; +using Lumina.Data.Parsing; using Lumina.Extensions; using OtterGui.Tasks; using Penumbra.GameData.Files; @@ -62,17 +64,26 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public void Execute(CancellationToken token) { - var meshBuilder = new MeshBuilder("mesh"); + // lol, lmao even + var meshIndex = 2; + var lod = 0; + + var elements = _mdl.VertexDeclarations[meshIndex].VertexElements; + + var usages = elements + .Select(element => (MdlFile.VertexUsage)element.Usage) + .ToImmutableHashSet(); + var geometryType = GetGeometryType(usages); + + // TODO: probablly can do this a bit later but w/e + var meshBuilderType = typeof(MeshBuilder<,,>).MakeGenericType(geometryType, typeof(VertexEmpty), typeof(VertexEmpty)); + var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, "mesh2")!; var material = new MaterialBuilder() .WithDoubleSide(true) .WithMetallicRoughnessShader() .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 1, 1, 1)); - // lol, lmao even - var meshIndex = 2; - var lod = 0; - var mesh = _mdl.Meshes[meshIndex]; var submesh = _mdl.SubMeshes[mesh.SubMeshIndex]; // just first for now @@ -86,18 +97,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var indices = dataReader.ReadStructuresAsArray((int)_mdl.IndexBufferSize[lod] / sizeof(ushort)); // read in verts for this mesh - var baseOffset = _mdl.VertexOffset[lod] + mesh.VertexBufferOffset[positionVertexElement.Stream] + positionVertexElement.Offset; - var vertices = new List(); - for (var vertexIndex = 0; vertexIndex < mesh.VertexCount; vertexIndex++) - { - dataReader.Seek(baseOffset + vertexIndex * mesh.VertexBufferStride[positionVertexElement.Stream]); - // todo handle type - vertices.Add(new VertexPosition( - dataReader.ReadSingle(), - dataReader.ReadSingle(), - dataReader.ReadSingle() - )); - } + var vertices = BuildVertices(lod, mesh, _mdl.VertexDeclarations[meshIndex].VertexElements, geometryType); // build a primitive for the submesh var primitiveBuilder = meshBuilder.UsePrimitive(material); @@ -120,12 +120,125 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable model.SaveGLTF(_path); } + // todo all of this is mesh specific so probably should be a class per mesh? with the lod, too? + private IReadOnlyList BuildVertices(int lod, MdlStructs.MeshStruct mesh, IEnumerable elements, Type geometryType) + { + var vertexBuilderType = typeof(VertexBuilder<,,>).MakeGenericType(geometryType, typeof(VertexEmpty), typeof(VertexEmpty)); + + // todo: demagic the 3 + // todo note this assumes that the buffer streams are tightly packed. that's a safe assumption - right? lumina assumes as much + var streams = new BinaryReader[3]; + for (var streamIndex = 0; streamIndex < 3; streamIndex++) + { + streams[streamIndex] = new BinaryReader(new MemoryStream(_mdl.RemainingData)); + streams[streamIndex].Seek(_mdl.VertexOffset[lod] + mesh.VertexBufferOffset[streamIndex]); + } + + var sortedElements = elements + .OrderBy(element => element.Offset) + .ToList(); + + var vertices = new List(); + + // note this is being reused + var attributes = new Dictionary(); + for (var vertexIndex = 0; vertexIndex < mesh.VertexCount; vertexIndex++) + { + attributes.Clear(); + + foreach (var element in sortedElements) + attributes[(MdlFile.VertexUsage)element.Usage] = ReadVertexAttribute(streams[element.Stream], element); + + var vertexGeometry = BuildVertexGeometry(geometryType, attributes); + + var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, new VertexEmpty(), new VertexEmpty())!; + vertices.Add(vertexBuilder); + } + + return vertices; + } + + // todo i fucking hate this `object` type god i hate c# gimme sum types pls + private object ReadVertexAttribute(BinaryReader reader, MdlStructs.VertexElement element) + { + return (MdlFile.VertexType)element.Type switch + { + MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), + MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), + MdlFile.VertexType.UInt => reader.ReadBytes(4), + MdlFile.VertexType.ByteFloat4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), + MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), + MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), + + _ => throw new ArgumentOutOfRangeException() + }; + } + + private Type GetGeometryType(IReadOnlySet usages) + { + if (!usages.Contains(MdlFile.VertexUsage.Position)) + throw new Exception("Mesh does not contain position vertex elements."); + + if (!usages.Contains(MdlFile.VertexUsage.Normal)) + return typeof(VertexPosition); + + if (!usages.Contains(MdlFile.VertexUsage.Tangent1)) + return typeof(VertexPositionNormal); + + return typeof(VertexPositionNormalTangent); + } + + private IVertexGeometry BuildVertexGeometry(Type geometryType, IReadOnlyDictionary attributes) + { + if (geometryType == typeof(VertexPosition)) + return new VertexPosition( + ToVector3(attributes[MdlFile.VertexUsage.Position]) + ); + + if (geometryType == typeof(VertexPositionNormal)) + return new VertexPositionNormal( + ToVector3(attributes[MdlFile.VertexUsage.Position]), + ToVector3(attributes[MdlFile.VertexUsage.Normal]) + ); + + if (geometryType == typeof(VertexPositionNormalTangent)) + return new VertexPositionNormalTangent( + ToVector3(attributes[MdlFile.VertexUsage.Position]), + ToVector3(attributes[MdlFile.VertexUsage.Normal]), + ToVector4(attributes[MdlFile.VertexUsage.Tangent1]) + ); + + throw new Exception($"Unknown geometry type {geometryType}."); + } + + private Vector3 ToVector3(object data) + { + return data switch + { + Vector2 v2 => new Vector3(v2.X, v2.Y, 0), + Vector3 v3 => v3, + Vector4 v4 => new Vector3(v4.X, v4.Y, v4.Z), + _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") + }; + } + + private Vector4 ToVector4(object data) + { + return data switch + { + Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0), + Vector3 v3 => new Vector4(v3.X, v3.Y, v3.Z, 1), + Vector4 v4 => v4, + _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") + }; + } + public bool Equals(IAction? other) { if (other is not ExportToGltfAction rhs) return false; - // TODO: compare configuration + // TODO: compare configuration and such return true; } } From bc24110c9f6860ab5da2082174911a9eb992c4ae Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 28 Dec 2023 02:15:14 +1100 Subject: [PATCH 0286/1381] Move mesh logic to new file, export all meshes --- Penumbra/Import/Models/MeshConverter.cs | 191 ++++++++++++++++++++++++ Penumbra/Import/Models/ModelManager.cs | 183 ++--------------------- 2 files changed, 205 insertions(+), 169 deletions(-) create mode 100644 Penumbra/Import/Models/MeshConverter.cs diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/MeshConverter.cs new file mode 100644 index 00000000..2fcd2816 --- /dev/null +++ b/Penumbra/Import/Models/MeshConverter.cs @@ -0,0 +1,191 @@ +using System.Collections.Immutable; +using Lumina.Data.Parsing; +using Lumina.Extensions; +using Penumbra.GameData.Files; +using SharpGLTF.Geometry; +using SharpGLTF.Geometry.VertexTypes; +using SharpGLTF.Materials; + +namespace Penumbra.Import.Modules; + +public sealed class MeshConverter +{ + public static IMeshBuilder ToGltf(MdlFile mdl, byte lod, ushort meshIndex) + { + var self = new MeshConverter(mdl, lod, meshIndex); + return self.BuildMesh(); + } + + private const byte MaximumMeshBufferStreams = 3; + + private readonly MdlFile _mdl; + private readonly byte _lod; + private readonly ushort _meshIndex; + private MdlStructs.MeshStruct Mesh => _mdl.Meshes[_meshIndex]; + + private readonly Type _geometryType; + + private MeshConverter(MdlFile mdl, byte lod, ushort meshIndex) + { + _mdl = mdl; + _lod = lod; + _meshIndex = meshIndex; + + var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements + .Select(element => (MdlFile.VertexUsage)element.Usage) + .ToImmutableHashSet(); + + _geometryType = GetGeometryType(usages); + } + + private IMeshBuilder BuildMesh() + { + var indices = BuildIndices(); + var vertices = BuildVertices(); + + var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( + typeof(MaterialBuilder), + _geometryType, + typeof(VertexEmpty), + typeof(VertexEmpty) + ); + var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, $"mesh{_meshIndex}")!; + + // TODO: share materials &c + var materialBuilder = new MaterialBuilder() + .WithDoubleSide(true) + .WithMetallicRoughnessShader() + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 1, 1, 1)); + + var primitiveBuilder = meshBuilder.UsePrimitive(materialBuilder); + + // All XIV meshes use triangle lists. + // TODO: split by submeshes + for (var indexOffset = 0; indexOffset < Mesh.IndexCount; indexOffset += 3) + primitiveBuilder.AddTriangle( + vertices[indices[indexOffset + 0]], + vertices[indices[indexOffset + 1]], + vertices[indices[indexOffset + 2]] + ); + + return meshBuilder; + } + + private IReadOnlyList BuildIndices() + { + var reader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); + reader.Seek(_mdl.IndexOffset[_lod] + Mesh.StartIndex * sizeof(ushort)); + return reader.ReadStructuresAsArray((int)Mesh.IndexCount); + } + + private IReadOnlyList BuildVertices() + { + var vertexBuilderType = typeof(VertexBuilder<,,>) + .MakeGenericType(_geometryType, typeof(VertexEmpty), typeof(VertexEmpty)); + + // NOTE: This assumes that buffer streams are tightly packed, which has proven safe across tested files. If this assumption is broken, seeks will need to be moved into the vertex element loop. + var streams = new BinaryReader[MaximumMeshBufferStreams]; + for (var streamIndex = 0; streamIndex < MaximumMeshBufferStreams; streamIndex++) + { + streams[streamIndex] = new BinaryReader(new MemoryStream(_mdl.RemainingData)); + streams[streamIndex].Seek(_mdl.VertexOffset[_lod] + Mesh.VertexBufferOffset[streamIndex]); + } + + var sortedElements = _mdl.VertexDeclarations[_meshIndex].VertexElements + .OrderBy(element => element.Offset) + .Select(element => ((MdlFile.VertexUsage)element.Usage, element)) + .ToList(); + + var vertices = new List(); + + var attributes = new Dictionary(); + for (var vertexIndex = 0; vertexIndex < Mesh.VertexCount; vertexIndex++) + { + attributes.Clear(); + + foreach (var (usage, element) in sortedElements) + attributes[usage] = ReadVertexAttribute(streams[element.Stream], element); + + var vertexGeometry = BuildVertexGeometry(attributes); + + var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, new VertexEmpty(), new VertexEmpty())!; + vertices.Add(vertexBuilder); + } + + return vertices; + } + + private object ReadVertexAttribute(BinaryReader reader, MdlStructs.VertexElement element) + { + return (MdlFile.VertexType)element.Type switch + { + MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), + MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), + MdlFile.VertexType.UInt => reader.ReadBytes(4), + MdlFile.VertexType.ByteFloat4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), + MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), + MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), + + _ => throw new ArgumentOutOfRangeException() + }; + } + + private Type GetGeometryType(IReadOnlySet usages) + { + if (!usages.Contains(MdlFile.VertexUsage.Position)) + throw new Exception("Mesh does not contain position vertex elements."); + + if (!usages.Contains(MdlFile.VertexUsage.Normal)) + return typeof(VertexPosition); + + if (!usages.Contains(MdlFile.VertexUsage.Tangent1)) + return typeof(VertexPositionNormal); + + return typeof(VertexPositionNormalTangent); + } + + private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary attributes) + { + if (_geometryType == typeof(VertexPosition)) + return new VertexPosition( + ToVector3(attributes[MdlFile.VertexUsage.Position]) + ); + + if (_geometryType == typeof(VertexPositionNormal)) + return new VertexPositionNormal( + ToVector3(attributes[MdlFile.VertexUsage.Position]), + ToVector3(attributes[MdlFile.VertexUsage.Normal]) + ); + + if (_geometryType == typeof(VertexPositionNormalTangent)) + return new VertexPositionNormalTangent( + ToVector3(attributes[MdlFile.VertexUsage.Position]), + ToVector3(attributes[MdlFile.VertexUsage.Normal]), + FixTangentVector(ToVector4(attributes[MdlFile.VertexUsage.Tangent1])) + ); + + throw new Exception($"Unknown geometry type {_geometryType}."); + } + + // Some tangent W values that should be -1 are stored as 0. + private Vector4 FixTangentVector(Vector4 tangent) + => tangent with { W = tangent.W == 1 ? 1 : -1 }; + + private Vector3 ToVector3(object data) + => data switch + { + Vector2 v2 => new Vector3(v2.X, v2.Y, 0), + Vector3 v3 => v3, + Vector4 v4 => new Vector3(v4.X, v4.Y, v4.Z), + _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") + }; + + private Vector4 ToVector4(object data) + => data switch + { + Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0), + Vector3 v3 => new Vector4(v3.X, v3.Y, v3.Z, 1), + Vector4 v4 => v4, + _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") + }; +} diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index af285cbb..429aad54 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,11 +1,6 @@ -using System.Collections.Immutable; -using Lumina.Data.Parsing; -using Lumina.Extensions; using OtterGui.Tasks; using Penumbra.GameData.Files; -using SharpGLTF.Geometry; -using SharpGLTF.Geometry.VertexTypes; -using SharpGLTF.Materials; +using Penumbra.Import.Modules; using SharpGLTF.Scenes; namespace Penumbra.Import.Models; @@ -64,175 +59,25 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public void Execute(CancellationToken token) { - // lol, lmao even - var meshIndex = 2; - var lod = 0; - - var elements = _mdl.VertexDeclarations[meshIndex].VertexElements; - - var usages = elements - .Select(element => (MdlFile.VertexUsage)element.Usage) - .ToImmutableHashSet(); - var geometryType = GetGeometryType(usages); - - // TODO: probablly can do this a bit later but w/e - var meshBuilderType = typeof(MeshBuilder<,,>).MakeGenericType(geometryType, typeof(VertexEmpty), typeof(VertexEmpty)); - var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, "mesh2")!; - - var material = new MaterialBuilder() - .WithDoubleSide(true) - .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 1, 1, 1)); - - var mesh = _mdl.Meshes[meshIndex]; - var submesh = _mdl.SubMeshes[mesh.SubMeshIndex]; // just first for now - - var positionVertexElement = _mdl.VertexDeclarations[meshIndex].VertexElements - .Where(decl => (MdlFile.VertexUsage)decl.Usage == MdlFile.VertexUsage.Position) - .First(); - - // reading in the entire indices list - var dataReader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - dataReader.Seek(_mdl.IndexOffset[lod]); - var indices = dataReader.ReadStructuresAsArray((int)_mdl.IndexBufferSize[lod] / sizeof(ushort)); - - // read in verts for this mesh - var vertices = BuildVertices(lod, mesh, _mdl.VertexDeclarations[meshIndex].VertexElements, geometryType); - - // build a primitive for the submesh - var primitiveBuilder = meshBuilder.UsePrimitive(material); - // they're all tri list - for (var indexOffset = 0; indexOffset < submesh.IndexCount; indexOffset += 3) - { - var index = indexOffset + submesh.IndexOffset; - - primitiveBuilder.AddTriangle( - vertices[indices[index + 0]], - vertices[indices[index + 1]], - vertices[indices[index + 2]] - ); - } - var scene = new SceneBuilder(); - scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); + + // TODO: group by LoD in output tree + for (byte lodIndex = 0; lodIndex < _mdl.LodCount; lodIndex++) + { + var lod = _mdl.Lods[lodIndex]; + + // TODO: consider other types? + for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) + { + var meshBuilder = MeshConverter.ToGltf(_mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset)); + scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); + } + } var model = scene.ToGltf2(); model.SaveGLTF(_path); } - // todo all of this is mesh specific so probably should be a class per mesh? with the lod, too? - private IReadOnlyList BuildVertices(int lod, MdlStructs.MeshStruct mesh, IEnumerable elements, Type geometryType) - { - var vertexBuilderType = typeof(VertexBuilder<,,>).MakeGenericType(geometryType, typeof(VertexEmpty), typeof(VertexEmpty)); - - // todo: demagic the 3 - // todo note this assumes that the buffer streams are tightly packed. that's a safe assumption - right? lumina assumes as much - var streams = new BinaryReader[3]; - for (var streamIndex = 0; streamIndex < 3; streamIndex++) - { - streams[streamIndex] = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - streams[streamIndex].Seek(_mdl.VertexOffset[lod] + mesh.VertexBufferOffset[streamIndex]); - } - - var sortedElements = elements - .OrderBy(element => element.Offset) - .ToList(); - - var vertices = new List(); - - // note this is being reused - var attributes = new Dictionary(); - for (var vertexIndex = 0; vertexIndex < mesh.VertexCount; vertexIndex++) - { - attributes.Clear(); - - foreach (var element in sortedElements) - attributes[(MdlFile.VertexUsage)element.Usage] = ReadVertexAttribute(streams[element.Stream], element); - - var vertexGeometry = BuildVertexGeometry(geometryType, attributes); - - var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, new VertexEmpty(), new VertexEmpty())!; - vertices.Add(vertexBuilder); - } - - return vertices; - } - - // todo i fucking hate this `object` type god i hate c# gimme sum types pls - private object ReadVertexAttribute(BinaryReader reader, MdlStructs.VertexElement element) - { - return (MdlFile.VertexType)element.Type switch - { - MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), - MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), - MdlFile.VertexType.UInt => reader.ReadBytes(4), - MdlFile.VertexType.ByteFloat4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), - MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), - MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), - - _ => throw new ArgumentOutOfRangeException() - }; - } - - private Type GetGeometryType(IReadOnlySet usages) - { - if (!usages.Contains(MdlFile.VertexUsage.Position)) - throw new Exception("Mesh does not contain position vertex elements."); - - if (!usages.Contains(MdlFile.VertexUsage.Normal)) - return typeof(VertexPosition); - - if (!usages.Contains(MdlFile.VertexUsage.Tangent1)) - return typeof(VertexPositionNormal); - - return typeof(VertexPositionNormalTangent); - } - - private IVertexGeometry BuildVertexGeometry(Type geometryType, IReadOnlyDictionary attributes) - { - if (geometryType == typeof(VertexPosition)) - return new VertexPosition( - ToVector3(attributes[MdlFile.VertexUsage.Position]) - ); - - if (geometryType == typeof(VertexPositionNormal)) - return new VertexPositionNormal( - ToVector3(attributes[MdlFile.VertexUsage.Position]), - ToVector3(attributes[MdlFile.VertexUsage.Normal]) - ); - - if (geometryType == typeof(VertexPositionNormalTangent)) - return new VertexPositionNormalTangent( - ToVector3(attributes[MdlFile.VertexUsage.Position]), - ToVector3(attributes[MdlFile.VertexUsage.Normal]), - ToVector4(attributes[MdlFile.VertexUsage.Tangent1]) - ); - - throw new Exception($"Unknown geometry type {geometryType}."); - } - - private Vector3 ToVector3(object data) - { - return data switch - { - Vector2 v2 => new Vector3(v2.X, v2.Y, 0), - Vector3 v3 => v3, - Vector4 v4 => new Vector3(v4.X, v4.Y, v4.Z), - _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") - }; - } - - private Vector4 ToVector4(object data) - { - return data switch - { - Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0), - Vector3 v3 => new Vector4(v3.X, v3.Y, v3.Z, 1), - Vector4 v4 => v4, - _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") - }; - } - public bool Equals(IAction? other) { if (other is not ExportToGltfAction rhs) From 635d606112979cf7661938a88afd711e92357cae Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 28 Dec 2023 15:51:20 +1100 Subject: [PATCH 0287/1381] Initial skeleton tests --- Penumbra/Import/Models/HavokConverter.cs | 141 +++++++++++++ Penumbra/Import/Models/ModelManager.cs | 187 +++++++++++++++++- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 4 + 3 files changed, 330 insertions(+), 2 deletions(-) create mode 100644 Penumbra/Import/Models/HavokConverter.cs diff --git a/Penumbra/Import/Models/HavokConverter.cs b/Penumbra/Import/Models/HavokConverter.cs new file mode 100644 index 00000000..515c6f97 --- /dev/null +++ b/Penumbra/Import/Models/HavokConverter.cs @@ -0,0 +1,141 @@ +using FFXIVClientStructs.Havok; + +namespace Penumbra.Import.Models; + +// TODO: where should this live? interop i guess, in penum? or game data? +public unsafe class HavokConverter +{ + /// Creates a temporary file and returns its path. + /// Path to a temporary file. + private string CreateTempFile() + { + var s = File.Create(Path.GetTempFileName()); + s.Close(); + return s.Name; + } + + /// Converts a .hkx file to a .xml file. + /// A byte array representing the .hkx file. + /// A string representing the .xml file. + /// Thrown if parsing the .hkx file fails. + /// Thrown if writing the .xml file fails. + public string HkxToXml(byte[] hkx) + { + var tempHkx = CreateTempFile(); + File.WriteAllBytes(tempHkx, hkx); + + var resource = Read(tempHkx); + File.Delete(tempHkx); + + if (resource == null) throw new Exception("HavokReadException"); + + var options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers + | hkSerializeUtil.SaveOptionBits.TextFormat + | hkSerializeUtil.SaveOptionBits.WriteAttributes; + + var file = Write(resource, options); + file.Close(); + + var bytes = File.ReadAllText(file.Name); + File.Delete(file.Name); + + return bytes; + } + + /// Converts a .xml file to a .hkx file. + /// A string representing the .xml file. + /// A byte array representing the .hkx file. + /// Thrown if parsing the .xml file fails. + /// Thrown if writing the .hkx file fails. + public byte[] XmlToHkx(string xml) + { + var tempXml = CreateTempFile(); + File.WriteAllText(tempXml, xml); + + var resource = Read(tempXml); + File.Delete(tempXml); + + if (resource == null) throw new Exception("HavokReadException"); + + var options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers + | hkSerializeUtil.SaveOptionBits.WriteAttributes; + + var file = Write(resource, options); + file.Close(); + + var bytes = File.ReadAllBytes(file.Name); + File.Delete(file.Name); + + return bytes; + } + + /// + /// Parses a serialized file into an hkResource*. + /// The type is guessed automatically by Havok. + /// This pointer might be null - you should check for that. + /// + /// Path to a file on the filesystem. + /// A (potentially null) pointer to an hkResource. + private hkResource* Read(string filePath) + { + var path = Marshal.StringToHGlobalAnsi(filePath); + + var builtinTypeRegistry = hkBuiltinTypeRegistry.Instance(); + + var loadOptions = stackalloc hkSerializeUtil.LoadOptions[1]; + loadOptions->Flags = new() { Storage = (int)hkSerializeUtil.LoadOptionBits.Default }; + loadOptions->ClassNameRegistry = builtinTypeRegistry->GetClassNameRegistry(); + loadOptions->TypeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); + + // TODO: probably can loadfrombuffer this + var resource = hkSerializeUtil.LoadFromFile((byte*)path, null, loadOptions); + return resource; + } + + /// Serializes an hkResource* to a temporary file. + /// A pointer to the hkResource, opened through Read(). + /// Flags representing how to serialize the file. + /// An opened FileStream of a temporary file. You are expected to read the file and delete it. + /// Thrown if accessing the root level container fails. + /// Thrown if an unknown failure in writing occurs. + private FileStream Write( + hkResource* resource, + hkSerializeUtil.SaveOptionBits optionBits + ) + { + var tempFile = CreateTempFile(); + var path = Marshal.StringToHGlobalAnsi(tempFile); + var oStream = new hkOstream(); + oStream.Ctor((byte*)path); + + var result = stackalloc hkResult[1]; + + var saveOptions = new hkSerializeUtil.SaveOptions() + { + Flags = new() { Storage = (int)optionBits } + }; + + + var builtinTypeRegistry = hkBuiltinTypeRegistry.Instance(); + var classNameRegistry = builtinTypeRegistry->GetClassNameRegistry(); + var typeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); + + try + { + var name = "hkRootLevelContainer"; + + var resourcePtr = (hkRootLevelContainer*)resource->GetContentsPointer(name, typeInfoRegistry); + if (resourcePtr == null) throw new Exception("HavokWriteException"); + + var hkRootLevelContainerClass = classNameRegistry->GetClassByName(name); + if (hkRootLevelContainerClass == null) throw new Exception("HavokWriteException"); + + hkSerializeUtil.Save(result, resourcePtr, hkRootLevelContainerClass, oStream.StreamWriter.ptr, saveOptions); + } + finally { oStream.Dtor(); } + + if (result->Result == hkResult.hkResultEnum.Failure) throw new Exception("HavokFailureException"); + + return new FileStream(tempFile, FileMode.Open); + } +} diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 429aad54..c4c46353 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,18 +1,26 @@ +using System.Xml; +using Dalamud.Plugin.Services; +using Lumina.Data; +using Lumina.Extensions; +using OtterGui; using OtterGui.Tasks; using Penumbra.GameData.Files; using Penumbra.Import.Modules; using SharpGLTF.Scenes; +using SharpGLTF.Transforms; namespace Penumbra.Import.Models; public sealed class ModelManager : SingleTaskQueue, IDisposable { + private readonly IDataManager _gameData; + private readonly ConcurrentDictionary _tasks = new(); private bool _disposed = false; - public ModelManager() + public ModelManager(IDataManager gameData) { - // + _gameData = gameData; } public void Dispose() @@ -46,6 +54,181 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public Task ExportToGltf(MdlFile mdl, string path) => Enqueue(new ExportToGltfAction(mdl, path)); + public void SkeletonTest() + { + var sklbPath = "chara/human/c0201/skeleton/base/b0001/skl_c0201b0001.sklb"; + + var something = _gameData.GetFile(sklbPath); + + var fuck = new HavokConverter(); + var killme = fuck.HkxToXml(something.Skeleton); + + var doc = new XmlDocument(); + doc.LoadXml(killme); + + var skels = doc.SelectNodes("/hktagfile/object[@type='hkaSkeleton']") + .Cast() + .Select(element => new Skel(element)) + .ToArray(); + + // todo: look into how this is selecting the skel - only first? + var animSkel = doc.SelectSingleNode("/hktagfile/object[@type='hkaAnimationContainer']") + .SelectNodes("array[@name='skeletons']") + .Cast() + .First(); + var mainSkelId = animSkel.ChildNodes[0].InnerText; + + var mainSkel = skels.First(skel => skel.Id == mainSkelId); + + // this is atrocious + NodeBuilder? root = null; + var boneMap = new Dictionary(); + for (var boneIndex = 0; boneIndex < mainSkel.BoneNames.Length; boneIndex++) + { + var name = mainSkel.BoneNames[boneIndex]; + if (boneMap.ContainsKey(name)) continue; + + var node = new NodeBuilder(name); + + var rp = mainSkel.ReferencePose[boneIndex]; + var transform = new AffineTransform( + new Vector3(rp[8], rp[9], rp[10]), + new Quaternion(rp[4], rp[5], rp[6], rp[7]), + new Vector3([rp[0], rp[1], rp[2]]) + ); + node.SetLocalTransform(transform, false); + + boneMap[name] = node; + + var parentId = mainSkel.ParentIndices[boneIndex]; + if (parentId == -1) + { + root = node; + continue; + } + + var parent = boneMap[mainSkel.BoneNames[parentId]]; + parent.AddNode(node); + } + + var scene = new SceneBuilder(); + scene.AddNode(root); + var model = scene.ToGltf2(); + model.SaveGLTF(@"C:\Users\ackwell\blender\gltf-tests\zoingo.gltf"); + + Penumbra.Log.Information($"zoingo {string.Join(',', mainSkel.ParentIndices)}"); + } + + // this is garbage that should be in gamedata + + private sealed class Garbage : FileResource + { + public byte[] Skeleton; + + public override void LoadFile() + { + var magic = Reader.ReadUInt32(); + if (magic != 0x736B6C62) + throw new InvalidDataException("Invalid sklb magic"); + + // todo do this all properly jfc + var version = Reader.ReadUInt32(); + + var oldHeader = version switch { + 0x31313030 or 0x31313130 or 0x31323030 => true, + 0x31333030 => false, + _ => throw new InvalidDataException($"Unknown version {version}") + }; + + // Skeleton offset directly follows the layer offset. + uint skeletonOffset; + if (oldHeader) + { + Reader.ReadInt16(); + skeletonOffset = Reader.ReadUInt16(); + } + else + { + Reader.ReadUInt32(); + skeletonOffset = Reader.ReadUInt32(); + } + + Reader.Seek(skeletonOffset); + Skeleton = Reader.ReadBytes((int)(Reader.BaseStream.Length - skeletonOffset)); + } + } + + private class Skel + { + public readonly string Id; + + public readonly float[][] ReferencePose; + public readonly int[] ParentIndices; + public readonly string[] BoneNames; + + // TODO: this shouldn't have any reference to the skel xml - i should just make it a bare class that can be repr'd in gamedata or whatever + public Skel(XmlElement el) + { + Id = el.GetAttribute("id"); + + ReferencePose = ReadReferencePose(el); + ParentIndices = ReadParentIndices(el); + BoneNames = ReadBoneNames(el); + } + + private float[][] ReadReferencePose(XmlElement el) + { + return ReadArray( + (XmlElement)el.SelectSingleNode("array[@name='referencePose']"), + ReadVec12 + ); + } + + private float[] ReadVec12(XmlElement el) + { + return el.ChildNodes + .Cast() + .Where(node => node.NodeType != XmlNodeType.Comment) + .Select(node => { + var t = node.InnerText.Trim()[1..]; + // todo: surely there's a less shit way to do this i mean seriously + return BitConverter.ToSingle(BitConverter.GetBytes(int.Parse(t, NumberStyles.HexNumber))); + }) + .ToArray(); + } + + private int[] ReadParentIndices(XmlElement el) + { + // todo: would be neat to genericise array between bare and children + return el.SelectSingleNode("array[@name='parentIndices']") + .InnerText + .Split(new char[] {' ', '\n'}, StringSplitOptions.RemoveEmptyEntries) + .Select(int.Parse) + .ToArray(); + } + + private string[] ReadBoneNames(XmlElement el) + { + return ReadArray( + (XmlElement)el.SelectSingleNode("array[@name='bones']"), + el => el.SelectSingleNode("string[@name='name']").InnerText + ); + } + + private T[] ReadArray(XmlElement el, Func convert) + { + var size = int.Parse(el.GetAttribute("size")); + + var array = new T[size]; + foreach (var (node, index) in el.ChildNodes.Cast().WithIndex()) + { + array[index] = convert(node); + } + + return array; + } + } + private class ExportToGltfAction : IAction { private readonly MdlFile _mdl; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index b64b4f40..f0cc34a6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -41,6 +41,10 @@ public partial class ModEditWindow var task = _models.ExportToGltf(file, "C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); task.ContinueWith(_ => _pendingIo = false); } + if (ImGui.Button("zoingo boingo")) + { + _models.SkeletonTest(); + } var ret = false; From d646c5e4b5ffc256c768258ff4c72765877311af Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 28 Dec 2023 16:49:44 +1100 Subject: [PATCH 0288/1381] Resolve skeleton path --- Penumbra/Import/Models/ModelManager.cs | 43 ++++++++++++++++++-------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index c4c46353..9074b67a 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,11 +1,12 @@ using System.Xml; using Dalamud.Plugin.Services; -using Lumina.Data; using Lumina.Extensions; using OtterGui; using OtterGui.Tasks; +using Penumbra.Collections.Manager; using Penumbra.GameData.Files; using Penumbra.Import.Modules; +using Penumbra.String.Classes; using SharpGLTF.Scenes; using SharpGLTF.Transforms; @@ -14,13 +15,15 @@ namespace Penumbra.Import.Models; public sealed class ModelManager : SingleTaskQueue, IDisposable { private readonly IDataManager _gameData; + private readonly ActiveCollectionData _activeCollectionData; private readonly ConcurrentDictionary _tasks = new(); private bool _disposed = false; - public ModelManager(IDataManager gameData) + public ModelManager(IDataManager gameData, ActiveCollectionData activeCollectionData) { _gameData = gameData; + _activeCollectionData = activeCollectionData; } public void Dispose() @@ -58,7 +61,18 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable { var sklbPath = "chara/human/c0201/skeleton/base/b0001/skl_c0201b0001.sklb"; - var something = _gameData.GetFile(sklbPath); + var succeeded = Utf8GamePath.FromString(sklbPath, out var utf8Path, true); + var testResolve = _activeCollectionData.Current.ResolvePath(utf8Path); + Penumbra.Log.Information($"resolved: {(testResolve == null ? "NULL" : testResolve.ToString())}"); + + // TODO: is it worth trying to use streams for these instead? i'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... + var bytes = testResolve switch + { + null => _gameData.GetFile(sklbPath).Data, + FullPath path => File.ReadAllBytes(path.ToPath()) + }; + + var something = new Garbage(bytes); var fuck = new HavokConverter(); var killme = fuck.HkxToXml(something.Skeleton); @@ -121,18 +135,21 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable // this is garbage that should be in gamedata - private sealed class Garbage : FileResource + private sealed class Garbage { public byte[] Skeleton; - public override void LoadFile() + public Garbage(byte[] data) { - var magic = Reader.ReadUInt32(); + using var stream = new MemoryStream(data); + using var reader = new BinaryReader(stream); + + var magic = reader.ReadUInt32(); if (magic != 0x736B6C62) throw new InvalidDataException("Invalid sklb magic"); // todo do this all properly jfc - var version = Reader.ReadUInt32(); + var version = reader.ReadUInt32(); var oldHeader = version switch { 0x31313030 or 0x31313130 or 0x31323030 => true, @@ -144,17 +161,17 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable uint skeletonOffset; if (oldHeader) { - Reader.ReadInt16(); - skeletonOffset = Reader.ReadUInt16(); + reader.ReadInt16(); + skeletonOffset = reader.ReadUInt16(); } else { - Reader.ReadUInt32(); - skeletonOffset = Reader.ReadUInt32(); + reader.ReadUInt32(); + skeletonOffset = reader.ReadUInt32(); } - Reader.Seek(skeletonOffset); - Skeleton = Reader.ReadBytes((int)(Reader.BaseStream.Length - skeletonOffset)); + reader.Seek(skeletonOffset); + Skeleton = reader.ReadBytes((int)(reader.BaseStream.Length - skeletonOffset)); } } From d7cac3e09a9f531261cf60e8bf5020149bc4073e Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 29 Dec 2023 02:31:02 +1100 Subject: [PATCH 0289/1381] Clean up and refactor skeleton logic --- Penumbra/Import/Models/ModelManager.cs | 171 +++----------------- Penumbra/Import/Models/Skeleton.cs | 25 +++ Penumbra/Import/Models/SkeletonConverter.cs | 132 +++++++++++++++ Penumbra/Import/Models/SklbFile.cs | 44 +++++ 4 files changed, 223 insertions(+), 149 deletions(-) create mode 100644 Penumbra/Import/Models/Skeleton.cs create mode 100644 Penumbra/Import/Models/SkeletonConverter.cs create mode 100644 Penumbra/Import/Models/SklbFile.cs diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 9074b67a..6a9ef334 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -61,6 +61,8 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable { var sklbPath = "chara/human/c0201/skeleton/base/b0001/skl_c0201b0001.sklb"; + // NOTE: to resolve game path from _mod_, will need to wire the mod class via the modeditwindow to the model editor, through to here. + // NOTE: to get the game path for a model we'll probably need to use a reverse resolve - there's no guarantee for a modded model that they're named per game path, nor that there's only one name. var succeeded = Utf8GamePath.FromString(sklbPath, out var utf8Path, true); var testResolve = _activeCollectionData.Current.ResolvePath(utf8Path); Penumbra.Log.Information($"resolved: {(testResolve == null ? "NULL" : testResolve.ToString())}"); @@ -72,56 +74,40 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable FullPath path => File.ReadAllBytes(path.ToPath()) }; - var something = new Garbage(bytes); + var sklb = new SklbFile(bytes); - var fuck = new HavokConverter(); - var killme = fuck.HkxToXml(something.Skeleton); + // TODO: Consider making these static methods. + var havokConverter = new HavokConverter(); + var xml = havokConverter.HkxToXml(sklb.Skeleton); - var doc = new XmlDocument(); - doc.LoadXml(killme); + var skeletonConverter = new SkeletonConverter(); + var skeleton = skeletonConverter.FromXml(xml); - var skels = doc.SelectNodes("/hktagfile/object[@type='hkaSkeleton']") - .Cast() - .Select(element => new Skel(element)) - .ToArray(); - - // todo: look into how this is selecting the skel - only first? - var animSkel = doc.SelectSingleNode("/hktagfile/object[@type='hkaAnimationContainer']") - .SelectNodes("array[@name='skeletons']") - .Cast() - .First(); - var mainSkelId = animSkel.ChildNodes[0].InnerText; - - var mainSkel = skels.First(skel => skel.Id == mainSkelId); - - // this is atrocious + // this is (less) atrocious NodeBuilder? root = null; var boneMap = new Dictionary(); - for (var boneIndex = 0; boneIndex < mainSkel.BoneNames.Length; boneIndex++) + for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) { - var name = mainSkel.BoneNames[boneIndex]; - if (boneMap.ContainsKey(name)) continue; + var bone = skeleton.Bones[boneIndex]; - var node = new NodeBuilder(name); + if (boneMap.ContainsKey(bone.Name)) continue; - var rp = mainSkel.ReferencePose[boneIndex]; - var transform = new AffineTransform( - new Vector3(rp[8], rp[9], rp[10]), - new Quaternion(rp[4], rp[5], rp[6], rp[7]), - new Vector3([rp[0], rp[1], rp[2]]) - ); - node.SetLocalTransform(transform, false); + var node = new NodeBuilder(bone.Name); + boneMap[bone.Name] = node; - boneMap[name] = node; + node.SetLocalTransform(new AffineTransform( + bone.Transform.Scale, + bone.Transform.Rotation, + bone.Transform.Translation + ), false); - var parentId = mainSkel.ParentIndices[boneIndex]; - if (parentId == -1) + if (bone.ParentIndex == -1) { root = node; continue; } - var parent = boneMap[mainSkel.BoneNames[parentId]]; + var parent = boneMap[skeleton.Bones[bone.ParentIndex].Name]; parent.AddNode(node); } @@ -130,120 +116,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var model = scene.ToGltf2(); model.SaveGLTF(@"C:\Users\ackwell\blender\gltf-tests\zoingo.gltf"); - Penumbra.Log.Information($"zoingo {string.Join(',', mainSkel.ParentIndices)}"); - } - - // this is garbage that should be in gamedata - - private sealed class Garbage - { - public byte[] Skeleton; - - public Garbage(byte[] data) - { - using var stream = new MemoryStream(data); - using var reader = new BinaryReader(stream); - - var magic = reader.ReadUInt32(); - if (magic != 0x736B6C62) - throw new InvalidDataException("Invalid sklb magic"); - - // todo do this all properly jfc - var version = reader.ReadUInt32(); - - var oldHeader = version switch { - 0x31313030 or 0x31313130 or 0x31323030 => true, - 0x31333030 => false, - _ => throw new InvalidDataException($"Unknown version {version}") - }; - - // Skeleton offset directly follows the layer offset. - uint skeletonOffset; - if (oldHeader) - { - reader.ReadInt16(); - skeletonOffset = reader.ReadUInt16(); - } - else - { - reader.ReadUInt32(); - skeletonOffset = reader.ReadUInt32(); - } - - reader.Seek(skeletonOffset); - Skeleton = reader.ReadBytes((int)(reader.BaseStream.Length - skeletonOffset)); - } - } - - private class Skel - { - public readonly string Id; - - public readonly float[][] ReferencePose; - public readonly int[] ParentIndices; - public readonly string[] BoneNames; - - // TODO: this shouldn't have any reference to the skel xml - i should just make it a bare class that can be repr'd in gamedata or whatever - public Skel(XmlElement el) - { - Id = el.GetAttribute("id"); - - ReferencePose = ReadReferencePose(el); - ParentIndices = ReadParentIndices(el); - BoneNames = ReadBoneNames(el); - } - - private float[][] ReadReferencePose(XmlElement el) - { - return ReadArray( - (XmlElement)el.SelectSingleNode("array[@name='referencePose']"), - ReadVec12 - ); - } - - private float[] ReadVec12(XmlElement el) - { - return el.ChildNodes - .Cast() - .Where(node => node.NodeType != XmlNodeType.Comment) - .Select(node => { - var t = node.InnerText.Trim()[1..]; - // todo: surely there's a less shit way to do this i mean seriously - return BitConverter.ToSingle(BitConverter.GetBytes(int.Parse(t, NumberStyles.HexNumber))); - }) - .ToArray(); - } - - private int[] ReadParentIndices(XmlElement el) - { - // todo: would be neat to genericise array between bare and children - return el.SelectSingleNode("array[@name='parentIndices']") - .InnerText - .Split(new char[] {' ', '\n'}, StringSplitOptions.RemoveEmptyEntries) - .Select(int.Parse) - .ToArray(); - } - - private string[] ReadBoneNames(XmlElement el) - { - return ReadArray( - (XmlElement)el.SelectSingleNode("array[@name='bones']"), - el => el.SelectSingleNode("string[@name='name']").InnerText - ); - } - - private T[] ReadArray(XmlElement el, Func convert) - { - var size = int.Parse(el.GetAttribute("size")); - - var array = new T[size]; - foreach (var (node, index) in el.ChildNodes.Cast().WithIndex()) - { - array[index] = convert(node); - } - - return array; - } + Penumbra.Log.Information($"zoingo!"); } private class ExportToGltfAction : IAction diff --git a/Penumbra/Import/Models/Skeleton.cs b/Penumbra/Import/Models/Skeleton.cs new file mode 100644 index 00000000..fb5c8284 --- /dev/null +++ b/Penumbra/Import/Models/Skeleton.cs @@ -0,0 +1,25 @@ +namespace Penumbra.Import.Models; + +// TODO: this should almost certainly live in gamedata. if not, it should at _least_ be adjacent to the model handling. +public class Skeleton +{ + public Bone[] Bones; + + public Skeleton(Bone[] bones) + { + Bones = bones; + } + + public struct Bone + { + public string Name; + public int ParentIndex; + public Transform Transform; + } + + public struct Transform { + public Vector3 Scale; + public Quaternion Rotation; + public Vector3 Translation; + } +} diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs new file mode 100644 index 00000000..d54b0294 --- /dev/null +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -0,0 +1,132 @@ +using System.Xml; +using OtterGui; + +namespace Penumbra.Import.Models; + +// TODO: tempted to say that this living here is more okay? that or next to havok converter, wherever that ends up. +public class SkeletonConverter +{ + public Skeleton FromXml(string xml) + { + var document = new XmlDocument(); + document.LoadXml(xml); + + var mainSkeletonId = GetMainSkeletonId(document); + + var skeletonNode = document.SelectSingleNode($"/hktagfile/object[@type='hkaSkeleton'][@id='{mainSkeletonId}']"); + if (skeletonNode == null) + throw new InvalidDataException(); + + var referencePose = ReadReferencePose(skeletonNode); + var parentIndices = ReadParentIndices(skeletonNode); + var boneNames = ReadBoneNames(skeletonNode); + + if (boneNames.Length != parentIndices.Length || boneNames.Length != referencePose.Length) + throw new InvalidDataException(); + + var bones = referencePose + .Zip(parentIndices, boneNames) + .Select(values => + { + var (transform, parentIndex, name) = values; + return new Skeleton.Bone() + { + Transform = transform, + ParentIndex = parentIndex, + Name = name, + }; + }) + .ToArray(); + + return new Skeleton(bones); + } + + /// Get the main skeleton ID for a given skeleton document. + /// XML skeleton document. + private string GetMainSkeletonId(XmlNode node) + { + var animationSkeletons = node + .SelectSingleNode("/hktagfile/object[@type='hkaAnimationContainer']/array[@name='skeletons']")? + .ChildNodes; + + if (animationSkeletons?.Count != 1) + throw new Exception($"Assumption broken: Expected 1 hkaAnimationContainer skeleton, got {animationSkeletons?.Count ?? 0}"); + + return animationSkeletons[0]!.InnerText; + } + + /// Read the reference pose transforms for a skeleton. + /// XML node for the skeleton. + private Skeleton.Transform[] ReadReferencePose(XmlNode node) + { + return ReadArray( + CheckExists(node.SelectSingleNode("array[@name='referencePose']")), + node => + { + var raw = ReadVec12(node); + return new Skeleton.Transform() + { + Translation = new(raw[0], raw[1], raw[2]), + Rotation = new(raw[4], raw[5], raw[6], raw[7]), + Scale = new(raw[8], raw[9], raw[10]), + }; + } + ); + } + + private float[] ReadVec12(XmlNode node) + { + var array = node.ChildNodes + .Cast() + .Where(node => node.NodeType != XmlNodeType.Comment) + .Select(node => + { + var text = node.InnerText.Trim()[1..]; + // TODO: surely there's a less shit way to do this i mean seriously + return BitConverter.ToSingle(BitConverter.GetBytes(int.Parse(text, NumberStyles.HexNumber))); + }) + .ToArray(); + + if (array.Length != 12) + throw new InvalidDataException(); + + return array; + } + + private int[] ReadParentIndices(XmlNode node) + { + // todo: would be neat to genericise array between bare and children + return CheckExists(node.SelectSingleNode("array[@name='parentIndices']")) + .InnerText + .Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(int.Parse) + .ToArray(); + } + + private string[] ReadBoneNames(XmlNode node) + { + return ReadArray( + CheckExists(node.SelectSingleNode("array[@name='bones']")), + node => CheckExists(node.SelectSingleNode("string[@name='name']")).InnerText + ); + } + + private T[] ReadArray(XmlNode node, Func convert) + { + var element = (XmlElement)node; + + var size = int.Parse(element.GetAttribute("size")); + + var array = new T[size]; + foreach (var (childNode, index) in element.ChildNodes.Cast().WithIndex()) + array[index] = convert(childNode); + + return array; + } + + private static T CheckExists(T? value) + { + ArgumentNullException.ThrowIfNull(value); + return value; + } +} diff --git a/Penumbra/Import/Models/SklbFile.cs b/Penumbra/Import/Models/SklbFile.cs new file mode 100644 index 00000000..9ae6f7db --- /dev/null +++ b/Penumbra/Import/Models/SklbFile.cs @@ -0,0 +1,44 @@ +using Lumina.Extensions; + +namespace Penumbra.Import.Models; + +// TODO: yeah this goes in gamedata. +public class SklbFile +{ + public byte[] Skeleton; + + public SklbFile(byte[] data) + { + using var stream = new MemoryStream(data); + using var reader = new BinaryReader(stream); + + var magic = reader.ReadUInt32(); + if (magic != 0x736B6C62) + throw new InvalidDataException("Invalid sklb magic"); + + // todo do this all properly jfc + var version = reader.ReadUInt32(); + + var oldHeader = version switch { + 0x31313030 or 0x31313130 or 0x31323030 => true, + 0x31333030 => false, + _ => throw new InvalidDataException($"Unknown version {version}") + }; + + // Skeleton offset directly follows the layer offset. + uint skeletonOffset; + if (oldHeader) + { + reader.ReadInt16(); + skeletonOffset = reader.ReadUInt16(); + } + else + { + reader.ReadUInt32(); + skeletonOffset = reader.ReadUInt32(); + } + + reader.Seek(skeletonOffset); + Skeleton = reader.ReadBytes((int)(reader.BaseStream.Length - skeletonOffset)); + } +} From 71fc901798ec9f90feab880c891667efab3f8893 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 29 Dec 2023 19:16:42 +1100 Subject: [PATCH 0290/1381] Resolve mdl game paths --- .../ModEditWindow.Models.MdlTab.cs | 18 +++++++++++++++++- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 3 +++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 4986963f..254db841 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,6 +1,8 @@ using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; +using Penumbra.Mods; +using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -9,12 +11,14 @@ public partial class ModEditWindow private class MdlTab : IWritable { public readonly MdlFile Mdl; + public readonly List GamePaths; private readonly List[] _attributes; - public MdlTab(byte[] bytes) + public MdlTab(byte[] bytes, string path, Mod? mod) { Mdl = new MdlFile(bytes); + GamePaths = mod == null ? new() : FindGamePaths(path, mod); _attributes = CreateAttributes(Mdl); } @@ -26,6 +30,18 @@ public partial class ModEditWindow public byte[] Write() => Mdl.Write(); + // TODO: this _needs_ to be done asynchronously, kart mods hang for a good second or so + private List FindGamePaths(string path, Mod mod) + { + // todo: might be worth ordering based on prio + selection for disambiguating between multiple matches? not sure. same for the multi group case + return mod.AllSubMods + .SelectMany(submod => submod.Files.Concat(submod.FileSwaps)) + // todo: using ordinal ignore case because the option group paths in mods being lowerecased somewhere, but the mod editor using fs paths, which may be uppercase. i'd say this will blow up on linux, but it's already the case so can't be too much worse than present right + .Where(kv => kv.Value.FullName.Equals(path, StringComparison.OrdinalIgnoreCase)) + .Select(kv => kv.Key) + .ToList(); + } + /// Remove the material given by the index. /// Meshes using the removed material are redirected to material 0, and those after the index are corrected. public void RemoveMaterial(int materialIndex) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index f0cc34a6..d5ca6fa5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -45,6 +45,9 @@ public partial class ModEditWindow { _models.SkeletonTest(); } + ImGui.TextUnformatted("blippity blap"); + foreach (var gamePath in tab.GamePaths) + ImGui.TextUnformatted(gamePath.ToString()); var ret = false; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 1a3d9182..181538ec 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -587,7 +587,7 @@ public partial class ModEditWindow : Window, IDisposable () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new MdlTab(bytes)); + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new MdlTab(bytes, path, _mod)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); From 18fd36d2d7123d3519b29c12bb580943b0f67e1c Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 29 Dec 2023 23:49:55 +1100 Subject: [PATCH 0291/1381] Bit of cleanup --- Penumbra/Import/Models/ModelManager.cs | 12 +++++------ .../ModEditWindow.Models.MdlTab.cs | 21 +++++++++++++++++-- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 7 ++----- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 4 files changed, 28 insertions(+), 14 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 6a9ef334..42134037 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -54,8 +54,8 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable return task; } - public Task ExportToGltf(MdlFile mdl, string path) - => Enqueue(new ExportToGltfAction(mdl, path)); + public Task ExportToGltf(MdlFile mdl, string outputPath) + => Enqueue(new ExportToGltfAction(mdl, outputPath)); public void SkeletonTest() { @@ -122,12 +122,12 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable private class ExportToGltfAction : IAction { private readonly MdlFile _mdl; - private readonly string _path; + private readonly string _outputPath; - public ExportToGltfAction(MdlFile mdl, string path) + public ExportToGltfAction(MdlFile mdl, string outputPath) { _mdl = mdl; - _path = path; + _outputPath = outputPath; } public void Execute(CancellationToken token) @@ -148,7 +148,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable } var model = scene.ToGltf2(); - model.SaveGLTF(_path); + model.SaveGLTF(_outputPath); } public bool Equals(IAction? other) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 254db841..4552078a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -10,13 +10,18 @@ public partial class ModEditWindow { private class MdlTab : IWritable { + private ModEditWindow _edit; + public readonly MdlFile Mdl; public readonly List GamePaths; - private readonly List[] _attributes; - public MdlTab(byte[] bytes, string path, Mod? mod) + public bool PendingIo { get; private set; } = false; + + public MdlTab(ModEditWindow edit, byte[] bytes, string path, Mod? mod) { + _edit = edit; + Mdl = new MdlFile(bytes); GamePaths = mod == null ? new() : FindGamePaths(path, mod); _attributes = CreateAttributes(Mdl); @@ -31,6 +36,9 @@ public partial class ModEditWindow => Mdl.Write(); // TODO: this _needs_ to be done asynchronously, kart mods hang for a good second or so + /// Find the list of game paths that may correspond to this model. + /// Resolved path to a .mdl. + /// Mod within which the .mdl is resolved. private List FindGamePaths(string path, Mod mod) { // todo: might be worth ordering based on prio + selection for disambiguating between multiple matches? not sure. same for the multi group case @@ -42,6 +50,15 @@ public partial class ModEditWindow .ToList(); } + /// Export model to an interchange format. + /// Disk path to save the resulting file to. + public void Export(string outputPath) + { + PendingIo = true; + _edit._models.ExportToGltf(Mdl, outputPath) + .ContinueWith(_ => PendingIo = false); + } + /// Remove the material given by the index. /// Meshes using the removed material are redirected to material 0, and those after the index are corrected. public void RemoveMaterial(int materialIndex) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index d5ca6fa5..0b145b89 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -17,7 +17,6 @@ public partial class ModEditWindow private readonly FileEditor _modelTab; private readonly ModelManager _models; - private bool _pendingIo = false; private string _modelNewMaterial = string.Empty; private readonly List _subMeshAttributeTagWidgets = []; @@ -35,11 +34,9 @@ public partial class ModEditWindow ); } - if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", _pendingIo)) + if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", tab.PendingIo)) { - _pendingIo = true; - var task = _models.ExportToGltf(file, "C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); - task.ContinueWith(_ => _pendingIo = false); + tab.Export("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); } if (ImGui.Button("zoingo boingo")) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 181538ec..20ad92c3 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -587,7 +587,7 @@ public partial class ModEditWindow : Window, IDisposable () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new MdlTab(bytes, path, _mod)); + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new MdlTab(this, bytes, path, _mod)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); From 695c18439db5dc353def4cd1edd72e761cb0a456 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 30 Dec 2023 02:41:19 +1100 Subject: [PATCH 0292/1381] Hook up rudimentary skeleton resolution for equipment models --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 134 ++++++++---------- Penumbra/Import/Models/SklbFile.cs | 44 ------ .../ModEditWindow.Models.MdlTab.cs | 60 +++++++- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 4 - 5 files changed, 121 insertions(+), 123 deletions(-) delete mode 100644 Penumbra/Import/Models/SklbFile.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 0dc4c892..b6a68ab6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 0dc4c892308aea30314d118362b3ebab7706f4e5 +Subproject commit b6a68ab60be6a46f8ede63425cd0716dedf693a3 diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 42134037..9f56588a 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,12 +1,8 @@ -using System.Xml; using Dalamud.Plugin.Services; -using Lumina.Extensions; -using OtterGui; using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData.Files; using Penumbra.Import.Modules; -using Penumbra.String.Classes; using SharpGLTF.Scenes; using SharpGLTF.Transforms; @@ -14,14 +10,16 @@ namespace Penumbra.Import.Models; public sealed class ModelManager : SingleTaskQueue, IDisposable { + private readonly IFramework _framework; private readonly IDataManager _gameData; private readonly ActiveCollectionData _activeCollectionData; private readonly ConcurrentDictionary _tasks = new(); private bool _disposed = false; - public ModelManager(IDataManager gameData, ActiveCollectionData activeCollectionData) + public ModelManager(IFramework framework, IDataManager gameData, ActiveCollectionData activeCollectionData) { + _framework = framework; _gameData = gameData; _activeCollectionData = activeCollectionData; } @@ -54,86 +52,33 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable return task; } - public Task ExportToGltf(MdlFile mdl, string outputPath) - => Enqueue(new ExportToGltfAction(mdl, outputPath)); - - public void SkeletonTest() - { - var sklbPath = "chara/human/c0201/skeleton/base/b0001/skl_c0201b0001.sklb"; - - // NOTE: to resolve game path from _mod_, will need to wire the mod class via the modeditwindow to the model editor, through to here. - // NOTE: to get the game path for a model we'll probably need to use a reverse resolve - there's no guarantee for a modded model that they're named per game path, nor that there's only one name. - var succeeded = Utf8GamePath.FromString(sklbPath, out var utf8Path, true); - var testResolve = _activeCollectionData.Current.ResolvePath(utf8Path); - Penumbra.Log.Information($"resolved: {(testResolve == null ? "NULL" : testResolve.ToString())}"); - - // TODO: is it worth trying to use streams for these instead? i'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... - var bytes = testResolve switch - { - null => _gameData.GetFile(sklbPath).Data, - FullPath path => File.ReadAllBytes(path.ToPath()) - }; - - var sklb = new SklbFile(bytes); - - // TODO: Consider making these static methods. - var havokConverter = new HavokConverter(); - var xml = havokConverter.HkxToXml(sklb.Skeleton); - - var skeletonConverter = new SkeletonConverter(); - var skeleton = skeletonConverter.FromXml(xml); - - // this is (less) atrocious - NodeBuilder? root = null; - var boneMap = new Dictionary(); - for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) - { - var bone = skeleton.Bones[boneIndex]; - - if (boneMap.ContainsKey(bone.Name)) continue; - - var node = new NodeBuilder(bone.Name); - boneMap[bone.Name] = node; - - node.SetLocalTransform(new AffineTransform( - bone.Transform.Scale, - bone.Transform.Rotation, - bone.Transform.Translation - ), false); - - if (bone.ParentIndex == -1) - { - root = node; - continue; - } - - var parent = boneMap[skeleton.Bones[bone.ParentIndex].Name]; - parent.AddNode(node); - } - - var scene = new SceneBuilder(); - scene.AddNode(root); - var model = scene.ToGltf2(); - model.SaveGLTF(@"C:\Users\ackwell\blender\gltf-tests\zoingo.gltf"); - - Penumbra.Log.Information($"zoingo!"); - } + public Task ExportToGltf(MdlFile mdl, SklbFile? sklb, string outputPath) + => Enqueue(new ExportToGltfAction(this, mdl, sklb, outputPath)); private class ExportToGltfAction : IAction { + private readonly ModelManager _manager; + private readonly MdlFile _mdl; + private readonly SklbFile? _sklb; private readonly string _outputPath; - public ExportToGltfAction(MdlFile mdl, string outputPath) + public ExportToGltfAction(ModelManager manager, MdlFile mdl, SklbFile? sklb, string outputPath) { + _manager = manager; _mdl = mdl; + _sklb = sklb; _outputPath = outputPath; } - public void Execute(CancellationToken token) + public void Execute(CancellationToken cancel) { var scene = new SceneBuilder(); + var skeletonRoot = BuildSkeleton(cancel); + if (skeletonRoot != null) + scene.AddNode(skeletonRoot); + // TODO: group by LoD in output tree for (byte lodIndex = 0; lodIndex < _mdl.LodCount; lodIndex++) { @@ -151,6 +96,53 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable model.SaveGLTF(_outputPath); } + // TODO: this should be moved to a seperate model converter or something + private NodeBuilder? BuildSkeleton(CancellationToken cancel) + { + if (_sklb == null) + return null; + + // TODO: Consider making these static methods. + // TODO: work out how i handle this havok deal. running it outside the framework causes an immediate ctd. + var havokConverter = new HavokConverter(); + var xmlTask = _manager._framework.RunOnFrameworkThread(() => havokConverter.HkxToXml(_sklb.Skeleton)); + xmlTask.Wait(cancel); + var xml = xmlTask.Result; + + var skeletonConverter = new SkeletonConverter(); + var skeleton = skeletonConverter.FromXml(xml); + + // this is (less) atrocious + NodeBuilder? root = null; + var boneMap = new Dictionary(); + for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) + { + var bone = skeleton.Bones[boneIndex]; + + if (boneMap.ContainsKey(bone.Name)) continue; + + var node = new NodeBuilder(bone.Name); + boneMap[bone.Name] = node; + + node.SetLocalTransform(new AffineTransform( + bone.Transform.Scale, + bone.Transform.Rotation, + bone.Transform.Translation + ), false); + + if (bone.ParentIndex == -1) + { + root = node; + continue; + } + + var parent = boneMap[skeleton.Bones[bone.ParentIndex].Name]; + parent.AddNode(node); + } + + return root; + } + public bool Equals(IAction? other) { if (other is not ExportToGltfAction rhs) diff --git a/Penumbra/Import/Models/SklbFile.cs b/Penumbra/Import/Models/SklbFile.cs deleted file mode 100644 index 9ae6f7db..00000000 --- a/Penumbra/Import/Models/SklbFile.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Lumina.Extensions; - -namespace Penumbra.Import.Models; - -// TODO: yeah this goes in gamedata. -public class SklbFile -{ - public byte[] Skeleton; - - public SklbFile(byte[] data) - { - using var stream = new MemoryStream(data); - using var reader = new BinaryReader(stream); - - var magic = reader.ReadUInt32(); - if (magic != 0x736B6C62) - throw new InvalidDataException("Invalid sklb magic"); - - // todo do this all properly jfc - var version = reader.ReadUInt32(); - - var oldHeader = version switch { - 0x31313030 or 0x31313130 or 0x31323030 => true, - 0x31333030 => false, - _ => throw new InvalidDataException($"Unknown version {version}") - }; - - // Skeleton offset directly follows the layer offset. - uint skeletonOffset; - if (oldHeader) - { - reader.ReadInt16(); - skeletonOffset = reader.ReadUInt16(); - } - else - { - reader.ReadUInt32(); - skeletonOffset = reader.ReadUInt32(); - } - - reader.Seek(skeletonOffset); - Skeleton = reader.ReadBytes((int)(reader.BaseStream.Length - skeletonOffset)); - } -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 4552078a..99c32761 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -8,16 +8,20 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private class MdlTab : IWritable + private partial class MdlTab : IWritable { private ModEditWindow _edit; public readonly MdlFile Mdl; public readonly List GamePaths; private readonly List[] _attributes; - + public bool PendingIo { get; private set; } = false; + // TODO: this can probably be genericised across all of chara + [GeneratedRegex(@"chara/equipment/e(?'Set'\d{4})/model/c(?'Race'\d{4})e\k'Set'_.+\.mdl", RegexOptions.Compiled)] + private static partial Regex CharaEquipmentRegex(); + public MdlTab(ModEditWindow edit, byte[] bytes, string path, Mod? mod) { _edit = edit; @@ -54,11 +58,61 @@ public partial class ModEditWindow /// Disk path to save the resulting file to. public void Export(string outputPath) { + // NOTES ON EST (i don't think it's worth supporting yet...) + // for collection wide lookup; + // Collections.Cache.EstCache::GetEstEntry + // Collections.Cache.MetaCache::GetEstEntry + // Collections.ModCollection.MetaCache? + // for default lookup, probably; + // EstFile.GetDefault(...) + + // TODO: allow user to pick the gamepath in the ui + // TODO: what if there's no gamepaths? + var mdlPath = GamePaths.First(); + var sklbPath = GetSklbPath(mdlPath.ToString()); + var sklb = sklbPath != null ? ReadSklb(sklbPath) : null; + PendingIo = true; - _edit._models.ExportToGltf(Mdl, outputPath) + _edit._models.ExportToGltf(Mdl, sklb, outputPath) .ContinueWith(_ => PendingIo = false); } + /// Try to find the .sklb path for a .mdl file. + /// .mdl file to look up the skeleton for. + private string? GetSklbPath(string mdlPath) + { + // TODO: This needs to be drastically expanded, it's dodgy af rn + + var match = CharaEquipmentRegex().Match(mdlPath); + if (!match.Success) + return null; + + var race = match.Groups["Race"].Value; + + return $"chara/human/c{race}/skeleton/base/b0001/skl_c{race}b0001.sklb"; + } + + /// Read a .sklb from the active collection or game. + /// Game path to the .sklb to load. + private SklbFile ReadSklb(string sklbPath) + { + // TODO: if cross-collection lookups are turned off, this conversion can be skipped + if (!Utf8GamePath.FromString(sklbPath, out var utf8SklbPath, true)) + throw new Exception("TODO: handle - should it throw, or try to fail gracefully?"); + + var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8SklbPath); + // TODO: is it worth trying to use streams for these instead? i'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... + var bytes = resolvedPath switch + { + null => _edit._dalamud.GameData.GetFile(sklbPath)?.Data, + FullPath path => File.ReadAllBytes(path.ToPath()), + }; + if (bytes == null) + throw new Exception("TODO: handle - this effectively means that the resolved path doesn't exist. graceful?"); + + return new SklbFile(bytes); + } + /// Remove the material given by the index. /// Meshes using the removed material are redirected to material 0, and those after the index are corrected. public void RemoveMaterial(int materialIndex) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 0b145b89..ff2c1ae5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -38,10 +38,6 @@ public partial class ModEditWindow { tab.Export("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); } - if (ImGui.Button("zoingo boingo")) - { - _models.SkeletonTest(); - } ImGui.TextUnformatted("blippity blap"); foreach (var gamePath in tab.GamePaths) ImGui.TextUnformatted(gamePath.ToString()); From 697b5fac6531d5dfc549f18f5c22540a1bb54033 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 29 Dec 2023 17:20:11 +0000 Subject: [PATCH 0293/1381] [CI] Updating repo.json for testing_0.8.3.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 173f6592..dbe1fe87 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.1", + "TestingAssemblyVersion": "0.8.3.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 727fa3c18352472927899f2826e70fbb15048d1f Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 30 Dec 2023 17:07:34 +1100 Subject: [PATCH 0294/1381] Initial pass on skinned mesh output --- Penumbra/Import/Models/MeshConverter.cs | 84 ++++++++++++++++++++++--- Penumbra/Import/Models/ModelManager.cs | 33 ++++++---- 2 files changed, 98 insertions(+), 19 deletions(-) diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/MeshConverter.cs index 2fcd2816..30d24c17 100644 --- a/Penumbra/Import/Models/MeshConverter.cs +++ b/Penumbra/Import/Models/MeshConverter.cs @@ -10,9 +10,9 @@ namespace Penumbra.Import.Modules; public sealed class MeshConverter { - public static IMeshBuilder ToGltf(MdlFile mdl, byte lod, ushort meshIndex) + public static IMeshBuilder ToGltf(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) { - var self = new MeshConverter(mdl, lod, meshIndex); + var self = new MeshConverter(mdl, lod, meshIndex, boneNameMap); return self.BuildMesh(); } @@ -23,21 +23,49 @@ public sealed class MeshConverter private readonly ushort _meshIndex; private MdlStructs.MeshStruct Mesh => _mdl.Meshes[_meshIndex]; - private readonly Type _geometryType; + private readonly Dictionary? _boneIndexMap; - private MeshConverter(MdlFile mdl, byte lod, ushort meshIndex) + private readonly Type _geometryType; + private readonly Type _skinningType; + + private MeshConverter(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) { _mdl = mdl; _lod = lod; _meshIndex = meshIndex; + if (boneNameMap != null) + _boneIndexMap = BuildBoneIndexMap(boneNameMap); + var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements .Select(element => (MdlFile.VertexUsage)element.Usage) .ToImmutableHashSet(); _geometryType = GetGeometryType(usages); + _skinningType = GetSkinningType(usages); } + private Dictionary BuildBoneIndexMap(Dictionary boneNameMap) + { + // todo: BoneTableIndex of 255 means null? if so, it should probably feed into the attributes we assign... + var xivBoneTable = _mdl.BoneTables[Mesh.BoneTableIndex]; + + var indexMap = new Dictionary(); + + foreach (var xivBoneIndex in xivBoneTable.BoneIndex.Take(xivBoneTable.BoneCount)) + { + var boneName = _mdl.Bones[xivBoneIndex]; + if (!boneNameMap.TryGetValue(boneName, out var gltfBoneIndex)) + // TODO: handle - i think this is a hard failure, it means that a bone name in the model doesn't exist in the armature. + throw new Exception($"looking for {boneName} in {string.Join(", ", boneNameMap.Keys)}"); + + indexMap.Add(xivBoneIndex, gltfBoneIndex); + } + + return indexMap; + } + + // TODO: consider a struct return type private IMeshBuilder BuildMesh() { var indices = BuildIndices(); @@ -47,7 +75,7 @@ public sealed class MeshConverter typeof(MaterialBuilder), _geometryType, typeof(VertexEmpty), - typeof(VertexEmpty) + _skinningType ); var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, $"mesh{_meshIndex}")!; @@ -81,7 +109,7 @@ public sealed class MeshConverter private IReadOnlyList BuildVertices() { var vertexBuilderType = typeof(VertexBuilder<,,>) - .MakeGenericType(_geometryType, typeof(VertexEmpty), typeof(VertexEmpty)); + .MakeGenericType(_geometryType, typeof(VertexEmpty), _skinningType); // NOTE: This assumes that buffer streams are tightly packed, which has proven safe across tested files. If this assumption is broken, seeks will need to be moved into the vertex element loop. var streams = new BinaryReader[MaximumMeshBufferStreams]; @@ -107,8 +135,9 @@ public sealed class MeshConverter attributes[usage] = ReadVertexAttribute(streams[element.Stream], element); var vertexGeometry = BuildVertexGeometry(attributes); + var vertexSkinning = BuildVertexSkinning(attributes); - var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, new VertexEmpty(), new VertexEmpty())!; + var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, new VertexEmpty(), vertexSkinning)!; vertices.Add(vertexBuilder); } @@ -167,6 +196,40 @@ public sealed class MeshConverter throw new Exception($"Unknown geometry type {_geometryType}."); } + private Type GetSkinningType(IReadOnlySet usages) + { + // TODO: possibly need to check only index - weight might be missing? + if (usages.Contains(MdlFile.VertexUsage.BlendWeights) && usages.Contains(MdlFile.VertexUsage.BlendIndices)) + return typeof(VertexJoints4); + + return typeof(VertexEmpty); + } + + private IVertexSkinning BuildVertexSkinning(IReadOnlyDictionary attributes) + { + if (_skinningType == typeof(VertexEmpty)) + return new VertexEmpty(); + + if (_skinningType == typeof(VertexJoints4)) + { + // todo: this shouldn't happen... right? better approach? + if (_boneIndexMap == null) + throw new Exception("cannot build skinned vertex without index mapping"); + + var indices = ToByteArray(attributes[MdlFile.VertexUsage.BlendIndices]); + var weights = ToVector4(attributes[MdlFile.VertexUsage.BlendWeights]); + + // todo: if this throws on the bone index map, the mod is broken, as it contains weights for bones that do not exist. + // i've not seen any of these that even tt can understand + var bindings = Enumerable.Range(0, 4) + .Select(index => (_boneIndexMap[indices[index]], weights[index])) + .ToArray(); + return new VertexJoints4(bindings); + } + + throw new Exception($"Unknown skinning type {_skinningType}"); + } + // Some tangent W values that should be -1 are stored as 0. private Vector4 FixTangentVector(Vector4 tangent) => tangent with { W = tangent.W == 1 ? 1 : -1 }; @@ -188,4 +251,11 @@ public sealed class MeshConverter Vector4 v4 => v4, _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") }; + + private byte[] ToByteArray(object data) + => data switch + { + byte[] value => value, + _ => throw new ArgumentOutOfRangeException($"Invalid byte[] input {data}") + }; } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 9f56588a..027ac841 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -75,20 +75,24 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable { var scene = new SceneBuilder(); - var skeletonRoot = BuildSkeleton(cancel); - if (skeletonRoot != null) - scene.AddNode(skeletonRoot); + var skeleton = BuildSkeleton(cancel); + if (skeleton != null) + scene.AddNode(skeleton.Value.Root); // TODO: group by LoD in output tree for (byte lodIndex = 0; lodIndex < _mdl.LodCount; lodIndex++) { var lod = _mdl.Lods[lodIndex]; - // TODO: consider other types? + // TODO: consider other types of mesh? for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) { - var meshBuilder = MeshConverter.ToGltf(_mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset)); - scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); + var meshBuilder = MeshConverter.ToGltf(_mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), skeleton?.Names); + // TODO: use a value from the mesh converter for this check, rather than assuming that it has joints + if (skeleton == null) + scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); + else + scene.AddSkinnedMesh(meshBuilder, Matrix4x4.Identity, skeleton?.Joints); } } @@ -97,7 +101,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable } // TODO: this should be moved to a seperate model converter or something - private NodeBuilder? BuildSkeleton(CancellationToken cancel) + private (NodeBuilder Root, NodeBuilder[] Joints, Dictionary Names)? BuildSkeleton(CancellationToken cancel) { if (_sklb == null) return null; @@ -114,15 +118,17 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable // this is (less) atrocious NodeBuilder? root = null; - var boneMap = new Dictionary(); + var names = new Dictionary(); + var joints = new List(); for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) { var bone = skeleton.Bones[boneIndex]; - if (boneMap.ContainsKey(bone.Name)) continue; + if (names.ContainsKey(bone.Name)) continue; var node = new NodeBuilder(bone.Name); - boneMap[bone.Name] = node; + names[bone.Name] = joints.Count; + joints.Add(node); node.SetLocalTransform(new AffineTransform( bone.Transform.Scale, @@ -136,11 +142,14 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable continue; } - var parent = boneMap[skeleton.Bones[bone.ParentIndex].Name]; + var parent = joints[names[skeleton.Bones[bone.ParentIndex].Name]]; parent.AddNode(node); } - return root; + if (root == null) + return null; + + return (root, joints.ToArray(), names); } public bool Equals(IAction? other) From f7a2c174152c6899618e437adb0566f3924073a9 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 30 Dec 2023 18:31:15 +1100 Subject: [PATCH 0295/1381] Quick submesh implementation --- Penumbra/Import/Models/MeshConverter.cs | 27 +++++++++++++++++-------- Penumbra/Import/Models/ModelManager.cs | 11 +++++----- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/MeshConverter.cs index 30d24c17..9f55383e 100644 --- a/Penumbra/Import/Models/MeshConverter.cs +++ b/Penumbra/Import/Models/MeshConverter.cs @@ -10,7 +10,7 @@ namespace Penumbra.Import.Modules; public sealed class MeshConverter { - public static IMeshBuilder ToGltf(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) + public static IMeshBuilder[] ToGltf(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) { var self = new MeshConverter(mdl, lod, meshIndex, boneNameMap); return self.BuildMesh(); @@ -65,12 +65,23 @@ public sealed class MeshConverter return indexMap; } - // TODO: consider a struct return type - private IMeshBuilder BuildMesh() + private IMeshBuilder[] BuildMesh() { - var indices = BuildIndices(); var vertices = BuildVertices(); + // TODO: handle submeshCount = 0 + + return _mdl.SubMeshes + .Skip(Mesh.SubMeshIndex) + .Take(Mesh.SubMeshCount) + .Select(submesh => BuildSubMesh(submesh, vertices)) + .ToArray(); + } + + private IMeshBuilder BuildSubMesh(MdlStructs.SubmeshStruct submesh, IReadOnlyList vertices) + { + var indices = BuildIndices(submesh); + var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( typeof(MaterialBuilder), _geometryType, @@ -89,7 +100,7 @@ public sealed class MeshConverter // All XIV meshes use triangle lists. // TODO: split by submeshes - for (var indexOffset = 0; indexOffset < Mesh.IndexCount; indexOffset += 3) + for (var indexOffset = 0; indexOffset < submesh.IndexCount; indexOffset += 3) primitiveBuilder.AddTriangle( vertices[indices[indexOffset + 0]], vertices[indices[indexOffset + 1]], @@ -99,11 +110,11 @@ public sealed class MeshConverter return meshBuilder; } - private IReadOnlyList BuildIndices() + private IReadOnlyList BuildIndices(MdlStructs.SubmeshStruct submesh) { var reader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - reader.Seek(_mdl.IndexOffset[_lod] + Mesh.StartIndex * sizeof(ushort)); - return reader.ReadStructuresAsArray((int)Mesh.IndexCount); + reader.Seek(_mdl.IndexOffset[_lod] + submesh.IndexOffset * sizeof(ushort)); + return reader.ReadStructuresAsArray((int)submesh.IndexCount); } private IReadOnlyList BuildVertices() diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 027ac841..2dd64235 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -87,12 +87,13 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable // TODO: consider other types of mesh? for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) { - var meshBuilder = MeshConverter.ToGltf(_mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), skeleton?.Names); + var meshBuilders = MeshConverter.ToGltf(_mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), skeleton?.Names); // TODO: use a value from the mesh converter for this check, rather than assuming that it has joints - if (skeleton == null) - scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); - else - scene.AddSkinnedMesh(meshBuilder, Matrix4x4.Identity, skeleton?.Joints); + foreach (var meshBuilder in meshBuilders) + if (skeleton == null) + scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); + else + scene.AddSkinnedMesh(meshBuilder, Matrix4x4.Identity, skeleton?.Joints); } } From 81cdcad72e62d4089e5501da066bbf1bbf014702 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 30 Dec 2023 14:37:31 +0100 Subject: [PATCH 0296/1381] Improve automatic service detection. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Services/BackupService.cs | 15 ++++-- Penumbra/Services/CommunicatorService.cs | 3 +- Penumbra/Services/ConfigMigrationService.cs | 31 +++++------- ...mudServices.cs => DalamudConfigService.cs} | 39 +-------------- Penumbra/Services/FilenameService.cs | 4 +- Penumbra/Services/MessageService.cs | 7 +-- Penumbra/Services/SaveService.cs | 8 ++- Penumbra/Services/ServiceManagerA.cs | 50 +++++++++++-------- Penumbra/Services/StainService.cs | 45 ++++++----------- Penumbra/Services/ValidityChecker.cs | 3 +- Penumbra/Util/PerformanceType.cs | 5 +- 13 files changed, 86 insertions(+), 128 deletions(-) rename Penumbra/Services/{DalamudServices.cs => DalamudConfigService.cs} (72%) diff --git a/OtterGui b/OtterGui index 197d23ee..f6a8ad0f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 197d23eee167c232000f22ef40a7a2bded913b6c +Subproject commit f6a8ad0f8e585408e0aa17c90209358403b52535 diff --git a/Penumbra.GameData b/Penumbra.GameData index ed37f834..192fd1e6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ed37f83424c11a5a601e74f4660cd52ebd68a7b3 +Subproject commit 192fd1e6ad269c3cbdb81aa8c43a8bc20c5ae7f0 diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index e8684f9d..a542dab5 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -1,15 +1,24 @@ using Newtonsoft.Json.Linq; using OtterGui.Classes; using OtterGui.Log; +using OtterGui.Services; namespace Penumbra.Services; -public class BackupService +public class BackupService : IAsyncService { + /// + public Task Awaiter { get; } + + /// + public bool Finished + => Awaiter.IsCompletedSuccessfully; + + /// Start a backup process on the collected files. public BackupService(Logger logger, FilenameService fileNames) { - var files = PenumbraFiles(fileNames); - Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), files); + var files = PenumbraFiles(fileNames); + Awaiter = Task.Run(() => Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), files)); } /// Collect all relevant files for penumbra configuration. diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index 3e61e3c1..c7efac04 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -1,10 +1,11 @@ using OtterGui.Classes; using OtterGui.Log; +using OtterGui.Services; using Penumbra.Communication; namespace Penumbra.Services; -public class CommunicatorService : IDisposable +public class CommunicatorService : IDisposable, IService { public CommunicatorService(Logger logger) { diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index beb23fa2..b84c0996 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -1,7 +1,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui.Classes; using OtterGui.Filesystem; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -22,10 +22,8 @@ namespace Penumbra.Services; /// Contains everything to migrate from older versions of the config to the current, /// including deprecated fields. /// -public class ConfigMigrationService +public class ConfigMigrationService(SaveService saveService) : IService { - private readonly SaveService _saveService; - private Configuration _config = null!; private JObject _data = null!; @@ -33,14 +31,11 @@ public class ConfigMigrationService public string DefaultCollection = ModCollection.DefaultCollectionName; public string ForcedCollection = string.Empty; public Dictionary CharacterCollections = []; - public Dictionary ModSortOrder = new(); + public Dictionary ModSortOrder = []; public bool InvertModListOrder; public bool SortFoldersFirst; public SortModeV3 SortMode = SortModeV3.FoldersFirst; - public ConfigMigrationService(SaveService saveService) - => _saveService = saveService; - /// Add missing colors to the dictionary if necessary. private static void AddColors(Configuration config, bool forceSave) { @@ -61,13 +56,13 @@ public class ConfigMigrationService // because it stayed alive for a bunch of people for some reason. DeleteMetaTmp(); - if (config.Version >= Configuration.Constants.CurrentVersion || !File.Exists(_saveService.FileNames.ConfigFile)) + if (config.Version >= Configuration.Constants.CurrentVersion || !File.Exists(saveService.FileNames.ConfigFile)) { AddColors(config, false); return; } - _data = JObject.Parse(File.ReadAllText(_saveService.FileNames.ConfigFile)); + _data = JObject.Parse(File.ReadAllText(saveService.FileNames.ConfigFile)); CreateBackup(); Version0To1(); @@ -118,7 +113,7 @@ public class ConfigMigrationService if (_config.Version != 6) return; - ActiveCollectionMigration.MigrateUngenderedCollections(_saveService.FileNames); + ActiveCollectionMigration.MigrateUngenderedCollections(saveService.FileNames); _config.Version = 7; } @@ -223,7 +218,7 @@ public class ConfigMigrationService return; // Add the previous forced collection to all current collections except itself as an inheritance. - foreach (var collection in _saveService.FileNames.CollectionFiles) + foreach (var collection in saveService.FileNames.CollectionFiles) { try { @@ -246,7 +241,7 @@ public class ConfigMigrationService private void ResettleSortOrder() { ModSortOrder = _data[nameof(ModSortOrder)]?.ToObject>() ?? ModSortOrder; - var file = _saveService.FileNames.FilesystemFile; + var file = saveService.FileNames.FilesystemFile; using var stream = File.Open(file, File.Exists(file) ? FileMode.Truncate : FileMode.CreateNew); using var writer = new StreamWriter(stream); using var j = new JsonTextWriter(writer); @@ -281,7 +276,7 @@ public class ConfigMigrationService private void SaveActiveCollectionsV0(string def, string ui, string current, IEnumerable<(string, string)> characters, IEnumerable<(CollectionType, string)> special) { - var file = _saveService.FileNames.ActiveCollectionsFile; + var file = saveService.FileNames.ActiveCollectionsFile; try { using var stream = File.Open(file, File.Exists(file) ? FileMode.Truncate : FileMode.CreateNew); @@ -337,7 +332,7 @@ public class ConfigMigrationService if (!collectionJson.Exists) return; - var defaultCollectionFile = new FileInfo(_saveService.FileNames.CollectionFile(ModCollection.DefaultCollectionName)); + var defaultCollectionFile = new FileInfo(saveService.FileNames.CollectionFile(ModCollection.DefaultCollectionName)); if (defaultCollectionFile.Exists) return; @@ -370,9 +365,9 @@ public class ConfigMigrationService dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value with { Priority = maxPriority - kvp.Value.Priority }); var emptyStorage = new ModStorage(); - var collection = ModCollection.CreateFromData(_saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, + var collection = ModCollection.CreateFromData(saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, Array.Empty()); - _saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); + saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) { @@ -384,7 +379,7 @@ public class ConfigMigrationService // Create a backup of the configuration file specifically. private void CreateBackup() { - var name = _saveService.FileNames.ConfigFile; + var name = saveService.FileNames.ConfigFile; var bakName = name + ".bak"; try { diff --git a/Penumbra/Services/DalamudServices.cs b/Penumbra/Services/DalamudConfigService.cs similarity index 72% rename from Penumbra/Services/DalamudServices.cs rename to Penumbra/Services/DalamudConfigService.cs index 51fb1192..8379a3e7 100644 --- a/Penumbra/Services/DalamudServices.cs +++ b/Penumbra/Services/DalamudConfigService.cs @@ -1,21 +1,12 @@ -using Dalamud.Game; -using Dalamud.Game.ClientState.Objects; -using Dalamud.Interface; -using Dalamud.IoC; using Dalamud.Plugin; -using Dalamud.Interface.DragDrop; -using Dalamud.Plugin.Services; using OtterGui.Services; -// ReSharper disable AutoPropertyCanBeMadeGetOnly.Local - namespace Penumbra.Services; -public class DalamudConfigService +public class DalamudConfigService : IService { - public DalamudConfigService(DalamudPluginInterface pluginInterface) + public DalamudConfigService() { - pluginInterface.Inject(this); try { var serviceType = @@ -115,29 +106,3 @@ public class DalamudConfigService } } } - -public static class DalamudServices -{ - public static void AddServices(ServiceManager services, DalamudPluginInterface pi) - { - services.AddExistingService(pi); - services.AddExistingService(pi.UiBuilder); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - services.AddDalamudService(pi); - } -} diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 52881b9e..5f918a90 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -1,11 +1,11 @@ using Dalamud.Plugin; -using OtterGui.Filesystem; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Mods; namespace Penumbra.Services; -public class FilenameService(DalamudPluginInterface pi) +public class FilenameService(DalamudPluginInterface pi) : IService { public readonly string ConfigDirectory = pi.ConfigDirectory.FullName; public readonly string CollectionDirectory = Path.Combine(pi.ConfigDirectory.FullName, "collections"); diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index c893b00f..06c3c4d0 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -5,15 +5,12 @@ using Dalamud.Interface; using Dalamud.Plugin.Services; using Lumina.Excel.GeneratedSheets; using OtterGui.Log; +using OtterGui.Services; namespace Penumbra.Services; -public class MessageService : OtterGui.Classes.MessageService +public class MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat) : OtterGui.Classes.MessageService(log, uiBuilder, chat), IService { - public MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat) - : base(log, uiBuilder, chat) - { } - public void LinkItem(Item item) { // @formatter:off diff --git a/Penumbra/Services/SaveService.cs b/Penumbra/Services/SaveService.cs index 40dc4107..801e0c1d 100644 --- a/Penumbra/Services/SaveService.cs +++ b/Penumbra/Services/SaveService.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using OtterGui.Log; +using OtterGui.Services; using Penumbra.Mods; using Penumbra.Mods.Subclasses; @@ -11,12 +12,9 @@ namespace Penumbra.Services; public interface ISavable : ISavable { } -public sealed class SaveService : SaveServiceBase +public sealed class SaveService(Logger log, FrameworkManager framework, FilenameService fileNames, BackupService backupService) + : SaveServiceBase(log, framework, fileNames, backupService.Awaiter), IService { - public SaveService(Logger log, FrameworkManager framework, FilenameService fileNames) - : base(log, framework, fileNames) - { } - /// Immediately delete all existing option group files for a mod and save them anew. public void SaveAllOptionGroups(Mod mod, bool backup, bool onlyAscii) { diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index 410acfb9..5a1c9f74 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -1,5 +1,10 @@ +using Dalamud.Game; +using Dalamud.Game.ClientState.Objects; +using Dalamud.Interface.DragDrop; using Dalamud.Plugin; +using Dalamud.Plugin.Services; using Microsoft.Extensions.DependencyInjection; +using OtterGui; using OtterGui.Classes; using OtterGui.Compression; using OtterGui.Log; @@ -8,7 +13,6 @@ using Penumbra.Api; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; -using Penumbra.GameData.Data; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Structs; using Penumbra.Import.Textures; @@ -37,10 +41,9 @@ public static class ServiceManagerA public static ServiceManager CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log) { var services = new ServiceManager(log) + .AddDalamudServices(pi) .AddExistingService(log) .AddExistingService(penumbra) - .AddMeta() - .AddGameData() .AddInterop() .AddConfiguration() .AddCollections() @@ -52,27 +55,31 @@ public static class ServiceManagerA .AddApi(); services.AddIServices(typeof(EquipItem).Assembly); services.AddIServices(typeof(Penumbra).Assembly); - DalamudServices.AddServices(services, pi); + services.AddIServices(typeof(ImGuiUtil).Assembly); services.CreateProvider(); return services; } - private static ServiceManager AddMeta(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); - - - private static ServiceManager AddGameData(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton(); + private static ServiceManager AddDalamudServices(this ServiceManager services, DalamudPluginInterface pi) + => services.AddExistingService(pi) + .AddExistingService(pi.UiBuilder) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi) + .AddDalamudService(pi); private static ServiceManager AddInterop(this ServiceManager services) => services.AddSingleton() @@ -95,8 +102,7 @@ public static class ServiceManagerA .AddSingleton(); private static ServiceManager AddConfiguration(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() + => services.AddSingleton() .AddSingleton(); private static ServiceManager AddCollections(this ServiceManager services) diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 714576b2..00fc0737 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -1,36 +1,26 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using Dalamud.Plugin; using Dalamud.Plugin.Services; using ImGuiNET; -using OtterGui.Log; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Files; using Penumbra.UI.AdvancedWindow; -using Penumbra.Util; namespace Penumbra.Services; -public class StainService : IDisposable +public class StainService : IService { - public sealed class StainTemplateCombo : FilterComboCache + public sealed class StainTemplateCombo(FilterComboColors stainCombo, StmFile stmFile) + : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), Penumbra.Log) { - private readonly StmFile _stmFile; - private readonly FilterComboColors _stainCombo; - - public StainTemplateCombo(FilterComboColors stainCombo, StmFile stmFile) - : base(stmFile.Entries.Keys.Prepend((ushort)0), Penumbra.Log) - { - _stainCombo = stainCombo; - _stmFile = stmFile; - } - protected override float GetFilterWidth() { - var baseSize = ImGui.CalcTextSize("0000").X + ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X; - if (_stainCombo.CurrentSelection.Key == 0) + var baseSize = ImGui.CalcTextSize("0000").X + ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X; + if (stainCombo.CurrentSelection.Key == 0) return baseSize; + return baseSize + ImGui.GetTextLineHeight() * 3 + ImGui.GetStyle().ItemInnerSpacing.X * 3; } @@ -46,19 +36,19 @@ public class StainService : IDisposable public override bool Draw(string label, string preview, string tooltip, ref int currentSelection, float previewWidth, float itemHeight, ImGuiComboFlags flags = ImGuiComboFlags.None) { - using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var font = ImRaii.PushFont(UiBuilder.MonoFont); using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(1, 0.5f)) .Push(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing with { X = ImGui.GetStyle().ItemInnerSpacing.X }); var spaceSize = ImGui.CalcTextSize(" ").X; - var spaces = (int) (previewWidth / spaceSize) - 1; + var spaces = (int)(previewWidth / spaceSize) - 1; return base.Draw(label, preview.PadLeft(spaces), tooltip, ref currentSelection, previewWidth, itemHeight, flags); } protected override bool DrawSelectable(int globalIdx, bool selected) { var ret = base.DrawSelectable(globalIdx, selected); - var selection = _stainCombo.CurrentSelection.Key; - if (selection == 0 || !_stmFile.TryGetValue(Items[globalIdx], selection, out var colors)) + var selection = stainCombo.CurrentSelection.Key; + if (selection == 0 || !stmFile.TryGetValue(Items[globalIdx], selection, out var colors)) return ret; ImGui.SameLine(); @@ -72,25 +62,18 @@ public class StainService : IDisposable } } - public readonly DictStains StainData; + public readonly DictStain StainData; public readonly FilterComboColors StainCombo; public readonly StmFile StmFile; public readonly StainTemplateCombo TemplateCombo; - public StainService(DalamudPluginInterface pluginInterface, IDataManager dataManager, Logger logger) + public StainService(IDataManager dataManager, DictStain stainData) { - StainData = new DictStains(pluginInterface, logger, dataManager); + StainData = stainData; StainCombo = new FilterComboColors(140, () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), Penumbra.Log); StmFile = new StmFile(dataManager); TemplateCombo = new StainTemplateCombo(StainCombo, StmFile); - Penumbra.Log.Verbose($"[{nameof(StainService)}] Created."); - } - - public void Dispose() - { - StainData.Dispose(); - Penumbra.Log.Verbose($"[{nameof(StainService)}] Disposed."); } } diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index 7287938c..4d071f85 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -1,10 +1,11 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Plugin; using OtterGui.Classes; +using OtterGui.Services; namespace Penumbra.Services; -public class ValidityChecker +public class ValidityChecker : IService { public const string Repository = "https://raw.githubusercontent.com/xivdev/Penumbra/master/repo.json"; public const string SeaOfStars = "https://raw.githubusercontent.com/Ottermandias/SeaOfStars/main/repo.json"; diff --git a/Penumbra/Util/PerformanceType.cs b/Penumbra/Util/PerformanceType.cs index b84813cc..d5755dfd 100644 --- a/Penumbra/Util/PerformanceType.cs +++ b/Penumbra/Util/PerformanceType.cs @@ -1,7 +1,10 @@ -global using PerformanceTracker = OtterGui.Classes.PerformanceTracker; +using Dalamud.Plugin.Services; +using OtterGui.Services; namespace Penumbra.Util; +public sealed class PerformanceTracker(IFramework framework) : OtterGui.Classes.PerformanceTracker(framework), IService; + public enum PerformanceType { UiMainWindow, From 309f0351fa2f5d95e831eb52ae78374a3d1ac772 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 31 Dec 2023 15:33:37 +1100 Subject: [PATCH 0297/1381] Build indices for entire mesh --- Penumbra/Import/Models/MeshConverter.cs | 26 +++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/MeshConverter.cs index 9f55383e..4aa60331 100644 --- a/Penumbra/Import/Models/MeshConverter.cs +++ b/Penumbra/Import/Models/MeshConverter.cs @@ -40,7 +40,7 @@ public sealed class MeshConverter var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements .Select(element => (MdlFile.VertexUsage)element.Usage) .ToImmutableHashSet(); - + _geometryType = GetGeometryType(usages); _skinningType = GetSkinningType(usages); } @@ -58,7 +58,7 @@ public sealed class MeshConverter if (!boneNameMap.TryGetValue(boneName, out var gltfBoneIndex)) // TODO: handle - i think this is a hard failure, it means that a bone name in the model doesn't exist in the armature. throw new Exception($"looking for {boneName} in {string.Join(", ", boneNameMap.Keys)}"); - + indexMap.Add(xivBoneIndex, gltfBoneIndex); } @@ -67,6 +67,7 @@ public sealed class MeshConverter private IMeshBuilder[] BuildMesh() { + var indices = BuildIndices(); var vertices = BuildVertices(); // TODO: handle submeshCount = 0 @@ -74,13 +75,14 @@ public sealed class MeshConverter return _mdl.SubMeshes .Skip(Mesh.SubMeshIndex) .Take(Mesh.SubMeshCount) - .Select(submesh => BuildSubMesh(submesh, vertices)) + .Select(submesh => BuildSubMesh(submesh, indices, vertices)) .ToArray(); } - private IMeshBuilder BuildSubMesh(MdlStructs.SubmeshStruct submesh, IReadOnlyList vertices) + private IMeshBuilder BuildSubMesh(MdlStructs.SubmeshStruct submesh, IReadOnlyList indices, IReadOnlyList vertices) { - var indices = BuildIndices(submesh); + // Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh. + var startIndex = (int)(submesh.IndexOffset - Mesh.StartIndex); var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( typeof(MaterialBuilder), @@ -102,19 +104,19 @@ public sealed class MeshConverter // TODO: split by submeshes for (var indexOffset = 0; indexOffset < submesh.IndexCount; indexOffset += 3) primitiveBuilder.AddTriangle( - vertices[indices[indexOffset + 0]], - vertices[indices[indexOffset + 1]], - vertices[indices[indexOffset + 2]] + vertices[indices[indexOffset + startIndex + 0]], + vertices[indices[indexOffset + startIndex + 1]], + vertices[indices[indexOffset + startIndex + 2]] ); return meshBuilder; } - private IReadOnlyList BuildIndices(MdlStructs.SubmeshStruct submesh) + private IReadOnlyList BuildIndices() { var reader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - reader.Seek(_mdl.IndexOffset[_lod] + submesh.IndexOffset * sizeof(ushort)); - return reader.ReadStructuresAsArray((int)submesh.IndexCount); + reader.Seek(_mdl.IndexOffset[_lod] + Mesh.StartIndex * sizeof(ushort)); + return reader.ReadStructuresAsArray((int)Mesh.IndexCount); } private IReadOnlyList BuildVertices() @@ -244,7 +246,7 @@ public sealed class MeshConverter // Some tangent W values that should be -1 are stored as 0. private Vector4 FixTangentVector(Vector4 tangent) => tangent with { W = tangent.W == 1 ? 1 : -1 }; - + private Vector3 ToVector3(object data) => data switch { From 989915ddbe36e6d5bedea429d3e132c97897a584 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 31 Dec 2023 16:10:20 +1100 Subject: [PATCH 0298/1381] Add initial shape key support --- Penumbra/Import/Models/MeshConverter.cs | 42 +++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/MeshConverter.cs index 4aa60331..ff52b967 100644 --- a/Penumbra/Import/Models/MeshConverter.cs +++ b/Penumbra/Import/Models/MeshConverter.cs @@ -100,14 +100,52 @@ public sealed class MeshConverter var primitiveBuilder = meshBuilder.UsePrimitive(materialBuilder); + // Store a list of the glTF indices. The list index will be equivalent to the xiv (submesh) index. + var gltfIndices = new List(); + // All XIV meshes use triangle lists. - // TODO: split by submeshes for (var indexOffset = 0; indexOffset < submesh.IndexCount; indexOffset += 3) - primitiveBuilder.AddTriangle( + { + var (a, b, c) = primitiveBuilder.AddTriangle( vertices[indices[indexOffset + startIndex + 0]], vertices[indices[indexOffset + startIndex + 1]], vertices[indices[indexOffset + startIndex + 2]] ); + gltfIndices.AddRange([a, b, c]); + } + + var primitiveVertices = meshBuilder.Primitives.First().Vertices; + var shapeNames = new List(); + + foreach (var shape in _mdl.Shapes) + { + // Filter down to shape values for the current mesh that sit within the bounds of the current submesh. + var shapeValues = _mdl.ShapeMeshes + .Skip(shape.ShapeMeshStartIndex[_lod]) + .Take(shape.ShapeMeshCount[_lod]) + .Where(shapeMesh => shapeMesh.MeshIndexOffset == Mesh.StartIndex) + .SelectMany(shapeMesh => + _mdl.ShapeValues + .Skip((int)shapeMesh.ShapeValueOffset) + .Take((int)shapeMesh.ShapeValueCount) + ) + .Where(shapeValue => + shapeValue.BaseIndicesIndex >= startIndex + && shapeValue.BaseIndicesIndex < startIndex + submesh.IndexCount + ) + .ToList(); + + if (shapeValues.Count == 0) continue; + + var morphBuilder = meshBuilder.UseMorphTarget(shapeNames.Count); + shapeNames.Add(shape.ShapeName); + + foreach (var shapeValue in shapeValues) + morphBuilder.SetVertex( + primitiveVertices[gltfIndices[shapeValue.BaseIndicesIndex - startIndex]].GetGeometry(), + vertices[shapeValue.ReplacingVertexIndex].GetGeometry() + ); + } return meshBuilder; } From 6a2b802196953d78033cdc6824c0c22bd87e6192 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 31 Dec 2023 17:11:08 +1100 Subject: [PATCH 0299/1381] Add shape key names --- Penumbra/Import/Models/MeshConverter.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/MeshConverter.cs index ff52b967..97121798 100644 --- a/Penumbra/Import/Models/MeshConverter.cs +++ b/Penumbra/Import/Models/MeshConverter.cs @@ -4,6 +4,7 @@ using Lumina.Extensions; using Penumbra.GameData.Files; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; +using SharpGLTF.IO; using SharpGLTF.Materials; namespace Penumbra.Import.Modules; @@ -124,7 +125,7 @@ public sealed class MeshConverter .Skip(shape.ShapeMeshStartIndex[_lod]) .Take(shape.ShapeMeshCount[_lod]) .Where(shapeMesh => shapeMesh.MeshIndexOffset == Mesh.StartIndex) - .SelectMany(shapeMesh => + .SelectMany(shapeMesh => _mdl.ShapeValues .Skip((int)shapeMesh.ShapeValueOffset) .Take((int)shapeMesh.ShapeValueCount) @@ -147,6 +148,10 @@ public sealed class MeshConverter ); } + meshBuilder.Extras = JsonContent.CreateFrom(new Dictionary() { + {"targetNames", shapeNames} + }); + return meshBuilder; } From 551c25a64cf93a58fe2e7ca253a79542da345474 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 00:18:03 +1100 Subject: [PATCH 0300/1381] Move a few things to export subdir --- .../MeshExporter.cs} | 60 +++++++---- .../Import/Models/Export/ModelExporter.cs | 100 ++++++++++++++++++ .../Import/Models/{ => Export}/Skeleton.cs | 16 ++- Penumbra/Import/Models/ModelManager.cs | 69 ++---------- Penumbra/Import/Models/SkeletonConverter.cs | 11 +- 5 files changed, 169 insertions(+), 87 deletions(-) rename Penumbra/Import/Models/{MeshConverter.cs => Export/MeshExporter.cs} (84%) create mode 100644 Penumbra/Import/Models/Export/ModelExporter.cs rename Penumbra/Import/Models/{ => Export}/Skeleton.cs (53%) diff --git a/Penumbra/Import/Models/MeshConverter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs similarity index 84% rename from Penumbra/Import/Models/MeshConverter.cs rename to Penumbra/Import/Models/Export/MeshExporter.cs index 97121798..fdfa59e4 100644 --- a/Penumbra/Import/Models/MeshConverter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -6,15 +6,39 @@ using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; using SharpGLTF.IO; using SharpGLTF.Materials; +using SharpGLTF.Scenes; -namespace Penumbra.Import.Modules; +namespace Penumbra.Import.Models.Export; -public sealed class MeshConverter +public class MeshExporter { - public static IMeshBuilder[] ToGltf(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) + public class Mesh { - var self = new MeshConverter(mdl, lod, meshIndex, boneNameMap); - return self.BuildMesh(); + private IMeshBuilder[] _meshes; + private NodeBuilder[]? _joints; + + public Mesh(IMeshBuilder[] meshes, NodeBuilder[]? joints) + { + _meshes = meshes; + _joints = joints; + } + + public void AddToScene(SceneBuilder scene) + { + // TODO: throw if mesh has skinned vertices but no joints are available? + foreach (var mesh in _meshes) + if (_joints == null) + scene.AddRigidMesh(mesh, Matrix4x4.Identity); + else + scene.AddSkinnedMesh(mesh, Matrix4x4.Identity, _joints); + } + } + + // TODO: replace bonenamemap with a gltfskeleton + public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, GltfSkeleton? skeleton) + { + var self = new MeshExporter(mdl, lod, meshIndex, skeleton?.Names); + return new Mesh(self.BuildMeshes(), skeleton?.Joints); } private const byte MaximumMeshBufferStreams = 3; @@ -22,14 +46,14 @@ public sealed class MeshConverter private readonly MdlFile _mdl; private readonly byte _lod; private readonly ushort _meshIndex; - private MdlStructs.MeshStruct Mesh => _mdl.Meshes[_meshIndex]; + private MdlStructs.MeshStruct XivMesh => _mdl.Meshes[_meshIndex]; private readonly Dictionary? _boneIndexMap; private readonly Type _geometryType; private readonly Type _skinningType; - private MeshConverter(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) + private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) { _mdl = mdl; _lod = lod; @@ -49,7 +73,7 @@ public sealed class MeshConverter private Dictionary BuildBoneIndexMap(Dictionary boneNameMap) { // todo: BoneTableIndex of 255 means null? if so, it should probably feed into the attributes we assign... - var xivBoneTable = _mdl.BoneTables[Mesh.BoneTableIndex]; + var xivBoneTable = _mdl.BoneTables[XivMesh.BoneTableIndex]; var indexMap = new Dictionary(); @@ -66,16 +90,16 @@ public sealed class MeshConverter return indexMap; } - private IMeshBuilder[] BuildMesh() + private IMeshBuilder[] BuildMeshes() { var indices = BuildIndices(); var vertices = BuildVertices(); - // TODO: handle submeshCount = 0 + // TODO: handle SubMeshCount = 0 return _mdl.SubMeshes - .Skip(Mesh.SubMeshIndex) - .Take(Mesh.SubMeshCount) + .Skip(XivMesh.SubMeshIndex) + .Take(XivMesh.SubMeshCount) .Select(submesh => BuildSubMesh(submesh, indices, vertices)) .ToArray(); } @@ -83,7 +107,7 @@ public sealed class MeshConverter private IMeshBuilder BuildSubMesh(MdlStructs.SubmeshStruct submesh, IReadOnlyList indices, IReadOnlyList vertices) { // Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh. - var startIndex = (int)(submesh.IndexOffset - Mesh.StartIndex); + var startIndex = (int)(submesh.IndexOffset - XivMesh.StartIndex); var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( typeof(MaterialBuilder), @@ -124,7 +148,7 @@ public sealed class MeshConverter var shapeValues = _mdl.ShapeMeshes .Skip(shape.ShapeMeshStartIndex[_lod]) .Take(shape.ShapeMeshCount[_lod]) - .Where(shapeMesh => shapeMesh.MeshIndexOffset == Mesh.StartIndex) + .Where(shapeMesh => shapeMesh.MeshIndexOffset == XivMesh.StartIndex) .SelectMany(shapeMesh => _mdl.ShapeValues .Skip((int)shapeMesh.ShapeValueOffset) @@ -158,8 +182,8 @@ public sealed class MeshConverter private IReadOnlyList BuildIndices() { var reader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - reader.Seek(_mdl.IndexOffset[_lod] + Mesh.StartIndex * sizeof(ushort)); - return reader.ReadStructuresAsArray((int)Mesh.IndexCount); + reader.Seek(_mdl.IndexOffset[_lod] + XivMesh.StartIndex * sizeof(ushort)); + return reader.ReadStructuresAsArray((int)XivMesh.IndexCount); } private IReadOnlyList BuildVertices() @@ -172,7 +196,7 @@ public sealed class MeshConverter for (var streamIndex = 0; streamIndex < MaximumMeshBufferStreams; streamIndex++) { streams[streamIndex] = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - streams[streamIndex].Seek(_mdl.VertexOffset[_lod] + Mesh.VertexBufferOffset[streamIndex]); + streams[streamIndex].Seek(_mdl.VertexOffset[_lod] + XivMesh.VertexBufferOffset[streamIndex]); } var sortedElements = _mdl.VertexDeclarations[_meshIndex].VertexElements @@ -183,7 +207,7 @@ public sealed class MeshConverter var vertices = new List(); var attributes = new Dictionary(); - for (var vertexIndex = 0; vertexIndex < Mesh.VertexCount; vertexIndex++) + for (var vertexIndex = 0; vertexIndex < XivMesh.VertexCount; vertexIndex++) { attributes.Clear(); diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs new file mode 100644 index 00000000..c8716cf3 --- /dev/null +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -0,0 +1,100 @@ +using Penumbra.GameData.Files; +using SharpGLTF.Scenes; +using SharpGLTF.Transforms; + +namespace Penumbra.Import.Models.Export; + +public class ModelExporter +{ + public class Model + { + private List _meshes; + private GltfSkeleton? _skeleton; + + public Model(List meshes, GltfSkeleton? skeleton) + { + _meshes = meshes; + _skeleton = skeleton; + } + + public void AddToScene(SceneBuilder scene) + { + // If there's a skeleton, the root node should be added before we add any potentially skinned meshes. + var skeletonRoot = _skeleton?.Root; + if (skeletonRoot != null) + scene.AddNode(skeletonRoot); + + // Add all the meshes to the scene. + foreach (var mesh in _meshes) + mesh.AddToScene(scene); + } + } + + public static Model Export(MdlFile mdl, XivSkeleton? xivSkeleton) + { + var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; + var meshes = ConvertMeshes(mdl, gltfSkeleton); + return new Model(meshes, gltfSkeleton); + } + + private static List ConvertMeshes(MdlFile mdl, GltfSkeleton? skeleton) + { + var meshes = new List(); + + for (byte lodIndex = 0; lodIndex < mdl.LodCount; lodIndex++) + { + var lod = mdl.Lods[lodIndex]; + + // TODO: consider other types of mesh? + for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) + { + var mesh = MeshExporter.Export(mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), skeleton); + meshes.Add(mesh); + } + } + + return meshes; + } + + private static GltfSkeleton? ConvertSkeleton(XivSkeleton skeleton) + { + NodeBuilder? root = null; + var names = new Dictionary(); + var joints = new List(); + for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) + { + var bone = skeleton.Bones[boneIndex]; + + if (names.ContainsKey(bone.Name)) continue; + + var node = new NodeBuilder(bone.Name); + names[bone.Name] = joints.Count; + joints.Add(node); + + node.SetLocalTransform(new AffineTransform( + bone.Transform.Scale, + bone.Transform.Rotation, + bone.Transform.Translation + ), false); + + if (bone.ParentIndex == -1) + { + root = node; + continue; + } + + var parent = joints[names[skeleton.Bones[bone.ParentIndex].Name]]; + parent.AddNode(node); + } + + if (root == null) + return null; + + return new() + { + Root = root, + Joints = joints.ToArray(), + Names = names, + }; + } +} diff --git a/Penumbra/Import/Models/Skeleton.cs b/Penumbra/Import/Models/Export/Skeleton.cs similarity index 53% rename from Penumbra/Import/Models/Skeleton.cs rename to Penumbra/Import/Models/Export/Skeleton.cs index fb5c8284..13379dc4 100644 --- a/Penumbra/Import/Models/Skeleton.cs +++ b/Penumbra/Import/Models/Export/Skeleton.cs @@ -1,11 +1,12 @@ -namespace Penumbra.Import.Models; +using SharpGLTF.Scenes; -// TODO: this should almost certainly live in gamedata. if not, it should at _least_ be adjacent to the model handling. -public class Skeleton +namespace Penumbra.Import.Models.Export; + +public class XivSkeleton { public Bone[] Bones; - public Skeleton(Bone[] bones) + public XivSkeleton(Bone[] bones) { Bones = bones; } @@ -23,3 +24,10 @@ public class Skeleton public Vector3 Translation; } } + +public struct GltfSkeleton +{ + public NodeBuilder Root; + public NodeBuilder[] Joints; + public Dictionary Names; +} diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 2dd64235..9f72619f 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -2,7 +2,7 @@ using Dalamud.Plugin.Services; using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData.Files; -using Penumbra.Import.Modules; +using Penumbra.Import.Models.Export; using SharpGLTF.Scenes; using SharpGLTF.Transforms; @@ -73,36 +73,18 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public void Execute(CancellationToken cancel) { + var xivSkeleton = BuildSkeleton(cancel); + var model = ModelExporter.Export(_mdl, xivSkeleton); + var scene = new SceneBuilder(); + model.AddToScene(scene); - var skeleton = BuildSkeleton(cancel); - if (skeleton != null) - scene.AddNode(skeleton.Value.Root); - - // TODO: group by LoD in output tree - for (byte lodIndex = 0; lodIndex < _mdl.LodCount; lodIndex++) - { - var lod = _mdl.Lods[lodIndex]; - - // TODO: consider other types of mesh? - for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) - { - var meshBuilders = MeshConverter.ToGltf(_mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), skeleton?.Names); - // TODO: use a value from the mesh converter for this check, rather than assuming that it has joints - foreach (var meshBuilder in meshBuilders) - if (skeleton == null) - scene.AddRigidMesh(meshBuilder, Matrix4x4.Identity); - else - scene.AddSkinnedMesh(meshBuilder, Matrix4x4.Identity, skeleton?.Joints); - } - } - - var model = scene.ToGltf2(); - model.SaveGLTF(_outputPath); + var gltfModel = scene.ToGltf2(); + gltfModel.SaveGLTF(_outputPath); } // TODO: this should be moved to a seperate model converter or something - private (NodeBuilder Root, NodeBuilder[] Joints, Dictionary Names)? BuildSkeleton(CancellationToken cancel) + private XivSkeleton? BuildSkeleton(CancellationToken cancel) { if (_sklb == null) return null; @@ -117,40 +99,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var skeletonConverter = new SkeletonConverter(); var skeleton = skeletonConverter.FromXml(xml); - // this is (less) atrocious - NodeBuilder? root = null; - var names = new Dictionary(); - var joints = new List(); - for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) - { - var bone = skeleton.Bones[boneIndex]; - - if (names.ContainsKey(bone.Name)) continue; - - var node = new NodeBuilder(bone.Name); - names[bone.Name] = joints.Count; - joints.Add(node); - - node.SetLocalTransform(new AffineTransform( - bone.Transform.Scale, - bone.Transform.Rotation, - bone.Transform.Translation - ), false); - - if (bone.ParentIndex == -1) - { - root = node; - continue; - } - - var parent = joints[names[skeleton.Bones[bone.ParentIndex].Name]]; - parent.AddNode(node); - } - - if (root == null) - return null; - - return (root, joints.ToArray(), names); + return skeleton; } public bool Equals(IAction? other) diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs index d54b0294..e265e5c3 100644 --- a/Penumbra/Import/Models/SkeletonConverter.cs +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -1,12 +1,13 @@ using System.Xml; using OtterGui; +using Penumbra.Import.Models.Export; namespace Penumbra.Import.Models; // TODO: tempted to say that this living here is more okay? that or next to havok converter, wherever that ends up. public class SkeletonConverter { - public Skeleton FromXml(string xml) + public XivSkeleton FromXml(string xml) { var document = new XmlDocument(); document.LoadXml(xml); @@ -29,7 +30,7 @@ public class SkeletonConverter .Select(values => { var (transform, parentIndex, name) = values; - return new Skeleton.Bone() + return new XivSkeleton.Bone() { Transform = transform, ParentIndex = parentIndex, @@ -38,7 +39,7 @@ public class SkeletonConverter }) .ToArray(); - return new Skeleton(bones); + return new XivSkeleton(bones); } /// Get the main skeleton ID for a given skeleton document. @@ -57,14 +58,14 @@ public class SkeletonConverter /// Read the reference pose transforms for a skeleton. /// XML node for the skeleton. - private Skeleton.Transform[] ReadReferencePose(XmlNode node) + private XivSkeleton.Transform[] ReadReferencePose(XmlNode node) { return ReadArray( CheckExists(node.SelectSingleNode("array[@name='referencePose']")), node => { var raw = ReadVec12(node); - return new Skeleton.Transform() + return new XivSkeleton.Transform() { Translation = new(raw[0], raw[1], raw[2]), Rotation = new(raw[4], raw[5], raw[6], raw[7]), From f1379af92cbf292622c79cc1b1ff4e82a441ec8b Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 00:38:24 +1100 Subject: [PATCH 0301/1381] Add UV export --- Penumbra/Import/Models/Export/MeshExporter.cs | 55 ++++++++++++++++++- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index fdfa59e4..06ca747b 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -51,6 +51,7 @@ public class MeshExporter private readonly Dictionary? _boneIndexMap; private readonly Type _geometryType; + private readonly Type _materialType; private readonly Type _skinningType; private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) @@ -67,6 +68,7 @@ public class MeshExporter .ToImmutableHashSet(); _geometryType = GetGeometryType(usages); + _materialType = GetMaterialType(usages); _skinningType = GetSkinningType(usages); } @@ -112,7 +114,7 @@ public class MeshExporter var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( typeof(MaterialBuilder), _geometryType, - typeof(VertexEmpty), + _materialType, _skinningType ); var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, $"mesh{_meshIndex}")!; @@ -189,7 +191,7 @@ public class MeshExporter private IReadOnlyList BuildVertices() { var vertexBuilderType = typeof(VertexBuilder<,,>) - .MakeGenericType(_geometryType, typeof(VertexEmpty), _skinningType); + .MakeGenericType(_geometryType, _materialType, _skinningType); // NOTE: This assumes that buffer streams are tightly packed, which has proven safe across tested files. If this assumption is broken, seeks will need to be moved into the vertex element loop. var streams = new BinaryReader[MaximumMeshBufferStreams]; @@ -215,9 +217,10 @@ public class MeshExporter attributes[usage] = ReadVertexAttribute(streams[element.Stream], element); var vertexGeometry = BuildVertexGeometry(attributes); + var vertexMaterial = BuildVertexMaterial(attributes); var vertexSkinning = BuildVertexSkinning(attributes); - var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, new VertexEmpty(), vertexSkinning)!; + var vertexBuilder = (IVertexBuilder)Activator.CreateInstance(vertexBuilderType, vertexGeometry, vertexMaterial, vertexSkinning)!; vertices.Add(vertexBuilder); } @@ -276,6 +279,43 @@ public class MeshExporter throw new Exception($"Unknown geometry type {_geometryType}."); } + private Type GetMaterialType(IReadOnlySet usages) + { + // TODO: IIUC, xiv's uv2 is usually represented as the second two components of a vec4 uv attribute - add support. + var materialUsages = ( + usages.Contains(MdlFile.VertexUsage.UV), + usages.Contains(MdlFile.VertexUsage.Color) + ); + + return materialUsages switch + { + (true, true) => typeof(VertexColor1Texture1), + (true, false) => typeof(VertexTexture1), + (false, true) => typeof(VertexColor1), + (false, false) => typeof(VertexEmpty), + }; + } + + private IVertexMaterial BuildVertexMaterial(IReadOnlyDictionary attributes) + { + if (_materialType == typeof(VertexEmpty)) + return new VertexEmpty(); + + if (_materialType == typeof(VertexColor1)) + return new VertexColor1(ToVector4(attributes[MdlFile.VertexUsage.Color])); + + if (_materialType == typeof(VertexTexture1)) + return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV])); + + if (_materialType == typeof(VertexColor1Texture1)) + return new VertexColor1Texture1( + ToVector4(attributes[MdlFile.VertexUsage.Color]), + ToVector2(attributes[MdlFile.VertexUsage.UV]) + ); + + throw new Exception($"Unknown material type {_skinningType}"); + } + private Type GetSkinningType(IReadOnlySet usages) { // TODO: possibly need to check only index - weight might be missing? @@ -314,6 +354,15 @@ public class MeshExporter private Vector4 FixTangentVector(Vector4 tangent) => tangent with { W = tangent.W == 1 ? 1 : -1 }; + private Vector2 ToVector2(object data) + => data switch + { + Vector2 v2 => v2, + Vector3 v3 => new Vector2(v3.X, v3.Y), + Vector4 v4 => new Vector2(v4.X, v4.Y), + _ => throw new ArgumentOutOfRangeException($"Invalid Vector2 input {data}") + }; + private Vector3 ToVector3(object data) => data switch { From dc845b766e654a1cfef2ff1c792091c3999eabea Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 00:57:27 +1100 Subject: [PATCH 0302/1381] Clean up top-level conversion utilities. --- Penumbra/Import/Models/HavokConverter.cs | 60 +++++++++------------ Penumbra/Import/Models/ModelManager.cs | 9 +--- Penumbra/Import/Models/SkeletonConverter.cs | 47 +++++++++------- 3 files changed, 55 insertions(+), 61 deletions(-) diff --git a/Penumbra/Import/Models/HavokConverter.cs b/Penumbra/Import/Models/HavokConverter.cs index 515c6f97..7f87d50a 100644 --- a/Penumbra/Import/Models/HavokConverter.cs +++ b/Penumbra/Import/Models/HavokConverter.cs @@ -2,24 +2,19 @@ using FFXIVClientStructs.Havok; namespace Penumbra.Import.Models; -// TODO: where should this live? interop i guess, in penum? or game data? -public unsafe class HavokConverter +public static unsafe class HavokConverter { - /// Creates a temporary file and returns its path. - /// Path to a temporary file. - private string CreateTempFile() + /// Creates a temporary file and returns its path. + private static string CreateTempFile() { - var s = File.Create(Path.GetTempFileName()); - s.Close(); - return s.Name; + var stream = File.Create(Path.GetTempFileName()); + stream.Close(); + return stream.Name; } - /// Converts a .hkx file to a .xml file. - /// A byte array representing the .hkx file. - /// A string representing the .xml file. - /// Thrown if parsing the .hkx file fails. - /// Thrown if writing the .xml file fails. - public string HkxToXml(byte[] hkx) + /// Converts a .hkx file to a .xml file. + /// A byte array representing the .hkx file. + public static string HkxToXml(byte[] hkx) { var tempHkx = CreateTempFile(); File.WriteAllBytes(tempHkx, hkx); @@ -27,7 +22,7 @@ public unsafe class HavokConverter var resource = Read(tempHkx); File.Delete(tempHkx); - if (resource == null) throw new Exception("HavokReadException"); + if (resource == null) throw new Exception("Failed to read havok file."); var options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers | hkSerializeUtil.SaveOptionBits.TextFormat @@ -42,12 +37,9 @@ public unsafe class HavokConverter return bytes; } - /// Converts a .xml file to a .hkx file. - /// A string representing the .xml file. - /// A byte array representing the .hkx file. - /// Thrown if parsing the .xml file fails. - /// Thrown if writing the .hkx file fails. - public byte[] XmlToHkx(string xml) + /// Converts an .xml file to a .hkx file. + /// A string representing the .xml file. + public static byte[] XmlToHkx(string xml) { var tempXml = CreateTempFile(); File.WriteAllText(tempXml, xml); @@ -55,7 +47,7 @@ public unsafe class HavokConverter var resource = Read(tempXml); File.Delete(tempXml); - if (resource == null) throw new Exception("HavokReadException"); + if (resource == null) throw new Exception("Failed to read havok file."); var options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers | hkSerializeUtil.SaveOptionBits.WriteAttributes; @@ -74,9 +66,8 @@ public unsafe class HavokConverter /// The type is guessed automatically by Havok. /// This pointer might be null - you should check for that. /// - /// Path to a file on the filesystem. - /// A (potentially null) pointer to an hkResource. - private hkResource* Read(string filePath) + /// Path to a file on the filesystem. + private static hkResource* Read(string filePath) { var path = Marshal.StringToHGlobalAnsi(filePath); @@ -87,18 +78,15 @@ public unsafe class HavokConverter loadOptions->ClassNameRegistry = builtinTypeRegistry->GetClassNameRegistry(); loadOptions->TypeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); - // TODO: probably can loadfrombuffer this + // TODO: probably can use LoadFromBuffer for this. var resource = hkSerializeUtil.LoadFromFile((byte*)path, null, loadOptions); return resource; } - /// Serializes an hkResource* to a temporary file. - /// A pointer to the hkResource, opened through Read(). - /// Flags representing how to serialize the file. - /// An opened FileStream of a temporary file. You are expected to read the file and delete it. - /// Thrown if accessing the root level container fails. - /// Thrown if an unknown failure in writing occurs. - private FileStream Write( + /// Serializes an hkResource* to a temporary file. + /// A pointer to the hkResource, opened through Read(). + /// Flags representing how to serialize the file. + private static FileStream Write( hkResource* resource, hkSerializeUtil.SaveOptionBits optionBits ) @@ -125,16 +113,16 @@ public unsafe class HavokConverter var name = "hkRootLevelContainer"; var resourcePtr = (hkRootLevelContainer*)resource->GetContentsPointer(name, typeInfoRegistry); - if (resourcePtr == null) throw new Exception("HavokWriteException"); + if (resourcePtr == null) throw new Exception("Failed to retrieve havok root level container resource."); var hkRootLevelContainerClass = classNameRegistry->GetClassByName(name); - if (hkRootLevelContainerClass == null) throw new Exception("HavokWriteException"); + if (hkRootLevelContainerClass == null) throw new Exception("Failed to retrieve havok root level container type."); hkSerializeUtil.Save(result, resourcePtr, hkRootLevelContainerClass, oStream.StreamWriter.ptr, saveOptions); } finally { oStream.Dtor(); } - if (result->Result == hkResult.hkResultEnum.Failure) throw new Exception("HavokFailureException"); + if (result->Result == hkResult.hkResultEnum.Failure) throw new Exception("Failed to serialize havok file."); return new FileStream(tempFile, FileMode.Open); } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 9f72619f..a56d7168 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -89,17 +89,12 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable if (_sklb == null) return null; - // TODO: Consider making these static methods. // TODO: work out how i handle this havok deal. running it outside the framework causes an immediate ctd. - var havokConverter = new HavokConverter(); - var xmlTask = _manager._framework.RunOnFrameworkThread(() => havokConverter.HkxToXml(_sklb.Skeleton)); + var xmlTask = _manager._framework.RunOnFrameworkThread(() => HavokConverter.HkxToXml(_sklb.Skeleton)); xmlTask.Wait(cancel); var xml = xmlTask.Result; - var skeletonConverter = new SkeletonConverter(); - var skeleton = skeletonConverter.FromXml(xml); - - return skeleton; + return SkeletonConverter.FromXml(xml); } public bool Equals(IAction? other) diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs index e265e5c3..24bcf3e0 100644 --- a/Penumbra/Import/Models/SkeletonConverter.cs +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -4,10 +4,11 @@ using Penumbra.Import.Models.Export; namespace Penumbra.Import.Models; -// TODO: tempted to say that this living here is more okay? that or next to havok converter, wherever that ends up. -public class SkeletonConverter +public static class SkeletonConverter { - public XivSkeleton FromXml(string xml) + /// Parse XIV skeleton data from a havok XML tagfile. + /// Havok XML tagfile containing skeleton data. + public static XivSkeleton FromXml(string xml) { var document = new XmlDocument(); document.LoadXml(xml); @@ -16,14 +17,14 @@ public class SkeletonConverter var skeletonNode = document.SelectSingleNode($"/hktagfile/object[@type='hkaSkeleton'][@id='{mainSkeletonId}']"); if (skeletonNode == null) - throw new InvalidDataException(); + throw new InvalidDataException($"Failed to find skeleton with id {mainSkeletonId}."); var referencePose = ReadReferencePose(skeletonNode); var parentIndices = ReadParentIndices(skeletonNode); var boneNames = ReadBoneNames(skeletonNode); if (boneNames.Length != parentIndices.Length || boneNames.Length != referencePose.Length) - throw new InvalidDataException(); + throw new InvalidDataException($"Mismatch in bone value array lengths: names({boneNames.Length}) parents({parentIndices.Length}) pose({referencePose.Length})"); var bones = referencePose .Zip(parentIndices, boneNames) @@ -38,27 +39,27 @@ public class SkeletonConverter }; }) .ToArray(); - + return new XivSkeleton(bones); } - /// Get the main skeleton ID for a given skeleton document. - /// XML skeleton document. - private string GetMainSkeletonId(XmlNode node) + /// Get the main skeleton ID for a given skeleton document. + /// XML skeleton document. + private static string GetMainSkeletonId(XmlNode node) { var animationSkeletons = node .SelectSingleNode("/hktagfile/object[@type='hkaAnimationContainer']/array[@name='skeletons']")? .ChildNodes; if (animationSkeletons?.Count != 1) - throw new Exception($"Assumption broken: Expected 1 hkaAnimationContainer skeleton, got {animationSkeletons?.Count ?? 0}"); + throw new Exception($"Assumption broken: Expected 1 hkaAnimationContainer skeleton, got {animationSkeletons?.Count ?? 0}."); return animationSkeletons[0]!.InnerText; } - /// Read the reference pose transforms for a skeleton. - /// XML node for the skeleton. - private XivSkeleton.Transform[] ReadReferencePose(XmlNode node) + /// Read the reference pose transforms for a skeleton. + /// XML node for the skeleton. + private static XivSkeleton.Transform[] ReadReferencePose(XmlNode node) { return ReadArray( CheckExists(node.SelectSingleNode("array[@name='referencePose']")), @@ -75,7 +76,9 @@ public class SkeletonConverter ); } - private float[] ReadVec12(XmlNode node) + /// Read a 12-item vector from a tagfile. + /// Havok Vec12 XML node. + private static float[] ReadVec12(XmlNode node) { var array = node.ChildNodes .Cast() @@ -89,12 +92,14 @@ public class SkeletonConverter .ToArray(); if (array.Length != 12) - throw new InvalidDataException(); + throw new InvalidDataException($"Unexpected Vector12 length ({array.Length})."); return array; } - private int[] ReadParentIndices(XmlNode node) + /// Read the bone parent relations for a skeleton. + /// XML node for the skeleton. + private static int[] ReadParentIndices(XmlNode node) { // todo: would be neat to genericise array between bare and children return CheckExists(node.SelectSingleNode("array[@name='parentIndices']")) @@ -104,7 +109,9 @@ public class SkeletonConverter .ToArray(); } - private string[] ReadBoneNames(XmlNode node) + /// Read the names of bones in a skeleton. + /// XML node for the skeleton. + private static string[] ReadBoneNames(XmlNode node) { return ReadArray( CheckExists(node.SelectSingleNode("array[@name='bones']")), @@ -112,7 +119,10 @@ public class SkeletonConverter ); } - private T[] ReadArray(XmlNode node, Func convert) + /// Read an XML tagfile array, converting it via the provided conversion function. + /// Tagfile XML array node. + /// Function to convert array item nodes to required data types. + private static T[] ReadArray(XmlNode node, Func convert) { var element = (XmlElement)node; @@ -125,6 +135,7 @@ public class SkeletonConverter return array; } + /// Check if the argument is null, returning a non-nullable value if it exists, and throwing if not. private static T CheckExists(T? value) { ArgumentNullException.ThrowIfNull(value); From da019e729d80690288ba7ff585ba7d9cd53c8fe6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 31 Dec 2023 15:10:30 +0100 Subject: [PATCH 0303/1381] Move all animation and game event hooks to own classes. --- OtterGui | 2 +- Penumbra/Api/PenumbraApi.cs | 2 +- Penumbra/Communication/ChangedItemClick.cs | 9 +- Penumbra/Communication/ChangedItemHover.cs | 9 +- Penumbra/Communication/CollectionChange.cs | 10 +- .../CollectionInheritanceChanged.cs | 10 +- .../Communication/CreatedCharacterBase.cs | 10 +- .../Communication/CreatingCharacterBase.cs | 10 +- Penumbra/Communication/EnabledChanged.cs | 9 +- Penumbra/Communication/ModDataChanged.cs | 9 +- Penumbra/Communication/ModDirectoryChanged.cs | 9 +- .../Communication/ModDiscoveryFinished.cs | 10 +- Penumbra/Communication/ModDiscoveryStarted.cs | 9 +- Penumbra/Communication/ModOptionChanged.cs | 10 +- Penumbra/Communication/ModPathChanged.cs | 10 +- Penumbra/Communication/ModSettingChanged.cs | 10 +- Penumbra/Communication/MtrlShpkLoaded.cs | 9 +- .../Communication/PostSettingsPanelDraw.cs | 9 +- .../Communication/PreSettingsPanelDraw.cs | 9 +- Penumbra/Communication/ResolvedFileChanged.cs | 14 +- Penumbra/Communication/SelectTab.cs | 9 +- .../Communication/TemporaryGlobalModChange.cs | 10 +- Penumbra/Interop/GameState.cs | 117 +++++ .../Animation/ApricotListenerSoundPlay.cs | 54 +++ .../Animation/CharacterBaseLoadAnimation.cs | 41 ++ Penumbra/Interop/Hooks/Animation/Dismount.cs | 44 ++ .../Interop/Hooks/Animation/LoadAreaVfx.cs | 38 ++ .../Hooks/Animation/LoadCharacterSound.cs | 34 ++ .../Hooks/Animation/LoadCharacterVfx.cs | 65 +++ .../Hooks/Animation/LoadTimelineResources.cs | 71 +++ .../Interop/Hooks/Animation/PlayFootstep.cs | 30 ++ .../Hooks/Animation/ScheduleClipUpdate.cs | 35 ++ .../Interop/Hooks/Animation/SomeActionLoad.cs | 32 ++ .../Hooks/Animation/SomeMountAnimation.cs | 31 ++ .../Interop/Hooks/Animation/SomePapLoad.cs | 46 ++ .../Hooks/Animation/SomeParasolAnimation.cs | 31 ++ .../Interop/Hooks/CharacterBaseDestructor.cs | 49 ++ Penumbra/Interop/Hooks/CharacterDestructor.cs | 49 ++ Penumbra/Interop/Hooks/CopyCharacter.cs | 47 ++ Penumbra/Interop/Hooks/CreateCharacterBase.cs | 74 +++ Penumbra/Interop/Hooks/DebugHook.cs | 43 ++ Penumbra/Interop/Hooks/EnableDraw.cs | 48 ++ .../Interop/Hooks/ResourceHandleDestructor.cs | 50 +++ Penumbra/Interop/Hooks/WeaponReload.cs | 71 +++ .../PathResolving/AnimationHookService.cs | 423 ------------------ .../PathResolving/CollectionResolver.cs | 127 +++--- .../Interop/PathResolving/CutsceneService.cs | 27 +- .../Interop/PathResolving/DrawObjectState.cs | 90 ++-- .../IdentifiedCollectionCache.cs | 18 +- Penumbra/Interop/PathResolving/MetaState.cs | 40 +- .../Interop/PathResolving/PathResolver.cs | 38 +- .../Interop/PathResolving/SubfileHelper.cs | 23 +- Penumbra/Interop/Services/GameEventManager.cs | 299 ------------- Penumbra/Interop/Services/SkinFixer.cs | 22 +- Penumbra/Mods/Manager/ModDataEditor.cs | 1 - Penumbra/Penumbra.cs | 4 + Penumbra/Penumbra.csproj | 5 +- Penumbra/Services/CommunicatorService.cs | 2 +- Penumbra/Services/ServiceManagerA.cs | 6 +- .../ModEditWindow.Materials.MtrlTab.cs | 16 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 72 +-- Penumbra/packages.lock.json | 34 +- 62 files changed, 1402 insertions(+), 1143 deletions(-) create mode 100644 Penumbra/Interop/GameState.cs create mode 100644 Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs create mode 100644 Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs create mode 100644 Penumbra/Interop/Hooks/Animation/Dismount.cs create mode 100644 Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs create mode 100644 Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs create mode 100644 Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs create mode 100644 Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs create mode 100644 Penumbra/Interop/Hooks/Animation/PlayFootstep.cs create mode 100644 Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs create mode 100644 Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs create mode 100644 Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs create mode 100644 Penumbra/Interop/Hooks/Animation/SomePapLoad.cs create mode 100644 Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs create mode 100644 Penumbra/Interop/Hooks/CharacterBaseDestructor.cs create mode 100644 Penumbra/Interop/Hooks/CharacterDestructor.cs create mode 100644 Penumbra/Interop/Hooks/CopyCharacter.cs create mode 100644 Penumbra/Interop/Hooks/CreateCharacterBase.cs create mode 100644 Penumbra/Interop/Hooks/DebugHook.cs create mode 100644 Penumbra/Interop/Hooks/EnableDraw.cs create mode 100644 Penumbra/Interop/Hooks/ResourceHandleDestructor.cs create mode 100644 Penumbra/Interop/Hooks/WeaponReload.cs delete mode 100644 Penumbra/Interop/PathResolving/AnimationHookService.cs delete mode 100644 Penumbra/Interop/Services/GameEventManager.cs diff --git a/OtterGui b/OtterGui index f6a8ad0f..22ae2a89 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit f6a8ad0f8e585408e0aa17c90209358403b52535 +Subproject commit 22ae2a8993ebf3af2313072968a44905a3fcdd2a diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index b7a46ae2..2a7a9bfb 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -259,7 +259,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi } else if (tab != TabType.None) { - _communicator.SelectTab.Invoke(tab); + _communicator.SelectTab.Invoke(tab, null); } return PenumbraApiEc.Success; diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index ea389bb6..b11f2306 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -11,7 +11,7 @@ namespace Penumbra.Communication; /// Parameter is the clicked object data if any. /// /// -public sealed class ChangedItemClick : EventWrapper, ChangedItemClick.Priority> +public sealed class ChangedItemClick() : EventWrapper(nameof(ChangedItemClick)) { public enum Priority { @@ -21,11 +21,4 @@ public sealed class ChangedItemClick : EventWrapper /// Link = 1, } - - public ChangedItemClick() - : base(nameof(ChangedItemClick)) - { } - - public void Invoke(MouseButton button, object? data) - => Invoke(this, button, data); } diff --git a/Penumbra/Communication/ChangedItemHover.cs b/Penumbra/Communication/ChangedItemHover.cs index cf270ba0..10607da4 100644 --- a/Penumbra/Communication/ChangedItemHover.cs +++ b/Penumbra/Communication/ChangedItemHover.cs @@ -8,7 +8,7 @@ namespace Penumbra.Communication; /// Parameter is the hovered object data if any. /// /// -public sealed class ChangedItemHover : EventWrapper, ChangedItemHover.Priority> +public sealed class ChangedItemHover() : EventWrapper(nameof(ChangedItemHover)) { public enum Priority { @@ -19,13 +19,6 @@ public sealed class ChangedItemHover : EventWrapper, ChangedItem Link = 1, } - public ChangedItemHover() - : base(nameof(ChangedItemHover)) - { } - - public void Invoke(object? data) - => Invoke(this, data); - public bool HasTooltip => HasSubscribers; } diff --git a/Penumbra/Communication/CollectionChange.cs b/Penumbra/Communication/CollectionChange.cs index b713cc72..95d4ac4d 100644 --- a/Penumbra/Communication/CollectionChange.cs +++ b/Penumbra/Communication/CollectionChange.cs @@ -12,7 +12,8 @@ namespace Penumbra.Communication; /// Parameter is the new collection, or null on deletions. /// Parameter is the display name for Individual collections or an empty string otherwise. /// -public sealed class CollectionChange : EventWrapper, CollectionChange.Priority> +public sealed class CollectionChange() + : EventWrapper(nameof(CollectionChange)) { public enum Priority { @@ -46,11 +47,4 @@ public sealed class CollectionChange : EventWrapper ModFileSystemSelector = 0, } - - public CollectionChange() - : base(nameof(CollectionChange)) - { } - - public void Invoke(CollectionType collectionType, ModCollection? oldCollection, ModCollection? newCollection, string displayName) - => Invoke(this, collectionType, oldCollection, newCollection, displayName); } diff --git a/Penumbra/Communication/CollectionInheritanceChanged.cs b/Penumbra/Communication/CollectionInheritanceChanged.cs index 8288341d..dbcf9e4a 100644 --- a/Penumbra/Communication/CollectionInheritanceChanged.cs +++ b/Penumbra/Communication/CollectionInheritanceChanged.cs @@ -10,7 +10,8 @@ namespace Penumbra.Communication; /// Parameter is whether the change was itself inherited, i.e. if it happened in a direct parent (false) or a more removed ancestor (true). /// /// -public sealed class CollectionInheritanceChanged : EventWrapper, CollectionInheritanceChanged.Priority> +public sealed class CollectionInheritanceChanged() + : EventWrapper(nameof(CollectionInheritanceChanged)) { public enum Priority { @@ -23,11 +24,4 @@ public sealed class CollectionInheritanceChanged : EventWrapper ModFileSystemSelector = 0, } - - public CollectionInheritanceChanged() - : base(nameof(CollectionInheritanceChanged)) - { } - - public void Invoke(ModCollection collection, bool inherited) - => Invoke(this, collection, inherited); } diff --git a/Penumbra/Communication/CreatedCharacterBase.cs b/Penumbra/Communication/CreatedCharacterBase.cs index b1903e5b..397f7bfd 100644 --- a/Penumbra/Communication/CreatedCharacterBase.cs +++ b/Penumbra/Communication/CreatedCharacterBase.cs @@ -9,18 +9,12 @@ namespace Penumbra.Communication; /// Parameter is the applied collection. /// Parameter is the created draw object. /// -public sealed class CreatedCharacterBase : EventWrapper, CreatedCharacterBase.Priority> +public sealed class CreatedCharacterBase() + : EventWrapper(nameof(CreatedCharacterBase)) { public enum Priority { /// Api = int.MinValue, } - - public CreatedCharacterBase() - : base(nameof(CreatedCharacterBase)) - { } - - public void Invoke(nint gameObject, ModCollection appliedCollection, nint drawObject) - => Invoke(this, gameObject, appliedCollection, drawObject); } diff --git a/Penumbra/Communication/CreatingCharacterBase.cs b/Penumbra/Communication/CreatingCharacterBase.cs index 090ca40b..1e232761 100644 --- a/Penumbra/Communication/CreatingCharacterBase.cs +++ b/Penumbra/Communication/CreatingCharacterBase.cs @@ -12,18 +12,12 @@ namespace Penumbra.Communication; /// Parameter is a pointer to the customize array. /// Parameter is a pointer to the equip data array. /// -public sealed class CreatingCharacterBase : EventWrapper, CreatingCharacterBase.Priority> +public sealed class CreatingCharacterBase() + : EventWrapper(nameof(CreatingCharacterBase)) { public enum Priority { /// Api = 0, } - - public CreatingCharacterBase() - : base(nameof(CreatingCharacterBase)) - { } - - public void Invoke(nint gameObject, string appliedCollectionName, nint modelIdAddress, nint customizeArrayAddress, nint equipDataAddress) - => Invoke(this, gameObject, appliedCollectionName, modelIdAddress, customizeArrayAddress, equipDataAddress); } diff --git a/Penumbra/Communication/EnabledChanged.cs b/Penumbra/Communication/EnabledChanged.cs index fa768235..be6343b7 100644 --- a/Penumbra/Communication/EnabledChanged.cs +++ b/Penumbra/Communication/EnabledChanged.cs @@ -9,7 +9,7 @@ namespace Penumbra.Communication; /// Parameter is whether Penumbra is now Enabled (true) or Disabled (false). /// /// -public sealed class EnabledChanged : EventWrapper, EnabledChanged.Priority> +public sealed class EnabledChanged() : EventWrapper(nameof(EnabledChanged)) { public enum Priority { @@ -19,11 +19,4 @@ public sealed class EnabledChanged : EventWrapper, EnabledChanged.P /// DalamudSubstitutionProvider = 0, } - - public EnabledChanged() - : base(nameof(EnabledChanged)) - { } - - public void Invoke(bool enabled) - => Invoke(this, enabled); } diff --git a/Penumbra/Communication/ModDataChanged.cs b/Penumbra/Communication/ModDataChanged.cs index 2f50f005..ffa43d43 100644 --- a/Penumbra/Communication/ModDataChanged.cs +++ b/Penumbra/Communication/ModDataChanged.cs @@ -11,7 +11,7 @@ namespace Penumbra.Communication; /// Parameter is the changed mod. /// Parameter is the old name of the mod in case of a name change, and null otherwise. /// -public sealed class ModDataChanged : EventWrapper, ModDataChanged.Priority> +public sealed class ModDataChanged() : EventWrapper(nameof(ModDataChanged)) { public enum Priority { @@ -27,11 +27,4 @@ public sealed class ModDataChanged : EventWrapper ModPanelHeader = 0, } - - public ModDataChanged() - : base(nameof(ModDataChanged)) - { } - - public void Invoke(ModDataChangeType changeType, Mod mod, string? oldName) - => Invoke(this, changeType, mod, oldName); } diff --git a/Penumbra/Communication/ModDirectoryChanged.cs b/Penumbra/Communication/ModDirectoryChanged.cs index 9fdb261e..20d13b20 100644 --- a/Penumbra/Communication/ModDirectoryChanged.cs +++ b/Penumbra/Communication/ModDirectoryChanged.cs @@ -10,7 +10,7 @@ namespace Penumbra.Communication; /// Parameter is whether the new directory is valid. /// /// -public sealed class ModDirectoryChanged : EventWrapper, ModDirectoryChanged.Priority> +public sealed class ModDirectoryChanged() : EventWrapper(nameof(ModDirectoryChanged)) { public enum Priority { @@ -20,11 +20,4 @@ public sealed class ModDirectoryChanged : EventWrapper, Mod /// FileDialogService = 0, } - - public ModDirectoryChanged() - : base(nameof(ModDirectoryChanged)) - { } - - public void Invoke(string newModDirectory, bool newDirectoryValid) - => Invoke(this, newModDirectory, newDirectoryValid); } diff --git a/Penumbra/Communication/ModDiscoveryFinished.cs b/Penumbra/Communication/ModDiscoveryFinished.cs index 04c13e95..759ea42e 100644 --- a/Penumbra/Communication/ModDiscoveryFinished.cs +++ b/Penumbra/Communication/ModDiscoveryFinished.cs @@ -1,10 +1,9 @@ using OtterGui.Classes; -using Penumbra.Mods.Manager; namespace Penumbra.Communication; /// Triggered whenever a new mod discovery has finished. -public sealed class ModDiscoveryFinished : EventWrapper +public sealed class ModDiscoveryFinished() : EventWrapper(nameof(ModDiscoveryFinished)) { public enum Priority { @@ -23,11 +22,4 @@ public sealed class ModDiscoveryFinished : EventWrapper ModFileSystem = 0, } - - public ModDiscoveryFinished() - : base(nameof(ModDiscoveryFinished)) - { } - - public void Invoke() - => Invoke(this); } diff --git a/Penumbra/Communication/ModDiscoveryStarted.cs b/Penumbra/Communication/ModDiscoveryStarted.cs index cf45528d..5cafd1ea 100644 --- a/Penumbra/Communication/ModDiscoveryStarted.cs +++ b/Penumbra/Communication/ModDiscoveryStarted.cs @@ -3,7 +3,7 @@ using OtterGui.Classes; namespace Penumbra.Communication; /// Triggered whenever mods are prepared to be rediscovered. -public sealed class ModDiscoveryStarted : EventWrapper +public sealed class ModDiscoveryStarted() : EventWrapper(nameof(ModDiscoveryStarted)) { public enum Priority { @@ -16,11 +16,4 @@ public sealed class ModDiscoveryStarted : EventWrapper ModFileSystemSelector = 200, } - - public ModDiscoveryStarted() - : base(nameof(ModDiscoveryStarted)) - { } - - public void Invoke() - => Invoke(this); } diff --git a/Penumbra/Communication/ModOptionChanged.cs b/Penumbra/Communication/ModOptionChanged.cs index 416cc8df..a0b4d26c 100644 --- a/Penumbra/Communication/ModOptionChanged.cs +++ b/Penumbra/Communication/ModOptionChanged.cs @@ -13,7 +13,8 @@ namespace Penumbra.Communication; /// Parameter is the index of the changed option inside the group or -1 if it does not concern a specific option. /// Parameter is the index of the group an option was moved to. /// -public sealed class ModOptionChanged : EventWrapper, ModOptionChanged.Priority> +public sealed class ModOptionChanged() + : EventWrapper(nameof(ModOptionChanged)) { public enum Priority { @@ -29,11 +30,4 @@ public sealed class ModOptionChanged : EventWrapper CollectionStorage = 100, } - - public ModOptionChanged() - : base(nameof(ModOptionChanged)) - { } - - public void Invoke(ModOptionChangeType changeType, Mod mod, int groupIndex, int optionIndex, int moveToIndex) - => Invoke(this, changeType, mod, groupIndex, optionIndex, moveToIndex); } diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index 83c3b5a5..3ec64f7e 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -14,7 +14,8 @@ namespace Penumbra.Communication; /// Parameter is the new directory on addition, move or reload and null on deletion. /// /// -public sealed class ModPathChanged : EventWrapper, ModPathChanged.Priority> +public sealed class ModPathChanged() + : EventWrapper(nameof(ModPathChanged)) { public enum Priority { @@ -48,11 +49,4 @@ public sealed class ModPathChanged : EventWrapper CollectionCacheManagerRemoval = 100, } - - public ModPathChanged() - : base(nameof(ModPathChanged)) - { } - - public void Invoke(ModPathChangeType changeType, Mod mod, DirectoryInfo? oldModDirectory, DirectoryInfo? newModDirectory) - => Invoke(this, changeType, mod, oldModDirectory, newModDirectory); } diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index 65bcf3ed..5e0bc0c0 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -17,7 +17,8 @@ namespace Penumbra.Communication; /// Parameter is whether the change was inherited from another collection. /// /// -public sealed class ModSettingChanged : EventWrapper, ModSettingChanged.Priority> +public sealed class ModSettingChanged() + : EventWrapper(nameof(ModSettingChanged)) { public enum Priority { @@ -33,11 +34,4 @@ public sealed class ModSettingChanged : EventWrapper ModFileSystemSelector = 0, } - - public ModSettingChanged() - : base(nameof(ModSettingChanged)) - { } - - public void Invoke(ModCollection collection, ModSettingChange type, Mod? mod, int oldValue, int groupIdx, bool inherited) - => Invoke(this, collection, type, mod, oldValue, groupIdx, inherited); } diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlShpkLoaded.cs index 868692cd..bd560fd8 100644 --- a/Penumbra/Communication/MtrlShpkLoaded.cs +++ b/Penumbra/Communication/MtrlShpkLoaded.cs @@ -6,18 +6,11 @@ namespace Penumbra.Communication; /// Parameter is the material resource handle for which the shader package has been loaded. /// Parameter is the associated game object. /// -public sealed class MtrlShpkLoaded : EventWrapper, MtrlShpkLoaded.Priority> +public sealed class MtrlShpkLoaded() : EventWrapper(nameof(MtrlShpkLoaded)) { public enum Priority { /// SkinFixer = 0, } - - public MtrlShpkLoaded() - : base(nameof(MtrlShpkLoaded)) - { } - - public void Invoke(nint mtrlResourceHandle, nint gameObject) - => Invoke(this, mtrlResourceHandle, gameObject); } diff --git a/Penumbra/Communication/PostSettingsPanelDraw.cs b/Penumbra/Communication/PostSettingsPanelDraw.cs index b32b0dfa..a918b610 100644 --- a/Penumbra/Communication/PostSettingsPanelDraw.cs +++ b/Penumbra/Communication/PostSettingsPanelDraw.cs @@ -8,18 +8,11 @@ namespace Penumbra.Communication; /// Parameter is the identifier (directory name) of the currently selected mod. /// /// -public sealed class PostSettingsPanelDraw : EventWrapper, PostSettingsPanelDraw.Priority> +public sealed class PostSettingsPanelDraw() : EventWrapper(nameof(PostSettingsPanelDraw)) { public enum Priority { /// Default = 0, } - - public PostSettingsPanelDraw() - : base(nameof(PostSettingsPanelDraw)) - { } - - public void Invoke(string modDirectory) - => Invoke(this, modDirectory); } diff --git a/Penumbra/Communication/PreSettingsPanelDraw.cs b/Penumbra/Communication/PreSettingsPanelDraw.cs index e5857474..cda00d78 100644 --- a/Penumbra/Communication/PreSettingsPanelDraw.cs +++ b/Penumbra/Communication/PreSettingsPanelDraw.cs @@ -8,18 +8,11 @@ namespace Penumbra.Communication; /// Parameter is the identifier (directory name) of the currently selected mod. /// /// -public sealed class PreSettingsPanelDraw : EventWrapper, PreSettingsPanelDraw.Priority> +public sealed class PreSettingsPanelDraw() : EventWrapper(nameof(PreSettingsPanelDraw)) { public enum Priority { /// Default = 0, } - - public PreSettingsPanelDraw() - : base(nameof(PreSettingsPanelDraw)) - { } - - public void Invoke(string modDirectory) - => Invoke(this, modDirectory); } diff --git a/Penumbra/Communication/ResolvedFileChanged.cs b/Penumbra/Communication/ResolvedFileChanged.cs index 55e95320..3211a26a 100644 --- a/Penumbra/Communication/ResolvedFileChanged.cs +++ b/Penumbra/Communication/ResolvedFileChanged.cs @@ -15,8 +15,9 @@ namespace Penumbra.Communication; /// Parameter is the old redirection path for Replaced, or empty. /// Parameter is the mod responsible for the new redirection if any. /// -public sealed class ResolvedFileChanged : EventWrapper, - ResolvedFileChanged.Priority> +public sealed class ResolvedFileChanged() + : EventWrapper( + nameof(ResolvedFileChanged)) { public enum Type { @@ -29,14 +30,7 @@ public sealed class ResolvedFileChanged : EventWrapper + /// DalamudSubstitutionProvider = 0, } - - public ResolvedFileChanged() - : base(nameof(ResolvedFileChanged)) - { } - - public void Invoke(ModCollection collection, Type type, Utf8GamePath key, FullPath value, FullPath old, IMod? mod) - => Invoke(this, collection, type, key, value, old, mod); } diff --git a/Penumbra/Communication/SelectTab.cs b/Penumbra/Communication/SelectTab.cs index aaa362f6..cb7e2e56 100644 --- a/Penumbra/Communication/SelectTab.cs +++ b/Penumbra/Communication/SelectTab.cs @@ -11,18 +11,11 @@ namespace Penumbra.Communication; /// Parameter is the selected mod, if any. /// /// -public sealed class SelectTab : EventWrapper, SelectTab.Priority> +public sealed class SelectTab() : EventWrapper(nameof(SelectTab)) { public enum Priority { /// ConfigTabBar = 0, } - - public SelectTab() - : base(nameof(SelectTab)) - { } - - public void Invoke(TabType tab = TabType.None, Mod? mod = null) - => Invoke(this, tab, mod); } diff --git a/Penumbra/Communication/TemporaryGlobalModChange.cs b/Penumbra/Communication/TemporaryGlobalModChange.cs index 12d42e48..6edf26d7 100644 --- a/Penumbra/Communication/TemporaryGlobalModChange.cs +++ b/Penumbra/Communication/TemporaryGlobalModChange.cs @@ -10,7 +10,8 @@ namespace Penumbra.Communication; /// Parameter is whether the mod was newly created. /// Parameter is whether the mod was deleted. /// -public sealed class TemporaryGlobalModChange : EventWrapper, TemporaryGlobalModChange.Priority> +public sealed class TemporaryGlobalModChange() + : EventWrapper(nameof(TemporaryGlobalModChange)) { public enum Priority { @@ -20,11 +21,4 @@ public sealed class TemporaryGlobalModChange : EventWrapper TempCollectionManager = 0, } - - public TemporaryGlobalModChange() - : base(nameof(TemporaryGlobalModChange)) - { } - - public void Invoke(TemporaryMod temporaryMod, bool newlyCreated, bool deleted) - => Invoke(this, temporaryMod, newlyCreated, deleted); } diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs new file mode 100644 index 00000000..2552f1a7 --- /dev/null +++ b/Penumbra/Interop/GameState.cs @@ -0,0 +1,117 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Interop.PathResolving; +using Penumbra.String.Classes; + +namespace Penumbra.Interop; + +public class GameState : IService +{ + #region Last Game Object + + private readonly ThreadLocal> _lastGameObject = new(() => new Queue()); + + public nint LastGameObject + => _lastGameObject.IsValueCreated && _lastGameObject.Value!.Count > 0 ? _lastGameObject.Value.Peek() : nint.Zero; + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public unsafe void QueueGameObject(GameObject* gameObject) + => QueueGameObject((nint)gameObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void QueueGameObject(nint gameObject) + => _lastGameObject.Value!.Enqueue(gameObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void DequeueGameObject() + => _lastGameObject.Value!.TryDequeue(out _); + + #endregion + + #region Animation Data + + private readonly ThreadLocal _animationLoadData = new(() => ResolveData.Invalid, true); + + public ResolveData AnimationData + => _animationLoadData.Value; + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public ResolveData SetAnimationData(ResolveData data) + { + var old = _animationLoadData.Value; + _animationLoadData.Value = data; + return old; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void RestoreAnimationData(ResolveData old) + => _animationLoadData.Value = old; + + #endregion + + #region Sound Data + + private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); + + public ResolveData SoundData + => _animationLoadData.Value; + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public ResolveData SetSoundData(ResolveData data) + { + var old = _characterSoundData.Value; + _characterSoundData.Value = data; + return old; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void RestoreSoundData(ResolveData old) + => _characterSoundData.Value = old; + + #endregion + + /// Return the correct resolve data from the stored data. + public unsafe bool HandleFiles(CollectionResolver resolver, ResourceType type, Utf8GamePath _, out ResolveData resolveData) + { + switch (type) + { + case ResourceType.Scd: + if (_characterSoundData is { IsValueCreated: true, Value.Valid: true }) + { + resolveData = _characterSoundData.Value; + return true; + } + + if (_animationLoadData is { IsValueCreated: true, Value.Valid: true }) + { + resolveData = _animationLoadData.Value; + return true; + } + + break; + case ResourceType.Tmb: + case ResourceType.Pap: + case ResourceType.Avfx: + case ResourceType.Atex: + if (_animationLoadData is { IsValueCreated: true, Value.Valid: true }) + { + resolveData = _animationLoadData.Value; + return true; + } + + break; + } + + var lastObj = LastGameObject; + if (lastObj != nint.Zero) + { + resolveData = resolver.IdentifyCollection((GameObject*)lastObj, true); + return true; + } + + resolveData = ResolveData.Invalid; + return false; + } +} diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs new file mode 100644 index 00000000..b91c5375 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -0,0 +1,54 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Called for some sound effects caused by animations or VFX. +public sealed unsafe class ApricotListenerSoundPlay : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public ApricotListenerSoundPlay(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Apricot Listener Sound Play", Sigs.ApricotListenerSoundPlay, Detour, true); + } + + public delegate nint Delegate(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private nint Detour(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6) + { + Penumbra.Log.Excessive($"[Apricot Listener Sound Play] Invoked on 0x{a1:X} with {a2}, {a3}, {a4}, {a5}, {a6}."); + if (a6 == nint.Zero) + return Task.Result.Original(a1, a2, a3, a4, a5, a6); + + // a6 is some instance of Apricot.IInstanceListenner, in some cases we can obtain the associated caster via vfunc 1. + var gameObject = (*(delegate* unmanaged**)a6)[1](a6); + var newData = ResolveData.Invalid; + if (gameObject != null) + { + newData = _collectionResolver.IdentifyCollection(gameObject, true); + } + else + { + // for VfxListenner we can obtain the associated draw object as its first member, + // if the object has different type, drawObject will contain other values or garbage, + // but only be used in a dictionary pointer lookup, so this does not hurt. + var drawObject = ((DrawObject**)a6)[1]; + if (drawObject != null) + newData = _collectionResolver.IdentifyCollection(drawObject, true); + } + + var last = _state.SetAnimationData(newData); + var ret = Task.Result.Original(a1, a2, a3, a4, a5, a6); + _state.RestoreAnimationData(last); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs b/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs new file mode 100644 index 00000000..959165a6 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs @@ -0,0 +1,41 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// +/// Probably used when the base idle animation gets loaded. +/// Make it aware of the correct collection to load the correct pap files. +/// +public sealed unsafe class CharacterBaseLoadAnimation : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly DrawObjectState _drawObjectState; + + public CharacterBaseLoadAnimation(HookManager hooks, GameState state, CollectionResolver collectionResolver, + DrawObjectState drawObjectState) + { + _state = state; + _collectionResolver = collectionResolver; + _drawObjectState = drawObjectState; + Task = hooks.CreateHook("CharacterBase Load Animation", Sigs.CharacterBaseLoadAnimation, Detour, true); + } + + public delegate void Delegate(DrawObject* drawBase); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject) + { + var lastObj = _state.LastGameObject; + if (lastObj == nint.Zero && _drawObjectState.TryGetValue((nint)drawObject, out var p)) + lastObj = p.Item1; + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection((GameObject*)lastObj, true)); + Penumbra.Log.Excessive($"[CharacterBase Load Animation] Invoked on {(nint)drawObject:X}"); + Task.Result.Original(drawObject); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/Dismount.cs b/Penumbra/Interop/Hooks/Animation/Dismount.cs new file mode 100644 index 00000000..8085bcdb --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/Dismount.cs @@ -0,0 +1,44 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Called for some animations when dismounting. +public sealed unsafe class Dismount : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public Dismount(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Dismount", Sigs.Dismount, Detour, true); + } + + public delegate void Delegate(nint a1, nint a2); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(nint a1, nint a2) + { + Penumbra.Log.Excessive($"[Dismount] Invoked on {a1:X} with {a2:X}."); + if (a1 == nint.Zero) + { + Task.Result.Original(a1, a2); + return; + } + + var gameObject = *(GameObject**)(a1 + 8); + if (gameObject == null) + { + Task.Result.Original(a1, a2); + return; + } + + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection(gameObject, true)); + Task.Result.Original(a1, a2); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs new file mode 100644 index 00000000..7be420be --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs @@ -0,0 +1,38 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Load a ground-based area VFX. +public sealed unsafe class LoadAreaVfx : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public LoadAreaVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Load Area VFX", Sigs.LoadAreaVfx, Detour, true); + } + + public delegate nint Delegate(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private nint Detour(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3) + { + var newData = caster != null + ? _collectionResolver.IdentifyCollection(caster, true) + : ResolveData.Invalid; + + var last = _state.SetAnimationData(newData); + var ret = Task.Result.Original(vfxId, pos, caster, unk1, unk2, unk3); + Penumbra.Log.Excessive( + $"[Load Area VFX] Invoked with {vfxId}, [{pos[0]} {pos[1]} {pos[2]}], 0x{(nint)caster:X}, {unk1}, {unk2}, {unk3} -> 0x{ret:X}."); + _state.RestoreAnimationData(last); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs new file mode 100644 index 00000000..af13805d --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs @@ -0,0 +1,34 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Characters load some of their voice lines or whatever with this function. +public sealed unsafe class LoadCharacterSound : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public LoadCharacterSound(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Load Character Sound", + (nint)FFXIVClientStructs.FFXIV.Client.Game.Character.Character.VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, + true); + } + + public delegate nint Delegate(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private nint Detour(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7) + { + var character = *(GameObject**)(container + 8); + var last = _state.SetSoundData(_collectionResolver.IdentifyCollection(character, true)); + var ret = Task.Result.Original(container, unk1, unk2, unk3, unk4, unk5, unk6, unk7); + Penumbra.Log.Excessive($"[Load Character Sound] Invoked with {container:X} {unk1} {unk2} {unk3} {unk4} {unk5} {unk6} {unk7} -> {ret}."); + _state.RestoreSoundData(last); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs new file mode 100644 index 00000000..240c062e --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs @@ -0,0 +1,65 @@ +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Structs; +using Penumbra.String; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Load a VFX specifically for a character. +public sealed unsafe class LoadCharacterVfx : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly IObjectTable _objects; + + public LoadCharacterVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects) + { + _state = state; + _collectionResolver = collectionResolver; + _objects = objects; + Task = hooks.CreateHook("Load Character VFX", Sigs.LoadCharacterVfx, Detour, true); + } + + public delegate nint Delegate(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private nint Detour(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4) + { + var newData = ResolveData.Invalid; + if (vfxParams != null && vfxParams->GameObjectId != unchecked((uint)-1)) + { + var obj = vfxParams->GameObjectType switch + { + 0 => _objects.SearchById(vfxParams->GameObjectId), + 2 => _objects[(int)vfxParams->GameObjectId], + 4 => GetOwnedObject(vfxParams->GameObjectId), + _ => null, + }; + newData = obj != null + ? _collectionResolver.IdentifyCollection((GameObject*)obj.Address, true) + : ResolveData.Invalid; + } + + var last = _state.SetAnimationData(newData); + var ret = Task.Result.Original(vfxPath, vfxParams, unk1, unk2, unk3, unk4); + Penumbra.Log.Excessive( + $"[Load Character VFX] Invoked with {new ByteString(vfxPath)}, 0x{vfxParams->GameObjectId:X}, {vfxParams->TargetCount}, {unk1}, {unk2}, {unk3}, {unk4} -> 0x{ret:X}."); + _state.RestoreAnimationData(last); + return ret; + } + + /// Search an object by its id, then get its minion/mount/ornament. + private Dalamud.Game.ClientState.Objects.Types.GameObject? GetOwnedObject(uint id) + { + var owner = _objects.SearchById(id); + if (owner == null) + return null; + + var idx = ((GameObject*)owner.Address)->ObjectIndex; + return _objects[idx + 1]; + } +} diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs new file mode 100644 index 00000000..2ca8ffe7 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -0,0 +1,71 @@ +using Dalamud.Game.ClientState.Conditions; +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// +/// The timeline object loads the requested .tmb and .pap files. The .tmb files load the respective .avfx files. +/// We can obtain the associated game object from the timelines 28'th vfunc and use that to apply the correct collection. +/// +public sealed unsafe class LoadTimelineResources : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly ICondition _conditions; + private readonly IObjectTable _objects; + + public LoadTimelineResources(HookManager hooks, GameState state, CollectionResolver collectionResolver, ICondition conditions, + IObjectTable objects) + { + _state = state; + _collectionResolver = collectionResolver; + _conditions = conditions; + _objects = objects; + Task = hooks.CreateHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, true); + } + + public delegate ulong Delegate(nint timeline); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private ulong Detour(nint timeline) + { + Penumbra.Log.Excessive($"[Load Timeline Resources] Invoked on {timeline:X}."); + // Do not check timeline loading in cutscenes. + if (_conditions[ConditionFlag.OccupiedInCutSceneEvent] || _conditions[ConditionFlag.WatchingCutscene78]) + return Task.Result.Original(timeline); + + var last = _state.SetAnimationData(GetDataFromTimeline(_objects, _collectionResolver, timeline)); + var ret = Task.Result.Original(timeline); + _state.RestoreAnimationData(last); + return ret; + } + + /// Use timelines vfuncs to obtain the associated game object. + public static ResolveData GetDataFromTimeline(IObjectTable objects, CollectionResolver resolver, nint timeline) + { + try + { + if (timeline != nint.Zero) + { + var getGameObjectIdx = ((delegate* unmanaged**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; + var idx = getGameObjectIdx(timeline); + if (idx >= 0 && idx < objects.Length) + { + var obj = (GameObject*)objects.GetObjectAddress(idx); + return obj != null ? resolver.IdentifyCollection(obj, true) : ResolveData.Invalid; + } + } + } + catch (Exception e) + { + Penumbra.Log.Error($"Error getting timeline data for 0x{timeline:X}:\n{e}"); + } + + return ResolveData.Invalid; + } +} diff --git a/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs b/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs new file mode 100644 index 00000000..491d7662 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs @@ -0,0 +1,30 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +public sealed unsafe class PlayFootstep : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public PlayFootstep(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Play Footstep", Sigs.FootStepSound, Detour, true); + } + + public delegate void Delegate(GameObject* gameObject, int id, int unk); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(GameObject* gameObject, int id, int unk) + { + Penumbra.Log.Excessive($"[Play Footstep] Invoked on 0x{(nint)gameObject:X} with {id}, {unk}."); + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection(gameObject, true)); + Task.Result.Original(gameObject, id, unk); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs new file mode 100644 index 00000000..8428f8ff --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs @@ -0,0 +1,35 @@ +using Dalamud.Plugin.Services; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Structs; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Called when some action timelines update. +public sealed unsafe class ScheduleClipUpdate : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly IObjectTable _objects; + + public ScheduleClipUpdate(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects) + { + _state = state; + _collectionResolver = collectionResolver; + _objects = objects; + Task = hooks.CreateHook("Schedule Clip Update", Sigs.ScheduleClipUpdate, Detour, true); + } + + public delegate void Delegate(ClipScheduler* x); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(ClipScheduler* clipScheduler) + { + Penumbra.Log.Excessive($"[Schedule Clip Update] Invoked on {(nint)clipScheduler:X}."); + var last = _state.SetAnimationData( + LoadTimelineResources.GetDataFromTimeline(_objects, _collectionResolver, clipScheduler->SchedulerTimeline)); + Task.Result.Original(clipScheduler); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs new file mode 100644 index 00000000..48931d73 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs @@ -0,0 +1,32 @@ +using FFXIVClientStructs.FFXIV.Client.Game; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Seems to load character actions when zoning or changing class, maybe. +public sealed unsafe class SomeActionLoad : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public SomeActionLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Some Action Load", Sigs.LoadSomeAction, Detour, true); + } + + public delegate void Delegate(ActionTimelineManager* timelineManager); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(ActionTimelineManager* timelineManager) + { + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection((GameObject*)timelineManager->Parent, true)); + Penumbra.Log.Excessive($"[Some Action Load] Invoked on 0x{(nint)timelineManager:X}."); + Task.Result.Original(timelineManager); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs b/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs new file mode 100644 index 00000000..5dd8227d --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs @@ -0,0 +1,31 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Called for some animations when mounted or mounting. +public sealed unsafe class SomeMountAnimation : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public SomeMountAnimation(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Some Mount Animation", Sigs.UnkMountAnimation, Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject, uint unk1, byte unk2, uint unk3); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject, uint unk1, byte unk2, uint unk3) + { + Penumbra.Log.Excessive($"[Some Mount Animation] Invoked on {(nint)drawObject:X} with {unk1}, {unk2}, {unk3}."); + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection(drawObject, true)); + Task.Result.Original(drawObject, unk1, unk2, unk3); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs new file mode 100644 index 00000000..75caacee --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs @@ -0,0 +1,46 @@ +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Unknown what exactly this is, but it seems to load a bunch of paps. +public sealed unsafe class SomePapLoad : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly IObjectTable _objects; + + public SomePapLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects) + { + _state = state; + _collectionResolver = collectionResolver; + _objects = objects; + Task = hooks.CreateHook("Some PAP Load", Sigs.LoadSomePap, Detour, true); + } + + public delegate void Delegate(nint a1, int a2, nint a3, int a4); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(nint a1, int a2, nint a3, int a4) + { + Penumbra.Log.Excessive($"[Some PAP Load] Invoked on 0x{a1:X} with {a2}, {a3}, {a4}."); + var timelinePtr = a1 + Offsets.TimeLinePtr; + if (timelinePtr != nint.Zero) + { + var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); + if (actorIdx >= 0 && actorIdx < _objects.Length) + { + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection((GameObject*)_objects.GetObjectAddress(actorIdx), + true)); + Task.Result.Original(a1, a2, a3, a4); + _state.RestoreAnimationData(last); + return; + } + } + + Task.Result.Original(a1, a2, a3, a4); + } +} diff --git a/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs b/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs new file mode 100644 index 00000000..ab4a7201 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs @@ -0,0 +1,31 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Called for some animations when using a Parasol. +public sealed unsafe class SomeParasolAnimation : FastHook +{ + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + + public SomeParasolAnimation(HookManager hooks, GameState state, CollectionResolver collectionResolver) + { + _state = state; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("Some Parasol Animation", Sigs.UnkParasolAnimation, Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject, int unk1); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject, int unk1) + { + Penumbra.Log.Excessive($"[Some Mount Animation] Invoked on {(nint)drawObject:X} with {unk1}."); + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection(drawObject, true)); + Task.Result.Original(drawObject, unk1); + _state.RestoreAnimationData(last); + } +} diff --git a/Penumbra/Interop/Hooks/CharacterBaseDestructor.cs b/Penumbra/Interop/Hooks/CharacterBaseDestructor.cs new file mode 100644 index 00000000..435ddea6 --- /dev/null +++ b/Penumbra/Interop/Hooks/CharacterBaseDestructor.cs @@ -0,0 +1,49 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.UI.AdvancedWindow; + +namespace Penumbra.Interop.Hooks; + +public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr, IHookService +{ + public enum Priority + { + /// + DrawObjectState = 0, + + /// + MtrlTab = -1000, + } + + public CharacterBaseDestructor(HookManager hooks) + : base("Destroy CharacterBase") + => _task = hooks.CreateHook(Name, Address, Detour, true); + + private readonly Task> _task; + + public nint Address + => (nint)CharacterBase.MemberFunctionPointers.Destroy; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate nint Delegate(CharacterBase* characterBase); + + private nint Detour(CharacterBase* characterBase) + { + Penumbra.Log.Verbose($"[{Name}] Triggered with 0x{(nint)characterBase:X}."); + Invoke(characterBase); + return _task.Result.Original(characterBase); + } +} diff --git a/Penumbra/Interop/Hooks/CharacterDestructor.cs b/Penumbra/Interop/Hooks/CharacterDestructor.cs new file mode 100644 index 00000000..4a0e9367 --- /dev/null +++ b/Penumbra/Interop/Hooks/CharacterDestructor.cs @@ -0,0 +1,49 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks; + +public sealed unsafe class CharacterDestructor : EventWrapperPtr, IHookService +{ + public enum Priority + { + /// + CutsceneService = 0, + + /// + IdentifiedCollectionCache = 0, + } + + public CharacterDestructor(HookManager hooks) + : base("Character Destructor") + => _task = hooks.CreateHook(Name, Sigs.CharacterDestructor, Detour, true); + + private readonly Task> _task; + + public nint Address + => _task.Result.Address; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate void Delegate(Character* character); + + private void Detour(Character* character) + { + Penumbra.Log.Verbose($"[{Name}] Triggered with 0x{(nint)character:X}."); + Invoke(character); + _task.Result.Original(character); + } +} diff --git a/Penumbra/Interop/Hooks/CopyCharacter.cs b/Penumbra/Interop/Hooks/CopyCharacter.cs new file mode 100644 index 00000000..d2e8d816 --- /dev/null +++ b/Penumbra/Interop/Hooks/CopyCharacter.cs @@ -0,0 +1,47 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Classes; +using OtterGui.Services; + +namespace Penumbra.Interop.Hooks; + +public sealed unsafe class CopyCharacter : EventWrapperPtr, IHookService +{ + public enum Priority + { + /// + CutsceneService = 0, + } + + public CopyCharacter(HookManager hooks) + : base("Copy Character") + => _task = hooks.CreateHook(Name, Address, Detour, true); + + private readonly Task> _task; + + public nint Address + => (nint)CharacterSetup.MemberFunctionPointers.CopyFromCharacter; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate ulong Delegate(CharacterSetup* target, Character* source, uint unk); + + private ulong Detour(CharacterSetup* target, Character* source, uint unk) + { + // TODO: update when CS updated. + var character = ((Character**)target)[1]; + Penumbra.Log.Verbose($"[{Name}] Triggered with target: 0x{(nint)target:X}, source : 0x{(nint)source:X} unk: {unk}."); + Invoke(character, source); + return _task.Result.Original(target, source, unk); + } +} diff --git a/Penumbra/Interop/Hooks/CreateCharacterBase.cs b/Penumbra/Interop/Hooks/CreateCharacterBase.cs new file mode 100644 index 00000000..7dbde666 --- /dev/null +++ b/Penumbra/Interop/Hooks/CreateCharacterBase.cs @@ -0,0 +1,74 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.GameData.Structs; + +namespace Penumbra.Interop.Hooks; + +public sealed unsafe class CreateCharacterBase : EventWrapperPtr, IHookService +{ + public enum Priority + { + /// + MetaState = 0, + } + + public CreateCharacterBase(HookManager hooks) + : base("Create CharacterBase") + => _task = hooks.CreateHook(Name, Address, Detour, true); + + private readonly Task> _task; + + public nint Address + => (nint)CharacterBase.MemberFunctionPointers.Create; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate CharacterBase* Delegate(ModelCharaId model, CustomizeArray* customize, CharacterArmor* equipment, byte unk); + + private CharacterBase* Detour(ModelCharaId model, CustomizeArray* customize, CharacterArmor* equipment, byte unk) + { + Penumbra.Log.Verbose($"[{Name}] Triggered with model: {model.Id}, customize: 0x{(nint) customize:X}, equipment: 0x{(nint)equipment:X}, unk: {unk}."); + Invoke(&model, customize, equipment); + var ret = _task.Result.Original(model, customize, equipment, unk); + _postEvent.Invoke(model, customize, equipment, ret); + return ret; + } + + public void Subscribe(ActionPtr234 subscriber, PostEvent.Priority priority) + => _postEvent.Subscribe(subscriber, priority); + + public void Unsubscribe(ActionPtr234 subscriber) + => _postEvent.Unsubscribe(subscriber); + + + private readonly PostEvent _postEvent = new("Created CharacterBase"); + + protected override void Dispose(bool disposing) + { + _postEvent.Dispose(); + } + + public class PostEvent(string name) : EventWrapperPtr234(name) + { + public enum Priority + { + /// + DrawObjectState = 0, + + /// + MetaState = 0, + } + } +} diff --git a/Penumbra/Interop/Hooks/DebugHook.cs b/Penumbra/Interop/Hooks/DebugHook.cs new file mode 100644 index 00000000..67823e94 --- /dev/null +++ b/Penumbra/Interop/Hooks/DebugHook.cs @@ -0,0 +1,43 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Services; + +namespace Penumbra.Interop.Hooks; + +#if DEBUG +public sealed unsafe class DebugHook : IHookService +{ + public const string Signature = ""; + + public DebugHook(HookManager hooks) + { + if (Signature.Length > 0) + _task = hooks.CreateHook("Debug Hook", Signature, Detour, true); + } + + private readonly Task>? _task; + + public nint Address + => _task?.Result.Address ?? nint.Zero; + + public void Enable() + => _task?.Result.Enable(); + + public void Disable() + => _task?.Result.Disable(); + + public Task Awaiter + => _task ?? Task.CompletedTask; + + public bool Finished + => _task?.IsCompletedSuccessfully ?? true; + + private delegate nint Delegate(ResourceHandle* resourceHandle); + + private nint Detour(ResourceHandle* resourceHandle) + { + Penumbra.Log.Information($"[Debug Hook] Triggered with 0x{(nint)resourceHandle:X}."); + return _task!.Result.Original(resourceHandle); + } +} +#endif diff --git a/Penumbra/Interop/Hooks/EnableDraw.cs b/Penumbra/Interop/Hooks/EnableDraw.cs new file mode 100644 index 00000000..884b643d --- /dev/null +++ b/Penumbra/Interop/Hooks/EnableDraw.cs @@ -0,0 +1,48 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks; + +/// +/// EnableDraw is what creates DrawObjects for gameObjects, +/// so we always keep track of the current GameObject to be able to link it to the DrawObject. +/// +public sealed unsafe class EnableDraw : IHookService +{ + private readonly Task> _task; + private readonly GameState _state; + + public EnableDraw(HookManager hooks, GameState state) + { + _state = state; + _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, true); + } + + private delegate void Delegate(GameObject* gameObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(GameObject* gameObject) + { + _state.QueueGameObject(gameObject); + Penumbra.Log.Excessive($"[Enable Draw] Invoked on 0x{(nint) gameObject:X}."); + _task.Result.Original.Invoke(gameObject); + _state.DequeueGameObject(); + } + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + public nint Address + => _task.Result.Address; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); +} diff --git a/Penumbra/Interop/Hooks/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/ResourceHandleDestructor.cs new file mode 100644 index 00000000..99eb1c23 --- /dev/null +++ b/Penumbra/Interop/Hooks/ResourceHandleDestructor.cs @@ -0,0 +1,50 @@ +using Dalamud.Hooking; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; + +namespace Penumbra.Interop.Hooks; + +public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr, IHookService +{ + public enum Priority + { + /// + SubfileHelper, + + /// + SkinFixer, + } + + public ResourceHandleDestructor(HookManager hooks) + : base("Destroy ResourceHandle") + => _task = hooks.CreateHook(Name, Sigs.ResourceHandleDestructor, Detour, true); + + private readonly Task> _task; + + public nint Address + => _task.Result.Address; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate nint Delegate(ResourceHandle* resourceHandle); + + private nint Detour(ResourceHandle* resourceHandle) + { + Penumbra.Log.Verbose($"[{Name}] Triggered with 0x{(nint)resourceHandle:X}."); + Invoke(resourceHandle); + return _task.Result.Original(resourceHandle); + } +} diff --git a/Penumbra/Interop/Hooks/WeaponReload.cs b/Penumbra/Interop/Hooks/WeaponReload.cs new file mode 100644 index 00000000..b931f8fb --- /dev/null +++ b/Penumbra/Interop/Hooks/WeaponReload.cs @@ -0,0 +1,71 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.GameData.Structs; + +namespace Penumbra.Interop.Hooks; + +public sealed unsafe class WeaponReload : EventWrapperPtr, IHookService +{ + public enum Priority + { + /// + DrawObjectState = 0, + } + + public WeaponReload(HookManager hooks) + : base("Reload Weapon") + => _task = hooks.CreateHook(Name, Address, Detour, true); + + private readonly Task> _task; + + public nint Address + => (nint)DrawDataContainer.MemberFunctionPointers.LoadWeapon; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate void Delegate(DrawDataContainer* drawData, uint slot, ulong weapon, byte d, byte e, byte f, byte g); + + private void Detour(DrawDataContainer* drawData, uint slot, ulong weapon, byte d, byte e, byte f, byte g) + { + var gameObject = drawData->Parent; + Penumbra.Log.Verbose($"[{Name}] Triggered with drawData: 0x{(nint)drawData:X}, {slot}, {weapon}, {d}, {e}, {f}, {g}."); + Invoke(drawData, gameObject, (CharacterWeapon*)(&weapon)); + _task.Result.Original(drawData, slot, weapon, d, e, f, g); + _postEvent.Invoke(drawData, gameObject); + } + + public void Subscribe(ActionPtr subscriber, PostEvent.Priority priority) + => _postEvent.Subscribe(subscriber, priority); + + public void Unsubscribe(ActionPtr subscriber) + => _postEvent.Unsubscribe(subscriber); + + + private readonly PostEvent _postEvent = new("Created CharacterBase"); + + protected override void Dispose(bool disposing) + { + _postEvent.Dispose(); + } + + public class PostEvent(string name) : EventWrapperPtr(name) + { + public enum Priority + { + /// + DrawObjectState = 0, + } + } +} diff --git a/Penumbra/Interop/PathResolving/AnimationHookService.cs b/Penumbra/Interop/PathResolving/AnimationHookService.cs deleted file mode 100644 index d13ef7f2..00000000 --- a/Penumbra/Interop/PathResolving/AnimationHookService.cs +++ /dev/null @@ -1,423 +0,0 @@ -using Dalamud.Game.ClientState.Conditions; -using Dalamud.Hooking; -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.Game; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using Penumbra.Collections; -using Penumbra.Api.Enums; -using Penumbra.GameData; -using Penumbra.Interop.Structs; -using Penumbra.String; -using Penumbra.String.Classes; -using Penumbra.Util; -using GameObject = FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject; - -namespace Penumbra.Interop.PathResolving; - -public unsafe class AnimationHookService : IDisposable -{ - private readonly PerformanceTracker _performance; - private readonly IObjectTable _objects; - private readonly CollectionResolver _collectionResolver; - private readonly DrawObjectState _drawObjectState; - private readonly CollectionResolver _resolver; - private readonly ICondition _conditions; - - private readonly ThreadLocal _animationLoadData = new(() => ResolveData.Invalid, true); - private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); - - public AnimationHookService(PerformanceTracker performance, IObjectTable objects, CollectionResolver collectionResolver, - DrawObjectState drawObjectState, CollectionResolver resolver, ICondition conditions, IGameInteropProvider interop) - { - _performance = performance; - _objects = objects; - _collectionResolver = collectionResolver; - _drawObjectState = drawObjectState; - _resolver = resolver; - _conditions = conditions; - - interop.InitializeFromAttributes(this); - _loadCharacterSoundHook = - interop.HookFromAddress( - (nint)FFXIVClientStructs.FFXIV.Client.Game.Character.Character.VfxContainer.MemberFunctionPointers.LoadCharacterSound, - LoadCharacterSoundDetour); - - _loadCharacterSoundHook.Enable(); - _loadTimelineResourcesHook.Enable(); - _characterBaseLoadAnimationHook.Enable(); - _loadSomePapHook.Enable(); - _someActionLoadHook.Enable(); - _loadCharacterVfxHook.Enable(); - _loadAreaVfxHook.Enable(); - _scheduleClipUpdateHook.Enable(); - _unkMountAnimationHook.Enable(); - _unkParasolAnimationHook.Enable(); - _dismountHook.Enable(); - _apricotListenerSoundPlayHook.Enable(); - _footStepHook.Enable(); - } - - public bool HandleFiles(ResourceType type, Utf8GamePath _, out ResolveData resolveData) - { - switch (type) - { - case ResourceType.Scd: - if (_characterSoundData is { IsValueCreated: true, Value.Valid: true }) - { - resolveData = _characterSoundData.Value; - return true; - } - - if (_animationLoadData is { IsValueCreated: true, Value.Valid: true }) - { - resolveData = _animationLoadData.Value; - return true; - } - - break; - case ResourceType.Tmb: - case ResourceType.Pap: - case ResourceType.Avfx: - case ResourceType.Atex: - if (_animationLoadData is { IsValueCreated: true, Value.Valid: true }) - { - resolveData = _animationLoadData.Value; - return true; - } - - break; - } - - var lastObj = _drawObjectState.LastGameObject; - if (lastObj != nint.Zero) - { - resolveData = _resolver.IdentifyCollection((GameObject*)lastObj, true); - return true; - } - - resolveData = ResolveData.Invalid; - return false; - } - - public void Dispose() - { - _loadCharacterSoundHook.Dispose(); - _loadTimelineResourcesHook.Dispose(); - _characterBaseLoadAnimationHook.Dispose(); - _loadSomePapHook.Dispose(); - _someActionLoadHook.Dispose(); - _loadCharacterVfxHook.Dispose(); - _loadAreaVfxHook.Dispose(); - _scheduleClipUpdateHook.Dispose(); - _unkMountAnimationHook.Dispose(); - _unkParasolAnimationHook.Dispose(); - _dismountHook.Dispose(); - _apricotListenerSoundPlayHook.Dispose(); - _footStepHook.Dispose(); - } - - /// Characters load some of their voice lines or whatever with this function. - private delegate nint LoadCharacterSound(nint character, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); - - private readonly Hook _loadCharacterSoundHook; - - private nint LoadCharacterSoundDetour(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7) - { - using var performance = _performance.Measure(PerformanceType.LoadSound); - var last = _characterSoundData.Value; - var character = *(GameObject**)(container + 8); - _characterSoundData.Value = _collectionResolver.IdentifyCollection(character, true); - var ret = _loadCharacterSoundHook.Original(container, unk1, unk2, unk3, unk4, unk5, unk6, unk7); - _characterSoundData.Value = last; - return ret; - } - - /// - /// The timeline object loads the requested .tmb and .pap files. The .tmb files load the respective .avfx files. - /// We can obtain the associated game object from the timelines 28'th vfunc and use that to apply the correct collection. - /// - private delegate ulong LoadTimelineResourcesDelegate(nint timeline); - - [Signature(Sigs.LoadTimelineResources, DetourName = nameof(LoadTimelineResourcesDetour))] - private readonly Hook _loadTimelineResourcesHook = null!; - - private ulong LoadTimelineResourcesDetour(nint timeline) - { - using var performance = _performance.Measure(PerformanceType.TimelineResources); - // Do not check timeline loading in cutscenes. - if (_conditions[ConditionFlag.OccupiedInCutSceneEvent] || _conditions[ConditionFlag.WatchingCutscene78]) - return _loadTimelineResourcesHook.Original(timeline); - - var last = _animationLoadData.Value; - _animationLoadData.Value = GetDataFromTimeline(timeline); - var ret = _loadTimelineResourcesHook.Original(timeline); - _animationLoadData.Value = last; - return ret; - } - - /// - /// Probably used when the base idle animation gets loaded. - /// Make it aware of the correct collection to load the correct pap files. - /// - private delegate void CharacterBaseNoArgumentDelegate(nint drawBase); - - [Signature(Sigs.CharacterBaseLoadAnimation, DetourName = nameof(CharacterBaseLoadAnimationDetour))] - private readonly Hook _characterBaseLoadAnimationHook = null!; - - private void CharacterBaseLoadAnimationDetour(nint drawObject) - { - using var performance = _performance.Measure(PerformanceType.LoadCharacterBaseAnimation); - var last = _animationLoadData.Value; - var lastObj = _drawObjectState.LastGameObject; - if (lastObj == nint.Zero && _drawObjectState.TryGetValue(drawObject, out var p)) - lastObj = p.Item1; - _animationLoadData.Value = _collectionResolver.IdentifyCollection((GameObject*)lastObj, true); - _characterBaseLoadAnimationHook.Original(drawObject); - _animationLoadData.Value = last; - } - - /// Unknown what exactly this is but it seems to load a bunch of paps. - private delegate void LoadSomePap(nint a1, int a2, nint a3, int a4); - - [Signature(Sigs.LoadSomePap, DetourName = nameof(LoadSomePapDetour))] - private readonly Hook _loadSomePapHook = null!; - - private void LoadSomePapDetour(nint a1, int a2, nint a3, int a4) - { - using var performance = _performance.Measure(PerformanceType.LoadPap); - var timelinePtr = a1 + Offsets.TimeLinePtr; - var last = _animationLoadData.Value; - if (timelinePtr != nint.Zero) - { - var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); - if (actorIdx >= 0 && actorIdx < _objects.Length) - _animationLoadData.Value = _collectionResolver.IdentifyCollection((GameObject*)_objects.GetObjectAddress(actorIdx), true); - } - - _loadSomePapHook.Original(a1, a2, a3, a4); - _animationLoadData.Value = last; - } - - private delegate void SomeActionLoadDelegate(ActionTimelineManager* timelineManager); - - /// Seems to load character actions when zoning or changing class, maybe. - [Signature(Sigs.LoadSomeAction, DetourName = nameof(SomeActionLoadDetour))] - private readonly Hook _someActionLoadHook = null!; - - private void SomeActionLoadDetour(ActionTimelineManager* timelineManager) - { - using var performance = _performance.Measure(PerformanceType.LoadAction); - var last = _animationLoadData.Value; - _animationLoadData.Value = _collectionResolver.IdentifyCollection((GameObject*)timelineManager->Parent, true); - _someActionLoadHook.Original(timelineManager); - _animationLoadData.Value = last; - } - - /// Load a VFX specifically for a character. - private delegate nint LoadCharacterVfxDelegate(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4); - - [Signature(Sigs.LoadCharacterVfx, DetourName = nameof(LoadCharacterVfxDetour))] - private readonly Hook _loadCharacterVfxHook = null!; - - private nint LoadCharacterVfxDetour(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4) - { - using var performance = _performance.Measure(PerformanceType.LoadCharacterVfx); - var last = _animationLoadData.Value; - if (vfxParams != null && vfxParams->GameObjectId != unchecked((uint)-1)) - { - var obj = vfxParams->GameObjectType switch - { - 0 => _objects.SearchById(vfxParams->GameObjectId), - 2 => _objects[(int)vfxParams->GameObjectId], - 4 => GetOwnedObject(vfxParams->GameObjectId), - _ => null, - }; - _animationLoadData.Value = obj != null - ? _collectionResolver.IdentifyCollection((GameObject*)obj.Address, true) - : ResolveData.Invalid; - } - else - { - _animationLoadData.Value = ResolveData.Invalid; - } - - var ret = _loadCharacterVfxHook.Original(vfxPath, vfxParams, unk1, unk2, unk3, unk4); - Penumbra.Log.Excessive( - $"Load Character VFX: {new ByteString(vfxPath)} 0x{vfxParams->GameObjectId:X} {vfxParams->TargetCount} {unk1} {unk2} {unk3} {unk4} -> " - + $"0x{ret:X} {_animationLoadData.Value.ModCollection.Name} {_animationLoadData.Value.AssociatedGameObject} {last.ModCollection.Name} {last.AssociatedGameObject}"); - _animationLoadData.Value = last; - return ret; - } - - /// Load a ground-based area VFX. - private delegate nint LoadAreaVfxDelegate(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3); - - [Signature(Sigs.LoadAreaVfx, DetourName = nameof(LoadAreaVfxDetour))] - private readonly Hook _loadAreaVfxHook = null!; - - private nint LoadAreaVfxDetour(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3) - { - using var performance = _performance.Measure(PerformanceType.LoadAreaVfx); - var last = _animationLoadData.Value; - _animationLoadData.Value = caster != null - ? _collectionResolver.IdentifyCollection(caster, true) - : ResolveData.Invalid; - - var ret = _loadAreaVfxHook.Original(vfxId, pos, caster, unk1, unk2, unk3); - Penumbra.Log.Excessive( - $"Load Area VFX: {vfxId}, {pos[0]} {pos[1]} {pos[2]} {(caster != null ? new ByteString(caster->GetName()).ToString() : "Unknown")} {unk1} {unk2} {unk3}" - + $" -> {ret:X} {_animationLoadData.Value.ModCollection.Name} {_animationLoadData.Value.AssociatedGameObject} {last.ModCollection.Name} {last.AssociatedGameObject}"); - _animationLoadData.Value = last; - return ret; - } - - - /// Called when some action timelines update. - private delegate void ScheduleClipUpdate(ClipScheduler* x); - - [Signature(Sigs.ScheduleClipUpdate, DetourName = nameof(ScheduleClipUpdateDetour))] - private readonly Hook _scheduleClipUpdateHook = null!; - - private void ScheduleClipUpdateDetour(ClipScheduler* x) - { - using var performance = _performance.Measure(PerformanceType.ScheduleClipUpdate); - var last = _animationLoadData.Value; - var timeline = x->SchedulerTimeline; - _animationLoadData.Value = GetDataFromTimeline(timeline); - _scheduleClipUpdateHook.Original(x); - _animationLoadData.Value = last; - } - - /// Search an object by its id, then get its minion/mount/ornament. - private Dalamud.Game.ClientState.Objects.Types.GameObject? GetOwnedObject(uint id) - { - var owner = _objects.SearchById(id); - if (owner == null) - return null; - - var idx = ((GameObject*)owner.Address)->ObjectIndex; - return _objects[idx + 1]; - } - - /// Use timelines vfuncs to obtain the associated game object. - private ResolveData GetDataFromTimeline(nint timeline) - { - try - { - if (timeline != nint.Zero) - { - var getGameObjectIdx = ((delegate* unmanaged**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; - var idx = getGameObjectIdx(timeline); - if (idx >= 0 && idx < _objects.Length) - { - var obj = (GameObject*)_objects.GetObjectAddress(idx); - return obj != null ? _collectionResolver.IdentifyCollection(obj, true) : ResolveData.Invalid; - } - } - } - catch (Exception e) - { - Penumbra.Log.Error($"Error getting timeline data for 0x{timeline:X}:\n{e}"); - } - - return ResolveData.Invalid; - } - - private delegate void UnkMountAnimationDelegate(DrawObject* drawObject, uint unk1, byte unk2, uint unk3); - - [Signature(Sigs.UnkMountAnimation, DetourName = nameof(UnkMountAnimationDetour))] - private readonly Hook _unkMountAnimationHook = null!; - - private void UnkMountAnimationDetour(DrawObject* drawObject, uint unk1, byte unk2, uint unk3) - { - var last = _animationLoadData.Value; - _animationLoadData.Value = _collectionResolver.IdentifyCollection(drawObject, true); - _unkMountAnimationHook.Original(drawObject, unk1, unk2, unk3); - _animationLoadData.Value = last; - } - - private delegate void UnkParasolAnimationDelegate(DrawObject* drawObject, int unk1); - - [Signature(Sigs.UnkParasolAnimation, DetourName = nameof(UnkParasolAnimationDetour))] - private readonly Hook _unkParasolAnimationHook = null!; - - private void UnkParasolAnimationDetour(DrawObject* drawObject, int unk1) - { - var last = _animationLoadData.Value; - _animationLoadData.Value = _collectionResolver.IdentifyCollection(drawObject, true); - _unkParasolAnimationHook.Original(drawObject, unk1); - _animationLoadData.Value = last; - } - - [Signature(Sigs.Dismount, DetourName = nameof(DismountDetour))] - private readonly Hook _dismountHook = null!; - - private delegate void DismountDelegate(nint a1, nint a2); - - private void DismountDetour(nint a1, nint a2) - { - if (a1 == nint.Zero) - { - _dismountHook.Original(a1, a2); - return; - } - - var gameObject = *(GameObject**)(a1 + 8); - if (gameObject == null) - { - _dismountHook.Original(a1, a2); - return; - } - - var last = _animationLoadData.Value; - _animationLoadData.Value = _collectionResolver.IdentifyCollection(gameObject, true); - _dismountHook.Original(a1, a2); - _animationLoadData.Value = last; - } - - [Signature(Sigs.ApricotListenerSoundPlay, DetourName = nameof(ApricotListenerSoundPlayDetour))] - private readonly Hook _apricotListenerSoundPlayHook = null!; - - private delegate nint ApricotListenerSoundPlayDelegate(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6); - - private nint ApricotListenerSoundPlayDetour(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6) - { - if (a6 == nint.Zero) - return _apricotListenerSoundPlayHook!.Original(a1, a2, a3, a4, a5, a6); - - var last = _animationLoadData.Value; - // a6 is some instance of Apricot.IInstanceListenner, in some cases we can obtain the associated caster via vfunc 1. - var gameObject = (*(delegate* unmanaged**)a6)[1](a6); - if (gameObject != null) - { - _animationLoadData.Value = _collectionResolver.IdentifyCollection(gameObject, true); - } - else - { - // for VfxListenner we can obtain the associated draw object as its first member, - // if the object has different type, drawObject will contain other values or garbage, - // but only be used in a dictionary pointer lookup, so this does not hurt. - var drawObject = ((DrawObject**)a6)[1]; - if (drawObject != null) - _animationLoadData.Value = _collectionResolver.IdentifyCollection(drawObject, true); - } - - var ret = _apricotListenerSoundPlayHook!.Original(a1, a2, a3, a4, a5, a6); - _animationLoadData.Value = last; - return ret; - } - - private delegate void FootStepDelegate(GameObject* gameObject, int id, int unk); - - [Signature(Sigs.FootStepSound, DetourName = nameof(FootStepDetour))] - private readonly Hook _footStepHook = null!; - - private void FootStepDetour(GameObject* gameObject, int id, int unk) - { - var last = _animationLoadData.Value; - _animationLoadData.Value = _collectionResolver.IdentifyCollection(gameObject, true); - _footStepHook.Original(gameObject, id, unk); - _animationLoadData.Value = last; - } -} diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index fe51a5cd..c649147a 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,11 +1,11 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Enums; -using Penumbra.Services; using Penumbra.Util; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; using GameObject = FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject; @@ -13,70 +13,51 @@ using ObjectKind = Dalamud.Game.ClientState.Objects.Enums.ObjectKind; namespace Penumbra.Interop.PathResolving; -public unsafe class CollectionResolver +public sealed unsafe class CollectionResolver( + PerformanceTracker performance, + IdentifiedCollectionCache cache, + IClientState clientState, + IGameGui gameGui, + ActorManager actors, + CutsceneService cutscenes, + Configuration config, + CollectionManager collectionManager, + TempCollectionManager tempCollections, + DrawObjectState drawObjectState, + HumanModelList humanModels) + : IService { - private readonly PerformanceTracker _performance; - private readonly IdentifiedCollectionCache _cache; - private readonly HumanModelList _humanModels; - - private readonly IClientState _clientState; - private readonly IGameGui _gameGui; - private readonly ActorManager _actors; - private readonly CutsceneService _cutscenes; - - private readonly Configuration _config; - private readonly CollectionManager _collectionManager; - private readonly TempCollectionManager _tempCollections; - private readonly DrawObjectState _drawObjectState; - - public CollectionResolver(PerformanceTracker performance, IdentifiedCollectionCache cache, IClientState clientState, IGameGui gameGui, - ActorManager actors, CutsceneService cutscenes, Configuration config, CollectionManager collectionManager, - TempCollectionManager tempCollections, DrawObjectState drawObjectState, HumanModelList humanModels) - { - _performance = performance; - _cache = cache; - _clientState = clientState; - _gameGui = gameGui; - _actors = actors; - _cutscenes = cutscenes; - _config = config; - _collectionManager = collectionManager; - _tempCollections = tempCollections; - _drawObjectState = drawObjectState; - _humanModels = humanModels; - } - /// /// Get the collection applying to the current player character /// or the Yourself or Default collection if no player exists. /// public ModCollection PlayerCollection() { - using var performance = _performance.Measure(PerformanceType.IdentifyCollection); - var gameObject = (GameObject*)(_clientState.LocalPlayer?.Address ?? nint.Zero); + using var performance1 = performance.Measure(PerformanceType.IdentifyCollection); + var gameObject = (GameObject*)(clientState.LocalPlayer?.Address ?? nint.Zero); if (gameObject == null) - return _collectionManager.Active.ByType(CollectionType.Yourself) - ?? _collectionManager.Active.Default; + return collectionManager.Active.ByType(CollectionType.Yourself) + ?? collectionManager.Active.Default; - var player = _actors.GetCurrentPlayer(); + var player = actors.GetCurrentPlayer(); var _ = false; return CollectionByIdentifier(player) ?? CheckYourself(player, gameObject) ?? CollectionByAttributes(gameObject, ref _) - ?? _collectionManager.Active.Default; + ?? collectionManager.Active.Default; } /// Identify the correct collection for a game object. public ResolveData IdentifyCollection(GameObject* gameObject, bool useCache) { - using var t = _performance.Measure(PerformanceType.IdentifyCollection); + using var t = performance.Measure(PerformanceType.IdentifyCollection); if (gameObject == null) - return _collectionManager.Active.Default.ToResolveData(); + return collectionManager.Active.Default.ToResolveData(); try { - if (useCache && _cache.TryGetValue(gameObject, out var data)) + if (useCache && cache.TryGetValue(gameObject, out var data)) return data; if (LoginScreen(gameObject, out data)) @@ -90,26 +71,26 @@ public unsafe class CollectionResolver catch (Exception ex) { Penumbra.Log.Error($"Error identifying collection:\n{ex}"); - return _collectionManager.Active.Default.ToResolveData(gameObject); + return collectionManager.Active.Default.ToResolveData(gameObject); } } /// Identify the correct collection for the last created game object. public ResolveData IdentifyLastGameObjectCollection(bool useCache) - => IdentifyCollection((GameObject*)_drawObjectState.LastGameObject, useCache); + => IdentifyCollection((GameObject*)drawObjectState.LastGameObject, useCache); /// Identify the correct collection for a draw object. public ResolveData IdentifyCollection(DrawObject* drawObject, bool useCache) { - var obj = (GameObject*)(_drawObjectState.TryGetValue((nint)drawObject, out var gameObject) + var obj = (GameObject*)(drawObjectState.TryGetValue((nint)drawObject, out var gameObject) ? gameObject.Item1 - : _drawObjectState.LastGameObject); + : drawObjectState.LastGameObject); return IdentifyCollection(obj, useCache); } /// Return whether the given ModelChara id refers to a human-type model. public bool IsModelHuman(uint modelCharaId) - => _humanModels.IsHuman(modelCharaId); + => humanModels.IsHuman(modelCharaId); /// Return whether the given character has a human model. public bool IsModelHuman(Character* character) @@ -124,36 +105,36 @@ public unsafe class CollectionResolver { // Also check for empty names because sometimes named other characters // might be loaded before being officially logged in. - if (_clientState.IsLoggedIn || gameObject->Name[0] != '\0') + if (clientState.IsLoggedIn || gameObject->Name[0] != '\0') { ret = ResolveData.Invalid; return false; } var notYetReady = false; - var collection = _collectionManager.Active.ByType(CollectionType.Yourself) + var collection = collectionManager.Active.ByType(CollectionType.Yourself) ?? CollectionByAttributes(gameObject, ref notYetReady) - ?? _collectionManager.Active.Default; - ret = notYetReady ? collection.ToResolveData(gameObject) : _cache.Set(collection, ActorIdentifier.Invalid, gameObject); + ?? collectionManager.Active.Default; + ret = notYetReady ? collection.ToResolveData(gameObject) : cache.Set(collection, ActorIdentifier.Invalid, gameObject); return true; } /// Used if at the aesthetician. The relevant actor is yourself, so use player collection when possible. private bool Aesthetician(GameObject* gameObject, out ResolveData ret) { - if (_gameGui.GetAddonByName("ScreenLog") != IntPtr.Zero) + if (gameGui.GetAddonByName("ScreenLog") != IntPtr.Zero) { ret = ResolveData.Invalid; return false; } - var player = _actors.GetCurrentPlayer(); + var player = actors.GetCurrentPlayer(); var notYetReady = false; var collection = (player.IsValid ? CollectionByIdentifier(player) : null) - ?? _collectionManager.Active.ByType(CollectionType.Yourself) + ?? collectionManager.Active.ByType(CollectionType.Yourself) ?? CollectionByAttributes(gameObject, ref notYetReady) - ?? _collectionManager.Active.Default; - ret = notYetReady ? collection.ToResolveData(gameObject) : _cache.Set(collection, ActorIdentifier.Invalid, gameObject); + ?? collectionManager.Active.Default; + ret = notYetReady ? collection.ToResolveData(gameObject) : cache.Set(collection, ActorIdentifier.Invalid, gameObject); return true; } @@ -163,12 +144,12 @@ public unsafe class CollectionResolver /// private ResolveData DefaultState(GameObject* gameObject) { - var identifier = _actors.FromObject(gameObject, out var owner, true, false, false); + var identifier = actors.FromObject(gameObject, out var owner, true, false, false); if (identifier.Type is IdentifierType.Special) { - (identifier, var type) = _collectionManager.Active.Individuals.ConvertSpecialIdentifier(identifier); - if (_config.UseNoModsInInspect && type == IndividualCollections.SpecialResult.Inspect) - return _cache.Set(ModCollection.Empty, identifier, gameObject); + (identifier, var type) = collectionManager.Active.Individuals.ConvertSpecialIdentifier(identifier); + if (config.UseNoModsInInspect && type == IndividualCollections.SpecialResult.Inspect) + return cache.Set(ModCollection.Empty, identifier, gameObject); } var notYetReady = false; @@ -176,15 +157,15 @@ public unsafe class CollectionResolver ?? CheckYourself(identifier, gameObject) ?? CollectionByAttributes(gameObject, ref notYetReady) ?? CheckOwnedCollection(identifier, owner, ref notYetReady) - ?? _collectionManager.Active.Default; + ?? collectionManager.Active.Default; - return notYetReady ? collection.ToResolveData(gameObject) : _cache.Set(collection, identifier, gameObject); + return notYetReady ? collection.ToResolveData(gameObject) : cache.Set(collection, identifier, gameObject); } /// Check both temporary and permanent character collections. Temporary first. private ModCollection? CollectionByIdentifier(ActorIdentifier identifier) - => _tempCollections.Collections.TryGetCollection(identifier, out var collection) - || _collectionManager.Active.Individuals.TryGetCollection(identifier, out collection) + => tempCollections.Collections.TryGetCollection(identifier, out var collection) + || collectionManager.Active.Individuals.TryGetCollection(identifier, out collection) ? collection : null; @@ -192,9 +173,9 @@ public unsafe class CollectionResolver private ModCollection? CheckYourself(ActorIdentifier identifier, GameObject* actor) { if (actor->ObjectIndex == 0 - || _cutscenes.GetParentIndex(actor->ObjectIndex) == 0 - || identifier.Equals(_actors.GetCurrentPlayer())) - return _collectionManager.Active.ByType(CollectionType.Yourself); + || cutscenes.GetParentIndex(actor->ObjectIndex) == 0 + || identifier.Equals(actors.GetCurrentPlayer())) + return collectionManager.Active.ByType(CollectionType.Yourself); return null; } @@ -219,8 +200,8 @@ public unsafe class CollectionResolver var bodyType = character->DrawData.CustomizeData[2]; var collection = bodyType switch { - 3 => _collectionManager.Active.ByType(CollectionType.NonPlayerElderly), - 4 => _collectionManager.Active.ByType(CollectionType.NonPlayerChild), + 3 => collectionManager.Active.ByType(CollectionType.NonPlayerElderly), + 4 => collectionManager.Active.ByType(CollectionType.NonPlayerChild), _ => null, }; if (collection != null) @@ -231,18 +212,18 @@ public unsafe class CollectionResolver var isNpc = actor->ObjectKind != (byte)ObjectKind.Player; var type = CollectionTypeExtensions.FromParts(race, gender, isNpc); - collection = _collectionManager.Active.ByType(type); - collection ??= _collectionManager.Active.ByType(CollectionTypeExtensions.FromParts(gender, isNpc)); + collection = collectionManager.Active.ByType(type); + collection ??= collectionManager.Active.ByType(CollectionTypeExtensions.FromParts(gender, isNpc)); return collection; } /// Get the collection applying to the owner if it is available. private ModCollection? CheckOwnedCollection(ActorIdentifier identifier, GameObject* owner, ref bool notYetReady) { - if (identifier.Type != IdentifierType.Owned || !_config.UseOwnerNameForCharacterCollection || owner == null) + if (identifier.Type != IdentifierType.Owned || !config.UseOwnerNameForCharacterCollection || owner == null) return null; - var id = _actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, + var id = actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); return CheckYourself(id, owner) diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 18c016b9..c7b24bd7 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -1,31 +1,34 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Services; using Penumbra.GameData.Enums; -using Penumbra.Interop.Services; +using Penumbra.Interop.Hooks; namespace Penumbra.Interop.PathResolving; -public class CutsceneService : IDisposable +public sealed class CutsceneService : IService, IDisposable { public const int CutsceneStartIdx = (int)ScreenActor.CutsceneStart; public const int CutsceneEndIdx = (int)ScreenActor.CutsceneEnd; public const int CutsceneSlots = CutsceneEndIdx - CutsceneStartIdx; - private readonly GameEventManager _events; - private readonly IObjectTable _objects; - private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); + private readonly IObjectTable _objects; + private readonly CopyCharacter _copyCharacter; + private readonly CharacterDestructor _characterDestructor; + private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); public IEnumerable> Actors => Enumerable.Range(CutsceneStartIdx, CutsceneSlots) .Where(i => _objects[i] != null) .Select(i => KeyValuePair.Create(i, this[i] ?? _objects[i]!)); - public unsafe CutsceneService(IObjectTable objects, GameEventManager events) + public unsafe CutsceneService(IObjectTable objects, CopyCharacter copyCharacter, CharacterDestructor characterDestructor) { - _objects = objects; - _events = events; - _events.CopyCharacter += OnCharacterCopy; - _events.CharacterDestructor += OnCharacterDestructor; + _objects = objects; + _copyCharacter = copyCharacter; + _characterDestructor = characterDestructor; + _copyCharacter.Subscribe(OnCharacterCopy, CopyCharacter.Priority.CutsceneService); + _characterDestructor.Subscribe(OnCharacterDestructor, CharacterDestructor.Priority.CutsceneService); } /// @@ -57,8 +60,8 @@ public class CutsceneService : IDisposable public unsafe void Dispose() { - _events.CopyCharacter -= OnCharacterCopy; - _events.CharacterDestructor -= OnCharacterDestructor; + _copyCharacter.Unsubscribe(OnCharacterCopy); + _characterDestructor.Unsubscribe(OnCharacterDestructor); } private unsafe void OnCharacterDestructor(Character* character) diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 9726d84c..19c0fd10 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -1,35 +1,39 @@ -using Dalamud.Hooking; -using Dalamud.Utility.Signatures; using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; -using Penumbra.GameData; -using Penumbra.Interop.Services; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Interop.Hooks; using Object = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.Object; +using Penumbra.GameData.Structs; namespace Penumbra.Interop.PathResolving; -public class DrawObjectState : IDisposable, IReadOnlyDictionary +public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary, IService { - private readonly IObjectTable _objects; - private readonly GameEventManager _gameEvents; + private readonly IObjectTable _objects; + private readonly CreateCharacterBase _createCharacterBase; + private readonly WeaponReload _weaponReload; + private readonly CharacterBaseDestructor _characterBaseDestructor; + private readonly GameState _gameState; - private readonly Dictionary _drawObjectToGameObject = new(); - - private readonly ThreadLocal> _lastGameObject = new(() => new Queue()); + private readonly Dictionary _drawObjectToGameObject = []; public nint LastGameObject - => _lastGameObject.IsValueCreated && _lastGameObject.Value!.Count > 0 ? _lastGameObject.Value.Peek() : nint.Zero; + => _gameState.LastGameObject; - public DrawObjectState(IObjectTable objects, GameEventManager gameEvents, IGameInteropProvider interop) + public unsafe DrawObjectState(IObjectTable objects, CreateCharacterBase createCharacterBase, WeaponReload weaponReload, + CharacterBaseDestructor characterBaseDestructor, GameState gameState) { - interop.InitializeFromAttributes(this); - _enableDrawHook.Enable(); - _objects = objects; - _gameEvents = gameEvents; - _gameEvents.WeaponReloading += OnWeaponReloading; - _gameEvents.WeaponReloaded += OnWeaponReloaded; - _gameEvents.CharacterBaseCreated += OnCharacterBaseCreated; - _gameEvents.CharacterBaseDestructor += OnCharacterBaseDestructor; + _objects = objects; + _createCharacterBase = createCharacterBase; + _weaponReload = weaponReload; + _characterBaseDestructor = characterBaseDestructor; + _gameState = gameState; + _weaponReload.Subscribe(OnWeaponReloading, WeaponReload.Priority.DrawObjectState); + _weaponReload.Subscribe(OnWeaponReloaded, WeaponReload.PostEvent.Priority.DrawObjectState); + _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.DrawObjectState); + _characterBaseDestructor.Subscribe(OnCharacterBaseDestructor, CharacterBaseDestructor.Priority.DrawObjectState); InitializeDrawObjects(); } @@ -57,32 +61,32 @@ public class DrawObjectState : IDisposable, IReadOnlyDictionary Values => _drawObjectToGameObject.Values; - public void Dispose() + public unsafe void Dispose() { - _gameEvents.WeaponReloading -= OnWeaponReloading; - _gameEvents.WeaponReloaded -= OnWeaponReloaded; - _gameEvents.CharacterBaseCreated -= OnCharacterBaseCreated; - _gameEvents.CharacterBaseDestructor -= OnCharacterBaseDestructor; - _enableDrawHook.Dispose(); + _weaponReload.Unsubscribe(OnWeaponReloading); + _weaponReload.Unsubscribe(OnWeaponReloaded); + _createCharacterBase.Unsubscribe(OnCharacterBaseCreated); + _characterBaseDestructor.Unsubscribe(OnCharacterBaseDestructor); } - private void OnWeaponReloading(nint _, nint gameObject) - => _lastGameObject.Value!.Enqueue(gameObject); + private unsafe void OnWeaponReloading(DrawDataContainer* _, Character* character, CharacterWeapon* _2) + => _gameState.QueueGameObject((nint)character); - private unsafe void OnWeaponReloaded(nint _, nint gameObject) + private unsafe void OnWeaponReloaded(DrawDataContainer* _, Character* character) { - _lastGameObject.Value!.Dequeue(); - IterateDrawObjectTree((Object*)((GameObject*)gameObject)->DrawObject, gameObject, false, false); + _gameState.DequeueGameObject(); + IterateDrawObjectTree((Object*)character->GameObject.DrawObject, (nint)character, false, false); } - private void OnCharacterBaseDestructor(nint characterBase) - => _drawObjectToGameObject.Remove(characterBase); + private unsafe void OnCharacterBaseDestructor(CharacterBase* characterBase) + => _drawObjectToGameObject.Remove((nint)characterBase); - private void OnCharacterBaseCreated(uint modelCharaId, nint customize, nint equipment, nint drawObject) + private unsafe void OnCharacterBaseCreated(ModelCharaId modelCharaId, CustomizeArray* customize, CharacterArmor* equipment, + CharacterBase* drawObject) { var gameObject = LastGameObject; if (gameObject != nint.Zero) - _drawObjectToGameObject[drawObject] = (gameObject, false); + _drawObjectToGameObject[(nint)drawObject] = (gameObject, false); } /// @@ -123,20 +127,4 @@ public class DrawObjectState : IDisposable, IReadOnlyDictionaryPreviousSiblingObject; } } - - /// - /// EnableDraw is what creates DrawObjects for gameObjects, - /// so we always keep track of the current GameObject to be able to link it to the DrawObject. - /// - private delegate void EnableDrawDelegate(nint gameObject); - - [Signature(Sigs.EnableDraw, DetourName = nameof(EnableDrawDetour))] - private readonly Hook _enableDrawHook = null!; - - private void EnableDrawDetour(nint gameObject) - { - _lastGameObject.Value!.Enqueue(gameObject); - _enableDrawHook.Original.Invoke(gameObject); - _lastGameObject.Value!.TryDequeue(out _); - } } diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 73c20ab9..3e7171f8 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -5,7 +5,7 @@ using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Actors; -using Penumbra.Interop.Services; +using Penumbra.Interop.Hooks; using Penumbra.Services; namespace Penumbra.Interop.PathResolving; @@ -13,20 +13,20 @@ namespace Penumbra.Interop.PathResolving; public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint Address, ActorIdentifier Identifier, ModCollection Collection)> { private readonly CommunicatorService _communicator; - private readonly GameEventManager _events; + private readonly CharacterDestructor _characterDestructor; private readonly IClientState _clientState; private readonly Dictionary _cache = new(317); private bool _dirty; - public IdentifiedCollectionCache(IClientState clientState, CommunicatorService communicator, GameEventManager events) + public IdentifiedCollectionCache(IClientState clientState, CommunicatorService communicator, CharacterDestructor characterDestructor) { - _clientState = clientState; - _communicator = communicator; - _events = events; + _clientState = clientState; + _communicator = communicator; + _characterDestructor = characterDestructor; _communicator.CollectionChange.Subscribe(CollectionChangeClear, CollectionChange.Priority.IdentifiedCollectionCache); _clientState.TerritoryChanged += TerritoryClear; - _events.CharacterDestructor += OnCharacterDestruct; + _characterDestructor.Subscribe(OnCharacterDestructor, CharacterDestructor.Priority.IdentifiedCollectionCache); } public ResolveData Set(ModCollection collection, ActorIdentifier identifier, GameObject* data) @@ -62,7 +62,7 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A { _communicator.CollectionChange.Unsubscribe(CollectionChangeClear); _clientState.TerritoryChanged -= TerritoryClear; - _events.CharacterDestructor -= OnCharacterDestruct; + _characterDestructor.Unsubscribe(OnCharacterDestructor); } public IEnumerator<(nint Address, ActorIdentifier Identifier, ModCollection Collection)> GetEnumerator() @@ -88,6 +88,6 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A private void TerritoryClear(ushort _2) => _dirty = _cache.Count > 0; - private void OnCharacterDestruct(Character* character) + private void OnCharacterDestructor(Character* character) => _cache.Remove((nint)character); } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index c1e0bb80..9ef291c7 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -9,6 +9,8 @@ using Penumbra.Collections; using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Hooks; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Services; @@ -52,24 +54,24 @@ public unsafe class MetaState : IDisposable private readonly PerformanceTracker _performance; private readonly CollectionResolver _collectionResolver; private readonly ResourceLoader _resources; - private readonly GameEventManager _gameEventManager; private readonly CharacterUtility _characterUtility; + private readonly CreateCharacterBase _createCharacterBase; private ResolveData _lastCreatedCollection = ResolveData.Invalid; private ResolveData _customizeChangeCollection = ResolveData.Invalid; private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; public MetaState(PerformanceTracker performance, CommunicatorService communicator, CollectionResolver collectionResolver, - ResourceLoader resources, GameEventManager gameEventManager, CharacterUtility characterUtility, Configuration config, + ResourceLoader resources, CreateCharacterBase createCharacterBase, CharacterUtility characterUtility, Configuration config, IGameInteropProvider interop) { - _performance = performance; - _communicator = communicator; - _collectionResolver = collectionResolver; - _resources = resources; - _gameEventManager = gameEventManager; - _characterUtility = characterUtility; - _config = config; + _performance = performance; + _communicator = communicator; + _collectionResolver = collectionResolver; + _resources = resources; + _createCharacterBase = createCharacterBase; + _characterUtility = characterUtility; + _config = config; interop.InitializeFromAttributes(this); _calculateHeightHook = interop.HookFromAddress((nint)Character.MemberFunctionPointers.CalculateHeight, CalculateHeightDetour); @@ -81,8 +83,8 @@ public unsafe class MetaState : IDisposable _rspSetupCharacterHook.Enable(); _changeCustomize.Enable(); _calculateHeightHook.Enable(); - _gameEventManager.CreatingCharacterBase += OnCreatingCharacterBase; - _gameEventManager.CharacterBaseCreated += OnCharacterBaseCreated; + _createCharacterBase.Subscribe(OnCreatingCharacterBase, CreateCharacterBase.Priority.MetaState); + _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.MetaState); } public bool HandleDecalFile(ResourceType type, Utf8GamePath gamePath, out ResolveData resolveData) @@ -124,31 +126,31 @@ public unsafe class MetaState : IDisposable _rspSetupCharacterHook.Dispose(); _changeCustomize.Dispose(); _calculateHeightHook.Dispose(); - _gameEventManager.CreatingCharacterBase -= OnCreatingCharacterBase; - _gameEventManager.CharacterBaseCreated -= OnCharacterBaseCreated; + _createCharacterBase.Unsubscribe(OnCreatingCharacterBase); + _createCharacterBase.Unsubscribe(OnCharacterBaseCreated); } - private void OnCreatingCharacterBase(nint modelCharaId, nint customize, nint equipData) + private void OnCreatingCharacterBase(ModelCharaId* modelCharaId, CustomizeArray* customize, CharacterArmor* equipData) { _lastCreatedCollection = _collectionResolver.IdentifyLastGameObjectCollection(true); if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero) _communicator.CreatingCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, - _lastCreatedCollection.ModCollection.Name, modelCharaId, customize, equipData); + _lastCreatedCollection.ModCollection.Name, (nint) modelCharaId, (nint) customize, (nint) equipData); var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, - UsesDecal(*(uint*)modelCharaId, customize)); + UsesDecal(*(uint*)modelCharaId, (nint) customize)); var cmp = _lastCreatedCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); _characterBaseCreateMetaChanges.Dispose(); // Should always be empty. _characterBaseCreateMetaChanges = new DisposableContainer(decal, cmp); } - private void OnCharacterBaseCreated(uint _1, nint _2, nint _3, nint drawObject) + private void OnCharacterBaseCreated(ModelCharaId _1, CustomizeArray* _2, CharacterArmor* _3, CharacterBase* drawObject) { _characterBaseCreateMetaChanges.Dispose(); _characterBaseCreateMetaChanges = DisposableContainer.Empty; - if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero && drawObject != nint.Zero) + if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero && drawObject != null) _communicator.CreatedCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, - _lastCreatedCollection.ModCollection, drawObject); + _lastCreatedCollection.ModCollection, (nint)drawObject); _lastCreatedCollection = ResolveData.Invalid; } diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 6db97b63..7c16b97b 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -18,26 +18,28 @@ public class PathResolver : IDisposable private readonly TempCollectionManager _tempCollections; private readonly ResourceLoader _loader; - private readonly AnimationHookService _animationHookService; - private readonly SubfileHelper _subfileHelper; - private readonly PathState _pathState; - private readonly MetaState _metaState; + private readonly SubfileHelper _subfileHelper; + private readonly PathState _pathState; + private readonly MetaState _metaState; + private readonly GameState _gameState; + private readonly CollectionResolver _collectionResolver; public unsafe PathResolver(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, - TempCollectionManager tempCollections, ResourceLoader loader, AnimationHookService animationHookService, SubfileHelper subfileHelper, - PathState pathState, MetaState metaState) + TempCollectionManager tempCollections, ResourceLoader loader, SubfileHelper subfileHelper, + PathState pathState, MetaState metaState, CollectionResolver collectionResolver, GameState gameState) { - _performance = performance; - _config = config; - _collectionManager = collectionManager; - _tempCollections = tempCollections; - _animationHookService = animationHookService; - _subfileHelper = subfileHelper; - _pathState = pathState; - _metaState = metaState; - _loader = loader; - _loader.ResolvePath = ResolvePath; - _loader.FileLoaded += ImcLoadResource; + _performance = performance; + _config = config; + _collectionManager = collectionManager; + _tempCollections = tempCollections; + _subfileHelper = subfileHelper; + _pathState = pathState; + _metaState = metaState; + _gameState = gameState; + _collectionResolver = collectionResolver; + _loader = loader; + _loader.ResolvePath = ResolvePath; + _loader.FileLoaded += ImcLoadResource; } /// Obtain a temporary or permanent collection by name. @@ -98,7 +100,7 @@ public class PathResolver : IDisposable // A potential next request will add the path anew. var nonDefault = _subfileHelper.HandleSubFiles(type, out var resolveData) || _pathState.Consume(gamePath.Path, out resolveData) - || _animationHookService.HandleFiles(type, gamePath, out resolveData) + || _gameState.HandleFiles(_collectionResolver, type, gamePath, out resolveData) || _metaState.HandleDecalFile(type, gamePath, out resolveData); if (!nonDefault || !resolveData.Valid) resolveData = _collectionManager.Active.Default.ToResolveData(); diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 3a60450d..370118ea 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -4,6 +4,7 @@ using Dalamud.Utility.Signatures; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData; +using Penumbra.Interop.Hooks; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; @@ -21,30 +22,30 @@ namespace Penumbra.Interop.PathResolving; /// public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection> { - private readonly PerformanceTracker _performance; - private readonly ResourceLoader _loader; - private readonly GameEventManager _events; - private readonly CommunicatorService _communicator; + private readonly PerformanceTracker _performance; + private readonly ResourceLoader _loader; + private readonly ResourceHandleDestructor _resourceHandleDestructor; + private readonly CommunicatorService _communicator; private readonly ThreadLocal _mtrlData = new(() => ResolveData.Invalid); private readonly ThreadLocal _avfxData = new(() => ResolveData.Invalid); private readonly ConcurrentDictionary _subFileCollection = new(); - public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, GameEventManager events, CommunicatorService communicator, IGameInteropProvider interop) + public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, CommunicatorService communicator, IGameInteropProvider interop, ResourceHandleDestructor resourceHandleDestructor) { interop.InitializeFromAttributes(this); - _performance = performance; - _loader = loader; - _events = events; - _communicator = communicator; + _performance = performance; + _loader = loader; + _communicator = communicator; + _resourceHandleDestructor = resourceHandleDestructor; _loadMtrlShpkHook.Enable(); _loadMtrlTexHook.Enable(); _apricotResourceLoadHook.Enable(); _loader.ResourceLoaded += SubfileContainerRequested; - _events.ResourceHandleDestructor += ResourceDestroyed; + _resourceHandleDestructor.Subscribe(ResourceDestroyed, ResourceHandleDestructor.Priority.SubfileHelper); } @@ -105,7 +106,7 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection((nint)CharacterSetup.MemberFunctionPointers.CopyFromCharacter, CopyCharacterDetour); - _characterBaseCreateHook = - interop.HookFromAddress((nint)CharacterBase.MemberFunctionPointers.Create, CharacterBaseCreateDetour); - _characterBaseDestructorHook = - interop.HookFromAddress((nint)CharacterBase.MemberFunctionPointers.Destroy, - CharacterBaseDestructorDetour); - _weaponReloadHook = - interop.HookFromAddress((nint)DrawDataContainer.MemberFunctionPointers.LoadWeapon, WeaponReloadDetour); - _characterDtorHook.Enable(); - _copyCharacterHook.Enable(); - _resourceHandleDestructorHook.Enable(); - _characterBaseCreateHook.Enable(); - _characterBaseDestructorHook.Enable(); - _weaponReloadHook.Enable(); - EnableDebugHook(); - Penumbra.Log.Verbose($"{Prefix} Created."); - } - - public void Dispose() - { - _characterDtorHook.Dispose(); - _copyCharacterHook.Dispose(); - _resourceHandleDestructorHook.Dispose(); - _characterBaseCreateHook.Dispose(); - _characterBaseDestructorHook.Dispose(); - _weaponReloadHook.Dispose(); - DisposeDebugHook(); - Penumbra.Log.Verbose($"{Prefix} Disposed."); - } - - #region Character Destructor - - private delegate void CharacterDestructorDelegate(Character* character); - - [Signature(Sigs.CharacterDestructor, DetourName = nameof(CharacterDestructorDetour))] - private readonly Hook _characterDtorHook = null!; - - private void CharacterDestructorDetour(Character* character) - { - if (CharacterDestructor != null) - foreach (var subscriber in CharacterDestructor.GetInvocationList()) - { - try - { - ((CharacterDestructorEvent)subscriber).Invoke(character); - } - catch (Exception ex) - { - Penumbra.Log.Error($"{Prefix} Error in {nameof(CharacterDestructor)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - Penumbra.Log.Verbose($"{Prefix} {nameof(CharacterDestructor)} triggered with 0x{(nint)character:X}."); - _characterDtorHook.Original(character); - } - - public delegate void CharacterDestructorEvent(Character* character); - - #endregion - - #region Copy Character - - private delegate ulong CopyCharacterDelegate(CharacterSetup* target, GameObject* source, uint unk); - - private readonly Hook _copyCharacterHook; - - private ulong CopyCharacterDetour(CharacterSetup* target, GameObject* source, uint unk) - { - // TODO: update when CS updated. - var character = ((Character**)target)[1]; - if (CopyCharacter != null) - foreach (var subscriber in CopyCharacter.GetInvocationList()) - { - try - { - ((CopyCharacterEvent)subscriber).Invoke(character, (Character*)source); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(CopyCharacter)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - Penumbra.Log.Verbose( - $"{Prefix} {nameof(CopyCharacter)} triggered with target 0x{(nint)target:X} and source 0x{(nint)source:X}."); - return _copyCharacterHook.Original(target, source, unk); - } - - public delegate void CopyCharacterEvent(Character* target, Character* source); - - #endregion - - #region ResourceHandle Destructor - - private delegate IntPtr ResourceHandleDestructorDelegate(ResourceHandle* handle); - - [Signature(Sigs.ResourceHandleDestructor, DetourName = nameof(ResourceHandleDestructorDetour))] - private readonly Hook _resourceHandleDestructorHook = null!; - - private IntPtr ResourceHandleDestructorDetour(ResourceHandle* handle) - { - if (ResourceHandleDestructor != null) - foreach (var subscriber in ResourceHandleDestructor.GetInvocationList()) - { - try - { - ((ResourceHandleDestructorEvent)subscriber).Invoke(handle); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(ResourceHandleDestructor)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - Penumbra.Log.Excessive($"{Prefix} {nameof(ResourceHandleDestructor)} triggered with 0x{(nint)handle:X}."); - return _resourceHandleDestructorHook!.Original(handle); - } - - public delegate void ResourceHandleDestructorEvent(ResourceHandle* handle); - - #endregion - - #region CharacterBaseCreate - - private delegate nint CharacterBaseCreateDelegate(uint a, nint b, nint c, byte d); - - private readonly Hook _characterBaseCreateHook; - - private nint CharacterBaseCreateDetour(uint a, nint b, nint c, byte d) - { - if (CreatingCharacterBase != null) - foreach (var subscriber in CreatingCharacterBase.GetInvocationList()) - { - try - { - ((CreatingCharacterBaseEvent)subscriber).Invoke((nint)(&a), b, c); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(CharacterBaseCreateDetour)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - var ret = _characterBaseCreateHook.Original(a, b, c, d); - if (CharacterBaseCreated != null) - foreach (var subscriber in CharacterBaseCreated.GetInvocationList()) - { - try - { - ((CharacterBaseCreatedEvent)subscriber).Invoke(a, b, c, ret); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(CharacterBaseCreateDetour)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - return ret; - } - - public delegate void CreatingCharacterBaseEvent(nint modelCharaId, nint customize, nint equipment); - public delegate void CharacterBaseCreatedEvent(uint modelCharaId, nint customize, nint equipment, nint drawObject); - - #endregion - - #region CharacterBase Destructor - - public delegate void CharacterBaseDestructorEvent(nint drawBase); - - private readonly Hook _characterBaseDestructorHook; - - private void CharacterBaseDestructorDetour(IntPtr drawBase) - { - if (CharacterBaseDestructor != null) - foreach (var subscriber in CharacterBaseDestructor.GetInvocationList()) - { - try - { - ((CharacterBaseDestructorEvent)subscriber).Invoke(drawBase); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(CharacterBaseDestructorDetour)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - _characterBaseDestructorHook.Original.Invoke(drawBase); - } - - #endregion - - #region Weapon Reload - - private delegate void WeaponReloadFunc(nint a1, uint a2, nint a3, byte a4, byte a5, byte a6, byte a7); - - private readonly Hook _weaponReloadHook; - - private void WeaponReloadDetour(nint a1, uint a2, nint a3, byte a4, byte a5, byte a6, byte a7) - { - var gameObject = *(nint*)(a1 + 8); - if (WeaponReloading != null) - foreach (var subscriber in WeaponReloading.GetInvocationList()) - { - try - { - ((WeaponReloadingEvent)subscriber).Invoke(a1, gameObject); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(WeaponReloadDetour)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - - _weaponReloadHook.Original(a1, a2, a3, a4, a5, a6, a7); - - if (WeaponReloaded != null) - foreach (var subscriber in WeaponReloaded.GetInvocationList()) - { - try - { - ((WeaponReloadedEvent)subscriber).Invoke(a1, gameObject); - } - catch (Exception ex) - { - Penumbra.Log.Error( - $"{Prefix} Error in {nameof(WeaponReloadDetour)} event when executing {subscriber.Method.Name}:\n{ex}"); - } - } - } - - public delegate void WeaponReloadingEvent(nint drawDataContainer, nint gameObject); - public delegate void WeaponReloadedEvent(nint drawDataContainer, nint gameObject); - - #endregion - - #region Testing - -#if DEBUG - //[Signature("48 89 5C 24 ?? 48 89 74 24 ?? 89 54 24 ?? 57 48 83 EC ?? 48 8B F9", DetourName = nameof(TestDetour))] - private readonly Hook? _testHook = null; - - private delegate void TestDelegate(nint a1, int a2); - - private void TestDetour(nint a1, int a2) - { - Penumbra.Log.Information($"Test: {a1:X} {a2}"); - _testHook!.Original(a1, a2); - } - - private void EnableDebugHook() - => _testHook?.Enable(); - - private void DisposeDebugHook() - => _testHook?.Dispose(); -#else - private void EnableDebugHook() - { } - - private void DisposeDebugHook() - { } -#endif - - #endregion -} diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index d25a5638..444b9a48 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -6,6 +6,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Classes; using Penumbra.Communication; using Penumbra.GameData; +using Penumbra.Interop.Hooks; using Penumbra.Services; namespace Penumbra.Interop.Services; @@ -32,9 +33,9 @@ public sealed unsafe class SkinFixer : IDisposable private readonly Hook _onRenderMaterialHook; - private readonly GameEventManager _gameEvents; - private readonly CommunicatorService _communicator; - private readonly CharacterUtility _utility; + private readonly ResourceHandleDestructor _resourceHandleDestructor; + private readonly CommunicatorService _communicator; + private readonly CharacterUtility _utility; // MaterialResourceHandle set private readonly ConcurrentSet _moddedSkinShpkMaterials = new(); @@ -50,15 +51,16 @@ public sealed unsafe class SkinFixer : IDisposable public int ModdedSkinShpkCount => _moddedSkinShpkCount; - public SkinFixer(GameEventManager gameEvents, CharacterUtility utility, CommunicatorService communicator, IGameInteropProvider interop) + public SkinFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, CommunicatorService communicator, + IGameInteropProvider interop) { interop.InitializeFromAttributes(this); - _gameEvents = gameEvents; - _utility = utility; - _communicator = communicator; - _onRenderMaterialHook = interop.HookFromAddress(_humanVTable[62], OnRenderHumanMaterial); + _resourceHandleDestructor = resourceHandleDestructor; + _utility = utility; + _communicator = communicator; + _onRenderMaterialHook = interop.HookFromAddress(_humanVTable[62], OnRenderHumanMaterial); _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.SkinFixer); - _gameEvents.ResourceHandleDestructor += OnResourceHandleDestructor; + _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.SkinFixer); _onRenderMaterialHook.Enable(); } @@ -66,7 +68,7 @@ public sealed unsafe class SkinFixer : IDisposable { _onRenderMaterialHook.Dispose(); _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); - _gameEvents.ResourceHandleDestructor -= OnResourceHandleDestructor; + _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); _moddedSkinShpkMaterials.Clear(); _moddedSkinShpkCount = 0; } diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 66101dcd..6c5f9c25 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -2,7 +2,6 @@ using Dalamud.Utility; using Newtonsoft.Json.Linq; using OtterGui.Classes; using Penumbra.Services; -using Penumbra.Util; namespace Penumbra.Mods.Manager; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 900d2770..350c20b2 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -80,6 +80,10 @@ public class Penumbra : IDalamudPlugin _services.GetService(); _services.GetService(); // Initialize before Interface. + + foreach (var service in _services.GetServicesImplementing()) + service.Awaiter.Wait(); + SetupInterface(); SetupApi(); diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 54f7a16f..b7f3de9d 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -69,6 +69,7 @@ + @@ -92,8 +93,8 @@ - - + + diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index c7efac04..be94a31e 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -9,7 +9,7 @@ public class CommunicatorService : IDisposable, IService { public CommunicatorService(Logger logger) { - EventWrapper.ChangeLogger(logger); + EventWrapperBase.ChangeLogger(logger); } /// diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index 5a1c9f74..8038152e 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -82,8 +82,7 @@ public static class ServiceManagerA .AddDalamudService(pi); private static ServiceManager AddInterop(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() + => services.AddSingleton() .AddSingleton() .AddSingleton(p => { @@ -135,8 +134,7 @@ public static class ServiceManagerA .AddSingleton(); private static ServiceManager AddResolvers(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() + => services.AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 09e22d67..376bbcf7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -1,5 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; using Newtonsoft.Json.Linq; using OtterGui; @@ -8,6 +9,7 @@ using OtterGui.Raii; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; +using Penumbra.Interop.Hooks; using Penumbra.Interop.MaterialPreview; using Penumbra.String; using Penumbra.String.Classes; @@ -503,12 +505,12 @@ public partial class ModEditWindow ColorTablePreviewers.Clear(); } - private unsafe void UnbindFromDrawObjectMaterialInstances(nint characterBase) + private unsafe void UnbindFromDrawObjectMaterialInstances(CharacterBase* characterBase) { for (var i = MaterialPreviewers.Count; i-- > 0;) { var previewer = MaterialPreviewers[i]; - if ((nint)previewer.DrawObject != characterBase) + if (previewer.DrawObject != characterBase) continue; previewer.Dispose(); @@ -518,7 +520,7 @@ public partial class ModEditWindow for (var i = ColorTablePreviewers.Count; i-- > 0;) { var previewer = ColorTablePreviewers[i]; - if ((nint)previewer.DrawObject != characterBase) + if (previewer.DrawObject != characterBase) continue; previewer.Dispose(); @@ -663,7 +665,7 @@ public partial class ModEditWindow UpdateConstants(); } - public MtrlTab(ModEditWindow edit, MtrlFile file, string filePath, bool writable) + public unsafe MtrlTab(ModEditWindow edit, MtrlFile file, string filePath, bool writable) { _edit = edit; Mtrl = file; @@ -673,16 +675,16 @@ public partial class ModEditWindow LoadShpk(FindAssociatedShpk(out _, out _)); if (writable) { - _edit._gameEvents.CharacterBaseDestructor += UnbindFromDrawObjectMaterialInstances; + _edit._characterBaseDestructor.Subscribe(UnbindFromDrawObjectMaterialInstances, CharacterBaseDestructor.Priority.MtrlTab); BindToMaterialInstances(); } } - public void Dispose() + public unsafe void Dispose() { UnbindFromMaterialInstances(); if (Writable) - _edit._gameEvents.CharacterBaseDestructor -= UnbindFromDrawObjectMaterialInstances; + _edit._characterBaseDestructor.Unsubscribe(UnbindFromDrawObjectMaterialInstances); } public bool Valid diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index df379a1c..8a4bd52b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -13,8 +13,8 @@ using Penumbra.Communication; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.Import.Textures; +using Penumbra.Interop.Hooks; using Penumbra.Interop.ResourceTree; -using Penumbra.Interop.Services; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -32,20 +32,20 @@ public partial class ModEditWindow : Window, IDisposable { private const string WindowBaseLabel = "###SubModEdit"; - private readonly PerformanceTracker _performance; - private readonly ModEditor _editor; - private readonly Configuration _config; - private readonly ItemSwapTab _itemSwapTab; - private readonly MetaFileManager _metaFileManager; - private readonly ActiveCollections _activeCollections; - private readonly StainService _stainService; - private readonly ModMergeTab _modMergeTab; - private readonly CommunicatorService _communicator; - private readonly IDragDropManager _dragDropManager; - private readonly GameEventManager _gameEvents; - private readonly IDataManager _gameData; - private readonly IFramework _framework; - private readonly IObjectTable _objects; + private readonly PerformanceTracker _performance; + private readonly ModEditor _editor; + private readonly Configuration _config; + private readonly ItemSwapTab _itemSwapTab; + private readonly MetaFileManager _metaFileManager; + private readonly ActiveCollections _activeCollections; + private readonly StainService _stainService; + private readonly ModMergeTab _modMergeTab; + private readonly CommunicatorService _communicator; + private readonly IDragDropManager _dragDropManager; + private readonly IDataManager _gameData; + private readonly IFramework _framework; + private readonly IObjectTable _objects; + private readonly CharacterBaseDestructor _characterBaseDestructor; private Mod? _mod; private Vector2 _iconSize = Vector2.Zero; @@ -565,26 +565,26 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, - CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, GameEventManager gameEvents, - ChangedItemDrawer changedItemDrawer, IObjectTable objects, IFramework framework) + CommunicatorService communicator, TextureManager textures, IDragDropManager dragDropManager, + ChangedItemDrawer changedItemDrawer, IObjectTable objects, IFramework framework, CharacterBaseDestructor characterBaseDestructor) : base(WindowBaseLabel) { - _performance = performance; - _itemSwapTab = itemSwapTab; - _gameData = gameData; - _config = config; - _editor = editor; - _metaFileManager = metaFileManager; - _stainService = stainService; - _activeCollections = activeCollections; - _modMergeTab = modMergeTab; - _communicator = communicator; - _dragDropManager = dragDropManager; - _textures = textures; - _fileDialog = fileDialog; - _gameEvents = gameEvents; - _objects = objects; - _framework = framework; + _performance = performance; + _itemSwapTab = itemSwapTab; + _gameData = gameData; + _config = config; + _editor = editor; + _metaFileManager = metaFileManager; + _stainService = stainService; + _activeCollections = activeCollections; + _modMergeTab = modMergeTab; + _communicator = communicator; + _dragDropManager = dragDropManager; + _textures = textures; + _fileDialog = fileDialog; + _objects = objects; + _framework = framework; + _characterBaseDestructor = characterBaseDestructor; _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); @@ -598,12 +598,12 @@ public partial class ModEditWindow : Window, IDisposable _resourceTreeFactory = resourceTreeFactory; _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); - _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ModEditWindow); + _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModEditWindow); } public void Dispose() { - _communicator.ModPathChanged.Unsubscribe(OnModPathChanged); + _communicator.ModPathChanged.Unsubscribe(OnModPathChange); _editor?.Dispose(); _materialTab.Dispose(); _modelTab.Dispose(); @@ -613,7 +613,7 @@ public partial class ModEditWindow : Window, IDisposable _center.Dispose(); } - private void OnModPathChanged(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) + private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) { if (type is ModPathChangeType.Reloaded or ModPathChangeType.Moved) ChangeMod(mod); diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 16353828..a0073d05 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -11,6 +11,18 @@ "Unosquare.Swan.Lite": "3.0.0" } }, + "Microsoft.CodeAnalysis.Common": { + "type": "Direct", + "requested": "[4.8.0, )", + "resolved": "4.8.0", + "contentHash": "/jR+e/9aT+BApoQJABlVCKnnggGQbvGh7BKq2/wI1LamxC+LbzhcLj4Vj7gXCofl1n4E521YfF9w0WcASGg/KA==", + "dependencies": { + "Microsoft.CodeAnalysis.Analyzers": "3.3.4", + "System.Collections.Immutable": "7.0.0", + "System.Reflection.Metadata": "7.0.0", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, "Microsoft.Extensions.DependencyInjection": { "type": "Direct", "requested": "[7.0.0, )", @@ -36,6 +48,11 @@ "System.Text.Encoding.CodePages": "5.0.0" } }, + "Microsoft.CodeAnalysis.Analyzers": { + "type": "Transitive", + "resolved": "3.3.4", + "contentHash": "AxkxcPR+rheX0SmvpLVIGLhOUXAKG56a64kV9VQZ4y9gR9ZmPXnqZvHJnmwLSwzrEP6junUF11vuc+aqo5r68g==" + }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", "resolved": "7.0.0", @@ -46,10 +63,23 @@ "resolved": "5.0.0", "contentHash": "VyPlqzH2wavqquTcYpkIIAQ6WdenuKoFN0BdYBbCWsclXacSOHNQn66Gt4z5NBqEYW0FAPm5rlvki9ZiCij5xQ==" }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "7.0.0", + "contentHash": "dQPcs0U1IKnBdRDBkrCTi1FoajSTBzLcVTpjO4MBCMC7f4pDOIPzgBoX8JjG7X6uZRJ8EBxsi8+DR1JuwjnzOQ==" + }, + "System.Reflection.Metadata": { + "type": "Transitive", + "resolved": "7.0.0", + "contentHash": "MclTG61lsD9sYdpNz9xsKBzjsmsfCtcMZYXz/IUr2zlhaTaABonlr1ESeompTgM+Xk+IwtGYU7/voh3YWB/fWw==", + "dependencies": { + "System.Collections.Immutable": "7.0.0" + } + }, "System.Runtime.CompilerServices.Unsafe": { "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "ZD9TMpsmYJLrxbbmdvhwt9YEgG5WntEnZ/d1eH8JBX9LBp+Ju8BSBhUGbZMNVHHomWo2KVImJhTDl2hIgw/6MA==" + "resolved": "6.0.0", + "contentHash": "/iUeP3tq1S0XdNNoMz5C9twLSrM/TH+qElHkXWaPvuNOt+99G75NrV0OS2EqHx5wMN7popYjpc8oTjC1y16DLg==" }, "System.Text.Encoding.CodePages": { "type": "Transitive", From 68c782f0b9317a1230d1d1b529b378a1fb356117 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 1 Jan 2024 00:17:15 +0100 Subject: [PATCH 0304/1381] Move all meta hooks to own classes. --- Penumbra/Interop/CharacterBaseVTables.cs | 24 ++ .../Interop/Hooks/Meta/CalculateHeight.cs | 31 +++ .../Interop/Hooks/Meta/ChangeCustomize.cs | 34 +++ Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs | 36 +++ .../Interop/Hooks/Meta/ModelLoadComplete.cs | 30 +++ .../Interop/Hooks/Meta/RspSetupCharacter.cs | 37 +++ Penumbra/Interop/Hooks/Meta/SetupVisor.cs | 35 +++ Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 36 +++ .../PathResolving/CollectionResolver.cs | 4 +- .../IdentifiedCollectionCache.cs | 4 +- Penumbra/Interop/PathResolving/MetaState.cs | 223 ++++-------------- 11 files changed, 314 insertions(+), 180 deletions(-) create mode 100644 Penumbra/Interop/CharacterBaseVTables.cs create mode 100644 Penumbra/Interop/Hooks/Meta/CalculateHeight.cs create mode 100644 Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs create mode 100644 Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs create mode 100644 Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs create mode 100644 Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs create mode 100644 Penumbra/Interop/Hooks/Meta/SetupVisor.cs create mode 100644 Penumbra/Interop/Hooks/Meta/UpdateModel.cs diff --git a/Penumbra/Interop/CharacterBaseVTables.cs b/Penumbra/Interop/CharacterBaseVTables.cs new file mode 100644 index 00000000..40b9a588 --- /dev/null +++ b/Penumbra/Interop/CharacterBaseVTables.cs @@ -0,0 +1,24 @@ +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop; + +public sealed unsafe class CharacterBaseVTables : IService +{ + [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] + public readonly nint* HumanVTable = null!; + + [Signature(Sigs.WeaponVTable, ScanType = ScanType.StaticAddress)] + public readonly nint* WeaponVTable = null!; + + [Signature(Sigs.DemiHumanVTable, ScanType = ScanType.StaticAddress)] + public readonly nint* DemiHumanVTable = null!; + + [Signature(Sigs.MonsterVTable, ScanType = ScanType.StaticAddress)] + public readonly nint* MonsterVTable = null!; + + public CharacterBaseVTables(IGameInteropProvider interop) + => interop.InitializeFromAttributes(this); +} diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs new file mode 100644 index 00000000..2fd87f6e --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -0,0 +1,31 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Interop.PathResolving; +using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class CalculateHeight : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public CalculateHeight(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, true); + } + + public delegate ulong Delegate(Character* character); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private ulong Detour(Character* character) + { + var collection = _collectionResolver.IdentifyCollection((GameObject*)character, true); + using var cmp = _metaState.ResolveRspData(collection.ModCollection); + var ret = Task.Result.Original.Invoke(character); + Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)character:X} -> {ret}."); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs new file mode 100644 index 00000000..81f6d552 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -0,0 +1,34 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class ChangeCustomize : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public ChangeCustomize(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Change Customize", Sigs.ChangeCustomize, Detour, true); + } + + public delegate bool Delegate(Human* human, CustomizeArray* data, byte skipEquipment); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private bool Detour(Human* human, CustomizeArray* data, byte skipEquipment) + { + _metaState.CustomizeChangeCollection = _collectionResolver.IdentifyCollection((DrawObject*)human, true); + using var cmp = _metaState.ResolveRspData(_metaState.CustomizeChangeCollection.ModCollection); + using var decal1 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, true); + using var decal2 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, false); + var ret = Task.Result.Original.Invoke(human, data, skipEquipment); + Penumbra.Log.Excessive($"[Change Customize] Invoked on {(nint)human:X} with {(nint)data:X}, {skipEquipment} -> {ret}."); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs new file mode 100644 index 00000000..c1b6eacc --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs @@ -0,0 +1,36 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class GetEqpIndirect : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public GetEqpIndirect(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Get EQP Indirect", Sigs.GetEqpIndirect, Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject) + { + if ((*(byte*)(drawObject + Offsets.GetEqpIndirectSkip1) & 1) == 0 || *(ulong*)(drawObject + Offsets.GetEqpIndirectSkip2) == 0) + return; + + Penumbra.Log.Excessive($"[Get EQP Indirect] Invoked on {(nint)drawObject:X}."); + // Shortcut because this is also called all the time. + // Same thing is checked at the beginning of the original function. + + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + using var eqp = _metaState.ResolveEqpData(collection.ModCollection); + Task.Result.Original(drawObject); + } +} diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs new file mode 100644 index 00000000..9f191fdd --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -0,0 +1,30 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class ModelLoadComplete : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public ModelLoadComplete(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState, CharacterBaseVTables vtables) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Model Load Complete", vtables.HumanVTable[58], Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject) + { + Penumbra.Log.Excessive($"[Model Load Complete] Invoked on {(nint)drawObject:X}."); + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + using var eqp = _metaState.ResolveEqpData(collection.ModCollection); + using var eqdp = _metaState.ResolveEqdpData(collection.ModCollection, MetaState.GetDrawObjectGenderRace((nint)drawObject), true, true); + Task.Result.Original(drawObject); + } +} diff --git a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs new file mode 100644 index 00000000..8f8f1d78 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs @@ -0,0 +1,37 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class RspSetupCharacter : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public RspSetupCharacter(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("RSP Setup Character", Sigs.RspSetupCharacter, Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject, nint unk2, float unk3, nint unk4, byte unk5); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject, nint unk2, float unk3, nint unk4, byte unk5) + { + Penumbra.Log.Excessive($"[RSP Setup Character] Invoked on {(nint)drawObject:X} with {unk2}, {unk3}, {unk4}, {unk5}."); + // Skip if we are coming from ChangeCustomize. + if (_metaState.CustomizeChangeCollection.Valid) + { + Task.Result.Original.Invoke(drawObject, unk2, unk3, unk4, unk5); + return; + } + + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + using var cmp = _metaState.ResolveRspData(collection.ModCollection); + Task.Result.Original.Invoke(drawObject, unk2, unk3, unk4, unk5); + } +} diff --git a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs new file mode 100644 index 00000000..e451f118 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs @@ -0,0 +1,35 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +/// +/// GMP. This gets called every time when changing visor state, and it accesses the gmp file itself, +/// but it only applies a changed gmp file after a redraw for some reason. +/// +public sealed unsafe class SetupVisor : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public SetupVisor(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Setup Visor", Sigs.SetupVisor, Detour, true); + } + + public delegate byte Delegate(DrawObject* drawObject, ushort modelId, byte visorState); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private byte Detour(DrawObject* drawObject, ushort modelId, byte visorState) + { + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + using var gmp = _metaState.ResolveGmpData(collection.ModCollection); + var ret = Task.Result.Original.Invoke(drawObject, modelId, visorState); + Penumbra.Log.Excessive($"[Setup Visor] Invoked on {(nint)drawObject:X} with {modelId}, {visorState} -> {ret}."); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs new file mode 100644 index 00000000..c169ead2 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs @@ -0,0 +1,36 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class UpdateModel : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public UpdateModel(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Update Model", Sigs.UpdateModel, Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject) + { + // Shortcut because this is called all the time. + // Same thing is checked at the beginning of the original function. + if (*(int*)(drawObject + Offsets.UpdateModelSkip) == 0) + return; + + Penumbra.Log.Excessive($"[Update Model] Invoked on {(nint)drawObject:X}."); + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + using var eqp = _metaState.ResolveEqpData(collection.ModCollection); + using var eqdp = _metaState.ResolveEqdpData(collection.ModCollection, MetaState.GetDrawObjectGenderRace((nint)drawObject), true, true); + Task.Result.Original.Invoke(drawObject); + } +} diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index c649147a..1a715f13 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -24,12 +24,12 @@ public sealed unsafe class CollectionResolver( CollectionManager collectionManager, TempCollectionManager tempCollections, DrawObjectState drawObjectState, - HumanModelList humanModels) + HumanModelList humanModels) : IService { /// /// Get the collection applying to the current player character - /// or the Yourself or Default collection if no player exists. + /// or the 'Yourself' or 'Default' collection if no player exists. /// public ModCollection PlayerCollection() { diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 3e7171f8..b944011d 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -20,8 +20,8 @@ public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint A public IdentifiedCollectionCache(IClientState clientState, CommunicatorService communicator, CharacterDestructor characterDestructor) { - _clientState = clientState; - _communicator = communicator; + _clientState = clientState; + _communicator = communicator; _characterDestructor = characterDestructor; _communicator.CollectionChange.Subscribe(CollectionChangeClear, CollectionChange.Priority.IdentifiedCollectionCache); diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 9ef291c7..9d899648 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -1,13 +1,7 @@ -using Dalamud.Hooking; -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.Game.Character; -using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Api.Enums; -using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks; @@ -15,10 +9,8 @@ using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Services; using Penumbra.String.Classes; -using Penumbra.Util; using ObjectType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; -using static Penumbra.GameData.Enums.GenderRace; namespace Penumbra.Interop.PathResolving; @@ -44,56 +36,40 @@ namespace Penumbra.Interop.PathResolving; // ChangeCustomize and RspSetupCharacter, which is hooked here, as well as Character.CalculateHeight. // GMP Entries seem to be only used by "48 8B ?? 53 55 57 48 83 ?? ?? 48 8B", which has a DrawObject as its first parameter. -public unsafe class MetaState : IDisposable +public sealed unsafe class MetaState : IDisposable { - [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _humanVTable = null!; - private readonly Configuration _config; private readonly CommunicatorService _communicator; - private readonly PerformanceTracker _performance; private readonly CollectionResolver _collectionResolver; private readonly ResourceLoader _resources; private readonly CharacterUtility _characterUtility; private readonly CreateCharacterBase _createCharacterBase; + public ResolveData CustomizeChangeCollection = ResolveData.Invalid; + private ResolveData _lastCreatedCollection = ResolveData.Invalid; - private ResolveData _customizeChangeCollection = ResolveData.Invalid; private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; - public MetaState(PerformanceTracker performance, CommunicatorService communicator, CollectionResolver collectionResolver, - ResourceLoader resources, CreateCharacterBase createCharacterBase, CharacterUtility characterUtility, Configuration config, - IGameInteropProvider interop) + public MetaState(CommunicatorService communicator, CollectionResolver collectionResolver, + ResourceLoader resources, CreateCharacterBase createCharacterBase, CharacterUtility characterUtility, Configuration config) { - _performance = performance; _communicator = communicator; _collectionResolver = collectionResolver; _resources = resources; _createCharacterBase = createCharacterBase; _characterUtility = characterUtility; _config = config; - interop.InitializeFromAttributes(this); - _calculateHeightHook = - interop.HookFromAddress((nint)Character.MemberFunctionPointers.CalculateHeight, CalculateHeightDetour); - _onModelLoadCompleteHook = interop.HookFromAddress(_humanVTable[58], OnModelLoadCompleteDetour); - _getEqpIndirectHook.Enable(); - _updateModelsHook.Enable(); - _onModelLoadCompleteHook.Enable(); - _setupVisorHook.Enable(); - _rspSetupCharacterHook.Enable(); - _changeCustomize.Enable(); - _calculateHeightHook.Enable(); _createCharacterBase.Subscribe(OnCreatingCharacterBase, CreateCharacterBase.Priority.MetaState); - _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.MetaState); + _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.MetaState); } public bool HandleDecalFile(ResourceType type, Utf8GamePath gamePath, out ResolveData resolveData) { if (type == ResourceType.Tex - && (_lastCreatedCollection.Valid || _customizeChangeCollection.Valid) + && (_lastCreatedCollection.Valid || CustomizeChangeCollection.Valid) && gamePath.Path.Substring("chara/common/texture/".Length).StartsWith("decal"u8)) { - resolveData = _lastCreatedCollection.Valid ? _lastCreatedCollection : _customizeChangeCollection; + resolveData = _lastCreatedCollection.Valid ? _lastCreatedCollection : CustomizeChangeCollection; return true; } @@ -102,30 +78,49 @@ public unsafe class MetaState : IDisposable } public DisposableContainer ResolveEqdpData(ModCollection collection, GenderRace race, bool equipment, bool accessory) - { - var races = race.Dependencies(); + => (equipment, accessory) switch + { + (true, true) => new DisposableContainer(race.Dependencies().SelectMany(r => new[] + { + collection.TemporarilySetEqdpFile(_characterUtility, r, false), + collection.TemporarilySetEqdpFile(_characterUtility, r, true), + })), + (true, false) => new DisposableContainer(race.Dependencies() + .Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, false))), + (false, true) => new DisposableContainer(race.Dependencies() + .Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, true))), + _ => DisposableContainer.Empty, + }; - var equipmentEnumerable = equipment - ? races.Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, false)) - : Array.Empty().AsEnumerable(); - var accessoryEnumerable = accessory - ? races.Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, true)) - : Array.Empty().AsEnumerable(); - return new DisposableContainer(equipmentEnumerable.Concat(accessoryEnumerable)); - } + public MetaList.MetaReverter ResolveEqpData(ModCollection collection) + => collection.TemporarilySetEqpFile(_characterUtility); + + public MetaList.MetaReverter ResolveGmpData(ModCollection collection) + => collection.TemporarilySetGmpFile(_characterUtility); + + public MetaList.MetaReverter ResolveRspData(ModCollection collection) + => collection.TemporarilySetCmpFile(_characterUtility); + + public DecalReverter ResolveDecal(ResolveData resolve, bool which) + => new(_config, _characterUtility, _resources, resolve, which); public static GenderRace GetHumanGenderRace(nint human) => (GenderRace)((Human*)human)->RaceSexId; + public static GenderRace GetDrawObjectGenderRace(nint drawObject) + { + var draw = (DrawObject*)drawObject; + if (draw->Object.GetObjectType() != ObjectType.CharacterBase) + return GenderRace.Unknown; + + var c = (CharacterBase*)drawObject; + return c->GetModelType() == CharacterBase.ModelType.Human + ? GetHumanGenderRace(drawObject) + : GenderRace.Unknown; + } + public void Dispose() { - _getEqpIndirectHook.Dispose(); - _updateModelsHook.Dispose(); - _onModelLoadCompleteHook.Dispose(); - _setupVisorHook.Dispose(); - _rspSetupCharacterHook.Dispose(); - _changeCustomize.Dispose(); - _calculateHeightHook.Dispose(); _createCharacterBase.Unsubscribe(OnCreatingCharacterBase); _createCharacterBase.Unsubscribe(OnCharacterBaseCreated); } @@ -135,10 +130,10 @@ public unsafe class MetaState : IDisposable _lastCreatedCollection = _collectionResolver.IdentifyLastGameObjectCollection(true); if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero) _communicator.CreatingCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, - _lastCreatedCollection.ModCollection.Name, (nint) modelCharaId, (nint) customize, (nint) equipData); + _lastCreatedCollection.ModCollection.Name, (nint)modelCharaId, (nint)customize, (nint)equipData); var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, - UsesDecal(*(uint*)modelCharaId, (nint) customize)); + UsesDecal(*(uint*)modelCharaId, (nint)customize)); var cmp = _lastCreatedCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); _characterBaseCreateMetaChanges.Dispose(); // Should always be empty. _characterBaseCreateMetaChanges = new DisposableContainer(decal, cmp); @@ -154,134 +149,10 @@ public unsafe class MetaState : IDisposable _lastCreatedCollection = ResolveData.Invalid; } - private delegate void OnModelLoadCompleteDelegate(nint drawObject); - private readonly Hook _onModelLoadCompleteHook; - - private void OnModelLoadCompleteDetour(nint drawObject) - { - var collection = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var eqp = collection.ModCollection.TemporarilySetEqpFile(_characterUtility); - using var eqdp = ResolveEqdpData(collection.ModCollection, GetDrawObjectGenderRace(drawObject), true, true); - _onModelLoadCompleteHook.Original.Invoke(drawObject); - } - - private delegate void UpdateModelDelegate(nint drawObject); - - [Signature(Sigs.UpdateModel, DetourName = nameof(UpdateModelsDetour))] - private readonly Hook _updateModelsHook = null!; - - private void UpdateModelsDetour(nint drawObject) - { - // Shortcut because this is called all the time. - // Same thing is checked at the beginning of the original function. - if (*(int*)(drawObject + Offsets.UpdateModelSkip) == 0) - return; - - using var performance = _performance.Measure(PerformanceType.UpdateModels); - - var collection = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var eqp = collection.ModCollection.TemporarilySetEqpFile(_characterUtility); - using var eqdp = ResolveEqdpData(collection.ModCollection, GetDrawObjectGenderRace(drawObject), true, true); - _updateModelsHook.Original.Invoke(drawObject); - } - - private static GenderRace GetDrawObjectGenderRace(nint drawObject) - { - var draw = (DrawObject*)drawObject; - if (draw->Object.GetObjectType() != ObjectType.CharacterBase) - return Unknown; - - var c = (CharacterBase*)drawObject; - return c->GetModelType() == CharacterBase.ModelType.Human - ? GetHumanGenderRace(drawObject) - : Unknown; - } - - [Signature(Sigs.GetEqpIndirect, DetourName = nameof(GetEqpIndirectDetour))] - private readonly Hook _getEqpIndirectHook = null!; - - private void GetEqpIndirectDetour(nint drawObject) - { - // Shortcut because this is also called all the time. - // Same thing is checked at the beginning of the original function. - if ((*(byte*)(drawObject + Offsets.GetEqpIndirectSkip1) & 1) == 0 || *(ulong*)(drawObject + Offsets.GetEqpIndirectSkip2) == 0) - return; - - using var performance = _performance.Measure(PerformanceType.GetEqp); - var resolveData = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var eqp = resolveData.ModCollection.TemporarilySetEqpFile(_characterUtility); - _getEqpIndirectHook.Original(drawObject); - } - - - // GMP. This gets called every time when changing visor state, and it accesses the gmp file itself, - // but it only applies a changed gmp file after a redraw for some reason. - private delegate byte SetupVisorDelegate(nint drawObject, ushort modelId, byte visorState); - - [Signature(Sigs.SetupVisor, DetourName = nameof(SetupVisorDetour))] - private readonly Hook _setupVisorHook = null!; - - private byte SetupVisorDetour(nint drawObject, ushort modelId, byte visorState) - { - using var performance = _performance.Measure(PerformanceType.SetupVisor); - var resolveData = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var gmp = resolveData.ModCollection.TemporarilySetGmpFile(_characterUtility); - return _setupVisorHook.Original(drawObject, modelId, visorState); - } - - // RSP - private delegate void RspSetupCharacterDelegate(nint drawObject, nint unk2, float unk3, nint unk4, byte unk5); - - [Signature(Sigs.RspSetupCharacter, DetourName = nameof(RspSetupCharacterDetour))] - private readonly Hook _rspSetupCharacterHook = null!; - - private void RspSetupCharacterDetour(nint drawObject, nint unk2, float unk3, nint unk4, byte unk5) - { - if (_customizeChangeCollection.Valid) - { - _rspSetupCharacterHook.Original(drawObject, unk2, unk3, unk4, unk5); - } - else - { - using var performance = _performance.Measure(PerformanceType.SetupCharacter); - var resolveData = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var cmp = resolveData.ModCollection.TemporarilySetCmpFile(_characterUtility); - _rspSetupCharacterHook.Original(drawObject, unk2, unk3, unk4, unk5); - } - } - - private delegate ulong CalculateHeightDelegate(Character* character); - - private readonly Hook _calculateHeightHook = null!; - - private ulong CalculateHeightDetour(Character* character) - { - var resolveData = _collectionResolver.IdentifyCollection((GameObject*)character, true); - using var cmp = resolveData.ModCollection.TemporarilySetCmpFile(_characterUtility); - return _calculateHeightHook.Original(character); - } - - private delegate bool ChangeCustomizeDelegate(nint human, nint data, byte skipEquipment); - - [Signature(Sigs.ChangeCustomize, DetourName = nameof(ChangeCustomizeDetour))] - private readonly Hook _changeCustomize = null!; - - private bool ChangeCustomizeDetour(nint human, nint data, byte skipEquipment) - { - using var performance = _performance.Measure(PerformanceType.ChangeCustomize); - _customizeChangeCollection = _collectionResolver.IdentifyCollection((DrawObject*)human, true); - using var cmp = _customizeChangeCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); - using var decals = new DecalReverter(_config, _characterUtility, _resources, _customizeChangeCollection, true); - using var decal2 = new DecalReverter(_config, _characterUtility, _resources, _customizeChangeCollection, false); - var ret = _changeCustomize.Original(human, data, skipEquipment); - _customizeChangeCollection = ResolveData.Invalid; - return ret; - } - /// /// Check the customize array for the FaceCustomization byte and the last bit of that. /// Also check for humans. /// - public static bool UsesDecal(uint modelId, nint customizeData) + private static bool UsesDecal(uint modelId, nint customizeData) => modelId == 0 && ((byte*)customizeData)[12] > 0x7F; } From bc068f991389d2adcaa05b26d2877ddf6acd63bc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 1 Jan 2024 00:48:20 +0100 Subject: [PATCH 0305/1381] Fix offsets. --- Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs | 7 +++---- Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs index c1b6eacc..8ffc050f 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs @@ -22,13 +22,12 @@ public sealed unsafe class GetEqpIndirect : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void Detour(DrawObject* drawObject) { - if ((*(byte*)(drawObject + Offsets.GetEqpIndirectSkip1) & 1) == 0 || *(ulong*)(drawObject + Offsets.GetEqpIndirectSkip2) == 0) + // Shortcut because this is also called all the time. + // Same thing is checked at the beginning of the original function. + if ((*(byte*)((nint)drawObject + Offsets.GetEqpIndirectSkip1) & 1) == 0 || *(ulong*)((nint)drawObject + Offsets.GetEqpIndirectSkip2) == 0) return; Penumbra.Log.Excessive($"[Get EQP Indirect] Invoked on {(nint)drawObject:X}."); - // Shortcut because this is also called all the time. - // Same thing is checked at the beginning of the original function. - var collection = _collectionResolver.IdentifyCollection(drawObject, true); using var eqp = _metaState.ResolveEqpData(collection.ModCollection); Task.Result.Original(drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs index c169ead2..786ad5f2 100644 --- a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs @@ -24,7 +24,7 @@ public sealed unsafe class UpdateModel : FastHook { // Shortcut because this is called all the time. // Same thing is checked at the beginning of the original function. - if (*(int*)(drawObject + Offsets.UpdateModelSkip) == 0) + if (*(int*)((nint)drawObject + Offsets.UpdateModelSkip) == 0) return; Penumbra.Log.Excessive($"[Update Model] Invoked on {(nint)drawObject:X}."); From 518117b25a5a31c5b1347541c78c5c0f57aeb98d Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 11:01:31 +1100 Subject: [PATCH 0306/1381] Add submeshless support --- Penumbra/Import/Models/Export/MeshExporter.cs | 34 +++++++++++-------- Penumbra/Import/Models/ModelManager.cs | 6 +++- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 06ca747b..7b51ca31 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -34,7 +34,6 @@ public class MeshExporter } } - // TODO: replace bonenamemap with a gltfskeleton public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, GltfSkeleton? skeleton) { var self = new MeshExporter(mdl, lod, meshIndex, skeleton?.Names); @@ -74,7 +73,7 @@ public class MeshExporter private Dictionary BuildBoneIndexMap(Dictionary boneNameMap) { - // todo: BoneTableIndex of 255 means null? if so, it should probably feed into the attributes we assign... + // TODO: BoneTableIndex of 255 means null? if so, it should probably feed into the attributes we assign... var xivBoneTable = _mdl.BoneTables[XivMesh.BoneTableIndex]; var indexMap = new Dictionary(); @@ -97,20 +96,25 @@ public class MeshExporter var indices = BuildIndices(); var vertices = BuildVertices(); - // TODO: handle SubMeshCount = 0 + // NOTE: Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh, so we're specifying the index base relative to the mesh's base. + + if (XivMesh.SubMeshCount == 0) + return [BuildMesh(indices, vertices, 0, (int)XivMesh.IndexCount)]; return _mdl.SubMeshes .Skip(XivMesh.SubMeshIndex) .Take(XivMesh.SubMeshCount) - .Select(submesh => BuildSubMesh(submesh, indices, vertices)) + .Select(submesh => BuildMesh(indices, vertices, (int)(submesh.IndexOffset - XivMesh.StartIndex), (int)submesh.IndexCount)) .ToArray(); } - private IMeshBuilder BuildSubMesh(MdlStructs.SubmeshStruct submesh, IReadOnlyList indices, IReadOnlyList vertices) + private IMeshBuilder BuildMesh( + IReadOnlyList indices, + IReadOnlyList vertices, + int indexBase, + int indexCount + ) { - // Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh. - var startIndex = (int)(submesh.IndexOffset - XivMesh.StartIndex); - var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( typeof(MaterialBuilder), _geometryType, @@ -131,12 +135,12 @@ public class MeshExporter var gltfIndices = new List(); // All XIV meshes use triangle lists. - for (var indexOffset = 0; indexOffset < submesh.IndexCount; indexOffset += 3) + for (var indexOffset = 0; indexOffset < indexCount; indexOffset += 3) { var (a, b, c) = primitiveBuilder.AddTriangle( - vertices[indices[indexOffset + startIndex + 0]], - vertices[indices[indexOffset + startIndex + 1]], - vertices[indices[indexOffset + startIndex + 2]] + vertices[indices[indexBase + indexOffset + 0]], + vertices[indices[indexBase + indexOffset + 1]], + vertices[indices[indexBase + indexOffset + 2]] ); gltfIndices.AddRange([a, b, c]); } @@ -157,8 +161,8 @@ public class MeshExporter .Take((int)shapeMesh.ShapeValueCount) ) .Where(shapeValue => - shapeValue.BaseIndicesIndex >= startIndex - && shapeValue.BaseIndicesIndex < startIndex + submesh.IndexCount + shapeValue.BaseIndicesIndex >= indexBase + && shapeValue.BaseIndicesIndex < indexBase + indexCount ) .ToList(); @@ -169,7 +173,7 @@ public class MeshExporter foreach (var shapeValue in shapeValues) morphBuilder.SetVertex( - primitiveVertices[gltfIndices[shapeValue.BaseIndicesIndex - startIndex]].GetGeometry(), + primitiveVertices[gltfIndices[shapeValue.BaseIndicesIndex - indexBase]].GetGeometry(), vertices[shapeValue.ReplacingVertexIndex].GetGeometry() ); } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index a56d7168..4f761549 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -73,17 +73,21 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public void Execute(CancellationToken cancel) { + Penumbra.Log.Debug("Reading skeleton."); var xivSkeleton = BuildSkeleton(cancel); + + Penumbra.Log.Debug("Converting model."); var model = ModelExporter.Export(_mdl, xivSkeleton); + Penumbra.Log.Debug("Building scene."); var scene = new SceneBuilder(); model.AddToScene(scene); + Penumbra.Log.Debug("Saving."); var gltfModel = scene.ToGltf2(); gltfModel.SaveGLTF(_outputPath); } - // TODO: this should be moved to a seperate model converter or something private XivSkeleton? BuildSkeleton(CancellationToken cancel) { if (_sklb == null) From 08ed3ca447149d7cc3c70ca99a74f6c6dfe1d108 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 11:31:38 +1100 Subject: [PATCH 0307/1381] Handle mesh skeleton edge cases --- Penumbra/Import/Models/Export/MeshExporter.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 7b51ca31..e835fe62 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -69,11 +69,18 @@ public class MeshExporter _geometryType = GetGeometryType(usages); _materialType = GetMaterialType(usages); _skinningType = GetSkinningType(usages); + + // If there's skinning usages but no bone mapping, there's probably something wrong with the data. + if (_skinningType != typeof(VertexEmpty) && _boneIndexMap == null) + Penumbra.Log.Warning($"Mesh {meshIndex} has skinned vertex usages but no bone information was provided."); } - private Dictionary BuildBoneIndexMap(Dictionary boneNameMap) + private Dictionary? BuildBoneIndexMap(Dictionary boneNameMap) { - // TODO: BoneTableIndex of 255 means null? if so, it should probably feed into the attributes we assign... + // A BoneTableIndex of 255 means that this mesh is not skinned. + if (XivMesh.BoneTableIndex == 255) + return null; + var xivBoneTable = _mdl.BoneTables[XivMesh.BoneTableIndex]; var indexMap = new Dictionary(); @@ -82,8 +89,7 @@ public class MeshExporter { var boneName = _mdl.Bones[xivBoneIndex]; if (!boneNameMap.TryGetValue(boneName, out var gltfBoneIndex)) - // TODO: handle - i think this is a hard failure, it means that a bone name in the model doesn't exist in the armature. - throw new Exception($"looking for {boneName} in {string.Join(", ", boneNameMap.Keys)}"); + throw new Exception($"Armature does not contain bone \"{boneName}\" requested by mesh {_meshIndex}."); indexMap.Add(xivBoneIndex, gltfBoneIndex); } From a059942bb2c4d4ae6efbbef19a92b36a512695a8 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 12:57:56 +1100 Subject: [PATCH 0308/1381] Clean up + docs --- Penumbra/Import/Models/Export/MeshExporter.cs | 52 ++++++++++++++----- .../Import/Models/Export/ModelExporter.cs | 3 ++ Penumbra/Import/Models/Export/Skeleton.cs | 7 +++ Penumbra/Import/Models/ModelManager.cs | 1 + 4 files changed, 49 insertions(+), 14 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index e835fe62..cf7cc975 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using Lumina.Data.Parsing; using Lumina.Extensions; +using OtterGui; using Penumbra.GameData.Files; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; @@ -25,7 +26,6 @@ public class MeshExporter public void AddToScene(SceneBuilder scene) { - // TODO: throw if mesh has skinned vertices but no joints are available? foreach (var mesh in _meshes) if (_joints == null) scene.AddRigidMesh(mesh, Matrix4x4.Identity); @@ -73,8 +73,11 @@ public class MeshExporter // If there's skinning usages but no bone mapping, there's probably something wrong with the data. if (_skinningType != typeof(VertexEmpty) && _boneIndexMap == null) Penumbra.Log.Warning($"Mesh {meshIndex} has skinned vertex usages but no bone information was provided."); + + Penumbra.Log.Debug($"Mesh {meshIndex} using vertex types geometry: {_geometryType.Name}, material: {_materialType.Name}, skinning: {_skinningType.Name}"); } + /// Build a mapping between indices in this mesh's bone table (if any), and the glTF joint indices provdied. private Dictionary? BuildBoneIndexMap(Dictionary boneNameMap) { // A BoneTableIndex of 255 means that this mesh is not skinned. @@ -97,6 +100,7 @@ public class MeshExporter return indexMap; } + /// Build glTF meshes for this XIV mesh. private IMeshBuilder[] BuildMeshes() { var indices = BuildIndices(); @@ -105,16 +109,19 @@ public class MeshExporter // NOTE: Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh, so we're specifying the index base relative to the mesh's base. if (XivMesh.SubMeshCount == 0) - return [BuildMesh(indices, vertices, 0, (int)XivMesh.IndexCount)]; + return [BuildMesh($"mesh {_meshIndex}", indices, vertices, 0, (int)XivMesh.IndexCount)]; return _mdl.SubMeshes .Skip(XivMesh.SubMeshIndex) .Take(XivMesh.SubMeshCount) - .Select(submesh => BuildMesh(indices, vertices, (int)(submesh.IndexOffset - XivMesh.StartIndex), (int)submesh.IndexCount)) + .WithIndex() + .Select(submesh => BuildMesh($"mesh {_meshIndex}.{submesh.Index}", indices, vertices, (int)(submesh.Value.IndexOffset - XivMesh.StartIndex), (int)submesh.Value.IndexCount)) .ToArray(); } + /// Build a mesh from the provided indices and vertices. A subset of the full indices may be built by providing an index base and count. private IMeshBuilder BuildMesh( + string name, IReadOnlyList indices, IReadOnlyList vertices, int indexBase, @@ -127,7 +134,7 @@ public class MeshExporter _materialType, _skinningType ); - var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, $"mesh{_meshIndex}")!; + var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, name)!; // TODO: share materials &c var materialBuilder = new MaterialBuilder() @@ -191,6 +198,7 @@ public class MeshExporter return meshBuilder; } + /// Read in the indices for this mesh. private IReadOnlyList BuildIndices() { var reader = new BinaryReader(new MemoryStream(_mdl.RemainingData)); @@ -198,6 +206,7 @@ public class MeshExporter return reader.ReadStructuresAsArray((int)XivMesh.IndexCount); } + /// Build glTF-compatible vertex data for all vertices in this mesh. private IReadOnlyList BuildVertices() { var vertexBuilderType = typeof(VertexBuilder<,,>) @@ -224,7 +233,7 @@ public class MeshExporter attributes.Clear(); foreach (var (usage, element) in sortedElements) - attributes[usage] = ReadVertexAttribute(streams[element.Stream], element); + attributes[usage] = ReadVertexAttribute((MdlFile.VertexType)element.Type, streams[element.Stream]); var vertexGeometry = BuildVertexGeometry(attributes); var vertexMaterial = BuildVertexMaterial(attributes); @@ -237,9 +246,10 @@ public class MeshExporter return vertices; } - private object ReadVertexAttribute(BinaryReader reader, MdlStructs.VertexElement element) + /// Read a vertex attribute of the specified type from a vertex buffer stream. + private object ReadVertexAttribute(MdlFile.VertexType type, BinaryReader reader) { - return (MdlFile.VertexType)element.Type switch + return type switch { MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), @@ -252,6 +262,7 @@ public class MeshExporter }; } + /// Get the vertex geometry type for this mesh's vertex usages. private Type GetGeometryType(IReadOnlySet usages) { if (!usages.Contains(MdlFile.VertexUsage.Position)) @@ -266,6 +277,7 @@ public class MeshExporter return typeof(VertexPositionNormalTangent); } + /// Build a geometry vertex from a vertex's attributes. private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary attributes) { if (_geometryType == typeof(VertexPosition)) @@ -289,6 +301,7 @@ public class MeshExporter throw new Exception($"Unknown geometry type {_geometryType}."); } + /// Get the vertex material type for this mesh's vertex usages. private Type GetMaterialType(IReadOnlySet usages) { // TODO: IIUC, xiv's uv2 is usually represented as the second two components of a vec4 uv attribute - add support. @@ -306,6 +319,7 @@ public class MeshExporter }; } + /// Build a material vertex from a vertex's attributes. private IVertexMaterial BuildVertexMaterial(IReadOnlyDictionary attributes) { if (_materialType == typeof(VertexEmpty)) @@ -326,15 +340,16 @@ public class MeshExporter throw new Exception($"Unknown material type {_skinningType}"); } + /// Get the vertex skinning type for this mesh's vertex usages. private Type GetSkinningType(IReadOnlySet usages) { - // TODO: possibly need to check only index - weight might be missing? if (usages.Contains(MdlFile.VertexUsage.BlendWeights) && usages.Contains(MdlFile.VertexUsage.BlendIndices)) return typeof(VertexJoints4); return typeof(VertexEmpty); } + /// Build a skinning vertex from a vertex's attributes. private IVertexSkinning BuildVertexSkinning(IReadOnlyDictionary attributes) { if (_skinningType == typeof(VertexEmpty)) @@ -342,17 +357,21 @@ public class MeshExporter if (_skinningType == typeof(VertexJoints4)) { - // todo: this shouldn't happen... right? better approach? if (_boneIndexMap == null) - throw new Exception("cannot build skinned vertex without index mapping"); + throw new Exception("Tried to build skinned vertex but no bone mappings are available."); var indices = ToByteArray(attributes[MdlFile.VertexUsage.BlendIndices]); var weights = ToVector4(attributes[MdlFile.VertexUsage.BlendWeights]); - // todo: if this throws on the bone index map, the mod is broken, as it contains weights for bones that do not exist. - // i've not seen any of these that even tt can understand var bindings = Enumerable.Range(0, 4) - .Select(index => (_boneIndexMap[indices[index]], weights[index])) + .Select(bindingIndex => { + // NOTE: I've not seen any files that throw this error that aren't completely broken. + var xivBoneIndex = indices[bindingIndex]; + if (!_boneIndexMap.TryGetValue(xivBoneIndex, out var jointIndex)) + throw new Exception($"Vertex contains weight for unknown bone index {xivBoneIndex}."); + + return (jointIndex, weights[bindingIndex]); + }) .ToArray(); return new VertexJoints4(bindings); } @@ -360,10 +379,12 @@ public class MeshExporter throw new Exception($"Unknown skinning type {_skinningType}"); } - // Some tangent W values that should be -1 are stored as 0. + /// Clamps any tangent W value other than 1 to -1. + /// Some XIV models seemingly store -1 as 0, this patches over that. private Vector4 FixTangentVector(Vector4 tangent) => tangent with { W = tangent.W == 1 ? 1 : -1 }; + /// Convert a vertex attribute value to a Vector2. Supported inputs are Vector2, Vector3, and Vector4. private Vector2 ToVector2(object data) => data switch { @@ -373,6 +394,7 @@ public class MeshExporter _ => throw new ArgumentOutOfRangeException($"Invalid Vector2 input {data}") }; + /// Convert a vertex attribute value to a Vector3. Supported inputs are Vector2, Vector3, and Vector4. private Vector3 ToVector3(object data) => data switch { @@ -382,6 +404,7 @@ public class MeshExporter _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") }; + /// Convert a vertex attribute value to a Vector4. Supported inputs are Vector2, Vector3, and Vector4. private Vector4 ToVector4(object data) => data switch { @@ -391,6 +414,7 @@ public class MeshExporter _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") }; + /// Convert a vertex attribute value to a byte array. private byte[] ToByteArray(object data) => data switch { diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index c8716cf3..35819e7a 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -30,6 +30,7 @@ public class ModelExporter } } + /// Export a model in preparation for usage in a glTF file. If provided, skeleton will be used to skin the resulting meshes where appropriate. public static Model Export(MdlFile mdl, XivSkeleton? xivSkeleton) { var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; @@ -37,6 +38,7 @@ public class ModelExporter return new Model(meshes, gltfSkeleton); } + /// Convert a .mdl to a mesh (group) per LoD. private static List ConvertMeshes(MdlFile mdl, GltfSkeleton? skeleton) { var meshes = new List(); @@ -56,6 +58,7 @@ public class ModelExporter return meshes; } + /// Convert XIV skeleton data into a glTF-compatible node tree, with mappings. private static GltfSkeleton? ConvertSkeleton(XivSkeleton skeleton) { NodeBuilder? root = null; diff --git a/Penumbra/Import/Models/Export/Skeleton.cs b/Penumbra/Import/Models/Export/Skeleton.cs index 13379dc4..09cdcc32 100644 --- a/Penumbra/Import/Models/Export/Skeleton.cs +++ b/Penumbra/Import/Models/Export/Skeleton.cs @@ -2,6 +2,7 @@ using SharpGLTF.Scenes; namespace Penumbra.Import.Models.Export; +/// Representation of a skeleton within XIV. public class XivSkeleton { public Bone[] Bones; @@ -25,9 +26,15 @@ public class XivSkeleton } } +/// Representation of a glTF-compatible skeleton. public struct GltfSkeleton { + /// Root node of the skeleton. public NodeBuilder Root; + + /// Flattened list of skeleton nodes. public NodeBuilder[] Joints; + + /// Mapping of bone names to their index within the joints array. public Dictionary Names; } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 4f761549..e71b8baf 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -88,6 +88,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable gltfModel.SaveGLTF(_outputPath); } + /// Attempt to read out the pertinent information from a .sklb. private XivSkeleton? BuildSkeleton(CancellationToken cancel) { if (_sklb == null) From 9f981a3e52268c6b1c98959c9eb4c0d398ef8837 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 13:10:50 +1100 Subject: [PATCH 0309/1381] Render export errors --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 6 +++++- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 99c32761..31f2f7e0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -17,6 +17,7 @@ public partial class ModEditWindow private readonly List[] _attributes; public bool PendingIo { get; private set; } = false; + public string? IoException { get; private set; } = null; // TODO: this can probably be genericised across all of chara [GeneratedRegex(@"chara/equipment/e(?'Set'\d{4})/model/c(?'Race'\d{4})e\k'Set'_.+\.mdl", RegexOptions.Compiled)] @@ -74,7 +75,10 @@ public partial class ModEditWindow PendingIo = true; _edit._models.ExportToGltf(Mdl, sklb, outputPath) - .ContinueWith(_ => PendingIo = false); + .ContinueWith(task => { + IoException = task.Exception?.ToString(); + PendingIo = false; + }); } /// Try to find the .sklb path for a .mdl file. diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index ff2c1ae5..57c47b8f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -42,6 +42,9 @@ public partial class ModEditWindow foreach (var gamePath in tab.GamePaths) ImGui.TextUnformatted(gamePath.ToString()); + if (tab.IoException != null) + ImGui.TextUnformatted(tab.IoException); + var ret = false; ret |= DrawModelMaterialDetails(tab, disabled); From 73ff3642fc7ae2e41234dc7eca6c33a3e6ae50a6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 13:30:04 +1100 Subject: [PATCH 0310/1381] Async game path resolution --- Penumbra/Import/Models/ModelManager.cs | 1 - .../ModEditWindow.Models.MdlTab.cs | 41 +++++++++++-------- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 12 +++--- 3 files changed, 30 insertions(+), 24 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index e71b8baf..217450dd 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -4,7 +4,6 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Files; using Penumbra.Import.Models.Export; using SharpGLTF.Scenes; -using SharpGLTF.Transforms; namespace Penumbra.Import.Models; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 31f2f7e0..ba6435c7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -13,7 +13,7 @@ public partial class ModEditWindow private ModEditWindow _edit; public readonly MdlFile Mdl; - public readonly List GamePaths; + public List? GamePaths { get; private set ;} private readonly List[] _attributes; public bool PendingIo { get; private set; } = false; @@ -28,8 +28,10 @@ public partial class ModEditWindow _edit = edit; Mdl = new MdlFile(bytes); - GamePaths = mod == null ? new() : FindGamePaths(path, mod); _attributes = CreateAttributes(Mdl); + + if (mod != null) + FindGamePaths(path, mod); } /// @@ -40,36 +42,41 @@ public partial class ModEditWindow public byte[] Write() => Mdl.Write(); - // TODO: this _needs_ to be done asynchronously, kart mods hang for a good second or so /// Find the list of game paths that may correspond to this model. /// Resolved path to a .mdl. /// Mod within which the .mdl is resolved. - private List FindGamePaths(string path, Mod mod) + private void FindGamePaths(string path, Mod mod) { - // todo: might be worth ordering based on prio + selection for disambiguating between multiple matches? not sure. same for the multi group case - return mod.AllSubMods - .SelectMany(submod => submod.Files.Concat(submod.FileSwaps)) - // todo: using ordinal ignore case because the option group paths in mods being lowerecased somewhere, but the mod editor using fs paths, which may be uppercase. i'd say this will blow up on linux, but it's already the case so can't be too much worse than present right - .Where(kv => kv.Value.FullName.Equals(path, StringComparison.OrdinalIgnoreCase)) - .Select(kv => kv.Key) - .ToList(); + PendingIo = true; + var task = Task.Run(() => { + // TODO: Is it worth trying to order results based on option priorities for cases where more than one match is found? + // NOTE: We're using case insensitive comparisons, as option group paths in mods are stored in lower case, but the mod editor uses paths directly from the file system, which may be mixed case. + return mod.AllSubMods + .SelectMany(submod => submod.Files.Concat(submod.FileSwaps)) + .Where(kv => kv.Value.FullName.Equals(path, StringComparison.OrdinalIgnoreCase)) + .Select(kv => kv.Key) + .ToList(); + }); + + task.ContinueWith(task => { + IoException = task.Exception?.ToString(); + PendingIo = false; + GamePaths = task.Result; + }); } /// Export model to an interchange format. /// Disk path to save the resulting file to. - public void Export(string outputPath) + public void Export(string outputPath, Utf8GamePath mdlPath) { - // NOTES ON EST (i don't think it's worth supporting yet...) + // NOTES ON EST // for collection wide lookup; // Collections.Cache.EstCache::GetEstEntry // Collections.Cache.MetaCache::GetEstEntry // Collections.ModCollection.MetaCache? // for default lookup, probably; // EstFile.GetDefault(...) - - // TODO: allow user to pick the gamepath in the ui - // TODO: what if there's no gamepaths? - var mdlPath = GamePaths.First(); + var sklbPath = GetSklbPath(mdlPath.ToString()); var sklb = sklbPath != null ? ReadSklb(sklbPath) : null; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 57c47b8f..9af2dd91 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -34,13 +34,13 @@ public partial class ModEditWindow ); } - if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", tab.PendingIo)) - { - tab.Export("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf"); - } + if (tab.GamePaths != null) + if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", tab.PendingIo)) + tab.Export("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf", tab.GamePaths.First()); ImGui.TextUnformatted("blippity blap"); - foreach (var gamePath in tab.GamePaths) - ImGui.TextUnformatted(gamePath.ToString()); + if (tab.GamePaths != null) + foreach (var gamePath in tab.GamePaths) + ImGui.TextUnformatted(gamePath.ToString()); if (tab.IoException != null) ImGui.TextUnformatted(tab.IoException); From bb9e7cac074e86987b939c115948cd85f2372e9a Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 14:21:38 +1100 Subject: [PATCH 0311/1381] Clean up UI --- Penumbra/Import/Models/ModelManager.cs | 1 - .../ModEditWindow.Models.MdlTab.cs | 4 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 73 ++++++++++++++++--- 3 files changed, 66 insertions(+), 12 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 217450dd..35a5e53e 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -93,7 +93,6 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable if (_sklb == null) return null; - // TODO: work out how i handle this havok deal. running it outside the framework causes an immediate ctd. var xmlTask = _manager._framework.RunOnFrameworkThread(() => HavokConverter.HkxToXml(_sklb.Skeleton)); xmlTask.Wait(cancel); var xml = xmlTask.Result; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index ba6435c7..38c1c6bd 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -13,8 +13,10 @@ public partial class ModEditWindow private ModEditWindow _edit; public readonly MdlFile Mdl; - public List? GamePaths { get; private set ;} private readonly List[] _attributes; + + public List? GamePaths { get; private set ;} + public int GamePathIndex; public bool PendingIo { get; private set; } = false; public string? IoException { get; private set; } = null; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 9af2dd91..aa69953b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -34,16 +34,7 @@ public partial class ModEditWindow ); } - if (tab.GamePaths != null) - if (ImGuiUtil.DrawDisabledButton("bingo bango", Vector2.Zero, "description", tab.PendingIo)) - tab.Export("C:\\Users\\ackwell\\blender\\gltf-tests\\bingo.gltf", tab.GamePaths.First()); - ImGui.TextUnformatted("blippity blap"); - if (tab.GamePaths != null) - foreach (var gamePath in tab.GamePaths) - ImGui.TextUnformatted(gamePath.ToString()); - - if (tab.IoException != null) - ImGui.TextUnformatted(tab.IoException); + DrawExport(tab, disabled); var ret = false; @@ -58,6 +49,68 @@ public partial class ModEditWindow return !disabled && ret; } + private void DrawExport(MdlTab tab, bool disabled) + { + // IO on a disabled panel doesn't really make sense. + if (disabled) + return; + + if (!ImGui.CollapsingHeader("Export")) + return; + + if (tab.GamePaths == null) + { + if (tab.IoException == null) + ImGui.TextUnformatted("Resolving model game paths."); + else + ImGuiUtil.TextWrapped(tab.IoException); + + return; + } + + DrawGamePathCombo(tab); + + if (ImGuiUtil.DrawDisabledButton("Export to glTF", Vector2.Zero, "Exports this mdl file to glTF, for use in 3D authoring applications.", tab.PendingIo)) + { + var gamePath = tab.GamePaths[tab.GamePathIndex]; + + _fileDialog.OpenSavePicker( + "Save model as glTF.", + ".gltf", + Path.GetFileNameWithoutExtension(gamePath.Filename().ToString()), + ".gltf", + (valid, path) => { + if (!valid) + return; + + tab.Export(path, gamePath); + }, + _mod!.ModPath.FullName, + false + ); + } + + if (tab.IoException != null) + ImGuiUtil.TextWrapped(tab.IoException); + + return; + } + + private void DrawGamePathCombo(MdlTab tab) + { + using var combo = ImRaii.Combo("Game Path", tab.GamePaths![tab.GamePathIndex].ToString()); + if (!combo) + return; + + foreach (var (path, index) in tab.GamePaths.WithIndex()) + { + if (!ImGui.Selectable(path.ToString(), index == tab.GamePathIndex)) + continue; + + tab.GamePathIndex = index; + } + } + private bool DrawModelMaterialDetails(MdlTab tab, bool disabled) { if (!ImGui.CollapsingHeader("Materials")) From 215f8074833ed5c7e9550853fba58a08871b1659 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 1 Jan 2024 23:52:37 +1100 Subject: [PATCH 0312/1381] Fix oversight in bone index mapping generation --- Penumbra/Import/Models/Export/MeshExporter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index cf7cc975..75283732 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -88,13 +88,13 @@ public class MeshExporter var indexMap = new Dictionary(); - foreach (var xivBoneIndex in xivBoneTable.BoneIndex.Take(xivBoneTable.BoneCount)) + foreach (var (xivBoneIndex, tableIndex) in xivBoneTable.BoneIndex.Take(xivBoneTable.BoneCount).WithIndex()) { var boneName = _mdl.Bones[xivBoneIndex]; if (!boneNameMap.TryGetValue(boneName, out var gltfBoneIndex)) throw new Exception($"Armature does not contain bone \"{boneName}\" requested by mesh {_meshIndex}."); - indexMap.Add(xivBoneIndex, gltfBoneIndex); + indexMap.Add((ushort)tableIndex, gltfBoneIndex); } return indexMap; From d85cbd805124ad877a7cc45f418812c0fa43284c Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 2 Jan 2024 12:41:14 +1100 Subject: [PATCH 0313/1381] Add UV2 support --- Penumbra/Import/Models/Export/MeshExporter.cs | 67 ++++++++++++++----- 1 file changed, 51 insertions(+), 16 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 75283732..5f67114d 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -63,8 +63,10 @@ public class MeshExporter _boneIndexMap = BuildBoneIndexMap(boneNameMap); var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements - .Select(element => (MdlFile.VertexUsage)element.Usage) - .ToImmutableHashSet(); + .ToImmutableDictionary( + element => (MdlFile.VertexUsage)element.Usage, + element => (MdlFile.VertexType)element.Type + ); _geometryType = GetGeometryType(usages); _materialType = GetMaterialType(usages); @@ -263,15 +265,15 @@ public class MeshExporter } /// Get the vertex geometry type for this mesh's vertex usages. - private Type GetGeometryType(IReadOnlySet usages) + private Type GetGeometryType(IReadOnlyDictionary usages) { - if (!usages.Contains(MdlFile.VertexUsage.Position)) + if (!usages.ContainsKey(MdlFile.VertexUsage.Position)) throw new Exception("Mesh does not contain position vertex elements."); - if (!usages.Contains(MdlFile.VertexUsage.Normal)) + if (!usages.ContainsKey(MdlFile.VertexUsage.Normal)) return typeof(VertexPosition); - if (!usages.Contains(MdlFile.VertexUsage.Tangent1)) + if (!usages.ContainsKey(MdlFile.VertexUsage.Tangent1)) return typeof(VertexPositionNormal); return typeof(VertexPositionNormalTangent); @@ -302,20 +304,32 @@ public class MeshExporter } /// Get the vertex material type for this mesh's vertex usages. - private Type GetMaterialType(IReadOnlySet usages) + private Type GetMaterialType(IReadOnlyDictionary usages) { - // TODO: IIUC, xiv's uv2 is usually represented as the second two components of a vec4 uv attribute - add support. + var uvCount = 0; + if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var type)) + uvCount = type switch + { + MdlFile.VertexType.Half2 => 1, + MdlFile.VertexType.Half4 => 2, + _ => throw new Exception($"Unexpected UV vertex type {type}.") + }; + var materialUsages = ( - usages.Contains(MdlFile.VertexUsage.UV), - usages.Contains(MdlFile.VertexUsage.Color) + uvCount, + usages.ContainsKey(MdlFile.VertexUsage.Color) ); return materialUsages switch { - (true, true) => typeof(VertexColor1Texture1), - (true, false) => typeof(VertexTexture1), - (false, true) => typeof(VertexColor1), - (false, false) => typeof(VertexEmpty), + (2, true) => typeof(VertexColor1Texture2), + (2, false) => typeof(VertexTexture2), + (1, true) => typeof(VertexColor1Texture1), + (1, false) => typeof(VertexTexture1), + (0, true) => typeof(VertexColor1), + (0, false) => typeof(VertexEmpty), + + _ => throw new Exception("Unreachable."), }; } @@ -337,13 +351,34 @@ public class MeshExporter ToVector2(attributes[MdlFile.VertexUsage.UV]) ); + // XIV packs two UVs into a single vec4 attribute. + + if (_materialType == typeof(VertexTexture2)) + { + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV]); + return new VertexTexture2( + new Vector2(uv.X, uv.Y), + new Vector2(uv.Z, uv.W) + ); + } + + if (_materialType == typeof(VertexColor1Texture2)) + { + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV]); + return new VertexColor1Texture2( + ToVector4(attributes[MdlFile.VertexUsage.Color]), + new Vector2(uv.X, uv.Y), + new Vector2(uv.Z, uv.W) + ); + } + throw new Exception($"Unknown material type {_skinningType}"); } /// Get the vertex skinning type for this mesh's vertex usages. - private Type GetSkinningType(IReadOnlySet usages) + private Type GetSkinningType(IReadOnlyDictionary usages) { - if (usages.Contains(MdlFile.VertexUsage.BlendWeights) && usages.Contains(MdlFile.VertexUsage.BlendIndices)) + if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) return typeof(VertexJoints4); return typeof(VertexEmpty); From 655e2fd2cae574b3536d86ea9b4649fe9561812b Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 2 Jan 2024 14:36:18 +1100 Subject: [PATCH 0314/1381] Flesh out skeleton path resolution a bit --- .../ModEditWindow.Models.MdlTab.cs | 65 +++++++++++++------ 1 file changed, 45 insertions(+), 20 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index c4fb10f8..20a4129d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -21,10 +21,15 @@ public partial class ModEditWindow public bool PendingIo { get; private set; } = false; public string? IoException { get; private set; } = null; - // TODO: this can probably be genericised across all of chara - [GeneratedRegex(@"chara/equipment/e(?'Set'\d{4})/model/c(?'Race'\d{4})e\k'Set'_.+\.mdl", RegexOptions.Compiled)] + [GeneratedRegex(@"chara/(?:equipment|accessory)/(?'Set'[a-z]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", RegexOptions.Compiled)] private static partial Regex CharaEquipmentRegex(); + [GeneratedRegex(@"chara/human/(?'Race'c\d{4})/obj/(?'Type'[^/]+)/(?'Set'[^/]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", RegexOptions.Compiled)] + private static partial Regex CharaHumanRegex(); + + [GeneratedRegex(@"chara/(?'SubCategory'demihuman|monster|weapon)/(?'Set'w\d{4})/obj/body/(?'Body'b\d{4})/model/\k'Set'\k'Body'.mdl", RegexOptions.Compiled)] + private static partial Regex CharaBodyRegex(); + public MdlTab(ModEditWindow edit, byte[] bytes, string path, Mod? mod) { _edit = edit; @@ -71,16 +76,14 @@ public partial class ModEditWindow /// Disk path to save the resulting file to. public void Export(string outputPath, Utf8GamePath mdlPath) { - // NOTES ON EST - // for collection wide lookup; - // Collections.Cache.EstCache::GetEstEntry - // Collections.Cache.MetaCache::GetEstEntry - // Collections.ModCollection.MetaCache? - // for default lookup, probably; - // EstFile.GetDefault(...) - - var sklbPath = GetSklbPath(mdlPath.ToString()); - var sklb = sklbPath != null ? ReadSklb(sklbPath) : null; + SklbFile? sklb = null; + try { + var sklbPath = GetSklbPath(mdlPath.ToString()); + sklb = sklbPath != null ? ReadSklb(sklbPath) : null; + } catch (Exception exception) { + IoException = exception?.ToString(); + return; + } PendingIo = true; _edit._models.ExportToGltf(Mdl, sklb, outputPath) @@ -94,15 +97,37 @@ public partial class ModEditWindow /// .mdl file to look up the skeleton for. private string? GetSklbPath(string mdlPath) { - // TODO: This needs to be drastically expanded, it's dodgy af rn - + // Equipment is skinned to the base body skeleton of the race they target. var match = CharaEquipmentRegex().Match(mdlPath); - if (!match.Success) - return null; + if (match.Success) + { + var race = match.Groups["Race"].Value; + return $"chara/human/{race}/skeleton/base/b0001/skl_{race}b0001.sklb"; + } - var race = match.Groups["Race"].Value; + // Some parts of human have their own skeletons. + match = CharaHumanRegex().Match(mdlPath); + if (match.Success) + { + var type = match.Groups["Type"].Value; + var race = match.Groups["Race"].Value; + return type switch + { + "body" or "tail" => $"chara/human/{race}/skeleton/base/b0001/skl_{race}b0001.sklb", + _ => throw new Exception($"Currently unsupported human model type \"{type}\"."), + }; + } - return $"chara/human/c{race}/skeleton/base/b0001/skl_c{race}b0001.sklb"; + // A few subcategories - such as weapons, demihumans, and monsters - have dedicated per-"body" skeletons. + match = CharaBodyRegex().Match(mdlPath); + if (match.Success) + { + var subCategory = match.Groups["SubCategory"].Value; + var set = match.Groups["Set"].Value; + return $"chara/{subCategory}/{set}/skeleton/base/b0001/skl_{set}b0001.sklb"; + } + + return null; } /// Read a .sklb from the active collection or game. @@ -111,7 +136,7 @@ public partial class ModEditWindow { // TODO: if cross-collection lookups are turned off, this conversion can be skipped if (!Utf8GamePath.FromString(sklbPath, out var utf8SklbPath, true)) - throw new Exception("TODO: handle - should it throw, or try to fail gracefully?"); + throw new Exception($"Resolved skeleton path {sklbPath} could not be converted to a game path."); var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8SklbPath); // TODO: is it worth trying to use streams for these instead? i'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... @@ -121,7 +146,7 @@ public partial class ModEditWindow FullPath path => File.ReadAllBytes(path.ToPath()), }; if (bytes == null) - throw new Exception("TODO: handle - this effectively means that the resolved path doesn't exist. graceful?"); + throw new Exception($"Resolved skeleton path {sklbPath} could not be found. If modded, is it enabled in the current collection?"); return new SklbFile(bytes); } From e8e87cc6cbadec1616cac63dca7b7f2f2642d173 Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 2 Jan 2024 14:36:24 +1100 Subject: [PATCH 0315/1381] Whoops --- Penumbra/Import/Models/Export/MeshExporter.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 5f67114d..1b53df8a 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -312,6 +312,7 @@ public class MeshExporter { MdlFile.VertexType.Half2 => 1, MdlFile.VertexType.Half4 => 2, + MdlFile.VertexType.Single4 => 2, _ => throw new Exception($"Unexpected UV vertex type {type}.") }; From b7edf521b62d205e43d82eef66c746a4b4e0f4f3 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 4 Jan 2024 19:27:04 +1100 Subject: [PATCH 0316/1381] SuzanneWalker --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 437 ++++++++++++++++++ .../ModEditWindow.Models.MdlTab.cs | 22 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 6 + 4 files changed, 461 insertions(+), 6 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index db421413..821194d0 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit db421413a15c48c63eb883dbfc2ac863c579d4c6 +Subproject commit 821194d0650a2dac98b7cbba9ff4a79e32b32d4d diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 35a5e53e..243390a7 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,9 +1,14 @@ using Dalamud.Plugin.Services; +using Lumina.Data.Parsing; using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData.Files; using Penumbra.Import.Models.Export; +using SharpGLTF.Geometry; +using SharpGLTF.Geometry.VertexTypes; +using SharpGLTF.Materials; using SharpGLTF.Scenes; +using SharpGLTF.Schema2; namespace Penumbra.Import.Models; @@ -54,6 +59,12 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public Task ExportToGltf(MdlFile mdl, SklbFile? sklb, string outputPath) => Enqueue(new ExportToGltfAction(this, mdl, sklb, outputPath)); + public Task ImportGltf() + { + var action = new ImportGltfAction(); + return Enqueue(action).ContinueWith(_ => action.Out!); + } + private class ExportToGltfAction : IAction { private readonly ModelManager _manager; @@ -109,4 +120,430 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable return true; } } + + private class ImportGltfAction : IAction + { + public MdlFile? Out; + + public ImportGltfAction() + { + // + } + + private ModelRoot Build() + { + // Build a super simple plane as a fake gltf input. + var material = new MaterialBuilder(); + var mesh = new MeshBuilder("mesh 0.0"); + var prim = mesh.UsePrimitive(material); + var tangent = new Vector4(.5f, .5f, 0, 1); + var vert1 = new VertexBuilder( + new VertexPositionNormalTangent(new Vector3(-1, 0, 1), Vector3.UnitY, tangent), + new VertexColor1Texture2(Vector4.One, Vector2.UnitY, Vector2.Zero), + new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) + ); + var vert2 = new VertexBuilder( + new VertexPositionNormalTangent(new Vector3(1, 0, 1), Vector3.UnitY, tangent), + new VertexColor1Texture2(Vector4.One, Vector2.One, Vector2.Zero), + new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) + ); + var vert3 = new VertexBuilder( + new VertexPositionNormalTangent(new Vector3(-1, 0, -1), Vector3.UnitY, tangent), + new VertexColor1Texture2(Vector4.One, Vector2.Zero, Vector2.Zero), + new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) + ); + var vert4 = new VertexBuilder( + new VertexPositionNormalTangent(new Vector3(1, 0, -1), Vector3.UnitY, tangent), + new VertexColor1Texture2(Vector4.One, Vector2.UnitX, Vector2.Zero), + new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) + ); + prim.AddTriangle(vert2, vert3, vert1); + prim.AddTriangle(vert2, vert4, vert3); + var jKosi = new NodeBuilder("j_kosi"); + var scene = new SceneBuilder(); + scene.AddNode(jKosi); + scene.AddSkinnedMesh(mesh, Matrix4x4.Identity, [jKosi]); + var model = scene.ToGltf2(); + + return model; + } + + private (MdlStructs.VertexElement, Action>) GetPositionWriter(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("POSITION", out var accessor)) + throw new Exception("todo: some error about position being hard required"); + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.Single3, + Usage = (byte)MdlFile.VertexUsage.Position, + }; + + IList values = accessor.AsVector3Array(); + + return ( + element, + (index, bytes) => WriteSingle3(values[index], bytes) + ); + } + + // TODO: probably should sanity check that if there's weights or indexes, both are available? game is always symmetric + private (MdlStructs.VertexElement, Action>)? GetBlendWeightWriter(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("WEIGHTS_0", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; + + var values = accessor.AsVector4Array(); + + return ( + element, + (index, bytes) => WriteByteFloat4(values[index], bytes) + ); + } + + // TODO: this will need to take in a skeleton mapping of some kind so i can persist the bones used and wire up the joints correctly. hopefully by the "write vertex buffer" stage of building, we already know something about the skeleton. + private (MdlStructs.VertexElement, Action>)? GetBlendIndexWriter(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("JOINTS_0", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.UInt, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; + + var values = accessor.AsVector4Array(); + + return ( + element, + (index, bytes) => WriteUInt(values[index], bytes) + ); + } + + private (MdlStructs.VertexElement, Action>)? GetNormalWriter(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("NORMAL", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Type = (byte)MdlFile.VertexType.Half4, + Usage = (byte)MdlFile.VertexUsage.Normal, + }; + + var values = accessor.AsVector3Array(); + + return ( + element, + (index, bytes) => WriteHalf4(new Vector4(values[index], 0), bytes) + ); + } + + private (MdlStructs.VertexElement, Action>)? GetUvWriter(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("TEXCOORD_0", out var accessor1)) + return null; + + // We're omitting type here, and filling it in on return, as there's two different types we might use. + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Usage = (byte)MdlFile.VertexUsage.UV, + }; + + var values1 = accessor1.AsVector2Array(); + + if (!accessors.TryGetValue("TEXCOORD_1", out var accessor2)) + return ( + element with {Type = (byte)MdlFile.VertexType.Half2}, + (index, bytes) => WriteHalf2(values1[index], bytes) + ); + + var values2 = accessor2.AsVector2Array(); + + return ( + element with {Type = (byte)MdlFile.VertexType.Half4}, + (index, bytes) => { + var value1 = values1[index]; + var value2 = values2[index]; + WriteHalf4(new Vector4(value1.X, value1.Y, value2.X, value2.Y), bytes); + } + ); + } + + private (MdlStructs.VertexElement, Action>)? GetTangent1Writer(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("TANGENT", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.Tangent1, + }; + + var values = accessor.AsVector4Array(); + + return ( + element, + (index, bytes) => WriteByteFloat4(values[index], bytes) + ); + } + + private (MdlStructs.VertexElement, Action>)? GetColorWriter(IReadOnlyDictionary accessors) + { + if (!accessors.TryGetValue("COLOR_0", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.Color, + }; + + var values = accessor.AsVector4Array(); + + return ( + element, + (index, bytes) => WriteByteFloat4(values[index], bytes) + ); + } + + private void WriteSingle3(Vector3 input, List bytes) + { + bytes.AddRange(BitConverter.GetBytes(input.X)); + bytes.AddRange(BitConverter.GetBytes(input.Y)); + bytes.AddRange(BitConverter.GetBytes(input.Z)); + } + + private void WriteUInt(Vector4 input, List bytes) + { + bytes.Add((byte)input.X); + bytes.Add((byte)input.Y); + bytes.Add((byte)input.Z); + bytes.Add((byte)input.W); + } + + private void WriteByteFloat4(Vector4 input, List bytes) + { + bytes.Add((byte)Math.Round(input.X * 255f)); + bytes.Add((byte)Math.Round(input.Y * 255f)); + bytes.Add((byte)Math.Round(input.Z * 255f)); + bytes.Add((byte)Math.Round(input.W * 255f)); + } + + private void WriteHalf2(Vector2 input, List bytes) + { + bytes.AddRange(BitConverter.GetBytes((Half)input.X)); + bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); + } + + private void WriteHalf4(Vector4 input, List bytes) + { + bytes.AddRange(BitConverter.GetBytes((Half)input.X)); + bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); + bytes.AddRange(BitConverter.GetBytes((Half)input.Z)); + bytes.AddRange(BitConverter.GetBytes((Half)input.W)); + } + + private byte TypeSize(MdlFile.VertexType type) + { + return type switch + { + MdlFile.VertexType.Single3 => 12, + MdlFile.VertexType.Single4 => 16, + MdlFile.VertexType.UInt => 4, + MdlFile.VertexType.ByteFloat4 => 4, + MdlFile.VertexType.Half2 => 4, + MdlFile.VertexType.Half4 => 8, + + _ => throw new Exception($"Unhandled vertex type {type}"), + }; + } + + public void Execute(CancellationToken cancel) + { + var model = Build(); + + // --- + + // todo this'll need to check names and such. also loop. i'm relying on a single mesh here which is Wrong:tm: + var mesh = model.LogicalNodes + .Where(node => node.Mesh != null) + .Select(node => node.Mesh) + .First(); + + // todo check how many prims there are - maybe throw if more than one? not sure + var prim = mesh.Primitives[0]; + + var accessors = prim.VertexAccessors; + + var rawWriters = new[] { + GetPositionWriter(accessors), + GetBlendWeightWriter(accessors), + GetBlendIndexWriter(accessors), + GetNormalWriter(accessors), + GetTangent1Writer(accessors), + GetColorWriter(accessors), + GetUvWriter(accessors), + }; + + var writers = new List<(MdlStructs.VertexElement, Action>)>(); + var offsets = new byte[] {0, 0, 0}; + foreach (var writer in rawWriters) + { + if (writer == null) continue; + var element = writer.Value.Item1; + writers.Add(( + element with {Offset = offsets[element.Stream]}, + writer.Value.Item2 + )); + offsets[element.Stream] += TypeSize((MdlFile.VertexType)element.Type); + } + var strides = offsets; + + var streams = new List[3]; + for (var i = 0; i < 3; i++) + streams[i] = new List(); + + // todo: this is a bit lmao but also... probably the most sane option? getting the count that is + var vertexCount = prim.VertexAccessors["POSITION"].Count; + for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) + { + foreach (var (element, writer) in writers) + { + writer(vertexIndex, streams[element.Stream]); + } + } + + // indices + var indexCount = prim.GetIndexAccessor().Count; + var indices = prim.GetIndices() + .SelectMany(index => BitConverter.GetBytes((ushort)index)) + .ToArray(); + + var dataBuffer = streams[0].Concat(streams[1]).Concat(streams[2]).Concat(indices); + + var lod1VertLen = (uint)(streams[0].Count + streams[1].Count + streams[2].Count); + + var mdl = new MdlFile() + { + Radius = 1, + // todo: lod calcs... probably handled in penum? we probably only need to think about lod0 for actual import workflow. + VertexOffset = [0, 0, 0], + IndexOffset = [lod1VertLen, 0, 0], + VertexBufferSize = [lod1VertLen, 0, 0], + IndexBufferSize = [(uint)indices.Length, 0, 0], + LodCount = 1, + BoundingBoxes = new MdlStructs.BoundingBoxStruct() + { + Min = [-1, 0, -1, 1], + Max = [1, 0, 1, 1], + }, + VertexDeclarations = [new MdlStructs.VertexDeclarationStruct() + { + VertexElements = writers.Select(x => x.Item1).ToArray(), + }], + Meshes = [new MdlStructs.MeshStruct() + { + VertexCount = (ushort)vertexCount, + IndexCount = (uint)indexCount, + MaterialIndex = 0, + SubMeshIndex = 0, + SubMeshCount = 1, + BoneTableIndex = 0, + StartIndex = 0, + // todo: this will need to be composed down across multiple submeshes. given submeshes store contiguous buffers + VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], + VertexBufferStride = strides, + VertexStreamCount = 2, + }], + BoneTables = [new MdlStructs.BoneTableStruct() + { + BoneCount = 1, + // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. + BoneIndex = new ushort[64], + }], + BoneBoundingBoxes = [ + // new MdlStructs.BoundingBoxStruct() + // { + // Min = [ + // -0.081672676f, + // -0.113717034f, + // -0.11905348f, + // 1.0f, + // ], + // Max = [ + // 0.03941727f, + // 0.09845419f, + // 0.107391916f, + // 1.0f, + // ], + // }, + + // _would_ be nice if i didn't need to fill out this + new MdlStructs.BoundingBoxStruct() + { + Min = [0, 0, 0, 0], + Max = [0, 0, 0, 0], + } + ], + SubMeshes = [new MdlStructs.SubmeshStruct() + { + IndexOffset = 0, + IndexCount = (uint)indexCount, + AttributeIndexMask = 0, + BoneStartIndex = 0, + BoneCount = 1, + }], + + // TODO pretty sure this is garbage data as far as textools functions + // game clearly doesn't rely on this, but the "correct" values are a listing of the bones used by each submesh + SubMeshBoneMap = [0], + + Lods = [new MdlStructs.LodStruct() + { + MeshIndex = 0, + MeshCount = 1, + ModelLodRange = 0, + TextureLodRange = 0, + VertexBufferSize = lod1VertLen, + VertexDataOffset = 0, + IndexBufferSize = (uint)indexCount, + IndexDataOffset = lod1VertLen, + }, + ], + Bones = [ + "j_kosi", + ], + Materials = [ + "/mt_c0201e6180_top_b.mtrl", + ], + RemainingData = dataBuffer.ToArray(), + }; + + Out = mdl; + } + + public bool Equals(IAction? other) + { + if (other is not ImportGltfAction rhs) + return false; + + return true; + } + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 20a4129d..5d9abda6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -12,10 +12,10 @@ public partial class ModEditWindow { private ModEditWindow _edit; - public readonly MdlFile Mdl; - private readonly List[] _attributes; + public MdlFile Mdl { get; private set; } + private List[] _attributes; - public List? GamePaths { get; private set ;} + public List? GamePaths { get; private set; } public int GamePathIndex; public bool PendingIo { get; private set; } = false; @@ -34,13 +34,19 @@ public partial class ModEditWindow { _edit = edit; - Mdl = new MdlFile(bytes); - _attributes = CreateAttributes(Mdl); + Initialize(new MdlFile(bytes)); if (mod != null) FindGamePaths(path, mod); } + [MemberNotNull(nameof(Mdl), nameof(_attributes))] + private void Initialize(MdlFile mdl) + { + Mdl = mdl; + _attributes = CreateAttributes(Mdl); + } + /// public bool Valid => Mdl.Valid; @@ -72,6 +78,12 @@ public partial class ModEditWindow }); } + public void Import() + { + // TODO: this needs to be fleshed out a bunch. + _edit._models.ImportGltf().ContinueWith(v => Initialize(v.Result)); + } + /// Export model to an interchange format. /// Disk path to save the resulting file to. public void Export(string outputPath, Utf8GamePath mdlPath) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index aa69953b..d59cf1e5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -37,6 +37,12 @@ public partial class ModEditWindow DrawExport(tab, disabled); var ret = false; + + if (ImGui.Button("import test")) + { + tab.Import(); + ret |= true; + } ret |= DrawModelMaterialDetails(tab, disabled); From b3fe538219bf3e7169a020719c4c44046a075e2b Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 4 Jan 2024 21:47:48 +1100 Subject: [PATCH 0317/1381] Split vertex attribute logic into seperate file --- .../Import/Models/Import/VertexAttribute.cs | 232 ++++++++++++++++ Penumbra/Import/Models/ModelManager.cs | 247 ++---------------- 2 files changed, 253 insertions(+), 226 deletions(-) create mode 100644 Penumbra/Import/Models/Import/VertexAttribute.cs diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs new file mode 100644 index 00000000..7c605ba8 --- /dev/null +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -0,0 +1,232 @@ +using Lumina.Data.Parsing; +using Penumbra.GameData.Files; +using SharpGLTF.Schema2; + +namespace Penumbra.Import.Models.Import; + +using Writer = Action>; +using Accessors = IReadOnlyDictionary; + +public class VertexAttribute +{ + /// XIV vertex element metadata structure. + public readonly MdlStructs.VertexElement Element; + /// Write this vertex attribute's value at the specified index to the provided byte array. + public readonly Writer Write; + + /// Size in bytes of a single vertex's attribute value. + public byte Size => (MdlFile.VertexType)Element.Type switch + { + MdlFile.VertexType.Single3 => 12, + MdlFile.VertexType.Single4 => 16, + MdlFile.VertexType.UInt => 4, + MdlFile.VertexType.ByteFloat4 => 4, + MdlFile.VertexType.Half2 => 4, + MdlFile.VertexType.Half4 => 8, + + _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), + }; + + public VertexAttribute(MdlStructs.VertexElement element, Writer write) + { + Element = element; + Write = write; + } + + public static VertexAttribute Position(Accessors accessors) + { + if (!accessors.TryGetValue("POSITION", out var accessor)) + throw new Exception("Meshes must contain a POSITION attribute."); + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.Single3, + Usage = (byte)MdlFile.VertexUsage.Position, + }; + + var values = accessor.AsVector3Array(); + + return new VertexAttribute( + element, + (index, bytes) => WriteSingle3(values[index], bytes) + ); + } + + public static VertexAttribute? BlendWeight(Accessors accessors) + { + if (!accessors.TryGetValue("WEIGHTS_0", out var accessor)) + return null; + + if (!accessors.ContainsKey("JOINTS_0")) + throw new Exception("Mesh contained WEIGHTS_0 attribute but no corresponding JOINTS_0 attribute."); + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; + + var values = accessor.AsVector4Array(); + + return new VertexAttribute( + element, + (index, bytes) => WriteByteFloat4(values[index], bytes) + ); + } + + // TODO: this will need to take in a skeleton mapping of some kind so i can persist the bones used and wire up the joints correctly. hopefully by the "write vertex buffer" stage of building, we already know something about the skeleton. + public static VertexAttribute? BlendIndex(Accessors accessors) + { + if (!accessors.TryGetValue("JOINTS_0", out var accessor)) + return null; + + if (!accessors.ContainsKey("WEIGHTS_0")) + throw new Exception("Mesh contained JOINTS_0 attribute but no corresponding WEIGHTS_0 attribute."); + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.UInt, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; + + var values = accessor.AsVector4Array(); + + return new VertexAttribute( + element, + (index, bytes) => WriteUInt(values[index], bytes) + ); + } + + public static VertexAttribute? Normal(Accessors accessors) + { + if (!accessors.TryGetValue("NORMAL", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Type = (byte)MdlFile.VertexType.Half4, + Usage = (byte)MdlFile.VertexUsage.Normal, + }; + + var values = accessor.AsVector3Array(); + + return new VertexAttribute( + element, + (index, bytes) => WriteHalf4(new Vector4(values[index], 0), bytes) + ); + } + + public static VertexAttribute? Uv(Accessors accessors) + { + if (!accessors.TryGetValue("TEXCOORD_0", out var accessor1)) + return null; + + // We're omitting type here, and filling it in on return, as there's two different types we might use. + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Usage = (byte)MdlFile.VertexUsage.UV, + }; + + var values1 = accessor1.AsVector2Array(); + + if (!accessors.TryGetValue("TEXCOORD_1", out var accessor2)) + return new VertexAttribute( + element with { Type = (byte)MdlFile.VertexType.Half2 }, + (index, bytes) => WriteHalf2(values1[index], bytes) + ); + + var values2 = accessor2.AsVector2Array(); + + return new VertexAttribute( + element with { Type = (byte)MdlFile.VertexType.Half4 }, + (index, bytes) => + { + var value1 = values1[index]; + var value2 = values2[index]; + WriteHalf4(new Vector4(value1.X, value1.Y, value2.X, value2.Y), bytes); + } + ); + } + + public static VertexAttribute? Tangent1(Accessors accessors) + { + if (!accessors.TryGetValue("TANGENT", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.Tangent1, + }; + + var values = accessor.AsVector4Array(); + + return new VertexAttribute( + element, + (index, bytes) => WriteByteFloat4(values[index], bytes) + ); + } + + public static VertexAttribute? Color(Accessors accessors) + { + if (!accessors.TryGetValue("COLOR_0", out var accessor)) + return null; + + var element = new MdlStructs.VertexElement() + { + Stream = 1, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.Color, + }; + + var values = accessor.AsVector4Array(); + + return new VertexAttribute( + element, + (index, bytes) => WriteByteFloat4(values[index], bytes) + ); + } + + private static void WriteSingle3(Vector3 input, List bytes) + { + bytes.AddRange(BitConverter.GetBytes(input.X)); + bytes.AddRange(BitConverter.GetBytes(input.Y)); + bytes.AddRange(BitConverter.GetBytes(input.Z)); + } + + private static void WriteUInt(Vector4 input, List bytes) + { + bytes.Add((byte)input.X); + bytes.Add((byte)input.Y); + bytes.Add((byte)input.Z); + bytes.Add((byte)input.W); + } + + private static void WriteByteFloat4(Vector4 input, List bytes) + { + bytes.Add((byte)Math.Round(input.X * 255f)); + bytes.Add((byte)Math.Round(input.Y * 255f)); + bytes.Add((byte)Math.Round(input.Z * 255f)); + bytes.Add((byte)Math.Round(input.W * 255f)); + } + + private static void WriteHalf2(Vector2 input, List bytes) + { + bytes.AddRange(BitConverter.GetBytes((Half)input.X)); + bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); + } + + private static void WriteHalf4(Vector4 input, List bytes) + { + bytes.AddRange(BitConverter.GetBytes((Half)input.X)); + bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); + bytes.AddRange(BitConverter.GetBytes((Half)input.Z)); + bytes.AddRange(BitConverter.GetBytes((Half)input.W)); + } +} diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 243390a7..e5349308 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -4,6 +4,7 @@ using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData.Files; using Penumbra.Import.Models.Export; +using Penumbra.Import.Models.Import; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; using SharpGLTF.Materials; @@ -127,7 +128,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public ImportGltfAction() { - // + // } private ModelRoot Build() @@ -168,212 +169,6 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable return model; } - private (MdlStructs.VertexElement, Action>) GetPositionWriter(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("POSITION", out var accessor)) - throw new Exception("todo: some error about position being hard required"); - - var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.Single3, - Usage = (byte)MdlFile.VertexUsage.Position, - }; - - IList values = accessor.AsVector3Array(); - - return ( - element, - (index, bytes) => WriteSingle3(values[index], bytes) - ); - } - - // TODO: probably should sanity check that if there's weights or indexes, both are available? game is always symmetric - private (MdlStructs.VertexElement, Action>)? GetBlendWeightWriter(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("WEIGHTS_0", out var accessor)) - return null; - - var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.ByteFloat4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, - }; - - var values = accessor.AsVector4Array(); - - return ( - element, - (index, bytes) => WriteByteFloat4(values[index], bytes) - ); - } - - // TODO: this will need to take in a skeleton mapping of some kind so i can persist the bones used and wire up the joints correctly. hopefully by the "write vertex buffer" stage of building, we already know something about the skeleton. - private (MdlStructs.VertexElement, Action>)? GetBlendIndexWriter(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("JOINTS_0", out var accessor)) - return null; - - var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.UInt, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, - }; - - var values = accessor.AsVector4Array(); - - return ( - element, - (index, bytes) => WriteUInt(values[index], bytes) - ); - } - - private (MdlStructs.VertexElement, Action>)? GetNormalWriter(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("NORMAL", out var accessor)) - return null; - - var element = new MdlStructs.VertexElement() - { - Stream = 1, - Type = (byte)MdlFile.VertexType.Half4, - Usage = (byte)MdlFile.VertexUsage.Normal, - }; - - var values = accessor.AsVector3Array(); - - return ( - element, - (index, bytes) => WriteHalf4(new Vector4(values[index], 0), bytes) - ); - } - - private (MdlStructs.VertexElement, Action>)? GetUvWriter(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("TEXCOORD_0", out var accessor1)) - return null; - - // We're omitting type here, and filling it in on return, as there's two different types we might use. - var element = new MdlStructs.VertexElement() - { - Stream = 1, - Usage = (byte)MdlFile.VertexUsage.UV, - }; - - var values1 = accessor1.AsVector2Array(); - - if (!accessors.TryGetValue("TEXCOORD_1", out var accessor2)) - return ( - element with {Type = (byte)MdlFile.VertexType.Half2}, - (index, bytes) => WriteHalf2(values1[index], bytes) - ); - - var values2 = accessor2.AsVector2Array(); - - return ( - element with {Type = (byte)MdlFile.VertexType.Half4}, - (index, bytes) => { - var value1 = values1[index]; - var value2 = values2[index]; - WriteHalf4(new Vector4(value1.X, value1.Y, value2.X, value2.Y), bytes); - } - ); - } - - private (MdlStructs.VertexElement, Action>)? GetTangent1Writer(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("TANGENT", out var accessor)) - return null; - - var element = new MdlStructs.VertexElement() - { - Stream = 1, - Type = (byte)MdlFile.VertexType.ByteFloat4, - Usage = (byte)MdlFile.VertexUsage.Tangent1, - }; - - var values = accessor.AsVector4Array(); - - return ( - element, - (index, bytes) => WriteByteFloat4(values[index], bytes) - ); - } - - private (MdlStructs.VertexElement, Action>)? GetColorWriter(IReadOnlyDictionary accessors) - { - if (!accessors.TryGetValue("COLOR_0", out var accessor)) - return null; - - var element = new MdlStructs.VertexElement() - { - Stream = 1, - Type = (byte)MdlFile.VertexType.ByteFloat4, - Usage = (byte)MdlFile.VertexUsage.Color, - }; - - var values = accessor.AsVector4Array(); - - return ( - element, - (index, bytes) => WriteByteFloat4(values[index], bytes) - ); - } - - private void WriteSingle3(Vector3 input, List bytes) - { - bytes.AddRange(BitConverter.GetBytes(input.X)); - bytes.AddRange(BitConverter.GetBytes(input.Y)); - bytes.AddRange(BitConverter.GetBytes(input.Z)); - } - - private void WriteUInt(Vector4 input, List bytes) - { - bytes.Add((byte)input.X); - bytes.Add((byte)input.Y); - bytes.Add((byte)input.Z); - bytes.Add((byte)input.W); - } - - private void WriteByteFloat4(Vector4 input, List bytes) - { - bytes.Add((byte)Math.Round(input.X * 255f)); - bytes.Add((byte)Math.Round(input.Y * 255f)); - bytes.Add((byte)Math.Round(input.Z * 255f)); - bytes.Add((byte)Math.Round(input.W * 255f)); - } - - private void WriteHalf2(Vector2 input, List bytes) - { - bytes.AddRange(BitConverter.GetBytes((Half)input.X)); - bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); - } - - private void WriteHalf4(Vector4 input, List bytes) - { - bytes.AddRange(BitConverter.GetBytes((Half)input.X)); - bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); - bytes.AddRange(BitConverter.GetBytes((Half)input.Z)); - bytes.AddRange(BitConverter.GetBytes((Half)input.W)); - } - - private byte TypeSize(MdlFile.VertexType type) - { - return type switch - { - MdlFile.VertexType.Single3 => 12, - MdlFile.VertexType.Single4 => 16, - MdlFile.VertexType.UInt => 4, - MdlFile.VertexType.ByteFloat4 => 4, - MdlFile.VertexType.Half2 => 4, - MdlFile.VertexType.Half4 => 8, - - _ => throw new Exception($"Unhandled vertex type {type}"), - }; - } - public void Execute(CancellationToken cancel) { var model = Build(); @@ -391,27 +186,27 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var accessors = prim.VertexAccessors; - var rawWriters = new[] { - GetPositionWriter(accessors), - GetBlendWeightWriter(accessors), - GetBlendIndexWriter(accessors), - GetNormalWriter(accessors), - GetTangent1Writer(accessors), - GetColorWriter(accessors), - GetUvWriter(accessors), + var rawAttributes = new[] { + VertexAttribute.Position(accessors), + VertexAttribute.BlendWeight(accessors), + VertexAttribute.BlendIndex(accessors), + VertexAttribute.Normal(accessors), + VertexAttribute.Tangent1(accessors), + VertexAttribute.Color(accessors), + VertexAttribute.Uv(accessors), }; - var writers = new List<(MdlStructs.VertexElement, Action>)>(); + var attributes = new List(); var offsets = new byte[] {0, 0, 0}; - foreach (var writer in rawWriters) + foreach (var attribute in rawAttributes) { - if (writer == null) continue; - var element = writer.Value.Item1; - writers.Add(( + if (attribute == null) continue; + var element = attribute.Element; + attributes.Add(new VertexAttribute( element with {Offset = offsets[element.Stream]}, - writer.Value.Item2 + attribute.Write )); - offsets[element.Stream] += TypeSize((MdlFile.VertexType)element.Type); + offsets[element.Stream] += attribute.Size; } var strides = offsets; @@ -423,9 +218,9 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var vertexCount = prim.VertexAccessors["POSITION"].Count; for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) { - foreach (var (element, writer) in writers) + foreach (var attribute in attributes) { - writer(vertexIndex, streams[element.Stream]); + attribute.Write(vertexIndex, streams[attribute.Element.Stream]); } } @@ -455,7 +250,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable }, VertexDeclarations = [new MdlStructs.VertexDeclarationStruct() { - VertexElements = writers.Select(x => x.Item1).ToArray(), + VertexElements = attributes.Select(attribute => attribute.Element).ToArray(), }], Meshes = [new MdlStructs.MeshStruct() { @@ -530,7 +325,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable "j_kosi", ], Materials = [ - "/mt_c0201e6180_top_b.mtrl", + "/mt_c0201e6180_top_a.mtrl", ], RemainingData = dataBuffer.ToArray(), }; From 79de6f1714730efcde6cbf861d43d171d51d9f35 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 4 Jan 2024 23:33:54 +1100 Subject: [PATCH 0318/1381] Basic multi mesh handling --- .../Import/Models/Import/VertexAttribute.cs | 8 +- Penumbra/Import/Models/ModelManager.cs | 285 ++++++++++++------ 2 files changed, 194 insertions(+), 99 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 7c605ba8..430bc422 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -72,7 +72,9 @@ public class VertexAttribute return new VertexAttribute( element, - (index, bytes) => WriteByteFloat4(values[index], bytes) + // TODO: TEMP TESTING PINNED TO BONE 0 UNTIL I SET UP BONE MAPPINGS + // (index, bytes) => WriteByteFloat4(values[index], bytes) + (index, bytes) => WriteByteFloat4(Vector4.UnitX, bytes) ); } @@ -96,7 +98,9 @@ public class VertexAttribute return new VertexAttribute( element, - (index, bytes) => WriteUInt(values[index], bytes) + // TODO: TEMP TESTING PINNED TO BONE 0 UNTIL I SET UP BONE MAPPINGS + // (index, bytes) => WriteUInt(values[index], bytes) + (index, bytes) => WriteUInt(Vector4.Zero, bytes) ); } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index e5349308..66f5202e 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -171,107 +171,75 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable public void Execute(CancellationToken cancel) { - var model = Build(); + var model = ModelRoot.Load("C:\\Users\\ackwell\\blender\\gltf-tests\\c0201e6180_top.gltf"); - // --- - - // todo this'll need to check names and such. also loop. i'm relying on a single mesh here which is Wrong:tm: - var mesh = model.LogicalNodes + // TODO: for grouping, should probably use `node.name ?? mesh.name`, as which are set seems to depend on the exporter. + var nodes = model.LogicalNodes .Where(node => node.Mesh != null) - .Select(node => node.Mesh) - .First(); + // TODO: I'm just grabbing the first 3, as that will contain 0.0, 0.1, and 1.0. testing, and all that. + .Take(3); - // todo check how many prims there are - maybe throw if more than one? not sure - var prim = mesh.Primitives[0]; - - var accessors = prim.VertexAccessors; - - var rawAttributes = new[] { - VertexAttribute.Position(accessors), - VertexAttribute.BlendWeight(accessors), - VertexAttribute.BlendIndex(accessors), - VertexAttribute.Normal(accessors), - VertexAttribute.Tangent1(accessors), - VertexAttribute.Color(accessors), - VertexAttribute.Uv(accessors), - }; - - var attributes = new List(); - var offsets = new byte[] {0, 0, 0}; - foreach (var attribute in rawAttributes) + // this is a representation of a single LoD + var vertexDeclarations = new List(); + var boneTables = new List(); + var meshes = new List(); + var submeshes = new List(); + var vertexBuffer = new List(); + var indices = new List(); + + foreach (var node in nodes) { - if (attribute == null) continue; - var element = attribute.Element; - attributes.Add(new VertexAttribute( - element with {Offset = offsets[element.Stream]}, - attribute.Write - )); - offsets[element.Stream] += attribute.Size; + var boneTableOffset = boneTables.Count; + var meshOffset = meshes.Count; + var subOffset = submeshes.Count; + var vertOffset = vertexBuffer.Count; + var idxOffset = indices.Count; + + var ( + vertexDeclaration, + boneTable, + xivMesh, + xivSubmesh, + meshVertexBuffer, + meshIndices + ) = MeshThing(node); + + vertexDeclarations.Add(vertexDeclaration); + boneTables.Add(boneTable); + meshes.Add(xivMesh with { + SubMeshIndex = (ushort)(xivMesh.SubMeshIndex + subOffset), + // TODO: should probably define a type for index type hey. + BoneTableIndex = (ushort)(xivMesh.BoneTableIndex + boneTableOffset), + StartIndex = (uint)(xivMesh.StartIndex + idxOffset / sizeof(ushort)), + VertexBufferOffset = xivMesh.VertexBufferOffset + .Select(offset => (uint)(offset + vertOffset)) + .ToArray(), + }); + submeshes.Add(xivSubmesh with { + // TODO: this will need to keep ticking up for each submesh in the same mesh + IndexOffset = (uint)(xivSubmesh.IndexOffset + idxOffset / sizeof(ushort)) + }); + vertexBuffer.AddRange(meshVertexBuffer); + indices.AddRange(meshIndices); } - var strides = offsets; - - var streams = new List[3]; - for (var i = 0; i < 3; i++) - streams[i] = new List(); - - // todo: this is a bit lmao but also... probably the most sane option? getting the count that is - var vertexCount = prim.VertexAccessors["POSITION"].Count; - for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) - { - foreach (var attribute in attributes) - { - attribute.Write(vertexIndex, streams[attribute.Element.Stream]); - } - } - - // indices - var indexCount = prim.GetIndexAccessor().Count; - var indices = prim.GetIndices() - .SelectMany(index => BitConverter.GetBytes((ushort)index)) - .ToArray(); - - var dataBuffer = streams[0].Concat(streams[1]).Concat(streams[2]).Concat(indices); - - var lod1VertLen = (uint)(streams[0].Count + streams[1].Count + streams[2].Count); var mdl = new MdlFile() { Radius = 1, // todo: lod calcs... probably handled in penum? we probably only need to think about lod0 for actual import workflow. VertexOffset = [0, 0, 0], - IndexOffset = [lod1VertLen, 0, 0], - VertexBufferSize = [lod1VertLen, 0, 0], - IndexBufferSize = [(uint)indices.Length, 0, 0], + IndexOffset = [(uint)vertexBuffer.Count, 0, 0], + VertexBufferSize = [(uint)vertexBuffer.Count, 0, 0], + IndexBufferSize = [(uint)indices.Count, 0, 0], LodCount = 1, BoundingBoxes = new MdlStructs.BoundingBoxStruct() { Min = [-1, 0, -1, 1], Max = [1, 0, 1, 1], }, - VertexDeclarations = [new MdlStructs.VertexDeclarationStruct() - { - VertexElements = attributes.Select(attribute => attribute.Element).ToArray(), - }], - Meshes = [new MdlStructs.MeshStruct() - { - VertexCount = (ushort)vertexCount, - IndexCount = (uint)indexCount, - MaterialIndex = 0, - SubMeshIndex = 0, - SubMeshCount = 1, - BoneTableIndex = 0, - StartIndex = 0, - // todo: this will need to be composed down across multiple submeshes. given submeshes store contiguous buffers - VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], - VertexBufferStride = strides, - VertexStreamCount = 2, - }], - BoneTables = [new MdlStructs.BoneTableStruct() - { - BoneCount = 1, - // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. - BoneIndex = new ushort[64], - }], + VertexDeclarations = vertexDeclarations.ToArray(), + Meshes = meshes.ToArray(), + BoneTables = boneTables.ToArray(), BoneBoundingBoxes = [ // new MdlStructs.BoundingBoxStruct() // { @@ -296,14 +264,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable Max = [0, 0, 0, 0], } ], - SubMeshes = [new MdlStructs.SubmeshStruct() - { - IndexOffset = 0, - IndexCount = (uint)indexCount, - AttributeIndexMask = 0, - BoneStartIndex = 0, - BoneCount = 1, - }], + SubMeshes = submeshes.ToArray(), // TODO pretty sure this is garbage data as far as textools functions // game clearly doesn't rely on this, but the "correct" values are a listing of the bones used by each submesh @@ -312,13 +273,13 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable Lods = [new MdlStructs.LodStruct() { MeshIndex = 0, - MeshCount = 1, + MeshCount = (ushort)meshes.Count, ModelLodRange = 0, TextureLodRange = 0, - VertexBufferSize = lod1VertLen, + VertexBufferSize = (uint)vertexBuffer.Count, VertexDataOffset = 0, - IndexBufferSize = (uint)indexCount, - IndexDataOffset = lod1VertLen, + IndexBufferSize = (uint)indices.Count, + IndexDataOffset = (uint)vertexBuffer.Count, }, ], Bones = [ @@ -327,12 +288,142 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable Materials = [ "/mt_c0201e6180_top_a.mtrl", ], - RemainingData = dataBuffer.ToArray(), + RemainingData = vertexBuffer.Concat(indices).ToArray(), }; Out = mdl; } + // this return type is an absolute meme, class that shit up. + public ( + MdlStructs.VertexDeclarationStruct, + MdlStructs.BoneTableStruct, + MdlStructs.MeshStruct, + MdlStructs.SubmeshStruct, + IEnumerable, + IEnumerable + ) MeshThing(Node node) + { + // BoneTable (mesh.btidx = 255 means unskinned) + // vertexdecl + + var mesh = node.Mesh; + + // TODO: should probably say _what_ mesh + // TODO: would be cool to support >1 primitive (esp. given they're effectively what submeshes are modeled as), but blender doesn't really use them, so not going to prio that at all. + if (mesh.Primitives.Count != 1) + throw new Exception($"Mesh has {mesh.Primitives.Count} primitives, expected 1."); + var primitive = mesh.Primitives[0]; + + var accessors = primitive.VertexAccessors; + + var rawAttributes = new[] { + VertexAttribute.Position(accessors), + VertexAttribute.BlendWeight(accessors), + VertexAttribute.BlendIndex(accessors), + VertexAttribute.Normal(accessors), + VertexAttribute.Tangent1(accessors), + VertexAttribute.Color(accessors), + VertexAttribute.Uv(accessors), + }; + + var attributes = new List(); + var offsets = new byte[] {0, 0, 0}; + foreach (var attribute in rawAttributes) + { + if (attribute == null) continue; + var element = attribute.Element; + attributes.Add(new VertexAttribute( + element with {Offset = offsets[element.Stream]}, + attribute.Write + )); + offsets[element.Stream] += attribute.Size; + } + var strides = offsets; + + // TODO: when merging submeshes, i'll need to check that vert els are the same for all of them, as xiv only stores verts at the mesh level and shares them. + + var streams = new List[3]; + for (var i = 0; i < 3; i++) + streams[i] = new List(); + + // todo: this is a bit lmao but also... probably the most sane option? getting the count that is + var vertexCount = primitive.VertexAccessors["POSITION"].Count; + for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) + { + foreach (var attribute in attributes) + { + attribute.Write(vertexIndex, streams[attribute.Element.Stream]); + } + } + + // indices + var indexCount = primitive.GetIndexAccessor().Count; + var indices = primitive.GetIndices() + .SelectMany(index => BitConverter.GetBytes((ushort)index)) + .ToArray(); + + // one of these per mesh + var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() + { + VertexElements = attributes.Select(attribute => attribute.Element).ToArray(), + }; + + // one of these per skinned mesh. + // TODO: check if mesh has skinning at all. + var boneTable = new MdlStructs.BoneTableStruct() + { + BoneCount = 1, + // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. + BoneIndex = new ushort[64], + }; + + // mesh + var xivMesh = new MdlStructs.MeshStruct() + { + // TODO: sum across submeshes. + // TODO: would be cool to share verts on submesh boundaries but that's way out of scope for now. + VertexCount = (ushort)vertexCount, + IndexCount = (uint)indexCount, + // TODO: will have to think about how to represent this - materials can be named, so maybe adjust in parent? + MaterialIndex = 0, + // TODO: this will need adjusting by parent + SubMeshIndex = 0, + SubMeshCount = 1, + // TODO: update in parent + BoneTableIndex = 0, + // TODO: this is relative to the lod's index buffer, and is an index, not byte offset + StartIndex = 0, + // TODO: these are relative to the lod vertex buffer. these values are accurate for a 0 offset, but lod will need to adjust + VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], + VertexBufferStride = strides, + VertexStreamCount = /* 2 */ (byte)(attributes.Select(attribute => attribute.Element.Stream).Max() + 1), + }; + + // submesh + // TODO: once we have multiple submeshes, the _first_ should probably set an index offset of 0, and then further ones delta from there - and then they can be blindly adjusted by the parent that's laying out the meshes. + var xivSubmesh = new MdlStructs.SubmeshStruct() + { + IndexOffset = 0, + IndexCount = (uint)indexCount, + AttributeIndexMask = 0, + // TODO: not sure how i want to handle these ones + BoneStartIndex = 0, + BoneCount = 1, + }; + + var vertexBuffer = streams[0].Concat(streams[1]).Concat(streams[2]); + + return ( + vertexDeclaration, + boneTable, + xivMesh, + xivSubmesh, + vertexBuffer, + indices + ); + } + public bool Equals(IAction? other) { if (other is not ImportGltfAction rhs) From 4e8695e7a4e1e6c18b13b93773eb391fa09d06ef Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 5 Jan 2024 01:03:54 +1100 Subject: [PATCH 0319/1381] Spike submeshes --- Penumbra/Import/Models/ModelManager.cs | 209 ++++++++++++++++++------- 1 file changed, 155 insertions(+), 54 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 66f5202e..43630f6e 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using Lumina.Data.Parsing; +using OtterGui; using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData.Files; @@ -13,7 +14,7 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models; -public sealed class ModelManager : SingleTaskQueue, IDisposable +public sealed partial class ModelManager : SingleTaskQueue, IDisposable { private readonly IFramework _framework; private readonly IDataManager _gameData; @@ -122,8 +123,12 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable } } - private class ImportGltfAction : IAction + private partial class ImportGltfAction : IAction { + // TODO: clean this up a bit, i don't actually need all of it. + [GeneratedRegex(@".*[_ ^](?'Mesh'[0-9]+)[\\.\\-]?([0-9]+)?$", RegexOptions.Compiled)] + private static partial Regex MeshNameGroupingRegex(); + public MdlFile? Out; public ImportGltfAction() @@ -174,10 +179,25 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var model = ModelRoot.Load("C:\\Users\\ackwell\\blender\\gltf-tests\\c0201e6180_top.gltf"); // TODO: for grouping, should probably use `node.name ?? mesh.name`, as which are set seems to depend on the exporter. + // var nodes = model.LogicalNodes + // .Where(node => node.Mesh != null) + // // TODO: I'm just grabbing the first 3, as that will contain 0.0, 0.1, and 1.0. testing, and all that. + // .Take(3); + + // tt uses this + // ".*[_ ^]([0-9]+)[\\.\\-]?([0-9]+)?$" var nodes = model.LogicalNodes .Where(node => node.Mesh != null) - // TODO: I'm just grabbing the first 3, as that will contain 0.0, 0.1, and 1.0. testing, and all that. - .Take(3); + .Take(6) // this model has all 3 lods in it - the first 6 are the real lod0 + .SelectWhere(node => { + var name = node.Name ?? node.Mesh.Name; + var match = MeshNameGroupingRegex().Match(name); + return match.Success + ? (true, (node, int.Parse(match.Groups["Mesh"].Value))) + : (false, (node, -1)); + }) + .GroupBy(pair => pair.Item2, pair => pair.node) + .OrderBy(group => group.Key); // this is a representation of a single LoD var vertexDeclarations = new List(); @@ -187,7 +207,7 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable var vertexBuffer = new List(); var indices = new List(); - foreach (var node in nodes) + foreach (var submeshnodes in nodes) { var boneTableOffset = boneTables.Count; var meshOffset = meshes.Count; @@ -199,10 +219,10 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable vertexDeclaration, boneTable, xivMesh, - xivSubmesh, + xivSubmeshes, meshVertexBuffer, meshIndices - ) = MeshThing(node); + ) = MeshThing(submeshnodes); vertexDeclarations.Add(vertexDeclaration); boneTables.Add(boneTable); @@ -215,12 +235,14 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable .Select(offset => (uint)(offset + vertOffset)) .ToArray(), }); - submeshes.Add(xivSubmesh with { - // TODO: this will need to keep ticking up for each submesh in the same mesh - IndexOffset = (uint)(xivSubmesh.IndexOffset + idxOffset / sizeof(ushort)) - }); + // TODO: could probably do this with linq cleaner + foreach (var xivSubmesh in xivSubmeshes) + submeshes.Add(xivSubmesh with { + // TODO: this will need to keep ticking up for each submesh in the same mesh + IndexOffset = (uint)(xivSubmesh.IndexOffset + idxOffset / sizeof(ushort)) + }); vertexBuffer.AddRange(meshVertexBuffer); - indices.AddRange(meshIndices); + indices.AddRange(meshIndices.SelectMany(index => BitConverter.GetBytes((ushort)index))); } var mdl = new MdlFile() @@ -295,14 +317,99 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable } // this return type is an absolute meme, class that shit up. - public ( + private ( MdlStructs.VertexDeclarationStruct, MdlStructs.BoneTableStruct, MdlStructs.MeshStruct, - MdlStructs.SubmeshStruct, + IEnumerable, IEnumerable, - IEnumerable - ) MeshThing(Node node) + IEnumerable + ) MeshThing(IEnumerable nodes) + { + var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = Array.Empty()}; + var vertexCount = (ushort)0; + // there's gotta be a better way to do this with streams or enumerables or something, surely + var streams = new List[3]; + for (var i = 0; i < 3; i++) + streams[i] = new List(); + var indexCount = (uint)0; + var indices = new List(); + var strides = new byte[] {0, 0, 0}; + var submeshes = new List(); + + // TODO: check that attrs/elems/strides match - we should be generating per-mesh stuff for sanity's sake, but we need to make sure they match if there's >1 node mesh in a mesh. + foreach (var node in nodes) + { + var vertOff = vertexCount; + var idxOff = indexCount; + + var (vertDecl, newStrides, submesh, vertCount, vertStreams, idxCount, idxs) = NodeMeshThing(node); + vertexDeclaration = vertDecl; // TODO: CHECK EQUAL AFTER FIRST + strides = newStrides; // ALSO CHECK EQUAL + vertexCount += vertCount; + for (var i = 0; i < 3; i++) + streams[i].AddRange(vertStreams[i]); + indexCount += idxCount; + // we need to offset the indexes to point into the new stuff + indices.AddRange(idxs.Select(idx => (ushort)(idx + vertOff))); + submeshes.Add(submesh with { + IndexOffset = submesh.IndexOffset + idxOff + // TODO: bone stuff probably + }); + } + + // one of these per skinned mesh. + // TODO: check if mesh has skinning at all. (err if mixed?) + var boneTable = new MdlStructs.BoneTableStruct() + { + BoneCount = 1, + // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. + BoneIndex = new ushort[64], + }; + + // mesh + var xivMesh = new MdlStructs.MeshStruct() + { + // TODO: sum across submeshes. + // TODO: would be cool to share verts on submesh boundaries but that's way out of scope for now. + VertexCount = vertexCount, + IndexCount = indexCount, + // TODO: will have to think about how to represent this - materials can be named, so maybe adjust in parent? + MaterialIndex = 0, + // TODO: this will need adjusting by parent + SubMeshIndex = 0, + SubMeshCount = (ushort)submeshes.Count, + // TODO: update in parent + BoneTableIndex = 0, + // TODO: this is relative to the lod's index buffer, and is an index, not byte offset + StartIndex = 0, + // TODO: these are relative to the lod vertex buffer. these values are accurate for a 0 offset, but lod will need to adjust + VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], + VertexBufferStride = strides, + // VertexStreamCount = /* 2 */ (byte)(attributes.Select(attribute => attribute.Element.Stream).Max() + 1), + VertexStreamCount = (byte)(vertexDeclaration.VertexElements.Select(element => element.Stream).Max() + 1) + }; + + return ( + vertexDeclaration, + boneTable, + xivMesh, + submeshes, + streams[0].Concat(streams[1]).Concat(streams[2]), + indices + ); + } + + private ( + MdlStructs.VertexDeclarationStruct, + byte[], + // MdlStructs.MeshStruct, + MdlStructs.SubmeshStruct, + ushort, + IEnumerable[], + uint, + IEnumerable + ) NodeMeshThing(Node node) { // BoneTable (mesh.btidx = 255 means unskinned) // vertexdecl @@ -358,10 +465,11 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable } // indices - var indexCount = primitive.GetIndexAccessor().Count; - var indices = primitive.GetIndices() - .SelectMany(index => BitConverter.GetBytes((ushort)index)) - .ToArray(); + // var indexCount = primitive.GetIndexAccessor().Count; + // var indices = primitive.GetIndices() + // .SelectMany(index => BitConverter.GetBytes((ushort)index)) + // .ToArray(); + var indices = primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); // one of these per mesh var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() @@ -369,57 +477,50 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable VertexElements = attributes.Select(attribute => attribute.Element).ToArray(), }; - // one of these per skinned mesh. - // TODO: check if mesh has skinning at all. - var boneTable = new MdlStructs.BoneTableStruct() - { - BoneCount = 1, - // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. - BoneIndex = new ushort[64], - }; - // mesh - var xivMesh = new MdlStructs.MeshStruct() - { - // TODO: sum across submeshes. - // TODO: would be cool to share verts on submesh boundaries but that's way out of scope for now. - VertexCount = (ushort)vertexCount, - IndexCount = (uint)indexCount, - // TODO: will have to think about how to represent this - materials can be named, so maybe adjust in parent? - MaterialIndex = 0, - // TODO: this will need adjusting by parent - SubMeshIndex = 0, - SubMeshCount = 1, - // TODO: update in parent - BoneTableIndex = 0, - // TODO: this is relative to the lod's index buffer, and is an index, not byte offset - StartIndex = 0, - // TODO: these are relative to the lod vertex buffer. these values are accurate for a 0 offset, but lod will need to adjust - VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], - VertexBufferStride = strides, - VertexStreamCount = /* 2 */ (byte)(attributes.Select(attribute => attribute.Element.Stream).Max() + 1), - }; + // var xivMesh = new MdlStructs.MeshStruct() + // { + // // TODO: sum across submeshes. + // // TODO: would be cool to share verts on submesh boundaries but that's way out of scope for now. + // VertexCount = (ushort)vertexCount, + // IndexCount = (uint)indexCount, + // // TODO: will have to think about how to represent this - materials can be named, so maybe adjust in parent? + // MaterialIndex = 0, + // // TODO: this will need adjusting by parent + // SubMeshIndex = 0, + // SubMeshCount = 1, + // // TODO: update in parent + // BoneTableIndex = 0, + // // TODO: this is relative to the lod's index buffer, and is an index, not byte offset + // StartIndex = 0, + // // TODO: these are relative to the lod vertex buffer. these values are accurate for a 0 offset, but lod will need to adjust + // VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], + // VertexBufferStride = strides, + // VertexStreamCount = /* 2 */ (byte)(attributes.Select(attribute => attribute.Element.Stream).Max() + 1), + // }; // submesh // TODO: once we have multiple submeshes, the _first_ should probably set an index offset of 0, and then further ones delta from there - and then they can be blindly adjusted by the parent that's laying out the meshes. var xivSubmesh = new MdlStructs.SubmeshStruct() { IndexOffset = 0, - IndexCount = (uint)indexCount, + IndexCount = (uint)indices.Length, AttributeIndexMask = 0, // TODO: not sure how i want to handle these ones BoneStartIndex = 0, BoneCount = 1, }; - var vertexBuffer = streams[0].Concat(streams[1]).Concat(streams[2]); + // var vertexBuffer = streams[0].Concat(streams[1]).Concat(streams[2]); return ( vertexDeclaration, - boneTable, - xivMesh, + strides, + // xivMesh, xivSubmesh, - vertexBuffer, + (ushort)vertexCount, + streams, + (uint)indices.Length, indices ); } From acaa49fec5520d5b0d8ce32b84b0cd9b14fb4eed Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 5 Jan 2024 15:32:31 +1100 Subject: [PATCH 0320/1381] Add shape key support --- .../Import/Models/Import/VertexAttribute.cs | 132 +++++++++---- Penumbra/Import/Models/ModelManager.cs | 176 +++++++++++++++++- 2 files changed, 260 insertions(+), 48 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 430bc422..9fd50513 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -4,7 +4,9 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; -using Writer = Action>; +using BuildFn = Func; +using HasMorphFn = Func; +using BuildMorphFn = Func; using Accessors = IReadOnlyDictionary; public class VertexAttribute @@ -12,7 +14,11 @@ public class VertexAttribute /// XIV vertex element metadata structure. public readonly MdlStructs.VertexElement Element; /// Write this vertex attribute's value at the specified index to the provided byte array. - public readonly Writer Write; + public readonly BuildFn Build; + + public readonly HasMorphFn HasMorph; + + public readonly BuildMorphFn BuildMorph; /// Size in bytes of a single vertex's attribute value. public byte Size => (MdlFile.VertexType)Element.Type switch @@ -27,13 +33,32 @@ public class VertexAttribute _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), }; - public VertexAttribute(MdlStructs.VertexElement element, Writer write) + public VertexAttribute( + MdlStructs.VertexElement element, + BuildFn write, + HasMorphFn? hasMorph = null, + BuildMorphFn? buildMorph = null + ) { Element = element; - Write = write; + Build = write; + HasMorph = hasMorph ?? DefaultHasMorph; + BuildMorph = buildMorph ?? DefaultBuildMorph; } - public static VertexAttribute Position(Accessors accessors) + // todo: this is per-shape at the moment - consider if it should do them all at once (i mean we always want to check all of them, it's mostly a semantics question on who owns the loop) + private static bool DefaultHasMorph(int morphIndex, int vertexIndex) + { + return false; + } + + // xiv stores shapes as full vertex replacements, so the default value for a morph attribute is simply it's built state (rather than a delta or w/e) + private byte[] DefaultBuildMorph(int morphIndex, int vertexIndex) + { + return Build(vertexIndex); + } + + public static VertexAttribute Position(Accessors accessors, IEnumerable morphAccessors) { if (!accessors.TryGetValue("POSITION", out var accessor)) throw new Exception("Meshes must contain a POSITION attribute."); @@ -47,9 +72,32 @@ public class VertexAttribute var values = accessor.AsVector3Array(); + var foo = morphAccessors + .Select(ma => ma.GetValueOrDefault("POSITION")?.AsVector3Array()) + .ToArray(); + return new VertexAttribute( element, - (index, bytes) => WriteSingle3(values[index], bytes) + index => BuildSingle3(values[index]), + // TODO: at the moment this is only defined for position - is it worth setting one up for normal, too? + (morphIndex, vertexIndex) => + { + var deltas = foo[morphIndex]; + if (deltas == null) return false; + var delta = deltas[vertexIndex]; + return delta != Vector3.Zero; + }, + // TODO: this will _need_ to be defined for any values that appear in morphs, i.e. geom and maybe mats + (morphIndex, vertexIndex) => + { + var value = values[vertexIndex]; + + var delta = foo[morphIndex]?[vertexIndex]; + if (delta != null) + value += delta.Value; + + return BuildSingle3(value); + } ); } @@ -73,8 +121,7 @@ public class VertexAttribute return new VertexAttribute( element, // TODO: TEMP TESTING PINNED TO BONE 0 UNTIL I SET UP BONE MAPPINGS - // (index, bytes) => WriteByteFloat4(values[index], bytes) - (index, bytes) => WriteByteFloat4(Vector4.UnitX, bytes) + index => BuildByteFloat4(Vector4.UnitX) ); } @@ -99,8 +146,7 @@ public class VertexAttribute return new VertexAttribute( element, // TODO: TEMP TESTING PINNED TO BONE 0 UNTIL I SET UP BONE MAPPINGS - // (index, bytes) => WriteUInt(values[index], bytes) - (index, bytes) => WriteUInt(Vector4.Zero, bytes) + index => BuildUInt(Vector4.Zero) ); } @@ -120,7 +166,7 @@ public class VertexAttribute return new VertexAttribute( element, - (index, bytes) => WriteHalf4(new Vector4(values[index], 0), bytes) + index => BuildHalf4(new Vector4(values[index], 0)) ); } @@ -141,18 +187,18 @@ public class VertexAttribute if (!accessors.TryGetValue("TEXCOORD_1", out var accessor2)) return new VertexAttribute( element with { Type = (byte)MdlFile.VertexType.Half2 }, - (index, bytes) => WriteHalf2(values1[index], bytes) + index => BuildHalf2(values1[index]) ); var values2 = accessor2.AsVector2Array(); return new VertexAttribute( element with { Type = (byte)MdlFile.VertexType.Half4 }, - (index, bytes) => + index => { var value1 = values1[index]; var value2 = values2[index]; - WriteHalf4(new Vector4(value1.X, value1.Y, value2.X, value2.Y), bytes); + return BuildHalf4(new Vector4(value1.X, value1.Y, value2.X, value2.Y)); } ); } @@ -173,7 +219,7 @@ public class VertexAttribute return new VertexAttribute( element, - (index, bytes) => WriteByteFloat4(values[index], bytes) + index => BuildByteFloat4(values[index]) ); } @@ -193,44 +239,54 @@ public class VertexAttribute return new VertexAttribute( element, - (index, bytes) => WriteByteFloat4(values[index], bytes) + index => BuildByteFloat4(values[index]) ); } - private static void WriteSingle3(Vector3 input, List bytes) + private static byte[] BuildSingle3(Vector3 input) { - bytes.AddRange(BitConverter.GetBytes(input.X)); - bytes.AddRange(BitConverter.GetBytes(input.Y)); - bytes.AddRange(BitConverter.GetBytes(input.Z)); + return [ + ..BitConverter.GetBytes(input.X), + ..BitConverter.GetBytes(input.Y), + ..BitConverter.GetBytes(input.Z), + ]; } - private static void WriteUInt(Vector4 input, List bytes) + private static byte[] BuildUInt(Vector4 input) { - bytes.Add((byte)input.X); - bytes.Add((byte)input.Y); - bytes.Add((byte)input.Z); - bytes.Add((byte)input.W); + return [ + (byte)input.X, + (byte)input.Y, + (byte)input.Z, + (byte)input.W, + ]; } - private static void WriteByteFloat4(Vector4 input, List bytes) + private static byte[] BuildByteFloat4(Vector4 input) { - bytes.Add((byte)Math.Round(input.X * 255f)); - bytes.Add((byte)Math.Round(input.Y * 255f)); - bytes.Add((byte)Math.Round(input.Z * 255f)); - bytes.Add((byte)Math.Round(input.W * 255f)); + return [ + (byte)Math.Round(input.X * 255f), + (byte)Math.Round(input.Y * 255f), + (byte)Math.Round(input.Z * 255f), + (byte)Math.Round(input.W * 255f), + ]; } - private static void WriteHalf2(Vector2 input, List bytes) + private static byte[] BuildHalf2(Vector2 input) { - bytes.AddRange(BitConverter.GetBytes((Half)input.X)); - bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); + return [ + ..BitConverter.GetBytes((Half)input.X), + ..BitConverter.GetBytes((Half)input.Y), + ]; } - private static void WriteHalf4(Vector4 input, List bytes) + private static byte[] BuildHalf4(Vector4 input) { - bytes.AddRange(BitConverter.GetBytes((Half)input.X)); - bytes.AddRange(BitConverter.GetBytes((Half)input.Y)); - bytes.AddRange(BitConverter.GetBytes((Half)input.Z)); - bytes.AddRange(BitConverter.GetBytes((Half)input.W)); + return [ + ..BitConverter.GetBytes((Half)input.X), + ..BitConverter.GetBytes((Half)input.Y), + ..BitConverter.GetBytes((Half)input.Z), + ..BitConverter.GetBytes((Half)input.W), + ]; } } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 43630f6e..223f43ea 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -206,6 +206,9 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var submeshes = new List(); var vertexBuffer = new List(); var indices = new List(); + + var shapeData = new Dictionary>(); + var shapeValues = new List(); foreach (var submeshnodes in nodes) { @@ -214,6 +217,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var subOffset = submeshes.Count; var vertOffset = vertexBuffer.Count; var idxOffset = indices.Count; + var shapeValueOffset = shapeValues.Count; var ( vertexDeclaration, @@ -221,16 +225,18 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable xivMesh, xivSubmeshes, meshVertexBuffer, - meshIndices + meshIndices, + meshShapeData // fasdfasd ) = MeshThing(submeshnodes); vertexDeclarations.Add(vertexDeclaration); boneTables.Add(boneTable); + var meshStartIndex = (uint)(xivMesh.StartIndex + idxOffset / sizeof(ushort)); meshes.Add(xivMesh with { SubMeshIndex = (ushort)(xivMesh.SubMeshIndex + subOffset), // TODO: should probably define a type for index type hey. BoneTableIndex = (ushort)(xivMesh.BoneTableIndex + boneTableOffset), - StartIndex = (uint)(xivMesh.StartIndex + idxOffset / sizeof(ushort)), + StartIndex = meshStartIndex, VertexBufferOffset = xivMesh.VertexBufferOffset .Select(offset => (uint)(offset + vertOffset)) .ToArray(), @@ -243,6 +249,39 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable }); vertexBuffer.AddRange(meshVertexBuffer); indices.AddRange(meshIndices.SelectMany(index => BitConverter.GetBytes((ushort)index))); + foreach (var (key, (shapeMesh, meshShapeValues)) in meshShapeData) + { + List keyshapedata; + if (!shapeData.TryGetValue(key, out keyshapedata)) + { + keyshapedata = new(); + shapeData.Add(key, keyshapedata); + } + + keyshapedata.Add(shapeMesh with { + MeshIndexOffset = meshStartIndex, + ShapeValueOffset = (uint)shapeValueOffset, + }); + + shapeValues.AddRange(meshShapeValues); + } + } + + var shapes = new List(); + var shapeMeshes = new List(); + + foreach (var (name, sms) in shapeData) + { + var smOff = shapeMeshes.Count; + + shapeMeshes.AddRange(sms); + shapes.Add(new MdlFile.Shape() + { + ShapeName = name, + // TODO: THESE IS PER LOD + ShapeMeshStartIndex = [(ushort)smOff, 0, 0], + ShapeMeshCount = [(ushort)sms.Count, 0, 0], + }); } var mdl = new MdlFile() @@ -292,6 +331,10 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable // game clearly doesn't rely on this, but the "correct" values are a listing of the bones used by each submesh SubMeshBoneMap = [0], + Shapes = shapes.ToArray(), + ShapeMeshes = shapeMeshes.ToArray(), + ShapeValues = shapeValues.ToArray(), + Lods = [new MdlStructs.LodStruct() { MeshIndex = 0, @@ -323,7 +366,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable MdlStructs.MeshStruct, IEnumerable, IEnumerable, - IEnumerable + IEnumerable, + IDictionary)> ) MeshThing(IEnumerable nodes) { var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = Array.Empty()}; @@ -336,6 +380,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var indices = new List(); var strides = new byte[] {0, 0, 0}; var submeshes = new List(); + var morphData = new Dictionary>(); // TODO: check that attrs/elems/strides match - we should be generating per-mesh stuff for sanity's sake, but we need to make sure they match if there's >1 node mesh in a mesh. foreach (var node in nodes) @@ -343,7 +388,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var vertOff = vertexCount; var idxOff = indexCount; - var (vertDecl, newStrides, submesh, vertCount, vertStreams, idxCount, idxs) = NodeMeshThing(node); + var (vertDecl, newStrides, submesh, vertCount, vertStreams, idxCount, idxs, subMorphData) = NodeMeshThing(node); vertexDeclaration = vertDecl; // TODO: CHECK EQUAL AFTER FIRST strides = newStrides; // ALSO CHECK EQUAL vertexCount += vertCount; @@ -356,6 +401,25 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable IndexOffset = submesh.IndexOffset + idxOff // TODO: bone stuff probably }); + // TODO: HANDLE MORPHS, NEED TO ADJUST EVERY VALUE'S INDEX OFFSETS + foreach (var (key, shapeValues) in subMorphData) + { + List valueList; + if (!morphData.TryGetValue(key, out valueList)) + { + valueList = new(); + morphData.Add(key, valueList); + } + valueList.AddRange( + shapeValues + .Select(value => value with { + // but this is actually an index index + BaseIndicesIndex = (ushort)(value.BaseIndicesIndex + idxOff), + // this is a vert idx + ReplacingVertexIndex = (ushort)(value.ReplacingVertexIndex + vertOff), + }) + ); + } } // one of these per skinned mesh. @@ -390,13 +454,30 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable VertexStreamCount = (byte)(vertexDeclaration.VertexElements.Select(element => element.Stream).Max() + 1) }; + // TODO: can probably get away with flattening the values and blindly setting offsets in parent - mesh matters above, but the values are already Dealt With at this point + var shapeData = morphData.ToDictionary( + (pair) => pair.Key, + pair => ( + new MdlStructs.ShapeMeshStruct() + { + // TODO: this needs to be adjusted by the parent + MeshIndexOffset = 0, + ShapeValueCount = (uint)pair.Value.Count, + // TODO: Also update by parent + ShapeValueOffset = 0, + }, + pair.Value + ) + ); + return ( vertexDeclaration, boneTable, xivMesh, submeshes, streams[0].Concat(streams[1]).Concat(streams[2]), - indices + indices, + shapeData ); } @@ -408,7 +489,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable ushort, IEnumerable[], uint, - IEnumerable + IEnumerable, + IDictionary> ) NodeMeshThing(Node node) { // BoneTable (mesh.btidx = 255 means unskinned) @@ -423,9 +505,22 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var primitive = mesh.Primitives[0]; var accessors = primitive.VertexAccessors; + + // var foo = primitive.GetMorphTargetAccessors(0); + // var bar = foo["POSITION"]; + // var baz = bar.AsVector3Array(); + + var morphAccessors = Enumerable.Range(0, primitive.MorphTargetsCount) + // todo: map by name, probably? or do that later (probably later) + .Select(index => primitive.GetMorphTargetAccessors(index)); + + // TODO: name + var morphChangedVerts = Enumerable.Range(0, primitive.MorphTargetsCount) + .Select(_ => new List()) + .ToArray(); var rawAttributes = new[] { - VertexAttribute.Position(accessors), + VertexAttribute.Position(accessors, morphAccessors), VertexAttribute.BlendWeight(accessors), VertexAttribute.BlendIndex(accessors), VertexAttribute.Normal(accessors), @@ -440,9 +535,12 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable { if (attribute == null) continue; var element = attribute.Element; + // recreating this here really sucks - add a "withstream" or something. attributes.Add(new VertexAttribute( element with {Offset = offsets[element.Stream]}, - attribute.Write + attribute.Build, + attribute.HasMorph, + attribute.BuildMorph )); offsets[element.Stream] += attribute.Size; } @@ -460,7 +558,18 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable { foreach (var attribute in attributes) { - attribute.Write(vertexIndex, streams[attribute.Element.Stream]); + streams[attribute.Element.Stream].AddRange(attribute.Build(vertexIndex)); + } + + // this is a meme but idk maybe it's the best approach? it's not like the attr array is ever long + foreach (var (list, morphIndex) in morphChangedVerts.WithIndex()) + { + var hasMorph = attributes.Aggregate(false, (cur, attr) => cur || attr.HasMorph(morphIndex, vertexIndex)); + // Penumbra.Log.Information($"eh? {vertexIndex} {morphIndex}: {hasMorph}"); + if (hasMorph) + { + list.Add(vertexIndex); + } } } @@ -471,6 +580,52 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable // .ToArray(); var indices = primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); + // BLAH + // foreach (var (list, morphIndex) in morphChangedVerts.WithIndex()) + // { + // Penumbra.Log.Information($"morph {morphIndex}: {string.Join(",", list)}"); + // } + // TODO BUILD THE MORPH VERTS + // (source, target) + var morphmappingstuff = new List[morphChangedVerts.Length]; + foreach (var (list, morphIndex) in morphChangedVerts.WithIndex()) + { + var morphmaplist = morphmappingstuff[morphIndex] = new(); + foreach (var vertIdx in list) + { + foreach (var attribute in attributes) + { + streams[attribute.Element.Stream].AddRange(attribute.BuildMorph(morphIndex, vertIdx)); + } + + var fuck = indices.WithIndex() + .Where(pair => pair.Value == vertIdx) + .Select(pair => pair.Index); + + foreach (var something in fuck) + { + morphmaplist.Add(new MdlStructs.ShapeValueStruct(){ + BaseIndicesIndex = (ushort)something, + ReplacingVertexIndex = (ushort)vertexCount, + }); + } + vertexCount++; + } + } + + // TODO: HANDLE THIS BEING MISSING - probably warn or something, it's not the end of the world + var morphData = new Dictionary>(); + if (morphmappingstuff.Length > 0) + { + var morphnames = mesh.Extras.GetNode("targetNames").Deserialize>(); + morphData = morphmappingstuff + .Zip(morphnames) + .ToDictionary( + (pair) => pair.Second, + (pair) => pair.First + ); + } + // one of these per mesh var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() { @@ -521,7 +676,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable (ushort)vertexCount, streams, (uint)indices.Length, - indices + indices, + morphData ); } From 6641f5425bf8cfe6f12f7e433a7709c57f597031 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 5 Jan 2024 20:13:39 +1100 Subject: [PATCH 0321/1381] Add morph handling for normal/tangent --- .../Import/Models/Import/VertexAttribute.cs | 38 +++++++++++++++++-- Penumbra/Import/Models/ModelManager.cs | 4 +- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 9fd50513..37ccb79d 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -150,7 +150,7 @@ public class VertexAttribute ); } - public static VertexAttribute? Normal(Accessors accessors) + public static VertexAttribute? Normal(Accessors accessors, IEnumerable morphAccessors) { if (!accessors.TryGetValue("NORMAL", out var accessor)) return null; @@ -164,9 +164,24 @@ public class VertexAttribute var values = accessor.AsVector3Array(); + var foo = morphAccessors + .Select(ma => ma.GetValueOrDefault("NORMAL")?.AsVector3Array()) + .ToArray(); + return new VertexAttribute( element, - index => BuildHalf4(new Vector4(values[index], 0)) + index => BuildHalf4(new Vector4(values[index], 0)), + null, + (morphIndex, vertexIndex) => + { + var value = values[vertexIndex]; + + var delta = foo[morphIndex]?[vertexIndex]; + if (delta != null) + value += delta.Value; + + return BuildHalf4(new Vector4(value, 0)); + } ); } @@ -203,7 +218,7 @@ public class VertexAttribute ); } - public static VertexAttribute? Tangent1(Accessors accessors) + public static VertexAttribute? Tangent1(Accessors accessors, IEnumerable morphAccessors) { if (!accessors.TryGetValue("TANGENT", out var accessor)) return null; @@ -217,9 +232,24 @@ public class VertexAttribute var values = accessor.AsVector4Array(); + var foo = morphAccessors + .Select(ma => ma.GetValueOrDefault("TANGENT")?.AsVector3Array()) + .ToArray(); + return new VertexAttribute( element, - index => BuildByteFloat4(values[index]) + index => BuildByteFloat4(values[index]), + null, + (morphIndex, vertexIndex) => + { + var value = values[vertexIndex]; + + var delta = foo[morphIndex]?[vertexIndex]; + if (delta != null) + value += new Vector4(delta.Value, 0); + + return BuildByteFloat4(value); + } ); } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 223f43ea..d849f3eb 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -523,8 +523,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable VertexAttribute.Position(accessors, morphAccessors), VertexAttribute.BlendWeight(accessors), VertexAttribute.BlendIndex(accessors), - VertexAttribute.Normal(accessors), - VertexAttribute.Tangent1(accessors), + VertexAttribute.Normal(accessors, morphAccessors), + VertexAttribute.Tangent1(accessors, morphAccessors), VertexAttribute.Color(accessors), VertexAttribute.Uv(accessors), }; From 70a09264a8eba3275412f01535b55f2471865ef3 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 5 Jan 2024 22:35:36 +1100 Subject: [PATCH 0322/1381] Bone table imports --- .../Import/Models/Import/VertexAttribute.cs | 19 +- Penumbra/Import/Models/ModelManager.cs | 189 ++++++++++++++---- .../ModEditWindow.Models.MdlTab.cs | 2 +- 3 files changed, 170 insertions(+), 40 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 37ccb79d..f2ec6f1a 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -120,13 +120,12 @@ public class VertexAttribute return new VertexAttribute( element, - // TODO: TEMP TESTING PINNED TO BONE 0 UNTIL I SET UP BONE MAPPINGS - index => BuildByteFloat4(Vector4.UnitX) + index => BuildByteFloat4(values[index]) ); } // TODO: this will need to take in a skeleton mapping of some kind so i can persist the bones used and wire up the joints correctly. hopefully by the "write vertex buffer" stage of building, we already know something about the skeleton. - public static VertexAttribute? BlendIndex(Accessors accessors) + public static VertexAttribute? BlendIndex(Accessors accessors, IDictionary? boneMap) { if (!accessors.TryGetValue("JOINTS_0", out var accessor)) return null; @@ -134,6 +133,9 @@ public class VertexAttribute if (!accessors.ContainsKey("WEIGHTS_0")) throw new Exception("Mesh contained JOINTS_0 attribute but no corresponding WEIGHTS_0 attribute."); + if (boneMap == null) + throw new Exception("Mesh contained JOINTS_0 attribute but no bone mapping was created."); + var element = new MdlStructs.VertexElement() { Stream = 0, @@ -145,8 +147,15 @@ public class VertexAttribute return new VertexAttribute( element, - // TODO: TEMP TESTING PINNED TO BONE 0 UNTIL I SET UP BONE MAPPINGS - index => BuildUInt(Vector4.Zero) + index => { + var foo = values[index]; + return BuildUInt(new Vector4( + boneMap[(ushort)foo.X], + boneMap[(ushort)foo.Y], + boneMap[(ushort)foo.Z], + boneMap[(ushort)foo.W] + )); + } ); } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index d849f3eb..875c6071 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -189,7 +189,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var nodes = model.LogicalNodes .Where(node => node.Mesh != null) .Take(6) // this model has all 3 lods in it - the first 6 are the real lod0 - .SelectWhere(node => { + .SelectWhere(node => + { var name = node.Name ?? node.Mesh.Name; var match = MeshNameGroupingRegex().Match(name); return match.Success @@ -201,6 +202,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable // this is a representation of a single LoD var vertexDeclarations = new List(); + var bones = new List(); var boneTables = new List(); var meshes = new List(); var submeshes = new List(); @@ -209,7 +211,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var shapeData = new Dictionary>(); var shapeValues = new List(); - + foreach (var submeshnodes in nodes) { var boneTableOffset = boneTables.Count; @@ -221,21 +223,52 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var ( vertexDeclaration, - boneTable, + // boneTable, xivMesh, xivSubmeshes, meshVertexBuffer, meshIndices, - meshShapeData // fasdfasd + meshShapeData, + meshBoneList ) = MeshThing(submeshnodes); + var boneTableIndex = 255; + // TODO: a better check than this would be real good + if (meshBoneList.Count() > 0) + { + var boneIndices = new List(); + foreach (var mb in meshBoneList) + { + var boneIndex = bones.IndexOf(mb); + if (boneIndex == -1) + { + boneIndex = bones.Count; + bones.Add(mb); + } + boneIndices.Add((ushort)boneIndex); + } + + if (boneIndices.Count > 64) + throw new Exception("One mesh cannot be weighted to more than 64 bones."); + + var boneIndicesArray = new ushort[64]; + Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); + + boneTableIndex = boneTableOffset; + boneTables.Add(new MdlStructs.BoneTableStruct() + { + BoneCount = (byte)boneIndices.Count, + BoneIndex = boneIndicesArray, + }); + } + vertexDeclarations.Add(vertexDeclaration); - boneTables.Add(boneTable); var meshStartIndex = (uint)(xivMesh.StartIndex + idxOffset / sizeof(ushort)); - meshes.Add(xivMesh with { + meshes.Add(xivMesh with + { SubMeshIndex = (ushort)(xivMesh.SubMeshIndex + subOffset), // TODO: should probably define a type for index type hey. - BoneTableIndex = (ushort)(xivMesh.BoneTableIndex + boneTableOffset), + BoneTableIndex = (ushort)boneTableIndex, StartIndex = meshStartIndex, VertexBufferOffset = xivMesh.VertexBufferOffset .Select(offset => (uint)(offset + vertOffset)) @@ -243,7 +276,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable }); // TODO: could probably do this with linq cleaner foreach (var xivSubmesh in xivSubmeshes) - submeshes.Add(xivSubmesh with { + submeshes.Add(xivSubmesh with + { // TODO: this will need to keep ticking up for each submesh in the same mesh IndexOffset = (uint)(xivSubmesh.IndexOffset + idxOffset / sizeof(ushort)) }); @@ -258,7 +292,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable shapeData.Add(key, keyshapedata); } - keyshapedata.Add(shapeMesh with { + keyshapedata.Add(shapeMesh with + { MeshIndexOffset = meshStartIndex, ShapeValueOffset = (uint)shapeValueOffset, }); @@ -347,9 +382,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable IndexDataOffset = (uint)vertexBuffer.Count, }, ], - Bones = [ - "j_kosi", - ], + Bones = bones.ToArray(), Materials = [ "/mt_c0201e6180_top_a.mtrl", ], @@ -362,15 +395,16 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable // this return type is an absolute meme, class that shit up. private ( MdlStructs.VertexDeclarationStruct, - MdlStructs.BoneTableStruct, + // MdlStructs.BoneTableStruct, MdlStructs.MeshStruct, IEnumerable, IEnumerable, IEnumerable, - IDictionary)> + IDictionary)>, + IEnumerable ) MeshThing(IEnumerable nodes) { - var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = Array.Empty()}; + var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = Array.Empty() }; var vertexCount = (ushort)0; // there's gotta be a better way to do this with streams or enumerables or something, surely var streams = new List[3]; @@ -378,17 +412,57 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable streams[i] = new List(); var indexCount = (uint)0; var indices = new List(); - var strides = new byte[] {0, 0, 0}; + var strides = new byte[] { 0, 0, 0 }; var submeshes = new List(); var morphData = new Dictionary>(); + /* + THOUGHTS + per submesh node, before calling down to build the mesh, build a bone mapping of joint index -> bone name (not node index) - the joint indexes are what will be used in the vertices. + per submesh node, eagerly collect all blend indexes (joints) used before building anything - just as a set or something + the above means i can create a limited set and a mapping, i.e. if skeleton contains {0->a 1->b 2->c}, and mesh contains 0, 2, then i can output [a, c] + {0->0, 2->1} + (throw if >64 entries in that name array) + + then for the second prim, + again get the joint-name mapping, and again get the joint set + then can extend the values. using the samme example, if skeleton2 contains {0->c 1->d, 2->e} and mesh contains [0,2] again, then bone array can be extended to [a, c, e] and the mesh-specific mapping would be {0->1, 2->2} + + repeat, etc + */ + + var usedBones = new List(); + // TODO: check that attrs/elems/strides match - we should be generating per-mesh stuff for sanity's sake, but we need to make sure they match if there's >1 node mesh in a mesh. foreach (var node in nodes) { var vertOff = vertexCount; var idxOff = indexCount; - var (vertDecl, newStrides, submesh, vertCount, vertStreams, idxCount, idxs, subMorphData) = NodeMeshThing(node); + Dictionary? nodeBoneMap = null; + var bonething = WalkBoneThing(node); + if (bonething.HasValue) + { + var (boneNames, usedJoints) = bonething.Value; + nodeBoneMap = new(); + + // todo: probably linq this shit + foreach (var usedJoint in usedJoints) + { + // this is the 0,2 + var boneName = boneNames[usedJoint]; + var boneIdx = usedBones.IndexOf(boneName); + if (boneIdx == -1) + { + boneIdx = usedBones.Count; + usedBones.Add(boneName); + } + nodeBoneMap.Add(usedJoint, (ushort)boneIdx); + } + + Penumbra.Log.Information($"nbm {string.Join(",", nodeBoneMap.Select(kv => $"{kv.Key}:{kv.Value}"))}"); + } + + var (vertDecl, newStrides, submesh, vertCount, vertStreams, idxCount, idxs, subMorphData) = NodeMeshThing(node, nodeBoneMap); vertexDeclaration = vertDecl; // TODO: CHECK EQUAL AFTER FIRST strides = newStrides; // ALSO CHECK EQUAL vertexCount += vertCount; @@ -397,7 +471,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable indexCount += idxCount; // we need to offset the indexes to point into the new stuff indices.AddRange(idxs.Select(idx => (ushort)(idx + vertOff))); - submeshes.Add(submesh with { + submeshes.Add(submesh with + { IndexOffset = submesh.IndexOffset + idxOff // TODO: bone stuff probably }); @@ -412,7 +487,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable } valueList.AddRange( shapeValues - .Select(value => value with { + .Select(value => value with + { // but this is actually an index index BaseIndicesIndex = (ushort)(value.BaseIndicesIndex + idxOff), // this is a vert idx @@ -424,12 +500,12 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable // one of these per skinned mesh. // TODO: check if mesh has skinning at all. (err if mixed?) - var boneTable = new MdlStructs.BoneTableStruct() - { - BoneCount = 1, - // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. - BoneIndex = new ushort[64], - }; + // var boneTable = new MdlStructs.BoneTableStruct() + // { + // BoneCount = 1, + // // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. + // BoneIndex = new ushort[64], + // }; // mesh var xivMesh = new MdlStructs.MeshStruct() @@ -472,15 +548,59 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable return ( vertexDeclaration, - boneTable, + // boneTable, xivMesh, submeshes, streams[0].Concat(streams[1]).Concat(streams[2]), indices, - shapeData + shapeData, + usedBones ); } + private (string[], ISet)? WalkBoneThing(Node node) + { + // + if (node.Skin == null) + return null; + + var jointNames = Enumerable.Range(0, node.Skin.JointsCount) + .Select(index => node.Skin.GetJoint(index).Joint.Name ?? $"UNNAMED") + .ToArray(); + + // it might make sense to do this in the submesh handling - i do need to maintain the mesh-wide bone list, but that can be passed in/out, perhaps? + var mesh = node.Mesh; + if (mesh.Primitives.Count != 1) + throw new Exception($"Mesh has {mesh.Primitives.Count} primitives, expected 1."); + var primitive = mesh.Primitives[0]; + + var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0"); + if (jointsAccessor == null) + throw new Exception($"Skinned meshes must contain a JOINTS_0 attribute."); + + // var weightsAccssor = primitive.GetVertexAccessor("WEIGHTS_0"); + // if (weightsAccssor == null) + // throw new Exception($"Skinned meshes must contain a WEIGHTS_0 attribute."); + + var usedJoints = new HashSet(); + + // TODO: would be neat to omit any joints that are only used in 0-weight positions, but doing so would require being a _little_ smarter in vertex attrs on how to fall back when mappings aren't found - or otherwise try to ensure that mappings for unused stuff always exists + // foreach (var (joints, weights) in jointsAccessor.AsVector4Array().Zip(weightsAccssor.AsVector4Array())) + // { + // for (var index = 0; index < 4; index++) + // if (weights[index] > 0) + // usedJoints.Add((ushort)joints[index]); + // } + + foreach (var joints in jointsAccessor.AsVector4Array()) + { + for (var index = 0; index < 4; index++) + usedJoints.Add((ushort)joints[index]); + } + + return (jointNames, usedJoints); + } + private ( MdlStructs.VertexDeclarationStruct, byte[], @@ -491,7 +611,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable uint, IEnumerable, IDictionary> - ) NodeMeshThing(Node node) + ) NodeMeshThing(Node node, IDictionary? nodeBoneMap) { // BoneTable (mesh.btidx = 255 means unskinned) // vertexdecl @@ -505,7 +625,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var primitive = mesh.Primitives[0]; var accessors = primitive.VertexAccessors; - + // var foo = primitive.GetMorphTargetAccessors(0); // var bar = foo["POSITION"]; // var baz = bar.AsVector3Array(); @@ -522,7 +642,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var rawAttributes = new[] { VertexAttribute.Position(accessors, morphAccessors), VertexAttribute.BlendWeight(accessors), - VertexAttribute.BlendIndex(accessors), + VertexAttribute.BlendIndex(accessors, nodeBoneMap), VertexAttribute.Normal(accessors, morphAccessors), VertexAttribute.Tangent1(accessors, morphAccessors), VertexAttribute.Color(accessors), @@ -530,14 +650,14 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable }; var attributes = new List(); - var offsets = new byte[] {0, 0, 0}; + var offsets = new byte[] { 0, 0, 0 }; foreach (var attribute in rawAttributes) { if (attribute == null) continue; var element = attribute.Element; // recreating this here really sucks - add a "withstream" or something. attributes.Add(new VertexAttribute( - element with {Offset = offsets[element.Stream]}, + element with { Offset = offsets[element.Stream] }, attribute.Build, attribute.HasMorph, attribute.BuildMorph @@ -547,7 +667,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var strides = offsets; // TODO: when merging submeshes, i'll need to check that vert els are the same for all of them, as xiv only stores verts at the mesh level and shares them. - + var streams = new List[3]; for (var i = 0; i < 3; i++) streams[i] = new List(); @@ -604,7 +724,8 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable foreach (var something in fuck) { - morphmaplist.Add(new MdlStructs.ShapeValueStruct(){ + morphmaplist.Add(new MdlStructs.ShapeValueStruct() + { BaseIndicesIndex = (ushort)something, ReplacingVertexIndex = (ushort)vertexCount, }); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 5d9abda6..e030c8c0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -81,7 +81,7 @@ public partial class ModEditWindow public void Import() { // TODO: this needs to be fleshed out a bunch. - _edit._models.ImportGltf().ContinueWith(v => Initialize(v.Result)); + _edit._models.ImportGltf().ContinueWith(v => Initialize(v.Result ?? Mdl)); } /// Export model to an interchange format. From 41d900ff5148d42b8d1cd1e585bac557618e4743 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Jan 2024 14:27:05 +0100 Subject: [PATCH 0323/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 192fd1e6..ac3fc098 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 192fd1e6ad269c3cbdb81aa8c43a8bc20c5ae7f0 +Subproject commit ac3fc0981ac8f503ac91d2419bd28c54f271763e From 306a9c217a2436ae58e2eb454eab0a9639fdd789 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Jan 2024 14:51:41 +0100 Subject: [PATCH 0324/1381] Fix FileDialog being drawn multiple times. --- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 -- Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs | 3 --- 2 files changed, 5 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 336be1a4..4783e76b 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -158,8 +158,6 @@ public class FileEditor : IDisposable where T : class, IWritable _quickImport = null; } - - _fileDialog.Draw(); } public void Reset() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 82fc78c0..8d1c8cb7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -6,7 +6,6 @@ using OtterGui.Raii; using OtterGui; using OtterGui.Classes; using Penumbra.GameData; -using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Interop; using Penumbra.String; @@ -43,8 +42,6 @@ public partial class ModEditWindow ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); DrawOtherShaderPackageDetails(file); - file.FileDialog.Draw(); - ret |= file.Shpk.IsChanged(); return !disabled && ret; From 55f38865e3d9885b3643b7d7e588d5c069d966e9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Jan 2024 18:13:03 +0100 Subject: [PATCH 0325/1381] Memorize last selected mod and state of advanced editing window. --- Penumbra/Communication/ModPathChanged.cs | 3 ++ Penumbra/EphemeralConfig.cs | 32 +++++++++++-- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 49 ++++++++++++-------- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 28 ++++++++--- 4 files changed, 82 insertions(+), 30 deletions(-) diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index 3ec64f7e..e6291781 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -19,6 +19,9 @@ public sealed class ModPathChanged() { public enum Priority { + /// + EphemeralConfig = -500, + /// CollectionCacheManagerAddition = -100, diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 6c87d331..8cf23de6 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -2,7 +2,10 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using OtterGui.Classes; using Penumbra.Api.Enums; +using Penumbra.Communication; using Penumbra.Enums; +using Penumbra.Mods; +using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; using Penumbra.UI.ResourceWatcher; @@ -11,11 +14,14 @@ using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra; -public class EphemeralConfig : ISavable +public class EphemeralConfig : ISavable, IDisposable { [JsonIgnore] private readonly SaveService _saveService; + [JsonIgnore] + private readonly ModPathChanged _modPathChanged; + public int Version { get; set; } = Configuration.Constants.CurrentVersion; public int LastSeenVersion { get; set; } = PenumbraChangelog.LastChangelogVersion; public bool DebugSeparateWindow { get; set; } = false; @@ -31,17 +37,24 @@ public class EphemeralConfig : ISavable public TabType SelectedTab { get; set; } = TabType.Settings; public ChangedItemDrawer.ChangedItemIcon ChangedItemFilter { get; set; } = ChangedItemDrawer.DefaultFlags; public bool FixMainWindow { get; set; } = false; + public string LastModPath { get; set; } = string.Empty; + public bool AdvancedEditingOpen { get; set; } = false; /// /// Load the current configuration. /// Includes adding new colors and migrating from old versions. /// - public EphemeralConfig(SaveService saveService) + public EphemeralConfig(SaveService saveService, ModPathChanged modPathChanged) { - _saveService = saveService; + _saveService = saveService; + _modPathChanged = modPathChanged; Load(); + _modPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.EphemeralConfig); } + public void Dispose() + => _modPathChanged.Unsubscribe(OnModPathChanged); + private void Load() { static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) @@ -80,8 +93,19 @@ public class EphemeralConfig : ISavable public void Save(StreamWriter writer) { - using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + using var jWriter = new JsonTextWriter(writer); + jWriter.Formatting = Formatting.Indented; var serializer = new JsonSerializer { Formatting = Formatting.Indented }; serializer.Serialize(jWriter, this); } + + /// Overwrite the last saved mod path if it changes. + private void OnModPathChanged(ModPathChangeType type, Mod mod, DirectoryInfo? old, DirectoryInfo? _) + { + if (type is not ModPathChangeType.Moved || !string.Equals(old?.Name, LastModPath, StringComparison.OrdinalIgnoreCase)) + return; + + LastModPath = mod.Identifier; + Save(); + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 96957ba8..167adafe 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -145,12 +145,20 @@ public partial class ModEditWindow : Window, IDisposable _materialTab.Reset(); _modelTab.Reset(); _shaderPackageTab.Reset(); + _config.Ephemeral.AdvancedEditingOpen = false; + _config.Ephemeral.Save(); } public override void Draw() { using var performance = _performance.Measure(PerformanceType.UiAdvancedWindow); + if (!_config.Ephemeral.AdvancedEditingOpen) + { + _config.Ephemeral.AdvancedEditingOpen = true; + _config.Ephemeral.Save(); + } + using var tabBar = ImRaii.TabBar("##tabs"); if (!tabBar) return; @@ -566,34 +574,36 @@ public partial class ModEditWindow : Window, IDisposable public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, - CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, + CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, ChangedItemDrawer changedItemDrawer, IObjectTable objects, IFramework framework, CharacterBaseDestructor characterBaseDestructor) : base(WindowBaseLabel) { - _performance = performance; - _itemSwapTab = itemSwapTab; - _gameData = gameData; - _config = config; - _editor = editor; - _metaFileManager = metaFileManager; - _stainService = stainService; - _activeCollections = activeCollections; - _modMergeTab = modMergeTab; - _communicator = communicator; - _dragDropManager = dragDropManager; - _textures = textures; - _models = models; - _fileDialog = fileDialog; - _objects = objects; - _framework = framework; + _performance = performance; + _itemSwapTab = itemSwapTab; + _gameData = gameData; + _config = config; + _editor = editor; + _metaFileManager = metaFileManager; + _stainService = stainService; + _activeCollections = activeCollections; + _modMergeTab = modMergeTab; + _communicator = communicator; + _dragDropManager = dragDropManager; + _textures = textures; + _models = models; + _fileDialog = fileDialog; + _objects = objects; + _framework = framework; _characterBaseDestructor = characterBaseDestructor; _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new MdlTab(this, bytes, path, _mod)); + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, + (bytes, path, _) => new MdlTab(this, bytes, path, _mod)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", - () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, + () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, + () => _mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); @@ -601,6 +611,7 @@ public partial class ModEditWindow : Window, IDisposable _quickImportViewer = new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModEditWindow); + IsOpen = _config is { OpenWindowAtStart: true, Ephemeral.AdvancedEditingOpen: true }; } public void Dispose() diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index c42b1018..0990f27b 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -39,8 +39,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector 0) + { + var mod = _modManager.FirstOrDefault(m + => string.Equals(m.Identifier, _config.Ephemeral.LastModPath, StringComparison.OrdinalIgnoreCase)); + if (mod != null) + SelectByValue(mod); + } + _communicator.CollectionChange.Subscribe(OnCollectionChange, CollectionChange.Priority.ModFileSystemSelector); _communicator.ModSettingChanged.Subscribe(OnSettingChange, ModSettingChanged.Priority.ModFileSystemSelector); _communicator.CollectionInheritanceChanged.Subscribe(OnInheritanceChange, CollectionInheritanceChanged.Priority.ModFileSystemSelector); @@ -87,15 +94,15 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Fri, 5 Jan 2024 19:02:50 +0100 Subject: [PATCH 0326/1381] Rework game path selection a bit. --- .../ModEditWindow.Models.MdlTab.cs | 63 +++++++++------ .../UI/AdvancedWindow/ModEditWindow.Models.cs | 79 +++++++++++++------ 2 files changed, 93 insertions(+), 49 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 20a4129d..93e674ea 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -12,27 +12,29 @@ public partial class ModEditWindow { private ModEditWindow _edit; - public readonly MdlFile Mdl; + public readonly MdlFile Mdl; private readonly List[] _attributes; - public List? GamePaths { get; private set ;} - public int GamePathIndex; - - public bool PendingIo { get; private set; } = false; + public List? GamePaths { get; private set; } + public int GamePathIndex; + + public bool PendingIo { get; private set; } = false; public string? IoException { get; private set; } = null; [GeneratedRegex(@"chara/(?:equipment|accessory)/(?'Set'[a-z]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", RegexOptions.Compiled)] private static partial Regex CharaEquipmentRegex(); - [GeneratedRegex(@"chara/human/(?'Race'c\d{4})/obj/(?'Type'[^/]+)/(?'Set'[^/]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", RegexOptions.Compiled)] + [GeneratedRegex(@"chara/human/(?'Race'c\d{4})/obj/(?'Type'[^/]+)/(?'Set'[^/]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", + RegexOptions.Compiled)] private static partial Regex CharaHumanRegex(); - [GeneratedRegex(@"chara/(?'SubCategory'demihuman|monster|weapon)/(?'Set'w\d{4})/obj/body/(?'Body'b\d{4})/model/\k'Set'\k'Body'.mdl", RegexOptions.Compiled)] + [GeneratedRegex(@"chara/(?'SubCategory'demihuman|monster|weapon)/(?'Set'w\d{4})/obj/body/(?'Body'b\d{4})/model/\k'Set'\k'Body'.mdl", + RegexOptions.Compiled)] private static partial Regex CharaBodyRegex(); public MdlTab(ModEditWindow edit, byte[] bytes, string path, Mod? mod) { - _edit = edit; + _edit = edit; Mdl = new MdlFile(bytes); _attributes = CreateAttributes(Mdl); @@ -54,21 +56,29 @@ public partial class ModEditWindow /// Mod within which the .mdl is resolved. private void FindGamePaths(string path, Mod mod) { + if (!Path.IsPathRooted(path) && Utf8GamePath.FromString(path, out var p)) + { + GamePaths = [p]; + return; + } + PendingIo = true; - var task = Task.Run(() => { + var task = Task.Run(() => + { // TODO: Is it worth trying to order results based on option priorities for cases where more than one match is found? - // NOTE: We're using case insensitive comparisons, as option group paths in mods are stored in lower case, but the mod editor uses paths directly from the file system, which may be mixed case. + // NOTE: We're using case-insensitive comparisons, as option group paths in mods are stored in lower case, but the mod editor uses paths directly from the file system, which may be mixed case. return mod.AllSubMods - .SelectMany(submod => submod.Files.Concat(submod.FileSwaps)) + .SelectMany(m => m.Files.Concat(m.FileSwaps)) .Where(kv => kv.Value.FullName.Equals(path, StringComparison.OrdinalIgnoreCase)) .Select(kv => kv.Key) .ToList(); }); - task.ContinueWith(task => { - IoException = task.Exception?.ToString(); - PendingIo = false; - GamePaths = task.Result; + task.ContinueWith(t => + { + IoException = t.Exception?.ToString(); + PendingIo = false; + GamePaths = t.Result; }); } @@ -77,19 +87,23 @@ public partial class ModEditWindow public void Export(string outputPath, Utf8GamePath mdlPath) { SklbFile? sklb = null; - try { + try + { var sklbPath = GetSklbPath(mdlPath.ToString()); sklb = sklbPath != null ? ReadSklb(sklbPath) : null; - } catch (Exception exception) { + } + catch (Exception exception) + { IoException = exception?.ToString(); return; } PendingIo = true; _edit._models.ExportToGltf(Mdl, sklb, outputPath) - .ContinueWith(task => { + .ContinueWith(task => + { IoException = task.Exception?.ToString(); - PendingIo = false; + PendingIo = false; }); } @@ -114,7 +128,7 @@ public partial class ModEditWindow return type switch { "body" or "tail" => $"chara/human/{race}/skeleton/base/b0001/skl_{race}b0001.sklb", - _ => throw new Exception($"Currently unsupported human model type \"{type}\"."), + _ => throw new Exception($"Currently unsupported human model type \"{type}\"."), }; } @@ -123,7 +137,7 @@ public partial class ModEditWindow if (match.Success) { var subCategory = match.Groups["SubCategory"].Value; - var set = match.Groups["Set"].Value; + var set = match.Groups["Set"].Value; return $"chara/{subCategory}/{set}/skeleton/base/b0001/skl_{set}b0001.sklb"; } @@ -137,16 +151,17 @@ public partial class ModEditWindow // TODO: if cross-collection lookups are turned off, this conversion can be skipped if (!Utf8GamePath.FromString(sklbPath, out var utf8SklbPath, true)) throw new Exception($"Resolved skeleton path {sklbPath} could not be converted to a game path."); - + var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8SklbPath); // TODO: is it worth trying to use streams for these instead? i'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... var bytes = resolvedPath switch { - null => _edit._gameData.GetFile(sklbPath)?.Data, + null => _edit._gameData.GetFile(sklbPath)?.Data, FullPath path => File.ReadAllBytes(path.ToPath()), }; if (bytes == null) - throw new Exception($"Resolved skeleton path {sklbPath} could not be found. If modded, is it enabled in the current collection?"); + throw new Exception( + $"Resolved skeleton path {sklbPath} could not be found. If modded, is it enabled in the current collection?"); return new SklbFile(bytes); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index aa69953b..3891eb95 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -20,6 +20,8 @@ public partial class ModEditWindow private string _modelNewMaterial = string.Empty; private readonly List _subMeshAttributeTagWidgets = []; + private string _customPath = string.Empty; + private Utf8GamePath _customGamePath = Utf8GamePath.Empty; private bool DrawModelPanel(MdlTab tab, bool disabled) { @@ -51,10 +53,6 @@ public partial class ModEditWindow private void DrawExport(MdlTab tab, bool disabled) { - // IO on a disabled panel doesn't really make sense. - if (disabled) - return; - if (!ImGui.CollapsingHeader("Export")) return; @@ -70,16 +68,14 @@ public partial class ModEditWindow DrawGamePathCombo(tab); - if (ImGuiUtil.DrawDisabledButton("Export to glTF", Vector2.Zero, "Exports this mdl file to glTF, for use in 3D authoring applications.", tab.PendingIo)) - { - var gamePath = tab.GamePaths[tab.GamePathIndex]; - - _fileDialog.OpenSavePicker( - "Save model as glTF.", - ".gltf", - Path.GetFileNameWithoutExtension(gamePath.Filename().ToString()), - ".gltf", - (valid, path) => { + var gamePath = tab.GamePathIndex >= 0 && tab.GamePathIndex < tab.GamePaths.Count + ? tab.GamePaths[tab.GamePathIndex] + : _customGamePath; + if (ImGuiUtil.DrawDisabledButton("Export to glTF", Vector2.Zero, "Exports this mdl file to glTF, for use in 3D authoring applications.", + tab.PendingIo || gamePath.IsEmpty)) + _fileDialog.OpenSavePicker("Save model as glTF.", ".gltf", Path.GetFileNameWithoutExtension(gamePath.Filename().ToString()), + ".gltf", (valid, path) => + { if (!valid) return; @@ -88,27 +84,60 @@ public partial class ModEditWindow _mod!.ModPath.FullName, false ); - } if (tab.IoException != null) ImGuiUtil.TextWrapped(tab.IoException); - - return; } private void DrawGamePathCombo(MdlTab tab) { - using var combo = ImRaii.Combo("Game Path", tab.GamePaths![tab.GamePathIndex].ToString()); - if (!combo) - return; - - foreach (var (path, index) in tab.GamePaths.WithIndex()) + if (tab.GamePaths!.Count == 0) { - if (!ImGui.Selectable(path.ToString(), index == tab.GamePathIndex)) - continue; + ImGui.TextUnformatted("No associated game path detected. Valid game paths are currently necessary for exporting."); + if (ImGui.InputTextWithHint("##customInput", "Enter custom game path...", ref _customPath, 256)) + if (!Utf8GamePath.FromString(_customPath, out _customGamePath, false)) + _customGamePath = Utf8GamePath.Empty; - tab.GamePathIndex = index; + return; } + + DrawComboButton(tab); + } + + private static void DrawComboButton(MdlTab tab) + { + const string label = "Game Path"; + var preview = tab.GamePaths![tab.GamePathIndex].ToString(); + var labelWidth = ImGui.CalcTextSize(label).X + ImGui.GetStyle().ItemInnerSpacing.X; + var buttonWidth = ImGui.GetContentRegionAvail().X - labelWidth; + if (tab.GamePaths!.Count == 1) + { + using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); + using var color = ImRaii.PushColor(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.FrameBg)) + .Push(ImGuiCol.ButtonHovered, ImGui.GetColorU32(ImGuiCol.FrameBgHovered)) + .Push(ImGuiCol.ButtonActive, ImGui.GetColorU32(ImGuiCol.FrameBgActive)); + using var group = ImRaii.Group(); + ImGui.Button(preview, new Vector2(buttonWidth, 0)); + ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.X); + ImGui.TextUnformatted("Game Path"); + } + else + { + ImGui.SetNextItemWidth(buttonWidth); + using var combo = ImRaii.Combo("Game Path", preview); + if (combo.Success) + foreach (var (path, index) in tab.GamePaths.WithIndex()) + { + if (!ImGui.Selectable(path.ToString(), index == tab.GamePathIndex)) + continue; + + tab.GamePathIndex = index; + } + } + + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImGui.SetClipboardText(preview); + ImGuiUtil.HoverTooltip("Right-Click to copy to clipboard.", ImGuiHoveredFlags.AllowWhenDisabled); } private bool DrawModelMaterialDetails(MdlTab tab, bool disabled) From b5b3e1b1f26184380dc49a425e7ccc74836262d0 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 6 Jan 2024 11:55:37 +1100 Subject: [PATCH 0327/1381] Tidy up vertex attributes --- .../Import/Models/Import/VertexAttribute.cs | 113 +++++++++--------- Penumbra/Import/Models/ModelManager.cs | 8 +- 2 files changed, 55 insertions(+), 66 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index f2ec6f1a..cae068db 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -13,11 +13,11 @@ public class VertexAttribute { /// XIV vertex element metadata structure. public readonly MdlStructs.VertexElement Element; - /// Write this vertex attribute's value at the specified index to the provided byte array. + /// Build a byte array containing this vertex attribute's data for the specified vertex index. public readonly BuildFn Build; - + /// Check if the specified morph target index contains a morph for the specified vertex index. public readonly HasMorphFn HasMorph; - + /// Build a byte array containing this vertex attribute's data, as modified by the specified morph target, for the specified vertex index. public readonly BuildMorphFn BuildMorph; /// Size in bytes of a single vertex's attribute value. @@ -33,7 +33,7 @@ public class VertexAttribute _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), }; - public VertexAttribute( + private VertexAttribute( MdlStructs.VertexElement element, BuildFn write, HasMorphFn? hasMorph = null, @@ -46,17 +46,19 @@ public class VertexAttribute BuildMorph = buildMorph ?? DefaultBuildMorph; } - // todo: this is per-shape at the moment - consider if it should do them all at once (i mean we always want to check all of them, it's mostly a semantics question on who owns the loop) - private static bool DefaultHasMorph(int morphIndex, int vertexIndex) - { - return false; - } + public VertexAttribute WithOffset(byte offset) => new VertexAttribute( + Element with { Offset = offset }, + Build, + HasMorph, + BuildMorph + ); - // xiv stores shapes as full vertex replacements, so the default value for a morph attribute is simply it's built state (rather than a delta or w/e) - private byte[] DefaultBuildMorph(int morphIndex, int vertexIndex) - { - return Build(vertexIndex); - } + // We assume that attributes don't have morph data unless explicitly configured. + private static bool DefaultHasMorph(int morphIndex, int vertexIndex) => false; + + // XIV stores shapes as full vertex replacements, so all attributes need to output something for a morph. + // As a fallback, we're just building the normal vertex data for the index. + private byte[] DefaultBuildMorph(int morphIndex, int vertexIndex) => Build(vertexIndex); public static VertexAttribute Position(Accessors accessors, IEnumerable morphAccessors) { @@ -72,27 +74,27 @@ public class VertexAttribute var values = accessor.AsVector3Array(); - var foo = morphAccessors - .Select(ma => ma.GetValueOrDefault("POSITION")?.AsVector3Array()) + var morphValues = morphAccessors + .Select(accessors => accessors.GetValueOrDefault("POSITION")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, index => BuildSingle3(values[index]), - // TODO: at the moment this is only defined for position - is it worth setting one up for normal, too? - (morphIndex, vertexIndex) => + + hasMorph: (morphIndex, vertexIndex) => { - var deltas = foo[morphIndex]; + var deltas = morphValues[morphIndex]; if (deltas == null) return false; var delta = deltas[vertexIndex]; return delta != Vector3.Zero; }, - // TODO: this will _need_ to be defined for any values that appear in morphs, i.e. geom and maybe mats - (morphIndex, vertexIndex) => + + buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; - var delta = foo[morphIndex]?[vertexIndex]; + var delta = morphValues[morphIndex]?[vertexIndex]; if (delta != null) value += delta.Value; @@ -124,7 +126,6 @@ public class VertexAttribute ); } - // TODO: this will need to take in a skeleton mapping of some kind so i can persist the bones used and wire up the joints correctly. hopefully by the "write vertex buffer" stage of building, we already know something about the skeleton. public static VertexAttribute? BlendIndex(Accessors accessors, IDictionary? boneMap) { if (!accessors.TryGetValue("JOINTS_0", out var accessor)) @@ -147,13 +148,14 @@ public class VertexAttribute return new VertexAttribute( element, - index => { - var foo = values[index]; + index => + { + var gltfIndices = values[index]; return BuildUInt(new Vector4( - boneMap[(ushort)foo.X], - boneMap[(ushort)foo.Y], - boneMap[(ushort)foo.Z], - boneMap[(ushort)foo.W] + boneMap[(ushort)gltfIndices.X], + boneMap[(ushort)gltfIndices.Y], + boneMap[(ushort)gltfIndices.Z], + boneMap[(ushort)gltfIndices.W] )); } ); @@ -173,19 +175,19 @@ public class VertexAttribute var values = accessor.AsVector3Array(); - var foo = morphAccessors - .Select(ma => ma.GetValueOrDefault("NORMAL")?.AsVector3Array()) + var morphValues = morphAccessors + .Select(accessors => accessors.GetValueOrDefault("NORMAL")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, index => BuildHalf4(new Vector4(values[index], 0)), - null, - (morphIndex, vertexIndex) => + + buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; - var delta = foo[morphIndex]?[vertexIndex]; + var delta = morphValues[morphIndex]?[vertexIndex]; if (delta != null) value += delta.Value; @@ -208,6 +210,7 @@ public class VertexAttribute var values1 = accessor1.AsVector2Array(); + // There's only one TEXCOORD, output UV coordinates as vec2s. if (!accessors.TryGetValue("TEXCOORD_1", out var accessor2)) return new VertexAttribute( element with { Type = (byte)MdlFile.VertexType.Half2 }, @@ -216,6 +219,7 @@ public class VertexAttribute var values2 = accessor2.AsVector2Array(); + // Two TEXCOORDs are available, repack them into xiv's vec4 [0X, 0Y, 1X, 1Y] format. return new VertexAttribute( element with { Type = (byte)MdlFile.VertexType.Half4 }, index => @@ -241,19 +245,20 @@ public class VertexAttribute var values = accessor.AsVector4Array(); - var foo = morphAccessors - .Select(ma => ma.GetValueOrDefault("TANGENT")?.AsVector3Array()) + // Per glTF specification, TANGENT morph values are stored as vec3, with the W component always considered to be 0. + var morphValues = morphAccessors + .Select(accessors => accessors.GetValueOrDefault("TANGENT")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, index => BuildByteFloat4(values[index]), - null, - (morphIndex, vertexIndex) => + + buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; - var delta = foo[morphIndex]?[vertexIndex]; + var delta = morphValues[morphIndex]?[vertexIndex]; if (delta != null) value += new Vector4(delta.Value, 0); @@ -282,50 +287,40 @@ public class VertexAttribute ); } - private static byte[] BuildSingle3(Vector3 input) - { - return [ + private static byte[] BuildSingle3(Vector3 input) => + [ ..BitConverter.GetBytes(input.X), ..BitConverter.GetBytes(input.Y), ..BitConverter.GetBytes(input.Z), ]; - } - private static byte[] BuildUInt(Vector4 input) - { - return [ + private static byte[] BuildUInt(Vector4 input) => + [ (byte)input.X, (byte)input.Y, (byte)input.Z, (byte)input.W, ]; - } - private static byte[] BuildByteFloat4(Vector4 input) - { - return [ + private static byte[] BuildByteFloat4(Vector4 input) => + [ (byte)Math.Round(input.X * 255f), (byte)Math.Round(input.Y * 255f), (byte)Math.Round(input.Z * 255f), (byte)Math.Round(input.W * 255f), ]; - } - private static byte[] BuildHalf2(Vector2 input) - { - return [ + private static byte[] BuildHalf2(Vector2 input) => + [ ..BitConverter.GetBytes((Half)input.X), ..BitConverter.GetBytes((Half)input.Y), ]; - } - private static byte[] BuildHalf4(Vector4 input) - { - return [ + private static byte[] BuildHalf4(Vector4 input) => + [ ..BitConverter.GetBytes((Half)input.X), ..BitConverter.GetBytes((Half)input.Y), ..BitConverter.GetBytes((Half)input.Z), ..BitConverter.GetBytes((Half)input.W), ]; - } } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 875c6071..b3a1d9a1 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -655,13 +655,7 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable { if (attribute == null) continue; var element = attribute.Element; - // recreating this here really sucks - add a "withstream" or something. - attributes.Add(new VertexAttribute( - element with { Offset = offsets[element.Stream] }, - attribute.Build, - attribute.HasMorph, - attribute.BuildMorph - )); + attributes.Add(attribute.WithOffset(offsets[element.Stream])); offsets[element.Stream] += attribute.Size; } var strides = offsets; From 6de3077afa93b1f5491ca261c4a7279de83ec5ed Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 6 Jan 2024 16:37:41 +1100 Subject: [PATCH 0328/1381] Clean up submeshes --- .../Import/Models/Import/SubMeshImporter.cs | 217 ++++++++++++++++++ .../Import/Models/Import/VertexAttribute.cs | 2 + Penumbra/Import/Models/ModelManager.cs | 215 +---------------- 3 files changed, 229 insertions(+), 205 deletions(-) create mode 100644 Penumbra/Import/Models/Import/SubMeshImporter.cs diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs new file mode 100644 index 00000000..941fa1d5 --- /dev/null +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -0,0 +1,217 @@ +using Lumina.Data.Parsing; +using OtterGui; +using SharpGLTF.Schema2; + +namespace Penumbra.Import.Models.Import; + +public class SubMeshImporter +{ + public struct SubMesh + { + public MdlStructs.SubmeshStruct Struct; + + public MdlStructs.VertexDeclarationStruct VertexDeclaration; + + public ushort VertexCount; + public byte[] Strides; + public List[] Streams; + + public ushort[] Indices; + + public Dictionary> ShapeValues; + } + + public static SubMesh Import(Node node, IDictionary? nodeBoneMap) + { + var importer = new SubMeshImporter(node, nodeBoneMap); + return importer.Create(); + } + + private readonly MeshPrimitive _primitive; + private readonly IDictionary? _nodeBoneMap; + + private List? _attributes; + + private ushort _vertexCount = 0; + private byte[] _strides = [0, 0, 0]; + private readonly List[] _streams; + + private ushort[]? _indices; + + private readonly List? _morphNames; + private Dictionary>? _shapeValues; + + private SubMeshImporter(Node node, IDictionary? nodeBoneMap) + { + var mesh = node.Mesh; + + var primitiveCount = mesh.Primitives.Count; + if (primitiveCount != 1) + { + var name = node.Name ?? mesh.Name ?? "(no name)"; + throw new Exception($"Mesh \"{name}\" has {primitiveCount} primitives, expected 1."); + } + + _primitive = mesh.Primitives[0]; + _nodeBoneMap = nodeBoneMap; + + try + { + _morphNames = mesh.Extras.GetNode("targetNames").Deserialize>(); + } + catch + { + _morphNames = null; + } + + // All meshes may use up to 3 byte streams. + _streams = new List[3]; + for (var i = 0; i < 3; i++) + _streams[i] = new List(); + } + + private SubMesh Create() + { + // Build all the data we'll need. + BuildIndices(); + BuildAttributes(); + BuildVertices(); + + ArgumentNullException.ThrowIfNull(_indices); + ArgumentNullException.ThrowIfNull(_attributes); + ArgumentNullException.ThrowIfNull(_shapeValues); + + return new SubMesh() + { + Struct = new MdlStructs.SubmeshStruct() + { + IndexOffset = 0, + IndexCount = (uint)_indices.Length, + AttributeIndexMask = 0, + + // TODO: Flesh these out. Game doesn't seem to rely on them existing, though. + BoneStartIndex = 0, + BoneCount = 0, + }, + + VertexDeclaration = new MdlStructs.VertexDeclarationStruct() + { + VertexElements = _attributes.Select(attribute => attribute.Element).ToArray(), + }, + + VertexCount = _vertexCount, + Strides = _strides, + Streams = _streams, + + Indices = _indices, + + ShapeValues = _shapeValues, + }; + } + + private void BuildIndices() + { + _indices = _primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); + } + + private void BuildAttributes() + { + var accessors = _primitive.VertexAccessors; + + var morphAccessors = Enumerable.Range(0, _primitive.MorphTargetsCount) + .Select(index => _primitive.GetMorphTargetAccessors(index)); + + // Try to build all the attributes the mesh might use. + // The order here is chosen to match a typical model's element order. + var rawAttributes = new[] { + VertexAttribute.Position(accessors, morphAccessors), + VertexAttribute.BlendWeight(accessors), + VertexAttribute.BlendIndex(accessors, _nodeBoneMap), + VertexAttribute.Normal(accessors, morphAccessors), + VertexAttribute.Tangent1(accessors, morphAccessors), + VertexAttribute.Color(accessors), + VertexAttribute.Uv(accessors), + }; + + var attributes = new List(); + var offsets = new byte[] { 0, 0, 0 }; + foreach (var attribute in rawAttributes) + { + if (attribute == null) continue; + attributes.Add(attribute.WithOffset(offsets[attribute.Stream])); + offsets[attribute.Stream] += attribute.Size; + } + + _attributes = attributes; + // After building the attributes, the resulting next offsets are our stream strides. + _strides = offsets; + } + + private void BuildVertices() + { + ArgumentNullException.ThrowIfNull(_attributes); + + // Lists of vertex indices that are effected by each morph target for this primitive. + var morphModifiedVertices = Enumerable.Range(0, _primitive.MorphTargetsCount) + .Select(_ => new List()) + .ToArray(); + + // We can safely assume that POSITION exists by this point - and if, by some bizarre chance, it doesn't, failing out is sane. + _vertexCount = (ushort)_primitive.VertexAccessors["POSITION"].Count; + + for (var vertexIndex = 0; vertexIndex < _vertexCount; vertexIndex++) + { + // Write out vertex data to streams for each attribute. + foreach (var attribute in _attributes) + _streams[attribute.Stream].AddRange(attribute.Build(vertexIndex)); + + // Record which morph targets have values for this vertex, if any. + var changedMorphs = morphModifiedVertices + .WithIndex() + .Where(pair => _attributes.Any(attribute => attribute.HasMorph(pair.Index, vertexIndex))) + .Select(pair => pair.Value); + foreach (var modifiedVertices in changedMorphs) + modifiedVertices.Add(vertexIndex); + } + + BuildShapeValues(morphModifiedVertices); + } + + private void BuildShapeValues(List[] morphModifiedVertices) + { + ArgumentNullException.ThrowIfNull(_indices); + ArgumentNullException.ThrowIfNull(_attributes); + + var morphShapeValues = new Dictionary>(); + + foreach (var (modifiedVertices, morphIndex) in morphModifiedVertices.WithIndex()) + { + // Each for a given mesh, each shape key contains a list of shape value mappings. + var shapeValues = new List(); + + foreach (var vertexIndex in modifiedVertices) + { + // Write out the morphed vertex to the vertex streams. + foreach (var attribute in _attributes) + _streams[attribute.Stream].AddRange(attribute.BuildMorph(morphIndex, vertexIndex)); + + // Find any indices that target this vertex index and create a mapping. + var targetingIndices = _indices.WithIndex() + .SelectWhere(pair => (pair.Value == vertexIndex, pair.Index)); + foreach (var targetingIndex in targetingIndices) + shapeValues.Add(new MdlStructs.ShapeValueStruct() + { + BaseIndicesIndex = (ushort)targetingIndex, + ReplacingVertexIndex = _vertexCount, + }); + + _vertexCount++; + } + + var name = _morphNames != null ? _morphNames[morphIndex] : $"unnamed_shape_{morphIndex}"; + morphShapeValues.Add(name, shapeValues); + } + + _shapeValues = morphShapeValues; + } +} diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index cae068db..6bb9971c 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -20,6 +20,8 @@ public class VertexAttribute /// Build a byte array containing this vertex attribute's data, as modified by the specified morph target, for the specified vertex index. public readonly BuildMorphFn BuildMorph; + public byte Stream => Element.Stream; + /// Size in bytes of a single vertex's attribute value. public byte Size => (MdlFile.VertexType)Element.Type switch { diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index b3a1d9a1..3153da78 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -462,22 +462,22 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable Penumbra.Log.Information($"nbm {string.Join(",", nodeBoneMap.Select(kv => $"{kv.Key}:{kv.Value}"))}"); } - var (vertDecl, newStrides, submesh, vertCount, vertStreams, idxCount, idxs, subMorphData) = NodeMeshThing(node, nodeBoneMap); - vertexDeclaration = vertDecl; // TODO: CHECK EQUAL AFTER FIRST - strides = newStrides; // ALSO CHECK EQUAL - vertexCount += vertCount; + var subMeshThingy = SubMeshImporter.Import(node, nodeBoneMap); + vertexDeclaration = subMeshThingy.VertexDeclaration; // TODO: CHECK EQUAL AFTER FIRST + strides = subMeshThingy.Strides; // ALSO CHECK EQUAL + vertexCount += subMeshThingy.VertexCount; for (var i = 0; i < 3; i++) - streams[i].AddRange(vertStreams[i]); - indexCount += idxCount; + streams[i].AddRange(subMeshThingy.Streams[i]); + indexCount += (uint)subMeshThingy.Indices.Length; // we need to offset the indexes to point into the new stuff - indices.AddRange(idxs.Select(idx => (ushort)(idx + vertOff))); - submeshes.Add(submesh with + indices.AddRange(subMeshThingy.Indices.Select(idx => (ushort)(idx + vertOff))); + submeshes.Add(subMeshThingy.Struct with { - IndexOffset = submesh.IndexOffset + idxOff + IndexOffset = subMeshThingy.Struct.IndexOffset + idxOff // TODO: bone stuff probably }); // TODO: HANDLE MORPHS, NEED TO ADJUST EVERY VALUE'S INDEX OFFSETS - foreach (var (key, shapeValues) in subMorphData) + foreach (var (key, shapeValues) in subMeshThingy.ShapeValues) { List valueList; if (!morphData.TryGetValue(key, out valueList)) @@ -601,201 +601,6 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable return (jointNames, usedJoints); } - private ( - MdlStructs.VertexDeclarationStruct, - byte[], - // MdlStructs.MeshStruct, - MdlStructs.SubmeshStruct, - ushort, - IEnumerable[], - uint, - IEnumerable, - IDictionary> - ) NodeMeshThing(Node node, IDictionary? nodeBoneMap) - { - // BoneTable (mesh.btidx = 255 means unskinned) - // vertexdecl - - var mesh = node.Mesh; - - // TODO: should probably say _what_ mesh - // TODO: would be cool to support >1 primitive (esp. given they're effectively what submeshes are modeled as), but blender doesn't really use them, so not going to prio that at all. - if (mesh.Primitives.Count != 1) - throw new Exception($"Mesh has {mesh.Primitives.Count} primitives, expected 1."); - var primitive = mesh.Primitives[0]; - - var accessors = primitive.VertexAccessors; - - // var foo = primitive.GetMorphTargetAccessors(0); - // var bar = foo["POSITION"]; - // var baz = bar.AsVector3Array(); - - var morphAccessors = Enumerable.Range(0, primitive.MorphTargetsCount) - // todo: map by name, probably? or do that later (probably later) - .Select(index => primitive.GetMorphTargetAccessors(index)); - - // TODO: name - var morphChangedVerts = Enumerable.Range(0, primitive.MorphTargetsCount) - .Select(_ => new List()) - .ToArray(); - - var rawAttributes = new[] { - VertexAttribute.Position(accessors, morphAccessors), - VertexAttribute.BlendWeight(accessors), - VertexAttribute.BlendIndex(accessors, nodeBoneMap), - VertexAttribute.Normal(accessors, morphAccessors), - VertexAttribute.Tangent1(accessors, morphAccessors), - VertexAttribute.Color(accessors), - VertexAttribute.Uv(accessors), - }; - - var attributes = new List(); - var offsets = new byte[] { 0, 0, 0 }; - foreach (var attribute in rawAttributes) - { - if (attribute == null) continue; - var element = attribute.Element; - attributes.Add(attribute.WithOffset(offsets[element.Stream])); - offsets[element.Stream] += attribute.Size; - } - var strides = offsets; - - // TODO: when merging submeshes, i'll need to check that vert els are the same for all of them, as xiv only stores verts at the mesh level and shares them. - - var streams = new List[3]; - for (var i = 0; i < 3; i++) - streams[i] = new List(); - - // todo: this is a bit lmao but also... probably the most sane option? getting the count that is - var vertexCount = primitive.VertexAccessors["POSITION"].Count; - for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) - { - foreach (var attribute in attributes) - { - streams[attribute.Element.Stream].AddRange(attribute.Build(vertexIndex)); - } - - // this is a meme but idk maybe it's the best approach? it's not like the attr array is ever long - foreach (var (list, morphIndex) in morphChangedVerts.WithIndex()) - { - var hasMorph = attributes.Aggregate(false, (cur, attr) => cur || attr.HasMorph(morphIndex, vertexIndex)); - // Penumbra.Log.Information($"eh? {vertexIndex} {morphIndex}: {hasMorph}"); - if (hasMorph) - { - list.Add(vertexIndex); - } - } - } - - // indices - // var indexCount = primitive.GetIndexAccessor().Count; - // var indices = primitive.GetIndices() - // .SelectMany(index => BitConverter.GetBytes((ushort)index)) - // .ToArray(); - var indices = primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); - - // BLAH - // foreach (var (list, morphIndex) in morphChangedVerts.WithIndex()) - // { - // Penumbra.Log.Information($"morph {morphIndex}: {string.Join(",", list)}"); - // } - // TODO BUILD THE MORPH VERTS - // (source, target) - var morphmappingstuff = new List[morphChangedVerts.Length]; - foreach (var (list, morphIndex) in morphChangedVerts.WithIndex()) - { - var morphmaplist = morphmappingstuff[morphIndex] = new(); - foreach (var vertIdx in list) - { - foreach (var attribute in attributes) - { - streams[attribute.Element.Stream].AddRange(attribute.BuildMorph(morphIndex, vertIdx)); - } - - var fuck = indices.WithIndex() - .Where(pair => pair.Value == vertIdx) - .Select(pair => pair.Index); - - foreach (var something in fuck) - { - morphmaplist.Add(new MdlStructs.ShapeValueStruct() - { - BaseIndicesIndex = (ushort)something, - ReplacingVertexIndex = (ushort)vertexCount, - }); - } - vertexCount++; - } - } - - // TODO: HANDLE THIS BEING MISSING - probably warn or something, it's not the end of the world - var morphData = new Dictionary>(); - if (morphmappingstuff.Length > 0) - { - var morphnames = mesh.Extras.GetNode("targetNames").Deserialize>(); - morphData = morphmappingstuff - .Zip(morphnames) - .ToDictionary( - (pair) => pair.Second, - (pair) => pair.First - ); - } - - // one of these per mesh - var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() - { - VertexElements = attributes.Select(attribute => attribute.Element).ToArray(), - }; - - // mesh - // var xivMesh = new MdlStructs.MeshStruct() - // { - // // TODO: sum across submeshes. - // // TODO: would be cool to share verts on submesh boundaries but that's way out of scope for now. - // VertexCount = (ushort)vertexCount, - // IndexCount = (uint)indexCount, - // // TODO: will have to think about how to represent this - materials can be named, so maybe adjust in parent? - // MaterialIndex = 0, - // // TODO: this will need adjusting by parent - // SubMeshIndex = 0, - // SubMeshCount = 1, - // // TODO: update in parent - // BoneTableIndex = 0, - // // TODO: this is relative to the lod's index buffer, and is an index, not byte offset - // StartIndex = 0, - // // TODO: these are relative to the lod vertex buffer. these values are accurate for a 0 offset, but lod will need to adjust - // VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], - // VertexBufferStride = strides, - // VertexStreamCount = /* 2 */ (byte)(attributes.Select(attribute => attribute.Element.Stream).Max() + 1), - // }; - - // submesh - // TODO: once we have multiple submeshes, the _first_ should probably set an index offset of 0, and then further ones delta from there - and then they can be blindly adjusted by the parent that's laying out the meshes. - var xivSubmesh = new MdlStructs.SubmeshStruct() - { - IndexOffset = 0, - IndexCount = (uint)indices.Length, - AttributeIndexMask = 0, - // TODO: not sure how i want to handle these ones - BoneStartIndex = 0, - BoneCount = 1, - }; - - // var vertexBuffer = streams[0].Concat(streams[1]).Concat(streams[2]); - - return ( - vertexDeclaration, - strides, - // xivMesh, - xivSubmesh, - (ushort)vertexCount, - streams, - (uint)indices.Length, - indices, - morphData - ); - } - public bool Equals(IAction? other) { if (other is not ImportGltfAction rhs) From 1a1c662364fb47fbc07e330bd0ccb4b1c42fa3cd Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 6 Jan 2024 20:40:30 +1100 Subject: [PATCH 0329/1381] Clean up meshes --- Penumbra/Import/Models/Import/MeshImporter.cs | 240 +++++++++++++++++ .../Import/Models/Import/SubMeshImporter.cs | 8 +- Penumbra/Import/Models/ModelManager.cs | 251 ++---------------- 3 files changed, 260 insertions(+), 239 deletions(-) create mode 100644 Penumbra/Import/Models/Import/MeshImporter.cs diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs new file mode 100644 index 00000000..e67b7c4e --- /dev/null +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -0,0 +1,240 @@ +using Lumina.Data.Parsing; +using SharpGLTF.Schema2; + +namespace Penumbra.Import.Models.Import; + +public class MeshImporter +{ + public struct Mesh + { + public MdlStructs.MeshStruct MeshStruct; + public List SubMeshStructs; + + public MdlStructs.VertexDeclarationStruct VertexDeclaration; + public IEnumerable VertexBuffer; + + public List Indicies; + + public List? Bones; + + public List ShapeKeys; + } + + public struct MeshShapeKey + { + public string Name; + public MdlStructs.ShapeMeshStruct ShapeMesh; + public List ShapeValues; + } + + public static Mesh Import(IEnumerable nodes) + { + var importer = new MeshImporter(nodes); + return importer.Create(); + } + + private IEnumerable _nodes; + + private List _subMeshes = new(); + + private MdlStructs.VertexDeclarationStruct? _vertexDeclaration; + private byte[]? _strides; + private ushort _vertexCount = 0; + private List[] _streams; + + private List _indices = new(); + + private List? _bones; + + private readonly Dictionary> _shapeValues = new(); + + private MeshImporter(IEnumerable nodes) + { + _nodes = nodes; + + // All meshes may use up to 3 byte streams. + _streams = new List[3]; + for (var streamIndex = 0; streamIndex < 3; streamIndex++) + _streams[streamIndex] = new List(); + } + + private Mesh Create() + { + foreach (var node in _nodes) + BuildSubMeshForNode(node); + + ArgumentNullException.ThrowIfNull(_strides); + ArgumentNullException.ThrowIfNull(_vertexDeclaration); + + return new Mesh() + { + MeshStruct = new MdlStructs.MeshStruct() + { + VertexBufferOffset = [0, (uint)_streams[0].Count, (uint)(_streams[0].Count + _streams[1].Count)], + VertexBufferStride = _strides, + VertexCount = _vertexCount, + VertexStreamCount = (byte)_vertexDeclaration.Value.VertexElements + .Select(element => element.Stream + 1) + .Max(), + + StartIndex = 0, + IndexCount = (uint)_indices.Count, + + // TODO: import material names + MaterialIndex = 0, + + SubMeshIndex = 0, + SubMeshCount = (ushort)_subMeshes.Count, + + BoneTableIndex = 0, + }, + SubMeshStructs = _subMeshes, + + VertexDeclaration = _vertexDeclaration.Value, + VertexBuffer = _streams[0].Concat(_streams[1]).Concat(_streams[2]), + + Indicies = _indices, + + Bones = _bones, + + ShapeKeys = _shapeValues + .Select(pair => new MeshShapeKey() + { + Name = pair.Key, + ShapeMesh = new MdlStructs.ShapeMeshStruct() + { + MeshIndexOffset = 0, + ShapeValueOffset = 0, + ShapeValueCount = (uint)pair.Value.Count, + }, + ShapeValues = pair.Value, + }) + .ToList(), + }; + } + + private void BuildSubMeshForNode(Node node) + { + // Record some offsets we'll be using later, before they get mutated with sub-mesh values. + var vertexOffset = _vertexCount; + var indexOffset = _indices.Count; + + var nodeBoneMap = CreateNodeBoneMap(node); + var subMesh = SubMeshImporter.Import(node, nodeBoneMap); + + var subMeshName = node.Name ?? node.Mesh.Name; + + // Check that vertex declarations match - we need to combine the buffers, so a mismatch would take a whole load of resolution. + if (_vertexDeclaration == null) + _vertexDeclaration = subMesh.VertexDeclaration; + else if (VertexDeclarationMismatch(subMesh.VertexDeclaration, _vertexDeclaration.Value)) + throw new Exception($"Sub-mesh \"{subMeshName}\" vertex declaration mismatch. All sub-meshes of a mesh must have equivalent vertex declarations."); + + // Given that strides are derived from declarations, a lack of mismatch in declarations means the strides are fine. + // TODO: I mean, given that strides are derivable, might be worth dropping strides from the submesh return structure and computing when needed. + if (_strides == null) + _strides = subMesh.Strides; + + // Merge the sub-mesh streams into the main mesh stream bodies. + _vertexCount += subMesh.VertexCount; + + for (var streamIndex = 0; streamIndex < 3; streamIndex++) + _streams[streamIndex].AddRange(subMesh.Streams[streamIndex]); + + // As we're appending vertex data to the buffers, we need to update indices to point into that later block. + _indices.AddRange(subMesh.Indices.Select(index => (ushort)(index + vertexOffset))); + + // Merge the sub-mesh's shape values into the mesh's. + foreach (var (name, subMeshShapeValues) in subMesh.ShapeValues) + { + if (!_shapeValues.TryGetValue(name, out var meshShapeValues)) + { + meshShapeValues = new(); + _shapeValues.Add(name, meshShapeValues); + } + + meshShapeValues.AddRange(subMeshShapeValues.Select(value => value with + { + BaseIndicesIndex = (ushort)(value.BaseIndicesIndex + indexOffset), + ReplacingVertexIndex = (ushort)(value.ReplacingVertexIndex + vertexOffset), + })); + } + + // And finally, merge in the sub-mesh struct itself. + _subMeshes.Add(subMesh.SubMeshStruct with + { + IndexOffset = (ushort)(subMesh.SubMeshStruct.IndexOffset + indexOffset), + }); + } + + private bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) + { + var elA = a.VertexElements; + var elB = b.VertexElements; + + if (elA.Length != elB.Length) return true; + + // NOTE: This assumes that elements will always be in the same order. Under the current implementation, that's guaranteed. + return elA.Zip(elB).Any(pair => + pair.First.Usage != pair.Second.Usage + || pair.First.Type != pair.Second.Type + || pair.First.Offset != pair.Second.Offset + || pair.First.Stream != pair.Second.Stream + ); + } + + private Dictionary? CreateNodeBoneMap(Node node) + { + // Unskinned assets can skip this all of this. + if (node.Skin == null) + return null; + + // Build an array of joint names, preserving the joint index from the skin. + // Any unnamed joints we'll be coalescing on a fallback bone name - though this is realistically unlikely to occur. + var jointNames = Enumerable.Range(0, node.Skin.JointsCount) + .Select(index => node.Skin.GetJoint(index).Joint.Name ?? "unnamed_joint") + .ToArray(); + + // TODO: This is duplicated with the submesh importer - would be good to avoid (not that it's a huge issue). + var mesh = node.Mesh; + var meshName = node.Name ?? mesh.Name ?? "(no name)"; + var primitiveCount = mesh.Primitives.Count; + if (primitiveCount != 1) + { + throw new Exception($"Mesh \"{meshName}\" has {primitiveCount} primitives, expected 1."); + } + var primitive = mesh.Primitives[0]; + + // Per glTF specification, an asset with a skin MUST contain skinning attributes on its mesh. + var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0"); + if (jointsAccessor == null) + throw new Exception($"Skinned mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); + + // Build a set of joints that are referenced by this mesh. + // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. + var usedJoints = new HashSet(); + foreach (var joints in jointsAccessor.AsVector4Array()) + for (var index = 0; index < 4; index++) + usedJoints.Add((ushort)joints[index]); + + // Only initialise the bones list if we're actually going to put something in it. + if (_bones == null) + _bones = new(); + + // Build a dictionary of node-specific joint indices mesh-wide bone indices. + var nodeBoneMap = new Dictionary(); + foreach (var usedJoint in usedJoints) + { + var jointName = jointNames[usedJoint]; + var boneIndex = _bones.IndexOf(jointName); + if (boneIndex == -1) + { + boneIndex = _bones.Count; + _bones.Add(jointName); + } + nodeBoneMap.Add(usedJoint, (ushort)boneIndex); + } + + return nodeBoneMap; + } +} diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 941fa1d5..1d604105 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -8,7 +8,7 @@ public class SubMeshImporter { public struct SubMesh { - public MdlStructs.SubmeshStruct Struct; + public MdlStructs.SubmeshStruct SubMeshStruct; public MdlStructs.VertexDeclarationStruct VertexDeclaration; @@ -66,8 +66,8 @@ public class SubMeshImporter // All meshes may use up to 3 byte streams. _streams = new List[3]; - for (var i = 0; i < 3; i++) - _streams[i] = new List(); + for (var streamIndex = 0; streamIndex < 3; streamIndex++) + _streams[streamIndex] = new List(); } private SubMesh Create() @@ -83,7 +83,7 @@ public class SubMeshImporter return new SubMesh() { - Struct = new MdlStructs.SubmeshStruct() + SubMeshStruct = new MdlStructs.SubmeshStruct() { IndexOffset = 0, IndexCount = (uint)_indices.Length, diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 3153da78..65067242 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -221,23 +221,13 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable var idxOffset = indices.Count; var shapeValueOffset = shapeValues.Count; - var ( - vertexDeclaration, - // boneTable, - xivMesh, - xivSubmeshes, - meshVertexBuffer, - meshIndices, - meshShapeData, - meshBoneList - ) = MeshThing(submeshnodes); + var meshthing = MeshImporter.Import(submeshnodes); var boneTableIndex = 255; - // TODO: a better check than this would be real good - if (meshBoneList.Count() > 0) + if (meshthing.Bones != null) { var boneIndices = new List(); - foreach (var mb in meshBoneList) + foreach (var mb in meshthing.Bones) { var boneIndex = bones.IndexOf(mb); if (boneIndex == -1) @@ -262,43 +252,43 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable }); } - vertexDeclarations.Add(vertexDeclaration); - var meshStartIndex = (uint)(xivMesh.StartIndex + idxOffset / sizeof(ushort)); - meshes.Add(xivMesh with + vertexDeclarations.Add(meshthing.VertexDeclaration); + var meshStartIndex = (uint)(meshthing.MeshStruct.StartIndex + idxOffset / sizeof(ushort)); + meshes.Add(meshthing.MeshStruct with { - SubMeshIndex = (ushort)(xivMesh.SubMeshIndex + subOffset), + SubMeshIndex = (ushort)(meshthing.MeshStruct.SubMeshIndex + subOffset), // TODO: should probably define a type for index type hey. BoneTableIndex = (ushort)boneTableIndex, StartIndex = meshStartIndex, - VertexBufferOffset = xivMesh.VertexBufferOffset + VertexBufferOffset = meshthing.MeshStruct.VertexBufferOffset .Select(offset => (uint)(offset + vertOffset)) .ToArray(), }); // TODO: could probably do this with linq cleaner - foreach (var xivSubmesh in xivSubmeshes) + foreach (var xivSubmesh in meshthing.SubMeshStructs) submeshes.Add(xivSubmesh with { // TODO: this will need to keep ticking up for each submesh in the same mesh IndexOffset = (uint)(xivSubmesh.IndexOffset + idxOffset / sizeof(ushort)) }); - vertexBuffer.AddRange(meshVertexBuffer); - indices.AddRange(meshIndices.SelectMany(index => BitConverter.GetBytes((ushort)index))); - foreach (var (key, (shapeMesh, meshShapeValues)) in meshShapeData) + vertexBuffer.AddRange(meshthing.VertexBuffer); + indices.AddRange(meshthing.Indicies.SelectMany(index => BitConverter.GetBytes((ushort)index))); + foreach (var shapeKey in meshthing.ShapeKeys) { List keyshapedata; - if (!shapeData.TryGetValue(key, out keyshapedata)) + if (!shapeData.TryGetValue(shapeKey.Name, out keyshapedata)) { keyshapedata = new(); - shapeData.Add(key, keyshapedata); + shapeData.Add(shapeKey.Name, keyshapedata); } - keyshapedata.Add(shapeMesh with + keyshapedata.Add(shapeKey.ShapeMesh with { MeshIndexOffset = meshStartIndex, ShapeValueOffset = (uint)shapeValueOffset, }); - shapeValues.AddRange(meshShapeValues); + shapeValues.AddRange(shapeKey.ShapeValues); } } @@ -392,215 +382,6 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable Out = mdl; } - // this return type is an absolute meme, class that shit up. - private ( - MdlStructs.VertexDeclarationStruct, - // MdlStructs.BoneTableStruct, - MdlStructs.MeshStruct, - IEnumerable, - IEnumerable, - IEnumerable, - IDictionary)>, - IEnumerable - ) MeshThing(IEnumerable nodes) - { - var vertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = Array.Empty() }; - var vertexCount = (ushort)0; - // there's gotta be a better way to do this with streams or enumerables or something, surely - var streams = new List[3]; - for (var i = 0; i < 3; i++) - streams[i] = new List(); - var indexCount = (uint)0; - var indices = new List(); - var strides = new byte[] { 0, 0, 0 }; - var submeshes = new List(); - var morphData = new Dictionary>(); - - /* - THOUGHTS - per submesh node, before calling down to build the mesh, build a bone mapping of joint index -> bone name (not node index) - the joint indexes are what will be used in the vertices. - per submesh node, eagerly collect all blend indexes (joints) used before building anything - just as a set or something - the above means i can create a limited set and a mapping, i.e. if skeleton contains {0->a 1->b 2->c}, and mesh contains 0, 2, then i can output [a, c] + {0->0, 2->1} - (throw if >64 entries in that name array) - - then for the second prim, - again get the joint-name mapping, and again get the joint set - then can extend the values. using the samme example, if skeleton2 contains {0->c 1->d, 2->e} and mesh contains [0,2] again, then bone array can be extended to [a, c, e] and the mesh-specific mapping would be {0->1, 2->2} - - repeat, etc - */ - - var usedBones = new List(); - - // TODO: check that attrs/elems/strides match - we should be generating per-mesh stuff for sanity's sake, but we need to make sure they match if there's >1 node mesh in a mesh. - foreach (var node in nodes) - { - var vertOff = vertexCount; - var idxOff = indexCount; - - Dictionary? nodeBoneMap = null; - var bonething = WalkBoneThing(node); - if (bonething.HasValue) - { - var (boneNames, usedJoints) = bonething.Value; - nodeBoneMap = new(); - - // todo: probably linq this shit - foreach (var usedJoint in usedJoints) - { - // this is the 0,2 - var boneName = boneNames[usedJoint]; - var boneIdx = usedBones.IndexOf(boneName); - if (boneIdx == -1) - { - boneIdx = usedBones.Count; - usedBones.Add(boneName); - } - nodeBoneMap.Add(usedJoint, (ushort)boneIdx); - } - - Penumbra.Log.Information($"nbm {string.Join(",", nodeBoneMap.Select(kv => $"{kv.Key}:{kv.Value}"))}"); - } - - var subMeshThingy = SubMeshImporter.Import(node, nodeBoneMap); - vertexDeclaration = subMeshThingy.VertexDeclaration; // TODO: CHECK EQUAL AFTER FIRST - strides = subMeshThingy.Strides; // ALSO CHECK EQUAL - vertexCount += subMeshThingy.VertexCount; - for (var i = 0; i < 3; i++) - streams[i].AddRange(subMeshThingy.Streams[i]); - indexCount += (uint)subMeshThingy.Indices.Length; - // we need to offset the indexes to point into the new stuff - indices.AddRange(subMeshThingy.Indices.Select(idx => (ushort)(idx + vertOff))); - submeshes.Add(subMeshThingy.Struct with - { - IndexOffset = subMeshThingy.Struct.IndexOffset + idxOff - // TODO: bone stuff probably - }); - // TODO: HANDLE MORPHS, NEED TO ADJUST EVERY VALUE'S INDEX OFFSETS - foreach (var (key, shapeValues) in subMeshThingy.ShapeValues) - { - List valueList; - if (!morphData.TryGetValue(key, out valueList)) - { - valueList = new(); - morphData.Add(key, valueList); - } - valueList.AddRange( - shapeValues - .Select(value => value with - { - // but this is actually an index index - BaseIndicesIndex = (ushort)(value.BaseIndicesIndex + idxOff), - // this is a vert idx - ReplacingVertexIndex = (ushort)(value.ReplacingVertexIndex + vertOff), - }) - ); - } - } - - // one of these per skinned mesh. - // TODO: check if mesh has skinning at all. (err if mixed?) - // var boneTable = new MdlStructs.BoneTableStruct() - // { - // BoneCount = 1, - // // this needs to be the full 64. this should be fine _here_ with 0s because i only have one bone, but will need to be fully populated properly. in real files. - // BoneIndex = new ushort[64], - // }; - - // mesh - var xivMesh = new MdlStructs.MeshStruct() - { - // TODO: sum across submeshes. - // TODO: would be cool to share verts on submesh boundaries but that's way out of scope for now. - VertexCount = vertexCount, - IndexCount = indexCount, - // TODO: will have to think about how to represent this - materials can be named, so maybe adjust in parent? - MaterialIndex = 0, - // TODO: this will need adjusting by parent - SubMeshIndex = 0, - SubMeshCount = (ushort)submeshes.Count, - // TODO: update in parent - BoneTableIndex = 0, - // TODO: this is relative to the lod's index buffer, and is an index, not byte offset - StartIndex = 0, - // TODO: these are relative to the lod vertex buffer. these values are accurate for a 0 offset, but lod will need to adjust - VertexBufferOffset = [0, (uint)streams[0].Count, (uint)(streams[0].Count + streams[1].Count)], - VertexBufferStride = strides, - // VertexStreamCount = /* 2 */ (byte)(attributes.Select(attribute => attribute.Element.Stream).Max() + 1), - VertexStreamCount = (byte)(vertexDeclaration.VertexElements.Select(element => element.Stream).Max() + 1) - }; - - // TODO: can probably get away with flattening the values and blindly setting offsets in parent - mesh matters above, but the values are already Dealt With at this point - var shapeData = morphData.ToDictionary( - (pair) => pair.Key, - pair => ( - new MdlStructs.ShapeMeshStruct() - { - // TODO: this needs to be adjusted by the parent - MeshIndexOffset = 0, - ShapeValueCount = (uint)pair.Value.Count, - // TODO: Also update by parent - ShapeValueOffset = 0, - }, - pair.Value - ) - ); - - return ( - vertexDeclaration, - // boneTable, - xivMesh, - submeshes, - streams[0].Concat(streams[1]).Concat(streams[2]), - indices, - shapeData, - usedBones - ); - } - - private (string[], ISet)? WalkBoneThing(Node node) - { - // - if (node.Skin == null) - return null; - - var jointNames = Enumerable.Range(0, node.Skin.JointsCount) - .Select(index => node.Skin.GetJoint(index).Joint.Name ?? $"UNNAMED") - .ToArray(); - - // it might make sense to do this in the submesh handling - i do need to maintain the mesh-wide bone list, but that can be passed in/out, perhaps? - var mesh = node.Mesh; - if (mesh.Primitives.Count != 1) - throw new Exception($"Mesh has {mesh.Primitives.Count} primitives, expected 1."); - var primitive = mesh.Primitives[0]; - - var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0"); - if (jointsAccessor == null) - throw new Exception($"Skinned meshes must contain a JOINTS_0 attribute."); - - // var weightsAccssor = primitive.GetVertexAccessor("WEIGHTS_0"); - // if (weightsAccssor == null) - // throw new Exception($"Skinned meshes must contain a WEIGHTS_0 attribute."); - - var usedJoints = new HashSet(); - - // TODO: would be neat to omit any joints that are only used in 0-weight positions, but doing so would require being a _little_ smarter in vertex attrs on how to fall back when mappings aren't found - or otherwise try to ensure that mappings for unused stuff always exists - // foreach (var (joints, weights) in jointsAccessor.AsVector4Array().Zip(weightsAccssor.AsVector4Array())) - // { - // for (var index = 0; index < 4; index++) - // if (weights[index] > 0) - // usedJoints.Add((ushort)joints[index]); - // } - - foreach (var joints in jointsAccessor.AsVector4Array()) - { - for (var index = 0; index < 4; index++) - usedJoints.Add((ushort)joints[index]); - } - - return (jointNames, usedJoints); - } - public bool Equals(IAction? other) { if (other is not ImportGltfAction rhs) From 13d594ca878c6a3cd7e12beb4ea7e8601aa5ad93 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 6 Jan 2024 23:13:34 +1100 Subject: [PATCH 0330/1381] Clean up models --- .../Import/Models/Import/ModelImporter.cs | 224 ++++++++++++++++ Penumbra/Import/Models/ModelManager.cs | 252 +----------------- 2 files changed, 226 insertions(+), 250 deletions(-) create mode 100644 Penumbra/Import/Models/Import/ModelImporter.cs diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs new file mode 100644 index 00000000..f53d2b64 --- /dev/null +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -0,0 +1,224 @@ +using Lumina.Data.Parsing; +using Penumbra.GameData.Files; +using SharpGLTF.Schema2; + +namespace Penumbra.Import.Models.Import; + +public partial class ModelImporter +{ + public static MdlFile Import(ModelRoot model) + { + var importer = new ModelImporter(model); + return importer.Create(); + } + + // NOTE: This is intended to match TexTool's grouping regex, ".*[_ ^]([0-9]+)[\\.\\-]?([0-9]+)?$" + [GeneratedRegex(@"[_ ^](?'Mesh'[0-9]+)[.-]?(?'SubMesh'[0-9]+)?$", RegexOptions.Compiled)] + private static partial Regex MeshNameGroupingRegex(); + + private readonly ModelRoot _model; + + private List _meshes = new(); + private List _subMeshes = new(); + + private List _vertexDeclarations = new(); + private List _vertexBuffer = new(); + + private List _indices = new(); + + private List _bones = new(); + private List _boneTables = new(); + + private Dictionary> _shapeMeshes = new(); + private List _shapeValues = new(); + + private ModelImporter(ModelRoot model) + { + _model = model; + } + + private MdlFile Create() + { + // Group and build out meshes in this model. + foreach (var subMeshNodes in GroupedMeshNodes()) + BuildMeshForGroup(subMeshNodes); + + // Now that all of the meshes have been built, we can build some of the model-wide metadata. + var shapes = new List(); + var shapeMeshes = new List(); + foreach (var (keyName, keyMeshes) in _shapeMeshes) + { + shapes.Add(new MdlFile.Shape() + { + ShapeName = keyName, + // NOTE: these values are per-LoD. + ShapeMeshStartIndex = [(ushort)shapeMeshes.Count, 0, 0], + ShapeMeshCount = [(ushort)keyMeshes.Count, 0, 0], + }); + shapeMeshes.AddRange(keyMeshes); + } + + var indexBuffer = _indices.SelectMany(BitConverter.GetBytes).ToArray(); + + var emptyBoundingBox = new MdlStructs.BoundingBoxStruct() + { + Min = [0, 0, 0, 0], + Max = [0, 0, 0, 0], + }; + + // And finally, the MdlFile itself. + return new MdlFile() + { + VertexOffset = [0, 0, 0], + VertexBufferSize = [(uint)_vertexBuffer.Count, 0, 0], + IndexOffset = [(uint)_vertexBuffer.Count, 0, 0], + IndexBufferSize = [(uint)indexBuffer.Length, 0, 0], + + VertexDeclarations = _vertexDeclarations.ToArray(), + Meshes = _meshes.ToArray(), + SubMeshes = _subMeshes.ToArray(), + + BoneTables = _boneTables.ToArray(), + Bones = _bones.ToArray(), + // TODO: Game doesn't seem to rely on this, but would be good to populate. + SubMeshBoneMap = [], + + Shapes = shapes.ToArray(), + ShapeMeshes = shapeMeshes.ToArray(), + ShapeValues = _shapeValues.ToArray(), + + LodCount = 1, + + Lods = [new MdlStructs.LodStruct() + { + MeshIndex = 0, + MeshCount = (ushort)_meshes.Count, + + ModelLodRange = 0, + TextureLodRange = 0, + + VertexDataOffset = 0, + VertexBufferSize = (uint)_vertexBuffer.Count, + IndexDataOffset = (uint)_vertexBuffer.Count, + IndexBufferSize = (uint)indexBuffer.Length, + }], + + // TODO: Would be good to populate from gltf material names. + Materials = ["/NO_MATERIAL"], + + // TODO: Would be good to calculate all of this up the tree. + Radius = 1, + BoundingBoxes = emptyBoundingBox, + BoneBoundingBoxes = Enumerable.Repeat(emptyBoundingBox, _bones.Count).ToArray(), + + RemainingData = [.._vertexBuffer, ..indexBuffer], + }; + } + + /// Returns an iterator over sorted, grouped mesh nodes. + private IEnumerable> GroupedMeshNodes() => + _model.LogicalNodes + .Where(node => node.Mesh != null) + .Select(node => + { + var name = node.Name ?? node.Mesh.Name ?? "NOMATCH"; + var match = MeshNameGroupingRegex().Match(name); + return (node, match); + }) + .Where(pair => pair.match.Success) + .OrderBy(pair => + { + var subMeshGroup = pair.match.Groups["SubMesh"]; + return subMeshGroup.Success ? int.Parse(subMeshGroup.Value) : 0; + }) + .GroupBy( + pair => int.Parse(pair.match.Groups["Mesh"].Value), + pair => pair.node + ) + .OrderBy(group => group.Key); + + private void BuildMeshForGroup(IEnumerable subMeshNodes) + { + // Record some offsets we'll be using later, before they get mutated with mesh values. + var subMeshOffset = _subMeshes.Count; + var vertexOffset = _vertexBuffer.Count; + var indexOffset = _indices.Count; + var shapeValueOffset = _shapeValues.Count; + + var mesh = MeshImporter.Import(subMeshNodes); + var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); + + // If no bone table is used for a mesh, the index is set to 255. + var boneTableIndex = 255; + if (mesh.Bones != null) + boneTableIndex = BuildBoneTable(mesh.Bones); + + _meshes.Add(mesh.MeshStruct with + { + SubMeshIndex = (ushort)(mesh.MeshStruct.SubMeshIndex + subMeshOffset), + BoneTableIndex = (ushort)boneTableIndex, + StartIndex = meshStartIndex, + VertexBufferOffset = mesh.MeshStruct.VertexBufferOffset + .Select(offset => (uint)(offset + vertexOffset)) + .ToArray(), + }); + + foreach (var subMesh in mesh.SubMeshStructs) + _subMeshes.Add(subMesh with + { + IndexOffset = (uint)(subMesh.IndexOffset + indexOffset), + }); + + _vertexDeclarations.Add(mesh.VertexDeclaration); + _vertexBuffer.AddRange(mesh.VertexBuffer); + + _indices.AddRange(mesh.Indicies); + + foreach (var meshShapeKey in mesh.ShapeKeys) + { + if (!_shapeMeshes.TryGetValue(meshShapeKey.Name, out var shapeMeshes)) + { + shapeMeshes = new(); + _shapeMeshes.Add(meshShapeKey.Name, shapeMeshes); + } + + shapeMeshes.Add(meshShapeKey.ShapeMesh with + { + MeshIndexOffset = meshStartIndex, + ShapeValueOffset = (uint)shapeValueOffset, + }); + + _shapeValues.AddRange(meshShapeKey.ShapeValues); + } + } + + private ushort BuildBoneTable(List boneNames) + { + var boneIndices = new List(); + foreach (var boneName in boneNames) + { + var boneIndex = _bones.IndexOf(boneName); + if (boneIndex == -1) + { + boneIndex = _bones.Count; + _bones.Add(boneName); + } + boneIndices.Add((ushort)boneIndex); + } + + if (boneIndices.Count > 64) + throw new Exception("XIV does not support meshes weighted to more than 64 bones."); + + var boneIndicesArray = new ushort[64]; + Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); + + var boneTableIndex = _boneTables.Count; + _boneTables.Add(new MdlStructs.BoneTableStruct() + { + BoneIndex = boneIndicesArray, + BoneCount = (byte)boneIndices.Count, + }); + + return (ushort)boneTableIndex; + } +} diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 65067242..ebbe0411 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,20 +1,15 @@ using Dalamud.Plugin.Services; -using Lumina.Data.Parsing; -using OtterGui; using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData.Files; using Penumbra.Import.Models.Export; using Penumbra.Import.Models.Import; -using SharpGLTF.Geometry; -using SharpGLTF.Geometry.VertexTypes; -using SharpGLTF.Materials; using SharpGLTF.Scenes; using SharpGLTF.Schema2; namespace Penumbra.Import.Models; -public sealed partial class ModelManager : SingleTaskQueue, IDisposable +public sealed class ModelManager : SingleTaskQueue, IDisposable { private readonly IFramework _framework; private readonly IDataManager _gameData; @@ -125,10 +120,6 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable private partial class ImportGltfAction : IAction { - // TODO: clean this up a bit, i don't actually need all of it. - [GeneratedRegex(@".*[_ ^](?'Mesh'[0-9]+)[\\.\\-]?([0-9]+)?$", RegexOptions.Compiled)] - private static partial Regex MeshNameGroupingRegex(); - public MdlFile? Out; public ImportGltfAction() @@ -136,250 +127,11 @@ public sealed partial class ModelManager : SingleTaskQueue, IDisposable // } - private ModelRoot Build() - { - // Build a super simple plane as a fake gltf input. - var material = new MaterialBuilder(); - var mesh = new MeshBuilder("mesh 0.0"); - var prim = mesh.UsePrimitive(material); - var tangent = new Vector4(.5f, .5f, 0, 1); - var vert1 = new VertexBuilder( - new VertexPositionNormalTangent(new Vector3(-1, 0, 1), Vector3.UnitY, tangent), - new VertexColor1Texture2(Vector4.One, Vector2.UnitY, Vector2.Zero), - new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) - ); - var vert2 = new VertexBuilder( - new VertexPositionNormalTangent(new Vector3(1, 0, 1), Vector3.UnitY, tangent), - new VertexColor1Texture2(Vector4.One, Vector2.One, Vector2.Zero), - new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) - ); - var vert3 = new VertexBuilder( - new VertexPositionNormalTangent(new Vector3(-1, 0, -1), Vector3.UnitY, tangent), - new VertexColor1Texture2(Vector4.One, Vector2.Zero, Vector2.Zero), - new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) - ); - var vert4 = new VertexBuilder( - new VertexPositionNormalTangent(new Vector3(1, 0, -1), Vector3.UnitY, tangent), - new VertexColor1Texture2(Vector4.One, Vector2.UnitX, Vector2.Zero), - new VertexJoints4([(0, 1), (0, 0), (0, 0), (0, 0)]) - ); - prim.AddTriangle(vert2, vert3, vert1); - prim.AddTriangle(vert2, vert4, vert3); - var jKosi = new NodeBuilder("j_kosi"); - var scene = new SceneBuilder(); - scene.AddNode(jKosi); - scene.AddSkinnedMesh(mesh, Matrix4x4.Identity, [jKosi]); - var model = scene.ToGltf2(); - - return model; - } - public void Execute(CancellationToken cancel) { var model = ModelRoot.Load("C:\\Users\\ackwell\\blender\\gltf-tests\\c0201e6180_top.gltf"); - // TODO: for grouping, should probably use `node.name ?? mesh.name`, as which are set seems to depend on the exporter. - // var nodes = model.LogicalNodes - // .Where(node => node.Mesh != null) - // // TODO: I'm just grabbing the first 3, as that will contain 0.0, 0.1, and 1.0. testing, and all that. - // .Take(3); - - // tt uses this - // ".*[_ ^]([0-9]+)[\\.\\-]?([0-9]+)?$" - var nodes = model.LogicalNodes - .Where(node => node.Mesh != null) - .Take(6) // this model has all 3 lods in it - the first 6 are the real lod0 - .SelectWhere(node => - { - var name = node.Name ?? node.Mesh.Name; - var match = MeshNameGroupingRegex().Match(name); - return match.Success - ? (true, (node, int.Parse(match.Groups["Mesh"].Value))) - : (false, (node, -1)); - }) - .GroupBy(pair => pair.Item2, pair => pair.node) - .OrderBy(group => group.Key); - - // this is a representation of a single LoD - var vertexDeclarations = new List(); - var bones = new List(); - var boneTables = new List(); - var meshes = new List(); - var submeshes = new List(); - var vertexBuffer = new List(); - var indices = new List(); - - var shapeData = new Dictionary>(); - var shapeValues = new List(); - - foreach (var submeshnodes in nodes) - { - var boneTableOffset = boneTables.Count; - var meshOffset = meshes.Count; - var subOffset = submeshes.Count; - var vertOffset = vertexBuffer.Count; - var idxOffset = indices.Count; - var shapeValueOffset = shapeValues.Count; - - var meshthing = MeshImporter.Import(submeshnodes); - - var boneTableIndex = 255; - if (meshthing.Bones != null) - { - var boneIndices = new List(); - foreach (var mb in meshthing.Bones) - { - var boneIndex = bones.IndexOf(mb); - if (boneIndex == -1) - { - boneIndex = bones.Count; - bones.Add(mb); - } - boneIndices.Add((ushort)boneIndex); - } - - if (boneIndices.Count > 64) - throw new Exception("One mesh cannot be weighted to more than 64 bones."); - - var boneIndicesArray = new ushort[64]; - Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); - - boneTableIndex = boneTableOffset; - boneTables.Add(new MdlStructs.BoneTableStruct() - { - BoneCount = (byte)boneIndices.Count, - BoneIndex = boneIndicesArray, - }); - } - - vertexDeclarations.Add(meshthing.VertexDeclaration); - var meshStartIndex = (uint)(meshthing.MeshStruct.StartIndex + idxOffset / sizeof(ushort)); - meshes.Add(meshthing.MeshStruct with - { - SubMeshIndex = (ushort)(meshthing.MeshStruct.SubMeshIndex + subOffset), - // TODO: should probably define a type for index type hey. - BoneTableIndex = (ushort)boneTableIndex, - StartIndex = meshStartIndex, - VertexBufferOffset = meshthing.MeshStruct.VertexBufferOffset - .Select(offset => (uint)(offset + vertOffset)) - .ToArray(), - }); - // TODO: could probably do this with linq cleaner - foreach (var xivSubmesh in meshthing.SubMeshStructs) - submeshes.Add(xivSubmesh with - { - // TODO: this will need to keep ticking up for each submesh in the same mesh - IndexOffset = (uint)(xivSubmesh.IndexOffset + idxOffset / sizeof(ushort)) - }); - vertexBuffer.AddRange(meshthing.VertexBuffer); - indices.AddRange(meshthing.Indicies.SelectMany(index => BitConverter.GetBytes((ushort)index))); - foreach (var shapeKey in meshthing.ShapeKeys) - { - List keyshapedata; - if (!shapeData.TryGetValue(shapeKey.Name, out keyshapedata)) - { - keyshapedata = new(); - shapeData.Add(shapeKey.Name, keyshapedata); - } - - keyshapedata.Add(shapeKey.ShapeMesh with - { - MeshIndexOffset = meshStartIndex, - ShapeValueOffset = (uint)shapeValueOffset, - }); - - shapeValues.AddRange(shapeKey.ShapeValues); - } - } - - var shapes = new List(); - var shapeMeshes = new List(); - - foreach (var (name, sms) in shapeData) - { - var smOff = shapeMeshes.Count; - - shapeMeshes.AddRange(sms); - shapes.Add(new MdlFile.Shape() - { - ShapeName = name, - // TODO: THESE IS PER LOD - ShapeMeshStartIndex = [(ushort)smOff, 0, 0], - ShapeMeshCount = [(ushort)sms.Count, 0, 0], - }); - } - - var mdl = new MdlFile() - { - Radius = 1, - // todo: lod calcs... probably handled in penum? we probably only need to think about lod0 for actual import workflow. - VertexOffset = [0, 0, 0], - IndexOffset = [(uint)vertexBuffer.Count, 0, 0], - VertexBufferSize = [(uint)vertexBuffer.Count, 0, 0], - IndexBufferSize = [(uint)indices.Count, 0, 0], - LodCount = 1, - BoundingBoxes = new MdlStructs.BoundingBoxStruct() - { - Min = [-1, 0, -1, 1], - Max = [1, 0, 1, 1], - }, - VertexDeclarations = vertexDeclarations.ToArray(), - Meshes = meshes.ToArray(), - BoneTables = boneTables.ToArray(), - BoneBoundingBoxes = [ - // new MdlStructs.BoundingBoxStruct() - // { - // Min = [ - // -0.081672676f, - // -0.113717034f, - // -0.11905348f, - // 1.0f, - // ], - // Max = [ - // 0.03941727f, - // 0.09845419f, - // 0.107391916f, - // 1.0f, - // ], - // }, - - // _would_ be nice if i didn't need to fill out this - new MdlStructs.BoundingBoxStruct() - { - Min = [0, 0, 0, 0], - Max = [0, 0, 0, 0], - } - ], - SubMeshes = submeshes.ToArray(), - - // TODO pretty sure this is garbage data as far as textools functions - // game clearly doesn't rely on this, but the "correct" values are a listing of the bones used by each submesh - SubMeshBoneMap = [0], - - Shapes = shapes.ToArray(), - ShapeMeshes = shapeMeshes.ToArray(), - ShapeValues = shapeValues.ToArray(), - - Lods = [new MdlStructs.LodStruct() - { - MeshIndex = 0, - MeshCount = (ushort)meshes.Count, - ModelLodRange = 0, - TextureLodRange = 0, - VertexBufferSize = (uint)vertexBuffer.Count, - VertexDataOffset = 0, - IndexBufferSize = (uint)indices.Count, - IndexDataOffset = (uint)vertexBuffer.Count, - }, - ], - Bones = bones.ToArray(), - Materials = [ - "/mt_c0201e6180_top_a.mtrl", - ], - RemainingData = vertexBuffer.Concat(indices).ToArray(), - }; - - Out = mdl; + Out = ModelImporter.Import(model); } public bool Equals(IAction? other) From 51bb9cf7cdabb7f0c47eb91405aa80e4945389ed Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 6 Jan 2024 18:26:30 +0100 Subject: [PATCH 0331/1381] Use existing game path functionality for sklb resolving, some cleanup. --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 84 ++++++++++--------- .../ModEditWindow.Models.MdlTab.cs | 79 +++-------------- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 17 ++-- 4 files changed, 69 insertions(+), 113 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ac3fc098..83c01275 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ac3fc0981ac8f503ac91d2419bd28c54f271763e +Subproject commit 83c012752cd9d13d39248eda85ab18cc59070a76 diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 35a5e53e..dd796a42 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,27 +1,20 @@ using Dalamud.Plugin.Services; using OtterGui.Tasks; -using Penumbra.Collections.Manager; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.Import.Models.Export; using SharpGLTF.Scenes; namespace Penumbra.Import.Models; -public sealed class ModelManager : SingleTaskQueue, IDisposable +public sealed class ModelManager(IFramework framework, GamePathParser _parser) : SingleTaskQueue, IDisposable { - private readonly IFramework _framework; - private readonly IDataManager _gameData; - private readonly ActiveCollectionData _activeCollectionData; + private readonly IFramework _framework = framework; private readonly ConcurrentDictionary _tasks = new(); - private bool _disposed = false; - public ModelManager(IFramework framework, IDataManager gameData, ActiveCollectionData activeCollectionData) - { - _framework = framework; - _gameData = gameData; - _activeCollectionData = activeCollectionData; - } + private bool _disposed; public void Dispose() { @@ -31,6 +24,31 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable _tasks.Clear(); } + public Task ExportToGltf(MdlFile mdl, SklbFile? sklb, string outputPath) + => Enqueue(new ExportToGltfAction(this, mdl, sklb, outputPath)); + + /// Try to find the .sklb path for a .mdl file. + /// .mdl file to look up the skeleton for. + public string? ResolveSklbForMdl(string mdlPath) + { + var info = _parser.GetFileInfo(mdlPath); + if (info.FileType is not FileType.Model) + return null; + + return info.ObjectType switch + { + ObjectType.Equipment => GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1), + ObjectType.Accessory => GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1), + ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", + 1), + ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), + ObjectType.DemiHuman => GamePaths.DemiHuman.Sklb.Path(info.PrimaryId), + ObjectType.Monster => GamePaths.Monster.Sklb.Path(info.PrimaryId), + ObjectType.Weapon => GamePaths.Weapon.Sklb.Path(info.PrimaryId), + _ => null, + }; + } + private Task Enqueue(IAction action) { if (_disposed) @@ -39,44 +57,34 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable Task task; lock (_tasks) { - task = _tasks.GetOrAdd(action, action => + task = _tasks.GetOrAdd(action, a => { var token = new CancellationTokenSource(); - var task = Enqueue(action, token.Token); - task.ContinueWith(_ => _tasks.TryRemove(action, out var unused), CancellationToken.None); - return (task, token); + var t = Enqueue(a, token.Token); + t.ContinueWith(_ => + { + lock (_tasks) + { + return _tasks.TryRemove(a, out var unused); + } + }, CancellationToken.None); + return (t, token); }).Item1; } return task; } - public Task ExportToGltf(MdlFile mdl, SklbFile? sklb, string outputPath) - => Enqueue(new ExportToGltfAction(this, mdl, sklb, outputPath)); - - private class ExportToGltfAction : IAction + private class ExportToGltfAction(ModelManager manager, MdlFile mdl, SklbFile? sklb, string outputPath) + : IAction { - private readonly ModelManager _manager; - - private readonly MdlFile _mdl; - private readonly SklbFile? _sklb; - private readonly string _outputPath; - - public ExportToGltfAction(ModelManager manager, MdlFile mdl, SklbFile? sklb, string outputPath) - { - _manager = manager; - _mdl = mdl; - _sklb = sklb; - _outputPath = outputPath; - } - public void Execute(CancellationToken cancel) { Penumbra.Log.Debug("Reading skeleton."); var xivSkeleton = BuildSkeleton(cancel); Penumbra.Log.Debug("Converting model."); - var model = ModelExporter.Export(_mdl, xivSkeleton); + var model = ModelExporter.Export(mdl, xivSkeleton); Penumbra.Log.Debug("Building scene."); var scene = new SceneBuilder(); @@ -84,16 +92,16 @@ public sealed class ModelManager : SingleTaskQueue, IDisposable Penumbra.Log.Debug("Saving."); var gltfModel = scene.ToGltf2(); - gltfModel.SaveGLTF(_outputPath); + gltfModel.SaveGLTF(outputPath); } /// Attempt to read out the pertinent information from a .sklb. private XivSkeleton? BuildSkeleton(CancellationToken cancel) { - if (_sklb == null) + if (sklb == null) return null; - var xmlTask = _manager._framework.RunOnFrameworkThread(() => HavokConverter.HkxToXml(_sklb.Skeleton)); + var xmlTask = manager._framework.RunOnFrameworkThread(() => HavokConverter.HkxToXml(sklb.Skeleton)); xmlTask.Wait(cancel); var xml = xmlTask.Result; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 93e674ea..b8573780 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -8,9 +8,9 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private partial class MdlTab : IWritable + private class MdlTab : IWritable { - private ModEditWindow _edit; + private readonly ModEditWindow _edit; public readonly MdlFile Mdl; private readonly List[] _attributes; @@ -18,21 +18,10 @@ public partial class ModEditWindow public List? GamePaths { get; private set; } public int GamePathIndex; - public bool PendingIo { get; private set; } = false; - public string? IoException { get; private set; } = null; + public bool PendingIo { get; private set; } + public string? IoException { get; private set; } - [GeneratedRegex(@"chara/(?:equipment|accessory)/(?'Set'[a-z]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", RegexOptions.Compiled)] - private static partial Regex CharaEquipmentRegex(); - - [GeneratedRegex(@"chara/human/(?'Race'c\d{4})/obj/(?'Type'[^/]+)/(?'Set'[^/]\d{4})/model/(?'Race'c\d{4})\k'Set'_[^/]+\.mdl", - RegexOptions.Compiled)] - private static partial Regex CharaHumanRegex(); - - [GeneratedRegex(@"chara/(?'SubCategory'demihuman|monster|weapon)/(?'Set'w\d{4})/obj/body/(?'Body'b\d{4})/model/\k'Set'\k'Body'.mdl", - RegexOptions.Compiled)] - private static partial Regex CharaBodyRegex(); - - public MdlTab(ModEditWindow edit, byte[] bytes, string path, Mod? mod) + public MdlTab(ModEditWindow edit, byte[] bytes, string path, IMod? mod) { _edit = edit; @@ -54,7 +43,7 @@ public partial class ModEditWindow /// Find the list of game paths that may correspond to this model. /// Resolved path to a .mdl. /// Mod within which the .mdl is resolved. - private void FindGamePaths(string path, Mod mod) + private void FindGamePaths(string path, IMod mod) { if (!Path.IsPathRooted(path) && Utf8GamePath.FromString(path, out var p)) { @@ -77,8 +66,8 @@ public partial class ModEditWindow task.ContinueWith(t => { IoException = t.Exception?.ToString(); - PendingIo = false; GamePaths = t.Result; + PendingIo = false; }); } @@ -89,7 +78,7 @@ public partial class ModEditWindow SklbFile? sklb = null; try { - var sklbPath = GetSklbPath(mdlPath.ToString()); + var sklbPath = _edit._models.ResolveSklbForMdl(mdlPath.ToString()); sklb = sklbPath != null ? ReadSklb(sklbPath) : null; } catch (Exception exception) @@ -107,43 +96,6 @@ public partial class ModEditWindow }); } - /// Try to find the .sklb path for a .mdl file. - /// .mdl file to look up the skeleton for. - private string? GetSklbPath(string mdlPath) - { - // Equipment is skinned to the base body skeleton of the race they target. - var match = CharaEquipmentRegex().Match(mdlPath); - if (match.Success) - { - var race = match.Groups["Race"].Value; - return $"chara/human/{race}/skeleton/base/b0001/skl_{race}b0001.sklb"; - } - - // Some parts of human have their own skeletons. - match = CharaHumanRegex().Match(mdlPath); - if (match.Success) - { - var type = match.Groups["Type"].Value; - var race = match.Groups["Race"].Value; - return type switch - { - "body" or "tail" => $"chara/human/{race}/skeleton/base/b0001/skl_{race}b0001.sklb", - _ => throw new Exception($"Currently unsupported human model type \"{type}\"."), - }; - } - - // A few subcategories - such as weapons, demihumans, and monsters - have dedicated per-"body" skeletons. - match = CharaBodyRegex().Match(mdlPath); - if (match.Success) - { - var subCategory = match.Groups["SubCategory"].Value; - var set = match.Groups["Set"].Value; - return $"chara/{subCategory}/{set}/skeleton/base/b0001/skl_{set}b0001.sklb"; - } - - return null; - } - /// Read a .sklb from the active collection or game. /// Game path to the .sklb to load. private SklbFile ReadSklb(string sklbPath) @@ -153,17 +105,12 @@ public partial class ModEditWindow throw new Exception($"Resolved skeleton path {sklbPath} could not be converted to a game path."); var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8SklbPath); - // TODO: is it worth trying to use streams for these instead? i'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... - var bytes = resolvedPath switch - { - null => _edit._gameData.GetFile(sklbPath)?.Data, - FullPath path => File.ReadAllBytes(path.ToPath()), - }; - if (bytes == null) - throw new Exception( + // TODO: is it worth trying to use streams for these instead? I'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... + var bytes = resolvedPath == null ? _edit._gameData.GetFile(sklbPath)?.Data : File.ReadAllBytes(resolvedPath.Value.ToPath()); + return bytes != null + ? new SklbFile(bytes) + : throw new Exception( $"Resolved skeleton path {sklbPath} could not be found. If modded, is it enabled in the current collection?"); - - return new SklbFile(bytes); } /// Remove the material given by the index. diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 3891eb95..24b45b88 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -15,7 +15,6 @@ public partial class ModEditWindow private const int MdlMaterialMaximum = 4; private readonly FileEditor _modelTab; - private readonly ModelManager _models; private string _modelNewMaterial = string.Empty; @@ -91,19 +90,21 @@ public partial class ModEditWindow private void DrawGamePathCombo(MdlTab tab) { - if (tab.GamePaths!.Count == 0) + if (tab.GamePaths!.Count != 0) { - ImGui.TextUnformatted("No associated game path detected. Valid game paths are currently necessary for exporting."); - if (ImGui.InputTextWithHint("##customInput", "Enter custom game path...", ref _customPath, 256)) - if (!Utf8GamePath.FromString(_customPath, out _customGamePath, false)) - _customGamePath = Utf8GamePath.Empty; - + DrawComboButton(tab); return; } - DrawComboButton(tab); + ImGui.TextUnformatted("No associated game path detected. Valid game paths are currently necessary for exporting."); + if (!ImGui.InputTextWithHint("##customInput", "Enter custom game path...", ref _customPath, 256)) + return; + + if (!Utf8GamePath.FromString(_customPath, out _customGamePath, false)) + _customGamePath = Utf8GamePath.Empty; } + /// I disliked the combo with only one selection so turn it into a button in that case. private static void DrawComboButton(MdlTab tab) { const string label = "Game Path"; From 677c9bd801490ddb961f5c923ab11a5c879c946f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 6 Jan 2024 18:37:52 +0100 Subject: [PATCH 0332/1381] Some cleanup and using new features / intellisense recommendations. --- Penumbra/Import/Models/Export/MeshExporter.cs | 113 +++++++++--------- .../Import/Models/Export/ModelExporter.cs | 23 +--- Penumbra/Import/Models/Export/Skeleton.cs | 9 +- Penumbra/Import/Models/HavokConverter.cs | 50 ++++---- Penumbra/Import/Models/SkeletonConverter.cs | 50 ++++---- 5 files changed, 117 insertions(+), 128 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 1b53df8a..84628c2c 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -13,24 +13,17 @@ namespace Penumbra.Import.Models.Export; public class MeshExporter { - public class Mesh + public class Mesh(IEnumerable> meshes, NodeBuilder[]? joints) { - private IMeshBuilder[] _meshes; - private NodeBuilder[]? _joints; - - public Mesh(IMeshBuilder[] meshes, NodeBuilder[]? joints) - { - _meshes = meshes; - _joints = joints; - } - public void AddToScene(SceneBuilder scene) { - foreach (var mesh in _meshes) - if (_joints == null) + foreach (var mesh in meshes) + { + if (joints == null) scene.AddRigidMesh(mesh, Matrix4x4.Identity); else - scene.AddSkinnedMesh(mesh, Matrix4x4.Identity, _joints); + scene.AddSkinnedMesh(mesh, Matrix4x4.Identity, joints); + } } } @@ -43,9 +36,11 @@ public class MeshExporter private const byte MaximumMeshBufferStreams = 3; private readonly MdlFile _mdl; - private readonly byte _lod; - private readonly ushort _meshIndex; - private MdlStructs.MeshStruct XivMesh => _mdl.Meshes[_meshIndex]; + private readonly byte _lod; + private readonly ushort _meshIndex; + + private MdlStructs.MeshStruct XivMesh + => _mdl.Meshes[_meshIndex]; private readonly Dictionary? _boneIndexMap; @@ -53,10 +48,10 @@ public class MeshExporter private readonly Type _materialType; private readonly Type _skinningType; - private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, Dictionary? boneNameMap) + private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, IReadOnlyDictionary? boneNameMap) { - _mdl = mdl; - _lod = lod; + _mdl = mdl; + _lod = lod; _meshIndex = meshIndex; if (boneNameMap != null) @@ -76,11 +71,12 @@ public class MeshExporter if (_skinningType != typeof(VertexEmpty) && _boneIndexMap == null) Penumbra.Log.Warning($"Mesh {meshIndex} has skinned vertex usages but no bone information was provided."); - Penumbra.Log.Debug($"Mesh {meshIndex} using vertex types geometry: {_geometryType.Name}, material: {_materialType.Name}, skinning: {_skinningType.Name}"); + Penumbra.Log.Debug( + $"Mesh {meshIndex} using vertex types geometry: {_geometryType.Name}, material: {_materialType.Name}, skinning: {_skinningType.Name}"); } - /// Build a mapping between indices in this mesh's bone table (if any), and the glTF joint indices provdied. - private Dictionary? BuildBoneIndexMap(Dictionary boneNameMap) + /// Build a mapping between indices in this mesh's bone table (if any), and the glTF joint indices provided. + private Dictionary? BuildBoneIndexMap(IReadOnlyDictionary boneNameMap) { // A BoneTableIndex of 255 means that this mesh is not skinned. if (XivMesh.BoneTableIndex == 255) @@ -105,11 +101,10 @@ public class MeshExporter /// Build glTF meshes for this XIV mesh. private IMeshBuilder[] BuildMeshes() { - var indices = BuildIndices(); + var indices = BuildIndices(); var vertices = BuildVertices(); // NOTE: Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh, so we're specifying the index base relative to the mesh's base. - if (XivMesh.SubMeshCount == 0) return [BuildMesh($"mesh {_meshIndex}", indices, vertices, 0, (int)XivMesh.IndexCount)]; @@ -117,7 +112,8 @@ public class MeshExporter .Skip(XivMesh.SubMeshIndex) .Take(XivMesh.SubMeshCount) .WithIndex() - .Select(submesh => BuildMesh($"mesh {_meshIndex}.{submesh.Index}", indices, vertices, (int)(submesh.Value.IndexOffset - XivMesh.StartIndex), (int)submesh.Value.IndexCount)) + .Select(subMesh => BuildMesh($"mesh {_meshIndex}.{subMesh.Index}", indices, vertices, + (int)(subMesh.Value.IndexOffset - XivMesh.StartIndex), (int)subMesh.Value.IndexCount)) .ToArray(); } @@ -161,7 +157,7 @@ public class MeshExporter } var primitiveVertices = meshBuilder.Primitives.First().Vertices; - var shapeNames = new List(); + var shapeNames = new List(); foreach (var shape in _mdl.Shapes) { @@ -177,24 +173,28 @@ public class MeshExporter ) .Where(shapeValue => shapeValue.BaseIndicesIndex >= indexBase - && shapeValue.BaseIndicesIndex < indexBase + indexCount + && shapeValue.BaseIndicesIndex < indexBase + indexCount ) .ToList(); - if (shapeValues.Count == 0) continue; + if (shapeValues.Count == 0) + continue; var morphBuilder = meshBuilder.UseMorphTarget(shapeNames.Count); shapeNames.Add(shape.ShapeName); foreach (var shapeValue in shapeValues) + { morphBuilder.SetVertex( primitiveVertices[gltfIndices[shapeValue.BaseIndicesIndex - indexBase]].GetGeometry(), vertices[shapeValue.ReplacingVertexIndex].GetGeometry() ); + } } - meshBuilder.Extras = JsonContent.CreateFrom(new Dictionary() { - {"targetNames", shapeNames} + meshBuilder.Extras = JsonContent.CreateFrom(new Dictionary() + { + { "targetNames", shapeNames }, }); return meshBuilder; @@ -249,23 +249,25 @@ public class MeshExporter } /// Read a vertex attribute of the specified type from a vertex buffer stream. - private object ReadVertexAttribute(MdlFile.VertexType type, BinaryReader reader) + private static object ReadVertexAttribute(MdlFile.VertexType type, BinaryReader reader) { return type switch { MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), - MdlFile.VertexType.UInt => reader.ReadBytes(4), - MdlFile.VertexType.ByteFloat4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), + MdlFile.VertexType.UInt => reader.ReadBytes(4), + MdlFile.VertexType.ByteFloat4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, + reader.ReadByte() / 255f), MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), - MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), + MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), + (float)reader.ReadHalf()), - _ => throw new ArgumentOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(), }; } /// Get the vertex geometry type for this mesh's vertex usages. - private Type GetGeometryType(IReadOnlyDictionary usages) + private static Type GetGeometryType(IReadOnlyDictionary usages) { if (!usages.ContainsKey(MdlFile.VertexUsage.Position)) throw new Exception("Mesh does not contain position vertex elements."); @@ -304,16 +306,16 @@ public class MeshExporter } /// Get the vertex material type for this mesh's vertex usages. - private Type GetMaterialType(IReadOnlyDictionary usages) + private static Type GetMaterialType(IReadOnlyDictionary usages) { var uvCount = 0; if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var type)) uvCount = type switch { - MdlFile.VertexType.Half2 => 1, - MdlFile.VertexType.Half4 => 2, + MdlFile.VertexType.Half2 => 1, + MdlFile.VertexType.Half4 => 2, MdlFile.VertexType.Single4 => 2, - _ => throw new Exception($"Unexpected UV vertex type {type}.") + _ => throw new Exception($"Unexpected UV vertex type {type}."), }; var materialUsages = ( @@ -323,11 +325,11 @@ public class MeshExporter return materialUsages switch { - (2, true) => typeof(VertexColor1Texture2), + (2, true) => typeof(VertexColor1Texture2), (2, false) => typeof(VertexTexture2), - (1, true) => typeof(VertexColor1Texture1), + (1, true) => typeof(VertexColor1Texture1), (1, false) => typeof(VertexTexture1), - (0, true) => typeof(VertexColor1), + (0, true) => typeof(VertexColor1), (0, false) => typeof(VertexEmpty), _ => throw new Exception("Unreachable."), @@ -377,7 +379,7 @@ public class MeshExporter } /// Get the vertex skinning type for this mesh's vertex usages. - private Type GetSkinningType(IReadOnlyDictionary usages) + private static Type GetSkinningType(IReadOnlyDictionary usages) { if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) return typeof(VertexJoints4); @@ -400,7 +402,8 @@ public class MeshExporter var weights = ToVector4(attributes[MdlFile.VertexUsage.BlendWeights]); var bindings = Enumerable.Range(0, 4) - .Select(bindingIndex => { + .Select(bindingIndex => + { // NOTE: I've not seen any files that throw this error that aren't completely broken. var xivBoneIndex = indices[bindingIndex]; if (!_boneIndexMap.TryGetValue(xivBoneIndex, out var jointIndex)) @@ -417,44 +420,44 @@ public class MeshExporter /// Clamps any tangent W value other than 1 to -1. /// Some XIV models seemingly store -1 as 0, this patches over that. - private Vector4 FixTangentVector(Vector4 tangent) + private static Vector4 FixTangentVector(Vector4 tangent) => tangent with { W = tangent.W == 1 ? 1 : -1 }; /// Convert a vertex attribute value to a Vector2. Supported inputs are Vector2, Vector3, and Vector4. - private Vector2 ToVector2(object data) + private static Vector2 ToVector2(object data) => data switch { Vector2 v2 => v2, Vector3 v3 => new Vector2(v3.X, v3.Y), Vector4 v4 => new Vector2(v4.X, v4.Y), - _ => throw new ArgumentOutOfRangeException($"Invalid Vector2 input {data}") + _ => throw new ArgumentOutOfRangeException($"Invalid Vector2 input {data}"), }; /// Convert a vertex attribute value to a Vector3. Supported inputs are Vector2, Vector3, and Vector4. - private Vector3 ToVector3(object data) + private static Vector3 ToVector3(object data) => data switch { Vector2 v2 => new Vector3(v2.X, v2.Y, 0), Vector3 v3 => v3, Vector4 v4 => new Vector3(v4.X, v4.Y, v4.Z), - _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") + _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}"), }; /// Convert a vertex attribute value to a Vector4. Supported inputs are Vector2, Vector3, and Vector4. - private Vector4 ToVector4(object data) + private static Vector4 ToVector4(object data) => data switch { - Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0), + Vector2 v2 => new Vector4(v2.X, v2.Y, 0, 0), Vector3 v3 => new Vector4(v3.X, v3.Y, v3.Z, 1), Vector4 v4 => v4, - _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}") + _ => throw new ArgumentOutOfRangeException($"Invalid Vector3 input {data}"), }; /// Convert a vertex attribute value to a byte array. - private byte[] ToByteArray(object data) + private static byte[] ToByteArray(object data) => data switch { byte[] value => value, - _ => throw new ArgumentOutOfRangeException($"Invalid byte[] input {data}") + _ => throw new ArgumentOutOfRangeException($"Invalid byte[] input {data}"), }; } diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 35819e7a..2060c323 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -6,26 +6,17 @@ namespace Penumbra.Import.Models.Export; public class ModelExporter { - public class Model + public class Model(List meshes, GltfSkeleton? skeleton) { - private List _meshes; - private GltfSkeleton? _skeleton; - - public Model(List meshes, GltfSkeleton? skeleton) - { - _meshes = meshes; - _skeleton = skeleton; - } - public void AddToScene(SceneBuilder scene) { // If there's a skeleton, the root node should be added before we add any potentially skinned meshes. - var skeletonRoot = _skeleton?.Root; + var skeletonRoot = skeleton?.Root; if (skeletonRoot != null) scene.AddNode(skeletonRoot); // Add all the meshes to the scene. - foreach (var mesh in _meshes) + foreach (var mesh in meshes) mesh.AddToScene(scene); } } @@ -64,10 +55,8 @@ public class ModelExporter NodeBuilder? root = null; var names = new Dictionary(); var joints = new List(); - for (var boneIndex = 0; boneIndex < skeleton.Bones.Length; boneIndex++) + foreach (var bone in skeleton.Bones) { - var bone = skeleton.Bones[boneIndex]; - if (names.ContainsKey(bone.Name)) continue; var node = new NodeBuilder(bone.Name); @@ -93,10 +82,10 @@ public class ModelExporter if (root == null) return null; - return new() + return new GltfSkeleton { Root = root, - Joints = joints.ToArray(), + Joints = [.. joints], Names = names, }; } diff --git a/Penumbra/Import/Models/Export/Skeleton.cs b/Penumbra/Import/Models/Export/Skeleton.cs index 09cdcc32..fee107a0 100644 --- a/Penumbra/Import/Models/Export/Skeleton.cs +++ b/Penumbra/Import/Models/Export/Skeleton.cs @@ -3,14 +3,9 @@ using SharpGLTF.Scenes; namespace Penumbra.Import.Models.Export; /// Representation of a skeleton within XIV. -public class XivSkeleton +public class XivSkeleton(XivSkeleton.Bone[] bones) { - public Bone[] Bones; - - public XivSkeleton(Bone[] bones) - { - Bones = bones; - } + public Bone[] Bones = bones; public struct Bone { diff --git a/Penumbra/Import/Models/HavokConverter.cs b/Penumbra/Import/Models/HavokConverter.cs index 7f87d50a..01c27b61 100644 --- a/Penumbra/Import/Models/HavokConverter.cs +++ b/Penumbra/Import/Models/HavokConverter.cs @@ -16,17 +16,18 @@ public static unsafe class HavokConverter /// A byte array representing the .hkx file. public static string HkxToXml(byte[] hkx) { + const hkSerializeUtil.SaveOptionBits options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers + | hkSerializeUtil.SaveOptionBits.TextFormat + | hkSerializeUtil.SaveOptionBits.WriteAttributes; + var tempHkx = CreateTempFile(); File.WriteAllBytes(tempHkx, hkx); var resource = Read(tempHkx); File.Delete(tempHkx); - if (resource == null) throw new Exception("Failed to read havok file."); - - var options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers - | hkSerializeUtil.SaveOptionBits.TextFormat - | hkSerializeUtil.SaveOptionBits.WriteAttributes; + if (resource == null) + throw new Exception("Failed to read havok file."); var file = Write(resource, options); file.Close(); @@ -41,17 +42,19 @@ public static unsafe class HavokConverter /// A string representing the .xml file. public static byte[] XmlToHkx(string xml) { + const hkSerializeUtil.SaveOptionBits options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers + | hkSerializeUtil.SaveOptionBits.WriteAttributes; + var tempXml = CreateTempFile(); File.WriteAllText(tempXml, xml); var resource = Read(tempXml); File.Delete(tempXml); - if (resource == null) throw new Exception("Failed to read havok file."); - - var options = hkSerializeUtil.SaveOptionBits.SerializeIgnoredMembers - | hkSerializeUtil.SaveOptionBits.WriteAttributes; + if (resource == null) + throw new Exception("Failed to read havok file."); + g var file = Write(resource, options); file.Close(); @@ -74,7 +77,7 @@ public static unsafe class HavokConverter var builtinTypeRegistry = hkBuiltinTypeRegistry.Instance(); var loadOptions = stackalloc hkSerializeUtil.LoadOptions[1]; - loadOptions->Flags = new() { Storage = (int)hkSerializeUtil.LoadOptionBits.Default }; + loadOptions->Flags = new hkFlags { Storage = (int)hkSerializeUtil.LoadOptionBits.Default }; loadOptions->ClassNameRegistry = builtinTypeRegistry->GetClassNameRegistry(); loadOptions->TypeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); @@ -92,37 +95,42 @@ public static unsafe class HavokConverter ) { var tempFile = CreateTempFile(); - var path = Marshal.StringToHGlobalAnsi(tempFile); - var oStream = new hkOstream(); + var path = Marshal.StringToHGlobalAnsi(tempFile); + var oStream = new hkOstream(); oStream.Ctor((byte*)path); var result = stackalloc hkResult[1]; var saveOptions = new hkSerializeUtil.SaveOptions() { - Flags = new() { Storage = (int)optionBits } + Flags = new hkFlags { Storage = (int)optionBits }, }; - var builtinTypeRegistry = hkBuiltinTypeRegistry.Instance(); - var classNameRegistry = builtinTypeRegistry->GetClassNameRegistry(); - var typeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); + var classNameRegistry = builtinTypeRegistry->GetClassNameRegistry(); + var typeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); try { - var name = "hkRootLevelContainer"; + const string name = "hkRootLevelContainer"; var resourcePtr = (hkRootLevelContainer*)resource->GetContentsPointer(name, typeInfoRegistry); - if (resourcePtr == null) throw new Exception("Failed to retrieve havok root level container resource."); + if (resourcePtr == null) + throw new Exception("Failed to retrieve havok root level container resource."); var hkRootLevelContainerClass = classNameRegistry->GetClassByName(name); - if (hkRootLevelContainerClass == null) throw new Exception("Failed to retrieve havok root level container type."); + if (hkRootLevelContainerClass == null) + throw new Exception("Failed to retrieve havok root level container type."); hkSerializeUtil.Save(result, resourcePtr, hkRootLevelContainerClass, oStream.StreamWriter.ptr, saveOptions); } - finally { oStream.Dtor(); } + finally + { + oStream.Dtor(); + } - if (result->Result == hkResult.hkResultEnum.Failure) throw new Exception("Failed to serialize havok file."); + if (result->Result == hkResult.hkResultEnum.Failure) + throw new Exception("Failed to serialize havok file."); return new FileStream(tempFile, FileMode.Open); } diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs index 24bcf3e0..7058a159 100644 --- a/Penumbra/Import/Models/SkeletonConverter.cs +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -15,16 +15,15 @@ public static class SkeletonConverter var mainSkeletonId = GetMainSkeletonId(document); - var skeletonNode = document.SelectSingleNode($"/hktagfile/object[@type='hkaSkeleton'][@id='{mainSkeletonId}']"); - if (skeletonNode == null) - throw new InvalidDataException($"Failed to find skeleton with id {mainSkeletonId}."); - + var skeletonNode = document.SelectSingleNode($"/hktagfile/object[@type='hkaSkeleton'][@id='{mainSkeletonId}']") + ?? throw new InvalidDataException($"Failed to find skeleton with id {mainSkeletonId}."); var referencePose = ReadReferencePose(skeletonNode); var parentIndices = ReadParentIndices(skeletonNode); - var boneNames = ReadBoneNames(skeletonNode); + var boneNames = ReadBoneNames(skeletonNode); if (boneNames.Length != parentIndices.Length || boneNames.Length != referencePose.Length) - throw new InvalidDataException($"Mismatch in bone value array lengths: names({boneNames.Length}) parents({parentIndices.Length}) pose({referencePose.Length})"); + throw new InvalidDataException( + $"Mismatch in bone value array lengths: names({boneNames.Length}) parents({parentIndices.Length}) pose({referencePose.Length})"); var bones = referencePose .Zip(parentIndices, boneNames) @@ -33,9 +32,9 @@ public static class SkeletonConverter var (transform, parentIndex, name) = values; return new XivSkeleton.Bone() { - Transform = transform, + Transform = transform, ParentIndex = parentIndex, - Name = name, + Name = name, }; }) .ToArray(); @@ -63,14 +62,14 @@ public static class SkeletonConverter { return ReadArray( CheckExists(node.SelectSingleNode("array[@name='referencePose']")), - node => + n => { - var raw = ReadVec12(node); + var raw = ReadVec12(n); return new XivSkeleton.Transform() { - Translation = new(raw[0], raw[1], raw[2]), - Rotation = new(raw[4], raw[5], raw[6], raw[7]), - Scale = new(raw[8], raw[9], raw[10]), + Translation = new Vector3(raw[0], raw[1], raw[2]), + Rotation = new Quaternion(raw[4], raw[5], raw[6], raw[7]), + Scale = new Vector3(raw[8], raw[9], raw[10]), }; } ); @@ -82,11 +81,11 @@ public static class SkeletonConverter { var array = node.ChildNodes .Cast() - .Where(node => node.NodeType != XmlNodeType.Comment) - .Select(node => + .Where(n => n.NodeType != XmlNodeType.Comment) + .Select(n => { - var text = node.InnerText.Trim()[1..]; - // TODO: surely there's a less shit way to do this i mean seriously + var text = n.InnerText.Trim()[1..]; + // TODO: surely there's a less shit way to do this I mean seriously return BitConverter.ToSingle(BitConverter.GetBytes(int.Parse(text, NumberStyles.HexNumber))); }) .ToArray(); @@ -100,24 +99,20 @@ public static class SkeletonConverter /// Read the bone parent relations for a skeleton. /// XML node for the skeleton. private static int[] ReadParentIndices(XmlNode node) - { // todo: would be neat to genericise array between bare and children - return CheckExists(node.SelectSingleNode("array[@name='parentIndices']")) + => CheckExists(node.SelectSingleNode("array[@name='parentIndices']")) .InnerText - .Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Split((char[]) [' ', '\n'], StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); - } /// Read the names of bones in a skeleton. /// XML node for the skeleton. private static string[] ReadBoneNames(XmlNode node) - { - return ReadArray( + => ReadArray( CheckExists(node.SelectSingleNode("array[@name='bones']")), - node => CheckExists(node.SelectSingleNode("string[@name='name']")).InnerText + n => CheckExists(n.SelectSingleNode("string[@name='name']")).InnerText ); - } /// Read an XML tagfile array, converting it via the provided conversion function. /// Tagfile XML array node. @@ -125,10 +120,9 @@ public static class SkeletonConverter private static T[] ReadArray(XmlNode node, Func convert) { var element = (XmlElement)node; + var size = int.Parse(element.GetAttribute("size")); + var array = new T[size]; - var size = int.Parse(element.GetAttribute("size")); - - var array = new T[size]; foreach (var (childNode, index) in element.ChildNodes.Cast().WithIndex()) array[index] = convert(childNode); From 9311f80455e169d44bfdc370d52b69291a0c2bf7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 6 Jan 2024 17:49:43 +0000 Subject: [PATCH 0333/1381] [CI] Updating repo.json for testing_0.8.3.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index dbe1fe87..e27d716a 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.2", + "TestingAssemblyVersion": "0.8.3.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 981721ae858ccee8ef47828884b15b12a5442320 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 6 Jan 2024 23:26:35 +0100 Subject: [PATCH 0334/1381] Fix issue with unloaded Message Service. --- OtterGui | 2 +- Penumbra/Penumbra.cs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 22ae2a89..2c603cea 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 22ae2a8993ebf3af2313072968a44905a3fcdd2a +Subproject commit 2c603cea9b1d4dd500e30972b64bd2f25012dc4c diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 350c20b2..5a03dc04 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -55,7 +55,10 @@ public class Penumbra : IDalamudPlugin _services = ServiceManagerA.CreateProvider(this, pluginInterface, Log); Messager = _services.GetService(); _validityChecker = _services.GetService(); - var startup = _services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool s) + _services.EnsureRequiredServices(); + + var startup = _services.GetService() + .GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool s) ? s.ToString() : "Unknown"; Log.Information( From b62bc44564c143f4aec0b14111c46dd18ddfa2df Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 7 Jan 2024 11:29:31 +1100 Subject: [PATCH 0335/1381] Clean up model import UI/wiring --- Penumbra/Import/Models/ModelManager.cs | 19 +++---- .../ModEditWindow.Models.MdlTab.cs | 35 +++++++++++-- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 49 +++++++++++++------ 3 files changed, 72 insertions(+), 31 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index e77a94e3..afb92fc0 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -10,7 +10,7 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models; -public sealed class ModelManager(IFramework framework, GamePathParser _parser) : SingleTaskQueue, IDisposable +public sealed class ModelManager(IFramework framework, GamePathParser parser) : SingleTaskQueue, IDisposable { private readonly IFramework _framework = framework; @@ -29,17 +29,17 @@ public sealed class ModelManager(IFramework framework, GamePathParser _parser) : public Task ExportToGltf(MdlFile mdl, SklbFile? sklb, string outputPath) => Enqueue(new ExportToGltfAction(this, mdl, sklb, outputPath)); - public Task ImportGltf() + public Task ImportGltf(string inputPath) { - var action = new ImportGltfAction(); - return Enqueue(action).ContinueWith(_ => action.Out!); + var action = new ImportGltfAction(inputPath); + return Enqueue(action).ContinueWith(_ => action.Out); } /// Try to find the .sklb path for a .mdl file. /// .mdl file to look up the skeleton for. public string? ResolveSklbForMdl(string mdlPath) { - var info = _parser.GetFileInfo(mdlPath); + var info = parser.GetFileInfo(mdlPath); if (info.FileType is not FileType.Model) return null; @@ -126,18 +126,13 @@ public sealed class ModelManager(IFramework framework, GamePathParser _parser) : } } - private partial class ImportGltfAction : IAction + private partial class ImportGltfAction(string inputPath) : IAction { public MdlFile? Out; - public ImportGltfAction() - { - // - } - public void Execute(CancellationToken cancel) { - var model = ModelRoot.Load("C:\\Users\\ackwell\\blender\\gltf-tests\\c0201e6180_top.gltf"); + var model = ModelRoot.Load(inputPath); Out = ModelImporter.Import(model); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 90a6645a..06196610 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -18,8 +18,9 @@ public partial class ModEditWindow public List? GamePaths { get; private set; } public int GamePathIndex; - public bool PendingIo { get; private set; } - public string? IoException { get; private set; } + private bool _dirty; + public bool PendingIo { get; private set; } + public string? IoException { get; private set; } public MdlTab(ModEditWindow edit, byte[] bytes, string path, IMod? mod) { @@ -46,6 +47,16 @@ public partial class ModEditWindow public byte[] Write() => Mdl.Write(); + public bool Dirty + { + get + { + var dirty = _dirty; + _dirty = false; + return dirty; + } + } + /// Find the list of game paths that may correspond to this model. /// Resolved path to a .mdl. /// Mod within which the .mdl is resolved. @@ -77,14 +88,28 @@ public partial class ModEditWindow }); } - public void Import() + /// Import a model from an interchange format. + /// Disk path to load model data from. + public void Import(string inputPath) { - // TODO: this needs to be fleshed out a bunch. - _edit._models.ImportGltf().ContinueWith(v => Initialize(v.Result ?? Mdl)); + PendingIo = true; + _edit._models.ImportGltf(inputPath) + .ContinueWith(task => + { + IoException = task.Exception?.ToString(); + PendingIo = false; + + if (task.IsCompletedSuccessfully && task.Result != null) + { + Initialize(task.Result); + _dirty = true; + } + }); } /// Export model to an interchange format. /// Disk path to save the resulting file to. + /// Game path to consider as the canonical .mdl path during export, used for resolution of other files. public void Export(string outputPath, Utf8GamePath mdlPath) { SklbFile? sklb = null; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 5703c882..b3598b9d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -35,15 +35,9 @@ public partial class ModEditWindow ); } - DrawExport(tab, disabled); + DrawImportExport(tab, disabled); - var ret = false; - - if (ImGui.Button("import test")) - { - tab.Import(); - ret |= true; - } + var ret = tab.Dirty; ret |= DrawModelMaterialDetails(tab, disabled); @@ -56,11 +50,41 @@ public partial class ModEditWindow return !disabled && ret; } - private void DrawExport(MdlTab tab, bool disabled) + private void DrawImportExport(MdlTab tab, bool disabled) { - if (!ImGui.CollapsingHeader("Export")) + if (!ImGui.CollapsingHeader("Import / Export")) return; + var windowWidth = ImGui.GetWindowContentRegionMax().X - ImGui.GetWindowContentRegionMin().X; + var childWidth = (windowWidth - ImGui.GetStyle().ItemSpacing.X * 3) / 2; + var childSize = new Vector2(childWidth, 0); + + DrawImport(tab, childSize, disabled); + ImGui.SameLine(); + DrawExport(tab, childSize, disabled); + + if (tab.IoException != null) + ImGuiUtil.TextWrapped(tab.IoException); + } + + private void DrawImport(MdlTab tab, Vector2 size, bool disabled) + { + using var frame = ImRaii.FramedGroup("Import", size); + + if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", tab.PendingIo)) + { + _fileDialog.OpenFilePicker("Load model from glTF.", "glTF{.gltf,.glb}", (success, paths) => + { + if (success && paths.Count > 0) + tab.Import(paths[0]); + }, 1, _mod!.ModPath.FullName, false); + } + } + + private void DrawExport(MdlTab tab, Vector2 size, bool disabled) + { + using var frame = ImRaii.FramedGroup("Export", size); + if (tab.GamePaths == null) { if (tab.IoException == null) @@ -89,9 +113,6 @@ public partial class ModEditWindow _mod!.ModPath.FullName, false ); - - if (tab.IoException != null) - ImGuiUtil.TextWrapped(tab.IoException); } private void DrawGamePathCombo(MdlTab tab) @@ -116,7 +137,7 @@ public partial class ModEditWindow const string label = "Game Path"; var preview = tab.GamePaths![tab.GamePathIndex].ToString(); var labelWidth = ImGui.CalcTextSize(label).X + ImGui.GetStyle().ItemInnerSpacing.X; - var buttonWidth = ImGui.GetContentRegionAvail().X - labelWidth; + var buttonWidth = ImGui.GetContentRegionAvail().X - labelWidth - ImGui.GetStyle().ItemSpacing.X; if (tab.GamePaths!.Count == 1) { using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); From aa7f0bace9a55da8fdcd08d7acb427081735f153 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 7 Jan 2024 19:49:13 +1100 Subject: [PATCH 0336/1381] Wire up hair EST resolution --- .../Import/Models/Export/ModelExporter.cs | 9 +- Penumbra/Import/Models/ModelManager.cs | 89 ++++++++++++++----- .../ModEditWindow.Models.MdlTab.cs | 42 ++++++--- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 4 files changed, 104 insertions(+), 38 deletions(-) diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 2060c323..07b37eeb 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -22,7 +22,7 @@ public class ModelExporter } /// Export a model in preparation for usage in a glTF file. If provided, skeleton will be used to skin the resulting meshes where appropriate. - public static Model Export(MdlFile mdl, XivSkeleton? xivSkeleton) + public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton) { var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; var meshes = ConvertMeshes(mdl, gltfSkeleton); @@ -50,12 +50,15 @@ public class ModelExporter } /// Convert XIV skeleton data into a glTF-compatible node tree, with mappings. - private static GltfSkeleton? ConvertSkeleton(XivSkeleton skeleton) + private static GltfSkeleton? ConvertSkeleton(IEnumerable skeletons) { NodeBuilder? root = null; var names = new Dictionary(); var joints = new List(); - foreach (var bone in skeleton.Bones) + + // Flatten out the bones across all the recieved skeletons, but retain a reference to the parent skeleton for lookups. + var iterator = skeletons.SelectMany(skeleton => skeleton.Bones.Select(bone => (skeleton, bone))); + foreach (var (skeleton, bone) in iterator) { if (names.ContainsKey(bone.Name)) continue; diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index dd796a42..a9e1b32d 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,14 +1,19 @@ using Dalamud.Plugin.Services; +using OtterGui; using OtterGui.Tasks; +using Penumbra.Collections.Manager; +using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; +using Penumbra.GameData.Structs; using Penumbra.Import.Models.Export; +using Penumbra.Meta.Manipulations; using SharpGLTF.Scenes; namespace Penumbra.Import.Models; -public sealed class ModelManager(IFramework framework, GamePathParser _parser) : SingleTaskQueue, IDisposable +public sealed class ModelManager(IFramework framework, ActiveCollections collections, GamePathParser parser) : SingleTaskQueue, IDisposable { private readonly IFramework _framework = framework; @@ -24,31 +29,55 @@ public sealed class ModelManager(IFramework framework, GamePathParser _parser) : _tasks.Clear(); } - public Task ExportToGltf(MdlFile mdl, SklbFile? sklb, string outputPath) - => Enqueue(new ExportToGltfAction(this, mdl, sklb, outputPath)); + public Task ExportToGltf(MdlFile mdl, IEnumerable? sklbs, string outputPath) + => Enqueue(new ExportToGltfAction(this, mdl, sklbs, outputPath)); - /// Try to find the .sklb path for a .mdl file. - /// .mdl file to look up the skeleton for. - public string? ResolveSklbForMdl(string mdlPath) + /// Try to find the .sklb paths for a .mdl file. + /// .mdl file to look up the skeletons for. + public string[]? ResolveSklbsForMdl(string mdlPath, EstManipulation[] estManipulations) { - var info = _parser.GetFileInfo(mdlPath); + var info = parser.GetFileInfo(mdlPath); if (info.FileType is not FileType.Model) return null; + var baseSkeleton = GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1); + return info.ObjectType switch { - ObjectType.Equipment => GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1), - ObjectType.Accessory => GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1), - ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", - 1), + ObjectType.Equipment => [baseSkeleton], + ObjectType.Accessory => [baseSkeleton], + ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => [baseSkeleton], + ObjectType.Character when info.BodySlot is BodySlot.Hair + => [baseSkeleton, ResolveHairSkeleton(info, estManipulations)], ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), - ObjectType.DemiHuman => GamePaths.DemiHuman.Sklb.Path(info.PrimaryId), - ObjectType.Monster => GamePaths.Monster.Sklb.Path(info.PrimaryId), - ObjectType.Weapon => GamePaths.Weapon.Sklb.Path(info.PrimaryId), + ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], + ObjectType.Monster => [GamePaths.Monster.Sklb.Path(info.PrimaryId)], + ObjectType.Weapon => [GamePaths.Weapon.Sklb.Path(info.PrimaryId)], _ => null, }; } + private string ResolveHairSkeleton(GameObjectInfo info, EstManipulation[] estManipulations) + { + // TODO: might be able to genericse this over esttype based on incoming info + var (gender, race) = info.GenderRace.Split(); + var modEst = estManipulations + .FirstOrNull(est => + est.Gender == gender + && est.Race == race + && est.Slot == EstManipulation.EstType.Hair + && est.SetId == info.PrimaryId + ); + + // Try to use an entry from the current mod, falling back to the current collection, and finally an unmodified value. + var targetId = modEst?.Entry + ?? collections.Current.MetaCache?.GetEstEntry(EstManipulation.EstType.Hair, info.GenderRace, info.PrimaryId) + ?? info.PrimaryId; + + // TODO: i'm not conviced ToSuffix is correct - check! + return GamePaths.Skeleton.Sklb.Path(info.GenderRace, info.BodySlot.ToSuffix(), targetId); + } + private Task Enqueue(IAction action) { if (_disposed) @@ -75,16 +104,16 @@ public sealed class ModelManager(IFramework framework, GamePathParser _parser) : return task; } - private class ExportToGltfAction(ModelManager manager, MdlFile mdl, SklbFile? sklb, string outputPath) + private class ExportToGltfAction(ModelManager manager, MdlFile mdl, IEnumerable? sklbs, string outputPath) : IAction { public void Execute(CancellationToken cancel) { - Penumbra.Log.Debug("Reading skeleton."); - var xivSkeleton = BuildSkeleton(cancel); + Penumbra.Log.Debug("Reading skeletons."); + var xivSkeletons = BuildSkeletons(cancel); Penumbra.Log.Debug("Converting model."); - var model = ModelExporter.Export(mdl, xivSkeleton); + var model = ModelExporter.Export(mdl, xivSkeletons); Penumbra.Log.Debug("Building scene."); var scene = new SceneBuilder(); @@ -96,16 +125,28 @@ public sealed class ModelManager(IFramework framework, GamePathParser _parser) : } /// Attempt to read out the pertinent information from a .sklb. - private XivSkeleton? BuildSkeleton(CancellationToken cancel) + private IEnumerable? BuildSkeletons(CancellationToken cancel) { - if (sklb == null) + if (sklbs == null) return null; - var xmlTask = manager._framework.RunOnFrameworkThread(() => HavokConverter.HkxToXml(sklb.Skeleton)); - xmlTask.Wait(cancel); - var xml = xmlTask.Result; + // The havok methods we're relying on for this conversion are a bit + // finicky at the best of times, and can outright cause a CTD if they + // get upset. Running each conversion on its own tick seems to make + // this consistently non-crashy across my testing. + Task CreateHavokTask((SklbFile Sklb, int Index) pair) => + manager._framework.RunOnTick( + () => HavokConverter.HkxToXml(pair.Sklb.Skeleton), + delayTicks: pair.Index + ); - return SkeletonConverter.FromXml(xml); + var havokTasks = sklbs + .WithIndex() + .Select(CreateHavokTask) + .ToArray(); + Task.WaitAll(havokTasks, cancel); + + return havokTasks.Select(task => SkeletonConverter.FromXml(task.Result)); } public bool Equals(IAction? other) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index b8573780..d4e75487 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,7 +1,7 @@ using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; -using Penumbra.Mods; +using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -21,15 +21,14 @@ public partial class ModEditWindow public bool PendingIo { get; private set; } public string? IoException { get; private set; } - public MdlTab(ModEditWindow edit, byte[] bytes, string path, IMod? mod) + public MdlTab(ModEditWindow edit, byte[] bytes, string path) { _edit = edit; Mdl = new MdlFile(bytes); _attributes = CreateAttributes(Mdl); - if (mod != null) - FindGamePaths(path, mod); + FindGamePaths(path); } /// @@ -42,9 +41,13 @@ public partial class ModEditWindow /// Find the list of game paths that may correspond to this model. /// Resolved path to a .mdl. - /// Mod within which the .mdl is resolved. - private void FindGamePaths(string path, IMod mod) + private void FindGamePaths(string path) { + // If there's no current mod (somehow), there's nothing to resolve the model within. + var mod = _edit._editor.Mod; + if (mod == null) + return; + if (!Path.IsPathRooted(path) && Utf8GamePath.FromString(path, out var p)) { GamePaths = [p]; @@ -71,15 +74,34 @@ public partial class ModEditWindow }); } + private EstManipulation[] GetCurrentEstManipulations() + { + var mod = _edit._editor.Mod; + var option = _edit._editor.Option; + if (mod == null || option == null) + return []; + + // Filter then prepend the current option to ensure it's chosen first. + return mod.AllSubMods + .Where(subMod => subMod != option) + .Prepend(option) + .SelectMany(subMod => subMod.Manipulations) + .Where(manipulation => manipulation.ManipulationType == MetaManipulation.Type.Est) + .Select(manipulation => manipulation.Est) + .ToArray(); + } + /// Export model to an interchange format. /// Disk path to save the resulting file to. public void Export(string outputPath, Utf8GamePath mdlPath) { - SklbFile? sklb = null; + IEnumerable? sklbs = null; try { - var sklbPath = _edit._models.ResolveSklbForMdl(mdlPath.ToString()); - sklb = sklbPath != null ? ReadSklb(sklbPath) : null; + var sklbPaths = _edit._models.ResolveSklbsForMdl(mdlPath.ToString(), GetCurrentEstManipulations()); + sklbs = sklbPaths != null + ? sklbPaths.Select(ReadSklb).ToArray() + : null; } catch (Exception exception) { @@ -88,7 +110,7 @@ public partial class ModEditWindow } PendingIo = true; - _edit._models.ExportToGltf(Mdl, sklb, outputPath) + _edit._models.ExportToGltf(Mdl, sklbs, outputPath) .ContinueWith(task => { IoException = task.Exception?.ToString(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 167adafe..8d3e32f9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -600,7 +600,7 @@ public partial class ModEditWindow : Window, IDisposable (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, - (bytes, path, _) => new MdlTab(this, bytes, path, _mod)); + (bytes, path, _) => new MdlTab(this, bytes, path)); _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => _mod?.ModPath.FullName ?? string.Empty, From 0440324432dd00e0c14d55f16aa65336736e95d6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 7 Jan 2024 20:16:15 +1100 Subject: [PATCH 0337/1381] Genericise est logic to handle face --- Penumbra/Import/Models/ModelManager.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index a9e1b32d..4564968d 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -48,7 +48,9 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ObjectType.Accessory => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Hair - => [baseSkeleton, ResolveHairSkeleton(info, estManipulations)], + => [baseSkeleton, ResolveEstSkeleton(EstManipulation.EstType.Hair, info, estManipulations)], + ObjectType.Character when info.BodySlot is BodySlot.Face + => [baseSkeleton, ResolveEstSkeleton(EstManipulation.EstType.Face, info, estManipulations)], ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], ObjectType.Monster => [GamePaths.Monster.Sklb.Path(info.PrimaryId)], @@ -57,24 +59,22 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect }; } - private string ResolveHairSkeleton(GameObjectInfo info, EstManipulation[] estManipulations) + private string ResolveEstSkeleton(EstManipulation.EstType type, GameObjectInfo info, EstManipulation[] estManipulations) { - // TODO: might be able to genericse this over esttype based on incoming info var (gender, race) = info.GenderRace.Split(); var modEst = estManipulations .FirstOrNull(est => est.Gender == gender && est.Race == race - && est.Slot == EstManipulation.EstType.Hair + && est.Slot == type && est.SetId == info.PrimaryId ); // Try to use an entry from the current mod, falling back to the current collection, and finally an unmodified value. var targetId = modEst?.Entry - ?? collections.Current.MetaCache?.GetEstEntry(EstManipulation.EstType.Hair, info.GenderRace, info.PrimaryId) + ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) ?? info.PrimaryId; - // TODO: i'm not conviced ToSuffix is correct - check! return GamePaths.Skeleton.Sklb.Path(info.GenderRace, info.BodySlot.ToSuffix(), targetId); } From 8bc71fb1b318b6589dc3a564f5698ccd80ccdf2e Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 7 Jan 2024 20:47:44 +1100 Subject: [PATCH 0338/1381] Fix viera ears --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 83c01275..e4ab3e91 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 83c012752cd9d13d39248eda85ab18cc59070a76 +Subproject commit e4ab3e914ab8b5651cea313af367e811a253d174 diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 4564968d..7ea19aab 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -49,7 +49,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Hair => [baseSkeleton, ResolveEstSkeleton(EstManipulation.EstType.Hair, info, estManipulations)], - ObjectType.Character when info.BodySlot is BodySlot.Face + ObjectType.Character when info.BodySlot is BodySlot.Face or BodySlot.Ear => [baseSkeleton, ResolveEstSkeleton(EstManipulation.EstType.Face, info, estManipulations)], ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], @@ -75,7 +75,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) ?? info.PrimaryId; - return GamePaths.Skeleton.Sklb.Path(info.GenderRace, info.BodySlot.ToSuffix(), targetId); + return GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId); } private Task Enqueue(IAction action) From 3f8ac1e8d04f95ad85576212d25c1cc3f493b4f0 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 7 Jan 2024 21:56:21 +1100 Subject: [PATCH 0339/1381] Add support for body and head slot EST --- Penumbra/Import/Models/ModelManager.cs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 7ea19aab..692a214f 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -44,13 +44,17 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return info.ObjectType switch { + ObjectType.Equipment when info.EquipSlot.ToSlot() is EquipSlot.Body + => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Body, info, estManipulations)], + ObjectType.Equipment when info.EquipSlot.ToSlot() is EquipSlot.Head + => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Head, info, estManipulations)], ObjectType.Equipment => [baseSkeleton], ObjectType.Accessory => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Hair - => [baseSkeleton, ResolveEstSkeleton(EstManipulation.EstType.Hair, info, estManipulations)], + => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Hair, info, estManipulations)], ObjectType.Character when info.BodySlot is BodySlot.Face or BodySlot.Ear - => [baseSkeleton, ResolveEstSkeleton(EstManipulation.EstType.Face, info, estManipulations)], + => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Face, info, estManipulations)], ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], ObjectType.Monster => [GamePaths.Monster.Sklb.Path(info.PrimaryId)], @@ -59,8 +63,9 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect }; } - private string ResolveEstSkeleton(EstManipulation.EstType type, GameObjectInfo info, EstManipulation[] estManipulations) + private string[] ResolveEstSkeleton(EstManipulation.EstType type, GameObjectInfo info, EstManipulation[] estManipulations) { + // Try to find an EST entry from the manipulations provided. var (gender, race) = info.GenderRace.Split(); var modEst = estManipulations .FirstOrNull(est => @@ -70,12 +75,16 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect && est.SetId == info.PrimaryId ); - // Try to use an entry from the current mod, falling back to the current collection, and finally an unmodified value. + // Try to use an entry from provided manipulations, falling back to the current collection. var targetId = modEst?.Entry ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) - ?? info.PrimaryId; + ?? 0; - return GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId); + // If there's no entries, we can assume that there's no additional skeleton. + if (targetId == 0) + return []; + + return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId)]; } private Task Enqueue(IAction action) From 2f6905cf357b81aed33e67476575a39809538db5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jan 2024 14:42:16 +0100 Subject: [PATCH 0340/1381] Minimal cleanup. --- Penumbra/Communication/ChangedItemClick.cs | 1 - .../Import/Models/Export/ModelExporter.cs | 5 ++- Penumbra/Import/Models/ModelManager.cs | 43 +++++++++---------- .../ModEditWindow.Models.MdlTab.cs | 13 +++--- 4 files changed, 30 insertions(+), 32 deletions(-) diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index b11f2306..754570e2 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -1,6 +1,5 @@ using OtterGui.Classes; using Penumbra.Api.Enums; -using Penumbra.GameData.Enums; namespace Penumbra.Communication; diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 07b37eeb..8271f266 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -56,11 +56,12 @@ public class ModelExporter var names = new Dictionary(); var joints = new List(); - // Flatten out the bones across all the recieved skeletons, but retain a reference to the parent skeleton for lookups. + // Flatten out the bones across all the received skeletons, but retain a reference to the parent skeleton for lookups. var iterator = skeletons.SelectMany(skeleton => skeleton.Bones.Select(bone => (skeleton, bone))); foreach (var (skeleton, bone) in iterator) { - if (names.ContainsKey(bone.Name)) continue; + if (names.ContainsKey(bone.Name)) + continue; var node = new NodeBuilder(bone.Name); names[bone.Name] = joints.Count; diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 692a214f..f4c17080 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -29,16 +29,17 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(MdlFile mdl, IEnumerable? sklbs, string outputPath) + public Task ExportToGltf(MdlFile mdl, IEnumerable sklbs, string outputPath) => Enqueue(new ExportToGltfAction(this, mdl, sklbs, outputPath)); /// Try to find the .sklb paths for a .mdl file. /// .mdl file to look up the skeletons for. - public string[]? ResolveSklbsForMdl(string mdlPath, EstManipulation[] estManipulations) + /// Modified extra skeleton template parameters. + public string[] ResolveSklbsForMdl(string mdlPath, EstManipulation[] estManipulations) { var info = parser.GetFileInfo(mdlPath); if (info.FileType is not FileType.Model) - return null; + return []; var baseSkeleton = GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1); @@ -59,7 +60,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], ObjectType.Monster => [GamePaths.Monster.Sklb.Path(info.PrimaryId)], ObjectType.Weapon => [GamePaths.Weapon.Sklb.Path(info.PrimaryId)], - _ => null, + _ => [], }; } @@ -113,31 +114,38 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return task; } - private class ExportToGltfAction(ModelManager manager, MdlFile mdl, IEnumerable? sklbs, string outputPath) + private class ExportToGltfAction(ModelManager manager, MdlFile mdl, IEnumerable sklbs, string outputPath) : IAction { public void Execute(CancellationToken cancel) { - Penumbra.Log.Debug("Reading skeletons."); + Penumbra.Log.Debug($"[GLTF Export] Exporting model to {outputPath}..."); + Penumbra.Log.Debug("[GLTF Export] Reading skeletons..."); var xivSkeletons = BuildSkeletons(cancel); - Penumbra.Log.Debug("Converting model."); + Penumbra.Log.Debug("[GLTF Export] Converting model..."); var model = ModelExporter.Export(mdl, xivSkeletons); - Penumbra.Log.Debug("Building scene."); + Penumbra.Log.Debug("[GLTF Export] Building scene..."); var scene = new SceneBuilder(); model.AddToScene(scene); - Penumbra.Log.Debug("Saving."); + Penumbra.Log.Debug("[GLTF Export] Saving..."); var gltfModel = scene.ToGltf2(); gltfModel.SaveGLTF(outputPath); + Penumbra.Log.Debug("[GLTF Export] Done."); } /// Attempt to read out the pertinent information from a .sklb. - private IEnumerable? BuildSkeletons(CancellationToken cancel) + private IEnumerable BuildSkeletons(CancellationToken cancel) { - if (sklbs == null) - return null; + var havokTasks = sklbs + .WithIndex() + .Select(CreateHavokTask) + .ToArray(); + + // Result waits automatically. + return havokTasks.Select(task => SkeletonConverter.FromXml(task.Result)); // The havok methods we're relying on for this conversion are a bit // finicky at the best of times, and can outright cause a CTD if they @@ -146,16 +154,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect Task CreateHavokTask((SklbFile Sklb, int Index) pair) => manager._framework.RunOnTick( () => HavokConverter.HkxToXml(pair.Sklb.Skeleton), - delayTicks: pair.Index - ); - - var havokTasks = sklbs - .WithIndex() - .Select(CreateHavokTask) - .ToArray(); - Task.WaitAll(havokTasks, cancel); - - return havokTasks.Select(task => SkeletonConverter.FromXml(task.Result)); + delayTicks: pair.Index, cancellationToken: cancel); } public bool Equals(IAction? other) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index d4e75487..dbedc164 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -86,31 +86,30 @@ public partial class ModEditWindow .Where(subMod => subMod != option) .Prepend(option) .SelectMany(subMod => subMod.Manipulations) - .Where(manipulation => manipulation.ManipulationType == MetaManipulation.Type.Est) + .Where(manipulation => manipulation.ManipulationType is MetaManipulation.Type.Est) .Select(manipulation => manipulation.Est) .ToArray(); } /// Export model to an interchange format. /// Disk path to save the resulting file to. + /// The game path of the model. public void Export(string outputPath, Utf8GamePath mdlPath) { - IEnumerable? sklbs = null; + IEnumerable skeletons; try { var sklbPaths = _edit._models.ResolveSklbsForMdl(mdlPath.ToString(), GetCurrentEstManipulations()); - sklbs = sklbPaths != null - ? sklbPaths.Select(ReadSklb).ToArray() - : null; + skeletons = sklbPaths.Select(ReadSklb).ToArray(); } catch (Exception exception) { - IoException = exception?.ToString(); + IoException = exception.ToString(); return; } PendingIo = true; - _edit._models.ExportToGltf(Mdl, sklbs, outputPath) + _edit._models.ExportToGltf(Mdl, skeletons, outputPath) .ContinueWith(task => { IoException = task.Exception?.ToString(); From 2e935a637815371cf2e4e65ffa9d200447024567 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jan 2024 15:14:58 +0100 Subject: [PATCH 0341/1381] Update GameData. --- Penumbra.GameData | 2 +- Penumbra/Collections/Manager/CollectionStorage.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index e4ab3e91..1dad8d07 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e4ab3e914ab8b5651cea313af367e811a253d174 +Subproject commit 1dad8d07047be0851f518cdac2b1c8bc76a7be98 diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 7c94d705..c43c3817 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -17,10 +17,10 @@ public class CollectionStorage : IReadOnlyList, IDisposable private readonly ModStorage _modStorage; /// The empty collection is always available at Index 0. - private readonly List _collections = new() - { + private readonly List _collections = + [ ModCollection.Empty, - }; + ]; public readonly ModCollection DefaultNamed; From a2b92f129656a8212312e694cdbbc5e819bc3eb5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jan 2024 23:03:52 +0100 Subject: [PATCH 0342/1381] Some rework, add drag & drop. --- .../ModEditWindow.Models.MdlTab.cs | 5 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 51 ++++++++++++++----- 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index c3fc4963..f9e19599 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -142,13 +142,12 @@ public partial class ModEditWindow .ContinueWith(task => { IoException = task.Exception?.ToString(); - PendingIo = false; - - if (task.IsCompletedSuccessfully && task.Result != null) + if (task is { IsCompletedSuccessfully: true, Result: not null }) { Initialize(task.Result); _dirty = true; } + PendingIo = false; }); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index b3598b9d..41c5591a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -15,7 +15,7 @@ public partial class ModEditWindow private const int MdlMaterialMaximum = 4; private readonly FileEditor _modelTab; - private readonly ModelManager _models; + private readonly ModelManager _models; private string _modelNewMaterial = string.Empty; private readonly List _subMeshAttributeTagWidgets = []; @@ -55,9 +55,7 @@ public partial class ModEditWindow if (!ImGui.CollapsingHeader("Import / Export")) return; - var windowWidth = ImGui.GetWindowContentRegionMax().X - ImGui.GetWindowContentRegionMin().X; - var childWidth = (windowWidth - ImGui.GetStyle().ItemSpacing.X * 3) / 2; - var childSize = new Vector2(childWidth, 0); + var childSize = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); DrawImport(tab, childSize, disabled); ImGui.SameLine(); @@ -67,21 +65,35 @@ public partial class ModEditWindow ImGuiUtil.TextWrapped(tab.IoException); } - private void DrawImport(MdlTab tab, Vector2 size, bool disabled) + private void DrawImport(MdlTab tab, Vector2 size, bool _1) { - using var frame = ImRaii.FramedGroup("Import", size); - - if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", tab.PendingIo)) - { - _fileDialog.OpenFilePicker("Load model from glTF.", "glTF{.gltf,.glb}", (success, paths) => + _dragDropManager.CreateImGuiSource("ModelDragDrop", + m => m.Extensions.Any(e => ValidModelExtensions.Contains(e.ToLowerInvariant())), m => { - if (success && paths.Count > 0) - tab.Import(paths[0]); - }, 1, _mod!.ModPath.FullName, false); + if (!GetFirstModel(m.Files, out var file)) + return false; + + ImGui.TextUnformatted($"Dragging model for editing: {Path.GetFileName(file)}"); + return true; + }); + + using (var frame = ImRaii.FramedGroup("Import", size)) + { + if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", + tab.PendingIo)) + _fileDialog.OpenFilePicker("Load model from glTF.", "glTF{.gltf,.glb}", (success, paths) => + { + if (success && paths.Count > 0) + tab.Import(paths[0]); + }, 1, _mod!.ModPath.FullName, false); + ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); } + + if (_dragDropManager.CreateImGuiTarget("ModelDragDrop", out var files, out _) && GetFirstModel(files, out var file)) + tab.Import(file); } - private void DrawExport(MdlTab tab, Vector2 size, bool disabled) + private void DrawExport(MdlTab tab, Vector2 size, bool _) { using var frame = ImRaii.FramedGroup("Export", size); @@ -431,4 +443,15 @@ public partial class ModEditWindow return false; } + + private static bool GetFirstModel(IEnumerable files, [NotNullWhen(true)] out string? file) + { + file = files.FirstOrDefault(f => ValidModelExtensions.Contains(Path.GetExtension(f).ToLowerInvariant())); + return file != null; + } + + private static readonly string[] ValidModelExtensions = + [ + ".gltf", + ]; } From b0f61e6929dddd0d184da55d10d363fd23af46e7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jan 2024 23:22:48 +0100 Subject: [PATCH 0343/1381] Auto formatting, some cleanup, some initialization changes. --- Penumbra/Import/Models/Import/MeshImporter.cs | 122 +++++++-------- .../Import/Models/Import/ModelImporter.cs | 140 ++++++++---------- .../Import/Models/Import/SubMeshImporter.cs | 63 ++++---- .../Import/Models/Import/VertexAttribute.cs | 119 ++++++++------- Penumbra/UI/ModsTab/MultiModPanel.cs | 2 +- 5 files changed, 213 insertions(+), 233 deletions(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index e67b7c4e..95eede2b 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -3,17 +3,17 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; -public class MeshImporter +public class MeshImporter(IEnumerable nodes) { public struct Mesh { - public MdlStructs.MeshStruct MeshStruct; + public MdlStructs.MeshStruct MeshStruct; public List SubMeshStructs; public MdlStructs.VertexDeclarationStruct VertexDeclaration; - public IEnumerable VertexBuffer; + public IEnumerable VertexBuffer; - public List Indicies; + public List Indices; public List? Bones; @@ -22,8 +22,8 @@ public class MeshImporter public struct MeshShapeKey { - public string Name; - public MdlStructs.ShapeMeshStruct ShapeMesh; + public string Name; + public MdlStructs.ShapeMeshStruct ShapeMesh; public List ShapeValues; } @@ -33,79 +33,60 @@ public class MeshImporter return importer.Create(); } - private IEnumerable _nodes; + private readonly List _subMeshes = []; - private List _subMeshes = new(); + private MdlStructs.VertexDeclarationStruct? _vertexDeclaration; + private byte[]? _strides; + private ushort _vertexCount; + private readonly List[] _streams = [[], [], []]; - private MdlStructs.VertexDeclarationStruct? _vertexDeclaration; - private byte[]? _strides; - private ushort _vertexCount = 0; - private List[] _streams; - - private List _indices = new(); + private readonly List _indices = []; private List? _bones; - private readonly Dictionary> _shapeValues = new(); - - private MeshImporter(IEnumerable nodes) - { - _nodes = nodes; - - // All meshes may use up to 3 byte streams. - _streams = new List[3]; - for (var streamIndex = 0; streamIndex < 3; streamIndex++) - _streams[streamIndex] = new List(); - } + private readonly Dictionary> _shapeValues = []; private Mesh Create() { - foreach (var node in _nodes) + foreach (var node in nodes) BuildSubMeshForNode(node); ArgumentNullException.ThrowIfNull(_strides); ArgumentNullException.ThrowIfNull(_vertexDeclaration); - return new Mesh() + return new Mesh { - MeshStruct = new MdlStructs.MeshStruct() + MeshStruct = new MdlStructs.MeshStruct { VertexBufferOffset = [0, (uint)_streams[0].Count, (uint)(_streams[0].Count + _streams[1].Count)], VertexBufferStride = _strides, - VertexCount = _vertexCount, + VertexCount = _vertexCount, VertexStreamCount = (byte)_vertexDeclaration.Value.VertexElements .Select(element => element.Stream + 1) .Max(), - StartIndex = 0, IndexCount = (uint)_indices.Count, // TODO: import material names - MaterialIndex = 0, - - SubMeshIndex = 0, - SubMeshCount = (ushort)_subMeshes.Count, - + MaterialIndex = 0, + SubMeshIndex = 0, + SubMeshCount = (ushort)_subMeshes.Count, BoneTableIndex = 0, }, - SubMeshStructs = _subMeshes, - + SubMeshStructs = _subMeshes, VertexDeclaration = _vertexDeclaration.Value, - VertexBuffer = _streams[0].Concat(_streams[1]).Concat(_streams[2]), - - Indicies = _indices, - - Bones = _bones, - + VertexBuffer = _streams[0].Concat(_streams[1]).Concat(_streams[2]), + Indices = _indices, + Bones = _bones, ShapeKeys = _shapeValues .Select(pair => new MeshShapeKey() { Name = pair.Key, ShapeMesh = new MdlStructs.ShapeMeshStruct() { - MeshIndexOffset = 0, + MeshIndexOffset = 0, ShapeValueOffset = 0, - ShapeValueCount = (uint)pair.Value.Count, + ShapeValueCount = (uint)pair.Value.Count, }, ShapeValues = pair.Value, }) @@ -117,10 +98,10 @@ public class MeshImporter { // Record some offsets we'll be using later, before they get mutated with sub-mesh values. var vertexOffset = _vertexCount; - var indexOffset = _indices.Count; + var indexOffset = _indices.Count; var nodeBoneMap = CreateNodeBoneMap(node); - var subMesh = SubMeshImporter.Import(node, nodeBoneMap); + var subMesh = SubMeshImporter.Import(node, nodeBoneMap); var subMeshName = node.Name ?? node.Mesh.Name; @@ -128,18 +109,18 @@ public class MeshImporter if (_vertexDeclaration == null) _vertexDeclaration = subMesh.VertexDeclaration; else if (VertexDeclarationMismatch(subMesh.VertexDeclaration, _vertexDeclaration.Value)) - throw new Exception($"Sub-mesh \"{subMeshName}\" vertex declaration mismatch. All sub-meshes of a mesh must have equivalent vertex declarations."); + throw new Exception( + $"Sub-mesh \"{subMeshName}\" vertex declaration mismatch. All sub-meshes of a mesh must have equivalent vertex declarations."); // Given that strides are derived from declarations, a lack of mismatch in declarations means the strides are fine. - // TODO: I mean, given that strides are derivable, might be worth dropping strides from the submesh return structure and computing when needed. - if (_strides == null) - _strides = subMesh.Strides; + // TODO: I mean, given that strides are derivable, might be worth dropping strides from the sub mesh return structure and computing when needed. + _strides ??= subMesh.Strides; // Merge the sub-mesh streams into the main mesh stream bodies. _vertexCount += subMesh.VertexCount; - for (var streamIndex = 0; streamIndex < 3; streamIndex++) - _streams[streamIndex].AddRange(subMesh.Streams[streamIndex]); + foreach (var (stream, subStream) in _streams.Zip(subMesh.Streams)) + stream.AddRange(subStream); // As we're appending vertex data to the buffers, we need to update indices to point into that later block. _indices.AddRange(subMesh.Indices.Select(index => (ushort)(index + vertexOffset))); @@ -149,7 +130,7 @@ public class MeshImporter { if (!_shapeValues.TryGetValue(name, out var meshShapeValues)) { - meshShapeValues = new(); + meshShapeValues = []; _shapeValues.Add(name, meshShapeValues); } @@ -167,19 +148,20 @@ public class MeshImporter }); } - private bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) + private static bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) { var elA = a.VertexElements; var elB = b.VertexElements; - if (elA.Length != elB.Length) return true; + if (elA.Length != elB.Length) + return true; // NOTE: This assumes that elements will always be in the same order. Under the current implementation, that's guaranteed. return elA.Zip(elB).Any(pair => pair.First.Usage != pair.Second.Usage - || pair.First.Type != pair.Second.Type - || pair.First.Offset != pair.Second.Offset - || pair.First.Stream != pair.Second.Stream + || pair.First.Type != pair.Second.Type + || pair.First.Offset != pair.Second.Offset + || pair.First.Stream != pair.Second.Stream ); } @@ -195,31 +177,30 @@ public class MeshImporter .Select(index => node.Skin.GetJoint(index).Joint.Name ?? "unnamed_joint") .ToArray(); - // TODO: This is duplicated with the submesh importer - would be good to avoid (not that it's a huge issue). - var mesh = node.Mesh; - var meshName = node.Name ?? mesh.Name ?? "(no name)"; + // TODO: This is duplicated with the sub mesh importer - would be good to avoid (not that it's a huge issue). + var mesh = node.Mesh; + var meshName = node.Name ?? mesh.Name ?? "(no name)"; var primitiveCount = mesh.Primitives.Count; if (primitiveCount != 1) - { throw new Exception($"Mesh \"{meshName}\" has {primitiveCount} primitives, expected 1."); - } + var primitive = mesh.Primitives[0]; // Per glTF specification, an asset with a skin MUST contain skinning attributes on its mesh. - var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0"); - if (jointsAccessor == null) - throw new Exception($"Skinned mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); + var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0") + ?? throw new Exception($"Skinned mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); // Build a set of joints that are referenced by this mesh. // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. var usedJoints = new HashSet(); foreach (var joints in jointsAccessor.AsVector4Array()) + { for (var index = 0; index < 4; index++) usedJoints.Add((ushort)joints[index]); - + } + // Only initialise the bones list if we're actually going to put something in it. - if (_bones == null) - _bones = new(); + _bones ??= []; // Build a dictionary of node-specific joint indices mesh-wide bone indices. var nodeBoneMap = new Dictionary(); @@ -232,6 +213,7 @@ public class MeshImporter boneIndex = _bones.Count; _bones.Add(jointName); } + nodeBoneMap.Add(usedJoint, (ushort)boneIndex); } diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index f53d2b64..abe87934 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -4,7 +4,7 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; -public partial class ModelImporter +public partial class ModelImporter(ModelRoot _model) { public static MdlFile Import(ModelRoot model) { @@ -13,29 +13,22 @@ public partial class ModelImporter } // NOTE: This is intended to match TexTool's grouping regex, ".*[_ ^]([0-9]+)[\\.\\-]?([0-9]+)?$" - [GeneratedRegex(@"[_ ^](?'Mesh'[0-9]+)[.-]?(?'SubMesh'[0-9]+)?$", RegexOptions.Compiled)] + [GeneratedRegex(@"[_ ^](?'Mesh'[0-9]+)[.-]?(?'SubMesh'[0-9]+)?$", RegexOptions.Compiled | RegexOptions.NonBacktracking | RegexOptions.ExplicitCapture)] private static partial Regex MeshNameGroupingRegex(); - private readonly ModelRoot _model; + private readonly List _meshes = []; + private readonly List _subMeshes = []; - private List _meshes = new(); - private List _subMeshes = new(); + private readonly List _vertexDeclarations = []; + private readonly List _vertexBuffer = []; - private List _vertexDeclarations = new(); - private List _vertexBuffer = new(); + private readonly List _indices = []; - private List _indices = new(); + private readonly List _bones = []; + private readonly List _boneTables = []; - private List _bones = new(); - private List _boneTables = new(); - - private Dictionary> _shapeMeshes = new(); - private List _shapeValues = new(); - - private ModelImporter(ModelRoot model) - { - _model = model; - } + private readonly Dictionary> _shapeMeshes = []; + private readonly List _shapeValues = []; private MdlFile Create() { @@ -43,8 +36,8 @@ public partial class ModelImporter foreach (var subMeshNodes in GroupedMeshNodes()) BuildMeshForGroup(subMeshNodes); - // Now that all of the meshes have been built, we can build some of the model-wide metadata. - var shapes = new List(); + // Now that all the meshes have been built, we can build some of the model-wide metadata. + var shapes = new List(); var shapeMeshes = new List(); foreach (var (keyName, keyMeshes) in _shapeMeshes) { @@ -53,75 +46,64 @@ public partial class ModelImporter ShapeName = keyName, // NOTE: these values are per-LoD. ShapeMeshStartIndex = [(ushort)shapeMeshes.Count, 0, 0], - ShapeMeshCount = [(ushort)keyMeshes.Count, 0, 0], + ShapeMeshCount = [(ushort)keyMeshes.Count, 0, 0], }); shapeMeshes.AddRange(keyMeshes); } var indexBuffer = _indices.SelectMany(BitConverter.GetBytes).ToArray(); - var emptyBoundingBox = new MdlStructs.BoundingBoxStruct() - { - Min = [0, 0, 0, 0], - Max = [0, 0, 0, 0], - }; - // And finally, the MdlFile itself. - return new MdlFile() + return new MdlFile { - VertexOffset = [0, 0, 0], - VertexBufferSize = [(uint)_vertexBuffer.Count, 0, 0], - IndexOffset = [(uint)_vertexBuffer.Count, 0, 0], - IndexBufferSize = [(uint)indexBuffer.Length, 0, 0], - - VertexDeclarations = _vertexDeclarations.ToArray(), - Meshes = _meshes.ToArray(), - SubMeshes = _subMeshes.ToArray(), - - BoneTables = _boneTables.ToArray(), - Bones = _bones.ToArray(), + VertexOffset = [0, 0, 0], + VertexBufferSize = [(uint)_vertexBuffer.Count, 0, 0], + IndexOffset = [(uint)_vertexBuffer.Count, 0, 0], + IndexBufferSize = [(uint)indexBuffer.Length, 0, 0], + VertexDeclarations = [.. _vertexDeclarations], + Meshes = [.. _meshes], + SubMeshes = [.. _subMeshes], + BoneTables = [.. _boneTables], + Bones = [.. _bones], // TODO: Game doesn't seem to rely on this, but would be good to populate. SubMeshBoneMap = [], - - Shapes = shapes.ToArray(), - ShapeMeshes = shapeMeshes.ToArray(), - ShapeValues = _shapeValues.ToArray(), - - LodCount = 1, - - Lods = [new MdlStructs.LodStruct() - { - MeshIndex = 0, - MeshCount = (ushort)_meshes.Count, - - ModelLodRange = 0, - TextureLodRange = 0, - - VertexDataOffset = 0, - VertexBufferSize = (uint)_vertexBuffer.Count, - IndexDataOffset = (uint)_vertexBuffer.Count, - IndexBufferSize = (uint)indexBuffer.Length, - }], + Shapes = [.. shapes], + ShapeMeshes = [.. shapeMeshes], + ShapeValues = [.. _shapeValues], + LodCount = 1, + Lods = + [ + new MdlStructs.LodStruct + { + MeshIndex = 0, + MeshCount = (ushort)_meshes.Count, + ModelLodRange = 0, + TextureLodRange = 0, + VertexDataOffset = 0, + VertexBufferSize = (uint)_vertexBuffer.Count, + IndexDataOffset = (uint)_vertexBuffer.Count, + IndexBufferSize = (uint)indexBuffer.Length, + }, + ], // TODO: Would be good to populate from gltf material names. Materials = ["/NO_MATERIAL"], // TODO: Would be good to calculate all of this up the tree. - Radius = 1, - BoundingBoxes = emptyBoundingBox, - BoneBoundingBoxes = Enumerable.Repeat(emptyBoundingBox, _bones.Count).ToArray(), - - RemainingData = [.._vertexBuffer, ..indexBuffer], + Radius = 1, + BoundingBoxes = MdlFile.EmptyBoundingBox, + BoneBoundingBoxes = Enumerable.Repeat(MdlFile.EmptyBoundingBox, _bones.Count).ToArray(), + RemainingData = [.._vertexBuffer, ..indexBuffer], }; } /// Returns an iterator over sorted, grouped mesh nodes. - private IEnumerable> GroupedMeshNodes() => - _model.LogicalNodes + private IEnumerable> GroupedMeshNodes() + => _model.LogicalNodes .Where(node => node.Mesh != null) - .Select(node => + .Select(node => { - var name = node.Name ?? node.Mesh.Name ?? "NOMATCH"; + var name = node.Name ?? node.Mesh.Name ?? "NOMATCH"; var match = MeshNameGroupingRegex().Match(name); return (node, match); }) @@ -140,12 +122,12 @@ public partial class ModelImporter private void BuildMeshForGroup(IEnumerable subMeshNodes) { // Record some offsets we'll be using later, before they get mutated with mesh values. - var subMeshOffset = _subMeshes.Count; - var vertexOffset = _vertexBuffer.Count; - var indexOffset = _indices.Count; + var subMeshOffset = _subMeshes.Count; + var vertexOffset = _vertexBuffer.Count; + var indexOffset = _indices.Count; var shapeValueOffset = _shapeValues.Count; - var mesh = MeshImporter.Import(subMeshNodes); + var mesh = MeshImporter.Import(subMeshNodes); var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); // If no bone table is used for a mesh, the index is set to 255. @@ -163,22 +145,21 @@ public partial class ModelImporter .ToArray(), }); - foreach (var subMesh in mesh.SubMeshStructs) - _subMeshes.Add(subMesh with - { - IndexOffset = (uint)(subMesh.IndexOffset + indexOffset), - }); + _subMeshes.AddRange(mesh.SubMeshStructs.Select(m => m with + { + IndexOffset = (uint)(m.IndexOffset + indexOffset), + })); _vertexDeclarations.Add(mesh.VertexDeclaration); _vertexBuffer.AddRange(mesh.VertexBuffer); - _indices.AddRange(mesh.Indicies); + _indices.AddRange(mesh.Indices); foreach (var meshShapeKey in mesh.ShapeKeys) { if (!_shapeMeshes.TryGetValue(meshShapeKey.Name, out var shapeMeshes)) { - shapeMeshes = new(); + shapeMeshes = []; _shapeMeshes.Add(meshShapeKey.Name, shapeMeshes); } @@ -203,6 +184,7 @@ public partial class ModelImporter boneIndex = _bones.Count; _bones.Add(boneName); } + boneIndices.Add((ushort)boneIndex); } diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 1d604105..5dec4384 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -12,8 +12,8 @@ public class SubMeshImporter public MdlStructs.VertexDeclarationStruct VertexDeclaration; - public ushort VertexCount; - public byte[] Strides; + public ushort VertexCount; + public byte[] Strides; public List[] Streams; public ushort[] Indices; @@ -27,19 +27,19 @@ public class SubMeshImporter return importer.Create(); } - private readonly MeshPrimitive _primitive; + private readonly MeshPrimitive _primitive; private readonly IDictionary? _nodeBoneMap; private List? _attributes; - private ushort _vertexCount = 0; - private byte[] _strides = [0, 0, 0]; + private ushort _vertexCount; + private byte[] _strides = [0, 0, 0]; private readonly List[] _streams; private ushort[]? _indices; - private readonly List? _morphNames; - private Dictionary>? _shapeValues; + private readonly List? _morphNames; + private Dictionary>? _shapeValues; private SubMeshImporter(Node node, IDictionary? nodeBoneMap) { @@ -52,7 +52,7 @@ public class SubMeshImporter throw new Exception($"Mesh \"{name}\" has {primitiveCount} primitives, expected 1."); } - _primitive = mesh.Primitives[0]; + _primitive = mesh.Primitives[0]; _nodeBoneMap = nodeBoneMap; try @@ -67,7 +67,7 @@ public class SubMeshImporter // All meshes may use up to 3 byte streams. _streams = new List[3]; for (var streamIndex = 0; streamIndex < 3; streamIndex++) - _streams[streamIndex] = new List(); + _streams[streamIndex] = []; } private SubMesh Create() @@ -85,26 +85,22 @@ public class SubMeshImporter { SubMeshStruct = new MdlStructs.SubmeshStruct() { - IndexOffset = 0, - IndexCount = (uint)_indices.Length, + IndexOffset = 0, + IndexCount = (uint)_indices.Length, AttributeIndexMask = 0, // TODO: Flesh these out. Game doesn't seem to rely on them existing, though. BoneStartIndex = 0, - BoneCount = 0, + BoneCount = 0, }, - VertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = _attributes.Select(attribute => attribute.Element).ToArray(), }, - VertexCount = _vertexCount, - Strides = _strides, - Streams = _streams, - - Indices = _indices, - + Strides = _strides, + Streams = _streams, + Indices = _indices, ShapeValues = _shapeValues, }; } @@ -119,11 +115,12 @@ public class SubMeshImporter var accessors = _primitive.VertexAccessors; var morphAccessors = Enumerable.Range(0, _primitive.MorphTargetsCount) - .Select(index => _primitive.GetMorphTargetAccessors(index)); + .Select(index => _primitive.GetMorphTargetAccessors(index)).ToList(); // Try to build all the attributes the mesh might use. // The order here is chosen to match a typical model's element order. - var rawAttributes = new[] { + var rawAttributes = new[] + { VertexAttribute.Position(accessors, morphAccessors), VertexAttribute.BlendWeight(accessors), VertexAttribute.BlendIndex(accessors, _nodeBoneMap), @@ -134,10 +131,17 @@ public class SubMeshImporter }; var attributes = new List(); - var offsets = new byte[] { 0, 0, 0 }; + var offsets = new byte[] + { + 0, + 0, + 0, + }; foreach (var attribute in rawAttributes) { - if (attribute == null) continue; + if (attribute == null) + continue; + attributes.Add(attribute.WithOffset(offsets[attribute.Stream])); offsets[attribute.Stream] += attribute.Size; } @@ -177,7 +181,7 @@ public class SubMeshImporter BuildShapeValues(morphModifiedVertices); } - private void BuildShapeValues(List[] morphModifiedVertices) + private void BuildShapeValues(IEnumerable> morphModifiedVertices) { ArgumentNullException.ThrowIfNull(_indices); ArgumentNullException.ThrowIfNull(_attributes); @@ -198,12 +202,11 @@ public class SubMeshImporter // Find any indices that target this vertex index and create a mapping. var targetingIndices = _indices.WithIndex() .SelectWhere(pair => (pair.Value == vertexIndex, pair.Index)); - foreach (var targetingIndex in targetingIndices) - shapeValues.Add(new MdlStructs.ShapeValueStruct() - { - BaseIndicesIndex = (ushort)targetingIndex, - ReplacingVertexIndex = _vertexCount, - }); + shapeValues.AddRange(targetingIndices.Select(targetingIndex => new MdlStructs.ShapeValueStruct + { + BaseIndicesIndex = (ushort)targetingIndex, + ReplacingVertexIndex = _vertexCount, + })); _vertexCount++; } diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 6bb9971c..0b0e90ba 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -13,27 +13,32 @@ public class VertexAttribute { /// XIV vertex element metadata structure. public readonly MdlStructs.VertexElement Element; + /// Build a byte array containing this vertex attribute's data for the specified vertex index. public readonly BuildFn Build; + /// Check if the specified morph target index contains a morph for the specified vertex index. public readonly HasMorphFn HasMorph; + /// Build a byte array containing this vertex attribute's data, as modified by the specified morph target, for the specified vertex index. public readonly BuildMorphFn BuildMorph; - public byte Stream => Element.Stream; + public byte Stream + => Element.Stream; /// Size in bytes of a single vertex's attribute value. - public byte Size => (MdlFile.VertexType)Element.Type switch - { - MdlFile.VertexType.Single3 => 12, - MdlFile.VertexType.Single4 => 16, - MdlFile.VertexType.UInt => 4, - MdlFile.VertexType.ByteFloat4 => 4, - MdlFile.VertexType.Half2 => 4, - MdlFile.VertexType.Half4 => 8, + public byte Size + => (MdlFile.VertexType)Element.Type switch + { + MdlFile.VertexType.Single3 => 12, + MdlFile.VertexType.Single4 => 16, + MdlFile.VertexType.UInt => 4, + MdlFile.VertexType.ByteFloat4 => 4, + MdlFile.VertexType.Half2 => 4, + MdlFile.VertexType.Half4 => 8, - _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), - }; + _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), + }; private VertexAttribute( MdlStructs.VertexElement element, @@ -42,25 +47,30 @@ public class VertexAttribute BuildMorphFn? buildMorph = null ) { - Element = element; - Build = write; - HasMorph = hasMorph ?? DefaultHasMorph; + Element = element; + Build = write; + HasMorph = hasMorph ?? DefaultHasMorph; BuildMorph = buildMorph ?? DefaultBuildMorph; } - public VertexAttribute WithOffset(byte offset) => new VertexAttribute( - Element with { Offset = offset }, - Build, - HasMorph, - BuildMorph - ); + public VertexAttribute WithOffset(byte offset) + => new( + Element with { Offset = offset }, + Build, + HasMorph, + BuildMorph + ); - // We assume that attributes don't have morph data unless explicitly configured. - private static bool DefaultHasMorph(int morphIndex, int vertexIndex) => false; + /// We assume that attributes don't have morph data unless explicitly configured. + private static bool DefaultHasMorph(int morphIndex, int vertexIndex) + => false; - // XIV stores shapes as full vertex replacements, so all attributes need to output something for a morph. - // As a fallback, we're just building the normal vertex data for the index. - private byte[] DefaultBuildMorph(int morphIndex, int vertexIndex) => Build(vertexIndex); + /// + /// XIV stores shapes as full vertex replacements, so all attributes need to output something for a morph. + /// As a fallback, we're just building the normal vertex data for the index. + /// > + private byte[] DefaultBuildMorph(int morphIndex, int vertexIndex) + => Build(vertexIndex); public static VertexAttribute Position(Accessors accessors, IEnumerable morphAccessors) { @@ -70,29 +80,29 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 0, - Type = (byte)MdlFile.VertexType.Single3, - Usage = (byte)MdlFile.VertexUsage.Position, + Type = (byte)MdlFile.VertexType.Single3, + Usage = (byte)MdlFile.VertexUsage.Position, }; var values = accessor.AsVector3Array(); var morphValues = morphAccessors - .Select(accessors => accessors.GetValueOrDefault("POSITION")?.AsVector3Array()) + .Select(a => a.GetValueOrDefault("POSITION")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, index => BuildSingle3(values[index]), - - hasMorph: (morphIndex, vertexIndex) => + (morphIndex, vertexIndex) => { var deltas = morphValues[morphIndex]; - if (deltas == null) return false; + if (deltas == null) + return false; + var delta = deltas[vertexIndex]; return delta != Vector3.Zero; }, - - buildMorph: (morphIndex, vertexIndex) => + (morphIndex, vertexIndex) => { var value = values[vertexIndex]; @@ -116,8 +126,8 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 0, - Type = (byte)MdlFile.VertexType.ByteFloat4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, }; var values = accessor.AsVector4Array(); @@ -142,8 +152,8 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 0, - Type = (byte)MdlFile.VertexType.UInt, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, + Type = (byte)MdlFile.VertexType.UInt, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, }; var values = accessor.AsVector4Array(); @@ -171,20 +181,19 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 1, - Type = (byte)MdlFile.VertexType.Half4, - Usage = (byte)MdlFile.VertexUsage.Normal, + Type = (byte)MdlFile.VertexType.Half4, + Usage = (byte)MdlFile.VertexUsage.Normal, }; var values = accessor.AsVector3Array(); var morphValues = morphAccessors - .Select(accessors => accessors.GetValueOrDefault("NORMAL")?.AsVector3Array()) + .Select(a => a.GetValueOrDefault("NORMAL")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, index => BuildHalf4(new Vector4(values[index], 0)), - buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; @@ -207,7 +216,7 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 1, - Usage = (byte)MdlFile.VertexUsage.UV, + Usage = (byte)MdlFile.VertexUsage.UV, }; var values1 = accessor1.AsVector2Array(); @@ -241,21 +250,20 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 1, - Type = (byte)MdlFile.VertexType.ByteFloat4, - Usage = (byte)MdlFile.VertexUsage.Tangent1, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.Tangent1, }; var values = accessor.AsVector4Array(); // Per glTF specification, TANGENT morph values are stored as vec3, with the W component always considered to be 0. var morphValues = morphAccessors - .Select(accessors => accessors.GetValueOrDefault("TANGENT")?.AsVector3Array()) + .Select(a => a.GetValueOrDefault("TANGENT")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, index => BuildByteFloat4(values[index]), - buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; @@ -277,8 +285,8 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 1, - Type = (byte)MdlFile.VertexType.ByteFloat4, - Usage = (byte)MdlFile.VertexUsage.Color, + Type = (byte)MdlFile.VertexType.ByteFloat4, + Usage = (byte)MdlFile.VertexUsage.Color, }; var values = accessor.AsVector4Array(); @@ -289,14 +297,16 @@ public class VertexAttribute ); } - private static byte[] BuildSingle3(Vector3 input) => + private static byte[] BuildSingle3(Vector3 input) + => [ ..BitConverter.GetBytes(input.X), ..BitConverter.GetBytes(input.Y), ..BitConverter.GetBytes(input.Z), ]; - private static byte[] BuildUInt(Vector4 input) => + private static byte[] BuildUInt(Vector4 input) + => [ (byte)input.X, (byte)input.Y, @@ -304,7 +314,8 @@ public class VertexAttribute (byte)input.W, ]; - private static byte[] BuildByteFloat4(Vector4 input) => + private static byte[] BuildByteFloat4(Vector4 input) + => [ (byte)Math.Round(input.X * 255f), (byte)Math.Round(input.Y * 255f), @@ -312,13 +323,15 @@ public class VertexAttribute (byte)Math.Round(input.W * 255f), ]; - private static byte[] BuildHalf2(Vector2 input) => + private static byte[] BuildHalf2(Vector2 input) + => [ ..BitConverter.GetBytes((Half)input.X), ..BitConverter.GetBytes((Half)input.Y), ]; - private static byte[] BuildHalf4(Vector4 input) => + private static byte[] BuildHalf4(Vector4 input) + => [ ..BitConverter.GetBytes((Half)input.X), ..BitConverter.GetBytes((Half)input.Y), diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs index 1e4117ec..595240f4 100644 --- a/Penumbra/UI/ModsTab/MultiModPanel.cs +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -49,7 +49,7 @@ public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _edito ImGui.TableNextColumn(); var icon = (path is ModFileSystem.Leaf ? FontAwesomeIcon.FileCircleMinus : FontAwesomeIcon.FolderMinus).ToIconString(); if (ImGuiUtil.DrawDisabledButton(icon, new Vector2(sizeType), "Remove from selection.", false, true)) - _selector.RemovePathFromMultiselection(path); + _selector.RemovePathFromMultiSelection(path); ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); From 8c7c7e20a0626ebda47889d661f12019a57acee1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jan 2024 23:23:25 +0100 Subject: [PATCH 0344/1381] Update OtterGui --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 2c603cea..df754445 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 2c603cea9b1d4dd500e30972b64bd2f25012dc4c +Subproject commit df754445aa6f67fbeb84a292fe808ee560bc3cf7 From 025e3798a74290e88452200f6b18538d8330b5c8 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 7 Jan 2024 22:25:53 +0000 Subject: [PATCH 0345/1381] [CI] Updating repo.json for testing_0.8.3.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e27d716a..47e102c9 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.3", + "TestingAssemblyVersion": "0.8.3.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 36cbca4684d38ccdd2be7f743599a809c0b271f4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 8 Jan 2024 13:52:45 +0100 Subject: [PATCH 0346/1381] Add icons to import/export headers. --- OtterGui | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OtterGui b/OtterGui index df754445..4c32d2d4 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit df754445aa6f67fbeb84a292fe808ee560bc3cf7 +Subproject commit 4c32d2d448c4e36ea665276ed755a96fa4907c33 diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 41c5591a..4f9303f8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -77,7 +77,7 @@ public partial class ModEditWindow return true; }); - using (var frame = ImRaii.FramedGroup("Import", size)) + using (var frame = ImRaii.FramedGroup("Import", size, headerPreIcon: FontAwesomeIcon.FileImport)) { if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", tab.PendingIo)) @@ -89,13 +89,13 @@ public partial class ModEditWindow ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); } - if (_dragDropManager.CreateImGuiTarget("ModelDragDrop", out var files, out _) && GetFirstModel(files, out var file)) - tab.Import(file); + if (_dragDropManager.CreateImGuiTarget("ModelDragDrop", out var files, out _) && GetFirstModel(files, out var importFile)) + tab.Import(importFile); } private void DrawExport(MdlTab tab, Vector2 size, bool _) { - using var frame = ImRaii.FramedGroup("Export", size); + using var frame = ImRaii.FramedGroup("Export", size, headerPreIcon: FontAwesomeIcon.FileExport); if (tab.GamePaths == null) { From c3ba8a22313fe3df96d75436c2d1cd86feb1c645 Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 9 Jan 2024 01:15:08 +1100 Subject: [PATCH 0347/1381] Improve error messaging --- Penumbra/Import/Models/ModelManager.cs | 7 +++- .../ModEditWindow.Models.MdlTab.cs | 23 +++++++++---- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 32 ++++++++++++++++--- 3 files changed, 50 insertions(+), 12 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index bae9569f..f099a0e0 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -37,7 +37,12 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect public Task ImportGltf(string inputPath) { var action = new ImportGltfAction(inputPath); - return Enqueue(action).ContinueWith(_ => action.Out); + return Enqueue(action).ContinueWith(task => + { + if (task.IsFaulted && task.Exception != null) + throw task.Exception; + return action.Out; + }); } /// Try to find the .sklb paths for a .mdl file. /// .mdl file to look up the skeletons for. diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index f9e19599..d52bf3f1 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -18,9 +18,9 @@ public partial class ModEditWindow public List? GamePaths { get; private set; } public int GamePathIndex; - private bool _dirty; - public bool PendingIo { get; private set; } - public string? IoException { get; private set; } + private bool _dirty; + public bool PendingIo { get; private set; } + public List IoExceptions { get; private set; } = []; public MdlTab(ModEditWindow edit, byte[] bytes, string path) { @@ -85,7 +85,7 @@ public partial class ModEditWindow task.ContinueWith(t => { - IoException = t.Exception?.ToString(); + RecordIoExceptions(t.Exception); GamePaths = t.Result; PendingIo = false; }); @@ -120,7 +120,7 @@ public partial class ModEditWindow } catch (Exception exception) { - IoException = exception.ToString(); + RecordIoExceptions(exception); return; } @@ -128,7 +128,7 @@ public partial class ModEditWindow _edit._models.ExportToGltf(Mdl, skeletons, outputPath) .ContinueWith(task => { - IoException = task.Exception?.ToString(); + RecordIoExceptions(task.Exception); PendingIo = false; }); } @@ -141,7 +141,7 @@ public partial class ModEditWindow _edit._models.ImportGltf(inputPath) .ContinueWith(task => { - IoException = task.Exception?.ToString(); + RecordIoExceptions(task.Exception); if (task is { IsCompletedSuccessfully: true, Result: not null }) { Initialize(task.Result); @@ -151,6 +151,15 @@ public partial class ModEditWindow }); } + private void RecordIoExceptions(Exception? exception) + { + IoExceptions = exception switch { + null => [], + AggregateException ae => ae.Flatten().InnerExceptions.ToList(), + Exception other => [other], + }; + } + /// Read a .sklb from the active collection or game. /// Game path to the .sklb to load. private SklbFile ReadSklb(string sklbPath) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 4f9303f8..28f41936 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -7,6 +7,7 @@ using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.Import.Models; using Penumbra.String.Classes; +using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -61,8 +62,7 @@ public partial class ModEditWindow ImGui.SameLine(); DrawExport(tab, childSize, disabled); - if (tab.IoException != null) - ImGuiUtil.TextWrapped(tab.IoException); + DrawIoExceptions(tab); } private void DrawImport(MdlTab tab, Vector2 size, bool _1) @@ -99,10 +99,10 @@ public partial class ModEditWindow if (tab.GamePaths == null) { - if (tab.IoException == null) + if (tab.IoExceptions.Count == 0) ImGui.TextUnformatted("Resolving model game paths."); else - ImGuiUtil.TextWrapped(tab.IoException); + ImGui.TextUnformatted("Failed to resolve model game paths."); return; } @@ -126,6 +126,30 @@ public partial class ModEditWindow false ); } + + private void DrawIoExceptions(MdlTab tab) + { + if (tab.IoExceptions.Count == 0) + return; + + var size = new Vector2(ImGui.GetContentRegionAvail().X, 0); + using var frame = ImRaii.FramedGroup("Exceptions", size, headerPreIcon: FontAwesomeIcon.TimesCircle, borderColor: Colors.RegexWarningBorder); + + var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; + foreach (var exception in tab.IoExceptions) + { + var message = $"{exception.GetType().Name}: {exception.Message} {exception.Message}"; + var textSize = ImGui.CalcTextSize(message).X; + if (textSize > spaceAvail) + message = message.Substring(0, (int)Math.Floor(message.Length * (spaceAvail / textSize))) + "..."; + + using (var exceptionNode = ImRaii.TreeNode(message)) + { + if (exceptionNode) + ImGuiUtil.TextWrapped(exception.ToString()); + } + } + } private void DrawGamePathCombo(MdlTab tab) { From ec114b3f6a21321e6570ca1091b72011d711e1d0 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 10 Jan 2024 00:03:32 +1100 Subject: [PATCH 0348/1381] Prevent import of models with too many shape values --- Penumbra/Import/Models/Import/ModelImporter.cs | 12 ++++++++++-- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index abe87934..1c49d4bd 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -4,7 +4,7 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; -public partial class ModelImporter(ModelRoot _model) +public partial class ModelImporter(ModelRoot model) { public static MdlFile Import(ModelRoot model) { @@ -99,7 +99,7 @@ public partial class ModelImporter(ModelRoot _model) /// Returns an iterator over sorted, grouped mesh nodes. private IEnumerable> GroupedMeshNodes() - => _model.LogicalNodes + => model.LogicalNodes .Where(node => node.Mesh != null) .Select(node => { @@ -171,6 +171,14 @@ public partial class ModelImporter(ModelRoot _model) _shapeValues.AddRange(meshShapeKey.ShapeValues); } + + // The number of shape values in a model is bounded by the count + // value, which is stored as a u16. + // While technically there are similar bounds on other shape struct + // arrays, values is practically guaranteed to be the highest of the + // group, so a failure on any of them will be a failure on it. + if (_shapeValues.Count > ushort.MaxValue) + throw new Exception($"Importing this file would require more than the maximum of {ushort.MaxValue} shape values.\nTry removing or applying shape keys that do not need to be changed at runtime in-game."); } private ushort BuildBoneTable(List boneNames) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 28f41936..d8818b21 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -138,7 +138,7 @@ public partial class ModEditWindow var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; foreach (var exception in tab.IoExceptions) { - var message = $"{exception.GetType().Name}: {exception.Message} {exception.Message}"; + var message = $"{exception.GetType().Name}: {exception.Message}"; var textSize = ImGui.CalcTextSize(message).X; if (textSize > spaceAvail) message = message.Substring(0, (int)Math.Floor(message.Length * (spaceAvail / textSize))) + "..."; From 3cd438bb5dc495e257a9f8731293010b8ea58ad6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 10 Jan 2024 01:17:47 +1100 Subject: [PATCH 0349/1381] Export material names --- Penumbra/Import/Models/Export/MeshExporter.cs | 18 +++++++------- .../Import/Models/Export/ModelExporter.cs | 24 +++++++++++++++---- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 84628c2c..6e6169ee 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -27,9 +27,9 @@ public class MeshExporter } } - public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, GltfSkeleton? skeleton) + public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton) { - var self = new MeshExporter(mdl, lod, meshIndex, skeleton?.Names); + var self = new MeshExporter(mdl, lod, meshIndex, materials, skeleton?.Names); return new Mesh(self.BuildMeshes(), skeleton?.Joints); } @@ -42,18 +42,22 @@ public class MeshExporter private MdlStructs.MeshStruct XivMesh => _mdl.Meshes[_meshIndex]; + private readonly MaterialBuilder _material; + private readonly Dictionary? _boneIndexMap; private readonly Type _geometryType; private readonly Type _materialType; private readonly Type _skinningType; - private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, IReadOnlyDictionary? boneNameMap) + private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, IReadOnlyDictionary? boneNameMap) { _mdl = mdl; _lod = lod; _meshIndex = meshIndex; + _material = materials[XivMesh.MaterialIndex]; + if (boneNameMap != null) _boneIndexMap = BuildBoneIndexMap(boneNameMap); @@ -134,13 +138,7 @@ public class MeshExporter ); var meshBuilder = (IMeshBuilder)Activator.CreateInstance(meshBuilderType, name)!; - // TODO: share materials &c - var materialBuilder = new MaterialBuilder() - .WithDoubleSide(true) - .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, new Vector4(1, 1, 1, 1)); - - var primitiveBuilder = meshBuilder.UsePrimitive(materialBuilder); + var primitiveBuilder = meshBuilder.UsePrimitive(_material); // Store a list of the glTF indices. The list index will be equivalent to the xiv (submesh) index. var gltfIndices = new List(); diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 8271f266..6a25af61 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -1,4 +1,5 @@ using Penumbra.GameData.Files; +using SharpGLTF.Materials; using SharpGLTF.Scenes; using SharpGLTF.Transforms; @@ -14,7 +15,7 @@ public class ModelExporter var skeletonRoot = skeleton?.Root; if (skeletonRoot != null) scene.AddNode(skeletonRoot); - + // Add all the meshes to the scene. foreach (var mesh in meshes) mesh.AddToScene(scene); @@ -25,12 +26,13 @@ public class ModelExporter public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton) { var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; - var meshes = ConvertMeshes(mdl, gltfSkeleton); + var materials = ConvertMaterials(mdl); + var meshes = ConvertMeshes(mdl, materials, gltfSkeleton); return new Model(meshes, gltfSkeleton); } /// Convert a .mdl to a mesh (group) per LoD. - private static List ConvertMeshes(MdlFile mdl, GltfSkeleton? skeleton) + private static List ConvertMeshes(MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton) { var meshes = new List(); @@ -41,7 +43,7 @@ public class ModelExporter // TODO: consider other types of mesh? for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) { - var mesh = MeshExporter.Export(mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), skeleton); + var mesh = MeshExporter.Export(mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), materials, skeleton); meshes.Add(mesh); } } @@ -49,6 +51,18 @@ public class ModelExporter return meshes; } + // TODO: Compose textures for use with these materials + /// Build placeholder materials for each of the material slots in the .mdl. + private static MaterialBuilder[] ConvertMaterials(MdlFile mdl) + => mdl.Materials + .Select(name => + new MaterialBuilder(name) + .WithMetallicRoughnessShader() + .WithDoubleSide(true) + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, Vector4.One) + ) + .ToArray(); + /// Convert XIV skeleton data into a glTF-compatible node tree, with mappings. private static GltfSkeleton? ConvertSkeleton(IEnumerable skeletons) { @@ -60,7 +74,7 @@ public class ModelExporter var iterator = skeletons.SelectMany(skeleton => skeleton.Bones.Select(bone => (skeleton, bone))); foreach (var (skeleton, bone) in iterator) { - if (names.ContainsKey(bone.Name)) + if (names.ContainsKey(bone.Name)) continue; var node = new NodeBuilder(bone.Name); From d2f93f85625d789189938ad4b0200b759779e722 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 10 Jan 2024 20:33:24 +1100 Subject: [PATCH 0350/1381] Import material names --- Penumbra/Import/Models/Import/MeshImporter.cs | 8 +++++ .../Import/Models/Import/ModelImporter.cs | 33 ++++++++++++++++--- .../Import/Models/Import/SubMeshImporter.cs | 7 ++++ 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 95eede2b..00663e43 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -10,6 +10,8 @@ public class MeshImporter(IEnumerable nodes) public MdlStructs.MeshStruct MeshStruct; public List SubMeshStructs; + public string? Material; + public MdlStructs.VertexDeclarationStruct VertexDeclaration; public IEnumerable VertexBuffer; @@ -35,6 +37,8 @@ public class MeshImporter(IEnumerable nodes) private readonly List _subMeshes = []; + private string? _material; + private MdlStructs.VertexDeclarationStruct? _vertexDeclaration; private byte[]? _strides; private ushort _vertexCount; @@ -74,6 +78,7 @@ public class MeshImporter(IEnumerable nodes) BoneTableIndex = 0, }, SubMeshStructs = _subMeshes, + Material = _material, VertexDeclaration = _vertexDeclaration.Value, VertexBuffer = _streams[0].Concat(_streams[1]).Concat(_streams[2]), Indices = _indices, @@ -105,6 +110,9 @@ public class MeshImporter(IEnumerable nodes) var subMeshName = node.Name ?? node.Mesh.Name; + // TODO: Record a warning if there's a mismatch between current and incoming, as we can't support multiple materials per mesh. + _material ??= subMesh.Material; + // Check that vertex declarations match - we need to combine the buffers, so a mismatch would take a whole load of resolution. if (_vertexDeclaration == null) _vertexDeclaration = subMesh.VertexDeclaration; diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index abe87934..d5d4bb53 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -19,6 +19,8 @@ public partial class ModelImporter(ModelRoot _model) private readonly List _meshes = []; private readonly List _subMeshes = []; + private readonly List _materials = []; + private readonly List _vertexDeclarations = []; private readonly List _vertexBuffer = []; @@ -37,6 +39,8 @@ public partial class ModelImporter(ModelRoot _model) BuildMeshForGroup(subMeshNodes); // Now that all the meshes have been built, we can build some of the model-wide metadata. + var materials = _materials.Count > 0 ? _materials : ["/NO_MATERIAL"]; + var shapes = new List(); var shapeMeshes = new List(); foreach (var (keyName, keyMeshes) in _shapeMeshes) @@ -86,8 +90,7 @@ public partial class ModelImporter(ModelRoot _model) }, ], - // TODO: Would be good to populate from gltf material names. - Materials = ["/NO_MATERIAL"], + Materials = [.. materials], // TODO: Would be good to calculate all of this up the tree. Radius = 1, @@ -130,15 +133,20 @@ public partial class ModelImporter(ModelRoot _model) var mesh = MeshImporter.Import(subMeshNodes); var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); + ushort materialIndex = 0; + if (mesh.Material != null) + materialIndex = GetMaterialIndex(mesh.Material); + // If no bone table is used for a mesh, the index is set to 255. - var boneTableIndex = 255; + ushort boneTableIndex = 255; if (mesh.Bones != null) boneTableIndex = BuildBoneTable(mesh.Bones); _meshes.Add(mesh.MeshStruct with { + MaterialIndex = materialIndex, SubMeshIndex = (ushort)(mesh.MeshStruct.SubMeshIndex + subMeshOffset), - BoneTableIndex = (ushort)boneTableIndex, + BoneTableIndex = boneTableIndex, StartIndex = meshStartIndex, VertexBufferOffset = mesh.MeshStruct.VertexBufferOffset .Select(offset => (uint)(offset + vertexOffset)) @@ -173,6 +181,23 @@ public partial class ModelImporter(ModelRoot _model) } } + private ushort GetMaterialIndex(string materialName) + { + // If we already have this material, grab the current one + var index = _materials.IndexOf(materialName); + if (index >= 0) + return (ushort)index; + + // If there's already 4 materials, we can't add any more. + // TODO: permit, with a warning to reduce, and validation in MdlTab. + var count = _materials.Count; + if (count >= 4) + return 0; + + _materials.Add(materialName); + return (ushort)count; + } + private ushort BuildBoneTable(List boneNames) { var boneIndices = new List(); diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 5dec4384..0d1dafb3 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -10,6 +10,8 @@ public class SubMeshImporter { public MdlStructs.SubmeshStruct SubMeshStruct; + public string? Material; + public MdlStructs.VertexDeclarationStruct VertexDeclaration; public ushort VertexCount; @@ -81,6 +83,10 @@ public class SubMeshImporter ArgumentNullException.ThrowIfNull(_attributes); ArgumentNullException.ThrowIfNull(_shapeValues); + var material = _primitive.Material.Name; + if (material == "") + material = null; + return new SubMesh() { SubMeshStruct = new MdlStructs.SubmeshStruct() @@ -93,6 +99,7 @@ public class SubMeshImporter BoneStartIndex = 0, BoneCount = 0, }, + Material = material, VertexDeclaration = new MdlStructs.VertexDeclarationStruct() { VertexElements = _attributes.Select(attribute => attribute.Element).ToArray(), From 64aed56f7c2949d9791354299deebd45b8d1cf27 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 10 Jan 2024 22:39:48 +1100 Subject: [PATCH 0351/1381] Allow keeping existing mdl materials --- .../ModEditWindow.Models.MdlTab.cs | 34 ++++++++++++++++--- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 3 +- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index f9e19599..bd599133 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -15,6 +15,8 @@ public partial class ModEditWindow public MdlFile Mdl { get; private set; } private List[] _attributes; + public bool ImportKeepMaterials; + public List? GamePaths { get; private set; } public int GamePathIndex; @@ -110,6 +112,7 @@ public partial class ModEditWindow /// Export model to an interchange format. /// Disk path to save the resulting file to. + /// .mdl game path to resolve satellite files such as skeletons relative to. public void Export(string outputPath, Utf8GamePath mdlPath) { IEnumerable skeletons; @@ -143,14 +146,37 @@ public partial class ModEditWindow { IoException = task.Exception?.ToString(); if (task is { IsCompletedSuccessfully: true, Result: not null }) - { - Initialize(task.Result); - _dirty = true; - } + FinalizeImport(task.Result); PendingIo = false; }); } + /// Finalise the import of a .mdl, applying any post-import transformations and state updates. + /// Model data to finalize. + private void FinalizeImport(MdlFile newMdl) + { + if (ImportKeepMaterials) + MergeMaterials(newMdl, Mdl); + + Initialize(newMdl); + _dirty = true; + } + + /// Merge material configuration from the source onto the target. + /// Model that will be updated. + /// Model to copy material configuration from. + public void MergeMaterials(MdlFile target, MdlFile source) + { + target.Materials = source.Materials; + + for (var meshIndex = 0; meshIndex < target.Meshes.Length; meshIndex++) + { + target.Meshes[meshIndex].MaterialIndex = meshIndex < source.Meshes.Length + ? source.Meshes[meshIndex].MaterialIndex + : (ushort)0; + } + } + /// Read a .sklb from the active collection or game. /// Game path to the .sklb to load. private SklbFile ReadSklb(string sklbPath) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 4f9303f8..9a69a4e8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -79,6 +79,8 @@ public partial class ModEditWindow using (var frame = ImRaii.FramedGroup("Import", size, headerPreIcon: FontAwesomeIcon.FileImport)) { + ImGui.Checkbox("Keep current materials", ref tab.ImportKeepMaterials); + if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", tab.PendingIo)) _fileDialog.OpenFilePicker("Load model from glTF.", "glTF{.gltf,.glb}", (success, paths) => @@ -86,7 +88,6 @@ public partial class ModEditWindow if (success && paths.Count > 0) tab.Import(paths[0]); }, 1, _mod!.ModPath.FullName, false); - ImGui.Dummy(new Vector2(ImGui.GetFrameHeight())); } if (_dragDropManager.CreateImGuiTarget("ModelDragDrop", out var files, out _) && GetFirstModel(files, out var importFile)) From 182550ce1538bead0f263f6b2a0c858629626e06 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 11 Jan 2024 00:34:18 +1100 Subject: [PATCH 0352/1381] Export attributes --- Penumbra/Import/Models/Export/MeshExporter.cs | 48 ++++++++++++++----- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 6e6169ee..8127f348 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -13,20 +13,31 @@ namespace Penumbra.Import.Models.Export; public class MeshExporter { - public class Mesh(IEnumerable> meshes, NodeBuilder[]? joints) + public class Mesh(IEnumerable meshes, NodeBuilder[]? joints) { public void AddToScene(SceneBuilder scene) { - foreach (var mesh in meshes) + foreach (var data in meshes) { - if (joints == null) - scene.AddRigidMesh(mesh, Matrix4x4.Identity); - else - scene.AddSkinnedMesh(mesh, Matrix4x4.Identity, joints); + var instance = joints != null + ? scene.AddSkinnedMesh(data.Mesh, Matrix4x4.Identity, joints) + : scene.AddRigidMesh(data.Mesh, Matrix4x4.Identity); + + var extras = new Dictionary(); + foreach (var attribute in data.Attributes) + extras.Add(attribute, true); + + instance.WithExtras(JsonContent.CreateFrom(extras)); } } } + public struct MeshData + { + public IMeshBuilder Mesh; + public string[] Attributes; + } + public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton) { var self = new MeshExporter(mdl, lod, meshIndex, materials, skeleton?.Names); @@ -103,31 +114,33 @@ public class MeshExporter } /// Build glTF meshes for this XIV mesh. - private IMeshBuilder[] BuildMeshes() + private MeshData[] BuildMeshes() { var indices = BuildIndices(); var vertices = BuildVertices(); // NOTE: Index indices are specified relative to the LOD's 0, but we're reading chunks for each mesh, so we're specifying the index base relative to the mesh's base. if (XivMesh.SubMeshCount == 0) - return [BuildMesh($"mesh {_meshIndex}", indices, vertices, 0, (int)XivMesh.IndexCount)]; + return [BuildMesh($"mesh {_meshIndex}", indices, vertices, 0, (int)XivMesh.IndexCount, 0)]; return _mdl.SubMeshes .Skip(XivMesh.SubMeshIndex) .Take(XivMesh.SubMeshCount) .WithIndex() .Select(subMesh => BuildMesh($"mesh {_meshIndex}.{subMesh.Index}", indices, vertices, - (int)(subMesh.Value.IndexOffset - XivMesh.StartIndex), (int)subMesh.Value.IndexCount)) + (int)(subMesh.Value.IndexOffset - XivMesh.StartIndex), (int)subMesh.Value.IndexCount, + subMesh.Value.AttributeIndexMask)) .ToArray(); } /// Build a mesh from the provided indices and vertices. A subset of the full indices may be built by providing an index base and count. - private IMeshBuilder BuildMesh( + private MeshData BuildMesh( string name, IReadOnlyList indices, IReadOnlyList vertices, int indexBase, - int indexCount + int indexCount, + uint attributeMask ) { var meshBuilderType = typeof(MeshBuilder<,,,>).MakeGenericType( @@ -190,12 +203,23 @@ public class MeshExporter } } + // Named morph targets aren't part of the specification, however `MESH.extras.targetNames` + // is a commonly-accepted means of providing the data. meshBuilder.Extras = JsonContent.CreateFrom(new Dictionary() { { "targetNames", shapeNames }, }); - return meshBuilder; + var attributes = Enumerable.Range(0, 32) + .Where(index => ((attributeMask >> index) & 1) == 1) + .Select(index => _mdl.Attributes[index]) + .ToArray(); + + return new MeshData + { + Mesh = meshBuilder, + Attributes = attributes, + }; } /// Read in the indices for this mesh. From 4b198ef1e474c072013ce6d0202be1235183b2ce Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 10 Jan 2024 16:27:11 +0100 Subject: [PATCH 0353/1381] Misc --- Penumbra/UI/Classes/Colors.cs | 1 - Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 0e3b9377..93d7e091 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -33,7 +33,6 @@ public enum ColorId public static class Colors { // These are written as 0xAABBGGRR. - public const uint PressEnterWarningBg = 0xFF202080; public const uint RegexWarningBorder = 0xFF0000B0; public const uint MetaInfoText = 0xAAFFFFFF; diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index d63e42ef..195c07d6 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -209,7 +209,7 @@ public class ModPanelSettingsTab : ITab { using var id = ImRaii.PushId(groupIdx); var selectedOption = _empty ? (int)group.DefaultSettings : (int)_settings.Settings[groupIdx]; - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var minWidth = Widget.BeginFramedGroup(group.Name, description:group.Description); void DrawOptions() { @@ -288,7 +288,7 @@ public class ModPanelSettingsTab : ITab { using var id = ImRaii.PushId(groupIdx); var flags = _empty ? group.DefaultSettings : _settings.Settings[groupIdx]; - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var minWidth = Widget.BeginFramedGroup(group.Name, description: group.Description); void DrawOptions() { From 7f7b35f3709ee85526379188cae49b779472b69b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 10 Jan 2024 21:20:19 +0100 Subject: [PATCH 0354/1381] Fix issue with RSP values. --- Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs index 81f6d552..2f717491 100644 --- a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Services; +using OtterGui.Services; +using Penumbra.Collections; using Penumbra.GameData; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; @@ -29,6 +30,7 @@ public sealed unsafe class ChangeCustomize : FastHook using var decal2 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, false); var ret = Task.Result.Original.Invoke(human, data, skipEquipment); Penumbra.Log.Excessive($"[Change Customize] Invoked on {(nint)human:X} with {(nint)data:X}, {skipEquipment} -> {ret}."); + _metaState.CustomizeChangeCollection = ResolveData.Invalid; return ret; } } From 0c5d47e3d1889f09fd9de16b5e0de3272f7d4cf8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 10 Jan 2024 22:40:10 +0100 Subject: [PATCH 0355/1381] Make Save-in-Place require modifier. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index e9facdf4..34d0800c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -108,11 +108,14 @@ public partial class ModEditWindow MipMapInput(); var canSaveInPlace = Path.IsPathRooted(_left.Path) && _left.Type is TextureType.Tex or TextureType.Dds or TextureType.Png; + var isActive = _config.DeleteModModifier.IsActive(); + var tt = isActive + ? "This saves the texture in place. This is not revertible." + : $"This saves the texture in place. This is not revertible. Hold {_config.DeleteModModifier} to save."; var buttonSize2 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); if (ImGuiUtil.DrawDisabledButton("Save in place", buttonSize2, - "This saves the texture in place. This is not revertible.", - !canSaveInPlace || _center.IsLeftCopy && _currentSaveAs == (int)CombinedTexture.TextureSaveType.AsIs)) + tt, !isActive || !canSaveInPlace || _center.IsLeftCopy && _currentSaveAs == (int)CombinedTexture.TextureSaveType.AsIs)) { _center.SaveAs(_left.Type, _textures, _left.Path, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); AddReloadTask(_left.Path, false); From dada03905f3191004a4769eb2349bfff4524b497 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 11 Jan 2024 18:54:53 +1100 Subject: [PATCH 0356/1381] Import attributes --- Penumbra/Import/Models/Import/MeshImporter.cs | 7 +++ .../Import/Models/Import/ModelImporter.cs | 5 ++ .../Import/Models/Import/SubMeshImporter.cs | 63 ++++++++++++++----- Penumbra/Import/Models/Import/Utility.cs | 34 ++++++++++ 4 files changed, 95 insertions(+), 14 deletions(-) create mode 100644 Penumbra/Import/Models/Import/Utility.cs diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 00663e43..7da4d1d7 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -19,6 +19,8 @@ public class MeshImporter(IEnumerable nodes) public List? Bones; + public List MetaAttributes; + public List ShapeKeys; } @@ -48,6 +50,8 @@ public class MeshImporter(IEnumerable nodes) private List? _bones; + private readonly List _metaAttributes = []; + private readonly Dictionary> _shapeValues = []; private Mesh Create() @@ -83,6 +87,7 @@ public class MeshImporter(IEnumerable nodes) VertexBuffer = _streams[0].Concat(_streams[1]).Concat(_streams[2]), Indices = _indices, Bones = _bones, + MetaAttributes = _metaAttributes, ShapeKeys = _shapeValues .Select(pair => new MeshShapeKey() { @@ -153,6 +158,8 @@ public class MeshImporter(IEnumerable nodes) _subMeshes.Add(subMesh.SubMeshStruct with { IndexOffset = (ushort)(subMesh.SubMeshStruct.IndexOffset + indexOffset), + AttributeIndexMask = Utility.GetMergedAttributeMask( + subMesh.SubMeshStruct.AttributeIndexMask, subMesh.MetaAttributes, _metaAttributes), }); } diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index d5d4bb53..d02d143c 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -29,6 +29,8 @@ public partial class ModelImporter(ModelRoot _model) private readonly List _bones = []; private readonly List _boneTables = []; + private readonly List _metaAttributes = []; + private readonly Dictionary> _shapeMeshes = []; private readonly List _shapeValues = []; @@ -71,6 +73,7 @@ public partial class ModelImporter(ModelRoot _model) Bones = [.. _bones], // TODO: Game doesn't seem to rely on this, but would be good to populate. SubMeshBoneMap = [], + Attributes = [.. _metaAttributes], Shapes = [.. shapes], ShapeMeshes = [.. shapeMeshes], ShapeValues = [.. _shapeValues], @@ -155,6 +158,8 @@ public partial class ModelImporter(ModelRoot _model) _subMeshes.AddRange(mesh.SubMeshStructs.Select(m => m with { + AttributeIndexMask = Utility.GetMergedAttributeMask( + m.AttributeIndexMask, mesh.MetaAttributes, _metaAttributes), IndexOffset = (uint)(m.IndexOffset + indexOffset), })); diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 0d1dafb3..6b12ee09 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using Lumina.Data.Parsing; using OtterGui; using SharpGLTF.Schema2; @@ -20,6 +21,8 @@ public class SubMeshImporter public ushort[] Indices; + public string[] MetaAttributes; + public Dictionary> ShapeValues; } @@ -29,10 +32,11 @@ public class SubMeshImporter return importer.Create(); } - private readonly MeshPrimitive _primitive; - private readonly IDictionary? _nodeBoneMap; + private readonly MeshPrimitive _primitive; + private readonly IDictionary? _nodeBoneMap; + private readonly IDictionary? _nodeExtras; - private List? _attributes; + private List? _vertexAttributes; private ushort _vertexCount; private byte[] _strides = [0, 0, 0]; @@ -40,6 +44,8 @@ public class SubMeshImporter private ushort[]? _indices; + private string[]? _metaAttributes; + private readonly List? _morphNames; private Dictionary>? _shapeValues; @@ -57,6 +63,15 @@ public class SubMeshImporter _primitive = mesh.Primitives[0]; _nodeBoneMap = nodeBoneMap; + try + { + _nodeExtras = node.Extras.Deserialize>(); + } + catch + { + _nodeExtras = null; + } + try { _morphNames = mesh.Extras.GetNode("targetNames").Deserialize>(); @@ -76,24 +91,34 @@ public class SubMeshImporter { // Build all the data we'll need. BuildIndices(); - BuildAttributes(); + BuildVertexAttributes(); BuildVertices(); + BuildMetaAttributes(); ArgumentNullException.ThrowIfNull(_indices); - ArgumentNullException.ThrowIfNull(_attributes); + ArgumentNullException.ThrowIfNull(_vertexAttributes); ArgumentNullException.ThrowIfNull(_shapeValues); + ArgumentNullException.ThrowIfNull(_metaAttributes); var material = _primitive.Material.Name; if (material == "") material = null; + // At this level, we assume that attributes are wholly controlled by this sub-mesh. + var attributeMask = _metaAttributes.Length switch + { + < 32 => (1u << _metaAttributes.Length) - 1, + 32 => uint.MaxValue, + > 32 => throw new Exception("Models may utilise a maximum of 32 attributes."), + }; + return new SubMesh() { SubMeshStruct = new MdlStructs.SubmeshStruct() { IndexOffset = 0, IndexCount = (uint)_indices.Length, - AttributeIndexMask = 0, + AttributeIndexMask = attributeMask, // TODO: Flesh these out. Game doesn't seem to rely on them existing, though. BoneStartIndex = 0, @@ -102,12 +127,13 @@ public class SubMeshImporter Material = material, VertexDeclaration = new MdlStructs.VertexDeclarationStruct() { - VertexElements = _attributes.Select(attribute => attribute.Element).ToArray(), + VertexElements = _vertexAttributes.Select(attribute => attribute.Element).ToArray(), }, VertexCount = _vertexCount, Strides = _strides, Streams = _streams, Indices = _indices, + MetaAttributes = _metaAttributes, ShapeValues = _shapeValues, }; } @@ -117,7 +143,7 @@ public class SubMeshImporter _indices = _primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); } - private void BuildAttributes() + private void BuildVertexAttributes() { var accessors = _primitive.VertexAccessors; @@ -153,14 +179,14 @@ public class SubMeshImporter offsets[attribute.Stream] += attribute.Size; } - _attributes = attributes; + _vertexAttributes = attributes; // After building the attributes, the resulting next offsets are our stream strides. _strides = offsets; } private void BuildVertices() { - ArgumentNullException.ThrowIfNull(_attributes); + ArgumentNullException.ThrowIfNull(_vertexAttributes); // Lists of vertex indices that are effected by each morph target for this primitive. var morphModifiedVertices = Enumerable.Range(0, _primitive.MorphTargetsCount) @@ -173,13 +199,13 @@ public class SubMeshImporter for (var vertexIndex = 0; vertexIndex < _vertexCount; vertexIndex++) { // Write out vertex data to streams for each attribute. - foreach (var attribute in _attributes) + foreach (var attribute in _vertexAttributes) _streams[attribute.Stream].AddRange(attribute.Build(vertexIndex)); // Record which morph targets have values for this vertex, if any. var changedMorphs = morphModifiedVertices .WithIndex() - .Where(pair => _attributes.Any(attribute => attribute.HasMorph(pair.Index, vertexIndex))) + .Where(pair => _vertexAttributes.Any(attribute => attribute.HasMorph(pair.Index, vertexIndex))) .Select(pair => pair.Value); foreach (var modifiedVertices in changedMorphs) modifiedVertices.Add(vertexIndex); @@ -191,7 +217,7 @@ public class SubMeshImporter private void BuildShapeValues(IEnumerable> morphModifiedVertices) { ArgumentNullException.ThrowIfNull(_indices); - ArgumentNullException.ThrowIfNull(_attributes); + ArgumentNullException.ThrowIfNull(_vertexAttributes); var morphShapeValues = new Dictionary>(); @@ -203,7 +229,7 @@ public class SubMeshImporter foreach (var vertexIndex in modifiedVertices) { // Write out the morphed vertex to the vertex streams. - foreach (var attribute in _attributes) + foreach (var attribute in _vertexAttributes) _streams[attribute.Stream].AddRange(attribute.BuildMorph(morphIndex, vertexIndex)); // Find any indices that target this vertex index and create a mapping. @@ -224,4 +250,13 @@ public class SubMeshImporter _shapeValues = morphShapeValues; } + + private void BuildMetaAttributes() + { + // We consider any "extras" key with a boolean value set to `true` to be an attribute. + _metaAttributes = _nodeExtras? + .Where(pair => pair.Value.ValueKind == JsonValueKind.True) + .Select(pair => pair.Key) + .ToArray() ?? []; + } } diff --git a/Penumbra/Import/Models/Import/Utility.cs b/Penumbra/Import/Models/Import/Utility.cs new file mode 100644 index 00000000..449d19e4 --- /dev/null +++ b/Penumbra/Import/Models/Import/Utility.cs @@ -0,0 +1,34 @@ +namespace Penumbra.Import.Models.Import; + +public static class Utility +{ + /// Merge attributes into an existing attribute array, providing an updated submesh mask. + /// Old submesh attribute mask. + /// Old attribute array that should be merged. + /// New attribute array. Will be mutated. + /// New submesh attribute mask, updated to match the merged attribute array. + public static uint GetMergedAttributeMask(uint oldMask, IList oldAttributes, List newAttributes) + { + var metaAttributes = Enumerable.Range(0, 32) + .Where(index => ((oldMask >> index) & 1) == 1) + .Select(index => oldAttributes[index]); + + var newMask = 0u; + + foreach (var metaAttribute in metaAttributes) + { + var attributeIndex = newAttributes.IndexOf(metaAttribute); + if (attributeIndex == -1) + { + if (newAttributes.Count >= 32) + throw new Exception("Models may utilise a maximum of 32 attributes."); + + newAttributes.Add(metaAttribute); + attributeIndex = newAttributes.Count - 1; + } + newMask |= 1u << attributeIndex; + } + + return newMask; + } +} From edcffb9d9f7f6ee7ac5e454a15842b3c4d3ed01d Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 11 Jan 2024 21:26:34 +1100 Subject: [PATCH 0357/1381] Allow keeping existing mdl attributes --- .../ModEditWindow.Models.MdlTab.cs | 34 +++++++++++++++++++ .../UI/AdvancedWindow/ModEditWindow.Models.cs | 1 + 2 files changed, 35 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index d38d8d92..cdaf399f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -16,6 +16,7 @@ public partial class ModEditWindow private List[] _attributes; public bool ImportKeepMaterials; + public bool ImportKeepAttributes; public List? GamePaths { get; private set; } public int GamePathIndex; @@ -158,6 +159,9 @@ public partial class ModEditWindow if (ImportKeepMaterials) MergeMaterials(newMdl, Mdl); + if (ImportKeepAttributes) + MergeAttributes(newMdl, Mdl); + Initialize(newMdl); _dirty = true; } @@ -177,6 +181,36 @@ public partial class ModEditWindow } } + /// Merge attribute configuration from the source onto the target. + /// + /// Model to copy attribute configuration from. + public void MergeAttributes(MdlFile target, MdlFile source) + { + target.Attributes = source.Attributes; + + var indexEnumerator = Enumerable.Range(0, target.Meshes.Length) + .SelectMany(mi => Enumerable.Range(0, target.Meshes[mi].SubMeshCount).Select(so => (mi, so))); + foreach (var (meshIndex, subMeshOffset) in indexEnumerator) + { + var subMeshIndex = target.Meshes[meshIndex].SubMeshIndex + subMeshOffset; + + // Preemptively reset the mask in case we need to shortcut out. + target.SubMeshes[subMeshIndex].AttributeIndexMask = 0u; + + // Rather than comparing sub-meshes directly, we're grouping by parent mesh in an attempt + // to maintain semantic connection betwen mesh index and submesh attributes. + if (meshIndex >= source.Meshes.Length) + continue; + var sourceMesh = source.Meshes[meshIndex]; + + if (subMeshOffset >= sourceMesh.SubMeshCount) + continue; + var sourceSubMesh = source.SubMeshes[sourceMesh.SubMeshIndex + subMeshOffset]; + + target.SubMeshes[subMeshIndex].AttributeIndexMask = sourceSubMesh.AttributeIndexMask; + } + } + private void RecordIoExceptions(Exception? exception) { IoExceptions = exception switch { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index fbdfcc74..8c298d4f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -80,6 +80,7 @@ public partial class ModEditWindow using (var frame = ImRaii.FramedGroup("Import", size, headerPreIcon: FontAwesomeIcon.FileImport)) { ImGui.Checkbox("Keep current materials", ref tab.ImportKeepMaterials); + ImGui.Checkbox("Keep current attributes", ref tab.ImportKeepAttributes); if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", tab.PendingIo)) From 2e473a62f4587b7c67724b4d6d219847e7f846c2 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 11 Jan 2024 21:28:52 +1100 Subject: [PATCH 0358/1381] Sneak a small one in --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 8c298d4f..c92e2926 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -479,5 +479,6 @@ public partial class ModEditWindow private static readonly string[] ValidModelExtensions = [ ".gltf", + ".glb", ]; } From b81f3f423c10a6bfba2c7bc00e7bcf1d221e576e Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 11 Jan 2024 21:54:52 +1100 Subject: [PATCH 0359/1381] Cleanup pass --- Penumbra/Import/Models/Import/ModelImporter.cs | 14 +++++++------- Penumbra/Import/Models/Import/SubMeshImporter.cs | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 0d8c029d..3b3d2cd0 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -136,14 +136,14 @@ public partial class ModelImporter(ModelRoot model) var mesh = MeshImporter.Import(subMeshNodes); var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); - ushort materialIndex = 0; - if (mesh.Material != null) - materialIndex = GetMaterialIndex(mesh.Material); + var materialIndex = mesh.Material != null + ? GetMaterialIndex(mesh.Material) + : (ushort)0; // If no bone table is used for a mesh, the index is set to 255. - ushort boneTableIndex = 255; - if (mesh.Bones != null) - boneTableIndex = BuildBoneTable(mesh.Bones); + var boneTableIndex = mesh.Bones != null + ? BuildBoneTable(mesh.Bones) + : (ushort)255; _meshes.Add(mesh.MeshStruct with { @@ -196,7 +196,7 @@ public partial class ModelImporter(ModelRoot model) private ushort GetMaterialIndex(string materialName) { - // If we already have this material, grab the current one + // If we already have this material, grab the current index. var index = _materials.IndexOf(materialName); if (index >= 0) return (ushort)index; diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 6b12ee09..51443f64 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -69,7 +69,7 @@ public class SubMeshImporter } catch { - _nodeExtras = null; + _nodeExtras = null; } try From 4a6e7fccecd3a7796ebae4c8d25b96f7de286b60 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 11 Jan 2024 13:31:33 +0100 Subject: [PATCH 0360/1381] Fix scrolling weirdness. --- Penumbra/UI/ModsTab/ModPanel.cs | 16 +++++++++++++- Penumbra/UI/Tabs/ModsTab.cs | 37 +++++++++++++++++---------------- 2 files changed, 34 insertions(+), 19 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index f9a3262f..b5542e43 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -1,4 +1,6 @@ +using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin; +using ImGuiNET; using Penumbra.Mods; using Penumbra.Services; using Penumbra.UI.AdvancedWindow; @@ -12,6 +14,7 @@ public class ModPanel : IDisposable private readonly ModEditWindow _editWindow; private readonly ModPanelHeader _header; private readonly ModPanelTabBar _tabs; + private bool _resetCursor; public ModPanel(DalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs, MultiModPanel multiModPanel, CommunicatorService communicator) @@ -32,8 +35,18 @@ public class ModPanel : IDisposable return; } + if (_resetCursor) + { + _resetCursor = false; + ImGui.SetScrollX(0); + } + _header.Draw(); - _tabs.Draw(_mod); + ImGui.SetCursorPosX(ImGui.GetScrollX() + ImGui.GetCursorPosX()); + using var child = ImRaii.Child("Tabs", + new Vector2(ImGui.GetWindowContentRegionMax().X - ImGui.GetWindowContentRegionMin().X, ImGui.GetContentRegionAvail().Y)); + if (child) + _tabs.Draw(_mod); } public void Dispose() @@ -47,6 +60,7 @@ public class ModPanel : IDisposable private void OnSelectionChange(Mod? old, Mod? mod, in ModFileSystemSelector.ModState _) { + _resetCursor = true; if (mod == null || _selector.Selected == null) { _editWindow.IsOpen = false; diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 7b30f7fc..9f070d35 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -139,24 +139,6 @@ public class ModsTab : ITab if (hovered) ImGui.SetTooltip($"The supported modifiers for '/penumbra redraw' are:\n{TutorialService.SupportedRedrawModifiers}"); - void DrawButton(Vector2 size, string label, string lower, string additionalTooltip) - { - using (var disabled = ImRaii.Disabled(additionalTooltip.Length > 0)) - { - if (ImGui.Button(label, size)) - { - if (lower.Length > 0) - _redrawService.RedrawObject(lower, RedrawType.Redraw); - else - _redrawService.RedrawAll(RedrawType.Redraw); - } - } - - ImGuiUtil.HoverTooltip(lower.Length > 0 - ? $"Execute '/penumbra redraw {lower}'.{additionalTooltip}" - : $"Execute '/penumbra redraw'.{additionalTooltip}", ImGuiHoveredFlags.AllowWhenDisabled); - } - using var id = ImRaii.PushId("Redraw"); using var disabled = ImRaii.Disabled(_clientState.LocalPlayer == null); ImGui.SameLine(); @@ -185,6 +167,25 @@ public class ModsTab : ITab ? "\nCan currently only be used for indoor furniture." : string.Empty; DrawButton(frameHeight with { X = ImGui.GetContentRegionAvail().X - 1 }, "Furniture", "furniture", tt); + return; + + void DrawButton(Vector2 size, string label, string lower, string additionalTooltip) + { + using (_ = ImRaii.Disabled(additionalTooltip.Length > 0)) + { + if (ImGui.Button(label, size)) + { + if (lower.Length > 0) + _redrawService.RedrawObject(lower, RedrawType.Redraw); + else + _redrawService.RedrawAll(RedrawType.Redraw); + } + } + + ImGuiUtil.HoverTooltip(lower.Length > 0 + ? $"Execute '/penumbra redraw {lower}'.{additionalTooltip}" + : $"Execute '/penumbra redraw'.{additionalTooltip}", ImGuiHoveredFlags.AllowWhenDisabled); + } } private static unsafe bool IsIndoors() From be588e2fa31e027ed804a6acd38c872bf506f191 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 11 Jan 2024 12:33:42 +0000 Subject: [PATCH 0361/1381] [CI] Updating repo.json for testing_0.8.3.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 47e102c9..a9c1829a 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.4", + "TestingAssemblyVersion": "0.8.3.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 91cea50f028bee2902cf21431c29d037c419ead5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 11 Jan 2024 15:31:25 +0100 Subject: [PATCH 0362/1381] Move more hooks in own classes. --- Penumbra/Interop/GameState.cs | 19 ++- .../{ => Objects}/CharacterBaseDestructor.cs | 2 +- .../{ => Objects}/CharacterDestructor.cs | 2 +- .../Hooks/{ => Objects}/CopyCharacter.cs | 2 +- .../{ => Objects}/CreateCharacterBase.cs | 4 +- .../Interop/Hooks/{ => Objects}/EnableDraw.cs | 8 +- .../Hooks/{ => Objects}/WeaponReload.cs | 2 +- .../Hooks/Resources/ApricotResourceLoad.cs | 28 +++++ .../Interop/Hooks/Resources/LoadMtrlShpk.cs | 32 +++++ .../Interop/Hooks/Resources/LoadMtrlTex.cs | 28 +++++ .../Hooks/Resources/ResolvePathHooks.cs | 38 ++++++ .../Resources/ResolvePathHooksBase.cs} | 55 +++++---- .../ResourceHandleDestructor.cs | 3 +- .../LiveColorTablePreviewer.cs | 17 +-- .../MaterialPreview/LiveMaterialPreviewer.cs | 75 +++++------ .../LiveMaterialPreviewerBase.cs | 5 +- .../Interop/MaterialPreview/MaterialInfo.cs | 32 ++--- .../Interop/PathResolving/CutsceneService.cs | 2 +- .../Interop/PathResolving/DrawObjectState.cs | 1 + .../IdentifiedCollectionCache.cs | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 2 +- Penumbra/Interop/PathResolving/PathState.cs | 55 +-------- .../Interop/PathResolving/SubfileHelper.cs | 116 +++--------------- Penumbra/Interop/Services/SkinFixer.cs | 2 +- .../ModEditWindow.Materials.MtrlTab.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 26 files changed, 274 insertions(+), 262 deletions(-) rename Penumbra/Interop/Hooks/{ => Objects}/CharacterBaseDestructor.cs (96%) rename Penumbra/Interop/Hooks/{ => Objects}/CharacterDestructor.cs (96%) rename Penumbra/Interop/Hooks/{ => Objects}/CopyCharacter.cs (96%) rename Penumbra/Interop/Hooks/{ => Objects}/CreateCharacterBase.cs (94%) rename Penumbra/Interop/Hooks/{ => Objects}/EnableDraw.cs (86%) rename Penumbra/Interop/Hooks/{ => Objects}/WeaponReload.cs (98%) create mode 100644 Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs create mode 100644 Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs create mode 100644 Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs create mode 100644 Penumbra/Interop/Hooks/Resources/ResolvePathHooks.cs rename Penumbra/Interop/{PathResolving/ResolvePathHooks.cs => Hooks/Resources/ResolvePathHooksBase.cs} (78%) rename Penumbra/Interop/Hooks/{ => Resources}/ResourceHandleDestructor.cs (95%) diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs index 2552f1a7..7e7abcd8 100644 --- a/Penumbra/Interop/GameState.cs +++ b/Penumbra/Interop/GameState.cs @@ -72,7 +72,24 @@ public class GameState : IService #endregion - /// Return the correct resolve data from the stored data. + #region Subfiles + + public readonly ThreadLocal MtrlData = new(() => ResolveData.Invalid); + public readonly ThreadLocal AvfxData = new(() => ResolveData.Invalid); + + public readonly ConcurrentDictionary SubFileCollection = new(); + + public ResolveData LoadSubFileHelper(nint resourceHandle) + { + if (resourceHandle == nint.Zero) + return ResolveData.Invalid; + + return SubFileCollection.TryGetValue(resourceHandle, out var c) ? c : ResolveData.Invalid; + } + + #endregion + + /// Return the correct resolve data from the stored data. public unsafe bool HandleFiles(CollectionResolver resolver, ResourceType type, Utf8GamePath _, out ResolveData resolveData) { switch (type) diff --git a/Penumbra/Interop/Hooks/CharacterBaseDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs similarity index 96% rename from Penumbra/Interop/Hooks/CharacterBaseDestructor.cs rename to Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs index 435ddea6..fc6dbfe6 100644 --- a/Penumbra/Interop/Hooks/CharacterBaseDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs @@ -4,7 +4,7 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.UI.AdvancedWindow; -namespace Penumbra.Interop.Hooks; +namespace Penumbra.Interop.Hooks.Objects; public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr, IHookService { diff --git a/Penumbra/Interop/Hooks/CharacterDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs similarity index 96% rename from Penumbra/Interop/Hooks/CharacterDestructor.cs rename to Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs index 4a0e9367..6e10c5e3 100644 --- a/Penumbra/Interop/Hooks/CharacterDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs @@ -4,7 +4,7 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.GameData; -namespace Penumbra.Interop.Hooks; +namespace Penumbra.Interop.Hooks.Objects; public sealed unsafe class CharacterDestructor : EventWrapperPtr, IHookService { diff --git a/Penumbra/Interop/Hooks/CopyCharacter.cs b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs similarity index 96% rename from Penumbra/Interop/Hooks/CopyCharacter.cs rename to Penumbra/Interop/Hooks/Objects/CopyCharacter.cs index d2e8d816..7b730f84 100644 --- a/Penumbra/Interop/Hooks/CopyCharacter.cs +++ b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs @@ -3,7 +3,7 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; using OtterGui.Classes; using OtterGui.Services; -namespace Penumbra.Interop.Hooks; +namespace Penumbra.Interop.Hooks.Objects; public sealed unsafe class CopyCharacter : EventWrapperPtr, IHookService { diff --git a/Penumbra/Interop/Hooks/CreateCharacterBase.cs b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs similarity index 94% rename from Penumbra/Interop/Hooks/CreateCharacterBase.cs rename to Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs index 7dbde666..299f312a 100644 --- a/Penumbra/Interop/Hooks/CreateCharacterBase.cs +++ b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs @@ -4,7 +4,7 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.GameData.Structs; -namespace Penumbra.Interop.Hooks; +namespace Penumbra.Interop.Hooks.Objects; public sealed unsafe class CreateCharacterBase : EventWrapperPtr, IHookService { @@ -39,7 +39,7 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr /// EnableDraw is what creates DrawObjects for gameObjects, @@ -12,12 +12,12 @@ namespace Penumbra.Interop.Hooks; public sealed unsafe class EnableDraw : IHookService { private readonly Task> _task; - private readonly GameState _state; + private readonly GameState _state; public EnableDraw(HookManager hooks, GameState state) { _state = state; - _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, true); + _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, true); } private delegate void Delegate(GameObject* gameObject); @@ -26,7 +26,7 @@ public sealed unsafe class EnableDraw : IHookService private void Detour(GameObject* gameObject) { _state.QueueGameObject(gameObject); - Penumbra.Log.Excessive($"[Enable Draw] Invoked on 0x{(nint) gameObject:X}."); + Penumbra.Log.Excessive($"[Enable Draw] Invoked on 0x{(nint)gameObject:X}."); _task.Result.Original.Invoke(gameObject); _state.DequeueGameObject(); } diff --git a/Penumbra/Interop/Hooks/WeaponReload.cs b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs similarity index 98% rename from Penumbra/Interop/Hooks/WeaponReload.cs rename to Penumbra/Interop/Hooks/Objects/WeaponReload.cs index b931f8fb..31c6b883 100644 --- a/Penumbra/Interop/Hooks/WeaponReload.cs +++ b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs @@ -4,7 +4,7 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.GameData.Structs; -namespace Penumbra.Interop.Hooks; +namespace Penumbra.Interop.Hooks.Objects; public sealed unsafe class WeaponReload : EventWrapperPtr, IHookService { diff --git a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs new file mode 100644 index 00000000..2e5698a3 --- /dev/null +++ b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs @@ -0,0 +1,28 @@ +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks.Resources; + +public sealed unsafe class ApricotResourceLoad : FastHook +{ + private readonly GameState _gameState; + + public ApricotResourceLoad(HookManager hooks, GameState gameState) + { + _gameState = gameState; + Task = hooks.CreateHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, true); + } + + public delegate byte Delegate(ResourceHandle* handle, nint unk1, byte unk2); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private byte Detour(ResourceHandle* handle, nint unk1, byte unk2) + { + var last = _gameState.AvfxData.Value; + _gameState.AvfxData.Value = _gameState.LoadSubFileHelper((nint)handle); + var ret = Task.Result.Original(handle, unk1, unk2); + _gameState.AvfxData.Value = last; + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs new file mode 100644 index 00000000..5ef3bf37 --- /dev/null +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs @@ -0,0 +1,32 @@ +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Services; + +namespace Penumbra.Interop.Hooks.Resources; + +public sealed unsafe class LoadMtrlShpk : FastHook +{ + private readonly GameState _gameState; + private readonly CommunicatorService _communicator; + + public LoadMtrlShpk(HookManager hooks, GameState gameState, CommunicatorService communicator) + { + _gameState = gameState; + _communicator = communicator; + Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, true); + } + + public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); + + private byte Detour(MaterialResourceHandle* handle) + { + var last = _gameState.MtrlData.Value; + var mtrlData = _gameState.LoadSubFileHelper((nint)handle); + _gameState.MtrlData.Value = mtrlData; + var ret = Task.Result.Original(handle); + _gameState.MtrlData.Value = last; + _communicator.MtrlShpkLoaded.Invoke((nint)handle, mtrlData.AssociatedGameObject); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs new file mode 100644 index 00000000..14a011ea --- /dev/null +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs @@ -0,0 +1,28 @@ +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks.Resources; + +public sealed unsafe class LoadMtrlTex : FastHook +{ + private readonly GameState _gameState; + + public LoadMtrlTex(HookManager hooks, GameState gameState) + { + _gameState = gameState; + Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, true); + } + + public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private byte Detour(MaterialResourceHandle* handle) + { + var last = _gameState.MtrlData.Value; + _gameState.MtrlData.Value = _gameState.LoadSubFileHelper((nint)handle); + var ret = Task.Result.Original(handle); + _gameState.MtrlData.Value = last; + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooks.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooks.cs new file mode 100644 index 00000000..8a52acd2 --- /dev/null +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooks.cs @@ -0,0 +1,38 @@ +using OtterGui.Services; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Resources; + +public sealed unsafe class ResolvePathHooks(HookManager hooks, CharacterBaseVTables vTables, PathState pathState) : IDisposable, IRequiredService +{ + // @formatter:off + private readonly ResolvePathHooksBase _human = new("Human", hooks, pathState, vTables.HumanVTable, ResolvePathHooksBase.Type.Human); + private readonly ResolvePathHooksBase _weapon = new("Weapon", hooks, pathState, vTables.WeaponVTable, ResolvePathHooksBase.Type.Other); + private readonly ResolvePathHooksBase _demiHuman = new("DemiHuman", hooks, pathState, vTables.DemiHumanVTable, ResolvePathHooksBase.Type.Other); + private readonly ResolvePathHooksBase _monster = new("Monster", hooks, pathState, vTables.MonsterVTable, ResolvePathHooksBase.Type.Other); + // @formatter:on + + public void Enable() + { + _human.Enable(); + _weapon.Enable(); + _demiHuman.Enable(); + _monster.Enable(); + } + + public void Disable() + { + _human.Disable(); + _weapon.Disable(); + _demiHuman.Disable(); + _monster.Disable(); + } + + public void Dispose() + { + _human.Dispose(); + _weapon.Dispose(); + _demiHuman.Dispose(); + _monster.Dispose(); + } +} diff --git a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs similarity index 78% rename from Penumbra/Interop/PathResolving/ResolvePathHooks.cs rename to Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 3be7ffdd..6b4abf90 100644 --- a/Penumbra/Interop/PathResolving/ResolvePathHooks.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -1,13 +1,14 @@ using Dalamud.Hooking; -using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Collections; +using Penumbra.Interop.PathResolving; using Penumbra.Meta.Manipulations; -namespace Penumbra.Interop.PathResolving; +namespace Penumbra.Interop.Hooks.Resources; -public unsafe class ResolvePathHooks : IDisposable +public sealed unsafe class ResolvePathHooksBase : IDisposable { public enum Type { @@ -19,7 +20,9 @@ public unsafe class ResolvePathHooks : IDisposable private delegate nint NamedResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint name); private delegate nint PerSlotResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex); private delegate nint SingleResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize); + private delegate nint TmbResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, nint timelineName); + // Kept separate from NamedResolveDelegate because the 5th parameter has out semantics here, instead of in. private delegate nint VfxResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam); @@ -38,21 +41,24 @@ public unsafe class ResolvePathHooks : IDisposable private readonly PathState _parent; - public ResolvePathHooks(IGameInteropProvider interop, PathState parent, nint* vTable, Type type) + public ResolvePathHooksBase(string name, HookManager hooks, PathState parent, nint* vTable, Type type) { - _parent = parent; - _resolveDecalPathHook = Create(interop, vTable[83], ResolveDecal); - _resolveEidPathHook = Create(interop, vTable[85], ResolveEid); - _resolveImcPathHook = Create(interop, vTable[81], ResolveImc); - _resolveMPapPathHook = Create(interop, vTable[79], ResolveMPap); - _resolveMdlPathHook = Create(interop, vTable[73], type, ResolveMdl, ResolveMdlHuman); - _resolveMtrlPathHook = Create(interop, vTable[82], ResolveMtrl); - _resolvePapPathHook = Create(interop, vTable[76], type, ResolvePap, ResolvePapHuman); - _resolvePhybPathHook = Create(interop, vTable[75], type, ResolvePhyb, ResolvePhybHuman); - _resolveSklbPathHook = Create(interop, vTable[72], type, ResolveSklb, ResolveSklbHuman); - _resolveSkpPathHook = Create(interop, vTable[74], type, ResolveSkp, ResolveSkpHuman); - _resolveTmbPathHook = Create(interop, vTable[77], ResolveTmb); - _resolveVfxPathHook = Create(interop, vTable[84], ResolveVfx); + _parent = parent; + // @formatter:off + _resolveDecalPathHook = Create($"{name}.{nameof(ResolveDecal)}", hooks, vTable[83], ResolveDecal); + _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[85], ResolveEid); + _resolveImcPathHook = Create($"{name}.{nameof(ResolveImc)}", hooks, vTable[81], ResolveImc); + _resolveMPapPathHook = Create( $"{name}.{nameof(ResolveMPap)}", hooks, vTable[79], ResolveMPap); + _resolveMdlPathHook = Create($"{name}.{nameof(ResolveMdl)}", hooks, vTable[73], type, ResolveMdl, ResolveMdlHuman); + _resolveMtrlPathHook = Create( $"{name}.{nameof(ResolveMtrl)}", hooks, vTable[82], ResolveMtrl); + _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[76], type, ResolvePap, ResolvePapHuman); + _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[75], type, ResolvePhyb, ResolvePhybHuman); + _resolveSklbPathHook = Create($"{name}.{nameof(ResolveSklb)}", hooks, vTable[72], type, ResolveSklb, ResolveSklbHuman); + _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[74], type, ResolveSkp, ResolveSkpHuman); + _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[77], ResolveTmb); + _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[84], ResolveVfx); + // @formatter:on + Enable(); } public void Enable() @@ -177,9 +183,8 @@ public unsafe class ResolvePathHooks : IDisposable { data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); if (_parent.InInternalResolve) - { return DisposableContainer.Empty; - } + return new DisposableContainer(data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Face), data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Body), data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Hair), @@ -188,19 +193,19 @@ public unsafe class ResolvePathHooks : IDisposable [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(IGameInteropProvider interop, nint address, Type type, T other, T human) where T : Delegate + private static Hook Create(string name, HookManager hooks, nint address, Type type, T other, T human) where T : Delegate { var del = type switch { - Type.Human => human, - _ => other, + Type.Human => human, + _ => other, }; - return interop.HookFromAddress(address, del); + return hooks.CreateHook(name, address, del).Result; } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(IGameInteropProvider interop, nint address, T del) where T : Delegate - => interop.HookFromAddress(address, del); + private static Hook Create(string name, HookManager hooks, nint address, T del) where T : Delegate + => hooks.CreateHook(name, address, del).Result; // Implementation diff --git a/Penumbra/Interop/Hooks/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs similarity index 95% rename from Penumbra/Interop/Hooks/ResourceHandleDestructor.cs rename to Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index 99eb1c23..776f2f92 100644 --- a/Penumbra/Interop/Hooks/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -2,10 +2,9 @@ using Dalamud.Hooking; using OtterGui.Classes; using OtterGui.Services; using Penumbra.GameData; -using Penumbra.Interop.Services; using Penumbra.Interop.Structs; -namespace Penumbra.Interop.Hooks; +namespace Penumbra.Interop.Hooks.Resources; public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr, IHookService { diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index 0b7bafe0..801c3bf0 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -16,11 +16,9 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase private readonly Texture** _colorTableTexture; private readonly SafeTextureHandle _originalColorTableTexture; - private Half[] _colorTable; - private bool _updatePending; + private bool _updatePending; - public Half[] ColorTable - => _colorTable; + public Half[] ColorTable { get; } public LiveColorTablePreviewer(IObjectTable objects, IFramework framework, MaterialInfo materialInfo) : base(objects, materialInfo) @@ -41,7 +39,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (_originalColorTableTexture == null) throw new InvalidOperationException("Material doesn't have a color table"); - _colorTable = new Half[TextureLength]; + ColorTable = new Half[TextureLength]; _updatePending = true; framework.Update += OnFrameworkUpdate; @@ -84,9 +82,9 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase return; bool success; - lock (_colorTable) + lock (ColorTable) { - fixed (Half* colorTable = _colorTable) + fixed (Half* colorTable = ColorTable) { success = texture.Texture->InitializeContents(colorTable); } @@ -105,9 +103,6 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (colorSetTextures == null) return false; - if (_colorTableTexture != colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot)) - return false; - - return true; + return _colorTableTexture == colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); } } diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 972d81be..9ed7ca3d 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -26,34 +26,29 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (_shaderPackage == null) throw new InvalidOperationException("Material doesn't have a shader package"); - var material = Material; + _originalShPkFlags = Material->ShaderFlags; - _originalShPkFlags = material->ShaderFlags; + _originalMaterialParameter = Material->MaterialParameterCBuffer->TryGetBuffer().ToArray(); - _originalMaterialParameter = material->MaterialParameterCBuffer->TryGetBuffer().ToArray(); - - _originalSamplerFlags = new uint[material->TextureCount]; + _originalSamplerFlags = new uint[Material->TextureCount]; for (var i = 0; i < _originalSamplerFlags.Length; ++i) - _originalSamplerFlags[i] = material->Textures[i].SamplerFlags; + _originalSamplerFlags[i] = Material->Textures[i].SamplerFlags; } protected override void Clear(bool disposing, bool reset) { base.Clear(disposing, reset); - if (reset) - { - var material = Material; + if (!reset) + return; - material->ShaderFlags = _originalShPkFlags; + Material->ShaderFlags = _originalShPkFlags; + var materialParameter = Material->MaterialParameterCBuffer->TryGetBuffer(); + if (!materialParameter.IsEmpty) + _originalMaterialParameter.AsSpan().CopyTo(materialParameter); - var materialParameter = material->MaterialParameterCBuffer->TryGetBuffer(); - if (!materialParameter.IsEmpty) - _originalMaterialParameter.AsSpan().CopyTo(materialParameter); - - for (var i = 0; i < _originalSamplerFlags.Length; ++i) - material->Textures[i].SamplerFlags = _originalSamplerFlags[i]; - } + for (var i = 0; i < _originalSamplerFlags.Length; ++i) + Material->Textures[i].SamplerFlags = _originalSamplerFlags[i]; } public void SetShaderPackageFlags(uint shPkFlags) @@ -80,16 +75,16 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase for (var i = 0; i < _shaderPackage->MaterialElementCount; ++i) { ref var parameter = ref _shaderPackage->MaterialElementsSpan[i]; - if (parameter.CRC == parameterCrc) - { - if ((parameter.Offset & 0x3) != 0 - || (parameter.Size & 0x3) != 0 - || (parameter.Offset + parameter.Size) >> 2 > buffer.Length) - return; + if (parameter.CRC != parameterCrc) + continue; - value.TryCopyTo(buffer.Slice(parameter.Offset >> 2, parameter.Size >> 2)[offset..]); + if ((parameter.Offset & 0x3) != 0 + || (parameter.Size & 0x3) != 0 + || (parameter.Offset + parameter.Size) >> 2 > buffer.Length) return; - } + + value.TryCopyTo(buffer.Slice(parameter.Offset >> 2, parameter.Size >> 2)[offset..]); + return; } } @@ -104,25 +99,24 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase var samplers = _shaderPackage->Samplers; for (var i = 0; i < _shaderPackage->SamplerCount; ++i) { - if (samplers[i].CRC == samplerCrc) - { - id = samplers[i].Id; - found = true; - break; - } + if (samplers[i].CRC != samplerCrc) + continue; + + id = samplers[i].Id; + found = true; + break; } if (!found) return; - var material = Material; - for (var i = 0; i < material->TextureCount; ++i) + for (var i = 0; i < Material->TextureCount; ++i) { - if (material->Textures[i].Id == id) - { - material->Textures[i].SamplerFlags = (samplerFlags & 0xFFFFFDFF) | 0x000001C0; - break; - } + if (Material->Textures[i].Id != id) + continue; + + Material->Textures[i].SamplerFlags = (samplerFlags & 0xFFFFFDFF) | 0x000001C0; + break; } } @@ -139,9 +133,6 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (shpkHandle == null) return false; - if (_shaderPackage != shpkHandle->ShaderPackage) - return false; - - return true; + return _shaderPackage == shpkHandle->ShaderPackage; } } diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs index 86fee976..07986f52 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs @@ -61,9 +61,6 @@ public abstract unsafe class LiveMaterialPreviewerBase : IDisposable if ((nint)DrawObject != MaterialInfo.GetDrawObject(gameObject)) return false; - if (Material != MaterialInfo.GetDrawObjectMaterial(DrawObject)) - return false; - - return true; + return Material == MaterialInfo.GetDrawObjectMaterial(DrawObject); } } diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index ec0ddd29..686b5a86 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -24,22 +24,6 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy public nint GetDrawObject(nint address) => GetDrawObject(Type, address); - public static unsafe nint GetDrawObject(DrawObjectType type, nint address) - { - var gameObject = (Character*)address; - if (gameObject == null) - return nint.Zero; - - return type switch - { - DrawObjectType.Character => (nint)gameObject->GameObject.GetDrawObject(), - DrawObjectType.Mainhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.MainHand).DrawObject, - DrawObjectType.Offhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.OffHand).DrawObject, - DrawObjectType.Vfx => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.Unk).DrawObject, - _ => nint.Zero, - }; - } - public unsafe Material* GetDrawObjectMaterial(IObjectTable objects) => GetDrawObjectMaterial((CharacterBase*)GetDrawObject(GetCharacter(objects))); @@ -103,4 +87,20 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy return result; } + + private static unsafe nint GetDrawObject(DrawObjectType type, nint address) + { + var gameObject = (Character*)address; + if (gameObject == null) + return nint.Zero; + + return type switch + { + DrawObjectType.Character => (nint)gameObject->GameObject.GetDrawObject(), + DrawObjectType.Mainhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.MainHand).DrawObject, + DrawObjectType.Offhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.OffHand).DrawObject, + DrawObjectType.Vfx => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.Unk).DrawObject, + _ => nint.Zero, + }; + } } diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index c7b24bd7..2eeefbd8 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -2,7 +2,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using OtterGui.Services; using Penumbra.GameData.Enums; -using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.Objects; namespace Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 19c0fd10..dd4b03f2 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -6,6 +6,7 @@ using OtterGui.Services; using Penumbra.Interop.Hooks; using Object = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.Object; using Penumbra.GameData.Structs; +using Penumbra.Interop.Hooks.Objects; namespace Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index b944011d..32090f7c 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -5,7 +5,7 @@ using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Actors; -using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.Objects; using Penumbra.Services; namespace Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 9d899648..a3400540 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -4,13 +4,13 @@ using Penumbra.Collections; using Penumbra.Api.Enums; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Hooks; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Services; using Penumbra.String.Classes; using ObjectType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; +using Penumbra.Interop.Hooks.Objects; namespace Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index 6d7840d8..f4218e9c 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -1,34 +1,15 @@ -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; using Penumbra.Collections; -using Penumbra.GameData; using Penumbra.Interop.Services; using Penumbra.String; namespace Penumbra.Interop.PathResolving; -public unsafe class PathState : IDisposable +public sealed class PathState(CollectionResolver collectionResolver, MetaState metaState, CharacterUtility characterUtility) + : IDisposable { - [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _humanVTable = null!; - - [Signature(Sigs.WeaponVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _weaponVTable = null!; - - [Signature(Sigs.DemiHumanVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _demiHumanVTable = null!; - - [Signature(Sigs.MonsterVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _monsterVTable = null!; - - public readonly CollectionResolver CollectionResolver; - public readonly MetaState MetaState; - public readonly CharacterUtility CharacterUtility; - - private readonly ResolvePathHooks _human; - private readonly ResolvePathHooks _weapon; - private readonly ResolvePathHooks _demiHuman; - private readonly ResolvePathHooks _monster; + public readonly CollectionResolver CollectionResolver = collectionResolver; + public readonly MetaState MetaState = metaState; + public readonly CharacterUtility CharacterUtility = characterUtility; private readonly ThreadLocal _resolveData = new(() => ResolveData.Invalid, true); private readonly ThreadLocal _internalResolve = new(() => 0, false); @@ -39,31 +20,11 @@ public unsafe class PathState : IDisposable public bool InInternalResolve => _internalResolve.Value != 0u; - public PathState(CollectionResolver collectionResolver, MetaState metaState, CharacterUtility characterUtility, IGameInteropProvider interop) - { - interop.InitializeFromAttributes(this); - CollectionResolver = collectionResolver; - MetaState = metaState; - CharacterUtility = characterUtility; - _human = new ResolvePathHooks(interop, this, _humanVTable, ResolvePathHooks.Type.Human); - _weapon = new ResolvePathHooks(interop, this, _weaponVTable, ResolvePathHooks.Type.Other); - _demiHuman = new ResolvePathHooks(interop, this, _demiHumanVTable, ResolvePathHooks.Type.Other); - _monster = new ResolvePathHooks(interop, this, _monsterVTable, ResolvePathHooks.Type.Other); - _human.Enable(); - _weapon.Enable(); - _demiHuman.Enable(); - _monster.Enable(); - } - public void Dispose() { _resolveData.Dispose(); _internalResolve.Dispose(); - _human.Dispose(); - _weapon.Dispose(); - _demiHuman.Dispose(); - _monster.Dispose(); } public bool Consume(ByteString _, out ResolveData collection) @@ -86,9 +47,7 @@ public unsafe class PathState : IDisposable return path; if (!InInternalResolve) - { _resolveData.Value = collection.ToResolveData(gameObject); - } return path; } @@ -99,9 +58,7 @@ public unsafe class PathState : IDisposable return path; if (!InInternalResolve) - { _resolveData.Value = data; - } return path; } @@ -126,7 +83,7 @@ public unsafe class PathState : IDisposable } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public readonly void Dispose() + public void Dispose() { --_internalResolve.Value; } diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 370118ea..2359c36e 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,17 +1,10 @@ -using Dalamud.Hooking; -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.GameData; -using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.ResourceLoading; -using Penumbra.Interop.Services; using Penumbra.Interop.Structs; -using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; -using Penumbra.Util; namespace Penumbra.Interop.PathResolving; @@ -20,49 +13,37 @@ namespace Penumbra.Interop.PathResolving; /// Those are loaded synchronously. /// Thus, we need to ensure the correct files are loaded when a material is loaded. /// -public unsafe class SubfileHelper : IDisposable, IReadOnlyCollection> +public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection> { - private readonly PerformanceTracker _performance; + private readonly GameState _gameState; private readonly ResourceLoader _loader; private readonly ResourceHandleDestructor _resourceHandleDestructor; - private readonly CommunicatorService _communicator; - private readonly ThreadLocal _mtrlData = new(() => ResolveData.Invalid); - private readonly ThreadLocal _avfxData = new(() => ResolveData.Invalid); - - private readonly ConcurrentDictionary _subFileCollection = new(); - - public SubfileHelper(PerformanceTracker performance, ResourceLoader loader, CommunicatorService communicator, IGameInteropProvider interop, ResourceHandleDestructor resourceHandleDestructor) + public SubfileHelper(GameState gameState, ResourceLoader loader, ResourceHandleDestructor resourceHandleDestructor) { - interop.InitializeFromAttributes(this); - - _performance = performance; - _loader = loader; - _communicator = communicator; + _gameState = gameState; + _loader = loader; _resourceHandleDestructor = resourceHandleDestructor; - _loadMtrlShpkHook.Enable(); - _loadMtrlTexHook.Enable(); - _apricotResourceLoadHook.Enable(); - _loader.ResourceLoaded += SubfileContainerRequested; + _loader.ResourceLoaded += SubfileContainerRequested; _resourceHandleDestructor.Subscribe(ResourceDestroyed, ResourceHandleDestructor.Priority.SubfileHelper); } public IEnumerator> GetEnumerator() - => _subFileCollection.GetEnumerator(); + => _gameState.SubFileCollection.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public int Count - => _subFileCollection.Count; + => _gameState.SubFileCollection.Count; public ResolveData MtrlData - => _mtrlData.IsValueCreated ? _mtrlData.Value : ResolveData.Invalid; + => _gameState.MtrlData.IsValueCreated ? _gameState.MtrlData.Value : ResolveData.Invalid; public ResolveData AvfxData - => _avfxData.IsValueCreated ? _avfxData.Value : ResolveData.Invalid; + => _gameState.AvfxData.IsValueCreated ? _gameState.AvfxData.Value : ResolveData.Invalid; /// /// Check specifically for shpk and tex files whether we are currently in a material load, @@ -71,13 +52,13 @@ public unsafe class SubfileHelper : IDisposable, IReadOnlyCollectionFileSize == 0) - _subFileCollection[(nint)handle] = resolveData; + _gameState.SubFileCollection[(nint)handle] = resolveData; break; } } private void ResourceDestroyed(ResourceHandle* handle) - => _subFileCollection.TryRemove((nint)handle, out _); - - private delegate byte LoadMtrlFilesDelegate(nint mtrlResourceHandle); - - [Signature(Sigs.LoadMtrlTex, DetourName = nameof(LoadMtrlTexDetour))] - private readonly Hook _loadMtrlTexHook = null!; - - private byte LoadMtrlTexDetour(nint mtrlResourceHandle) - { - using var performance = _performance.Measure(PerformanceType.LoadTextures); - var last = _mtrlData.Value; - _mtrlData.Value = LoadFileHelper(mtrlResourceHandle); - var ret = _loadMtrlTexHook.Original(mtrlResourceHandle); - _mtrlData.Value = last; - return ret; - } - - [Signature(Sigs.LoadMtrlShpk, DetourName = nameof(LoadMtrlShpkDetour))] - private readonly Hook _loadMtrlShpkHook = null!; - - private byte LoadMtrlShpkDetour(nint mtrlResourceHandle) - { - using var performance = _performance.Measure(PerformanceType.LoadShaders); - var last = _mtrlData.Value; - var mtrlData = LoadFileHelper(mtrlResourceHandle); - _mtrlData.Value = mtrlData; - var ret = _loadMtrlShpkHook.Original(mtrlResourceHandle); - _mtrlData.Value = last; - _communicator.MtrlShpkLoaded.Invoke(mtrlResourceHandle, mtrlData.AssociatedGameObject); - return ret; - } - - private ResolveData LoadFileHelper(nint resourceHandle) - { - if (resourceHandle == nint.Zero) - return ResolveData.Invalid; - - return _subFileCollection.TryGetValue(resourceHandle, out var c) ? c : ResolveData.Invalid; - } - - - private delegate byte ApricotResourceLoadDelegate(nint handle, nint unk1, byte unk2); - - [Signature(Sigs.ApricotResourceLoad, DetourName = nameof(ApricotResourceLoadDetour))] - private readonly Hook _apricotResourceLoadHook = null!; - - private byte ApricotResourceLoadDetour(nint handle, nint unk1, byte unk2) - { - using var performance = _performance.Measure(PerformanceType.LoadApricotResources); - var last = _avfxData.Value; - _avfxData.Value = LoadFileHelper(handle); - var ret = _apricotResourceLoadHook.Original(handle, unk1, unk2); - _avfxData.Value = last; - return ret; - } + => _gameState.SubFileCollection.TryRemove((nint)handle, out _); } diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs index 444b9a48..21331916 100644 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ b/Penumbra/Interop/Services/SkinFixer.cs @@ -6,7 +6,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Classes; using Penumbra.Communication; using Penumbra.GameData; -using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.Resources; using Penumbra.Services; namespace Penumbra.Interop.Services; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 376bbcf7..b4801f5f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -9,7 +9,7 @@ using OtterGui.Raii; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Structs; -using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.Objects; using Penumbra.Interop.MaterialPreview; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 8d3e32f9..8b6ef331 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -14,7 +14,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.Import.Models; using Penumbra.Import.Textures; -using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.Objects; using Penumbra.Interop.ResourceTree; using Penumbra.Meta; using Penumbra.Mods; From c6642c4fa30eaee0f10dc1cbd208101d76b33630 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 11:32:26 +1100 Subject: [PATCH 0363/1381] Spike material export workflow --- .../Import/Models/Export/MaterialExporter.cs | 81 +++++++++++++++++++ .../Import/Models/Export/ModelExporter.cs | 18 ++--- Penumbra/Import/Models/ModelManager.cs | 65 ++++++++++++++- 3 files changed, 149 insertions(+), 15 deletions(-) create mode 100644 Penumbra/Import/Models/Export/MaterialExporter.cs diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs new file mode 100644 index 00000000..ef417e35 --- /dev/null +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -0,0 +1,81 @@ +using Lumina.Data.Parsing; +using Penumbra.GameData.Files; +using SharpGLTF.Materials; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.PixelFormats; + +namespace Penumbra.Import.Models.Export; + +public class MaterialExporter +{ + // input stuff + public struct Material + { + public MtrlFile Mtrl; + public Sampler[] Samplers; + // variant? + } + + public struct Sampler + { + public TextureUsage Usage; + public Image Texture; + } + + public static MaterialBuilder Export(Material material, string name) + { + return material.Mtrl.ShaderPackage.Name switch + { + "character.shpk" => BuildCharacter(material, name), + _ => BuildFallback(material, name), + }; + } + + private static MaterialBuilder BuildCharacter(Material material, string name) + { + // TODO: pixelbashing time + var sampler = material.Samplers + .Where(s => s.Usage == TextureUsage.SamplerNormal) + .First(); + + // TODO: clean up this name generation a bunch. probably a method. + var imageName = name.Replace("/", ""); + var baseColor = BuildImage(sampler.Texture, $"{imageName}_basecolor"); + + return BuildSharedBase(material, name) + .WithBaseColor(baseColor); + } + + private static MaterialBuilder BuildFallback(Material material, string name) + { + Penumbra.Log.Warning($"Unhandled shader package: {material.Mtrl.ShaderPackage.Name}"); + return BuildSharedBase(material, name) + .WithMetallicRoughnessShader() + .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, Vector4.One); + } + + private static MaterialBuilder BuildSharedBase(Material material, string name) + { + // TODO: Move this and potentially the other known stuff into MtrlFile? + const uint backfaceMask = 0x1; + var showBackfaces = (material.Mtrl.ShaderPackage.Flags & backfaceMask) == 0; + + return new MaterialBuilder(name) + .WithDoubleSide(showBackfaces); + } + + private static ImageBuilder BuildImage(Image image, string name) + { + byte[] textureBytes; + using (var memoryStream = new MemoryStream()) + { + image.Save(memoryStream, PngFormat.Instance); + textureBytes = memoryStream.ToArray(); + } + + var imageBuilder = ImageBuilder.From(textureBytes, name); + imageBuilder.AlternateWriteFileName = $"{name}.*"; + return imageBuilder; + } +} diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 6a25af61..da24fbb0 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -23,10 +23,10 @@ public class ModelExporter } /// Export a model in preparation for usage in a glTF file. If provided, skeleton will be used to skin the resulting meshes where appropriate. - public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton) + public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton, Dictionary rawMaterials) { var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; - var materials = ConvertMaterials(mdl); + var materials = ConvertMaterials(mdl, rawMaterials); var meshes = ConvertMeshes(mdl, materials, gltfSkeleton); return new Model(meshes, gltfSkeleton); } @@ -51,16 +51,12 @@ public class ModelExporter return meshes; } - // TODO: Compose textures for use with these materials - /// Build placeholder materials for each of the material slots in the .mdl. - private static MaterialBuilder[] ConvertMaterials(MdlFile mdl) + /// Build materials for each of the material slots in the .mdl. + private static MaterialBuilder[] ConvertMaterials(MdlFile mdl, Dictionary rawMaterials) => mdl.Materials - .Select(name => - new MaterialBuilder(name) - .WithMetallicRoughnessShader() - .WithDoubleSide(true) - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, Vector4.One) - ) + // TODO: material generation should be fallible, which means this lookup should be a tryget, with a fallback. + // fallback can likely be a static on the material exporter. + .Select(name => MaterialExporter.Export(rawMaterials[name], name)) .ToArray(); /// Convert XIV skeleton data into a glTF-compatible node tree, with mappings. diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index f099a0e0..ccf56fe8 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,4 +1,5 @@ using Dalamud.Plugin.Services; +using Lumina.Data.Parsing; using OtterGui; using OtterGui.Tasks; using Penumbra.Collections.Manager; @@ -9,15 +10,22 @@ using Penumbra.GameData.Files; using Penumbra.GameData.Structs; using Penumbra.Import.Models.Export; using Penumbra.Import.Models.Import; +using Penumbra.Import.Textures; using Penumbra.Meta.Manipulations; using SharpGLTF.Scenes; -using SharpGLTF.Schema2; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; namespace Penumbra.Import.Models; -public sealed class ModelManager(IFramework framework, ActiveCollections collections, GamePathParser parser) : SingleTaskQueue, IDisposable +using Schema2 = SharpGLTF.Schema2; +using LuminaMaterial = Lumina.Models.Materials.Material; + +public sealed class ModelManager(IFramework framework, ActiveCollections collections, IDataManager gameData, GamePathParser parser, TextureManager textureManager) : SingleTaskQueue, IDisposable { private readonly IFramework _framework = framework; + private readonly IDataManager _gameData = gameData; + private readonly TextureManager _textureManager = textureManager; private readonly ConcurrentDictionary _tasks = new(); @@ -132,11 +140,18 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect public void Execute(CancellationToken cancel) { Penumbra.Log.Debug($"[GLTF Export] Exporting model to {outputPath}..."); + Penumbra.Log.Debug("[GLTF Export] Reading skeletons..."); var xivSkeletons = BuildSkeletons(cancel); + Penumbra.Log.Debug("[GLTF Export] Reading materials..."); + var materials = mdl.Materials.ToDictionary( + path => path, + path => BuildMaterial(path, cancel) + ); + Penumbra.Log.Debug("[GLTF Export] Converting model..."); - var model = ModelExporter.Export(mdl, xivSkeletons); + var model = ModelExporter.Export(mdl, xivSkeletons, materials); Penumbra.Log.Debug("[GLTF Export] Building scene..."); var scene = new SceneBuilder(); @@ -169,6 +184,48 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect delayTicks: pair.Index, cancellationToken: cancel); } + private MaterialExporter.Material BuildMaterial(string relativePath, CancellationToken cancel) + { + // TODO: this should probably be chosen in the export settings + var variantId = 1; + + var absolutePath = relativePath.StartsWith("/") + ? LuminaMaterial.ResolveRelativeMaterialPath(relativePath, variantId) + : relativePath; + + // TODO: this should be a recoverable warning - as should the one below it i think + if (absolutePath == null) + throw new Exception("Failed to resolve material path."); + + // TODO: collection lookup and such. this is currently in mdltab (readsklb), and should be wholesale moved in here. + var data = manager._gameData.GetFile(absolutePath); + if (data == null) + throw new Exception("Failed to fetch material game data."); + + var mtrl = new MtrlFile(data.Data); + + return new MaterialExporter.Material + { + Mtrl = mtrl, + Samplers = mtrl.ShaderPackage.Samplers + .Select(sampler => new MaterialExporter.Sampler + { + Usage = (TextureUsage)sampler.SamplerId, + Texture = ConvertImage(mtrl.Textures[sampler.TextureIndex], cancel), + }) + .ToArray(), + }; + } + + private Image ConvertImage(MtrlFile.Texture texture, CancellationToken cancel) + { + var (image, _) = manager._textureManager.Load(texture.Path); + var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; + if (pngImage == null) + throw new Exception("Failed to convert texture to png."); + return pngImage; + } + public bool Equals(IAction? other) { if (other is not ExportToGltfAction rhs) @@ -185,7 +242,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect public void Execute(CancellationToken cancel) { - var model = ModelRoot.Load(inputPath); + var model = Schema2.ModelRoot.Load(inputPath); Out = ModelImporter.Import(model); } From c8e58c08a064a948b3b3bc333caed3df20b55c4a Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 16:11:51 +1100 Subject: [PATCH 0364/1381] Compose character diffuse --- .../Import/Models/Export/MaterialExporter.cs | 40 +++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index ef417e35..4d085f18 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -34,19 +34,51 @@ public class MaterialExporter private static MaterialBuilder BuildCharacter(Material material, string name) { - // TODO: pixelbashing time - var sampler = material.Samplers + var table = material.Mtrl.Table; + var normal = material.Samplers .Where(s => s.Usage == TextureUsage.SamplerNormal) - .First(); + .First() + .Texture; + + var baseColorTarget = new Image(normal.Width, normal.Height); + normal.ProcessPixelRows(baseColorTarget, (sourceAccessor, targetAccessor) => + { + for (int y = 0; y < sourceAccessor.Height; y++) + { + var sourceRow = sourceAccessor.GetRowSpan(y); + var targetRow = targetAccessor.GetRowSpan(y); + + for (int x = 0; x < sourceRow.Length; x++) + { + var (smoothed, stepped) = GetTableRowIndices(sourceRow[x].A / 255f); + var prevRow = table[(int)MathF.Floor(smoothed)]; + var nextRow = table[(int)MathF.Ceiling(smoothed)]; + var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, smoothed % 1); + targetRow[x].FromVector4(new Vector4(lerpedDiffuse, 1)); + } + } + }); // TODO: clean up this name generation a bunch. probably a method. var imageName = name.Replace("/", ""); - var baseColor = BuildImage(sampler.Texture, $"{imageName}_basecolor"); + var baseColor = BuildImage(baseColorTarget, $"{imageName}_basecolor"); return BuildSharedBase(material, name) .WithBaseColor(baseColor); } + private static (float Smooth, float Stepped) GetTableRowIndices(float input) + { + // These calculations are ported from character.shpk. + var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) + * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) + + input * 15; + + var stepped = MathF.Floor(smoothed + 0.5f); + + return (smoothed, stepped); + } + private static MaterialBuilder BuildFallback(Material material, string name) { Penumbra.Log.Warning($"Unhandled shader package: {material.Mtrl.ShaderPackage.Name}"); From 509b4c8866bd0ed37a994d9237059b6be0bb3ec2 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 17:05:57 +1100 Subject: [PATCH 0365/1381] Wire up normals and opacity --- .../Import/Models/Export/MaterialExporter.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 4d085f18..d16e9367 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -50,11 +50,22 @@ public class MaterialExporter for (int x = 0; x < sourceRow.Length; x++) { + ref var sourcePixel = ref sourceRow[x]; + ref var targetPixel = ref targetRow[x]; + var (smoothed, stepped) = GetTableRowIndices(sourceRow[x].A / 255f); var prevRow = table[(int)MathF.Floor(smoothed)]; var nextRow = table[(int)MathF.Ceiling(smoothed)]; + + // Base colour (table[.a], .b) var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, smoothed % 1); - targetRow[x].FromVector4(new Vector4(lerpedDiffuse, 1)); + targetPixel.FromVector4(new Vector4(lerpedDiffuse, 1)); + targetPixel.A = sourcePixel.B; + + // Normal (.rg) + // TODO: we don't actually need alpha at all for normal, but _not_ using the existing rgba texture means I'll need a new one, with a new accessor. Think about it. + sourcePixel.B = byte.MaxValue; + sourcePixel.A = byte.MaxValue; } } }); @@ -62,9 +73,13 @@ public class MaterialExporter // TODO: clean up this name generation a bunch. probably a method. var imageName = name.Replace("/", ""); var baseColor = BuildImage(baseColorTarget, $"{imageName}_basecolor"); + var normalThing = BuildImage(normal, $"{imageName}_normal"); return BuildSharedBase(material, name) - .WithBaseColor(baseColor); + // NOTE: this isn't particularly precise to game behavior, but good enough for now. + .WithAlpha(AlphaMode.MASK, 0.5f) + .WithBaseColor(baseColor) + .WithNormal(normalThing); } private static (float Smooth, float Stepped) GetTableRowIndices(float input) From 96f40b7ddcb25f19bcd9fe306b473f7c5a9d5e3f Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 20:33:45 +1100 Subject: [PATCH 0366/1381] Expand to more general-purpose transform codepath --- .../Import/Models/Export/MaterialExporter.cs | 99 ++++++++++++------- 1 file changed, 66 insertions(+), 33 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index d16e9367..c08d954c 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -2,11 +2,15 @@ using Lumina.Data.Parsing; using Penumbra.GameData.Files; using SharpGLTF.Materials; using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; namespace Penumbra.Import.Models.Export; +using ImageSharpConfiguration = SixLabors.ImageSharp.Configuration; + public class MaterialExporter { // input stuff @@ -34,52 +38,81 @@ public class MaterialExporter private static MaterialBuilder BuildCharacter(Material material, string name) { + // TODO: handle models with an underlying diffuse var table = material.Mtrl.Table; + // TODO: this should probably be a dict var normal = material.Samplers .Where(s => s.Usage == TextureUsage.SamplerNormal) .First() .Texture; - var baseColorTarget = new Image(normal.Width, normal.Height); - normal.ProcessPixelRows(baseColorTarget, (sourceAccessor, targetAccessor) => + var operation = new CharacterOperation() { - for (int y = 0; y < sourceAccessor.Height; y++) - { - var sourceRow = sourceAccessor.GetRowSpan(y); - var targetRow = targetAccessor.GetRowSpan(y); - - for (int x = 0; x < sourceRow.Length; x++) - { - ref var sourcePixel = ref sourceRow[x]; - ref var targetPixel = ref targetRow[x]; - - var (smoothed, stepped) = GetTableRowIndices(sourceRow[x].A / 255f); - var prevRow = table[(int)MathF.Floor(smoothed)]; - var nextRow = table[(int)MathF.Ceiling(smoothed)]; - - // Base colour (table[.a], .b) - var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, smoothed % 1); - targetPixel.FromVector4(new Vector4(lerpedDiffuse, 1)); - targetPixel.A = sourcePixel.B; - - // Normal (.rg) - // TODO: we don't actually need alpha at all for normal, but _not_ using the existing rgba texture means I'll need a new one, with a new accessor. Think about it. - sourcePixel.B = byte.MaxValue; - sourcePixel.A = byte.MaxValue; - } - } - }); + Table = table, + Normal = normal, + BaseColor = new Image(normal.Width, normal.Height), + Emissive = new Image(normal.Width, normal.Height), + }; + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); // TODO: clean up this name generation a bunch. probably a method. var imageName = name.Replace("/", ""); - var baseColor = BuildImage(baseColorTarget, $"{imageName}_basecolor"); - var normalThing = BuildImage(normal, $"{imageName}_normal"); return BuildSharedBase(material, name) + // .WithSpecularGlossinessShader() + // .WithDiffuse() // NOTE: this isn't particularly precise to game behavior, but good enough for now. .WithAlpha(AlphaMode.MASK, 0.5f) - .WithBaseColor(baseColor) - .WithNormal(normalThing); + .WithBaseColor(BuildImage(operation.BaseColor, $"{imageName}_basecolor")) + .WithNormal(BuildImage(operation.Normal, $"{imageName}_normal")) + .WithEmissive(BuildImage(operation.Emissive, $"{imageName}_emissive"), Vector3.One, 1); + } + + private readonly struct CharacterOperation : IRowOperation + { + public required MtrlFile.ColorTable Table { get; init; } + + public required Image Normal { get; init; } + public required Image BaseColor { get; init; } + public required Image Emissive { get; init; } + + private Buffer2D NormalBuffer => Normal.Frames.RootFrame.PixelBuffer; + private Buffer2D BaseColorBuffer => BaseColor.Frames.RootFrame.PixelBuffer; + private Buffer2D EmissiveBuffer => Emissive.Frames.RootFrame.PixelBuffer; + + public void Invoke(int y) + { + var normalSpan = NormalBuffer.DangerousGetRowSpan(y); + var baseColorSpan = BaseColorBuffer.DangerousGetRowSpan(y); + var emissiveSpan = EmissiveBuffer.DangerousGetRowSpan(y); + + for (int x = 0; x < normalSpan.Length; x++) + { + ref var normalPixel = ref normalSpan[x]; + ref var baseColorPixel = ref baseColorSpan[x]; + ref var emissivePixel = ref emissiveSpan[x]; + + // Table row data (.a) + var (smoothed, stepped) = GetTableRowIndices(normalPixel.A / 255f); + var weight = smoothed % 1; + var prevRow = Table[(int)MathF.Floor(smoothed)]; + var nextRow = Table[(int)MathF.Ceiling(smoothed)]; + + // Base colour (table, .b) + var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, weight); + baseColorPixel.FromVector4(new Vector4(lerpedDiffuse, 1)); + baseColorPixel.A = normalPixel.B; + + // Emissive (table) + var lerpedEmissive = Vector3.Lerp(prevRow.Emissive, nextRow.Emissive, weight); + emissivePixel.FromVector4(new Vector4(lerpedEmissive, 1)); + + // Normal (.rg) + // TODO: we don't actually need alpha at all for normal, but _not_ using the existing rgba texture means I'll need a new one, with a new accessor. Think about it. + normalPixel.B = byte.MaxValue; + normalPixel.A = byte.MaxValue; + } + } } private static (float Smooth, float Stepped) GetTableRowIndices(float input) @@ -112,7 +145,7 @@ public class MaterialExporter .WithDoubleSide(showBackfaces); } - private static ImageBuilder BuildImage(Image image, string name) + private static ImageBuilder BuildImage(Image image, string name) { byte[] textureBytes; using (var memoryStream = new MemoryStream()) From 74ffc56d6c48d10bd91fee053ded67baa8647418 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 20:48:15 +1100 Subject: [PATCH 0367/1381] Fix errors with same name expanding together --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index c92e2926..4ac789ad 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -138,14 +138,14 @@ public partial class ModEditWindow using var frame = ImRaii.FramedGroup("Exceptions", size, headerPreIcon: FontAwesomeIcon.TimesCircle, borderColor: Colors.RegexWarningBorder); var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; - foreach (var exception in tab.IoExceptions) + foreach (var (exception, index) in tab.IoExceptions.WithIndex()) { var message = $"{exception.GetType().Name}: {exception.Message}"; var textSize = ImGui.CalcTextSize(message).X; if (textSize > spaceAvail) message = message.Substring(0, (int)Math.Floor(message.Length * (spaceAvail / textSize))) + "..."; - using (var exceptionNode = ImRaii.TreeNode(message)) + using (var exceptionNode = ImRaii.TreeNode($"{message}###exception{index}")) { if (exceptionNode) ImGuiUtil.TextWrapped(exception.ToString()); From 4572cb83f0f1b311510536d5dd1622e98d0d0517 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 20:48:46 +1100 Subject: [PATCH 0368/1381] Move table calcs into struct --- .../Import/Models/Export/MaterialExporter.cs | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index c08d954c..437b57f7 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -93,18 +93,17 @@ public class MaterialExporter ref var emissivePixel = ref emissiveSpan[x]; // Table row data (.a) - var (smoothed, stepped) = GetTableRowIndices(normalPixel.A / 255f); - var weight = smoothed % 1; - var prevRow = Table[(int)MathF.Floor(smoothed)]; - var nextRow = Table[(int)MathF.Ceiling(smoothed)]; + var tableRow = GetTableRowIndices(normalPixel.A / 255f); + var prevRow = Table[tableRow.Previous]; + var nextRow = Table[tableRow.Next]; // Base colour (table, .b) - var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, weight); + var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, tableRow.Weight); baseColorPixel.FromVector4(new Vector4(lerpedDiffuse, 1)); baseColorPixel.A = normalPixel.B; // Emissive (table) - var lerpedEmissive = Vector3.Lerp(prevRow.Emissive, nextRow.Emissive, weight); + var lerpedEmissive = Vector3.Lerp(prevRow.Emissive, nextRow.Emissive, tableRow.Weight); emissivePixel.FromVector4(new Vector4(lerpedEmissive, 1)); // Normal (.rg) @@ -115,7 +114,7 @@ public class MaterialExporter } } - private static (float Smooth, float Stepped) GetTableRowIndices(float input) + private static TableRow GetTableRowIndices(float input) { // These calculations are ported from character.shpk. var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) @@ -124,7 +123,21 @@ public class MaterialExporter var stepped = MathF.Floor(smoothed + 0.5f); - return (smoothed, stepped); + return new TableRow + { + Stepped = (int)stepped, + Previous = (int)MathF.Floor(smoothed), + Next = (int)MathF.Ceiling(smoothed), + Weight = smoothed % 1, + }; + } + + private ref struct TableRow + { + public int Stepped; + public int Previous; + public int Next; + public float Weight; } private static MaterialBuilder BuildFallback(Material material, string name) From db2081f14d944283f890244f50f1acb4b84ff3da Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 21:36:42 +1100 Subject: [PATCH 0369/1381] More refactors of operation, extract specular color --- .../Import/Models/Export/MaterialExporter.cs | 44 +++++++++---------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 437b57f7..de2f1425 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -46,65 +46,63 @@ public class MaterialExporter .First() .Texture; - var operation = new CharacterOperation() - { - Table = table, - Normal = normal, - BaseColor = new Image(normal.Width, normal.Height), - Emissive = new Image(normal.Width, normal.Height), - }; + var operation = new ProcessCharacterNormalOperation(normal, table); ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); // TODO: clean up this name generation a bunch. probably a method. - var imageName = name.Replace("/", ""); + var imageName = name.Replace("/", "").Replace(".mtrl", ""); return BuildSharedBase(material, name) - // .WithSpecularGlossinessShader() - // .WithDiffuse() // NOTE: this isn't particularly precise to game behavior, but good enough for now. .WithAlpha(AlphaMode.MASK, 0.5f) .WithBaseColor(BuildImage(operation.BaseColor, $"{imageName}_basecolor")) .WithNormal(BuildImage(operation.Normal, $"{imageName}_normal")) + .WithSpecularColor(BuildImage(operation.Specular, $"{imageName}_specular")) .WithEmissive(BuildImage(operation.Emissive, $"{imageName}_emissive"), Vector3.One, 1); } - private readonly struct CharacterOperation : IRowOperation + // TODO: It feels a little silly to request the entire normal here when extrating the normal only needs some of the components. + // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. + private readonly struct ProcessCharacterNormalOperation(Image normal, MtrlFile.ColorTable table) : IRowOperation { - public required MtrlFile.ColorTable Table { get; init; } - - public required Image Normal { get; init; } - public required Image BaseColor { get; init; } - public required Image Emissive { get; init; } + public Image Normal { get; private init; } = normal.Clone(); + public Image BaseColor { get; private init; } = new Image(normal.Width, normal.Height); + public Image Specular { get; private init; } = new Image(normal.Width, normal.Height); + public Image Emissive { get; private init; } = new Image(normal.Width, normal.Height); private Buffer2D NormalBuffer => Normal.Frames.RootFrame.PixelBuffer; private Buffer2D BaseColorBuffer => BaseColor.Frames.RootFrame.PixelBuffer; + private Buffer2D SpecularBuffer => Specular.Frames.RootFrame.PixelBuffer; private Buffer2D EmissiveBuffer => Emissive.Frames.RootFrame.PixelBuffer; public void Invoke(int y) { var normalSpan = NormalBuffer.DangerousGetRowSpan(y); var baseColorSpan = BaseColorBuffer.DangerousGetRowSpan(y); + var specularSpan = SpecularBuffer.DangerousGetRowSpan(y); var emissiveSpan = EmissiveBuffer.DangerousGetRowSpan(y); for (int x = 0; x < normalSpan.Length; x++) { ref var normalPixel = ref normalSpan[x]; - ref var baseColorPixel = ref baseColorSpan[x]; - ref var emissivePixel = ref emissiveSpan[x]; // Table row data (.a) var tableRow = GetTableRowIndices(normalPixel.A / 255f); - var prevRow = Table[tableRow.Previous]; - var nextRow = Table[tableRow.Next]; + var prevRow = table[tableRow.Previous]; + var nextRow = table[tableRow.Next]; // Base colour (table, .b) var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, tableRow.Weight); - baseColorPixel.FromVector4(new Vector4(lerpedDiffuse, 1)); - baseColorPixel.A = normalPixel.B; + baseColorSpan[x].FromVector4(new Vector4(lerpedDiffuse, 1)); + baseColorSpan[x].A = normalPixel.B; + + // Specular (table) + var lerpedSpecularColor = Vector3.Lerp(prevRow.Specular, nextRow.Specular, tableRow.Weight); + specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, 1)); // Emissive (table) var lerpedEmissive = Vector3.Lerp(prevRow.Emissive, nextRow.Emissive, tableRow.Weight); - emissivePixel.FromVector4(new Vector4(lerpedEmissive, 1)); + emissiveSpan[x].FromVector4(new Vector4(lerpedEmissive, 1)); // Normal (.rg) // TODO: we don't actually need alpha at all for normal, but _not_ using the existing rgba texture means I'll need a new one, with a new accessor. Think about it. From e8fd452b8f12d23a0e30a6c684919edaac1f32fe Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 22:16:47 +1100 Subject: [PATCH 0370/1381] Improve file reading --- .../Import/Models/Export/MaterialExporter.cs | 19 ++++-------- Penumbra/Import/Models/ModelManager.cs | 30 +++++++----------- .../ModEditWindow.Models.MdlTab.cs | 31 ++++++++++--------- 3 files changed, 34 insertions(+), 46 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index de2f1425..dee386df 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -13,22 +13,16 @@ using ImageSharpConfiguration = SixLabors.ImageSharp.Configuration; public class MaterialExporter { - // input stuff public struct Material { public MtrlFile Mtrl; - public Sampler[] Samplers; + public Dictionary> Textures; // variant? } - public struct Sampler - { - public TextureUsage Usage; - public Image Texture; - } - public static MaterialBuilder Export(Material material, string name) { + Penumbra.Log.Debug($"Exporting material \"{name}\"."); return material.Mtrl.ShaderPackage.Name switch { "character.shpk" => BuildCharacter(material, name), @@ -40,11 +34,10 @@ public class MaterialExporter { // TODO: handle models with an underlying diffuse var table = material.Mtrl.Table; - // TODO: this should probably be a dict - var normal = material.Samplers - .Where(s => s.Usage == TextureUsage.SamplerNormal) - .First() - .Texture; + + // TODO: there's a few normal usages i should check, i think. + // TODO: tryget + var normal = material.Textures[TextureUsage.SamplerNormal]; var operation = new ProcessCharacterNormalOperation(normal, table); ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index ccf56fe8..4f652436 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -39,8 +39,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(MdlFile mdl, IEnumerable sklbs, string outputPath) - => Enqueue(new ExportToGltfAction(this, mdl, sklbs, outputPath)); + public Task ExportToGltf(MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + => Enqueue(new ExportToGltfAction(this, mdl, sklbPaths, read, outputPath)); public Task ImportGltf(string inputPath) { @@ -134,7 +134,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return task; } - private class ExportToGltfAction(ModelManager manager, MdlFile mdl, IEnumerable sklbs, string outputPath) + private class ExportToGltfAction(ModelManager manager, MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) : IAction { public void Execute(CancellationToken cancel) @@ -166,7 +166,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect /// Attempt to read out the pertinent information from a .sklb. private IEnumerable BuildSkeletons(CancellationToken cancel) { - var havokTasks = sklbs + var havokTasks = sklbPaths + .Select(path => new SklbFile(read(path))) .WithIndex() .Select(CreateHavokTask) .ToArray(); @@ -197,29 +198,22 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect if (absolutePath == null) throw new Exception("Failed to resolve material path."); - // TODO: collection lookup and such. this is currently in mdltab (readsklb), and should be wholesale moved in here. - var data = manager._gameData.GetFile(absolutePath); - if (data == null) - throw new Exception("Failed to fetch material game data."); - - var mtrl = new MtrlFile(data.Data); + var mtrl = new MtrlFile(read(absolutePath)); return new MaterialExporter.Material { Mtrl = mtrl, - Samplers = mtrl.ShaderPackage.Samplers - .Select(sampler => new MaterialExporter.Sampler - { - Usage = (TextureUsage)sampler.SamplerId, - Texture = ConvertImage(mtrl.Textures[sampler.TextureIndex], cancel), - }) - .ToArray(), + Textures = mtrl.ShaderPackage.Samplers.ToDictionary( + sampler => (TextureUsage)sampler.SamplerId, + sampler => ConvertImage(mtrl.Textures[sampler.TextureIndex], cancel) + ), }; } private Image ConvertImage(MtrlFile.Texture texture, CancellationToken cancel) { - var (image, _) = manager._textureManager.Load(texture.Path); + using var textureData = new MemoryStream(read(texture.Path)); + var image = TexFileParser.Parse(textureData); var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; if (pngImage == null) throw new Exception("Failed to convert texture to png."); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index cdaf399f..f79d161e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -116,11 +116,10 @@ public partial class ModEditWindow /// .mdl game path to resolve satellite files such as skeletons relative to. public void Export(string outputPath, Utf8GamePath mdlPath) { - IEnumerable skeletons; + IEnumerable sklbPaths; try { - var sklbPaths = _edit._models.ResolveSklbsForMdl(mdlPath.ToString(), GetCurrentEstManipulations()); - skeletons = sklbPaths.Select(ReadSklb).ToArray(); + sklbPaths = _edit._models.ResolveSklbsForMdl(mdlPath.ToString(), GetCurrentEstManipulations()); } catch (Exception exception) { @@ -129,7 +128,7 @@ public partial class ModEditWindow } PendingIo = true; - _edit._models.ExportToGltf(Mdl, skeletons, outputPath) + _edit._models.ExportToGltf(Mdl, sklbPaths, ReadFile, outputPath) .ContinueWith(task => { RecordIoExceptions(task.Exception); @@ -219,22 +218,24 @@ public partial class ModEditWindow Exception other => [other], }; } - - /// Read a .sklb from the active collection or game. - /// Game path to the .sklb to load. - private SklbFile ReadSklb(string sklbPath) + + /// Read a file from the active collection or game. + /// Game path to the file to load. + // TODO: Also look up files within the current mod regardless of mod state? + private byte[] ReadFile(string path) { // TODO: if cross-collection lookups are turned off, this conversion can be skipped - if (!Utf8GamePath.FromString(sklbPath, out var utf8SklbPath, true)) - throw new Exception($"Resolved skeleton path {sklbPath} could not be converted to a game path."); + if (!Utf8GamePath.FromString(path, out var utf8SklbPath, true)) + throw new Exception($"Resolved path {path} could not be converted to a game path."); var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8SklbPath); // TODO: is it worth trying to use streams for these instead? I'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... - var bytes = resolvedPath == null ? _edit._gameData.GetFile(sklbPath)?.Data : File.ReadAllBytes(resolvedPath.Value.ToPath()); - return bytes != null - ? new SklbFile(bytes) - : throw new Exception( - $"Resolved skeleton path {sklbPath} could not be found. If modded, is it enabled in the current collection?"); + var bytes = resolvedPath == null + ? _edit._gameData.GetFile(path)?.Data + : File.ReadAllBytes(resolvedPath.Value.ToPath()); + + return bytes ?? throw new Exception( + $"Resolved path {path} could not be found. If modded, is it enabled in the current collection?"); } /// Remove the material given by the index. From 2fa72727622fb872d2c65f761892540d060a389b Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 13 Jan 2024 23:52:26 +1100 Subject: [PATCH 0371/1381] Add support for explicit diffuse + specular textures --- .../Import/Models/Export/MaterialExporter.cs | 55 +++++++++++++++++-- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index dee386df..3d274ff9 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -6,6 +6,7 @@ using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; namespace Penumbra.Import.Models.Export; @@ -32,25 +33,37 @@ public class MaterialExporter private static MaterialBuilder BuildCharacter(Material material, string name) { - // TODO: handle models with an underlying diffuse var table = material.Mtrl.Table; // TODO: there's a few normal usages i should check, i think. - // TODO: tryget var normal = material.Textures[TextureUsage.SamplerNormal]; var operation = new ProcessCharacterNormalOperation(normal, table); ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); + var baseColor = operation.BaseColor; + if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) + { + MultiplyOperation.Execute(diffuse, baseColor); + baseColor = diffuse; + } + + // TODO: what about the two specularmaps? + var specular = operation.Specular; + if (material.Textures.TryGetValue(TextureUsage.SamplerSpecular, out var newSpecular)) + { + MultiplyOperation.Execute(newSpecular, specular); + } + // TODO: clean up this name generation a bunch. probably a method. var imageName = name.Replace("/", "").Replace(".mtrl", ""); return BuildSharedBase(material, name) // NOTE: this isn't particularly precise to game behavior, but good enough for now. .WithAlpha(AlphaMode.MASK, 0.5f) - .WithBaseColor(BuildImage(operation.BaseColor, $"{imageName}_basecolor")) + .WithBaseColor(BuildImage(baseColor, $"{imageName}_basecolor")) .WithNormal(BuildImage(operation.Normal, $"{imageName}_normal")) - .WithSpecularColor(BuildImage(operation.Specular, $"{imageName}_specular")) + .WithSpecularColor(BuildImage(specular, $"{imageName}_specular")) .WithEmissive(BuildImage(operation.Emissive, $"{imageName}_emissive"), Vector3.One, 1); } @@ -105,6 +118,40 @@ public class MaterialExporter } } + private readonly struct MultiplyOperation + { + public static void Execute(Image target, Image multiplier) + where TPixel1 : unmanaged, IPixel + where TPixel2 : unmanaged, IPixel + { + // Ensure the images are the same size + var (small, large) = target.Width < multiplier.Width && target.Height < multiplier.Height + ? ((Image)target, (Image)multiplier) + : (multiplier, target); + small.Mutate(context => context.Resize(large.Width, large.Height)); + + var operation = new MultiplyOperation(target, multiplier); + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, target.Bounds(), in operation); + } + } + + private readonly struct MultiplyOperation(Image target, Image multiplier) : IRowOperation + where TPixel1 : unmanaged, IPixel + where TPixel2 : unmanaged, IPixel + { + + public void Invoke(int y) + { + var targetSpan = target.Frames.RootFrame.PixelBuffer.DangerousGetRowSpan(y); + var multiplierSpan = multiplier.Frames.RootFrame.PixelBuffer.DangerousGetRowSpan(y); + + for (int x = 0; x < targetSpan.Length; x++) + { + targetSpan[x].FromVector4(targetSpan[x].ToVector4() * multiplierSpan[x].ToVector4()); + } + } + } + private static TableRow GetTableRowIndices(float input) { // These calculations are ported from character.shpk. From ca58c81bcebc051b0ac8e25255e5bc28095adee6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 00:06:16 +1100 Subject: [PATCH 0372/1381] Add characterglass support --- Penumbra/Import/Models/Export/MaterialExporter.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 3d274ff9..eff5f835 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -26,8 +26,10 @@ public class MaterialExporter Penumbra.Log.Debug($"Exporting material \"{name}\"."); return material.Mtrl.ShaderPackage.Name switch { - "character.shpk" => BuildCharacter(material, name), - _ => BuildFallback(material, name), + // NOTE: this isn't particularly precise to game behavior (it has some fade around high opacity), but good enough for now. + "character.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), + "characterglass.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.BLEND), + _ => BuildFallback(material, name), }; } @@ -59,8 +61,6 @@ public class MaterialExporter var imageName = name.Replace("/", "").Replace(".mtrl", ""); return BuildSharedBase(material, name) - // NOTE: this isn't particularly precise to game behavior, but good enough for now. - .WithAlpha(AlphaMode.MASK, 0.5f) .WithBaseColor(BuildImage(baseColor, $"{imageName}_basecolor")) .WithNormal(BuildImage(operation.Normal, $"{imageName}_normal")) .WithSpecularColor(BuildImage(specular, $"{imageName}_specular")) From 2d8b7efc006ad6303754900b941c0b1b21899054 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 13 Jan 2024 14:06:45 +0100 Subject: [PATCH 0373/1381] Some cleanup. --- Penumbra/Mods/Editor/DuplicateManager.cs | 68 +++++++-------- Penumbra/Mods/Editor/FileRegistry.cs | 4 +- Penumbra/Mods/Editor/ModMerger.cs | 10 +-- Penumbra/UI/AdvancedWindow/FileEditor.cs | 1 + .../UI/AdvancedWindow/ModEditWindow.Files.cs | 1 + Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 85 +++++++++---------- 6 files changed, 78 insertions(+), 91 deletions(-) diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 47c34ce5..4773d840 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; @@ -5,25 +6,15 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class DuplicateManager +public class DuplicateManager(ModManager modManager, SaveService saveService, Configuration config) { - private readonly Configuration _config; - private readonly SaveService _saveService; - private readonly ModManager _modManager; - private readonly SHA256 _hasher = SHA256.Create(); - private readonly List<(FullPath[] Paths, long Size, byte[] Hash)> _duplicates = new(); - - public DuplicateManager(ModManager modManager, SaveService saveService, Configuration config) - { - _modManager = modManager; - _saveService = saveService; - _config = config; - } + private readonly SHA256 _hasher = SHA256.Create(); + private readonly List<(FullPath[] Paths, long Size, byte[] Hash)> _duplicates = []; public IReadOnlyList<(FullPath[] Paths, long Size, byte[] Hash)> Duplicates => _duplicates; - public long SavedSpace { get; private set; } = 0; + public long SavedSpace { get; private set; } public Task Worker { get; private set; } = Task.CompletedTask; private CancellationTokenSource _cancellationTokenSource = new(); @@ -68,6 +59,19 @@ public class DuplicateManager private void HandleDuplicate(Mod mod, FullPath duplicate, FullPath remaining, bool useModManager) { + ModEditor.ApplyToAllOptions(mod, HandleSubMod); + + try + { + File.Delete(duplicate.FullName); + } + catch (Exception e) + { + Penumbra.Log.Error($"[DeleteDuplicates] Could not delete duplicate {duplicate.FullName} of {remaining.FullName}:\n{e}"); + } + + return; + void HandleSubMod(ISubMod subMod, int groupIdx, int optionIdx) { var changes = false; @@ -78,26 +82,15 @@ public class DuplicateManager if (useModManager) { - _modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict); + modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict); } else { var sub = (SubMod)subMod; sub.FileData = dict; - _saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); + saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); } } - - ModEditor.ApplyToAllOptions(mod, HandleSubMod); - - try - { - File.Delete(duplicate.FullName); - } - catch (Exception e) - { - Penumbra.Log.Error($"[DeleteDuplicates] Could not delete duplicate {duplicate.FullName} of {remaining.FullName}:\n{e}"); - } } private static FullPath ChangeDuplicatePath(Mod mod, FullPath value, FullPath from, FullPath to, Utf8GamePath key, ref bool changes) @@ -199,15 +192,6 @@ public class DuplicateManager } } - public static bool CompareHashes(byte[] f1, byte[] f2) - => StructuralComparisons.StructuralEqualityComparer.Equals(f1, f2); - - public byte[] ComputeHash(FullPath f) - { - using var stream = File.OpenRead(f.FullName); - return _hasher.ComputeHash(stream); - } - /// /// Recursively delete all empty directories starting from the given directory. /// Deletes inner directories first, so that a tree of empty directories is actually deleted. @@ -232,14 +216,13 @@ public class DuplicateManager } } - /// Deduplicate a mod simply by its directory without any confirmation or waiting time. internal void DeduplicateMod(DirectoryInfo modDirectory) { try { var mod = new Mod(modDirectory); - _modManager.Creator.ReloadMod(mod, true, out _); + modManager.Creator.ReloadMod(mod, true, out _); Clear(); var files = new ModFileCollection(); @@ -252,4 +235,13 @@ public class DuplicateManager Penumbra.Log.Warning($"Could not deduplicate mod {modDirectory.Name}:\n{e}"); } } + + private static bool CompareHashes(byte[] f1, byte[] f2) + => StructuralComparisons.StructuralEqualityComparer.Equals(f1, f2); + + private byte[] ComputeHash(FullPath f) + { + using var stream = File.OpenRead(f.FullName); + return _hasher.ComputeHash(stream); + } } diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index a223b51e..96d027b3 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -1,11 +1,11 @@ using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; public class FileRegistry : IEquatable { - public readonly List<(ISubMod, Utf8GamePath)> SubModUsage = new(); + public readonly List<(ISubMod, Utf8GamePath)> SubModUsage = []; public FullPath File { get; private init; } public Utf8RelPath RelPath { get; private init; } public long FileSize { get; private init; } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 1dfe9e76..f5d0e4a4 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -29,12 +29,12 @@ public class ModMerger : IDisposable public string OptionGroupName = "Merges"; public string OptionName = string.Empty; - private readonly Dictionary _fileToFile = new(); - private readonly HashSet _createdDirectories = new(); - private readonly HashSet _createdGroups = new(); - private readonly HashSet _createdOptions = new(); + private readonly Dictionary _fileToFile = []; + private readonly HashSet _createdDirectories = []; + private readonly HashSet _createdGroups = []; + private readonly HashSet _createdOptions = []; - public readonly HashSet SelectedOptions = new(); + public readonly HashSet SelectedOptions = []; public readonly IReadOnlyList Warnings = new List(); public Exception? Error { get; private set; } diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 4783e76b..16cacaa4 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -9,6 +9,7 @@ using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.GameData.Files; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 4a193591..bae23729 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -4,6 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index 7d4fa96f..1df814da 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -9,22 +9,14 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; -public class ModMergeTab +public class ModMergeTab(ModMerger modMerger) { - private readonly ModMerger _modMerger; - private readonly ModCombo _modCombo; - - private string _newModName = string.Empty; - - public ModMergeTab(ModMerger modMerger) - { - _modMerger = modMerger; - _modCombo = new ModCombo(() => _modMerger.ModsWithoutCurrent.ToList()); - } + private readonly ModCombo _modCombo = new(() => modMerger.ModsWithoutCurrent.ToList()); + private string _newModName = string.Empty; public void Draw() { - if (_modMerger.MergeFromMod == null) + if (modMerger.MergeFromMod == null) return; using var tab = ImRaii.TabItem("Merge Mods"); @@ -54,23 +46,23 @@ public class ModMergeTab { using var bigGroup = ImRaii.Group(); ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted($"Merge {_modMerger.MergeFromMod!.Name} into "); + ImGui.TextUnformatted($"Merge {modMerger.MergeFromMod!.Name} into "); ImGui.SameLine(); DrawCombo(size - ImGui.GetItemRectSize().X - ImGui.GetStyle().ItemSpacing.X); var width = ImGui.GetItemRectSize(); using (var g = ImRaii.Group()) { - using var disabled = ImRaii.Disabled(_modMerger.MergeFromMod.HasOptions); + using var disabled = ImRaii.Disabled(modMerger.MergeFromMod.HasOptions); var buttonWidth = (size - ImGui.GetStyle().ItemSpacing.X) / 2; using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 1); - var group = _modMerger.MergeToMod?.Groups.FirstOrDefault(g => g.Name == _modMerger.OptionGroupName); - var color = group != null || _modMerger.OptionGroupName.Length == 0 && _modMerger.OptionName.Length == 0 + var group = modMerger.MergeToMod?.Groups.FirstOrDefault(g => g.Name == modMerger.OptionGroupName); + var color = group != null || modMerger.OptionGroupName.Length == 0 && modMerger.OptionName.Length == 0 ? Colors.PressEnterWarningBg : Colors.DiscordColor; using var c = ImRaii.PushColor(ImGuiCol.Border, color); ImGui.SetNextItemWidth(buttonWidth); - ImGui.InputTextWithHint("##optionGroupInput", "Target Option Group", ref _modMerger.OptionGroupName, 64); + ImGui.InputTextWithHint("##optionGroupInput", "Target Option Group", ref modMerger.OptionGroupName, 64); ImGuiUtil.HoverTooltip( "The name of the new or existing option group to find or create the option in. Leave both group and option name blank for the default option.\n" + "A red border indicates an existing option group, a blue border indicates a new one."); @@ -79,29 +71,29 @@ public class ModMergeTab color = color == Colors.DiscordColor ? Colors.DiscordColor - : group == null || group.Any(o => o.Name == _modMerger.OptionName) + : group == null || group.Any(o => o.Name == modMerger.OptionName) ? Colors.PressEnterWarningBg : Colors.DiscordColor; c.Push(ImGuiCol.Border, color); ImGui.SetNextItemWidth(buttonWidth); - ImGui.InputTextWithHint("##optionInput", "Target Option Name", ref _modMerger.OptionName, 64); + ImGui.InputTextWithHint("##optionInput", "Target Option Name", ref modMerger.OptionName, 64); ImGuiUtil.HoverTooltip( "The name of the new or existing option to merge this mod into. Leave both group and option name blank for the default option.\n" + "A red border indicates an existing option, a blue border indicates a new one."); } - if (_modMerger.MergeFromMod.HasOptions) + if (modMerger.MergeFromMod.HasOptions) ImGuiUtil.HoverTooltip("You can only specify a target option if the source mod has no true options itself.", ImGuiHoveredFlags.AllowWhenDisabled); if (ImGuiUtil.DrawDisabledButton("Merge", new Vector2(size, 0), - _modMerger.CanMerge ? string.Empty : "Please select a target mod different from the current mod.", !_modMerger.CanMerge)) - _modMerger.Merge(); + modMerger.CanMerge ? string.Empty : "Please select a target mod different from the current mod.", !modMerger.CanMerge)) + modMerger.Merge(); } private void DrawMergeIntoDesc() { - ImGuiUtil.TextWrapped(_modMerger.MergeFromMod!.HasOptions + ImGuiUtil.TextWrapped(modMerger.MergeFromMod!.HasOptions ? "The currently selected mod has options.\n\nThis means, that all of those options will be merged into the target. If merging an option is not possible due to the redirections already existing in an existing option, it will revert all changes and break." : "The currently selected mod has no true options.\n\nThis means that you can select an existing or new option to merge all its changes into in the target mod. On failure to merge into an existing option, all changes will be reverted."); } @@ -110,7 +102,7 @@ public class ModMergeTab { _modCombo.Draw("##ModSelection", _modCombo.CurrentSelection?.Name.Text ?? "Select the target Mod...", string.Empty, width, ImGui.GetTextLineHeight()); - _modMerger.MergeToMod = _modCombo.CurrentSelection; + modMerger.MergeToMod = _modCombo.CurrentSelection; } private void DrawSplitOff(float size) @@ -121,24 +113,24 @@ public class ModMergeTab ImGuiUtil.HoverTooltip("Choose a name for the newly created mod. This does not need to be unique."); var tt = _newModName.Length == 0 ? "Please enter a name for the newly created mod first." - : _modMerger.SelectedOptions.Count == 0 + : modMerger.SelectedOptions.Count == 0 ? "Please select at least one option to split off." : string.Empty; var buttonText = - $"Split Off {_modMerger.SelectedOptions.Count} Option{(_modMerger.SelectedOptions.Count > 1 ? "s" : string.Empty)}###SplitOff"; + $"Split Off {modMerger.SelectedOptions.Count} Option{(modMerger.SelectedOptions.Count > 1 ? "s" : string.Empty)}###SplitOff"; if (ImGuiUtil.DrawDisabledButton(buttonText, new Vector2(size, 0), tt, tt.Length > 0)) - _modMerger.SplitIntoMod(_newModName); + modMerger.SplitIntoMod(_newModName); ImGui.Dummy(Vector2.One); var buttonSize = new Vector2((size - 2 * ImGui.GetStyle().ItemSpacing.X) / 3, 0); if (ImGui.Button("Select All", buttonSize)) - _modMerger.SelectedOptions.UnionWith(_modMerger.MergeFromMod!.AllSubMods); + modMerger.SelectedOptions.UnionWith(modMerger.MergeFromMod!.AllSubMods); ImGui.SameLine(); if (ImGui.Button("Unselect All", buttonSize)) - _modMerger.SelectedOptions.Clear(); + modMerger.SelectedOptions.Clear(); ImGui.SameLine(); if (ImGui.Button("Invert Selection", buttonSize)) - _modMerger.SelectedOptions.SymmetricExceptWith(_modMerger.MergeFromMod!.AllSubMods); + modMerger.SelectedOptions.SymmetricExceptWith(modMerger.MergeFromMod!.AllSubMods); DrawOptionTable(size); } @@ -152,8 +144,8 @@ public class ModMergeTab private void DrawOptionTable(float size) { - var options = _modMerger.MergeFromMod!.AllSubMods.ToList(); - var height = _modMerger.Warnings.Count == 0 && _modMerger.Error == null + var options = modMerger.MergeFromMod!.AllSubMods.ToList(); + var height = modMerger.Warnings.Count == 0 && modMerger.Error == null ? ImGui.GetContentRegionAvail().Y - 3 * ImGui.GetFrameHeightWithSpacing() : 8 * ImGui.GetFrameHeightWithSpacing(); height = Math.Min(height, (options.Count + 1) * ImGui.GetFrameHeightWithSpacing()); @@ -178,15 +170,7 @@ public class ModMergeTab foreach (var (option, idx) in options.WithIndex()) { using var id = ImRaii.PushId(idx); - var selected = _modMerger.SelectedOptions.Contains(option); - - void Handle(SubMod option2, bool selected2) - { - if (selected2) - _modMerger.SelectedOptions.Add(option2); - else - _modMerger.SelectedOptions.Remove(option2); - } + var selected = modMerger.SelectedOptions.Contains(option); ImGui.TableNextColumn(); if (ImGui.Checkbox("##check", ref selected)) @@ -222,34 +206,43 @@ public class ModMergeTab ImGuiUtil.RightAlign(option.FileSwapData.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); ImGui.TableNextColumn(); ImGuiUtil.RightAlign(option.Manipulations.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); + continue; + + void Handle(SubMod option2, bool selected2) + { + if (selected2) + modMerger.SelectedOptions.Add(option2); + else + modMerger.SelectedOptions.Remove(option2); + } } } private void DrawWarnings() { - if (_modMerger.Warnings.Count == 0) + if (modMerger.Warnings.Count == 0) return; ImGui.Separator(); ImGui.Dummy(Vector2.One); using var color = ImRaii.PushColor(ImGuiCol.Text, Colors.TutorialBorder); - foreach (var warning in _modMerger.Warnings.SkipLast(1)) + foreach (var warning in modMerger.Warnings.SkipLast(1)) { ImGuiUtil.TextWrapped(warning); ImGui.Separator(); } - ImGuiUtil.TextWrapped(_modMerger.Warnings[^1]); + ImGuiUtil.TextWrapped(modMerger.Warnings[^1]); } private void DrawError() { - if (_modMerger.Error == null) + if (modMerger.Error == null) return; ImGui.Separator(); ImGui.Dummy(Vector2.One); using var color = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); - ImGuiUtil.TextWrapped(_modMerger.Error.ToString()); + ImGuiUtil.TextWrapped(modMerger.Error.ToString()); } } From f71096f8b07fd69f8a505a7a68628784da45a125 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 00:38:28 +1100 Subject: [PATCH 0374/1381] Handle mask ambient occlusion --- .../Import/Models/Export/MaterialExporter.cs | 34 +++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index eff5f835..97bfb6bc 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -43,28 +43,50 @@ public class MaterialExporter var operation = new ProcessCharacterNormalOperation(normal, table); ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); - var baseColor = operation.BaseColor; + Image baseColor = operation.BaseColor; if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) { - MultiplyOperation.Execute(diffuse, baseColor); + MultiplyOperation.Execute(diffuse, operation.BaseColor); baseColor = diffuse; } // TODO: what about the two specularmaps? - var specular = operation.Specular; - if (material.Textures.TryGetValue(TextureUsage.SamplerSpecular, out var newSpecular)) + Image specular = operation.Specular; + if (material.Textures.TryGetValue(TextureUsage.SamplerSpecular, out var specularTexture)) { - MultiplyOperation.Execute(newSpecular, specular); + MultiplyOperation.Execute(specularTexture, operation.Specular); + specular = specularTexture; + } + + Image? occlusion = null; + if (material.Textures.TryGetValue(TextureUsage.SamplerMask, out var maskTexture)) + { + // Extract the red channel for ambient occlusion. + maskTexture.Mutate(context => context.Filter(new ColorMatrix( + 1f, 1f, 1f, 0f, + 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 0f, + 0f, 0f, 0f, 1f, + 0f, 0f, 0f, 0f + ))); + occlusion = maskTexture; + + // TODO: handle other textures stored in the mask? } // TODO: clean up this name generation a bunch. probably a method. var imageName = name.Replace("/", "").Replace(".mtrl", ""); - return BuildSharedBase(material, name) + var materialBuilder = BuildSharedBase(material, name) .WithBaseColor(BuildImage(baseColor, $"{imageName}_basecolor")) .WithNormal(BuildImage(operation.Normal, $"{imageName}_normal")) .WithSpecularColor(BuildImage(specular, $"{imageName}_specular")) .WithEmissive(BuildImage(operation.Emissive, $"{imageName}_emissive"), Vector3.One, 1); + + if (occlusion != null) + materialBuilder.WithOcclusion(BuildImage(occlusion, $"{imageName}_occlusion")); + + return materialBuilder; } // TODO: It feels a little silly to request the entire normal here when extrating the normal only needs some of the components. From b5d4b31301927aff8e4f81dc877d87cb2ffdf693 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 12:35:26 +1100 Subject: [PATCH 0375/1381] Add skin.shpk support --- .../Import/Models/Export/MaterialExporter.cs | 92 ++++++++++++++----- 1 file changed, 71 insertions(+), 21 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 97bfb6bc..923b9c95 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -29,6 +29,7 @@ public class MaterialExporter // NOTE: this isn't particularly precise to game behavior (it has some fade around high opacity), but good enough for now. "character.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), "characterglass.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.BLEND), + "skin.shpk" => BuildSkin(material, name), _ => BuildFallback(material, name), }; } @@ -74,17 +75,14 @@ public class MaterialExporter // TODO: handle other textures stored in the mask? } - // TODO: clean up this name generation a bunch. probably a method. - var imageName = name.Replace("/", "").Replace(".mtrl", ""); - var materialBuilder = BuildSharedBase(material, name) - .WithBaseColor(BuildImage(baseColor, $"{imageName}_basecolor")) - .WithNormal(BuildImage(operation.Normal, $"{imageName}_normal")) - .WithSpecularColor(BuildImage(specular, $"{imageName}_specular")) - .WithEmissive(BuildImage(operation.Emissive, $"{imageName}_emissive"), Vector3.One, 1); + .WithBaseColor(BuildImage(baseColor, name, "basecolor")) + .WithNormal(BuildImage(operation.Normal, name, "normal")) + .WithSpecularColor(BuildImage(specular, name, "specular")) + .WithEmissive(BuildImage(operation.Emissive, name, "emissive"), Vector3.One, 1); if (occlusion != null) - materialBuilder.WithOcclusion(BuildImage(occlusion, $"{imageName}_occlusion")); + materialBuilder.WithOcclusion(BuildImage(occlusion, name, "occlusion")); return materialBuilder; } @@ -140,6 +138,24 @@ public class MaterialExporter } } + private static TableRow GetTableRowIndices(float input) + { + // These calculations are ported from character.shpk. + var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) + * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) + + input * 15; + + var stepped = MathF.Floor(smoothed + 0.5f); + + return new TableRow + { + Stepped = (int)stepped, + Previous = (int)MathF.Floor(smoothed), + Next = (int)MathF.Ceiling(smoothed), + Weight = smoothed % 1, + }; + } + private readonly struct MultiplyOperation { public static void Execute(Image target, Image multiplier) @@ -174,22 +190,54 @@ public class MaterialExporter } } - private static TableRow GetTableRowIndices(float input) + private static MaterialBuilder BuildSkin(Material material, string name) { - // These calculations are ported from character.shpk. - var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) - * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) - + input * 15; + // Trust me bro. + const uint categorySkinType = 0x380CAED0; + const uint valueFace = 0xF5673524; - var stepped = MathF.Floor(smoothed + 0.5f); + // Face is the default for the skin shader, so a lack of skin type category is also correct. + var isFace = !material.Mtrl.ShaderPackage.ShaderKeys + .Any(key => key.Category == categorySkinType && key.Value != valueFace); - return new TableRow + // TODO: There's more nuance to skin than this, but this should be enough for a baseline reference. + // TODO: Specular? + var diffuse = material.Textures[TextureUsage.SamplerDiffuse]; + var normal = material.Textures[TextureUsage.SamplerNormal]; + + // Create a copy of the normal that's the same size as the diffuse for purposes of copying the opacity across. + var resizedNormal = normal.Clone(context => context.Resize(diffuse.Width, diffuse.Height)); + diffuse.ProcessPixelRows(resizedNormal, (diffuseAccessor, normalAccessor) => { - Stepped = (int)stepped, - Previous = (int)MathF.Floor(smoothed), - Next = (int)MathF.Ceiling(smoothed), - Weight = smoothed % 1, - }; + for (int y = 0; y < diffuseAccessor.Height; y++) + { + var diffuseSpan = diffuseAccessor.GetRowSpan(y); + var normalSpan = normalAccessor.GetRowSpan(y); + + for (int x = 0; x < diffuseSpan.Length; x++) + { + diffuseSpan[x].A = normalSpan[x].B; + } + } + }); + + // Clear the blue channel out of the normal now that we're done with it. + normal.ProcessPixelRows(normalAccessor => { + for (int y = 0; y < normalAccessor.Height; y++) + { + var normalSpan = normalAccessor.GetRowSpan(y); + + for (int x = 0; x < normalSpan.Length; x++) + { + normalSpan[x].B = byte.MaxValue; + } + } + }); + + return BuildSharedBase(material, name) + .WithBaseColor(BuildImage(diffuse, name, "basecolor")) + .WithNormal(BuildImage(normal, name, "normal")) + .WithAlpha(isFace? AlphaMode.MASK : AlphaMode.OPAQUE, 0.5f); } private ref struct TableRow @@ -218,8 +266,10 @@ public class MaterialExporter .WithDoubleSide(showBackfaces); } - private static ImageBuilder BuildImage(Image image, string name) + private static ImageBuilder BuildImage(Image image, string materialName, string suffix) { + var name = materialName.Replace("/", "").Replace(".mtrl", "") + $"_{suffix}"; + byte[] textureBytes; using (var memoryStream = new MemoryStream()) { From a6788c6dd3c69a2f183df1f7af06d1188c9c5ff7 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 17:30:13 +1100 Subject: [PATCH 0376/1381] Add hair and iris support --- .../Import/Models/Export/MaterialExporter.cs | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 923b9c95..98e4b3b9 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -29,6 +29,8 @@ public class MaterialExporter // NOTE: this isn't particularly precise to game behavior (it has some fade around high opacity), but good enough for now. "character.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), "characterglass.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.BLEND), + "hair.shpk" => BuildHair(material, name), + "iris.shpk" => BuildIris(material, name), "skin.shpk" => BuildSkin(material, name), _ => BuildFallback(material, name), }; @@ -190,6 +192,84 @@ public class MaterialExporter } } + // TODO: These are hardcoded colours - I'm not keen on supporting highly customiseable exports, but there's possibly some more sensible values to use here. + private static Vector4 _defaultHairColor = new Vector4(130, 64, 13, 255) / new Vector4(255); + private static Vector4 _defaultHighlightColor = new Vector4(77, 126, 240, 255) / new Vector4(255); + + private static MaterialBuilder BuildHair(Material material, string name) + { + // Trust me bro. + const uint categoryHairType = 0x24826489; + const uint valueFace = 0x6E5B8F10; + + var isFace = material.Mtrl.ShaderPackage.ShaderKeys + .Any(key => key.Category == categoryHairType && key.Value == valueFace); + + var normal = material.Textures[TextureUsage.SamplerNormal]; + var mask = material.Textures[TextureUsage.SamplerMask]; + + mask.Mutate(context => context.Resize(normal.Width, normal.Height)); + + var baseColor = new Image(normal.Width, normal.Height); + normal.ProcessPixelRows(mask, baseColor, (normalAccessor, maskAccessor, baseColorAccessor) => + { + for (int y = 0; y < normalAccessor.Height; y++) + { + var normalSpan = normalAccessor.GetRowSpan(y); + var maskSpan = maskAccessor.GetRowSpan(y); + var baseColorSpan = baseColorAccessor.GetRowSpan(y); + + for (int x = 0; x < normalSpan.Length; x++) + { + var color = Vector4.Lerp(_defaultHairColor, _defaultHighlightColor, maskSpan[x].A / 255f); + baseColorSpan[x].FromVector4(color * new Vector4(maskSpan[x].R / 255f)); + baseColorSpan[x].A = normalSpan[x].A; + + normalSpan[x].A = byte.MaxValue; + } + } + }); + + return BuildSharedBase(material, name) + .WithBaseColor(BuildImage(baseColor, name, "basecolor")) + .WithNormal(BuildImage(normal, name, "normal")) + .WithAlpha(isFace? AlphaMode.BLEND : AlphaMode.MASK, 0.5f); + } + + private static Vector4 _defaultEyeColor = new Vector4(21, 176, 172, 255) / new Vector4(255); + + // NOTE: This is largely the same as the hair material, but is also missing a few features that would cause it to diverge. Keeping seperate for now. + private static MaterialBuilder BuildIris(Material material, string name) + { + var normal = material.Textures[TextureUsage.SamplerNormal]; + var mask = material.Textures[TextureUsage.SamplerMask]; + + mask.Mutate(context => context.Resize(normal.Width, normal.Height)); + + var baseColor = new Image(normal.Width, normal.Height); + normal.ProcessPixelRows(mask, baseColor, (normalAccessor, maskAccessor, baseColorAccessor) => + { + for (int y = 0; y < normalAccessor.Height; y++) + { + var normalSpan = normalAccessor.GetRowSpan(y); + var maskSpan = maskAccessor.GetRowSpan(y); + var baseColorSpan = baseColorAccessor.GetRowSpan(y); + + for (int x = 0; x < normalSpan.Length; x++) + { + baseColorSpan[x].FromVector4(_defaultEyeColor * new Vector4(maskSpan[x].R / 255f)); + baseColorSpan[x].A = normalSpan[x].A; + + normalSpan[x].A = byte.MaxValue; + } + } + }); + + return BuildSharedBase(material, name) + .WithBaseColor(BuildImage(baseColor, name, "basecolor")) + .WithNormal(BuildImage(normal, name, "normal")); + } + private static MaterialBuilder BuildSkin(Material material, string name) { // Trust me bro. From 5e6ca8b22c384fa5b4246d09ab3371d671454df3 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 17:37:34 +1100 Subject: [PATCH 0377/1381] Improve fallback handling --- .../Import/Models/Export/MaterialExporter.cs | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 98e4b3b9..0b109ddf 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -158,6 +158,14 @@ public class MaterialExporter }; } + private ref struct TableRow + { + public int Stepped; + public int Previous; + public int Next; + public float Weight; + } + private readonly struct MultiplyOperation { public static void Execute(Image target, Image multiplier) @@ -320,20 +328,21 @@ public class MaterialExporter .WithAlpha(isFace? AlphaMode.MASK : AlphaMode.OPAQUE, 0.5f); } - private ref struct TableRow - { - public int Stepped; - public int Previous; - public int Next; - public float Weight; - } - private static MaterialBuilder BuildFallback(Material material, string name) { Penumbra.Log.Warning($"Unhandled shader package: {material.Mtrl.ShaderPackage.Name}"); - return BuildSharedBase(material, name) + + var materialBuilder = BuildSharedBase(material, name) .WithMetallicRoughnessShader() - .WithChannelParam(KnownChannel.BaseColor, KnownProperty.RGBA, Vector4.One); + .WithBaseColor(Vector4.One); + + if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) + materialBuilder.WithBaseColor(BuildImage(diffuse, name, "basecolor")); + + if (material.Textures.TryGetValue(TextureUsage.SamplerNormal, out var normal)) + materialBuilder.WithNormal(BuildImage(normal, name, "normal")); + + return materialBuilder; } private static MaterialBuilder BuildSharedBase(Material material, string name) From 9ff3227cf4105b602c40f3eec2adddf5759cb507 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 20:12:17 +1100 Subject: [PATCH 0378/1381] Cleanup pass --- .../Import/Models/Export/MaterialExporter.cs | 29 +++++++++++++------ Penumbra/Import/Models/ModelManager.cs | 12 ++++---- .../ModEditWindow.Models.MdlTab.cs | 5 ++-- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 0b109ddf..a189e7bc 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -21,6 +21,7 @@ public class MaterialExporter // variant? } + /// Build a glTF material from a hydrated XIV model, with the provided name. public static MaterialBuilder Export(Material material, string name) { Penumbra.Log.Debug($"Exporting material \"{name}\"."); @@ -36,16 +37,18 @@ public class MaterialExporter }; } + /// Build a material following the semantics of character.shpk. private static MaterialBuilder BuildCharacter(Material material, string name) { + // Build the textures from the color table. var table = material.Mtrl.Table; - // TODO: there's a few normal usages i should check, i think. var normal = material.Textures[TextureUsage.SamplerNormal]; var operation = new ProcessCharacterNormalOperation(normal, table); ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); + // Check if full textures are provided, and merge in if available. Image baseColor = operation.BaseColor; if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) { @@ -53,7 +56,6 @@ public class MaterialExporter baseColor = diffuse; } - // TODO: what about the two specularmaps? Image specular = operation.Specular; if (material.Textures.TryGetValue(TextureUsage.SamplerSpecular, out var specularTexture)) { @@ -61,6 +63,7 @@ public class MaterialExporter specular = specularTexture; } + // Pull further information from the mask. Image? occlusion = null; if (material.Textures.TryGetValue(TextureUsage.SamplerMask, out var maskTexture)) { @@ -73,7 +76,7 @@ public class MaterialExporter 0f, 0f, 0f, 0f ))); occlusion = maskTexture; - + // TODO: handle other textures stored in the mask? } @@ -89,7 +92,7 @@ public class MaterialExporter return materialBuilder; } - // TODO: It feels a little silly to request the entire normal here when extrating the normal only needs some of the components. + // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. private readonly struct ProcessCharacterNormalOperation(Image normal, MtrlFile.ColorTable table) : IRowOperation { @@ -143,7 +146,7 @@ public class MaterialExporter private static TableRow GetTableRowIndices(float input) { // These calculations are ported from character.shpk. - var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) + var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) + input * 15; @@ -204,6 +207,7 @@ public class MaterialExporter private static Vector4 _defaultHairColor = new Vector4(130, 64, 13, 255) / new Vector4(255); private static Vector4 _defaultHighlightColor = new Vector4(77, 126, 240, 255) / new Vector4(255); + /// Build a material following the semantics of hair.shpk. private static MaterialBuilder BuildHair(Material material, string name) { // Trust me bro. @@ -241,11 +245,12 @@ public class MaterialExporter return BuildSharedBase(material, name) .WithBaseColor(BuildImage(baseColor, name, "basecolor")) .WithNormal(BuildImage(normal, name, "normal")) - .WithAlpha(isFace? AlphaMode.BLEND : AlphaMode.MASK, 0.5f); + .WithAlpha(isFace ? AlphaMode.BLEND : AlphaMode.MASK, 0.5f); } private static Vector4 _defaultEyeColor = new Vector4(21, 176, 172, 255) / new Vector4(255); + /// Build a material following the semantics of iris.shpk. // NOTE: This is largely the same as the hair material, but is also missing a few features that would cause it to diverge. Keeping seperate for now. private static MaterialBuilder BuildIris(Material material, string name) { @@ -278,6 +283,7 @@ public class MaterialExporter .WithNormal(BuildImage(normal, name, "normal")); } + /// Build a material following the semantics of skin.shpk. private static MaterialBuilder BuildSkin(Material material, string name) { // Trust me bro. @@ -310,7 +316,8 @@ public class MaterialExporter }); // Clear the blue channel out of the normal now that we're done with it. - normal.ProcessPixelRows(normalAccessor => { + normal.ProcessPixelRows(normalAccessor => + { for (int y = 0; y < normalAccessor.Height; y++) { var normalSpan = normalAccessor.GetRowSpan(y); @@ -325,14 +332,16 @@ public class MaterialExporter return BuildSharedBase(material, name) .WithBaseColor(BuildImage(diffuse, name, "basecolor")) .WithNormal(BuildImage(normal, name, "normal")) - .WithAlpha(isFace? AlphaMode.MASK : AlphaMode.OPAQUE, 0.5f); + .WithAlpha(isFace ? AlphaMode.MASK : AlphaMode.OPAQUE, 0.5f); } + /// Build a material from a source with unknown semantics. + /// Will make a loose effort to fetch common / simple textures. private static MaterialBuilder BuildFallback(Material material, string name) { Penumbra.Log.Warning($"Unhandled shader package: {material.Mtrl.ShaderPackage.Name}"); - var materialBuilder = BuildSharedBase(material, name) + var materialBuilder = BuildSharedBase(material, name) .WithMetallicRoughnessShader() .WithBaseColor(Vector4.One); @@ -345,6 +354,7 @@ public class MaterialExporter return materialBuilder; } + /// Build a material pre-configured with settings common to all XIV materials/shaders. private static MaterialBuilder BuildSharedBase(Material material, string name) { // TODO: Move this and potentially the other known stuff into MtrlFile? @@ -355,6 +365,7 @@ public class MaterialExporter .WithDoubleSide(showBackfaces); } + /// Convert an ImageSharp Image into an ImageBuilder for use with SharpGLTF. private static ImageBuilder BuildImage(Image image, string materialName, string suffix) { var name = materialName.Replace("/", "").Replace(".mtrl", "") + $"_{suffix}"; diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 4f652436..bbc274a5 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -23,8 +23,8 @@ using LuminaMaterial = Lumina.Models.Materials.Material; public sealed class ModelManager(IFramework framework, ActiveCollections collections, IDataManager gameData, GamePathParser parser, TextureManager textureManager) : SingleTaskQueue, IDisposable { - private readonly IFramework _framework = framework; - private readonly IDataManager _gameData = gameData; + private readonly IFramework _framework = framework; + private readonly IDataManager _gameData = gameData; private readonly TextureManager _textureManager = textureManager; private readonly ConcurrentDictionary _tasks = new(); @@ -163,7 +163,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect Penumbra.Log.Debug("[GLTF Export] Done."); } - /// Attempt to read out the pertinent information from a .sklb. + /// Attempt to read out the pertinent information from the sklb file paths provided. private IEnumerable BuildSkeletons(CancellationToken cancel) { var havokTasks = sklbPaths @@ -185,6 +185,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect delayTicks: pair.Index, cancellationToken: cancel); } + /// Read a .mtrl and hydrate its textures. private MaterialExporter.Material BuildMaterial(string relativePath, CancellationToken cancel) { // TODO: this should probably be chosen in the export settings @@ -194,7 +195,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ? LuminaMaterial.ResolveRelativeMaterialPath(relativePath, variantId) : relativePath; - // TODO: this should be a recoverable warning - as should the one below it i think + // TODO: this should be a recoverable warning if (absolutePath == null) throw new Exception("Failed to resolve material path."); @@ -202,7 +203,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return new MaterialExporter.Material { - Mtrl = mtrl, + Mtrl = mtrl, Textures = mtrl.ShaderPackage.Samplers.ToDictionary( sampler => (TextureUsage)sampler.SamplerId, sampler => ConvertImage(mtrl.Textures[sampler.TextureIndex], cancel) @@ -210,6 +211,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect }; } + /// Read a texture referenced by a .mtrl and convert it into an ImageSharp image. private Image ConvertImage(MtrlFile.Texture texture, CancellationToken cancel) { using var textureData = new MemoryStream(read(texture.Path)); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index f79d161e..43a06012 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -225,15 +225,16 @@ public partial class ModEditWindow private byte[] ReadFile(string path) { // TODO: if cross-collection lookups are turned off, this conversion can be skipped - if (!Utf8GamePath.FromString(path, out var utf8SklbPath, true)) + if (!Utf8GamePath.FromString(path, out var utf8Path, true)) throw new Exception($"Resolved path {path} could not be converted to a game path."); - var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8SklbPath); + var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8Path); // TODO: is it worth trying to use streams for these instead? I'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... var bytes = resolvedPath == null ? _edit._gameData.GetFile(path)?.Data : File.ReadAllBytes(resolvedPath.Value.ToPath()); + // TODO: some callers may not care about failures - handle exceptions seperately? return bytes ?? throw new Exception( $"Resolved path {path} could not be found. If modded, is it enabled in the current collection?"); } From 0e50cc9c47ddffe5e9e6d6f9019d59402ae74209 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 22:27:23 +1100 Subject: [PATCH 0379/1381] Handle character mask R same as other shaders --- .../Import/Models/Export/MaterialExporter.cs | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index a189e7bc..0bacb98a 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -49,7 +49,7 @@ public class MaterialExporter ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); // Check if full textures are provided, and merge in if available. - Image baseColor = operation.BaseColor; + Image baseColor = operation.BaseColor; if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) { MultiplyOperation.Execute(diffuse, operation.BaseColor); @@ -64,32 +64,31 @@ public class MaterialExporter } // Pull further information from the mask. - Image? occlusion = null; if (material.Textures.TryGetValue(TextureUsage.SamplerMask, out var maskTexture)) { - // Extract the red channel for ambient occlusion. - maskTexture.Mutate(context => context.Filter(new ColorMatrix( - 1f, 1f, 1f, 0f, - 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 0f, - 0f, 0f, 0f, 1f, - 0f, 0f, 0f, 0f - ))); - occlusion = maskTexture; + // Extract the red channel for "ambient occlusion". + maskTexture.Mutate(context => context.Resize(baseColor.Width, baseColor.Height)); + maskTexture.ProcessPixelRows(baseColor, (maskAccessor, baseColorAccessor) => + { + for (int y = 0; y < maskAccessor.Height; y++) + { + var maskSpan = maskAccessor.GetRowSpan(y); + var baseColorSpan = baseColorAccessor.GetRowSpan(y); + + for (int x = 0; x < maskSpan.Length; x++) + baseColorSpan[x].FromVector4(baseColorSpan[x].ToVector4() * new Vector4(maskSpan[x].R / 255f)); + } + }); + // TODO: handle other textures stored in the mask? } - var materialBuilder = BuildSharedBase(material, name) + return BuildSharedBase(material, name) .WithBaseColor(BuildImage(baseColor, name, "basecolor")) .WithNormal(BuildImage(operation.Normal, name, "normal")) .WithSpecularColor(BuildImage(specular, name, "specular")) .WithEmissive(BuildImage(operation.Emissive, name, "emissive"), Vector3.One, 1); - - if (occlusion != null) - materialBuilder.WithOcclusion(BuildImage(occlusion, name, "occlusion")); - - return materialBuilder; } // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. From ec92f93d229389d901cd57107a8fbd967007e24c Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 14 Jan 2024 22:36:33 +1100 Subject: [PATCH 0380/1381] Improve material and texture path resolution --- Penumbra/Import/Models/ModelManager.cs | 63 ++++++++++++++++++++------ 1 file changed, 50 insertions(+), 13 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index bbc274a5..c6e2d836 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -108,6 +108,40 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId)]; } + /// Try to resolve the absolute path to a .mtrl from the potentially-partial path provided by a model. + private string ResolveMtrlPath(string rawPath) + { + // TODO: this should probably be chosen in the export settings + var variantId = 1; + + // Get standardised paths + var absolutePath = rawPath.StartsWith('/') + ? LuminaMaterial.ResolveRelativeMaterialPath(rawPath, variantId) + : rawPath; + var relativePath = rawPath.StartsWith('/') + ? rawPath + : '/' + Path.GetFileName(rawPath); + + // TODO: this should be a recoverable warning + if (absolutePath == null) + throw new Exception("Failed to resolve material path."); + + var info = parser.GetFileInfo(absolutePath); + if (info.FileType is not FileType.Material) + throw new Exception($"Material path {rawPath} does not conform to material conventions."); + + var resolvedPath = info.ObjectType switch + { + ObjectType.Character => GamePaths.Character.Mtrl.Path( + info.GenderRace, info.BodySlot, info.PrimaryId, relativePath, out _, out _, info.Variant), + _ => absolutePath, + }; + + Penumbra.Log.Debug($"Resolved material {rawPath} to {resolvedPath}"); + + return resolvedPath; + } + private Task Enqueue(IAction action) { if (_disposed) @@ -188,18 +222,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect /// Read a .mtrl and hydrate its textures. private MaterialExporter.Material BuildMaterial(string relativePath, CancellationToken cancel) { - // TODO: this should probably be chosen in the export settings - var variantId = 1; - - var absolutePath = relativePath.StartsWith("/") - ? LuminaMaterial.ResolveRelativeMaterialPath(relativePath, variantId) - : relativePath; - - // TODO: this should be a recoverable warning - if (absolutePath == null) - throw new Exception("Failed to resolve material path."); - - var mtrl = new MtrlFile(read(absolutePath)); + var path = manager.ResolveMtrlPath(relativePath); + var mtrl = new MtrlFile(read(path)); return new MaterialExporter.Material { @@ -214,7 +238,20 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect /// Read a texture referenced by a .mtrl and convert it into an ImageSharp image. private Image ConvertImage(MtrlFile.Texture texture, CancellationToken cancel) { - using var textureData = new MemoryStream(read(texture.Path)); + // Work out the texture's path - the DX11 material flag controls a file name prefix. + var texturePath = texture.Path; + if (texture.DX11) + { + var lastSlashIndex = texturePath.LastIndexOf('/'); + var directory = lastSlashIndex == -1 ? texturePath : texturePath.Substring(0, lastSlashIndex); + var fileName = Path.GetFileName(texturePath); + if (!fileName.StartsWith("--")) + { + texturePath = $"{directory}/--{fileName}"; + } + } + + using var textureData = new MemoryStream(read(texturePath)); var image = TexFileParser.Parse(textureData); var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; if (pngImage == null) From 65fbf13afe7b957ec12b9dc9f3cbc2fd6eb4d388 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Jan 2024 13:16:30 +0100 Subject: [PATCH 0381/1381] Parsing... --- Penumbra.GameData | 2 +- Penumbra/Penumbra.cs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 1dad8d07..96e95378 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1dad8d07047be0851f518cdac2b1c8bc76a7be98 +Subproject commit 96e95378325ff1533ca41b934fcb712f24d5260b diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 5a03dc04..706e4a01 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -79,7 +79,6 @@ public class Penumbra : IDalamudPlugin _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); _services.GetService(); - _services.GetService(); _services.GetService(); // Initialize before Interface. From 3b9d841014029a38a67c83caff89ddc89cad8be7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Jan 2024 13:35:46 +0100 Subject: [PATCH 0382/1381] Minor cleanup. --- .../Import/Models/Export/MaterialExporter.cs | 137 +++++++++--------- Penumbra/Import/Models/ModelManager.cs | 67 +++++---- .../ModEditWindow.Models.MdlTab.cs | 12 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 17 +-- 4 files changed, 115 insertions(+), 118 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 0bacb98a..2a49e77f 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -17,6 +17,7 @@ public class MaterialExporter public struct Material { public MtrlFile Mtrl; + public Dictionary> Textures; // variant? } @@ -49,7 +50,7 @@ public class MaterialExporter ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); // Check if full textures are provided, and merge in if available. - Image baseColor = operation.BaseColor; + var baseColor = operation.BaseColor; if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) { MultiplyOperation.Execute(diffuse, operation.BaseColor); @@ -70,24 +71,22 @@ public class MaterialExporter maskTexture.Mutate(context => context.Resize(baseColor.Width, baseColor.Height)); maskTexture.ProcessPixelRows(baseColor, (maskAccessor, baseColorAccessor) => { - for (int y = 0; y < maskAccessor.Height; y++) + for (var y = 0; y < maskAccessor.Height; y++) { - var maskSpan = maskAccessor.GetRowSpan(y); + var maskSpan = maskAccessor.GetRowSpan(y); var baseColorSpan = baseColorAccessor.GetRowSpan(y); - for (int x = 0; x < maskSpan.Length; x++) + for (var x = 0; x < maskSpan.Length; x++) baseColorSpan[x].FromVector4(baseColorSpan[x].ToVector4() * new Vector4(maskSpan[x].R / 255f)); } }); - - // TODO: handle other textures stored in the mask? } return BuildSharedBase(material, name) - .WithBaseColor(BuildImage(baseColor, name, "basecolor")) - .WithNormal(BuildImage(operation.Normal, name, "normal")) - .WithSpecularColor(BuildImage(specular, name, "specular")) + .WithBaseColor(BuildImage(baseColor, name, "basecolor")) + .WithNormal(BuildImage(operation.Normal, name, "normal")) + .WithSpecularColor(BuildImage(specular, name, "specular")) .WithEmissive(BuildImage(operation.Emissive, name, "emissive"), Vector3.One, 1); } @@ -95,31 +94,38 @@ public class MaterialExporter // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. private readonly struct ProcessCharacterNormalOperation(Image normal, MtrlFile.ColorTable table) : IRowOperation { - public Image Normal { get; private init; } = normal.Clone(); - public Image BaseColor { get; private init; } = new Image(normal.Width, normal.Height); - public Image Specular { get; private init; } = new Image(normal.Width, normal.Height); - public Image Emissive { get; private init; } = new Image(normal.Width, normal.Height); + public Image Normal { get; } = normal.Clone(); + public Image BaseColor { get; } = new(normal.Width, normal.Height); + public Image Specular { get; } = new(normal.Width, normal.Height); + public Image Emissive { get; } = new(normal.Width, normal.Height); - private Buffer2D NormalBuffer => Normal.Frames.RootFrame.PixelBuffer; - private Buffer2D BaseColorBuffer => BaseColor.Frames.RootFrame.PixelBuffer; - private Buffer2D SpecularBuffer => Specular.Frames.RootFrame.PixelBuffer; - private Buffer2D EmissiveBuffer => Emissive.Frames.RootFrame.PixelBuffer; + private Buffer2D NormalBuffer + => Normal.Frames.RootFrame.PixelBuffer; + + private Buffer2D BaseColorBuffer + => BaseColor.Frames.RootFrame.PixelBuffer; + + private Buffer2D SpecularBuffer + => Specular.Frames.RootFrame.PixelBuffer; + + private Buffer2D EmissiveBuffer + => Emissive.Frames.RootFrame.PixelBuffer; public void Invoke(int y) { - var normalSpan = NormalBuffer.DangerousGetRowSpan(y); + var normalSpan = NormalBuffer.DangerousGetRowSpan(y); var baseColorSpan = BaseColorBuffer.DangerousGetRowSpan(y); - var specularSpan = SpecularBuffer.DangerousGetRowSpan(y); - var emissiveSpan = EmissiveBuffer.DangerousGetRowSpan(y); + var specularSpan = SpecularBuffer.DangerousGetRowSpan(y); + var emissiveSpan = EmissiveBuffer.DangerousGetRowSpan(y); - for (int x = 0; x < normalSpan.Length; x++) + for (var x = 0; x < normalSpan.Length; x++) { ref var normalPixel = ref normalSpan[x]; // Table row data (.a) var tableRow = GetTableRowIndices(normalPixel.A / 255f); - var prevRow = table[tableRow.Previous]; - var nextRow = table[tableRow.Next]; + var prevRow = table[tableRow.Previous]; + var nextRow = table[tableRow.Next]; // Base colour (table, .b) var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, tableRow.Weight); @@ -145,9 +151,9 @@ public class MaterialExporter private static TableRow GetTableRowIndices(float input) { // These calculations are ported from character.shpk. - var smoothed = MathF.Floor(((input * 7.5f) % 1.0f) * 2) - * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) - + input * 15; + var smoothed = MathF.Floor(input * 7.5f % 1.0f * 2) + * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) + + input * 15; var stepped = MathF.Floor(smoothed + 0.5f); @@ -162,9 +168,9 @@ public class MaterialExporter private ref struct TableRow { - public int Stepped; - public int Previous; - public int Next; + public int Stepped; + public int Previous; + public int Next; public float Weight; } @@ -189,50 +195,47 @@ public class MaterialExporter where TPixel1 : unmanaged, IPixel where TPixel2 : unmanaged, IPixel { - public void Invoke(int y) { - var targetSpan = target.Frames.RootFrame.PixelBuffer.DangerousGetRowSpan(y); + var targetSpan = target.Frames.RootFrame.PixelBuffer.DangerousGetRowSpan(y); var multiplierSpan = multiplier.Frames.RootFrame.PixelBuffer.DangerousGetRowSpan(y); - for (int x = 0; x < targetSpan.Length; x++) - { + for (var x = 0; x < targetSpan.Length; x++) targetSpan[x].FromVector4(targetSpan[x].ToVector4() * multiplierSpan[x].ToVector4()); - } } } - // TODO: These are hardcoded colours - I'm not keen on supporting highly customiseable exports, but there's possibly some more sensible values to use here. - private static Vector4 _defaultHairColor = new Vector4(130, 64, 13, 255) / new Vector4(255); - private static Vector4 _defaultHighlightColor = new Vector4(77, 126, 240, 255) / new Vector4(255); + // TODO: These are hardcoded colours - I'm not keen on supporting highly customizable exports, but there's possibly some more sensible values to use here. + private static readonly Vector4 DefaultHairColor = new Vector4(130, 64, 13, 255) / new Vector4(255); + private static readonly Vector4 DefaultHighlightColor = new Vector4(77, 126, 240, 255) / new Vector4(255); /// Build a material following the semantics of hair.shpk. private static MaterialBuilder BuildHair(Material material, string name) { // Trust me bro. const uint categoryHairType = 0x24826489; - const uint valueFace = 0x6E5B8F10; + const uint valueFace = 0x6E5B8F10; var isFace = material.Mtrl.ShaderPackage.ShaderKeys - .Any(key => key.Category == categoryHairType && key.Value == valueFace); + .Any(key => key is { Category: categoryHairType, Value: valueFace }); var normal = material.Textures[TextureUsage.SamplerNormal]; - var mask = material.Textures[TextureUsage.SamplerMask]; + var mask = material.Textures[TextureUsage.SamplerMask]; mask.Mutate(context => context.Resize(normal.Width, normal.Height)); var baseColor = new Image(normal.Width, normal.Height); normal.ProcessPixelRows(mask, baseColor, (normalAccessor, maskAccessor, baseColorAccessor) => { - for (int y = 0; y < normalAccessor.Height; y++) + for (var y = 0; y < normalAccessor.Height; y++) { - var normalSpan = normalAccessor.GetRowSpan(y); - var maskSpan = maskAccessor.GetRowSpan(y); + var normalSpan = normalAccessor.GetRowSpan(y); + var maskSpan = maskAccessor.GetRowSpan(y); var baseColorSpan = baseColorAccessor.GetRowSpan(y); - for (int x = 0; x < normalSpan.Length; x++) + for (var x = 0; x < normalSpan.Length; x++) { - var color = Vector4.Lerp(_defaultHairColor, _defaultHighlightColor, maskSpan[x].A / 255f); + var color = Vector4.Lerp(DefaultHairColor, DefaultHighlightColor, maskSpan[x].A / 255f); baseColorSpan[x].FromVector4(color * new Vector4(maskSpan[x].R / 255f)); baseColorSpan[x].A = normalSpan[x].A; @@ -243,33 +246,33 @@ public class MaterialExporter return BuildSharedBase(material, name) .WithBaseColor(BuildImage(baseColor, name, "basecolor")) - .WithNormal(BuildImage(normal, name, "normal")) + .WithNormal(BuildImage(normal, name, "normal")) .WithAlpha(isFace ? AlphaMode.BLEND : AlphaMode.MASK, 0.5f); } - private static Vector4 _defaultEyeColor = new Vector4(21, 176, 172, 255) / new Vector4(255); + private static readonly Vector4 DefaultEyeColor = new Vector4(21, 176, 172, 255) / new Vector4(255); /// Build a material following the semantics of iris.shpk. - // NOTE: This is largely the same as the hair material, but is also missing a few features that would cause it to diverge. Keeping seperate for now. + // NOTE: This is largely the same as the hair material, but is also missing a few features that would cause it to diverge. Keeping separate for now. private static MaterialBuilder BuildIris(Material material, string name) { var normal = material.Textures[TextureUsage.SamplerNormal]; - var mask = material.Textures[TextureUsage.SamplerMask]; + var mask = material.Textures[TextureUsage.SamplerMask]; mask.Mutate(context => context.Resize(normal.Width, normal.Height)); var baseColor = new Image(normal.Width, normal.Height); normal.ProcessPixelRows(mask, baseColor, (normalAccessor, maskAccessor, baseColorAccessor) => { - for (int y = 0; y < normalAccessor.Height; y++) + for (var y = 0; y < normalAccessor.Height; y++) { - var normalSpan = normalAccessor.GetRowSpan(y); - var maskSpan = maskAccessor.GetRowSpan(y); + var normalSpan = normalAccessor.GetRowSpan(y); + var maskSpan = maskAccessor.GetRowSpan(y); var baseColorSpan = baseColorAccessor.GetRowSpan(y); - for (int x = 0; x < normalSpan.Length; x++) + for (var x = 0; x < normalSpan.Length; x++) { - baseColorSpan[x].FromVector4(_defaultEyeColor * new Vector4(maskSpan[x].R / 255f)); + baseColorSpan[x].FromVector4(DefaultEyeColor * new Vector4(maskSpan[x].R / 255f)); baseColorSpan[x].A = normalSpan[x].A; normalSpan[x].A = byte.MaxValue; @@ -279,7 +282,7 @@ public class MaterialExporter return BuildSharedBase(material, name) .WithBaseColor(BuildImage(baseColor, name, "basecolor")) - .WithNormal(BuildImage(normal, name, "normal")); + .WithNormal(BuildImage(normal, name, "normal")); } /// Build a material following the semantics of skin.shpk. @@ -287,7 +290,7 @@ public class MaterialExporter { // Trust me bro. const uint categorySkinType = 0x380CAED0; - const uint valueFace = 0xF5673524; + const uint valueFace = 0xF5673524; // Face is the default for the skin shader, so a lack of skin type category is also correct. var isFace = !material.Mtrl.ShaderPackage.ShaderKeys @@ -296,41 +299,37 @@ public class MaterialExporter // TODO: There's more nuance to skin than this, but this should be enough for a baseline reference. // TODO: Specular? var diffuse = material.Textures[TextureUsage.SamplerDiffuse]; - var normal = material.Textures[TextureUsage.SamplerNormal]; + var normal = material.Textures[TextureUsage.SamplerNormal]; // Create a copy of the normal that's the same size as the diffuse for purposes of copying the opacity across. var resizedNormal = normal.Clone(context => context.Resize(diffuse.Width, diffuse.Height)); diffuse.ProcessPixelRows(resizedNormal, (diffuseAccessor, normalAccessor) => { - for (int y = 0; y < diffuseAccessor.Height; y++) + for (var y = 0; y < diffuseAccessor.Height; y++) { var diffuseSpan = diffuseAccessor.GetRowSpan(y); - var normalSpan = normalAccessor.GetRowSpan(y); + var normalSpan = normalAccessor.GetRowSpan(y); - for (int x = 0; x < diffuseSpan.Length; x++) - { + for (var x = 0; x < diffuseSpan.Length; x++) diffuseSpan[x].A = normalSpan[x].B; - } } }); // Clear the blue channel out of the normal now that we're done with it. normal.ProcessPixelRows(normalAccessor => { - for (int y = 0; y < normalAccessor.Height; y++) + for (var y = 0; y < normalAccessor.Height; y++) { var normalSpan = normalAccessor.GetRowSpan(y); - for (int x = 0; x < normalSpan.Length; x++) - { + for (var x = 0; x < normalSpan.Length; x++) normalSpan[x].B = byte.MaxValue; - } } }); return BuildSharedBase(material, name) .WithBaseColor(BuildImage(diffuse, name, "basecolor")) - .WithNormal(BuildImage(normal, name, "normal")) + .WithNormal(BuildImage(normal, name, "normal")) .WithAlpha(isFace ? AlphaMode.MASK : AlphaMode.OPAQUE, 0.5f); } @@ -357,8 +356,8 @@ public class MaterialExporter private static MaterialBuilder BuildSharedBase(Material material, string name) { // TODO: Move this and potentially the other known stuff into MtrlFile? - const uint backfaceMask = 0x1; - var showBackfaces = (material.Mtrl.ShaderPackage.Flags & backfaceMask) == 0; + const uint backfaceMask = 0x1; + var showBackfaces = (material.Mtrl.ShaderPackage.Flags & backfaceMask) == 0; return new MaterialBuilder(name) .WithDoubleSide(showBackfaces); diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index c6e2d836..8c6dc31a 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -21,11 +21,9 @@ namespace Penumbra.Import.Models; using Schema2 = SharpGLTF.Schema2; using LuminaMaterial = Lumina.Models.Materials.Material; -public sealed class ModelManager(IFramework framework, ActiveCollections collections, IDataManager gameData, GamePathParser parser, TextureManager textureManager) : SingleTaskQueue, IDisposable +public sealed class ModelManager(IFramework framework, ActiveCollections collections, GamePathParser parser) : SingleTaskQueue, IDisposable { - private readonly IFramework _framework = framework; - private readonly IDataManager _gameData = gameData; - private readonly TextureManager _textureManager = textureManager; + private readonly IFramework _framework = framework; private readonly ConcurrentDictionary _tasks = new(); @@ -45,13 +43,15 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect public Task ImportGltf(string inputPath) { var action = new ImportGltfAction(inputPath); - return Enqueue(action).ContinueWith(task => + return Enqueue(action).ContinueWith(task => { - if (task.IsFaulted && task.Exception != null) + if (task is { IsFaulted: true, Exception: not null }) throw task.Exception; + return action.Out; }); } + /// Try to find the .sklb paths for a .mdl file. /// .mdl file to look up the skeletons for. /// Modified extra skeleton template parameters. @@ -69,8 +69,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Body, info, estManipulations)], ObjectType.Equipment when info.EquipSlot.ToSlot() is EquipSlot.Head => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Head, info, estManipulations)], - ObjectType.Equipment => [baseSkeleton], - ObjectType.Accessory => [baseSkeleton], + ObjectType.Equipment => [baseSkeleton], + ObjectType.Accessory => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Hair => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Hair, info, estManipulations)], @@ -89,17 +89,17 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect // Try to find an EST entry from the manipulations provided. var (gender, race) = info.GenderRace.Split(); var modEst = estManipulations - .FirstOrNull(est => + .FirstOrNull(est => est.Gender == gender - && est.Race == race - && est.Slot == type - && est.SetId == info.PrimaryId + && est.Race == race + && est.Slot == type + && est.SetId == info.PrimaryId ); - + // Try to use an entry from provided manipulations, falling back to the current collection. var targetId = modEst?.Entry - ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) - ?? 0; + ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) + ?? 0; // If there's no entries, we can assume that there's no additional skeleton. if (targetId == 0) @@ -121,11 +121,11 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect var relativePath = rawPath.StartsWith('/') ? rawPath : '/' + Path.GetFileName(rawPath); - + // TODO: this should be a recoverable warning if (absolutePath == null) throw new Exception("Failed to resolve material path."); - + var info = parser.GetFileInfo(absolutePath); if (info.FileType is not FileType.Material) throw new Exception($"Material path {rawPath} does not conform to material conventions."); @@ -168,7 +168,12 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return task; } - private class ExportToGltfAction(ModelManager manager, MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + private class ExportToGltfAction( + ModelManager manager, + MdlFile mdl, + IEnumerable sklbPaths, + Func read, + string outputPath) : IAction { public void Execute(CancellationToken cancel) @@ -213,21 +218,21 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect // finicky at the best of times, and can outright cause a CTD if they // get upset. Running each conversion on its own tick seems to make // this consistently non-crashy across my testing. - Task CreateHavokTask((SklbFile Sklb, int Index) pair) => - manager._framework.RunOnTick( + Task CreateHavokTask((SklbFile Sklb, int Index) pair) + => manager._framework.RunOnTick( () => HavokConverter.HkxToXml(pair.Sklb.Skeleton), delayTicks: pair.Index, cancellationToken: cancel); } - /// Read a .mtrl and hydrate its textures. + /// Read a .mtrl and populate its textures. private MaterialExporter.Material BuildMaterial(string relativePath, CancellationToken cancel) { var path = manager.ResolveMtrlPath(relativePath); var mtrl = new MtrlFile(read(path)); - + return new MaterialExporter.Material { - Mtrl = mtrl, + Mtrl = mtrl, Textures = mtrl.ShaderPackage.Samplers.ToDictionary( sampler => (TextureUsage)sampler.SamplerId, sampler => ConvertImage(mtrl.Textures[sampler.TextureIndex], cancel) @@ -242,21 +247,15 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect var texturePath = texture.Path; if (texture.DX11) { - var lastSlashIndex = texturePath.LastIndexOf('/'); - var directory = lastSlashIndex == -1 ? texturePath : texturePath.Substring(0, lastSlashIndex); - var fileName = Path.GetFileName(texturePath); + var fileName = Path.GetFileName(texturePath); if (!fileName.StartsWith("--")) - { - texturePath = $"{directory}/--{fileName}"; - } + texturePath = $"{Path.GetDirectoryName(texturePath)}/--{fileName}"; } using var textureData = new MemoryStream(read(texturePath)); - var image = TexFileParser.Parse(textureData); - var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; - if (pngImage == null) - throw new Exception("Failed to convert texture to png."); - return pngImage; + var image = TexFileParser.Parse(textureData); + var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; + return pngImage ?? throw new Exception("Failed to convert texture to png."); } public bool Equals(IAction? other) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 43a06012..9cfe0739 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -181,9 +181,9 @@ public partial class ModEditWindow } /// Merge attribute configuration from the source onto the target. - /// + /// Model that will be updated. > /// Model to copy attribute configuration from. - public void MergeAttributes(MdlFile target, MdlFile source) + public static void MergeAttributes(MdlFile target, MdlFile source) { target.Attributes = source.Attributes; @@ -197,7 +197,7 @@ public partial class ModEditWindow target.SubMeshes[subMeshIndex].AttributeIndexMask = 0u; // Rather than comparing sub-meshes directly, we're grouping by parent mesh in an attempt - // to maintain semantic connection betwen mesh index and submesh attributes. + // to maintain semantic connection between mesh index and sub mesh attributes. if (meshIndex >= source.Meshes.Length) continue; var sourceMesh = source.Meshes[meshIndex]; @@ -214,8 +214,8 @@ public partial class ModEditWindow { IoExceptions = exception switch { null => [], - AggregateException ae => ae.Flatten().InnerExceptions.ToList(), - Exception other => [other], + AggregateException ae => [.. ae.Flatten().InnerExceptions], + _ => [exception], }; } @@ -234,7 +234,7 @@ public partial class ModEditWindow ? _edit._gameData.GetFile(path)?.Data : File.ReadAllBytes(resolvedPath.Value.ToPath()); - // TODO: some callers may not care about failures - handle exceptions seperately? + // TODO: some callers may not care about failures - handle exceptions separately? return bytes ?? throw new Exception( $"Resolved path {path} could not be found. If modded, is it enabled in the current collection?"); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 4ac789ad..ad609285 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -129,7 +129,7 @@ public partial class ModEditWindow ); } - private void DrawIoExceptions(MdlTab tab) + private static void DrawIoExceptions(MdlTab tab) { if (tab.IoExceptions.Count == 0) return; @@ -140,16 +140,15 @@ public partial class ModEditWindow var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; foreach (var (exception, index) in tab.IoExceptions.WithIndex()) { - var message = $"{exception.GetType().Name}: {exception.Message}"; - var textSize = ImGui.CalcTextSize(message).X; + using var id = ImRaii.PushId(index); + var message = $"{exception.GetType().Name}: {exception.Message}"; + var textSize = ImGui.CalcTextSize(message).X; if (textSize > spaceAvail) - message = message.Substring(0, (int)Math.Floor(message.Length * (spaceAvail / textSize))) + "..."; + message = message[..(int)Math.Floor(message.Length * (spaceAvail / textSize))] + "..."; - using (var exceptionNode = ImRaii.TreeNode($"{message}###exception{index}")) - { - if (exceptionNode) - ImGuiUtil.TextWrapped(exception.ToString()); - } + using var exceptionNode = ImRaii.TreeNode(message); + if (exceptionNode) + ImGuiUtil.TextWrapped(exception.ToString()); } } From 574a129772a31b02594e4a21c830ddcd92ec27f6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 14 Jan 2024 12:37:57 +0000 Subject: [PATCH 0383/1381] [CI] Updating repo.json for testing_0.8.3.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a9c1829a..bcf1f82b 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.5", + "TestingAssemblyVersion": "0.8.3.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 965f8efd80cb6d9e66f567935f1edfbf657c1711 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Jan 2024 14:15:07 +0100 Subject: [PATCH 0384/1381] Add function that handles prepending DX11 dashes. --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 9 +-------- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 16 ++-------------- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 18 +++--------------- 4 files changed, 7 insertions(+), 38 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 96e95378..13545143 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 96e95378325ff1533ca41b934fcb712f24d5260b +Subproject commit 135451430344f2f12e8c02fd4c4c6f0875d74e60 diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 8c6dc31a..7f1171f3 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -244,14 +244,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect private Image ConvertImage(MtrlFile.Texture texture, CancellationToken cancel) { // Work out the texture's path - the DX11 material flag controls a file name prefix. - var texturePath = texture.Path; - if (texture.DX11) - { - var fileName = Path.GetFileName(texturePath); - if (!fileName.StartsWith("--")) - texturePath = $"{Path.GetDirectoryName(texturePath)}/--{fileName}"; - } - + GamePaths.Tex.HandleDx11Path(texture, out var texturePath); using var textureData = new MemoryStream(read(texturePath)); var image = TexFileParser.Parse(textureData); var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index fc32df0c..78c49b59 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -79,21 +79,9 @@ public static class CustomizationSwap } public static FileSwap CreateTex(MetaFileManager manager, Func redirections, BodySlot slot, GenderRace race, - PrimaryId idFrom, ref MtrlFile.Texture texture, - ref bool dataWasChanged) + PrimaryId idFrom, ref MtrlFile.Texture texture, ref bool dataWasChanged) { - var path = texture.Path; - var addedDashes = false; - if (texture.DX11) - { - var fileName = Path.GetFileName(path); - if (!fileName.StartsWith("--")) - { - path = path.Replace(fileName, $"--{fileName}"); - addedDashes = true; - } - } - + var addedDashes = GamePaths.Tex.HandleDx11Path(texture, out var path); var newPath = ItemSwap.ReplaceAnyRace(path, race); newPath = ItemSwap.ReplaceAnyBody(newPath, slot, idFrom); newPath = ItemSwap.AddSuffix(newPath, ".tex", $"_{Path.GetFileName(texture.Path).GetStableHashCode():x8}", true); diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 516df251..5a5181a5 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -402,22 +402,10 @@ public static class EquipmentSwap => CreateTex(manager, redirections, prefix, EquipSlot.Unknown, EquipSlot.Unknown, idFrom, idTo, ref texture, ref dataWasChanged); public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, EquipSlot slotFrom, - EquipSlot slotTo, PrimaryId idFrom, - PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) + EquipSlot slotTo, PrimaryId idFrom, PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) { - var path = texture.Path; - var addedDashes = false; - if (texture.DX11) - { - var fileName = Path.GetFileName(path); - if (!fileName.StartsWith("--")) - { - path = path.Replace(fileName, $"--{fileName}"); - addedDashes = true; - } - } - - var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); + var addedDashes = GamePaths.Tex.HandleDx11Path(texture, out var path); + var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); newPath = ItemSwap.ReplaceSlot(newPath, slotTo, slotFrom, slotTo != slotFrom); newPath = ItemSwap.AddSuffix(newPath, ".tex", $"_{Path.GetFileName(texture.Path).GetStableHashCode():x8}"); if (newPath != path) From f147e66953f63c1afd32922bf2dfad1aee5bea7c Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 14 Jan 2024 13:17:42 +0000 Subject: [PATCH 0385/1381] [CI] Updating repo.json for testing_0.8.3.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index bcf1f82b..4dfac5a0 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.6", + "TestingAssemblyVersion": "0.8.3.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 70e72f57901fc47e11f916d7c40d799f869da018 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Jan 2024 19:28:31 +0100 Subject: [PATCH 0386/1381] Update OtterGui and maybe handle dependency issues. --- Penumbra/Import/Textures/TextureDrawer.cs | 10 ++++++++++ Penumbra/lib/DirectXTexC.dll | Bin 806400 -> 983552 bytes Penumbra/lib/OtterTex.dll | Bin 32256 -> 41984 bytes 3 files changed, 10 insertions(+) diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index 6d68efbd..04422116 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -27,7 +27,17 @@ public static class TextureDrawer } else if (texture.LoadError != null) { + const string link = "https://aka.ms/vcredist"; ImGui.TextUnformatted("Could not load file:"); + + if (texture.LoadError is DllNotFoundException) + { + ImGuiUtil.TextColored(Colors.RegexWarningBorder, "A texture handling dependency could not be found. Try installing a current Microsoft VC Redistributable."); + if (ImGui.Button("Microsoft VC Redistributables")) + Dalamud.Utility.Util.OpenLink(link); + ImGuiUtil.HoverTooltip($"Open {link} in your browser."); + } + ImGuiUtil.TextColored(Colors.RegexWarningBorder, texture.LoadError.ToString()); } } diff --git a/Penumbra/lib/DirectXTexC.dll b/Penumbra/lib/DirectXTexC.dll index 5e0aa0c43150ac1a01cfb8e0e016517559f6328a..2cab1dcea5a148712aa14312788227fd61b8800d 100644 GIT binary patch delta 364593 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%0D0D-3zbM(Yjab2m}SIf&(9)q=9r5Fk4N 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℞?}PSs#N*{X9O;~fS)mo58~ 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 BY|a1x delta 189779 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 diff --git a/Penumbra/lib/OtterTex.dll b/Penumbra/lib/OtterTex.dll index d4819ff2a44a62390ff6e861cf98b902676fd91e..29912e6215ff28a7959b73aa1e00cc9ebb919d76 100644 GIT binary patch literal 41984 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

6!_KBfJth4basr$B2eOH&>0GlJ>So@a7 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 literal 32256 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 Date: Sun, 14 Jan 2024 19:28:42 +0100 Subject: [PATCH 0387/1381] Some further cleanup. --- Penumbra/Api/DalamudSubstitutionProvider.cs | 1 + Penumbra/Collections/Cache/CollectionCache.cs | 1 + .../Collections/Cache/CollectionModData.cs | 1 + Penumbra/Collections/Cache/MetaCache.cs | 1 + .../Collections/ModCollection.Cache.Access.cs | 1 + Penumbra/Communication/ResolvedFileChanged.cs | 1 + Penumbra/Interop/Hooks/DebugHook.cs | 9 ++- Penumbra/Mods/Editor/DuplicateManager.cs | 1 - Penumbra/Mods/Editor/IMod.cs | 2 +- Penumbra/Mods/Editor/MdlMaterialEditor.cs | 14 ++--- Penumbra/Mods/Editor/ModEditor.cs | 41 ++++++------- Penumbra/Mods/Editor/ModFileCollection.cs | 21 +++---- Penumbra/Mods/Editor/ModFileEditor.cs | 60 ++++++++----------- Penumbra/Mods/Editor/ModMetaEditor.cs | 24 +++----- Penumbra/Mods/Editor/ModNormalizer.cs | 6 +- Penumbra/Mods/Editor/ModSwapEditor.cs | 10 +--- Penumbra/Mods/Mod.cs | 1 + Penumbra/Mods/Subclasses/SubMod.cs | 1 + Penumbra/Mods/TemporaryMod.cs | 1 + Penumbra/Services/ServiceManagerA.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 1 + Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 1 + Penumbra/UI/Tabs/ChangedItemsTab.cs | 1 + Penumbra/UI/Tabs/EffectiveTab.cs | 1 + 24 files changed, 90 insertions(+), 112 deletions(-) diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index 498c25e3..0374e31a 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -3,6 +3,7 @@ using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index a6e5fef5..9a0e525b 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -4,6 +4,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.Api.Enums; using Penumbra.Communication; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; diff --git a/Penumbra/Collections/Cache/CollectionModData.cs b/Penumbra/Collections/Cache/CollectionModData.cs index fcbccc96..3a3afad2 100644 --- a/Penumbra/Collections/Cache/CollectionModData.cs +++ b/Penumbra/Collections/Cache/CollectionModData.cs @@ -1,5 +1,6 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index b22aaa6e..4c147c3c 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -5,6 +5,7 @@ using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 5d1d10e2..7c29676d 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -7,6 +7,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; using Penumbra.Collections.Cache; using Penumbra.Interop.Services; +using Penumbra.Mods.Editor; namespace Penumbra.Collections; diff --git a/Penumbra/Communication/ResolvedFileChanged.cs b/Penumbra/Communication/ResolvedFileChanged.cs index 3211a26a..75444340 100644 --- a/Penumbra/Communication/ResolvedFileChanged.cs +++ b/Penumbra/Communication/ResolvedFileChanged.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Communication; diff --git a/Penumbra/Interop/Hooks/DebugHook.cs b/Penumbra/Interop/Hooks/DebugHook.cs index 67823e94..db14805c 100644 --- a/Penumbra/Interop/Hooks/DebugHook.cs +++ b/Penumbra/Interop/Hooks/DebugHook.cs @@ -1,5 +1,4 @@ using Dalamud.Hooking; -using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Services; namespace Penumbra.Interop.Hooks; @@ -32,12 +31,12 @@ public sealed unsafe class DebugHook : IHookService public bool Finished => _task?.IsCompletedSuccessfully ?? true; - private delegate nint Delegate(ResourceHandle* resourceHandle); + private delegate void Delegate(nint a, int b, nint c, float* d); - private nint Detour(ResourceHandle* resourceHandle) + private void Detour(nint a, int b, nint c, float* d) { - Penumbra.Log.Information($"[Debug Hook] Triggered with 0x{(nint)resourceHandle:X}."); - return _task!.Result.Original(resourceHandle); + _task!.Result.Original(a, b, c, d); + Penumbra.Log.Information($"[Debug Hook] Results with 0x{a:X} {b} {c:X} {d[0]} {d[1]} {d[2]} {d[3]}."); } } #endif diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 4773d840..dad05102 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -1,4 +1,3 @@ -using OtterGui.Services; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index cd8a9594..78250341 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -1,7 +1,7 @@ using OtterGui.Classes; using Penumbra.Mods.Subclasses; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; public interface IMod { diff --git a/Penumbra/Mods/Editor/MdlMaterialEditor.cs b/Penumbra/Mods/Editor/MdlMaterialEditor.cs index 8881ac4b..738e606e 100644 --- a/Penumbra/Mods/Editor/MdlMaterialEditor.cs +++ b/Penumbra/Mods/Editor/MdlMaterialEditor.cs @@ -2,25 +2,19 @@ using OtterGui; using OtterGui.Compression; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; -using Penumbra.Mods.Editor; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; -public partial class MdlMaterialEditor +public partial class MdlMaterialEditor(ModFileCollection files) { [GeneratedRegex(@"/mt_c(?'RaceCode'\d{4})b0001_(?'Suffix'.*?)\.mtrl", RegexOptions.ExplicitCapture | RegexOptions.NonBacktracking)] private static partial Regex MaterialRegex(); - private readonly ModFileCollection _files; - - private readonly List _modelFiles = new(); + private readonly List _modelFiles = []; public IReadOnlyList ModelFiles => _modelFiles; - public MdlMaterialEditor(ModFileCollection files) - => _files = files; - public void SaveAllModels(FileCompactor compactor) { foreach (var info in _modelFiles) @@ -73,7 +67,7 @@ public partial class MdlMaterialEditor public void ScanModels(Mod mod) { _modelFiles.Clear(); - foreach (var file in _files.Mdl) + foreach (var file in files.Mdl) { try { diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index 2f39970d..b22aea17 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -4,16 +4,25 @@ using Penumbra.Mods.Subclasses; namespace Penumbra.Mods.Editor; -public class ModEditor : IDisposable +public class ModEditor( + ModNormalizer modNormalizer, + ModMetaEditor metaEditor, + ModFileCollection files, + ModFileEditor fileEditor, + DuplicateManager duplicates, + ModSwapEditor swapEditor, + MdlMaterialEditor mdlMaterialEditor, + FileCompactor compactor) + : IDisposable { - public readonly ModNormalizer ModNormalizer; - public readonly ModMetaEditor MetaEditor; - public readonly ModFileEditor FileEditor; - public readonly DuplicateManager Duplicates; - public readonly ModFileCollection Files; - public readonly ModSwapEditor SwapEditor; - public readonly MdlMaterialEditor MdlMaterialEditor; - public readonly FileCompactor Compactor; + public readonly ModNormalizer ModNormalizer = modNormalizer; + public readonly ModMetaEditor MetaEditor = metaEditor; + public readonly ModFileEditor FileEditor = fileEditor; + public readonly DuplicateManager Duplicates = duplicates; + public readonly ModFileCollection Files = files; + public readonly ModSwapEditor SwapEditor = swapEditor; + public readonly MdlMaterialEditor MdlMaterialEditor = mdlMaterialEditor; + public readonly FileCompactor Compactor = compactor; public Mod? Mod { get; private set; } public int GroupIdx { get; private set; } @@ -22,20 +31,6 @@ public class ModEditor : IDisposable public IModGroup? Group { get; private set; } public ISubMod? Option { get; private set; } - public ModEditor(ModNormalizer modNormalizer, ModMetaEditor metaEditor, ModFileCollection files, - ModFileEditor fileEditor, DuplicateManager duplicates, ModSwapEditor swapEditor, MdlMaterialEditor mdlMaterialEditor, - FileCompactor compactor) - { - ModNormalizer = modNormalizer; - MetaEditor = metaEditor; - Files = files; - FileEditor = fileEditor; - Duplicates = duplicates; - SwapEditor = swapEditor; - MdlMaterialEditor = mdlMaterialEditor; - Compactor = compactor; - } - public void LoadMod(Mod mod) => LoadMod(mod, -1, 0); diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index e3862c90..2f8bdfb1 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -6,20 +6,20 @@ namespace Penumbra.Mods.Editor; public class ModFileCollection : IDisposable { - private readonly List _available = new(); - private readonly List _mtrl = new(); - private readonly List _mdl = new(); - private readonly List _tex = new(); - private readonly List _shpk = new(); + private readonly List _available = []; + private readonly List _mtrl = []; + private readonly List _mdl = []; + private readonly List _tex = []; + private readonly List _shpk = []; - private readonly SortedSet _missing = new(); - private readonly HashSet _usedPaths = new(); + private readonly SortedSet _missing = []; + private readonly HashSet _usedPaths = []; public IReadOnlySet Missing - => Ready ? _missing : new HashSet(); + => Ready ? _missing : []; public IReadOnlySet UsedPaths - => Ready ? _usedPaths : new HashSet(); + => Ready ? _usedPaths : []; public IReadOnlyList Available => Ready ? _available : Array.Empty(); @@ -38,9 +38,6 @@ public class ModFileCollection : IDisposable public bool Ready { get; private set; } = true; - public ModFileCollection() - { } - public void UpdateAll(Mod mod, ISubMod option) { UpdateFiles(mod, new CancellationToken()); diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 82629971..5328b8fe 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -1,23 +1,13 @@ -using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; -public class ModFileEditor +public class ModFileEditor(ModFileCollection files, ModManager modManager) { - private readonly ModFileCollection _files; - private readonly ModManager _modManager; - public bool Changes { get; private set; } - public ModFileEditor(ModFileCollection files, ModManager modManager) - { - _files = files; - _modManager = modManager; - } - public void Clear() { Changes = false; @@ -27,21 +17,21 @@ public class ModFileEditor { var dict = new Dictionary(); var num = 0; - foreach (var file in _files.Available) + foreach (var file in files.Available) { foreach (var path in file.SubModUsage.Where(p => p.Item1 == option)) num += dict.TryAdd(path.Item2, file.File) ? 0 : 1; } - _modManager.OptionEditor.OptionSetFiles(mod, option.GroupIdx, option.OptionIdx, dict); - _files.UpdatePaths(mod, option); + modManager.OptionEditor.OptionSetFiles(mod, option.GroupIdx, option.OptionIdx, dict); + files.UpdatePaths(mod, option); Changes = false; return num; } public void Revert(Mod mod, ISubMod option) { - _files.UpdateAll(mod, option); + files.UpdateAll(mod, option); Changes = false; } @@ -53,16 +43,16 @@ public class ModFileEditor var newDict = subMod.Files.Where(kvp => CheckAgainstMissing(mod, subMod, kvp.Value, kvp.Key, subMod == option)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (newDict.Count != subMod.Files.Count) - _modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, newDict); + modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, newDict); } ModEditor.ApplyToAllOptions(mod, HandleSubMod); - _files.ClearMissingFiles(); + files.ClearMissingFiles(); } ///

Return whether the given path is already used in the current option. public bool CanAddGamePath(Utf8GamePath path) - => !_files.UsedPaths.Contains(path); + => !files.UsedPaths.Contains(path); /// /// Try to set a given path for a given file. @@ -72,17 +62,17 @@ public class ModFileEditor /// public bool SetGamePath(ISubMod option, int fileIdx, int pathIdx, Utf8GamePath path) { - if (!CanAddGamePath(path) || fileIdx < 0 || fileIdx > _files.Available.Count) + if (!CanAddGamePath(path) || fileIdx < 0 || fileIdx > files.Available.Count) return false; - var registry = _files.Available[fileIdx]; + var registry = files.Available[fileIdx]; if (pathIdx > registry.SubModUsage.Count) return false; if ((pathIdx == -1 || pathIdx == registry.SubModUsage.Count) && !path.IsEmpty) - _files.AddUsedPath(option, registry, path); + files.AddUsedPath(option, registry, path); else - _files.ChangeUsedPath(registry, pathIdx, path); + files.ChangeUsedPath(registry, pathIdx, path); Changes = true; @@ -93,10 +83,10 @@ public class ModFileEditor /// Transform a set of files to the appropriate game paths with the given number of folders skipped, /// and add them to the given option. ///
- public int AddPathsToSelected(ISubMod option, IEnumerable files, int skipFolders = 0) + public int AddPathsToSelected(ISubMod option, IEnumerable files1, int skipFolders = 0) { var failed = 0; - foreach (var file in files) + foreach (var file in files1) { var gamePath = file.RelPath.ToGamePath(skipFolders); if (gamePath.IsEmpty) @@ -107,7 +97,7 @@ public class ModFileEditor if (CanAddGamePath(gamePath)) { - _files.AddUsedPath(option, file, gamePath); + files.AddUsedPath(option, file, gamePath); Changes = true; } else @@ -120,9 +110,9 @@ public class ModFileEditor } /// Remove all paths in the current option from the given files. - public void RemovePathsFromSelected(ISubMod option, IEnumerable files) + public void RemovePathsFromSelected(ISubMod option, IEnumerable files1) { - foreach (var file in files) + foreach (var file in files1) { for (var i = 0; i < file.SubModUsage.Count; ++i) { @@ -130,7 +120,7 @@ public class ModFileEditor if (option != opt) continue; - _files.RemoveUsedPath(option, file, path); + files.RemoveUsedPath(option, file, path); Changes = true; --i; } @@ -138,10 +128,10 @@ public class ModFileEditor } /// Delete all given files from your filesystem - public void DeleteFiles(Mod mod, ISubMod option, IEnumerable files) + public void DeleteFiles(Mod mod, ISubMod option, IEnumerable files1) { var deletions = 0; - foreach (var file in files) + foreach (var file in files1) { try { @@ -158,18 +148,18 @@ public class ModFileEditor if (deletions <= 0) return; - _modManager.Creator.ReloadMod(mod, false, out _); - _files.UpdateAll(mod, option); + modManager.Creator.ReloadMod(mod, false, out _); + files.UpdateAll(mod, option); } private bool CheckAgainstMissing(Mod mod, ISubMod option, FullPath file, Utf8GamePath key, bool removeUsed) { - if (!_files.Missing.Contains(file)) + if (!files.Missing.Contains(file)) return true; if (removeUsed) - _files.RemoveUsedPath(option, file, key); + files.RemoveUsedPath(option, file, key); Penumbra.Log.Debug($"[RemoveMissingPaths] Removing {key} -> {file} from {mod.Name}."); return false; diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 09c5c77a..bbf0d4b5 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -4,16 +4,14 @@ using Penumbra.Mods.Subclasses; namespace Penumbra.Mods; -public class ModMetaEditor +public class ModMetaEditor(ModManager modManager) { - private readonly ModManager _modManager; - - private readonly HashSet _imc = new(); - private readonly HashSet _eqp = new(); - private readonly HashSet _eqdp = new(); - private readonly HashSet _gmp = new(); - private readonly HashSet _est = new(); - private readonly HashSet _rsp = new(); + private readonly HashSet _imc = []; + private readonly HashSet _eqp = []; + private readonly HashSet _eqdp = []; + private readonly HashSet _gmp = []; + private readonly HashSet _est = []; + private readonly HashSet _rsp = []; public int OtherImcCount { get; private set; } public int OtherEqpCount { get; private set; } @@ -22,11 +20,7 @@ public class ModMetaEditor public int OtherEstCount { get; private set; } public int OtherRspCount { get; private set; } - - public ModMetaEditor(ModManager modManager) - => _modManager = modManager; - - public bool Changes { get; private set; } = false; + public bool Changes { get; private set; } public IReadOnlySet Imc => _imc; @@ -156,7 +150,7 @@ public class ModMetaEditor if (!Changes) return; - _modManager.OptionEditor.OptionSetManipulations(mod, groupIdx, optionIdx, Recombine().ToHashSet()); + modManager.OptionEditor.OptionSetManipulations(mod, groupIdx, optionIdx, Recombine().ToHashSet()); Changes = false; } diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index c146b6f4..a9a31212 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -10,7 +10,7 @@ namespace Penumbra.Mods.Editor; public class ModNormalizer(ModManager _modManager, Configuration _config) { - private readonly List>> _redirections = new(); + private readonly List>> _redirections = []; public Mod Mod { get; private set; } = null!; private string _normalizationDirName = null!; @@ -141,7 +141,7 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) { var directory = Directory.CreateDirectory(_normalizationDirName); for (var i = _redirections.Count; i < Mod.Groups.Count + 1; ++i) - _redirections.Add(new List>()); + _redirections.Add([]); if (_redirections[0].Count == 0) _redirections[0].Add(new Dictionary(Mod.Default.Files.Count)); @@ -169,7 +169,7 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) { _redirections[groupIdx + 1].EnsureCapacity(group.Count); for (var i = _redirections[groupIdx + 1].Count; i < group.Count; ++i) - _redirections[groupIdx + 1].Add(new Dictionary()); + _redirections[groupIdx + 1].Add([]); var groupDir = ModCreator.CreateModFolder(directory, group.Name, _config.ReplaceNonAsciiOnImport, true); foreach (var option in group.OfType()) diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index b9834da8..ada06264 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -4,17 +4,13 @@ using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; using Penumbra.Util; -public class ModSwapEditor +public class ModSwapEditor(ModManager modManager) { - private readonly ModManager _modManager; - private readonly Dictionary _swaps = new(); + private readonly Dictionary _swaps = []; public IReadOnlyDictionary Swaps => _swaps; - public ModSwapEditor(ModManager modManager) - => _modManager = modManager; - public void Revert(ISubMod option) { _swaps.SetTo(option.FileSwaps); @@ -26,7 +22,7 @@ public class ModSwapEditor if (!Changes) return; - _modManager.OptionEditor.OptionSetFileSwaps(mod, groupIdx, optionIdx, _swaps); + modManager.OptionEditor.OptionSetFileSwaps(mod, groupIdx, optionIdx, _swaps); Changes = false; } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 41cc023e..a9ef22cb 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,5 +1,6 @@ using OtterGui; using OtterGui.Classes; +using Penumbra.Mods.Editor; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs index a081f7bc..88c4e4ce 100644 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 52159258..c80334aa 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index a81ae55b..2b2bbf95 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -33,6 +33,7 @@ using Penumbra.UI.ModsTab; using Penumbra.UI.ResourceWatcher; using Penumbra.UI.Tabs; using Penumbra.UI.Tabs.Debug; +using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra.Services; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 8b6ef331..6d406461 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -26,6 +26,7 @@ using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI.Classes; using Penumbra.Util; +using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 926ba77b..9d57d3a8 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -8,6 +8,7 @@ using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.Meta.Manipulations; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index f7e64125..76fb8c96 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -6,6 +6,7 @@ using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Services; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index 0cc2e5c1..8ef6c30e 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -9,6 +9,7 @@ using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.Meta.Manipulations; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.UI.Classes; From 9fae88934d2ee827021d01f6bbaf98c7ed3a9bc6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 00:00:58 +1100 Subject: [PATCH 0388/1381] Calculate missing tangents on import, convert all to bitangents for use --- .../Import/Models/Import/SubMeshImporter.cs | 6 +- .../Import/Models/Import/VertexAttribute.cs | 123 +++++++++++++++++- 2 files changed, 122 insertions(+), 7 deletions(-) diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 51443f64..e5b5bc8e 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -140,11 +140,15 @@ public class SubMeshImporter private void BuildIndices() { + // TODO: glTF supports a bunch of primitive types, ref. Schema2.PrimitiveType. All this code is currently assuming that it's using plain triangles (4). It should probably be generalised to other formats - I _suspect_ we should be able to get away with evaulating the indices to triangles with GetTriangleIndices, but will need investigation. _indices = _primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); } private void BuildVertexAttributes() { + // Tangent calculation requires indices if missing. + ArgumentNullException.ThrowIfNull(_indices); + var accessors = _primitive.VertexAccessors; var morphAccessors = Enumerable.Range(0, _primitive.MorphTargetsCount) @@ -158,7 +162,7 @@ public class SubMeshImporter VertexAttribute.BlendWeight(accessors), VertexAttribute.BlendIndex(accessors, _nodeBoneMap), VertexAttribute.Normal(accessors, morphAccessors), - VertexAttribute.Tangent1(accessors, morphAccessors), + VertexAttribute.Tangent1(accessors, morphAccessors, _indices), VertexAttribute.Color(accessors), VertexAttribute.Uv(accessors), }; diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 0b0e90ba..5008b58e 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -242,10 +242,24 @@ public class VertexAttribute ); } - public static VertexAttribute? Tangent1(Accessors accessors, IEnumerable morphAccessors) + public static VertexAttribute? Tangent1(Accessors accessors, IEnumerable morphAccessors, ushort[] indices) { - if (!accessors.TryGetValue("TANGENT", out var accessor)) + if (!accessors.TryGetValue("NORMAL", out var normalAccessor)) + { + Penumbra.Log.Warning("Normals are required to facilitate import or calculation of tangents."); return null; + } + + var normals = normalAccessor.AsVector3Array(); + var values = accessors.TryGetValue("TANGENT", out var accessor) + ? accessor.AsVector4Array() + : CalculateTangents(accessors, indices, normals); + + if (values == null) + { + Penumbra.Log.Warning("No tangents available for sub-mesh. This could lead to incorrect lighting, or mismatched vertex attributes."); + return null; + } var element = new MdlStructs.VertexElement() { @@ -254,8 +268,6 @@ public class VertexAttribute Usage = (byte)MdlFile.VertexUsage.Tangent1, }; - var values = accessor.AsVector4Array(); - // Per glTF specification, TANGENT morph values are stored as vec3, with the W component always considered to be 0. var morphValues = morphAccessors .Select(a => a.GetValueOrDefault("TANGENT")?.AsVector3Array()) @@ -263,7 +275,7 @@ public class VertexAttribute return new VertexAttribute( element, - index => BuildByteFloat4(values[index]), + index => BuildBitangent(values[index], normals[index]), buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; @@ -272,11 +284,110 @@ public class VertexAttribute if (delta != null) value += new Vector4(delta.Value, 0); - return BuildByteFloat4(value); + return BuildBitangent(value, normals[vertexIndex]); } ); } + /// Build a byte array representing bitagent data computed from the provided tangent and normal. + /// XIV primarily stores bitangents, rather than tangents as with most other software, so we calculate on import. + private static byte[] BuildBitangent(Vector4 tangent, Vector3 normal) + { + var handedness = tangent.W; + var tangent3 = new Vector3(tangent.X, tangent.Y, tangent.Z); + var bitangent = Vector3.Normalize(Vector3.Cross(normal, tangent3)); + bitangent *= handedness; + + // Byte floats encode 0..1, and bitangents are stored as -1..1. Convert. + bitangent = (bitangent + Vector3.One) / 2; + return BuildByteFloat4(new Vector4(bitangent, handedness)); + } + + /// Attempt to calculate tangent values based on other pre-existing data. + private static Vector4[]? CalculateTangents(Accessors accessors, ushort[] indices, IList normals) + { + // To calculate tangents, we will also need access to uv data. + if (!accessors.TryGetValue("TEXCOORD_0", out var uvAccessor)) + return null; + + var positions = accessors["POSITION"].AsVector3Array(); + var uvs = uvAccessor.AsVector2Array(); + + // TODO: Surface this in the UI. + Penumbra.Log.Warning("Calculating tangents, this may result in degraded light interaction. For best results, ensure tangents are caculated or retained during export from 3D modelling tools."); + + var vertexCount = positions.Count; + + // https://github.com/TexTools/xivModdingFramework/blob/master/xivModdingFramework/Models/Helpers/ModelModifiers.cs#L1569 + // https://gamedev.stackexchange.com/a/68617 + // https://marti.works/posts/post-calculating-tangents-for-your-mesh/post/ + var tangents = new Vector3[vertexCount]; + var bitangents = new Vector3[vertexCount]; + + // Iterate over triangles, calculating tangents relative to the UVs. + for (var index = 0; index < indices.Length; index += 3) + { + // Collect information for this triangle. + var vertexIndex1 = indices[index]; + var vertexIndex2 = indices[index + 1]; + var vertexIndex3 = indices[index + 2]; + + var position1 = positions[vertexIndex1]; + var position2 = positions[vertexIndex2]; + var position3 = positions[vertexIndex3]; + + var texcoord1 = uvs[vertexIndex1]; + var texcoord2 = uvs[vertexIndex2]; + var texcoord3 = uvs[vertexIndex3]; + + // Calculate deltas for the position XYZ, and texcoord UV. + var edge1 = position2 - position1; + var edge2 = position3 - position1; + + var uv1 = texcoord2 - texcoord1; + var uv2 = texcoord3 - texcoord1; + + // Solve. + var r = 1.0f / (uv1.X * uv2.Y - uv1.Y * uv2.X); + var tangent = new Vector3( + (edge1.X * uv2.Y - edge2.X * uv1.Y) * r, + (edge1.Y * uv2.Y - edge2.Y * uv1.Y) * r, + (edge1.Z * uv2.Y - edge2.Z * uv1.Y) * r + ); + var bitangent = new Vector3( + (edge1.X * uv2.X - edge2.X * uv1.X) * r, + (edge1.Y * uv2.X - edge2.Y * uv1.X) * r, + (edge1.Z * uv2.X - edge2.Z * uv1.X) * r + ); + + // Update vertex values. + tangents[vertexIndex1] += tangent; + tangents[vertexIndex2] += tangent; + tangents[vertexIndex3] += tangent; + + bitangents[vertexIndex1] += bitangent; + bitangents[vertexIndex2] += bitangent; + bitangents[vertexIndex3] += bitangent; + } + + // All the triangles have been calcualted, normalise the results for each vertex. + var result = new Vector4[vertexCount]; + for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) + { + var n = normals[vertexIndex]; + var t = tangents[vertexIndex]; + var b = bitangents[vertexIndex]; + + // Gram-Schmidt orthogonalize and calculate handedness. + var tangent = Vector3.Normalize(t - n * Vector3.Dot(n, t)); + var handedness = Vector3.Dot(Vector3.Cross(t, b), n) > 0 ? 1 : -1; + + result[vertexIndex] = new Vector4(tangent, handedness); + } + + return result; + } + public static VertexAttribute? Color(Accessors accessors) { if (!accessors.TryGetValue("COLOR_0", out var accessor)) From ea04cc554f9e1b6be72ba538b9ea737e6dbfec45 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 00:22:13 +1100 Subject: [PATCH 0389/1381] Fix up export a little --- Penumbra/Import/Models/Export/MeshExporter.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 8127f348..b00ca49e 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -318,11 +318,17 @@ public class MeshExporter ); if (_geometryType == typeof(VertexPositionNormalTangent)) + { + // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. + // TODO: While this assumption is safe, it would be sensible to actually check. + var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1]) * 2 - Vector4.One; + return new VertexPositionNormalTangent( ToVector3(attributes[MdlFile.VertexUsage.Position]), ToVector3(attributes[MdlFile.VertexUsage.Normal]), - FixTangentVector(ToVector4(attributes[MdlFile.VertexUsage.Tangent1])) + bitangent ); + } throw new Exception($"Unknown geometry type {_geometryType}."); } @@ -440,11 +446,6 @@ public class MeshExporter throw new Exception($"Unknown skinning type {_skinningType}"); } - /// Clamps any tangent W value other than 1 to -1. - /// Some XIV models seemingly store -1 as 0, this patches over that. - private static Vector4 FixTangentVector(Vector4 tangent) - => tangent with { W = tangent.W == 1 ? 1 : -1 }; - /// Convert a vertex attribute value to a Vector2. Supported inputs are Vector2, Vector3, and Vector4. private static Vector2 ToVector2(object data) => data switch From 5e794b73baca68c557093ebcd0b4a1cecdd41659 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 01:40:19 +1100 Subject: [PATCH 0390/1381] Consider normal morphs for morphed bitangent calculations --- .../Import/Models/Import/VertexAttribute.cs | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 5008b58e..bbf49bcf 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -251,11 +251,11 @@ public class VertexAttribute } var normals = normalAccessor.AsVector3Array(); - var values = accessors.TryGetValue("TANGENT", out var accessor) + var tangents = accessors.TryGetValue("TANGENT", out var accessor) ? accessor.AsVector4Array() : CalculateTangents(accessors, indices, normals); - if (values == null) + if (tangents == null) { Penumbra.Log.Warning("No tangents available for sub-mesh. This could lead to incorrect lighting, or mismatched vertex attributes."); return null; @@ -269,22 +269,30 @@ public class VertexAttribute }; // Per glTF specification, TANGENT morph values are stored as vec3, with the W component always considered to be 0. - var morphValues = morphAccessors + var tangentMorphValues = morphAccessors + .Select(a => a.GetValueOrDefault("TANGENT")?.AsVector3Array()) + .ToArray(); + + var normalMorphValues = morphAccessors .Select(a => a.GetValueOrDefault("TANGENT")?.AsVector3Array()) .ToArray(); return new VertexAttribute( element, - index => BuildBitangent(values[index], normals[index]), + index => BuildBitangent(tangents[index], normals[index]), buildMorph: (morphIndex, vertexIndex) => { - var value = values[vertexIndex]; + var tangent = tangents[vertexIndex]; + var tangentDelta = tangentMorphValues[morphIndex]?[vertexIndex]; + if (tangentDelta != null) + tangent += new Vector4(tangentDelta.Value, 0); - var delta = morphValues[morphIndex]?[vertexIndex]; - if (delta != null) - value += new Vector4(delta.Value, 0); + var normal = normals[vertexIndex]; + var normalDelta = normalMorphValues[morphIndex]?[vertexIndex]; + if (normalDelta != null) + normal += normalDelta.Value; - return BuildBitangent(value, normals[vertexIndex]); + return BuildBitangent(tangent, normal); } ); } From 0ff7e49e4d2e0572bd1b3873af4f77a39a050cb4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 15 Jan 2024 21:38:25 +0100 Subject: [PATCH 0391/1381] Prepare changelog. --- Penumbra/Services/MessageService.cs | 4 ++-- Penumbra/UI/Changelog.cs | 19 +++++++++++++++++++ Penumbra/UI/Tabs/MessagesTab.cs | 11 +++-------- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index 06c3c4d0..daad29ef 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -25,8 +25,8 @@ public class MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat) : Ot new UIForegroundPayload(0), new UIGlowPayload(0), new TextPayload(item.Name), - new RawPayload(new byte[] { 0x02, 0x27, 0x07, 0xCF, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03 }), - new RawPayload(new byte[] { 0x02, 0x13, 0x02, 0xEC, 0x03 }), + new RawPayload([0x02, 0x27, 0x07, 0xCF, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03]), + new RawPayload([0x02, 0x13, 0x02, 0xEC, 0x03]), }; // @formatter:on diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index d5b77bf4..94084fea 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -46,10 +46,29 @@ public class PenumbraChangelog Add8_1_2(Changelog); Add8_2_0(Changelog); Add8_3_0(Changelog); + Add1_0_0_0(Changelog); } #region Changelogs + private static void Add1_0_0_0(Changelog log) + => log.NextVersion("Version 1.0.0.0") + .RegisterHighlight("Mods in the mod selector can now be filtered by changed item categories.") + .RegisterHighlight("Model Editing options in the Advanced Editing Window have been greatly extended (by Ackwell):") + .RegisterEntry("Attributes and referenced materials can now be set per mesh.", 1) + .RegisterEntry("Model files (.mdl) can now be exported to the well-established glTF format, which can be imported e.g. by Blender.", 1) + .RegisterEntry("glTF files can also be imported back to a .mdl file.", 1) + .RegisterHighlight("Model Export and Import are a work in progress and may encounter issues, not support all cases or produce wrong results, please let us know!", 1) + .RegisterEntry("The last selected mod and the open/close state of the Advanced Editing Window are now stored across launches.") + .RegisterEntry("Footsteps of certain mounts will now be associated to collections correctly.") + .RegisterEntry("Save-in-Place in the texture tab now requires the configurable modifier.") + .RegisterEntry("Updated OtterTex to a newer version of DirectXTex.") + .RegisterEntry("Fixed an issue with horizontal scrolling if a mod title was very long.") + .RegisterEntry("Fixed an issue with the mod panels header not updating its data when the selected mod updates.") + .RegisterEntry("Fixed some issues with EQDP files for invalid characters.") + .RegisterEntry("Fixed an issue with the FileDialog being drawn twice in certain situations.") + .RegisterEntry("A lot of backend changes that should not have an effect on users, but may cause issues if something got messed up."); + private static void Add8_3_0(Changelog log) => log.NextVersion("Version 0.8.3.0") .RegisterHighlight("Improved the UI for the On-Screen tabs with highlighting of used paths, filtering and more selections. (by Ny)") diff --git a/Penumbra/UI/Tabs/MessagesTab.cs b/Penumbra/UI/Tabs/MessagesTab.cs index e834a4b4..abaf2ba6 100644 --- a/Penumbra/UI/Tabs/MessagesTab.cs +++ b/Penumbra/UI/Tabs/MessagesTab.cs @@ -3,19 +3,14 @@ using Penumbra.Services; namespace Penumbra.UI.Tabs; -public class MessagesTab : ITab +public class MessagesTab(MessageService messages) : ITab { public ReadOnlySpan Label => "Messages"u8; - private readonly MessageService _messages; - - public MessagesTab(MessageService messages) - => _messages = messages; - public bool IsVisible - => _messages.Count > 0; + => messages.Count > 0; public void DrawContent() - => _messages.Draw(); + => messages.Draw(); } From da1b9e9e90e3ab97545bc013e152e6dec5d9c990 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jan 2024 16:34:57 +0100 Subject: [PATCH 0392/1381] Cleanup, fix tangent/normal mixup. --- Penumbra/Import/Models/Export/MeshExporter.cs | 2 +- .../Import/Models/Import/SubMeshImporter.cs | 2 +- .../Import/Models/Import/VertexAttribute.cs | 56 +++++++++---------- 3 files changed, 29 insertions(+), 31 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index b00ca49e..da6b4df4 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -23,7 +23,7 @@ public class MeshExporter ? scene.AddSkinnedMesh(data.Mesh, Matrix4x4.Identity, joints) : scene.AddRigidMesh(data.Mesh, Matrix4x4.Identity); - var extras = new Dictionary(); + var extras = new Dictionary(data.Attributes.Length); foreach (var attribute in data.Attributes) extras.Add(attribute, true); diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index e5b5bc8e..bca75090 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -140,7 +140,7 @@ public class SubMeshImporter private void BuildIndices() { - // TODO: glTF supports a bunch of primitive types, ref. Schema2.PrimitiveType. All this code is currently assuming that it's using plain triangles (4). It should probably be generalised to other formats - I _suspect_ we should be able to get away with evaulating the indices to triangles with GetTriangleIndices, but will need investigation. + // TODO: glTF supports a bunch of primitive types, ref. Schema2.PrimitiveType. All this code is currently assuming that it's using plain triangles (4). It should probably be generalised to other formats - I _suspect_ we should be able to get away with evaluating the indices to triangles with GetTriangleIndices, but will need investigation. _indices = _primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); } diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index bbf49bcf..b5b20a3a 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -244,7 +244,7 @@ public class VertexAttribute public static VertexAttribute? Tangent1(Accessors accessors, IEnumerable morphAccessors, ushort[] indices) { - if (!accessors.TryGetValue("NORMAL", out var normalAccessor)) + if (!accessors.TryGetValue("NORMAL", out var normalAccessor)) { Penumbra.Log.Warning("Normals are required to facilitate import or calculation of tangents."); return null; @@ -261,7 +261,7 @@ public class VertexAttribute return null; } - var element = new MdlStructs.VertexElement() + var element = new MdlStructs.VertexElement { Stream = 1, Type = (byte)MdlFile.VertexType.ByteFloat4, @@ -269,26 +269,23 @@ public class VertexAttribute }; // Per glTF specification, TANGENT morph values are stored as vec3, with the W component always considered to be 0. - var tangentMorphValues = morphAccessors - .Select(a => a.GetValueOrDefault("TANGENT")?.AsVector3Array()) - .ToArray(); - - var normalMorphValues = morphAccessors - .Select(a => a.GetValueOrDefault("TANGENT")?.AsVector3Array()) - .ToArray(); + var morphValues = morphAccessors + .Select(a => (Tangent: a.GetValueOrDefault("TANGENT")?.AsVector3Array(), + Normal: a.GetValueOrDefault("NORMAL")?.AsVector3Array())) + .ToList(); return new VertexAttribute( element, index => BuildBitangent(tangents[index], normals[index]), buildMorph: (morphIndex, vertexIndex) => { - var tangent = tangents[vertexIndex]; - var tangentDelta = tangentMorphValues[morphIndex]?[vertexIndex]; + var tangent = tangents[vertexIndex]; + var tangentDelta = morphValues[morphIndex].Tangent?[vertexIndex]; if (tangentDelta != null) tangent += new Vector4(tangentDelta.Value, 0); - var normal = normals[vertexIndex]; - var normalDelta = normalMorphValues[morphIndex]?[vertexIndex]; + var normal = normals[vertexIndex]; + var normalDelta = morphValues[morphIndex].Normal?[vertexIndex]; if (normalDelta != null) normal += normalDelta.Value; @@ -297,13 +294,13 @@ public class VertexAttribute ); } - /// Build a byte array representing bitagent data computed from the provided tangent and normal. + /// Build a byte array representing bitangent data computed from the provided tangent and normal. /// XIV primarily stores bitangents, rather than tangents as with most other software, so we calculate on import. private static byte[] BuildBitangent(Vector4 tangent, Vector3 normal) { var handedness = tangent.W; - var tangent3 = new Vector3(tangent.X, tangent.Y, tangent.Z); - var bitangent = Vector3.Normalize(Vector3.Cross(normal, tangent3)); + var tangent3 = new Vector3(tangent.X, tangent.Y, tangent.Z); + var bitangent = Vector3.Normalize(Vector3.Cross(normal, tangent3)); bitangent *= handedness; // Byte floats encode 0..1, and bitangents are stored as -1..1. Convert. @@ -319,19 +316,20 @@ public class VertexAttribute return null; var positions = accessors["POSITION"].AsVector3Array(); - var uvs = uvAccessor.AsVector2Array(); + var uvs = uvAccessor.AsVector2Array(); // TODO: Surface this in the UI. - Penumbra.Log.Warning("Calculating tangents, this may result in degraded light interaction. For best results, ensure tangents are caculated or retained during export from 3D modelling tools."); + Penumbra.Log.Warning( + "Calculating tangents, this may result in degraded light interaction. For best results, ensure tangents are caculated or retained during export from 3D modelling tools."); var vertexCount = positions.Count; // https://github.com/TexTools/xivModdingFramework/blob/master/xivModdingFramework/Models/Helpers/ModelModifiers.cs#L1569 // https://gamedev.stackexchange.com/a/68617 // https://marti.works/posts/post-calculating-tangents-for-your-mesh/post/ - var tangents = new Vector3[vertexCount]; + var tangents = new Vector3[vertexCount]; var bitangents = new Vector3[vertexCount]; - + // Iterate over triangles, calculating tangents relative to the UVs. for (var index = 0; index < indices.Length; index += 3) { @@ -344,16 +342,16 @@ public class VertexAttribute var position2 = positions[vertexIndex2]; var position3 = positions[vertexIndex3]; - var texcoord1 = uvs[vertexIndex1]; - var texcoord2 = uvs[vertexIndex2]; - var texcoord3 = uvs[vertexIndex3]; - + var texCoord1 = uvs[vertexIndex1]; + var texCoord2 = uvs[vertexIndex2]; + var texCoord3 = uvs[vertexIndex3]; + // Calculate deltas for the position XYZ, and texcoord UV. var edge1 = position2 - position1; var edge2 = position3 - position1; - - var uv1 = texcoord2 - texcoord1; - var uv2 = texcoord3 - texcoord1; + + var uv1 = texCoord2 - texCoord1; + var uv2 = texCoord3 - texCoord1; // Solve. var r = 1.0f / (uv1.X * uv2.Y - uv1.Y * uv2.X); @@ -378,7 +376,7 @@ public class VertexAttribute bitangents[vertexIndex3] += bitangent; } - // All the triangles have been calcualted, normalise the results for each vertex. + // All the triangles have been calculated, normalise the results for each vertex. var result = new Vector4[vertexCount]; for (var vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++) { @@ -387,7 +385,7 @@ public class VertexAttribute var b = bitangents[vertexIndex]; // Gram-Schmidt orthogonalize and calculate handedness. - var tangent = Vector3.Normalize(t - n * Vector3.Dot(n, t)); + var tangent = Vector3.Normalize(t - n * Vector3.Dot(n, t)); var handedness = Vector3.Dot(Vector3.Cross(t, b), n) > 0 ? 1 : -1; result[vertexIndex] = new Vector4(tangent, handedness); From 8509ccba30ab52c938470d059e64dc00782b0358 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 16 Jan 2024 15:39:56 +0000 Subject: [PATCH 0393/1381] [CI] Updating repo.json for 1.0.0.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 4dfac5a0..01d169b5 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "0.8.3.1", - "TestingAssemblyVersion": "0.8.3.7", + "AssemblyVersion": "1.0.0.0", + "TestingAssemblyVersion": "1.0.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_0.8.3.7/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/0.8.3.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From e5ddae585c536b94987699dfe2afe8fad72a7a45 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jan 2024 18:21:46 +0100 Subject: [PATCH 0394/1381] Update Submodules. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 4c32d2d4..6d6e7b37 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 4c32d2d448c4e36ea665276ed755a96fa4907c33 +Subproject commit 6d6e7b37c31bc82b8b2811c85a09f67fb0434f8a diff --git a/Penumbra.GameData b/Penumbra.GameData index 13545143..119ffaa2 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 135451430344f2f12e8c02fd4c4c6f0875d74e60 +Subproject commit 119ffaa240f0446bdd05c5254c4e0dd8539a2d7d From 0b50593acdc6c6fb7a3a556a83ca802a3158d79f Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 16 Jan 2024 17:24:05 +0000 Subject: [PATCH 0395/1381] [CI] Updating repo.json for 1.0.0.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 01d169b5..c328dd6f 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.0", - "TestingAssemblyVersion": "1.0.0.0", + "AssemblyVersion": "1.0.0.1", + "TestingAssemblyVersion": "1.0.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From bbac3daf0130ea55d2ab8275ae0eae7384aa3e69 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jan 2024 12:14:22 +0100 Subject: [PATCH 0396/1381] Update BNPCs. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 119ffaa2..afc03458 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 119ffaa240f0446bdd05c5254c4e0dd8539a2d7d +Subproject commit afc0345819ca64ec08432e0011b65ff9880c2967 From fdd01459759b3b31e149f6f862a8565da393684e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jan 2024 12:14:58 +0100 Subject: [PATCH 0397/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 6d6e7b37..92590901 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 6d6e7b37c31bc82b8b2811c85a09f67fb0434f8a +Subproject commit 9259090121b26f097948e7bbd83b32708ea0410d From eb02d2a7a74d7f5e93dd76fe7a32ee3810e44fd4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jan 2024 14:37:49 +0100 Subject: [PATCH 0398/1381] Fix variant path generation. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index afc03458..ab09e21f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit afc0345819ca64ec08432e0011b65ff9880c2967 +Subproject commit ab09e21fa46be83f82c400dfd2fe05a281b6f28d From 4b81b065aa406903398de4bee7292aca4094bf9f Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 23:06:02 +1100 Subject: [PATCH 0399/1381] Calculate primary BoundingBox --- Penumbra/Import/Models/Import/BoundingBox.cs | 33 +++++++++++++++++++ Penumbra/Import/Models/Import/MeshImporter.cs | 7 ++++ .../Import/Models/Import/ModelImporter.cs | 7 +++- .../Import/Models/Import/SubMeshImporter.cs | 14 ++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 Penumbra/Import/Models/Import/BoundingBox.cs diff --git a/Penumbra/Import/Models/Import/BoundingBox.cs b/Penumbra/Import/Models/Import/BoundingBox.cs new file mode 100644 index 00000000..34aac827 --- /dev/null +++ b/Penumbra/Import/Models/Import/BoundingBox.cs @@ -0,0 +1,33 @@ +using Lumina.Data.Parsing; + +namespace Penumbra.Import.Models.Import; + +/// Mutable representation of the bounding box surrouding a collection of vertices. +public class BoundingBox +{ + private Vector3 _minimum = Vector3.Zero; + private Vector3 _maximum = Vector3.Zero; + + /// Use the specified position to update this bounding box, expanding it if necessary. + public void Merge(Vector3 position) + { + _minimum = Vector3.Min(_minimum, position); + _maximum = Vector3.Max(_maximum, position); + } + + /// Merge the provided bounding box into this one, expanding it if necessary. + /// + public void Merge(BoundingBox other) + { + _minimum = Vector3.Min(_minimum, other._minimum); + _maximum = Vector3.Max(_maximum, other._maximum); + } + + /// Convert this bounding box to the struct format used in .mdl data structures. + public MdlStructs.BoundingBoxStruct ToStruct() + => new MdlStructs.BoundingBoxStruct + { + Min = [_minimum.X, _minimum.Y, _minimum.Z, 1], + Max = [_maximum.X, _maximum.Y, _maximum.Z, 1], + }; +} diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 7da4d1d7..2a461304 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -19,6 +19,8 @@ public class MeshImporter(IEnumerable nodes) public List? Bones; + public BoundingBox BoundingBox; + public List MetaAttributes; public List ShapeKeys; @@ -50,6 +52,8 @@ public class MeshImporter(IEnumerable nodes) private List? _bones; + private readonly BoundingBox _boundingBox = new BoundingBox(); + private readonly List _metaAttributes = []; private readonly Dictionary> _shapeValues = []; @@ -87,6 +91,7 @@ public class MeshImporter(IEnumerable nodes) VertexBuffer = _streams[0].Concat(_streams[1]).Concat(_streams[2]), Indices = _indices, Bones = _bones, + BoundingBox = _boundingBox, MetaAttributes = _metaAttributes, ShapeKeys = _shapeValues .Select(pair => new MeshShapeKey() @@ -154,6 +159,8 @@ public class MeshImporter(IEnumerable nodes) })); } + _boundingBox.Merge(subMesh.BoundingBox); + // And finally, merge in the sub-mesh struct itself. _subMeshes.Add(subMesh.SubMeshStruct with { diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 3b3d2cd0..1b7fdfa5 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -29,6 +29,8 @@ public partial class ModelImporter(ModelRoot model) private readonly List _bones = []; private readonly List _boneTables = []; + private readonly BoundingBox _boundingBox = new BoundingBox(); + private readonly List _metaAttributes = []; private readonly Dictionary> _shapeMeshes = []; @@ -95,9 +97,10 @@ public partial class ModelImporter(ModelRoot model) Materials = [.. materials], + BoundingBoxes = _boundingBox.ToStruct(), + // TODO: Would be good to calculate all of this up the tree. Radius = 1, - BoundingBoxes = MdlFile.EmptyBoundingBox, BoneBoundingBoxes = Enumerable.Repeat(MdlFile.EmptyBoundingBox, _bones.Count).ToArray(), RemainingData = [.._vertexBuffer, ..indexBuffer], }; @@ -156,6 +159,8 @@ public partial class ModelImporter(ModelRoot model) .ToArray(), }); + _boundingBox.Merge(mesh.BoundingBox); + _subMeshes.AddRange(mesh.SubMeshStructs.Select(m => m with { AttributeIndexMask = Utility.GetMergedAttributeMask( diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index bca75090..6a5d0d52 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -21,6 +21,8 @@ public class SubMeshImporter public ushort[] Indices; + public BoundingBox BoundingBox; + public string[] MetaAttributes; public Dictionary> ShapeValues; @@ -44,6 +46,8 @@ public class SubMeshImporter private ushort[]? _indices; + private BoundingBox _boundingBox = new BoundingBox(); + private string[]? _metaAttributes; private readonly List? _morphNames; @@ -90,9 +94,11 @@ public class SubMeshImporter private SubMesh Create() { // Build all the data we'll need. + // TODO: This structure is verging on a little silly. Reconsider. BuildIndices(); BuildVertexAttributes(); BuildVertices(); + BuildBoundingBox(); BuildMetaAttributes(); ArgumentNullException.ThrowIfNull(_indices); @@ -133,6 +139,7 @@ public class SubMeshImporter Strides = _strides, Streams = _streams, Indices = _indices, + BoundingBox = _boundingBox, MetaAttributes = _metaAttributes, ShapeValues = _shapeValues, }; @@ -255,6 +262,13 @@ public class SubMeshImporter _shapeValues = morphShapeValues; } + private void BuildBoundingBox() + { + var positions = _primitive.VertexAccessors["POSITION"].AsVector3Array(); + foreach (var position in positions) + _boundingBox.Merge(position); + } + private void BuildMetaAttributes() { // We consider any "extras" key with a boolean value set to `true` to be an attribute. From b089bbca37b3006401b4950f6847d9c38c9c7391 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 23:13:53 +1100 Subject: [PATCH 0400/1381] Merge element ids and flags --- .../ModEditWindow.Models.MdlTab.cs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 9cfe0739..841eff4c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,3 +1,4 @@ +using Lumina.Data.Parsing; using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; @@ -161,6 +162,13 @@ public partial class ModEditWindow if (ImportKeepAttributes) MergeAttributes(newMdl, Mdl); + // Until someone works out how to actually author these, unconditionally merge element ids. + MergeElementIds(newMdl, Mdl); + + // TODO: Add flag editing. + newMdl.Flags1 = Mdl.Flags1; + newMdl.Flags2 = Mdl.Flags2; + Initialize(newMdl); _dirty = true; } @@ -210,6 +218,29 @@ public partial class ModEditWindow } } + /// Merge element ids from the source onto the target. + /// Model that will be updated. > + /// Model to copy element ids from. + private static void MergeElementIds(MdlFile target, MdlFile source) + { + var elementIds = new List(); + + foreach (var sourceElement in source.ElementIds) + { + var sourceBone = source.Bones[sourceElement.ParentBoneName]; + var targetIndex = target.Bones.IndexOf(sourceBone); + // Given that there's no means of authoring these at the moment, this should probably remain a hard error. + if (targetIndex == -1) + throw new Exception($"Failed to merge element IDs. Original model contains element IDs targeting bone {sourceBone}, which is not present on the imported model."); + elementIds.Add(sourceElement with + { + ParentBoneName = (uint)targetIndex, + }); + } + + target.ElementIds = [.. elementIds]; + } + private void RecordIoExceptions(Exception? exception) { IoExceptions = exception switch { From 107f6706d315eb0dd5917f44e8fb87fdd45d70e6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 23:14:12 +1100 Subject: [PATCH 0401/1381] i am immensely vain --- Penumbra/UI/Changelog.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 94084fea..67ab1a87 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -54,7 +54,7 @@ public class PenumbraChangelog private static void Add1_0_0_0(Changelog log) => log.NextVersion("Version 1.0.0.0") .RegisterHighlight("Mods in the mod selector can now be filtered by changed item categories.") - .RegisterHighlight("Model Editing options in the Advanced Editing Window have been greatly extended (by Ackwell):") + .RegisterHighlight("Model Editing options in the Advanced Editing Window have been greatly extended (by ackwell):") .RegisterEntry("Attributes and referenced materials can now be set per mesh.", 1) .RegisterEntry("Model files (.mdl) can now be exported to the well-established glTF format, which can be imported e.g. by Blender.", 1) .RegisterEntry("glTF files can also be imported back to a .mdl file.", 1) From 2c5f22047a1d84eff94cbce4f14f9b9ee1f89bb2 Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 17 Jan 2024 23:25:20 +1100 Subject: [PATCH 0402/1381] Generate white vertex colours if missing --- Penumbra/Import/Models/Import/VertexAttribute.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index b5b20a3a..7c875162 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -394,10 +394,9 @@ public class VertexAttribute return result; } - public static VertexAttribute? Color(Accessors accessors) + public static VertexAttribute Color(Accessors accessors) { - if (!accessors.TryGetValue("COLOR_0", out var accessor)) - return null; + accessors.TryGetValue("COLOR_0", out var accessor); var element = new MdlStructs.VertexElement() { @@ -406,11 +405,12 @@ public class VertexAttribute Usage = (byte)MdlFile.VertexUsage.Color, }; - var values = accessor.AsVector4Array(); + // Some shaders rely on the presence of vertex colors to render - fall back to a pure white value if it's missing. + var values = accessor?.AsVector4Array(); return new VertexAttribute( element, - index => BuildByteFloat4(values[index]) + index => BuildByteFloat4(values?[index] ?? Vector4.One) ); } From 202f6e472869547de56910f732d3769260cf4aca Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 18 Jan 2024 00:09:19 +1100 Subject: [PATCH 0403/1381] Fix file path resolution for file swaps --- .../UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 841eff4c..26fcd1ee 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -259,11 +259,12 @@ public partial class ModEditWindow if (!Utf8GamePath.FromString(path, out var utf8Path, true)) throw new Exception($"Resolved path {path} could not be converted to a game path."); - var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8Path); + var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8Path) ?? new FullPath(utf8Path); + // TODO: is it worth trying to use streams for these instead? I'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... - var bytes = resolvedPath == null - ? _edit._gameData.GetFile(path)?.Data - : File.ReadAllBytes(resolvedPath.Value.ToPath()); + var bytes = resolvedPath.IsRooted + ? File.ReadAllBytes(resolvedPath.FullName) + : _edit._gameData.GetFile(resolvedPath.InternalName.ToString())?.Data; // TODO: some callers may not care about failures - handle exceptions separately? return bytes ?? throw new Exception( From 65af4267f073533b4795953808621bc8120d4004 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jan 2024 14:46:44 +0100 Subject: [PATCH 0404/1381] Fix variant path generation (2), file was unsaved :/ --- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index 78c49b59..cd36de93 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -46,7 +46,7 @@ public static class CustomizationSwap PrimaryId idFrom, PrimaryId idTo, byte variant, ref string fileName, ref bool dataWasChanged) { - variant = slot is BodySlot.Face or BodySlot.Ear ? byte.MaxValue : variant; + variant = slot is BodySlot.Face or BodySlot.Ear ? Variant.None.Id : variant; var mtrlFromPath = GamePaths.Character.Mtrl.Path(race, slot, idFrom, fileName, out var gameRaceFrom, out var gameSetIdFrom, variant); var mtrlToPath = GamePaths.Character.Mtrl.Path(race, slot, idTo, fileName, out var gameRaceTo, out var gameSetIdTo, variant); From 8c763d5379778bfc0bbf90cba265f0be8e80305d Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 17 Jan 2024 16:24:57 +0000 Subject: [PATCH 0405/1381] [CI] Updating repo.json for 1.0.0.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index c328dd6f..aa03fe77 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.1", - "TestingAssemblyVersion": "1.0.0.1", + "AssemblyVersion": "1.0.0.2", + "TestingAssemblyVersion": "1.0.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 5c15a3a4ffdac635b82f11aeb7bba4ad8b715899 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 19 Jan 2024 02:09:43 +1100 Subject: [PATCH 0406/1381] Set up notifier infrastructure --- Penumbra/Import/Models/IoNotifier.cs | 52 +++++++++++++++++++ .../ModEditWindow.Models.MdlTab.cs | 1 + .../UI/AdvancedWindow/ModEditWindow.Models.cs | 37 +++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 Penumbra/Import/Models/IoNotifier.cs diff --git a/Penumbra/Import/Models/IoNotifier.cs b/Penumbra/Import/Models/IoNotifier.cs new file mode 100644 index 00000000..e1d649f6 --- /dev/null +++ b/Penumbra/Import/Models/IoNotifier.cs @@ -0,0 +1,52 @@ +using Dalamud.Interface.Internal.Notifications; +using OtterGui.Classes; + +namespace Penumbra.Import.Models; + +public record class IoNotifier +{ + /// Notification subclass so that we have a distinct type to filter by. + private class LegallyDistinctNotification : Notification + { + public LegallyDistinctNotification(string content, NotificationType type): base(content, type) + {} + } + + private readonly DateTime _startTime = DateTime.UtcNow; + private string _context = ""; + + /// Create a new notifier with the specified context appended to any other context already present. + public IoNotifier WithContext(string context) + => this with { _context = $"{_context}{context}: "}; + + /// Send a warning with any current context to notification channels. + public void Warning(string content) + => SendNotification(content, NotificationType.Warning); + + /// Get the current warnings for this notifier. + /// This does not currently filter to notifications with the current notifier's context - it will return all IO notifications from all notifiers. + public IEnumerable GetWarnings() + => GetFilteredNotifications(NotificationType.Warning); + + /// Create an exception with any current context. + [StackTraceHidden] + public Exception Exception(string message) + => Exception(message); + + /// Create an exception of the provided type with any current context. + [StackTraceHidden] + public TException Exception(string message) + where TException : Exception, new() + => (TException)Activator.CreateInstance(typeof(TException), $"{_context}{message}")!; + + private void SendNotification(string message, NotificationType type) + => Penumbra.Messager.AddMessage( + new LegallyDistinctNotification($"{_context}{message}", type), + true, false, true, false + ); + + private IEnumerable GetFilteredNotifications(NotificationType type) + => Penumbra.Messager + .Where(p => p.Key >= _startTime && p.Value is LegallyDistinctNotification && p.Value.NotificationType == type) + .Select(p => p.Value.PrintMessage); +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 26fcd1ee..15c6cb21 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -25,6 +25,7 @@ public partial class ModEditWindow private bool _dirty; public bool PendingIo { get; private set; } public List IoExceptions { get; private set; } = []; + public List IoWarnings { get; private set; } = []; public MdlTab(ModEditWindow edit, byte[] bytes, string path) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index ad609285..1a200fdf 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -63,6 +63,7 @@ public partial class ModEditWindow DrawExport(tab, childSize, disabled); DrawIoExceptions(tab); + DrawIoWarnings(tab); } private void DrawImport(MdlTab tab, Vector2 size, bool _1) @@ -148,7 +149,43 @@ public partial class ModEditWindow using var exceptionNode = ImRaii.TreeNode(message); if (exceptionNode) + { + ImGui.Dummy(new Vector2(ImGui.GetStyle().IndentSpacing, 0)); + ImGui.SameLine(); ImGuiUtil.TextWrapped(exception.ToString()); + } + } + } + + private static void DrawIoWarnings(MdlTab tab) + { + if (tab.IoWarnings.Count == 0) + return; + + var size = new Vector2(ImGui.GetContentRegionAvail().X, 0); + using var frame = ImRaii.FramedGroup("Warnings", size, headerPreIcon: FontAwesomeIcon.ExclamationCircle, borderColor: 0xFF40FFFF); + + var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; + foreach (var (warning, index) in tab.IoWarnings.WithIndex()) + { + using var id = ImRaii.PushId(index); + var textSize = ImGui.CalcTextSize(warning).X; + + if (textSize <= spaceAvail) + { + ImRaii.TreeNode(warning, ImGuiTreeNodeFlags.Leaf).Dispose(); + continue; + } + + var firstLine = warning[..(int)Math.Floor(warning.Length * (spaceAvail / textSize))] + "..."; + + using var warningNode = ImRaii.TreeNode(firstLine); + if (warningNode) + { + ImGui.Dummy(new Vector2(ImGui.GetStyle().IndentSpacing, 0)); + ImGui.SameLine(); + ImGuiUtil.TextWrapped(warning.ToString()); + } } } From 6f3be39cb9288f2c7e46559b77b5264ec36b4ca4 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 19 Jan 2024 02:11:50 +1100 Subject: [PATCH 0407/1381] Wire up notifications through export --- .../Import/Models/Export/MaterialExporter.cs | 8 ++--- Penumbra/Import/Models/Export/MeshExporter.cs | 35 ++++++++++--------- .../Import/Models/Export/ModelExporter.cs | 15 ++++---- Penumbra/Import/Models/ModelManager.cs | 35 ++++++++++++------- .../ModEditWindow.Models.MdlTab.cs | 2 ++ 5 files changed, 55 insertions(+), 40 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 2a49e77f..61609bb5 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -23,7 +23,7 @@ public class MaterialExporter } /// Build a glTF material from a hydrated XIV model, with the provided name. - public static MaterialBuilder Export(Material material, string name) + public static MaterialBuilder Export(Material material, string name, IoNotifier notifier) { Penumbra.Log.Debug($"Exporting material \"{name}\"."); return material.Mtrl.ShaderPackage.Name switch @@ -34,7 +34,7 @@ public class MaterialExporter "hair.shpk" => BuildHair(material, name), "iris.shpk" => BuildIris(material, name), "skin.shpk" => BuildSkin(material, name), - _ => BuildFallback(material, name), + _ => BuildFallback(material, name, notifier), }; } @@ -335,9 +335,9 @@ public class MaterialExporter /// Build a material from a source with unknown semantics. /// Will make a loose effort to fetch common / simple textures. - private static MaterialBuilder BuildFallback(Material material, string name) + private static MaterialBuilder BuildFallback(Material material, string name, IoNotifier notifier) { - Penumbra.Log.Warning($"Unhandled shader package: {material.Mtrl.ShaderPackage.Name}"); + notifier.Warning($"Unhandled shader package: {material.Mtrl.ShaderPackage.Name}"); var materialBuilder = BuildSharedBase(material, name) .WithMetallicRoughnessShader() diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index da6b4df4..71e8f082 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -38,14 +38,16 @@ public class MeshExporter public string[] Attributes; } - public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton) + public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) { - var self = new MeshExporter(mdl, lod, meshIndex, materials, skeleton?.Names); + var self = new MeshExporter(mdl, lod, meshIndex, materials, skeleton?.Names, notifier); return new Mesh(self.BuildMeshes(), skeleton?.Joints); } private const byte MaximumMeshBufferStreams = 3; + private readonly IoNotifier _notifier; + private readonly MdlFile _mdl; private readonly byte _lod; private readonly ushort _meshIndex; @@ -61,8 +63,9 @@ public class MeshExporter private readonly Type _materialType; private readonly Type _skinningType; - private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, IReadOnlyDictionary? boneNameMap) + private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, IReadOnlyDictionary? boneNameMap, IoNotifier notifier) { + _notifier = notifier; _mdl = mdl; _lod = lod; _meshIndex = meshIndex; @@ -84,7 +87,7 @@ public class MeshExporter // If there's skinning usages but no bone mapping, there's probably something wrong with the data. if (_skinningType != typeof(VertexEmpty) && _boneIndexMap == null) - Penumbra.Log.Warning($"Mesh {meshIndex} has skinned vertex usages but no bone information was provided."); + _notifier.Warning($"Skinned vertex usages but no bone information was provided."); Penumbra.Log.Debug( $"Mesh {meshIndex} using vertex types geometry: {_geometryType.Name}, material: {_materialType.Name}, skinning: {_skinningType.Name}"); @@ -105,7 +108,7 @@ public class MeshExporter { var boneName = _mdl.Bones[xivBoneIndex]; if (!boneNameMap.TryGetValue(boneName, out var gltfBoneIndex)) - throw new Exception($"Armature does not contain bone \"{boneName}\" requested by mesh {_meshIndex}."); + throw _notifier.Exception($"Armature does not contain bone \"{boneName}\". Ensure all dependencies are enabled in the current collection, and EST entries (if required) are configured."); indexMap.Add((ushort)tableIndex, gltfBoneIndex); } @@ -271,7 +274,7 @@ public class MeshExporter } /// Read a vertex attribute of the specified type from a vertex buffer stream. - private static object ReadVertexAttribute(MdlFile.VertexType type, BinaryReader reader) + private object ReadVertexAttribute(MdlFile.VertexType type, BinaryReader reader) { return type switch { @@ -284,15 +287,15 @@ public class MeshExporter MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), - _ => throw new ArgumentOutOfRangeException(), + var other => throw _notifier.Exception($"Unhandled vertex type {other}"), }; } /// Get the vertex geometry type for this mesh's vertex usages. - private static Type GetGeometryType(IReadOnlyDictionary usages) + private Type GetGeometryType(IReadOnlyDictionary usages) { if (!usages.ContainsKey(MdlFile.VertexUsage.Position)) - throw new Exception("Mesh does not contain position vertex elements."); + throw _notifier.Exception("Mesh does not contain position vertex elements."); if (!usages.ContainsKey(MdlFile.VertexUsage.Normal)) return typeof(VertexPosition); @@ -330,11 +333,11 @@ public class MeshExporter ); } - throw new Exception($"Unknown geometry type {_geometryType}."); + throw _notifier.Exception($"Unknown geometry type {_geometryType}."); } /// Get the vertex material type for this mesh's vertex usages. - private static Type GetMaterialType(IReadOnlyDictionary usages) + private Type GetMaterialType(IReadOnlyDictionary usages) { var uvCount = 0; if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var type)) @@ -343,7 +346,7 @@ public class MeshExporter MdlFile.VertexType.Half2 => 1, MdlFile.VertexType.Half4 => 2, MdlFile.VertexType.Single4 => 2, - _ => throw new Exception($"Unexpected UV vertex type {type}."), + _ => throw _notifier.Exception($"Unexpected UV vertex type {type}."), }; var materialUsages = ( @@ -403,7 +406,7 @@ public class MeshExporter ); } - throw new Exception($"Unknown material type {_skinningType}"); + throw _notifier.Exception($"Unknown material type {_skinningType}"); } /// Get the vertex skinning type for this mesh's vertex usages. @@ -424,7 +427,7 @@ public class MeshExporter if (_skinningType == typeof(VertexJoints4)) { if (_boneIndexMap == null) - throw new Exception("Tried to build skinned vertex but no bone mappings are available."); + throw _notifier.Exception("Tried to build skinned vertex but no bone mappings are available."); var indices = ToByteArray(attributes[MdlFile.VertexUsage.BlendIndices]); var weights = ToVector4(attributes[MdlFile.VertexUsage.BlendWeights]); @@ -435,7 +438,7 @@ public class MeshExporter // NOTE: I've not seen any files that throw this error that aren't completely broken. var xivBoneIndex = indices[bindingIndex]; if (!_boneIndexMap.TryGetValue(xivBoneIndex, out var jointIndex)) - throw new Exception($"Vertex contains weight for unknown bone index {xivBoneIndex}."); + throw _notifier.Exception($"Vertex contains weight for unknown bone index {xivBoneIndex}."); return (jointIndex, weights[bindingIndex]); }) @@ -443,7 +446,7 @@ public class MeshExporter return new VertexJoints4(bindings); } - throw new Exception($"Unknown skinning type {_skinningType}"); + throw _notifier.Exception($"Unknown skinning type {_skinningType}"); } /// Convert a vertex attribute value to a Vector2. Supported inputs are Vector2, Vector3, and Vector4. diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index da24fbb0..550aaf11 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -23,16 +23,16 @@ public class ModelExporter } /// Export a model in preparation for usage in a glTF file. If provided, skeleton will be used to skin the resulting meshes where appropriate. - public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton, Dictionary rawMaterials) + public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton, Dictionary rawMaterials, IoNotifier notifier) { var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; - var materials = ConvertMaterials(mdl, rawMaterials); - var meshes = ConvertMeshes(mdl, materials, gltfSkeleton); + var materials = ConvertMaterials(mdl, rawMaterials, notifier); + var meshes = ConvertMeshes(mdl, materials, gltfSkeleton, notifier); return new Model(meshes, gltfSkeleton); } /// Convert a .mdl to a mesh (group) per LoD. - private static List ConvertMeshes(MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton) + private static List ConvertMeshes(MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) { var meshes = new List(); @@ -43,7 +43,8 @@ public class ModelExporter // TODO: consider other types of mesh? for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) { - var mesh = MeshExporter.Export(mdl, lodIndex, (ushort)(lod.MeshIndex + meshOffset), materials, skeleton); + var meshIndex = (ushort)(lod.MeshIndex + meshOffset); + var mesh = MeshExporter.Export(mdl, lodIndex, meshIndex, materials, skeleton, notifier.WithContext($"Mesh {meshIndex}")); meshes.Add(mesh); } } @@ -52,11 +53,11 @@ public class ModelExporter } /// Build materials for each of the material slots in the .mdl. - private static MaterialBuilder[] ConvertMaterials(MdlFile mdl, Dictionary rawMaterials) + private static MaterialBuilder[] ConvertMaterials(MdlFile mdl, Dictionary rawMaterials, IoNotifier notifier) => mdl.Materials // TODO: material generation should be fallible, which means this lookup should be a tryget, with a fallback. // fallback can likely be a static on the material exporter. - .Select(name => MaterialExporter.Export(rawMaterials[name], name)) + .Select(name => MaterialExporter.Export(rawMaterials[name], name, notifier.WithContext($"Material {name}"))) .ToArray(); /// Convert XIV skeleton data into a glTF-compatible node tree, with mappings. diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 7f1171f3..ffcb5bbe 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -37,20 +37,17 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) - => Enqueue(new ExportToGltfAction(this, mdl, sklbPaths, read, outputPath)); + public Task ExportToGltf(MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + => EnqueueWithResult( + new ExportToGltfAction(this, mdl, sklbPaths, read, outputPath), + action => action.Notifier + ); public Task ImportGltf(string inputPath) - { - var action = new ImportGltfAction(inputPath); - return Enqueue(action).ContinueWith(task => - { - if (task is { IsFaulted: true, Exception: not null }) - throw task.Exception; - - return action.Out; - }); - } + => EnqueueWithResult( + new ImportGltfAction(inputPath), + action => action.Out + ); /// Try to find the .sklb paths for a .mdl file. /// .mdl file to look up the skeletons for. @@ -168,6 +165,16 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return task; } + private Task EnqueueWithResult(TAction action, Func process) + where TAction : IAction + => Enqueue(action).ContinueWith(task => + { + if (task is { IsFaulted: true, Exception: not null }) + throw task.Exception; + + return process(action); + }); + private class ExportToGltfAction( ModelManager manager, MdlFile mdl, @@ -176,6 +183,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect string outputPath) : IAction { + public IoNotifier Notifier = new IoNotifier(); + public void Execute(CancellationToken cancel) { Penumbra.Log.Debug($"[GLTF Export] Exporting model to {outputPath}..."); @@ -190,7 +199,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ); Penumbra.Log.Debug("[GLTF Export] Converting model..."); - var model = ModelExporter.Export(mdl, xivSkeletons, materials); + var model = ModelExporter.Export(mdl, xivSkeletons, materials, Notifier); Penumbra.Log.Debug("[GLTF Export] Building scene..."); var scene = new SceneBuilder(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 15c6cb21..17b46626 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -134,6 +134,8 @@ public partial class ModEditWindow .ContinueWith(task => { RecordIoExceptions(task.Exception); + if (task is { IsCompletedSuccessfully: true, Result: not null }) + IoWarnings = task.Result.GetWarnings().ToList(); PendingIo = false; }); } From 6da725350affe1bf78194acdac6663d510c29709 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 19 Jan 2024 02:56:01 +1100 Subject: [PATCH 0408/1381] Wire up notifier through import --- Penumbra/Import/Models/Import/MeshImporter.cs | 26 +++++++++++------- .../Import/Models/Import/ModelImporter.cs | 19 ++++++------- .../Import/Models/Import/SubMeshImporter.cs | 25 ++++++++--------- .../Import/Models/Import/VertexAttribute.cs | 27 +++++++++---------- Penumbra/Import/Models/ModelManager.cs | 7 ++--- .../ModEditWindow.Models.MdlTab.cs | 10 ++++--- 6 files changed, 63 insertions(+), 51 deletions(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 2a461304..28a7a9c1 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -3,7 +3,7 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; -public class MeshImporter(IEnumerable nodes) +public class MeshImporter(IEnumerable nodes, IoNotifier notifier) { public struct Mesh { @@ -33,9 +33,9 @@ public class MeshImporter(IEnumerable nodes) public List ShapeValues; } - public static Mesh Import(IEnumerable nodes) + public static Mesh Import(IEnumerable nodes, IoNotifier notifier) { - var importer = new MeshImporter(nodes); + var importer = new MeshImporter(nodes, notifier); return importer.Create(); } @@ -115,11 +115,11 @@ public class MeshImporter(IEnumerable nodes) var vertexOffset = _vertexCount; var indexOffset = _indices.Count; - var nodeBoneMap = CreateNodeBoneMap(node); - var subMesh = SubMeshImporter.Import(node, nodeBoneMap); - var subMeshName = node.Name ?? node.Mesh.Name; + var nodeBoneMap = CreateNodeBoneMap(node); + var subMesh = SubMeshImporter.Import(node, nodeBoneMap, notifier.WithContext($"Sub-mesh {subMeshName}")); + // TODO: Record a warning if there's a mismatch between current and incoming, as we can't support multiple materials per mesh. _material ??= subMesh.Material; @@ -127,8 +127,11 @@ public class MeshImporter(IEnumerable nodes) if (_vertexDeclaration == null) _vertexDeclaration = subMesh.VertexDeclaration; else if (VertexDeclarationMismatch(subMesh.VertexDeclaration, _vertexDeclaration.Value)) - throw new Exception( - $"Sub-mesh \"{subMeshName}\" vertex declaration mismatch. All sub-meshes of a mesh must have equivalent vertex declarations."); + throw notifier.Exception( + $@"All sub-meshes of a mesh must have equivalent vertex declarations. + Current: {FormatVertexDeclaration(_vertexDeclaration.Value)} + Sub-mesh ""{subMeshName}"": {FormatVertexDeclaration(subMesh.VertexDeclaration)}" + ); // Given that strides are derived from declarations, a lack of mismatch in declarations means the strides are fine. // TODO: I mean, given that strides are derivable, might be worth dropping strides from the sub mesh return structure and computing when needed. @@ -170,6 +173,9 @@ public class MeshImporter(IEnumerable nodes) }); } + private static string FormatVertexDeclaration(MdlStructs.VertexDeclarationStruct vertexDeclaration) + => string.Join(", ", vertexDeclaration.VertexElements.Select(element => $"{element.Usage} ({element.Type}@{element.Stream}:{element.Offset})")); + private static bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) { var elA = a.VertexElements; @@ -204,13 +210,13 @@ public class MeshImporter(IEnumerable nodes) var meshName = node.Name ?? mesh.Name ?? "(no name)"; var primitiveCount = mesh.Primitives.Count; if (primitiveCount != 1) - throw new Exception($"Mesh \"{meshName}\" has {primitiveCount} primitives, expected 1."); + throw notifier.Exception($"Mesh \"{meshName}\" has {primitiveCount} primitives, expected 1."); var primitive = mesh.Primitives[0]; // Per glTF specification, an asset with a skin MUST contain skinning attributes on its mesh. var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0") - ?? throw new Exception($"Skinned mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); + ?? throw notifier.Exception($"Skinned mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); // Build a set of joints that are referenced by this mesh. // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 1b7fdfa5..bf59f278 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -1,14 +1,15 @@ using Lumina.Data.Parsing; +using OtterGui; using Penumbra.GameData.Files; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; -public partial class ModelImporter(ModelRoot model) +public partial class ModelImporter(ModelRoot model, IoNotifier notifier) { - public static MdlFile Import(ModelRoot model) + public static MdlFile Import(ModelRoot model, IoNotifier notifier) { - var importer = new ModelImporter(model); + var importer = new ModelImporter(model, notifier); return importer.Create(); } @@ -39,8 +40,8 @@ public partial class ModelImporter(ModelRoot model) private MdlFile Create() { // Group and build out meshes in this model. - foreach (var subMeshNodes in GroupedMeshNodes()) - BuildMeshForGroup(subMeshNodes); + foreach (var (subMeshNodes, index) in GroupedMeshNodes().WithIndex()) + BuildMeshForGroup(subMeshNodes, index); // Now that all the meshes have been built, we can build some of the model-wide metadata. var materials = _materials.Count > 0 ? _materials : ["/NO_MATERIAL"]; @@ -128,7 +129,7 @@ public partial class ModelImporter(ModelRoot model) ) .OrderBy(group => group.Key); - private void BuildMeshForGroup(IEnumerable subMeshNodes) + private void BuildMeshForGroup(IEnumerable subMeshNodes, int index) { // Record some offsets we'll be using later, before they get mutated with mesh values. var subMeshOffset = _subMeshes.Count; @@ -136,7 +137,7 @@ public partial class ModelImporter(ModelRoot model) var indexOffset = _indices.Count; var shapeValueOffset = _shapeValues.Count; - var mesh = MeshImporter.Import(subMeshNodes); + var mesh = MeshImporter.Import(subMeshNodes, notifier.WithContext($"Mesh {index}")); var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); var materialIndex = mesh.Material != null @@ -196,7 +197,7 @@ public partial class ModelImporter(ModelRoot model) // arrays, values is practically guaranteed to be the highest of the // group, so a failure on any of them will be a failure on it. if (_shapeValues.Count > ushort.MaxValue) - throw new Exception($"Importing this file would require more than the maximum of {ushort.MaxValue} shape values.\nTry removing or applying shape keys that do not need to be changed at runtime in-game."); + throw notifier.Exception($"Importing this file would require more than the maximum of {ushort.MaxValue} shape values.\nTry removing or applying shape keys that do not need to be changed at runtime in-game."); } private ushort GetMaterialIndex(string materialName) @@ -232,7 +233,7 @@ public partial class ModelImporter(ModelRoot model) } if (boneIndices.Count > 64) - throw new Exception("XIV does not support meshes weighted to more than 64 bones."); + throw notifier.Exception("XIV does not support meshes weighted to a total of more than 64 bones."); var boneIndicesArray = new ushort[64]; Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 6a5d0d52..a7e0d583 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -28,12 +28,14 @@ public class SubMeshImporter public Dictionary> ShapeValues; } - public static SubMesh Import(Node node, IDictionary? nodeBoneMap) + public static SubMesh Import(Node node, IDictionary? nodeBoneMap, IoNotifier notifier) { - var importer = new SubMeshImporter(node, nodeBoneMap); + var importer = new SubMeshImporter(node, nodeBoneMap, notifier); return importer.Create(); } + private readonly IoNotifier _notifier; + private readonly MeshPrimitive _primitive; private readonly IDictionary? _nodeBoneMap; private readonly IDictionary? _nodeExtras; @@ -53,16 +55,15 @@ public class SubMeshImporter private readonly List? _morphNames; private Dictionary>? _shapeValues; - private SubMeshImporter(Node node, IDictionary? nodeBoneMap) + private SubMeshImporter(Node node, IDictionary? nodeBoneMap, IoNotifier notifier) { + _notifier = notifier; + var mesh = node.Mesh; var primitiveCount = mesh.Primitives.Count; if (primitiveCount != 1) - { - var name = node.Name ?? mesh.Name ?? "(no name)"; - throw new Exception($"Mesh \"{name}\" has {primitiveCount} primitives, expected 1."); - } + throw _notifier.Exception($"Mesh has {primitiveCount} primitives, expected 1."); _primitive = mesh.Primitives[0]; _nodeBoneMap = nodeBoneMap; @@ -115,7 +116,7 @@ public class SubMeshImporter { < 32 => (1u << _metaAttributes.Length) - 1, 32 => uint.MaxValue, - > 32 => throw new Exception("Models may utilise a maximum of 32 attributes."), + > 32 => throw _notifier.Exception("Models may utilise a maximum of 32 attributes."), }; return new SubMesh() @@ -165,11 +166,11 @@ public class SubMeshImporter // The order here is chosen to match a typical model's element order. var rawAttributes = new[] { - VertexAttribute.Position(accessors, morphAccessors), - VertexAttribute.BlendWeight(accessors), - VertexAttribute.BlendIndex(accessors, _nodeBoneMap), + VertexAttribute.Position(accessors, morphAccessors, _notifier), + VertexAttribute.BlendWeight(accessors, _notifier), + VertexAttribute.BlendIndex(accessors, _nodeBoneMap, _notifier), VertexAttribute.Normal(accessors, morphAccessors), - VertexAttribute.Tangent1(accessors, morphAccessors, _indices), + VertexAttribute.Tangent1(accessors, morphAccessors, _indices, _notifier), VertexAttribute.Color(accessors), VertexAttribute.Uv(accessors), }; diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 7c875162..b73f6a89 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -72,10 +72,10 @@ public class VertexAttribute private byte[] DefaultBuildMorph(int morphIndex, int vertexIndex) => Build(vertexIndex); - public static VertexAttribute Position(Accessors accessors, IEnumerable morphAccessors) + public static VertexAttribute Position(Accessors accessors, IEnumerable morphAccessors, IoNotifier notifier) { if (!accessors.TryGetValue("POSITION", out var accessor)) - throw new Exception("Meshes must contain a POSITION attribute."); + throw notifier.Exception("Meshes must contain a POSITION attribute."); var element = new MdlStructs.VertexElement() { @@ -115,13 +115,13 @@ public class VertexAttribute ); } - public static VertexAttribute? BlendWeight(Accessors accessors) + public static VertexAttribute? BlendWeight(Accessors accessors, IoNotifier notifier) { if (!accessors.TryGetValue("WEIGHTS_0", out var accessor)) return null; if (!accessors.ContainsKey("JOINTS_0")) - throw new Exception("Mesh contained WEIGHTS_0 attribute but no corresponding JOINTS_0 attribute."); + throw notifier.Exception("Mesh contained WEIGHTS_0 attribute but no corresponding JOINTS_0 attribute."); var element = new MdlStructs.VertexElement() { @@ -138,16 +138,16 @@ public class VertexAttribute ); } - public static VertexAttribute? BlendIndex(Accessors accessors, IDictionary? boneMap) + public static VertexAttribute? BlendIndex(Accessors accessors, IDictionary? boneMap, IoNotifier notifier) { if (!accessors.TryGetValue("JOINTS_0", out var accessor)) return null; if (!accessors.ContainsKey("WEIGHTS_0")) - throw new Exception("Mesh contained JOINTS_0 attribute but no corresponding WEIGHTS_0 attribute."); + throw notifier.Exception("Mesh contained JOINTS_0 attribute but no corresponding WEIGHTS_0 attribute."); if (boneMap == null) - throw new Exception("Mesh contained JOINTS_0 attribute but no bone mapping was created."); + throw notifier.Exception("Mesh contained JOINTS_0 attribute but no bone mapping was created."); var element = new MdlStructs.VertexElement() { @@ -242,22 +242,22 @@ public class VertexAttribute ); } - public static VertexAttribute? Tangent1(Accessors accessors, IEnumerable morphAccessors, ushort[] indices) + public static VertexAttribute? Tangent1(Accessors accessors, IEnumerable morphAccessors, ushort[] indices, IoNotifier notifier) { if (!accessors.TryGetValue("NORMAL", out var normalAccessor)) { - Penumbra.Log.Warning("Normals are required to facilitate import or calculation of tangents."); + notifier.Warning("Normals are required to facilitate import or calculation of tangents."); return null; } var normals = normalAccessor.AsVector3Array(); var tangents = accessors.TryGetValue("TANGENT", out var accessor) ? accessor.AsVector4Array() - : CalculateTangents(accessors, indices, normals); + : CalculateTangents(accessors, indices, normals, notifier); if (tangents == null) { - Penumbra.Log.Warning("No tangents available for sub-mesh. This could lead to incorrect lighting, or mismatched vertex attributes."); + notifier.Warning("No tangents available for sub-mesh. This could lead to incorrect lighting, or mismatched vertex attributes."); return null; } @@ -309,7 +309,7 @@ public class VertexAttribute } /// Attempt to calculate tangent values based on other pre-existing data. - private static Vector4[]? CalculateTangents(Accessors accessors, ushort[] indices, IList normals) + private static Vector4[]? CalculateTangents(Accessors accessors, ushort[] indices, IList normals, IoNotifier notifier) { // To calculate tangents, we will also need access to uv data. if (!accessors.TryGetValue("TEXCOORD_0", out var uvAccessor)) @@ -318,8 +318,7 @@ public class VertexAttribute var positions = accessors["POSITION"].AsVector3Array(); var uvs = uvAccessor.AsVector2Array(); - // TODO: Surface this in the UI. - Penumbra.Log.Warning( + notifier.Warning( "Calculating tangents, this may result in degraded light interaction. For best results, ensure tangents are caculated or retained during export from 3D modelling tools."); var vertexCount = positions.Count; diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index ffcb5bbe..c41f28e5 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -43,10 +43,10 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect action => action.Notifier ); - public Task ImportGltf(string inputPath) + public Task<(MdlFile?, IoNotifier)> ImportGltf(string inputPath) => EnqueueWithResult( new ImportGltfAction(inputPath), - action => action.Out + action => (action.Out, action.Notifier) ); /// Try to find the .sklb paths for a .mdl file. @@ -273,12 +273,13 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect private partial class ImportGltfAction(string inputPath) : IAction { public MdlFile? Out; + public IoNotifier Notifier = new IoNotifier(); public void Execute(CancellationToken cancel) { var model = Schema2.ModelRoot.Load(inputPath); - Out = ModelImporter.Import(model); + Out = ModelImporter.Import(model, Notifier); } public bool Equals(IAction? other) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 17b46626..6decd344 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -2,6 +2,7 @@ using Lumina.Data.Parsing; using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; +using Penumbra.Import.Models; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; @@ -146,11 +147,14 @@ public partial class ModEditWindow { PendingIo = true; _edit._models.ImportGltf(inputPath) - .ContinueWith(task => + .ContinueWith((Task<(MdlFile?, IoNotifier)> task) => { RecordIoExceptions(task.Exception); - if (task is { IsCompletedSuccessfully: true, Result: not null }) - FinalizeImport(task.Result); + if (task is { IsCompletedSuccessfully: true, Result: (not null, _) }) + { + IoWarnings = task.Result.Item2.GetWarnings().ToList(); + FinalizeImport(task.Result.Item1); + } PendingIo = false; }); } From aa01acd76a8fd9b37cfbadcb45e791a3c4fa43bf Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 19 Jan 2024 19:41:00 +1100 Subject: [PATCH 0409/1381] Move off messager --- Penumbra/Import/Models/IoNotifier.cs | 34 +++++++++------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/Penumbra/Import/Models/IoNotifier.cs b/Penumbra/Import/Models/IoNotifier.cs index e1d649f6..56ef7103 100644 --- a/Penumbra/Import/Models/IoNotifier.cs +++ b/Penumbra/Import/Models/IoNotifier.cs @@ -1,19 +1,11 @@ -using Dalamud.Interface.Internal.Notifications; -using OtterGui.Classes; +using OtterGui.Log; namespace Penumbra.Import.Models; public record class IoNotifier { - /// Notification subclass so that we have a distinct type to filter by. - private class LegallyDistinctNotification : Notification - { - public LegallyDistinctNotification(string content, NotificationType type): base(content, type) - {} - } - - private readonly DateTime _startTime = DateTime.UtcNow; - private string _context = ""; + private readonly List _messages = []; + private string _context = ""; /// Create a new notifier with the specified context appended to any other context already present. public IoNotifier WithContext(string context) @@ -21,12 +13,12 @@ public record class IoNotifier /// Send a warning with any current context to notification channels. public void Warning(string content) - => SendNotification(content, NotificationType.Warning); + => SendMessage(content, Logger.LogLevel.Warning); /// Get the current warnings for this notifier. /// This does not currently filter to notifications with the current notifier's context - it will return all IO notifications from all notifiers. public IEnumerable GetWarnings() - => GetFilteredNotifications(NotificationType.Warning); + => _messages; /// Create an exception with any current context. [StackTraceHidden] @@ -39,14 +31,10 @@ public record class IoNotifier where TException : Exception, new() => (TException)Activator.CreateInstance(typeof(TException), $"{_context}{message}")!; - private void SendNotification(string message, NotificationType type) - => Penumbra.Messager.AddMessage( - new LegallyDistinctNotification($"{_context}{message}", type), - true, false, true, false - ); - - private IEnumerable GetFilteredNotifications(NotificationType type) - => Penumbra.Messager - .Where(p => p.Key >= _startTime && p.Value is LegallyDistinctNotification && p.Value.NotificationType == type) - .Select(p => p.Value.PrintMessage); + private void SendMessage(string message, Logger.LogLevel type) + { + var fullText = $"{_context}{message}"; + Penumbra.Log.Message(type, fullText); + _messages.Add(fullText); + } } From 0486d049b0dbec021d9f9a3497eecf8980e33473 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 19 Jan 2024 22:20:54 +1100 Subject: [PATCH 0410/1381] Make material export fallible --- .../Import/Models/Export/MaterialExporter.cs | 6 +++ .../Import/Models/Export/ModelExporter.cs | 11 ++-- Penumbra/Import/Models/ModelManager.cs | 53 +++++++++++++------ .../ModEditWindow.Models.MdlTab.cs | 8 +-- 4 files changed, 54 insertions(+), 24 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 61609bb5..307e9d2b 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -22,6 +22,12 @@ public class MaterialExporter // variant? } + /// Dependency-less material configuration, for use when no material data can be resolved. + public static readonly MaterialBuilder Unknown = new MaterialBuilder("UNKNOWN") + .WithMetallicRoughnessShader() + .WithDoubleSide(true) + .WithBaseColor(Vector4.One); + /// Build a glTF material from a hydrated XIV model, with the provided name. public static MaterialBuilder Export(Material material, string name, IoNotifier notifier) { diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 550aaf11..9bc33697 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -55,9 +55,14 @@ public class ModelExporter /// Build materials for each of the material slots in the .mdl. private static MaterialBuilder[] ConvertMaterials(MdlFile mdl, Dictionary rawMaterials, IoNotifier notifier) => mdl.Materials - // TODO: material generation should be fallible, which means this lookup should be a tryget, with a fallback. - // fallback can likely be a static on the material exporter. - .Select(name => MaterialExporter.Export(rawMaterials[name], name, notifier.WithContext($"Material {name}"))) + .Select(name => + { + if (rawMaterials.TryGetValue(name, out var rawMaterial)) + return MaterialExporter.Export(rawMaterial, name, notifier.WithContext($"Material {name}")); + + notifier.Warning($"Material \"{name}\" missing, using blank fallback."); + return MaterialExporter.Unknown; + }) .ToArray(); /// Convert XIV skeleton data into a glTF-compatible node tree, with mappings. diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index c41f28e5..bfd55281 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -37,7 +37,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + public Task ExportToGltf(MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) => EnqueueWithResult( new ExportToGltfAction(this, mdl, sklbPaths, read, outputPath), action => action.Notifier @@ -106,7 +106,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect } /// Try to resolve the absolute path to a .mtrl from the potentially-partial path provided by a model. - private string ResolveMtrlPath(string rawPath) + private string? ResolveMtrlPath(string rawPath, IoNotifier notifier) { // TODO: this should probably be chosen in the export settings var variantId = 1; @@ -119,13 +119,18 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ? rawPath : '/' + Path.GetFileName(rawPath); - // TODO: this should be a recoverable warning if (absolutePath == null) - throw new Exception("Failed to resolve material path."); + { + notifier.Warning($"Material path \"{rawPath}\" could not be resolved."); + return null; + } var info = parser.GetFileInfo(absolutePath); if (info.FileType is not FileType.Material) - throw new Exception($"Material path {rawPath} does not conform to material conventions."); + { + notifier.Warning($"Material path {rawPath} does not conform to material conventions."); + return null; + } var resolvedPath = info.ObjectType switch { @@ -179,7 +184,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect ModelManager manager, MdlFile mdl, IEnumerable sklbPaths, - Func read, + Func read, string outputPath) : IAction { @@ -193,10 +198,10 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect var xivSkeletons = BuildSkeletons(cancel); Penumbra.Log.Debug("[GLTF Export] Reading materials..."); - var materials = mdl.Materials.ToDictionary( - path => path, - path => BuildMaterial(path, cancel) - ); + var materials = mdl.Materials + .Select(path => (path, material: BuildMaterial(path, Notifier, cancel))) + .Where(pair => pair.material != null) + .ToDictionary(pair => pair.path, pair => pair.material!.Value); Penumbra.Log.Debug("[GLTF Export] Converting model..."); var model = ModelExporter.Export(mdl, xivSkeletons, materials, Notifier); @@ -215,7 +220,9 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect private IEnumerable BuildSkeletons(CancellationToken cancel) { var havokTasks = sklbPaths - .Select(path => new SklbFile(read(path))) + .Select(path => read(path) ?? throw new Exception( + $"Resolved skeleton \"{path}\" could not be read. Ensure EST metadata is configured, and/or relevant mods are enabled in the current collection.")) + .Select(bytes => new SklbFile(bytes)) .WithIndex() .Select(CreateHavokTask) .ToArray(); @@ -234,10 +241,15 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect } /// Read a .mtrl and populate its textures. - private MaterialExporter.Material BuildMaterial(string relativePath, CancellationToken cancel) + private MaterialExporter.Material? BuildMaterial(string relativePath, IoNotifier notifier, CancellationToken cancel) { - var path = manager.ResolveMtrlPath(relativePath); - var mtrl = new MtrlFile(read(path)); + var path = manager.ResolveMtrlPath(relativePath, notifier); + if (path == null) + return null; + var bytes = read(path); + if (bytes == null) + return null; + var mtrl = new MtrlFile(bytes); return new MaterialExporter.Material { @@ -254,12 +266,23 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect { // Work out the texture's path - the DX11 material flag controls a file name prefix. GamePaths.Tex.HandleDx11Path(texture, out var texturePath); - using var textureData = new MemoryStream(read(texturePath)); + var bytes = read(texturePath); + if (bytes == null) + return CreateDummyImage(); + + using var textureData = new MemoryStream(bytes); var image = TexFileParser.Parse(textureData); var pngImage = TextureManager.ConvertToPng(image, cancel).AsPng; return pngImage ?? throw new Exception("Failed to convert texture to png."); } + private Image CreateDummyImage() + { + var image = new Image(1, 1); + image[0, 0] = Color.White; + return image; + } + public bool Equals(IAction? other) { if (other is not ExportToGltfAction rhs) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 6decd344..cb8e662f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -260,7 +260,7 @@ public partial class ModEditWindow /// Read a file from the active collection or game. /// Game path to the file to load. // TODO: Also look up files within the current mod regardless of mod state? - private byte[] ReadFile(string path) + private byte[]? ReadFile(string path) { // TODO: if cross-collection lookups are turned off, this conversion can be skipped if (!Utf8GamePath.FromString(path, out var utf8Path, true)) @@ -269,13 +269,9 @@ public partial class ModEditWindow var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8Path) ?? new FullPath(utf8Path); // TODO: is it worth trying to use streams for these instead? I'll need to do this for mtrl/tex too, so might be a good idea. that said, the mtrl reader doesn't accept streams, so... - var bytes = resolvedPath.IsRooted + return resolvedPath.IsRooted ? File.ReadAllBytes(resolvedPath.FullName) : _edit._gameData.GetFile(resolvedPath.InternalName.ToString())?.Data; - - // TODO: some callers may not care about failures - handle exceptions separately? - return bytes ?? throw new Exception( - $"Resolved path {path} could not be found. If modded, is it enabled in the current collection?"); } /// Remove the material given by the index. From cbd99f833a1fd3f13ed149dea8bd1344049c56be Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Jan 2024 00:03:58 +1100 Subject: [PATCH 0411/1381] Allow export of missing bones with warnings --- Penumbra/Import/Models/Export/Config.cs | 6 +++ Penumbra/Import/Models/Export/MeshExporter.cs | 39 ++++++++++++------- .../Import/Models/Export/ModelExporter.cs | 12 +++--- Penumbra/Import/Models/Export/Skeleton.cs | 12 +++++- Penumbra/Import/Models/ModelManager.cs | 16 +++++--- .../ModEditWindow.Models.MdlTab.cs | 5 ++- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 8 ++++ 7 files changed, 71 insertions(+), 27 deletions(-) create mode 100644 Penumbra/Import/Models/Export/Config.cs diff --git a/Penumbra/Import/Models/Export/Config.cs b/Penumbra/Import/Models/Export/Config.cs new file mode 100644 index 00000000..58329a1d --- /dev/null +++ b/Penumbra/Import/Models/Export/Config.cs @@ -0,0 +1,6 @@ +namespace Penumbra.Import.Models.Export; + +public struct ExportConfig +{ + public bool GenerateMissingBones; +} diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 71e8f082..83a0c3cf 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -13,14 +13,14 @@ namespace Penumbra.Import.Models.Export; public class MeshExporter { - public class Mesh(IEnumerable meshes, NodeBuilder[]? joints) + public class Mesh(IEnumerable meshes, GltfSkeleton? skeleton) { public void AddToScene(SceneBuilder scene) { foreach (var data in meshes) { - var instance = joints != null - ? scene.AddSkinnedMesh(data.Mesh, Matrix4x4.Identity, joints) + var instance = skeleton != null + ? scene.AddSkinnedMesh(data.Mesh, Matrix4x4.Identity, [.. skeleton.Value.Joints]) : scene.AddRigidMesh(data.Mesh, Matrix4x4.Identity); var extras = new Dictionary(data.Attributes.Length); @@ -38,15 +38,16 @@ public class MeshExporter public string[] Attributes; } - public static Mesh Export(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) + public static Mesh Export(ExportConfig config, MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) { - var self = new MeshExporter(mdl, lod, meshIndex, materials, skeleton?.Names, notifier); - return new Mesh(self.BuildMeshes(), skeleton?.Joints); + var self = new MeshExporter(config, mdl, lod, meshIndex, materials, skeleton, notifier); + return new Mesh(self.BuildMeshes(), skeleton); } private const byte MaximumMeshBufferStreams = 3; - private readonly IoNotifier _notifier; + private readonly ExportConfig _config; + private readonly IoNotifier _notifier; private readonly MdlFile _mdl; private readonly byte _lod; @@ -63,8 +64,10 @@ public class MeshExporter private readonly Type _materialType; private readonly Type _skinningType; - private MeshExporter(MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, IReadOnlyDictionary? boneNameMap, IoNotifier notifier) + // TODO: This signature is getting out of control. + private MeshExporter(ExportConfig config, MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) { + _config = config; _notifier = notifier; _mdl = mdl; _lod = lod; @@ -72,8 +75,8 @@ public class MeshExporter _material = materials[XivMesh.MaterialIndex]; - if (boneNameMap != null) - _boneIndexMap = BuildBoneIndexMap(boneNameMap); + if (skeleton != null) + _boneIndexMap = BuildBoneIndexMap(skeleton.Value); var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements .ToImmutableDictionary( @@ -94,7 +97,7 @@ public class MeshExporter } /// Build a mapping between indices in this mesh's bone table (if any), and the glTF joint indices provided. - private Dictionary? BuildBoneIndexMap(IReadOnlyDictionary boneNameMap) + private Dictionary? BuildBoneIndexMap(GltfSkeleton skeleton) { // A BoneTableIndex of 255 means that this mesh is not skinned. if (XivMesh.BoneTableIndex == 255) @@ -107,8 +110,18 @@ public class MeshExporter foreach (var (xivBoneIndex, tableIndex) in xivBoneTable.BoneIndex.Take(xivBoneTable.BoneCount).WithIndex()) { var boneName = _mdl.Bones[xivBoneIndex]; - if (!boneNameMap.TryGetValue(boneName, out var gltfBoneIndex)) - throw _notifier.Exception($"Armature does not contain bone \"{boneName}\". Ensure all dependencies are enabled in the current collection, and EST entries (if required) are configured."); + if (!skeleton.Names.TryGetValue(boneName, out var gltfBoneIndex)) + { + if (!_config.GenerateMissingBones) + throw _notifier.Exception( + $@"Armature does not contain bone ""{boneName}"". + Ensure all dependencies are enabled in the current collection, and EST entries (if required) are configured. + If this is a known issue with this model and you would like to export anyway, enable the ""Generate missing bones"" option." + ); + + (_, gltfBoneIndex) = skeleton.GenerateBone(boneName); + _notifier.Warning($"Generated missing bone \"{boneName}\". Vertices weighted to this bone will not move with the rest of the armature."); + } indexMap.Add((ushort)tableIndex, gltfBoneIndex); } diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index 9bc33697..b3e9c68d 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -23,16 +23,16 @@ public class ModelExporter } /// Export a model in preparation for usage in a glTF file. If provided, skeleton will be used to skin the resulting meshes where appropriate. - public static Model Export(MdlFile mdl, IEnumerable? xivSkeleton, Dictionary rawMaterials, IoNotifier notifier) + public static Model Export(ExportConfig config, MdlFile mdl, IEnumerable xivSkeletons, Dictionary rawMaterials, IoNotifier notifier) { - var gltfSkeleton = xivSkeleton != null ? ConvertSkeleton(xivSkeleton) : null; + var gltfSkeleton = ConvertSkeleton(xivSkeletons); var materials = ConvertMaterials(mdl, rawMaterials, notifier); - var meshes = ConvertMeshes(mdl, materials, gltfSkeleton, notifier); + var meshes = ConvertMeshes(config, mdl, materials, gltfSkeleton, notifier); return new Model(meshes, gltfSkeleton); } /// Convert a .mdl to a mesh (group) per LoD. - private static List ConvertMeshes(MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) + private static List ConvertMeshes(ExportConfig config, MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) { var meshes = new List(); @@ -44,7 +44,7 @@ public class ModelExporter for (ushort meshOffset = 0; meshOffset < lod.MeshCount; meshOffset++) { var meshIndex = (ushort)(lod.MeshIndex + meshOffset); - var mesh = MeshExporter.Export(mdl, lodIndex, meshIndex, materials, skeleton, notifier.WithContext($"Mesh {meshIndex}")); + var mesh = MeshExporter.Export(config, mdl, lodIndex, meshIndex, materials, skeleton, notifier.WithContext($"Mesh {meshIndex}")); meshes.Add(mesh); } } @@ -105,7 +105,7 @@ public class ModelExporter return new GltfSkeleton { Root = root, - Joints = [.. joints], + Joints = joints, Names = names, }; } diff --git a/Penumbra/Import/Models/Export/Skeleton.cs b/Penumbra/Import/Models/Export/Skeleton.cs index fee107a0..ca72a1f8 100644 --- a/Penumbra/Import/Models/Export/Skeleton.cs +++ b/Penumbra/Import/Models/Export/Skeleton.cs @@ -28,8 +28,18 @@ public struct GltfSkeleton public NodeBuilder Root; /// Flattened list of skeleton nodes. - public NodeBuilder[] Joints; + public List Joints; /// Mapping of bone names to their index within the joints array. public Dictionary Names; + + public (NodeBuilder, int) GenerateBone(string name) + { + var node = new NodeBuilder(name); + var index = Joints.Count; + Names[name] = index; + Joints.Add(node); + Root.AddNode(node); + return (node, index); + } } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index bfd55281..5340d556 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -37,9 +37,9 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + public Task ExportToGltf(ExportConfig config, MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) => EnqueueWithResult( - new ExportToGltfAction(this, mdl, sklbPaths, read, outputPath), + new ExportToGltfAction(this, config, mdl, sklbPaths, read, outputPath), action => action.Notifier ); @@ -182,6 +182,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect private class ExportToGltfAction( ModelManager manager, + ExportConfig config, MdlFile mdl, IEnumerable sklbPaths, Func read, @@ -204,7 +205,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect .ToDictionary(pair => pair.path, pair => pair.material!.Value); Penumbra.Log.Debug("[GLTF Export] Converting model..."); - var model = ModelExporter.Export(mdl, xivSkeletons, materials, Notifier); + var model = ModelExporter.Export(config, mdl, xivSkeletons, materials, Notifier); Penumbra.Log.Debug("[GLTF Export] Building scene..."); var scene = new SceneBuilder(); @@ -219,10 +220,13 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect /// Attempt to read out the pertinent information from the sklb file paths provided. private IEnumerable BuildSkeletons(CancellationToken cancel) { + // We're intentionally filtering failed reads here - the failure will + // be picked up, if relevant, when the model tries to create mappings + // for a bone in the failed sklb. var havokTasks = sklbPaths - .Select(path => read(path) ?? throw new Exception( - $"Resolved skeleton \"{path}\" could not be read. Ensure EST metadata is configured, and/or relevant mods are enabled in the current collection.")) - .Select(bytes => new SklbFile(bytes)) + .Select(path => read(path)) + .Where(bytes => bytes != null) + .Select(bytes => new SklbFile(bytes!)) .WithIndex() .Select(CreateHavokTask) .ToArray(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index cb8e662f..5b2f024c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -3,6 +3,7 @@ using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.Import.Models; +using Penumbra.Import.Models.Export; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; @@ -20,6 +21,8 @@ public partial class ModEditWindow public bool ImportKeepMaterials; public bool ImportKeepAttributes; + public ExportConfig ExportConfig; + public List? GamePaths { get; private set; } public int GamePathIndex; @@ -131,7 +134,7 @@ public partial class ModEditWindow } PendingIo = true; - _edit._models.ExportToGltf(Mdl, sklbPaths, ReadFile, outputPath) + _edit._models.ExportToGltf(ExportConfig, Mdl, sklbPaths, ReadFile, outputPath) .ContinueWith(task => { RecordIoExceptions(task.Exception); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 1a200fdf..7304d3dd 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -112,6 +112,14 @@ public partial class ModEditWindow DrawGamePathCombo(tab); + // ImGui.Checkbox("##exportGeneratedMissingBones", ref tab.ExportGenerateMissingBones); + ImGui.Checkbox("##exportGeneratedMissingBones", ref tab.ExportConfig.GenerateMissingBones); + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker("Generate missing bones", + "WARNING: Enabling this option can result in unusable exported meshes.\n" + + "It is primarily intended to allow exporting models weighted to bones that do not exist.\n" + + "Before enabling, ensure dependencies are enabled in the current collection, and EST metadata is correctly configured."); + var gamePath = tab.GamePathIndex >= 0 && tab.GamePathIndex < tab.GamePaths.Count ? tab.GamePaths[tab.GamePathIndex] : _customGamePath; From 0d3dde7df39306320a32a9ba31473ca92c01fa09 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Jan 2024 01:09:26 +1100 Subject: [PATCH 0412/1381] Tweaks --- Penumbra/Import/Models/Export/ModelExporter.cs | 2 +- Penumbra/Import/Models/Import/MeshImporter.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index b3e9c68d..e0c42d40 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -59,7 +59,7 @@ public class ModelExporter { if (rawMaterials.TryGetValue(name, out var rawMaterial)) return MaterialExporter.Export(rawMaterial, name, notifier.WithContext($"Material {name}")); - + notifier.Warning($"Material \"{name}\" missing, using blank fallback."); return MaterialExporter.Unknown; }) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 28a7a9c1..b6b146b5 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -216,7 +216,7 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) // Per glTF specification, an asset with a skin MUST contain skinning attributes on its mesh. var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0") - ?? throw notifier.Exception($"Skinned mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); + ?? throw notifier.Exception($"Mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); // Build a set of joints that are referenced by this mesh. // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 7304d3dd..43b26f10 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -112,7 +112,6 @@ public partial class ModEditWindow DrawGamePathCombo(tab); - // ImGui.Checkbox("##exportGeneratedMissingBones", ref tab.ExportGenerateMissingBones); ImGui.Checkbox("##exportGeneratedMissingBones", ref tab.ExportConfig.GenerateMissingBones); ImGui.SameLine(); ImGuiUtil.LabeledHelpMarker("Generate missing bones", From ae409c2cd1732f8889949d5f10865703285441b9 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Jan 2024 15:31:27 +1100 Subject: [PATCH 0413/1381] Fix shape value offset handling --- Penumbra/Import/Models/Import/ModelImporter.cs | 3 +-- Penumbra/Import/Models/Import/SubMeshImporter.cs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 1b7fdfa5..3c7e97c7 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -134,7 +134,6 @@ public partial class ModelImporter(ModelRoot model) var subMeshOffset = _subMeshes.Count; var vertexOffset = _vertexBuffer.Count; var indexOffset = _indices.Count; - var shapeValueOffset = _shapeValues.Count; var mesh = MeshImporter.Import(subMeshNodes); var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); @@ -184,7 +183,7 @@ public partial class ModelImporter(ModelRoot model) shapeMeshes.Add(meshShapeKey.ShapeMesh with { MeshIndexOffset = meshStartIndex, - ShapeValueOffset = (uint)shapeValueOffset, + ShapeValueOffset = (uint)_shapeValues.Count, }); _shapeValues.AddRange(meshShapeKey.ShapeValues); diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 6a5d0d52..023e5c2f 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -234,7 +234,7 @@ public class SubMeshImporter foreach (var (modifiedVertices, morphIndex) in morphModifiedVertices.WithIndex()) { - // Each for a given mesh, each shape key contains a list of shape value mappings. + // For a given mesh, each shape key contains a list of shape value mappings. var shapeValues = new List(); foreach (var vertexIndex in modifiedVertices) From c11519c95ef223bd4964bfd94739dfecc470012a Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Jan 2024 15:32:44 +1100 Subject: [PATCH 0414/1381] Fix further content expanding other sections --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index ad609285..cc6493b6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -386,6 +386,8 @@ public partial class ModEditWindow if (!ImGui.CollapsingHeader("Further Content")) return false; + using var furtherContentId = ImRaii.PushId("furtherContent"); + using (var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit)) { if (table) From 655d1722c18fbd24b5a569129c6005c439d7102d Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Jan 2024 17:49:39 +1100 Subject: [PATCH 0415/1381] Fail soft on invalid attribute masks --- .../ModEditWindow.Models.MdlTab.cs | 27 +++++++++++++------ .../UI/AdvancedWindow/ModEditWindow.Models.cs | 10 +++++-- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 26fcd1ee..98bd66d6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -14,7 +14,7 @@ public partial class ModEditWindow private readonly ModEditWindow _edit; public MdlFile Mdl { get; private set; } - private List[] _attributes; + private List?[] _attributes; public bool ImportKeepMaterials; public bool ImportKeepAttributes; @@ -290,15 +290,21 @@ public partial class ModEditWindow } /// Create a list of attributes per sub mesh. - private static List[] CreateAttributes(MdlFile mdl) - => mdl.SubMeshes.Select(s => Enumerable.Range(0, 32) - .Where(idx => ((s.AttributeIndexMask >> idx) & 1) == 1) - .Select(idx => mdl.Attributes[idx]) - .ToList() - ).ToArray(); + private static List?[] CreateAttributes(MdlFile mdl) + => mdl.SubMeshes.Select(s => + { + var maxAttribute = 31 - BitOperations.LeadingZeroCount(s.AttributeIndexMask); + // TODO: Research what results in this - it seems to primarily be reproducible on bgparts, is it garbage data, or an alternative usage of the value? + return maxAttribute < mdl.Attributes.Length + ? Enumerable.Range(0, 32) + .Where(idx => ((s.AttributeIndexMask >> idx) & 1) == 1) + .Select(idx => mdl.Attributes[idx]) + .ToList() + : null; + }).ToArray(); /// Obtain the attributes associated with a sub mesh by its index. - public IReadOnlyList GetSubMeshAttributes(int subMeshIndex) + public IReadOnlyList? GetSubMeshAttributes(int subMeshIndex) => _attributes[subMeshIndex]; /// Remove or add attributes from a sub mesh by its index. @@ -308,6 +314,8 @@ public partial class ModEditWindow public void UpdateSubMeshAttribute(int subMeshIndex, string? old, string? @new) { var attributes = _attributes[subMeshIndex]; + if (attributes == null) + return; if (old != null) attributes.Remove(old); @@ -325,6 +333,9 @@ public partial class ModEditWindow foreach (var (attributes, subMeshIndex) in _attributes.WithIndex()) { + if (attributes == null) + continue; + var mask = 0u; foreach (var attribute in attributes) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index cc6493b6..bc763d7d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -326,7 +326,7 @@ public partial class ModEditWindow // Sub meshes for (var subMeshOffset = 0; subMeshOffset < mesh.SubMeshCount; subMeshOffset++) - ret |= DrawSubMeshAttributes(tab, meshIndex, disabled, subMeshOffset); + ret |= DrawSubMeshAttributes(tab, meshIndex, subMeshOffset, disabled); return ret; } @@ -354,7 +354,7 @@ public partial class ModEditWindow return ret; } - private bool DrawSubMeshAttributes(MdlTab tab, int meshIndex, bool disabled, int subMeshOffset) + private bool DrawSubMeshAttributes(MdlTab tab, int meshIndex, int subMeshOffset, bool disabled) { using var _ = ImRaii.PushId(subMeshOffset); @@ -369,6 +369,12 @@ public partial class ModEditWindow var widget = _subMeshAttributeTagWidgets[subMeshIndex]; var attributes = tab.GetSubMeshAttributes(subMeshIndex); + if (attributes == null) + { + attributes = ["invalid attribute data"]; + disabled = true; + } + var tagIndex = widget.Draw(string.Empty, string.Empty, attributes, out var editedAttribute, !disabled); if (tagIndex < 0) From de08862a88c19dba406db90b7e3770386be68225 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Jan 2024 21:13:53 +1100 Subject: [PATCH 0416/1381] Add documentation links --- OtterGui | 2 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 34 +++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index 92590901..5d0aed2b 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9259090121b26f097948e7bbd83b32708ea0410d +Subproject commit 5d0aed2b32a61654321a6616689932635cb35dde diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index bc763d7d..1fb744ae 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; +using OtterGui.Custom; using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.GameData; @@ -13,7 +14,9 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private const int MdlMaterialMaximum = 4; + private const int MdlMaterialMaximum = 4; + private const string MdlImportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#import"; + private const string MdlExportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#export"; private readonly FileEditor _modelTab; private readonly ModelManager _models; @@ -67,6 +70,8 @@ public partial class ModEditWindow private void DrawImport(MdlTab tab, Vector2 size, bool _1) { + using var id = ImRaii.PushId("import"); + _dragDropManager.CreateImGuiSource("ModelDragDrop", m => m.Extensions.Any(e => ValidModelExtensions.Contains(e.ToLowerInvariant())), m => { @@ -89,6 +94,9 @@ public partial class ModEditWindow if (success && paths.Count > 0) tab.Import(paths[0]); }, 1, _mod!.ModPath.FullName, false); + + ImGui.SameLine(); + DrawDocumentationLink(MdlImportDocumentation); } if (_dragDropManager.CreateImGuiTarget("ModelDragDrop", out var files, out _) && GetFirstModel(files, out var importFile)) @@ -97,6 +105,7 @@ public partial class ModEditWindow private void DrawExport(MdlTab tab, Vector2 size, bool _) { + using var id = ImRaii.PushId("export"); using var frame = ImRaii.FramedGroup("Export", size, headerPreIcon: FontAwesomeIcon.FileExport); if (tab.GamePaths == null) @@ -110,10 +119,10 @@ public partial class ModEditWindow } DrawGamePathCombo(tab); - var gamePath = tab.GamePathIndex >= 0 && tab.GamePathIndex < tab.GamePaths.Count ? tab.GamePaths[tab.GamePathIndex] : _customGamePath; + if (ImGuiUtil.DrawDisabledButton("Export to glTF", Vector2.Zero, "Exports this mdl file to glTF, for use in 3D authoring applications.", tab.PendingIo || gamePath.IsEmpty)) _fileDialog.OpenSavePicker("Save model as glTF.", ".gltf", Path.GetFileNameWithoutExtension(gamePath.Filename().ToString()), @@ -127,6 +136,9 @@ public partial class ModEditWindow _mod!.ModPath.FullName, false ); + + ImGui.SameLine(); + DrawDocumentationLink(MdlExportDocumentation); } private static void DrawIoExceptions(MdlTab tab) @@ -205,6 +217,24 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip("Right-Click to copy to clipboard.", ImGuiHoveredFlags.AllowWhenDisabled); } + private void DrawDocumentationLink(string address) + { + const string text = "Documentation →"; + + var framePadding = ImGui.GetStyle().FramePadding; + var width = ImGui.CalcTextSize(text).X + framePadding.X * 2; + + // Draw the link button. We set the background colour to transparent to mimic the look of a link. + using var color = ImRaii.PushColor(ImGuiCol.Button, 0x00000000); + CustomGui.DrawLinkButton(Penumbra.Messager, text, address, width); + + // Draw an underline for the text. + var lineStart = ImGui.GetItemRectMax(); + lineStart -= framePadding; + var lineEnd = lineStart with { X = ImGui.GetItemRectMin().X + framePadding.X }; + ImGui.GetWindowDrawList().AddLine(lineStart, lineEnd, 0xFFFFFFFF); + } + private bool DrawModelMaterialDetails(MdlTab tab, bool disabled) { if (!ImGui.CollapsingHeader("Materials")) From c752835d2c3d59692815b3f565c61b1a17bd3d71 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Jan 2024 13:12:08 +0100 Subject: [PATCH 0417/1381] Make CopySettings save even for unused settings. --- Penumbra/Collections/Manager/CollectionEditor.cs | 9 +++++++-- .../Interop/Hooks/Objects/CharacterBaseDestructor.cs | 4 ++-- Penumbra/Interop/PathResolving/DrawObjectState.cs | 1 - 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index f0b4d509..73950942 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -156,9 +156,14 @@ public class CollectionEditor // Either copy the unused source settings directly if they are not inheriting, // or remove any unused settings for the target if they are inheriting. if (savedSettings != null) + { ((Dictionary)collection.UnusedSettings)[targetName] = savedSettings.Value; - else - ((Dictionary)collection.UnusedSettings).Remove(targetName); + _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + } + else if (((Dictionary)collection.UnusedSettings).Remove(targetName)) + { + _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + } } return true; diff --git a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs index fc6dbfe6..e01a6550 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs @@ -10,10 +10,10 @@ public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr + /// DrawObjectState = 0, - /// + /// MtrlTab = -1000, } diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index dd4b03f2..b3ae108b 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -3,7 +3,6 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; -using Penumbra.Interop.Hooks; using Object = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.Object; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.Objects; From 153b1e0d83170547ce77aa8e0ff2611a1b7d8f64 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Jan 2024 13:17:12 +0100 Subject: [PATCH 0418/1381] Meep --- OtterGui | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/OtterGui b/OtterGui index 5d0aed2b..c6f101bb 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5d0aed2b32a61654321a6616689932635cb35dde +Subproject commit c6f101bbef976b74eb651523445563dd81fafbaf diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 1fb744ae..022f48f1 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -419,11 +419,9 @@ public partial class ModEditWindow private static bool DrawOtherModelDetails(MdlFile file, bool _) { - if (!ImGui.CollapsingHeader("Further Content")) + if (!ImRaii.CollapsingHeader("Further Content")) return false; - using var furtherContentId = ImRaii.PushId("furtherContent"); - using (var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit)) { if (table) From 3debd470643ccee23cdfc109ebb39c7012d7a020 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Jan 2024 13:33:51 +0100 Subject: [PATCH 0419/1381] stupid. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 022f48f1..d799834c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -419,7 +419,8 @@ public partial class ModEditWindow private static bool DrawOtherModelDetails(MdlFile file, bool _) { - if (!ImRaii.CollapsingHeader("Further Content")) + using var header = ImRaii.CollapsingHeader("Further Content"); + if (!header) return false; using (var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit)) From edad7d9ec97863ff066da3588698d7342397074e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Jan 2024 13:47:03 +0100 Subject: [PATCH 0420/1381] Update persistent links. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index d799834c..a12be0f6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -15,8 +15,8 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { private const int MdlMaterialMaximum = 4; - private const string MdlImportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#import"; - private const string MdlExportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#export"; + private const string MdlImportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-9b49d296-23ab-410a-845b-a3be769b71ea"; + private const string MdlExportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-25968400-ebe5-4861-b610-cb1556db7ec4"; private readonly FileEditor _modelTab; private readonly ModelManager _models; From 7db95995113a4545f8c0feb3a7d6a1666f2d9e62 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Jan 2024 16:06:33 +0100 Subject: [PATCH 0421/1381] Auto-format and stuff. --- Penumbra/Import/Models/Export/MeshExporter.cs | 16 +++++--- .../Import/Models/Export/ModelExporter.cs | 4 +- Penumbra/Import/Models/ModelManager.cs | 12 +++--- .../ModEditWindow.Models.MdlTab.cs | 38 +++++++++++-------- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 8 ++-- 5 files changed, 43 insertions(+), 35 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 83a0c3cf..928c8670 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -38,7 +38,9 @@ public class MeshExporter public string[] Attributes; } - public static Mesh Export(ExportConfig config, MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) + public static Mesh Export(in ExportConfig config, MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, + GltfSkeleton? skeleton, + IoNotifier notifier) { var self = new MeshExporter(config, mdl, lod, meshIndex, materials, skeleton, notifier); return new Mesh(self.BuildMeshes(), skeleton); @@ -65,7 +67,8 @@ public class MeshExporter private readonly Type _skinningType; // TODO: This signature is getting out of control. - private MeshExporter(ExportConfig config, MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) + private MeshExporter(in ExportConfig config, MdlFile mdl, byte lod, ushort meshIndex, MaterialBuilder[] materials, + GltfSkeleton? skeleton, IoNotifier notifier) { _config = config; _notifier = notifier; @@ -118,9 +121,10 @@ public class MeshExporter Ensure all dependencies are enabled in the current collection, and EST entries (if required) are configured. If this is a known issue with this model and you would like to export anyway, enable the ""Generate missing bones"" option." ); - + (_, gltfBoneIndex) = skeleton.GenerateBone(boneName); - _notifier.Warning($"Generated missing bone \"{boneName}\". Vertices weighted to this bone will not move with the rest of the armature."); + _notifier.Warning( + $"Generated missing bone \"{boneName}\". Vertices weighted to this bone will not move with the rest of the armature."); } indexMap.Add((ushort)tableIndex, gltfBoneIndex); @@ -144,7 +148,7 @@ public class MeshExporter .Take(XivMesh.SubMeshCount) .WithIndex() .Select(subMesh => BuildMesh($"mesh {_meshIndex}.{subMesh.Index}", indices, vertices, - (int)(subMesh.Value.IndexOffset - XivMesh.StartIndex), (int)subMesh.Value.IndexCount, + (int)(subMesh.Value.IndexOffset - XivMesh.StartIndex), (int)subMesh.Value.IndexCount, subMesh.Value.AttributeIndexMask)) .ToArray(); } @@ -233,7 +237,7 @@ public class MeshExporter return new MeshData { - Mesh = meshBuilder, + Mesh = meshBuilder, Attributes = attributes, }; } diff --git a/Penumbra/Import/Models/Export/ModelExporter.cs b/Penumbra/Import/Models/Export/ModelExporter.cs index e0c42d40..55997ef8 100644 --- a/Penumbra/Import/Models/Export/ModelExporter.cs +++ b/Penumbra/Import/Models/Export/ModelExporter.cs @@ -23,7 +23,7 @@ public class ModelExporter } /// Export a model in preparation for usage in a glTF file. If provided, skeleton will be used to skin the resulting meshes where appropriate. - public static Model Export(ExportConfig config, MdlFile mdl, IEnumerable xivSkeletons, Dictionary rawMaterials, IoNotifier notifier) + public static Model Export(in ExportConfig config, MdlFile mdl, IEnumerable xivSkeletons, Dictionary rawMaterials, IoNotifier notifier) { var gltfSkeleton = ConvertSkeleton(xivSkeletons); var materials = ConvertMaterials(mdl, rawMaterials, notifier); @@ -32,7 +32,7 @@ public class ModelExporter } /// Convert a .mdl to a mesh (group) per LoD. - private static List ConvertMeshes(ExportConfig config, MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) + private static List ConvertMeshes(in ExportConfig config, MdlFile mdl, MaterialBuilder[] materials, GltfSkeleton? skeleton, IoNotifier notifier) { var meshes = new List(); diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 5340d556..2c341c8b 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -37,7 +37,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(ExportConfig config, MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + public Task ExportToGltf(in ExportConfig config, MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) => EnqueueWithResult( new ExportToGltfAction(this, config, mdl, sklbPaths, read, outputPath), action => action.Notifier @@ -189,7 +189,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect string outputPath) : IAction { - public IoNotifier Notifier = new IoNotifier(); + public readonly IoNotifier Notifier = new(); public void Execute(CancellationToken cancel) { @@ -224,7 +224,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect // be picked up, if relevant, when the model tries to create mappings // for a bone in the failed sklb. var havokTasks = sklbPaths - .Select(path => read(path)) + .Select(read) .Where(bytes => bytes != null) .Select(bytes => new SklbFile(bytes!)) .WithIndex() @@ -280,7 +280,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return pngImage ?? throw new Exception("Failed to convert texture to png."); } - private Image CreateDummyImage() + private static Image CreateDummyImage() { var image = new Image(1, 1); image[0, 0] = Color.White; @@ -299,8 +299,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect private partial class ImportGltfAction(string inputPath) : IAction { - public MdlFile? Out; - public IoNotifier Notifier = new IoNotifier(); + public MdlFile? Out; + public readonly IoNotifier Notifier = new(); public void Execute(CancellationToken cancel) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 8b3a7040..f24464d1 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -15,7 +15,7 @@ public partial class ModEditWindow { private readonly ModEditWindow _edit; - public MdlFile Mdl { get; private set; } + public MdlFile Mdl { get; private set; } private List?[] _attributes; public bool ImportKeepMaterials; @@ -43,7 +43,7 @@ public partial class ModEditWindow [MemberNotNull(nameof(Mdl), nameof(_attributes))] private void Initialize(MdlFile mdl) { - Mdl = mdl; + Mdl = mdl; _attributes = CreateAttributes(Mdl); } @@ -95,14 +95,14 @@ public partial class ModEditWindow task.ContinueWith(t => { RecordIoExceptions(t.Exception); - GamePaths = t.Result; - PendingIo = false; + GamePaths = t.Result; + PendingIo = false; }); } private EstManipulation[] GetCurrentEstManipulations() { - var mod = _edit._editor.Mod; + var mod = _edit._editor.Mod; var option = _edit._editor.Option; if (mod == null || option == null) return []; @@ -140,17 +140,17 @@ public partial class ModEditWindow RecordIoExceptions(task.Exception); if (task is { IsCompletedSuccessfully: true, Result: not null }) IoWarnings = task.Result.GetWarnings().ToList(); - PendingIo = false; + PendingIo = false; }); } - - /// Import a model from an interchange format. + + /// Import a model from an interchange format. /// Disk path to load model data from. public void Import(string inputPath) { PendingIo = true; _edit._models.ImportGltf(inputPath) - .ContinueWith((Task<(MdlFile?, IoNotifier)> task) => + .ContinueWith(task => { RecordIoExceptions(task.Exception); if (task is { IsCompletedSuccessfully: true, Result: (not null, _) }) @@ -158,6 +158,7 @@ public partial class ModEditWindow IoWarnings = task.Result.Item2.GetWarnings().ToList(); FinalizeImport(task.Result.Item1); } + PendingIo = false; }); } @@ -178,11 +179,11 @@ public partial class ModEditWindow // TODO: Add flag editing. newMdl.Flags1 = Mdl.Flags1; newMdl.Flags2 = Mdl.Flags2; - + Initialize(newMdl); _dirty = true; } - + /// Merge material configuration from the source onto the target. /// Model that will be updated. /// Model to copy material configuration from. @@ -218,10 +219,12 @@ public partial class ModEditWindow // to maintain semantic connection between mesh index and sub mesh attributes. if (meshIndex >= source.Meshes.Length) continue; + var sourceMesh = source.Meshes[meshIndex]; if (subMeshOffset >= sourceMesh.SubMeshCount) continue; + var sourceSubMesh = source.SubMeshes[sourceMesh.SubMeshIndex + subMeshOffset]; target.SubMeshes[subMeshIndex].AttributeIndexMask = sourceSubMesh.AttributeIndexMask; @@ -237,11 +240,13 @@ public partial class ModEditWindow foreach (var sourceElement in source.ElementIds) { - var sourceBone = source.Bones[sourceElement.ParentBoneName]; + var sourceBone = source.Bones[sourceElement.ParentBoneName]; var targetIndex = target.Bones.IndexOf(sourceBone); // Given that there's no means of authoring these at the moment, this should probably remain a hard error. if (targetIndex == -1) - throw new Exception($"Failed to merge element IDs. Original model contains element IDs targeting bone {sourceBone}, which is not present on the imported model."); + throw new Exception( + $"Failed to merge element IDs. Original model contains element IDs targeting bone {sourceBone}, which is not present on the imported model."); + elementIds.Add(sourceElement with { ParentBoneName = (uint)targetIndex, @@ -253,13 +258,14 @@ public partial class ModEditWindow private void RecordIoExceptions(Exception? exception) { - IoExceptions = exception switch { + IoExceptions = exception switch + { null => [], AggregateException ae => [.. ae.Flatten().InnerExceptions], _ => [exception], }; } - + /// Read a file from the active collection or game. /// Game path to the file to load. // TODO: Also look up files within the current mod regardless of mod state? @@ -297,7 +303,7 @@ public partial class ModEditWindow /// Create a list of attributes per sub mesh. private static List?[] CreateAttributes(MdlFile mdl) - => mdl.SubMeshes.Select(s => + => mdl.SubMeshes.Select(s => { var maxAttribute = 31 - BitOperations.LeadingZeroCount(s.AttributeIndexMask); // TODO: Research what results in this - it seems to primarily be reproducible on bgparts, is it garbage data, or an alternative usage of the value? diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 744e9ea2..561cbed7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -170,8 +170,7 @@ public partial class ModEditWindow using var exceptionNode = ImRaii.TreeNode(message); if (exceptionNode) { - ImGui.Dummy(new Vector2(ImGui.GetStyle().IndentSpacing, 0)); - ImGui.SameLine(); + using var indent = ImRaii.PushIndent(); ImGuiUtil.TextWrapped(exception.ToString()); } } @@ -202,9 +201,8 @@ public partial class ModEditWindow using var warningNode = ImRaii.TreeNode(firstLine); if (warningNode) { - ImGui.Dummy(new Vector2(ImGui.GetStyle().IndentSpacing, 0)); - ImGui.SameLine(); - ImGuiUtil.TextWrapped(warning.ToString()); + using var indent = ImRaii.PushIndent(); + ImGuiUtil.TextWrapped(warning); } } } From 38d855684bb66c0ad5b42a5472bff7653ad98232 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 20 Jan 2024 15:09:07 +0000 Subject: [PATCH 0422/1381] [CI] Updating repo.json for 1.0.0.3 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index aa03fe77..eef374b5 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.2", - "TestingAssemblyVersion": "1.0.0.2", + "AssemblyVersion": "1.0.0.3", + "TestingAssemblyVersion": "1.0.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.3/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From ca393267f6ab467f5f05a24c06658e45afd10c3f Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 21 Jan 2024 19:33:20 +1100 Subject: [PATCH 0423/1381] Spike custom vertex attribute handling --- Penumbra/Import/Models/Export/MeshExporter.cs | 10 +- .../Import/Models/Export/VertexFragment.cs | 92 +++++++++++++++++++ .../Import/Models/Import/VertexAttribute.cs | 4 +- 3 files changed, 100 insertions(+), 6 deletions(-) create mode 100644 Penumbra/Import/Models/Export/VertexFragment.cs diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 928c8670..03734db8 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -373,7 +373,7 @@ public class MeshExporter return materialUsages switch { - (2, true) => typeof(VertexColor1Texture2), + (2, true) => typeof(VertexTexture2ColorFfxiv), (2, false) => typeof(VertexTexture2), (1, true) => typeof(VertexColor1Texture1), (1, false) => typeof(VertexTexture1), @@ -413,13 +413,13 @@ public class MeshExporter ); } - if (_materialType == typeof(VertexColor1Texture2)) + if (_materialType == typeof(VertexTexture2ColorFfxiv)) { var uv = ToVector4(attributes[MdlFile.VertexUsage.UV]); - return new VertexColor1Texture2( - ToVector4(attributes[MdlFile.VertexUsage.Color]), + return new VertexTexture2ColorFfxiv( new Vector2(uv.X, uv.Y), - new Vector2(uv.Z, uv.W) + new Vector2(uv.Z, uv.W), + ToVector4(attributes[MdlFile.VertexUsage.Color]) ); } diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs new file mode 100644 index 00000000..234844d8 --- /dev/null +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -0,0 +1,92 @@ +using SharpGLTF.Geometry.VertexTypes; +using SharpGLTF.Schema2; + +namespace Penumbra.Import.Models.Export; + +public struct VertexTexture2ColorFfxiv : IVertexCustom +{ + public const string FFXIV_COLOR = "_FFXIV_COLOR"; + + [VertexAttribute("TEXCOORD_0")] + public Vector2 TexCoord0; + + [VertexAttribute("TEXCOORD_1")] + public Vector2 TexCoord1; + + [VertexAttribute(FFXIV_COLOR, EncodingType.UNSIGNED_BYTE, false)] + public Vector4 FfxivColor; + + public int MaxColors => 0; + + public int MaxTextCoords => 2; + + private static readonly string[] CustomNames = [FFXIV_COLOR]; + public IEnumerable CustomAttributes => CustomNames; + + public VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor) + { + TexCoord0 = texCoord0; + TexCoord1 = texCoord1; + FfxivColor = ffxivColor; + } + + public void Add(in VertexMaterialDelta delta) + { + TexCoord0 += delta.TexCoord0Delta; + TexCoord1 += delta.TexCoord1Delta; + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + { + return new VertexMaterialDelta(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), TexCoord1 - baseValue.GetTexCoord(1)); + } + + public Vector2 GetTexCoord(int index) + => index switch + { + 0 => TexCoord0, + 1 => TexCoord1, + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + public void SetTexCoord(int setIndex, Vector2 coord) + { + if (setIndex == 0) TexCoord0 = coord; + if (setIndex == 1) TexCoord1 = coord; + if (setIndex >= 2) throw new ArgumentOutOfRangeException(nameof(setIndex)); + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case FFXIV_COLOR: + value = FfxivColor; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + if (attributeName == FFXIV_COLOR && value is Vector4 valueVector4) + FfxivColor = valueVector4; + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { + } + + public void Validate() + { + var components = new[] { FfxivColor.X, FfxivColor.Y, FfxivColor.Z, FfxivColor.W }; + if (components.Any(component => component < 0 || component > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor)); + } +} diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index b73f6a89..b8576108 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -395,7 +395,9 @@ public class VertexAttribute public static VertexAttribute Color(Accessors accessors) { - accessors.TryGetValue("COLOR_0", out var accessor); + // Try to retrieve the custom color attribute we use for export, falling back to the glTF standard name. + if (!accessors.TryGetValue("_FFXIV_COLOR", out var accessor)) + accessors.TryGetValue("COLOR_0", out accessor); var element = new MdlStructs.VertexElement() { From 8167907d91fe785f0f3c32a756fbe07d3e1a156a Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 22 Jan 2024 00:34:16 +1100 Subject: [PATCH 0424/1381] The other two --- Penumbra/Import/Models/Export/MeshExporter.cs | 16 +- .../Import/Models/Export/VertexFragment.cs | 161 +++++++++++++++++- 2 files changed, 163 insertions(+), 14 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 03734db8..1c266e52 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -375,9 +375,9 @@ public class MeshExporter { (2, true) => typeof(VertexTexture2ColorFfxiv), (2, false) => typeof(VertexTexture2), - (1, true) => typeof(VertexColor1Texture1), + (1, true) => typeof(VertexTexture1ColorFfxiv), (1, false) => typeof(VertexTexture1), - (0, true) => typeof(VertexColor1), + (0, true) => typeof(VertexColorFfxiv), (0, false) => typeof(VertexEmpty), _ => throw new Exception("Unreachable."), @@ -390,16 +390,16 @@ public class MeshExporter if (_materialType == typeof(VertexEmpty)) return new VertexEmpty(); - if (_materialType == typeof(VertexColor1)) - return new VertexColor1(ToVector4(attributes[MdlFile.VertexUsage.Color])); + if (_materialType == typeof(VertexColorFfxiv)) + return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color])); if (_materialType == typeof(VertexTexture1)) return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV])); - if (_materialType == typeof(VertexColor1Texture1)) - return new VertexColor1Texture1( - ToVector4(attributes[MdlFile.VertexUsage.Color]), - ToVector2(attributes[MdlFile.VertexUsage.UV]) + if (_materialType == typeof(VertexTexture1ColorFfxiv)) + return new VertexTexture1ColorFfxiv( + ToVector2(attributes[MdlFile.VertexUsage.UV]), + ToVector4(attributes[MdlFile.VertexUsage.Color]) ); // XIV packs two UVs into a single vec4 attribute. diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index 234844d8..27d2ab10 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -3,24 +3,173 @@ using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Export; +/* +Yeah, look, I tried to make this file less garbage. It's a little difficult. +Realistically, it will need to stick around until transforms/mutations are built +and there's reason to overhaul the export pipeline. +*/ + +public struct VertexColorFfxiv : IVertexCustom +{ + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_BYTE, false)] + public Vector4 FfxivColor; + + public int MaxColors => 0; + + public int MaxTextCoords => 0; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; + public IEnumerable CustomAttributes => CustomNames; + + public VertexColorFfxiv(Vector4 ffxivColor) + { + FfxivColor = ffxivColor; + } + + public void Add(in VertexMaterialDelta delta) + { + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + => new VertexMaterialDelta(Vector4.Zero, Vector4.Zero, Vector2.Zero, Vector2.Zero); + + public Vector2 GetTexCoord(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetTexCoord(int setIndex, Vector2 coord) + { + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR": + value = FfxivColor; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + if (attributeName == "_FFXIV_COLOR" && value is Vector4 valueVector4) + FfxivColor = valueVector4; + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { + } + + public void Validate() + { + var components = new[] { FfxivColor.X, FfxivColor.Y, FfxivColor.Z, FfxivColor.W }; + if (components.Any(component => component < 0 || component > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor)); + } +} + +public struct VertexTexture1ColorFfxiv : IVertexCustom +{ + [VertexAttribute("TEXCOORD_0")] + public Vector2 TexCoord0; + + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_BYTE, false)] + public Vector4 FfxivColor; + + public int MaxColors => 0; + + public int MaxTextCoords => 1; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; + public IEnumerable CustomAttributes => CustomNames; + + public VertexTexture1ColorFfxiv(Vector2 texCoord0, Vector4 ffxivColor) + { + TexCoord0 = texCoord0; + FfxivColor = ffxivColor; + } + + public void Add(in VertexMaterialDelta delta) + { + TexCoord0 += delta.TexCoord0Delta; + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + { + return new VertexMaterialDelta(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), Vector2.Zero); + } + + public Vector2 GetTexCoord(int index) + => index switch + { + 0 => TexCoord0, + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + public void SetTexCoord(int setIndex, Vector2 coord) + { + if (setIndex == 0) TexCoord0 = coord; + if (setIndex >= 1) throw new ArgumentOutOfRangeException(nameof(setIndex)); + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR": + value = FfxivColor; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + if (attributeName == "_FFXIV_COLOR" && value is Vector4 valueVector4) + FfxivColor = valueVector4; + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { + } + + public void Validate() + { + var components = new[] { FfxivColor.X, FfxivColor.Y, FfxivColor.Z, FfxivColor.W }; + if (components.Any(component => component < 0 || component > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor)); + } +} + public struct VertexTexture2ColorFfxiv : IVertexCustom { - public const string FFXIV_COLOR = "_FFXIV_COLOR"; - [VertexAttribute("TEXCOORD_0")] public Vector2 TexCoord0; [VertexAttribute("TEXCOORD_1")] public Vector2 TexCoord1; - [VertexAttribute(FFXIV_COLOR, EncodingType.UNSIGNED_BYTE, false)] + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_BYTE, false)] public Vector4 FfxivColor; public int MaxColors => 0; public int MaxTextCoords => 2; - private static readonly string[] CustomNames = [FFXIV_COLOR]; + private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; public IEnumerable CustomAttributes => CustomNames; public VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor) @@ -60,7 +209,7 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom { switch (attributeName) { - case FFXIV_COLOR: + case "_FFXIV_COLOR": value = FfxivColor; return true; @@ -72,7 +221,7 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom public void SetCustomAttribute(string attributeName, object value) { - if (attributeName == FFXIV_COLOR && value is Vector4 valueVector4) + if (attributeName == "_FFXIV_COLOR" && value is Vector4 valueVector4) FfxivColor = valueVector4; } From 4183e29249ddce748902c6b50dea43e11b3f2d6d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 21 Jan 2024 18:33:57 +0100 Subject: [PATCH 0425/1381] Increase version. (Cargo Cult'd from Glamourer) --- Penumbra/Penumbra.csproj | 4 ++-- Penumbra/Penumbra.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index f1956742..01b3d680 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -7,8 +7,8 @@ absolute gangstas Penumbra Copyright © 2022 - 1.0.0.0 - 1.0.0.0 + 9.0.0.1 + 9.0.0.1 bin\$(Configuration)\ true enable diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 28dbc90d..8173e001 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -3,7 +3,7 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.0", + "AssemblyVersion": "9.0.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], From b5a71ed7b3d37d630d4e6d95c8a2de63475cb95b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 21 Jan 2024 17:17:26 +0100 Subject: [PATCH 0426/1381] Add locale environment variables to support info --- Penumbra/Penumbra.cs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 706e4a01..9ecd2232 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -192,6 +192,8 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Enable Mods: `** {_config.EnableMods}\n"); sb.Append($"> **`Enable HTTP API: `** {_config.EnableHttpApi}\n"); sb.Append($"> **`Operating System: `** {(Dalamud.Utility.Util.IsWine() ? "Mac/Linux (Wine)" : "Windows")}\n"); + if (Dalamud.Utility.Util.IsWine()) + sb.Append($"> **`Locale Environment Variables:`** {CollectLocaleEnvironmentVariables()}\n"); sb.Append($"> **`Root Directory: `** `{_config.ModDirectory}`, {(exists ? "Exists" : "Not Existing")}\n"); sb.Append( $"> **`Free Drive Space: `** {(drive != null ? Functions.HumanReadableSize(drive.AvailableFreeSpace) : "Unknown")}\n"); @@ -243,4 +245,39 @@ public class Penumbra : IDalamudPlugin return sb.ToString(); } + + private static string CollectLocaleEnvironmentVariables() + { + var variableNames = new List(); + var variables = new Dictionary(StringComparer.Ordinal); + foreach (DictionaryEntry variable in Environment.GetEnvironmentVariables()) + { + var key = (string)variable.Key; + if (key.Equals("LANG", StringComparison.Ordinal) || key.StartsWith("LC_", StringComparison.Ordinal)) + { + variableNames.Add(key); + variables.Add(key, ((string?)variable.Value) ?? string.Empty); + } + } + + variableNames.Sort(); + + var pos = variableNames.IndexOf("LC_ALL"); + if (pos > 0) // If it's == 0, we're going to do a no-op. + { + variableNames.RemoveAt(pos); + variableNames.Insert(0, "LC_ALL"); + } + + pos = variableNames.IndexOf("LANG"); + if (pos >= 0 && pos < variableNames.Count - 1) + { + variableNames.RemoveAt(pos); + variableNames.Add("LANG"); + } + + return variableNames.Count == 0 + ? "None" + : string.Join(", ", variableNames.Select(name => $"`{name}={variables[name]}`")); + } } From c2e5499aef456fab9a2ba9ae13ab3a9d9a09eb03 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 22 Jan 2024 01:51:42 +0100 Subject: [PATCH 0427/1381] ClientStructs-ify some stuff --- .../ResolveContext.PathResolution.cs | 13 ++-- .../Interop/ResourceTree/ResolveContext.cs | 8 +-- .../Interop/Structs/CharacterBaseUtility.cs | 62 ------------------- .../Structs/ModelResourceHandleUtility.cs | 19 ------ Penumbra/Interop/Structs/StructExtensions.cs | 57 ++++++++++++----- Penumbra/Penumbra.cs | 1 - Penumbra/Services/ServiceManagerA.cs | 3 +- 7 files changed, 53 insertions(+), 110 deletions(-) delete mode 100644 Penumbra/Interop/Structs/CharacterBaseUtility.cs delete mode 100644 Penumbra/Interop/Structs/ModelResourceHandleUtility.cs diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 0ab1e0e3..66af5521 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -7,7 +7,7 @@ using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.String; using Penumbra.String.Classes; -using static Penumbra.Interop.Structs.CharacterBaseUtility; +using static Penumbra.Interop.Structs.StructExtensions; using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; namespace Penumbra.Interop.ResourceTree; @@ -71,7 +71,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveModelPathNative() { - var path = ResolveMdlPath(CharacterBase, SlotIndex); + var path = CharacterBase.Value->ResolveMdlPathAsByteString(SlotIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -139,8 +139,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveMonsterMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { - // TODO: Submit this (Monster->Variant) to ClientStructs - var variant = ResolveMaterialVariant(imc, ((byte*)CharacterBase.Value)[0x8F4]); + var variant = ResolveMaterialVariant(imc, (byte)((Monster*)CharacterBase.Value)->Variant); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; @@ -196,7 +195,7 @@ internal partial record ResolveContext ByteString? path; try { - path = ResolveMtrlPath(CharacterBase, SlotIndex, mtrlFileName); + path = CharacterBase.Value->ResolveMtrlPathAsByteString(SlotIndex, mtrlFileName); } catch (AccessViolationException) { @@ -277,7 +276,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveSkeletonPathNative(uint partialSkeletonIndex) { - var path = ResolveSklbPath(CharacterBase, partialSkeletonIndex); + var path = CharacterBase.Value->ResolveSklbPathAsByteString(partialSkeletonIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -305,7 +304,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveSkeletonParameterPathNative(uint partialSkeletonIndex) { - var path = ResolveSkpPath(CharacterBase, partialSkeletonIndex); + var path = CharacterBase.Value->ResolveSkpPathAsByteString(partialSkeletonIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 431f1ac0..7a31c9dd 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -13,8 +13,6 @@ using Penumbra.GameData.Structs; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; -using static Penumbra.Interop.Structs.CharacterBaseUtility; -using static Penumbra.Interop.Structs.ModelResourceHandleUtility; using static Penumbra.Interop.Structs.StructExtensions; using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; @@ -126,7 +124,7 @@ internal partial record ResolveContext( if (eid == null) return null; - if (!Utf8GamePath.FromByteString(ResolveEidPath(CharacterBase), out var path)) + if (!Utf8GamePath.FromByteString(CharacterBase.Value->ResolveEidPathAsByteString(), out var path)) return null; return GetOrCreateNode(ResourceType.Eid, 0, eid, path); @@ -137,7 +135,7 @@ internal partial record ResolveContext( if (imc == null) return null; - if (!Utf8GamePath.FromByteString(ResolveImcPath(CharacterBase, SlotIndex), out var path)) + if (!Utf8GamePath.FromByteString(CharacterBase.Value->ResolveImcPathAsByteString(SlotIndex), out var path)) return null; return GetOrCreateNode(ResourceType.Imc, 0, imc, path); @@ -174,7 +172,7 @@ internal partial record ResolveContext( if (mtrl == null) continue; - var mtrlFileName = GetMaterialFileNameBySlot(mdlResource, (uint)i); + var mtrlFileName = mdlResource->GetMaterialFileNameBySlot((uint)i); var mtrlNode = CreateNodeFromMaterial(mtrl, ResolveMaterialPath(path, imc, mtrlFileName)); if (mtrlNode != null) { diff --git a/Penumbra/Interop/Structs/CharacterBaseUtility.cs b/Penumbra/Interop/Structs/CharacterBaseUtility.cs deleted file mode 100644 index c29f44a3..00000000 --- a/Penumbra/Interop/Structs/CharacterBaseUtility.cs +++ /dev/null @@ -1,62 +0,0 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using Penumbra.String; - -namespace Penumbra.Interop.Structs; - -// TODO submit these to ClientStructs -public static unsafe class CharacterBaseUtility -{ - private const int PathBufferSize = 260; - - private const uint ResolveSklbPathVf = 72; - private const uint ResolveMdlPathVf = 73; - private const uint ResolveSkpPathVf = 74; - private const uint ResolveImcPathVf = 81; - private const uint ResolveMtrlPathVf = 82; - private const uint ResolveEidPathVf = 85; - - private static void* GetVFunc(CharacterBase* characterBase, uint vfIndex) - => ((void**)characterBase->VTable)[vfIndex]; - - private static ByteString? ResolvePath(CharacterBase* characterBase, uint vfIndex) - { - var vFunc = (delegate* unmanaged)GetVFunc(characterBase, vfIndex); - var pathBuffer = stackalloc byte[PathBufferSize]; - var path = vFunc(characterBase, pathBuffer, PathBufferSize); - return path != null ? new ByteString(path).Clone() : null; - } - - private static ByteString? ResolvePath(CharacterBase* characterBase, uint vfIndex, uint slotIndex) - { - var vFunc = (delegate* unmanaged)GetVFunc(characterBase, vfIndex); - var pathBuffer = stackalloc byte[PathBufferSize]; - var path = vFunc(characterBase, pathBuffer, PathBufferSize, slotIndex); - return path != null ? new ByteString(path).Clone() : null; - } - - private static ByteString? ResolvePath(CharacterBase* characterBase, uint vfIndex, uint slotIndex, byte* name) - { - var vFunc = (delegate* unmanaged)GetVFunc(characterBase, vfIndex); - var pathBuffer = stackalloc byte[PathBufferSize]; - var path = vFunc(characterBase, pathBuffer, PathBufferSize, slotIndex, name); - return path != null ? new ByteString(path).Clone() : null; - } - - public static ByteString? ResolveEidPath(CharacterBase* characterBase) - => ResolvePath(characterBase, ResolveEidPathVf); - - public static ByteString? ResolveImcPath(CharacterBase* characterBase, uint slotIndex) - => ResolvePath(characterBase, ResolveImcPathVf, slotIndex); - - public static ByteString? ResolveMdlPath(CharacterBase* characterBase, uint slotIndex) - => ResolvePath(characterBase, ResolveMdlPathVf, slotIndex); - - public static ByteString? ResolveMtrlPath(CharacterBase* characterBase, uint slotIndex, byte* mtrlFileName) - => ResolvePath(characterBase, ResolveMtrlPathVf, slotIndex, mtrlFileName); - - public static ByteString? ResolveSklbPath(CharacterBase* characterBase, uint partialSkeletonIndex) - => ResolvePath(characterBase, ResolveSklbPathVf, partialSkeletonIndex); - - public static ByteString? ResolveSkpPath(CharacterBase* characterBase, uint partialSkeletonIndex) - => ResolvePath(characterBase, ResolveSkpPathVf, partialSkeletonIndex); -} diff --git a/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs b/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs deleted file mode 100644 index bcfa2fa2..00000000 --- a/Penumbra/Interop/Structs/ModelResourceHandleUtility.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; -using Penumbra.GameData; - -namespace Penumbra.Interop.Structs; - -// TODO submit this to ClientStructs -public class ModelResourceHandleUtility -{ - public ModelResourceHandleUtility(IGameInteropProvider interop) - => interop.InitializeFromAttributes(this); - - [Signature(Sigs.GetMaterialFileNameBySlot)] - private static nint _getMaterialFileNameBySlot = nint.Zero; - - public static unsafe byte* GetMaterialFileNameBySlot(ModelResourceHandle* handle, uint slot) - => ((delegate* unmanaged)_getMaterialFileNameBySlot)(handle, slot); -} diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index d1a38ae4..3cd87424 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -1,3 +1,4 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.STD; using Penumbra.String; @@ -5,20 +6,48 @@ namespace Penumbra.Interop.Structs; internal static class StructExtensions { - // TODO submit this to ClientStructs - public static unsafe ReadOnlySpan AsSpan(in this StdString str) - { - if (str.Length < 16) - { - fixed (StdString* pStr = &str) - { - return new(pStr->Buffer, (int)str.Length); - } - } - else - return new(str.BufferPtr, (int)str.Length); - } - public static unsafe ByteString AsByteString(in this StdString str) => ByteString.FromSpanUnsafe(str.AsSpan(), true); + + public static ByteString ResolveEidPathAsByteString(in this CharacterBase character) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveEidPath(pathBuffer)); + } + + public static ByteString ResolveImcPathAsByteString(in this CharacterBase character, uint slotIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveImcPath(pathBuffer, slotIndex)); + } + + public static ByteString ResolveMdlPathAsByteString(in this CharacterBase character, uint slotIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveMdlPath(pathBuffer, slotIndex)); + } + + public static unsafe ByteString ResolveMtrlPathAsByteString(in this CharacterBase character, uint slotIndex, byte* mtrlFileName) + { + var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex, mtrlFileName)); + } + + public static ByteString ResolveSklbPathAsByteString(in this CharacterBase character, uint partialSkeletonIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveSklbPath(pathBuffer, partialSkeletonIndex)); + } + + public static ByteString ResolveSkpPathAsByteString(in this CharacterBase character, uint partialSkeletonIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveSkpPath(pathBuffer, partialSkeletonIndex)); + } + + private static unsafe ByteString ToOwnedByteString(byte* str) + => str == null ? ByteString.Empty : new ByteString(str).Clone(); + + private static ByteString ToOwnedByteString(ReadOnlySpan str) + => str.Length == 0 ? ByteString.Empty : ByteString.FromSpanUnsafe(str, true).Clone(); } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 9ecd2232..15b7ce56 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -76,7 +76,6 @@ public class Penumbra : IDalamudPlugin _communicatorService = _services.GetService(); _services.GetService(); // Initialize because not required anywhere else. _services.GetService(); // Initialize because not required anywhere else. - _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); _services.GetService(); _services.GetService(); diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index 2b2bbf95..f25aac7c 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -99,8 +99,7 @@ public static class ServiceManagerA .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() - .AddSingleton(); + .AddSingleton(); private static ServiceManager AddConfiguration(this ServiceManager services) => services.AddSingleton() From d76411e66c6a4ea52c2fc3d3ad61630eb57317e5 Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 23 Jan 2024 00:40:29 +1100 Subject: [PATCH 0428/1381] Fix bounding box calculations for models offset from the origin --- Penumbra/Import/Models/Import/BoundingBox.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Import/BoundingBox.cs b/Penumbra/Import/Models/Import/BoundingBox.cs index 34aac827..be47ebb8 100644 --- a/Penumbra/Import/Models/Import/BoundingBox.cs +++ b/Penumbra/Import/Models/Import/BoundingBox.cs @@ -5,8 +5,8 @@ namespace Penumbra.Import.Models.Import; /// Mutable representation of the bounding box surrouding a collection of vertices. public class BoundingBox { - private Vector3 _minimum = Vector3.Zero; - private Vector3 _maximum = Vector3.Zero; + private Vector3 _minimum = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + private Vector3 _maximum = new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); /// Use the specified position to update this bounding box, expanding it if necessary. public void Merge(Vector3 position) From 363b22061318f69ff20463cd29e351ef6e927094 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jan 2024 16:53:13 +0100 Subject: [PATCH 0429/1381] Some improvements of the cutscene service. --- .../Interop/PathResolving/CutsceneService.cs | 74 +++++++++++++++++-- 1 file changed, 69 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 2eeefbd8..85944d74 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -1,8 +1,10 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; +using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.Interop.Hooks.Objects; +using Penumbra.String; namespace Penumbra.Interop.PathResolving; @@ -22,15 +24,19 @@ public sealed class CutsceneService : IService, IDisposable .Where(i => _objects[i] != null) .Select(i => KeyValuePair.Create(i, this[i] ?? _objects[i]!)); - public unsafe CutsceneService(IObjectTable objects, CopyCharacter copyCharacter, CharacterDestructor characterDestructor) + public unsafe CutsceneService(IObjectTable objects, CopyCharacter copyCharacter, CharacterDestructor characterDestructor, + IClientState clientState) { _objects = objects; _copyCharacter = copyCharacter; _characterDestructor = characterDestructor; _copyCharacter.Subscribe(OnCharacterCopy, CopyCharacter.Priority.CutsceneService); _characterDestructor.Subscribe(OnCharacterDestructor, CharacterDestructor.Priority.CutsceneService); + if (clientState.IsGPosing) + RecoverGPoseActors(); } + /// /// Get the related actor to a cutscene actor. /// Does not check for valid input index. @@ -66,11 +72,28 @@ public sealed class CutsceneService : IService, IDisposable private unsafe void OnCharacterDestructor(Character* character) { - if (character->GameObject.ObjectIndex is < CutsceneStartIdx or >= CutsceneEndIdx) - return; + if (character->GameObject.ObjectIndex < CutsceneStartIdx) + { + // Remove all associations for now non-existing actor. + for (var i = 0; i < _copiedCharacters.Length; ++i) + { + if (_copiedCharacters[i] == character->GameObject.ObjectIndex) + { + // A hack to deal with GPose actors leaving and thus losing the link, we just set the home world instead. + // I do not think this breaks anything? + var address = (GameObject*)_objects.GetObjectAddress(i + CutsceneStartIdx); + if (address != null && address->GetObjectKind() is (byte)ObjectKind.Pc) + ((Character*)address)->HomeWorld = character->HomeWorld; - var idx = character->GameObject.ObjectIndex - CutsceneStartIdx; - _copiedCharacters[idx] = -1; + _copiedCharacters[i] = -1; + } + } + } + else if (character->GameObject.ObjectIndex < CutsceneEndIdx) + { + var idx = character->GameObject.ObjectIndex - CutsceneStartIdx; + _copiedCharacters[idx] = -1; + } } private unsafe void OnCharacterCopy(Character* target, Character* source) @@ -81,4 +104,45 @@ public sealed class CutsceneService : IService, IDisposable var idx = target->GameObject.ObjectIndex - CutsceneStartIdx; _copiedCharacters[idx] = (short)(source != null ? source->GameObject.ObjectIndex : -1); } + + /// Try to recover GPose actors on reloads into a running game. + /// This is not 100% accurate due to world IDs, minions etc., but will be mostly sane. + private unsafe void RecoverGPoseActors() + { + Dictionary? actors = null; + + for (var i = CutsceneStartIdx; i < CutsceneEndIdx; ++i) + { + if (!TryGetName(i, out var name)) + continue; + + if ((actors ??= CreateActors()).TryGetValue(name, out var idx)) + _copiedCharacters[i - CutsceneStartIdx] = idx; + } + + return; + + bool TryGetName(int idx, out ByteString name) + { + name = ByteString.Empty; + var address = (GameObject*)_objects.GetObjectAddress(idx); + if (address == null) + return false; + + name = new ByteString(address->Name); + return !name.IsEmpty; + } + + Dictionary CreateActors() + { + var ret = new Dictionary(); + for (short i = 0; i < CutsceneStartIdx; ++i) + { + if (TryGetName(i, out var name)) + ret.TryAdd(name, i); + } + + return ret; + } + } } From b79fbc7653b5d91f17f4e56f7cf33db70fc3c03f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jan 2024 16:53:35 +0100 Subject: [PATCH 0430/1381] Some cleanup. --- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 6 ++-- Penumbra/Mods/Subclasses/ModSettings.cs | 38 +++++++++------------ 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index ff722945..e229738d 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -95,10 +95,10 @@ public class ItemSwapContainer public void LoadMod(Mod? mod, ModSettings? settings) { Clear(); - if (mod == null) + if (mod == null || mod.Index < 0) { - _modRedirections = new Dictionary(); - _modManipulations = new HashSet(); + _modRedirections = []; + _modManipulations = []; } else { diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index 122c6d29..71a56c80 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -11,7 +11,7 @@ namespace Penumbra.Mods.Subclasses; public class ModSettings { public static readonly ModSettings Empty = new(); - public List< uint > Settings { get; private init; } = new(); + public List< uint > Settings { get; private init; } = []; public int Priority { get; set; } public bool Enabled { get; set; } @@ -21,7 +21,7 @@ public class ModSettings { Enabled = Enabled, Priority = Priority, - Settings = Settings.ToList(), + Settings = [.. Settings], }; // Create default settings for a given mod. @@ -36,31 +36,14 @@ public class ModSettings // Return everything required to resolve things for a single mod with given settings (which can be null, in which case the default is used. public static (Dictionary< Utf8GamePath, FullPath >, HashSet< MetaManipulation >) GetResolveData( Mod mod, ModSettings? settings ) { - if( settings == null ) - { - settings = DefaultSettings( mod ); - } + if (settings == null) + settings = DefaultSettings(mod); else - { settings.AddMissingSettings( mod ); - } var dict = new Dictionary< Utf8GamePath, FullPath >(); var set = new HashSet< MetaManipulation >(); - void AddOption( ISubMod option ) - { - foreach( var (path, file) in option.Files.Concat( option.FileSwaps ) ) - { - dict.TryAdd( path, file ); - } - - foreach( var manip in option.Manipulations ) - { - set.Add( manip ); - } - } - foreach( var (group, index) in mod.Groups.WithIndex().OrderByDescending( g => g.Value.Priority ) ) { if( group.Type is GroupType.Single ) @@ -81,6 +64,19 @@ public class ModSettings AddOption( mod.Default ); return ( dict, set ); + + void AddOption( ISubMod option ) + { + foreach( var (path, file) in option.Files.Concat( option.FileSwaps ) ) + { + dict.TryAdd( path, file ); + } + + foreach( var manip in option.Manipulations ) + { + set.Add( manip ); + } + } } // Automatically react to changes in a mods available options. From 77762734d7c759a4dd0bd5bf3cdfc65542f8d5c0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jan 2024 16:59:51 +0100 Subject: [PATCH 0431/1381] Some Cleanup. --- .../Interop/ResourceTree/ResolveContext.cs | 118 ++++++++---------- 1 file changed, 49 insertions(+), 69 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 7a31c9dd..acac9a6f 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -6,7 +6,6 @@ using FFXIVClientStructs.Interop; using OtterGui; using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -27,20 +26,23 @@ internal record GlobalResolveContext(ObjectIdentification Identifier, ModCollect => new(this, characterBase, slotIndex, slot, equipment, secondaryId); } -internal partial record ResolveContext( +internal unsafe partial record ResolveContext( GlobalResolveContext Global, - Pointer CharacterBase, + Pointer CharacterBasePointer, uint SlotIndex, EquipSlot Slot, CharacterArmor Equipment, SecondaryId SecondaryId) { + public CharacterBase* CharacterBase + => CharacterBasePointer.Value; + private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); - private unsafe ModelType ModelType - => CharacterBase.Value->GetModelType(); + private ModelType ModelType + => CharacterBase->GetModelType(); - private unsafe ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath) + private ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath) { if (resourceHandle == null) return null; @@ -52,7 +54,7 @@ internal partial record ResolveContext( return GetOrCreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); } - private unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool dx11) + private ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool dx11) { if (resourceHandle == null) return null; @@ -88,7 +90,7 @@ internal partial record ResolveContext( return GetOrCreateNode(ResourceType.Tex, (nint)resourceHandle->Texture, &resourceHandle->ResourceHandle, path); } - private unsafe ResourceNode GetOrCreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, + private ResourceNode GetOrCreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, Utf8GamePath gamePath) { if (resourceHandle == null) @@ -100,7 +102,7 @@ internal partial record ResolveContext( return CreateNode(type, objectAddress, resourceHandle, gamePath); } - private unsafe ResourceNode CreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, + private ResourceNode CreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, Utf8GamePath gamePath, bool autoAdd = true) { if (resourceHandle == null) @@ -119,29 +121,29 @@ internal partial record ResolveContext( return node; } - public unsafe ResourceNode? CreateNodeFromEid(ResourceHandle* eid) + public ResourceNode? CreateNodeFromEid(ResourceHandle* eid) { if (eid == null) return null; - if (!Utf8GamePath.FromByteString(CharacterBase.Value->ResolveEidPathAsByteString(), out var path)) + if (!Utf8GamePath.FromByteString(CharacterBase->ResolveEidPathAsByteString(), out var path)) return null; return GetOrCreateNode(ResourceType.Eid, 0, eid, path); } - public unsafe ResourceNode? CreateNodeFromImc(ResourceHandle* imc) + public ResourceNode? CreateNodeFromImc(ResourceHandle* imc) { if (imc == null) return null; - if (!Utf8GamePath.FromByteString(CharacterBase.Value->ResolveImcPathAsByteString(SlotIndex), out var path)) + if (!Utf8GamePath.FromByteString(CharacterBase->ResolveImcPathAsByteString(SlotIndex), out var path)) return null; return GetOrCreateNode(ResourceType.Imc, 0, imc, path); } - public unsafe ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, string gamePath) + public ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, string gamePath) { if (tex == null) return null; @@ -152,7 +154,7 @@ internal partial record ResolveContext( return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, path); } - public unsafe ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc) + public ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc) { if (mdl == null || mdl->ModelResourceHandle == null) return null; @@ -187,30 +189,8 @@ internal partial record ResolveContext( return node; } - private unsafe ResourceNode? CreateNodeFromMaterial(Material* mtrl, Utf8GamePath path) + private ResourceNode? CreateNodeFromMaterial(Material* mtrl, Utf8GamePath path) { - static ushort GetTextureIndex(Material* mtrl, ushort texFlags, HashSet alreadyVisitedSamplerIds) - { - if ((texFlags & 0x001F) != 0x001F && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[texFlags & 0x001F].Id)) - return (ushort)(texFlags & 0x001F); - if ((texFlags & 0x03E0) != 0x03E0 && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[(texFlags >> 5) & 0x001F].Id)) - return (ushort)((texFlags >> 5) & 0x001F); - if ((texFlags & 0x7C00) != 0x7C00 && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[(texFlags >> 10) & 0x001F].Id)) - return (ushort)((texFlags >> 10) & 0x001F); - - return 0x001F; - } - - static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle, HashSet alreadyVisitedSamplerIds) - => mtrl->TexturesSpan.FindFirst(p => p.Texture == handle && !alreadyVisitedSamplerIds.Contains(p.Id), out var p) - ? p.Id - : null; - - static uint? GetSamplerCrcById(ShaderPackage* shpk, uint id) - => shpk->SamplersSpan.FindFirst(s => s.Id == id, out var s) - ? s.CRC - : null; - if (mtrl == null || mtrl->MaterialResourceHandle == null) return null; @@ -219,9 +199,6 @@ internal partial record ResolveContext( return cached; var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); - if (node == null) - return null; - var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName)); if (shpkNode != null) { @@ -247,11 +224,9 @@ internal partial record ResolveContext( if (shpk != null) { var index = GetTextureIndex(mtrl, resource->Textures[i].Flags, alreadyProcessedSamplerIds); - uint? samplerId; - if (index != 0x001F) - samplerId = mtrl->Textures[index].Id; - else - samplerId = GetTextureSamplerId(mtrl, resource->Textures[i].TextureResourceHandle, alreadyProcessedSamplerIds); + var samplerId = index != 0x001F + ? mtrl->Textures[index].Id + : GetTextureSamplerId(mtrl, resource->Textures[i].TextureResourceHandle, alreadyProcessedSamplerIds); if (samplerId.HasValue) { alreadyProcessedSamplerIds.Add(samplerId.Value); @@ -271,9 +246,31 @@ internal partial record ResolveContext( Global.Nodes.Add((path, (nint)resource), node); return node; + + static uint? GetSamplerCrcById(ShaderPackage* shpk, uint id) + => shpk->SamplersSpan.FindFirst(s => s.Id == id, out var s) + ? s.CRC + : null; + + static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle, HashSet alreadyVisitedSamplerIds) + => mtrl->TexturesSpan.FindFirst(p => p.Texture == handle && !alreadyVisitedSamplerIds.Contains(p.Id), out var p) + ? p.Id + : null; + + static ushort GetTextureIndex(Material* mtrl, ushort texFlags, HashSet alreadyVisitedSamplerIds) + { + if ((texFlags & 0x001F) != 0x001F && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[texFlags & 0x001F].Id)) + return (ushort)(texFlags & 0x001F); + if ((texFlags & 0x03E0) != 0x03E0 && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[(texFlags >> 5) & 0x001F].Id)) + return (ushort)((texFlags >> 5) & 0x001F); + if ((texFlags & 0x7C00) != 0x7C00 && !alreadyVisitedSamplerIds.Contains(mtrl->Textures[(texFlags >> 10) & 0x001F].Id)) + return (ushort)((texFlags >> 10) & 0x001F); + + return 0x001F; + } } - public unsafe ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) + public ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) { if (sklb == null || sklb->SkeletonResourceHandle == null) return null; @@ -283,19 +280,10 @@ internal partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonResourceHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); - if (node != null) - { - var skpNode = CreateParameterNodeFromPartialSkeleton(sklb, partialSkeletonIndex); - if (skpNode != null) - node.Children.Add(skpNode); - Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); - } - - return node; + return CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); } - private unsafe ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) + private ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) { if (sklb == null || sklb->SkeletonParameterResourceHandle == null) return null; @@ -305,15 +293,7 @@ internal partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonParameterResourceHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, path, false); - if (node != null) - { - if (Global.WithUiData) - node.FallbackName = "Skeleton Parameters"; - Global.Nodes.Add((path, (nint)sklb->SkeletonParameterResourceHandle), node); - } - - return node; + return CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, path, false); } internal ResourceNode.UiData GuessModelUiData(Utf8GamePath gamePath) @@ -363,7 +343,7 @@ internal partial record ResolveContext( return i >= 0 && i < array.Length ? array[i] : null; } - internal static unsafe ByteString GetResourceHandlePath(ResourceHandle* handle, bool stripPrefix = true) + internal static ByteString GetResourceHandlePath(ResourceHandle* handle, bool stripPrefix = true) { if (handle == null) return ByteString.Empty; @@ -384,7 +364,7 @@ internal partial record ResolveContext( return name; } - private static unsafe ulong GetResourceHandleLength(ResourceHandle* handle) + private static ulong GetResourceHandleLength(ResourceHandle* handle) { if (handle == null) return 0; From 7b1e28c2cfc8658f912cc02c09bccdbcbe99ebbd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jan 2024 17:08:38 +0100 Subject: [PATCH 0432/1381] Woops. --- .../Interop/ResourceTree/ResolveContext.cs | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index acac9a6f..0637cba6 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -198,7 +198,7 @@ internal unsafe partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)resource), out var cached)) return cached; - var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); + var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName)); if (shpkNode != null) { @@ -223,9 +223,9 @@ internal unsafe partial record ResolveContext( string? name = null; if (shpk != null) { - var index = GetTextureIndex(mtrl, resource->Textures[i].Flags, alreadyProcessedSamplerIds); - var samplerId = index != 0x001F - ? mtrl->Textures[index].Id + var index = GetTextureIndex(mtrl, resource->Textures[i].Flags, alreadyProcessedSamplerIds); + var samplerId = index != 0x001F + ? mtrl->Textures[index].Id : GetTextureSamplerId(mtrl, resource->Textures[i].TextureResourceHandle, alreadyProcessedSamplerIds); if (samplerId.HasValue) { @@ -280,7 +280,13 @@ internal unsafe partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonResourceHandle), out var cached)) return cached; - return CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); + var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); + var skpNode = CreateParameterNodeFromPartialSkeleton(sklb, partialSkeletonIndex); + if (skpNode != null) + node.Children.Add(skpNode); + Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); + + return node; } private ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) @@ -293,7 +299,12 @@ internal unsafe partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonParameterResourceHandle), out var cached)) return cached; - return CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, path, false); + var node = CreateNode(ResourceType.Skp, (nint)sklb, (ResourceHandle*)sklb->SkeletonParameterResourceHandle, path, false); + if (Global.WithUiData) + node.FallbackName = "Skeleton Parameters"; + Global.Nodes.Add((path, (nint)sklb->SkeletonParameterResourceHandle), node); + + return node; } internal ResourceNode.UiData GuessModelUiData(Utf8GamePath gamePath) From 6c93cc20df70987e0be7bf03bf5930412983b307 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jan 2024 17:24:08 +0100 Subject: [PATCH 0433/1381] Woops2 --- .../ResolveContext.PathResolution.cs | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 66af5521..cf939292 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -33,7 +33,7 @@ internal partial record ResolveContext return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } - private unsafe GenderRace ResolveModelRaceCode() + private GenderRace ResolveModelRaceCode() => ResolveEqdpRaceCode(Slot, Equipment.Set); private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, PrimaryId primaryId) @@ -42,7 +42,7 @@ internal partial record ResolveContext if (slotIndex >= 10 || ModelType != ModelType.Human) return GenderRace.MidlanderMale; - var characterRaceCode = (GenderRace)((Human*)CharacterBase.Value)->RaceSexId; + var characterRaceCode = (GenderRace)((Human*)CharacterBase)->RaceSexId; if (characterRaceCode == GenderRace.MidlanderMale) return GenderRace.MidlanderMale; @@ -71,7 +71,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveModelPathNative() { - var path = CharacterBase.Value->ResolveMdlPathAsByteString(SlotIndex); + var path = CharacterBase->ResolveMdlPathAsByteString(SlotIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -139,7 +139,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveMonsterMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { - var variant = ResolveMaterialVariant(imc, (byte)((Monster*)CharacterBase.Value)->Variant); + var variant = ResolveMaterialVariant(imc, (byte)((Monster*)CharacterBase)->Variant); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; @@ -195,11 +195,11 @@ internal partial record ResolveContext ByteString? path; try { - path = CharacterBase.Value->ResolveMtrlPathAsByteString(SlotIndex, mtrlFileName); + path = CharacterBase->ResolveMtrlPathAsByteString(SlotIndex, mtrlFileName); } catch (AccessViolationException) { - Penumbra.Log.Error($"Access violation during attempt to resolve material path\nDraw object: {(nint)CharacterBase.Value:X} (of type {ModelType})\nSlot index: {SlotIndex}\nMaterial file name: {(nint)mtrlFileName:X} ({new string((sbyte*)mtrlFileName)})"); + Penumbra.Log.Error($"Access violation during attempt to resolve material path\nDraw object: {(nint)CharacterBase:X} (of type {ModelType})\nSlot index: {SlotIndex}\nMaterial file name: {(nint)mtrlFileName:X} ({new string((sbyte*)mtrlFileName)})"); return Utf8GamePath.Empty; } return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; @@ -217,7 +217,7 @@ internal partial record ResolveContext }; } - private unsafe Utf8GamePath ResolveHumanSkeletonPath(uint partialSkeletonIndex) + private Utf8GamePath ResolveHumanSkeletonPath(uint partialSkeletonIndex) { var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); if (set == 0) @@ -229,7 +229,7 @@ internal partial record ResolveContext private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanSkeletonData(uint partialSkeletonIndex) { - var human = (Human*)CharacterBase.Value; + var human = (Human*)CharacterBase; var characterRaceCode = (GenderRace)human->RaceSexId; switch (partialSkeletonIndex) { @@ -262,21 +262,21 @@ internal partial record ResolveContext private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanEquipmentSkeletonData(EquipSlot slot, EstManipulation.EstType type) { - var human = (Human*)CharacterBase.Value; + var human = (Human*)CharacterBase; var equipment = ((CharacterArmor*)&human->Head)[slot.ToIndex()]; return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot, equipment.Set), type, equipment.Set); } - private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstManipulation.EstType type, PrimaryId primary) + private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstManipulation.EstType type, PrimaryId primary) { var metaCache = Global.Collection.MetaCache; - var skeletonSet = metaCache == null ? default : metaCache.GetEstEntry(type, raceCode, primary); + var skeletonSet = metaCache?.GetEstEntry(type, raceCode, primary) ?? default; return (raceCode, EstManipulation.ToName(type), skeletonSet); } private unsafe Utf8GamePath ResolveSkeletonPathNative(uint partialSkeletonIndex) { - var path = CharacterBase.Value->ResolveSklbPathAsByteString(partialSkeletonIndex); + var path = CharacterBase->ResolveSklbPathAsByteString(partialSkeletonIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -304,7 +304,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveSkeletonParameterPathNative(uint partialSkeletonIndex) { - var path = CharacterBase.Value->ResolveSkpPathAsByteString(partialSkeletonIndex); + var path = CharacterBase->ResolveSkpPathAsByteString(partialSkeletonIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } } From 8487661bc80f4b19ffe5f695f6e38496a3be794e Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 23 Jan 2024 21:25:18 +1100 Subject: [PATCH 0434/1381] Increase imported vertex precision --- Penumbra.GameData | 2 +- Penumbra/Import/Models/Export/MeshExporter.cs | 4 +- .../Import/Models/Import/VertexAttribute.cs | 82 ++++++++++--------- 3 files changed, 46 insertions(+), 42 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ab09e21f..63f4de73 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ab09e21fa46be83f82c400dfd2fe05a281b6f28d +Subproject commit 63f4de7305616b6cb8921513e5d83baa8913353f diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 928c8670..d5e168a3 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -297,8 +297,8 @@ public class MeshExporter { MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), - MdlFile.VertexType.UInt => reader.ReadBytes(4), - MdlFile.VertexType.ByteFloat4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, + MdlFile.VertexType.UByte4 => reader.ReadBytes(4), + MdlFile.VertexType.NByte4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index b73f6a89..74a29f72 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -30,12 +30,16 @@ public class VertexAttribute public byte Size => (MdlFile.VertexType)Element.Type switch { - MdlFile.VertexType.Single3 => 12, - MdlFile.VertexType.Single4 => 16, - MdlFile.VertexType.UInt => 4, - MdlFile.VertexType.ByteFloat4 => 4, - MdlFile.VertexType.Half2 => 4, - MdlFile.VertexType.Half4 => 8, + MdlFile.VertexType.Single1 => 4, + MdlFile.VertexType.Single2 => 8, + MdlFile.VertexType.Single3 => 12, + MdlFile.VertexType.Single4 => 16, + MdlFile.VertexType.UByte4 => 4, + MdlFile.VertexType.Short2 => 4, + MdlFile.VertexType.Short4 => 8, + MdlFile.VertexType.NByte4 => 4, + MdlFile.VertexType.Half2 => 4, + MdlFile.VertexType.Half4 => 8, _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), }; @@ -126,7 +130,7 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 0, - Type = (byte)MdlFile.VertexType.ByteFloat4, + Type = (byte)MdlFile.VertexType.NByte4, Usage = (byte)MdlFile.VertexUsage.BlendWeights, }; @@ -134,7 +138,7 @@ public class VertexAttribute return new VertexAttribute( element, - index => BuildByteFloat4(values[index]) + index => BuildNByte4(values[index]) ); } @@ -152,7 +156,7 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 0, - Type = (byte)MdlFile.VertexType.UInt, + Type = (byte)MdlFile.VertexType.UByte4, Usage = (byte)MdlFile.VertexUsage.BlendIndices, }; @@ -163,7 +167,7 @@ public class VertexAttribute index => { var gltfIndices = values[index]; - return BuildUInt(new Vector4( + return BuildUByte4(new Vector4( boneMap[(ushort)gltfIndices.X], boneMap[(ushort)gltfIndices.Y], boneMap[(ushort)gltfIndices.Z], @@ -181,7 +185,7 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 1, - Type = (byte)MdlFile.VertexType.Half4, + Type = (byte)MdlFile.VertexType.Single3, Usage = (byte)MdlFile.VertexUsage.Normal, }; @@ -193,7 +197,7 @@ public class VertexAttribute return new VertexAttribute( element, - index => BuildHalf4(new Vector4(values[index], 0)), + index => BuildSingle3(values[index]), buildMorph: (morphIndex, vertexIndex) => { var value = values[vertexIndex]; @@ -202,7 +206,7 @@ public class VertexAttribute if (delta != null) value += delta.Value; - return BuildHalf4(new Vector4(value, 0)); + return BuildSingle3(value); } ); } @@ -224,20 +228,20 @@ public class VertexAttribute // There's only one TEXCOORD, output UV coordinates as vec2s. if (!accessors.TryGetValue("TEXCOORD_1", out var accessor2)) return new VertexAttribute( - element with { Type = (byte)MdlFile.VertexType.Half2 }, - index => BuildHalf2(values1[index]) + element with { Type = (byte)MdlFile.VertexType.Single2 }, + index => BuildSingle2(values1[index]) ); var values2 = accessor2.AsVector2Array(); // Two TEXCOORDs are available, repack them into xiv's vec4 [0X, 0Y, 1X, 1Y] format. return new VertexAttribute( - element with { Type = (byte)MdlFile.VertexType.Half4 }, + element with { Type = (byte)MdlFile.VertexType.Single4 }, index => { var value1 = values1[index]; var value2 = values2[index]; - return BuildHalf4(new Vector4(value1.X, value1.Y, value2.X, value2.Y)); + return BuildSingle4(new Vector4(value1.X, value1.Y, value2.X, value2.Y)); } ); } @@ -264,7 +268,7 @@ public class VertexAttribute var element = new MdlStructs.VertexElement { Stream = 1, - Type = (byte)MdlFile.VertexType.ByteFloat4, + Type = (byte)MdlFile.VertexType.NByte4, Usage = (byte)MdlFile.VertexUsage.Tangent1, }; @@ -305,7 +309,7 @@ public class VertexAttribute // Byte floats encode 0..1, and bitangents are stored as -1..1. Convert. bitangent = (bitangent + Vector3.One) / 2; - return BuildByteFloat4(new Vector4(bitangent, handedness)); + return BuildNByte4(new Vector4(bitangent, handedness)); } /// Attempt to calculate tangent values based on other pre-existing data. @@ -400,7 +404,7 @@ public class VertexAttribute var element = new MdlStructs.VertexElement() { Stream = 1, - Type = (byte)MdlFile.VertexType.ByteFloat4, + Type = (byte)MdlFile.VertexType.NByte4, Usage = (byte)MdlFile.VertexUsage.Color, }; @@ -409,10 +413,17 @@ public class VertexAttribute return new VertexAttribute( element, - index => BuildByteFloat4(values?[index] ?? Vector4.One) + index => BuildNByte4(values?[index] ?? Vector4.One) ); } + private static byte[] BuildSingle2(Vector2 input) + => + [ + ..BitConverter.GetBytes(input.X), + ..BitConverter.GetBytes(input.Y), + ]; + private static byte[] BuildSingle3(Vector3 input) => [ @@ -421,7 +432,16 @@ public class VertexAttribute ..BitConverter.GetBytes(input.Z), ]; - private static byte[] BuildUInt(Vector4 input) + private static byte[] BuildSingle4(Vector4 input) + => + [ + ..BitConverter.GetBytes(input.X), + ..BitConverter.GetBytes(input.Y), + ..BitConverter.GetBytes(input.Z), + ..BitConverter.GetBytes(input.W), + ]; + + private static byte[] BuildUByte4(Vector4 input) => [ (byte)input.X, @@ -430,7 +450,7 @@ public class VertexAttribute (byte)input.W, ]; - private static byte[] BuildByteFloat4(Vector4 input) + private static byte[] BuildNByte4(Vector4 input) => [ (byte)Math.Round(input.X * 255f), @@ -438,20 +458,4 @@ public class VertexAttribute (byte)Math.Round(input.Z * 255f), (byte)Math.Round(input.W * 255f), ]; - - private static byte[] BuildHalf2(Vector2 input) - => - [ - ..BitConverter.GetBytes((Half)input.X), - ..BitConverter.GetBytes((Half)input.Y), - ]; - - private static byte[] BuildHalf4(Vector4 input) - => - [ - ..BitConverter.GetBytes((Half)input.X), - ..BitConverter.GetBytes((Half)input.Y), - ..BitConverter.GetBytes((Half)input.Z), - ..BitConverter.GetBytes((Half)input.W), - ]; } From b2bd31a1663b67d2bce4546c4f4aa7518c4bd04e Mon Sep 17 00:00:00 2001 From: ackwell Date: Wed, 24 Jan 2024 01:54:56 +1100 Subject: [PATCH 0435/1381] Import all primitives of a mesh --- Penumbra/Import/Models/Import/MeshImporter.cs | 72 ++---- .../Import/Models/Import/PrimitiveImporter.cs | 210 +++++++++++++++ .../Import/Models/Import/SubMeshImporter.cs | 243 ++++++------------ Penumbra/Import/Models/Import/Utility.cs | 33 +++ .../ModEditWindow.Models.MdlTab.cs | 1 - 5 files changed, 341 insertions(+), 218 deletions(-) create mode 100644 Penumbra/Import/Models/Import/PrimitiveImporter.cs diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index b6b146b5..f76fa1ea 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -1,4 +1,5 @@ using Lumina.Data.Parsing; +using OtterGui; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; @@ -117,21 +118,19 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) var subMeshName = node.Name ?? node.Mesh.Name; - var nodeBoneMap = CreateNodeBoneMap(node); - var subMesh = SubMeshImporter.Import(node, nodeBoneMap, notifier.WithContext($"Sub-mesh {subMeshName}")); + var subNotifier = notifier.WithContext($"Sub-mesh {subMeshName}"); + var nodeBoneMap = CreateNodeBoneMap(node, subNotifier); + var subMesh = SubMeshImporter.Import(node, nodeBoneMap, subNotifier); - // TODO: Record a warning if there's a mismatch between current and incoming, as we can't support multiple materials per mesh. _material ??= subMesh.Material; + if (subMesh.Material != null && _material != subMesh.Material) + notifier.Warning($"Meshes may only reference one material. Sub-mesh {subMeshName} material \"{subMesh.Material}\" has been ignored."); // Check that vertex declarations match - we need to combine the buffers, so a mismatch would take a whole load of resolution. if (_vertexDeclaration == null) _vertexDeclaration = subMesh.VertexDeclaration; - else if (VertexDeclarationMismatch(subMesh.VertexDeclaration, _vertexDeclaration.Value)) - throw notifier.Exception( - $@"All sub-meshes of a mesh must have equivalent vertex declarations. - Current: {FormatVertexDeclaration(_vertexDeclaration.Value)} - Sub-mesh ""{subMeshName}"": {FormatVertexDeclaration(subMesh.VertexDeclaration)}" - ); + else + Utility.EnsureVertexDeclarationMatch(_vertexDeclaration.Value, subMesh.VertexDeclaration, notifier); // Given that strides are derived from declarations, a lack of mismatch in declarations means the strides are fine. // TODO: I mean, given that strides are derivable, might be worth dropping strides from the sub mesh return structure and computing when needed. @@ -173,27 +172,7 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) }); } - private static string FormatVertexDeclaration(MdlStructs.VertexDeclarationStruct vertexDeclaration) - => string.Join(", ", vertexDeclaration.VertexElements.Select(element => $"{element.Usage} ({element.Type}@{element.Stream}:{element.Offset})")); - - private static bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) - { - var elA = a.VertexElements; - var elB = b.VertexElements; - - if (elA.Length != elB.Length) - return true; - - // NOTE: This assumes that elements will always be in the same order. Under the current implementation, that's guaranteed. - return elA.Zip(elB).Any(pair => - pair.First.Usage != pair.Second.Usage - || pair.First.Type != pair.Second.Type - || pair.First.Offset != pair.Second.Offset - || pair.First.Stream != pair.Second.Stream - ); - } - - private Dictionary? CreateNodeBoneMap(Node node) + private Dictionary? CreateNodeBoneMap(Node node, IoNotifier notifier) { // Unskinned assets can skip this all of this. if (node.Skin == null) @@ -205,32 +184,27 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) .Select(index => node.Skin.GetJoint(index).Joint.Name ?? "unnamed_joint") .ToArray(); - // TODO: This is duplicated with the sub mesh importer - would be good to avoid (not that it's a huge issue). - var mesh = node.Mesh; - var meshName = node.Name ?? mesh.Name ?? "(no name)"; - var primitiveCount = mesh.Primitives.Count; - if (primitiveCount != 1) - throw notifier.Exception($"Mesh \"{meshName}\" has {primitiveCount} primitives, expected 1."); - - var primitive = mesh.Primitives[0]; - - // Per glTF specification, an asset with a skin MUST contain skinning attributes on its mesh. - var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0") - ?? throw notifier.Exception($"Mesh \"{meshName}\" is skinned but does not contain skinning vertex attributes."); - - // Build a set of joints that are referenced by this mesh. - // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. var usedJoints = new HashSet(); - foreach (var joints in jointsAccessor.AsVector4Array()) + + foreach (var (primitive, primitiveIndex) in node.Mesh.Primitives.WithIndex()) { - for (var index = 0; index < 4; index++) - usedJoints.Add((ushort)joints[index]); + // Per glTF specification, an asset with a skin MUST contain skinning attributes on its meshes. + var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0") + ?? throw notifier.Exception($"Primitive {primitiveIndex} is skinned but does not contain skinning vertex attributes."); + + // Build a set of joints that are referenced by this mesh. + // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. + foreach (var joints in jointsAccessor.AsVector4Array()) + { + for (var index = 0; index < 4; index++) + usedJoints.Add((ushort)joints[index]); + } } // Only initialise the bones list if we're actually going to put something in it. _bones ??= []; - // Build a dictionary of node-specific joint indices mesh-wide bone indices. + // Build a dictionary of node-specific joint indices mapped to mesh-wide bone indices. var nodeBoneMap = new Dictionary(); foreach (var usedJoint in usedJoints) { diff --git a/Penumbra/Import/Models/Import/PrimitiveImporter.cs b/Penumbra/Import/Models/Import/PrimitiveImporter.cs new file mode 100644 index 00000000..9ac3d73c --- /dev/null +++ b/Penumbra/Import/Models/Import/PrimitiveImporter.cs @@ -0,0 +1,210 @@ +using Lumina.Data.Parsing; +using OtterGui; +using SharpGLTF.Schema2; + +namespace Penumbra.Import.Models.Import; + +public class PrimitiveImporter +{ + public struct Primitive + { + public string? Material; + + public MdlStructs.VertexDeclarationStruct VertexDeclaration; + + public ushort VertexCount; + public byte[] Strides; + public List[] Streams; + + public ushort[] Indices; + + public BoundingBox BoundingBox; + + public List> ShapeValues; + } + + public static Primitive Import(MeshPrimitive primitive, IDictionary? nodeBoneMap, IoNotifier notifier) + { + var importer = new PrimitiveImporter(primitive, nodeBoneMap, notifier); + return importer.Create(); + } + + private readonly IoNotifier _notifier; + + private readonly MeshPrimitive _primitive; + private readonly IDictionary? _nodeBoneMap; + + private ushort[]? _indices; + + private List? _vertexAttributes; + + private ushort _vertexCount; + private byte[] _strides = [0, 0, 0]; + private readonly List[] _streams = [[], [], []]; + + private BoundingBox _boundingBox = new BoundingBox(); + + private List>? _shapeValues; + + private PrimitiveImporter(MeshPrimitive primitive, IDictionary? nodeBoneMap, IoNotifier notifier) + { + _notifier = notifier; + _primitive = primitive; + _nodeBoneMap = nodeBoneMap; + } + + private Primitive Create() + { + // TODO: This structure is verging on a little silly. Reconsider. + BuildIndices(); + BuildVertexAttributes(); + BuildVertices(); + BuildBoundingBox(); + + ArgumentNullException.ThrowIfNull(_vertexAttributes); + ArgumentNullException.ThrowIfNull(_indices); + ArgumentNullException.ThrowIfNull(_shapeValues); + + var material = _primitive.Material.Name; + if (material == "") + material = null; + + return new Primitive + { + Material = material, + VertexDeclaration = new MdlStructs.VertexDeclarationStruct + { + VertexElements = _vertexAttributes.Select(attribute => attribute.Element).ToArray(), + }, + VertexCount = _vertexCount, + Strides = _strides, + Streams = _streams, + Indices = _indices, + BoundingBox = _boundingBox, + ShapeValues = _shapeValues, + }; + } + + private void BuildIndices() + { + // TODO: glTF supports a bunch of primitive types, ref. Schema2.PrimitiveType. All this code is currently assuming that it's using plain triangles (4). It should probably be generalised to other formats - I _suspect_ we should be able to get away with evaluating the indices to triangles with GetTriangleIndices, but will need investigation. + _indices = _primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); + } + + private void BuildVertexAttributes() + { + // Tangent calculation requires indices if missing. + ArgumentNullException.ThrowIfNull(_indices); + + var accessors = _primitive.VertexAccessors; + + var morphAccessors = Enumerable.Range(0, _primitive.MorphTargetsCount) + .Select(index => _primitive.GetMorphTargetAccessors(index)).ToList(); + + // Try to build all the attributes the mesh might use. + // The order here is chosen to match a typical model's element order. + var rawAttributes = new[] + { + VertexAttribute.Position(accessors, morphAccessors, _notifier), + VertexAttribute.BlendWeight(accessors, _notifier), + VertexAttribute.BlendIndex(accessors, _nodeBoneMap, _notifier), + VertexAttribute.Normal(accessors, morphAccessors), + VertexAttribute.Tangent1(accessors, morphAccessors, _indices, _notifier), + VertexAttribute.Color(accessors), + VertexAttribute.Uv(accessors), + }; + + var attributes = new List(); + var offsets = new byte[] + { + 0, + 0, + 0, + }; + foreach (var attribute in rawAttributes) + { + if (attribute == null) + continue; + + attributes.Add(attribute.WithOffset(offsets[attribute.Stream])); + offsets[attribute.Stream] += attribute.Size; + } + + _vertexAttributes = attributes; + // After building the attributes, the resulting next offsets are our stream strides. + _strides = offsets; + } + + private void BuildVertices() + { + ArgumentNullException.ThrowIfNull(_vertexAttributes); + + // Lists of vertex indices that are effected by each morph target for this primitive. + var morphModifiedVertices = Enumerable.Range(0, _primitive.MorphTargetsCount) + .Select(_ => new List()) + .ToArray(); + + // We can safely assume that POSITION exists by this point - and if, by some bizarre chance, it doesn't, failing out is sane. + _vertexCount = (ushort)_primitive.VertexAccessors["POSITION"].Count; + + for (var vertexIndex = 0; vertexIndex < _vertexCount; vertexIndex++) + { + // Write out vertex data to streams for each attribute. + foreach (var attribute in _vertexAttributes) + _streams[attribute.Stream].AddRange(attribute.Build(vertexIndex)); + + // Record which morph targets have values for this vertex, if any. + var changedMorphs = morphModifiedVertices + .WithIndex() + .Where(pair => _vertexAttributes.Any(attribute => attribute.HasMorph(pair.Index, vertexIndex))) + .Select(pair => pair.Value); + foreach (var modifiedVertices in changedMorphs) + modifiedVertices.Add(vertexIndex); + } + + BuildShapeValues(morphModifiedVertices); + } + + private void BuildShapeValues(IEnumerable> morphModifiedVertices) + { + ArgumentNullException.ThrowIfNull(_indices); + ArgumentNullException.ThrowIfNull(_vertexAttributes); + + var morphShapeValues = new List>(); + + foreach (var (modifiedVertices, morphIndex) in morphModifiedVertices.WithIndex()) + { + // For a given mesh, each shape key contains a list of shape value mappings. + var shapeValues = new List(); + + foreach (var vertexIndex in modifiedVertices) + { + // Write out the morphed vertex to the vertex streams. + foreach (var attribute in _vertexAttributes) + _streams[attribute.Stream].AddRange(attribute.BuildMorph(morphIndex, vertexIndex)); + + // Find any indices that target this vertex index and create a mapping. + var targetingIndices = _indices.WithIndex() + .SelectWhere(pair => (pair.Value == vertexIndex, pair.Index)); + shapeValues.AddRange(targetingIndices.Select(targetingIndex => new MdlStructs.ShapeValueStruct + { + BaseIndicesIndex = (ushort)targetingIndex, + ReplacingVertexIndex = _vertexCount, + })); + + _vertexCount++; + } + + morphShapeValues.Add(shapeValues); + } + + _shapeValues = morphShapeValues; + } + + private void BuildBoundingBox() + { + var positions = _primitive.VertexAccessors["POSITION"].AsVector3Array(); + foreach (var position in positions) + _boundingBox.Merge(position); + } +} diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index caa48757..26f98b04 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -19,7 +19,7 @@ public class SubMeshImporter public byte[] Strides; public List[] Streams; - public ushort[] Indices; + public List Indices; public BoundingBox BoundingBox; @@ -36,85 +36,56 @@ public class SubMeshImporter private readonly IoNotifier _notifier; - private readonly MeshPrimitive _primitive; - private readonly IDictionary? _nodeBoneMap; - private readonly IDictionary? _nodeExtras; + private readonly Node _node; + private readonly IDictionary? _nodeBoneMap; - private List? _vertexAttributes; + private string? _material; - private ushort _vertexCount; - private byte[] _strides = [0, 0, 0]; - private readonly List[] _streams; + private MdlStructs.VertexDeclarationStruct? _vertexDeclaration; + private ushort _vertexCount; + private byte[]? _strides; + private readonly List[] _streams = [[], [], []]; - private ushort[]? _indices; + private List _indices = []; private BoundingBox _boundingBox = new BoundingBox(); - private string[]? _metaAttributes; - - private readonly List? _morphNames; - private Dictionary>? _shapeValues; + private readonly List? _morphNames; + private Dictionary> _shapeValues = []; private SubMeshImporter(Node node, IDictionary? nodeBoneMap, IoNotifier notifier) { - _notifier = notifier; - - var mesh = node.Mesh; - - var primitiveCount = mesh.Primitives.Count; - if (primitiveCount != 1) - throw _notifier.Exception($"Mesh has {primitiveCount} primitives, expected 1."); - - _primitive = mesh.Primitives[0]; + _notifier = notifier; + _node = node; _nodeBoneMap = nodeBoneMap; try { - _nodeExtras = node.Extras.Deserialize>(); - } - catch - { - _nodeExtras = null; - } - - try - { - _morphNames = mesh.Extras.GetNode("targetNames").Deserialize>(); + _morphNames = node.Mesh.Extras.GetNode("targetNames").Deserialize>(); } catch { _morphNames = null; } - - // All meshes may use up to 3 byte streams. - _streams = new List[3]; - for (var streamIndex = 0; streamIndex < 3; streamIndex++) - _streams[streamIndex] = []; } private SubMesh Create() { // Build all the data we'll need. - // TODO: This structure is verging on a little silly. Reconsider. - BuildIndices(); - BuildVertexAttributes(); - BuildVertices(); - BuildBoundingBox(); - BuildMetaAttributes(); + foreach (var (primitive, index) in _node.Mesh.Primitives.WithIndex()) + BuildPrimitive(primitive, index); ArgumentNullException.ThrowIfNull(_indices); - ArgumentNullException.ThrowIfNull(_vertexAttributes); + ArgumentNullException.ThrowIfNull(_vertexDeclaration); + ArgumentNullException.ThrowIfNull(_strides); ArgumentNullException.ThrowIfNull(_shapeValues); - ArgumentNullException.ThrowIfNull(_metaAttributes); - var material = _primitive.Material.Name; - if (material == "") - material = null; + var metaAttributes = BuildMetaAttributes(); // At this level, we assume that attributes are wholly controlled by this sub-mesh. - var attributeMask = _metaAttributes.Length switch + var attributeMask = metaAttributes.Length switch { - < 32 => (1u << _metaAttributes.Length) - 1, + < 32 => (1u << metaAttributes.Length) - 1, 32 => uint.MaxValue, > 32 => throw _notifier.Exception("Models may utilise a maximum of 32 attributes."), }; @@ -124,156 +95,92 @@ public class SubMeshImporter SubMeshStruct = new MdlStructs.SubmeshStruct() { IndexOffset = 0, - IndexCount = (uint)_indices.Length, + IndexCount = (uint)_indices.Count, AttributeIndexMask = attributeMask, // TODO: Flesh these out. Game doesn't seem to rely on them existing, though. BoneStartIndex = 0, BoneCount = 0, }, - Material = material, - VertexDeclaration = new MdlStructs.VertexDeclarationStruct() - { - VertexElements = _vertexAttributes.Select(attribute => attribute.Element).ToArray(), - }, + Material = _material, + VertexDeclaration = _vertexDeclaration.Value, VertexCount = _vertexCount, Strides = _strides, Streams = _streams, Indices = _indices, BoundingBox = _boundingBox, - MetaAttributes = _metaAttributes, + MetaAttributes = metaAttributes, ShapeValues = _shapeValues, }; } - private void BuildIndices() + private void BuildPrimitive(MeshPrimitive meshPrimitive, int index) { - // TODO: glTF supports a bunch of primitive types, ref. Schema2.PrimitiveType. All this code is currently assuming that it's using plain triangles (4). It should probably be generalised to other formats - I _suspect_ we should be able to get away with evaluating the indices to triangles with GetTriangleIndices, but will need investigation. - _indices = _primitive.GetIndices().Select(idx => (ushort)idx).ToArray(); - } + var vertexOffset = _vertexCount; + var indexOffset = _indices.Count; - private void BuildVertexAttributes() - { - // Tangent calculation requires indices if missing. - ArgumentNullException.ThrowIfNull(_indices); + var primitive = PrimitiveImporter.Import(meshPrimitive, _nodeBoneMap, _notifier.WithContext($"Primitive {index}")); - var accessors = _primitive.VertexAccessors; + // Material + _material ??= primitive.Material; + if (primitive.Material != null && _material != primitive.Material) + _notifier.Warning($"Meshes may only reference one material. Primitive {index} material \"{primitive.Material}\" has been ignored."); - var morphAccessors = Enumerable.Range(0, _primitive.MorphTargetsCount) - .Select(index => _primitive.GetMorphTargetAccessors(index)).ToList(); + // Vertex metadata + if (_vertexDeclaration == null) + _vertexDeclaration = primitive.VertexDeclaration; + else + Utility.EnsureVertexDeclarationMatch(_vertexDeclaration.Value, primitive.VertexDeclaration, _notifier); - // Try to build all the attributes the mesh might use. - // The order here is chosen to match a typical model's element order. - var rawAttributes = new[] + _strides ??= primitive.Strides; + + // Vertices + _vertexCount += primitive.VertexCount; + + foreach (var (stream, primitiveStream) in _streams.Zip(primitive.Streams)) + stream.AddRange(primitiveStream); + + // Indices + _indices.AddRange(primitive.Indices.Select(index => (ushort)(index + vertexOffset))); + + // Shape values + foreach (var (primitiveShapeValues, morphIndex) in primitive.ShapeValues.WithIndex()) { - VertexAttribute.Position(accessors, morphAccessors, _notifier), - VertexAttribute.BlendWeight(accessors, _notifier), - VertexAttribute.BlendIndex(accessors, _nodeBoneMap, _notifier), - VertexAttribute.Normal(accessors, morphAccessors), - VertexAttribute.Tangent1(accessors, morphAccessors, _indices, _notifier), - VertexAttribute.Color(accessors), - VertexAttribute.Uv(accessors), - }; + // Per glTF spec, all primitives MUST have the same number of morph targets in the same order. + // As such, this lookup should be safe - a failure here is a broken glTF file. + var name = _morphNames != null ? _morphNames[morphIndex] : $"unnamed_shape_{morphIndex}"; - var attributes = new List(); - var offsets = new byte[] - { - 0, - 0, - 0, - }; - foreach (var attribute in rawAttributes) - { - if (attribute == null) - continue; - - attributes.Add(attribute.WithOffset(offsets[attribute.Stream])); - offsets[attribute.Stream] += attribute.Size; - } - - _vertexAttributes = attributes; - // After building the attributes, the resulting next offsets are our stream strides. - _strides = offsets; - } - - private void BuildVertices() - { - ArgumentNullException.ThrowIfNull(_vertexAttributes); - - // Lists of vertex indices that are effected by each morph target for this primitive. - var morphModifiedVertices = Enumerable.Range(0, _primitive.MorphTargetsCount) - .Select(_ => new List()) - .ToArray(); - - // We can safely assume that POSITION exists by this point - and if, by some bizarre chance, it doesn't, failing out is sane. - _vertexCount = (ushort)_primitive.VertexAccessors["POSITION"].Count; - - for (var vertexIndex = 0; vertexIndex < _vertexCount; vertexIndex++) - { - // Write out vertex data to streams for each attribute. - foreach (var attribute in _vertexAttributes) - _streams[attribute.Stream].AddRange(attribute.Build(vertexIndex)); - - // Record which morph targets have values for this vertex, if any. - var changedMorphs = morphModifiedVertices - .WithIndex() - .Where(pair => _vertexAttributes.Any(attribute => attribute.HasMorph(pair.Index, vertexIndex))) - .Select(pair => pair.Value); - foreach (var modifiedVertices in changedMorphs) - modifiedVertices.Add(vertexIndex); - } - - BuildShapeValues(morphModifiedVertices); - } - - private void BuildShapeValues(IEnumerable> morphModifiedVertices) - { - ArgumentNullException.ThrowIfNull(_indices); - ArgumentNullException.ThrowIfNull(_vertexAttributes); - - var morphShapeValues = new Dictionary>(); - - foreach (var (modifiedVertices, morphIndex) in morphModifiedVertices.WithIndex()) - { - // For a given mesh, each shape key contains a list of shape value mappings. - var shapeValues = new List(); - - foreach (var vertexIndex in modifiedVertices) + if (!_shapeValues.TryGetValue(name, out var subMeshShapeValues)) { - // Write out the morphed vertex to the vertex streams. - foreach (var attribute in _vertexAttributes) - _streams[attribute.Stream].AddRange(attribute.BuildMorph(morphIndex, vertexIndex)); - - // Find any indices that target this vertex index and create a mapping. - var targetingIndices = _indices.WithIndex() - .SelectWhere(pair => (pair.Value == vertexIndex, pair.Index)); - shapeValues.AddRange(targetingIndices.Select(targetingIndex => new MdlStructs.ShapeValueStruct - { - BaseIndicesIndex = (ushort)targetingIndex, - ReplacingVertexIndex = _vertexCount, - })); - - _vertexCount++; + subMeshShapeValues = []; + _shapeValues.Add(name, subMeshShapeValues); } - var name = _morphNames != null ? _morphNames[morphIndex] : $"unnamed_shape_{morphIndex}"; - morphShapeValues.Add(name, shapeValues); + subMeshShapeValues.AddRange(primitiveShapeValues.Select(value => value with + { + BaseIndicesIndex = (ushort)(value.BaseIndicesIndex + indexOffset), + ReplacingVertexIndex = (ushort)(value.ReplacingVertexIndex + vertexOffset), + })); } - _shapeValues = morphShapeValues; + // Bounds + _boundingBox.Merge(primitive.BoundingBox); } - private void BuildBoundingBox() + private string[] BuildMetaAttributes() { - var positions = _primitive.VertexAccessors["POSITION"].AsVector3Array(); - foreach (var position in positions) - _boundingBox.Merge(position); - } + Dictionary? nodeExtras; + try + { + nodeExtras = _node.Extras.Deserialize>(); + } + catch + { + nodeExtras = null; + } - private void BuildMetaAttributes() - { // We consider any "extras" key with a boolean value set to `true` to be an attribute. - _metaAttributes = _nodeExtras? + return nodeExtras? .Where(pair => pair.Value.ValueKind == JsonValueKind.True) .Select(pair => pair.Key) .ToArray() ?? []; diff --git a/Penumbra/Import/Models/Import/Utility.cs b/Penumbra/Import/Models/Import/Utility.cs index 449d19e4..28f47024 100644 --- a/Penumbra/Import/Models/Import/Utility.cs +++ b/Penumbra/Import/Models/Import/Utility.cs @@ -1,3 +1,5 @@ +using Lumina.Data.Parsing; + namespace Penumbra.Import.Models.Import; public static class Utility @@ -31,4 +33,35 @@ public static class Utility return newMask; } + + /// Ensures that the two vertex declarations provided are equal, throwing if not. + public static void EnsureVertexDeclarationMatch(MdlStructs.VertexDeclarationStruct current, MdlStructs.VertexDeclarationStruct @new, IoNotifier notifier) + { + if (VertexDeclarationMismatch(current, @new)) + throw notifier.Exception( + $@"All sub-meshes of a mesh must have equivalent vertex declarations. + Current: {FormatVertexDeclaration(current)} + New: {FormatVertexDeclaration(@new)}" + ); + } + + private static string FormatVertexDeclaration(MdlStructs.VertexDeclarationStruct vertexDeclaration) + => string.Join(", ", vertexDeclaration.VertexElements.Select(element => $"{element.Usage} ({element.Type}@{element.Stream}:{element.Offset})")); + + private static bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) + { + var elA = a.VertexElements; + var elB = b.VertexElements; + + if (elA.Length != elB.Length) + return true; + + // NOTE: This assumes that elements will always be in the same order. Under the current implementation, that's guaranteed. + return elA.Zip(elB).Any(pair => + pair.First.Usage != pair.Second.Usage + || pair.First.Type != pair.Second.Type + || pair.First.Offset != pair.Second.Offset + || pair.First.Stream != pair.Second.Stream + ); + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index f24464d1..ace2bcfc 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -2,7 +2,6 @@ using Lumina.Data.Parsing; using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; -using Penumbra.Import.Models; using Penumbra.Import.Models.Export; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; From a159ef28c37b3fa5fabc621610d9ebce3e0e8c0b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 23 Jan 2024 23:23:03 +0100 Subject: [PATCH 0436/1381] Cleanup --- Penumbra/Import/Models/Import/BoundingBox.cs | 8 ++--- Penumbra/Import/Models/Import/MeshImporter.cs | 5 +-- .../Import/Models/Import/PrimitiveImporter.cs | 17 ++++----- .../Import/Models/Import/SubMeshImporter.cs | 35 ++++++++++--------- Penumbra/Import/Models/Import/Utility.cs | 21 ++++++----- 5 files changed, 47 insertions(+), 39 deletions(-) diff --git a/Penumbra/Import/Models/Import/BoundingBox.cs b/Penumbra/Import/Models/Import/BoundingBox.cs index be47ebb8..b6d670ae 100644 --- a/Penumbra/Import/Models/Import/BoundingBox.cs +++ b/Penumbra/Import/Models/Import/BoundingBox.cs @@ -2,11 +2,11 @@ using Lumina.Data.Parsing; namespace Penumbra.Import.Models.Import; -/// Mutable representation of the bounding box surrouding a collection of vertices. +/// Mutable representation of the bounding box surrounding a collection of vertices. public class BoundingBox { - private Vector3 _minimum = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); - private Vector3 _maximum = new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); + private Vector3 _minimum = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + private Vector3 _maximum = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); /// Use the specified position to update this bounding box, expanding it if necessary. public void Merge(Vector3 position) @@ -25,7 +25,7 @@ public class BoundingBox /// Convert this bounding box to the struct format used in .mdl data structures. public MdlStructs.BoundingBoxStruct ToStruct() - => new MdlStructs.BoundingBoxStruct + => new() { Min = [_minimum.X, _minimum.Y, _minimum.Z, 1], Max = [_maximum.X, _maximum.Y, _maximum.Z, 1], diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index f76fa1ea..8ab55734 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -53,7 +53,7 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) private List? _bones; - private readonly BoundingBox _boundingBox = new BoundingBox(); + private readonly BoundingBox _boundingBox = new(); private readonly List _metaAttributes = []; @@ -124,7 +124,8 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) _material ??= subMesh.Material; if (subMesh.Material != null && _material != subMesh.Material) - notifier.Warning($"Meshes may only reference one material. Sub-mesh {subMeshName} material \"{subMesh.Material}\" has been ignored."); + notifier.Warning( + $"Meshes may only reference one material. Sub-mesh {subMeshName} material \"{subMesh.Material}\" has been ignored."); // Check that vertex declarations match - we need to combine the buffers, so a mismatch would take a whole load of resolution. if (_vertexDeclaration == null) diff --git a/Penumbra/Import/Models/Import/PrimitiveImporter.cs b/Penumbra/Import/Models/Import/PrimitiveImporter.cs index 9ac3d73c..0c2968df 100644 --- a/Penumbra/Import/Models/Import/PrimitiveImporter.cs +++ b/Penumbra/Import/Models/Import/PrimitiveImporter.cs @@ -35,21 +35,21 @@ public class PrimitiveImporter private readonly IDictionary? _nodeBoneMap; private ushort[]? _indices; - + private List? _vertexAttributes; - + private ushort _vertexCount; private byte[] _strides = [0, 0, 0]; private readonly List[] _streams = [[], [], []]; - - private BoundingBox _boundingBox = new BoundingBox(); + + private readonly BoundingBox _boundingBox = new(); private List>? _shapeValues; private PrimitiveImporter(MeshPrimitive primitive, IDictionary? nodeBoneMap, IoNotifier notifier) { - _notifier = notifier; - _primitive = primitive; + _notifier = notifier; + _primitive = primitive; _nodeBoneMap = nodeBoneMap; } @@ -154,9 +154,10 @@ public class PrimitiveImporter _streams[attribute.Stream].AddRange(attribute.Build(vertexIndex)); // Record which morph targets have values for this vertex, if any. + var index = vertexIndex; var changedMorphs = morphModifiedVertices .WithIndex() - .Where(pair => _vertexAttributes.Any(attribute => attribute.HasMorph(pair.Index, vertexIndex))) + .Where(pair => _vertexAttributes.Any(attribute => attribute.HasMorph(pair.Index, index))) .Select(pair => pair.Value); foreach (var modifiedVertices in changedMorphs) modifiedVertices.Add(vertexIndex); @@ -200,7 +201,7 @@ public class PrimitiveImporter _shapeValues = morphShapeValues; } - + private void BuildBoundingBox() { var positions = _primitive.VertexAccessors["POSITION"].AsVector3Array(); diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index 26f98b04..e81bb622 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -46,12 +46,12 @@ public class SubMeshImporter private byte[]? _strides; private readonly List[] _streams = [[], [], []]; - private List _indices = []; + private readonly List _indices = []; - private BoundingBox _boundingBox = new BoundingBox(); + private readonly BoundingBox _boundingBox = new(); private readonly List? _morphNames; - private Dictionary> _shapeValues = []; + private readonly Dictionary> _shapeValues = []; private SubMeshImporter(Node node, IDictionary? nodeBoneMap, IoNotifier notifier) { @@ -86,7 +86,7 @@ public class SubMeshImporter var attributeMask = metaAttributes.Length switch { < 32 => (1u << metaAttributes.Length) - 1, - 32 => uint.MaxValue, + 32 => uint.MaxValue, > 32 => throw _notifier.Exception("Models may utilise a maximum of 32 attributes."), }; @@ -102,22 +102,22 @@ public class SubMeshImporter BoneStartIndex = 0, BoneCount = 0, }, - Material = _material, + Material = _material, VertexDeclaration = _vertexDeclaration.Value, - VertexCount = _vertexCount, - Strides = _strides, - Streams = _streams, - Indices = _indices, - BoundingBox = _boundingBox, - MetaAttributes = metaAttributes, - ShapeValues = _shapeValues, + VertexCount = _vertexCount, + Strides = _strides, + Streams = _streams, + Indices = _indices, + BoundingBox = _boundingBox, + MetaAttributes = metaAttributes, + ShapeValues = _shapeValues, }; } private void BuildPrimitive(MeshPrimitive meshPrimitive, int index) { var vertexOffset = _vertexCount; - var indexOffset = _indices.Count; + var indexOffset = _indices.Count; var primitive = PrimitiveImporter.Import(meshPrimitive, _nodeBoneMap, _notifier.WithContext($"Primitive {index}")); @@ -141,7 +141,7 @@ public class SubMeshImporter stream.AddRange(primitiveStream); // Indices - _indices.AddRange(primitive.Indices.Select(index => (ushort)(index + vertexOffset))); + _indices.AddRange(primitive.Indices.Select(i => (ushort)(i + vertexOffset))); // Shape values foreach (var (primitiveShapeValues, morphIndex) in primitive.ShapeValues.WithIndex()) @@ -181,8 +181,9 @@ public class SubMeshImporter // We consider any "extras" key with a boolean value set to `true` to be an attribute. return nodeExtras? - .Where(pair => pair.Value.ValueKind == JsonValueKind.True) - .Select(pair => pair.Key) - .ToArray() ?? []; + .Where(pair => pair.Value.ValueKind == JsonValueKind.True) + .Select(pair => pair.Key) + .ToArray() + ?? []; } } diff --git a/Penumbra/Import/Models/Import/Utility.cs b/Penumbra/Import/Models/Import/Utility.cs index 28f47024..a1e44136 100644 --- a/Penumbra/Import/Models/Import/Utility.cs +++ b/Penumbra/Import/Models/Import/Utility.cs @@ -4,11 +4,11 @@ namespace Penumbra.Import.Models.Import; public static class Utility { - /// Merge attributes into an existing attribute array, providing an updated submesh mask. - /// Old submesh attribute mask. + /// Merge attributes into an existing attribute array, providing an updated sub mesh mask. + /// Old sub mesh attribute mask. /// Old attribute array that should be merged. /// New attribute array. Will be mutated. - /// New submesh attribute mask, updated to match the merged attribute array. + /// New sub mesh attribute mask, updated to match the merged attribute array. public static uint GetMergedAttributeMask(uint oldMask, IList oldAttributes, List newAttributes) { var metaAttributes = Enumerable.Range(0, 32) @@ -28,6 +28,7 @@ public static class Utility newAttributes.Add(metaAttribute); attributeIndex = newAttributes.Count - 1; } + newMask |= 1u << attributeIndex; } @@ -35,18 +36,22 @@ public static class Utility } /// Ensures that the two vertex declarations provided are equal, throwing if not. - public static void EnsureVertexDeclarationMatch(MdlStructs.VertexDeclarationStruct current, MdlStructs.VertexDeclarationStruct @new, IoNotifier notifier) + public static void EnsureVertexDeclarationMatch(MdlStructs.VertexDeclarationStruct current, MdlStructs.VertexDeclarationStruct @new, + IoNotifier notifier) { if (VertexDeclarationMismatch(current, @new)) throw notifier.Exception( - $@"All sub-meshes of a mesh must have equivalent vertex declarations. - Current: {FormatVertexDeclaration(current)} - New: {FormatVertexDeclaration(@new)}" + $""" + All sub-meshes of a mesh must have equivalent vertex declarations. + Current: {FormatVertexDeclaration(current)} + New: {FormatVertexDeclaration(@new)} + """ ); } private static string FormatVertexDeclaration(MdlStructs.VertexDeclarationStruct vertexDeclaration) - => string.Join(", ", vertexDeclaration.VertexElements.Select(element => $"{element.Usage} ({element.Type}@{element.Stream}:{element.Offset})")); + => string.Join(", ", + vertexDeclaration.VertexElements.Select(element => $"{element.Usage} ({element.Type}@{element.Stream}:{element.Offset})")); private static bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) { From 6693a1e0bad504916906aa161cec69365fcbb8a6 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 27 Jan 2024 13:53:56 +1100 Subject: [PATCH 0437/1381] Clear errors/warnings before starting IO --- .../ModEditWindow.Models.MdlTab.cs | 58 ++++++++++++------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index ace2bcfc..b3c0cacd 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -2,6 +2,7 @@ using Lumina.Data.Parsing; using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; +using Penumbra.Import.Models; using Penumbra.Import.Models.Export; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; @@ -79,7 +80,7 @@ public partial class ModEditWindow return; } - PendingIo = true; + BeginIo(); var task = Task.Run(() => { // TODO: Is it worth trying to order results based on option priorities for cases where more than one match is found? @@ -93,9 +94,7 @@ public partial class ModEditWindow task.ContinueWith(t => { - RecordIoExceptions(t.Exception); - GamePaths = t.Result; - PendingIo = false; + GamePaths = FinalizeIo(task); }); } @@ -132,33 +131,22 @@ public partial class ModEditWindow return; } - PendingIo = true; + BeginIo(); _edit._models.ExportToGltf(ExportConfig, Mdl, sklbPaths, ReadFile, outputPath) - .ContinueWith(task => - { - RecordIoExceptions(task.Exception); - if (task is { IsCompletedSuccessfully: true, Result: not null }) - IoWarnings = task.Result.GetWarnings().ToList(); - PendingIo = false; - }); + .ContinueWith(FinalizeIo); } /// Import a model from an interchange format. /// Disk path to load model data from. public void Import(string inputPath) { - PendingIo = true; + BeginIo(); _edit._models.ImportGltf(inputPath) .ContinueWith(task => { - RecordIoExceptions(task.Exception); - if (task is { IsCompletedSuccessfully: true, Result: (not null, _) }) - { - IoWarnings = task.Result.Item2.GetWarnings().ToList(); - FinalizeImport(task.Result.Item1); - } - - PendingIo = false; + var mdlFile = FinalizeIo(task, result => result.Item1, result => result.Item2); + if (mdlFile != null) + FinalizeImport(mdlFile); }); } @@ -255,6 +243,34 @@ public partial class ModEditWindow target.ElementIds = [.. elementIds]; } + private void BeginIo() + { + PendingIo = true; + IoWarnings = []; + IoExceptions = []; + } + + private void FinalizeIo(Task task) + => FinalizeIo(task, notifier => null, notifier => notifier); + + private TResult? FinalizeIo(Task task) + => FinalizeIo(task, result => result, null); + + private TResult? FinalizeIo(Task task, Func getResult, Func? getNotifier) + { + TResult? result = default; + RecordIoExceptions(task.Exception); + if (task is { IsCompletedSuccessfully: true, Result: not null }) + { + result = getResult(task.Result); + if (getNotifier != null) + IoWarnings = getNotifier(task.Result).GetWarnings().ToList(); + } + PendingIo = false; + + return result; + } + private void RecordIoExceptions(Exception? exception) { IoExceptions = exception switch From 72775a80bfbcc1b7c7ab06827f1caf6722195a9d Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 27 Jan 2024 14:08:56 +1100 Subject: [PATCH 0438/1381] Ignore invalid attributes on export --- Penumbra/Import/Models/Export/MeshExporter.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 5347b87d..1a06acd1 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -230,10 +230,19 @@ public class MeshExporter { "targetNames", shapeNames }, }); - var attributes = Enumerable.Range(0, 32) - .Where(index => ((attributeMask >> index) & 1) == 1) - .Select(index => _mdl.Attributes[index]) - .ToArray(); + string[] attributes = []; + var maxAttribute = 31 - BitOperations.LeadingZeroCount(attributeMask); + if (maxAttribute < _mdl.Attributes.Length) + { + attributes = Enumerable.Range(0, 32) + .Where(index => ((attributeMask >> index) & 1) == 1) + .Select(index => _mdl.Attributes[index]) + .ToArray(); + } + else + { + _notifier.Warning($"Invalid attribute data, ignoring."); + } return new MeshData { From 1649da70a899fa90ad3ced2a37ff1d8e726b0a16 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 27 Jan 2024 17:56:32 +1100 Subject: [PATCH 0439/1381] Fix Blender 3.6 support for custom colour attribute --- Penumbra/Import/Models/Export/VertexFragment.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index 27d2ab10..08b2a214 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -11,7 +11,8 @@ and there's reason to overhaul the export pipeline. public struct VertexColorFfxiv : IVertexCustom { - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_BYTE, false)] + // NOTE: We only realistically require UNSIGNED_BYTE for this, however Blender 3.6 errors on that (fixed in 4.0). + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, false)] public Vector4 FfxivColor; public int MaxColors => 0; @@ -80,7 +81,7 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom [VertexAttribute("TEXCOORD_0")] public Vector2 TexCoord0; - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_BYTE, false)] + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, false)] public Vector4 FfxivColor; public int MaxColors => 0; @@ -162,7 +163,7 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom [VertexAttribute("TEXCOORD_1")] public Vector2 TexCoord1; - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_BYTE, false)] + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, false)] public Vector4 FfxivColor; public int MaxColors => 0; From e9628afaf84ac8afc24eaeddc5a92f12c00e3f2f Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 27 Jan 2024 18:35:26 +1100 Subject: [PATCH 0440/1381] Include specular factor in character material export --- .../Import/Models/Export/MaterialExporter.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 307e9d2b..cb2cf6f5 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -89,11 +89,15 @@ public class MaterialExporter // TODO: handle other textures stored in the mask? } + // Specular extension puts colour on RGB and factor on A. We're already packing like that, so we can reuse the texture. + var specularImage = BuildImage(specular, name, "specular"); + return BuildSharedBase(material, name) .WithBaseColor(BuildImage(baseColor, name, "basecolor")) .WithNormal(BuildImage(operation.Normal, name, "normal")) - .WithSpecularColor(BuildImage(specular, name, "specular")) - .WithEmissive(BuildImage(operation.Emissive, name, "emissive"), Vector3.One, 1); + .WithEmissive(BuildImage(operation.Emissive, name, "emissive"), Vector3.One, 1) + .WithSpecularFactor(specularImage, 1) + .WithSpecularColor(specularImage); } // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. @@ -102,7 +106,7 @@ public class MaterialExporter { public Image Normal { get; } = normal.Clone(); public Image BaseColor { get; } = new(normal.Width, normal.Height); - public Image Specular { get; } = new(normal.Width, normal.Height); + public Image Specular { get; } = new(normal.Width, normal.Height); public Image Emissive { get; } = new(normal.Width, normal.Height); private Buffer2D NormalBuffer @@ -111,7 +115,7 @@ public class MaterialExporter private Buffer2D BaseColorBuffer => BaseColor.Frames.RootFrame.PixelBuffer; - private Buffer2D SpecularBuffer + private Buffer2D SpecularBuffer => Specular.Frames.RootFrame.PixelBuffer; private Buffer2D EmissiveBuffer @@ -140,7 +144,9 @@ public class MaterialExporter // Specular (table) var lerpedSpecularColor = Vector3.Lerp(prevRow.Specular, nextRow.Specular, tableRow.Weight); - specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, 1)); + // float.Lerp is .NET8 ;-; + var lerpedSpecularFactor = prevRow.SpecularStrength * (1.0f - tableRow.Weight) + nextRow.SpecularStrength * tableRow.Weight; + specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, lerpedSpecularFactor)); // Emissive (table) var lerpedEmissive = Vector3.Lerp(prevRow.Emissive, nextRow.Emissive, tableRow.Weight); From 5a80e65d3b6dced06f7bcd1445c9660c507e72b5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Jan 2024 18:51:16 +0100 Subject: [PATCH 0441/1381] Add SetCutsceneParentIndex. --- Penumbra.Api | 2 +- Penumbra/Api/IpcTester.cs | 17 +++++++++++++++-- Penumbra/Api/PenumbraApi.cs | 9 +++++++++ Penumbra/Api/PenumbraIpcProviders.cs | 3 +++ .../Interop/PathResolving/CutsceneService.cs | 18 ++++++++++++++++++ 5 files changed, 46 insertions(+), 3 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index cfc51714..b28288ee 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit cfc51714f74cae93608bc507775a9580cd1801de +Subproject commit b28288ee9668425f49f41cba88e8dc417ad62aff diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index aea95156..380b741c 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -484,7 +484,9 @@ public class IpcTester : IDisposable private DateTimeOffset _lastResolvedGamePathTime = DateTimeOffset.MaxValue; private string _currentDrawObjectString = string.Empty; private IntPtr _currentDrawObject = IntPtr.Zero; - private int _currentCutsceneActor = 0; + private int _currentCutsceneActor; + private int _currentCutsceneParent; + private PenumbraApiEc _cutsceneError = PenumbraApiEc.Success; public GameState(DalamudPluginInterface pi) { @@ -507,7 +509,14 @@ public class IpcTester : IDisposable ? tmp : IntPtr.Zero; - ImGui.InputInt("Cutscene Actor", ref _currentCutsceneActor, 0); + ImGui.InputInt("Cutscene Actor", ref _currentCutsceneActor, 0); + ImGui.InputInt("Cutscene Parent", ref _currentCutsceneParent, 0); + if (_cutsceneError is not PenumbraApiEc.Success) + { + ImGui.SameLine(); + ImGui.TextUnformatted("Invalid Argument on last Call"); + } + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); if (!table) return; @@ -526,6 +535,10 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetCutsceneParentIndex.Label, "Cutscene Parent"); ImGui.TextUnformatted(Ipc.GetCutsceneParentIndex.Subscriber(_pi).Invoke(_currentCutsceneActor).ToString()); + DrawIntro(Ipc.SetCutsceneParentIndex.Label, "Cutscene Parent"); + if (ImGui.Button("Set Parent")) + _cutsceneError = Ipc.SetCutsceneParentIndex.Subscriber(_pi).Invoke(_currentCutsceneActor, _currentCutsceneParent); + DrawIntro(Ipc.CreatingCharacterBase.Label, "Last Drawobject created"); if (_lastCreatedGameObjectTime < DateTimeOffset.Now) ImGui.TextUnformatted(_lastCreatedDrawObject != IntPtr.Zero diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 2a7a9bfb..04c0499b 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -600,6 +600,15 @@ public class PenumbraApi : IDisposable, IPenumbraApi return _cutsceneService.GetParentIndex(actorIdx); } + public PenumbraApiEc SetCutsceneParentIndex(int copyIdx, int newParentIdx) + { + CheckInitialized(); + if (_cutsceneService.SetParentIndex(copyIdx, newParentIdx)) + return PenumbraApiEc.Success; + + return PenumbraApiEc.InvalidArgument; + } + public IList<(string, string)> GetModList() { CheckInitialized(); diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index 1df90dd9..d478b675 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -47,6 +47,7 @@ public class PenumbraIpcProviders : IDisposable // Game State internal readonly FuncProvider GetDrawObjectInfo; internal readonly FuncProvider GetCutsceneParentIndex; + internal readonly FuncProvider SetCutsceneParentIndex; internal readonly EventProvider CreatingCharacterBase; internal readonly EventProvider CreatedCharacterBase; internal readonly EventProvider GameObjectResourcePathResolved; @@ -171,6 +172,7 @@ public class PenumbraIpcProviders : IDisposable // Game State GetDrawObjectInfo = Ipc.GetDrawObjectInfo.Provider(pi, Api.GetDrawObjectInfo); GetCutsceneParentIndex = Ipc.GetCutsceneParentIndex.Provider(pi, Api.GetCutsceneParentIndex); + SetCutsceneParentIndex = Ipc.SetCutsceneParentIndex.Provider(pi, Api.SetCutsceneParentIndex); CreatingCharacterBase = Ipc.CreatingCharacterBase.Provider(pi, () => Api.CreatingCharacterBase += CreatingCharacterBaseEvent, () => Api.CreatingCharacterBase -= CreatingCharacterBaseEvent); @@ -293,6 +295,7 @@ public class PenumbraIpcProviders : IDisposable // Game State GetDrawObjectInfo.Dispose(); GetCutsceneParentIndex.Dispose(); + SetCutsceneParentIndex.Dispose(); CreatingCharacterBase.Dispose(); CreatedCharacterBase.Dispose(); GameObjectResourcePathResolved.Dispose(); diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 85944d74..89b9f917 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -56,6 +56,24 @@ public sealed class CutsceneService : IService, IDisposable public int GetParentIndex(int idx) => GetParentIndex((ushort)idx); + public bool SetParentIndex(int copyIdx, int parentIdx) + { + if (copyIdx is < CutsceneStartIdx or >= CutsceneEndIdx) + return false; + + if (parentIdx is < -1 or >= CutsceneEndIdx) + return false; + + if (_objects.GetObjectAddress(copyIdx) == nint.Zero) + return false; + + if (parentIdx != -1 && _objects.GetObjectAddress(parentIdx) == nint.Zero) + return false; + + _copiedCharacters[copyIdx - CutsceneStartIdx] = (short)parentIdx; + return true; + } + public short GetParentIndex(ushort idx) { if (idx is >= CutsceneStartIdx and < CutsceneEndIdx) From 076dab924fa21e67d28e88ee5a01601c532160a5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Jan 2024 18:58:26 +0100 Subject: [PATCH 0442/1381] Reuse same list for warnings and exceptions. --- .../ModEditWindow.Models.MdlTab.cs | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index b3c0cacd..37b9dfb5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -28,8 +28,8 @@ public partial class ModEditWindow private bool _dirty; public bool PendingIo { get; private set; } - public List IoExceptions { get; private set; } = []; - public List IoWarnings { get; private set; } = []; + public List IoExceptions { get; } = []; + public List IoWarnings { get; } = []; public MdlTab(ModEditWindow edit, byte[] bytes, string path) { @@ -92,10 +92,7 @@ public partial class ModEditWindow .ToList(); }); - task.ContinueWith(t => - { - GamePaths = FinalizeIo(task); - }); + task.ContinueWith(t => { GamePaths = FinalizeIo(task); }); } private EstManipulation[] GetCurrentEstManipulations() @@ -246,8 +243,8 @@ public partial class ModEditWindow private void BeginIo() { PendingIo = true; - IoWarnings = []; - IoExceptions = []; + IoWarnings.Clear(); + IoExceptions.Clear(); } private void FinalizeIo(Task task) @@ -264,8 +261,9 @@ public partial class ModEditWindow { result = getResult(task.Result); if (getNotifier != null) - IoWarnings = getNotifier(task.Result).GetWarnings().ToList(); + IoWarnings.AddRange(getNotifier(task.Result).GetWarnings()); } + PendingIo = false; return result; @@ -273,12 +271,16 @@ public partial class ModEditWindow private void RecordIoExceptions(Exception? exception) { - IoExceptions = exception switch + switch (exception) { - null => [], - AggregateException ae => [.. ae.Flatten().InnerExceptions], - _ => [exception], - }; + case null: break; + case AggregateException ae: + IoExceptions.AddRange(ae.Flatten().InnerExceptions); + break; + default: + IoExceptions.Add(exception); + break; + } } /// Read a file from the active collection or game. From 1e4570bd79193e22d6870e1d057888d7f9b1653a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Jan 2024 19:05:05 +0100 Subject: [PATCH 0443/1381] Slight cleanup. --- Penumbra/Import/Models/Export/MaterialExporter.cs | 2 +- Penumbra/Import/Models/Export/MeshExporter.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index cb2cf6f5..f17fdaa2 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -144,7 +144,7 @@ public class MaterialExporter // Specular (table) var lerpedSpecularColor = Vector3.Lerp(prevRow.Specular, nextRow.Specular, tableRow.Weight); - // float.Lerp is .NET8 ;-; + // float.Lerp is .NET8 ;-; #TODO var lerpedSpecularFactor = prevRow.SpecularStrength * (1.0f - tableRow.Weight) + nextRow.SpecularStrength * tableRow.Weight; specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, lerpedSpecularFactor)); diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 1a06acd1..df315094 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -241,7 +241,7 @@ public class MeshExporter } else { - _notifier.Warning($"Invalid attribute data, ignoring."); + _notifier.Warning("Invalid attribute data, ignoring."); } return new MeshData diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 37b9dfb5..7adc4379 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -92,7 +92,7 @@ public partial class ModEditWindow .ToList(); }); - task.ContinueWith(t => { GamePaths = FinalizeIo(task); }); + task.ContinueWith(t => { GamePaths = FinalizeIo(t); }); } private EstManipulation[] GetCurrentEstManipulations() @@ -171,7 +171,7 @@ public partial class ModEditWindow /// Merge material configuration from the source onto the target. /// Model that will be updated. /// Model to copy material configuration from. - public void MergeMaterials(MdlFile target, MdlFile source) + private static void MergeMaterials(MdlFile target, MdlFile source) { target.Materials = source.Materials; @@ -186,7 +186,7 @@ public partial class ModEditWindow /// Merge attribute configuration from the source onto the target. /// Model that will be updated. > /// Model to copy attribute configuration from. - public static void MergeAttributes(MdlFile target, MdlFile source) + private static void MergeAttributes(MdlFile target, MdlFile source) { target.Attributes = source.Attributes; @@ -248,7 +248,7 @@ public partial class ModEditWindow } private void FinalizeIo(Task task) - => FinalizeIo(task, notifier => null, notifier => notifier); + => FinalizeIo(task, _ => null, notifier => notifier); private TResult? FinalizeIo(Task task) => FinalizeIo(task, result => result, null); From e321cbdf9691b3e97d73761b4852a08866425bb9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Jan 2024 19:07:51 +0100 Subject: [PATCH 0444/1381] Update API minor Version. --- Penumbra.Api | 2 +- Penumbra/Api/PenumbraApi.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index b28288ee..31bf4ad9 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit b28288ee9668425f49f41cba88e8dc417ad62aff +Subproject commit 31bf4ad9b82fc980d6bda049da595368ad754931 diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 04c0499b..1a0764c7 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -30,7 +30,7 @@ namespace Penumbra.Api; public class PenumbraApi : IDisposable, IPenumbraApi { public (int, int) ApiVersion - => (4, 22); + => (4, 23); public event Action? PreSettingsPanelDraw { From 4610686a70636863d0671bde99298e6e198c7e53 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 27 Jan 2024 18:10:34 +0000 Subject: [PATCH 0445/1381] [CI] Updating repo.json for 1.0.0.4 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index eef374b5..fc95fef3 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.3", - "TestingAssemblyVersion": "1.0.0.3", + "AssemblyVersion": "1.0.0.4", + "TestingAssemblyVersion": "1.0.0.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.3/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.4/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.4/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a5f0c2f94398c85884f9646b4a6046d98be5680d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 29 Jan 2024 13:27:05 +0100 Subject: [PATCH 0446/1381] Fix exception with empty option groups. --- Penumbra/Mods/Subclasses/ModSettings.cs | 180 ++++++++++----------- Penumbra/Mods/Subclasses/SingleModGroup.cs | 2 +- 2 files changed, 87 insertions(+), 95 deletions(-) diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index 71a56c80..a20cb9cb 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -11,9 +11,9 @@ namespace Penumbra.Mods.Subclasses; public class ModSettings { public static readonly ModSettings Empty = new(); - public List< uint > Settings { get; private init; } = []; - public int Priority { get; set; } - public bool Enabled { get; set; } + public List Settings { get; private init; } = []; + public int Priority { get; set; } + public bool Enabled { get; set; } // Create an independent copy of the current settings. public ModSettings DeepCopy() @@ -25,148 +25,143 @@ public class ModSettings }; // Create default settings for a given mod. - public static ModSettings DefaultSettings( Mod mod ) + public static ModSettings DefaultSettings(Mod mod) => new() { Enabled = false, Priority = 0, - Settings = mod.Groups.Select( g => g.DefaultSettings ).ToList(), + Settings = mod.Groups.Select(g => g.DefaultSettings).ToList(), }; // Return everything required to resolve things for a single mod with given settings (which can be null, in which case the default is used. - public static (Dictionary< Utf8GamePath, FullPath >, HashSet< MetaManipulation >) GetResolveData( Mod mod, ModSettings? settings ) + public static (Dictionary, HashSet) GetResolveData(Mod mod, ModSettings? settings) { if (settings == null) settings = DefaultSettings(mod); else - settings.AddMissingSettings( mod ); + settings.AddMissingSettings(mod); - var dict = new Dictionary< Utf8GamePath, FullPath >(); - var set = new HashSet< MetaManipulation >(); + var dict = new Dictionary(); + var set = new HashSet(); - foreach( var (group, index) in mod.Groups.WithIndex().OrderByDescending( g => g.Value.Priority ) ) + foreach (var (group, index) in mod.Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) { - if( group.Type is GroupType.Single ) + if (group.Type is GroupType.Single) { - AddOption( group[ ( int )settings.Settings[ index ] ] ); + if (group.Count > 0) + AddOption(group[(int)settings.Settings[index]]); } else { - foreach( var (option, optionIdx) in group.WithIndex().OrderByDescending( o => group.OptionPriority( o.Index ) ) ) + foreach (var (option, optionIdx) in group.WithIndex().OrderByDescending(o => group.OptionPriority(o.Index))) { - if( ( ( settings.Settings[ index ] >> optionIdx ) & 1 ) == 1 ) - { - AddOption( option ); - } + if (((settings.Settings[index] >> optionIdx) & 1) == 1) + AddOption(option); } } } - AddOption( mod.Default ); - return ( dict, set ); + AddOption(mod.Default); + return (dict, set); - void AddOption( ISubMod option ) + void AddOption(ISubMod option) { - foreach( var (path, file) in option.Files.Concat( option.FileSwaps ) ) - { - dict.TryAdd( path, file ); - } + foreach (var (path, file) in option.Files.Concat(option.FileSwaps)) + dict.TryAdd(path, file); - foreach( var manip in option.Manipulations ) - { - set.Add( manip ); - } + foreach (var manip in option.Manipulations) + set.Add(manip); } } // Automatically react to changes in a mods available options. - public bool HandleChanges( ModOptionChangeType type, Mod mod, int groupIdx, int optionIdx, int movedToIdx ) + public bool HandleChanges(ModOptionChangeType type, Mod mod, int groupIdx, int optionIdx, int movedToIdx) { - switch( type ) + switch (type) { case ModOptionChangeType.GroupRenamed: return true; case ModOptionChangeType.GroupAdded: // Add new empty setting for new mod. - Settings.Insert( groupIdx, mod.Groups[ groupIdx ].DefaultSettings ); + Settings.Insert(groupIdx, mod.Groups[groupIdx].DefaultSettings); return true; case ModOptionChangeType.GroupDeleted: // Remove setting for deleted mod. - Settings.RemoveAt( groupIdx ); + Settings.RemoveAt(groupIdx); return true; case ModOptionChangeType.GroupTypeChanged: { // Fix settings for a changed group type. // Single -> Multi: set single as enabled, rest as disabled // Multi -> Single: set the first enabled option or 0. - var group = mod.Groups[ groupIdx ]; - var config = Settings[ groupIdx ]; - Settings[ groupIdx ] = group.Type switch + var group = mod.Groups[groupIdx]; + var config = Settings[groupIdx]; + Settings[groupIdx] = group.Type switch { - GroupType.Single => ( uint )Math.Max( Math.Min( group.Count - 1, BitOperations.TrailingZeroCount( config ) ), 0 ), - GroupType.Multi => 1u << ( int )config, + GroupType.Single => (uint)Math.Max(Math.Min(group.Count - 1, BitOperations.TrailingZeroCount(config)), 0), + GroupType.Multi => 1u << (int)config, _ => config, }; - return config != Settings[ groupIdx ]; + return config != Settings[groupIdx]; } case ModOptionChangeType.OptionDeleted: { // Single -> select the previous option if any. // Multi -> excise the corresponding bit. - var group = mod.Groups[ groupIdx ]; - var config = Settings[ groupIdx ]; - Settings[ groupIdx ] = group.Type switch + var group = mod.Groups[groupIdx]; + var config = Settings[groupIdx]; + Settings[groupIdx] = group.Type switch { GroupType.Single => config >= optionIdx ? config > 1 ? config - 1 : 0 : config, - GroupType.Multi => Functions.RemoveBit( config, optionIdx ), + GroupType.Multi => Functions.RemoveBit(config, optionIdx), _ => config, }; - return config != Settings[ groupIdx ]; + return config != Settings[groupIdx]; } case ModOptionChangeType.GroupMoved: // Move the group the same way. - return Settings.Move( groupIdx, movedToIdx ); + return Settings.Move(groupIdx, movedToIdx); case ModOptionChangeType.OptionMoved: { // Single -> select the moved option if it was currently selected // Multi -> move the corresponding bit - var group = mod.Groups[ groupIdx ]; - var config = Settings[ groupIdx ]; - Settings[ groupIdx ] = group.Type switch + var group = mod.Groups[groupIdx]; + var config = Settings[groupIdx]; + Settings[groupIdx] = group.Type switch { - GroupType.Single => config == optionIdx ? ( uint )movedToIdx : config, - GroupType.Multi => Functions.MoveBit( config, optionIdx, movedToIdx ), + GroupType.Single => config == optionIdx ? (uint)movedToIdx : config, + GroupType.Multi => Functions.MoveBit(config, optionIdx, movedToIdx), _ => config, }; - return config != Settings[ groupIdx ]; + return config != Settings[groupIdx]; } default: return false; } } // Ensure that a value is valid for a group. - private static uint FixSetting( IModGroup group, uint value ) + private static uint FixSetting(IModGroup group, uint value) => group.Type switch { - GroupType.Single => ( uint )Math.Min( value, group.Count - 1 ), - GroupType.Multi => ( uint )( value & ( ( 1ul << group.Count ) - 1 ) ), + GroupType.Single => (uint)Math.Min(value, group.Count - 1), + GroupType.Multi => (uint)(value & ((1ul << group.Count) - 1)), _ => value, }; // Set a setting. Ensures that there are enough settings and fixes the setting beforehand. - public void SetValue( Mod mod, int groupIdx, uint newValue ) + public void SetValue(Mod mod, int groupIdx, uint newValue) { - AddMissingSettings( mod ); - var group = mod.Groups[ groupIdx ]; - Settings[ groupIdx ] = FixSetting( group, newValue ); + AddMissingSettings(mod); + var group = mod.Groups[groupIdx]; + Settings[groupIdx] = FixSetting(group, newValue); } // Add defaulted settings up to the required count. - private bool AddMissingSettings( Mod mod ) + private bool AddMissingSettings(Mod mod) { var changes = false; - for( var i = Settings.Count; i < mod.Groups.Count; ++i ) + for (var i = Settings.Count; i < mod.Groups.Count; ++i) { - Settings.Add( mod.Groups[ i ].DefaultSettings ); + Settings.Add(mod.Groups[i].DefaultSettings); changes = true; } @@ -176,51 +171,47 @@ public class ModSettings // A simple struct conversion to easily save settings by name instead of value. public struct SavedSettings { - public Dictionary< string, long > Settings; - public int Priority; - public bool Enabled; + public Dictionary Settings; + public int Priority; + public bool Enabled; public SavedSettings DeepCopy() => new() { Enabled = Enabled, Priority = Priority, - Settings = Settings.ToDictionary( kvp => kvp.Key, kvp => kvp.Value ), + Settings = Settings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), }; - public SavedSettings( ModSettings settings, Mod mod ) + public SavedSettings(ModSettings settings, Mod mod) { Priority = settings.Priority; Enabled = settings.Enabled; - Settings = new Dictionary< string, long >( mod.Groups.Count ); - settings.AddMissingSettings( mod ); + Settings = new Dictionary(mod.Groups.Count); + settings.AddMissingSettings(mod); - foreach( var (group, setting) in mod.Groups.Zip( settings.Settings ) ) - { - Settings.Add( group.Name, setting ); - } + foreach (var (group, setting) in mod.Groups.Zip(settings.Settings)) + Settings.Add(group.Name, setting); } // Convert and fix. - public bool ToSettings( Mod mod, out ModSettings settings ) + public bool ToSettings(Mod mod, out ModSettings settings) { - var list = new List< uint >( mod.Groups.Count ); + var list = new List(mod.Groups.Count); var changes = Settings.Count != mod.Groups.Count; - foreach( var group in mod.Groups ) + foreach (var group in mod.Groups) { - if( Settings.TryGetValue( group.Name, out var config ) ) + if (Settings.TryGetValue(group.Name, out var config)) { - var castConfig = ( uint )Math.Clamp( config, 0, uint.MaxValue ); - var actualConfig = FixSetting( group, castConfig ); - list.Add( actualConfig ); - if( actualConfig != config ) - { + var castConfig = (uint)Math.Clamp(config, 0, uint.MaxValue); + var actualConfig = FixSetting(group, castConfig); + list.Add(actualConfig); + if (actualConfig != config) changes = true; - } } else { - list.Add( 0 ); + list.Add(0); changes = true; } } @@ -238,28 +229,29 @@ public class ModSettings // Return the settings for a given mod in a shareable format, using the names of groups and options instead of indices. // Does not repair settings but ignores settings not fitting to the given mod. - public (bool Enabled, int Priority, Dictionary< string, IList< string > > Settings) ConvertToShareable( Mod mod ) + public (bool Enabled, int Priority, Dictionary> Settings) ConvertToShareable(Mod mod) { - var dict = new Dictionary< string, IList< string > >( Settings.Count ); - foreach( var (setting, idx) in Settings.WithIndex() ) + var dict = new Dictionary>(Settings.Count); + foreach (var (setting, idx) in Settings.WithIndex()) { - if( idx >= mod.Groups.Count ) - { + if (idx >= mod.Groups.Count) break; - } - var group = mod.Groups[ idx ]; - if( group.Type == GroupType.Single && setting < group.Count ) + var group = mod.Groups[idx]; + if (group.Type == GroupType.Single && setting < group.Count) { - dict.Add( group.Name, new[] { group[ ( int )setting ].Name } ); + dict.Add(group.Name, new[] + { + group[(int)setting].Name, + }); } else { - var list = group.Where( ( _, optionIdx ) => ( setting & ( 1 << optionIdx ) ) != 0 ).Select( o => o.Name ).ToList(); - dict.Add( group.Name, list ); + var list = group.Where((_, optionIdx) => (setting & (1 << optionIdx)) != 0).Select(o => o.Name).ToList(); + dict.Add(group.Name, list); } } - return ( Enabled, Priority, dict ); + return (Enabled, Priority, dict); } } diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index 1184b6ed..2b7ebd09 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -17,7 +17,7 @@ public sealed class SingleModGroup : IModGroup public int Priority { get; set; } public uint DefaultSettings { get; set; } - public readonly List OptionData = new(); + public readonly List OptionData = []; public int OptionPriority(Index _) => Priority; From 95d5d6c4b01c9269950bf42851d20f303317541f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 12 Feb 2024 23:30:41 +0100 Subject: [PATCH 0447/1381] Update submodules. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index c6f101bb..1a187f75 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c6f101bbef976b74eb651523445563dd81fafbaf +Subproject commit 1a187f756f2e8823197bd43db1c3383231f5eaff diff --git a/Penumbra.Api b/Penumbra.Api index 31bf4ad9..a28219ac 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 31bf4ad9b82fc980d6bda049da595368ad754931 +Subproject commit a28219ac57b53c3be6ca8c252ceb9f76ae0b6c21 diff --git a/Penumbra.GameData b/Penumbra.GameData index 63f4de73..0d267233 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 63f4de7305616b6cb8921513e5d83baa8913353f +Subproject commit 0d267233724d493d9ae2bf8d1e67bfbb8b337916 From d2bfcefb899d7e8ede7f4a424ea5de9da66c681e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 12 Feb 2024 23:32:45 +0100 Subject: [PATCH 0448/1381] Update Combos. --- Penumbra/Import/Textures/TextureDrawer.cs | 14 +++++++------- Penumbra/Mods/Manager/ModStorage.cs | 2 +- Penumbra/Services/StainService.cs | 6 +++--- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 17 ++--------------- Penumbra/UI/CollectionTab/CollectionCombo.cs | 14 +++++--------- 6 files changed, 19 insertions(+), 36 deletions(-) diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index 04422116..427db92d 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -32,7 +32,8 @@ public static class TextureDrawer if (texture.LoadError is DllNotFoundException) { - ImGuiUtil.TextColored(Colors.RegexWarningBorder, "A texture handling dependency could not be found. Try installing a current Microsoft VC Redistributable."); + ImGuiUtil.TextColored(Colors.RegexWarningBorder, + "A texture handling dependency could not be found. Try installing a current Microsoft VC Redistributable."); if (ImGui.Button("Microsoft VC Redistributables")) Dalamud.Utility.Util.OpenLink(link); ImGuiUtil.HoverTooltip($"Open {link} in your browser."); @@ -111,14 +112,12 @@ public static class TextureDrawer } } - public sealed class PathSelectCombo : FilterComboCache<(string Path, bool Game, bool IsOnPlayer)> + public sealed class PathSelectCombo(TextureManager textures, ModEditor editor, Func> getPlayerResources) + : FilterComboCache<(string Path, bool Game, bool IsOnPlayer)>(() => CreateFiles(textures, editor, getPlayerResources), + MouseWheelType.None, Penumbra.Log) { private int _skipPrefix = 0; - public PathSelectCombo(TextureManager textures, ModEditor editor, Func> getPlayerResources) - : base(() => CreateFiles(textures, editor, getPlayerResources), Penumbra.Log) - { } - protected override string ToString((string Path, bool Game, bool IsOnPlayer) obj) => obj.Path; @@ -140,7 +139,8 @@ public static class TextureDrawer return ret; } - private static IReadOnlyList<(string Path, bool Game, bool IsOnPlayer)> CreateFiles(TextureManager textures, ModEditor editor, Func> getPlayerResources) + private static IReadOnlyList<(string Path, bool Game, bool IsOnPlayer)> CreateFiles(TextureManager textures, ModEditor editor, + Func> getPlayerResources) { var playerResources = getPlayerResources(); diff --git a/Penumbra/Mods/Manager/ModStorage.cs b/Penumbra/Mods/Manager/ModStorage.cs index 490381d6..1e5df6b9 100644 --- a/Penumbra/Mods/Manager/ModStorage.cs +++ b/Penumbra/Mods/Manager/ModStorage.cs @@ -12,7 +12,7 @@ public class ModCombo : FilterComboCache => obj.Name.Text; public ModCombo(Func> generator) - : base(generator, Penumbra.Log) + : base(generator, MouseWheelType.None, Penumbra.Log) { } } diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 00fc0737..26b39229 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -13,7 +13,7 @@ namespace Penumbra.Services; public class StainService : IService { public sealed class StainTemplateCombo(FilterComboColors stainCombo, StmFile stmFile) - : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), Penumbra.Log) + : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) { protected override float GetFilterWidth() { @@ -70,8 +70,8 @@ public class StainService : IService public StainService(IDataManager dataManager, DictStain stainData) { StainData = stainData; - StainCombo = new FilterComboColors(140, - () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), + StainCombo = new FilterComboColors(140, MouseWheelType.None, + () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), Penumbra.Log); StmFile = new StmFile(dataManager); TemplateCombo = new StainTemplateCombo(StainCombo, StmFile); diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 16cacaa4..89d47eb2 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -278,7 +278,7 @@ public class FileEditor : IDisposable where T : class, IWritable private readonly Configuration _config; public Combo(Configuration config, Func> generator) - : base(generator, Penumbra.Log) + : base(generator, MouseWheelType.None, Penumbra.Log) => _config = config; protected override bool DrawSelectable(int globalIdx, bool selected) diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index d31a08ae..0205f3c6 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -125,26 +125,13 @@ public class ItemSwapTab : IDisposable, ITab Weapon, } - private class ItemSelector : FilterComboCache + private class ItemSelector(ItemData data, FullEquipType type) + : FilterComboCache(() => data.ByType[type], MouseWheelType.None, Penumbra.Log) { - public ItemSelector(ItemData data, FullEquipType type) - : base(() => data.ByType[type], Penumbra.Log) - { } - protected override string ToString(EquipItem obj) => obj.Name; } - private class WeaponSelector : FilterComboCache - { - public WeaponSelector() - : base(FullEquipTypeExtensions.WeaponTypes.Concat(FullEquipTypeExtensions.ToolTypes), Penumbra.Log) - { } - - protected override string ToString(FullEquipType type) - => type.ToName(); - } - private readonly Dictionary _selectors; private readonly ItemSwapContainer _swapData; diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index b2ee5c3b..9d195eed 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -7,14 +7,10 @@ using Penumbra.GameData.Actors; namespace Penumbra.UI.CollectionTab; -public sealed class CollectionCombo : FilterComboCache +public sealed class CollectionCombo(CollectionManager manager, Func> items) + : FilterComboCache(items, MouseWheelType.None, Penumbra.Log) { - private readonly CollectionManager _collectionManager; - private readonly ImRaii.Color _color = new(); - - public CollectionCombo(CollectionManager manager, Func> items) - : base(items, Penumbra.Log) - => _collectionManager = manager; + private readonly ImRaii.Color _color = new(); protected override void DrawFilter(int currentSelected, float width) { @@ -24,11 +20,11 @@ public sealed class CollectionCombo : FilterComboCache public void Draw(string label, float width, uint color) { - var current = _collectionManager.Active.ByType(CollectionType.Current, ActorIdentifier.Invalid); + var current = manager.Active.ByType(CollectionType.Current, ActorIdentifier.Invalid); _color.Push(ImGuiCol.FrameBg, color).Push(ImGuiCol.FrameBgHovered, color); if (Draw(label, current?.Name ?? string.Empty, string.Empty, width, ImGui.GetTextLineHeightWithSpacing()) && CurrentSelection != null) - _collectionManager.Active.SetCollection(CurrentSelection, CollectionType.Current); + manager.Active.SetCollection(CurrentSelection, CollectionType.Current); _color.Dispose(); } From a0ac0dfcfa16befa83d5c9f94e9191e0c0bf7e40 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 13 Feb 2024 00:22:44 +0100 Subject: [PATCH 0449/1381] Bit more update. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 0d267233..3a7f6d86 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 0d267233724d493d9ae2bf8d1e67bfbb8b337916 +Subproject commit 3a7f6d86c9975a4892f58be3c629b7664e6c3733 From 06cf6ce752b1c864cad72b5e509984cc1065d44f Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 13 Feb 2024 12:42:23 +0000 Subject: [PATCH 0450/1381] [CI] Updating repo.json for 1.0.0.5 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index fc95fef3..547ccca1 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.4", - "TestingAssemblyVersion": "1.0.0.4", + "AssemblyVersion": "1.0.0.5", + "TestingAssemblyVersion": "1.0.0.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.4/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.4/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.4/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.5/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.5/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 2e0e125913d2b9e92587cdefc55e0650fcbd8469 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 17 Feb 2024 13:35:42 +0100 Subject: [PATCH 0451/1381] Fix issue with renaming mods with open advanced window. --- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 6d406461..38fdf482 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -629,7 +629,10 @@ public partial class ModEditWindow : Window, IDisposable private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) { - if (type is ModPathChangeType.Reloaded or ModPathChangeType.Moved) - ChangeMod(mod); + if (type is not (ModPathChangeType.Reloaded or ModPathChangeType.Moved) || mod != _mod) + return; + + _mod = null; + ChangeMod(mod); } } From 80ce6fe21f92793340267b01d8c4d9f3d2a3cafd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 Feb 2024 12:59:06 +0100 Subject: [PATCH 0452/1381] Use new font functionality. --- Penumbra/UI/CollectionTab/CollectionPanel.cs | 11 ++++++----- Penumbra/UI/ModsTab/ModPanelHeader.cs | 9 +++++---- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 8f90750f..6f6e4dbd 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -2,6 +2,7 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.GameFonts; +using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Utility; using Dalamud.Plugin; using ImGuiNET; @@ -28,7 +29,7 @@ public sealed class CollectionPanel : IDisposable private readonly InheritanceUi _inheritanceUi; private readonly ModStorage _mods; - private readonly GameFontHandle _nameFont; + private readonly IFontHandle _nameFont; private static readonly IReadOnlyDictionary Buttons = CreateButtons(); private static readonly IReadOnlyList<(CollectionType, bool, bool, string, uint)> AdvancedTree = CreateTree(); @@ -47,7 +48,7 @@ public sealed class CollectionPanel : IDisposable _mods = mods; _individualAssignmentUi = new IndividualAssignmentUi(communicator, actors, manager); _inheritanceUi = new InheritanceUi(manager, _selector); - _nameFont = pi.UiBuilder.GetGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); + _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); } public void Dispose() @@ -426,7 +427,7 @@ public sealed class CollectionPanel : IDisposable ImGui.Dummy(Vector2.One); using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 2 * UiHelpers.Scale); - using var font = ImRaii.PushFont(_nameFont.ImFont, _nameFont.Available); + using var f = _nameFont.Available ? _nameFont.Push() : null; var name = Name(collection); var size = ImGui.CalcTextSize(name).X; var pos = ImGui.GetContentRegionAvail().X - size + ImGui.GetStyle().FramePadding.X * 2; @@ -445,7 +446,7 @@ public sealed class CollectionPanel : IDisposable if (_inUseCache.Count == 0 && collection.DirectParentOf.Count == 0) { ImGui.Dummy(Vector2.One); - using var font = ImRaii.PushFont(_nameFont.ImFont, _nameFont.Available); + using var f = _nameFont.Available ? _nameFont.Push() : null; ImGuiUtil.DrawTextButton("Collection is not used.", new Vector2(ImGui.GetContentRegionAvail().X, buttonHeight), Colors.PressEnterWarningBg); ImGui.Dummy(Vector2.One); @@ -512,7 +513,7 @@ public sealed class CollectionPanel : IDisposable ImGuiUtil.DrawTextButton("Inherited by", ImGui.GetContentRegionAvail() with { Y = 0 }, 0); } - using var font = ImRaii.PushFont(_nameFont.ImFont, _nameFont.Available); + using var f = _nameFont.Available ? _nameFont.Push() : null; using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); ImGuiUtil.DrawTextButton(Name(collection.DirectParentOf[0]), Vector2.Zero, 0); diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index 4b127059..a28c3668 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -1,4 +1,5 @@ using Dalamud.Interface.GameFonts; +using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Plugin; using ImGuiNET; using OtterGui; @@ -14,14 +15,14 @@ namespace Penumbra.UI.ModsTab; public class ModPanelHeader : IDisposable { /// We use a big, nice game font for the title. - private readonly GameFontHandle _nameFont; + private readonly IFontHandle _nameFont; private readonly CommunicatorService _communicator; public ModPanelHeader(DalamudPluginInterface pi, CommunicatorService communicator) { _communicator = communicator; - _nameFont = pi.UiBuilder.GetGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); + _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); _communicator.ModDataChanged.Subscribe(OnModDataChange, ModDataChanged.Priority.ModPanelHeader); } @@ -46,7 +47,7 @@ public class ModPanelHeader : IDisposable var name = $" {mod.Name} "; if (name != _modName) { - using var font = ImRaii.PushFont(_nameFont.ImFont, _nameFont.Available); + using var f = _nameFont.Available ? _nameFont.Push() : null; _modName = name; _modNameWidth = ImGui.CalcTextSize(name).X + 2 * (ImGui.GetStyle().FramePadding.X + 2 * UiHelpers.Scale); } @@ -121,7 +122,7 @@ public class ModPanelHeader : IDisposable using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 2 * UiHelpers.Scale); - using var font = ImRaii.PushFont(_nameFont.ImFont, _nameFont.Available); + using var f = _nameFont.Available ? _nameFont.Push() : null; ImGuiUtil.DrawTextButton(_modName, Vector2.Zero, 0); return offset; } From 31bc5ec6f9d4b21dfa1b09f8764f87860cffc14b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 Feb 2024 13:03:56 +0100 Subject: [PATCH 0453/1381] Make settings change invoke on Temporary Mods. --- Penumbra.Api | 2 +- Penumbra/Api/TempModManager.cs | 3 +++ Penumbra/Collections/Cache/CollectionCacheManager.cs | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index a28219ac..2b6bcf33 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit a28219ac57b53c3be6ca8c252ceb9f76ae0b6c21 +Subproject commit 2b6bcf338794b34bcba2730c70dcbb73ce97311b diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index efbfd7f9..c7840b75 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -1,3 +1,4 @@ +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Meta.Manipulations; using Penumbra.Mods; @@ -84,11 +85,13 @@ public class TempModManager : IDisposable { Penumbra.Log.Verbose($"Removing temporary Mod {mod.Name} from {collection.AnonymizedName}."); collection.Remove(mod); + _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, 0, 0, false); } else { Penumbra.Log.Verbose($"Adding {(created ? "new " : string.Empty)}temporary Mod {mod.Name} to {collection.AnonymizedName}."); collection.Apply(mod, created); + _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, 1, 0, false); } } else diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 7d4a5722..4e524ddf 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -322,6 +322,9 @@ public class CollectionCacheManager : IDisposable case ModSettingChange.MultiEnableState: FullRecalculation(collection); break; + case ModSettingChange.TemporaryMod: + // handled otherwise + break; } } From a2bf477481f78c62333947498fc21c092fc505f8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 Feb 2024 14:46:22 +0100 Subject: [PATCH 0454/1381] Cleanup. --- Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index 776f2f92..31387101 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -42,7 +42,7 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr Date: Sun, 18 Feb 2024 13:48:18 +0000 Subject: [PATCH 0455/1381] [CI] Updating repo.json for 1.0.0.6 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 547ccca1..29b1647d 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.5", - "TestingAssemblyVersion": "1.0.0.5", + "AssemblyVersion": "1.0.0.6", + "TestingAssemblyVersion": "1.0.0.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.5/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.5/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.5/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.6/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 529788d2e57b95adf434dac84b119b17c02921d7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 20 Feb 2024 16:26:33 +0100 Subject: [PATCH 0456/1381] Change font pushes. --- Penumbra/UI/CollectionTab/CollectionPanel.cs | 6 +++--- Penumbra/UI/ModsTab/ModPanelHeader.cs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 6f6e4dbd..4d922af5 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -427,7 +427,7 @@ public sealed class CollectionPanel : IDisposable ImGui.Dummy(Vector2.One); using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 2 * UiHelpers.Scale); - using var f = _nameFont.Available ? _nameFont.Push() : null; + using var f = _nameFont.Push(); var name = Name(collection); var size = ImGui.CalcTextSize(name).X; var pos = ImGui.GetContentRegionAvail().X - size + ImGui.GetStyle().FramePadding.X * 2; @@ -446,7 +446,7 @@ public sealed class CollectionPanel : IDisposable if (_inUseCache.Count == 0 && collection.DirectParentOf.Count == 0) { ImGui.Dummy(Vector2.One); - using var f = _nameFont.Available ? _nameFont.Push() : null; + using var f = _nameFont.Push(); ImGuiUtil.DrawTextButton("Collection is not used.", new Vector2(ImGui.GetContentRegionAvail().X, buttonHeight), Colors.PressEnterWarningBg); ImGui.Dummy(Vector2.One); @@ -513,7 +513,7 @@ public sealed class CollectionPanel : IDisposable ImGuiUtil.DrawTextButton("Inherited by", ImGui.GetContentRegionAvail() with { Y = 0 }, 0); } - using var f = _nameFont.Available ? _nameFont.Push() : null; + using var f = _nameFont.Push(); using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); ImGuiUtil.DrawTextButton(Name(collection.DirectParentOf[0]), Vector2.Zero, 0); diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index a28c3668..ed499b4f 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -47,7 +47,7 @@ public class ModPanelHeader : IDisposable var name = $" {mod.Name} "; if (name != _modName) { - using var f = _nameFont.Available ? _nameFont.Push() : null; + using var f = _nameFont.Push(); _modName = name; _modNameWidth = ImGui.CalcTextSize(name).X + 2 * (ImGui.GetStyle().FramePadding.X + 2 * UiHelpers.Scale); } @@ -122,7 +122,7 @@ public class ModPanelHeader : IDisposable using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 2 * UiHelpers.Scale); - using var f = _nameFont.Available ? _nameFont.Push() : null; + using var f = _nameFont.Push(); ImGuiUtil.DrawTextButton(_modName, Vector2.Zero, 0); return offset; } From add4b8aa83b55f1e274bd994396faaeda3809226 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 23 Feb 2024 21:44:49 +0100 Subject: [PATCH 0457/1381] Misc. --- Penumbra/Collections/ModCollectionSave.cs | 31 ++++++------------- .../ResourceLoading/CreateFileWHook.cs | 2 +- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index 4cc7706e..f2cb4ada 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -1,32 +1,21 @@ using Newtonsoft.Json.Linq; -using Penumbra.Mods; using Penumbra.Services; using Newtonsoft.Json; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; -using Penumbra.Util; namespace Penumbra.Collections; /// /// Handle saving and loading a collection. /// -internal readonly struct ModCollectionSave : ISavable +internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection modCollection) : ISavable { - private readonly ModStorage _modStorage; - private readonly ModCollection _modCollection; - - public ModCollectionSave(ModStorage modStorage, ModCollection modCollection) - { - _modStorage = modStorage; - _modCollection = modCollection; - } - public string ToFilename(FilenameService fileNames) - => fileNames.CollectionFile(_modCollection); + => fileNames.CollectionFile(modCollection); public string LogName(string _) - => _modCollection.AnonymizedName; + => modCollection.AnonymizedName; public string TypeName => "Collection"; @@ -40,20 +29,20 @@ internal readonly struct ModCollectionSave : ISavable j.WritePropertyName("Version"); j.WriteValue(ModCollection.CurrentVersion); j.WritePropertyName(nameof(ModCollection.Name)); - j.WriteValue(_modCollection.Name); + j.WriteValue(modCollection.Name); j.WritePropertyName(nameof(ModCollection.Settings)); // Write all used and unused settings by mod directory name. j.WriteStartObject(); - var list = new List<(string, ModSettings.SavedSettings)>(_modCollection.Settings.Count + _modCollection.UnusedSettings.Count); - for (var i = 0; i < _modCollection.Settings.Count; ++i) + var list = new List<(string, ModSettings.SavedSettings)>(modCollection.Settings.Count + modCollection.UnusedSettings.Count); + for (var i = 0; i < modCollection.Settings.Count; ++i) { - var settings = _modCollection.Settings[i]; + var settings = modCollection.Settings[i]; if (settings != null) - list.Add((_modStorage[i].ModPath.Name, new ModSettings.SavedSettings(settings, _modStorage[i]))); + list.Add((modStorage[i].ModPath.Name, new ModSettings.SavedSettings(settings, modStorage[i]))); } - list.AddRange(_modCollection.UnusedSettings.Select(kvp => (kvp.Key, kvp.Value))); + list.AddRange(modCollection.UnusedSettings.Select(kvp => (kvp.Key, kvp.Value))); list.Sort((a, b) => string.Compare(a.Item1, b.Item1, StringComparison.OrdinalIgnoreCase)); foreach (var (modDir, settings) in list) @@ -66,7 +55,7 @@ internal readonly struct ModCollectionSave : ISavable // Inherit by collection name. j.WritePropertyName("Inheritance"); - x.Serialize(j, _modCollection.InheritanceByName ?? _modCollection.DirectlyInheritsFrom.Select(c => c.Name)); + x.Serialize(j, modCollection.InheritanceByName ?? modCollection.DirectlyInheritsFrom.Select(c => c.Name)); j.WriteEndObject(); } diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs index 7d94b1d5..8a5e779b 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs @@ -100,7 +100,7 @@ public unsafe class CreateFileWHook : IDisposable { // Use static storage. var ptr = WriteFileName(name); - Penumbra.Log.Verbose($"[ResourceHooks] Calling CreateFileWDetour with {ByteString.FromSpanUnsafe(name, false)}."); + Penumbra.Log.Excessive($"[ResourceHooks] Calling CreateFileWDetour with {ByteString.FromSpanUnsafe(name, false)}."); return _createFileWHook.OriginalDisposeSafe(ptr, access, shareMode, security, creation, flags, template); } From 1000841f69b8c439e498d2b36986514aadc9d3a7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Feb 2024 12:06:57 +0100 Subject: [PATCH 0458/1381] Add some settingchanged events. --- Penumbra.Api | 2 +- Penumbra/Api/PenumbraApi.cs | 46 +++++--- .../Cache/CollectionCacheManager.cs | 1 + .../Collections/Manager/CollectionManager.cs | 31 +++--- Penumbra/Communication/ModOptionChanged.cs | 4 + Penumbra/Communication/ModPathChanged.cs | 6 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 +- Penumbra/Mods/Manager/ModDataEditor.cs | 61 +++++------ Penumbra/Mods/Manager/ModOptionEditor.cs | 101 ++++++++---------- 9 files changed, 128 insertions(+), 126 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 2b6bcf33..79ffdd69 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 2b6bcf338794b34bcba2730c70dcbb73ce97311b +Subproject commit 79ffdd69a28141a1ac93daa24d76573b2fa0d71e diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 1a0764c7..59ef6677 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -141,6 +141,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _communicator.ModPathChanged.Subscribe(ModPathChangeSubscriber, ModPathChanged.Priority.Api); _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); + _communicator.ModOptionChanged.Subscribe(OnModOptionEdited, ModOptionChanged.Priority.Api); } public unsafe void Dispose() @@ -342,10 +343,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); if (!_config.EnableMods) - return new[] - { - path, - }; + return [path]; var ret = _collectionManager.Active.Individual(NameToIdentifier(characterName, worldId)).ReverseResolvePath(new FullPath(path)); return ret.Select(r => r.ToString()).ToArray(); @@ -355,10 +353,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); if (!_config.EnableMods) - return new[] - { - path, - }; + return [path]; AssociatedCollection(gameObjectIdx, out var collection); var ret = collection.ReverseResolvePath(new FullPath(path)); @@ -369,10 +364,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); if (!_config.EnableMods) - return new[] - { - path, - }; + return [path]; var ret = _collectionResolver.PlayerCollection().ReverseResolvePath(new FullPath(path)); return ret.Select(r => r.ToString()).ToArray(); @@ -698,6 +690,9 @@ public class PenumbraApi : IDisposable, IPenumbraApi { switch (type) { + case ModPathChangeType.Reloaded: + TriggerSettingEdited(mod); + break; case ModPathChangeType.Deleted when oldDirectory != null: ModDeleted?.Invoke(oldDirectory.Name); break; @@ -1262,4 +1257,31 @@ public class PenumbraApi : IDisposable, IPenumbraApi private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) => CreatedCharacterBase?.Invoke(gameObject, collection.Name, drawObject); + + private void OnModOptionEdited(ModOptionChangeType type, Mod mod, int groupIndex, int optionIndex, int moveIndex) + { + switch (type) + { + case ModOptionChangeType.GroupDeleted: + case ModOptionChangeType.GroupMoved: + case ModOptionChangeType.GroupTypeChanged: + case ModOptionChangeType.PriorityChanged: + case ModOptionChangeType.OptionDeleted: + case ModOptionChangeType.OptionMoved: + case ModOptionChangeType.OptionFilesChanged: + case ModOptionChangeType.OptionFilesAdded: + case ModOptionChangeType.OptionSwapsChanged: + case ModOptionChangeType.OptionMetaChanged: + TriggerSettingEdited(mod); + break; + } + } + + private void TriggerSettingEdited(Mod mod) + { + var collection = _collectionResolver.PlayerCollection(); + var (settings, parent) = collection[mod.Index]; + if (settings != null) + ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Name, mod.Identifier, parent != collection); + } } diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 4e524ddf..94b3ef5a 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -323,6 +323,7 @@ public class CollectionCacheManager : IDisposable FullRecalculation(collection); break; case ModSettingChange.TemporaryMod: + case ModSettingChange.Edited: // handled otherwise break; } diff --git a/Penumbra/Collections/Manager/CollectionManager.cs b/Penumbra/Collections/Manager/CollectionManager.cs index 16bf754c..e95617b1 100644 --- a/Penumbra/Collections/Manager/CollectionManager.cs +++ b/Penumbra/Collections/Manager/CollectionManager.cs @@ -2,23 +2,18 @@ using Penumbra.Collections.Cache; namespace Penumbra.Collections.Manager; -public class CollectionManager +public class CollectionManager( + CollectionStorage storage, + ActiveCollections active, + InheritanceManager inheritances, + CollectionCacheManager caches, + TempCollectionManager temp, + CollectionEditor editor) { - public readonly CollectionStorage Storage; - public readonly ActiveCollections Active; - public readonly InheritanceManager Inheritances; - public readonly CollectionCacheManager Caches; - public readonly TempCollectionManager Temp; - public readonly CollectionEditor Editor; - - public CollectionManager(CollectionStorage storage, ActiveCollections active, InheritanceManager inheritances, - CollectionCacheManager caches, TempCollectionManager temp, CollectionEditor editor) - { - Storage = storage; - Active = active; - Inheritances = inheritances; - Caches = caches; - Temp = temp; - Editor = editor; - } + public readonly CollectionStorage Storage = storage; + public readonly ActiveCollections Active = active; + public readonly InheritanceManager Inheritances = inheritances; + public readonly CollectionCacheManager Caches = caches; + public readonly TempCollectionManager Temp = temp; + public readonly CollectionEditor Editor = editor; } diff --git a/Penumbra/Communication/ModOptionChanged.cs b/Penumbra/Communication/ModOptionChanged.cs index a0b4d26c..f02b17dc 100644 --- a/Penumbra/Communication/ModOptionChanged.cs +++ b/Penumbra/Communication/ModOptionChanged.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -18,6 +19,9 @@ public sealed class ModOptionChanged() { public enum Priority { + /// + Api = int.MinValue, + /// CollectionCacheManager = -100, diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index e6291781..01c8fa64 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -19,15 +19,15 @@ public sealed class ModPathChanged() { public enum Priority { + /// + Api = int.MinValue, + /// EphemeralConfig = -500, /// CollectionCacheManagerAddition = -100, - /// - Api = 0, - /// ModCacheManager = 0, diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index bbf0d4b5..31aefdf5 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -2,7 +2,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; -namespace Penumbra.Mods; +namespace Penumbra.Mods.Editor; public class ModMetaEditor(ModManager modManager) { diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 6c5f9c25..e0af6f36 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -23,17 +23,8 @@ public enum ModDataChangeType : ushort Note = 0x0800, } -public class ModDataEditor +public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService) { - private readonly SaveService _saveService; - private readonly CommunicatorService _communicatorService; - - public ModDataEditor(SaveService saveService, CommunicatorService communicatorService) - { - _saveService = saveService; - _communicatorService = communicatorService; - } - /// Create the file containing the meta information about a mod from scratch. public void CreateMeta(DirectoryInfo directory, string? name, string? author, string? description, string? version, string? website) @@ -44,12 +35,12 @@ public class ModDataEditor mod.Description = description ?? mod.Description; mod.Version = version ?? mod.Version; mod.Website = website ?? mod.Website; - _saveService.ImmediateSave(new ModMeta(mod)); + saveService.ImmediateSave(new ModMeta(mod)); } public ModDataChangeType LoadLocalData(Mod mod) { - var dataFile = _saveService.FileNames.LocalDataFile(mod); + var dataFile = saveService.FileNames.LocalDataFile(mod); var importDate = 0L; var localTags = Enumerable.Empty(); @@ -101,14 +92,14 @@ public class ModDataEditor } if (save) - _saveService.QueueSave(new ModLocalData(mod)); + saveService.QueueSave(new ModLocalData(mod)); return changes; } public ModDataChangeType LoadMeta(ModCreator creator, Mod mod) { - var metaFile = _saveService.FileNames.ModMetaPath(mod); + var metaFile = saveService.FileNames.ModMetaPath(mod); if (!File.Exists(metaFile)) { Penumbra.Log.Debug($"No mod meta found for {mod.ModPath.Name}."); @@ -161,10 +152,10 @@ public class ModDataEditor } if (newFileVersion != ModMeta.FileVersion) - if (ModMigration.Migrate(creator, _saveService, mod, json, ref newFileVersion)) + if (ModMigration.Migrate(creator, saveService, mod, json, ref newFileVersion)) { changes |= ModDataChangeType.Migration; - _saveService.ImmediateSave(new ModMeta(mod)); + saveService.ImmediateSave(new ModMeta(mod)); } if (importDate != null && mod.ImportDate != importDate.Value) @@ -191,8 +182,8 @@ public class ModDataEditor var oldName = mod.Name; mod.Name = newName; - _saveService.QueueSave(new ModMeta(mod)); - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Name, mod, oldName.Text); + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Name, mod, oldName.Text); } public void ChangeModAuthor(Mod mod, string newAuthor) @@ -201,8 +192,8 @@ public class ModDataEditor return; mod.Author = newAuthor; - _saveService.QueueSave(new ModMeta(mod)); - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Author, mod, null); + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Author, mod, null); } public void ChangeModDescription(Mod mod, string newDescription) @@ -211,8 +202,8 @@ public class ModDataEditor return; mod.Description = newDescription; - _saveService.QueueSave(new ModMeta(mod)); - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Description, mod, null); + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Description, mod, null); } public void ChangeModVersion(Mod mod, string newVersion) @@ -221,8 +212,8 @@ public class ModDataEditor return; mod.Version = newVersion; - _saveService.QueueSave(new ModMeta(mod)); - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Version, mod, null); + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Version, mod, null); } public void ChangeModWebsite(Mod mod, string newWebsite) @@ -231,8 +222,8 @@ public class ModDataEditor return; mod.Website = newWebsite; - _saveService.QueueSave(new ModMeta(mod)); - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Website, mod, null); + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Website, mod, null); } public void ChangeModTag(Mod mod, int tagIdx, string newTag) @@ -247,9 +238,9 @@ public class ModDataEditor return; mod.Favorite = state; - _saveService.QueueSave(new ModLocalData(mod)); + saveService.QueueSave(new ModLocalData(mod)); ; - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); } public void ChangeModNote(Mod mod, string newNote) @@ -258,9 +249,9 @@ public class ModDataEditor return; mod.Note = newNote; - _saveService.QueueSave(new ModLocalData(mod)); + saveService.QueueSave(new ModLocalData(mod)); ; - _communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); } private void ChangeTag(Mod mod, int tagIdx, string newTag, bool local) @@ -282,19 +273,19 @@ public class ModDataEditor } if (flags.HasFlag(ModDataChangeType.ModTags)) - _saveService.QueueSave(new ModMeta(mod)); + saveService.QueueSave(new ModMeta(mod)); if (flags.HasFlag(ModDataChangeType.LocalTags)) - _saveService.QueueSave(new ModLocalData(mod)); + saveService.QueueSave(new ModLocalData(mod)); if (flags != 0) - _communicatorService.ModDataChanged.Invoke(flags, mod, null); + communicatorService.ModDataChanged.Invoke(flags, mod, null); } public void MoveDataFile(DirectoryInfo oldMod, DirectoryInfo newMod) { - var oldFile = _saveService.FileNames.LocalDataFile(oldMod.Name); - var newFile = _saveService.FileNames.LocalDataFile(newMod.Name); + var oldFile = saveService.FileNames.LocalDataFile(oldMod.Name); + var newFile = saveService.FileNames.LocalDataFile(newMod.Name); if (!File.Exists(oldFile)) return; diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 73cb80cc..3459ce1a 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -31,19 +31,8 @@ public enum ModOptionChangeType DefaultOptionChanged, } -public class ModOptionEditor +public class ModOptionEditor(CommunicatorService communicator, SaveService saveService, Configuration config) { - private readonly Configuration _config; - private readonly CommunicatorService _communicator; - private readonly SaveService _saveService; - - public ModOptionEditor(CommunicatorService communicator, SaveService saveService, Configuration config) - { - _communicator = communicator; - _saveService = saveService; - _config = config; - } - /// Change the type of a group given by mod and index to type, if possible. public void ChangeModGroupType(Mod mod, int groupIdx, GroupType type) { @@ -52,8 +41,8 @@ public class ModOptionEditor return; mod.Groups[groupIdx] = group.Convert(type); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, mod, groupIdx, -1, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, mod, groupIdx, -1, -1); } /// Change the settings stored as default options in a mod. @@ -64,8 +53,8 @@ public class ModOptionEditor return; group.DefaultSettings = defaultOption; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, mod, groupIdx, -1, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, mod, groupIdx, -1, -1); } /// Rename an option group if possible. @@ -76,7 +65,7 @@ public class ModOptionEditor if (oldName == newName || !VerifyFileName(mod, group, newName, true)) return; - _saveService.ImmediateDelete(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); + saveService.ImmediateDelete(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); var _ = group switch { SingleModGroup s => s.Name = newName, @@ -84,8 +73,8 @@ public class ModOptionEditor _ => newName, }; - _saveService.ImmediateSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, mod, groupIdx, -1, -1); + saveService.ImmediateSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, mod, groupIdx, -1, -1); } /// Add a new, empty option group of the given type and name. @@ -107,8 +96,8 @@ public class ModOptionEditor Name = newName, Priority = maxPriority, }); - _saveService.ImmediateSave(new ModSaveGroup(mod, mod.Groups.Count - 1, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, mod.Groups.Count - 1, -1, -1); + saveService.ImmediateSave(new ModSaveGroup(mod, mod.Groups.Count - 1, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, mod.Groups.Count - 1, -1, -1); } /// Add a new mod, empty option group of the given type and name if it does not exist already. @@ -128,11 +117,11 @@ public class ModOptionEditor /// Delete a given option group. Fires an event to prepare before actually deleting. public void DeleteModGroup(Mod mod, int groupIdx) { - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, -1, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, -1, -1); mod.Groups.RemoveAt(groupIdx); UpdateSubModPositions(mod, groupIdx); - _saveService.SaveAllOptionGroups(mod, false, _config.ReplaceNonAsciiOnImport); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, groupIdx, -1, -1); + saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, groupIdx, -1, -1); } /// Move the index of a given option group. @@ -142,8 +131,8 @@ public class ModOptionEditor return; UpdateSubModPositions(mod, Math.Min(groupIdxFrom, groupIdxTo)); - _saveService.SaveAllOptionGroups(mod, false, _config.ReplaceNonAsciiOnImport); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, groupIdxFrom, -1, groupIdxTo); + saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, groupIdxFrom, -1, groupIdxTo); } /// Change the description of the given option group. @@ -159,8 +148,8 @@ public class ModOptionEditor MultiModGroup m => m.Description = newDescription, _ => newDescription, }; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, -1, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, -1, -1); } /// Change the description of the given option. @@ -172,8 +161,8 @@ public class ModOptionEditor return; s.Description = newDescription; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } /// Change the internal priority of the given option group. @@ -189,8 +178,8 @@ public class ModOptionEditor MultiModGroup m => m.Priority = newPriority, _ => newPriority, }; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, -1, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, -1, -1); } /// Change the internal priority of the given option. @@ -206,8 +195,8 @@ public class ModOptionEditor return; m.PrioritizedOptions[optionIdx] = (m.PrioritizedOptions[optionIdx].Mod, newPriority); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, optionIdx, -1); return; } } @@ -232,8 +221,8 @@ public class ModOptionEditor break; } - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } /// Add a new empty option of the given name for the given group. @@ -252,8 +241,8 @@ public class ModOptionEditor break; } - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); } /// Add a new empty option of the given name for the given group if it does not exist already. @@ -298,15 +287,15 @@ public class ModOptionEditor break; } - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); } /// Delete the given option from the given group. public void DeleteOption(Mod mod, int groupIdx, int optionIdx) { var group = mod.Groups[groupIdx]; - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); switch (group) { case SingleModGroup s: @@ -319,8 +308,8 @@ public class ModOptionEditor } group.UpdatePositions(optionIdx); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionDeleted, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionDeleted, mod, groupIdx, optionIdx, -1); } /// Move an option inside the given option group. @@ -330,8 +319,8 @@ public class ModOptionEditor if (!group.MoveOption(optionIdxFrom, optionIdxTo)) return; - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, mod, groupIdx, optionIdxFrom, optionIdxTo); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, mod, groupIdx, optionIdxFrom, optionIdxTo); } /// Set the meta manipulations for a given option. Replaces existing manipulations. @@ -342,10 +331,10 @@ public class ModOptionEditor && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) return; - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.ManipulationData.SetTo(manipulations); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, optionIdx, -1); } /// Set the file redirections for a given option. Replaces existing redirections. @@ -355,10 +344,10 @@ public class ModOptionEditor if (subMod.FileData.SetEquals(replacements)) return; - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.FileData.SetTo(replacements); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, optionIdx, -1); } /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. @@ -369,8 +358,8 @@ public class ModOptionEditor subMod.FileData.AddFrom(additions); if (oldCount != subMod.FileData.Count) { - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, mod, groupIdx, optionIdx, -1); } } @@ -381,10 +370,10 @@ public class ModOptionEditor if (subMod.FileSwapData.SetEquals(swaps)) return; - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.FileSwapData.SetTo(swaps); - _saveService.QueueSave(new ModSaveGroup(mod, groupIdx, _config.ReplaceNonAsciiOnImport)); - _communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, optionIdx, -1); + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, optionIdx, -1); } From 883580d4654c66a92e0435a628878d3b4fe38a17 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 24 Feb 2024 11:09:19 +0000 Subject: [PATCH 0459/1381] [CI] Updating repo.json for 1.0.0.7 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 29b1647d..1a599362 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.6", - "TestingAssemblyVersion": "1.0.0.6", + "AssemblyVersion": "1.0.0.7", + "TestingAssemblyVersion": "1.0.0.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.6/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.6/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 7b0be25f6ee4d07eae56248887abbb16847b1160 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Feb 2024 14:04:39 +0100 Subject: [PATCH 0460/1381] Add even more setting changed events and add auto-player-redraw on saving files. --- Penumbra/Api/PenumbraApi.cs | 14 ++- .../Collections/Manager/CollectionStorage.cs | 32 +++++- Penumbra/Communication/ModFileChanged.cs | 28 ++++++ Penumbra/Configuration.cs | 1 - Penumbra/EphemeralConfig.cs | 1 + Penumbra/Interop/Services/RedrawService.cs | 31 ++++-- Penumbra/Mods/Editor/ModFileEditor.cs | 4 +- Penumbra/Services/CommunicatorService.cs | 3 + Penumbra/UI/AdvancedWindow/FileEditor.cs | 99 ++++++++++--------- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 2 +- .../ModEditWindow.Materials.Shpk.cs | 2 +- .../AdvancedWindow/ModEditWindow.Materials.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 4 +- .../ModEditWindow.QuickImport.cs | 2 +- .../AdvancedWindow/ModEditWindow.Textures.cs | 38 ++++++- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 55 ++++++----- 17 files changed, 221 insertions(+), 99 deletions(-) create mode 100644 Penumbra/Communication/ModFileChanged.cs diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 59ef6677..aed1a963 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -24,6 +24,7 @@ using Penumbra.Interop.Services; using Penumbra.UI; using TextureType = Penumbra.Api.Enums.TextureType; using Penumbra.Interop.ResourceTree; +using Penumbra.Mods.Editor; namespace Penumbra.Api; @@ -142,6 +143,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); _communicator.ModOptionChanged.Subscribe(OnModOptionEdited, ModOptionChanged.Priority.Api); + _communicator.ModFileChanged.Subscribe(OnModFileChanged, ModFileChanged.Priority.Api); } public unsafe void Dispose() @@ -153,6 +155,8 @@ public class PenumbraApi : IDisposable, IPenumbraApi _communicator.ModPathChanged.Unsubscribe(ModPathChangeSubscriber); _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); _communicator.CreatedCharacterBase.Unsubscribe(OnCreatedCharacterBase); + _communicator.ModOptionChanged.Unsubscribe(OnModOptionEdited); + _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); _lumina = null; _communicator = null!; _modManager = null!; @@ -1277,11 +1281,19 @@ public class PenumbraApi : IDisposable, IPenumbraApi } } + private void OnModFileChanged(Mod mod, FileRegistry file) + { + if (file.CurrentUsage == 0) + return; + + TriggerSettingEdited(mod); + } + private void TriggerSettingEdited(Mod mod) { var collection = _collectionResolver.PlayerCollection(); var (settings, parent) = collection[mod.Index]; - if (settings != null) + if (settings is { Enabled: true }) ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Name, mod.Identifier, parent != collection); } } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index c43c3817..a84c79e6 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -4,6 +4,7 @@ using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; @@ -56,6 +57,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable _communicator.ModDiscoveryFinished.Subscribe(OnModDiscoveryFinished, ModDiscoveryFinished.Priority.CollectionStorage); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.CollectionStorage); _communicator.ModOptionChanged.Subscribe(OnModOptionChange, ModOptionChanged.Priority.CollectionStorage); + _communicator.ModFileChanged.Subscribe(OnModFileChanged, ModFileChanged.Priority.CollectionStorage); ReadCollections(out DefaultNamed); } @@ -65,6 +67,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable _communicator.ModDiscoveryFinished.Unsubscribe(OnModDiscoveryFinished); _communicator.ModPathChanged.Unsubscribe(OnModPathChange); _communicator.ModOptionChanged.Unsubscribe(OnModOptionChange); + _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); } /// @@ -104,7 +107,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable if (!CanAddCollection(name, out var fixedName)) { Penumbra.Messager.NotificationMessage( - $"The new collection {name} would lead to the same path {fixedName} as one that already exists.", NotificationType.Warning, false); + $"The new collection {name} would lead to the same path {fixedName} as one that already exists.", NotificationType.Warning, + false); return false; } @@ -185,20 +189,23 @@ public class CollectionStorage : IReadOnlyList, IDisposable if (!IsValidName(name)) { // TODO: handle better. - Penumbra.Messager.NotificationMessage($"Collection of unsupported name found: {name} is not a valid collection name.", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Collection of unsupported name found: {name} is not a valid collection name.", + NotificationType.Warning); continue; } if (ByName(name, out _)) { - Penumbra.Messager.NotificationMessage($"Duplicate collection found: {name} already exists. Import skipped.", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Duplicate collection found: {name} already exists. Import skipped.", + NotificationType.Warning); continue; } var collection = ModCollection.CreateFromData(_saveService, _modStorage, name, version, Count, settings, inheritance); var correctName = _saveService.FileNames.CollectionFile(collection); if (file.FullName != correctName) - Penumbra.Messager.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Name}.", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Name}.", + NotificationType.Warning); _collections.Add(collection); } @@ -220,7 +227,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable return _collections[^1]; Penumbra.Messager.NotificationMessage( - $"Unknown problem creating a collection with the name {ModCollection.DefaultCollectionName}, which is required to exist.", NotificationType.Error); + $"Unknown problem creating a collection with the name {ModCollection.DefaultCollectionName}, which is required to exist.", + NotificationType.Error); return Count > 1 ? _collections[1] : _collections[0]; } @@ -273,4 +281,18 @@ public class CollectionStorage : IReadOnlyList, IDisposable _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); } } + + /// Update change counters when changing files. + private void OnModFileChanged(Mod mod, FileRegistry file) + { + if (file.CurrentUsage == 0) + return; + + foreach (var collection in this) + { + var (settings, _) = collection[mod.Index]; + if (settings is { Enabled: true }) + collection.IncrementCounter(); + } + } } diff --git a/Penumbra/Communication/ModFileChanged.cs b/Penumbra/Communication/ModFileChanged.cs new file mode 100644 index 00000000..8b4b6f5d --- /dev/null +++ b/Penumbra/Communication/ModFileChanged.cs @@ -0,0 +1,28 @@ +using OtterGui.Classes; +using Penumbra.Api; +using Penumbra.Mods; +using Penumbra.Mods.Editor; + +namespace Penumbra.Communication; + +/// +/// Triggered whenever an existing file in a mod is overwritten by Penumbra. +/// +/// Parameter is the changed mod. +/// Parameter file registry of the changed file. +/// +public sealed class ModFileChanged() + : EventWrapper(nameof(ModFileChanged)) +{ + public enum Priority + { + /// + Api = int.MinValue, + + /// + RedrawService = -50, + + /// + CollectionStorage = 0, + } +} diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index a5a615bd..188be65d 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -47,7 +47,6 @@ public class Configuration : IPluginConfiguration, ISavable public bool UseNoModsInInspect { get; set; } = false; public bool HideChangedItemFilters { get; set; } = false; public bool ReplaceNonAsciiOnImport { get; set; } = false; - public bool HidePrioritiesInSelector { get; set; } = false; public bool HideRedrawBar { get; set; } = false; public int OptionGroupCollapsibleMin { get; set; } = 5; diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 8cf23de6..98b1a5d6 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -39,6 +39,7 @@ public class EphemeralConfig : ISavable, IDisposable public bool FixMainWindow { get; set; } = false; public string LastModPath { get; set; } = string.Empty; public bool AdvancedEditingOpen { get; set; } = false; + public bool ForceRedrawOnFileChange { get; set; } = false; /// /// Load the current configuration. diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index e2e57b1c..c1bd8573 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -8,9 +8,13 @@ using FFXIVClientStructs.FFXIV.Client.Game.Housing; using FFXIVClientStructs.Interop; using Penumbra.Api; using Penumbra.Api.Enums; +using Penumbra.Communication; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; +using Penumbra.Mods; +using Penumbra.Mods.Editor; +using Penumbra.Services; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; namespace Penumbra.Interop.Services; @@ -106,11 +110,13 @@ public sealed unsafe partial class RedrawService : IDisposable { private const int FurnitureIdx = 1337; - private readonly IFramework _framework; - private readonly IObjectTable _objects; - private readonly ITargetManager _targets; - private readonly ICondition _conditions; - private readonly IClientState _clientState; + private readonly IFramework _framework; + private readonly IObjectTable _objects; + private readonly ITargetManager _targets; + private readonly ICondition _conditions; + private readonly IClientState _clientState; + private readonly Configuration _config; + private readonly CommunicatorService _communicator; private readonly List _queue = new(100); private readonly List _afterGPoseQueue = new(GPoseSlots); @@ -127,19 +133,24 @@ public sealed unsafe partial class RedrawService : IDisposable public event GameObjectRedrawnDelegate? GameObjectRedrawn; - public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions, IClientState clientState) + public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions, IClientState clientState, + Configuration config, CommunicatorService communicator) { _framework = framework; _objects = objects; _targets = targets; _conditions = conditions; _clientState = clientState; + _config = config; + _communicator = communicator; _framework.Update += OnUpdateEvent; + _communicator.ModFileChanged.Subscribe(OnModFileChanged, ModFileChanged.Priority.RedrawService); } public void Dispose() { _framework.Update -= OnUpdateEvent; + _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); } public static DrawState* ActorDrawState(GameObject actor) @@ -419,4 +430,12 @@ public sealed unsafe partial class RedrawService : IDisposable gameObject->DisableDraw(); } } + + private void OnModFileChanged(Mod _1, FileRegistry _2) + { + if (!_config.ForceRedrawOnFileChange) + return; + + RedrawObject(0, RedrawType.Redraw); + } } diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 5328b8fe..30e97093 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -1,10 +1,11 @@ using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; +using Penumbra.Services; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class ModFileEditor(ModFileCollection files, ModManager modManager) +public class ModFileEditor(ModFileCollection files, ModManager modManager, CommunicatorService communicator) { public bool Changes { get; private set; } @@ -136,6 +137,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager) try { File.Delete(file.File.FullName); + communicator.ModFileChanged.Invoke(mod, file); Penumbra.Log.Debug($"[DeleteFiles] Deleted {file.File.FullName} from {mod.Name}."); ++deletions; } diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index be94a31e..da852855 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -42,6 +42,9 @@ public class CommunicatorService : IDisposable, IService /// public readonly ModDirectoryChanged ModDirectoryChanged = new(); + /// + public readonly ModFileChanged ModFileChanged = new(); + /// public readonly ModPathChanged ModPathChanged = new(); diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 89d47eb2..c891d33a 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -8,39 +8,32 @@ using OtterGui.Compression; using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.GameData.Files; -using Penumbra.Mods; using Penumbra.Mods.Editor; +using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; -public class FileEditor : IDisposable where T : class, IWritable +public class FileEditor( + ModEditWindow owner, + CommunicatorService communicator, + IDataManager gameData, + Configuration config, + FileCompactor compactor, + FileDialogService fileDialog, + string tabName, + string fileType, + Func> getFiles, + Func drawEdit, + Func getInitialPath, + Func parseFile) + : IDisposable + where T : class, IWritable { - private readonly FileDialogService _fileDialog; - private readonly IDataManager _gameData; - private readonly ModEditWindow _owner; - private readonly FileCompactor _compactor; - - public FileEditor(ModEditWindow owner, IDataManager gameData, Configuration config, FileCompactor compactor, FileDialogService fileDialog, - string tabName, string fileType, Func> getFiles, Func drawEdit, Func getInitialPath, - Func parseFile) - { - _owner = owner; - _gameData = gameData; - _fileDialog = fileDialog; - _tabName = tabName; - _fileType = fileType; - _drawEdit = drawEdit; - _getInitialPath = getInitialPath; - _parseFile = parseFile; - _compactor = compactor; - _combo = new Combo(config, getFiles); - } - public void Draw() { - using var tab = ImRaii.TabItem(_tabName); + using var tab = ImRaii.TabItem(tabName); if (!tab) { _quickImport = null; @@ -53,12 +46,26 @@ public class FileEditor : IDisposable where T : class, IWritable ImGui.SameLine(); ResetButton(); ImGui.SameLine(); + RedrawOnSaveBox(); + ImGui.SameLine(); DefaultInput(); ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); DrawFilePanel(); } + private void RedrawOnSaveBox() + { + var redraw = config.Ephemeral.ForceRedrawOnFileChange; + if (ImGui.Checkbox("Redraw on Save", ref redraw)) + { + config.Ephemeral.ForceRedrawOnFileChange = redraw; + config.Ephemeral.Save(); + } + + ImGuiUtil.HoverTooltip("Force a redraw of your player character whenever you save a file here."); + } + public void Dispose() { (_currentFile as IDisposable)?.Dispose(); @@ -67,12 +74,6 @@ public class FileEditor : IDisposable where T : class, IWritable _defaultFile = null; } - private readonly string _tabName; - private readonly string _fileType; - private readonly Func _drawEdit; - private readonly Func _getInitialPath; - private readonly Func _parseFile; - private FileRegistry? _currentPath; private T? _currentFile; private Exception? _currentException; @@ -85,7 +86,7 @@ public class FileEditor : IDisposable where T : class, IWritable private T? _defaultFile; private Exception? _defaultException; - private readonly Combo _combo; + private readonly Combo _combo = new(config, getFiles); private ModEditWindow.QuickImportAction? _quickImport; @@ -99,16 +100,16 @@ public class FileEditor : IDisposable where T : class, IWritable { _isDefaultPathUtf8Valid = Utf8GamePath.FromString(_defaultPath, out _defaultPathUtf8, true); _quickImport = null; - _fileDialog.Reset(); + fileDialog.Reset(); try { - var file = _gameData.GetFile(_defaultPath); + var file = gameData.GetFile(_defaultPath); if (file != null) { _defaultException = null; (_defaultFile as IDisposable)?.Dispose(); _defaultFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. - _defaultFile = _parseFile(file.Data, _defaultPath, false); + _defaultFile = parseFile(file.Data, _defaultPath, false); } else { @@ -126,7 +127,7 @@ public class FileEditor : IDisposable where T : class, IWritable ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Export this file.", _defaultFile == null, true)) - _fileDialog.OpenSavePicker($"Export {_defaultPath} to...", _fileType, Path.GetFileNameWithoutExtension(_defaultPath), _fileType, + fileDialog.OpenSavePicker($"Export {_defaultPath} to...", fileType, Path.GetFileNameWithoutExtension(_defaultPath), fileType, (success, name) => { if (!success) @@ -134,16 +135,16 @@ public class FileEditor : IDisposable where T : class, IWritable try { - _compactor.WriteAllBytes(name, _defaultFile?.Write() ?? throw new Exception("File invalid.")); + compactor.WriteAllBytes(name, _defaultFile?.Write() ?? throw new Exception("File invalid.")); } catch (Exception e) { Penumbra.Messager.NotificationMessage(e, $"Could not export {_defaultPath}.", NotificationType.Error); } - }, _getInitialPath(), false); + }, getInitialPath(), false); _quickImport ??= - ModEditWindow.QuickImportAction.Prepare(_owner, _isDefaultPathUtf8Valid ? _defaultPathUtf8 : Utf8GamePath.Empty, _defaultFile); + ModEditWindow.QuickImportAction.Prepare(owner, _isDefaultPathUtf8Valid ? _defaultPathUtf8 : Utf8GamePath.Empty, _defaultFile); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileImport.ToIconString(), new Vector2(ImGui.GetFrameHeight()), $"Add a copy of this file to {_quickImport.OptionName}.", !_quickImport.CanExecute, true)) @@ -172,7 +173,7 @@ public class FileEditor : IDisposable where T : class, IWritable private void DrawFileSelectCombo() { - if (_combo.Draw("##fileSelect", _currentPath?.RelPath.ToString() ?? $"Select {_fileType} File...", string.Empty, + if (_combo.Draw("##fileSelect", _currentPath?.RelPath.ToString() ?? $"Select {fileType} File...", string.Empty, ImGui.GetContentRegionAvail().X, ImGui.GetTextLineHeight()) && _combo.CurrentSelection != null) UpdateCurrentFile(_combo.CurrentSelection); @@ -191,7 +192,7 @@ public class FileEditor : IDisposable where T : class, IWritable var bytes = File.ReadAllBytes(_currentPath.File.FullName); (_currentFile as IDisposable)?.Dispose(); _currentFile = null; // Avoid double disposal if an exception occurs during the parsing of the new file. - _currentFile = _parseFile(bytes, _currentPath.File.FullName, true); + _currentFile = parseFile(bytes, _currentPath.File.FullName, true); } catch (Exception e) { @@ -204,9 +205,11 @@ public class FileEditor : IDisposable where T : class, IWritable private void SaveButton() { if (ImGuiUtil.DrawDisabledButton("Save to File", Vector2.Zero, - $"Save the selected {_fileType} file with all changes applied. This is not revertible.", !_changed)) + $"Save the selected {fileType} file with all changes applied. This is not revertible.", !_changed)) { - _compactor.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); + compactor.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); + if (owner.Mod != null) + communicator.ModFileChanged.Invoke(owner.Mod, _currentPath); _changed = false; } } @@ -214,7 +217,7 @@ public class FileEditor : IDisposable where T : class, IWritable private void ResetButton() { if (ImGuiUtil.DrawDisabledButton("Reset Changes", Vector2.Zero, - $"Reset all changes made to the {_fileType} file.", !_changed)) + $"Reset all changes made to the {fileType} file.", !_changed)) { var tmp = _currentPath; _currentPath = null; @@ -232,7 +235,7 @@ public class FileEditor : IDisposable where T : class, IWritable { if (_currentFile == null) { - ImGui.TextUnformatted($"Could not parse selected {_fileType} file."); + ImGui.TextUnformatted($"Could not parse selected {fileType} file."); if (_currentException != null) { using var tab = ImRaii.PushIndent(); @@ -242,7 +245,7 @@ public class FileEditor : IDisposable where T : class, IWritable else { using var id = ImRaii.PushId(0); - _changed |= _drawEdit(_currentFile, false); + _changed |= drawEdit(_currentFile, false); } } @@ -258,7 +261,7 @@ public class FileEditor : IDisposable where T : class, IWritable if (_defaultFile == null) { - ImGui.TextUnformatted($"Could not parse provided {_fileType} game file:\n"); + ImGui.TextUnformatted($"Could not parse provided {fileType} game file:\n"); if (_defaultException != null) { using var tab = ImRaii.PushIndent(); @@ -268,7 +271,7 @@ public class FileEditor : IDisposable where T : class, IWritable else { using var id = ImRaii.PushId(1); - _drawEdit(_defaultFile, true); + drawEdit(_defaultFile, true); } } } @@ -283,7 +286,7 @@ public class FileEditor : IDisposable where T : class, IWritable protected override bool DrawSelectable(int globalIdx, bool selected) { - var file = Items[globalIdx]; + var file = Items[globalIdx]; bool ret; using (var c = ImRaii.PushColor(ImGuiCol.Text, ColorId.HandledConflictMod.Value(), file.IsOnPlayer)) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index bae23729..c8db7770 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -80,7 +80,7 @@ public partial class ModEditWindow return f.SubModUsage.Count == 0 ? Enumerable.Repeat((file, "Unused", string.Empty, 0x40000080u), 1) : f.SubModUsage.Select(s => (file, s.Item2.ToString(), s.Item1.FullName, - _editor.Option! == s.Item1 && _mod!.HasOptions ? 0x40008000u : 0u)); + _editor.Option! == s.Item1 && Mod!.HasOptions ? 0x40008000u : 0u)); }); void DrawLine((string, string, string, uint) data) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 9e9557d3..3ce10224 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -143,7 +143,7 @@ public partial class ModEditWindow { if (success) tab.LoadShpk(new FullPath(name[0])); - }, 1, _mod!.ModPath.FullName, false); + }, 1, Mod!.ModPath.FullName, false); var moddedPath = tab.FindAssociatedShpk(out var defaultPath, out var gamePath); ImGui.SameLine(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index df20d60f..fab41c7d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -209,7 +209,7 @@ public partial class ModEditWindow info.Restore(); ImGui.TableNextColumn(); - ImGui.TextUnformatted(info.Path.FullName[(_mod!.ModPath.FullName.Length + 1)..]); + ImGui.TextUnformatted(info.Path.FullName[(Mod!.ModPath.FullName.Length + 1)..]); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(400 * UiHelpers.Scale); var tmp = info.CurrentMaterials[0]; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 20550a15..aad70cb3 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -60,7 +60,7 @@ public partial class ModEditWindow CopyToClipboardButton("Copy all current manipulations to clipboard.", _iconSize, _editor.MetaEditor.Recombine()); ImGui.SameLine(); if (ImGui.Button("Write as TexTools Files")) - _metaFileManager.WriteAllTexToolsMeta(_mod!); + _metaFileManager.WriteAllTexToolsMeta(Mod!); using var child = ImRaii.Child("##meta", -Vector2.One, true); if (!child) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 561cbed7..67ec97f2 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -94,7 +94,7 @@ public partial class ModEditWindow { if (success && paths.Count > 0) tab.Import(paths[0]); - }, 1, _mod!.ModPath.FullName, false); + }, 1, Mod!.ModPath.FullName, false); ImGui.SameLine(); DrawDocumentationLink(MdlImportDocumentation); @@ -142,7 +142,7 @@ public partial class ModEditWindow tab.Export(path, gamePath); }, - _mod!.ModPath.FullName, + Mod!.ModPath.FullName, false ); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index c9cd3d06..9a38a5d5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -195,7 +195,7 @@ public partial class ModEditWindow if (subMod.Files.ContainsKey(gamePath) || subMod.FileSwaps.ContainsKey(gamePath)) return new QuickImportAction(editor, optionName, gamePath); - var mod = owner._mod; + var mod = owner.Mod; if (mod == null) return new QuickImportAction(editor, optionName, gamePath); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 34d0800c..71c64059 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -3,6 +3,7 @@ using OtterGui; using OtterGui.Raii; using OtterTex; using Penumbra.Import.Textures; +using Penumbra.Mods; using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -45,10 +46,10 @@ public partial class ModEditWindow using (var disabled = ImRaii.Disabled(!_center.SaveTask.IsCompleted)) { TextureDrawer.PathInputBox(_textures, tex, ref tex.TmpPath, "##input", "Import Image...", - "Can import game paths as well as your own files.", _mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); + "Can import game paths as well as your own files.", Mod!.ModPath.FullName, _fileDialog, _config.DefaultModImportPath); if (_textureSelectCombo.Draw("##combo", "Select the textures included in this mod on your drive or the ones they replace from the game files.", tex.Path, - _mod.ModPath.FullName.Length + 1, out var newPath) + Mod.ModPath.FullName.Length + 1, out var newPath) && newPath != tex.Path) tex.Load(_textures, newPath); @@ -84,6 +85,18 @@ public partial class ModEditWindow ImGuiUtil.SelectableHelpMarker(newDesc); } + } + + private void RedrawOnSaveBox() + { + var redraw = _config.Ephemeral.ForceRedrawOnFileChange; + if (ImGui.Checkbox("Redraw on Save", ref redraw)) + { + _config.Ephemeral.ForceRedrawOnFileChange = redraw; + _config.Ephemeral.Save(); + } + + ImGuiUtil.HoverTooltip("Force a redraw of your player character whenever you save a file here."); } private void MipMapInput() @@ -103,6 +116,8 @@ public partial class ModEditWindow if (_center.IsLoaded) { + RedrawOnSaveBox(); + ImGui.SameLine(); SaveAsCombo(); ImGui.SameLine(); MipMapInput(); @@ -118,6 +133,7 @@ public partial class ModEditWindow tt, !isActive || !canSaveInPlace || _center.IsLeftCopy && _currentSaveAs == (int)CombinedTexture.TextureSaveType.AsIs)) { _center.SaveAs(_left.Type, _textures, _left.Path, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + InvokeChange(Mod, _left.Path); AddReloadTask(_left.Path, false); } @@ -141,6 +157,7 @@ public partial class ModEditWindow !canConvertInPlace || _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); + InvokeChange(Mod, _left.Path); AddReloadTask(_left.Path, false); } @@ -150,6 +167,7 @@ public partial class ModEditWindow !canConvertInPlace || _left.Format is DXGIFormat.BC3Typeless or DXGIFormat.BC3UNorm or DXGIFormat.BC3UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); + InvokeChange(Mod, _left.Path); AddReloadTask(_left.Path, false); } @@ -160,6 +178,7 @@ public partial class ModEditWindow || _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); + InvokeChange(Mod, _left.Path); AddReloadTask(_left.Path, false); } } @@ -192,6 +211,18 @@ public partial class ModEditWindow _center.Draw(_textures, imageSize); } + private void InvokeChange(Mod? mod, string path) + { + if (mod == null) + return; + + if (!_editor.Files.Tex.FindFirst(r => string.Equals(r.File.FullName, path, StringComparison.OrdinalIgnoreCase), + out var registry)) + return; + + _communicator.ModFileChanged.Invoke(mod, registry); + } + private void OpenSaveAsDialog(string defaultExtension) { var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); @@ -201,12 +232,13 @@ public partial class ModEditWindow if (a) { _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); + InvokeChange(Mod, b); if (b == _left.Path) AddReloadTask(_left.Path, false); else if (b == _right.Path) AddReloadTask(_right.Path, true); } - }, _mod!.ModPath.FullName, _forceTextureStartPath); + }, Mod!.ModPath.FullName, _forceTextureStartPath); _forceTextureStartPath = false; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 38fdf482..afa846b5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -49,17 +49,18 @@ public partial class ModEditWindow : Window, IDisposable private readonly IObjectTable _objects; private readonly CharacterBaseDestructor _characterBaseDestructor; - private Mod? _mod; private Vector2 _iconSize = Vector2.Zero; private bool _allowReduplicate; + public Mod? Mod { get; private set; } + public void ChangeMod(Mod mod) { - if (mod == _mod) + if (mod == Mod) return; _editor.LoadMod(mod, -1, 0); - _mod = mod; + Mod = mod; SizeConstraints = new WindowSizeConstraints { @@ -80,12 +81,12 @@ public partial class ModEditWindow : Window, IDisposable public void UpdateModels() { - if (_mod != null) - _editor.MdlMaterialEditor.ScanModels(_mod); + if (Mod != null) + _editor.MdlMaterialEditor.ScanModels(Mod); } public override bool DrawConditions() - => _mod != null; + => Mod != null; public override void PreDraw() { @@ -106,13 +107,13 @@ public partial class ModEditWindow : Window, IDisposable }); var manipulations = 0; var subMods = 0; - var swaps = _mod!.AllSubMods.Sum(m => + var swaps = Mod!.AllSubMods.Sum(m => { ++subMods; manipulations += m.Manipulations.Count; return m.FileSwaps.Count; }); - sb.Append(_mod!.Name); + sb.Append(Mod!.Name); if (subMods > 1) sb.Append($" | {subMods} Options"); @@ -271,7 +272,7 @@ public partial class ModEditWindow : Window, IDisposable ImGui.NewLine(); if (ImGui.Button("Remove Missing Files from Mod")) - _editor.FileEditor.RemoveMissingPaths(_mod!, _editor.Option!); + _editor.FileEditor.RemoveMissingPaths(Mod!, _editor.Option!); using var child = ImRaii.Child("##unusedFiles", -Vector2.One, true); if (!child) @@ -324,8 +325,8 @@ public partial class ModEditWindow : Window, IDisposable } else if (ImGuiUtil.DrawDisabledButton("Re-Duplicate and Normalize Mod", Vector2.Zero, tt, !_allowReduplicate && !modifier)) { - _editor.ModNormalizer.Normalize(_mod!); - _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(_mod!, _editor.GroupIdx, _editor.OptionIdx)); + _editor.ModNormalizer.Normalize(Mod!); + _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(Mod!, _editor.GroupIdx, _editor.OptionIdx)); } if (!_editor.Duplicates.Worker.IsCompleted) @@ -363,7 +364,7 @@ public partial class ModEditWindow : Window, IDisposable foreach (var (set, size, hash) in _editor.Duplicates.Duplicates.Where(s => s.Paths.Length > 1)) { ImGui.TableNextColumn(); - using var tree = ImRaii.TreeNode(set[0].FullName[(_mod!.ModPath.FullName.Length + 1)..], + using var tree = ImRaii.TreeNode(set[0].FullName[(Mod!.ModPath.FullName.Length + 1)..], ImGuiTreeNodeFlags.NoTreePushOnOpen); ImGui.TableNextColumn(); ImGuiUtil.RightAlign(Functions.HumanReadableSize(size)); @@ -384,7 +385,7 @@ public partial class ModEditWindow : Window, IDisposable { ImGui.TableNextColumn(); ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, Colors.RedTableBgTint); - using var node = ImRaii.TreeNode(duplicate.FullName[(_mod!.ModPath.FullName.Length + 1)..], ImGuiTreeNodeFlags.Leaf); + using var node = ImRaii.TreeNode(duplicate.FullName[(Mod!.ModPath.FullName.Length + 1)..], ImGuiTreeNodeFlags.Leaf); ImGui.TableNextColumn(); ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, Colors.RedTableBgTint); ImGui.TableNextColumn(); @@ -421,7 +422,7 @@ public partial class ModEditWindow : Window, IDisposable if (!combo) return ret; - foreach (var (option, idx) in _mod!.AllSubMods.WithIndex()) + foreach (var (option, idx) in Mod!.AllSubMods.WithIndex()) { using var id = ImRaii.PushId(idx); if (ImGui.Selectable(option.FullName, option == _editor.Option)) @@ -537,10 +538,10 @@ public partial class ModEditWindow : Window, IDisposable if (currentFile != null) return currentFile.Value; - if (_mod != null) - foreach (var option in _mod.Groups.OrderByDescending(g => g.Priority) + if (Mod != null) + foreach (var option in Mod.Groups.OrderByDescending(g => g.Priority) .SelectMany(g => g.WithIndex().OrderByDescending(o => g.OptionPriority(o.Index)).Select(g => g.Value)) - .Append(_mod.Default)) + .Append(Mod.Default)) { if (option.Files.TryGetValue(path, out var value) || option.FileSwaps.TryGetValue(path, out value)) return value; @@ -559,8 +560,8 @@ public partial class ModEditWindow : Window, IDisposable ret.Add(path); } - if (_mod != null) - foreach (var option in _mod.Groups.SelectMany(g => g).Append(_mod.Default)) + if (Mod != null) + foreach (var option in Mod.Groups.SelectMany(g => g).Append(Mod.Default)) { foreach (var path in option.Files.Keys) { @@ -596,15 +597,15 @@ public partial class ModEditWindow : Window, IDisposable _objects = objects; _framework = framework; _characterBaseDestructor = characterBaseDestructor; - _materialTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", - () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => _mod?.ModPath.FullName ?? string.Empty, + _materialTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", + () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => Mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); - _modelTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", - () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => _mod?.ModPath.FullName ?? string.Empty, + _modelTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", + () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => Mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new MdlTab(this, bytes, path)); - _shaderPackageTab = new FileEditor(this, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", + _shaderPackageTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, - () => _mod?.ModPath.FullName ?? string.Empty, + () => Mod?.ModPath.FullName ?? string.Empty, (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); @@ -629,10 +630,10 @@ public partial class ModEditWindow : Window, IDisposable private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) { - if (type is not (ModPathChangeType.Reloaded or ModPathChangeType.Moved) || mod != _mod) + if (type is not (ModPathChangeType.Reloaded or ModPathChangeType.Moved) || mod != Mod) return; - _mod = null; + Mod = null; ChangeMod(mod); } } From a89aafb31008961eea0993e155150b77673c1b71 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Feb 2024 14:24:50 +0100 Subject: [PATCH 0461/1381] Let's do this one more time. --- Penumbra/Interop/Services/RedrawService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index c1bd8573..e0a94d30 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -433,7 +433,7 @@ public sealed unsafe partial class RedrawService : IDisposable private void OnModFileChanged(Mod _1, FileRegistry _2) { - if (!_config.ForceRedrawOnFileChange) + if (!_config.Ephemeral.ForceRedrawOnFileChange) return; RedrawObject(0, RedrawType.Redraw); From 1d74001281083620af6ec6f1423fa74fb9217a88 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 24 Feb 2024 13:27:11 +0000 Subject: [PATCH 0462/1381] [CI] Updating repo.json for testing_1.0.0.8 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 1a599362..cbc5677f 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.0.7", - "TestingAssemblyVersion": "1.0.0.7", + "TestingAssemblyVersion": "1.0.0.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.0.8/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From af6100dfe4d8af2f475e09df8411b2f5cbb07bf4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 1 Mar 2024 14:35:41 +0100 Subject: [PATCH 0463/1381] Mawp. --- Penumbra/Collections/ResolveData.cs | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/Penumbra/Collections/ResolveData.cs b/Penumbra/Collections/ResolveData.cs index 0f3a1155..8fe160b3 100644 --- a/Penumbra/Collections/ResolveData.cs +++ b/Penumbra/Collections/ResolveData.cs @@ -1,15 +1,15 @@ namespace Penumbra.Collections; -public readonly struct ResolveData +public readonly struct ResolveData(ModCollection collection, nint gameObject) { public static readonly ResolveData Invalid = new(); - private readonly ModCollection? _modCollection; + private readonly ModCollection? _modCollection = collection; public ModCollection ModCollection => _modCollection ?? ModCollection.Empty; - public readonly nint AssociatedGameObject; + public readonly nint AssociatedGameObject = gameObject; public bool Valid => _modCollection != null; @@ -18,12 +18,6 @@ public readonly struct ResolveData : this(null!, nint.Zero) { } - public ResolveData(ModCollection collection, nint gameObject) - { - _modCollection = collection; - AssociatedGameObject = gameObject; - } - public ResolveData(ModCollection collection) : this(collection, nint.Zero) { } From 0220257efa49d57acea181eddb94561de2fbbe01 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 1 Mar 2024 13:37:51 +0000 Subject: [PATCH 0464/1381] [CI] Updating repo.json for 1.0.1.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index cbc5677f..1780c6c0 100644 --- a/repo.json +++ b/repo.json @@ -4,8 +4,8 @@ "Name": "Penumbra", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.0.7", - "TestingAssemblyVersion": "1.0.0.8", + "AssemblyVersion": "1.0.1.0", + "TestingAssemblyVersion": "1.0.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -16,9 +16,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.0.8/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.0.7/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 7128326ab9f30e2fb2a3449953ed9d6a4c0e0ba1 Mon Sep 17 00:00:00 2001 From: AeAstralis Date: Fri, 1 Mar 2024 17:10:33 -0500 Subject: [PATCH 0465/1381] Add shared tag system for tagging individual mods Adds a new system of shared tags that are saved in the Penumbra config, and can then be 1-click added or removed to/from mods via a popup menu. The use case for this new system is to allow users to more easily re-use tags and to allow them to quickly tag individual mods. Shared tags can be added/removed/modified via a new Tags section of the main Penumbra Settings tab. Once any shared tags have been saved, they can be added via a new tags button that shows up in the Description and Edit Mod tabs, to the right of the existing + button that already existed for typing in new tags. Shared tags have the same restrictions as regular mod tags, and the application of shared tags should respect the same limits as application of normal tags. Signed-off-by: AeAstralis --- Penumbra/Configuration.cs | 2 + Penumbra/Services/ServiceManagerA.cs | 3 +- Penumbra/UI/Classes/Colors.cs | 4 + Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 29 +++- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 30 +++- Penumbra/UI/SharedTagManager.cs | 160 ++++++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 26 ++- 7 files changed, 248 insertions(+), 6 deletions(-) create mode 100644 Penumbra/UI/SharedTagManager.cs diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 188be65d..43253223 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -87,6 +87,8 @@ public class Configuration : IPluginConfiguration, ISavable public Dictionary Colors { get; set; } = Enum.GetValues().ToDictionary(c => c, c => c.Data().DefaultColor); + public IReadOnlyList SharedTags { get; set; } + /// /// Load the current configuration. /// Includes adding new colors and migrating from old versions. diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index f25aac7c..b0ecdcf0 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -103,7 +103,8 @@ public static class ServiceManagerA private static ServiceManager AddConfiguration(this ServiceManager services) => services.AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static ServiceManager AddCollections(this ServiceManager services) => services.AddSingleton() diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 93d7e091..50096696 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -28,6 +28,8 @@ public enum ColorId ResTreePlayer, ResTreeNetworked, ResTreeNonNetworked, + SharedTagAdd, + SharedTagRemove } public static class Colors @@ -73,6 +75,8 @@ public static class Colors ColorId.ResTreePlayer => ( 0xFFC0FFC0, "On-Screen: Other Players", "Other players and what they own, in the On-Screen tab." ), ColorId.ResTreeNetworked => ( 0xFFFFFFFF, "On-Screen: Non-Players (Networked)", "Non-player entities handled by the game server, in the On-Screen tab." ), ColorId.ResTreeNonNetworked => ( 0xFFC0C0FF, "On-Screen: Non-Players (Local)", "Non-player entities handled locally, in the On-Screen tab." ), + ColorId.SharedTagAdd => ( 0xFF44AA44, "Shared Tags: Add Tag", "A shared tag that is not present on the current mod and can be added." ), + ColorId.SharedTagRemove => ( 0xFF2222AA, "Shared Tags: Remove Tag", "A shared tag that is already present on the current mod and can be removed." ), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 3cc59661..7da13966 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -12,14 +12,16 @@ public class ModPanelDescriptionTab : ITab private readonly ModFileSystemSelector _selector; private readonly TutorialService _tutorial; private readonly ModManager _modManager; + private readonly SharedTagManager _sharedTagManager; private readonly TagButtons _localTags = new(); private readonly TagButtons _modTags = new(); - public ModPanelDescriptionTab(ModFileSystemSelector selector, TutorialService tutorial, ModManager modManager) + public ModPanelDescriptionTab(ModFileSystemSelector selector, TutorialService tutorial, ModManager modManager, SharedTagManager sharedTagsConfig) { _selector = selector; _tutorial = tutorial; _modManager = modManager; + _sharedTagManager = sharedTagsConfig; } public ReadOnlySpan Label @@ -34,14 +36,37 @@ public class ModPanelDescriptionTab : ITab ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); + var sharedTagsEnabled = _sharedTagManager.SharedTags.Count() > 0; + var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _localTags.Draw("Local Tags: ", "Custom tags you can set personally that will not be exported to the mod data but only set for you.\n" + "If the mod already contains a local tag in its own tags, the local tag will be ignored.", _selector.Selected!.LocalTags, - out var editedTag); + out var editedTag, rightEndOffset: sharedTagButtonOffset); _tutorial.OpenTutorial(BasicTutorialSteps.Tags); if (tagIdx >= 0) _modManager.DataEditor.ChangeLocalTag(_selector.Selected!, tagIdx, editedTag); + if (sharedTagsEnabled) + { + ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); + ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); + var sharedTag = _sharedTagManager.DrawAddFromSharedTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, true); + if (sharedTag.Length > 0) + { + var index = _selector.Selected!.LocalTags.IndexOf(sharedTag); + if (index < 0) + { + index = _selector.Selected!.LocalTags.Count; + _modManager.DataEditor.ChangeLocalTag(_selector.Selected, index, sharedTag); + } + else + { + _modManager.DataEditor.ChangeLocalTag(_selector.Selected, index, string.Empty); + } + + } + } + if (_selector.Selected!.ModTags.Count > 0) _modTags.Draw("Mod Tags: ", "Tags assigned by the mod creator and saved with the mod data. To edit these, look at Edit Mod.", _selector.Selected!.ModTags, out var _, false, diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 20da8fde..3620c7ac 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -28,6 +28,7 @@ public class ModPanelEditTab : ITab private readonly ModEditWindow _editWindow; private readonly ModEditor _editor; private readonly Configuration _config; + private readonly SharedTagManager _sharedTagManager; private readonly TagButtons _modTags = new(); @@ -37,7 +38,8 @@ public class ModPanelEditTab : ITab private Mod _mod = null!; public ModPanelEditTab(ModManager modManager, ModFileSystemSelector selector, ModFileSystem fileSystem, Services.MessageService messager, - ModEditWindow editWindow, ModEditor editor, FilenameService filenames, ModExportManager modExportManager, Configuration config) + ModEditWindow editWindow, ModEditor editor, FilenameService filenames, ModExportManager modExportManager, Configuration config, + SharedTagManager sharedTagManager) { _modManager = modManager; _selector = selector; @@ -48,6 +50,7 @@ public class ModPanelEditTab : ITab _filenames = filenames; _modExportManager = modExportManager; _config = config; + _sharedTagManager = sharedTagManager; } public ReadOnlySpan Label @@ -80,11 +83,34 @@ public class ModPanelEditTab : ITab } UiHelpers.DefaultLineSpace(); + var sharedTagsEnabled = _sharedTagManager.SharedTags.Count() > 0; + var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, - out var editedTag); + out var editedTag, rightEndOffset: sharedTagButtonOffset); if (tagIdx >= 0) _modManager.DataEditor.ChangeModTag(_mod, tagIdx, editedTag); + if (sharedTagsEnabled) + { + ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); + ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); + var sharedTag = _sharedTagManager.DrawAddFromSharedTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, false); + if (sharedTag.Length > 0) + { + var index = _selector.Selected!.ModTags.IndexOf(sharedTag); + if (index < 0) + { + index = _selector.Selected!.ModTags.Count; + _modManager.DataEditor.ChangeModTag(_selector.Selected, index, sharedTag); + } + else + { + _modManager.DataEditor.ChangeModTag(_selector.Selected, index, string.Empty); + } + + } + } + UiHelpers.DefaultLineSpace(); AddOptionGroup.Draw(_filenames, _modManager, _mod, _config.ReplaceNonAsciiOnImport); UiHelpers.DefaultLineSpace(); diff --git a/Penumbra/UI/SharedTagManager.cs b/Penumbra/UI/SharedTagManager.cs new file mode 100644 index 00000000..9562b24c --- /dev/null +++ b/Penumbra/UI/SharedTagManager.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Widgets; +using Penumbra.Mods; +using Penumbra.UI.Classes; + +namespace Penumbra.UI; +public sealed class SharedTagManager +{ + private static uint _tagButtonAddColor = ColorId.SharedTagAdd.Value(); + private static uint _tagButtonRemoveColor = ColorId.SharedTagRemove.Value(); + + private static float _minTagButtonWidth = 15; + + private const string PopupContext = "SharedTagsPopup"; + private bool _isPopupOpen = false; + + + public IReadOnlyList SharedTags { get; internal set; } = Array.Empty(); + + public SharedTagManager() + { + } + + public void ChangeSharedTag(int tagIdx, string tag) + { + if (tagIdx < 0 || tagIdx > SharedTags.Count) + return; + + if (tagIdx == SharedTags.Count) // Adding a new tag + { + SharedTags = SharedTags.Append(tag).Distinct().Where(tag => tag.Length > 0).OrderBy(a => a).ToArray(); + } + else // Editing an existing tag + { + var tmpTags = SharedTags.ToArray(); + tmpTags[tagIdx] = tag; + SharedTags = tmpTags.Distinct().Where(tag => tag.Length > 0).OrderBy(a => a).ToArray(); + } + } + + public string DrawAddFromSharedTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) + { + var tagToAdd = ""; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Tags.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Add Shared Tag... (Right-click to close popup)", + false, true) || _isPopupOpen) + return DrawSharedTagsPopup(localTags, modTags, editLocal); + + + return tagToAdd; + } + + private string DrawSharedTagsPopup(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) + { + var selected = ""; + if (!ImGui.IsPopupOpen(PopupContext)) + { + ImGui.OpenPopup(PopupContext); + _isPopupOpen = true; + } + + var display = ImGui.GetIO().DisplaySize; + var height = Math.Min(display.Y / 4, 10 * ImGui.GetFrameHeightWithSpacing()); + var width = display.X / 6; + var size = new Vector2(width, height); + ImGui.SetNextWindowSize(size); + using var popup = ImRaii.Popup(PopupContext); + if (!popup) + return selected; + + ImGui.Text("Shared Tags"); + ImGuiUtil.HoverTooltip("Right-click to close popup"); + ImGui.Separator(); + + foreach (var tag in SharedTags) + { + if (DrawColoredButton(localTags, modTags, tag, editLocal)) + { + selected = tag; + return selected; + } + ImGui.SameLine(); + } + + if (ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _isPopupOpen = false; + } + + return selected; + } + + private static bool DrawColoredButton(IReadOnlyCollection localTags, IReadOnlyCollection modTags, string buttonLabel, bool editLocal) + { + var isLocalTagPresent = localTags.Contains(buttonLabel); + var isModTagPresent = modTags.Contains(buttonLabel); + + var buttonWidth = CalcTextButtonWidth(buttonLabel); + // Would prefer to be able to fit at least 2 buttons per line so the popup doesn't look sparse with lots of long tags. Thus long tags will be trimmed. + var maxButtonWidth = (ImGui.GetContentRegionMax().X - ImGui.GetWindowContentRegionMin().X) * 0.5f - ImGui.GetStyle().ItemSpacing.X; + var displayedLabel = buttonLabel; + if (buttonWidth >= maxButtonWidth) + { + displayedLabel = TrimButtonTextToWidth(buttonLabel, maxButtonWidth); + buttonWidth = CalcTextButtonWidth(displayedLabel); + } + + // Prevent adding a new tag past the right edge of the popup + if (buttonWidth + ImGui.GetStyle().ItemSpacing.X >= ImGui.GetContentRegionAvail().X) + ImGui.NewLine(); + + // Trimmed tag names can collide, but the full tags are guaranteed distinct so use the full tag as the ID to avoid an ImGui moment. + ImRaii.PushId(buttonLabel); + + if (editLocal && isModTagPresent || !editLocal && isLocalTagPresent) + { + using var alpha = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f); + ImGui.Button(displayedLabel); + alpha.Pop(); + return false; + } + + using (ImRaii.PushColor(ImGuiCol.Button, isLocalTagPresent || isModTagPresent ? _tagButtonRemoveColor : _tagButtonAddColor)) + { + return ImGui.Button(displayedLabel); + } + } + + private static string TrimButtonTextToWidth(string fullText, float maxWidth) + { + var trimmedText = fullText; + + while (trimmedText.Length > _minTagButtonWidth) + { + var nextTrim = trimmedText.Substring(0, Math.Max(trimmedText.Length - 1, 0)); + + // An ellipsis will be used to indicate trimmed tags + if (CalcTextButtonWidth(nextTrim + "...") < maxWidth) + { + return nextTrim + "..."; + } + trimmedText = nextTrim; + } + + return trimmedText; + } + + private static float CalcTextButtonWidth(string text) + { + return ImGui.CalcTextSize(text).X + 2 * ImGui.GetStyle().FramePadding.X; + } + +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index a03e7b87..f37c2c81 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -41,15 +41,18 @@ public class SettingsTab : ITab private readonly DalamudConfigService _dalamudConfig; private readonly DalamudPluginInterface _pluginInterface; private readonly IDataManager _gameData; + private readonly SharedTagManager _sharedTagManager; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; + private readonly TagButtons _sharedTags = new(); + public SettingsTab(DalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, - IDataManager gameData) + IDataManager gameData, SharedTagManager sharedTagConfig) { _pluginInterface = pluginInterface; _config = config; @@ -69,6 +72,9 @@ public class SettingsTab : ITab _gameData = gameData; if (_compactor.CanCompact) _compactor.Enabled = _config.UseFileSystemCompression; + _sharedTagManager = sharedTagConfig; + if (sharedTagConfig.SharedTags.Count == 0 && _config.SharedTags != null) + sharedTagConfig.SharedTags = _config.SharedTags; } public void DrawHeader() @@ -96,6 +102,7 @@ public class SettingsTab : ITab DrawGeneralSettings(); DrawColorSettings(); DrawAdvancedSettings(); + DrawSharedTagsSection(); DrawSupportButtons(); } @@ -902,4 +909,21 @@ public class SettingsTab : ITab if (ImGui.Button("Show Changelogs", new Vector2(width, 0))) _penumbra.ForceChangelogOpen(); } + + private void DrawSharedTagsSection() + { + if (!ImGui.CollapsingHeader("Tags")) + return; + + var tagIdx = _sharedTags.Draw("Shared Tags: ", + "Tags that can be added/removed from mods with 1 click.", _sharedTagManager.SharedTags, + out var editedTag); + + if (tagIdx >= 0) + { + _sharedTagManager.ChangeSharedTag(tagIdx, editedTag); + _config.SharedTags = _sharedTagManager.SharedTags; + _config.Save(); + } + } } From 334be441f88dc554461cdddbb81ba658abe5b958 Mon Sep 17 00:00:00 2001 From: AeAstralis Date: Fri, 1 Mar 2024 18:04:03 -0500 Subject: [PATCH 0466/1381] Update OtterGui to 97ac353 Updates OtterGui to 97ac3538536a17e980027f783ec5e5167b371f71 to include change that xivdev/Penumbra#399 is dependent on. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 1a187f75..97ac3538 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 1a187f756f2e8823197bd43db1c3383231f5eaff +Subproject commit 97ac3538536a17e980027f783ec5e5167b371f71 From 282f6d48551e0208d4ad06da18167ad74c48d9e2 Mon Sep 17 00:00:00 2001 From: AeAstralis Date: Fri, 1 Mar 2024 21:03:34 -0500 Subject: [PATCH 0467/1381] Migrate shared tag to own config, address comments Migrates the configuration for shared tags to a separate config file, and addresses CR feedback. --- Penumbra/Configuration.cs | 2 - Penumbra/Services/FilenameService.cs | 1 + Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 20 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 20 +- Penumbra/UI/SharedTagManager.cs | 171 ++++++++++++++---- Penumbra/UI/Tabs/SettingsTab.cs | 6 +- 6 files changed, 143 insertions(+), 77 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 43253223..188be65d 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -87,8 +87,6 @@ public class Configuration : IPluginConfiguration, ISavable public Dictionary Colors { get; set; } = Enum.GetValues().ToDictionary(c => c, c => c.Data().DefaultColor); - public IReadOnlyList SharedTags { get; set; } - /// /// Load the current configuration. /// Includes adding new colors and migrating from old versions. diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 5f918a90..23694ebc 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -14,6 +14,7 @@ public class FilenameService(DalamudPluginInterface pi) : IService public readonly string EphemeralConfigFile = Path.Combine(pi.ConfigDirectory.FullName, "ephemeral_config.json"); public readonly string FilesystemFile = Path.Combine(pi.ConfigDirectory.FullName, "sort_order.json"); public readonly string ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); + public readonly string SharedTagFile = Path.Combine(pi.ConfigDirectory.FullName, "shared_tags.json"); /// Obtain the path of a collection file given its name. public string CollectionFile(ModCollection collection) diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 7da13966..5f2687c3 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -36,7 +36,7 @@ public class ModPanelDescriptionTab : ITab ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); - var sharedTagsEnabled = _sharedTagManager.SharedTags.Count() > 0; + var sharedTagsEnabled = _sharedTagManager.SharedTags.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _localTags.Draw("Local Tags: ", "Custom tags you can set personally that will not be exported to the mod data but only set for you.\n" @@ -48,23 +48,7 @@ public class ModPanelDescriptionTab : ITab if (sharedTagsEnabled) { - ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); - ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); - var sharedTag = _sharedTagManager.DrawAddFromSharedTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, true); - if (sharedTag.Length > 0) - { - var index = _selector.Selected!.LocalTags.IndexOf(sharedTag); - if (index < 0) - { - index = _selector.Selected!.LocalTags.Count; - _modManager.DataEditor.ChangeLocalTag(_selector.Selected, index, sharedTag); - } - else - { - _modManager.DataEditor.ChangeLocalTag(_selector.Selected, index, string.Empty); - } - - } + _sharedTagManager.DrawAddFromSharedTagsAndUpdateTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, true, _selector.Selected!); } if (_selector.Selected!.ModTags.Count > 0) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 3620c7ac..9b4a582f 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -83,7 +83,7 @@ public class ModPanelEditTab : ITab } UiHelpers.DefaultLineSpace(); - var sharedTagsEnabled = _sharedTagManager.SharedTags.Count() > 0; + var sharedTagsEnabled = _sharedTagManager.SharedTags.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); @@ -92,23 +92,7 @@ public class ModPanelEditTab : ITab if (sharedTagsEnabled) { - ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); - ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); - var sharedTag = _sharedTagManager.DrawAddFromSharedTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, false); - if (sharedTag.Length > 0) - { - var index = _selector.Selected!.ModTags.IndexOf(sharedTag); - if (index < 0) - { - index = _selector.Selected!.ModTags.Count; - _modManager.DataEditor.ChangeModTag(_selector.Selected, index, sharedTag); - } - else - { - _modManager.DataEditor.ChangeModTag(_selector.Selected, index, string.Empty); - } - - } + _sharedTagManager.DrawAddFromSharedTagsAndUpdateTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, false, _selector.Selected!); } UiHelpers.DefaultLineSpace(); diff --git a/Penumbra/UI/SharedTagManager.cs b/Penumbra/UI/SharedTagManager.cs index 9562b24c..23196319 100644 --- a/Penumbra/UI/SharedTagManager.cs +++ b/Penumbra/UI/SharedTagManager.cs @@ -1,19 +1,22 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Dalamud.Interface; +using Dalamud.Interface; +using Dalamud.Interface.Internal.Notifications; +using Dalamud.Utility; using ImGuiNET; +using Newtonsoft.Json; using OtterGui; +using OtterGui.Classes; using OtterGui.Raii; -using OtterGui.Widgets; -using Penumbra.Mods; +using Penumbra.Mods.Manager; +using Penumbra.Services; using Penumbra.UI.Classes; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra.UI; -public sealed class SharedTagManager +public sealed class SharedTagManager : ISavable { + private readonly ModManager _modManager; + private readonly SaveService _saveService; + private static uint _tagButtonAddColor = ColorId.SharedTagAdd.Value(); private static uint _tagButtonRemoveColor = ColorId.SharedTagRemove.Value(); @@ -22,11 +25,66 @@ public sealed class SharedTagManager private const string PopupContext = "SharedTagsPopup"; private bool _isPopupOpen = false; + // Operations on this list assume that it is sorted and will keep it sorted if that is the case. + // The list also gets re-sorted when first loaded from config in case the config was modified. + [JsonRequired] + private readonly List _sharedTags = []; + [JsonIgnore] + public IReadOnlyList SharedTags => _sharedTags; - public IReadOnlyList SharedTags { get; internal set; } = Array.Empty(); + public int ConfigVersion = 1; - public SharedTagManager() + public SharedTagManager(ModManager modManager, SaveService saveService) { + _modManager = modManager; + _saveService = saveService; + Load(); + } + + public string ToFilename(FilenameService fileNames) + { + return fileNames.SharedTagFile; + } + + public void Save(StreamWriter writer) + { + using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + serializer.Serialize(jWriter, this); + } + + public void Save() + => _saveService.DelaySave(this, TimeSpan.FromSeconds(5)); + + private void Load() + { + static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) + { + Penumbra.Log.Error( + $"Error parsing shared tags Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); + errorArgs.ErrorContext.Handled = true; + } + + if (!File.Exists(_saveService.FileNames.SharedTagFile)) + return; + + try + { + var text = File.ReadAllText(_saveService.FileNames.SharedTagFile); + JsonConvert.PopulateObject(text, this, new JsonSerializerSettings + { + Error = HandleDeserializationError, + }); + + // Any changes to this within this class should keep it sorted, but in case someone went in and manually changed the JSON, run a sort on initial load. + _sharedTags.Sort(); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, + "Error reading shared tags Configuration, reverting to default.", + "Error reading shared tags Configuration", NotificationType.Error); + } } public void ChangeSharedTag(int tagIdx, string tag) @@ -34,32 +92,74 @@ public sealed class SharedTagManager if (tagIdx < 0 || tagIdx > SharedTags.Count) return; - if (tagIdx == SharedTags.Count) // Adding a new tag + // In the case of editing a tag, remove what's there prior to doing an insert. + if (tagIdx != SharedTags.Count) { - SharedTags = SharedTags.Append(tag).Distinct().Where(tag => tag.Length > 0).OrderBy(a => a).ToArray(); + _sharedTags.RemoveAt(tagIdx); } - else // Editing an existing tag + + if (!string.IsNullOrEmpty(tag)) { - var tmpTags = SharedTags.ToArray(); - tmpTags[tagIdx] = tag; - SharedTags = tmpTags.Distinct().Where(tag => tag.Length > 0).OrderBy(a => a).ToArray(); + // Taking advantage of the fact that BinarySearch returns the complement of the correct sorted position for the tag. + var existingIdx = _sharedTags.BinarySearch(tag); + if (existingIdx < 0) + _sharedTags.Insert(~existingIdx, tag); + } + + Save(); + } + + public void DrawAddFromSharedTagsAndUpdateTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, Mods.Mod mod) + { + ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); + ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); + + var sharedTag = DrawAddFromSharedTags(localTags, modTags, editLocal); + + if (sharedTag.Length > 0) + { + var index = editLocal ? mod.LocalTags.IndexOf(sharedTag) : mod.ModTags.IndexOf(sharedTag); + + if (editLocal) + { + if (index < 0) + { + index = mod.LocalTags.Count; + _modManager.DataEditor.ChangeLocalTag(mod, index, sharedTag); + } + else + { + _modManager.DataEditor.ChangeLocalTag(mod, index, string.Empty); + } + } else + { + if (index < 0) + { + index = mod.ModTags.Count; + _modManager.DataEditor.ChangeModTag(mod, index, sharedTag); + } + else + { + _modManager.DataEditor.ChangeModTag(mod, index, string.Empty); + } + } + } } public string DrawAddFromSharedTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) { - var tagToAdd = ""; + var tagToAdd = string.Empty; if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Tags.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Add Shared Tag... (Right-click to close popup)", false, true) || _isPopupOpen) return DrawSharedTagsPopup(localTags, modTags, editLocal); - return tagToAdd; } private string DrawSharedTagsPopup(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) { - var selected = ""; + var selected = string.Empty; if (!ImGui.IsPopupOpen(PopupContext)) { ImGui.OpenPopup(PopupContext); @@ -75,16 +175,15 @@ public sealed class SharedTagManager if (!popup) return selected; - ImGui.Text("Shared Tags"); + ImGui.TextUnformatted("Shared Tags"); ImGuiUtil.HoverTooltip("Right-click to close popup"); ImGui.Separator(); - foreach (var tag in SharedTags) + foreach (var (tag, idx) in SharedTags.WithIndex()) { - if (DrawColoredButton(localTags, modTags, tag, editLocal)) + if (DrawColoredButton(localTags, modTags, tag, editLocal, idx)) { selected = tag; - return selected; } ImGui.SameLine(); } @@ -97,8 +196,10 @@ public sealed class SharedTagManager return selected; } - private static bool DrawColoredButton(IReadOnlyCollection localTags, IReadOnlyCollection modTags, string buttonLabel, bool editLocal) + private static bool DrawColoredButton(IReadOnlyCollection localTags, IReadOnlyCollection modTags, string buttonLabel, bool editLocal, int index) { + var ret = false; + var isLocalTagPresent = localTags.Contains(buttonLabel); var isModTagPresent = modTags.Contains(buttonLabel); @@ -116,21 +217,24 @@ public sealed class SharedTagManager if (buttonWidth + ImGui.GetStyle().ItemSpacing.X >= ImGui.GetContentRegionAvail().X) ImGui.NewLine(); - // Trimmed tag names can collide, but the full tags are guaranteed distinct so use the full tag as the ID to avoid an ImGui moment. - ImRaii.PushId(buttonLabel); + // Trimmed tag names can collide, and while tag names are currently distinct this may not always be the case. As such use the index to avoid an ImGui moment. + using var id = ImRaii.PushId(index); if (editLocal && isModTagPresent || !editLocal && isLocalTagPresent) { using var alpha = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f); ImGui.Button(displayedLabel); - alpha.Pop(); - return false; + } + else + { + using (ImRaii.PushColor(ImGuiCol.Button, isLocalTagPresent || isModTagPresent ? _tagButtonRemoveColor : _tagButtonAddColor)) + { + if (ImGui.Button(displayedLabel)) + ret = true; + } } - using (ImRaii.PushColor(ImGuiCol.Button, isLocalTagPresent || isModTagPresent ? _tagButtonRemoveColor : _tagButtonAddColor)) - { - return ImGui.Button(displayedLabel); - } + return ret; } private static string TrimButtonTextToWidth(string fullText, float maxWidth) @@ -156,5 +260,4 @@ public sealed class SharedTagManager { return ImGui.CalcTextSize(text).X + 2 * ImGui.GetStyle().FramePadding.X; } - } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index f37c2c81..71f108c2 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -73,8 +73,6 @@ public class SettingsTab : ITab if (_compactor.CanCompact) _compactor.Enabled = _config.UseFileSystemCompression; _sharedTagManager = sharedTagConfig; - if (sharedTagConfig.SharedTags.Count == 0 && _config.SharedTags != null) - sharedTagConfig.SharedTags = _config.SharedTags; } public void DrawHeader() @@ -916,14 +914,12 @@ public class SettingsTab : ITab return; var tagIdx = _sharedTags.Draw("Shared Tags: ", - "Tags that can be added/removed from mods with 1 click.", _sharedTagManager.SharedTags, + "Predefined tags that can be added or removed from mods with a single click.", _sharedTagManager.SharedTags, out var editedTag); if (tagIdx >= 0) { _sharedTagManager.ChangeSharedTag(tagIdx, editedTag); - _config.SharedTags = _sharedTagManager.SharedTags; - _config.Save(); } } } From c1cdb28bb5f35a9816b3042d786bcde40e4bed18 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 29 Jan 2024 16:58:47 +1100 Subject: [PATCH 0468/1381] Use named enum values for vertex decl mismatch error --- Penumbra/Import/Models/Import/Utility.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Import/Utility.cs b/Penumbra/Import/Models/Import/Utility.cs index a1e44136..21655563 100644 --- a/Penumbra/Import/Models/Import/Utility.cs +++ b/Penumbra/Import/Models/Import/Utility.cs @@ -1,4 +1,5 @@ using Lumina.Data.Parsing; +using Penumbra.GameData.Files; namespace Penumbra.Import.Models.Import; @@ -43,15 +44,15 @@ public static class Utility throw notifier.Exception( $""" All sub-meshes of a mesh must have equivalent vertex declarations. - Current: {FormatVertexDeclaration(current)} - New: {FormatVertexDeclaration(@new)} + Current: {FormatVertexDeclaration(current)} + New: {FormatVertexDeclaration(@new)} """ ); } private static string FormatVertexDeclaration(MdlStructs.VertexDeclarationStruct vertexDeclaration) => string.Join(", ", - vertexDeclaration.VertexElements.Select(element => $"{element.Usage} ({element.Type}@{element.Stream}:{element.Offset})")); + vertexDeclaration.VertexElements.Select(element => $"{(MdlFile.VertexUsage)element.Usage} ({(MdlFile.VertexType)element.Type}@{element.Stream}:{element.Offset})")); private static bool VertexDeclarationMismatch(MdlStructs.VertexDeclarationStruct a, MdlStructs.VertexDeclarationStruct b) { From 1cee1c24ec219a00f20bb5112771b77591f32844 Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 30 Jan 2024 21:39:12 +1100 Subject: [PATCH 0469/1381] Skip degenerate triangles targeted by shape keys --- Penumbra/Import/Models/Export/MeshExporter.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index df315094..d3ca87dc 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -214,10 +214,18 @@ public class MeshExporter var morphBuilder = meshBuilder.UseMorphTarget(shapeNames.Count); shapeNames.Add(shape.ShapeName); - foreach (var shapeValue in shapeValues) + foreach (var (shapeValue, shapeValueIndex) in shapeValues.WithIndex()) { + var gltfIndex = gltfIndices[shapeValue.BaseIndicesIndex - indexBase]; + + if (gltfIndex == -1) + { + _notifier.Warning($"{name}: Shape {shape.ShapeName} mapping {shapeValueIndex} targets a degenerate triangle, ignoring."); + continue; + } + morphBuilder.SetVertex( - primitiveVertices[gltfIndices[shapeValue.BaseIndicesIndex - indexBase]].GetGeometry(), + primitiveVertices[gltfIndex].GetGeometry(), vertices[shapeValue.ReplacingVertexIndex].GetGeometry() ); } From a4bd015836a6a7e8dec83a3a3553e946832c40b8 Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 20 Feb 2024 21:35:14 +1100 Subject: [PATCH 0470/1381] Fix index offset mis-cast causing overflow --- Penumbra/Import/Models/Import/MeshImporter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 8ab55734..efebdba4 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -167,7 +167,7 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) // And finally, merge in the sub-mesh struct itself. _subMeshes.Add(subMesh.SubMeshStruct with { - IndexOffset = (ushort)(subMesh.SubMeshStruct.IndexOffset + indexOffset), + IndexOffset = (uint)(subMesh.SubMeshStruct.IndexOffset + indexOffset), AttributeIndexMask = Utility.GetMergedAttributeMask( subMesh.SubMeshStruct.AttributeIndexMask, subMesh.MetaAttributes, _metaAttributes), }); From 5c6e0701d96f626ba7f58fcf7541ddc1b62be930 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 25 Feb 2024 22:09:55 +1100 Subject: [PATCH 0471/1381] Simplify EID handling because IDFK at this point --- Penumbra/Import/Models/Import/MeshImporter.cs | 1 - .../ModEditWindow.Models.MdlTab.cs | 21 +++---------------- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index efebdba4..1d4b223d 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -80,7 +80,6 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) StartIndex = 0, IndexCount = (uint)_indices.Count, - // TODO: import material names MaterialIndex = 0, SubMeshIndex = 0, SubMeshCount = (ushort)_subMeshes.Count, diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 7adc4379..637c8401 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -220,24 +220,9 @@ public partial class ModEditWindow /// Model to copy element ids from. private static void MergeElementIds(MdlFile target, MdlFile source) { - var elementIds = new List(); - - foreach (var sourceElement in source.ElementIds) - { - var sourceBone = source.Bones[sourceElement.ParentBoneName]; - var targetIndex = target.Bones.IndexOf(sourceBone); - // Given that there's no means of authoring these at the moment, this should probably remain a hard error. - if (targetIndex == -1) - throw new Exception( - $"Failed to merge element IDs. Original model contains element IDs targeting bone {sourceBone}, which is not present on the imported model."); - - elementIds.Add(sourceElement with - { - ParentBoneName = (uint)targetIndex, - }); - } - - target.ElementIds = [.. elementIds]; + // This is overly simplistic, but effectively reproduces what TT did, sort of. + // TODO: Get a better idea of what these values represent. `ParentBoneName`, if it is a pointer into the bone array, does not seem to be _bounded_ by the bone array length, at least in the model. I'm guessing it _may_ be pointing into a .sklb instead? (i.e. the weapon's skeleton). EID stuff in general needs more work. + target.ElementIds = [.. source.ElementIds]; } private void BeginIo() From da423b746400d72f3fd7e79ab9d191dc7593bcf6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Mar 2024 18:13:44 +0100 Subject: [PATCH 0472/1381] Make lack of Root Directory louder. --- Penumbra/UI/Tabs/SettingsTab.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index a03e7b87..7ea37a75 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -1,5 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Components; +using Dalamud.Interface.Utility; using Dalamud.Plugin; using Dalamud.Plugin.Services; using Dalamud.Utility; @@ -223,7 +224,15 @@ public class SettingsTab : ITab using var group = ImRaii.Group(); ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); - var save = ImGui.InputText("##rootDirectory", ref _newModDirectory, RootDirectoryMaxLength, ImGuiInputTextFlags.EnterReturnsTrue); + bool save; + using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale, !_modManager.Valid)) + { + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder) + .Push(ImGuiCol.TextDisabled, Colors.RegexWarningBorder, !_modManager.Valid); + save = ImGui.InputTextWithHint("##rootDirectory", "Enter Root Directory here (MANDATORY)...", ref _newModDirectory, + RootDirectoryMaxLength, ImGuiInputTextFlags.EnterReturnsTrue); + } + var selected = ImGui.IsItemActive(); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); ImGui.SameLine(); From 29c93f46a0131ba28eca812697b3010b86e520db Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 9 Mar 2024 22:28:46 +0100 Subject: [PATCH 0473/1381] Add characterglass.shpk to the skin.shpk fixer --- Penumbra.GameData | 2 +- Penumbra/Communication/MtrlShpkLoaded.cs | 4 +- .../Resources/ResourceHandleDestructor.cs | 4 +- Penumbra/Interop/Services/ModelRenderer.cs | 71 +++++++ .../Services/ShaderReplacementFixer.cs | 197 ++++++++++++++++++ Penumbra/Interop/Services/SkinFixer.cs | 139 ------------ Penumbra/Penumbra.cs | 2 +- Penumbra/Services/ServiceManagerA.cs | 3 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 23 +- 9 files changed, 290 insertions(+), 155 deletions(-) create mode 100644 Penumbra/Interop/Services/ModelRenderer.cs create mode 100644 Penumbra/Interop/Services/ShaderReplacementFixer.cs delete mode 100644 Penumbra/Interop/Services/SkinFixer.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 3a7f6d86..c0c7eb0d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3a7f6d86c9975a4892f58be3c629b7664e6c3733 +Subproject commit c0c7eb0dedb32ea83b019626abba041e90a95319 diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlShpkLoaded.cs index bd560fd8..8aab0e0e 100644 --- a/Penumbra/Communication/MtrlShpkLoaded.cs +++ b/Penumbra/Communication/MtrlShpkLoaded.cs @@ -10,7 +10,7 @@ public sealed class MtrlShpkLoaded() : EventWrapper - SkinFixer = 0, + /// + ShaderReplacementFixer = 0, } } diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index 31387101..5ddb7eaa 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -13,8 +13,8 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr SubfileHelper, - /// - SkinFixer, + /// + ShaderReplacementFixer, } public ResourceHandleDestructor(HookManager hooks) diff --git a/Penumbra/Interop/Services/ModelRenderer.cs b/Penumbra/Interop/Services/ModelRenderer.cs new file mode 100644 index 00000000..6a3bf776 --- /dev/null +++ b/Penumbra/Interop/Services/ModelRenderer.cs @@ -0,0 +1,71 @@ +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Penumbra.GameData; + +namespace Penumbra.Interop.Services; + +// TODO ClientStructs-ify (https://github.com/aers/FFXIVClientStructs/pull/817) +public unsafe class ModelRenderer : IDisposable +{ + // Will be Manager.Instance()->ModelRenderer.CharacterGlassShaderPackage in CS + private const nint ModelRendererOffset = 0x13660; + private const nint CharacterGlassShaderPackageOffset = 0xD0; + + /// A static pointer to the Render::Manager address. + [Signature(Sigs.RenderManager, ScanType = ScanType.StaticAddress)] + private readonly nint* _renderManagerAddress = null; + + public bool Ready { get; private set; } + + public ShaderPackageResourceHandle** CharacterGlassShaderPackage + => *_renderManagerAddress == 0 + ? null + : (ShaderPackageResourceHandle**)(*_renderManagerAddress + ModelRendererOffset + CharacterGlassShaderPackageOffset).ToPointer(); + + public ShaderPackageResourceHandle* DefaultCharacterGlassShaderPackage { get; private set; } + + private readonly IFramework _framework; + + public ModelRenderer(IFramework framework, IGameInteropProvider interop) + { + interop.InitializeFromAttributes(this); + _framework = framework; + LoadDefaultResources(null!); + if (!Ready) + _framework.Update += LoadDefaultResources; + } + + /// We store the default data of the resources so we can always restore them. + private void LoadDefaultResources(object _) + { + if (*_renderManagerAddress == 0) + return; + + var anyMissing = false; + + if (DefaultCharacterGlassShaderPackage == null) + { + DefaultCharacterGlassShaderPackage = *CharacterGlassShaderPackage; + anyMissing |= DefaultCharacterGlassShaderPackage == null; + } + + if (anyMissing) + return; + + Ready = true; + _framework.Update -= LoadDefaultResources; + } + + /// Return all relevant resources to the default resource. + public void ResetAll() + { + if (!Ready) + return; + + *CharacterGlassShaderPackage = DefaultCharacterGlassShaderPackage; + } + + public void Dispose() + => ResetAll(); +} diff --git a/Penumbra/Interop/Services/ShaderReplacementFixer.cs b/Penumbra/Interop/Services/ShaderReplacementFixer.cs new file mode 100644 index 00000000..e57fe313 --- /dev/null +++ b/Penumbra/Interop/Services/ShaderReplacementFixer.cs @@ -0,0 +1,197 @@ +using Dalamud.Hooking; +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Classes; +using Penumbra.Communication; +using Penumbra.GameData; +using Penumbra.Interop.Hooks.Resources; +using Penumbra.Services; + +namespace Penumbra.Interop.Services; + +public sealed unsafe class ShaderReplacementFixer : IDisposable +{ + public static ReadOnlySpan SkinShpkName + => "skin.shpk"u8; + + public static ReadOnlySpan CharacterGlassShpkName + => "characterglass.shpk"u8; + + [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] + private readonly nint* _humanVTable = null!; + + private delegate nint CharacterBaseOnRenderMaterialDelegate(nint drawObject, OnRenderMaterialParams* param); + private delegate nint ModelRendererOnRenderMaterialDelegate(nint modelRenderer, nint outFlags, nint param, Material* material, uint materialIndex); + + [StructLayout(LayoutKind.Explicit)] + private struct OnRenderMaterialParams + { + [FieldOffset(0x0)] + public Model* Model; + + [FieldOffset(0x8)] + public uint MaterialIndex; + } + + private readonly Hook _humanOnRenderMaterialHook; + + [Signature(Sigs.ModelRendererOnRenderMaterial, DetourName = nameof(ModelRendererOnRenderMaterialDetour))] + private readonly Hook _modelRendererOnRenderMaterialHook = null!; + + private readonly ResourceHandleDestructor _resourceHandleDestructor; + private readonly CommunicatorService _communicator; + private readonly CharacterUtility _utility; + private readonly ModelRenderer _modelRenderer; + + // MaterialResourceHandle set + private readonly ConcurrentSet _moddedSkinShpkMaterials = new(); + private readonly ConcurrentSet _moddedCharacterGlassShpkMaterials = new(); + + private readonly object _skinLock = new(); + private readonly object _characterGlassLock = new(); + + // ConcurrentDictionary.Count uses a lock in its current implementation. + private int _moddedSkinShpkCount; + private int _moddedCharacterGlassShpkCount; + private ulong _skinSlowPathCallDelta; + private ulong _characterGlassSlowPathCallDelta; + + public bool Enabled { get; internal set; } = true; + + public int ModdedSkinShpkCount + => _moddedSkinShpkCount; + + public int ModdedCharacterGlassShpkCount + => _moddedCharacterGlassShpkCount; + + public ShaderReplacementFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, ModelRenderer modelRenderer, + CommunicatorService communicator, IGameInteropProvider interop) + { + interop.InitializeFromAttributes(this); + _resourceHandleDestructor = resourceHandleDestructor; + _utility = utility; + _modelRenderer = modelRenderer; + _communicator = communicator; + _humanOnRenderMaterialHook = interop.HookFromAddress(_humanVTable[62], OnRenderHumanMaterial); + _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.ShaderReplacementFixer); + _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.ShaderReplacementFixer); + _humanOnRenderMaterialHook.Enable(); + _modelRendererOnRenderMaterialHook.Enable(); + } + + public void Dispose() + { + _modelRendererOnRenderMaterialHook.Dispose(); + _humanOnRenderMaterialHook.Dispose(); + _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); + _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); + _moddedCharacterGlassShpkMaterials.Clear(); + _moddedSkinShpkMaterials.Clear(); + _moddedCharacterGlassShpkCount = 0; + _moddedSkinShpkCount = 0; + } + + public (ulong Skin, ulong CharacterGlass) GetAndResetSlowPathCallDeltas() + => (Interlocked.Exchange(ref _skinSlowPathCallDelta, 0), Interlocked.Exchange(ref _characterGlassSlowPathCallDelta, 0)); + + private static bool IsMaterialWithShpk(MaterialResourceHandle* mtrlResource, ReadOnlySpan shpkName) + { + if (mtrlResource == null) + return false; + + return shpkName.SequenceEqual(mtrlResource->ShpkNameSpan); + } + + private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) + { + var mtrl = (MaterialResourceHandle*)mtrlResourceHandle; + var shpk = mtrl->ShaderPackageResourceHandle; + if (shpk == null) + return; + + var shpkName = mtrl->ShpkNameSpan; + + if (SkinShpkName.SequenceEqual(shpkName) && (nint)shpk != _utility.DefaultSkinShpkResource) + { + if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle)) + Interlocked.Increment(ref _moddedSkinShpkCount); + } + + if (CharacterGlassShpkName.SequenceEqual(shpkName) && shpk != _modelRenderer.DefaultCharacterGlassShaderPackage) + { + if (_moddedCharacterGlassShpkMaterials.TryAdd(mtrlResourceHandle)) + Interlocked.Increment(ref _moddedCharacterGlassShpkCount); + } + } + + private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) + { + if (_moddedSkinShpkMaterials.TryRemove((nint)handle)) + Interlocked.Decrement(ref _moddedSkinShpkCount); + + if (_moddedCharacterGlassShpkMaterials.TryRemove((nint)handle)) + Interlocked.Decrement(ref _moddedCharacterGlassShpkCount); + } + + private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) + { + // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. + if (!Enabled || _moddedSkinShpkCount == 0) + return _humanOnRenderMaterialHook.Original(human, param); + + var material = param->Model->Materials[param->MaterialIndex]; + var mtrlResource = material->MaterialResourceHandle; + if (!IsMaterialWithShpk(mtrlResource, SkinShpkName)) + return _humanOnRenderMaterialHook.Original(human, param); + + Interlocked.Increment(ref _skinSlowPathCallDelta); + + // Performance considerations: + // - This function is called from several threads simultaneously, hence the need for synchronization in the swapping path ; + // - Function is called each frame for each material on screen, after culling, i. e. up to thousands of times a frame in crowded areas ; + // - Swapping path is taken up to hundreds of times a frame. + // At the time of writing, the lock doesn't seem to have a noticeable impact in either framerate or CPU usage, but the swapping path shall still be avoided as much as possible. + lock (_skinLock) + { + try + { + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShaderPackageResourceHandle; + return _humanOnRenderMaterialHook.Original(human, param); + } + finally + { + _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)_utility.DefaultSkinShpkResource; + } + } + } + + private nint ModelRendererOnRenderMaterialDetour(nint modelRenderer, nint outFlags, nint param, Material* material, uint materialIndex) + { + + // If we don't have any on-screen instances of modded characterglass.shpk, we don't need the slow path at all. + if (!Enabled || _moddedCharacterGlassShpkCount == 0) + return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); + + var mtrlResource = material->MaterialResourceHandle; + if (!IsMaterialWithShpk(mtrlResource, CharacterGlassShpkName)) + return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); + + Interlocked.Increment(ref _characterGlassSlowPathCallDelta); + + // Same performance considerations as above. + lock (_characterGlassLock) + { + try + { + *_modelRenderer.CharacterGlassShaderPackage = mtrlResource->ShaderPackageResourceHandle; + return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); + } + finally + { + *_modelRenderer.CharacterGlassShaderPackage = _modelRenderer.DefaultCharacterGlassShaderPackage; + } + } + } +} diff --git a/Penumbra/Interop/Services/SkinFixer.cs b/Penumbra/Interop/Services/SkinFixer.cs deleted file mode 100644 index 21331916..00000000 --- a/Penumbra/Interop/Services/SkinFixer.cs +++ /dev/null @@ -1,139 +0,0 @@ -using Dalamud.Hooking; -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; -using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; -using OtterGui.Classes; -using Penumbra.Communication; -using Penumbra.GameData; -using Penumbra.Interop.Hooks.Resources; -using Penumbra.Services; - -namespace Penumbra.Interop.Services; - -public sealed unsafe class SkinFixer : IDisposable -{ - public static ReadOnlySpan SkinShpkName - => "skin.shpk"u8; - - [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _humanVTable = null!; - - private delegate nint OnRenderMaterialDelegate(nint drawObject, OnRenderMaterialParams* param); - - [StructLayout(LayoutKind.Explicit)] - private struct OnRenderMaterialParams - { - [FieldOffset(0x0)] - public Model* Model; - - [FieldOffset(0x8)] - public uint MaterialIndex; - } - - private readonly Hook _onRenderMaterialHook; - - private readonly ResourceHandleDestructor _resourceHandleDestructor; - private readonly CommunicatorService _communicator; - private readonly CharacterUtility _utility; - - // MaterialResourceHandle set - private readonly ConcurrentSet _moddedSkinShpkMaterials = new(); - - private readonly object _lock = new(); - - // ConcurrentDictionary.Count uses a lock in its current implementation. - private int _moddedSkinShpkCount; - private ulong _slowPathCallDelta; - - public bool Enabled { get; internal set; } = true; - - public int ModdedSkinShpkCount - => _moddedSkinShpkCount; - - public SkinFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, CommunicatorService communicator, - IGameInteropProvider interop) - { - interop.InitializeFromAttributes(this); - _resourceHandleDestructor = resourceHandleDestructor; - _utility = utility; - _communicator = communicator; - _onRenderMaterialHook = interop.HookFromAddress(_humanVTable[62], OnRenderHumanMaterial); - _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.SkinFixer); - _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.SkinFixer); - _onRenderMaterialHook.Enable(); - } - - public void Dispose() - { - _onRenderMaterialHook.Dispose(); - _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); - _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); - _moddedSkinShpkMaterials.Clear(); - _moddedSkinShpkCount = 0; - } - - public ulong GetAndResetSlowPathCallDelta() - => Interlocked.Exchange(ref _slowPathCallDelta, 0); - - private static bool IsSkinMaterial(MaterialResourceHandle* mtrlResource) - { - if (mtrlResource == null) - return false; - - var shpkName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlResource->ShpkName); - return SkinShpkName.SequenceEqual(shpkName); - } - - private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) - { - var mtrl = (MaterialResourceHandle*)mtrlResourceHandle; - var shpk = mtrl->ShaderPackageResourceHandle; - if (shpk == null) - return; - - if (!IsSkinMaterial(mtrl) || (nint)shpk == _utility.DefaultSkinShpkResource) - return; - - if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle)) - Interlocked.Increment(ref _moddedSkinShpkCount); - } - - private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) - { - if (_moddedSkinShpkMaterials.TryRemove((nint)handle)) - Interlocked.Decrement(ref _moddedSkinShpkCount); - } - - private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) - { - // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. - if (!Enabled || _moddedSkinShpkCount == 0) - return _onRenderMaterialHook.Original(human, param); - - var material = param->Model->Materials[param->MaterialIndex]; - var mtrlResource = material->MaterialResourceHandle; - if (!IsSkinMaterial(mtrlResource)) - return _onRenderMaterialHook.Original(human, param); - - Interlocked.Increment(ref _slowPathCallDelta); - - // Performance considerations: - // - This function is called from several threads simultaneously, hence the need for synchronization in the swapping path ; - // - Function is called each frame for each material on screen, after culling, i. e. up to thousands of times a frame in crowded areas ; - // - Swapping path is taken up to hundreds of times a frame. - // At the time of writing, the lock doesn't seem to have a noticeable impact in either framerate or CPU usage, but the swapping path shall still be avoided as much as possible. - lock (_lock) - { - try - { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShaderPackageResourceHandle; - return _onRenderMaterialHook.Original(human, param); - } - finally - { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)_utility.DefaultSkinShpkResource; - } - } - } -} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 15b7ce56..67f523ba 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -78,7 +78,7 @@ public class Penumbra : IDalamudPlugin _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); _services.GetService(); - _services.GetService(); + _services.GetService(); _services.GetService(); // Initialize before Interface. diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index f25aac7c..191d8d11 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -92,6 +92,7 @@ public static class ServiceManagerA return new CutsceneResolver(cutsceneService.GetParentIndex); }) .AddSingleton() + .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() @@ -132,7 +133,7 @@ public static class ServiceManagerA .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton(); private static ServiceManager AddResolvers(this ServiceManager services) => services.AddSingleton() diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 66b93b04..f4ddbe31 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -86,7 +86,7 @@ public class DebugTab : Window, ITab private readonly ImportPopup _importPopup; private readonly FrameworkManager _framework; private readonly TextureManager _textureManager; - private readonly SkinFixer _skinFixer; + private readonly ShaderReplacementFixer _shaderReplacementFixer; private readonly RedrawService _redraws; private readonly DictEmote _emotes; private readonly Diagnostics _diagnostics; @@ -99,7 +99,7 @@ public class DebugTab : Window, ITab ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager, SkinFixer skinFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester) + TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -130,7 +130,7 @@ public class DebugTab : Window, ITab _importPopup = importPopup; _framework = framework; _textureManager = textureManager; - _skinFixer = skinFixer; + _shaderReplacementFixer = shaderReplacementFixer; _redraws = redraws; _emotes = emotes; _diagnostics = diagnostics; @@ -702,20 +702,25 @@ public class DebugTab : Window, ITab if (!ImGui.CollapsingHeader("Character Utility")) return; - var enableSkinFixer = _skinFixer.Enabled; - if (ImGui.Checkbox("Enable Skin Fixer", ref enableSkinFixer)) - _skinFixer.Enabled = enableSkinFixer; + var enableShaderReplacementFixer = _shaderReplacementFixer.Enabled; + if (ImGui.Checkbox("Enable Shader Replacement Fixer", ref enableShaderReplacementFixer)) + _shaderReplacementFixer.Enabled = enableShaderReplacementFixer; - if (enableSkinFixer) + if (enableShaderReplacementFixer) { ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + var slowPathCallDeltas = _shaderReplacementFixer.GetAndResetSlowPathCallDeltas(); ImGui.SameLine(); - ImGui.TextUnformatted($"\u0394 Slow-Path Calls: {_skinFixer.GetAndResetSlowPathCallDelta()}"); + ImGui.TextUnformatted($"\u0394 Slow-Path Calls for skin.shpk: {slowPathCallDeltas.Skin}"); + ImGui.SameLine(); + ImGui.TextUnformatted($"characterglass.shpk: {slowPathCallDeltas.CharacterGlass}"); ImGui.SameLine(); ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); ImGui.SameLine(); - ImGui.TextUnformatted($"Materials with Modded skin.shpk: {_skinFixer.ModdedSkinShpkCount}"); + ImGui.TextUnformatted($"Materials with Modded skin.shpk: {_shaderReplacementFixer.ModdedSkinShpkCount}"); + ImGui.SameLine(); + ImGui.TextUnformatted($"characterglass.shpk: {_shaderReplacementFixer.ModdedCharacterGlassShpkCount}"); } using var table = Table("##CharacterUtility", 7, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, From 9ba6e4d0afb74c9603dc9353ea27244223dcbd0b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 9 Mar 2024 22:49:19 +0100 Subject: [PATCH 0474/1381] Update API. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 79ffdd69..34921fd2 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 79ffdd69a28141a1ac93daa24d76573b2fa0d71e +Subproject commit 34921fd2c5a9aff5d34aef664bdb78331e8b9436 From e08e9c4d1368765af5fa36a5537673cda645f3a5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Mar 2024 16:20:34 +0100 Subject: [PATCH 0475/1381] Add crash handler stuff. --- .../Buffers/AnimationInvocationBuffer.cs | 119 +++++++ .../Buffers/CharacterBaseBuffer.cs | 85 +++++ .../Buffers/MemoryMappedBuffer.cs | 215 +++++++++++++ .../Buffers/ModdedFileBuffer.cs | 99 ++++++ Penumbra.CrashHandler/CrashData.cs | 62 ++++ Penumbra.CrashHandler/GameEventLogReader.cs | 53 ++++ Penumbra.CrashHandler/GameEventLogWriter.cs | 17 + .../Penumbra.CrashHandler.csproj | 28 ++ Penumbra.CrashHandler/Program.cs | 30 ++ Penumbra.sln | 6 + .../Communication/CreatingCharacterBase.cs | 4 + Penumbra/Configuration.cs | 1 + Penumbra/EphemeralConfig.cs | 8 +- .../Animation/ApricotListenerSoundPlay.cs | 11 +- .../Animation/CharacterBaseLoadAnimation.cs | 16 +- .../Interop/Hooks/Animation/LoadAreaVfx.cs | 15 +- .../Hooks/Animation/LoadCharacterSound.cs | 16 +- .../Hooks/Animation/LoadCharacterVfx.cs | 14 +- .../Hooks/Animation/LoadTimelineResources.cs | 24 +- .../Hooks/Animation/ScheduleClipUpdate.cs | 32 +- .../Interop/Hooks/Animation/SomeActionLoad.cs | 26 +- .../Interop/Hooks/Animation/SomePapLoad.cs | 18 +- Penumbra/Penumbra.csproj | 9 +- Penumbra/Services/CrashHandlerService.cs | 296 ++++++++++++++++++ Penumbra/Services/FilenameService.cs | 6 + Penumbra/UI/Tabs/ChangedItemsTab.cs | 37 +-- Penumbra/UI/Tabs/ConfigTabBar.cs | 6 +- Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs | 104 ++++++ Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs | 136 ++++++++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 23 +- Penumbra/UI/Tabs/EffectiveTab.cs | 17 +- Penumbra/UI/Tabs/ModsTab.cs | 85 +++-- Penumbra/UI/Tabs/OnScreenTab.cs | 2 +- Penumbra/UI/Tabs/ResourceTab.cs | 26 +- Penumbra/packages.lock.json | 63 +--- 35 files changed, 1472 insertions(+), 237 deletions(-) create mode 100644 Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs create mode 100644 Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs create mode 100644 Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs create mode 100644 Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs create mode 100644 Penumbra.CrashHandler/CrashData.cs create mode 100644 Penumbra.CrashHandler/GameEventLogReader.cs create mode 100644 Penumbra.CrashHandler/GameEventLogWriter.cs create mode 100644 Penumbra.CrashHandler/Penumbra.CrashHandler.csproj create mode 100644 Penumbra.CrashHandler/Program.cs create mode 100644 Penumbra/Services/CrashHandlerService.cs create mode 100644 Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs create mode 100644 Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs diff --git a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs new file mode 100644 index 00000000..dd966542 --- /dev/null +++ b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs @@ -0,0 +1,119 @@ +using System.Text.Json.Nodes; + +namespace Penumbra.CrashHandler.Buffers; + +/// The types of currently hooked and relevant animation loading functions. +public enum AnimationInvocationType : int +{ + PapLoad, + ActionLoad, + ScheduleClipUpdate, + LoadTimelineResources, + LoadCharacterVfx, + LoadCharacterSound, + ApricotSoundPlay, + LoadAreaVfx, + CharacterBaseLoadAnimation, +} + +/// The full crash entry for an invoked vfx function. +public record struct VfxFuncInvokedEntry( + double Age, + DateTimeOffset Timestamp, + int ThreadId, + string InvocationType, + string CharacterName, + string CharacterAddress, + string CollectionName) : ICrashDataEntry; + +/// Only expose the write interface for the buffer. +public interface IAnimationInvocationBufferWriter +{ + /// Write a line into the buffer with the given data. + /// The address of the related character, if known. + /// The name of the related character, anonymized or relying on index if unavailable, if known. + /// The name of the associated collection. Not anonymized. + /// The type of VFX func called. + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, AnimationInvocationType type); +} + +internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimationInvocationBufferWriter, IBufferReader +{ + private const int _version = 1; + private const int _lineCount = 64; + private const int _lineCapacity = 256; + private const string _name = "Penumbra.AnimationInvocation"; + + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, AnimationInvocationType type) + { + var accessor = GetCurrentLineLocking(); + lock (accessor) + { + accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + accessor.Write(8, Environment.CurrentManagedThreadId); + accessor.Write(12, (int)type); + accessor.Write(16, characterAddress); + var span = GetSpan(accessor, 24, 104); + WriteSpan(characterName, span); + span = GetSpan(accessor, 128); + WriteString(collectionName, span); + } + } + + public uint TotalCount + => TotalWrittenLines; + + public IEnumerable GetLines(DateTimeOffset crashTime) + { + var lineCount = (int)CurrentLineCount; + for (var i = lineCount - 1; i >= 0; --i) + { + var line = GetLine(i); + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); + var thread = BitConverter.ToInt32(line[8..]); + var type = (AnimationInvocationType)BitConverter.ToInt32(line[12..]); + var address = BitConverter.ToUInt64(line[16..]); + var characterName = ReadString(line[24..]); + var collectionName = ReadString(line[128..]); + yield return new JsonObject() + { + [nameof(VfxFuncInvokedEntry.Age)] = (crashTime - timestamp).TotalSeconds, + [nameof(VfxFuncInvokedEntry.Timestamp)] = timestamp, + [nameof(VfxFuncInvokedEntry.ThreadId)] = thread, + [nameof(VfxFuncInvokedEntry.InvocationType)] = ToName(type), + [nameof(VfxFuncInvokedEntry.CharacterName)] = characterName, + [nameof(VfxFuncInvokedEntry.CharacterAddress)] = address.ToString("X"), + [nameof(VfxFuncInvokedEntry.CollectionName)] = collectionName, + }; + } + } + + public static IBufferReader CreateReader() + => new AnimationInvocationBuffer(false); + + public static IAnimationInvocationBufferWriter CreateWriter() + => new AnimationInvocationBuffer(); + + private AnimationInvocationBuffer(bool writer) + : base(_name, _version) + { } + + private AnimationInvocationBuffer() + : base(_name, _version, _lineCount, _lineCapacity) + { } + + private static string ToName(AnimationInvocationType type) + => type switch + { + AnimationInvocationType.PapLoad => "PAP Load", + AnimationInvocationType.ActionLoad => "Action Load", + AnimationInvocationType.ScheduleClipUpdate => "Schedule Clip Update", + AnimationInvocationType.LoadTimelineResources => "Load Timeline Resources", + AnimationInvocationType.LoadCharacterVfx => "Load Character VFX", + AnimationInvocationType.LoadCharacterSound => "Load Character Sound", + AnimationInvocationType.ApricotSoundPlay => "Apricot Sound Play", + AnimationInvocationType.LoadAreaVfx => "Load Area VFX", + AnimationInvocationType.CharacterBaseLoadAnimation => "Load Animation (CharacterBase)", + _ => $"Unknown ({(int)type})", + }; +} diff --git a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs new file mode 100644 index 00000000..1fe5d7ba --- /dev/null +++ b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs @@ -0,0 +1,85 @@ +using System.Text.Json.Nodes; + +namespace Penumbra.CrashHandler.Buffers; + +/// Only expose the write interface for the buffer. +public interface ICharacterBaseBufferWriter +{ + /// Write a line into the buffer with the given data. + /// The address of the related character, if known. + /// The name of the related character, anonymized or relying on index if unavailable, if known. + /// The name of the associated collection. Not anonymized. + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName); +} + +/// The full crash entry for a loaded character base. +public record struct CharacterLoadedEntry( + double Age, + DateTimeOffset Timestamp, + int ThreadId, + string CharacterName, + string CharacterAddress, + string CollectionName) : ICrashDataEntry; + +internal sealed class CharacterBaseBuffer : MemoryMappedBuffer, ICharacterBaseBufferWriter, IBufferReader +{ + private const int _version = 1; + private const int _lineCount = 10; + private const int _lineCapacity = 256; + private const string _name = "Penumbra.CharacterBase"; + + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName) + { + var accessor = GetCurrentLineLocking(); + lock (accessor) + { + accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + accessor.Write(8, Environment.CurrentManagedThreadId); + accessor.Write(12, characterAddress); + var span = GetSpan(accessor, 20, 108); + WriteSpan(characterName, span); + span = GetSpan(accessor, 128); + WriteString(collectionName, span); + } + } + + public IEnumerable GetLines(DateTimeOffset crashTime) + { + var lineCount = (int)CurrentLineCount; + for (var i = lineCount - 1; i >= 0; --i) + { + var line = GetLine(i); + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); + var thread = BitConverter.ToInt32(line[8..]); + var address = BitConverter.ToUInt64(line[12..]); + var characterName = ReadString(line[20..]); + var collectionName = ReadString(line[128..]); + yield return new JsonObject + { + [nameof(CharacterLoadedEntry.Age)] = (crashTime - timestamp).TotalSeconds, + [nameof(CharacterLoadedEntry.Timestamp)] = timestamp, + [nameof(CharacterLoadedEntry.ThreadId)] = thread, + [nameof(CharacterLoadedEntry.CharacterName)] = characterName, + [nameof(CharacterLoadedEntry.CharacterAddress)] = address.ToString("X"), + [nameof(CharacterLoadedEntry.CollectionName)] = collectionName, + }; + } + } + + public uint TotalCount + => TotalWrittenLines; + + public static IBufferReader CreateReader() + => new CharacterBaseBuffer(false); + + public static ICharacterBaseBufferWriter CreateWriter() + => new CharacterBaseBuffer(); + + private CharacterBaseBuffer(bool writer) + : base(_name, _version) + { } + + private CharacterBaseBuffer() + : base(_name, _version, _lineCount, _lineCapacity) + { } +} diff --git a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs new file mode 100644 index 00000000..35055864 --- /dev/null +++ b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs @@ -0,0 +1,215 @@ +using System.Diagnostics.CodeAnalysis; +using System.IO.MemoryMappedFiles; +using System.Numerics; +using System.Text; + +namespace Penumbra.CrashHandler.Buffers; + +public class MemoryMappedBuffer : IDisposable +{ + private const int MinHeaderLength = 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4; + + private readonly MemoryMappedFile _file; + private readonly MemoryMappedViewAccessor _header; + private readonly MemoryMappedViewAccessor[] _lines; + + public readonly int Version; + public readonly uint LineCount; + public readonly uint LineCapacity; + private readonly uint _lineMask; + private bool _disposed; + + protected uint CurrentLineCount + { + get => _header.ReadUInt32(16); + set => _header.Write(16, value); + } + + protected uint CurrentLinePosition + { + get => _header.ReadUInt32(20); + set => _header.Write(20, value); + } + + public uint TotalWrittenLines + { + get => _header.ReadUInt32(24); + protected set => _header.Write(24, value); + } + + public MemoryMappedBuffer(string mapName, int version, uint lineCount, uint lineCapacity) + { + Version = version; + LineCount = BitOperations.RoundUpToPowerOf2(Math.Clamp(lineCount, 2, int.MaxValue >> 3)); + LineCapacity = BitOperations.RoundUpToPowerOf2(Math.Clamp(lineCapacity, 2, int.MaxValue >> 3)); + _lineMask = LineCount - 1; + var fileName = Encoding.UTF8.GetBytes(mapName); + var headerLength = (uint)(4 + 4 + 4 + 4 + 4 + 4 + 4 + fileName.Length + 1); + headerLength = (headerLength & 0b111) > 0 ? (headerLength & ~0b111u) + 0b1000 : headerLength; + var capacity = LineCount * LineCapacity + headerLength; + _file = MemoryMappedFile.CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, + HandleInheritability.Inheritable); + _header = _file.CreateViewAccessor(0, headerLength); + _header.Write(0, headerLength); + _header.Write(4, Version); + _header.Write(8, LineCount); + _header.Write(12, LineCapacity); + _header.WriteArray(28, fileName, 0, fileName.Length); + _header.Write(fileName.Length + 28, (byte)0); + _lines = Enumerable.Range(0, (int)LineCount).Select(i + => _file.CreateViewAccessor(headerLength + i * LineCapacity, LineCapacity, MemoryMappedFileAccess.ReadWrite)) + .ToArray(); + } + + public MemoryMappedBuffer(string mapName, int? expectedVersion = null, uint? expectedMinLineCount = null, + uint? expectedMinLineCapacity = null) + { + _file = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable); + using var headerLine = _file.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read); + var headerLength = headerLine.ReadUInt32(0); + if (headerLength < MinHeaderLength) + Throw($"Map {mapName} did not contain a valid header."); + + _header = _file.CreateViewAccessor(0, headerLength, MemoryMappedFileAccess.ReadWrite); + Version = _header.ReadInt32(4); + LineCount = _header.ReadUInt32(8); + LineCapacity = _header.ReadUInt32(12); + _lineMask = LineCount - 1; + if (expectedVersion.HasValue && expectedVersion.Value != Version) + Throw($"Map {mapName} has version {Version} instead of {expectedVersion.Value}."); + + if (LineCount < expectedMinLineCount) + Throw($"Map {mapName} has line count {LineCount} but line count >= {expectedMinLineCount.Value} is required."); + + if (LineCapacity < expectedMinLineCapacity) + Throw($"Map {mapName} has line capacity {LineCapacity} but line capacity >= {expectedMinLineCapacity.Value} is required."); + + var name = ReadString(GetSpan(_header, 28)); + if (name != mapName) + Throw($"Map {mapName} does not contain its map name at the expected location."); + + _lines = Enumerable.Range(0, (int)LineCount).Select(i + => _file.CreateViewAccessor(headerLength + i * LineCapacity, LineCapacity, MemoryMappedFileAccess.ReadWrite)) + .ToArray(); + + [DoesNotReturn] + void Throw(string text) + { + _file.Dispose(); + _disposed = true; + throw new Exception(text); + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + _disposed = true; + } + + protected static string ReadString(Span span) + { + if (span.IsEmpty) + throw new Exception("String from empty span requested."); + + var termination = span.IndexOf((byte)0); + if (termination < 0) + throw new Exception("String in span is not terminated."); + + return Encoding.UTF8.GetString(span[..termination]); + } + + protected static int WriteString(string text, Span span) + { + var bytes = Encoding.UTF8.GetBytes(text); + var length = bytes.Length + 1; + if (length > span.Length) + throw new Exception($"String {text} is too long to write into span."); + + bytes.CopyTo(span); + span[bytes.Length] = 0; + return length; + } + + protected static int WriteSpan(ReadOnlySpan input, Span span) + { + var length = input.Length + 1; + if (length > span.Length) + throw new Exception("Byte array is too long to write into span."); + + input.CopyTo(span); + span[input.Length] = 0; + return length; + } + + protected Span GetLine(int i) + { + if (i < 0 || i > LineCount) + return null; + + lock (_header) + { + var lineIdx = CurrentLinePosition + i & _lineMask; + if (lineIdx > CurrentLineCount) + return null; + + return GetSpan(_lines[lineIdx]); + } + } + + + protected MemoryMappedViewAccessor GetCurrentLineLocking() + { + MemoryMappedViewAccessor view; + lock (_header) + { + var currentLineCount = CurrentLineCount; + if (currentLineCount == LineCount) + { + var currentLinePos = CurrentLinePosition; + view = _lines[currentLinePos]!; + CurrentLinePosition = currentLinePos + 1 & _lineMask; + } + else + { + view = _lines[currentLineCount]; + ++CurrentLineCount; + } + + ++TotalWrittenLines; + _header.Flush(); + } + + return view; + } + + protected static Span GetSpan(MemoryMappedViewAccessor accessor, int offset = 0) + => GetSpan(accessor, offset, (int)accessor.Capacity - offset); + + protected static unsafe Span GetSpan(MemoryMappedViewAccessor accessor, int offset, int size) + { + byte* ptr = null; + accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr); + size = Math.Min(size, (int)accessor.Capacity - offset); + if (size < 0) + return []; + + var span = new Span(ptr + offset + accessor.PointerOffset, size); + return span; + } + + protected void Dispose(bool disposing) + { + if (_disposed) + return; + + _header.Dispose(); + foreach (var line in _lines) + line.Dispose(); + _file.Dispose(); + } + + ~MemoryMappedBuffer() + => Dispose(false); +} diff --git a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs new file mode 100644 index 00000000..b472d413 --- /dev/null +++ b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs @@ -0,0 +1,99 @@ +using System.Text.Json.Nodes; + +namespace Penumbra.CrashHandler.Buffers; + +/// Only expose the write interface for the buffer. +public interface IModdedFileBufferWriter +{ + /// Write a line into the buffer with the given data. + /// The address of the related character, if known. + /// The name of the related character, anonymized or relying on index if unavailable, if known. + /// The name of the associated collection. Not anonymized. + /// The file name as requested by the game. + /// The actual modded file name loaded. + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, ReadOnlySpan requestedFileName, + ReadOnlySpan actualFileName); +} + +/// The full crash entry for a loaded modded file. +public record struct ModdedFileLoadedEntry( + double Age, + DateTimeOffset Timestamp, + int ThreadId, + string CharacterName, + string CharacterAddress, + string CollectionName, + string RequestedFileName, + string ActualFileName) : ICrashDataEntry; + +internal sealed class ModdedFileBuffer : MemoryMappedBuffer, IModdedFileBufferWriter, IBufferReader +{ + private const int _version = 1; + private const int _lineCount = 128; + private const int _lineCapacity = 1024; + private const string _name = "Penumbra.ModdedFile"; + + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, ReadOnlySpan requestedFileName, + ReadOnlySpan actualFileName) + { + var accessor = GetCurrentLineLocking(); + lock (accessor) + { + accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + accessor.Write(8, Environment.CurrentManagedThreadId); + accessor.Write(12, characterAddress); + var span = GetSpan(accessor, 20, 80); + WriteSpan(characterName, span); + span = GetSpan(accessor, 92, 80); + WriteString(collectionName, span); + span = GetSpan(accessor, 172, 260); + WriteSpan(requestedFileName, span); + span = GetSpan(accessor, 432); + WriteSpan(actualFileName, span); + } + } + + public uint TotalCount + => TotalWrittenLines; + + public IEnumerable GetLines(DateTimeOffset crashTime) + { + var lineCount = (int)CurrentLineCount; + for (var i = lineCount - 1; i >= 0; --i) + { + var line = GetLine(i); + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); + var thread = BitConverter.ToInt32(line[8..]); + var address = BitConverter.ToUInt64(line[12..]); + var characterName = ReadString(line[20..]); + var collectionName = ReadString(line[92..]); + var requestedFileName = ReadString(line[172..]); + var actualFileName = ReadString(line[432..]); + yield return new JsonObject() + { + [nameof(ModdedFileLoadedEntry.Age)] = (crashTime - timestamp).TotalSeconds, + [nameof(ModdedFileLoadedEntry.Timestamp)] = timestamp, + [nameof(ModdedFileLoadedEntry.ThreadId)] = thread, + [nameof(ModdedFileLoadedEntry.CharacterName)] = characterName, + [nameof(ModdedFileLoadedEntry.CharacterAddress)] = address.ToString("X"), + [nameof(ModdedFileLoadedEntry.CollectionName)] = collectionName, + [nameof(ModdedFileLoadedEntry.RequestedFileName)] = requestedFileName, + [nameof(ModdedFileLoadedEntry.ActualFileName)] = actualFileName, + }; + } + } + + public static IBufferReader CreateReader() + => new ModdedFileBuffer(false); + + public static IModdedFileBufferWriter CreateWriter() + => new ModdedFileBuffer(); + + private ModdedFileBuffer(bool writer) + : base(_name, _version) + { } + + private ModdedFileBuffer() + : base(_name, _version, _lineCount, _lineCapacity) + { } +} diff --git a/Penumbra.CrashHandler/CrashData.cs b/Penumbra.CrashHandler/CrashData.cs new file mode 100644 index 00000000..956a3db7 --- /dev/null +++ b/Penumbra.CrashHandler/CrashData.cs @@ -0,0 +1,62 @@ +using Penumbra.CrashHandler.Buffers; + +namespace Penumbra.CrashHandler; + +/// A base entry for crash data. +public interface ICrashDataEntry +{ + /// The timestamp of the event. + DateTimeOffset Timestamp { get; } + + /// The thread invoking the event. + int ThreadId { get; } + + /// The age of the event compared to the crash. (Redundantly with the timestamp) + double Age { get; } +} + +/// A full set of crash data. +public class CrashData +{ + /// The mode this data was obtained - manually or from a crash. + public string Mode { get; set; } = "Unknown"; + + /// The time this crash data was generated. + public DateTimeOffset CrashTime { get; set; } = DateTimeOffset.UnixEpoch; + + /// The FFXIV process ID when this data was generated. + public int ProcessId { get; set; } = 0; + + /// The FFXIV Exit Code (if any) when this data was generated. + public int ExitCode { get; set; } = 0; + + /// The total amount of characters loaded during this session. + public int TotalCharactersLoaded { get; set; } = 0; + + /// The total amount of modded files loaded during this session. + public int TotalModdedFilesLoaded { get; set; } = 0; + + /// The total amount of vfx functions invoked during this session. + public int TotalVFXFuncsInvoked { get; set; } = 0; + + /// The last character loaded before this crash data was generated. + public CharacterLoadedEntry? LastCharacterLoaded + => LastCharactersLoaded.Count == 0 ? default : LastCharactersLoaded[0]; + + /// The last modded file loaded before this crash data was generated. + public ModdedFileLoadedEntry? LastModdedFileLoaded + => LastModdedFilesLoaded.Count == 0 ? default : LastModdedFilesLoaded[0]; + + /// The last vfx function invoked before this crash data was generated. + public VfxFuncInvokedEntry? LastVfxFuncInvoked + => LastVfxFuncsInvoked.Count == 0 ? default : LastVfxFuncsInvoked[0]; + + /// A collection of the last few characters loaded before this crash data was generated. + public List LastCharactersLoaded { get; } = []; + + /// A collection of the last few modded files loaded before this crash data was generated. + public List LastModdedFilesLoaded { get; } = []; + + /// A collection of the last few vfx functions invoked before this crash data was generated. + public List LastVfxFuncsInvoked { get; } = []; +} diff --git a/Penumbra.CrashHandler/GameEventLogReader.cs b/Penumbra.CrashHandler/GameEventLogReader.cs new file mode 100644 index 00000000..283be526 --- /dev/null +++ b/Penumbra.CrashHandler/GameEventLogReader.cs @@ -0,0 +1,53 @@ +using System.Text.Json.Nodes; +using Penumbra.CrashHandler.Buffers; + +namespace Penumbra.CrashHandler; + +public interface IBufferReader +{ + public uint TotalCount { get; } + public IEnumerable GetLines(DateTimeOffset crashTime); +} + +public sealed class GameEventLogReader : IDisposable +{ + public readonly (IBufferReader Reader, string TypeSingular, string TypePlural)[] Readers = + [ + (CharacterBaseBuffer.CreateReader(), "CharacterLoaded", "CharactersLoaded"), + (ModdedFileBuffer.CreateReader(), "ModdedFileLoaded", "ModdedFilesLoaded"), + (AnimationInvocationBuffer.CreateReader(), "VFXFuncInvoked", "VFXFuncsInvoked"), + ]; + + public void Dispose() + { + foreach (var (reader, _, _) in Readers) + (reader as IDisposable)?.Dispose(); + } + + + public JsonObject Dump(string mode, int processId, int exitCode) + { + var crashTime = DateTimeOffset.UtcNow; + var obj = new JsonObject + { + [nameof(CrashData.Mode)] = mode, + [nameof(CrashData.CrashTime)] = DateTimeOffset.UtcNow, + [nameof(CrashData.ProcessId)] = processId, + [nameof(CrashData.ExitCode)] = exitCode, + }; + + foreach (var (reader, singular, _) in Readers) + obj["Last" + singular] = reader.GetLines(crashTime).FirstOrDefault(); + + foreach (var (reader, _, plural) in Readers) + { + obj["Total" + plural] = reader.TotalCount; + var array = new JsonArray(); + foreach (var file in reader.GetLines(crashTime)) + array.Add(file); + obj["Last" + plural] = array; + } + + return obj; + } +} diff --git a/Penumbra.CrashHandler/GameEventLogWriter.cs b/Penumbra.CrashHandler/GameEventLogWriter.cs new file mode 100644 index 00000000..8e809cec --- /dev/null +++ b/Penumbra.CrashHandler/GameEventLogWriter.cs @@ -0,0 +1,17 @@ +using Penumbra.CrashHandler.Buffers; + +namespace Penumbra.CrashHandler; + +public sealed class GameEventLogWriter : IDisposable +{ + public readonly ICharacterBaseBufferWriter CharacterBase = CharacterBaseBuffer.CreateWriter(); + public readonly IModdedFileBufferWriter FileLoaded = ModdedFileBuffer.CreateWriter(); + public readonly IAnimationInvocationBufferWriter AnimationFuncInvoked = AnimationInvocationBuffer.CreateWriter(); + + public void Dispose() + { + (CharacterBase as IDisposable)?.Dispose(); + (FileLoaded as IDisposable)?.Dispose(); + (AnimationFuncInvoked as IDisposable)?.Dispose(); + } +} diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj new file mode 100644 index 00000000..ea61b968 --- /dev/null +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -0,0 +1,28 @@ + + + + Exe + net7.0-windows + preview + enable + x64 + enable + true + false + + + + $(appdata)\XIVLauncher\addon\Hooks\dev\ + $(HOME)/.xlcore/dalamud/Hooks/dev/ + $(DALAMUD_HOME)/ + + + + embedded + + + + embedded + + + diff --git a/Penumbra.CrashHandler/Program.cs b/Penumbra.CrashHandler/Program.cs new file mode 100644 index 00000000..e4a46348 --- /dev/null +++ b/Penumbra.CrashHandler/Program.cs @@ -0,0 +1,30 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace Penumbra.CrashHandler; + +public class CrashHandler +{ + public static void Main(string[] args) + { + if (args.Length < 2 || !int.TryParse(args[1], out var pid)) + return; + + try + { + using var reader = new GameEventLogReader(); + var parent = Process.GetProcessById(pid); + + parent.WaitForExit(); + var exitCode = parent.ExitCode; + var obj = reader.Dump("Crash", pid, exitCode); + using var fs = File.Open(args[0], FileMode.Create); + using var w = new Utf8JsonWriter(fs, new JsonWriterOptions { Indented = true }); + obj.WriteTo(w, new JsonSerializerOptions() { WriteIndented = true }); + } + catch (Exception ex) + { + File.WriteAllText(args[0], $"{DateTime.UtcNow} {pid} {ex}"); + } + } +} diff --git a/Penumbra.sln b/Penumbra.sln index 5c11aaea..78fa1543 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -18,6 +18,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.Api", "Penumbra.Ap EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.String", "Penumbra.String\Penumbra.String.csproj", "{5549BAFD-6357-4B1A-800C-75AC36E5B76D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Penumbra.CrashHandler", "Penumbra.CrashHandler\Penumbra.CrashHandler.csproj", "{EE834491-A98F-4395-BE0D-6861AE5AD953}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -44,6 +46,10 @@ Global {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Debug|Any CPU.Build.0 = Debug|Any CPU {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Release|Any CPU.Build.0 = Release|Any CPU + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Penumbra/Communication/CreatingCharacterBase.cs b/Penumbra/Communication/CreatingCharacterBase.cs index 1e232761..2f249c14 100644 --- a/Penumbra/Communication/CreatingCharacterBase.cs +++ b/Penumbra/Communication/CreatingCharacterBase.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Services; namespace Penumbra.Communication; @@ -19,5 +20,8 @@ public sealed class CreatingCharacterBase() { /// Api = 0, + + /// + CrashHandler = 0, } } diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 188be65d..9c0b4f2d 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -33,6 +33,7 @@ public class Configuration : IPluginConfiguration, ISavable public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; + public bool UseCrashHandler { get; set; } = true; public bool OpenWindowAtStart { get; set; } = false; public bool HideUiInGPose { get; set; } = false; public bool HideUiInCutscenes { get; set; } = true; diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 98b1a5d6..0a542d04 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -47,7 +47,7 @@ public class EphemeralConfig : ISavable, IDisposable /// public EphemeralConfig(SaveService saveService, ModPathChanged modPathChanged) { - _saveService = saveService; + _saveService = saveService; _modPathChanged = modPathChanged; Load(); _modPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.EphemeralConfig); @@ -94,13 +94,13 @@ public class EphemeralConfig : ISavable, IDisposable public void Save(StreamWriter writer) { - using var jWriter = new JsonTextWriter(writer); + using var jWriter = new JsonTextWriter(writer); jWriter.Formatting = Formatting.Indented; - var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; serializer.Serialize(jWriter, this); } - /// Overwrite the last saved mod path if it changes. + /// Overwrite the last saved mod path if it changes. private void OnModPathChanged(ModPathChangeType type, Mod mod, DirectoryInfo? old, DirectoryInfo? _) { if (type is not ModPathChangeType.Moved || !string.Equals(old?.Name, LastModPath, StringComparison.OrdinalIgnoreCase)) diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index b91c5375..77927593 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -2,21 +2,25 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; using Penumbra.Collections; +using Penumbra.CrashHandler.Buffers; using Penumbra.GameData; using Penumbra.Interop.PathResolving; +using Penumbra.Services; namespace Penumbra.Interop.Hooks.Animation; /// Called for some sound effects caused by animations or VFX. public sealed unsafe class ApricotListenerSoundPlay : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly CrashHandlerService _crashHandler; - public ApricotListenerSoundPlay(HookManager hooks, GameState state, CollectionResolver collectionResolver) + public ApricotListenerSoundPlay(HookManager hooks, GameState state, CollectionResolver collectionResolver, CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; + _crashHandler = crashHandler; Task = hooks.CreateHook("Apricot Listener Sound Play", Sigs.ApricotListenerSoundPlay, Detour, true); } @@ -46,6 +50,7 @@ public sealed unsafe class ApricotListenerSoundPlay : FastHook public sealed unsafe class CharacterBaseLoadAnimation : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; - private readonly DrawObjectState _drawObjectState; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly DrawObjectState _drawObjectState; + private readonly CrashHandlerService _crashHandler; public CharacterBaseLoadAnimation(HookManager hooks, GameState state, CollectionResolver collectionResolver, - DrawObjectState drawObjectState) + DrawObjectState drawObjectState, CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; _drawObjectState = drawObjectState; + _crashHandler = crashHandler; Task = hooks.CreateHook("CharacterBase Load Animation", Sigs.CharacterBaseLoadAnimation, Detour, true); } @@ -33,7 +37,9 @@ public sealed unsafe class CharacterBaseLoadAnimation : FastHook Load a ground-based area VFX. public sealed unsafe class LoadAreaVfx : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly CrashHandlerService _crashHandler; - public LoadAreaVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver) + public LoadAreaVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver, CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; + _crashHandler = crashHandler; Task = hooks.CreateHook("Load Area VFX", Sigs.LoadAreaVfx, Detour, true); } @@ -25,10 +29,11 @@ public sealed unsafe class LoadAreaVfx : FastHook private nint Detour(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3) { var newData = caster != null - ? _collectionResolver.IdentifyCollection(caster, true) - : ResolveData.Invalid; + ? _collectionResolver.IdentifyCollection(caster, true) + : ResolveData.Invalid; var last = _state.SetAnimationData(newData); + _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.LoadAreaVfx); var ret = Task.Result.Original(vfxId, pos, caster, unk1, unk2, unk3); Penumbra.Log.Excessive( $"[Load Area VFX] Invoked with {vfxId}, [{pos[0]} {pos[1]} {pos[2]}], 0x{(nint)caster:X}, {unk1}, {unk2}, {unk3} -> 0x{ret:X}."); diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs index af13805d..98454a77 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs @@ -1,19 +1,23 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; +using Penumbra.CrashHandler.Buffers; using Penumbra.Interop.PathResolving; +using Penumbra.Services; namespace Penumbra.Interop.Hooks.Animation; /// Characters load some of their voice lines or whatever with this function. public sealed unsafe class LoadCharacterSound : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly CrashHandlerService _crashHandler; - public LoadCharacterSound(HookManager hooks, GameState state, CollectionResolver collectionResolver) + public LoadCharacterSound(HookManager hooks, GameState state, CollectionResolver collectionResolver, CrashHandlerService crashHandler) { - _state = state; + _state = state; _collectionResolver = collectionResolver; + _crashHandler = crashHandler; Task = hooks.CreateHook("Load Character Sound", (nint)FFXIVClientStructs.FFXIV.Client.Game.Character.Character.VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, true); @@ -25,7 +29,9 @@ public sealed unsafe class LoadCharacterSound : FastHook {ret}."); _state.RestoreSoundData(last); diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs index 240c062e..69c22773 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs @@ -2,9 +2,11 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.Collections; +using Penumbra.CrashHandler.Buffers; using Penumbra.GameData; using Penumbra.Interop.PathResolving; using Penumbra.Interop.Structs; +using Penumbra.Services; using Penumbra.String; namespace Penumbra.Interop.Hooks.Animation; @@ -12,15 +14,18 @@ namespace Penumbra.Interop.Hooks.Animation; /// Load a VFX specifically for a character. public sealed unsafe class LoadCharacterVfx : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; - private readonly IObjectTable _objects; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly IObjectTable _objects; + private readonly CrashHandlerService _crashHandler; - public LoadCharacterVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects) + public LoadCharacterVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects, + CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; _objects = objects; + _crashHandler = crashHandler; Task = hooks.CreateHook("Load Character VFX", Sigs.LoadCharacterVfx, Detour, true); } @@ -45,6 +50,7 @@ public sealed unsafe class LoadCharacterVfx : FastHookGameObjectId:X}, {vfxParams->TargetCount}, {unk1}, {unk2}, {unk3}, {unk4} -> 0x{ret:X}."); diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index 2ca8ffe7..ade957b9 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -3,8 +3,10 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.Collections; +using Penumbra.CrashHandler; using Penumbra.GameData; using Penumbra.Interop.PathResolving; +using Penumbra.Services; namespace Penumbra.Interop.Hooks.Animation; @@ -14,19 +16,21 @@ namespace Penumbra.Interop.Hooks.Animation; /// public sealed unsafe class LoadTimelineResources : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; - private readonly ICondition _conditions; - private readonly IObjectTable _objects; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly ICondition _conditions; + private readonly IObjectTable _objects; + private readonly CrashHandlerService _crashHandler; public LoadTimelineResources(HookManager hooks, GameState state, CollectionResolver collectionResolver, ICondition conditions, - IObjectTable objects) + IObjectTable objects, CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; _conditions = conditions; _objects = objects; - Task = hooks.CreateHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, true); + _crashHandler = crashHandler; + Task = hooks.CreateHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, true); } public delegate ulong Delegate(nint timeline); @@ -39,7 +43,13 @@ public sealed unsafe class LoadTimelineResources : FastHook Called when some action timelines update. public sealed unsafe class ScheduleClipUpdate : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; - private readonly IObjectTable _objects; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly IObjectTable _objects; + private readonly CrashHandlerService _crashHandler; - public ScheduleClipUpdate(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects) + public ScheduleClipUpdate(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects, + CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; _objects = objects; + _crashHandler = crashHandler; Task = hooks.CreateHook("Schedule Clip Update", Sigs.ScheduleClipUpdate, Detour, true); } @@ -27,8 +32,9 @@ public sealed unsafe class ScheduleClipUpdate : FastHookSchedulerTimeline)); + var newData = LoadTimelineResources.GetDataFromTimeline(_objects, _collectionResolver, clipScheduler->SchedulerTimeline); + var last = _state.SetAnimationData(newData); + _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.ScheduleClipUpdate); Task.Result.Original(clipScheduler); _state.RestoreAnimationData(last); } diff --git a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs index 48931d73..6de3aeb0 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs @@ -1,21 +1,25 @@ -using FFXIVClientStructs.FFXIV.Client.Game; -using FFXIVClientStructs.FFXIV.Client.Game.Object; -using OtterGui.Services; -using Penumbra.GameData; +using FFXIVClientStructs.FFXIV.Client.Game; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.CrashHandler.Buffers; +using Penumbra.GameData; using Penumbra.Interop.PathResolving; +using Penumbra.Services; + +namespace Penumbra.Interop.Hooks.Animation; -namespace Penumbra.Interop.Hooks.Animation; - /// Seems to load character actions when zoning or changing class, maybe. public sealed unsafe class SomeActionLoad : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly CrashHandlerService _crashHandler; - public SomeActionLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver) + public SomeActionLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver, CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; + _crashHandler = crashHandler; Task = hooks.CreateHook("Some Action Load", Sigs.LoadSomeAction, Detour, true); } @@ -24,8 +28,10 @@ public sealed unsafe class SomeActionLoad : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void Detour(ActionTimelineManager* timelineManager) { - var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection((GameObject*)timelineManager->Parent, true)); + var newData = _collectionResolver.IdentifyCollection((GameObject*)timelineManager->Parent, true); + var last = _state.SetAnimationData(newData); Penumbra.Log.Excessive($"[Some Action Load] Invoked on 0x{(nint)timelineManager:X}."); + _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.ActionLoad); Task.Result.Original(timelineManager); _state.RestoreAnimationData(last); } diff --git a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs index 75caacee..3e60e62f 100644 --- a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs @@ -1,23 +1,28 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; +using Penumbra.CrashHandler.Buffers; using Penumbra.GameData; using Penumbra.Interop.PathResolving; +using Penumbra.Services; namespace Penumbra.Interop.Hooks.Animation; /// Unknown what exactly this is, but it seems to load a bunch of paps. public sealed unsafe class SomePapLoad : FastHook { - private readonly GameState _state; - private readonly CollectionResolver _collectionResolver; - private readonly IObjectTable _objects; + private readonly GameState _state; + private readonly CollectionResolver _collectionResolver; + private readonly IObjectTable _objects; + private readonly CrashHandlerService _crashHandler; - public SomePapLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects) + public SomePapLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects, + CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; _objects = objects; + _crashHandler = crashHandler; Task = hooks.CreateHook("Some PAP Load", Sigs.LoadSomePap, Detour, true); } @@ -33,8 +38,9 @@ public sealed unsafe class SomePapLoad : FastHook var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); if (actorIdx >= 0 && actorIdx < _objects.Length) { - var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection((GameObject*)_objects.GetObjectAddress(actorIdx), - true)); + var newData = _collectionResolver.IdentifyCollection((GameObject*)_objects.GetObjectAddress(actorIdx), true); + var last = _state.SetAnimationData(newData); + _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.PapLoad); Task.Result.Original(a1, a2, a3, a4); _state.RestoreAnimationData(last); return; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 01b3d680..796eae01 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,4 +1,4 @@ - + net7.0-windows preview @@ -69,8 +69,7 @@ - - + @@ -79,8 +78,10 @@ + + @@ -103,4 +104,4 @@ $(GitCommitHash) - \ No newline at end of file + diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs new file mode 100644 index 00000000..4e2bce0f --- /dev/null +++ b/Penumbra/Services/CrashHandlerService.cs @@ -0,0 +1,296 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Communication; +using Penumbra.CrashHandler; +using Penumbra.CrashHandler.Buffers; +using Penumbra.GameData.Actors; +using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Structs; +using Penumbra.String; +using Penumbra.String.Classes; +using FileMode = System.IO.FileMode; + +namespace Penumbra.Services; + +public sealed class CrashHandlerService : IDisposable, IService +{ + private readonly FilenameService _files; + private readonly CommunicatorService _communicator; + private readonly ActorManager _actors; + private readonly ResourceLoader _resourceLoader; + private readonly Configuration _config; + + public CrashHandlerService(FilenameService files, CommunicatorService communicator, ActorManager actors, ResourceLoader resourceLoader, + Configuration config) + { + _files = files; + _communicator = communicator; + _actors = actors; + _resourceLoader = resourceLoader; + _config = config; + + if (!_config.UseCrashHandler) + return; + + OpenEventWriter(); + LaunchCrashHandler(); + if (_eventWriter != null) + Subscribe(); + } + + public void Dispose() + { + CloseEventWriter(); + _eventWriter?.Dispose(); + if (_child != null) + { + _child.Kill(); + Penumbra.Log.Debug($"Killed crash handler child process {_child.Id}."); + } + + Unsubscribe(); + } + + private Process? _child; + private GameEventLogWriter? _eventWriter; + + public string CopiedExe = string.Empty; + + public string OriginalExe + => _files.CrashHandlerExe; + + public string LogPath + => _files.LogFileName; + + public int ChildProcessId + => _child?.Id ?? -1; + + public int ProcessId + => Environment.ProcessId; + + public bool IsRunning + => _eventWriter != null && _child is { HasExited: false }; + + public int ChildExitCode + => IsRunning ? 0 : _child?.ExitCode ?? 0; + + public void Enable() + { + if (_config.UseCrashHandler) + return; + + _config.UseCrashHandler = true; + _config.Save(); + OpenEventWriter(); + LaunchCrashHandler(); + if (_eventWriter != null) + Subscribe(); + } + + public void Disable() + { + if (!_config.UseCrashHandler) + return; + + _config.UseCrashHandler = false; + _config.Save(); + CloseEventWriter(); + CloseCrashHandler(); + Unsubscribe(); + } + + public JsonObject? Load(string fileName) + { + if (!File.Exists(fileName)) + return null; + + try + { + var data = File.ReadAllText(fileName); + return JsonNode.Parse(data) as JsonObject; + } + catch (Exception ex) + { + Penumbra.Log.Error($"Could not parse crash dump at {fileName}:\n{ex}"); + return null; + } + } + + public void CloseCrashHandler() + { + if (_child == null) + return; + + try + { + if (_child.HasExited) + return; + + _child.Kill(); + Penumbra.Log.Debug($"Closed Crash Handler at {CopiedExe}."); + } + catch (Exception ex) + { + _child = null; + Penumbra.Log.Debug($"Closed not close Crash Handler at {CopiedExe}:\n{ex}."); + } + } + + public void LaunchCrashHandler() + { + try + { + CloseCrashHandler(); + CopiedExe = CopyExecutables(); + var info = new ProcessStartInfo() + { + CreateNoWindow = true, + FileName = CopiedExe, + }; + info.ArgumentList.Add(_files.LogFileName); + info.ArgumentList.Add(Environment.ProcessId.ToString()); + _child = Process.Start(info); + if (_child == null) + throw new Exception("Child Process could not be created."); + + Penumbra.Log.Information($"Opened Crash Handler at {CopiedExe}, PID {_child.Id}."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Could not launch crash handler process:\n{ex}"); + CloseCrashHandler(); + _child = null; + } + } + + public JsonObject? Dump() + { + if (_eventWriter == null) + return null; + + try + { + using var reader = new GameEventLogReader(); + JsonObject jObj; + lock (_eventWriter) + { + jObj = reader.Dump("Manual Dump", Environment.ProcessId, 0); + } + + var logFile = _files.LogFileName; + using var s = File.Open(logFile, FileMode.Create); + using var jw = new Utf8JsonWriter(s, new JsonWriterOptions() { Indented = true }); + jObj.WriteTo(jw); + Penumbra.Log.Information($"Dumped crash handler memory to {logFile}."); + return jObj; + } + catch (Exception ex) + { + Penumbra.Log.Error($"Error dumping crash handler memory to file:\n{ex}"); + return null; + } + } + + private string CopyExecutables() + { + var parent = Path.GetDirectoryName(_files.CrashHandlerExe)!; + var folder = Path.Combine(parent, "temp"); + Directory.CreateDirectory(folder); + foreach (var file in Directory.EnumerateFiles(parent, "Penumbra.CrashHandler.*")) + File.Copy(file, Path.Combine(folder, Path.GetFileName(file)), true); + return Path.Combine(folder, Path.GetFileName(_files.CrashHandlerExe)); + } + + public void LogAnimation(nint character, ModCollection collection, AnimationInvocationType type) + { + if (_eventWriter == null) + return; + + var name = GetActorName(character); + lock (_eventWriter) + { + _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Name, type); + } + } + + private void OnCreatingCharacterBase(nint address, string collection, nint _1, nint _2, nint _3) + { + if (_eventWriter == null) + return; + + var name = GetActorName(address); + + lock (_eventWriter) + { + _eventWriter?.CharacterBase.WriteLine(address, name.Span, collection); + } + } + + private unsafe ByteString GetActorName(nint address) + { + var obj = (GameObject*)address; + if (obj == null) + return ByteString.FromSpanUnsafe("Unknown"u8, true, false, true); + + var id = _actors.FromObject(obj, out _, false, true, false); + return id.IsValid ? ByteString.FromStringUnsafe(id.Incognito(null), false) : + obj->Name[0] != 0 ? new ByteString(obj->Name) : ByteString.FromStringUnsafe($"Actor #{obj->ObjectIndex}", false); + } + + private unsafe void OnResourceLoaded(ResourceHandle* handle, Utf8GamePath originalPath, FullPath? manipulatedPath, ResolveData resolveData) + { + if (manipulatedPath == null || _eventWriter == null) + return; + + var dashIdx = manipulatedPath.Value.InternalName[0] == (byte)'|' ? manipulatedPath.Value.InternalName.IndexOf((byte)'|', 1) : -1; + if (dashIdx >= 0 && !Utf8GamePath.IsRooted(manipulatedPath.Value.InternalName.Substring(dashIdx + 1))) + return; + + var name = GetActorName(resolveData.AssociatedGameObject); + lock (_eventWriter) + { + _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Name, + manipulatedPath.Value.InternalName.Span, originalPath.Path.Span); + } + } + + private void CloseEventWriter() + { + if (_eventWriter == null) + return; + + _eventWriter.Dispose(); + _eventWriter = null; + Penumbra.Log.Debug("Closed Event Writer for crash handler."); + } + + private void OpenEventWriter() + { + try + { + CloseEventWriter(); + _eventWriter = new GameEventLogWriter(); + Penumbra.Log.Debug("Opened new Event Writer for crash handler."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Could not open Event Writer:\n{ex}"); + CloseEventWriter(); + } + } + + private unsafe void Subscribe() + { + _communicator.CreatingCharacterBase.Subscribe(OnCreatingCharacterBase, CreatingCharacterBase.Priority.CrashHandler); + _resourceLoader.ResourceLoaded += OnResourceLoaded; + } + + private unsafe void Unsubscribe() + { + _communicator.CreatingCharacterBase.Unsubscribe(OnCreatingCharacterBase); + _resourceLoader.ResourceLoaded -= OnResourceLoaded; + } +} diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 5f918a90..49b4cb42 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -15,6 +15,12 @@ public class FilenameService(DalamudPluginInterface pi) : IService public readonly string FilesystemFile = Path.Combine(pi.ConfigDirectory.FullName, "sort_order.json"); public readonly string ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); + public readonly string CrashHandlerExe = + Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Penumbra.CrashHandler.exe"); + + public readonly string LogFileName = + Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(pi.ConfigDirectory.FullName)!)!, "Penumbra.log"); + /// Obtain the path of a collection file given its name. public string CollectionFile(ModCollection collection) => CollectionFile(collection.Name); diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index 76fb8c96..ab0badf4 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -12,22 +12,13 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.Tabs; -public class ChangedItemsTab : ITab +public class ChangedItemsTab( + CollectionManager collectionManager, + CollectionSelectHeader collectionHeader, + ChangedItemDrawer drawer, + CommunicatorService communicator) + : ITab { - private readonly CollectionManager _collectionManager; - private readonly ChangedItemDrawer _drawer; - private readonly CollectionSelectHeader _collectionHeader; - private readonly CommunicatorService _communicator; - - public ChangedItemsTab(CollectionManager collectionManager, CollectionSelectHeader collectionHeader, ChangedItemDrawer drawer, - CommunicatorService communicator) - { - _collectionManager = collectionManager; - _collectionHeader = collectionHeader; - _drawer = drawer; - _communicator = communicator; - } - public ReadOnlySpan Label => "Changed Items"u8; @@ -36,8 +27,8 @@ public class ChangedItemsTab : ITab public void DrawContent() { - _collectionHeader.Draw(true); - _drawer.DrawTypeFilter(); + collectionHeader.Draw(true); + drawer.DrawTypeFilter(); var varWidth = DrawFilters(); using var child = ImRaii.Child("##changedItemsChild", -Vector2.One); if (!child) @@ -54,7 +45,7 @@ public class ChangedItemsTab : ITab ImGui.TableSetupColumn("mods", flags, varWidth - 130 * UiHelpers.Scale); ImGui.TableSetupColumn("id", flags, 130 * UiHelpers.Scale); - var items = _collectionManager.Active.Current.ChangedItems; + var items = collectionManager.Active.Current.ChangedItems; var rest = ImGuiClip.FilteredClippedDraw(items, skips, FilterChangedItem, DrawChangedItemColumn); ImGuiClip.DrawEndDummy(rest, height); } @@ -75,21 +66,21 @@ public class ChangedItemsTab : ITab /// Apply the current filters. private bool FilterChangedItem(KeyValuePair, object?)> item) - => _drawer.FilterChangedItem(item.Key, item.Value.Item2, _changedItemFilter) + => drawer.FilterChangedItem(item.Key, item.Value.Item2, _changedItemFilter) && (_changedItemModFilter.IsEmpty || item.Value.Item1.Any(m => m.Name.Contains(_changedItemModFilter))); /// Draw a full column for a changed item. private void DrawChangedItemColumn(KeyValuePair, object?)> item) { ImGui.TableNextColumn(); - _drawer.DrawCategoryIcon(item.Key, item.Value.Item2); + drawer.DrawCategoryIcon(item.Key, item.Value.Item2); ImGui.SameLine(); - _drawer.DrawChangedItem(item.Key, item.Value.Item2); + drawer.DrawChangedItem(item.Key, item.Value.Item2); ImGui.TableNextColumn(); DrawModColumn(item.Value.Item1); ImGui.TableNextColumn(); - _drawer.DrawModelData(item.Value.Item2); + drawer.DrawModelData(item.Value.Item2); } private void DrawModColumn(SingleArray mods) @@ -102,7 +93,7 @@ public class ChangedItemsTab : ITab if (ImGui.Selectable(first.Name, false, ImGuiSelectableFlags.None, new Vector2(0, ImGui.GetFrameHeight())) && ImGui.GetIO().KeyCtrl && first is Mod mod) - _communicator.SelectTab.Invoke(TabType.Mods, mod); + communicator.SelectTab.Invoke(TabType.Mods, mod); if (ImGui.IsItemHovered()) { diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index ad3fdb3d..9fd07f27 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -44,8 +44,8 @@ public class ConfigTabBar : IDisposable Watcher = watcher; OnScreen = onScreen; Messages = messages; - Tabs = new ITab[] - { + Tabs = + [ Settings, Collections, Mods, @@ -56,7 +56,7 @@ public class ConfigTabBar : IDisposable Resource, Watcher, Messages, - }; + ]; _communicator.SelectTab.Subscribe(OnSelectTab, Communication.SelectTab.Priority.ConfigTabBar); } diff --git a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs new file mode 100644 index 00000000..3d32d267 --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs @@ -0,0 +1,104 @@ +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using Penumbra.CrashHandler; + +namespace Penumbra.UI.Tabs.Debug; + +public static class CrashDataExtensions +{ + public static void DrawMeta(this CrashData data) + { + using (ImRaii.Group()) + { + ImGui.TextUnformatted(nameof(data.Mode)); + ImGui.TextUnformatted(nameof(data.CrashTime)); + ImGui.TextUnformatted(nameof(data.ExitCode)); + ImGui.TextUnformatted(nameof(data.ProcessId)); + ImGui.TextUnformatted(nameof(data.TotalModdedFilesLoaded)); + ImGui.TextUnformatted(nameof(data.TotalCharactersLoaded)); + ImGui.TextUnformatted(nameof(data.TotalVFXFuncsInvoked)); + } + + ImGui.SameLine(); + using (ImRaii.Group()) + { + ImGui.TextUnformatted(data.Mode); + ImGui.TextUnformatted(data.CrashTime.ToString()); + ImGui.TextUnformatted(data.ExitCode.ToString()); + ImGui.TextUnformatted(data.ProcessId.ToString()); + ImGui.TextUnformatted(data.TotalModdedFilesLoaded.ToString()); + ImGui.TextUnformatted(data.TotalCharactersLoaded.ToString()); + ImGui.TextUnformatted(data.TotalVFXFuncsInvoked.ToString()); + } + } + + public static void DrawCharacters(this CrashData data) + { + using var tree = ImRaii.TreeNode("Last Characters"); + if (!tree) + return; + + using var table = ImRaii.Table("##characterTable", 6, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInner); + if (!table) + return; + + ImGuiClip.ClippedDraw(data.LastCharactersLoaded, character => + { + ImGuiUtil.DrawTableColumn(character.Age.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(character.ThreadId.ToString()); + ImGuiUtil.DrawTableColumn(character.CharacterName); + ImGuiUtil.DrawTableColumn(character.CollectionName); + ImGuiUtil.DrawTableColumn(character.CharacterAddress); + ImGuiUtil.DrawTableColumn(character.Timestamp.ToString()); + }, ImGui.GetTextLineHeightWithSpacing()); + } + + public static void DrawFiles(this CrashData data) + { + using var tree = ImRaii.TreeNode("Last Files"); + if (!tree) + return; + + using var table = ImRaii.Table("##filesTable", 8, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInner); + if (!table) + return; + + ImGuiClip.ClippedDraw(data.LastModdedFilesLoaded, file => + { + ImGuiUtil.DrawTableColumn(file.Age.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(file.ThreadId.ToString()); + ImGuiUtil.DrawTableColumn(file.ActualFileName); + ImGuiUtil.DrawTableColumn(file.RequestedFileName); + ImGuiUtil.DrawTableColumn(file.CharacterName); + ImGuiUtil.DrawTableColumn(file.CollectionName); + ImGuiUtil.DrawTableColumn(file.CharacterAddress); + ImGuiUtil.DrawTableColumn(file.Timestamp.ToString()); + }, ImGui.GetTextLineHeightWithSpacing()); + } + + public static void DrawVfxInvocations(this CrashData data) + { + using var tree = ImRaii.TreeNode("Last VFX Invocations"); + if (!tree) + return; + + using var table = ImRaii.Table("##vfxTable", 7, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInner); + if (!table) + return; + + ImGuiClip.ClippedDraw(data.LastVfxFuncsInvoked, vfx => + { + ImGuiUtil.DrawTableColumn(vfx.Age.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(vfx.ThreadId.ToString()); + ImGuiUtil.DrawTableColumn(vfx.InvocationType); + ImGuiUtil.DrawTableColumn(vfx.CharacterName); + ImGuiUtil.DrawTableColumn(vfx.CollectionName); + ImGuiUtil.DrawTableColumn(vfx.CharacterAddress); + ImGuiUtil.DrawTableColumn(vfx.Timestamp.ToString()); + }, ImGui.GetTextLineHeightWithSpacing()); + } +} diff --git a/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs b/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs new file mode 100644 index 00000000..c8e7f001 --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs @@ -0,0 +1,136 @@ +using System.Text.Json; +using Dalamud.Interface.DragDrop; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.CrashHandler; +using Penumbra.Services; + +namespace Penumbra.UI.Tabs.Debug; + +public class CrashHandlerPanel(CrashHandlerService _service, Configuration _config, IDragDropManager _dragDrop) : IService +{ + private CrashData? _lastDump; + private string _lastLoadedFile = string.Empty; + private CrashData? _lastLoad; + private Exception? _lastLoadException; + + public void Draw() + { + DrawDropSource(); + DrawData(); + DrawDropTarget(); + } + + private void DrawData() + { + using var _ = ImRaii.Group(); + using var header = ImRaii.CollapsingHeader("Crash Handler"); + if (!header) + return; + + DrawButtons(); + DrawMainData(); + DrawObject("Last Manual Dump", _lastDump, null); + DrawObject(_lastLoadedFile.Length > 0 ? $"Loaded File ({_lastLoadedFile})###Loaded File" : "Loaded File", _lastLoad, + _lastLoadException); + } + + private void DrawMainData() + { + using var table = ImRaii.Table("##CrashHandlerTable", 2, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + PrintValue("Enabled", _config.UseCrashHandler); + PrintValue("Copied Executable Path", _service.CopiedExe); + PrintValue("Original Executable Path", _service.OriginalExe); + PrintValue("Log File Path", _service.LogPath); + PrintValue("XIV Process ID", _service.ProcessId.ToString()); + PrintValue("Crash Handler Running", _service.IsRunning.ToString()); + PrintValue("Crash Handler Process ID", _service.ChildProcessId.ToString()); + PrintValue("Crash Handler Exit Code", _service.ChildExitCode.ToString()); + } + + private void DrawButtons() + { + if (ImGui.Button("Dump Crash Handler Memory")) + _lastDump = _service.Dump()?.Deserialize(); + + if (ImGui.Button("Enable")) + _service.Enable(); + + ImGui.SameLine(); + if (ImGui.Button("Disable")) + _service.Disable(); + + if (ImGui.Button("Shutdown Crash Handler")) + _service.CloseCrashHandler(); + ImGui.SameLine(); + if (ImGui.Button("Relaunch Crash Handler")) + _service.LaunchCrashHandler(); + } + + private void DrawDropSource() + { + _dragDrop.CreateImGuiSource("LogDragDrop", m => m.Files.Any(f => f.EndsWith("Penumbra.log")), m => + { + ImGui.TextUnformatted("Dragging Penumbra.log for import."); + return true; + }); + } + + private void DrawDropTarget() + { + if (!_dragDrop.CreateImGuiTarget("LogDragDrop", out var files, out _)) + return; + + var file = files.FirstOrDefault(f => f.EndsWith("Penumbra.log")); + if (file == null) + return; + + _lastLoadedFile = file; + try + { + var jObj = _service.Load(file); + _lastLoad = jObj?.Deserialize(); + _lastLoadException = null; + } + catch (Exception ex) + { + _lastLoad = null; + _lastLoadException = ex; + } + } + + private static void DrawObject(string name, CrashData? data, Exception? ex) + { + using var tree = ImRaii.TreeNode(name); + if (!tree) + return; + + if (ex != null) + { + ImGuiUtil.TextWrapped(ex.ToString()); + return; + } + + if (data == null) + { + ImGui.TextUnformatted("Nothing loaded."); + return; + } + + data.DrawMeta(); + data.DrawFiles(); + data.DrawCharacters(); + data.DrawVfxInvocations(); + } + + private static void PrintValue(string label, in T data) + { + ImGuiUtil.DrawTableColumn(label); + ImGuiUtil.DrawTableColumn(data?.ToString() ?? "NULL"); + } +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index f4ddbe31..ab7ccf0c 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -53,7 +53,7 @@ public class Diagnostics(IServiceProvider provider) foreach (var type in typeof(ActorManager).Assembly.GetTypes() .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncDataContainer)))) { - var container = (IAsyncDataContainer) provider.GetRequiredService(type); + var container = (IAsyncDataContainer)provider.GetRequiredService(type); ImGuiUtil.DrawTableColumn(container.Name); ImGuiUtil.DrawTableColumn(container.Time.ToString()); ImGuiUtil.DrawTableColumn(Functions.HumanReadableSize(container.Memory)); @@ -88,18 +88,22 @@ public class DebugTab : Window, ITab private readonly TextureManager _textureManager; private readonly ShaderReplacementFixer _shaderReplacementFixer; private readonly RedrawService _redraws; - private readonly DictEmote _emotes; + private readonly DictEmote _emotes; private readonly Diagnostics _diagnostics; private readonly IObjectTable _objects; private readonly IClientState _clientState; private readonly IpcTester _ipcTester; + private readonly CrashHandlerPanel _crashHandlerPanel; - public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, IObjectTable objects, IClientState clientState, - ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, CharacterUtility characterUtility, ResidentResourceManager residentResources, + public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, IObjectTable objects, + IClientState clientState, + ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, + CharacterUtility characterUtility, ResidentResourceManager residentResources, ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, - TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester) + TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, + Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -134,7 +138,8 @@ public class DebugTab : Window, ITab _redraws = redraws; _emotes = emotes; _diagnostics = diagnostics; - _ipcTester = ipcTester; + _ipcTester = ipcTester; + _crashHandlerPanel = crashHandlerPanel; _objects = objects; _clientState = clientState; } @@ -158,6 +163,9 @@ public class DebugTab : Window, ITab return; DrawDebugTabGeneral(); + ImGui.NewLine(); + _crashHandlerPanel.Draw(); + ImGui.NewLine(); _diagnostics.DrawDiagnostics(); DrawPerformanceTab(); ImGui.NewLine(); @@ -257,6 +265,7 @@ public class DebugTab : Window, ITab } } + var issues = _modManager.WithIndex().Count(p => p.Index != p.Value.Index); using (var tree = TreeNode($"Mods ({issues} Issues)###Mods")) { @@ -394,7 +403,7 @@ public class DebugTab : Window, ITab private void DrawPerformanceTab() { ImGui.NewLine(); - if (ImGui.CollapsingHeader("Performance")) + if (!ImGui.CollapsingHeader("Performance")) return; using (var start = TreeNode("Startup Performance", ImGuiTreeNodeFlags.DefaultOpen)) diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index 8ef6c30e..37561000 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -8,31 +8,22 @@ using Penumbra.Collections; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.Meta.Manipulations; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.UI.Classes; namespace Penumbra.UI.Tabs; -public class EffectiveTab : ITab +public class EffectiveTab(CollectionManager collectionManager, CollectionSelectHeader collectionHeader) + : ITab { - private readonly CollectionManager _collectionManager; - private readonly CollectionSelectHeader _collectionHeader; - - public EffectiveTab(CollectionManager collectionManager, CollectionSelectHeader collectionHeader) - { - _collectionManager = collectionManager; - _collectionHeader = collectionHeader; - } - public ReadOnlySpan Label => "Effective Changes"u8; public void DrawContent() { SetupEffectiveSizes(); - _collectionHeader.Draw(true); + collectionHeader.Draw(true); DrawFilters(); using var child = ImRaii.Child("##EffectiveChangesTab", -Vector2.One, false); if (!child) @@ -48,7 +39,7 @@ public class EffectiveTab : ITab ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, _effectiveArrowLength); ImGui.TableSetupColumn("##file", ImGuiTableColumnFlags.WidthFixed, _effectiveRightTextLength); - DrawEffectiveRows(_collectionManager.Active.Current, skips, height, + DrawEffectiveRows(collectionManager.Active.Current, skips, height, _effectiveFilePathFilter.Length > 0 || _effectiveGamePathFilter.Length > 0); } diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 9f070d35..d111c465 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -17,68 +17,53 @@ using Penumbra.Collections.Manager; namespace Penumbra.UI.Tabs; -public class ModsTab : ITab +public class ModsTab( + ModManager modManager, + CollectionManager collectionManager, + ModFileSystemSelector selector, + ModPanel panel, + TutorialService tutorial, + RedrawService redrawService, + Configuration config, + IClientState clientState, + CollectionSelectHeader collectionHeader, + ITargetManager targets, + IObjectTable objectTable) + : ITab { - private readonly ModFileSystemSelector _selector; - private readonly ModPanel _panel; - private readonly TutorialService _tutorial; - private readonly ModManager _modManager; - private readonly ActiveCollections _activeCollections; - private readonly RedrawService _redrawService; - private readonly Configuration _config; - private readonly IClientState _clientState; - private readonly CollectionSelectHeader _collectionHeader; - private readonly ITargetManager _targets; - private readonly IObjectTable _objectTable; - - public ModsTab(ModManager modManager, CollectionManager collectionManager, ModFileSystemSelector selector, ModPanel panel, - TutorialService tutorial, RedrawService redrawService, Configuration config, IClientState clientState, - CollectionSelectHeader collectionHeader, ITargetManager targets, IObjectTable objectTable) - { - _modManager = modManager; - _activeCollections = collectionManager.Active; - _selector = selector; - _panel = panel; - _tutorial = tutorial; - _redrawService = redrawService; - _config = config; - _clientState = clientState; - _collectionHeader = collectionHeader; - _targets = targets; - _objectTable = objectTable; - } + private readonly ActiveCollections _activeCollections = collectionManager.Active; public bool IsVisible - => _modManager.Valid; + => modManager.Valid; public ReadOnlySpan Label => "Mods"u8; public void DrawHeader() - => _tutorial.OpenTutorial(BasicTutorialSteps.Mods); + => tutorial.OpenTutorial(BasicTutorialSteps.Mods); public Mod SelectMod { - set => _selector.SelectByValue(value); + set => selector.SelectByValue(value); } public void DrawContent() { try { - _selector.Draw(GetModSelectorSize(_config)); + selector.Draw(GetModSelectorSize(config)); ImGui.SameLine(); using var group = ImRaii.Group(); - _collectionHeader.Draw(false); + collectionHeader.Draw(false); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero); - using (var child = ImRaii.Child("##ModsTabMod", new Vector2(-1, _config.HideRedrawBar ? 0 : -ImGui.GetFrameHeight()), + using (var child = ImRaii.Child("##ModsTabMod", new Vector2(-1, config.HideRedrawBar ? 0 : -ImGui.GetFrameHeight()), true, ImGuiWindowFlags.HorizontalScrollbar)) { style.Pop(); if (child) - _panel.Draw(); + panel.Draw(); style.Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero); } @@ -89,14 +74,14 @@ public class ModsTab : ITab catch (Exception e) { Penumbra.Log.Error($"Exception thrown during ModPanel Render:\n{e}"); - Penumbra.Log.Error($"{_modManager.Count} Mods\n" + Penumbra.Log.Error($"{modManager.Count} Mods\n" + $"{_activeCollections.Current.AnonymizedName} Current Collection\n" + $"{_activeCollections.Current.Settings.Count} Settings\n" - + $"{_selector.SortMode.Name} Sort Mode\n" - + $"{_selector.SelectedLeaf?.Name ?? "NULL"} Selected Leaf\n" - + $"{_selector.Selected?.Name ?? "NULL"} Selected Mod\n" + + $"{selector.SortMode.Name} Sort Mode\n" + + $"{selector.SelectedLeaf?.Name ?? "NULL"} Selected Leaf\n" + + $"{selector.Selected?.Name ?? "NULL"} Selected Mod\n" + $"{string.Join(", ", _activeCollections.Current.DirectlyInheritsFrom.Select(c => c.AnonymizedName))} Inheritances\n" - + $"{_selector.SelectedSettingCollection.AnonymizedName} Collection\n"); + + $"{selector.SelectedSettingCollection.AnonymizedName} Collection\n"); } } @@ -115,9 +100,9 @@ public class ModsTab : ITab private void DrawRedrawLine() { - if (_config.HideRedrawBar) + if (config.HideRedrawBar) { - _tutorial.SkipTutorial(BasicTutorialSteps.Redrawing); + tutorial.SkipTutorial(BasicTutorialSteps.Redrawing); return; } @@ -135,15 +120,15 @@ public class ModsTab : ITab } var hovered = ImGui.IsItemHovered(); - _tutorial.OpenTutorial(BasicTutorialSteps.Redrawing); + tutorial.OpenTutorial(BasicTutorialSteps.Redrawing); if (hovered) ImGui.SetTooltip($"The supported modifiers for '/penumbra redraw' are:\n{TutorialService.SupportedRedrawModifiers}"); using var id = ImRaii.PushId("Redraw"); - using var disabled = ImRaii.Disabled(_clientState.LocalPlayer == null); + using var disabled = ImRaii.Disabled(clientState.LocalPlayer == null); ImGui.SameLine(); var buttonWidth = frameHeight with { X = ImGui.GetContentRegionAvail().X / 5 }; - var tt = _objectTable.GetObjectAddress(0) == nint.Zero + var tt = objectTable.GetObjectAddress(0) == nint.Zero ? "\nCan only be used when you are logged in and your character is available." : string.Empty; DrawButton(buttonWidth, "All", string.Empty, tt); @@ -151,13 +136,13 @@ public class ModsTab : ITab DrawButton(buttonWidth, "Self", "self", tt); ImGui.SameLine(); - tt = _targets.Target == null && _targets.GPoseTarget == null + tt = targets.Target == null && targets.GPoseTarget == null ? "\nCan only be used when you have a target." : string.Empty; DrawButton(buttonWidth, "Target", "target", tt); ImGui.SameLine(); - tt = _targets.FocusTarget == null + tt = targets.FocusTarget == null ? "\nCan only be used when you have a focus target." : string.Empty; DrawButton(buttonWidth, "Focus", "focus", tt); @@ -176,9 +161,9 @@ public class ModsTab : ITab if (ImGui.Button(label, size)) { if (lower.Length > 0) - _redrawService.RedrawObject(lower, RedrawType.Redraw); + redrawService.RedrawObject(lower, RedrawType.Redraw); else - _redrawService.RedrawAll(RedrawType.Redraw); + redrawService.RedrawAll(RedrawType.Redraw); } } diff --git a/Penumbra/UI/Tabs/OnScreenTab.cs b/Penumbra/UI/Tabs/OnScreenTab.cs index 8d323baf..09772d8e 100644 --- a/Penumbra/UI/Tabs/OnScreenTab.cs +++ b/Penumbra/UI/Tabs/OnScreenTab.cs @@ -7,7 +7,7 @@ namespace Penumbra.UI.Tabs; public class OnScreenTab : ITab { private readonly Configuration _config; - private ResourceTreeViewer _viewer; + private readonly ResourceTreeViewer _viewer; public OnScreenTab(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer) { diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index 6f3dec30..bbb0561b 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -12,24 +12,14 @@ using Penumbra.String.Classes; namespace Penumbra.UI.Tabs; -public class ResourceTab : ITab +public class ResourceTab(Configuration config, ResourceManagerService resourceManager, ISigScanner sigScanner) + : ITab { - private readonly Configuration _config; - private readonly ResourceManagerService _resourceManager; - private readonly ISigScanner _sigScanner; - - public ResourceTab(Configuration config, ResourceManagerService resourceManager, ISigScanner sigScanner) - { - _config = config; - _resourceManager = resourceManager; - _sigScanner = sigScanner; - } - public ReadOnlySpan Label => "Resource Manager"u8; public bool IsVisible - => _config.DebugMode; + => config.DebugMode; /// Draw a tab to iterate over the main resource maps and see what resources are currently loaded. public void DrawContent() @@ -44,15 +34,15 @@ public class ResourceTab : ITab unsafe { - _resourceManager.IterateGraphs(DrawCategoryContainer); + resourceManager.IterateGraphs(DrawCategoryContainer); } ImGui.NewLine(); unsafe { ImGui.TextUnformatted( - $"Static Address: 0x{(ulong)_resourceManager.ResourceManagerAddress:X} (+0x{(ulong)_resourceManager.ResourceManagerAddress - (ulong)_sigScanner.Module.BaseAddress:X})"); - ImGui.TextUnformatted($"Actual Address: 0x{(ulong)_resourceManager.ResourceManager:X}"); + $"Static Address: 0x{(ulong)resourceManager.ResourceManagerAddress:X} (+0x{(ulong)resourceManager.ResourceManagerAddress - (ulong)sigScanner.Module.BaseAddress:X})"); + ImGui.TextUnformatted($"Actual Address: 0x{(ulong)resourceManager.ResourceManager:X}"); } } @@ -82,7 +72,7 @@ public class ResourceTab : ITab ImGui.TableSetupColumn("Refs", ImGuiTableColumnFlags.WidthFixed, _refsColumnWidth); ImGui.TableHeadersRow(); - _resourceManager.IterateResourceMap(map, (hash, r) => + resourceManager.IterateResourceMap(map, (hash, r) => { // Filter unwanted names. if (_resourceManagerFilter.Length != 0 @@ -125,7 +115,7 @@ public class ResourceTab : ITab if (tree) { SetTableWidths(); - _resourceManager.IterateExtMap(map, (ext, m) => DrawResourceMap(category, ext, m)); + resourceManager.IterateExtMap(map, (ext, m) => DrawResourceMap(category, ext, m)); } } diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index cb873592..d0e8fa1a 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -11,18 +11,6 @@ "Unosquare.Swan.Lite": "3.0.0" } }, - "Microsoft.CodeAnalysis.Common": { - "type": "Direct", - "requested": "[4.8.0, )", - "resolved": "4.8.0", - "contentHash": "/jR+e/9aT+BApoQJABlVCKnnggGQbvGh7BKq2/wI1LamxC+LbzhcLj4Vj7gXCofl1n4E521YfF9w0WcASGg/KA==", - "dependencies": { - "Microsoft.CodeAnalysis.Analyzers": "3.3.4", - "System.Collections.Immutable": "7.0.0", - "System.Reflection.Metadata": "7.0.0", - "System.Runtime.CompilerServices.Unsafe": "6.0.0" - } - }, "Microsoft.Extensions.DependencyInjection": { "type": "Direct", "requested": "[7.0.0, )", @@ -55,29 +43,15 @@ }, "SixLabors.ImageSharp": { "type": "Direct", - "requested": "[2.1.2, )", - "resolved": "2.1.2", - "contentHash": "In0pC521LqJXJXZgFVHegvSzES10KkKRN31McxqA1+fKtKsNe+EShWavBFQnKRlXCdeAmfx/wDjLILbvCaq+8Q==", - "dependencies": { - "System.Runtime.CompilerServices.Unsafe": "5.0.0", - "System.Text.Encoding.CodePages": "5.0.0" - } - }, - "Microsoft.CodeAnalysis.Analyzers": { - "type": "Transitive", - "resolved": "3.3.4", - "contentHash": "AxkxcPR+rheX0SmvpLVIGLhOUXAKG56a64kV9VQZ4y9gR9ZmPXnqZvHJnmwLSwzrEP6junUF11vuc+aqo5r68g==" + "requested": "[3.1.3, )", + "resolved": "3.1.3", + "contentHash": "wybtaqZQ1ZRZ4ZeU+9h+PaSeV14nyiGKIy7qRbDfSHzHq4ybqyOcjoifeaYbiKLO1u+PVxLBuy7MF/DMmwwbfg==" }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", "resolved": "7.0.0", "contentHash": "h3j/QfmFN4S0w4C2A6X7arXij/M/OVw3uQHSOFxnND4DyAzO1F9eMX7Eti7lU/OkSthEE0WzRsfT/Dmx86jzCw==" }, - "Microsoft.NETCore.Platforms": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "VyPlqzH2wavqquTcYpkIIAQ6WdenuKoFN0BdYBbCWsclXacSOHNQn66Gt4z5NBqEYW0FAPm5rlvki9ZiCij5xQ==" - }, "SharpGLTF.Runtime": { "type": "Transitive", "resolved": "1.0.0-alpha0030", @@ -86,32 +60,6 @@ "SharpGLTF.Core": "1.0.0-alpha0030" } }, - "System.Collections.Immutable": { - "type": "Transitive", - "resolved": "7.0.0", - "contentHash": "dQPcs0U1IKnBdRDBkrCTi1FoajSTBzLcVTpjO4MBCMC7f4pDOIPzgBoX8JjG7X6uZRJ8EBxsi8+DR1JuwjnzOQ==" - }, - "System.Reflection.Metadata": { - "type": "Transitive", - "resolved": "7.0.0", - "contentHash": "MclTG61lsD9sYdpNz9xsKBzjsmsfCtcMZYXz/IUr2zlhaTaABonlr1ESeompTgM+Xk+IwtGYU7/voh3YWB/fWw==", - "dependencies": { - "System.Collections.Immutable": "7.0.0" - } - }, - "System.Runtime.CompilerServices.Unsafe": { - "type": "Transitive", - "resolved": "6.0.0", - "contentHash": "/iUeP3tq1S0XdNNoMz5C9twLSrM/TH+qElHkXWaPvuNOt+99G75NrV0OS2EqHx5wMN7popYjpc8oTjC1y16DLg==" - }, - "System.Text.Encoding.CodePages": { - "type": "Transitive", - "resolved": "5.0.0", - "contentHash": "NyscU59xX6Uo91qvhOs2Ccho3AR2TnZPomo1Z0K6YpyztBPM/A5VbkzOO19sy3A3i1TtEnTxA7bCe3Us+r5MWg==", - "dependencies": { - "Microsoft.NETCore.Platforms": "5.0.0" - } - }, "System.ValueTuple": { "type": "Transitive", "resolved": "4.5.0", @@ -134,11 +82,14 @@ "penumbra.api": { "type": "Project" }, + "penumbra.crashhandler": { + "type": "Project" + }, "penumbra.gamedata": { "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[1.0.13, )", + "Penumbra.Api": "[1.0.14, )", "Penumbra.String": "[1.0.4, )" } }, From 8318a4bd84786858c67171261f18f55a6a8a6cc7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Mar 2024 16:20:46 +0100 Subject: [PATCH 0476/1381] Compatibility fix. --- Penumbra/Import/Models/Export/MaterialExporter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index f17fdaa2..82e13eb9 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -53,7 +53,7 @@ public class MaterialExporter var normal = material.Textures[TextureUsage.SamplerNormal]; var operation = new ProcessCharacterNormalOperation(normal, table); - ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds(), in operation); + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds, in operation); // Check if full textures are provided, and merge in if available. var baseColor = operation.BaseColor; @@ -199,7 +199,7 @@ public class MaterialExporter small.Mutate(context => context.Resize(large.Width, large.Height)); var operation = new MultiplyOperation(target, multiplier); - ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, target.Bounds(), in operation); + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, target.Bounds, in operation); } } From 4fc763c9aa719948d41b4075e684e0647c5e96de Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Mar 2024 16:21:06 +0100 Subject: [PATCH 0477/1381] Keep first empty option in its desired location. --- Penumbra/Import/TexToolsImporter.ModPack.cs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 94a5e5ac..7c4b94d8 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using OtterGui; using Penumbra.Api.Enums; using Penumbra.Import.Structs; using Penumbra.Mods; @@ -35,7 +36,8 @@ public partial class TexToolsImporter var modList = modListRaw.Select(m => JsonConvert.DeserializeObject(m, JsonSettings)!).ToList(); - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetFileNameWithoutExtension(modPackFile.Name), _config.ReplaceNonAsciiOnImport, true); + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetFileNameWithoutExtension(modPackFile.Name), + _config.ReplaceNonAsciiOnImport, true); // Create a new ModMeta from the TTMP mod list info _modManager.DataEditor.CreateMeta(_currentModDirectory, _currentModName, DefaultTexToolsData.Author, DefaultTexToolsData.Description, null, null); @@ -193,15 +195,17 @@ public partial class TexToolsImporter optionIdx += maxOptions; // Handle empty options for single select groups without creating a folder for them. - // We only want one of those at most, and it should usually be the first option. + // We only want one of those at most. if (group.SelectionType == GroupType.Single) { - var empty = group.OptionList.FirstOrDefault(o => o.Name.Length > 0 && o.ModsJsons.Length == 0); - if (empty != null) + var idx = group.OptionList.IndexOf(o => o.Name.Length > 0 && o.ModsJsons.Length == 0); + if (idx >= 0) { - _currentOptionName = empty.Name; - options.Insert(0, ModCreator.CreateEmptySubMod(empty.Name)); - defaultSettings = defaultSettings == null ? 0 : defaultSettings.Value + 1; + var option = group.OptionList[idx]; + _currentOptionName = option.Name; + options.Insert(idx, ModCreator.CreateEmptySubMod(option.Name)); + if (option.IsChecked) + defaultSettings = (uint) idx; } } From 50f81cc889999c2cee7634a72d547eeecd3516b7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Mar 2024 16:21:23 +0100 Subject: [PATCH 0478/1381] Skip locals init. --- .../MaterialPreview/LiveColorTablePreviewer.cs | 1 + .../ResolveContext.PathResolution.cs | 4 +++- .../Interop/ResourceTree/ResolveContext.cs | 1 + Penumbra/Mods/Editor/DuplicateManager.cs | 18 +++++++++--------- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index 801c3bf0..a8e4ea4d 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -62,6 +62,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase _updatePending = true; } + [SkipLocalsInit] private void OnFrameworkUpdate(IFramework _) { if (!_updatePending) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index cf939292..d5b4fa39 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -89,6 +89,7 @@ internal partial record ResolveContext }; } + [SkipLocalsInit] private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { var variant = ResolveMaterialVariant(imc, Equipment.Variant); @@ -100,6 +101,7 @@ internal partial record ResolveContext return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; } + [SkipLocalsInit] private unsafe Utf8GamePath ResolveWeaponMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { var setIdHigh = Equipment.Set.Id / 100; @@ -168,7 +170,7 @@ internal partial record ResolveContext { var modelPosition = modelPath.IndexOf("/model/"u8); if (modelPosition < 0) - return Span.Empty; + return []; var baseDirectory = modelPath[..modelPosition]; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 0637cba6..d1701f47 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -54,6 +54,7 @@ internal unsafe partial record ResolveContext( return GetOrCreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); } + [SkipLocalsInit] private ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool dx11) { if (resourceHandle == null) diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index dad05102..77d10cc4 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -7,8 +7,8 @@ namespace Penumbra.Mods.Editor; public class DuplicateManager(ModManager modManager, SaveService saveService, Configuration config) { - private readonly SHA256 _hasher = SHA256.Create(); - private readonly List<(FullPath[] Paths, long Size, byte[] Hash)> _duplicates = []; + private readonly SHA256 _hasher = SHA256.Create(); + private readonly List<(FullPath[] Paths, long Size, byte[] Hash)> _duplicates = []; public IReadOnlyList<(FullPath[] Paths, long Size, byte[] Hash)> Duplicates => _duplicates; @@ -164,17 +164,17 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co } /// Check if two files are identical on a binary level. Returns true if they are identical. + [SkipLocalsInit] public static unsafe bool CompareFilesDirectly(FullPath f1, FullPath f2) { + const int size = 256; if (!f1.Exists || !f2.Exists) return false; - using var s1 = File.OpenRead(f1.FullName); - using var s2 = File.OpenRead(f2.FullName); - var buffer1 = stackalloc byte[256]; - var buffer2 = stackalloc byte[256]; - var span1 = new Span(buffer1, 256); - var span2 = new Span(buffer2, 256); + using var s1 = File.OpenRead(f1.FullName); + using var s2 = File.OpenRead(f2.FullName); + Span span1 = stackalloc byte[size]; + Span span2 = stackalloc byte[size]; while (true) { @@ -186,7 +186,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co if (!span1[..bytes1].SequenceEqual(span2[..bytes2])) return false; - if (bytes1 < 256) + if (bytes1 < size) return true; } } From c1a9c798ae844c79023a1248fa4ce80731dcf50b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Mar 2024 16:22:07 +0100 Subject: [PATCH 0479/1381] auto format. --- Penumbra/Penumbra.cs | 71 ++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 67f523ba..b532339f 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -19,7 +19,6 @@ using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; using Penumbra.GameData.Enums; -using Penumbra.Interop.Structs; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; @@ -74,8 +73,8 @@ public class Penumbra : IDalamudPlugin _tempCollections = _services.GetService(); _redrawService = _services.GetService(); _communicatorService = _services.GetService(); - _services.GetService(); // Initialize because not required anywhere else. - _services.GetService(); // Initialize because not required anywhere else. + _services.GetService(); // Initialize because not required anywhere else. + _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); _services.GetService(); _services.GetService(); @@ -245,38 +244,38 @@ public class Penumbra : IDalamudPlugin return sb.ToString(); } - private static string CollectLocaleEnvironmentVariables() - { - var variableNames = new List(); - var variables = new Dictionary(StringComparer.Ordinal); - foreach (DictionaryEntry variable in Environment.GetEnvironmentVariables()) - { - var key = (string)variable.Key; - if (key.Equals("LANG", StringComparison.Ordinal) || key.StartsWith("LC_", StringComparison.Ordinal)) - { - variableNames.Add(key); - variables.Add(key, ((string?)variable.Value) ?? string.Empty); - } - } - - variableNames.Sort(); - - var pos = variableNames.IndexOf("LC_ALL"); - if (pos > 0) // If it's == 0, we're going to do a no-op. - { - variableNames.RemoveAt(pos); - variableNames.Insert(0, "LC_ALL"); - } - - pos = variableNames.IndexOf("LANG"); - if (pos >= 0 && pos < variableNames.Count - 1) - { - variableNames.RemoveAt(pos); - variableNames.Add("LANG"); - } - - return variableNames.Count == 0 - ? "None" - : string.Join(", ", variableNames.Select(name => $"`{name}={variables[name]}`")); + private static string CollectLocaleEnvironmentVariables() + { + var variableNames = new List(); + var variables = new Dictionary(StringComparer.Ordinal); + foreach (DictionaryEntry variable in Environment.GetEnvironmentVariables()) + { + var key = (string)variable.Key; + if (key.Equals("LANG", StringComparison.Ordinal) || key.StartsWith("LC_", StringComparison.Ordinal)) + { + variableNames.Add(key); + variables.Add(key, (string?)variable.Value ?? string.Empty); + } + } + + variableNames.Sort(); + + var pos = variableNames.IndexOf("LC_ALL"); + if (pos > 0) // If it's == 0, we're going to do a no-op. + { + variableNames.RemoveAt(pos); + variableNames.Insert(0, "LC_ALL"); + } + + pos = variableNames.IndexOf("LANG"); + if (pos >= 0 && pos < variableNames.Count - 1) + { + variableNames.RemoveAt(pos); + variableNames.Add("LANG"); + } + + return variableNames.Count == 0 + ? "None" + : string.Join(", ", variableNames.Select(name => $"`{name}={variables[name]}`")); } } From 7cb50030f97d353b3870d41c4edb00e082b2c177 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Mar 2024 16:58:02 +0100 Subject: [PATCH 0480/1381] Fix some stuff, add versions. --- Penumbra.CrashHandler/CrashData.cs | 12 +++++++++--- Penumbra.CrashHandler/GameEventLogReader.cs | 12 +++++++----- Penumbra.CrashHandler/Program.cs | 4 ++-- Penumbra/Services/CrashHandlerService.cs | 18 +++++++++++------- Penumbra/Services/ValidityChecker.cs | 13 ++++++++++--- Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs | 6 ++++++ 6 files changed, 45 insertions(+), 20 deletions(-) diff --git a/Penumbra.CrashHandler/CrashData.cs b/Penumbra.CrashHandler/CrashData.cs index 956a3db7..cdac103f 100644 --- a/Penumbra.CrashHandler/CrashData.cs +++ b/Penumbra.CrashHandler/CrashData.cs @@ -24,6 +24,12 @@ public class CrashData /// The time this crash data was generated. public DateTimeOffset CrashTime { get; set; } = DateTimeOffset.UnixEpoch; + /// Penumbra's Version when this crash data was created. + public string Version { get; set; } = string.Empty; + + /// The Game's Version when this crash data was created. + public string GameVersion { get; set; } = string.Empty; + /// The FFXIV process ID when this data was generated. public int ProcessId { get; set; } = 0; @@ -52,11 +58,11 @@ public class CrashData => LastVfxFuncsInvoked.Count == 0 ? default : LastVfxFuncsInvoked[0]; /// A collection of the last few characters loaded before this crash data was generated. - public List LastCharactersLoaded { get; } = []; + public List LastCharactersLoaded { get; set; } = []; /// A collection of the last few modded files loaded before this crash data was generated. - public List LastModdedFilesLoaded { get; } = []; + public List LastModdedFilesLoaded { get; set; } = []; /// A collection of the last few vfx functions invoked before this crash data was generated. - public List LastVfxFuncsInvoked { get; } = []; + public List LastVfxFuncsInvoked { get; set; } = []; } diff --git a/Penumbra.CrashHandler/GameEventLogReader.cs b/Penumbra.CrashHandler/GameEventLogReader.cs index 283be526..1ae49fa5 100644 --- a/Penumbra.CrashHandler/GameEventLogReader.cs +++ b/Penumbra.CrashHandler/GameEventLogReader.cs @@ -25,15 +25,17 @@ public sealed class GameEventLogReader : IDisposable } - public JsonObject Dump(string mode, int processId, int exitCode) + public JsonObject Dump(string mode, int processId, int exitCode, string version, string gameVersion) { var crashTime = DateTimeOffset.UtcNow; var obj = new JsonObject { - [nameof(CrashData.Mode)] = mode, - [nameof(CrashData.CrashTime)] = DateTimeOffset.UtcNow, - [nameof(CrashData.ProcessId)] = processId, - [nameof(CrashData.ExitCode)] = exitCode, + [nameof(CrashData.Mode)] = mode, + [nameof(CrashData.CrashTime)] = DateTimeOffset.UtcNow, + [nameof(CrashData.ProcessId)] = processId, + [nameof(CrashData.ExitCode)] = exitCode, + [nameof(CrashData.Version)] = version, + [nameof(CrashData.GameVersion)] = gameVersion, }; foreach (var (reader, singular, _) in Readers) diff --git a/Penumbra.CrashHandler/Program.cs b/Penumbra.CrashHandler/Program.cs index e4a46348..518e2d04 100644 --- a/Penumbra.CrashHandler/Program.cs +++ b/Penumbra.CrashHandler/Program.cs @@ -7,7 +7,7 @@ public class CrashHandler { public static void Main(string[] args) { - if (args.Length < 2 || !int.TryParse(args[1], out var pid)) + if (args.Length < 4 || !int.TryParse(args[1], out var pid)) return; try @@ -17,7 +17,7 @@ public class CrashHandler parent.WaitForExit(); var exitCode = parent.ExitCode; - var obj = reader.Dump("Crash", pid, exitCode); + var obj = reader.Dump("Crash", pid, exitCode, args[2], args[3]); using var fs = File.Open(args[0], FileMode.Create); using var w = new Utf8JsonWriter(fs, new JsonWriterOptions { Indented = true }); obj.WriteTo(w, new JsonSerializerOptions() { WriteIndented = true }); diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 4e2bce0f..a3a35b78 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -22,15 +22,17 @@ public sealed class CrashHandlerService : IDisposable, IService private readonly ActorManager _actors; private readonly ResourceLoader _resourceLoader; private readonly Configuration _config; + private readonly ValidityChecker _validityChecker; public CrashHandlerService(FilenameService files, CommunicatorService communicator, ActorManager actors, ResourceLoader resourceLoader, - Configuration config) + Configuration config, ValidityChecker validityChecker) { - _files = files; - _communicator = communicator; - _actors = actors; - _resourceLoader = resourceLoader; - _config = config; + _files = files; + _communicator = communicator; + _actors = actors; + _resourceLoader = resourceLoader; + _config = config; + _validityChecker = validityChecker; if (!_config.UseCrashHandler) return; @@ -152,6 +154,8 @@ public sealed class CrashHandlerService : IDisposable, IService }; info.ArgumentList.Add(_files.LogFileName); info.ArgumentList.Add(Environment.ProcessId.ToString()); + info.ArgumentList.Add($"{_validityChecker.Version} ({_validityChecker.CommitHash})"); + info.ArgumentList.Add(_validityChecker.GameVersion); _child = Process.Start(info); if (_child == null) throw new Exception("Child Process could not be created."); @@ -177,7 +181,7 @@ public sealed class CrashHandlerService : IDisposable, IService JsonObject jObj; lock (_eventWriter) { - jObj = reader.Dump("Manual Dump", Environment.ProcessId, 0); + jObj = reader.Dump("Manual Dump", Environment.ProcessId, 0, $"{_validityChecker.Version} ({_validityChecker.CommitHash})", _validityChecker.GameVersion); } var logFile = _files.LogFileName; diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index 4d071f85..d4b5005f 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Plugin; +using FFXIVClientStructs.FFXIV.Client.System.Framework; using OtterGui.Classes; using OtterGui.Services; @@ -20,6 +21,7 @@ public class ValidityChecker : IService public readonly string Version; public readonly string CommitHash; + public readonly string GameVersion; public ValidityChecker(DalamudPluginInterface pi) { @@ -28,14 +30,19 @@ public class ValidityChecker : IService IsValidSourceRepo = CheckSourceRepo(pi); var assembly = GetType().Assembly; - Version = assembly.GetName().Version?.ToString() ?? string.Empty; - CommitHash = assembly.GetCustomAttribute()?.InformationalVersion ?? "Unknown"; + Version = assembly.GetName().Version?.ToString() ?? string.Empty; + CommitHash = assembly.GetCustomAttribute()?.InformationalVersion ?? "Unknown"; + GameVersion = GetGameVersion(); } + private static unsafe string GetGameVersion() + => Framework.Instance()->GameVersion[0]; + public void LogExceptions() { if (ImcExceptions.Count > 0) - Penumbra.Messager.NotificationMessage($"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", + NotificationType.Warning); } // Because remnants of penumbra in devPlugins cause issues, we check for them to warn users to remove them. diff --git a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs index 3d32d267..78014054 100644 --- a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs +++ b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs @@ -13,6 +13,9 @@ public static class CrashDataExtensions { ImGui.TextUnformatted(nameof(data.Mode)); ImGui.TextUnformatted(nameof(data.CrashTime)); + ImGui.TextUnformatted("Current Age"); + ImGui.TextUnformatted(nameof(data.Version)); + ImGui.TextUnformatted(nameof(data.GameVersion)); ImGui.TextUnformatted(nameof(data.ExitCode)); ImGui.TextUnformatted(nameof(data.ProcessId)); ImGui.TextUnformatted(nameof(data.TotalModdedFilesLoaded)); @@ -25,6 +28,9 @@ public static class CrashDataExtensions { ImGui.TextUnformatted(data.Mode); ImGui.TextUnformatted(data.CrashTime.ToString()); + ImGui.TextUnformatted((DateTimeOffset.UtcNow - data.CrashTime).ToString(@"dd\.hh\:mm\:ss")); + ImGui.TextUnformatted(data.Version); + ImGui.TextUnformatted(data.GameVersion); ImGui.TextUnformatted(data.ExitCode.ToString()); ImGui.TextUnformatted(data.ProcessId.ToString()); ImGui.TextUnformatted(data.TotalModdedFilesLoaded.ToString()); From ceb3bbc5c37f1f4d929d36cd6e11e4eac8bd0d1d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Mar 2024 13:34:49 +0100 Subject: [PATCH 0481/1381] Fix issue with compressed file sizes. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 1a187f75..1be9365d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 1a187f756f2e8823197bd43db1c3383231f5eaff +Subproject commit 1be9365d048bf1da3700e8cf1df9acbe42523f5c From 038c230427f6bf8c7bd2283939b343fcc60c6d4e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Mar 2024 13:59:40 +0100 Subject: [PATCH 0482/1381] Rename to Predefined. --- Penumbra/Services/FilenameService.cs | 6 +- Penumbra/Services/ServiceManagerA.cs | 2 +- Penumbra/UI/Classes/Colors.cs | 8 +- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 42 ++++------ Penumbra/UI/ModsTab/ModPanelEditTab.cs | 83 ++++++++----------- ...dTagManager.cs => PredefinedTagManager.cs} | 71 ++++++++-------- Penumbra/UI/Tabs/SettingsTab.cs | 22 +++-- 7 files changed, 102 insertions(+), 132 deletions(-) rename Penumbra/UI/{SharedTagManager.cs => PredefinedTagManager.cs} (83%) diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 20794f12..2de4bff0 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -14,7 +14,7 @@ public class FilenameService(DalamudPluginInterface pi) : IService public readonly string EphemeralConfigFile = Path.Combine(pi.ConfigDirectory.FullName, "ephemeral_config.json"); public readonly string FilesystemFile = Path.Combine(pi.ConfigDirectory.FullName, "sort_order.json"); public readonly string ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); - public readonly string SharedTagFile = Path.Combine(pi.ConfigDirectory.FullName, "shared_tags.json"); + public readonly string PredefinedTagFile = Path.Combine(pi.ConfigDirectory.FullName, "predefined_tags.json"); public readonly string CrashHandlerExe = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Penumbra.CrashHandler.exe"); @@ -44,7 +44,7 @@ public class FilenameService(DalamudPluginInterface pi) : IService get { var directory = new DirectoryInfo(CollectionDirectory); - return directory.Exists ? directory.EnumerateFiles("*.json") : Array.Empty(); + return directory.Exists ? directory.EnumerateFiles("*.json") : []; } } @@ -54,7 +54,7 @@ public class FilenameService(DalamudPluginInterface pi) : IService get { var directory = new DirectoryInfo(LocalDataDirectory); - return directory.Exists ? directory.EnumerateFiles("*.json") : Array.Empty(); + return directory.Exists ? directory.EnumerateFiles("*.json") : []; } } diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index cb2032a2..39ef0560 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -105,7 +105,7 @@ public static class ServiceManagerA private static ServiceManager AddConfiguration(this ServiceManager services) => services.AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton(); private static ServiceManager AddCollections(this ServiceManager services) => services.AddSingleton() diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 50096696..4d0c62af 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -28,8 +28,8 @@ public enum ColorId ResTreePlayer, ResTreeNetworked, ResTreeNonNetworked, - SharedTagAdd, - SharedTagRemove + PredefinedTagAdd, + PredefinedTagRemove, } public static class Colors @@ -75,8 +75,8 @@ public static class Colors ColorId.ResTreePlayer => ( 0xFFC0FFC0, "On-Screen: Other Players", "Other players and what they own, in the On-Screen tab." ), ColorId.ResTreeNetworked => ( 0xFFFFFFFF, "On-Screen: Non-Players (Networked)", "Non-player entities handled by the game server, in the On-Screen tab." ), ColorId.ResTreeNonNetworked => ( 0xFFC0C0FF, "On-Screen: Non-Players (Local)", "Non-player entities handled locally, in the On-Screen tab." ), - ColorId.SharedTagAdd => ( 0xFF44AA44, "Shared Tags: Add Tag", "A shared tag that is not present on the current mod and can be added." ), - ColorId.SharedTagRemove => ( 0xFF2222AA, "Shared Tags: Remove Tag", "A shared tag that is already present on the current mod and can be removed." ), + ColorId.PredefinedTagAdd => ( 0xFF44AA44, "Predefined Tags: Add Tag", "A predefined tag that is not present on the current mod and can be added." ), + ColorId.PredefinedTagRemove => ( 0xFF2222AA, "Predefined Tags: Remove Tag", "A predefined tag that is already present on the current mod and can be removed." ), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 5f2687c3..4c5e68ff 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -7,22 +7,15 @@ using Penumbra.Mods.Manager; namespace Penumbra.UI.ModsTab; -public class ModPanelDescriptionTab : ITab +public class ModPanelDescriptionTab( + ModFileSystemSelector selector, + TutorialService tutorial, + ModManager modManager, + PredefinedTagManager predefinedTagsConfig) + : ITab { - private readonly ModFileSystemSelector _selector; - private readonly TutorialService _tutorial; - private readonly ModManager _modManager; - private readonly SharedTagManager _sharedTagManager; - private readonly TagButtons _localTags = new(); - private readonly TagButtons _modTags = new(); - - public ModPanelDescriptionTab(ModFileSystemSelector selector, TutorialService tutorial, ModManager modManager, SharedTagManager sharedTagsConfig) - { - _selector = selector; - _tutorial = tutorial; - _modManager = modManager; - _sharedTagManager = sharedTagsConfig; - } + private readonly TagButtons _localTags = new(); + private readonly TagButtons _modTags = new(); public ReadOnlySpan Label => "Description"u8; @@ -36,29 +29,28 @@ public class ModPanelDescriptionTab : ITab ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); - var sharedTagsEnabled = _sharedTagManager.SharedTags.Count > 0; + var sharedTagsEnabled = predefinedTagsConfig.SharedTags.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _localTags.Draw("Local Tags: ", "Custom tags you can set personally that will not be exported to the mod data but only set for you.\n" - + "If the mod already contains a local tag in its own tags, the local tag will be ignored.", _selector.Selected!.LocalTags, + + "If the mod already contains a local tag in its own tags, the local tag will be ignored.", selector.Selected!.LocalTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); - _tutorial.OpenTutorial(BasicTutorialSteps.Tags); + tutorial.OpenTutorial(BasicTutorialSteps.Tags); if (tagIdx >= 0) - _modManager.DataEditor.ChangeLocalTag(_selector.Selected!, tagIdx, editedTag); + modManager.DataEditor.ChangeLocalTag(selector.Selected!, tagIdx, editedTag); if (sharedTagsEnabled) - { - _sharedTagManager.DrawAddFromSharedTagsAndUpdateTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, true, _selector.Selected!); - } + predefinedTagsConfig.DrawAddFromSharedTagsAndUpdateTags(selector.Selected!.LocalTags, selector.Selected!.ModTags, true, + selector.Selected!); - if (_selector.Selected!.ModTags.Count > 0) + if (selector.Selected!.ModTags.Count > 0) _modTags.Draw("Mod Tags: ", "Tags assigned by the mod creator and saved with the mod data. To edit these, look at Edit Mod.", - _selector.Selected!.ModTags, out var _, false, + selector.Selected!.ModTags, out _, false, ImGui.CalcTextSize("Local ").X - ImGui.CalcTextSize("Mod ").X); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Separator(); - ImGuiUtil.TextWrapped(_selector.Selected!.Description); + ImGuiUtil.TextWrapped(selector.Selected!.Description); } } diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 9b4a582f..275c89ef 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -17,18 +17,20 @@ using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; -public class ModPanelEditTab : ITab +public class ModPanelEditTab( + ModManager modManager, + ModFileSystemSelector selector, + ModFileSystem fileSystem, + Services.MessageService messager, + ModEditWindow editWindow, + ModEditor editor, + FilenameService filenames, + ModExportManager modExportManager, + Configuration config, + PredefinedTagManager predefinedTagManager) + : ITab { - private readonly Services.MessageService _messager; - private readonly FilenameService _filenames; - private readonly ModManager _modManager; - private readonly ModExportManager _modExportManager; - private readonly ModFileSystem _fileSystem; - private readonly ModFileSystemSelector _selector; - private readonly ModEditWindow _editWindow; - private readonly ModEditor _editor; - private readonly Configuration _config; - private readonly SharedTagManager _sharedTagManager; + private readonly ModManager _modManager = modManager; private readonly TagButtons _modTags = new(); @@ -37,22 +39,6 @@ public class ModPanelEditTab : ITab private ModFileSystem.Leaf _leaf = null!; private Mod _mod = null!; - public ModPanelEditTab(ModManager modManager, ModFileSystemSelector selector, ModFileSystem fileSystem, Services.MessageService messager, - ModEditWindow editWindow, ModEditor editor, FilenameService filenames, ModExportManager modExportManager, Configuration config, - SharedTagManager sharedTagManager) - { - _modManager = modManager; - _selector = selector; - _fileSystem = fileSystem; - _messager = messager; - _editWindow = editWindow; - _editor = editor; - _filenames = filenames; - _modExportManager = modExportManager; - _config = config; - _sharedTagManager = sharedTagManager; - } - public ReadOnlySpan Label => "Edit Mod"u8; @@ -62,8 +48,8 @@ public class ModPanelEditTab : ITab if (!child) return; - _leaf = _selector.SelectedLeaf!; - _mod = _selector.Selected!; + _leaf = selector.SelectedLeaf!; + _mod = selector.Selected!; _cellPadding = ImGui.GetStyle().CellPadding with { X = 2 * UiHelpers.Scale }; _itemSpacing = ImGui.GetStyle().CellPadding with { X = 4 * UiHelpers.Scale }; @@ -75,15 +61,15 @@ public class ModPanelEditTab : ITab if (Input.Text("Mod Path", Input.Path, Input.None, _leaf.FullName(), out var newPath, 256, UiHelpers.InputTextWidth.X)) try { - _fileSystem.RenameAndMove(_leaf, newPath); + fileSystem.RenameAndMove(_leaf, newPath); } catch (Exception e) { - _messager.NotificationMessage(e.Message, NotificationType.Warning, false); + messager.NotificationMessage(e.Message, NotificationType.Warning, false); } UiHelpers.DefaultLineSpace(); - var sharedTagsEnabled = _sharedTagManager.SharedTags.Count > 0; + var sharedTagsEnabled = predefinedTagManager.SharedTags.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); @@ -91,12 +77,11 @@ public class ModPanelEditTab : ITab _modManager.DataEditor.ChangeModTag(_mod, tagIdx, editedTag); if (sharedTagsEnabled) - { - _sharedTagManager.DrawAddFromSharedTagsAndUpdateTags(_selector.Selected!.LocalTags, _selector.Selected!.ModTags, false, _selector.Selected!); - } + predefinedTagManager.DrawAddFromSharedTagsAndUpdateTags(selector.Selected!.LocalTags, selector.Selected!.ModTags, false, + selector.Selected!); UiHelpers.DefaultLineSpace(); - AddOptionGroup.Draw(_filenames, _modManager, _mod, _config.ReplaceNonAsciiOnImport); + AddOptionGroup.Draw(filenames, _modManager, _mod, config.ReplaceNonAsciiOnImport); UiHelpers.DefaultLineSpace(); for (var groupIdx = 0; groupIdx < _mod.Groups.Count; ++groupIdx) @@ -144,11 +129,11 @@ public class ModPanelEditTab : ITab { if (ImGui.Button("Update Bibo Material", buttonSize)) { - _editor.LoadMod(_mod); - _editor.MdlMaterialEditor.ReplaceAllMaterials("bibo", "b"); - _editor.MdlMaterialEditor.ReplaceAllMaterials("bibopube", "c"); - _editor.MdlMaterialEditor.SaveAllModels(_editor.Compactor); - _editWindow.UpdateModels(); + editor.LoadMod(_mod); + editor.MdlMaterialEditor.ReplaceAllMaterials("bibo", "b"); + editor.MdlMaterialEditor.ReplaceAllMaterials("bibopube", "c"); + editor.MdlMaterialEditor.SaveAllModels(editor.Compactor); + editWindow.UpdateModels(); } ImGuiUtil.HoverTooltip( @@ -160,7 +145,7 @@ public class ModPanelEditTab : ITab private void BackupButtons(Vector2 buttonSize) { - var backup = new ModBackup(_modExportManager, _mod); + var backup = new ModBackup(modExportManager, _mod); var tt = ModBackup.CreatingBackup ? "Already exporting a mod." : backup.Exists @@ -171,16 +156,16 @@ public class ModPanelEditTab : ITab ImGui.SameLine(); tt = backup.Exists - ? $"Delete existing mod export \"{backup.Name}\" (hold {_config.DeleteModModifier} while clicking)." + ? $"Delete existing mod export \"{backup.Name}\" (hold {config.DeleteModModifier} while clicking)." : $"Exported mod \"{backup.Name}\" does not exist."; - if (ImGuiUtil.DrawDisabledButton("Delete Export", buttonSize, tt, !backup.Exists || !_config.DeleteModModifier.IsActive())) + if (ImGuiUtil.DrawDisabledButton("Delete Export", buttonSize, tt, !backup.Exists || !config.DeleteModModifier.IsActive())) backup.Delete(); tt = backup.Exists - ? $"Restore mod from exported file \"{backup.Name}\" (hold {_config.DeleteModModifier} while clicking)." + ? $"Restore mod from exported file \"{backup.Name}\" (hold {config.DeleteModModifier} while clicking)." : $"Exported mod \"{backup.Name}\" does not exist."; ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Restore From Export", buttonSize, tt, !backup.Exists || !_config.DeleteModModifier.IsActive())) + if (ImGuiUtil.DrawDisabledButton("Restore From Export", buttonSize, tt, !backup.Exists || !config.DeleteModModifier.IsActive())) backup.Restore(_modManager); if (backup.Exists) { @@ -218,13 +203,13 @@ public class ModPanelEditTab : ITab _delayedActions.Enqueue(() => DescriptionEdit.OpenPopup(_mod, Input.Description)); ImGui.SameLine(); - var fileExists = File.Exists(_filenames.ModMetaPath(_mod)); + var fileExists = File.Exists(filenames.ModMetaPath(_mod)); var tt = fileExists ? "Open the metadata json file in the text editor of your choice." : "The metadata json file does not exist."; if (ImGuiUtil.DrawDisabledButton($"{FontAwesomeIcon.FileExport.ToIconString()}##metaFile", UiHelpers.IconButtonSize, tt, !fileExists, true)) - Process.Start(new ProcessStartInfo(_filenames.ModMetaPath(_mod)) { UseShellExecute = true }); + Process.Start(new ProcessStartInfo(filenames.ModMetaPath(_mod)) { UseShellExecute = true }); } /// Do some edits outside of iterations. @@ -448,7 +433,7 @@ public class ModPanelEditTab : ITab _delayedActions.Enqueue(() => DescriptionEdit.OpenPopup(_mod, groupIdx)); ImGui.SameLine(); - var fileName = _filenames.OptionGroupFile(_mod, groupIdx, _config.ReplaceNonAsciiOnImport); + var fileName = filenames.OptionGroupFile(_mod, groupIdx, config.ReplaceNonAsciiOnImport); var fileExists = File.Exists(fileName); tt = fileExists ? $"Open the {group.Name} json file in the text editor of your choice." diff --git a/Penumbra/UI/SharedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs similarity index 83% rename from Penumbra/UI/SharedTagManager.cs rename to Penumbra/UI/PredefinedTagManager.cs index 23196319..fafca101 100644 --- a/Penumbra/UI/SharedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -1,6 +1,5 @@ using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; -using Dalamud.Utility; using ImGuiNET; using Newtonsoft.Json; using OtterGui; @@ -12,44 +11,45 @@ using Penumbra.UI.Classes; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra.UI; -public sealed class SharedTagManager : ISavable + +public sealed class PredefinedTagManager : ISavable { - private readonly ModManager _modManager; + private readonly ModManager _modManager; private readonly SaveService _saveService; - private static uint _tagButtonAddColor = ColorId.SharedTagAdd.Value(); - private static uint _tagButtonRemoveColor = ColorId.SharedTagRemove.Value(); + private static uint _tagButtonAddColor = ColorId.PredefinedTagAdd.Value(); + private static uint _tagButtonRemoveColor = ColorId.PredefinedTagRemove.Value(); private static float _minTagButtonWidth = 15; private const string PopupContext = "SharedTagsPopup"; - private bool _isPopupOpen = false; + private bool _isPopupOpen = false; // Operations on this list assume that it is sorted and will keep it sorted if that is the case. // The list also gets re-sorted when first loaded from config in case the config was modified. [JsonRequired] private readonly List _sharedTags = []; + [JsonIgnore] - public IReadOnlyList SharedTags => _sharedTags; + public IReadOnlyList SharedTags + => _sharedTags; public int ConfigVersion = 1; - public SharedTagManager(ModManager modManager, SaveService saveService) + public PredefinedTagManager(ModManager modManager, SaveService saveService) { - _modManager = modManager; + _modManager = modManager; _saveService = saveService; Load(); } public string ToFilename(FilenameService fileNames) - { - return fileNames.SharedTagFile; - } + => fileNames.PredefinedTagFile; public void Save(StreamWriter writer) { - using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; - var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; serializer.Serialize(jWriter, this); } @@ -65,12 +65,12 @@ public sealed class SharedTagManager : ISavable errorArgs.ErrorContext.Handled = true; } - if (!File.Exists(_saveService.FileNames.SharedTagFile)) + if (!File.Exists(_saveService.FileNames.PredefinedTagFile)) return; try { - var text = File.ReadAllText(_saveService.FileNames.SharedTagFile); + var text = File.ReadAllText(_saveService.FileNames.PredefinedTagFile); JsonConvert.PopulateObject(text, this, new JsonSerializerSettings { Error = HandleDeserializationError, @@ -94,9 +94,7 @@ public sealed class SharedTagManager : ISavable // In the case of editing a tag, remove what's there prior to doing an insert. if (tagIdx != SharedTags.Count) - { _sharedTags.RemoveAt(tagIdx); - } if (!string.IsNullOrEmpty(tag)) { @@ -109,7 +107,8 @@ public sealed class SharedTagManager : ISavable Save(); } - public void DrawAddFromSharedTagsAndUpdateTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, Mods.Mod mod) + public void DrawAddFromSharedTagsAndUpdateTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, + Mods.Mod mod) { ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); @@ -131,7 +130,8 @@ public sealed class SharedTagManager : ISavable { _modManager.DataEditor.ChangeLocalTag(mod, index, string.Empty); } - } else + } + else { if (index < 0) { @@ -143,15 +143,16 @@ public sealed class SharedTagManager : ISavable _modManager.DataEditor.ChangeModTag(mod, index, string.Empty); } } - } } public string DrawAddFromSharedTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) { var tagToAdd = string.Empty; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Tags.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Add Shared Tag... (Right-click to close popup)", - false, true) || _isPopupOpen) + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Tags.ToIconString(), new Vector2(ImGui.GetFrameHeight()), + "Add Shared Tag... (Right-click to close popup)", + false, true) + || _isPopupOpen) return DrawSharedTagsPopup(localTags, modTags, editLocal); return tagToAdd; @@ -167,9 +168,9 @@ public sealed class SharedTagManager : ISavable } var display = ImGui.GetIO().DisplaySize; - var height = Math.Min(display.Y / 4, 10 * ImGui.GetFrameHeightWithSpacing()); - var width = display.X / 6; - var size = new Vector2(width, height); + var height = Math.Min(display.Y / 4, 10 * ImGui.GetFrameHeightWithSpacing()); + var width = display.X / 6; + var size = new Vector2(width, height); ImGui.SetNextWindowSize(size); using var popup = ImRaii.Popup(PopupContext); if (!popup) @@ -182,26 +183,23 @@ public sealed class SharedTagManager : ISavable foreach (var (tag, idx) in SharedTags.WithIndex()) { if (DrawColoredButton(localTags, modTags, tag, editLocal, idx)) - { selected = tag; - } ImGui.SameLine(); } if (ImGui.IsMouseClicked(ImGuiMouseButton.Right)) - { _isPopupOpen = false; - } return selected; } - private static bool DrawColoredButton(IReadOnlyCollection localTags, IReadOnlyCollection modTags, string buttonLabel, bool editLocal, int index) + private static bool DrawColoredButton(IReadOnlyCollection localTags, IReadOnlyCollection modTags, string buttonLabel, + bool editLocal, int index) { var ret = false; var isLocalTagPresent = localTags.Contains(buttonLabel); - var isModTagPresent = modTags.Contains(buttonLabel); + var isModTagPresent = modTags.Contains(buttonLabel); var buttonWidth = CalcTextButtonWidth(buttonLabel); // Would prefer to be able to fit at least 2 buttons per line so the popup doesn't look sparse with lots of long tags. Thus long tags will be trimmed. @@ -210,7 +208,7 @@ public sealed class SharedTagManager : ISavable if (buttonWidth >= maxButtonWidth) { displayedLabel = TrimButtonTextToWidth(buttonLabel, maxButtonWidth); - buttonWidth = CalcTextButtonWidth(displayedLabel); + buttonWidth = CalcTextButtonWidth(displayedLabel); } // Prevent adding a new tag past the right edge of the popup @@ -247,9 +245,8 @@ public sealed class SharedTagManager : ISavable // An ellipsis will be used to indicate trimmed tags if (CalcTextButtonWidth(nextTrim + "...") < maxWidth) - { return nextTrim + "..."; - } + trimmedText = nextTrim; } @@ -257,7 +254,5 @@ public sealed class SharedTagManager : ISavable } private static float CalcTextButtonWidth(string text) - { - return ImGui.CalcTextSize(text).X + 2 * ImGui.GetStyle().FramePadding.X; - } + => ImGui.CalcTextSize(text).X + 2 * ImGui.GetStyle().FramePadding.X; } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index b311bb93..c36c63b2 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -42,7 +42,7 @@ public class SettingsTab : ITab private readonly DalamudConfigService _dalamudConfig; private readonly DalamudPluginInterface _pluginInterface; private readonly IDataManager _gameData; - private readonly SharedTagManager _sharedTagManager; + private readonly PredefinedTagManager _predefinedTagManager; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -53,7 +53,7 @@ public class SettingsTab : ITab Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, - IDataManager gameData, SharedTagManager sharedTagConfig) + IDataManager gameData, PredefinedTagManager predefinedTagConfig) { _pluginInterface = pluginInterface; _config = config; @@ -73,7 +73,7 @@ public class SettingsTab : ITab _gameData = gameData; if (_compactor.CanCompact) _compactor.Enabled = _config.UseFileSystemCompression; - _sharedTagManager = sharedTagConfig; + _predefinedTagManager = predefinedTagConfig; } public void DrawHeader() @@ -101,7 +101,7 @@ public class SettingsTab : ITab DrawGeneralSettings(); DrawColorSettings(); DrawAdvancedSettings(); - DrawSharedTagsSection(); + DrawPredefinedTagsSection(); DrawSupportButtons(); } @@ -239,7 +239,7 @@ public class SettingsTab : ITab } var selected = ImGui.IsItemActive(); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); ImGui.SameLine(); DrawDirectoryPickerButton(); style.Pop(); @@ -388,7 +388,7 @@ public class SettingsTab : ITab "Hide the Penumbra main window when you manually hide the in-game user interface.", _config.HideUiWhenUiHidden, v => { - _config.HideUiWhenUiHidden = v; + _config.HideUiWhenUiHidden = v; _pluginInterface.UiBuilder.DisableUserUiHide = !v; }); Checkbox("Hide Config Window when in Cutscenes", @@ -917,18 +917,16 @@ public class SettingsTab : ITab _penumbra.ForceChangelogOpen(); } - private void DrawSharedTagsSection() + private void DrawPredefinedTagsSection() { if (!ImGui.CollapsingHeader("Tags")) return; - var tagIdx = _sharedTags.Draw("Shared Tags: ", - "Predefined tags that can be added or removed from mods with a single click.", _sharedTagManager.SharedTags, + var tagIdx = _sharedTags.Draw("Predefined Tags: ", + "Predefined tags that can be added or removed from mods with a single click.", _predefinedTagManager.SharedTags, out var editedTag); if (tagIdx >= 0) - { - _sharedTagManager.ChangeSharedTag(tagIdx, editedTag); - } + _predefinedTagManager.ChangeSharedTag(tagIdx, editedTag); } } From 814aa92e19e7a971ef12c2950c0cff023d3e0b8d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Mar 2024 14:08:14 +0100 Subject: [PATCH 0483/1381] Move tags before advanced. --- Penumbra/UI/Tabs/SettingsTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index c36c63b2..60c18d5f 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -100,8 +100,8 @@ public class SettingsTab : ITab DrawGeneralSettings(); DrawColorSettings(); - DrawAdvancedSettings(); DrawPredefinedTagsSection(); + DrawAdvancedSettings(); DrawSupportButtons(); } From 19526dd92d4361fe7eebbeb1bc6fe0844be7a8c0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Mar 2024 14:09:01 +0100 Subject: [PATCH 0484/1381] Help marker position. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 1be9365d..cf42043c 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 1be9365d048bf1da3700e8cf1df9acbe42523f5c +Subproject commit cf42043c2b0e76b59919688dc250a762fe52d4b1 From 0ec440c388e0667e73069fa0cc8ae2216e7972a9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Mar 2024 16:41:40 +0100 Subject: [PATCH 0485/1381] Fix reloading mods not fixing settings, add some messages on IPC. --- Penumbra/Api/PenumbraApi.cs | 93 +++++++++++++++---- .../Collections/Manager/CollectionStorage.cs | 8 ++ Penumbra/Mods/Subclasses/ModSettings.cs | 16 ++++ Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 9 +- 4 files changed, 103 insertions(+), 23 deletions(-) diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index aed1a963..f5bb67bd 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -10,6 +10,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Compression; +using OtterGui.Log; using Penumbra.Api.Enums; using Penumbra.GameData.Actors; using Penumbra.Interop.ResourceLoading; @@ -642,10 +643,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.ModMissing; + return Return(PenumbraApiEc.ModMissing, Args("ModDirectory", modDirectory, "ModName", modName)); _modManager.ReloadMod(mod); - return PenumbraApiEc.Success; + return Return(PenumbraApiEc.Success, Args("ModDirectory", modDirectory, "ModName", modName)); } public PenumbraApiEc InstallMod(string modFilePackagePath) @@ -653,11 +654,11 @@ public class PenumbraApi : IDisposable, IPenumbraApi if (File.Exists(modFilePackagePath)) { _modImportManager.AddUnpack(modFilePackagePath); - return PenumbraApiEc.Success; + return Return(PenumbraApiEc.Success, Args("ModFilePackagePath", modFilePackagePath)); } else { - return PenumbraApiEc.FileMissing; + return Return(PenumbraApiEc.FileMissing, Args("ModFilePackagePath", modFilePackagePath)); } } @@ -666,23 +667,24 @@ public class PenumbraApi : IDisposable, IPenumbraApi CheckInitialized(); var dir = new DirectoryInfo(Path.Join(_modManager.BasePath.FullName, Path.GetFileName(modDirectory))); if (!dir.Exists) - return PenumbraApiEc.FileMissing; + return Return(PenumbraApiEc.FileMissing, Args("ModDirectory", modDirectory)); + _modManager.AddMod(dir); if (_config.UseFileSystemCompression) new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K); - return PenumbraApiEc.Success; + return Return(PenumbraApiEc.Success, Args("ModDirectory", modDirectory)); } public PenumbraApiEc DeleteMod(string modDirectory, string modName) { CheckInitialized(); if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.NothingChanged; + return Return(PenumbraApiEc.NothingChanged, Args("ModDirectory", modDirectory, "ModName", modName)); _modManager.DeleteMod(mod); - return PenumbraApiEc.Success; + return Return(PenumbraApiEc.Success, Args("ModDirectory", modDirectory, "ModName", modName)); } public event Action? ModDeleted; @@ -784,22 +786,33 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return PenumbraApiEc.CollectionMissing; + return Return(PenumbraApiEc.CollectionMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "OptionName", optionName)); if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.ModMissing; + return Return(PenumbraApiEc.ModMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "OptionName", optionName)); var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); if (groupIdx < 0) - return PenumbraApiEc.OptionGroupMissing; + return Return(PenumbraApiEc.OptionGroupMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "OptionName", optionName)); var optionIdx = mod.Groups[groupIdx].IndexOf(o => o.Name == optionName); if (optionIdx < 0) - return PenumbraApiEc.OptionMissing; + return Return(PenumbraApiEc.OptionMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "OptionName", optionName)); var setting = mod.Groups[groupIdx].Type == GroupType.Multi ? 1u << optionIdx : (uint)optionIdx; - return _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged; + return Return( + _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "OptionName", optionName)); } public PenumbraApiEc TrySetModSettings(string collectionName, string modDirectory, string modName, string optionGroupName, @@ -807,14 +820,20 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return PenumbraApiEc.CollectionMissing; + return Return(PenumbraApiEc.CollectionMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "#optionNames", optionNames.Count.ToString())); if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.ModMissing; + return Return(PenumbraApiEc.ModMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "#optionNames", optionNames.Count.ToString())); var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); if (groupIdx < 0) - return PenumbraApiEc.OptionGroupMissing; + return Return(PenumbraApiEc.OptionGroupMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "#optionNames", optionNames.Count.ToString())); var group = mod.Groups[groupIdx]; @@ -823,7 +842,9 @@ public class PenumbraApi : IDisposable, IPenumbraApi { var optionIdx = optionNames.Count == 0 ? -1 : group.IndexOf(o => o.Name == optionNames[^1]); if (optionIdx < 0) - return PenumbraApiEc.OptionMissing; + return Return(PenumbraApiEc.OptionMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "#optionNames", optionNames.Count.ToString())); setting = (uint)optionIdx; } @@ -833,13 +854,18 @@ public class PenumbraApi : IDisposable, IPenumbraApi { var optionIdx = group.IndexOf(o => o.Name == name); if (optionIdx < 0) - return PenumbraApiEc.OptionMissing; + return Return(PenumbraApiEc.OptionMissing, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", + optionGroupName, "#optionNames", optionNames.Count.ToString())); setting |= 1u << optionIdx; } } - return _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged; + return Return( + _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, + Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, + "#optionNames", optionNames.Count.ToString())); } @@ -1296,4 +1322,33 @@ public class PenumbraApi : IDisposable, IPenumbraApi if (settings is { Enabled: true }) ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Name, mod.Identifier, parent != collection); } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static LazyString Args(params string[] arguments) + { + if (arguments.Length == 0) + return new LazyString(() => "no arguments"); + + return new LazyString(() => + { + var sb = new StringBuilder(); + for (var i = 0; i < arguments.Length / 2; ++i) + { + sb.Append(arguments[2 * i]); + sb.Append(" = "); + sb.Append(arguments[2 * i + 1]); + sb.Append(", "); + } + + return sb.ToString(0, sb.Length - 2); + }); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static PenumbraApiEc Return(PenumbraApiEc ec, LazyString args, [CallerMemberName] string name = "Unknown") + { + Penumbra.Log.Debug( + $"[{name}] Called with {args}, returned {ec}."); + return ec; + } } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index a84c79e6..0ee55376 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -265,6 +265,14 @@ public class CollectionStorage : IReadOnlyList, IDisposable foreach (var collection in this.Where(collection => collection.Settings[mod.Index] != null)) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); break; + case ModPathChangeType.Reloaded: + foreach (var collection in this) + { + if (collection.Settings[mod.Index]?.FixAllSettings(mod) ?? false) + _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + } + + break; } } diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index a20cb9cb..ed8ad84e 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -138,6 +138,22 @@ public class ModSettings } } + public bool FixAllSettings(Mod mod) + { + var ret = false; + for (var i = 0; i < Settings.Count; ++i) + { + var newValue = FixSetting(mod.Groups[i], Settings[i]); + if (newValue != Settings[i]) + { + ret = true; + Settings[i] = newValue; + } + } + + return AddMissingSettings(mod) || ret; + } + // Ensure that a value is valid for a group. private static uint FixSetting(IModGroup group, uint value) => group.Type switch diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 195c07d6..5c7ddbf3 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -211,6 +211,11 @@ public class ModPanelSettingsTab : ITab var selectedOption = _empty ? (int)group.DefaultSettings : (int)_settings.Settings[groupIdx]; var minWidth = Widget.BeginFramedGroup(group.Name, description:group.Description); + DrawCollapseHandling(group, minWidth, DrawOptions); + + Widget.EndFramedGroup(); + return; + void DrawOptions() { for (var idx = 0; idx < group.Count; ++idx) @@ -227,10 +232,6 @@ public class ModPanelSettingsTab : ITab ImGuiComponents.HelpMarker(option.Description); } } - - DrawCollapseHandling(group, minWidth, DrawOptions); - - Widget.EndFramedGroup(); } From 9f7b95746dff2f83a82e810276bf48f9f3f93a2f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Mar 2024 16:50:26 +0100 Subject: [PATCH 0486/1381] Use default task scheduler. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Collections/Manager/IndividualCollections.Files.cs | 2 +- Penumbra/Import/Models/ModelManager.cs | 4 ++-- Penumbra/Import/TexToolsImport.cs | 4 ++-- Penumbra/Import/Textures/TextureManager.cs | 2 +- Penumbra/Mods/Manager/ModCacheManager.cs | 2 +- Penumbra/Services/ServiceWrapper.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 6 +++--- Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs | 2 +- 12 files changed, 16 insertions(+), 16 deletions(-) diff --git a/OtterGui b/OtterGui index 1be9365d..5a2e12a1 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 1be9365d048bf1da3700e8cf1df9acbe42523f5c +Subproject commit 5a2e12a1acd6760a3a592447a92215135e79197c diff --git a/Penumbra.GameData b/Penumbra.GameData index c0c7eb0d..c39f683d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c0c7eb0dedb32ea83b019626abba041e90a95319 +Subproject commit c39f683d65d4541e9f97ed4ea1abcb10e8ca5690 diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index dc20da1e..21a8cf8a 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -41,7 +41,7 @@ public partial class IndividualCollections saver.ImmediateSave(parent); IsLoaded = true; Loaded.Invoke(); - }); + }, TaskScheduler.Default); return false; } diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 2c341c8b..1a52c4dd 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -162,7 +162,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect { return _tasks.TryRemove(a, out var unused); } - }, CancellationToken.None); + }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); return (t, token); }).Item1; } @@ -178,7 +178,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect throw task.Exception; return process(action); - }); + }, TaskScheduler.Default); private class ExportToGltfAction( ModelManager manager, diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index 3f3304b8..bb006d8d 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -46,12 +46,12 @@ public partial class TexToolsImporter : IDisposable ExtractedMods = new List<(FileInfo, DirectoryInfo?, Exception?)>(count); _token = _cancellation.Token; Task.Run(ImportFiles, _token) - .ContinueWith(_ => CloseStreams()) + .ContinueWith(_ => CloseStreams(), TaskScheduler.Default) .ContinueWith(_ => { foreach (var (file, dir, error) in ExtractedMods) handler(file, dir, error); - }); + }, TaskScheduler.Default); } private void CloseStreams() diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 5653d760..976bc179 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -64,7 +64,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable { var token = new CancellationTokenSource(); var task = Enqueue(a, token.Token); - task.ContinueWith(_ => _tasks.TryRemove(a, out var unused), CancellationToken.None); + task.ContinueWith(_ => _tasks.TryRemove(a, out var unused), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); return (task, token); }).Item1; } diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index a95567ce..99ad1a4f 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -23,7 +23,7 @@ public class ModCacheManager : IDisposable _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModCacheManager); _communicator.ModDataChanged.Subscribe(OnModDataChange, ModDataChanged.Priority.ModCacheManager); _communicator.ModDiscoveryFinished.Subscribe(OnModDiscoveryFinished, ModDiscoveryFinished.Priority.ModCacheManager); - identifier.Awaiter.ContinueWith(_ => OnIdentifierCreation()); + identifier.Awaiter.ContinueWith(_ => OnIdentifierCreation(), TaskScheduler.Default); OnModDiscoveryFinished(); } diff --git a/Penumbra/Services/ServiceWrapper.cs b/Penumbra/Services/ServiceWrapper.cs index 37acdfd0..e321b35c 100644 --- a/Penumbra/Services/ServiceWrapper.cs +++ b/Penumbra/Services/ServiceWrapper.cs @@ -74,7 +74,7 @@ public abstract class AsyncServiceWrapper : IDisposable { if (!_isDisposed) FinishedCreation?.Invoke(); - }, null); + }, TaskScheduler.Default); } public void Dispose() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 637c8401..cca8fe10 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -92,7 +92,7 @@ public partial class ModEditWindow .ToList(); }); - task.ContinueWith(t => { GamePaths = FinalizeIo(t); }); + task.ContinueWith(t => { GamePaths = FinalizeIo(t); }, TaskScheduler.Default); } private EstManipulation[] GetCurrentEstManipulations() @@ -130,7 +130,7 @@ public partial class ModEditWindow BeginIo(); _edit._models.ExportToGltf(ExportConfig, Mdl, sklbPaths, ReadFile, outputPath) - .ContinueWith(FinalizeIo); + .ContinueWith(FinalizeIo, TaskScheduler.Default); } /// Import a model from an interchange format. @@ -144,7 +144,7 @@ public partial class ModEditWindow var mdlFile = FinalizeIo(task, result => result.Item1, result => result.Item2); if (mdlFile != null) FinalizeImport(mdlFile); - }); + }, TaskScheduler.Default); } /// Finalise the import of a .mdl, applying any post-import transformations and state updates. diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 71c64059..652ecb49 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -255,7 +255,7 @@ public partial class ModEditWindow return; _framework.RunOnFrameworkThread(() => tex.Reload(_textures)); - }); + }, TaskScheduler.Default); } private Vector2 GetChildWidth() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index afa846b5..72dd91d3 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -326,7 +326,7 @@ public partial class ModEditWindow : Window, IDisposable else if (ImGuiUtil.DrawDisabledButton("Re-Duplicate and Normalize Mod", Vector2.Zero, tt, !_allowReduplicate && !modifier)) { _editor.ModNormalizer.Normalize(Mod!); - _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(Mod!, _editor.GroupIdx, _editor.OptionIdx)); + _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(Mod!, _editor.GroupIdx, _editor.OptionIdx), TaskScheduler.Default); } if (!_editor.Duplicates.Worker.IsCompleted) diff --git a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs index a0e35cff..fd8f9b25 100644 --- a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs +++ b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs @@ -33,7 +33,7 @@ public class IndividualAssignmentUi : IDisposable _actors = actors; _collectionManager = collectionManager; _communicator.CollectionChange.Subscribe(UpdateIdentifiers, CollectionChange.Priority.IndividualAssignmentUi); - _actors.Awaiter.ContinueWith(_ => SetupCombos()); + _actors.Awaiter.ContinueWith(_ => SetupCombos(), TaskScheduler.Default); } public string PlayerTooltip { get; private set; } = NewPlayerTooltipEmpty; From 0f89e243779334d3c916698290e9157fd787775c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Mar 2024 17:12:30 +0100 Subject: [PATCH 0487/1381] Improve tag button positioning. --- OtterGui | 2 +- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 9 +++++---- Penumbra/UI/PredefinedTagManager.cs | 4 +--- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/OtterGui b/OtterGui index 5a2e12a1..c59b1c09 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5a2e12a1acd6760a3a592447a92215135e79197c +Subproject commit c59b1c09ff7b8093d3a70c45957f9c41341dd3a4 diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 4c5e68ff..e1b80b23 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -29,17 +29,18 @@ public class ModPanelDescriptionTab( ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); - var sharedTagsEnabled = predefinedTagsConfig.SharedTags.Count > 0; - var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; + var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.SharedTags.Count > 0 + ? (true, ImGui.GetFrameHeight() + ImGui.GetStyle().WindowPadding.X + (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0)) + : (false, 0); var tagIdx = _localTags.Draw("Local Tags: ", "Custom tags you can set personally that will not be exported to the mod data but only set for you.\n" + "If the mod already contains a local tag in its own tags, the local tag will be ignored.", selector.Selected!.LocalTags, - out var editedTag, rightEndOffset: sharedTagButtonOffset); + out var editedTag, rightEndOffset: predefinedTagButtonOffset); tutorial.OpenTutorial(BasicTutorialSteps.Tags); if (tagIdx >= 0) modManager.DataEditor.ChangeLocalTag(selector.Selected!, tagIdx, editedTag); - if (sharedTagsEnabled) + if (predefinedTagsEnabled) predefinedTagsConfig.DrawAddFromSharedTagsAndUpdateTags(selector.Selected!.LocalTags, selector.Selected!.ModTags, true, selector.Selected!); diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index fafca101..b85b5dea 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -110,9 +110,7 @@ public sealed class PredefinedTagManager : ISavable public void DrawAddFromSharedTagsAndUpdateTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, Mods.Mod mod) { - ImGui.SetCursorPosY(ImGui.GetCursorPosY() - ImGui.GetFrameHeightWithSpacing()); - ImGui.SetCursorPosX(ImGui.GetWindowWidth() - ImGui.GetFrameHeight() - ImGui.GetStyle().FramePadding.X); - + ImGui.SameLine(ImGui.GetContentRegionMax().X - ImGui.GetFrameHeight() - ImGui.GetStyle().WindowPadding.X); var sharedTag = DrawAddFromSharedTags(localTags, modTags, editLocal); if (sharedTag.Length > 0) From 05b7234748ddc2cbcb7d5cfe329cd7a39e50276b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 17:35:05 +0100 Subject: [PATCH 0488/1381] Update to .net8. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.CrashHandler/Penumbra.CrashHandler.csproj | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Import/Models/Export/MaterialExporter.cs | 3 +-- Penumbra/Penumbra.csproj | 2 +- Penumbra/Services/FilenameService.cs | 2 +- Penumbra/Services/MessageService.cs | 3 ++- Penumbra/Services/ServiceManagerA.cs | 3 ++- Penumbra/UI/TutorialService.cs | 2 +- Penumbra/packages.lock.json | 2 +- 12 files changed, 14 insertions(+), 13 deletions(-) diff --git a/OtterGui b/OtterGui index 5a2e12a1..b4b14367 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5a2e12a1acd6760a3a592447a92215135e79197c +Subproject commit b4b14367d8235eabedd561ad3626beb1d2a83889 diff --git a/Penumbra.Api b/Penumbra.Api index 34921fd2..1df06807 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 34921fd2c5a9aff5d34aef664bdb78331e8b9436 +Subproject commit 1df06807650a79813791effaa01fb7c4710b3dab diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj index ea61b968..c9f97fde 100644 --- a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -2,7 +2,7 @@ Exe - net7.0-windows + net8.0-windows preview enable x64 diff --git a/Penumbra.GameData b/Penumbra.GameData index c39f683d..33b51274 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c39f683d65d4541e9f97ed4ea1abcb10e8ca5690 +Subproject commit 33b512746e80b7b1276b644430923eee9bec9fba diff --git a/Penumbra.String b/Penumbra.String index 620a7edf..14e00f77 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 620a7edf009b92288257ce7d64fffb8fba44d8b5 +Subproject commit 14e00f77d42bc677e02325660db765ef11932560 diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 82e13eb9..2fa4e1b2 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -144,8 +144,7 @@ public class MaterialExporter // Specular (table) var lerpedSpecularColor = Vector3.Lerp(prevRow.Specular, nextRow.Specular, tableRow.Weight); - // float.Lerp is .NET8 ;-; #TODO - var lerpedSpecularFactor = prevRow.SpecularStrength * (1.0f - tableRow.Weight) + nextRow.SpecularStrength * tableRow.Weight; + var lerpedSpecularFactor = float.Lerp(prevRow.SpecularStrength, nextRow.SpecularStrength, tableRow.Weight); specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, lerpedSpecularFactor)); // Emissive (table) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 796eae01..df18ff13 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,6 +1,6 @@ - net7.0-windows + net8.0-windows preview x64 Penumbra diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 49b4cb42..c1b067d0 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -16,7 +16,7 @@ public class FilenameService(DalamudPluginInterface pi) : IService public readonly string ActiveCollectionsFile = Path.Combine(pi.ConfigDirectory.FullName, "active_collections.json"); public readonly string CrashHandlerExe = - Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Penumbra.CrashHandler.exe"); + Path.Combine(pi.AssemblyLocation.DirectoryName!, "Penumbra.CrashHandler.exe"); public readonly string LogFileName = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(pi.ConfigDirectory.FullName)!)!, "Penumbra.log"); diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index daad29ef..0a85a569 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -9,7 +9,8 @@ using OtterGui.Services; namespace Penumbra.Services; -public class MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat) : OtterGui.Classes.MessageService(log, uiBuilder, chat), IService +public class MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat, INotificationManager notificationManager) + : OtterGui.Classes.MessageService(log, uiBuilder, chat, notificationManager), IService { public void LinkItem(Item item) { diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/ServiceManagerA.cs index 191d8d11..a5de33bb 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/ServiceManagerA.cs @@ -81,7 +81,8 @@ public static class ServiceManagerA .AddDalamudService(pi) .AddDalamudService(pi) .AddDalamudService(pi) - .AddDalamudService(pi); + .AddDalamudService(pi) + .AddDalamudService(pi); private static ServiceManager AddInterop(this ServiceManager services) => services.AddSingleton() diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index 6c6b0612..d87df19e 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -108,7 +108,7 @@ public class TutorialService .Register("Initial Setup, Step 8: Mod Import", "Click this button to open a file selector with which to select TTMP mod files. You can select multiple at once.\n\n" + "It is not recommended to import huge mod packs of all your TexTools mods, but rather import the mods themselves, otherwise you lose out on a lot of Penumbra features!\n\n" - + "A feature to import raw texture mods for Tattoos etc. is available under Advanced Editing, but is currently a work in progress.") // TODO + + "A feature to import raw texture mods for Tattoos etc. is available under Advanced Editing, but is currently a work in progress.") .Register("Advanced Help", "Click this button to get detailed information on what you can do in the mod selector.\n\n" + "Import and select a mod now to continue.") .Register("Mod Filters", "You can filter the available mods by name, author, changed items or various attributes here.") diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index d0e8fa1a..3f795631 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -1,7 +1,7 @@ { "version": 1, "dependencies": { - "net7.0-windows7.0": { + "net8.0-windows7.0": { "EmbedIO": { "type": "Direct", "requested": "[3.4.3, )", From 02f2bf1bc18fd9362f6e765a424a23797f2442f3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 17:38:02 +0100 Subject: [PATCH 0489/1381] Update actions. --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/test_release.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3dd1d45b..b40b2538 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,7 +16,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '7.x.x' + dotnet-version: '8.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f3afe9c1..7c9e2909 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '7.x.x' + dotnet-version: '8.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 0968430d..91361646 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -15,7 +15,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '7.x.x' + dotnet-version: '8.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud From a6e08a18652499caf5ede1a010b34e2ac7da4073 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 18:30:00 +0100 Subject: [PATCH 0490/1381] Rename ServiceManagerA. --- Penumbra/Penumbra.cs | 2 +- .../{ServiceManagerA.cs => StaticServiceManager.cs} | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) rename Penumbra/Services/{ServiceManagerA.cs => StaticServiceManager.cs} (97%) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b532339f..ff068928 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -51,7 +51,7 @@ public class Penumbra : IDalamudPlugin { try { - _services = ServiceManagerA.CreateProvider(this, pluginInterface, Log); + _services = StaticServiceManager.CreateProvider(this, pluginInterface, Log); Messager = _services.GetService(); _validityChecker = _services.GetService(); _services.EnsureRequiredServices(); diff --git a/Penumbra/Services/ServiceManagerA.cs b/Penumbra/Services/StaticServiceManager.cs similarity index 97% rename from Penumbra/Services/ServiceManagerA.cs rename to Penumbra/Services/StaticServiceManager.cs index a5de33bb..66c90e84 100644 --- a/Penumbra/Services/ServiceManagerA.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -6,7 +6,6 @@ using Dalamud.Plugin.Services; using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; -using OtterGui.Compression; using OtterGui.Log; using OtterGui.Services; using Penumbra.Api; @@ -14,14 +13,12 @@ using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.Import.Models; -using Penumbra.GameData.DataContainers; using Penumbra.GameData.Structs; using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.ResourceTree; using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -38,7 +35,7 @@ using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManage namespace Penumbra.Services; -public static class ServiceManagerA +public static class StaticServiceManager { public static ServiceManager CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log) { @@ -105,7 +102,8 @@ public static class ServiceManagerA private static ServiceManager AddConfiguration(this ServiceManager services) => services.AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); private static ServiceManager AddCollections(this ServiceManager services) => services.AddSingleton() From fe6e1edecc7877d99ed2a467601310a420d1575f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 18:31:02 +0100 Subject: [PATCH 0491/1381] Fix a game object table warning. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 33b51274..d53db6a3 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 33b512746e80b7b1276b644430923eee9bec9fba +Subproject commit d53db6a358cedecd3ef18f62f12a07deff4b61ee From 52c1708dd270ec46a3de242d57a42116a9de094c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 20:45:16 +0100 Subject: [PATCH 0492/1381] Change predefined tag handling. --- Penumbra/Mods/Mod.cs | 6 +- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 2 +- Penumbra/UI/PredefinedTagManager.cs | 210 ++++++------------ Penumbra/UI/Tabs/ModsTab.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 65 +++--- 6 files changed, 112 insertions(+), 175 deletions(-) diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index a9ef22cb..c5e671af 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -45,19 +45,19 @@ public sealed class Mod : IMod public string Description { get; internal set; } = string.Empty; public string Version { get; internal set; } = string.Empty; public string Website { get; internal set; } = string.Empty; - public IReadOnlyList ModTags { get; internal set; } = Array.Empty(); + public IReadOnlyList ModTags { get; internal set; } = []; // Local Data public long ImportDate { get; internal set; } = DateTimeOffset.UnixEpoch.ToUnixTimeMilliseconds(); - public IReadOnlyList LocalTags { get; internal set; } = Array.Empty(); + public IReadOnlyList LocalTags { get; internal set; } = []; public string Note { get; internal set; } = string.Empty; public bool Favorite { get; internal set; } = false; // Options public readonly SubMod Default; - public readonly List Groups = new(); + public readonly List Groups = []; ISubMod IMod.Default => Default; diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index e1b80b23..4ad30a6f 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -29,7 +29,7 @@ public class ModPanelDescriptionTab( ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); - var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.SharedTags.Count > 0 + var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.PredefinedTags.Count > 0 ? (true, ImGui.GetFrameHeight() + ImGui.GetStyle().WindowPadding.X + (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0)) : (false, 0); var tagIdx = _localTags.Draw("Local Tags: ", diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 275c89ef..a0e32c22 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -69,7 +69,7 @@ public class ModPanelEditTab( } UiHelpers.DefaultLineSpace(); - var sharedTagsEnabled = predefinedTagManager.SharedTags.Count > 0; + var sharedTagsEnabled = predefinedTagManager.PredefinedTags.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index b85b5dea..63be42de 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -17,22 +17,19 @@ public sealed class PredefinedTagManager : ISavable private readonly ModManager _modManager; private readonly SaveService _saveService; - private static uint _tagButtonAddColor = ColorId.PredefinedTagAdd.Value(); - private static uint _tagButtonRemoveColor = ColorId.PredefinedTagRemove.Value(); + private bool _isListOpen = false; + private uint _enabledColor; + private uint _disabledColor; - private static float _minTagButtonWidth = 15; - - private const string PopupContext = "SharedTagsPopup"; - private bool _isPopupOpen = false; // Operations on this list assume that it is sorted and will keep it sorted if that is the case. // The list also gets re-sorted when first loaded from config in case the config was modified. [JsonRequired] - private readonly List _sharedTags = []; + private readonly List _predefinedTags = []; [JsonIgnore] - public IReadOnlyList SharedTags - => _sharedTags; + public IReadOnlyList PredefinedTags + => _predefinedTags; public int ConfigVersion = 1; @@ -48,8 +45,9 @@ public sealed class PredefinedTagManager : ISavable public void Save(StreamWriter writer) { - using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; - var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + using var jWriter = new JsonTextWriter(writer); + jWriter.Formatting = Formatting.Indented; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; serializer.Serialize(jWriter, this); } @@ -58,13 +56,6 @@ public sealed class PredefinedTagManager : ISavable private void Load() { - static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) - { - Penumbra.Log.Error( - $"Error parsing shared tags Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); - errorArgs.ErrorContext.Handled = true; - } - if (!File.Exists(_saveService.FileNames.PredefinedTagFile)) return; @@ -77,7 +68,7 @@ public sealed class PredefinedTagManager : ISavable }); // Any changes to this within this class should keep it sorted, but in case someone went in and manually changed the JSON, run a sort on initial load. - _sharedTags.Sort(); + _predefinedTags.Sort(); } catch (Exception ex) { @@ -85,23 +76,32 @@ public sealed class PredefinedTagManager : ISavable "Error reading shared tags Configuration, reverting to default.", "Error reading shared tags Configuration", NotificationType.Error); } + + return; + + static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) + { + Penumbra.Log.Error( + $"Error parsing shared tags Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); + errorArgs.ErrorContext.Handled = true; + } } public void ChangeSharedTag(int tagIdx, string tag) { - if (tagIdx < 0 || tagIdx > SharedTags.Count) + if (tagIdx < 0 || tagIdx > PredefinedTags.Count) return; // In the case of editing a tag, remove what's there prior to doing an insert. - if (tagIdx != SharedTags.Count) - _sharedTags.RemoveAt(tagIdx); + if (tagIdx != PredefinedTags.Count) + _predefinedTags.RemoveAt(tagIdx); if (!string.IsNullOrEmpty(tag)) { // Taking advantage of the fact that BinarySearch returns the complement of the correct sorted position for the tag. - var existingIdx = _sharedTags.BinarySearch(tag); + var existingIdx = _predefinedTags.BinarySearch(tag); if (existingIdx < 0) - _sharedTags.Insert(~existingIdx, tag); + _predefinedTags.Insert(~existingIdx, tag); } Save(); @@ -110,147 +110,83 @@ public sealed class PredefinedTagManager : ISavable public void DrawAddFromSharedTagsAndUpdateTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, Mods.Mod mod) { - ImGui.SameLine(ImGui.GetContentRegionMax().X - ImGui.GetFrameHeight() - ImGui.GetStyle().WindowPadding.X); - var sharedTag = DrawAddFromSharedTags(localTags, modTags, editLocal); + DrawToggleButton(); + if (!DrawList(localTags, modTags, editLocal, out var changedTag, out var index)) + return; - if (sharedTag.Length > 0) - { - var index = editLocal ? mod.LocalTags.IndexOf(sharedTag) : mod.ModTags.IndexOf(sharedTag); - - if (editLocal) - { - if (index < 0) - { - index = mod.LocalTags.Count; - _modManager.DataEditor.ChangeLocalTag(mod, index, sharedTag); - } - else - { - _modManager.DataEditor.ChangeLocalTag(mod, index, string.Empty); - } - } - else - { - if (index < 0) - { - index = mod.ModTags.Count; - _modManager.DataEditor.ChangeModTag(mod, index, sharedTag); - } - else - { - _modManager.DataEditor.ChangeModTag(mod, index, string.Empty); - } - } - } + if (editLocal) + _modManager.DataEditor.ChangeLocalTag(mod, index, changedTag); + else + _modManager.DataEditor.ChangeModTag(mod, index, changedTag); } - public string DrawAddFromSharedTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) + private void DrawToggleButton() { - var tagToAdd = string.Empty; + ImGui.SameLine(ImGui.GetContentRegionMax().X + - ImGui.GetFrameHeight() + - (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ItemInnerSpacing.X : 0)); + using var color = ImRaii.PushColor(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.ButtonActive), _isListOpen); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Tags.ToIconString(), new Vector2(ImGui.GetFrameHeight()), - "Add Shared Tag... (Right-click to close popup)", - false, true) - || _isPopupOpen) - return DrawSharedTagsPopup(localTags, modTags, editLocal); - - return tagToAdd; + "Add Predefined Tags...", false, true)) + _isListOpen = !_isListOpen; } - private string DrawSharedTagsPopup(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal) + private bool DrawList(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, out string changedTag, + out int changedIndex) { - var selected = string.Empty; - if (!ImGui.IsPopupOpen(PopupContext)) - { - ImGui.OpenPopup(PopupContext); - _isPopupOpen = true; - } + changedTag = string.Empty; + changedIndex = -1; - var display = ImGui.GetIO().DisplaySize; - var height = Math.Min(display.Y / 4, 10 * ImGui.GetFrameHeightWithSpacing()); - var width = display.X / 6; - var size = new Vector2(width, height); - ImGui.SetNextWindowSize(size); - using var popup = ImRaii.Popup(PopupContext); - if (!popup) - return selected; + if (!_isListOpen) + return false; - ImGui.TextUnformatted("Shared Tags"); - ImGuiUtil.HoverTooltip("Right-click to close popup"); + ImGui.TextUnformatted("Predefined Tags"); ImGui.Separator(); - foreach (var (tag, idx) in SharedTags.WithIndex()) + var ret = false; + _enabledColor = ColorId.PredefinedTagAdd.Value(); + _disabledColor = ColorId.PredefinedTagRemove.Value(); + var (edited, others) = editLocal ? (localTags, modTags) : (modTags, localTags); + foreach (var (tag, idx) in PredefinedTags.WithIndex()) { - if (DrawColoredButton(localTags, modTags, tag, editLocal, idx)) - selected = tag; + var tagIdx = edited.IndexOf(tag); + var inOther = tagIdx < 0 && others.IndexOf(tag) >= 0; + if (DrawColoredButton(tag, idx, tagIdx, inOther)) + { + (changedTag, changedIndex) = tagIdx >= 0 ? (string.Empty, tagIdx) : (tag, edited.Count); + ret = true; + } + ImGui.SameLine(); } - if (ImGui.IsMouseClicked(ImGuiMouseButton.Right)) - _isPopupOpen = false; - - return selected; + ImGui.NewLine(); + ImGui.Separator(); + return ret; } - private static bool DrawColoredButton(IReadOnlyCollection localTags, IReadOnlyCollection modTags, string buttonLabel, - bool editLocal, int index) + private bool DrawColoredButton(string buttonLabel, int index, int tagIdx, bool inOther) { - var ret = false; - - var isLocalTagPresent = localTags.Contains(buttonLabel); - var isModTagPresent = modTags.Contains(buttonLabel); - - var buttonWidth = CalcTextButtonWidth(buttonLabel); - // Would prefer to be able to fit at least 2 buttons per line so the popup doesn't look sparse with lots of long tags. Thus long tags will be trimmed. - var maxButtonWidth = (ImGui.GetContentRegionMax().X - ImGui.GetWindowContentRegionMin().X) * 0.5f - ImGui.GetStyle().ItemSpacing.X; - var displayedLabel = buttonLabel; - if (buttonWidth >= maxButtonWidth) - { - displayedLabel = TrimButtonTextToWidth(buttonLabel, maxButtonWidth); - buttonWidth = CalcTextButtonWidth(displayedLabel); - } - + using var id = ImRaii.PushId(index); + var buttonWidth = CalcTextButtonWidth(buttonLabel); // Prevent adding a new tag past the right edge of the popup if (buttonWidth + ImGui.GetStyle().ItemSpacing.X >= ImGui.GetContentRegionAvail().X) ImGui.NewLine(); - // Trimmed tag names can collide, and while tag names are currently distinct this may not always be the case. As such use the index to avoid an ImGui moment. - using var id = ImRaii.PushId(index); + bool ret; + using (ImRaii.Disabled(inOther)) + { + using var color = ImRaii.PushColor(ImGuiCol.Button, tagIdx >= 0 || inOther ? _disabledColor : _enabledColor); + ret = ImGui.Button(buttonLabel); + } + + if (inOther && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGui.SetTooltip("This tag is already present in the other set of tags."); - if (editLocal && isModTagPresent || !editLocal && isLocalTagPresent) - { - using var alpha = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f); - ImGui.Button(displayedLabel); - } - else - { - using (ImRaii.PushColor(ImGuiCol.Button, isLocalTagPresent || isModTagPresent ? _tagButtonRemoveColor : _tagButtonAddColor)) - { - if (ImGui.Button(displayedLabel)) - ret = true; - } - } return ret; } - private static string TrimButtonTextToWidth(string fullText, float maxWidth) - { - var trimmedText = fullText; - - while (trimmedText.Length > _minTagButtonWidth) - { - var nextTrim = trimmedText.Substring(0, Math.Max(trimmedText.Length - 1, 0)); - - // An ellipsis will be used to indicate trimmed tags - if (CalcTextButtonWidth(nextTrim + "...") < maxWidth) - return nextTrim + "..."; - - trimmedText = nextTrim; - } - - return trimmedText; - } - private static float CalcTextButtonWidth(string text) => ImGui.CalcTextSize(text).X + 2 * ImGui.GetStyle().FramePadding.X; } diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index d111c465..bb8856b3 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -110,7 +110,7 @@ public class ModsTab( var frameColor = ImGui.GetColorU32(ImGuiCol.FrameBg); using (var _ = ImRaii.Group()) { - using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + using (ImRaii.PushFont(UiBuilder.IconFont)) { ImGuiUtil.DrawTextButton(FontAwesomeIcon.InfoCircle.ToIconString(), frameHeight, frameColor); ImGui.SameLine(); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 60c18d5f..9f8ffb38 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -227,37 +227,38 @@ public class SettingsTab : ITab if (_newModDirectory.IsNullOrEmpty()) _newModDirectory = _config.ModDirectory; - using var group = ImRaii.Group(); - ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); - bool save; - using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale, !_modManager.Valid)) - { - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder) - .Push(ImGuiCol.TextDisabled, Colors.RegexWarningBorder, !_modManager.Valid); - save = ImGui.InputTextWithHint("##rootDirectory", "Enter Root Directory here (MANDATORY)...", ref _newModDirectory, - RootDirectoryMaxLength, ImGuiInputTextFlags.EnterReturnsTrue); + bool save, selected; + using (ImRaii.Group()) + { + ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); + using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale, !_modManager.Valid)) + { + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder) + .Push(ImGuiCol.TextDisabled, Colors.RegexWarningBorder, !_modManager.Valid); + save = ImGui.InputTextWithHint("##rootDirectory", "Enter Root Directory here (MANDATORY)...", ref _newModDirectory, + RootDirectoryMaxLength, ImGuiInputTextFlags.EnterReturnsTrue); + } + + selected = ImGui.IsItemActive(); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); + ImGui.SameLine(); + DrawDirectoryPickerButton(); + style.Pop(); + ImGui.SameLine(); + + const string tt = "This is where Penumbra will store your extracted mod files.\n" + + "TTMP files are not copied, just extracted.\n" + + "This directory needs to be accessible and you need write access here.\n" + + "It is recommended that this directory is placed on a fast hard drive, preferably an SSD.\n" + + "It should also be placed near the root of a logical drive - the shorter the total path to this folder, the better.\n" + + "Definitely do not place it in your Dalamud directory or any sub-directory thereof."; + ImGuiComponents.HelpMarker(tt); + _tutorial.OpenTutorial(BasicTutorialSteps.GeneralTooltips); + ImGui.SameLine(); + ImGui.TextUnformatted("Root Directory"); + ImGuiUtil.HoverTooltip(tt); } - var selected = ImGui.IsItemActive(); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); - ImGui.SameLine(); - DrawDirectoryPickerButton(); - style.Pop(); - ImGui.SameLine(); - - const string tt = "This is where Penumbra will store your extracted mod files.\n" - + "TTMP files are not copied, just extracted.\n" - + "This directory needs to be accessible and you need write access here.\n" - + "It is recommended that this directory is placed on a fast hard drive, preferably an SSD.\n" - + "It should also be placed near the root of a logical drive - the shorter the total path to this folder, the better.\n" - + "Definitely do not place it in your Dalamud directory or any sub-directory thereof."; - ImGuiComponents.HelpMarker(tt); - _tutorial.OpenTutorial(BasicTutorialSteps.GeneralTooltips); - ImGui.SameLine(); - ImGui.TextUnformatted("Root Directory"); - ImGuiUtil.HoverTooltip(tt); - - group.Dispose(); _tutorial.OpenTutorial(BasicTutorialSteps.ModDirectory); ImGui.SameLine(); var pos = ImGui.GetCursorPosX(); @@ -685,7 +686,7 @@ public class SettingsTab : ITab foreach (var color in Enum.GetValues()) { var (defaultColor, name, description) = color.Data(); - var currentColor = _config.Colors.TryGetValue(color, out var current) ? current : defaultColor; + var currentColor = _config.Colors.GetValueOrDefault(color, defaultColor); if (Widget.ColorPicker(name, description, currentColor, c => _config.Colors[color] = c, defaultColor)) _config.Save(); } @@ -871,7 +872,7 @@ public class SettingsTab : ITab if (!_dalamudConfig.GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool value)) { using var disabled = ImRaii.Disabled(); - Checkbox("Wait for Plugins on Startup (Disabled, can not access Dalamud Configuration)", string.Empty, false, v => { }); + Checkbox("Wait for Plugins on Startup (Disabled, can not access Dalamud Configuration)", string.Empty, false, _ => { }); } else { @@ -923,7 +924,7 @@ public class SettingsTab : ITab return; var tagIdx = _sharedTags.Draw("Predefined Tags: ", - "Predefined tags that can be added or removed from mods with a single click.", _predefinedTagManager.SharedTags, + "Predefined tags that can be added or removed from mods with a single click.", _predefinedTagManager.PredefinedTags, out var editedTag); if (tagIdx >= 0) From 0e50a8a9e5155423ab8db2334a07861d83cf44db Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 21:01:48 +0100 Subject: [PATCH 0493/1381] More future proof structure for tags. --- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 2 +- Penumbra/UI/PredefinedTagManager.cs | 86 ++++++++++--------- Penumbra/UI/Tabs/SettingsTab.cs | 2 +- 4 files changed, 47 insertions(+), 45 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 4ad30a6f..ed6340ab 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -29,7 +29,7 @@ public class ModPanelDescriptionTab( ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); - var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.PredefinedTags.Count > 0 + var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.Count > 0 ? (true, ImGui.GetFrameHeight() + ImGui.GetStyle().WindowPadding.X + (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0)) : (false, 0); var tagIdx = _localTags.Draw("Local Tags: ", diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index a0e32c22..eb79869e 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -69,7 +69,7 @@ public class ModPanelEditTab( } UiHelpers.DefaultLineSpace(); - var sharedTagsEnabled = predefinedTagManager.PredefinedTags.Count > 0; + var sharedTagsEnabled = predefinedTagManager.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index 63be42de..17e8432b 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using ImGuiNET; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; @@ -12,8 +13,13 @@ using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra.UI; -public sealed class PredefinedTagManager : ISavable +public sealed class PredefinedTagManager : ISavable, IReadOnlyList { + public const int Version = 1; + + public record struct TagData + { } + private readonly ModManager _modManager; private readonly SaveService _saveService; @@ -21,17 +27,7 @@ public sealed class PredefinedTagManager : ISavable private uint _enabledColor; private uint _disabledColor; - - // Operations on this list assume that it is sorted and will keep it sorted if that is the case. - // The list also gets re-sorted when first loaded from config in case the config was modified. - [JsonRequired] - private readonly List _predefinedTags = []; - - [JsonIgnore] - public IReadOnlyList PredefinedTags - => _predefinedTags; - - public int ConfigVersion = 1; + private readonly SortedList _predefinedTags = []; public PredefinedTagManager(ModManager modManager, SaveService saveService) { @@ -47,8 +43,12 @@ public sealed class PredefinedTagManager : ISavable { using var jWriter = new JsonTextWriter(writer); jWriter.Formatting = Formatting.Indented; - var serializer = new JsonSerializer { Formatting = Formatting.Indented }; - serializer.Serialize(jWriter, this); + var jObj = new JObject() + { + ["Version"] = Version, + ["Tags"] = JObject.FromObject(_predefinedTags), + }; + jObj.WriteTo(jWriter); } public void Save() @@ -61,48 +61,38 @@ public sealed class PredefinedTagManager : ISavable try { - var text = File.ReadAllText(_saveService.FileNames.PredefinedTagFile); - JsonConvert.PopulateObject(text, this, new JsonSerializerSettings + var text = File.ReadAllText(_saveService.FileNames.PredefinedTagFile); + var jObj = JObject.Parse(text); + var version = jObj["Version"]?.ToObject() ?? 0; + switch (version) { - Error = HandleDeserializationError, - }); - - // Any changes to this within this class should keep it sorted, but in case someone went in and manually changed the JSON, run a sort on initial load. - _predefinedTags.Sort(); + case 1: + var tags = jObj["Tags"]?.ToObject>() ?? []; + foreach (var (tag, data) in tags) + _predefinedTags.TryAdd(tag, data); + break; + default: + throw new Exception($"Invalid version {version}."); + } } catch (Exception ex) { Penumbra.Messager.NotificationMessage(ex, - "Error reading shared tags Configuration, reverting to default.", - "Error reading shared tags Configuration", NotificationType.Error); - } - - return; - - static void HandleDeserializationError(object? sender, ErrorEventArgs errorArgs) - { - Penumbra.Log.Error( - $"Error parsing shared tags Configuration at {errorArgs.ErrorContext.Path}, using default or migrating:\n{errorArgs.ErrorContext.Error}"); - errorArgs.ErrorContext.Handled = true; + "Error reading predefined tags Configuration, reverting to default.", + "Error reading predefined tags Configuration", NotificationType.Error); } } public void ChangeSharedTag(int tagIdx, string tag) { - if (tagIdx < 0 || tagIdx > PredefinedTags.Count) + if (tagIdx < 0 || tagIdx > _predefinedTags.Count) return; - // In the case of editing a tag, remove what's there prior to doing an insert. - if (tagIdx != PredefinedTags.Count) + if (tagIdx != _predefinedTags.Count) _predefinedTags.RemoveAt(tagIdx); if (!string.IsNullOrEmpty(tag)) - { - // Taking advantage of the fact that BinarySearch returns the complement of the correct sorted position for the tag. - var existingIdx = _predefinedTags.BinarySearch(tag); - if (existingIdx < 0) - _predefinedTags.Insert(~existingIdx, tag); - } + _predefinedTags.TryAdd(tag, default); Save(); } @@ -147,7 +137,7 @@ public sealed class PredefinedTagManager : ISavable _enabledColor = ColorId.PredefinedTagAdd.Value(); _disabledColor = ColorId.PredefinedTagRemove.Value(); var (edited, others) = editLocal ? (localTags, modTags) : (modTags, localTags); - foreach (var (tag, idx) in PredefinedTags.WithIndex()) + foreach (var (tag, idx) in _predefinedTags.Keys.WithIndex()) { var tagIdx = edited.IndexOf(tag); var inOther = tagIdx < 0 && others.IndexOf(tag) >= 0; @@ -189,4 +179,16 @@ public sealed class PredefinedTagManager : ISavable private static float CalcTextButtonWidth(string text) => ImGui.CalcTextSize(text).X + 2 * ImGui.GetStyle().FramePadding.X; + + public IEnumerator GetEnumerator() + => _predefinedTags.Keys.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); + + public int Count + => _predefinedTags.Count; + + public string this[int index] + => _predefinedTags.Keys[index]; } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 9f8ffb38..80fe6fb6 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -924,7 +924,7 @@ public class SettingsTab : ITab return; var tagIdx = _sharedTags.Draw("Predefined Tags: ", - "Predefined tags that can be added or removed from mods with a single click.", _predefinedTagManager.PredefinedTags, + "Predefined tags that can be added or removed from mods with a single click.", _predefinedTagManager, out var editedTag); if (tagIdx >= 0) From c8216b0accd2d8ce99dc2ae44d50ac037e2daf45 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 19 Mar 2024 22:52:20 +0100 Subject: [PATCH 0494/1381] Use ObjectManager, Actor and Model. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/IpcTester.cs | 140 +++++++++--------- Penumbra/Api/PenumbraApi.cs | 47 +++--- .../Hooks/Animation/LoadCharacterVfx.cs | 26 ++-- .../Hooks/Animation/LoadTimelineResources.cs | 14 +- .../Hooks/Animation/ScheduleClipUpdate.cs | 6 +- .../Interop/Hooks/Animation/SomePapLoad.cs | 11 +- .../LiveColorTablePreviewer.cs | 3 +- .../MaterialPreview/LiveMaterialPreviewer.cs | 4 +- .../LiveMaterialPreviewerBase.cs | 5 +- .../Interop/MaterialPreview/MaterialInfo.cs | 36 ++--- .../PathResolving/CollectionResolver.cs | 32 ++-- .../Interop/PathResolving/CutsceneService.cs | 31 ++-- .../Interop/PathResolving/DrawObjectState.cs | 15 +- .../ResourceTree/ResourceTreeFactory.cs | 89 ++--------- .../Interop/ResourceTree/TreeBuildCache.cs | 41 ++--- Penumbra/Interop/Services/RedrawService.cs | 39 ++--- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 7 +- Penumbra/UI/PredefinedTagManager.cs | 3 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 7 +- Penumbra/UI/Tabs/ModsTab.cs | 5 +- 22 files changed, 240 insertions(+), 325 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 1df06807..d2a1406b 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 1df06807650a79813791effaa01fb7c4710b3dab +Subproject commit d2a1406bc32f715c0687613f02e3f74caf7ceea9 diff --git a/Penumbra.GameData b/Penumbra.GameData index d53db6a3..a1262e24 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d53db6a358cedecd3ef18f62f12a07deff4b61ee +Subproject commit a1262e242ca33bb0e9e4f080d294d9160b5e54eb diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 380b741c..e1dd81cb 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -1,3 +1,4 @@ +using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Interface; using Dalamud.Interface.Utility; using Dalamud.Plugin; @@ -18,6 +19,7 @@ using Penumbra.Collections.Manager; using Dalamud.Plugin.Services; using Penumbra.GameData.Structs; using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; namespace Penumbra.Api; @@ -40,7 +42,7 @@ public class IpcTester : IDisposable private readonly Temporary _temporary; private readonly ResourceTree _resourceTree; - public IpcTester(Configuration config, DalamudPluginInterface pi, IObjectTable objects, IClientState clientState, + public IpcTester(Configuration config, DalamudPluginInterface pi, ObjectManager objects, IClientState clientState, PenumbraIpcProviders ipcProviders, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService) { @@ -280,16 +282,16 @@ public class IpcTester : IDisposable { ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); using var popup = ImRaii.Popup("Config Popup"); - if (popup) - { - using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) - { - ImGuiUtil.TextWrapped(_currentConfiguration); - } + if (!popup) + return; - if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) - ImGui.CloseCurrentPopup(); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImGuiUtil.TextWrapped(_currentConfiguration); } + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + ImGui.CloseCurrentPopup(); } private void UpdateModDirectoryChanged(string path, bool valid) @@ -304,15 +306,15 @@ public class IpcTester : IDisposable public readonly EventSubscriber Tooltip; public readonly EventSubscriber Click; - private string _lastDrawnMod = string.Empty; - private DateTimeOffset _lastDrawnModTime = DateTimeOffset.MinValue; - private bool _subscribedToTooltip = false; - private bool _subscribedToClick = false; - private string _lastClicked = string.Empty; - private string _lastHovered = string.Empty; - private TabType _selectTab = TabType.None; - private string _modName = string.Empty; - private PenumbraApiEc _ec = PenumbraApiEc.Success; + private string _lastDrawnMod = string.Empty; + private DateTimeOffset _lastDrawnModTime = DateTimeOffset.MinValue; + private bool _subscribedToTooltip; + private bool _subscribedToClick; + private string _lastClicked = string.Empty; + private string _lastHovered = string.Empty; + private TabType _selectTab = TabType.None; + private string _modName = string.Empty; + private PenumbraApiEc _ec = PenumbraApiEc.Success; public Ui(DalamudPluginInterface pi) { @@ -401,14 +403,14 @@ public class IpcTester : IDisposable { private readonly DalamudPluginInterface _pi; private readonly IClientState _clientState; - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; public readonly EventSubscriber Redrawn; - private string _redrawName = string.Empty; - private int _redrawIndex = 0; + private string _redrawName = string.Empty; + private int _redrawIndex; private string _lastRedrawnString = "None"; - public Redrawing(DalamudPluginInterface pi, IObjectTable objects, IClientState clientState) + public Redrawing(DalamudPluginInterface pi, ObjectManager objects, IClientState clientState) { _pi = pi; _objects = objects; @@ -440,8 +442,8 @@ public class IpcTester : IDisposable DrawIntro(Ipc.RedrawObjectByIndex.Label, "Redraw by Index"); var tmp = _redrawIndex; ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.Length)) - _redrawIndex = Math.Clamp(tmp, 0, _objects.Length); + if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.Count)) + _redrawIndex = Math.Clamp(tmp, 0, _objects.Count); ImGui.SameLine(); if (ImGui.Button("Redraw##Index")) @@ -458,12 +460,12 @@ public class IpcTester : IDisposable private void SetLastRedrawn(IntPtr address, int index) { if (index < 0 - || index > _objects.Length + || index > _objects.Count || address == IntPtr.Zero - || _objects[index]?.Address != address) + || _objects[index].Address != address) _lastRedrawnString = "Invalid"; - _lastRedrawnString = $"{_objects[index]!.Name} (0x{address:X}, {index})"; + _lastRedrawnString = $"{_objects[index].Utf8Name} (0x{address:X}, {index})"; } } @@ -588,8 +590,8 @@ public class IpcTester : IDisposable private string _currentResolvePath = string.Empty; private string _currentResolveCharacter = string.Empty; private string _currentReversePath = string.Empty; - private int _currentReverseIdx = 0; - private Task<(string[], string[][])> _task = Task.FromException<(string[], string[][])>(new Exception()); + private int _currentReverseIdx; + private Task<(string[], string[][])> _task = Task.FromException<(string[], string[][])>(new Exception()); public Resolve(DalamudPluginInterface pi) => _pi = pi; @@ -696,8 +698,6 @@ public class IpcTester : IDisposable return text; } - ; - DrawIntro(Ipc.ResolvePlayerPaths.Label, "Resolved Paths (Player)"); if (forwardArray.Length > 0 || reverseArray.Length > 0) { @@ -721,18 +721,18 @@ public class IpcTester : IDisposable { private readonly DalamudPluginInterface _pi; - private int _objectIdx = 0; + private int _objectIdx; private string _collectionName = string.Empty; private bool _allowCreation = true; private bool _allowDeletion = true; private ApiCollectionType _type = ApiCollectionType.Current; private string _characterCollectionName = string.Empty; - private IList _collections = new List(); + private IList _collections = []; private string _changedItemCollection = string.Empty; private IReadOnlyDictionary _changedItems = new Dictionary(); private PenumbraApiEc _returnCode = PenumbraApiEc.Success; - private string? _oldCollection = null; + private string? _oldCollection; public Collections(DalamudPluginInterface pi) => _pi = pi; @@ -845,8 +845,8 @@ public class IpcTester : IDisposable { private readonly DalamudPluginInterface _pi; - private string _characterName = string.Empty; - private int _gameObjectIndex = 0; + private string _characterName = string.Empty; + private int _gameObjectIndex; public Meta(DalamudPluginInterface pi) => _pi = pi; @@ -1040,11 +1040,11 @@ public class IpcTester : IDisposable private string _settingsModName = string.Empty; private string _settingsCollection = string.Empty; private bool _settingsAllowInheritance = true; - private bool _settingsInherit = false; - private bool _settingsEnabled = false; - private int _settingsPriority = 0; + private bool _settingsInherit; + private bool _settingsEnabled; + private int _settingsPriority; private IDictionary, GroupType)>? _availableSettings; - private IDictionary>? _currentSettings = null; + private IDictionary>? _currentSettings; public ModSettings(DalamudPluginInterface pi) { @@ -1287,7 +1287,7 @@ public class IpcTester : IDisposable private string _tempFilePath = "test/success.mtrl"; private string _tempManipulation = string.Empty; private PenumbraApiEc _lastTempError; - private int _tempActorIndex = 0; + private int _tempActorIndex; private bool _forceOverwrite; public void Draw() @@ -1441,15 +1441,13 @@ public class IpcTester : IDisposable } } - private class ResourceTree + private class ResourceTree(DalamudPluginInterface pi, ObjectManager objects) { - private readonly DalamudPluginInterface _pi; - private readonly IObjectTable _objects; - private readonly Stopwatch _stopwatch = new(); + private readonly Stopwatch _stopwatch = new(); private string _gameObjectIndices = "0"; private ResourceType _type = ResourceType.Mtrl; - private bool _withUIData = false; + private bool _withUiData; private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcePaths; private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcePaths; @@ -1459,12 +1457,6 @@ public class IpcTester : IDisposable private (string, Ipc.ResourceTree)[]? _lastPlayerResourceTrees; private TimeSpan _lastCallDuration; - public ResourceTree(DalamudPluginInterface pi, IObjectTable objects) - { - _pi = pi; - _objects = objects; - } - public void Draw() { using var _ = ImRaii.TreeNode("Resource Tree"); @@ -1473,7 +1465,7 @@ public class IpcTester : IDisposable ImGui.InputText("GameObject indices", ref _gameObjectIndices, 511); ImGuiUtil.GenericEnumCombo("Resource type", ImGui.CalcItemWidth(), _type, out _type, Enum.GetValues()); - ImGui.Checkbox("Also get names and icons", ref _withUIData); + ImGui.Checkbox("Also get names and icons", ref _withUiData); using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); if (!table) @@ -1483,7 +1475,7 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourcePaths")) { var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourcePaths.Subscriber(_pi); + var subscriber = Ipc.GetGameObjectResourcePaths.Subscriber(pi); _stopwatch.Restart(); var resourcePaths = subscriber.Invoke(gameObjects); @@ -1499,7 +1491,7 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcePaths.Label, "Get local player resource paths"); if (ImGui.Button("Get##PlayerResourcePaths")) { - var subscriber = Ipc.GetPlayerResourcePaths.Subscriber(_pi); + var subscriber = Ipc.GetPlayerResourcePaths.Subscriber(pi); _stopwatch.Restart(); var resourcePaths = subscriber.Invoke(); @@ -1515,9 +1507,9 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourcesOfType")) { var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourcesOfType.Subscriber(_pi); + var subscriber = Ipc.GetGameObjectResourcesOfType.Subscriber(pi); _stopwatch.Restart(); - var resourcesOfType = subscriber.Invoke(_type, _withUIData, gameObjects); + var resourcesOfType = subscriber.Invoke(_type, _withUiData, gameObjects); _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourcesOfType = gameObjects @@ -1531,9 +1523,9 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourcesOfType.Label, "Get local player resources of type"); if (ImGui.Button("Get##PlayerResourcesOfType")) { - var subscriber = Ipc.GetPlayerResourcesOfType.Subscriber(_pi); + var subscriber = Ipc.GetPlayerResourcesOfType.Subscriber(pi); _stopwatch.Restart(); - var resourcesOfType = subscriber.Invoke(_type, _withUIData); + var resourcesOfType = subscriber.Invoke(_type, _withUiData); _lastCallDuration = _stopwatch.Elapsed; _lastPlayerResourcesOfType = resourcesOfType @@ -1547,9 +1539,9 @@ public class IpcTester : IDisposable if (ImGui.Button("Get##GameObjectResourceTrees")) { var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourceTrees.Subscriber(_pi); + var subscriber = Ipc.GetGameObjectResourceTrees.Subscriber(pi); _stopwatch.Restart(); - var trees = subscriber.Invoke(_withUIData, gameObjects); + var trees = subscriber.Invoke(_withUiData, gameObjects); _lastCallDuration = _stopwatch.Elapsed; _lastGameObjectResourceTrees = gameObjects @@ -1563,9 +1555,9 @@ public class IpcTester : IDisposable DrawIntro(Ipc.GetPlayerResourceTrees.Label, "Get local player resource trees"); if (ImGui.Button("Get##PlayerResourceTrees")) { - var subscriber = Ipc.GetPlayerResourceTrees.Subscriber(_pi); + var subscriber = Ipc.GetPlayerResourceTrees.Subscriber(pi); _stopwatch.Restart(); - var trees = subscriber.Invoke(_withUIData); + var trees = subscriber.Invoke(_withUiData); _lastCallDuration = _stopwatch.Elapsed; _lastPlayerResourceTrees = trees @@ -1666,13 +1658,13 @@ public class IpcTester : IDisposable { DrawWithHeaders(result, resources => { - using var table = ImRaii.Table(string.Empty, _withUIData ? 3 : 2, ImGuiTableFlags.SizingFixedFit); + using var table = ImRaii.Table(string.Empty, _withUiData ? 3 : 2, ImGuiTableFlags.SizingFixedFit); if (!table) return; ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.15f); - ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUIData ? 0.55f : 0.85f); - if (_withUIData) + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUiData ? 0.55f : 0.85f); + if (_withUiData) ImGui.TableSetupColumn("Icon & Name", ImGuiTableColumnFlags.WidthStretch, 0.3f); ImGui.TableHeadersRow(); @@ -1682,7 +1674,7 @@ public class IpcTester : IDisposable TextUnformattedMono($"0x{resourceHandle:X}"); ImGui.TableNextColumn(); ImGui.TextUnformatted(actualPath); - if (_withUIData) + if (_withUiData) { ImGui.TableNextColumn(); TextUnformattedMono(icon.ToString()); @@ -1699,11 +1691,11 @@ public class IpcTester : IDisposable { ImGui.TextUnformatted($"Name: {tree.Name}\nRaceCode: {(GenderRace)tree.RaceCode}"); - using var table = ImRaii.Table(string.Empty, _withUIData ? 7 : 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.Resizable); + using var table = ImRaii.Table(string.Empty, _withUiData ? 7 : 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.Resizable); if (!table) return; - if (_withUIData) + if (_withUiData) { ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch, 0.5f); ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.1f); @@ -1726,11 +1718,11 @@ public class IpcTester : IDisposable ImGui.TableNextColumn(); var hasChildren = node.Children.Any(); using var treeNode = ImRaii.TreeNode( - $"{(_withUIData ? node.Name ?? "Unknown" : node.Type)}##{node.ObjectAddress:X8}", + $"{(_withUiData ? node.Name ?? "Unknown" : node.Type)}##{node.ObjectAddress:X8}", hasChildren ? ImGuiTreeNodeFlags.SpanFullWidth : ImGuiTreeNodeFlags.SpanFullWidth | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen); - if (_withUIData) + if (_withUiData) { ImGui.TableNextColumn(); TextUnformattedMono(node.Type.ToString()); @@ -1770,10 +1762,10 @@ public class IpcTester : IDisposable private unsafe string GameObjectToString(ObjectIndex gameObjectIndex) { - var gameObject = _objects[gameObjectIndex.Index]; + var gameObject = objects[gameObjectIndex]; - return gameObject != null - ? $"[{gameObjectIndex}] {gameObject.Name} ({gameObject.ObjectKind})" + return gameObject.Valid + ? $"[{gameObjectIndex}] {gameObject.Utf8Name} ({(ObjectKind)gameObject.AsObject->ObjectKind})" : $"[{gameObjectIndex}] null"; } } diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index f5bb67bd..5146383d 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -20,6 +20,7 @@ using Penumbra.String.Classes; using Penumbra.Services; using Penumbra.Collections.Manager; using Penumbra.Communication; +using Penumbra.GameData.Interop; using Penumbra.Import.Textures; using Penumbra.Interop.Services; using Penumbra.UI; @@ -93,7 +94,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi private IDataManager _gameData; private IFramework _framework; - private IObjectTable _objects; + private ObjectManager _objects; private ModManager _modManager; private ResourceLoader _resourceLoader; private Configuration _config; @@ -111,7 +112,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi private TextureManager _textureManager; private ResourceTreeFactory _resourceTreeFactory; - public unsafe PenumbraApi(CommunicatorService communicator, IDataManager gameData, IFramework framework, IObjectTable objects, + public unsafe PenumbraApi(CommunicatorService communicator, IDataManager gameData, IFramework framework, ObjectManager objects, ModManager modManager, ResourceLoader resourceLoader, Configuration config, CollectionManager collectionManager, TempCollectionManager tempCollections, TempModManager tempMods, ActorManager actors, CollectionResolver collectionResolver, CutsceneService cutsceneService, ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, @@ -928,10 +929,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); - if (actorIndex < 0 || actorIndex >= _objects.Length) + if (actorIndex < 0 || actorIndex >= _objects.Count) return PenumbraApiEc.InvalidArgument; - var identifier = _actors.FromObject(_objects[actorIndex], false, false, true); + var identifier = _actors.FromObject(_objects[actorIndex], out _, false, false, true); if (!identifier.IsValid) return PenumbraApiEc.InvalidArgument; @@ -1076,11 +1077,11 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects) { - var characters = gameObjects.Select(index => _objects[index]).OfType(); + var characters = gameObjects.Select(index => _objects.GetDalamudObject((int) index)).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, 0); var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); - return Array.ConvertAll(gameObjects, obj => pathDictionaries.TryGetValue(obj, out var pathDict) ? pathDict : null); + return Array.ConvertAll(gameObjects, obj => pathDictionaries.GetValueOrDefault(obj)); } public IReadOnlyDictionary> GetPlayerResourcePaths() @@ -1091,39 +1092,39 @@ public class PenumbraApi : IDisposable, IPenumbraApi return pathDictionaries.AsReadOnly(); } - public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ResourceType type, bool withUIData, + public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ResourceType type, bool withUiData, params ushort[] gameObjects) { - var characters = gameObjects.Select(index => _objects[index]).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); + var characters = gameObjects.Select(index => _objects.GetDalamudObject((int)index)).OfType(); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); - return Array.ConvertAll(gameObjects, obj => resDictionaries.TryGetValue(obj, out var resDict) ? resDict : null); + return Array.ConvertAll(gameObjects, obj => resDictionaries.GetValueOrDefault(obj)); } public IReadOnlyDictionary> GetPlayerResourcesOfType(ResourceType type, - bool withUIData) + bool withUiData) { var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly - | (withUIData ? ResourceTreeFactory.Flags.WithUiData : 0)); + | (withUiData ? ResourceTreeFactory.Flags.WithUiData : 0)); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); return resDictionaries.AsReadOnly(); } - public Ipc.ResourceTree?[] GetGameObjectResourceTrees(bool withUIData, params ushort[] gameObjects) + public Ipc.ResourceTree?[] GetGameObjectResourceTrees(bool withUiData, params ushort[] gameObjects) { - var characters = gameObjects.Select(index => _objects[index]).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUIData ? ResourceTreeFactory.Flags.WithUiData : 0); + var characters = gameObjects.Select(index => _objects.GetDalamudObject((int)index)).OfType(); + var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); - return Array.ConvertAll(gameObjects, obj => resDictionary.TryGetValue(obj, out var nodes) ? nodes : null); + return Array.ConvertAll(gameObjects, obj => resDictionary.GetValueOrDefault(obj)); } - public IReadOnlyDictionary GetPlayerResourceTrees(bool withUIData) + public IReadOnlyDictionary GetPlayerResourceTrees(bool withUiData) { var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly - | (withUIData ? ResourceTreeFactory.Flags.WithUiData : 0)); + | (withUiData ? ResourceTreeFactory.Flags.WithUiData : 0)); var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); return resDictionary.AsReadOnly(); @@ -1165,11 +1166,11 @@ public class PenumbraApi : IDisposable, IPenumbraApi private unsafe bool AssociatedCollection(int gameObjectIdx, out ModCollection collection) { collection = _collectionManager.Active.Default; - if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Length) + if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Count) return false; - var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_objects.GetObjectAddress(gameObjectIdx); - var data = _collectionResolver.IdentifyCollection(ptr, false); + var ptr = _objects[gameObjectIdx]; + var data = _collectionResolver.IdentifyCollection(ptr.AsObject, false); if (data.Valid) collection = data.ModCollection; @@ -1179,10 +1180,10 @@ public class PenumbraApi : IDisposable, IPenumbraApi [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe ActorIdentifier AssociatedIdentifier(int gameObjectIdx) { - if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Length) + if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Count) return ActorIdentifier.Invalid; - var ptr = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)_objects.GetObjectAddress(gameObjectIdx); + var ptr = _objects[gameObjectIdx]; return _actors.FromObject(ptr, out _, false, true, true); } diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs index 69c22773..77aaa742 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs @@ -1,9 +1,9 @@ -using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.Collections; using Penumbra.CrashHandler.Buffers; using Penumbra.GameData; +using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; using Penumbra.Interop.Structs; using Penumbra.Services; @@ -16,10 +16,10 @@ public sealed unsafe class LoadCharacterVfx : FastHookGameObjectType switch { - 0 => _objects.SearchById(vfxParams->GameObjectId), + 0 => _objects.ById(vfxParams->GameObjectId), 2 => _objects[(int)vfxParams->GameObjectId], 4 => GetOwnedObject(vfxParams->GameObjectId), - _ => null, + _ => Actor.Null, }; - newData = obj != null + newData = obj.Valid ? _collectionResolver.IdentifyCollection((GameObject*)obj.Address, true) : ResolveData.Invalid; } var last = _state.SetAnimationData(newData); _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.LoadCharacterVfx); - var ret = Task.Result.Original(vfxPath, vfxParams, unk1, unk2, unk3, unk4); + var ret = Task.Result.Original(vfxPath, vfxParams, unk1, unk2, unk3, unk4); Penumbra.Log.Excessive( $"[Load Character VFX] Invoked with {new ByteString(vfxPath)}, 0x{vfxParams->GameObjectId:X}, {vfxParams->TargetCount}, {unk1}, {unk2}, {unk3}, {unk4} -> 0x{ret:X}."); _state.RestoreAnimationData(last); @@ -59,13 +59,11 @@ public sealed unsafe class LoadCharacterVfx : FastHook Search an object by its id, then get its minion/mount/ornament. - private Dalamud.Game.ClientState.Objects.Types.GameObject? GetOwnedObject(uint id) + private Actor GetOwnedObject(uint id) { - var owner = _objects.SearchById(id); - if (owner == null) - return null; - - var idx = ((GameObject*)owner.Address)->ObjectIndex; - return _objects[idx + 1]; + var owner = _objects.ById(id); + return !owner.Valid + ? Actor.Null + : _objects[owner.Index.Index + 1]; } } diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index ade957b9..4bae084e 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -3,8 +3,8 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.Collections; -using Penumbra.CrashHandler; using Penumbra.GameData; +using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; using Penumbra.Services; @@ -19,11 +19,11 @@ public sealed unsafe class LoadTimelineResources : FastHook Use timelines vfuncs to obtain the associated game object.
- public static ResolveData GetDataFromTimeline(IObjectTable objects, CollectionResolver resolver, nint timeline) + public static ResolveData GetDataFromTimeline(ObjectManager objects, CollectionResolver resolver, nint timeline) { try { @@ -64,10 +64,10 @@ public sealed unsafe class LoadTimelineResources : FastHook**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; var idx = getGameObjectIdx(timeline); - if (idx >= 0 && idx < objects.Length) + if (idx >= 0 && idx < objects.Count) { - var obj = (GameObject*)objects.GetObjectAddress(idx); - return obj != null ? resolver.IdentifyCollection(obj, true) : ResolveData.Invalid; + var obj = objects[idx]; + return obj.Valid ? resolver.IdentifyCollection(obj.AsObject, true) : ResolveData.Invalid; } } } diff --git a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs index 91b63838..342ffc25 100644 --- a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs +++ b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs @@ -1,7 +1,7 @@ -using Dalamud.Plugin.Services; using OtterGui.Services; using Penumbra.CrashHandler.Buffers; using Penumbra.GameData; +using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; using Penumbra.Interop.Structs; using Penumbra.Services; @@ -13,10 +13,10 @@ public sealed unsafe class ScheduleClipUpdate : FastHook { private readonly GameState _state; private readonly CollectionResolver _collectionResolver; - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; private readonly CrashHandlerService _crashHandler; - public SomePapLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver, IObjectTable objects, + public SomePapLoad(HookManager hooks, GameState state, CollectionResolver collectionResolver, ObjectManager objects, CrashHandlerService crashHandler) { _state = state; @@ -36,9 +35,9 @@ public sealed unsafe class SomePapLoad : FastHook if (timelinePtr != nint.Zero) { var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); - if (actorIdx >= 0 && actorIdx < _objects.Length) + if (actorIdx >= 0 && actorIdx < _objects.Count) { - var newData = _collectionResolver.IdentifyCollection((GameObject*)_objects.GetObjectAddress(actorIdx), true); + var newData = _collectionResolver.IdentifyCollection(_objects[actorIdx].AsObject, true); var last = _state.SetAnimationData(newData); _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.PapLoad); Task.Result.Original(a1, a2, a3, a4); diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index a8e4ea4d..4d35e68a 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; using Penumbra.Interop.SafeHandles; namespace Penumbra.Interop.MaterialPreview; @@ -20,7 +21,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase public Half[] ColorTable { get; } - public LiveColorTablePreviewer(IObjectTable objects, IFramework framework, MaterialInfo materialInfo) + public LiveColorTablePreviewer(ObjectManager objects, IFramework framework, MaterialInfo materialInfo) : base(objects, materialInfo) { _framework = framework; diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 9ed7ca3d..0556fdc4 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -1,5 +1,5 @@ -using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using Penumbra.GameData.Interop; namespace Penumbra.Interop.MaterialPreview; @@ -11,7 +11,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase private readonly float[] _originalMaterialParameter; private readonly uint[] _originalSamplerFlags; - public LiveMaterialPreviewer(IObjectTable objects, MaterialInfo materialInfo) + public LiveMaterialPreviewer(ObjectManager objects, MaterialInfo materialInfo) : base(objects, materialInfo) { var mtrlHandle = Material->MaterialResourceHandle; diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs index 07986f52..f176990e 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewerBase.cs @@ -1,12 +1,13 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.GameData.Interop; namespace Penumbra.Interop.MaterialPreview; public abstract unsafe class LiveMaterialPreviewerBase : IDisposable { - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; public readonly MaterialInfo MaterialInfo; public readonly CharacterBase* DrawObject; @@ -14,7 +15,7 @@ public abstract unsafe class LiveMaterialPreviewerBase : IDisposable protected bool Valid; - public LiveMaterialPreviewerBase(IObjectTable objects, MaterialInfo materialInfo) + public LiveMaterialPreviewerBase(ObjectManager objects, MaterialInfo materialInfo) { _objects = objects; diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index 686b5a86..61e7c764 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -1,10 +1,11 @@ -using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; using Penumbra.Interop.ResourceTree; using Penumbra.String; +using Model = Penumbra.GameData.Interop.Model; namespace Penumbra.Interop.MaterialPreview; @@ -18,13 +19,13 @@ public enum DrawObjectType public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectType Type, int ModelSlot, int MaterialSlot) { - public nint GetCharacter(IObjectTable objects) - => objects.GetObjectAddress(ObjectIndex.Index); + public Actor GetCharacter(ObjectManager objects) + => objects[ObjectIndex]; - public nint GetDrawObject(nint address) + public nint GetDrawObject(Actor address) => GetDrawObject(Type, address); - public unsafe Material* GetDrawObjectMaterial(IObjectTable objects) + public unsafe Material* GetDrawObjectMaterial(ObjectManager objects) => GetDrawObjectMaterial((CharacterBase*)GetDrawObject(GetCharacter(objects))); public unsafe Material* GetDrawObjectMaterial(CharacterBase* drawObject) @@ -60,13 +61,13 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy foreach (var type in Enum.GetValues()) { - var drawObject = (CharacterBase*)GetDrawObject(type, objectPtr); - if (drawObject == null) + var drawObject = GetDrawObject(type, objectPtr); + if (!drawObject.Valid) continue; - for (var i = 0; i < drawObject->SlotCount; ++i) + for (var i = 0; i < drawObject.AsCharacterBase->SlotCount; ++i) { - var model = drawObject->Models[i]; + var model = drawObject.AsCharacterBase->Models[i]; if (model == null) continue; @@ -88,19 +89,18 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy return result; } - private static unsafe nint GetDrawObject(DrawObjectType type, nint address) + private static unsafe Model GetDrawObject(DrawObjectType type, Actor address) { - var gameObject = (Character*)address; - if (gameObject == null) - return nint.Zero; + if (!address.Valid) + return Model.Null; return type switch { - DrawObjectType.Character => (nint)gameObject->GameObject.GetDrawObject(), - DrawObjectType.Mainhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.MainHand).DrawObject, - DrawObjectType.Offhand => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.OffHand).DrawObject, - DrawObjectType.Vfx => (nint)gameObject->DrawData.Weapon(DrawDataContainer.WeaponSlot.Unk).DrawObject, - _ => nint.Zero, + DrawObjectType.Character => address.Model, + DrawObjectType.Mainhand => address.AsCharacter->DrawData.Weapon(DrawDataContainer.WeaponSlot.MainHand).DrawObject, + DrawObjectType.Offhand => address.AsCharacter->DrawData.Weapon(DrawDataContainer.WeaponSlot.OffHand).DrawObject, + DrawObjectType.Vfx => address.AsCharacter->DrawData.Weapon(DrawDataContainer.WeaponSlot.Unk).DrawObject, + _ => Model.Null, }; } } diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 1a715f13..fa122e39 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -6,6 +6,7 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; using Penumbra.Util; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; using GameObject = FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject; @@ -170,10 +171,10 @@ public sealed unsafe class CollectionResolver( : null; /// Check for the Yourself collection. - private ModCollection? CheckYourself(ActorIdentifier identifier, GameObject* actor) + private ModCollection? CheckYourself(ActorIdentifier identifier, Actor actor) { - if (actor->ObjectIndex == 0 - || cutscenes.GetParentIndex(actor->ObjectIndex) == 0 + if (actor.Index == 0 + || cutscenes.GetParentIndex(actor.Index.Index) == 0 || identifier.Equals(actors.GetCurrentPlayer())) return collectionManager.Active.ByType(CollectionType.Yourself); @@ -181,23 +182,23 @@ public sealed unsafe class CollectionResolver( } /// Check special collections given the actor. Returns notYetReady if the customize array is not filled. - private ModCollection? CollectionByAttributes(GameObject* actor, ref bool notYetReady) + private ModCollection? CollectionByAttributes(Actor actor, ref bool notYetReady) { - if (!actor->IsCharacter()) + if (!actor.IsCharacter) return null; // Only handle human models. - var character = (Character*)actor; - if (!IsModelHuman((uint)character->CharacterData.ModelCharaId)) + + if (!IsModelHuman((uint)actor.AsCharacter->CharacterData.ModelCharaId)) return null; - if (character->DrawData.CustomizeData[0] == 0) + if (actor.Customize->Data[0] == 0) { notYetReady = true; return null; } - var bodyType = character->DrawData.CustomizeData[2]; + var bodyType = actor.Customize->Data[2]; var collection = bodyType switch { 3 => collectionManager.Active.ByType(CollectionType.NonPlayerElderly), @@ -207,9 +208,9 @@ public sealed unsafe class CollectionResolver( if (collection != null) return collection; - var race = (SubRace)character->DrawData.CustomizeData[4]; - var gender = (Gender)(character->DrawData.CustomizeData[1] + 1); - var isNpc = actor->ObjectKind != (byte)ObjectKind.Player; + var race = (SubRace)actor.Customize->Data[4]; + var gender = (Gender)(actor.Customize->Data[1] + 1); + var isNpc = !actor.IsPlayer; var type = CollectionTypeExtensions.FromParts(race, gender, isNpc); collection = collectionManager.Active.ByType(type); @@ -218,15 +219,14 @@ public sealed unsafe class CollectionResolver( } /// Get the collection applying to the owner if it is available. - private ModCollection? CheckOwnedCollection(ActorIdentifier identifier, GameObject* owner, ref bool notYetReady) + private ModCollection? CheckOwnedCollection(ActorIdentifier identifier, Actor owner, ref bool notYetReady) { - if (identifier.Type != IdentifierType.Owned || !config.UseOwnerNameForCharacterCollection || owner == null) + if (identifier.Type != IdentifierType.Owned || !config.UseOwnerNameForCharacterCollection || !owner.Valid) return null; var id = actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); - return CheckYourself(id, owner) - ?? CollectionByAttributes(owner, ref notYetReady); + return CheckYourself(id, owner) ?? CollectionByAttributes(owner, ref notYetReady); } } diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 89b9f917..93fee11e 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -3,6 +3,7 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; using Penumbra.Interop.Hooks.Objects; using Penumbra.String; @@ -14,17 +15,17 @@ public sealed class CutsceneService : IService, IDisposable public const int CutsceneEndIdx = (int)ScreenActor.CutsceneEnd; public const int CutsceneSlots = CutsceneEndIdx - CutsceneStartIdx; - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; private readonly CopyCharacter _copyCharacter; private readonly CharacterDestructor _characterDestructor; private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); public IEnumerable> Actors => Enumerable.Range(CutsceneStartIdx, CutsceneSlots) - .Where(i => _objects[i] != null) - .Select(i => KeyValuePair.Create(i, this[i] ?? _objects[i]!)); + .Where(i => _objects[i].Valid) + .Select(i => KeyValuePair.Create(i, this[i] ?? _objects.GetDalamudObject(i)!)); - public unsafe CutsceneService(IObjectTable objects, CopyCharacter copyCharacter, CharacterDestructor characterDestructor, + public unsafe CutsceneService(ObjectManager objects, CopyCharacter copyCharacter, CharacterDestructor characterDestructor, IClientState clientState) { _objects = objects; @@ -42,13 +43,13 @@ public sealed class CutsceneService : IService, IDisposable /// Does not check for valid input index. /// Returns null if no connected actor is set or the actor does not exist anymore. /// - public Dalamud.Game.ClientState.Objects.Types.GameObject? this[int idx] + private Dalamud.Game.ClientState.Objects.Types.GameObject? this[int idx] { get { Debug.Assert(idx is >= CutsceneStartIdx and < CutsceneEndIdx); idx = _copiedCharacters[idx - CutsceneStartIdx]; - return idx < 0 ? null : _objects[idx]; + return idx < 0 ? null : _objects.GetDalamudObject(idx); } } @@ -64,10 +65,10 @@ public sealed class CutsceneService : IService, IDisposable if (parentIdx is < -1 or >= CutsceneEndIdx) return false; - if (_objects.GetObjectAddress(copyIdx) == nint.Zero) + if (!_objects[copyIdx].Valid) return false; - if (parentIdx != -1 && _objects.GetObjectAddress(parentIdx) == nint.Zero) + if (parentIdx != -1 && !_objects[parentIdx].Valid) return false; _copiedCharacters[copyIdx - CutsceneStartIdx] = (short)parentIdx; @@ -99,9 +100,9 @@ public sealed class CutsceneService : IService, IDisposable { // A hack to deal with GPose actors leaving and thus losing the link, we just set the home world instead. // I do not think this breaks anything? - var address = (GameObject*)_objects.GetObjectAddress(i + CutsceneStartIdx); - if (address != null && address->GetObjectKind() is (byte)ObjectKind.Pc) - ((Character*)address)->HomeWorld = character->HomeWorld; + var address = _objects[i + CutsceneStartIdx]; + if (address.IsPlayer) + address.AsCharacter->HomeWorld = character->HomeWorld; _copiedCharacters[i] = -1; } @@ -125,7 +126,7 @@ public sealed class CutsceneService : IService, IDisposable /// Try to recover GPose actors on reloads into a running game. /// This is not 100% accurate due to world IDs, minions etc., but will be mostly sane. - private unsafe void RecoverGPoseActors() + private void RecoverGPoseActors() { Dictionary? actors = null; @@ -143,11 +144,11 @@ public sealed class CutsceneService : IService, IDisposable bool TryGetName(int idx, out ByteString name) { name = ByteString.Empty; - var address = (GameObject*)_objects.GetObjectAddress(idx); - if (address == null) + var address = _objects[idx]; + if (!address.Valid) return false; - name = new ByteString(address->Name); + name = address.Utf8Name; return !name.IsEmpty; } diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index b3ae108b..784ac3fb 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -1,8 +1,7 @@ -using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; -using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.GameData.Interop; using Object = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.Object; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.Objects; @@ -11,7 +10,7 @@ namespace Penumbra.Interop.PathResolving; public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary, IService { - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; private readonly CreateCharacterBase _createCharacterBase; private readonly WeaponReload _weaponReload; private readonly CharacterBaseDestructor _characterBaseDestructor; @@ -22,7 +21,7 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _gameState.LastGameObject; - public unsafe DrawObjectState(IObjectTable objects, CreateCharacterBase createCharacterBase, WeaponReload weaponReload, + public unsafe DrawObjectState(ObjectManager objects, CreateCharacterBase createCharacterBase, WeaponReload weaponReload, CharacterBaseDestructor characterBaseDestructor, GameState gameState) { _objects = objects; @@ -95,11 +94,11 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary private unsafe void InitializeDrawObjects() { - for (var i = 0; i < _objects.Length; ++i) + for (var i = 0; i < _objects.Count; ++i) { - var ptr = (GameObject*)_objects.GetObjectAddress(i); - if (ptr != null && ptr->IsCharacter() && ptr->DrawObject != null) - IterateDrawObjectTree(&ptr->DrawObject->Object, (nint)ptr, false, false); + var ptr = _objects[i]; + if (ptr is { IsCharacter: true, Model.Valid: true }) + IterateDrawObjectTree((Object*)ptr.Model.Address, ptr, false, false); } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index df5e1964..ae7187f0 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,39 +1,26 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Penumbra.Api.Enums; -using Penumbra.Collections; using Penumbra.GameData.Actors; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; -public class ResourceTreeFactory +public class ResourceTreeFactory( + IDataManager gameData, + ObjectManager objects, + CollectionResolver resolver, + ObjectIdentification identifier, + Configuration config, + ActorManager actors, + PathState pathState) { - private readonly IDataManager _gameData; - private readonly IObjectTable _objects; - private readonly CollectionResolver _collectionResolver; - private readonly ObjectIdentification _identifier; - private readonly Configuration _config; - private readonly ActorManager _actors; - private readonly PathState _pathState; - - public ResourceTreeFactory(IDataManager gameData, IObjectTable objects, CollectionResolver resolver, ObjectIdentification identifier, - Configuration config, ActorManager actors, PathState pathState) - { - _gameData = gameData; - _objects = objects; - _collectionResolver = resolver; - _identifier = identifier; - _config = config; - _actors = actors; - _pathState = pathState; - } - private TreeBuildCache CreateTreeBuildCache() - => new(_objects, _gameData, _actors); + => new(objects, gameData, actors); public IEnumerable GetLocalPlayerRelatedCharacters() { @@ -80,7 +67,7 @@ public class ResourceTreeFactory if (drawObjStruct == null) return null; - var collectionResolveData = _collectionResolver.IdentifyCollection(gameObjStruct, true); + var collectionResolveData = resolver.IdentifyCollection(gameObjStruct, true); if (!collectionResolveData.Valid) return null; @@ -89,9 +76,9 @@ public class ResourceTreeFactory var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name); - var globalContext = new GlobalResolveContext(_identifier, collectionResolveData.ModCollection, + var globalContext = new GlobalResolveContext(identifier, collectionResolveData.ModCollection, cache, (flags & Flags.WithUiData) != 0); - using (var _ = _pathState.EnterInternalResolve()) + using (var _ = pathState.EnterInternalResolve()) { tree.LoadResources(globalContext); } @@ -103,56 +90,12 @@ public class ResourceTreeFactory // ResolveGamePaths(tree, collectionResolveData.ModCollection); if (globalContext.WithUiData) ResolveUiData(tree); - FilterFullPaths(tree, (flags & Flags.RedactExternalPaths) != 0 ? _config.ModDirectory : null); + FilterFullPaths(tree, (flags & Flags.RedactExternalPaths) != 0 ? config.ModDirectory : null); Cleanup(tree); return tree; } - private static void ResolveGamePaths(ResourceTree tree, ModCollection collection) - { - var forwardDictionary = new Dictionary(); - var reverseDictionary = new Dictionary>(); - foreach (var node in tree.FlatNodes) - { - if (node.PossibleGamePaths.Length == 0 && !node.FullPath.InternalName.IsEmpty) - reverseDictionary.TryAdd(node.FullPath.ToPath(), null!); - else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) - forwardDictionary.TryAdd(node.GamePath, null); - } - - foreach (var key in forwardDictionary.Keys) - forwardDictionary[key] = collection.ResolvePath(key); - - var reverseResolvedArray = collection.ReverseResolvePaths(reverseDictionary.Keys); - foreach (var (key, set) in reverseDictionary.Keys.Zip(reverseResolvedArray)) - reverseDictionary[key] = set; - - foreach (var node in tree.FlatNodes) - { - if (node.PossibleGamePaths.Length == 0 && !node.FullPath.InternalName.IsEmpty) - { - if (!reverseDictionary.TryGetValue(node.FullPath.ToPath(), out var resolvedSet)) - continue; - - if (resolvedSet.Count != 1) - { - Penumbra.Log.Debug( - $"Found {resolvedSet.Count} game paths while reverse-resolving {node.FullPath} in {collection.Name}:"); - foreach (var gamePath in resolvedSet) - Penumbra.Log.Debug($"Game path: {gamePath}"); - } - - node.PossibleGamePaths = resolvedSet.ToArray(); - } - else if (node.FullPath.InternalName.IsEmpty && node.PossibleGamePaths.Length == 1) - { - if (forwardDictionary.TryGetValue(node.GamePath, out var resolved)) - node.FullPath = resolved ?? new FullPath(node.GamePath); - } - } - } - private static void ResolveUiData(ResourceTree tree) { foreach (var node in tree.FlatNodes) @@ -217,12 +160,12 @@ public class ResourceTreeFactory private unsafe (string Name, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache) { - var identifier = _actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); + var identifier = actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); switch (identifier.Type) { case IdentifierType.Player: return (identifier.PlayerName.ToString(), true); case IdentifierType.Owned: - var ownerChara = _objects.CreateObjectReference((nint)owner) as Dalamud.Game.ClientState.Objects.Types.Character; + var ownerChara = objects.Objects.CreateObjectReference(owner) as Dalamud.Game.ClientState.Objects.Types.Character; if (ownerChara != null) { var ownerName = GetCharacterName(ownerChara, cache); diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 7582c753..2798002a 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -3,19 +3,19 @@ using Dalamud.Plugin.Services; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; -using Penumbra.String; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; -internal readonly struct TreeBuildCache(IObjectTable objects, IDataManager dataManager, ActorManager actors) +internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager dataManager, ActorManager actors) { private readonly Dictionary _shaderPackages = []; public unsafe bool IsLocalPlayerRelated(Character character) { - var player = objects[0]; + var player = objects.GetDalamudObject(0); if (player == null) return false; @@ -31,30 +31,30 @@ internal readonly struct TreeBuildCache(IObjectTable objects, IDataManager dataM } public IEnumerable GetCharacters() - => objects.OfType(); + => objects.Objects.OfType(); public IEnumerable GetLocalPlayerRelatedCharacters() { - var player = objects[0]; + var player = objects.GetDalamudObject(0); if (player == null) yield break; yield return (Character)player; - var minion = objects[1]; + var minion = objects.GetDalamudObject(1); if (minion != null) yield return (Character)minion; var playerId = player.ObjectId; for (var i = 2; i < ObjectIndex.CutsceneStart.Index; i += 2) { - if (objects[i] is Character owned && owned.OwnerId == playerId) + if (objects.GetDalamudObject(i) is Character owned && owned.OwnerId == playerId) yield return owned; } for (var i = ObjectIndex.CutsceneStart.Index; i < ObjectIndex.CharacterScreen.Index; ++i) { - var character = objects[i] as Character; + var character = objects.GetDalamudObject((int) i) as Character; if (character == null) continue; @@ -62,34 +62,11 @@ internal readonly struct TreeBuildCache(IObjectTable objects, IDataManager dataM if (parent < 0) continue; - if (parent is 0 or 1 || objects[parent]?.OwnerId == playerId) + if (parent is 0 or 1 || objects.GetDalamudObject(parent)?.OwnerId == playerId) yield return character; } } - private unsafe ByteString GetPlayerName(GameObject player) - { - var gameObject = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)player.Address; - return new ByteString(gameObject->Name); - } - - private unsafe bool GetOwnedId(ByteString playerName, uint playerId, int idx, [NotNullWhen(true)] out Character? character) - { - character = objects[idx] as Character; - if (character == null) - return false; - - var actorId = actors.FromObject(character, out var owner, true, true, true); - if (!actorId.IsValid) - return false; - if (owner != null && owner->OwnerID != playerId) - return false; - if (actorId.Type is not IdentifierType.Player || !actorId.PlayerName.Equals(playerName)) - return false; - - return true; - } - /// Try to read a shpk file from the given path and cache it on success. public ShpkFile? ReadShaderPackage(FullPath path) => ReadFile(dataManager, path, _shaderPackages, bytes => new ShpkFile(bytes)); diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index e0a94d30..a6fec0b5 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -11,6 +11,7 @@ using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.GameData; using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; using Penumbra.Interop.Structs; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -57,7 +58,7 @@ public unsafe partial class RedrawService // this will be in obj and true will be returned. private bool FindCorrectActor(int idx, out GameObject? obj) { - obj = _objects[idx]; + obj = _objects.GetDalamudObject(idx); if (!InGPose || obj == null || IsGPoseActor(idx)) return false; @@ -70,21 +71,21 @@ public unsafe partial class RedrawService if (name == gPoseName) { - obj = _objects[GPosePlayerIdx + i]; + obj = _objects.GetDalamudObject(GPosePlayerIdx + i); return true; } } for (; _gPoseNameCounter < GPoseSlots; ++_gPoseNameCounter) { - var gPoseName = _objects[GPosePlayerIdx + _gPoseNameCounter]?.Name.ToString(); + var gPoseName = _objects.GetDalamudObject(GPosePlayerIdx + _gPoseNameCounter)?.Name.ToString(); _gPoseNames[_gPoseNameCounter] = gPoseName; if (gPoseName == null) break; if (name == gPoseName) { - obj = _objects[GPosePlayerIdx + _gPoseNameCounter]; + obj = _objects.GetDalamudObject(GPosePlayerIdx + _gPoseNameCounter); return true; } } @@ -111,7 +112,7 @@ public sealed unsafe partial class RedrawService : IDisposable private const int FurnitureIdx = 1337; private readonly IFramework _framework; - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; private readonly ITargetManager _targets; private readonly ICondition _conditions; private readonly IClientState _clientState; @@ -133,7 +134,7 @@ public sealed unsafe partial class RedrawService : IDisposable public event GameObjectRedrawnDelegate? GameObjectRedrawn; - public RedrawService(IFramework framework, IObjectTable objects, ITargetManager targets, ICondition conditions, IClientState clientState, + public RedrawService(IFramework framework, ObjectManager objects, ITargetManager targets, ICondition conditions, IClientState clientState, Configuration config, CommunicatorService communicator) { _framework = framework; @@ -170,7 +171,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) DisableDraw(actor!); - if (actor is PlayerCharacter && _objects[tableIndex + 1] is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) + if (actor is PlayerCharacter && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { *ActorDrawState(mountOrOrnament) |= DrawState.Invisibility; if (gPose) @@ -189,7 +190,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) EnableDraw(actor!); - if (actor is PlayerCharacter && _objects[tableIndex + 1] is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) + if (actor is PlayerCharacter && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { *ActorDrawState(mountOrOrnament) &= ~DrawState.Invisibility; if (gPose) @@ -212,7 +213,7 @@ public sealed unsafe partial class RedrawService : IDisposable private void ReloadActorAfterGPose(GameObject? actor) { - if (_objects[GPosePlayerIdx] != null) + if (_objects[GPosePlayerIdx].Valid) { ReloadActor(actor); return; @@ -230,7 +231,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (_target < 0) return; - var actor = _objects[_target]; + var actor = _objects.GetDalamudObject(_target); if (actor == null || _targets.Target != null) return; @@ -316,12 +317,12 @@ public sealed unsafe partial class RedrawService : IDisposable if (idx < 0) { var newIdx = ~idx; - WriteInvisible(_objects[newIdx]); + WriteInvisible(_objects.GetDalamudObject(newIdx)); _afterGPoseQueue[numKept++] = newIdx; } else { - WriteVisible(_objects[idx]); + WriteVisible(_objects.GetDalamudObject(idx)); } } @@ -357,8 +358,8 @@ public sealed unsafe partial class RedrawService : IDisposable private GameObject? GetLocalPlayer() { - var gPosePlayer = _objects[GPosePlayerIdx]; - return gPosePlayer ?? _objects[0]; + var gPosePlayer = _objects.GetDalamudObject(GPosePlayerIdx); + return gPosePlayer ?? _objects.GetDalamudObject(0); } public bool GetName(string lowerName, out GameObject? actor) @@ -379,7 +380,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (!ret && lowerName.Length > 1 && lowerName[0] == '#' && ushort.TryParse(lowerName[1..], out var objectIndex)) { ret = true; - actor = _objects[objectIndex]; + actor = _objects.GetDalamudObject((int) objectIndex); } return ret; @@ -387,8 +388,8 @@ public sealed unsafe partial class RedrawService : IDisposable public void RedrawObject(int tableIndex, RedrawType settings) { - if (tableIndex >= 0 && tableIndex < _objects.Length) - RedrawObject(_objects[tableIndex], settings); + if (tableIndex >= 0 && tableIndex < _objects.Count) + RedrawObject(_objects.GetDalamudObject(tableIndex), settings); } public void RedrawObject(string name, RedrawType settings) @@ -399,13 +400,13 @@ public sealed unsafe partial class RedrawService : IDisposable else if (GetName(lowerName, out var target)) RedrawObject(target, settings); else - foreach (var actor in _objects.Where(a => a.Name.ToString().ToLowerInvariant() == lowerName)) + foreach (var actor in _objects.Objects.Where(a => a.Name.ToString().ToLowerInvariant() == lowerName)) RedrawObject(actor, settings); } public void RedrawAll(RedrawType settings) { - foreach (var actor in _objects) + foreach (var actor in _objects.Objects) RedrawObject(actor, settings); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 72dd91d3..6cf24f62 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -12,6 +12,7 @@ using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; using Penumbra.Import.Models; using Penumbra.Import.Textures; using Penumbra.Interop.Hooks.Objects; @@ -46,7 +47,7 @@ public partial class ModEditWindow : Window, IDisposable private readonly IDragDropManager _dragDropManager; private readonly IDataManager _gameData; private readonly IFramework _framework; - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; private readonly CharacterBaseDestructor _characterBaseDestructor; private Vector2 _iconSize = Vector2.Zero; @@ -446,7 +447,7 @@ public partial class ModEditWindow : Window, IDisposable DrawOptionSelectHeader(); - var setsEqual = !_editor!.SwapEditor.Changes; + var setsEqual = !_editor.SwapEditor.Changes; var tt = setsEqual ? "No changes staged." : "Apply the currently staged changes to the option."; ImGui.NewLine(); if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, setsEqual)) @@ -577,7 +578,7 @@ public partial class ModEditWindow : Window, IDisposable Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, - ChangedItemDrawer changedItemDrawer, IObjectTable objects, IFramework framework, CharacterBaseDestructor characterBaseDestructor) + ChangedItemDrawer changedItemDrawer, ObjectManager objects, IFramework framework, CharacterBaseDestructor characterBaseDestructor) : base(WindowBaseLabel) { _performance = performance; diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index 17e8432b..0e5377d6 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -71,8 +71,7 @@ public sealed class PredefinedTagManager : ISavable, IReadOnlyList foreach (var (tag, data) in tags) _predefinedTags.TryAdd(tag, data); break; - default: - throw new Exception($"Invalid version {version}."); + default: throw new Exception($"Invalid version {version}."); } } catch (Exception ex) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index ab7ccf0c..2003f0ef 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -21,6 +21,7 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; using Penumbra.Import.Structs; using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; @@ -90,12 +91,12 @@ public class DebugTab : Window, ITab private readonly RedrawService _redraws; private readonly DictEmote _emotes; private readonly Diagnostics _diagnostics; - private readonly IObjectTable _objects; + private readonly ObjectManager _objects; private readonly IClientState _clientState; private readonly IpcTester _ipcTester; private readonly CrashHandlerPanel _crashHandlerPanel; - public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, IObjectTable objects, + public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, CharacterUtility characterUtility, ResidentResourceManager residentResources, @@ -430,7 +431,7 @@ public class DebugTab : Window, ITab DrawSpecial("Current Card", _actors.GetCardPlayer()); DrawSpecial("Current Glamour", _actors.GetGlamourPlayer()); - foreach (var obj in _objects) + foreach (var obj in _objects.Objects) { ImGuiUtil.DrawTableColumn($"{((GameObject*)obj.Address)->ObjectIndex}"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index bb8856b3..e4d94bb5 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -14,6 +14,7 @@ using Penumbra.Mods.Manager; using Penumbra.UI.ModsTab; using ModFileSystemSelector = Penumbra.UI.ModsTab.ModFileSystemSelector; using Penumbra.Collections.Manager; +using Penumbra.GameData.Interop; namespace Penumbra.UI.Tabs; @@ -28,7 +29,7 @@ public class ModsTab( IClientState clientState, CollectionSelectHeader collectionHeader, ITargetManager targets, - IObjectTable objectTable) + ObjectManager objects) : ITab { private readonly ActiveCollections _activeCollections = collectionManager.Active; @@ -128,7 +129,7 @@ public class ModsTab( using var disabled = ImRaii.Disabled(clientState.LocalPlayer == null); ImGui.SameLine(); var buttonWidth = frameHeight with { X = ImGui.GetContentRegionAvail().X / 5 }; - var tt = objectTable.GetObjectAddress(0) == nint.Zero + var tt = !objects[0].Valid ? "\nCan only be used when you are logged in and your character is available." : string.Empty; DrawButton(buttonWidth, "All", string.Empty, tt); From 26f3742b31b93787ed608b23c7cfbacf7b107876 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Mar 2024 15:27:51 +0100 Subject: [PATCH 0495/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index a1262e24..74a30576 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit a1262e242ca33bb0e9e4f080d294d9160b5e54eb +Subproject commit 74a305768880cd783b21e85ef97e9be77b119885 From 6cb4f7ac8a141faa908b0641ff7c6991ac582122 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Mar 2024 17:35:45 +0100 Subject: [PATCH 0496/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 74a30576..529e1811 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 74a305768880cd783b21e85ef97e9be77b119885 +Subproject commit 529e18115023732794994bfb8df4818b68951ea4 From e8fffa47a05d33e2c4f2e9364e72c2b61e0e71d2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Mar 2024 18:20:08 +0100 Subject: [PATCH 0497/1381] 1.0.2.0 --- Penumbra/UI/Changelog.cs | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 67ab1a87..8b00ab8d 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -47,18 +47,46 @@ public class PenumbraChangelog Add8_2_0(Changelog); Add8_3_0(Changelog); Add1_0_0_0(Changelog); + Add1_0_2_0(Changelog); } #region Changelogs + private static void Add1_0_2_0(Changelog log) + => log.NextVersion("Version 1.0.2.0") + .RegisterEntry("Updated to .net8 and XIV 6.58, using some new framework facilities to improve performance and stability.") + .RegisterHighlight( + "Added an experimental crash handler that is supposed to write a Penumbra.log file when the game crashes, containing Penumbra-specific information.") + .RegisterEntry("Various improvements to model import/export by ackwell (throughout all patches).") + .RegisterHighlight( + "Added predefined tags that can be setup in the Settings tab and can be more easily applied or removed from mods. (by DZD)") + .RegisterEntry( + "The first empty option in a single-select option group imported from a TTMP will now keep its location instead of being moved to the first option.") + .RegisterEntry("Further empty options are still removed.", 1) + .RegisterEntry("Made it more obvious if a user has not set their root directory yet.") + .RegisterEntry("Added the characterglass.shpk shader file to special shader treatment to fix issues when replacing it. (By Ny)") + .RegisterEntry("Fixed some issues with the file sizes of compressed files.") + .RegisterEntry("Fixed an issue where reloading a mod did not ensure settings for that mod being correct afterwards.") + .RegisterEntry("Added an option to automatically redraw the player character when saving files. (1.0.0.8)") + .RegisterEntry("Fixed issue with manipulating mods not triggering some events. (1.0.0.7)") + .RegisterEntry("Fixed issue with temporary mods not triggering some events. (1.0.0.6)") + .RegisterEntry("Fixed issue when renaming mods while the advanced edit window is open. (1.0.0.6)") + .RegisterEntry("Fixed issue with empty option groups. (1.0.0.5)") + .RegisterEntry("Fixed issues with cutscene character identification. (1.0.0.4)") + .RegisterEntry("Added locale environment information to support info. (1.0.0.4)") + .RegisterEntry("Fixed an issue with copied mod settings in IPC missing unused settings. (1.0.0.3)"); + private static void Add1_0_0_0(Changelog log) => log.NextVersion("Version 1.0.0.0") .RegisterHighlight("Mods in the mod selector can now be filtered by changed item categories.") .RegisterHighlight("Model Editing options in the Advanced Editing Window have been greatly extended (by ackwell):") .RegisterEntry("Attributes and referenced materials can now be set per mesh.", 1) - .RegisterEntry("Model files (.mdl) can now be exported to the well-established glTF format, which can be imported e.g. by Blender.", 1) + .RegisterEntry("Model files (.mdl) can now be exported to the well-established glTF format, which can be imported e.g. by Blender.", + 1) .RegisterEntry("glTF files can also be imported back to a .mdl file.", 1) - .RegisterHighlight("Model Export and Import are a work in progress and may encounter issues, not support all cases or produce wrong results, please let us know!", 1) + .RegisterHighlight( + "Model Export and Import are a work in progress and may encounter issues, not support all cases or produce wrong results, please let us know!", + 1) .RegisterEntry("The last selected mod and the open/close state of the Advanced Editing Window are now stored across launches.") .RegisterEntry("Footsteps of certain mounts will now be associated to collections correctly.") .RegisterEntry("Save-in-Place in the texture tab now requires the configurable modifier.") @@ -67,7 +95,8 @@ public class PenumbraChangelog .RegisterEntry("Fixed an issue with the mod panels header not updating its data when the selected mod updates.") .RegisterEntry("Fixed some issues with EQDP files for invalid characters.") .RegisterEntry("Fixed an issue with the FileDialog being drawn twice in certain situations.") - .RegisterEntry("A lot of backend changes that should not have an effect on users, but may cause issues if something got messed up."); + .RegisterEntry( + "A lot of backend changes that should not have an effect on users, but may cause issues if something got messed up."); private static void Add8_3_0(Changelog log) => log.NextVersion("Version 0.8.3.0") From fda77b49cdd79a60ede094262473088ca6f2ebf6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 20 Mar 2024 17:22:25 +0000 Subject: [PATCH 0498/1381] [CI] Updating repo.json for testing_1.0.2.0 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 1780c6c0..a4dc2f49 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.1.0", + "TestingAssemblyVersion": "1.0.2.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.0/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 978f41a4d9a282c53d5cbc176fecfe462acc75e3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Mar 2024 22:38:39 +0100 Subject: [PATCH 0499/1381] Make some stuff safer maybe. --- .../Buffers/MemoryMappedBuffer.cs | 60 +++++++++---------- Penumbra.CrashHandler/Program.cs | 19 ++++-- Penumbra/Services/ValidityChecker.cs | 44 +++++++------- 3 files changed, 67 insertions(+), 56 deletions(-) diff --git a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs index 35055864..c4e2627e 100644 --- a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs @@ -9,15 +9,15 @@ public class MemoryMappedBuffer : IDisposable { private const int MinHeaderLength = 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4; - private readonly MemoryMappedFile _file; - private readonly MemoryMappedViewAccessor _header; + private readonly MemoryMappedFile _file; + private readonly MemoryMappedViewAccessor _header; private readonly MemoryMappedViewAccessor[] _lines; - public readonly int Version; - public readonly uint LineCount; - public readonly uint LineCapacity; + public readonly int Version; + public readonly uint LineCount; + public readonly uint LineCapacity; private readonly uint _lineMask; - private bool _disposed; + private bool _disposed; protected uint CurrentLineCount { @@ -39,20 +39,20 @@ public class MemoryMappedBuffer : IDisposable public MemoryMappedBuffer(string mapName, int version, uint lineCount, uint lineCapacity) { - Version = version; - LineCount = BitOperations.RoundUpToPowerOf2(Math.Clamp(lineCount, 2, int.MaxValue >> 3)); + Version = version; + LineCount = BitOperations.RoundUpToPowerOf2(Math.Clamp(lineCount, 2, int.MaxValue >> 3)); LineCapacity = BitOperations.RoundUpToPowerOf2(Math.Clamp(lineCapacity, 2, int.MaxValue >> 3)); - _lineMask = LineCount - 1; - var fileName = Encoding.UTF8.GetBytes(mapName); + _lineMask = LineCount - 1; + var fileName = Encoding.UTF8.GetBytes(mapName); var headerLength = (uint)(4 + 4 + 4 + 4 + 4 + 4 + 4 + fileName.Length + 1); headerLength = (headerLength & 0b111) > 0 ? (headerLength & ~0b111u) + 0b1000 : headerLength; var capacity = LineCount * LineCapacity + headerLength; _file = MemoryMappedFile.CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.Inheritable); _header = _file.CreateViewAccessor(0, headerLength); - _header.Write(0, headerLength); - _header.Write(4, Version); - _header.Write(8, LineCount); + _header.Write(0, headerLength); + _header.Write(4, Version); + _header.Write(8, LineCount); _header.Write(12, LineCapacity); _header.WriteArray(28, fileName, 0, fileName.Length); _header.Write(fileName.Length + 28, (byte)0); @@ -65,16 +65,16 @@ public class MemoryMappedBuffer : IDisposable uint? expectedMinLineCapacity = null) { _file = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable); - using var headerLine = _file.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read); - var headerLength = headerLine.ReadUInt32(0); + using var headerLine = _file.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read); + var headerLength = headerLine.ReadUInt32(0); if (headerLength < MinHeaderLength) Throw($"Map {mapName} did not contain a valid header."); - _header = _file.CreateViewAccessor(0, headerLength, MemoryMappedFileAccess.ReadWrite); - Version = _header.ReadInt32(4); - LineCount = _header.ReadUInt32(8); + _header = _file.CreateViewAccessor(0, headerLength, MemoryMappedFileAccess.ReadWrite); + Version = _header.ReadInt32(4); + LineCount = _header.ReadUInt32(8); LineCapacity = _header.ReadUInt32(12); - _lineMask = LineCount - 1; + _lineMask = LineCount - 1; if (expectedVersion.HasValue && expectedVersion.Value != Version) Throw($"Map {mapName} has version {Version} instead of {expectedVersion.Value}."); @@ -122,25 +122,25 @@ public class MemoryMappedBuffer : IDisposable protected static int WriteString(string text, Span span) { - var bytes = Encoding.UTF8.GetBytes(text); - var length = bytes.Length + 1; + var bytes = Encoding.UTF8.GetBytes(text); + var source = (Span)bytes; + var length = source.Length + 1; if (length > span.Length) - throw new Exception($"String {text} is too long to write into span."); - - bytes.CopyTo(span); + source = source[..(span.Length - 1)]; + source.CopyTo(span); span[bytes.Length] = 0; - return length; + return source.Length + 1; } protected static int WriteSpan(ReadOnlySpan input, Span span) { var length = input.Length + 1; if (length > span.Length) - throw new Exception("Byte array is too long to write into span."); + input = input[..(span.Length - 1)]; input.CopyTo(span); span[input.Length] = 0; - return length; + return input.Length + 1; } protected Span GetLine(int i) @@ -150,7 +150,7 @@ public class MemoryMappedBuffer : IDisposable lock (_header) { - var lineIdx = CurrentLinePosition + i & _lineMask; + var lineIdx = (CurrentLinePosition + i) & _lineMask; if (lineIdx > CurrentLineCount) return null; @@ -168,8 +168,8 @@ public class MemoryMappedBuffer : IDisposable if (currentLineCount == LineCount) { var currentLinePos = CurrentLinePosition; - view = _lines[currentLinePos]!; - CurrentLinePosition = currentLinePos + 1 & _lineMask; + view = _lines[currentLinePos]!; + CurrentLinePosition = (currentLinePos + 1) & _lineMask; } else { diff --git a/Penumbra.CrashHandler/Program.cs b/Penumbra.CrashHandler/Program.cs index 518e2d04..0ea76ac6 100644 --- a/Penumbra.CrashHandler/Program.cs +++ b/Penumbra.CrashHandler/Program.cs @@ -14,12 +14,21 @@ public class CrashHandler { using var reader = new GameEventLogReader(); var parent = Process.GetProcessById(pid); - + using var handle = parent.SafeHandle; parent.WaitForExit(); - var exitCode = parent.ExitCode; - var obj = reader.Dump("Crash", pid, exitCode, args[2], args[3]); - using var fs = File.Open(args[0], FileMode.Create); - using var w = new Utf8JsonWriter(fs, new JsonWriterOptions { Indented = true }); + int exitCode; + try + { + exitCode = parent.ExitCode; + } + catch (Exception ex) + { + exitCode = -1; + } + + var obj = reader.Dump("Crash", pid, exitCode, args[2], args[3]); + using var fs = File.Open(args[0], FileMode.Create); + using var w = new Utf8JsonWriter(fs, new JsonWriterOptions { Indented = true }); obj.WriteTo(w, new JsonSerializerOptions() { WriteIndented = true }); } catch (Exception ex) diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index d4b5005f..cc70306b 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -21,7 +21,15 @@ public class ValidityChecker : IService public readonly string Version; public readonly string CommitHash; - public readonly string GameVersion; + + public unsafe string GameVersion + { + get + { + var framework = Framework.Instance(); + return framework == null ? string.Empty : framework->GameVersion[0]; + } + } public ValidityChecker(DalamudPluginInterface pi) { @@ -30,14 +38,10 @@ public class ValidityChecker : IService IsValidSourceRepo = CheckSourceRepo(pi); var assembly = GetType().Assembly; - Version = assembly.GetName().Version?.ToString() ?? string.Empty; - CommitHash = assembly.GetCustomAttribute()?.InformationalVersion ?? "Unknown"; - GameVersion = GetGameVersion(); + Version = assembly.GetName().Version?.ToString() ?? string.Empty; + CommitHash = assembly.GetCustomAttribute()?.InformationalVersion ?? "Unknown"; } - private static unsafe string GetGameVersion() - => Framework.Instance()->GameVersion[0]; - public void LogExceptions() { if (ImcExceptions.Count > 0) @@ -49,16 +53,16 @@ public class ValidityChecker : IService private static bool CheckDevPluginPenumbra(DalamudPluginInterface pi) { #if !DEBUG - var path = Path.Combine( pi.DalamudAssetDirectory.Parent?.FullName ?? "INVALIDPATH", "devPlugins", "Penumbra" ); - var dir = new DirectoryInfo( path ); + var path = Path.Combine(pi.DalamudAssetDirectory.Parent?.FullName ?? "INVALIDPATH", "devPlugins", "Penumbra"); + var dir = new DirectoryInfo(path); try { - return dir.Exists && dir.EnumerateFiles( "*.dll", SearchOption.AllDirectories ).Any(); + return dir.Exists && dir.EnumerateFiles("*.dll", SearchOption.AllDirectories).Any(); } - catch( Exception e ) + catch (Exception e) { - Penumbra.Log.Error( $"Could not check for dev plugin Penumbra:\n{e}" ); + Penumbra.Log.Error($"Could not check for dev plugin Penumbra:\n{e}"); return true; } #else @@ -71,11 +75,9 @@ public class ValidityChecker : IService { #if !DEBUG var checkedDirectory = pi.AssemblyLocation.Directory?.Parent?.Parent?.Name; - var ret = checkedDirectory?.Equals( "installedPlugins", StringComparison.OrdinalIgnoreCase ) ?? false; - if( !ret ) - { - Penumbra.Log.Error( $"Penumbra is not correctly installed. Application loaded from \"{pi.AssemblyLocation.Directory!.FullName}\"." ); - } + var ret = checkedDirectory?.Equals("installedPlugins", StringComparison.OrdinalIgnoreCase) ?? false; + if (!ret) + Penumbra.Log.Error($"Penumbra is not correctly installed. Application loaded from \"{pi.AssemblyLocation.Directory!.FullName}\"."); return !ret; #else @@ -89,10 +91,10 @@ public class ValidityChecker : IService #if !DEBUG return pi.SourceRepository?.Trim().ToLowerInvariant() switch { - null => false, - RepositoryLower => true, - SeaOfStarsLower => true, - _ => false, + null => false, + RepositoryLower => true, + SeaOfStarsLower => true, + _ => false, }; #else return true; From 384b8fd489c1e4b952703ed1d75544875bf790c8 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 20 Mar 2024 21:40:54 +0000 Subject: [PATCH 0500/1381] [CI] Updating repo.json for testing_1.0.2.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a4dc2f49..9487b2b3 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.0", + "TestingAssemblyVersion": "1.0.2.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0ad769e08e5c3b92249ff7bc1f3ac65878e73449 Mon Sep 17 00:00:00 2001 From: AeAstralis Date: Wed, 20 Mar 2024 22:33:35 -0400 Subject: [PATCH 0501/1381] Add tri count per LoD to models tab Adds the tri count of each LoD on the selected model to the Models tab under Advanced Editing. --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 67ec97f2..494ad3f6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -508,6 +508,11 @@ public partial class ModEditWindow ImGuiUtil.DrawTableColumn(file.VertexDeclarations.Length.ToString()); ImGuiUtil.DrawTableColumn("Stack Size"); ImGuiUtil.DrawTableColumn(file.StackSize.ToString()); + for (var lod = 0; lod < file.Lods.Length; lod++) + { + ImGuiUtil.DrawTableColumn("LoD " + lod + " Triangle Count"); + ImGuiUtil.DrawTableColumn(GetTriangleCountForLod(file, lod).ToString()); + } } } @@ -555,6 +560,18 @@ public partial class ModEditWindow return file != null; } + private static long GetTriangleCountForLod(MdlFile model, int lod) + { + var vertSum = 0u; + var meshIndex = model.Lods[lod].MeshIndex; + var meshCount = model.Lods[lod].MeshCount; + + for (var i = meshIndex; i < meshIndex + meshCount; i++) + vertSum += model.Meshes[i].IndexCount; + + return vertSum / 3; + } + private static readonly string[] ValidModelExtensions = [ ".gltf", From 739b5b5ad6a7c58c0d95c90557bf44c4a342e895 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 20 Mar 2024 20:02:09 +0100 Subject: [PATCH 0502/1381] CS-ify ShaderReplacementFixer and ModelRenderer --- Penumbra/Interop/Services/ModelRenderer.cs | 25 ++++++------------- .../Services/ShaderReplacementFixer.cs | 20 +++++---------- 2 files changed, 14 insertions(+), 31 deletions(-) diff --git a/Penumbra/Interop/Services/ModelRenderer.cs b/Penumbra/Interop/Services/ModelRenderer.cs index 6a3bf776..7df83cf7 100644 --- a/Penumbra/Interop/Services/ModelRenderer.cs +++ b/Penumbra/Interop/Services/ModelRenderer.cs @@ -1,35 +1,26 @@ using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; -using Penumbra.GameData; namespace Penumbra.Interop.Services; -// TODO ClientStructs-ify (https://github.com/aers/FFXIVClientStructs/pull/817) public unsafe class ModelRenderer : IDisposable { - // Will be Manager.Instance()->ModelRenderer.CharacterGlassShaderPackage in CS - private const nint ModelRendererOffset = 0x13660; - private const nint CharacterGlassShaderPackageOffset = 0xD0; - - /// A static pointer to the Render::Manager address. - [Signature(Sigs.RenderManager, ScanType = ScanType.StaticAddress)] - private readonly nint* _renderManagerAddress = null; - public bool Ready { get; private set; } public ShaderPackageResourceHandle** CharacterGlassShaderPackage - => *_renderManagerAddress == 0 - ? null - : (ShaderPackageResourceHandle**)(*_renderManagerAddress + ModelRendererOffset + CharacterGlassShaderPackageOffset).ToPointer(); + => Manager.Instance() switch + { + null => null, + var renderManager => &renderManager->ModelRenderer.CharacterGlassShaderPackage, + }; public ShaderPackageResourceHandle* DefaultCharacterGlassShaderPackage { get; private set; } private readonly IFramework _framework; - public ModelRenderer(IFramework framework, IGameInteropProvider interop) + public ModelRenderer(IFramework framework) { - interop.InitializeFromAttributes(this); _framework = framework; LoadDefaultResources(null!); if (!Ready) @@ -39,7 +30,7 @@ public unsafe class ModelRenderer : IDisposable /// We store the default data of the resources so we can always restore them. private void LoadDefaultResources(object _) { - if (*_renderManagerAddress == 0) + if (Manager.Instance() == null) return; var anyMissing = false; diff --git a/Penumbra/Interop/Services/ShaderReplacementFixer.cs b/Penumbra/Interop/Services/ShaderReplacementFixer.cs index e57fe313..26906ace 100644 --- a/Penumbra/Interop/Services/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Services/ShaderReplacementFixer.cs @@ -2,12 +2,14 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Classes; using Penumbra.Communication; using Penumbra.GameData; using Penumbra.Interop.Hooks.Resources; using Penumbra.Services; +using CSModelRenderer = FFXIVClientStructs.FFXIV.Client.Graphics.Render.ModelRenderer; namespace Penumbra.Interop.Services; @@ -22,18 +24,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] private readonly nint* _humanVTable = null!; - private delegate nint CharacterBaseOnRenderMaterialDelegate(nint drawObject, OnRenderMaterialParams* param); - private delegate nint ModelRendererOnRenderMaterialDelegate(nint modelRenderer, nint outFlags, nint param, Material* material, uint materialIndex); - - [StructLayout(LayoutKind.Explicit)] - private struct OnRenderMaterialParams - { - [FieldOffset(0x0)] - public Model* Model; - - [FieldOffset(0x8)] - public uint MaterialIndex; - } + private delegate nint CharacterBaseOnRenderMaterialDelegate(CharacterBase* drawObject, CSModelRenderer.OnRenderMaterialParams* param); + private delegate nint ModelRendererOnRenderMaterialDelegate(CSModelRenderer* modelRenderer, ushort* outFlags, CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex); private readonly Hook _humanOnRenderMaterialHook; @@ -135,7 +127,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable Interlocked.Decrement(ref _moddedCharacterGlassShpkCount); } - private nint OnRenderHumanMaterial(nint human, OnRenderMaterialParams* param) + private nint OnRenderHumanMaterial(CharacterBase* human, CSModelRenderer.OnRenderMaterialParams* param) { // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. if (!Enabled || _moddedSkinShpkCount == 0) @@ -167,7 +159,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable } } - private nint ModelRendererOnRenderMaterialDetour(nint modelRenderer, nint outFlags, nint param, Material* material, uint materialIndex) + private nint ModelRendererOnRenderMaterialDetour(CSModelRenderer* modelRenderer, ushort* outFlags, CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex) { // If we don't have any on-screen instances of modded characterglass.shpk, we don't need the slow path at all. From c55d6966cd02e0d765ddfccfd928649680592206 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Mar 2024 14:28:57 +0100 Subject: [PATCH 0503/1381] Update Internal csproj. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index b4b14367..2bbb9b2a 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit b4b14367d8235eabedd561ad3626beb1d2a83889 +Subproject commit 2bbb9b2a8a4479461b252594b9d1b788b551c13c From f3ceb9034e8ad4456e6541fbe3d61024e7a55a55 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Mar 2024 20:27:55 +0100 Subject: [PATCH 0504/1381] Make crashhandler somewhat more stable, support multi boxing maybe? --- .../Buffers/AnimationInvocationBuffer.cs | 16 ++-- .../Buffers/CharacterBaseBuffer.cs | 16 ++-- .../Buffers/MemoryMappedBuffer.cs | 12 +-- .../Buffers/ModdedFileBuffer.cs | 16 ++-- Penumbra.CrashHandler/GameEventLogReader.cs | 8 +- Penumbra.CrashHandler/GameEventLogWriter.cs | 8 +- Penumbra.CrashHandler/Program.cs | 2 +- Penumbra/Services/CrashHandlerService.cs | 88 ++++++++++++++----- 8 files changed, 105 insertions(+), 61 deletions(-) diff --git a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs index dd966542..c92a14fd 100644 --- a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs @@ -88,18 +88,18 @@ internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimation } } - public static IBufferReader CreateReader() - => new AnimationInvocationBuffer(false); + public static IBufferReader CreateReader(int pid) + => new AnimationInvocationBuffer(false, pid); - public static IAnimationInvocationBufferWriter CreateWriter() - => new AnimationInvocationBuffer(); + public static IAnimationInvocationBufferWriter CreateWriter(int pid) + => new AnimationInvocationBuffer(pid); - private AnimationInvocationBuffer(bool writer) - : base(_name, _version) + private AnimationInvocationBuffer(bool writer, int pid) + : base($"{_name}_{pid}_{_version}", _version) { } - private AnimationInvocationBuffer() - : base(_name, _version, _lineCount, _lineCapacity) + private AnimationInvocationBuffer(int pid) + : base($"{_name}_{pid}_{_version}", _version, _lineCount, _lineCapacity) { } private static string ToName(AnimationInvocationType type) diff --git a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs index 1fe5d7ba..d83c6e6c 100644 --- a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs @@ -69,17 +69,17 @@ internal sealed class CharacterBaseBuffer : MemoryMappedBuffer, ICharacterBaseBu public uint TotalCount => TotalWrittenLines; - public static IBufferReader CreateReader() - => new CharacterBaseBuffer(false); + public static IBufferReader CreateReader(int pid) + => new CharacterBaseBuffer(false, pid); - public static ICharacterBaseBufferWriter CreateWriter() - => new CharacterBaseBuffer(); + public static ICharacterBaseBufferWriter CreateWriter(int pid) + => new CharacterBaseBuffer(pid); - private CharacterBaseBuffer(bool writer) - : base(_name, _version) + private CharacterBaseBuffer(bool writer, int pid) + : base($"{_name}_{pid}_{_version}", _version) { } - private CharacterBaseBuffer() - : base(_name, _version, _lineCount, _lineCapacity) + private CharacterBaseBuffer(int pid) + : base($"{_name}_{pid}_{_version}", _version, _lineCount, _lineCapacity) { } } diff --git a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs index c4e2627e..a1b3de52 100644 --- a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs @@ -11,7 +11,7 @@ public class MemoryMappedBuffer : IDisposable private readonly MemoryMappedFile _file; private readonly MemoryMappedViewAccessor _header; - private readonly MemoryMappedViewAccessor[] _lines; + private readonly MemoryMappedViewAccessor[] _lines = []; public readonly int Version; public readonly uint LineCount; @@ -64,7 +64,8 @@ public class MemoryMappedBuffer : IDisposable public MemoryMappedBuffer(string mapName, int? expectedVersion = null, uint? expectedMinLineCount = null, uint? expectedMinLineCapacity = null) { - _file = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable); + _lines = []; + _file = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable); using var headerLine = _file.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read); var headerLength = headerLine.ReadUInt32(0); if (headerLength < MinHeaderLength) @@ -96,6 +97,7 @@ public class MemoryMappedBuffer : IDisposable void Throw(string text) { _file.Dispose(); + _header?.Dispose(); _disposed = true; throw new Exception(text); } @@ -204,10 +206,10 @@ public class MemoryMappedBuffer : IDisposable if (_disposed) return; - _header.Dispose(); + _header?.Dispose(); foreach (var line in _lines) - line.Dispose(); - _file.Dispose(); + line?.Dispose(); + _file?.Dispose(); } ~MemoryMappedBuffer() diff --git a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs index b472d413..6c774e4b 100644 --- a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs @@ -83,17 +83,17 @@ internal sealed class ModdedFileBuffer : MemoryMappedBuffer, IModdedFileBufferWr } } - public static IBufferReader CreateReader() - => new ModdedFileBuffer(false); + public static IBufferReader CreateReader(int pid) + => new ModdedFileBuffer(false, pid); - public static IModdedFileBufferWriter CreateWriter() - => new ModdedFileBuffer(); + public static IModdedFileBufferWriter CreateWriter(int pid) + => new ModdedFileBuffer(pid); - private ModdedFileBuffer(bool writer) - : base(_name, _version) + private ModdedFileBuffer(bool writer, int pid) + : base($"{_name}_{pid}_{_version}", _version) { } - private ModdedFileBuffer() - : base(_name, _version, _lineCount, _lineCapacity) + private ModdedFileBuffer(int pid) + : base($"{_name}_{pid}_{_version}", _version, _lineCount, _lineCapacity) { } } diff --git a/Penumbra.CrashHandler/GameEventLogReader.cs b/Penumbra.CrashHandler/GameEventLogReader.cs index 1ae49fa5..1813a671 100644 --- a/Penumbra.CrashHandler/GameEventLogReader.cs +++ b/Penumbra.CrashHandler/GameEventLogReader.cs @@ -9,13 +9,13 @@ public interface IBufferReader public IEnumerable GetLines(DateTimeOffset crashTime); } -public sealed class GameEventLogReader : IDisposable +public sealed class GameEventLogReader(int pid) : IDisposable { public readonly (IBufferReader Reader, string TypeSingular, string TypePlural)[] Readers = [ - (CharacterBaseBuffer.CreateReader(), "CharacterLoaded", "CharactersLoaded"), - (ModdedFileBuffer.CreateReader(), "ModdedFileLoaded", "ModdedFilesLoaded"), - (AnimationInvocationBuffer.CreateReader(), "VFXFuncInvoked", "VFXFuncsInvoked"), + (CharacterBaseBuffer.CreateReader(pid), "CharacterLoaded", "CharactersLoaded"), + (ModdedFileBuffer.CreateReader(pid), "ModdedFileLoaded", "ModdedFilesLoaded"), + (AnimationInvocationBuffer.CreateReader(pid), "VFXFuncInvoked", "VFXFuncsInvoked"), ]; public void Dispose() diff --git a/Penumbra.CrashHandler/GameEventLogWriter.cs b/Penumbra.CrashHandler/GameEventLogWriter.cs index 8e809cec..e2c461f4 100644 --- a/Penumbra.CrashHandler/GameEventLogWriter.cs +++ b/Penumbra.CrashHandler/GameEventLogWriter.cs @@ -2,11 +2,11 @@ namespace Penumbra.CrashHandler; -public sealed class GameEventLogWriter : IDisposable +public sealed class GameEventLogWriter(int pid) : IDisposable { - public readonly ICharacterBaseBufferWriter CharacterBase = CharacterBaseBuffer.CreateWriter(); - public readonly IModdedFileBufferWriter FileLoaded = ModdedFileBuffer.CreateWriter(); - public readonly IAnimationInvocationBufferWriter AnimationFuncInvoked = AnimationInvocationBuffer.CreateWriter(); + public readonly ICharacterBaseBufferWriter CharacterBase = CharacterBaseBuffer.CreateWriter(pid); + public readonly IModdedFileBufferWriter FileLoaded = ModdedFileBuffer.CreateWriter(pid); + public readonly IAnimationInvocationBufferWriter AnimationFuncInvoked = AnimationInvocationBuffer.CreateWriter(pid); public void Dispose() { diff --git a/Penumbra.CrashHandler/Program.cs b/Penumbra.CrashHandler/Program.cs index 0ea76ac6..94e90bfc 100644 --- a/Penumbra.CrashHandler/Program.cs +++ b/Penumbra.CrashHandler/Program.cs @@ -12,7 +12,7 @@ public class CrashHandler try { - using var reader = new GameEventLogReader(); + using var reader = new GameEventLogReader(pid); var parent = Process.GetProcessById(pid); using var handle = parent.SafeHandle; parent.WaitForExit(); diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index a3a35b78..c713d623 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -24,6 +24,8 @@ public sealed class CrashHandlerService : IDisposable, IService private readonly Configuration _config; private readonly ValidityChecker _validityChecker; + private string _tempExecutableDirectory = string.Empty; + public CrashHandlerService(FilenameService files, CommunicatorService communicator, ActorManager actors, ResourceLoader resourceLoader, Configuration config, ValidityChecker validityChecker) { @@ -54,6 +56,7 @@ public sealed class CrashHandlerService : IDisposable, IService } Unsubscribe(); + CleanExecutables(); } private Process? _child; @@ -177,11 +180,12 @@ public sealed class CrashHandlerService : IDisposable, IService try { - using var reader = new GameEventLogReader(); + using var reader = new GameEventLogReader(Environment.ProcessId); JsonObject jObj; lock (_eventWriter) { - jObj = reader.Dump("Manual Dump", Environment.ProcessId, 0, $"{_validityChecker.Version} ({_validityChecker.CommitHash})", _validityChecker.GameVersion); + jObj = reader.Dump("Manual Dump", Environment.ProcessId, 0, $"{_validityChecker.Version} ({_validityChecker.CommitHash})", + _validityChecker.GameVersion); } var logFile = _files.LogFileName; @@ -198,14 +202,31 @@ public sealed class CrashHandlerService : IDisposable, IService } } - private string CopyExecutables() + private void CleanExecutables() { var parent = Path.GetDirectoryName(_files.CrashHandlerExe)!; - var folder = Path.Combine(parent, "temp"); - Directory.CreateDirectory(folder); + foreach (var dir in Directory.EnumerateDirectories(parent, "temp_*")) + { + try + { + Directory.Delete(dir, true); + } + catch (Exception ex) + { + Penumbra.Log.Debug($"Could not delete {dir}:\n{ex}"); + } + } + } + + private string CopyExecutables() + { + CleanExecutables(); + var parent = Path.GetDirectoryName(_files.CrashHandlerExe)!; + _tempExecutableDirectory = Path.Combine(parent, $"temp_{Environment.ProcessId}"); + Directory.CreateDirectory(_tempExecutableDirectory); foreach (var file in Directory.EnumerateFiles(parent, "Penumbra.CrashHandler.*")) - File.Copy(file, Path.Combine(folder, Path.GetFileName(file)), true); - return Path.Combine(folder, Path.GetFileName(_files.CrashHandlerExe)); + File.Copy(file, Path.Combine(_tempExecutableDirectory, Path.GetFileName(file)), true); + return Path.Combine(_tempExecutableDirectory, Path.GetFileName(_files.CrashHandlerExe)); } public void LogAnimation(nint character, ModCollection collection, AnimationInvocationType type) @@ -213,10 +234,17 @@ public sealed class CrashHandlerService : IDisposable, IService if (_eventWriter == null) return; - var name = GetActorName(character); - lock (_eventWriter) + try { - _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Name, type); + var name = GetActorName(character); + lock (_eventWriter) + { + _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Name, type); + } + } + catch (Exception ex) + { + Penumbra.Log.Warning($"Error logging animation function {type} to crash handler:\n{ex}"); } } @@ -225,11 +253,18 @@ public sealed class CrashHandlerService : IDisposable, IService if (_eventWriter == null) return; - var name = GetActorName(address); - - lock (_eventWriter) + try { - _eventWriter?.CharacterBase.WriteLine(address, name.Span, collection); + var name = GetActorName(address); + + lock (_eventWriter) + { + _eventWriter?.CharacterBase.WriteLine(address, name.Span, collection); + } + } + catch (Exception ex) + { + Penumbra.Log.Warning($"Error logging character creation to crash handler:\n{ex}"); } } @@ -249,15 +284,22 @@ public sealed class CrashHandlerService : IDisposable, IService if (manipulatedPath == null || _eventWriter == null) return; - var dashIdx = manipulatedPath.Value.InternalName[0] == (byte)'|' ? manipulatedPath.Value.InternalName.IndexOf((byte)'|', 1) : -1; - if (dashIdx >= 0 && !Utf8GamePath.IsRooted(manipulatedPath.Value.InternalName.Substring(dashIdx + 1))) - return; - - var name = GetActorName(resolveData.AssociatedGameObject); - lock (_eventWriter) + try { - _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Name, - manipulatedPath.Value.InternalName.Span, originalPath.Path.Span); + var dashIdx = manipulatedPath.Value.InternalName[0] == (byte)'|' ? manipulatedPath.Value.InternalName.IndexOf((byte)'|', 1) : -1; + if (dashIdx >= 0 && !Utf8GamePath.IsRooted(manipulatedPath.Value.InternalName.Substring(dashIdx + 1))) + return; + + var name = GetActorName(resolveData.AssociatedGameObject); + lock (_eventWriter) + { + _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Name, + manipulatedPath.Value.InternalName.Span, originalPath.Path.Span); + } + } + catch (Exception ex) + { + Penumbra.Log.Warning($"Error logging resource to crash handler:\n{ex}"); } } @@ -276,7 +318,7 @@ public sealed class CrashHandlerService : IDisposable, IService try { CloseEventWriter(); - _eventWriter = new GameEventLogWriter(); + _eventWriter = new GameEventLogWriter(Environment.ProcessId); Penumbra.Log.Debug("Opened new Event Writer for crash handler."); } catch (Exception ex) From 72979a9743158749d01d74f400c878c3e3f9c41e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Mar 2024 21:31:30 +0100 Subject: [PATCH 0505/1381] Remarked changes. --- OtterGui | 2 +- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 139 ++++++++++-------- 2 files changed, 82 insertions(+), 59 deletions(-) diff --git a/OtterGui b/OtterGui index b4b14367..2bbb9b2a 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit b4b14367d8235eabedd561ad3626beb1d2a83889 +Subproject commit 2bbb9b2a8a4479461b252594b9d1b788b551c13c diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 494ad3f6..3672dce7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -7,6 +7,7 @@ using OtterGui.Widgets; using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.Import.Models; +using Penumbra.Mods; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -14,9 +15,13 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private const int MdlMaterialMaximum = 4; - private const string MdlImportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-9b49d296-23ab-410a-845b-a3be769b71ea"; - private const string MdlExportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-25968400-ebe5-4861-b610-cb1556db7ec4"; + private const int MdlMaterialMaximum = 4; + + private const string MdlImportDocumentation = + @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-9b49d296-23ab-410a-845b-a3be769b71ea"; + + private const string MdlExportDocumentation = + @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-25968400-ebe5-4861-b610-cb1556db7ec4"; private readonly FileEditor _modelTab; private readonly ModelManager _models; @@ -25,31 +30,51 @@ public partial class ModEditWindow private readonly List _subMeshAttributeTagWidgets = []; private string _customPath = string.Empty; private Utf8GamePath _customGamePath = Utf8GamePath.Empty; + private MdlFile _lastFile = null!; + private long[] _lodTriCount = []; + + private void UpdateFile(MdlFile file, bool force) + { + if (file == _lastFile) + { + if (force) + UpdateMeshes(); + } + else + { + UpdateMeshes(); + _lastFile = file; + _lodTriCount = Enumerable.Range(0, file.Lods.Length).Select(l => GetTriangleCountForLod(file, l)).ToArray(); + } + + return; + + void UpdateMeshes() + { + var subMeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); + if (_subMeshAttributeTagWidgets.Count != subMeshTotal) + { + _subMeshAttributeTagWidgets.Clear(); + _subMeshAttributeTagWidgets.AddRange( + Enumerable.Range(0, subMeshTotal).Select(_ => new TagButtons()) + ); + } + } + } private bool DrawModelPanel(MdlTab tab, bool disabled) { - var file = tab.Mdl; - - var subMeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); - if (_subMeshAttributeTagWidgets.Count != subMeshTotal) - { - _subMeshAttributeTagWidgets.Clear(); - _subMeshAttributeTagWidgets.AddRange( - Enumerable.Range(0, subMeshTotal).Select(_ => new TagButtons()) - ); - } - + UpdateFile(tab.Mdl, tab.Dirty); DrawImportExport(tab, disabled); var ret = tab.Dirty; - ret |= DrawModelMaterialDetails(tab, disabled); - if (ImGui.CollapsingHeader($"Meshes ({file.Meshes.Length})###meshes")) - for (var i = 0; i < file.LodCount; ++i) + if (ImGui.CollapsingHeader($"Meshes ({_lastFile.Meshes.Length})###meshes")) + for (var i = 0; i < _lastFile.LodCount; ++i) ret |= DrawModelLodDetails(tab, i, disabled); - ret |= DrawOtherModelDetails(file, disabled); + ret |= DrawOtherModelDetails(disabled); return !disabled && ret; } @@ -85,7 +110,7 @@ public partial class ModEditWindow using (var frame = ImRaii.FramedGroup("Import", size, headerPreIcon: FontAwesomeIcon.FileImport)) { - ImGui.Checkbox("Keep current materials", ref tab.ImportKeepMaterials); + ImGui.Checkbox("Keep current materials", ref tab.ImportKeepMaterials); ImGui.Checkbox("Keep current attributes", ref tab.ImportKeepAttributes); if (ImGuiUtil.DrawDisabledButton("Import from glTF", Vector2.Zero, "Imports a glTF file, overriding the content of this mdl.", @@ -111,10 +136,7 @@ public partial class ModEditWindow if (tab.GamePaths == null) { - if (tab.IoExceptions.Count == 0) - ImGui.TextUnformatted("Resolving model game paths."); - else - ImGui.TextUnformatted("Failed to resolve model game paths."); + ImGui.TextUnformatted(tab.IoExceptions.Count == 0 ? "Resolving model game paths." : "Failed to resolve model game paths."); return; } @@ -149,14 +171,15 @@ public partial class ModEditWindow ImGui.SameLine(); DrawDocumentationLink(MdlExportDocumentation); } - + private static void DrawIoExceptions(MdlTab tab) { if (tab.IoExceptions.Count == 0) return; var size = new Vector2(ImGui.GetContentRegionAvail().X, 0); - using var frame = ImRaii.FramedGroup("Exceptions", size, headerPreIcon: FontAwesomeIcon.TimesCircle, borderColor: Colors.RegexWarningBorder); + using var frame = ImRaii.FramedGroup("Exceptions", size, headerPreIcon: FontAwesomeIcon.TimesCircle, + borderColor: Colors.RegexWarningBorder); var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; foreach (var (exception, index) in tab.IoExceptions.WithIndex()) @@ -181,7 +204,7 @@ public partial class ModEditWindow if (tab.IoWarnings.Count == 0) return; - var size = new Vector2(ImGui.GetContentRegionAvail().X, 0); + var size = new Vector2(ImGui.GetContentRegionAvail().X, 0); using var frame = ImRaii.FramedGroup("Warnings", size, headerPreIcon: FontAwesomeIcon.ExclamationCircle, borderColor: 0xFF40FFFF); var spaceAvail = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X - 100; @@ -445,7 +468,7 @@ public partial class ModEditWindow if (attributes == null) { attributes = ["invalid attribute data"]; - disabled = true; + disabled = true; } var tagIndex = widget.Draw(string.Empty, string.Empty, attributes, @@ -460,7 +483,7 @@ public partial class ModEditWindow return true; } - private static bool DrawOtherModelDetails(MdlFile file, bool _) + private bool DrawOtherModelDetails(bool _) { using var header = ImRaii.CollapsingHeader("Further Content"); if (!header) @@ -471,47 +494,47 @@ public partial class ModEditWindow if (table) { ImGuiUtil.DrawTableColumn("Version"); - ImGuiUtil.DrawTableColumn(file.Version.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.Version.ToString()); ImGuiUtil.DrawTableColumn("Radius"); - ImGuiUtil.DrawTableColumn(file.Radius.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(_lastFile.Radius.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("Model Clip Out Distance"); - ImGuiUtil.DrawTableColumn(file.ModelClipOutDistance.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(_lastFile.ModelClipOutDistance.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("Shadow Clip Out Distance"); - ImGuiUtil.DrawTableColumn(file.ShadowClipOutDistance.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(_lastFile.ShadowClipOutDistance.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("LOD Count"); - ImGuiUtil.DrawTableColumn(file.LodCount.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.LodCount.ToString()); ImGuiUtil.DrawTableColumn("Enable Index Buffer Streaming"); - ImGuiUtil.DrawTableColumn(file.EnableIndexBufferStreaming.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.EnableIndexBufferStreaming.ToString()); ImGuiUtil.DrawTableColumn("Enable Edge Geometry"); - ImGuiUtil.DrawTableColumn(file.EnableEdgeGeometry.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.EnableEdgeGeometry.ToString()); ImGuiUtil.DrawTableColumn("Flags 1"); - ImGuiUtil.DrawTableColumn(file.Flags1.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.Flags1.ToString()); ImGuiUtil.DrawTableColumn("Flags 2"); - ImGuiUtil.DrawTableColumn(file.Flags2.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.Flags2.ToString()); ImGuiUtil.DrawTableColumn("Vertex Declarations"); - ImGuiUtil.DrawTableColumn(file.VertexDeclarations.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.VertexDeclarations.Length.ToString()); ImGuiUtil.DrawTableColumn("Bone Bounding Boxes"); - ImGuiUtil.DrawTableColumn(file.BoneBoundingBoxes.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.BoneBoundingBoxes.Length.ToString()); ImGuiUtil.DrawTableColumn("Bone Tables"); - ImGuiUtil.DrawTableColumn(file.BoneTables.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.BoneTables.Length.ToString()); ImGuiUtil.DrawTableColumn("Element IDs"); - ImGuiUtil.DrawTableColumn(file.ElementIds.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.ElementIds.Length.ToString()); ImGuiUtil.DrawTableColumn("Extra LoDs"); - ImGuiUtil.DrawTableColumn(file.ExtraLods.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.ExtraLods.Length.ToString()); ImGuiUtil.DrawTableColumn("Meshes"); - ImGuiUtil.DrawTableColumn(file.Meshes.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.Meshes.Length.ToString()); ImGuiUtil.DrawTableColumn("Shape Meshes"); - ImGuiUtil.DrawTableColumn(file.ShapeMeshes.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.ShapeMeshes.Length.ToString()); ImGuiUtil.DrawTableColumn("LoDs"); - ImGuiUtil.DrawTableColumn(file.Lods.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.Lods.Length.ToString()); ImGuiUtil.DrawTableColumn("Vertex Declarations"); - ImGuiUtil.DrawTableColumn(file.VertexDeclarations.Length.ToString()); + ImGuiUtil.DrawTableColumn(_lastFile.VertexDeclarations.Length.ToString()); ImGuiUtil.DrawTableColumn("Stack Size"); - ImGuiUtil.DrawTableColumn(file.StackSize.ToString()); - for (var lod = 0; lod < file.Lods.Length; lod++) + ImGuiUtil.DrawTableColumn(_lastFile.StackSize.ToString()); + foreach (var (triCount, lod) in _lodTriCount.WithIndex()) { - ImGuiUtil.DrawTableColumn("LoD " + lod + " Triangle Count"); - ImGuiUtil.DrawTableColumn(GetTriangleCountForLod(file, lod).ToString()); + ImGuiUtil.DrawTableColumn($"LOD #{lod + 1} Triangle Count"); + ImGuiUtil.DrawTableColumn(triCount.ToString()); } } } @@ -519,36 +542,36 @@ public partial class ModEditWindow using (var materials = ImRaii.TreeNode("Materials", ImGuiTreeNodeFlags.DefaultOpen)) { if (materials) - foreach (var material in file.Materials) + foreach (var material in _lastFile.Materials) ImRaii.TreeNode(material, ImGuiTreeNodeFlags.Leaf).Dispose(); } using (var attributes = ImRaii.TreeNode("Attributes", ImGuiTreeNodeFlags.DefaultOpen)) { if (attributes) - foreach (var attribute in file.Attributes) + foreach (var attribute in _lastFile.Attributes) ImRaii.TreeNode(attribute, ImGuiTreeNodeFlags.Leaf).Dispose(); } using (var bones = ImRaii.TreeNode("Bones", ImGuiTreeNodeFlags.DefaultOpen)) { if (bones) - foreach (var bone in file.Bones) + foreach (var bone in _lastFile.Bones) ImRaii.TreeNode(bone, ImGuiTreeNodeFlags.Leaf).Dispose(); } using (var shapes = ImRaii.TreeNode("Shapes", ImGuiTreeNodeFlags.DefaultOpen)) { if (shapes) - foreach (var shape in file.Shapes) + foreach (var shape in _lastFile.Shapes) ImRaii.TreeNode(shape.ShapeName, ImGuiTreeNodeFlags.Leaf).Dispose(); } - if (file.RemainingData.Length > 0) + if (_lastFile.RemainingData.Length > 0) { - using var t = ImRaii.TreeNode($"Additional Data (Size: {file.RemainingData.Length})###AdditionalData"); + using var t = ImRaii.TreeNode($"Additional Data (Size: {_lastFile.RemainingData.Length})###AdditionalData"); if (t) - ImGuiUtil.TextWrapped(string.Join(' ', file.RemainingData.Select(c => $"{c:X2}"))); + ImGuiUtil.TextWrapped(string.Join(' ', _lastFile.RemainingData.Select(c => $"{c:X2}"))); } return false; @@ -562,7 +585,7 @@ public partial class ModEditWindow private static long GetTriangleCountForLod(MdlFile model, int lod) { - var vertSum = 0u; + var vertSum = 0u; var meshIndex = model.Lods[lod].MeshIndex; var meshCount = model.Lods[lod].MeshCount; From cc88738e3e28232b6735e3279240b833bccb5b1c Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 21 Mar 2024 20:33:37 +0000 Subject: [PATCH 0506/1381] [CI] Updating repo.json for testing_1.0.2.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 9487b2b3..3aac5de6 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.1", + "TestingAssemblyVersion": "1.0.2.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 1a9239a358fbbd0e423f606995ab8cdbfe484105 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Mar 2024 23:02:07 +0100 Subject: [PATCH 0507/1381] Test improving object manager. --- Penumbra.GameData | 2 +- Penumbra/Api/IpcTester.cs | 6 +++--- Penumbra/Api/PenumbraApi.cs | 6 +++--- .../Interop/Hooks/Animation/LoadTimelineResources.cs | 2 +- Penumbra/Interop/Hooks/Animation/SomePapLoad.cs | 2 +- Penumbra/Interop/PathResolving/DrawObjectState.cs | 9 ++++----- Penumbra/Interop/Services/RedrawService.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 6 +++--- 8 files changed, 17 insertions(+), 18 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 529e1811..9a1e5e72 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 529e18115023732794994bfb8df4818b68951ea4 +Subproject commit 9a1e5e7294a6929ee1cc72b1b5d76e12c000c327 diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index e1dd81cb..30f3c80f 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -442,8 +442,8 @@ public class IpcTester : IDisposable DrawIntro(Ipc.RedrawObjectByIndex.Label, "Redraw by Index"); var tmp = _redrawIndex; ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.Count)) - _redrawIndex = Math.Clamp(tmp, 0, _objects.Count); + if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.TotalCount)) + _redrawIndex = Math.Clamp(tmp, 0, _objects.TotalCount); ImGui.SameLine(); if (ImGui.Button("Redraw##Index")) @@ -460,7 +460,7 @@ public class IpcTester : IDisposable private void SetLastRedrawn(IntPtr address, int index) { if (index < 0 - || index > _objects.Count + || index > _objects.TotalCount || address == IntPtr.Zero || _objects[index].Address != address) _lastRedrawnString = "Invalid"; diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index 5146383d..c8be90aa 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -929,7 +929,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); - if (actorIndex < 0 || actorIndex >= _objects.Count) + if (actorIndex < 0 || actorIndex >= _objects.TotalCount) return PenumbraApiEc.InvalidArgument; var identifier = _actors.FromObject(_objects[actorIndex], out _, false, false, true); @@ -1166,7 +1166,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi private unsafe bool AssociatedCollection(int gameObjectIdx, out ModCollection collection) { collection = _collectionManager.Active.Default; - if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Count) + if (gameObjectIdx < 0 || gameObjectIdx >= _objects.TotalCount) return false; var ptr = _objects[gameObjectIdx]; @@ -1180,7 +1180,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private unsafe ActorIdentifier AssociatedIdentifier(int gameObjectIdx) { - if (gameObjectIdx < 0 || gameObjectIdx >= _objects.Count) + if (gameObjectIdx < 0 || gameObjectIdx >= _objects.TotalCount) return ActorIdentifier.Invalid; var ptr = _objects[gameObjectIdx]; diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index 4bae084e..018892a0 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -64,7 +64,7 @@ public sealed unsafe class LoadTimelineResources : FastHook**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; var idx = getGameObjectIdx(timeline); - if (idx >= 0 && idx < objects.Count) + if (idx >= 0 && idx < objects.TotalCount) { var obj = objects[idx]; return obj.Valid ? resolver.IdentifyCollection(obj.AsObject, true) : ResolveData.Invalid; diff --git a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs index a4563bf3..fad1f819 100644 --- a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs @@ -35,7 +35,7 @@ public sealed unsafe class SomePapLoad : FastHook if (timelinePtr != nint.Zero) { var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); - if (actorIdx >= 0 && actorIdx < _objects.Count) + if (actorIdx >= 0 && actorIdx < _objects.TotalCount) { var newData = _collectionResolver.IdentifyCollection(_objects[actorIdx].AsObject, true); var last = _state.SetAnimationData(newData); diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 784ac3fb..2a9ec7a9 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -94,11 +94,10 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary private unsafe void InitializeDrawObjects() { - for (var i = 0; i < _objects.Count; ++i) - { - var ptr = _objects[i]; - if (ptr is { IsCharacter: true, Model.Valid: true }) - IterateDrawObjectTree((Object*)ptr.Model.Address, ptr, false, false); + foreach(var actor in _objects) + { + if (actor is { IsCharacter: true, Model.Valid: true }) + IterateDrawObjectTree((Object*)actor.Model.Address, actor, false, false); } } diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index a6fec0b5..21ecfd4f 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -388,7 +388,7 @@ public sealed unsafe partial class RedrawService : IDisposable public void RedrawObject(int tableIndex, RedrawType settings) { - if (tableIndex >= 0 && tableIndex < _objects.Count) + if (tableIndex >= 0 && tableIndex < _objects.TotalCount) RedrawObject(_objects.GetDalamudObject(tableIndex), settings); } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 2003f0ef..06f1d126 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -431,16 +431,16 @@ public class DebugTab : Window, ITab DrawSpecial("Current Card", _actors.GetCardPlayer()); DrawSpecial("Current Glamour", _actors.GetGlamourPlayer()); - foreach (var obj in _objects.Objects) + foreach (var obj in _objects) { ImGuiUtil.DrawTableColumn($"{((GameObject*)obj.Address)->ObjectIndex}"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero ? string.Empty : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); - var identifier = _actors.FromObject(obj, false, true, false); + var identifier = _actors.FromObject(obj, out _, false, true, false); ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); - var id = obj.ObjectKind == ObjectKind.BattleNpc ? $"{identifier.DataId} | {obj.DataId}" : identifier.DataId.ToString(); + var id = obj.AsObject->ObjectKind ==(byte) ObjectKind.BattleNpc ? $"{identifier.DataId} | {obj.AsObject->DataID}" : identifier.DataId.ToString(); ImGuiUtil.DrawTableColumn(id); } From 8fded888137117823f521d6d4a8e8d4d826db87d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 21 Mar 2024 23:50:55 +0100 Subject: [PATCH 0508/1381] Update. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 9a1e5e72..66687643 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 9a1e5e7294a6929ee1cc72b1b5d76e12c000c327 +Subproject commit 66687643da2163c938575ad6949c8d0fbd03afe7 From 5ea140db980ff112149fdb0dbc7cf069a68f1ec3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Mar 2024 00:45:52 +0100 Subject: [PATCH 0509/1381] Add new draw events. --- Penumbra.Api | 2 +- Penumbra/Api/PenumbraApi.cs | 14 ++++++++++++- Penumbra/Communication/PostEnabledDraw.cs | 18 +++++++++++++++++ .../Communication/PreSettingsTabBarDraw.cs | 20 +++++++++++++++++++ Penumbra/Penumbra.cs | 11 ++++++++++ Penumbra/Services/CommunicatorService.cs | 8 ++++++++ Penumbra/UI/ModsTab/ModPanelHeader.cs | 16 ++++++++++++--- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 6 ++++-- 8 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 Penumbra/Communication/PostEnabledDraw.cs create mode 100644 Penumbra/Communication/PreSettingsTabBarDraw.cs diff --git a/Penumbra.Api b/Penumbra.Api index d2a1406b..a28a2537 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit d2a1406bc32f715c0687613f02e3f74caf7ceea9 +Subproject commit a28a2537c0ff030cf09f740bff3b1a51ac0b41f6 diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index c8be90aa..da1eafd0 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -33,12 +33,24 @@ namespace Penumbra.Api; public class PenumbraApi : IDisposable, IPenumbraApi { public (int, int) ApiVersion - => (4, 23); + => (4, 24); + + public event Action? PreSettingsTabBarDraw + { + add => _communicator.PreSettingsTabBarDraw.Subscribe(value!, Communication.PreSettingsTabBarDraw.Priority.Default); + remove => _communicator.PreSettingsTabBarDraw.Unsubscribe(value!); + } public event Action? PreSettingsPanelDraw { add => _communicator.PreSettingsPanelDraw.Subscribe(value!, Communication.PreSettingsPanelDraw.Priority.Default); remove => _communicator.PreSettingsPanelDraw.Unsubscribe(value!); + } + + public event Action? PostEnabledDraw + { + add => _communicator.PostEnabledDraw.Subscribe(value!, Communication.PostEnabledDraw.Priority.Default); + remove => _communicator.PostEnabledDraw.Unsubscribe(value!); } public event Action? PostSettingsPanelDraw diff --git a/Penumbra/Communication/PostEnabledDraw.cs b/Penumbra/Communication/PostEnabledDraw.cs new file mode 100644 index 00000000..68637442 --- /dev/null +++ b/Penumbra/Communication/PostEnabledDraw.cs @@ -0,0 +1,18 @@ +using OtterGui.Classes; + +namespace Penumbra.Communication; + +/// +/// Triggered after the Enabled Checkbox line in settings is drawn, but before options are drawn. +/// +/// Parameter is the identifier (directory name) of the currently selected mod. +/// +/// +public sealed class PostEnabledDraw() : EventWrapper(nameof(PostEnabledDraw)) +{ + public enum Priority + { + /// + Default = 0, + } +} diff --git a/Penumbra/Communication/PreSettingsTabBarDraw.cs b/Penumbra/Communication/PreSettingsTabBarDraw.cs new file mode 100644 index 00000000..2c14cdf1 --- /dev/null +++ b/Penumbra/Communication/PreSettingsTabBarDraw.cs @@ -0,0 +1,20 @@ +using OtterGui.Classes; + +namespace Penumbra.Communication; + +/// +/// Triggered before the settings tab bar for a mod is drawn, after the title group is drawn. +/// +/// Parameter is the identifier (directory name) of the currently selected mod. +/// is the total width of the header group. +/// is the width of the title box. +/// +/// +public sealed class PreSettingsTabBarDraw() : EventWrapper(nameof(PreSettingsTabBarDraw)) +{ + public enum Priority + { + /// + Default = 0, + } +} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index ff068928..34451dfa 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -95,6 +95,17 @@ public class Penumbra : IDalamudPlugin if (_characterUtility.Ready) _residentResources.Reload(); + + var api = _services.GetService(); + api.PostEnabledDraw += ImGui.TextUnformatted; + api.PreSettingsTabBarDraw += (name, width, titleWidth) => + { + ImGui.TextUnformatted(width.ToString()); + ImGui.TextUnformatted(titleWidth.ToString()); + ImGui.TextUnformatted(ImGui.GetContentRegionMax().X.ToString()); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + (width - titleWidth) / 2); + ImGui.Button("Test", new Vector2(titleWidth, 0)); + }; } catch (Exception ex) { diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index da852855..cacbe689 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -57,9 +57,15 @@ public class CommunicatorService : IDisposable, IService /// public readonly EnabledChanged EnabledChanged = new(); + /// + public readonly PreSettingsTabBarDraw PreSettingsTabBarDraw = new(); + /// public readonly PreSettingsPanelDraw PreSettingsPanelDraw = new(); + /// + public readonly PostEnabledDraw PostEnabledDraw = new(); + /// public readonly PostSettingsPanelDraw PostSettingsPanelDraw = new(); @@ -91,7 +97,9 @@ public class CommunicatorService : IDisposable, IService ModSettingChanged.Dispose(); CollectionInheritanceChanged.Dispose(); EnabledChanged.Dispose(); + PreSettingsTabBarDraw.Dispose(); PreSettingsPanelDraw.Dispose(); + PostEnabledDraw.Dispose(); PostSettingsPanelDraw.Dispose(); ChangedItemHover.Dispose(); ChangedItemClick.Dispose(); diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index ed499b4f..05f47809 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -32,9 +32,14 @@ public class ModPanelHeader : IDisposable /// public void Draw() { - var offset = DrawModName(); - DrawVersion(offset); - DrawSecondRow(offset); + using (ImRaii.Group()) + { + var offset = DrawModName(); + DrawVersion(offset); + DrawSecondRow(offset); + } + + _communicator.PreSettingsTabBarDraw.Invoke(_mod.Identifier, ImGui.GetItemRectSize().X, _nameWidth); } /// @@ -43,6 +48,7 @@ public class ModPanelHeader : IDisposable /// public void UpdateModData(Mod mod) { + _mod = mod; // Name var name = $" {mod.Name} "; if (name != _modName) @@ -90,6 +96,7 @@ public class ModPanelHeader : IDisposable } // Header data. + private Mod _mod = null!; private string _modName = string.Empty; private string _modAuthor = string.Empty; private string _modVersion = string.Empty; @@ -103,6 +110,8 @@ public class ModPanelHeader : IDisposable private float _modWebsiteButtonWidth; private float _secondRowWidth; + private float _nameWidth; + /// /// Draw the mod name in the game font with a 2px border, centered, /// with at least the width of the version space to each side. @@ -124,6 +133,7 @@ public class ModPanelHeader : IDisposable using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, 2 * UiHelpers.Scale); using var f = _nameFont.Push(); ImGuiUtil.DrawTextButton(_modName, Vector2.Zero, 0); + _nameWidth = ImGui.GetItemRectSize().X; return offset; } diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 5c7ddbf3..b14cad01 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -61,7 +61,7 @@ public class ModPanelSettingsTab : ITab DrawInheritedWarning(); UiHelpers.DefaultLineSpace(); - _communicator.PreSettingsPanelDraw.Invoke(_selector.Selected!.ModPath.Name); + _communicator.PreSettingsPanelDraw.Invoke(_selector.Selected!.Identifier); DrawEnabledInput(); _tutorial.OpenTutorial(BasicTutorialSteps.EnablingMods); ImGui.SameLine(); @@ -69,6 +69,8 @@ public class ModPanelSettingsTab : ITab _tutorial.OpenTutorial(BasicTutorialSteps.Priority); DrawRemoveSettings(); + _communicator.PostEnabledDraw.Invoke(_selector.Selected!.Identifier); + if (_selector.Selected!.Groups.Count > 0) { var useDummy = true; @@ -98,7 +100,7 @@ public class ModPanelSettingsTab : ITab } UiHelpers.DefaultLineSpace(); - _communicator.PostSettingsPanelDraw.Invoke(_selector.Selected!.ModPath.Name); + _communicator.PostSettingsPanelDraw.Invoke(_selector.Selected!.Identifier); } /// Draw a big red bar if the current setting is inherited. From ca95b9c14c1eb487a1e38a6aa1d7272e7549ecba Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Mar 2024 00:55:53 +0100 Subject: [PATCH 0510/1381] PackageVersion. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index a28a2537..8787efc8 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit a28a2537c0ff030cf09f740bff3b1a51ac0b41f6 +Subproject commit 8787efc8fc897dfbb4515ebbabbcd5e6f54d1b42 From 26730efc1bee0a415c433fd06d8cbf53ac93d3b1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Mar 2024 13:31:38 +0100 Subject: [PATCH 0511/1381] Update OtterGui --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 2bbb9b2a..4e06921d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 2bbb9b2a8a4479461b252594b9d1b788b551c13c +Subproject commit 4e06921da239788331a4527aa6a2943cf0e809fe From d171cea627c65a22b9fed2671b55b140085e4ca4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Mar 2024 13:36:55 +0100 Subject: [PATCH 0512/1381] Remove DI Reference. --- Penumbra.CrashHandler/Program.cs | 2 +- Penumbra/Penumbra.csproj | 1 - Penumbra/packages.lock.json | 25 ++++++++++++------------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/Penumbra.CrashHandler/Program.cs b/Penumbra.CrashHandler/Program.cs index 94e90bfc..3bc461f7 100644 --- a/Penumbra.CrashHandler/Program.cs +++ b/Penumbra.CrashHandler/Program.cs @@ -21,7 +21,7 @@ public class CrashHandler { exitCode = parent.ExitCode; } - catch (Exception ex) + catch { exitCode = -1; } diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index df18ff13..b07917e8 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -71,7 +71,6 @@ - diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 3f795631..68e1b880 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -11,15 +11,6 @@ "Unosquare.Swan.Lite": "3.0.0" } }, - "Microsoft.Extensions.DependencyInjection": { - "type": "Direct", - "requested": "[7.0.0, )", - "resolved": "7.0.0", - "contentHash": "elNeOmkeX3eDVG6pYVeV82p29hr+UKDaBhrZyWvWLw/EVZSYEkZlQdkp0V39k/Xehs2Qa0mvoCvkVj3eQxNQ1Q==", - "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "7.0.0" - } - }, "SharpCompress": { "type": "Direct", "requested": "[0.33.0, )", @@ -47,10 +38,18 @@ "resolved": "3.1.3", "contentHash": "wybtaqZQ1ZRZ4ZeU+9h+PaSeV14nyiGKIy7qRbDfSHzHq4ybqyOcjoifeaYbiKLO1u+PVxLBuy7MF/DMmwwbfg==" }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "V8S3bsm50ig6JSyrbcJJ8bW2b9QLGouz+G1miK3UTaOWmMtFwNNNzUf4AleyDWUmTrWMLNnFSLEQtxmxgNQnNQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0" + } + }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "7.0.0", - "contentHash": "h3j/QfmFN4S0w4C2A6X7arXij/M/OVw3uQHSOFxnND4DyAzO1F9eMX7Eti7lU/OkSthEE0WzRsfT/Dmx86jzCw==" + "resolved": "8.0.0", + "contentHash": "cjWrLkJXK0rs4zofsK4bSdg+jhDLTaxrkXu4gS6Y7MAlCvRyNNgwY/lJi5RDlQOnSZweHqoyvgvbdvQsRIW+hg==" }, "SharpGLTF.Runtime": { "type": "Transitive", @@ -76,7 +75,7 @@ "ottergui": { "type": "Project", "dependencies": { - "Microsoft.Extensions.DependencyInjection": "[7.0.0, )" + "Microsoft.Extensions.DependencyInjection": "[8.0.0, )" } }, "penumbra.api": { @@ -89,7 +88,7 @@ "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[1.0.14, )", + "Penumbra.Api": "[1.0.15, )", "Penumbra.String": "[1.0.4, )" } }, From aabd988a7747fc974171298b28bb6e9458555969 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Mar 2024 12:38:55 +0000 Subject: [PATCH 0513/1381] [CI] Updating repo.json for testing_1.2.1.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 3aac5de6..a359a4ce 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.2", + "TestingAssemblyVersion": "1.2.1.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From d0d35a79387c19e40baefc20eb339505d0533767 Mon Sep 17 00:00:00 2001 From: Ottermandias <70807659+Ottermandias@users.noreply.github.com> Date: Fri, 22 Mar 2024 13:39:46 +0100 Subject: [PATCH 0514/1381] Update repo.json --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a359a4ce..3aac5de6 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.2.1.2", + "TestingAssemblyVersion": "1.0.2.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 8dcd0451babfb5354808279a0cca8b62c18a5490 Mon Sep 17 00:00:00 2001 From: Ottermandias <70807659+Ottermandias@users.noreply.github.com> Date: Fri, 22 Mar 2024 13:43:38 +0100 Subject: [PATCH 0515/1381] Update repo.json --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 3aac5de6..44ada6e8 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.2", + "TestingAssemblyVersion": "1.0.2.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 6792ed4f9489f061f657a536c323d588e6d53d56 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Mar 2024 14:44:41 +0100 Subject: [PATCH 0516/1381] Remove the fucking test I'm a fucking moron. --- Penumbra/Penumbra.cs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 34451dfa..ff068928 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -95,17 +95,6 @@ public class Penumbra : IDalamudPlugin if (_characterUtility.Ready) _residentResources.Reload(); - - var api = _services.GetService(); - api.PostEnabledDraw += ImGui.TextUnformatted; - api.PreSettingsTabBarDraw += (name, width, titleWidth) => - { - ImGui.TextUnformatted(width.ToString()); - ImGui.TextUnformatted(titleWidth.ToString()); - ImGui.TextUnformatted(ImGui.GetContentRegionMax().X.ToString()); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + (width - titleWidth) / 2); - ImGui.Button("Test", new Vector2(titleWidth, 0)); - }; } catch (Exception ex) { From 78a3ff177f8304c7ed9f0bc59b6f15985c6929c1 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Mar 2024 13:46:45 +0000 Subject: [PATCH 0517/1381] [CI] Updating repo.json for testing_1.0.2.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 44ada6e8..2af4a645 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.3", + "TestingAssemblyVersion": "1.0.2.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 4175a582b8ece7d088a27c6fd95cd2be5c2e54ef Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Mar 2024 15:15:41 +0100 Subject: [PATCH 0518/1381] Add IPC Providers because I'm still a fucking moron. --- Penumbra/Api/PenumbraIpcProviders.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs index d478b675..78887156 100644 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ b/Penumbra/Api/PenumbraIpcProviders.cs @@ -30,7 +30,9 @@ public class PenumbraIpcProviders : IDisposable internal readonly EventProvider ModDirectoryChanged; // UI + internal readonly EventProvider PreSettingsTabBarDraw; internal readonly EventProvider PreSettingsDraw; + internal readonly EventProvider PostEnabledDraw; internal readonly EventProvider PostSettingsDraw; internal readonly EventProvider ChangedItemTooltip; internal readonly EventProvider ChangedItemClick; @@ -130,8 +132,8 @@ public class PenumbraIpcProviders : IDisposable FuncProvider>> GetPlayerResourcesOfType; - internal readonly FuncProvider GetGameObjectResourceTrees; - internal readonly FuncProvider> GetPlayerResourceTrees; + internal readonly FuncProvider GetGameObjectResourceTrees; + internal readonly FuncProvider> GetPlayerResourceTrees; public PenumbraIpcProviders(DalamudPluginInterface pi, IPenumbraApi api, ModManager modManager, CollectionManager collections, TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) @@ -153,7 +155,11 @@ public class PenumbraIpcProviders : IDisposable ModDirectoryChanged = Ipc.ModDirectoryChanged.Provider(pi, a => Api.ModDirectoryChanged += a, a => Api.ModDirectoryChanged -= a); // UI - PreSettingsDraw = Ipc.PreSettingsDraw.Provider(pi, a => Api.PreSettingsPanelDraw += a, a => Api.PreSettingsPanelDraw -= a); + PreSettingsTabBarDraw = + Ipc.PreSettingsTabBarDraw.Provider(pi, a => Api.PreSettingsTabBarDraw += a, a => Api.PreSettingsTabBarDraw -= a); + PreSettingsDraw = Ipc.PreSettingsDraw.Provider(pi, a => Api.PreSettingsPanelDraw += a, a => Api.PreSettingsPanelDraw -= a); + PostEnabledDraw = + Ipc.PostEnabledDraw.Provider(pi, a => Api.PostEnabledDraw += a, a => Api.PostEnabledDraw -= a); PostSettingsDraw = Ipc.PostSettingsDraw.Provider(pi, a => Api.PostSettingsPanelDraw += a, a => Api.PostSettingsPanelDraw -= a); ChangedItemTooltip = Ipc.ChangedItemTooltip.Provider(pi, () => Api.ChangedItemTooltip += OnTooltip, () => Api.ChangedItemTooltip -= OnTooltip); @@ -278,7 +284,9 @@ public class PenumbraIpcProviders : IDisposable ModDirectoryChanged.Dispose(); // UI + PreSettingsTabBarDraw.Dispose(); PreSettingsDraw.Dispose(); + PostEnabledDraw.Dispose(); PostSettingsDraw.Dispose(); ChangedItemTooltip.Dispose(); ChangedItemClick.Dispose(); From 12532dee2810c9f770a467a2f61c0c007226e373 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Mar 2024 14:17:47 +0000 Subject: [PATCH 0519/1381] [CI] Updating repo.json for testing_1.0.2.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 2af4a645..5a51afa2 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.4", + "TestingAssemblyVersion": "1.0.2.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From efdd5a824b16fb9e5a423062b644cea038a9275f Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 26 Mar 2024 02:29:07 +0100 Subject: [PATCH 0520/1381] Make human.pbd moddable --- Penumbra/Collections/Cache/CollectionCache.cs | 31 ++++-- .../Interop/ResourceLoading/ResourceLoader.cs | 28 ++++++ .../ResourceLoading/ResourceService.cs | 9 +- .../Interop/ResourceTree/ResolveContext.cs | 9 ++ Penumbra/Interop/ResourceTree/ResourceTree.cs | 18 +++- .../Interop/SafeHandles/SafeResourceHandle.cs | 10 +- Penumbra/Interop/Services/CharacterUtility.cs | 8 ++ .../Services/PreBoneDeformerReplacer.cs | 95 +++++++++++++++++++ .../Interop/Structs/CharacterUtilityData.cs | 4 + Penumbra/Penumbra.cs | 1 + Penumbra/Services/StaticServiceManager.cs | 1 + 11 files changed, 202 insertions(+), 12 deletions(-) create mode 100644 Penumbra/Interop/Services/PreBoneDeformerReplacer.cs diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 9a0e525b..c2c215aa 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -8,6 +8,9 @@ using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; +using Penumbra.Interop.SafeHandles; +using System.IO; +using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.Collections.Cache; @@ -20,13 +23,14 @@ public record ModConflicts(IMod Mod2, List Conflicts, bool HasPriority, /// public class CollectionCache : IDisposable { - private readonly CollectionCacheManager _manager; - private readonly ModCollection _collection; - public readonly CollectionModData ModData = new(); - private readonly SortedList, object?)> _changedItems = []; - public readonly ConcurrentDictionary ResolvedFiles = new(); - public readonly MetaCache Meta; - public readonly Dictionary> ConflictDict = []; + private readonly CollectionCacheManager _manager; + private readonly ModCollection _collection; + public readonly CollectionModData ModData = new(); + private readonly SortedList, object?)> _changedItems = []; + public readonly ConcurrentDictionary ResolvedFiles = new(); + public readonly ConcurrentDictionary LoadedResources = new(); + public readonly MetaCache Meta; + public readonly Dictionary> ConflictDict = []; public int Calculating = -1; @@ -136,6 +140,13 @@ public class CollectionCache : IDisposable public void RemoveMod(IMod mod, bool addMetaChanges) => _manager.AddChange(ChangeData.ModRemoval(this, mod, addMetaChanges)); + /// Invalidates caches subsequently to a resolved file being modified. + private void InvalidateResolvedFile(Utf8GamePath path) + { + if (LoadedResources.Remove(path, out var handle)) + handle.Dispose(); + } + /// Force a file to be resolved to a specific path regardless of conflicts. internal void ForceFileSync(Utf8GamePath path, FullPath fullPath) { @@ -148,17 +159,20 @@ public class CollectionCache : IDisposable if (fullPath.FullName.Length > 0) { ResolvedFiles.TryAdd(path, new ModPath(Mod.ForcedFiles, fullPath)); + InvalidateResolvedFile(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, fullPath, modPath.Path, Mod.ForcedFiles); } else { + InvalidateResolvedFile(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Removed, path, FullPath.Empty, modPath.Path, null); } } else if (fullPath.FullName.Length > 0) { ResolvedFiles.TryAdd(path, new ModPath(Mod.ForcedFiles, fullPath)); + InvalidateResolvedFile(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, fullPath, FullPath.Empty, Mod.ForcedFiles); } } @@ -181,6 +195,7 @@ public class CollectionCache : IDisposable { if (ResolvedFiles.Remove(path, out var mp)) { + InvalidateResolvedFile(path); if (mp.Mod != mod) Penumbra.Log.Warning( $"Invalid mod state, removing {mod.Name} and associated file {path} returned current mod {mp.Mod.Name}."); @@ -295,6 +310,7 @@ public class CollectionCache : IDisposable if (ResolvedFiles.TryAdd(path, new ModPath(mod, file))) { ModData.AddPath(mod, path); + InvalidateResolvedFile(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, file, FullPath.Empty, mod); return; } @@ -309,6 +325,7 @@ public class CollectionCache : IDisposable ModData.RemovePath(modPath.Mod, path); ResolvedFiles[path] = new ModPath(mod, file); ModData.AddPath(mod, path); + InvalidateResolvedFile(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, file, modPath.Path, mod); } } diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 8ccdfa80..1b467a8c 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,6 +1,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; +using Penumbra.Interop.SafeHandles; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; @@ -39,6 +40,33 @@ public unsafe class ResourceLoader : IDisposable return ret; } + /// Load a resource for a given path and a specific collection. + public SafeResourceHandle LoadResolvedSafeResource(ResourceCategory category, ResourceType type, ByteString path, ResolveData resolveData) + { + _resolvedData = resolveData; + var ret = _resources.GetSafeResource(category, type, path); + _resolvedData = ResolveData.Invalid; + return ret; + } + + public SafeResourceHandle LoadCacheableSafeResource(ResourceCategory category, ResourceType type, Utf8GamePath path, ResolveData resolveData) + { + var cache = resolveData.ModCollection._cache; + if (cache == null) + return LoadResolvedSafeResource(category, type, path.Path, resolveData); + + if (cache.LoadedResources.TryGetValue(path, out var cached)) + return cached.Clone(); + + var ret = LoadResolvedSafeResource(category, type, path.Path, resolveData); + + cached = ret.Clone(); + if (!cache.LoadedResources.TryAdd(path, cached)) + cached.Dispose(); + + return ret; + } + /// The function to use to resolve a given path. public Func ResolvePath = null!; diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 6fb2e560..e3338e6c 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -4,10 +4,12 @@ using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.GameData; +using Penumbra.Interop.SafeHandles; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.Util; +using CSResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle; namespace Penumbra.Interop.ResourceLoading; @@ -25,11 +27,11 @@ public unsafe class ResourceService : IDisposable _getResourceAsyncHook.Enable(); _resourceHandleDestructorHook.Enable(); _incRefHook = interop.HookFromAddress( - (nint)FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle.MemberFunctionPointers.IncRef, + (nint)CSResourceHandle.MemberFunctionPointers.IncRef, ResourceHandleIncRefDetour); _incRefHook.Enable(); _decRefHook = interop.HookFromAddress( - (nint)FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle.MemberFunctionPointers.DecRef, + (nint)CSResourceHandle.MemberFunctionPointers.DecRef, ResourceHandleDecRefDetour); _decRefHook.Enable(); } @@ -41,6 +43,9 @@ public unsafe class ResourceService : IDisposable &category, &type, &hash, path.Path, null, false); } + public SafeResourceHandle GetSafeResource(ResourceCategory category, ResourceType type, ByteString path) + => new((CSResourceHandle*)GetResource(category, type, path), false); + public void Dispose() { _getResourceSyncHook.Dispose(); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index d1701f47..615ef2b0 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -9,6 +9,7 @@ using Penumbra.Collections; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Interop.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; @@ -144,6 +145,14 @@ internal unsafe partial record ResolveContext( return GetOrCreateNode(ResourceType.Imc, 0, imc, path); } + public ResourceNode? CreateNodeFromPbd(ResourceHandle* pbd) + { + if (pbd == null) + return null; + + return GetOrCreateNode(ResourceType.Pbd, 0, pbd, PreBoneDeformerReplacer.PreBoneDeformerPath); + } + public ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, string gamePath) { if (tex == null) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 24112a9f..15546ed3 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,4 +1,3 @@ -using Dalamud.Game.ClientState.Objects.Enums; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; @@ -6,6 +5,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Interop.Services; using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; using CustomizeIndex = Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex; @@ -155,6 +155,22 @@ public class ResourceTree { var genericContext = globalContext.CreateContext(&human->CharacterBase); + var cache = globalContext.Collection._cache; + if (cache != null && cache.LoadedResources.TryGetValue(PreBoneDeformerReplacer.PreBoneDeformerPath, out var pbdHandle)) + { + var pbdNode = genericContext.CreateNodeFromPbd(pbdHandle.ResourceHandle); + if (pbdNode != null) + { + if (globalContext.WithUiData) + { + pbdNode = pbdNode.Clone(); + pbdNode.FallbackName = "Racial Deformer"; + pbdNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + } + Nodes.Add(pbdNode); + } + } + var decalId = (byte)(human->Customize[(int)CustomizeIndex.Facepaint] & 0x7F); var decalPath = decalId != 0 ? GamePaths.Human.Decal.FaceDecalPath(decalId) diff --git a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs index 1f788a39..a5e73867 100644 --- a/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs +++ b/Penumbra/Interop/SafeHandles/SafeResourceHandle.cs @@ -1,8 +1,8 @@ -using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; namespace Penumbra.Interop.SafeHandles; -public unsafe class SafeResourceHandle : SafeHandle +public unsafe class SafeResourceHandle : SafeHandle, ICloneable { public ResourceHandle* ResourceHandle => (ResourceHandle*)handle; @@ -21,6 +21,12 @@ public unsafe class SafeResourceHandle : SafeHandle SetHandle((nint)handle); } + public SafeResourceHandle Clone() + => new(ResourceHandle, true); + + object ICloneable.Clone() + => Clone(); + public static SafeResourceHandle CreateInvalid() => new(null, false); diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 699b59e0..da04bf90 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -28,6 +28,7 @@ public unsafe class CharacterUtility : IDisposable public bool Ready { get; private set; } public event Action LoadingFinished; + public nint DefaultHumanPbdResource { get; private set; } public nint DefaultTransparentResource { get; private set; } public nint DefaultDecalResource { get; private set; } public nint DefaultSkinShpkResource { get; private set; } @@ -88,6 +89,12 @@ public unsafe class CharacterUtility : IDisposable anyMissing |= !_lists[i].Ready; } + if (DefaultHumanPbdResource == nint.Zero) + { + DefaultHumanPbdResource = (nint)Address->HumanPbdResource; + anyMissing |= DefaultHumanPbdResource == nint.Zero; + } + if (DefaultTransparentResource == nint.Zero) { DefaultTransparentResource = (nint)Address->TransparentTexResource; @@ -151,6 +158,7 @@ public unsafe class CharacterUtility : IDisposable foreach (var list in _lists) list.Dispose(); + Address->HumanPbdResource = (ResourceHandle*)DefaultHumanPbdResource; Address->TransparentTexResource = (TextureResourceHandle*)DefaultTransparentResource; Address->DecalTexResource = (TextureResourceHandle*)DefaultDecalResource; Address->SkinShpkResource = (ResourceHandle*)DefaultSkinShpkResource; diff --git a/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs new file mode 100644 index 00000000..44c6541e --- /dev/null +++ b/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs @@ -0,0 +1,95 @@ +using Dalamud.Hooking; +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.SafeHandles; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Services; + +public sealed unsafe class PreBoneDeformerReplacer : IDisposable +{ + public static readonly Utf8GamePath PreBoneDeformerPath = + Utf8GamePath.FromSpan("chara/xls/boneDeformer/human.pbd"u8, out var p) ? p : Utf8GamePath.Empty; + + [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] + private readonly nint* _humanVTable = null!; + + // Approximate name guesses. + private delegate void CharacterBaseSetupScalingDelegate(CharacterBase* drawObject, uint slotIndex); + private delegate void* CharacterBaseCreateDeformerDelegate(CharacterBase* drawObject, uint slotIndex); + + private readonly Hook _humanSetupScalingHook; + private readonly Hook _humanCreateDeformerHook; + + private readonly CharacterUtility _utility; + private readonly CollectionResolver _collectionResolver; + private readonly ResourceLoader _resourceLoader; + private readonly IFramework _framework; + + public PreBoneDeformerReplacer(CharacterUtility utility, CollectionResolver collectionResolver, ResourceLoader resourceLoader, IGameInteropProvider interop, IFramework framework) + { + interop.InitializeFromAttributes(this); + _utility = utility; + _collectionResolver = collectionResolver; + _resourceLoader = resourceLoader; + _framework = framework; + _humanSetupScalingHook = interop.HookFromAddress(_humanVTable[57], SetupScaling); + _humanCreateDeformerHook = interop.HookFromAddress(_humanVTable[91], CreateDeformer); + _humanSetupScalingHook.Enable(); + _humanCreateDeformerHook.Enable(); + } + + public void Dispose() + { + _humanCreateDeformerHook.Dispose(); + _humanSetupScalingHook.Dispose(); + } + + private SafeResourceHandle GetPreBoneDeformerForCharacter(CharacterBase* drawObject) + { + var resolveData = _collectionResolver.IdentifyCollection(&drawObject->DrawObject, true); + return _resourceLoader.LoadCacheableSafeResource(ResourceCategory.Chara, ResourceType.Pbd, PreBoneDeformerPath, resolveData); + } + + private void SetupScaling(CharacterBase* drawObject, uint slotIndex) + { + if (!_framework.IsInFrameworkUpdateThread) + Penumbra.Log.Warning($"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupScaling)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); + + using var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); + try + { + if (!preBoneDeformer.IsInvalid) + _utility.Address->HumanPbdResource = (Structs.ResourceHandle*)preBoneDeformer.ResourceHandle; + _humanSetupScalingHook.Original(drawObject, slotIndex); + } + finally + { + _utility.Address->HumanPbdResource = (Structs.ResourceHandle*)_utility.DefaultHumanPbdResource; + } + } + + private void* CreateDeformer(CharacterBase* drawObject, uint slotIndex) + { + if (!_framework.IsInFrameworkUpdateThread) + Penumbra.Log.Warning($"{nameof(PreBoneDeformerReplacer)}.{nameof(CreateDeformer)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); + + using var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); + try + { + if (!preBoneDeformer.IsInvalid) + _utility.Address->HumanPbdResource = (Structs.ResourceHandle*)preBoneDeformer.ResourceHandle; + return _humanCreateDeformerHook.Original(drawObject, slotIndex); + } + finally + { + _utility.Address->HumanPbdResource = (Structs.ResourceHandle*)_utility.DefaultHumanPbdResource; + } + } +} diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 08857292..22150cc1 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -5,6 +5,7 @@ namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] public unsafe struct CharacterUtilityData { + public const int IndexHumanPbd = 63; public const int IndexTransparentTex = 72; public const int IndexDecalTex = 73; public const int IndexSkinShpk = 76; @@ -72,6 +73,9 @@ public unsafe struct CharacterUtilityData public ResourceHandle* EqdpResource(GenderRace raceCode, bool accessory) => Resource((int)EqdpIdx(raceCode, accessory)); + [FieldOffset(8 + IndexHumanPbd * 8)] + public ResourceHandle* HumanPbdResource; + [FieldOffset(8 + (int)MetaIndex.HumanCmp * 8)] public ResourceHandle* HumanCmpResource; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index ff068928..c34a7771 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -77,6 +77,7 @@ public class Penumbra : IDalamudPlugin _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); _services.GetService(); + _services.GetService(); _services.GetService(); _services.GetService(); // Initialize before Interface. diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 66c90e84..6f85ddd2 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -132,6 +132,7 @@ public static class StaticServiceManager .AddSingleton() .AddSingleton() .AddSingleton() + .AddSingleton() .AddSingleton(); private static ServiceManager AddResolvers(this ServiceManager services) From 3066bf84d5fc4398e642d21c0449ba7a2300e6c2 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Tue, 26 Mar 2024 02:32:33 +0100 Subject: [PATCH 0521/1381] Where did these `using`s even come from? --- Penumbra/Collections/Cache/CollectionCache.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index c2c215aa..00968175 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -9,8 +9,6 @@ using Penumbra.String.Classes; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Interop.SafeHandles; -using System.IO; -using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.Collections.Cache; From e793e7793b1e4eeae991ba0beb4f7f49745b2bd4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Mar 2024 15:19:19 +0100 Subject: [PATCH 0522/1381] Fix model import resetting dirty flag. --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 37 +++++++------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 3672dce7..737c41d9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -35,39 +35,28 @@ public partial class ModEditWindow private void UpdateFile(MdlFile file, bool force) { - if (file == _lastFile) + if (file == _lastFile && !force) + return; + + _lastFile = file; + var subMeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); + if (_subMeshAttributeTagWidgets.Count != subMeshTotal) { - if (force) - UpdateMeshes(); - } - else - { - UpdateMeshes(); - _lastFile = file; - _lodTriCount = Enumerable.Range(0, file.Lods.Length).Select(l => GetTriangleCountForLod(file, l)).ToArray(); + _subMeshAttributeTagWidgets.Clear(); + _subMeshAttributeTagWidgets.AddRange( + Enumerable.Range(0, subMeshTotal).Select(_ => new TagButtons()) + ); } - return; - - void UpdateMeshes() - { - var subMeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); - if (_subMeshAttributeTagWidgets.Count != subMeshTotal) - { - _subMeshAttributeTagWidgets.Clear(); - _subMeshAttributeTagWidgets.AddRange( - Enumerable.Range(0, subMeshTotal).Select(_ => new TagButtons()) - ); - } - } + _lodTriCount = Enumerable.Range(0, file.Lods.Length).Select(l => GetTriangleCountForLod(file, l)).ToArray(); } private bool DrawModelPanel(MdlTab tab, bool disabled) { - UpdateFile(tab.Mdl, tab.Dirty); + var ret = tab.Dirty; + UpdateFile(tab.Mdl, ret); DrawImportExport(tab, disabled); - var ret = tab.Dirty; ret |= DrawModelMaterialDetails(tab, disabled); if (ImGui.CollapsingHeader($"Meshes ({_lastFile.Meshes.Length})###meshes")) From 1ba5011bfa5120821a30a39a8953f33329a59bc7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Mar 2024 17:37:17 +0100 Subject: [PATCH 0523/1381] Small changes. --- Penumbra/Collections/Cache/CollectionCache.cs | 65 +++++++++---------- .../Cache/CollectionCacheManager.cs | 8 ++- .../Collections/Cache/CustomResourceCache.cs | 49 ++++++++++++++ .../Interop/ResourceLoading/ResourceLoader.cs | 18 ----- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- .../Services/PreBoneDeformerReplacer.cs | 34 +++++----- .../Services/ShaderReplacementFixer.cs | 33 +++++----- Penumbra/Penumbra.cs | 2 - Penumbra/Services/StaticServiceManager.cs | 4 +- 9 files changed, 120 insertions(+), 95 deletions(-) create mode 100644 Penumbra/Collections/Cache/CustomResourceCache.cs diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 00968175..6b2b688b 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -8,7 +8,6 @@ using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; -using Penumbra.Interop.SafeHandles; namespace Penumbra.Collections.Cache; @@ -19,16 +18,16 @@ public record ModConflicts(IMod Mod2, List Conflicts, bool HasPriority, /// The Cache contains all required temporary data to use a collection. /// It will only be setup if a collection gets activated in any way. /// -public class CollectionCache : IDisposable +public sealed class CollectionCache : IDisposable { - private readonly CollectionCacheManager _manager; - private readonly ModCollection _collection; - public readonly CollectionModData ModData = new(); - private readonly SortedList, object?)> _changedItems = []; - public readonly ConcurrentDictionary ResolvedFiles = new(); - public readonly ConcurrentDictionary LoadedResources = new(); - public readonly MetaCache Meta; - public readonly Dictionary> ConflictDict = []; + private readonly CollectionCacheManager _manager; + private readonly ModCollection _collection; + public readonly CollectionModData ModData = new(); + private readonly SortedList, object?)> _changedItems = []; + public readonly ConcurrentDictionary ResolvedFiles = new(); + public readonly CustomResourceCache CustomResources; + public readonly MetaCache Meta; + public readonly Dictionary> ConflictDict = []; public int Calculating = -1; @@ -39,7 +38,7 @@ public class CollectionCache : IDisposable => ConflictDict.Values; public SingleArray Conflicts(IMod mod) - => ConflictDict.TryGetValue(mod, out SingleArray c) ? c : new SingleArray(); + => ConflictDict.TryGetValue(mod, out var c) ? c : new SingleArray(); private int _changedItemsSaveCounter = -1; @@ -56,16 +55,21 @@ public class CollectionCache : IDisposable // The cache reacts through events on its collection changing. public CollectionCache(CollectionCacheManager manager, ModCollection collection) { - _manager = manager; - _collection = collection; - Meta = new MetaCache(manager.MetaFileManager, _collection); + _manager = manager; + _collection = collection; + Meta = new MetaCache(manager.MetaFileManager, _collection); + CustomResources = new CustomResourceCache(manager.ResourceLoader); } public void Dispose() - => Meta.Dispose(); + { + Meta.Dispose(); + CustomResources.Dispose(); + GC.SuppressFinalize(this); + } ~CollectionCache() - => Meta.Dispose(); + => Dispose(); // Resolve a given game path according to this collection. public FullPath? ResolvePath(Utf8GamePath gameResourcePath) @@ -74,7 +78,7 @@ public class CollectionCache : IDisposable return null; if (candidate.Path.InternalName.Length > Utf8GamePath.MaxGamePathLength - || candidate.Path.IsRooted && !candidate.Path.Exists) + || candidate.Path is { IsRooted: true, Exists: false }) return null; return candidate.Path; @@ -102,7 +106,7 @@ public class CollectionCache : IDisposable public HashSet[] ReverseResolvePaths(IReadOnlyCollection fullPaths) { if (fullPaths.Count == 0) - return Array.Empty>(); + return []; var ret = new HashSet[fullPaths.Count]; var dict = new Dictionary(fullPaths.Count); @@ -110,8 +114,8 @@ public class CollectionCache : IDisposable { dict[new FullPath(path)] = idx; ret[idx] = !Path.IsPathRooted(path) && Utf8GamePath.FromString(path, out var utf8) - ? new HashSet { utf8 } - : new HashSet(); + ? [utf8] + : []; } foreach (var (game, full) in ResolvedFiles) @@ -138,13 +142,6 @@ public class CollectionCache : IDisposable public void RemoveMod(IMod mod, bool addMetaChanges) => _manager.AddChange(ChangeData.ModRemoval(this, mod, addMetaChanges)); - /// Invalidates caches subsequently to a resolved file being modified. - private void InvalidateResolvedFile(Utf8GamePath path) - { - if (LoadedResources.Remove(path, out var handle)) - handle.Dispose(); - } - /// Force a file to be resolved to a specific path regardless of conflicts. internal void ForceFileSync(Utf8GamePath path, FullPath fullPath) { @@ -157,20 +154,20 @@ public class CollectionCache : IDisposable if (fullPath.FullName.Length > 0) { ResolvedFiles.TryAdd(path, new ModPath(Mod.ForcedFiles, fullPath)); - InvalidateResolvedFile(path); + CustomResources.Invalidate(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, fullPath, modPath.Path, Mod.ForcedFiles); } else { - InvalidateResolvedFile(path); + CustomResources.Invalidate(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Removed, path, FullPath.Empty, modPath.Path, null); } } else if (fullPath.FullName.Length > 0) { ResolvedFiles.TryAdd(path, new ModPath(Mod.ForcedFiles, fullPath)); - InvalidateResolvedFile(path); + CustomResources.Invalidate(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, fullPath, FullPath.Empty, Mod.ForcedFiles); } } @@ -193,7 +190,7 @@ public class CollectionCache : IDisposable { if (ResolvedFiles.Remove(path, out var mp)) { - InvalidateResolvedFile(path); + CustomResources.Invalidate(path); if (mp.Mod != mod) Penumbra.Log.Warning( $"Invalid mod state, removing {mod.Name} and associated file {path} returned current mod {mp.Mod.Name}."); @@ -308,7 +305,7 @@ public class CollectionCache : IDisposable if (ResolvedFiles.TryAdd(path, new ModPath(mod, file))) { ModData.AddPath(mod, path); - InvalidateResolvedFile(path); + CustomResources.Invalidate(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Added, path, file, FullPath.Empty, mod); return; } @@ -323,14 +320,14 @@ public class CollectionCache : IDisposable ModData.RemovePath(modPath.Mod, path); ResolvedFiles[path] = new ModPath(mod, file); ModData.AddPath(mod, path); - InvalidateResolvedFile(path); + CustomResources.Invalidate(path); InvokeResolvedFileChange(_collection, ResolvedFileChanged.Type.Replaced, path, file, modPath.Path, mod); } } catch (Exception ex) { Penumbra.Log.Error( - $"[{Thread.CurrentThread.ManagedThreadId}] Error adding redirection {file} -> {path} for mod {mod.Name} to collection cache {AnonymizedName}:\n{ex}"); + $"[{Environment.CurrentManagedThreadId}] Error adding redirection {file} -> {path} for mod {mod.Name} to collection cache {AnonymizedName}:\n{ex}"); } } diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 94b3ef5a..5a6b5593 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -4,6 +4,7 @@ using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Communication; +using Penumbra.Interop.ResourceLoading; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -21,8 +22,8 @@ public class CollectionCacheManager : IDisposable private readonly CollectionStorage _storage; private readonly ActiveCollections _active; internal readonly ResolvedFileChanged ResolvedFileChanged; - - internal readonly MetaFileManager MetaFileManager; + internal readonly MetaFileManager MetaFileManager; + internal readonly ResourceLoader ResourceLoader; private readonly ConcurrentQueue _changeQueue = new(); @@ -35,7 +36,7 @@ public class CollectionCacheManager : IDisposable => _storage.Where(c => c.HasCache); public CollectionCacheManager(FrameworkManager framework, CommunicatorService communicator, TempModManager tempMods, ModStorage modStorage, - MetaFileManager metaFileManager, ActiveCollections active, CollectionStorage storage) + MetaFileManager metaFileManager, ActiveCollections active, CollectionStorage storage, ResourceLoader resourceLoader) { _framework = framework; _communicator = communicator; @@ -44,6 +45,7 @@ public class CollectionCacheManager : IDisposable MetaFileManager = metaFileManager; _active = active; _storage = storage; + ResourceLoader = resourceLoader; ResolvedFileChanged = _communicator.ResolvedFileChanged; if (!_active.Individuals.IsLoaded) diff --git a/Penumbra/Collections/Cache/CustomResourceCache.cs b/Penumbra/Collections/Cache/CustomResourceCache.cs new file mode 100644 index 00000000..46c28393 --- /dev/null +++ b/Penumbra/Collections/Cache/CustomResourceCache.cs @@ -0,0 +1,49 @@ +using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; +using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.SafeHandles; +using Penumbra.String.Classes; + +namespace Penumbra.Collections.Cache; + +/// A cache for resources owned by a collection. +public sealed class CustomResourceCache(ResourceLoader loader) + : ConcurrentDictionary, IDisposable +{ + /// Invalidate an existing resource by clearing it from the cache and disposing it. + public void Invalidate(Utf8GamePath path) + { + if (TryRemove(path, out var handle)) + handle.Dispose(); + } + + public void Dispose() + { + foreach (var handle in Values) + handle.Dispose(); + Clear(); + } + + /// Get the requested resource either from the cached resource, or load a new one if it does not exist. + public SafeResourceHandle Get(ResourceCategory category, ResourceType type, Utf8GamePath path, ResolveData data) + { + if (TryGetClonedValue(path, out var handle)) + return handle; + + handle = loader.LoadResolvedSafeResource(category, type, path.Path, data); + var clone = handle.Clone(); + if (!TryAdd(path, clone)) + clone.Dispose(); + return handle; + } + + /// Get a cloned cached resource if it exists. + private bool TryGetClonedValue(Utf8GamePath path, [NotNullWhen(true)] out SafeResourceHandle? handle) + { + if (!TryGetValue(path, out handle)) + return false; + + handle = handle.Clone(); + return true; + } +} diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 1b467a8c..6c2c83b3 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -49,24 +49,6 @@ public unsafe class ResourceLoader : IDisposable return ret; } - public SafeResourceHandle LoadCacheableSafeResource(ResourceCategory category, ResourceType type, Utf8GamePath path, ResolveData resolveData) - { - var cache = resolveData.ModCollection._cache; - if (cache == null) - return LoadResolvedSafeResource(category, type, path.Path, resolveData); - - if (cache.LoadedResources.TryGetValue(path, out var cached)) - return cached.Clone(); - - var ret = LoadResolvedSafeResource(category, type, path.Path, resolveData); - - cached = ret.Clone(); - if (!cache.LoadedResources.TryAdd(path, cached)) - cached.Dispose(); - - return ret; - } - /// The function to use to resolve a given path. public Func ResolvePath = null!; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 15546ed3..dac86e44 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -156,7 +156,7 @@ public class ResourceTree var genericContext = globalContext.CreateContext(&human->CharacterBase); var cache = globalContext.Collection._cache; - if (cache != null && cache.LoadedResources.TryGetValue(PreBoneDeformerReplacer.PreBoneDeformerPath, out var pbdHandle)) + if (cache != null && cache.CustomResources.TryGetValue(PreBoneDeformerReplacer.PreBoneDeformerPath, out var pbdHandle)) { var pbdNode = genericContext.CreateNodeFromPbd(pbdHandle.ResourceHandle); if (pbdNode != null) diff --git a/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs index 44c6541e..9f553257 100644 --- a/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs @@ -1,10 +1,9 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using OtterGui.Services; using Penumbra.Api.Enums; -using Penumbra.GameData; using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.SafeHandles; @@ -12,14 +11,11 @@ using Penumbra.String.Classes; namespace Penumbra.Interop.Services; -public sealed unsafe class PreBoneDeformerReplacer : IDisposable +public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredService { public static readonly Utf8GamePath PreBoneDeformerPath = Utf8GamePath.FromSpan("chara/xls/boneDeformer/human.pbd"u8, out var p) ? p : Utf8GamePath.Empty; - [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _humanVTable = null!; - // Approximate name guesses. private delegate void CharacterBaseSetupScalingDelegate(CharacterBase* drawObject, uint slotIndex); private delegate void* CharacterBaseCreateDeformerDelegate(CharacterBase* drawObject, uint slotIndex); @@ -32,15 +28,16 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable private readonly ResourceLoader _resourceLoader; private readonly IFramework _framework; - public PreBoneDeformerReplacer(CharacterUtility utility, CollectionResolver collectionResolver, ResourceLoader resourceLoader, IGameInteropProvider interop, IFramework framework) + public PreBoneDeformerReplacer(CharacterUtility utility, CollectionResolver collectionResolver, ResourceLoader resourceLoader, + IGameInteropProvider interop, IFramework framework, CharacterBaseVTables vTables) { interop.InitializeFromAttributes(this); - _utility = utility; - _collectionResolver = collectionResolver; - _resourceLoader = resourceLoader; - _framework = framework; - _humanSetupScalingHook = interop.HookFromAddress(_humanVTable[57], SetupScaling); - _humanCreateDeformerHook = interop.HookFromAddress(_humanVTable[91], CreateDeformer); + _utility = utility; + _collectionResolver = collectionResolver; + _resourceLoader = resourceLoader; + _framework = framework; + _humanSetupScalingHook = interop.HookFromAddress(vTables.HumanVTable[57], SetupScaling); + _humanCreateDeformerHook = interop.HookFromAddress(vTables.HumanVTable[91], CreateDeformer); _humanSetupScalingHook.Enable(); _humanCreateDeformerHook.Enable(); } @@ -54,13 +51,17 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable private SafeResourceHandle GetPreBoneDeformerForCharacter(CharacterBase* drawObject) { var resolveData = _collectionResolver.IdentifyCollection(&drawObject->DrawObject, true); - return _resourceLoader.LoadCacheableSafeResource(ResourceCategory.Chara, ResourceType.Pbd, PreBoneDeformerPath, resolveData); + if (resolveData.ModCollection._cache is not { } cache) + return _resourceLoader.LoadResolvedSafeResource(ResourceCategory.Chara, ResourceType.Pbd, PreBoneDeformerPath.Path, resolveData); + + return cache.CustomResources.Get(ResourceCategory.Chara, ResourceType.Pbd, PreBoneDeformerPath, resolveData); } private void SetupScaling(CharacterBase* drawObject, uint slotIndex) { if (!_framework.IsInFrameworkUpdateThread) - Penumbra.Log.Warning($"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupScaling)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); + Penumbra.Log.Warning( + $"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupScaling)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); using var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); try @@ -78,7 +79,8 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable private void* CreateDeformer(CharacterBase* drawObject, uint slotIndex) { if (!_framework.IsInFrameworkUpdateThread) - Penumbra.Log.Warning($"{nameof(PreBoneDeformerReplacer)}.{nameof(CreateDeformer)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); + Penumbra.Log.Warning( + $"{nameof(PreBoneDeformerReplacer)}.{nameof(CreateDeformer)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); using var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); try diff --git a/Penumbra/Interop/Services/ShaderReplacementFixer.cs b/Penumbra/Interop/Services/ShaderReplacementFixer.cs index 26906ace..3809ecbd 100644 --- a/Penumbra/Interop/Services/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Services/ShaderReplacementFixer.cs @@ -5,6 +5,7 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData; using Penumbra.Interop.Hooks.Resources; @@ -13,7 +14,7 @@ using CSModelRenderer = FFXIVClientStructs.FFXIV.Client.Graphics.Render.ModelRen namespace Penumbra.Interop.Services; -public sealed unsafe class ShaderReplacementFixer : IDisposable +public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredService { public static ReadOnlySpan SkinShpkName => "skin.shpk"u8; @@ -21,11 +22,10 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable public static ReadOnlySpan CharacterGlassShpkName => "characterglass.shpk"u8; - [Signature(Sigs.HumanVTable, ScanType = ScanType.StaticAddress)] - private readonly nint* _humanVTable = null!; - private delegate nint CharacterBaseOnRenderMaterialDelegate(CharacterBase* drawObject, CSModelRenderer.OnRenderMaterialParams* param); - private delegate nint ModelRendererOnRenderMaterialDelegate(CSModelRenderer* modelRenderer, ushort* outFlags, CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex); + + private delegate nint ModelRendererOnRenderMaterialDelegate(CSModelRenderer* modelRenderer, ushort* outFlags, + CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex); private readonly Hook _humanOnRenderMaterialHook; @@ -59,14 +59,15 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable => _moddedCharacterGlassShpkCount; public ShaderReplacementFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, ModelRenderer modelRenderer, - CommunicatorService communicator, IGameInteropProvider interop) + CommunicatorService communicator, IGameInteropProvider interop, CharacterBaseVTables vTables) { interop.InitializeFromAttributes(this); - _resourceHandleDestructor = resourceHandleDestructor; - _utility = utility; - _modelRenderer = modelRenderer; - _communicator = communicator; - _humanOnRenderMaterialHook = interop.HookFromAddress(_humanVTable[62], OnRenderHumanMaterial); + _resourceHandleDestructor = resourceHandleDestructor; + _utility = utility; + _modelRenderer = modelRenderer; + _communicator = communicator; + _humanOnRenderMaterialHook = + interop.HookFromAddress(vTables.HumanVTable[62], OnRenderHumanMaterial); _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.ShaderReplacementFixer); _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.ShaderReplacementFixer); _humanOnRenderMaterialHook.Enable(); @@ -82,7 +83,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable _moddedCharacterGlassShpkMaterials.Clear(); _moddedSkinShpkMaterials.Clear(); _moddedCharacterGlassShpkCount = 0; - _moddedSkinShpkCount = 0; + _moddedSkinShpkCount = 0; } public (ulong Skin, ulong CharacterGlass) GetAndResetSlowPathCallDeltas() @@ -106,16 +107,12 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable var shpkName = mtrl->ShpkNameSpan; if (SkinShpkName.SequenceEqual(shpkName) && (nint)shpk != _utility.DefaultSkinShpkResource) - { if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle)) Interlocked.Increment(ref _moddedSkinShpkCount); - } if (CharacterGlassShpkName.SequenceEqual(shpkName) && shpk != _modelRenderer.DefaultCharacterGlassShaderPackage) - { if (_moddedCharacterGlassShpkMaterials.TryAdd(mtrlResourceHandle)) Interlocked.Increment(ref _moddedCharacterGlassShpkCount); - } } private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) @@ -159,9 +156,9 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable } } - private nint ModelRendererOnRenderMaterialDetour(CSModelRenderer* modelRenderer, ushort* outFlags, CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex) + private nint ModelRendererOnRenderMaterialDetour(CSModelRenderer* modelRenderer, ushort* outFlags, + CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex) { - // If we don't have any on-screen instances of modded characterglass.shpk, we don't need the slow path at all. if (!Enabled || _moddedCharacterGlassShpkCount == 0) return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index c34a7771..b76780c0 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -77,8 +77,6 @@ public class Penumbra : IDalamudPlugin _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); _services.GetService(); - _services.GetService(); - _services.GetService(); _services.GetService(); // Initialize before Interface. diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 6f85ddd2..9e6071b4 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -131,9 +131,7 @@ public static class StaticServiceManager => services.AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); + .AddSingleton(); private static ServiceManager AddResolvers(this ServiceManager services) => services.AddSingleton() From b04cb343dd5aacd4a6134ad28e7dca1154cce979 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Mar 2024 19:32:10 +0100 Subject: [PATCH 0524/1381] Make setting for crash handler. --- Penumbra/Configuration.cs | 18 +++--- Penumbra/Services/CrashHandlerService.cs | 6 +- Penumbra/UI/Tabs/SettingsTab.cs | 77 +++++++++++++++--------- 3 files changed, 59 insertions(+), 42 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 9c0b4f2d..f91e0534 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -33,12 +33,12 @@ public class Configuration : IPluginConfiguration, ISavable public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; - public bool UseCrashHandler { get; set; } = true; - public bool OpenWindowAtStart { get; set; } = false; - public bool HideUiInGPose { get; set; } = false; - public bool HideUiInCutscenes { get; set; } = true; - public bool HideUiWhenUiHidden { get; set; } = false; - public bool UseDalamudUiTextureRedirection { get; set; } = true; + public bool? UseCrashHandler { get; set; } = null; + public bool OpenWindowAtStart { get; set; } = false; + public bool HideUiInGPose { get; set; } = false; + public bool HideUiInCutscenes { get; set; } = true; + public bool HideUiWhenUiHidden { get; set; } = false; + public bool UseDalamudUiTextureRedirection { get; set; } = true; public bool UseCharacterCollectionInMainWindow { get; set; } = true; public bool UseCharacterCollectionsInCards { get; set; } = true; @@ -48,9 +48,9 @@ public class Configuration : IPluginConfiguration, ISavable public bool UseNoModsInInspect { get; set; } = false; public bool HideChangedItemFilters { get; set; } = false; public bool ReplaceNonAsciiOnImport { get; set; } = false; - public bool HidePrioritiesInSelector { get; set; } = false; - public bool HideRedrawBar { get; set; } = false; - public int OptionGroupCollapsibleMin { get; set; } = 5; + public bool HidePrioritiesInSelector { get; set; } = false; + public bool HideRedrawBar { get; set; } = false; + public int OptionGroupCollapsibleMin { get; set; } = 5; public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index c713d623..6025c2c0 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -36,7 +36,7 @@ public sealed class CrashHandlerService : IDisposable, IService _config = config; _validityChecker = validityChecker; - if (!_config.UseCrashHandler) + if (_config.UseCrashHandler ?? false) return; OpenEventWriter(); @@ -84,7 +84,7 @@ public sealed class CrashHandlerService : IDisposable, IService public void Enable() { - if (_config.UseCrashHandler) + if (_config.UseCrashHandler ?? false) return; _config.UseCrashHandler = true; @@ -97,7 +97,7 @@ public sealed class CrashHandlerService : IDisposable, IService public void Disable() { - if (!_config.UseCrashHandler) + if (!(_config.UseCrashHandler ?? false)) return; _config.UseCrashHandler = false; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 80fe6fb6..c524a840 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -43,6 +43,7 @@ public class SettingsTab : ITab private readonly DalamudPluginInterface _pluginInterface; private readonly IDataManager _gameData; private readonly PredefinedTagManager _predefinedTagManager; + private readonly CrashHandlerService _crashService; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -53,7 +54,7 @@ public class SettingsTab : ITab Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, - IDataManager gameData, PredefinedTagManager predefinedTagConfig) + IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService) { _pluginInterface = pluginInterface; _config = config; @@ -74,6 +75,7 @@ public class SettingsTab : ITab if (_compactor.CanCompact) _compactor.Enabled = _config.UseFileSystemCompression; _predefinedTagManager = predefinedTagConfig; + _crashService = crashService; } public void DrawHeader() @@ -228,35 +230,35 @@ public class SettingsTab : ITab _newModDirectory = _config.ModDirectory; bool save, selected; - using (ImRaii.Group()) - { - ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); - using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale, !_modManager.Valid)) - { - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder) - .Push(ImGuiCol.TextDisabled, Colors.RegexWarningBorder, !_modManager.Valid); - save = ImGui.InputTextWithHint("##rootDirectory", "Enter Root Directory here (MANDATORY)...", ref _newModDirectory, - RootDirectoryMaxLength, ImGuiInputTextFlags.EnterReturnsTrue); - } - - selected = ImGui.IsItemActive(); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); - ImGui.SameLine(); - DrawDirectoryPickerButton(); - style.Pop(); - ImGui.SameLine(); - - const string tt = "This is where Penumbra will store your extracted mod files.\n" - + "TTMP files are not copied, just extracted.\n" - + "This directory needs to be accessible and you need write access here.\n" - + "It is recommended that this directory is placed on a fast hard drive, preferably an SSD.\n" - + "It should also be placed near the root of a logical drive - the shorter the total path to this folder, the better.\n" - + "Definitely do not place it in your Dalamud directory or any sub-directory thereof."; - ImGuiComponents.HelpMarker(tt); - _tutorial.OpenTutorial(BasicTutorialSteps.GeneralTooltips); - ImGui.SameLine(); - ImGui.TextUnformatted("Root Directory"); - ImGuiUtil.HoverTooltip(tt); + using (ImRaii.Group()) + { + ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); + using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale, !_modManager.Valid)) + { + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder) + .Push(ImGuiCol.TextDisabled, Colors.RegexWarningBorder, !_modManager.Valid); + save = ImGui.InputTextWithHint("##rootDirectory", "Enter Root Directory here (MANDATORY)...", ref _newModDirectory, + RootDirectoryMaxLength, ImGuiInputTextFlags.EnterReturnsTrue); + } + + selected = ImGui.IsItemActive(); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3, 0)); + ImGui.SameLine(); + DrawDirectoryPickerButton(); + style.Pop(); + ImGui.SameLine(); + + const string tt = "This is where Penumbra will store your extracted mod files.\n" + + "TTMP files are not copied, just extracted.\n" + + "This directory needs to be accessible and you need write access here.\n" + + "It is recommended that this directory is placed on a fast hard drive, preferably an SSD.\n" + + "It should also be placed near the root of a logical drive - the shorter the total path to this folder, the better.\n" + + "Definitely do not place it in your Dalamud directory or any sub-directory thereof."; + ImGuiComponents.HelpMarker(tt); + _tutorial.OpenTutorial(BasicTutorialSteps.GeneralTooltips); + ImGui.SameLine(); + ImGui.TextUnformatted("Root Directory"); + ImGuiUtil.HoverTooltip(tt); } _tutorial.OpenTutorial(BasicTutorialSteps.ModDirectory); @@ -704,6 +706,7 @@ public class SettingsTab : ITab if (!header) return; + DrawCrashHandler(); DrawMinimumDimensionConfig(); Checkbox("Auto Deduplicate on Import", "Automatically deduplicate mod files on import. This will make mod file sizes smaller, but deletes (binary identical) files.", @@ -721,6 +724,20 @@ public class SettingsTab : ITab ImGui.NewLine(); } + private void DrawCrashHandler() + { + Checkbox("Enable Penumbra Crash Logging (Experimental)", + "Enables Penumbra to launch a secondary process that records some game activity which may or may not help diagnosing Penumbra-related game crashes.", + _config.UseCrashHandler ?? false, + v => + { + if (v) + _crashService.Enable(); + else + _crashService.Disable(); + }); + } + private void DrawCompressionBox() { if (!_compactor.CanCompact) From 47c5187ad929468610f49ae04a4f534e21dc4a21 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Mar 2024 19:34:30 +0100 Subject: [PATCH 0525/1381] Derp. --- Penumbra/Services/CrashHandlerService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 6025c2c0..5423ec15 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -36,7 +36,7 @@ public sealed class CrashHandlerService : IDisposable, IService _config = config; _validityChecker = validityChecker; - if (_config.UseCrashHandler ?? false) + if (!(_config.UseCrashHandler ?? false)) return; OpenEventWriter(); From a39419288c1432f5fa9a9a7e1b7b97a8e48ea574 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 28 Mar 2024 18:36:31 +0000 Subject: [PATCH 0526/1381] [CI] Updating repo.json for testing_1.0.2.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 5a51afa2..936adfc0 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.5", + "TestingAssemblyVersion": "1.0.2.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,7 +17,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From de239578ccb83137d2c4f69ad2b7bd8781d686d5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 29 Mar 2024 14:44:08 +0100 Subject: [PATCH 0527/1381] Fix weird exception. --- Penumbra/Api/IpcTester.cs | 76 +++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 43 deletions(-) diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs index 30f3c80f..898c5de3 100644 --- a/Penumbra/Api/IpcTester.cs +++ b/Penumbra/Api/IpcTester.cs @@ -583,23 +583,18 @@ public class IpcTester : IDisposable } } - private class Resolve + private class Resolve(DalamudPluginInterface pi) { - private readonly DalamudPluginInterface _pi; - private string _currentResolvePath = string.Empty; private string _currentResolveCharacter = string.Empty; private string _currentReversePath = string.Empty; private int _currentReverseIdx; - private Task<(string[], string[][])> _task = Task.FromException<(string[], string[][])>(new Exception()); - - public Resolve(DalamudPluginInterface pi) - => _pi = pi; + private Task<(string[], string[][])> _task = Task.FromResult<(string[], string[][])>(([], [])); public void Draw() { - using var _ = ImRaii.TreeNode("Resolving"); - if (!_) + using var tree = ImRaii.TreeNode("Resolving"); + if (!tree) return; ImGui.InputTextWithHint("##resolvePath", "Resolve this game path...", ref _currentResolvePath, Utf8GamePath.MaxGamePathLength); @@ -613,28 +608,28 @@ public class IpcTester : IDisposable DrawIntro(Ipc.ResolveDefaultPath.Label, "Default Collection Resolve"); if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveDefaultPath.Subscriber(_pi).Invoke(_currentResolvePath)); + ImGui.TextUnformatted(Ipc.ResolveDefaultPath.Subscriber(pi).Invoke(_currentResolvePath)); DrawIntro(Ipc.ResolveInterfacePath.Label, "Interface Collection Resolve"); if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveInterfacePath.Subscriber(_pi).Invoke(_currentResolvePath)); + ImGui.TextUnformatted(Ipc.ResolveInterfacePath.Subscriber(pi).Invoke(_currentResolvePath)); DrawIntro(Ipc.ResolvePlayerPath.Label, "Player Collection Resolve"); if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolvePlayerPath.Subscriber(_pi).Invoke(_currentResolvePath)); + ImGui.TextUnformatted(Ipc.ResolvePlayerPath.Subscriber(pi).Invoke(_currentResolvePath)); DrawIntro(Ipc.ResolveCharacterPath.Label, "Character Collection Resolve"); if (_currentResolvePath.Length != 0 && _currentResolveCharacter.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveCharacterPath.Subscriber(_pi).Invoke(_currentResolvePath, _currentResolveCharacter)); + ImGui.TextUnformatted(Ipc.ResolveCharacterPath.Subscriber(pi).Invoke(_currentResolvePath, _currentResolveCharacter)); DrawIntro(Ipc.ResolveGameObjectPath.Label, "Game Object Collection Resolve"); if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveGameObjectPath.Subscriber(_pi).Invoke(_currentResolvePath, _currentReverseIdx)); + ImGui.TextUnformatted(Ipc.ResolveGameObjectPath.Subscriber(pi).Invoke(_currentResolvePath, _currentReverseIdx)); DrawIntro(Ipc.ReverseResolvePath.Label, "Reversed Game Paths"); if (_currentReversePath.Length > 0) { - var list = Ipc.ReverseResolvePath.Subscriber(_pi).Invoke(_currentReversePath, _currentResolveCharacter); + var list = Ipc.ReverseResolvePath.Subscriber(pi).Invoke(_currentReversePath, _currentResolveCharacter); if (list.Length > 0) { ImGui.TextUnformatted(list[0]); @@ -646,7 +641,7 @@ public class IpcTester : IDisposable DrawIntro(Ipc.ReverseResolvePlayerPath.Label, "Reversed Game Paths (Player)"); if (_currentReversePath.Length > 0) { - var list = Ipc.ReverseResolvePlayerPath.Subscriber(_pi).Invoke(_currentReversePath); + var list = Ipc.ReverseResolvePlayerPath.Subscriber(pi).Invoke(_currentReversePath); if (list.Length > 0) { ImGui.TextUnformatted(list[0]); @@ -658,7 +653,7 @@ public class IpcTester : IDisposable DrawIntro(Ipc.ReverseResolveGameObjectPath.Label, "Reversed Game Paths (Game Object)"); if (_currentReversePath.Length > 0) { - var list = Ipc.ReverseResolveGameObjectPath.Subscriber(_pi).Invoke(_currentReversePath, _currentReverseIdx); + var list = Ipc.ReverseResolveGameObjectPath.Subscriber(pi).Invoke(_currentReversePath, _currentReverseIdx); if (list.Length > 0) { ImGui.TextUnformatted(list[0]); @@ -668,19 +663,31 @@ public class IpcTester : IDisposable } var forwardArray = _currentResolvePath.Length > 0 - ? new[] - { - _currentResolvePath, - } + ? [_currentResolvePath] : Array.Empty(); var reverseArray = _currentReversePath.Length > 0 - ? new[] - { - _currentReversePath, - } + ? [_currentReversePath] : Array.Empty(); - string ConvertText((string[], string[][]) data) + DrawIntro(Ipc.ResolvePlayerPaths.Label, "Resolved Paths (Player)"); + if (forwardArray.Length > 0 || reverseArray.Length > 0) + { + var ret = Ipc.ResolvePlayerPaths.Subscriber(pi).Invoke(forwardArray, reverseArray); + ImGui.TextUnformatted(ConvertText(ret)); + } + + DrawIntro(Ipc.ResolvePlayerPathsAsync.Label, "Resolved Paths Async (Player)"); + if (ImGui.Button("Start")) + _task = Ipc.ResolvePlayerPathsAsync.Subscriber(pi).Invoke(forwardArray, reverseArray); + var hovered = ImGui.IsItemHovered(); + ImGui.SameLine(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(_task.Status.ToString()); + if ((hovered || ImGui.IsItemHovered()) && _task.IsCompletedSuccessfully) + ImGui.SetTooltip(ConvertText(_task.Result)); + return; + + static string ConvertText((string[], string[][]) data) { var text = string.Empty; if (data.Item1.Length > 0) @@ -697,23 +704,6 @@ public class IpcTester : IDisposable return text; } - - DrawIntro(Ipc.ResolvePlayerPaths.Label, "Resolved Paths (Player)"); - if (forwardArray.Length > 0 || reverseArray.Length > 0) - { - var ret = Ipc.ResolvePlayerPaths.Subscriber(_pi).Invoke(forwardArray, reverseArray); - ImGui.TextUnformatted(ConvertText(ret)); - } - - DrawIntro(Ipc.ResolvePlayerPathsAsync.Label, "Resolved Paths Async (Player)"); - if (ImGui.Button("Start")) - _task = Ipc.ResolvePlayerPathsAsync.Subscriber(_pi).Invoke(forwardArray, reverseArray); - var hovered = ImGui.IsItemHovered(); - ImGui.SameLine(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(_task.Status.ToString()); - if ((hovered || ImGui.IsItemHovered()) && _task.IsCompletedSuccessfully) - ImGui.SetTooltip(ConvertText(_task.Result)); } } From b4b813fe5e05ef321cda034de6691d58cc8d5b9d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 29 Mar 2024 20:05:25 +0100 Subject: [PATCH 0528/1381] Advanced Editing minor improvements --- OtterGui | 2 +- Penumbra.GameData | 2 +- .../UI/AdvancedWindow/ModEditWindow.Materials.cs | 3 ++- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 2 +- .../AdvancedWindow/ModEditWindow.ShaderPackages.cs | 12 +++++++++--- 5 files changed, 14 insertions(+), 7 deletions(-) diff --git a/OtterGui b/OtterGui index 4e06921d..b70c7cc2 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 4e06921da239788331a4527aa6a2943cf0e809fe +Subproject commit b70c7cc2f6c71f80884de30a237cab201d7fe150 diff --git a/Penumbra.GameData b/Penumbra.GameData index 66687643..45679aa3 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 66687643da2163c938575ad6949c8d0fbd03afe7 +Subproject commit 45679aa32cc37b59f5eeb7cf6bf5a3ea36c626e0 diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index fab41c7d..68b3717f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Widgets; using Penumbra.GameData.Files; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -170,7 +171,7 @@ public partial class ModEditWindow using var t = ImRaii.TreeNode($"Additional Data (Size: {file.AdditionalData.Length})###AdditionalData"); if (t) - ImGuiUtil.TextWrapped(string.Join(' ', file.AdditionalData.Select(c => $"{c:X2}"))); + Widget.DrawHexViewer(file.AdditionalData); } private void DrawMaterialReassignmentTab() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 737c41d9..03f276ea 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -560,7 +560,7 @@ public partial class ModEditWindow { using var t = ImRaii.TreeNode($"Additional Data (Size: {_lastFile.RemainingData.Length})###AdditionalData"); if (t) - ImGuiUtil.TextWrapped(string.Join(' ', _lastFile.RemainingData.Select(c => $"{c:X2}"))); + Widget.DrawHexViewer(_lastFile.RemainingData); } return false; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 8d1c8cb7..070895b5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -10,6 +10,7 @@ using Penumbra.GameData.Files; using Penumbra.GameData.Interop; using Penumbra.String; using static Penumbra.GameData.Files.ShpkFile; +using OtterGui.Widgets; namespace Penumbra.UI.AdvancedWindow; @@ -172,11 +173,16 @@ public partial class ModEditWindow ret |= DrawShaderPackageResourceArray("Samplers", "slot", false, shader.Samplers, true); ret |= DrawShaderPackageResourceArray("Unordered Access Views", "slot", true, shader.Uavs, true); - if (shader.AdditionalHeader.Length > 0) + if (shader.DeclaredInputs != 0) + ImRaii.TreeNode($"Declared Inputs: {shader.DeclaredInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + if (shader.UsedInputs != 0) + ImRaii.TreeNode($"Used Inputs: {shader.UsedInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + + if (shader.AdditionalHeader.Length > 8) { using var t2 = ImRaii.TreeNode($"Additional Header (Size: {shader.AdditionalHeader.Length})###AdditionalHeader"); if (t2) - ImGuiUtil.TextWrapped(string.Join(' ', shader.AdditionalHeader.Select(c => $"{c:X2}"))); + Widget.DrawHexViewer(shader.AdditionalHeader); } if (tab.Shpk.Disassembled) @@ -549,7 +555,7 @@ public partial class ModEditWindow { using var t = ImRaii.TreeNode($"Additional Data (Size: {tab.Shpk.AdditionalData.Length})###AdditionalData"); if (t) - ImGuiUtil.TextWrapped(string.Join(' ', tab.Shpk.AdditionalData.Select(c => $"{c:X2}"))); + Widget.DrawHexViewer(tab.Shpk.AdditionalData); } } From 5cebddb0ab680fa38edb62e3b5cc6cfe23203388 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 30 Mar 2024 14:59:31 +0100 Subject: [PATCH 0529/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index b70c7cc2..f641a34f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit b70c7cc2f6c71f80884de30a237cab201d7fe150 +Subproject commit f641a34ffa80e89bd61701f60f15d15c4c5b361e From a65009dfb0f7714a4343c44d9f0dd0dc61ee0760 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 1 Apr 2024 13:59:09 +0200 Subject: [PATCH 0530/1381] Fix issue with merging and deduplicating. --- OtterGui | 2 +- Penumbra/Mods/Editor/DuplicateManager.cs | 16 ++++--- Penumbra/Mods/Editor/ModMerger.cs | 58 ++++++++++++------------ Penumbra/Mods/Manager/ModOptionEditor.cs | 31 +++++++------ Penumbra/Services/CrashHandlerService.cs | 2 +- 5 files changed, 59 insertions(+), 50 deletions(-) diff --git a/OtterGui b/OtterGui index f641a34f..f48c6886 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit f641a34ffa80e89bd61701f60f15d15c4c5b361e +Subproject commit f48c6886cbc163c5a292fa8b9fd919cb01c11d7b diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 77d10cc4..c8530936 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Classes; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; using Penumbra.Services; @@ -81,7 +82,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co if (useModManager) { - modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict); + modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict, SaveType.ImmediateSync); } else { @@ -216,18 +217,21 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co } /// Deduplicate a mod simply by its directory without any confirmation or waiting time. - internal void DeduplicateMod(DirectoryInfo modDirectory) + internal void DeduplicateMod(DirectoryInfo modDirectory, bool useModManager = false) { try { - var mod = new Mod(modDirectory); - modManager.Creator.ReloadMod(mod, true, out _); + if (!useModManager || !modManager.TryGetMod(modDirectory.Name, string.Empty, out var mod)) + { + mod = new Mod(modDirectory); + modManager.Creator.ReloadMod(mod, true, out _); + } Clear(); var files = new ModFileCollection(); files.UpdateAll(mod, mod.Default); - CheckDuplicates(files.Available.OrderByDescending(f => f.FileSize).ToArray(), CancellationToken.None); - DeleteDuplicates(files, mod, mod.Default, false); + CheckDuplicates([.. files.Available.OrderByDescending(f => f.FileSize)], CancellationToken.None); + DeleteDuplicates(files, mod, mod.Default, useModManager); } catch (Exception e) { diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index f5d0e4a4..842b1bb3 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -36,7 +36,7 @@ public class ModMerger : IDisposable public readonly HashSet SelectedOptions = []; - public readonly IReadOnlyList Warnings = new List(); + public readonly IReadOnlyList Warnings = []; public Exception? Error { get; private set; } public ModMerger(ModManager mods, ModOptionEditor editor, ModFileSystemSelector selector, DuplicateManager duplicates, @@ -78,7 +78,8 @@ public class ModMerger : IDisposable MergeWithOptions(); else MergeIntoOption(OptionGroupName, OptionName); - _duplicates.DeduplicateMod(MergeToMod.ModPath); + + _duplicates.DeduplicateMod(MergeToMod.ModPath, true); } catch (Exception ex) { @@ -134,10 +135,10 @@ public class ModMerger : IDisposable return; } - var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, GroupType.Multi, groupName); + var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, GroupType.Multi, groupName, SaveType.None); if (groupCreated) _createdGroups.Add(groupIdx); - var (option, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName); + var (option, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName, SaveType.None); if (optionCreated) _createdOptions.Add(option); var dir = ModCreator.NewOptionDirectory(MergeToMod!.ModPath, groupName, _config.ReplaceNonAsciiOnImport); @@ -156,27 +157,6 @@ public class ModMerger : IDisposable var swaps = option.FileSwapData.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); var manips = option.ManipulationData.ToHashSet(); - bool GetFullPath(FullPath input, out FullPath ret) - { - if (fromFileToFile) - { - if (!_fileToFile.TryGetValue(input.FullName, out var s)) - { - ret = input; - return false; - } - - ret = new FullPath(s); - return true; - } - - if (!Utf8RelPath.FromFile(input, MergeFromMod!.ModPath, out var relPath)) - throw new Exception($"Could not create relative path from {input} and {MergeFromMod!.ModPath}."); - - ret = new FullPath(MergeToMod!.ModPath, relPath); - return true; - } - foreach (var originalOption in mergeOptions) { foreach (var manip in originalOption.Manipulations) @@ -204,9 +184,31 @@ public class ModMerger : IDisposable } } - _editor.OptionSetFiles(MergeToMod!, option.GroupIdx, option.OptionIdx, redirections); - _editor.OptionSetFileSwaps(MergeToMod!, option.GroupIdx, option.OptionIdx, swaps); - _editor.OptionSetManipulations(MergeToMod!, option.GroupIdx, option.OptionIdx, manips); + _editor.OptionSetFiles(MergeToMod!, option.GroupIdx, option.OptionIdx, redirections, SaveType.None); + _editor.OptionSetFileSwaps(MergeToMod!, option.GroupIdx, option.OptionIdx, swaps, SaveType.None); + _editor.OptionSetManipulations(MergeToMod!, option.GroupIdx, option.OptionIdx, manips, SaveType.ImmediateSync); + return; + + bool GetFullPath(FullPath input, out FullPath ret) + { + if (fromFileToFile) + { + if (!_fileToFile.TryGetValue(input.FullName, out var s)) + { + ret = input; + return false; + } + + ret = new FullPath(s); + return true; + } + + if (!Utf8RelPath.FromFile(input, MergeFromMod!.ModPath, out var relPath)) + throw new Exception($"Could not create relative path from {input} and {MergeFromMod!.ModPath}."); + + ret = new FullPath(MergeToMod!.ModPath, relPath); + return true; + } } private void CopyFiles(DirectoryInfo directory) diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 3459ce1a..60508d33 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -78,7 +78,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Add a new, empty option group of the given type and name. - public void AddModGroup(Mod mod, GroupType type, string newName) + public void AddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) { if (!VerifyFileName(mod, null, newName, true)) return; @@ -96,18 +96,18 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS Name = newName, Priority = maxPriority, }); - saveService.ImmediateSave(new ModSaveGroup(mod, mod.Groups.Count - 1, config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(mod, mod.Groups.Count - 1, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, mod.Groups.Count - 1, -1, -1); } /// Add a new mod, empty option group of the given type and name if it does not exist already. - public (IModGroup, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string newName) + public (IModGroup, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) { var idx = mod.Groups.IndexOf(g => g.Name == newName); if (idx >= 0) return (mod.Groups[idx], idx, false); - AddModGroup(mod, type, newName); + AddModGroup(mod, type, newName, saveType); if (mod.Groups[^1].Name != newName) throw new Exception($"Could not create new mod group with name {newName}."); @@ -226,7 +226,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Add a new empty option of the given name for the given group. - public void AddOption(Mod mod, int groupIdx, string newName) + public void AddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) { var group = mod.Groups[groupIdx]; var subMod = new SubMod(mod) { Name = newName }; @@ -241,19 +241,19 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS break; } - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); } /// Add a new empty option of the given name for the given group if it does not exist already. - public (SubMod, bool) FindOrAddOption(Mod mod, int groupIdx, string newName) + public (SubMod, bool) FindOrAddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) { var group = mod.Groups[groupIdx]; var idx = group.IndexOf(o => o.Name == newName); if (idx >= 0) return ((SubMod)group[idx], false); - AddOption(mod, groupIdx, newName); + AddOption(mod, groupIdx, newName, saveType); if (group[^1].Name != newName) throw new Exception($"Could not create new option with name {newName} in {group.Name}."); @@ -324,7 +324,8 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Set the meta manipulations for a given option. Replaces existing manipulations. - public void OptionSetManipulations(Mod mod, int groupIdx, int optionIdx, HashSet manipulations) + public void OptionSetManipulations(Mod mod, int groupIdx, int optionIdx, HashSet manipulations, + SaveType saveType = SaveType.Queue) { var subMod = GetSubMod(mod, groupIdx, optionIdx); if (subMod.Manipulations.Count == manipulations.Count @@ -333,12 +334,13 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.ManipulationData.SetTo(manipulations); - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, optionIdx, -1); } /// Set the file redirections for a given option. Replaces existing redirections. - public void OptionSetFiles(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary replacements) + public void OptionSetFiles(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary replacements, + SaveType saveType = SaveType.Queue) { var subMod = GetSubMod(mod, groupIdx, optionIdx); if (subMod.FileData.SetEquals(replacements)) @@ -346,7 +348,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.FileData.SetTo(replacements); - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, optionIdx, -1); } @@ -364,7 +366,8 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Set the file swaps for a given option. Replaces existing swaps. - public void OptionSetFileSwaps(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary swaps) + public void OptionSetFileSwaps(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary swaps, + SaveType saveType = SaveType.Queue) { var subMod = GetSubMod(mod, groupIdx, optionIdx); if (subMod.FileSwapData.SetEquals(swaps)) @@ -372,7 +375,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); subMod.FileSwapData.SetTo(swaps); - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, optionIdx, -1); } diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 5423ec15..078b812b 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -213,7 +213,7 @@ public sealed class CrashHandlerService : IDisposable, IService } catch (Exception ex) { - Penumbra.Log.Debug($"Could not delete {dir}:\n{ex}"); + Penumbra.Log.Verbose($"Could not delete {dir}. This is generally not an error:\n{ex}"); } } } From 6e7512c13e20d0585f4d9c36aeb0c1563b62c568 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Apr 2024 14:53:30 +0200 Subject: [PATCH 0531/1381] Add Punchline. --- Penumbra/Penumbra.json | 1 + repo.json | 1 + 2 files changed, 2 insertions(+) diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 8173e001..85e01c84 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -1,6 +1,7 @@ { "Author": "Ottermandias, Adam, Wintermute", "Name": "Penumbra", + "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "9.0.0.1", diff --git a/repo.json b/repo.json index 936adfc0..232afaa0 100644 --- a/repo.json +++ b/repo.json @@ -2,6 +2,7 @@ { "Author": "Ottermandias, Adam, Wintermute", "Name": "Penumbra", + "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", From 77bf441e626a00a1d7e4b4de2c791472c2de66ec Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Apr 2024 15:29:19 +0200 Subject: [PATCH 0532/1381] Update Open Settings and Main UI. --- Penumbra/UI/ConfigWindow.cs | 7 +++++++ Penumbra/UI/WindowSystem.cs | 6 ++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index d52ebb99..9ae11fc3 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -4,6 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Custom; using OtterGui.Raii; +using Penumbra.Api.Enums; using Penumbra.Services; using Penumbra.UI.Classes; using Penumbra.UI.Tabs; @@ -35,6 +36,12 @@ public sealed class ConfigWindow : Window IsOpen = _config.OpenWindowAtStart; } + public void OpenSettings() + { + _configTabs.SelectTab = TabType.Settings; + IsOpen = true; + } + public void Setup(Penumbra penumbra, ConfigTabBar configTabs) { _penumbra = penumbra; diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index 62ad5a6e..c5418eb3 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -27,7 +27,8 @@ public class PenumbraWindowSystem : IDisposable _windowSystem.AddWindow(editWindow); _windowSystem.AddWindow(importPopup); _windowSystem.AddWindow(debugTab); - _uiBuilder.OpenConfigUi += Window.Toggle; + _uiBuilder.OpenMainUi += Window.Toggle; + _uiBuilder.OpenConfigUi += Window.OpenSettings; _uiBuilder.Draw += _windowSystem.Draw; _uiBuilder.Draw += _fileDialog.Draw; _uiBuilder.DisableGposeUiHide = !config.HideUiInGPose; @@ -40,7 +41,8 @@ public class PenumbraWindowSystem : IDisposable public void Dispose() { - _uiBuilder.OpenConfigUi -= Window.Toggle; + _uiBuilder.OpenMainUi -= Window.Toggle; + _uiBuilder.OpenConfigUi -= Window.OpenSettings; _uiBuilder.Draw -= _windowSystem.Draw; _uiBuilder.Draw -= _fileDialog.Draw; } From b1ca073276e140ab88cc2121ee52b0a166af02dc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Apr 2024 16:35:55 +0200 Subject: [PATCH 0533/1381] Turn Settings and Priority into their own types. --- Penumbra/Api/PenumbraApi.cs | 49 ++++---- Penumbra/Api/TempModManager.cs | 21 ++-- Penumbra/Collections/Cache/CollectionCache.cs | 8 +- .../Cache/CollectionCacheManager.cs | 7 +- .../Collections/Manager/CollectionEditor.cs | 66 +++------- .../Collections/Manager/CollectionStorage.cs | 2 +- .../Manager/ModCollectionMigration.cs | 4 +- Penumbra/Communication/ModSettingChanged.cs | 5 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 10 +- .../PathResolving/CollectionResolver.cs | 5 +- Penumbra/Mods/Editor/IMod.cs | 4 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 5 +- Penumbra/Mods/Mod.cs | 8 +- Penumbra/Mods/ModCreator.cs | 2 +- Penumbra/Mods/Subclasses/IModGroup.cs | 7 +- Penumbra/Mods/Subclasses/ModPriority.cs | 61 ++++++++++ Penumbra/Mods/Subclasses/ModSettings.cs | 115 ++++++------------ Penumbra/Mods/Subclasses/MultiModGroup.cs | 22 ++-- Penumbra/Mods/Subclasses/Setting.cs | 62 ++++++++++ Penumbra/Mods/Subclasses/SettingList.cs | 57 +++++++++ Penumbra/Mods/Subclasses/SingleModGroup.cs | 32 ++--- Penumbra/Mods/TemporaryMod.cs | 7 +- Penumbra/Services/ConfigMigrationService.cs | 17 ++- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 18 +-- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 57 ++++----- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 10 +- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 55 +++++---- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 +- 29 files changed, 422 insertions(+), 298 deletions(-) create mode 100644 Penumbra/Mods/Subclasses/ModPriority.cs create mode 100644 Penumbra/Mods/Subclasses/Setting.cs create mode 100644 Penumbra/Mods/Subclasses/SettingList.cs diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs index da1eafd0..dc1e8472 100644 --- a/Penumbra/Api/PenumbraApi.cs +++ b/Penumbra/Api/PenumbraApi.cs @@ -27,6 +27,7 @@ using Penumbra.UI; using TextureType = Penumbra.Api.Enums.TextureType; using Penumbra.Interop.ResourceTree; using Penumbra.Mods.Editor; +using Penumbra.Mods.Subclasses; namespace Penumbra.Api; @@ -39,13 +40,13 @@ public class PenumbraApi : IDisposable, IPenumbraApi { add => _communicator.PreSettingsTabBarDraw.Subscribe(value!, Communication.PreSettingsTabBarDraw.Priority.Default); remove => _communicator.PreSettingsTabBarDraw.Unsubscribe(value!); - } + } public event Action? PreSettingsPanelDraw { add => _communicator.PreSettingsPanelDraw.Subscribe(value!, Communication.PreSettingsPanelDraw.Priority.Default); remove => _communicator.PreSettingsPanelDraw.Unsubscribe(value!); - } + } public event Action? PostEnabledDraw { @@ -649,7 +650,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi var shareSettings = settings.ConvertToShareable(mod); return (PenumbraApiEc.Success, - (shareSettings.Enabled, shareSettings.Priority, shareSettings.Settings, collection.Settings[mod.Index] != null)); + (shareSettings.Enabled, shareSettings.Priority.Value, shareSettings.Settings, collection.Settings[mod.Index] != null)); } public PenumbraApiEc ReloadMod(string modDirectory, string modName) @@ -791,7 +792,9 @@ public class PenumbraApi : IDisposable, IPenumbraApi if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) return PenumbraApiEc.ModMissing; - return _collectionEditor.SetModPriority(collection, mod, priority) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged; + return _collectionEditor.SetModPriority(collection, mod, new ModPriority(priority)) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; } public PenumbraApiEc TrySetModSetting(string collectionName, string modDirectory, string modName, string optionGroupName, @@ -820,7 +823,12 @@ public class PenumbraApi : IDisposable, IPenumbraApi Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, "OptionName", optionName)); - var setting = mod.Groups[groupIdx].Type == GroupType.Multi ? 1u << optionIdx : (uint)optionIdx; + var setting = mod.Groups[groupIdx].Type switch + { + GroupType.Multi => Setting.Multi(optionIdx), + GroupType.Single => Setting.Single(optionIdx), + _ => Setting.Zero, + }; return Return( _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, @@ -850,7 +858,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi var group = mod.Groups[groupIdx]; - uint setting = 0; + var setting = Setting.Zero; if (group.Type == GroupType.Single) { var optionIdx = optionNames.Count == 0 ? -1 : group.IndexOf(o => o.Name == optionNames[^1]); @@ -859,7 +867,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, "#optionNames", optionNames.Count.ToString())); - setting = (uint)optionIdx; + setting = Setting.Single(optionIdx); } else { @@ -871,7 +879,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, "#optionNames", optionNames.Count.ToString())); - setting |= 1u << optionIdx; + setting |= Setting.Multi(optionIdx); } } @@ -993,7 +1001,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi if (!ConvertManips(manipString, out var m)) return PenumbraApiEc.InvalidManipulation; - return _tempMods.Register(tag, null, p, m, priority) switch + return _tempMods.Register(tag, null, p, m, new ModPriority(priority)) switch { RedirectResult.Success => PenumbraApiEc.Success, _ => PenumbraApiEc.UnknownError, @@ -1014,7 +1022,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi if (!ConvertManips(manipString, out var m)) return PenumbraApiEc.InvalidManipulation; - return _tempMods.Register(tag, collection, p, m, priority) switch + return _tempMods.Register(tag, collection, p, m, new ModPriority(priority)) switch { RedirectResult.Success => PenumbraApiEc.Success, _ => PenumbraApiEc.UnknownError, @@ -1024,7 +1032,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public PenumbraApiEc RemoveTemporaryModAll(string tag, int priority) { CheckInitialized(); - return _tempMods.Unregister(tag, null, priority) switch + return _tempMods.Unregister(tag, null, new ModPriority(priority)) switch { RedirectResult.Success => PenumbraApiEc.Success, RedirectResult.NotRegistered => PenumbraApiEc.NothingChanged, @@ -1039,7 +1047,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi && !_collectionManager.Storage.ByName(collectionName, out collection)) return PenumbraApiEc.CollectionMissing; - return _tempMods.Unregister(tag, collection, priority) switch + return _tempMods.Unregister(tag, collection, new ModPriority(priority)) switch { RedirectResult.Success => PenumbraApiEc.Success, RedirectResult.NotRegistered => PenumbraApiEc.NothingChanged, @@ -1089,7 +1097,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects) { - var characters = gameObjects.Select(index => _objects.GetDalamudObject((int) index)).OfType(); + var characters = gameObjects.Select(index => _objects.GetDalamudObject((int)index)).OfType(); var resourceTrees = _resourceTreeFactory.FromCharacters(characters, 0); var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); @@ -1153,7 +1161,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi var collection = _tempCollections.Collections.TryGetCollection(identifier, out var c) ? c : _collectionManager.Active.Individual(identifier); - var set = collection.MetaCache?.Manipulations.ToArray() ?? Array.Empty(); + var set = collection.MetaCache?.Manipulations.ToArray() ?? []; return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); } @@ -1161,7 +1169,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi { CheckInitialized(); AssociatedCollection(gameObjectIdx, out var collection); - var set = collection.MetaCache?.Manipulations.ToArray() ?? Array.Empty(); + var set = collection.MetaCache?.Manipulations.ToArray() ?? []; return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); } @@ -1190,7 +1198,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private unsafe ActorIdentifier AssociatedIdentifier(int gameObjectIdx) + private ActorIdentifier AssociatedIdentifier(int gameObjectIdx) { if (gameObjectIdx < 0 || gameObjectIdx >= _objects.TotalCount) return ActorIdentifier.Invalid; @@ -1217,10 +1225,9 @@ public class PenumbraApi : IDisposable, IPenumbraApi CheckInitialized(); try { - if (Path.IsPathRooted(resolvedPath)) - return _lumina?.GetFileFromDisk(resolvedPath); - - return _gameData.GetFile(resolvedPath); + return Path.IsPathRooted(resolvedPath) + ? _lumina?.GetFileFromDisk(resolvedPath) + : _gameData.GetFile(resolvedPath); } catch (Exception e) { @@ -1295,7 +1302,7 @@ public class PenumbraApi : IDisposable, IPenumbraApi return _actors.CreatePlayer(b, worldId); } - private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, int _1, int _2, bool inherited) + private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting _1, int _2, bool inherited) => ModSettingChanged?.Invoke(type, collection.Name, mod?.ModPath.Name ?? string.Empty, inherited); private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index c7840b75..7d682338 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -6,6 +6,7 @@ using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Collections.Manager; using Penumbra.Communication; +using Penumbra.Mods.Subclasses; namespace Penumbra.Api; @@ -21,8 +22,8 @@ public class TempModManager : IDisposable { private readonly CommunicatorService _communicator; - private readonly Dictionary> _mods = new(); - private readonly List _modsForAllCollections = new(); + private readonly Dictionary> _mods = []; + private readonly List _modsForAllCollections = []; public TempModManager(CommunicatorService communicator) { @@ -42,7 +43,7 @@ public class TempModManager : IDisposable => _modsForAllCollections; public RedirectResult Register(string tag, ModCollection? collection, Dictionary dict, - HashSet manips, int priority) + HashSet manips, ModPriority priority) { var mod = GetOrCreateMod(tag, collection, priority, out var created); Penumbra.Log.Verbose($"{(created ? "Created" : "Changed")} temporary Mod {mod.Name}."); @@ -51,10 +52,10 @@ public class TempModManager : IDisposable return RedirectResult.Success; } - public RedirectResult Unregister(string tag, ModCollection? collection, int? priority) + public RedirectResult Unregister(string tag, ModCollection? collection, ModPriority? priority) { Penumbra.Log.Verbose($"Removing temporary mod with tag {tag}..."); - var list = collection == null ? _modsForAllCollections : _mods.TryGetValue(collection, out var l) ? l : null; + var list = collection == null ? _modsForAllCollections : _mods.GetValueOrDefault(collection); if (list == null) return RedirectResult.NotRegistered; @@ -85,13 +86,13 @@ public class TempModManager : IDisposable { Penumbra.Log.Verbose($"Removing temporary Mod {mod.Name} from {collection.AnonymizedName}."); collection.Remove(mod); - _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, 0, 0, false); + _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, Setting.False, 0, false); } else { Penumbra.Log.Verbose($"Adding {(created ? "new " : string.Empty)}temporary Mod {mod.Name} to {collection.AnonymizedName}."); collection.Apply(mod, created); - _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, 1, 0, false); + _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, Setting.True, 0, false); } } else @@ -116,7 +117,7 @@ public class TempModManager : IDisposable // Find or create a mod with the given tag as name and the given priority, for the given collection (or all collections). // Returns the found or created mod and whether it was newly created. - private TemporaryMod GetOrCreateMod(string tag, ModCollection? collection, int priority, out bool created) + private TemporaryMod GetOrCreateMod(string tag, ModCollection? collection, ModPriority priority, out bool created) { List list; if (collection == null) @@ -129,14 +130,14 @@ public class TempModManager : IDisposable } else { - list = new List(); + list = []; _mods.Add(collection, list); } var mod = list.Find(m => m.Priority == priority && m.Name == tag); if (mod == null) { - mod = new TemporaryMod() + mod = new TemporaryMod { Name = tag, Priority = priority, diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 6b2b688b..72f0fb59 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -237,7 +237,7 @@ public sealed class CollectionCache : IDisposable if (settings is not { Enabled: true }) return; - foreach (var (group, groupIndex) in mod.Groups.WithIndex().OrderByDescending(g => g.Item1.Priority)) + foreach (var (group, groupIndex) in mod.Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) { if (group.Count == 0) continue; @@ -246,13 +246,13 @@ public sealed class CollectionCache : IDisposable switch (group.Type) { case GroupType.Single: - AddSubMod(group[(int)config], mod); + AddSubMod(group[config.AsIndex], mod); break; case GroupType.Multi: { foreach (var (option, _) in group.WithIndex() - .Where(p => ((1 << p.Item2) & config) != 0) - .OrderByDescending(p => group.OptionPriority(p.Item2))) + .Where(p => config.HasFlag(p.Index)) + .OrderByDescending(p => group.OptionPriority(p.Index))) AddSubMod(option, mod); break; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 5a6b5593..f6c6e14a 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -8,6 +8,7 @@ using Penumbra.Interop.ResourceLoading; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.String.Classes; @@ -288,7 +289,7 @@ public class CollectionCacheManager : IDisposable MetaFileManager.CharacterUtility.LoadingFinished -= IncrementCounters; } - private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, int oldValue, int groupIdx, bool _) + private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx, bool _) { if (!collection.HasCache) return; @@ -300,9 +301,9 @@ public class CollectionCacheManager : IDisposable cache.ReloadMod(mod!, true); break; case ModSettingChange.EnableState: - if (oldValue == 0) + if (oldValue == Setting.False) cache.AddMod(mod!, true); - else if (oldValue == 1) + else if (oldValue == Setting.True) cache.RemoveMod(mod!, true); else if (collection[mod!.Index].Settings?.Enabled == true) cache.ReloadMod(mod!, true); diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 73950942..4af19e6b 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -7,26 +7,15 @@ using Penumbra.Services; namespace Penumbra.Collections.Manager; -public class CollectionEditor +public class CollectionEditor(SaveService saveService, CommunicatorService communicator, ModStorage modStorage) { - private readonly CommunicatorService _communicator; - private readonly SaveService _saveService; - private readonly ModStorage _modStorage; - - public CollectionEditor(SaveService saveService, CommunicatorService communicator, ModStorage modStorage) - { - _saveService = saveService; - _communicator = communicator; - _modStorage = modStorage; - } - /// Enable or disable the mod inheritance of mod idx. public bool SetModInheritance(ModCollection collection, Mod mod, bool inherit) { if (!FixInheritance(collection, mod, inherit)) return false; - InvokeChange(collection, ModSettingChange.Inheritance, mod, inherit ? 0 : 1, 0); + InvokeChange(collection, ModSettingChange.Inheritance, mod, inherit ? Setting.False : Setting.True, 0); return true; } @@ -42,7 +31,8 @@ public class CollectionEditor var inheritance = FixInheritance(collection, mod, false); ((List)collection.Settings)[mod.Index]!.Enabled = newValue; - InvokeChange(collection, ModSettingChange.EnableState, mod, inheritance ? -1 : newValue ? 0 : 1, 0); + InvokeChange(collection, ModSettingChange.EnableState, mod, inheritance ? Setting.Indefinite : newValue ? Setting.False : Setting.True, + 0); return true; } @@ -52,7 +42,7 @@ public class CollectionEditor if (!mods.Aggregate(false, (current, mod) => current | FixInheritance(collection, mod, inherit))) return; - InvokeChange(collection, ModSettingChange.MultiInheritance, null, -1, 0); + InvokeChange(collection, ModSettingChange.MultiInheritance, null, Setting.Indefinite, 0); } /// @@ -76,22 +66,22 @@ public class CollectionEditor if (!changes) return; - InvokeChange(collection, ModSettingChange.MultiEnableState, null, -1, 0); + InvokeChange(collection, ModSettingChange.MultiEnableState, null, Setting.Indefinite, 0); } /// /// Set the priority of mod idx to newValue if it differs from the current priority. /// If the mod is currently inherited, stop the inheritance. /// - public bool SetModPriority(ModCollection collection, Mod mod, int newValue) + public bool SetModPriority(ModCollection collection, Mod mod, ModPriority newValue) { - var oldValue = collection.Settings[mod.Index]?.Priority ?? collection[mod.Index].Settings?.Priority ?? 0; + var oldValue = collection.Settings[mod.Index]?.Priority ?? collection[mod.Index].Settings?.Priority ?? ModPriority.Default; if (newValue == oldValue) return false; var inheritance = FixInheritance(collection, mod, false); ((List)collection.Settings)[mod.Index]!.Priority = newValue; - InvokeChange(collection, ModSettingChange.Priority, mod, inheritance ? -1 : oldValue, 0); + InvokeChange(collection, ModSettingChange.Priority, mod, inheritance ? Setting.Indefinite : oldValue.AsSetting, 0); return true; } @@ -99,7 +89,7 @@ public class CollectionEditor /// Set a given setting group settingName of mod idx to newValue if it differs from the current value and fix it if necessary. /// /// If the mod is currently inherited, stop the inheritance. /// - public bool SetModSetting(ModCollection collection, Mod mod, int groupIdx, uint newValue) + public bool SetModSetting(ModCollection collection, Mod mod, int groupIdx, Setting newValue) { var settings = collection.Settings[mod.Index] != null ? collection.Settings[mod.Index]!.Settings @@ -110,7 +100,7 @@ public class CollectionEditor var inheritance = FixInheritance(collection, mod, false); ((List)collection.Settings)[mod.Index]!.SetValue(mod, groupIdx, newValue); - InvokeChange(collection, ModSettingChange.Setting, mod, inheritance ? -1 : (int)oldValue, groupIdx); + InvokeChange(collection, ModSettingChange.Setting, mod, inheritance ? Setting.Indefinite : oldValue, groupIdx); return true; } @@ -158,35 +148,17 @@ public class CollectionEditor if (savedSettings != null) { ((Dictionary)collection.UnusedSettings)[targetName] = savedSettings.Value; - _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + saveService.QueueSave(new ModCollectionSave(modStorage, collection)); } else if (((Dictionary)collection.UnusedSettings).Remove(targetName)) { - _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + saveService.QueueSave(new ModCollectionSave(modStorage, collection)); } } return true; } - /// - /// Change one of the available mod settings for mod idx discerned by type. - /// If type == Setting, settingName should be a valid setting for that mod, otherwise it will be ignored. - /// The setting will also be automatically fixed if it is invalid for that setting group. - /// For boolean parameters, newValue == 0 will be treated as false and != 0 as true. - /// - public bool ChangeModSetting(ModCollection collection, ModSettingChange type, Mod mod, int newValue, int groupIdx) - { - return type switch - { - ModSettingChange.Inheritance => SetModInheritance(collection, mod, newValue != 0), - ModSettingChange.EnableState => SetModState(collection, mod, newValue != 0), - ModSettingChange.Priority => SetModPriority(collection, mod, newValue), - ModSettingChange.Setting => SetModSetting(collection, mod, groupIdx, (uint)newValue), - _ => throw new ArgumentOutOfRangeException(nameof(type), type, null), - }; - } - /// /// Set inheritance of a mod without saving, /// to be used as an intermediary. @@ -204,16 +176,16 @@ public class CollectionEditor /// Queue saves and trigger changes for any non-inherited change in a collection, then trigger changes for all inheritors. [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void InvokeChange(ModCollection changedCollection, ModSettingChange type, Mod? mod, int oldValue, int groupIdx) + private void InvokeChange(ModCollection changedCollection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx) { - _saveService.QueueSave(new ModCollectionSave(_modStorage, changedCollection)); - _communicator.ModSettingChanged.Invoke(changedCollection, type, mod, oldValue, groupIdx, false); + saveService.QueueSave(new ModCollectionSave(modStorage, changedCollection)); + communicator.ModSettingChanged.Invoke(changedCollection, type, mod, oldValue, groupIdx, false); RecurseInheritors(changedCollection, type, mod, oldValue, groupIdx); } /// Trigger changes in all inherited collections. [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void RecurseInheritors(ModCollection directParent, ModSettingChange type, Mod? mod, int oldValue, int groupIdx) + private void RecurseInheritors(ModCollection directParent, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx) { foreach (var directInheritor in directParent.DirectParentOf) { @@ -221,11 +193,11 @@ public class CollectionEditor { case ModSettingChange.MultiInheritance: case ModSettingChange.MultiEnableState: - _communicator.ModSettingChanged.Invoke(directInheritor, type, null, oldValue, groupIdx, true); + communicator.ModSettingChanged.Invoke(directInheritor, type, null, oldValue, groupIdx, true); break; default: if (directInheritor.Settings[mod!.Index] == null) - _communicator.ModSettingChanged.Invoke(directInheritor, type, mod, oldValue, groupIdx, true); + communicator.ModSettingChanged.Invoke(directInheritor, type, mod, oldValue, groupIdx, true); break; } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 0ee55376..d0b61e57 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -268,7 +268,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable case ModPathChangeType.Reloaded: foreach (var collection in this) { - if (collection.Settings[mod.Index]?.FixAllSettings(mod) ?? false) + if (collection.Settings[mod.Index]?.Settings.FixAll(mod) ?? false) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); } diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index b2b8df0d..053f0a2b 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -40,9 +40,9 @@ internal static class ModCollectionMigration /// We treat every completely defaulted setting as inheritance-ready. private static bool SettingIsDefaultV0(ModSettings.SavedSettings setting) - => setting is { Enabled: false, Priority: 0 } && setting.Settings.Values.All(s => s == 0); + => setting is { Enabled: true, Priority.IsDefault: true } && setting.Settings.Values.All(s => s == Setting.Zero); /// private static bool SettingIsDefaultV0(ModSettings? setting) - => setting is { Enabled: false, Priority: 0 } && setting.Settings.All(s => s == 0); + => setting is { Enabled: true, Priority.IsDefault: true } && setting.Settings.All(s => s == Setting.Zero); } diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index 5e0bc0c0..412b3003 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -3,6 +3,7 @@ using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Mods; +using Penumbra.Mods.Subclasses; namespace Penumbra.Communication; @@ -12,13 +13,13 @@ namespace Penumbra.Communication; /// Parameter is the collection in which the setting was changed. /// Parameter is the type of change. /// Parameter is the mod the setting was changed for, unless it was a multi-change. -/// Parameter is the old value of the setting before the change as int. +/// Parameter is the old value of the setting before the change as Setting. /// Parameter is the index of the changed group if the change type is Setting. /// Parameter is whether the change was inherited from another collection. /// /// public sealed class ModSettingChanged() - : EventWrapper(nameof(ModSettingChanged)) + : EventWrapper(nameof(ModSettingChanged)) { public enum Priority { diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 7c4b94d8..7a247a53 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -174,7 +174,7 @@ public partial class TexToolsImporter ?? new DirectoryInfo(Path.Combine(_currentModDirectory.FullName, numGroups == 1 ? $"Group {groupPriority + 1}" : $"Group {groupPriority + 1}, Part {groupId + 1}")); - uint? defaultSettings = group.SelectionType == GroupType.Multi ? 0u : null; + Setting? defaultSettings = group.SelectionType == GroupType.Multi ? Setting.Zero : null; for (var i = 0; i + optionIdx < allOptions.Count && i < maxOptions; ++i) { var option = allOptions[i + optionIdx]; @@ -186,8 +186,8 @@ public partial class TexToolsImporter options.Add(_modManager.Creator.CreateSubMod(_currentModDirectory, optionFolder, option)); if (option.IsChecked) defaultSettings = group.SelectionType == GroupType.Multi - ? defaultSettings!.Value | (1u << i) - : (uint)i; + ? defaultSettings!.Value | Setting.Multi(i) + : Setting.Single(i); ++_currentOptionIdx; } @@ -205,12 +205,12 @@ public partial class TexToolsImporter _currentOptionName = option.Name; options.Insert(idx, ModCreator.CreateEmptySubMod(option.Name)); if (option.IsChecked) - defaultSettings = (uint) idx; + defaultSettings = Setting.Single(idx); } } _modManager.Creator.CreateOptionGroup(_currentModDirectory, group.SelectionType, name, groupPriority, groupPriority, - defaultSettings ?? 0, group.Description, options); + defaultSettings ?? Setting.Zero, group.Description, options); ++groupPriority; } } diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index fa122e39..aea58304 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -18,6 +18,7 @@ public sealed unsafe class CollectionResolver( PerformanceTracker performance, IdentifiedCollectionCache cache, IClientState clientState, + ObjectManager objects, IGameGui gameGui, ActorManager actors, CutsceneService cutscenes, @@ -35,8 +36,8 @@ public sealed unsafe class CollectionResolver( public ModCollection PlayerCollection() { using var performance1 = performance.Measure(PerformanceType.IdentifyCollection); - var gameObject = (GameObject*)(clientState.LocalPlayer?.Address ?? nint.Zero); - if (gameObject == null) + var gameObject = objects[0]; + if (!gameObject.Valid) return collectionManager.Active.ByType(CollectionType.Yourself) ?? collectionManager.Active.Default; diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index 78250341..d3bc19b0 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -7,8 +7,8 @@ public interface IMod { LowerString Name { get; } - public int Index { get; } - public int Priority { get; } + public int Index { get; } + public ModPriority Priority { get; } public ISubMod Default { get; } public IReadOnlyList Groups { get; } diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 60508d33..ea6a62df 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -1,3 +1,4 @@ +using System.Security.AccessControl; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; @@ -33,6 +34,8 @@ public enum ModOptionChangeType public class ModOptionEditor(CommunicatorService communicator, SaveService saveService, Configuration config) { + + /// Change the type of a group given by mod and index to type, if possible. public void ChangeModGroupType(Mod mod, int groupIdx, GroupType type) { @@ -46,7 +49,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Change the settings stored as default options in a mod. - public void ChangeModGroupDefaultOption(Mod mod, int groupIdx, uint defaultOption) + public void ChangeModGroupDefaultOption(Mod mod, int groupIdx, Setting defaultOption) { var group = mod.Groups[groupIdx]; if (group.DefaultSettings == defaultOption) diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index c5e671af..b7d1186d 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -12,7 +12,7 @@ public sealed class Mod : IMod { Name = "Forced Files", Index = -1, - Priority = int.MaxValue, + Priority = ModPriority.MaxValue, }; // Main Data @@ -26,9 +26,9 @@ public sealed class Mod : IMod public bool IsTemporary => Index < 0; - /// Unused if Index < 0 but used for special temporary mods. - public int Priority - => 0; + /// Unused if Index is less than 0 but used for special temporary mods. + public ModPriority Priority + => ModPriority.Default; internal Mod(DirectoryInfo modPath) { diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 042c98b4..c324af48 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -235,7 +235,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, /// Create a file for an option group from given data. public void CreateOptionGroup(DirectoryInfo baseFolder, GroupType type, string name, - int priority, int index, uint defaultSettings, string desc, IEnumerable subMods) + int priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) { switch (type) { diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index ea5f176c..2f6b2403 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -12,7 +12,7 @@ public interface IModGroup : IEnumerable public string Description { get; } public GroupType Type { get; } public int Priority { get; } - public uint DefaultSettings { get; set; } + public Setting DefaultSettings { get; set; } public int OptionPriority(Index optionIdx); @@ -31,6 +31,9 @@ public interface IModGroup : IEnumerable public IModGroup Convert(GroupType type); public bool MoveOption(int optionIdxFrom, int optionIdxTo); public void UpdatePositions(int from = 0); + + /// Ensure that a value is valid for a group. + public Setting FixSetting(Setting setting); } public readonly struct ModSaveGroup : ISavable @@ -87,7 +90,7 @@ public readonly struct ModSaveGroup : ISavable j.WritePropertyName(nameof(Type)); j.WriteValue(_group.Type.ToString()); j.WritePropertyName(nameof(_group.DefaultSettings)); - j.WriteValue(_group.DefaultSettings); + j.WriteValue(_group.DefaultSettings.Value); j.WritePropertyName("Options"); j.WriteStartArray(); for (var idx = 0; idx < _group.Count; ++idx) diff --git a/Penumbra/Mods/Subclasses/ModPriority.cs b/Penumbra/Mods/Subclasses/ModPriority.cs new file mode 100644 index 00000000..3302c627 --- /dev/null +++ b/Penumbra/Mods/Subclasses/ModPriority.cs @@ -0,0 +1,61 @@ +using Newtonsoft.Json; + +namespace Penumbra.Mods.Subclasses; + +[JsonConverter(typeof(Converter))] +public readonly record struct ModPriority(int Value) : + IComparisonOperators, + IAdditionOperators, + IAdditionOperators, + ISubtractionOperators, + ISubtractionOperators +{ + public static readonly ModPriority Default = new(0); + public static readonly ModPriority MaxValue = new(int.MaxValue); + + public bool IsDefault + => Value == Default.Value; + + public Setting AsSetting + => new((uint)Value); + + public ModPriority Max(ModPriority other) + => this < other ? other : this; + + public override string ToString() + => Value.ToString(); + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, ModPriority value, JsonSerializer serializer) + => serializer.Serialize(writer, value.Value); + + public override ModPriority ReadJson(JsonReader reader, Type objectType, ModPriority existingValue, bool hasExistingValue, + JsonSerializer serializer) + => new(serializer.Deserialize(reader)); + } + + public static bool operator >(ModPriority left, ModPriority right) + => left.Value > right.Value; + + public static bool operator >=(ModPriority left, ModPriority right) + => left.Value >= right.Value; + + public static bool operator <(ModPriority left, ModPriority right) + => left.Value < right.Value; + + public static bool operator <=(ModPriority left, ModPriority right) + => left.Value <= right.Value; + + public static ModPriority operator +(ModPriority left, ModPriority right) + => new(left.Value + right.Value); + + public static ModPriority operator +(ModPriority left, int right) + => new(left.Value + right); + + public static ModPriority operator -(ModPriority left, ModPriority right) + => new(left.Value - right.Value); + + public static ModPriority operator -(ModPriority left, int right) + => new(left.Value - right); +} diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index ed8ad84e..b79b3242 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -11,8 +11,8 @@ namespace Penumbra.Mods.Subclasses; public class ModSettings { public static readonly ModSettings Empty = new(); - public List Settings { get; private init; } = []; - public int Priority { get; set; } + public SettingList Settings { get; private init; } = []; + public ModPriority Priority { get; set; } public bool Enabled { get; set; } // Create an independent copy of the current settings. @@ -21,7 +21,7 @@ public class ModSettings { Enabled = Enabled, Priority = Priority, - Settings = [.. Settings], + Settings = Settings.Clone(), }; // Create default settings for a given mod. @@ -29,8 +29,8 @@ public class ModSettings => new() { Enabled = false, - Priority = 0, - Settings = mod.Groups.Select(g => g.DefaultSettings).ToList(), + Priority = ModPriority.Default, + Settings = SettingList.Default(mod), }; // Return everything required to resolve things for a single mod with given settings (which can be null, in which case the default is used. @@ -39,7 +39,7 @@ public class ModSettings if (settings == null) settings = DefaultSettings(mod); else - settings.AddMissingSettings(mod); + settings.Settings.FixSize(mod); var dict = new Dictionary(); var set = new HashSet(); @@ -49,13 +49,13 @@ public class ModSettings if (group.Type is GroupType.Single) { if (group.Count > 0) - AddOption(group[(int)settings.Settings[index]]); + AddOption(group[settings.Settings[index].AsIndex]); } else { foreach (var (option, optionIdx) in group.WithIndex().OrderByDescending(o => group.OptionPriority(o.Index))) { - if (((settings.Settings[index] >> optionIdx) & 1) == 1) + if (settings.Settings[index].HasFlag(optionIdx)) AddOption(option); } } @@ -97,8 +97,8 @@ public class ModSettings var config = Settings[groupIdx]; Settings[groupIdx] = group.Type switch { - GroupType.Single => (uint)Math.Max(Math.Min(group.Count - 1, BitOperations.TrailingZeroCount(config)), 0), - GroupType.Multi => 1u << (int)config, + GroupType.Single => config.TurnMulti(group.Count), + GroupType.Multi => Setting.Multi((int)config.Value), _ => config, }; return config != Settings[groupIdx]; @@ -111,9 +111,11 @@ public class ModSettings var config = Settings[groupIdx]; Settings[groupIdx] = group.Type switch { - GroupType.Single => config >= optionIdx ? config > 1 ? config - 1 : 0 : config, - GroupType.Multi => Functions.RemoveBit(config, optionIdx), - _ => config, + GroupType.Single => config.AsIndex >= optionIdx + ? config.AsIndex > 1 ? Setting.Single(config.AsIndex - 1) : Setting.Zero + : config, + GroupType.Multi => config.RemoveBit(optionIdx), + _ => config, }; return config != Settings[groupIdx]; } @@ -128,8 +130,8 @@ public class ModSettings var config = Settings[groupIdx]; Settings[groupIdx] = group.Type switch { - GroupType.Single => config == optionIdx ? (uint)movedToIdx : config, - GroupType.Multi => Functions.MoveBit(config, optionIdx, movedToIdx), + GroupType.Single => config.AsIndex == optionIdx ? Setting.Single(movedToIdx) : config, + GroupType.Multi => config.MoveBit(optionIdx, movedToIdx), _ => config, }; return config != Settings[groupIdx]; @@ -138,96 +140,52 @@ public class ModSettings } } - public bool FixAllSettings(Mod mod) + /// Set a setting. Ensures that there are enough settings and fixes the setting beforehand. + public void SetValue(Mod mod, int groupIdx, Setting newValue) { - var ret = false; - for (var i = 0; i < Settings.Count; ++i) - { - var newValue = FixSetting(mod.Groups[i], Settings[i]); - if (newValue != Settings[i]) - { - ret = true; - Settings[i] = newValue; - } - } - - return AddMissingSettings(mod) || ret; - } - - // Ensure that a value is valid for a group. - private static uint FixSetting(IModGroup group, uint value) - => group.Type switch - { - GroupType.Single => (uint)Math.Min(value, group.Count - 1), - GroupType.Multi => (uint)(value & ((1ul << group.Count) - 1)), - _ => value, - }; - - // Set a setting. Ensures that there are enough settings and fixes the setting beforehand. - public void SetValue(Mod mod, int groupIdx, uint newValue) - { - AddMissingSettings(mod); + Settings.FixSize(mod); var group = mod.Groups[groupIdx]; - Settings[groupIdx] = FixSetting(group, newValue); - } - - // Add defaulted settings up to the required count. - private bool AddMissingSettings(Mod mod) - { - var changes = false; - for (var i = Settings.Count; i < mod.Groups.Count; ++i) - { - Settings.Add(mod.Groups[i].DefaultSettings); - changes = true; - } - - return changes; + Settings[groupIdx] = group.FixSetting(newValue); } // A simple struct conversion to easily save settings by name instead of value. public struct SavedSettings { - public Dictionary Settings; - public int Priority; - public bool Enabled; + public Dictionary Settings; + public ModPriority Priority; + public bool Enabled; public SavedSettings DeepCopy() - => new() - { - Enabled = Enabled, - Priority = Priority, - Settings = Settings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), - }; + => this with { Settings = Settings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) }; public SavedSettings(ModSettings settings, Mod mod) { Priority = settings.Priority; Enabled = settings.Enabled; - Settings = new Dictionary(mod.Groups.Count); - settings.AddMissingSettings(mod); + Settings = new Dictionary(mod.Groups.Count); + settings.Settings.FixSize(mod); foreach (var (group, setting) in mod.Groups.Zip(settings.Settings)) Settings.Add(group.Name, setting); } // Convert and fix. - public bool ToSettings(Mod mod, out ModSettings settings) + public readonly bool ToSettings(Mod mod, out ModSettings settings) { - var list = new List(mod.Groups.Count); + var list = new SettingList(mod.Groups.Count); var changes = Settings.Count != mod.Groups.Count; foreach (var group in mod.Groups) { if (Settings.TryGetValue(group.Name, out var config)) { - var castConfig = (uint)Math.Clamp(config, 0, uint.MaxValue); - var actualConfig = FixSetting(group, castConfig); + var actualConfig = group.FixSetting(config); list.Add(actualConfig); if (actualConfig != config) changes = true; } else { - list.Add(0); + list.Add(group.DefaultSettings); changes = true; } } @@ -245,7 +203,7 @@ public class ModSettings // Return the settings for a given mod in a shareable format, using the names of groups and options instead of indices. // Does not repair settings but ignores settings not fitting to the given mod. - public (bool Enabled, int Priority, Dictionary> Settings) ConvertToShareable(Mod mod) + public (bool Enabled, ModPriority Priority, Dictionary> Settings) ConvertToShareable(Mod mod) { var dict = new Dictionary>(Settings.Count); foreach (var (setting, idx) in Settings.WithIndex()) @@ -254,16 +212,13 @@ public class ModSettings break; var group = mod.Groups[idx]; - if (group.Type == GroupType.Single && setting < group.Count) + if (group.Type == GroupType.Single && setting.Value < (ulong)group.Count) { - dict.Add(group.Name, new[] - { - group[(int)setting].Name, - }); + dict.Add(group.Name, [group[(int)setting.Value].Name]); } else { - var list = group.Where((_, optionIdx) => (setting & (1 << optionIdx)) != 0).Select(o => o.Name).ToList(); + var list = group.Where((_, optionIdx) => (setting.Value & (1ul << optionIdx)) != 0).Select(o => o.Name).ToList(); dict.Add(group.Name, list); } } diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 07f84722..8a8e10bd 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -14,10 +14,10 @@ public sealed class MultiModGroup : IModGroup public GroupType Type => GroupType.Multi; - public string Name { get; set; } = "Group"; - public string Description { get; set; } = "A non-exclusive group of settings."; - public int Priority { get; set; } - public uint DefaultSettings { get; set; } + public string Name { get; set; } = "Group"; + public string Description { get; set; } = "A non-exclusive group of settings."; + public int Priority { get; set; } + public Setting DefaultSettings { get; set; } public int OptionPriority(Index idx) => PrioritizedOptions[idx].Priority; @@ -44,7 +44,7 @@ public sealed class MultiModGroup : IModGroup Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, Priority = json[nameof(Priority)]?.ToObject() ?? 0, - DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? 0, + DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) return null; @@ -56,7 +56,8 @@ public sealed class MultiModGroup : IModGroup if (ret.PrioritizedOptions.Count == IModGroup.MaxMultiOptions) { Penumbra.Messager.NotificationMessage( - $"Multi Group {ret.Name} in {mod.Name} has more than {IModGroup.MaxMultiOptions} options, ignoring excessive options.", NotificationType.Warning); + $"Multi Group {ret.Name} in {mod.Name} has more than {IModGroup.MaxMultiOptions} options, ignoring excessive options.", + NotificationType.Warning); break; } @@ -66,7 +67,7 @@ public sealed class MultiModGroup : IModGroup ret.PrioritizedOptions.Add((subMod, priority)); } - ret.DefaultSettings = (uint)(ret.DefaultSettings & ((1ul << ret.Count) - 1)); + ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); return ret; } @@ -82,7 +83,7 @@ public sealed class MultiModGroup : IModGroup Name = Name, Description = Description, Priority = Priority, - DefaultSettings = (uint)Math.Max(Math.Min(Count - 1, BitOperations.TrailingZeroCount(DefaultSettings)), 0), + DefaultSettings = DefaultSettings.TurnMulti(Count), }; multi.OptionData.AddRange(PrioritizedOptions.Select(p => p.Mod)); return multi; @@ -95,7 +96,7 @@ public sealed class MultiModGroup : IModGroup if (!PrioritizedOptions.Move(optionIdxFrom, optionIdxTo)) return false; - DefaultSettings = Functions.MoveBit(DefaultSettings, optionIdxFrom, optionIdxTo); + DefaultSettings = DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); UpdatePositions(Math.Min(optionIdxFrom, optionIdxTo)); return true; } @@ -105,4 +106,7 @@ public sealed class MultiModGroup : IModGroup foreach (var ((o, _), i) in PrioritizedOptions.WithIndex().Skip(from)) o.SetPosition(o.GroupIdx, i); } + + public Setting FixSetting(Setting setting) + => new(setting.Value & ((1ul << Count) - 1)); } diff --git a/Penumbra/Mods/Subclasses/Setting.cs b/Penumbra/Mods/Subclasses/Setting.cs new file mode 100644 index 00000000..18b1e4ca --- /dev/null +++ b/Penumbra/Mods/Subclasses/Setting.cs @@ -0,0 +1,62 @@ +using Newtonsoft.Json; +using OtterGui; + +namespace Penumbra.Mods.Subclasses; + +[JsonConverter(typeof(Converter))] +public readonly record struct Setting(ulong Value) +{ + public static readonly Setting Zero = new(0); + public static readonly Setting True = new(1); + public static readonly Setting False = new(0); + public static readonly Setting Indefinite = new(ulong.MaxValue); + + public static Setting Multi(int idx) + => new(1ul << idx); + + public static Setting Single(int idx) + => new(Math.Max(0ul, (ulong)idx)); + + public static Setting operator |(Setting lhs, Setting rhs) + => new(lhs.Value | rhs.Value); + + public int AsIndex + => (int)Math.Clamp(Value, 0ul, int.MaxValue); + + public bool HasFlag(int idx) + => idx >= 0 && (Value & (1ul << idx)) != 0; + + public Setting MoveBit(int idx1, int idx2) + => new(Functions.MoveBit(Value, idx1, idx2)); + + public Setting RemoveBit(int idx) + => new(Functions.RemoveBit(Value, idx)); + + public Setting SetBit(int idx, bool value) + => new(value ? Value | (1ul << idx) : Value & ~(1ul << idx)); + + public static Setting AllBits(int count) + => new((1ul << Math.Clamp(count, 0, 63)) - 1); + + public Setting TurnMulti(int count) + => new(Math.Max((ulong)Math.Min(count - 1, BitOperations.TrailingZeroCount(Value)), 0)); + + public ModPriority AsPriority + => new((int)(Value & 0xFFFFFFFF)); + + public static Setting FromBool(bool value) + => value ? True : False; + + public bool AsBool + => Value != 0; + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, Setting value, JsonSerializer serializer) + => serializer.Serialize(writer, value.Value); + + public override Setting ReadJson(JsonReader reader, Type objectType, Setting existingValue, bool hasExistingValue, + JsonSerializer serializer) + => new(serializer.Deserialize(reader)); + } +} diff --git a/Penumbra/Mods/Subclasses/SettingList.cs b/Penumbra/Mods/Subclasses/SettingList.cs new file mode 100644 index 00000000..ea1e447f --- /dev/null +++ b/Penumbra/Mods/Subclasses/SettingList.cs @@ -0,0 +1,57 @@ +namespace Penumbra.Mods.Subclasses; + +public class SettingList : List +{ + public SettingList() + { } + + public SettingList(int capacity) + : base(capacity) + { } + + public SettingList(IEnumerable settings) + => AddRange(settings); + + public SettingList Clone() + => new(this); + + public static SettingList Default(Mod mod) + => new(mod.Groups.Select(g => g.DefaultSettings)); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public bool FixSize(Mod mod) + { + var diff = Count - mod.Groups.Count; + + switch (diff) + { + case 0: return false; + case > 0: + RemoveRange(mod.Groups.Count, diff); + return true; + default: + EnsureCapacity(mod.Groups.Count); + for (var i = Count; i < mod.Groups.Count; ++i) + Add(mod.Groups[i].DefaultSettings); + return true; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public bool FixAll(Mod mod) + { + var ret = false; + for (var i = 0; i < Count; ++i) + { + var oldValue = this[i]; + var newValue = mod.Groups[i].FixSetting(oldValue); + if (newValue == oldValue) + continue; + + ret = true; + this[i] = newValue; + } + + return FixSize(mod) | ret; + } +} diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index 2b7ebd09..be1dbde5 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -12,10 +12,10 @@ public sealed class SingleModGroup : IModGroup public GroupType Type => GroupType.Single; - public string Name { get; set; } = "Option"; - public string Description { get; set; } = "A mutually exclusive group of settings."; - public int Priority { get; set; } - public uint DefaultSettings { get; set; } + public string Name { get; set; } = "Option"; + public string Description { get; set; } = "A mutually exclusive group of settings."; + public int Priority { get; set; } + public Setting DefaultSettings { get; set; } public readonly List OptionData = []; @@ -43,7 +43,7 @@ public sealed class SingleModGroup : IModGroup Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, Priority = json[nameof(Priority)]?.ToObject() ?? 0, - DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? 0u, + DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) return null; @@ -57,9 +57,7 @@ public sealed class SingleModGroup : IModGroup ret.OptionData.Add(subMod); } - if ((int)ret.DefaultSettings >= ret.Count) - ret.DefaultSettings = 0; - + ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); return ret; } @@ -74,7 +72,7 @@ public sealed class SingleModGroup : IModGroup Name = Name, Description = Description, Priority = Priority, - DefaultSettings = 1u << (int)DefaultSettings, + DefaultSettings = Setting.Multi((int) DefaultSettings.Value), }; multi.PrioritizedOptions.AddRange(OptionData.Select((o, i) => (o, i))); return multi; @@ -87,19 +85,20 @@ public sealed class SingleModGroup : IModGroup if (!OptionData.Move(optionIdxFrom, optionIdxTo)) return false; + var currentIndex = DefaultSettings.AsIndex; // Update default settings with the move. - if (DefaultSettings == optionIdxFrom) + if (currentIndex == optionIdxFrom) { - DefaultSettings = (uint)optionIdxTo; + DefaultSettings = Setting.Single(optionIdxTo); } else if (optionIdxFrom < optionIdxTo) { - if (DefaultSettings > optionIdxFrom && DefaultSettings <= optionIdxTo) - --DefaultSettings; + if (currentIndex > optionIdxFrom && currentIndex <= optionIdxTo) + DefaultSettings = Setting.Single(currentIndex - 1); } - else if (DefaultSettings < optionIdxFrom && DefaultSettings >= optionIdxTo) + else if (currentIndex < optionIdxFrom && currentIndex >= optionIdxTo) { - ++DefaultSettings; + DefaultSettings = Setting.Single(currentIndex + 1); } UpdatePositions(Math.Min(optionIdxFrom, optionIdxTo)); @@ -111,4 +110,7 @@ public sealed class SingleModGroup : IModGroup foreach (var (o, i) in OptionData.WithIndex().Skip(from)) o.SetPosition(o.GroupIdx, i); } + + public Setting FixSetting(Setting setting) + => Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(Count - 1))); } diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index c80334aa..4de2ac13 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -13,7 +13,7 @@ public class TemporaryMod : IMod { public LowerString Name { get; init; } = LowerString.Empty; public int Index { get; init; } = -2; - public int Priority { get; init; } = int.MaxValue; + public ModPriority Priority { get; init; } = ModPriority.MaxValue; public int TotalManipulations => Default.Manipulations.Count; @@ -27,10 +27,7 @@ public class TemporaryMod : IMod => Array.Empty(); public IEnumerable AllSubMods - => new[] - { - Default, - }; + => [Default]; public TemporaryMod() => Default = new SubMod(this); diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index b84c0996..d1e952f1 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -341,15 +341,15 @@ public class ConfigMigrationService(SaveService saveService) : IService var text = File.ReadAllText(collectionJson.FullName); var data = JArray.Parse(text); - var maxPriority = 0; + var maxPriority = ModPriority.Default; var dict = new Dictionary(); foreach (var setting in data.Cast()) { - var modName = (string)setting["FolderName"]!; - var enabled = (bool)setting["Enabled"]!; - var priority = (int)setting["Priority"]!; - var settings = setting["Settings"]!.ToObject>() - ?? setting["Conf"]!.ToObject>(); + var modName = setting["FolderName"]?.ToObject()!; + var enabled = setting["Enabled"]?.ToObject() ?? false; + var priority = setting["Priority"]?.ToObject() ?? ModPriority.Default; + var settings = setting["Settings"]!.ToObject>() + ?? setting["Conf"]!.ToObject>(); dict[modName] = new ModSettings.SavedSettings() { @@ -357,7 +357,7 @@ public class ConfigMigrationService(SaveService saveService) : IService Priority = priority, Settings = settings!, }; - maxPriority = Math.Max(maxPriority, priority); + maxPriority = maxPriority.Max(priority); } InvertModListOrder = _data[nameof(InvertModListOrder)]?.ToObject() ?? InvertModListOrder; @@ -365,8 +365,7 @@ public class ConfigMigrationService(SaveService saveService) : IService dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value with { Priority = maxPriority - kvp.Value.Priority }); var emptyStorage = new ModStorage(); - var collection = ModCollection.CreateFromData(saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, - Array.Empty()); + var collection = ModCollection.CreateFromData(saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, []); saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 0205f3c6..7b5ce2dc 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -694,7 +694,7 @@ public class ItemSwapTab : IDisposable, ITab UpdateMod(_mod, _mod.Index < newCollection.Settings.Count ? newCollection[_mod.Index].Settings : null); } - private void OnSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, int oldValue, int groupIdx, bool inherited) + private void OnSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx, bool inherited) { if (collection != _collectionManager.Active.Current || mod != _mod) return; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 15b18692..cd0eb982 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -74,7 +74,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector 0) { var mod = _modManager.FirstOrDefault(m @@ -92,7 +92,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Label => "Conflicts"u8; public bool IsVisible - => _collectionManager.Active.Current.Conflicts(_selector.Selected!).Count > 0; + => collectionManager.Active.Current.Conflicts(selector.Selected!).Count > 0; - private readonly ConditionalWeakTable _expandedMods = new(); + private readonly ConditionalWeakTable _expandedMods = []; - private int GetPriority(ModConflicts conflicts) + private ModPriority GetPriority(ModConflicts conflicts) { if (conflicts.Mod2.Index < 0) return conflicts.Mod2.Priority; - return _collectionManager.Active.Current[conflicts.Mod2.Index].Settings?.Priority ?? 0; + return collectionManager.Active.Current[conflicts.Mod2.Index].Settings?.Priority ?? ModPriority.Default; } public void DrawContent() @@ -63,8 +55,8 @@ public class ModPanelConflictsTab : ITab DrawCurrentRow(priorityWidth); // Can not be null because otherwise the tab bar is never drawn. - var mod = _selector.Selected!; - foreach (var (conflict, index) in _collectionManager.Active.Current.Conflicts(mod).OrderByDescending(GetPriority) + var mod = selector.Selected!; + foreach (var (conflict, index) in collectionManager.Active.Current.Conflicts(mod).OrderByDescending(GetPriority) .ThenBy(c => c.Mod2.Name.Lower).WithIndex()) { using var id = ImRaii.PushId(index); @@ -77,18 +69,18 @@ public class ModPanelConflictsTab : ITab ImGui.TableNextColumn(); using var c = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderLine.Value()); ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(_selector.Selected!.Name); + ImGui.TextUnformatted(selector.Selected!.Name); ImGui.TableNextColumn(); - var priority = _collectionManager.Active.Current[_selector.Selected!.Index].Settings!.Priority; + var priority = collectionManager.Active.Current[selector.Selected!.Index].Settings!.Priority.Value; ImGui.SetNextItemWidth(priorityWidth); if (ImGui.InputInt("##priority", ref priority, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue)) _currentPriority = priority; if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { - if (_currentPriority != _collectionManager.Active.Current[_selector.Selected!.Index].Settings!.Priority) - _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, (Mod)_selector.Selected!, - _currentPriority.Value); + if (_currentPriority != collectionManager.Active.Current[selector.Selected!.Index].Settings!.Priority.Value) + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selector.Selected!, + new ModPriority(_currentPriority.Value)); _currentPriority = null; } @@ -104,7 +96,7 @@ public class ModPanelConflictsTab : ITab { ImGui.AlignTextToFramePadding(); if (ImGui.Selectable(conflict.Mod2.Name) && conflict.Mod2 is Mod otherMod) - _selector.SelectByValue(otherMod); + selector.SelectByValue(otherMod); var hovered = ImGui.IsItemHovered(); var rightClicked = ImGui.IsItemClicked(ImGuiMouseButton.Right); if (conflict.Mod2 is Mod otherMod2) @@ -112,7 +104,7 @@ public class ModPanelConflictsTab : ITab if (hovered) ImGui.SetTooltip("Click to jump to mod, Control + Right-Click to disable mod."); if (rightClicked && ImGui.GetIO().KeyCtrl) - _collectionManager.Editor.SetModState(_collectionManager.Active.Current, otherMod2, false); + collectionManager.Editor.SetModState(collectionManager.Active.Current, otherMod2, false); } } @@ -146,7 +138,7 @@ public class ModPanelConflictsTab : ITab ImGui.TableNextColumn(); var conflictPriority = DrawPriorityInput(conflict, priorityWidth); ImGui.SameLine(); - var selectedPriority = _collectionManager.Active.Current[_selector.Selected!.Index].Settings!.Priority; + var selectedPriority = collectionManager.Active.Current[selector.Selected!.Index].Settings!.Priority.Value; DrawPriorityButtons(conflict.Mod2 as Mod, conflictPriority, selectedPriority, buttonSize); ImGui.TableNextColumn(); DrawExpandButton(conflict.Mod2, expanded, buttonSize); @@ -171,7 +163,7 @@ public class ModPanelConflictsTab : ITab using var color = ImRaii.PushColor(ImGuiCol.Text, conflict.HasPriority ? ColorId.HandledConflictMod.Value() : ColorId.ConflictingMod.Value()); using var disabled = ImRaii.Disabled(conflict.Mod2.Index < 0); - var priority = _currentPriority ?? GetPriority(conflict); + var priority = _currentPriority ?? GetPriority(conflict).Value; ImGui.SetNextItemWidth(priorityWidth); if (ImGui.InputInt("##priority", ref priority, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue)) @@ -179,8 +171,9 @@ public class ModPanelConflictsTab : ITab if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { - if (_currentPriority != GetPriority(conflict)) - _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, (Mod)conflict.Mod2, _currentPriority.Value); + if (_currentPriority != GetPriority(conflict).Value) + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, (Mod)conflict.Mod2, + new ModPriority(_currentPriority.Value)); _currentPriority = null; } @@ -195,12 +188,14 @@ public class ModPanelConflictsTab : ITab private void DrawPriorityButtons(Mod? conflict, int conflictPriority, int selectedPriority, Vector2 buttonSize) { if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.SortNumericUpAlt.ToIconString(), buttonSize, - $"Set the priority of the currently selected mod to this mods priority plus one. ({selectedPriority} -> {conflictPriority + 1})", selectedPriority > conflictPriority, true)) - _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, _selector.Selected!, conflictPriority + 1); + $"Set the priority of the currently selected mod to this mods priority plus one. ({selectedPriority} -> {conflictPriority + 1})", + selectedPriority > conflictPriority, true)) + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selector.Selected!, + new ModPriority(conflictPriority + 1)); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.SortNumericDownAlt.ToIconString(), buttonSize, $"Set the priority of this mod to the currently selected mods priority minus one. ({conflictPriority} -> {selectedPriority - 1})", selectedPriority > conflictPriority || conflict == null, true)) - _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, conflict!, selectedPriority - 1); + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, conflict!, new ModPriority(selectedPriority - 1)); } } diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index eb79869e..1292367a 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -502,18 +502,16 @@ public class ModPanelEditTab( if (group.Type == GroupType.Single) { - if (ImGui.RadioButton("##default", group.DefaultSettings == optionIdx)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, (uint)optionIdx); + if (ImGui.RadioButton("##default", group.DefaultSettings.AsIndex == optionIdx)) + panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, Setting.Single(optionIdx)); ImGuiUtil.HoverTooltip($"Set {option.Name} as the default choice for this group."); } else { - var isDefaultOption = ((group.DefaultSettings >> optionIdx) & 1) != 0; + var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); if (ImGui.Checkbox("##default", ref isDefaultOption)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, isDefaultOption - ? group.DefaultSettings | (1u << optionIdx) - : group.DefaultSettings & ~(1u << optionIdx)); + panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); ImGuiUtil.HoverTooltip($"{(isDefaultOption ? "Disable" : "Enable")} {option.Name} per default in this group."); } diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index b14cad01..1107aa20 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -26,7 +26,7 @@ public class ModPanelSettingsTab : ITab private ModSettings _settings = null!; private ModCollection _collection = null!; private bool _empty; - private int? _currentPriority = null; + private int? _currentPriority; public ModPanelSettingsTab(CollectionManager collectionManager, ModManager modManager, ModFileSystemSelector selector, TutorialService tutorial, CommunicatorService communicator, Configuration config) @@ -136,15 +136,15 @@ public class ModPanelSettingsTab : ITab private void DrawPriorityInput() { using var group = ImRaii.Group(); - var priority = _currentPriority ?? _settings.Priority; + var priority = _currentPriority ?? _settings.Priority.Value; ImGui.SetNextItemWidth(50 * UiHelpers.Scale); if (ImGui.InputInt("##Priority", ref priority, 0, 0)) _currentPriority = priority; if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { - if (_currentPriority != _settings.Priority) - _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, _selector.Selected!, _currentPriority.Value); + if (_currentPriority != _settings.Priority.Value) + _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, _selector.Selected!, new ModPriority(_currentPriority.Value)); _currentPriority = null; } @@ -179,7 +179,7 @@ public class ModPanelSettingsTab : ITab private void DrawSingleGroupCombo(IModGroup group, int groupIdx) { using var id = ImRaii.PushId(groupIdx); - var selectedOption = _empty ? (int)group.DefaultSettings : (int)_settings.Settings[groupIdx]; + var selectedOption = _empty ? group.DefaultSettings.AsIndex : _settings.Settings[groupIdx].AsIndex; ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); using (var combo = ImRaii.Combo(string.Empty, group[selectedOption].Name)) { @@ -189,7 +189,8 @@ public class ModPanelSettingsTab : ITab id.Push(idx2); var option = group[idx2]; if (ImGui.Selectable(option.Name, idx2 == selectedOption)) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, (uint)idx2); + _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, + Setting.Single(idx2)); if (option.Description.Length > 0) ImGuiUtil.SelectableHelpMarker(option.Description); @@ -210,8 +211,8 @@ public class ModPanelSettingsTab : ITab private void DrawSingleGroupRadio(IModGroup group, int groupIdx) { using var id = ImRaii.PushId(groupIdx); - var selectedOption = _empty ? (int)group.DefaultSettings : (int)_settings.Settings[groupIdx]; - var minWidth = Widget.BeginFramedGroup(group.Name, description:group.Description); + var selectedOption = _empty ? group.DefaultSettings.AsIndex : _settings.Settings[groupIdx].AsIndex; + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); DrawCollapseHandling(group, minWidth, DrawOptions); @@ -225,7 +226,8 @@ public class ModPanelSettingsTab : ITab using var i = ImRaii.PushId(idx); var option = group[idx]; if (ImGui.RadioButton(option.Name, selectedOption == idx)) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, (uint)idx); + _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, + Setting.Single(idx)); if (option.Description.Length <= 0) continue; @@ -291,7 +293,17 @@ public class ModPanelSettingsTab : ITab { using var id = ImRaii.PushId(groupIdx); var flags = _empty ? group.DefaultSettings : _settings.Settings[groupIdx]; - var minWidth = Widget.BeginFramedGroup(group.Name, description: group.Description); + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + + DrawCollapseHandling(group, minWidth, DrawOptions); + + Widget.EndFramedGroup(); + var label = $"##multi{groupIdx}"; + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImGui.OpenPopup($"##multi{groupIdx}"); + + DrawMultiPopup(group, groupIdx, label); + return; void DrawOptions() { @@ -299,12 +311,11 @@ public class ModPanelSettingsTab : ITab { using var i = ImRaii.PushId(idx); var option = group[idx]; - var flag = 1u << idx; - var setting = (flags & flag) != 0; + var setting = flags.HasFlag(idx); if (ImGui.Checkbox(option.Name, ref setting)) { - flags = setting ? flags | flag : flags & ~flag; + flags = flags.SetBit(idx, setting); _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, flags); } @@ -315,14 +326,10 @@ public class ModPanelSettingsTab : ITab } } } + } - DrawCollapseHandling(group, minWidth, DrawOptions); - - Widget.EndFramedGroup(); - var label = $"##multi{groupIdx}"; - if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) - ImGui.OpenPopup($"##multi{groupIdx}"); - + private void DrawMultiPopup(IModGroup group, int groupIdx, string label) + { using var style = ImRaii.PushStyle(ImGuiStyleVar.PopupBorderSize, 1); using var popup = ImRaii.Popup(label); if (!popup) @@ -331,12 +338,10 @@ public class ModPanelSettingsTab : ITab ImGui.TextUnformatted(group.Name); ImGui.Separator(); if (ImGui.Selectable("Enable All")) - { - flags = group.Count == 32 ? uint.MaxValue : (1u << group.Count) - 1u; - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, flags); - } + _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, + Setting.AllBits(group.Count)); if (ImGui.Selectable("Disable All")) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, 0); + _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, Setting.Zero); } } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 06f1d126..9a956d2d 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -211,7 +211,7 @@ public class DebugTab : Window, ITab color.Pop(); foreach (var (mod, paths, manips) in collection._cache!.ModData.Data.OrderBy(t => t.Item1.Name)) { - using var id = mod is TemporaryMod t ? PushId(t.Priority) : PushId(((Mod)mod).ModPath.Name); + using var id = mod is TemporaryMod t ? PushId(t.Priority.Value) : PushId(((Mod)mod).ModPath.Name); using var node2 = TreeNode(mod.Name.Text); if (!node2) continue; From e94cdaec4627cf06e4dfcb5cb55e746779a04f94 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Apr 2024 23:19:41 +0200 Subject: [PATCH 0534/1381] Some more. --- Penumbra/Import/TexToolsImporter.ModPack.cs | 6 +++--- Penumbra/Mods/Manager/ModMigration.cs | 12 ++++++------ Penumbra/Mods/Manager/ModOptionEditor.cs | 18 ++++++++++-------- Penumbra/Mods/ModCreator.cs | 4 ++-- Penumbra/Mods/Subclasses/IModGroup.cs | 18 +++++++++++------- Penumbra/Mods/Subclasses/ISubMod.cs | 4 ++-- Penumbra/Mods/Subclasses/ModPriority.cs | 10 +++++++++- Penumbra/Mods/Subclasses/MultiModGroup.cs | 14 +++++++------- Penumbra/Mods/Subclasses/SingleModGroup.cs | 16 ++++++++-------- Penumbra/Mods/Subclasses/SubMod.cs | 4 ++-- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 19 ++++++++++--------- 11 files changed, 70 insertions(+), 55 deletions(-) diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 7a247a53..099b133c 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -153,7 +153,7 @@ public partial class TexToolsImporter // Iterate through all pages var options = new List(); - var groupPriority = 0; + var groupPriority = ModPriority.Default; var groupNames = new HashSet(); foreach (var page in modList.ModPackPages) { @@ -209,9 +209,9 @@ public partial class TexToolsImporter } } - _modManager.Creator.CreateOptionGroup(_currentModDirectory, group.SelectionType, name, groupPriority, groupPriority, + _modManager.Creator.CreateOptionGroup(_currentModDirectory, group.SelectionType, name, groupPriority, groupPriority.Value, defaultSettings ?? Setting.Zero, group.Description, options); - ++groupPriority; + groupPriority += 1; } } } diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 8b73cae5..295afd7b 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -61,10 +61,9 @@ public static partial class ModMigration if (fileVersion > 0) return false; - var swaps = json["FileSwaps"]?.ToObject>() - ?? new Dictionary(); - var groups = json["Groups"]?.ToObject>() ?? new Dictionary(); - var priority = 1; + var swaps = json["FileSwaps"]?.ToObject>() ?? []; + var groups = json["Groups"]?.ToObject>() ?? []; + var priority = new ModPriority(1); var seenMetaFiles = new HashSet(); foreach (var group in groups.Values) ConvertGroup(creator, mod, group, ref priority, seenMetaFiles); @@ -116,7 +115,8 @@ public static partial class ModMigration return true; } - private static void ConvertGroup(ModCreator creator, Mod mod, OptionGroupV0 group, ref int priority, HashSet seenMetaFiles) + private static void ConvertGroup(ModCreator creator, Mod mod, OptionGroupV0 group, ref ModPriority priority, + HashSet seenMetaFiles) { if (group.Options.Count == 0) return; @@ -125,7 +125,7 @@ public static partial class ModMigration { case GroupType.Multi: - var optionPriority = 0; + var optionPriority = ModPriority.Default; var newMultiGroup = new MultiModGroup() { Name = group.GroupName, diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index ea6a62df..0ffdc4af 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -34,8 +34,6 @@ public enum ModOptionChangeType public class ModOptionEditor(CommunicatorService communicator, SaveService saveService, Configuration config) { - - /// Change the type of a group given by mod and index to type, if possible. public void ChangeModGroupType(Mod mod, int groupIdx, GroupType type) { @@ -86,7 +84,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS if (!VerifyFileName(mod, null, newName, true)) return; - var maxPriority = mod.Groups.Count == 0 ? 0 : mod.Groups.Max(o => o.Priority) + 1; + var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; mod.Groups.Add(type == GroupType.Multi ? new MultiModGroup @@ -169,7 +167,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Change the internal priority of the given option group. - public void ChangeGroupPriority(Mod mod, int groupIdx, int newPriority) + public void ChangeGroupPriority(Mod mod, int groupIdx, ModPriority newPriority) { var group = mod.Groups[groupIdx]; if (group.Priority == newPriority) @@ -186,7 +184,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Change the internal priority of the given option. - public void ChangeOptionPriority(Mod mod, int groupIdx, int optionIdx, int newPriority) + public void ChangeOptionPriority(Mod mod, int groupIdx, int optionIdx, ModPriority newPriority) { switch (mod.Groups[groupIdx]) { @@ -240,7 +238,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS s.OptionData.Add(subMod); break; case MultiModGroup m: - m.PrioritizedOptions.Add((subMod, 0)); + m.PrioritizedOptions.Add((subMod, ModPriority.Default)); break; } @@ -263,8 +261,12 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS return ((SubMod)group[^1], true); } - /// Add an existing option to a given group with a given priority. - public void AddOption(Mod mod, int groupIdx, ISubMod option, int priority = 0) + /// Add an existing option to a given group with default priority. + public void AddOption(Mod mod, int groupIdx, ISubMod option) + => AddOption(mod, groupIdx, option, ModPriority.Default); + + /// Add an existing option to a given group with a given priority. + public void AddOption(Mod mod, int groupIdx, ISubMod option, ModPriority priority) { if (option is not SubMod o) return; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index c324af48..2bcdd3b1 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -235,7 +235,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, /// Create a file for an option group from given data. public void CreateOptionGroup(DirectoryInfo baseFolder, GroupType type, string name, - int priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) + ModPriority priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) { switch (type) { @@ -248,7 +248,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, Priority = priority, DefaultSettings = defaultSettings, }; - group.PrioritizedOptions.AddRange(subMods.OfType().Select((s, idx) => (s, idx))); + group.PrioritizedOptions.AddRange(subMods.OfType().Select((s, idx) => (s, new ModPriority(idx)))); _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 2f6b2403..e9e2a93b 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -8,13 +8,13 @@ public interface IModGroup : IEnumerable { public const int MaxMultiOptions = 32; - public string Name { get; } - public string Description { get; } - public GroupType Type { get; } - public int Priority { get; } - public Setting DefaultSettings { get; set; } + public string Name { get; } + public string Description { get; } + public GroupType Type { get; } + public ModPriority Priority { get; } + public Setting DefaultSettings { get; set; } - public int OptionPriority(Index optionIdx); + public ModPriority OptionPriority(Index optionIdx); public ISubMod this[Index idx] { get; } @@ -94,7 +94,11 @@ public readonly struct ModSaveGroup : ISavable j.WritePropertyName("Options"); j.WriteStartArray(); for (var idx = 0; idx < _group.Count; ++idx) - ISubMod.WriteSubMod(j, serializer, _group[idx], _basePath, _group.Type == GroupType.Multi ? _group.OptionPriority(idx) : null); + ISubMod.WriteSubMod(j, serializer, _group[idx], _basePath, _group.Type switch + { + GroupType.Multi => _group.OptionPriority(idx), + _ => null, + }); j.WriteEndArray(); j.WriteEndObject(); diff --git a/Penumbra/Mods/Subclasses/ISubMod.cs b/Penumbra/Mods/Subclasses/ISubMod.cs index 8c296f20..29323c1d 100644 --- a/Penumbra/Mods/Subclasses/ISubMod.cs +++ b/Penumbra/Mods/Subclasses/ISubMod.cs @@ -16,7 +16,7 @@ public interface ISubMod public bool IsDefault { get; } - public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, ISubMod mod, DirectoryInfo basePath, int? priority) + public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, ISubMod mod, DirectoryInfo basePath, ModPriority? priority) { j.WriteStartObject(); j.WritePropertyName(nameof(Name)); @@ -26,7 +26,7 @@ public interface ISubMod if (priority != null) { j.WritePropertyName(nameof(IModGroup.Priority)); - j.WriteValue(priority.Value); + j.WriteValue(priority.Value.Value); } j.WritePropertyName(nameof(mod.Files)); diff --git a/Penumbra/Mods/Subclasses/ModPriority.cs b/Penumbra/Mods/Subclasses/ModPriority.cs index 3302c627..a99c12ed 100644 --- a/Penumbra/Mods/Subclasses/ModPriority.cs +++ b/Penumbra/Mods/Subclasses/ModPriority.cs @@ -8,7 +8,9 @@ public readonly record struct ModPriority(int Value) : IAdditionOperators, IAdditionOperators, ISubtractionOperators, - ISubtractionOperators + ISubtractionOperators, + IIncrementOperators, + IComparable { public static readonly ModPriority Default = new(0); public static readonly ModPriority MaxValue = new(int.MaxValue); @@ -58,4 +60,10 @@ public readonly record struct ModPriority(int Value) : public static ModPriority operator -(ModPriority left, int right) => new(left.Value - right); + + public static ModPriority operator ++(ModPriority value) + => new(value.Value + 1); + + public int CompareTo(ModPriority other) + => Value.CompareTo(other.Value); } diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 8a8e10bd..444e8e2c 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -14,12 +14,12 @@ public sealed class MultiModGroup : IModGroup public GroupType Type => GroupType.Multi; - public string Name { get; set; } = "Group"; - public string Description { get; set; } = "A non-exclusive group of settings."; - public int Priority { get; set; } - public Setting DefaultSettings { get; set; } + public string Name { get; set; } = "Group"; + public string Description { get; set; } = "A non-exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } - public int OptionPriority(Index idx) + public ModPriority OptionPriority(Index idx) => PrioritizedOptions[idx].Priority; public ISubMod this[Index idx] @@ -29,7 +29,7 @@ public sealed class MultiModGroup : IModGroup public int Count => PrioritizedOptions.Count; - public readonly List<(SubMod Mod, int Priority)> PrioritizedOptions = new(); + public readonly List<(SubMod Mod, ModPriority Priority)> PrioritizedOptions = []; public IEnumerator GetEnumerator() => PrioritizedOptions.Select(o => o.Mod).GetEnumerator(); @@ -43,7 +43,7 @@ public sealed class MultiModGroup : IModGroup { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? 0, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index be1dbde5..0bfa04f4 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -12,14 +12,14 @@ public sealed class SingleModGroup : IModGroup public GroupType Type => GroupType.Single; - public string Name { get; set; } = "Option"; - public string Description { get; set; } = "A mutually exclusive group of settings."; - public int Priority { get; set; } - public Setting DefaultSettings { get; set; } + public string Name { get; set; } = "Option"; + public string Description { get; set; } = "A mutually exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public readonly List OptionData = []; - public int OptionPriority(Index _) + public ModPriority OptionPriority(Index _) => Priority; public ISubMod this[Index idx] @@ -42,7 +42,7 @@ public sealed class SingleModGroup : IModGroup { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? 0, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) @@ -72,9 +72,9 @@ public sealed class SingleModGroup : IModGroup Name = Name, Description = Description, Priority = Priority, - DefaultSettings = Setting.Multi((int) DefaultSettings.Value), + DefaultSettings = Setting.Multi((int)DefaultSettings.Value), }; - multi.PrioritizedOptions.AddRange(OptionData.Select((o, i) => (o, i))); + multi.PrioritizedOptions.AddRange(OptionData.Select((o, i) => (o, new ModPriority(i)))); return multi; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs index 88c4e4ce..4f35cd33 100644 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -53,7 +53,7 @@ public sealed class SubMod : ISubMod OptionIdx = optionIdx; } - public void Load(DirectoryInfo basePath, JToken json, out int priority) + public void Load(DirectoryInfo basePath, JToken json, out ModPriority priority) { FileData.Clear(); FileSwapData.Clear(); @@ -62,7 +62,7 @@ public sealed class SubMod : ISubMod // Every option has a name, but priorities are only relevant for multi group options. Name = json[nameof(ISubMod.Name)]?.ToObject() ?? string.Empty; Description = json[nameof(ISubMod.Description)]?.ToObject() ?? string.Empty; - priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? 0; + priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; var files = (JObject?)json[nameof(Files)]; if (files != null) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 1292367a..80af7b15 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -511,7 +511,8 @@ public class ModPanelEditTab( { var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); if (ImGui.Checkbox("##default", ref isDefaultOption)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); + panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, + group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); ImGuiUtil.HoverTooltip($"{(isDefaultOption ? "Disable" : "Enable")} {option.Name} per default in this group."); } @@ -669,10 +670,10 @@ public class ModPanelEditTab( public const int Description = -7; // Temporary strings - private static string? _currentEdit; - private static int? _currentGroupPriority; - private static int _currentField = None; - private static int _optionIndex = None; + private static string? _currentEdit; + private static ModPriority? _currentGroupPriority; + private static int _currentField = None; + private static int _optionIndex = None; public static void Reset() { @@ -705,13 +706,13 @@ public class ModPanelEditTab( return false; } - public static bool Priority(string label, int field, int option, int oldValue, out int value, float width) + public static bool Priority(string label, int field, int option, ModPriority oldValue, out ModPriority value, float width) { - var tmp = field == _currentField && option == _optionIndex ? _currentGroupPriority ?? oldValue : oldValue; + var tmp = (field == _currentField && option == _optionIndex ? _currentGroupPriority ?? oldValue : oldValue).Value; ImGui.SetNextItemWidth(width); if (ImGui.InputInt(label, ref tmp, 0, 0)) { - _currentGroupPriority = tmp; + _currentGroupPriority = new ModPriority(tmp); _optionIndex = option; _currentField = field; } @@ -724,7 +725,7 @@ public class ModPanelEditTab( return ret; } - value = 0; + value = ModPriority.Default; return false; } } From 21a55b95d9a3379e3df1c8cd885780412476fc1c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Apr 2024 15:19:44 +0200 Subject: [PATCH 0535/1381] Add rename mod field. --- Penumbra/Configuration.cs | 24 +++++----- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 49 +++++++++++++++++++- Penumbra/UI/ModsTab/RenameField.cs | 26 +++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 30 ++++++++++++ 4 files changed, 117 insertions(+), 12 deletions(-) create mode 100644 Penumbra/UI/ModsTab/RenameField.cs diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index f91e0534..98668e8a 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -11,6 +11,7 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.Classes; +using Penumbra.UI.ModsTab; using Penumbra.UI.ResourceWatcher; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; @@ -40,17 +41,18 @@ public class Configuration : IPluginConfiguration, ISavable public bool HideUiWhenUiHidden { get; set; } = false; public bool UseDalamudUiTextureRedirection { get; set; } = true; - public bool UseCharacterCollectionInMainWindow { get; set; } = true; - public bool UseCharacterCollectionsInCards { get; set; } = true; - public bool UseCharacterCollectionInInspect { get; set; } = true; - public bool UseCharacterCollectionInTryOn { get; set; } = true; - public bool UseOwnerNameForCharacterCollection { get; set; } = true; - public bool UseNoModsInInspect { get; set; } = false; - public bool HideChangedItemFilters { get; set; } = false; - public bool ReplaceNonAsciiOnImport { get; set; } = false; - public bool HidePrioritiesInSelector { get; set; } = false; - public bool HideRedrawBar { get; set; } = false; - public int OptionGroupCollapsibleMin { get; set; } = 5; + public bool UseCharacterCollectionInMainWindow { get; set; } = true; + public bool UseCharacterCollectionsInCards { get; set; } = true; + public bool UseCharacterCollectionInInspect { get; set; } = true; + public bool UseCharacterCollectionInTryOn { get; set; } = true; + public bool UseOwnerNameForCharacterCollection { get; set; } = true; + public bool UseNoModsInInspect { get; set; } = false; + public bool HideChangedItemFilters { get; set; } = false; + public bool ReplaceNonAsciiOnImport { get; set; } = false; + public bool HidePrioritiesInSelector { get; set; } = false; + public bool HideRedrawBar { get; set; } = false; + public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; + public int OptionGroupCollapsibleMin { get; set; } = 5; public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index cd0eb982..11a2d96f 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -66,7 +66,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector ClearQuickMove(1, _config.QuickMoveFolder2, () => {_config.QuickMoveFolder2 = string.Empty; _config.Save();}), 120); SubscribeRightClickMain(() => ClearQuickMove(2, _config.QuickMoveFolder3, () => {_config.QuickMoveFolder3 = string.Empty; _config.Save();}), 130); UnsubscribeRightClickLeaf(RenameLeaf); - SubscribeRightClickLeaf(RenameLeafMod, 1000); + SetRenameSearchPath(_config.ShowRename); AddButton(AddNewModButton, 0); AddButton(AddImportModButton, 1); AddButton(AddHelpButton, 2); @@ -92,6 +92,37 @@ public sealed class ModFileSystemSelector : FileSystemSelector DeleteSelectionButton(size, _config.DeleteModModifier, "mod", "mods", _modManager.DeleteMod); diff --git a/Penumbra/UI/ModsTab/RenameField.cs b/Penumbra/UI/ModsTab/RenameField.cs new file mode 100644 index 00000000..00232750 --- /dev/null +++ b/Penumbra/UI/ModsTab/RenameField.cs @@ -0,0 +1,26 @@ +namespace Penumbra.UI.ModsTab; + +public enum RenameField +{ + None, + RenameSearchPath, + RenameData, + BothSearchPathPrio, + BothDataPrio, +} + +public static class RenameFieldExtensions +{ + public static (string Name, string Desc) GetData(this RenameField value) + => value switch + { + RenameField.None => ("None", "Show no rename fields in the context menu for mods."), + RenameField.RenameSearchPath => ("Search Path", "Show only the search path / move field in the context menu for mods."), + RenameField.RenameData => ("Mod Name", "Show only the mod name field in the context menu for mods."), + RenameField.BothSearchPathPrio => ("Both (Focus Search Path)", + "Show both rename fields in the context menu for mods, but put the keyboard cursor on the search path field."), + RenameField.BothDataPrio => ("Both (Focus Mod Name)", + "Show both rename fields in the context menu for mods, but put the keyboard cursor on the mod name field"), + _ => (string.Empty, string.Empty), + }; +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index c524a840..439f7be4 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -533,12 +533,42 @@ public class SettingsTab : ITab "Instead of keeping the mod-selector in the Installed Mods tab a fixed width, this will let it scale with the total size of the Penumbra window."); } + private void DrawRenameSettings() + { + ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X); + using (var combo = ImRaii.Combo("##renameSettings", _config.ShowRename.GetData().Name)) + { + if (combo) + foreach (var value in Enum.GetValues()) + { + var (name, desc) = value.GetData(); + if (ImGui.Selectable(name, _config.ShowRename == value)) + { + _config.ShowRename = value; + _selector.SetRenameSearchPath(value); + _config.Save(); + } + + ImGuiUtil.HoverTooltip(desc); + } + } + + ImGui.SameLine(); + const string tt = + "Select which of the two renaming input fields are visible when opening the right-click context menu of a mod in the mod selector."; + ImGuiComponents.HelpMarker(tt); + ImGui.SameLine(); + ImGui.TextUnformatted("Rename Fields in Mod Context Menu"); + ImGuiUtil.HoverTooltip(tt); + } + /// Draw all settings pertaining to the mod selector. private void DrawModSelectorSettings() { DrawFolderSortType(); DrawAbsoluteSizeSelector(); DrawRelativeSizeSelector(); + DrawRenameSettings(); Checkbox("Open Folders by Default", "Whether to start with all folders collapsed or expanded in the mod selector.", _config.OpenFoldersByDefault, v => { From 7280c4b2f72c6b14b2a04b0387a1e6536429f7b9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Apr 2024 15:20:38 +0200 Subject: [PATCH 0536/1381] Selector improvements. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index f48c6886..5de71c22 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit f48c6886cbc163c5a292fa8b9fd919cb01c11d7b +Subproject commit 5de71c22c03581738c25aa43d7dff10365ec7db3 From c0ee80629df66b987b391afb4625b742dc7a298c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Apr 2024 16:05:55 +0200 Subject: [PATCH 0537/1381] Allow right click to paste into filter as long as it is unfocused. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 5de71c22..4673e93f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5de71c22c03581738c25aa43d7dff10365ec7db3 +Subproject commit 4673e93f5165108a7f5b91236406d527f16384a5 From 45b1c55b67bc41fbf16aa36692c5d2657c380134 Mon Sep 17 00:00:00 2001 From: ocealot Date: Thu, 11 Apr 2024 15:00:54 -0400 Subject: [PATCH 0538/1381] Add accessory vfxs --- .../Hooks/Resources/ResolvePathHooksBase.cs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 6b4abf90..537992e2 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Memory; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using OtterGui.Services; @@ -57,6 +58,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[74], type, ResolveSkp, ResolveSkpHuman); _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[77], ResolveTmb); _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[84], ResolveVfx); + _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[84], type, ResolveVfx, ResolveVfxHuman); // @formatter:on Enable(); } @@ -179,6 +181,27 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ResolvePath(data, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } + private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) + { + if (slotIndex <= 4) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + + // Enable vfxs for accessories + var data = Marshal.ReadIntPtr(drawObject + 0xA38); + if (data == IntPtr.Zero) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + + var slot = data + 12 * (nint)slotIndex; + var model = Marshal.ReadInt16(slot); + var variant = Marshal.ReadInt16(slot + 2); + var vfxId = Marshal.ReadInt16(slot + 8); + + if (model == 0 || variant == 0 || vfxId == 0) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + var path = "chara/accessory/a" + model.ToString().PadLeft(4, '0') + "/vfx/eff/va" + vfxId.ToString().PadLeft(4, '0') + ".avfx"; + + MemoryHelper.WriteString(pathBuffer, path); + Marshal.WriteIntPtr(unkOutParam, 0x00000004); + return ResolvePath(drawObject, pathBuffer); + } + private DisposableContainer GetEstChanges(nint drawObject, out ResolveData data) { data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); From eb0e7e2f5fd8ec434ff6caf0b047da8c8b5ee0eb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 11 Apr 2024 21:25:00 +0200 Subject: [PATCH 0539/1381] Update ocealots code #1. --- .../Hooks/Resources/ResolvePathHooksBase.cs | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 537992e2..f322267b 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -1,5 +1,5 @@ +using System.Text.Unicode; using Dalamud.Hooking; -using Dalamud.Memory; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using OtterGui.Services; @@ -57,7 +57,6 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveSklbPathHook = Create($"{name}.{nameof(ResolveSklb)}", hooks, vTable[72], type, ResolveSklb, ResolveSklbHuman); _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[74], type, ResolveSkp, ResolveSkpHuman); _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[77], ResolveTmb); - _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[84], ResolveVfx); _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[84], type, ResolveVfx, ResolveVfxHuman); // @formatter:on Enable(); @@ -183,22 +182,27 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) { - if (slotIndex <= 4) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + if (slotIndex <= 4) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + var changedEquipData = ((Human*)drawObject)->ChangedEquipData; // Enable vfxs for accessories - var data = Marshal.ReadIntPtr(drawObject + 0xA38); - if (data == IntPtr.Zero) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + if (changedEquipData == null) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - var slot = data + 12 * (nint)slotIndex; - var model = Marshal.ReadInt16(slot); - var variant = Marshal.ReadInt16(slot + 2); - var vfxId = Marshal.ReadInt16(slot + 8); + var slot = (ushort*)(changedEquipData + 12 * (nint)slotIndex); + var model = slot[0]; + var variant = slot[1]; + var vfxId = slot[4]; - if (model == 0 || variant == 0 || vfxId == 0) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - var path = "chara/accessory/a" + model.ToString().PadLeft(4, '0') + "/vfx/eff/va" + vfxId.ToString().PadLeft(4, '0') + ".avfx"; + if (model == 0 || variant == 0 || vfxId == 0) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - MemoryHelper.WriteString(pathBuffer, path); - Marshal.WriteIntPtr(unkOutParam, 0x00000004); + if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), $"chara/accessory/a{model:D4}/vfx/eff/va{vfxId:D4}.avfx", + out _)) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + + *(ulong*)unkOutParam = 4; return ResolvePath(drawObject, pathBuffer); } From 793ed4f0a722c78b11332b391f8beeed938c896b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 00:02:09 +0200 Subject: [PATCH 0540/1381] With explicit null-termination, maybe? --- Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index f322267b..4e24ba39 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -198,7 +198,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable if (model == 0 || variant == 0 || vfxId == 0) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), $"chara/accessory/a{model:D4}/vfx/eff/va{vfxId:D4}.avfx", + if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), $"chara/accessory/a{model:D4}/vfx/eff/va{vfxId:D4}.avfx\0", out _)) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); From ba8999914fd24408fb0635cffbb4da48b0dafc44 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 12:33:57 +0200 Subject: [PATCH 0541/1381] Rework API, use Collection ID in crash handler, use collection GUIDs in more places. --- OtterGui | 2 +- Penumbra.Api | 2 +- .../Buffers/AnimationInvocationBuffer.cs | 32 +- .../Buffers/CharacterBaseBuffer.cs | 48 +- .../Buffers/ModdedFileBuffer.cs | 60 +- Penumbra.GameData | 2 +- Penumbra/Api/Api/ApiHelpers.cs | 76 + Penumbra/Api/Api/CollectionApi.cs | 141 ++ Penumbra/Api/Api/EditingApi.cs | 40 + Penumbra/Api/Api/GameStateApi.cs | 82 + Penumbra/Api/Api/MetaApi.cs | 23 + Penumbra/Api/Api/ModSettingsApi.cs | 282 +++ Penumbra/Api/Api/ModsApi.cs | 132 ++ Penumbra/Api/Api/PenumbraApi.cs | 40 + Penumbra/Api/Api/PluginStateApi.cs | 30 + Penumbra/Api/Api/RedrawApi.cs | 27 + Penumbra/Api/Api/ResolveApi.cs | 101 + Penumbra/Api/Api/ResourceTreeApi.cs | 63 + Penumbra/Api/Api/TemporaryApi.cs | 190 ++ Penumbra/Api/Api/UiApi.cs | 101 + Penumbra/Api/DalamudSubstitutionProvider.cs | 3 +- Penumbra/Api/HttpApi.cs | 22 +- Penumbra/Api/IpcProviders.cs | 118 ++ Penumbra/Api/IpcTester.cs | 1762 ----------------- .../Api/IpcTester/CollectionsIpcTester.cs | 166 ++ Penumbra/Api/IpcTester/EditingIpcTester.cs | 70 + Penumbra/Api/IpcTester/GameStateIpcTester.cs | 137 ++ Penumbra/Api/IpcTester/IpcTester.cs | 133 ++ Penumbra/Api/IpcTester/MetaIpcTester.cs | 38 + .../Api/IpcTester/ModSettingsIpcTester.cs | 181 ++ Penumbra/Api/IpcTester/ModsIpcTester.cs | 154 ++ .../Api/IpcTester/PluginStateIpcTester.cs | 132 ++ Penumbra/Api/IpcTester/RedrawingIpcTester.cs | 72 + Penumbra/Api/IpcTester/ResolveIpcTester.cs | 114 ++ .../Api/IpcTester/ResourceTreeIpcTester.cs | 349 ++++ Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 203 ++ Penumbra/Api/IpcTester/UiIpcTester.cs | 128 ++ Penumbra/Api/PenumbraApi.cs | 1374 ------------- Penumbra/Api/PenumbraIpcProviders.cs | 435 ---- Penumbra/Collections/Cache/CollectionCache.cs | 10 +- .../Cache/CollectionCacheManager.cs | 2 +- Penumbra/Collections/Cache/ImcCache.cs | 2 +- .../Collections/Manager/ActiveCollections.cs | 160 +- .../Collections/Manager/CollectionStorage.cs | 107 +- .../Manager/IndividualCollections.Files.cs | 98 +- .../Collections/Manager/InheritanceManager.cs | 11 +- .../Manager/TempCollectionManager.cs | 53 +- Penumbra/Collections/ModCollection.cs | 35 +- Penumbra/Collections/ModCollectionSave.cs | 18 +- Penumbra/CommandHandler.cs | 2 +- Penumbra/Communication/ChangedItemClick.cs | 3 +- Penumbra/Communication/ChangedItemHover.cs | 3 +- .../Communication/CreatedCharacterBase.cs | 1 + .../Communication/CreatingCharacterBase.cs | 3 +- Penumbra/Communication/EnabledChanged.cs | 3 +- Penumbra/Communication/ModDirectoryChanged.cs | 1 + Penumbra/Communication/ModFileChanged.cs | 1 + Penumbra/Communication/ModOptionChanged.cs | 1 + Penumbra/Communication/ModPathChanged.cs | 8 +- Penumbra/Communication/ModSettingChanged.cs | 1 + Penumbra/Communication/PostEnabledDraw.cs | 3 +- .../Communication/PostSettingsPanelDraw.cs | 3 +- .../Communication/PreSettingsPanelDraw.cs | 3 +- .../Communication/PreSettingsTabBarDraw.cs | 3 +- Penumbra/GuidExtensions.cs | 254 +++ Penumbra/Interop/PathResolving/MetaState.cs | 2 +- .../Interop/PathResolving/PathResolver.cs | 10 +- .../Interop/PathResolving/SubfileHelper.cs | 2 +- .../ResourceTree/ResourceTreeApiHelper.cs | 82 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 17 +- Penumbra/Mods/Manager/ModStorage.cs | 2 +- Penumbra/Mods/Subclasses/IModGroup.cs | 18 +- Penumbra/Mods/Subclasses/ModSettings.cs | 8 +- Penumbra/Mods/Subclasses/MultiModGroup.cs | 3 + Penumbra/Mods/Subclasses/SingleModGroup.cs | 3 + Penumbra/Mods/TemporaryMod.cs | 6 +- Penumbra/Penumbra.cs | 4 +- Penumbra/Penumbra.csproj | 2 +- Penumbra/Services/ConfigMigrationService.cs | 4 +- Penumbra/Services/CrashHandlerService.cs | 6 +- Penumbra/Services/FilenameService.cs | 2 +- Penumbra/Services/StaticServiceManager.cs | 10 +- .../ModEditWindow.QuickImport.cs | 4 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 54 +- .../UI/CollectionTab/CollectionSelector.cs | 2 +- Penumbra/UI/Tabs/CollectionsTab.cs | 4 +- Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs | 6 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 18 +- 88 files changed, 4193 insertions(+), 3930 deletions(-) create mode 100644 Penumbra/Api/Api/ApiHelpers.cs create mode 100644 Penumbra/Api/Api/CollectionApi.cs create mode 100644 Penumbra/Api/Api/EditingApi.cs create mode 100644 Penumbra/Api/Api/GameStateApi.cs create mode 100644 Penumbra/Api/Api/MetaApi.cs create mode 100644 Penumbra/Api/Api/ModSettingsApi.cs create mode 100644 Penumbra/Api/Api/ModsApi.cs create mode 100644 Penumbra/Api/Api/PenumbraApi.cs create mode 100644 Penumbra/Api/Api/PluginStateApi.cs create mode 100644 Penumbra/Api/Api/RedrawApi.cs create mode 100644 Penumbra/Api/Api/ResolveApi.cs create mode 100644 Penumbra/Api/Api/ResourceTreeApi.cs create mode 100644 Penumbra/Api/Api/TemporaryApi.cs create mode 100644 Penumbra/Api/Api/UiApi.cs create mode 100644 Penumbra/Api/IpcProviders.cs delete mode 100644 Penumbra/Api/IpcTester.cs create mode 100644 Penumbra/Api/IpcTester/CollectionsIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/EditingIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/GameStateIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/IpcTester.cs create mode 100644 Penumbra/Api/IpcTester/MetaIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/ModSettingsIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/ModsIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/PluginStateIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/RedrawingIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/ResolveIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/TemporaryIpcTester.cs create mode 100644 Penumbra/Api/IpcTester/UiIpcTester.cs delete mode 100644 Penumbra/Api/PenumbraApi.cs delete mode 100644 Penumbra/Api/PenumbraIpcProviders.cs create mode 100644 Penumbra/GuidExtensions.cs diff --git a/OtterGui b/OtterGui index 4673e93f..9599c806 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 4673e93f5165108a7f5b91236406d527f16384a5 +Subproject commit 9599c806877e2972f964dfa68e5207cf3a8f2b84 diff --git a/Penumbra.Api b/Penumbra.Api index 8787efc8..e5c8f544 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 8787efc8fc897dfbb4515ebbabbcd5e6f54d1b42 +Subproject commit e5c8f5446879e2e0e541eb4d8fee15e98b1885bc diff --git a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs index c92a14fd..3446530a 100644 --- a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs @@ -24,7 +24,7 @@ public record struct VfxFuncInvokedEntry( string InvocationType, string CharacterName, string CharacterAddress, - string CollectionName) : ICrashDataEntry; + Guid CollectionId) : ICrashDataEntry; /// Only expose the write interface for the buffer. public interface IAnimationInvocationBufferWriter @@ -32,19 +32,19 @@ public interface IAnimationInvocationBufferWriter /// Write a line into the buffer with the given data. /// The address of the related character, if known. /// The name of the related character, anonymized or relying on index if unavailable, if known. - /// The name of the associated collection. Not anonymized. + /// The GUID of the associated collection. /// The type of VFX func called. - public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, AnimationInvocationType type); + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, Guid collectionId, AnimationInvocationType type); } internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimationInvocationBufferWriter, IBufferReader { private const int _version = 1; private const int _lineCount = 64; - private const int _lineCapacity = 256; + private const int _lineCapacity = 128; private const string _name = "Penumbra.AnimationInvocation"; - public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, AnimationInvocationType type) + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, Guid collectionId, AnimationInvocationType type) { var accessor = GetCurrentLineLocking(); lock (accessor) @@ -53,10 +53,10 @@ internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimation accessor.Write(8, Environment.CurrentManagedThreadId); accessor.Write(12, (int)type); accessor.Write(16, characterAddress); - var span = GetSpan(accessor, 24, 104); + var span = GetSpan(accessor, 24, 16); + collectionId.TryWriteBytes(span); + span = GetSpan(accessor, 40); WriteSpan(characterName, span); - span = GetSpan(accessor, 128); - WriteString(collectionName, span); } } @@ -68,13 +68,13 @@ internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimation var lineCount = (int)CurrentLineCount; for (var i = lineCount - 1; i >= 0; --i) { - var line = GetLine(i); - var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); - var thread = BitConverter.ToInt32(line[8..]); - var type = (AnimationInvocationType)BitConverter.ToInt32(line[12..]); - var address = BitConverter.ToUInt64(line[16..]); - var characterName = ReadString(line[24..]); - var collectionName = ReadString(line[128..]); + var line = GetLine(i); + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); + var thread = BitConverter.ToInt32(line[8..]); + var type = (AnimationInvocationType)BitConverter.ToInt32(line[12..]); + var address = BitConverter.ToUInt64(line[16..]); + var collectionId = new Guid(line[24..40]); + var characterName = ReadString(line[40..]); yield return new JsonObject() { [nameof(VfxFuncInvokedEntry.Age)] = (crashTime - timestamp).TotalSeconds, @@ -83,7 +83,7 @@ internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimation [nameof(VfxFuncInvokedEntry.InvocationType)] = ToName(type), [nameof(VfxFuncInvokedEntry.CharacterName)] = characterName, [nameof(VfxFuncInvokedEntry.CharacterAddress)] = address.ToString("X"), - [nameof(VfxFuncInvokedEntry.CollectionName)] = collectionName, + [nameof(VfxFuncInvokedEntry.CollectionId)] = collectionId, }; } } diff --git a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs index d83c6e6c..4036455d 100644 --- a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs @@ -8,8 +8,8 @@ public interface ICharacterBaseBufferWriter /// Write a line into the buffer with the given data. /// The address of the related character, if known. /// The name of the related character, anonymized or relying on index if unavailable, if known. - /// The name of the associated collection. Not anonymized. - public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName); + /// The GUID of the associated collection. + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, Guid collectionId); } /// The full crash entry for a loaded character base. @@ -19,27 +19,27 @@ public record struct CharacterLoadedEntry( int ThreadId, string CharacterName, string CharacterAddress, - string CollectionName) : ICrashDataEntry; + Guid CollectionId) : ICrashDataEntry; internal sealed class CharacterBaseBuffer : MemoryMappedBuffer, ICharacterBaseBufferWriter, IBufferReader { - private const int _version = 1; - private const int _lineCount = 10; - private const int _lineCapacity = 256; - private const string _name = "Penumbra.CharacterBase"; + private const int _version = 1; + private const int _lineCount = 10; + private const int _lineCapacity = 128; + private const string _name = "Penumbra.CharacterBase"; - public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName) + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, Guid collectionId) { var accessor = GetCurrentLineLocking(); lock (accessor) { - accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); - accessor.Write(8, Environment.CurrentManagedThreadId); + accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + accessor.Write(8, Environment.CurrentManagedThreadId); accessor.Write(12, characterAddress); - var span = GetSpan(accessor, 20, 108); + var span = GetSpan(accessor, 20, 16); + collectionId.TryWriteBytes(span); + span = GetSpan(accessor, 36); WriteSpan(characterName, span); - span = GetSpan(accessor, 128); - WriteString(collectionName, span); } } @@ -48,20 +48,20 @@ internal sealed class CharacterBaseBuffer : MemoryMappedBuffer, ICharacterBaseBu var lineCount = (int)CurrentLineCount; for (var i = lineCount - 1; i >= 0; --i) { - var line = GetLine(i); - var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); - var thread = BitConverter.ToInt32(line[8..]); - var address = BitConverter.ToUInt64(line[12..]); - var characterName = ReadString(line[20..]); - var collectionName = ReadString(line[128..]); + var line = GetLine(i); + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); + var thread = BitConverter.ToInt32(line[8..]); + var address = BitConverter.ToUInt64(line[12..]); + var collectionId = new Guid(line[20..36]); + var characterName = ReadString(line[36..]); yield return new JsonObject { - [nameof(CharacterLoadedEntry.Age)] = (crashTime - timestamp).TotalSeconds, - [nameof(CharacterLoadedEntry.Timestamp)] = timestamp, - [nameof(CharacterLoadedEntry.ThreadId)] = thread, - [nameof(CharacterLoadedEntry.CharacterName)] = characterName, + [nameof(CharacterLoadedEntry.Age)] = (crashTime - timestamp).TotalSeconds, + [nameof(CharacterLoadedEntry.Timestamp)] = timestamp, + [nameof(CharacterLoadedEntry.ThreadId)] = thread, + [nameof(CharacterLoadedEntry.CharacterName)] = characterName, [nameof(CharacterLoadedEntry.CharacterAddress)] = address.ToString("X"), - [nameof(CharacterLoadedEntry.CollectionName)] = collectionName, + [nameof(CharacterLoadedEntry.CollectionId)] = collectionId, }; } } diff --git a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs index 6c774e4b..03f63ba4 100644 --- a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs @@ -8,10 +8,10 @@ public interface IModdedFileBufferWriter /// Write a line into the buffer with the given data. /// The address of the related character, if known. /// The name of the related character, anonymized or relying on index if unavailable, if known. - /// The name of the associated collection. Not anonymized. + /// The GUID of the associated collection. /// The file name as requested by the game. /// The actual modded file name loaded. - public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, ReadOnlySpan requestedFileName, + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, Guid collectionId, ReadOnlySpan requestedFileName, ReadOnlySpan actualFileName); } @@ -22,33 +22,33 @@ public record struct ModdedFileLoadedEntry( int ThreadId, string CharacterName, string CharacterAddress, - string CollectionName, + Guid CollectionId, string RequestedFileName, string ActualFileName) : ICrashDataEntry; internal sealed class ModdedFileBuffer : MemoryMappedBuffer, IModdedFileBufferWriter, IBufferReader { - private const int _version = 1; - private const int _lineCount = 128; - private const int _lineCapacity = 1024; - private const string _name = "Penumbra.ModdedFile"; + private const int _version = 1; + private const int _lineCount = 128; + private const int _lineCapacity = 1024; + private const string _name = "Penumbra.ModdedFile"; - public void WriteLine(nint characterAddress, ReadOnlySpan characterName, string collectionName, ReadOnlySpan requestedFileName, + public void WriteLine(nint characterAddress, ReadOnlySpan characterName, Guid collectionId, ReadOnlySpan requestedFileName, ReadOnlySpan actualFileName) { var accessor = GetCurrentLineLocking(); lock (accessor) { - accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); - accessor.Write(8, Environment.CurrentManagedThreadId); + accessor.Write(0, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + accessor.Write(8, Environment.CurrentManagedThreadId); accessor.Write(12, characterAddress); - var span = GetSpan(accessor, 20, 80); + var span = GetSpan(accessor, 20, 16); + collectionId.TryWriteBytes(span); + span = GetSpan(accessor, 36, 80); WriteSpan(characterName, span); - span = GetSpan(accessor, 92, 80); - WriteString(collectionName, span); - span = GetSpan(accessor, 172, 260); + span = GetSpan(accessor, 116, 260); WriteSpan(requestedFileName, span); - span = GetSpan(accessor, 432); + span = GetSpan(accessor, 376); WriteSpan(actualFileName, span); } } @@ -61,24 +61,24 @@ internal sealed class ModdedFileBuffer : MemoryMappedBuffer, IModdedFileBufferWr var lineCount = (int)CurrentLineCount; for (var i = lineCount - 1; i >= 0; --i) { - var line = GetLine(i); - var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); - var thread = BitConverter.ToInt32(line[8..]); - var address = BitConverter.ToUInt64(line[12..]); - var characterName = ReadString(line[20..]); - var collectionName = ReadString(line[92..]); - var requestedFileName = ReadString(line[172..]); - var actualFileName = ReadString(line[432..]); + var line = GetLine(i); + var timestamp = DateTimeOffset.FromUnixTimeMilliseconds(BitConverter.ToInt64(line)); + var thread = BitConverter.ToInt32(line[8..]); + var address = BitConverter.ToUInt64(line[12..]); + var collectionId = new Guid(line[20..36]); + var characterName = ReadString(line[36..]); + var requestedFileName = ReadString(line[116..]); + var actualFileName = ReadString(line[376..]); yield return new JsonObject() { - [nameof(ModdedFileLoadedEntry.Age)] = (crashTime - timestamp).TotalSeconds, - [nameof(ModdedFileLoadedEntry.Timestamp)] = timestamp, - [nameof(ModdedFileLoadedEntry.ThreadId)] = thread, - [nameof(ModdedFileLoadedEntry.CharacterName)] = characterName, - [nameof(ModdedFileLoadedEntry.CharacterAddress)] = address.ToString("X"), - [nameof(ModdedFileLoadedEntry.CollectionName)] = collectionName, + [nameof(ModdedFileLoadedEntry.Age)] = (crashTime - timestamp).TotalSeconds, + [nameof(ModdedFileLoadedEntry.Timestamp)] = timestamp, + [nameof(ModdedFileLoadedEntry.ThreadId)] = thread, + [nameof(ModdedFileLoadedEntry.CharacterName)] = characterName, + [nameof(ModdedFileLoadedEntry.CharacterAddress)] = address.ToString("X"), + [nameof(ModdedFileLoadedEntry.CollectionId)] = collectionId, [nameof(ModdedFileLoadedEntry.RequestedFileName)] = requestedFileName, - [nameof(ModdedFileLoadedEntry.ActualFileName)] = actualFileName, + [nameof(ModdedFileLoadedEntry.ActualFileName)] = actualFileName, }; } } diff --git a/Penumbra.GameData b/Penumbra.GameData index 45679aa3..60222d79 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 45679aa32cc37b59f5eeb7cf6bf5a3ea36c626e0 +Subproject commit 60222d79420662fb8e9960a66e262a380fcaf186 diff --git a/Penumbra/Api/Api/ApiHelpers.cs b/Penumbra/Api/Api/ApiHelpers.cs new file mode 100644 index 00000000..32a3956f --- /dev/null +++ b/Penumbra/Api/Api/ApiHelpers.cs @@ -0,0 +1,76 @@ +using OtterGui.Log; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Actors; +using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Api.Api; + +public class ApiHelpers( + CollectionManager collectionManager, + ObjectManager objects, + CollectionResolver collectionResolver, + ActorManager actors) : IApiService +{ + /// Return the associated identifier for an object given by its index. + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + internal ActorIdentifier AssociatedIdentifier(int gameObjectIdx) + { + if (gameObjectIdx < 0 || gameObjectIdx >= objects.TotalCount) + return ActorIdentifier.Invalid; + + var ptr = objects[gameObjectIdx]; + return actors.FromObject(ptr, out _, false, true, true); + } + + /// + /// Return the collection associated to a current game object. If it does not exist, return the default collection. + /// If the index is invalid, returns false and the default collection. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + internal unsafe bool AssociatedCollection(int gameObjectIdx, out ModCollection collection) + { + collection = collectionManager.Active.Default; + if (gameObjectIdx < 0 || gameObjectIdx >= objects.TotalCount) + return false; + + var ptr = objects[gameObjectIdx]; + var data = collectionResolver.IdentifyCollection(ptr.AsObject, false); + if (data.Valid) + collection = data.ModCollection; + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + internal static PenumbraApiEc Return(PenumbraApiEc ec, LazyString args, [CallerMemberName] string name = "Unknown") + { + Penumbra.Log.Debug( + $"[{name}] Called with {args}, returned {ec}."); + return ec; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + internal static LazyString Args(params object[] arguments) + { + if (arguments.Length == 0) + return new LazyString(() => "no arguments"); + + return new LazyString(() => + { + var sb = new StringBuilder(); + for (var i = 0; i < arguments.Length / 2; ++i) + { + sb.Append(arguments[2 * i]); + sb.Append(" = "); + sb.Append(arguments[2 * i + 1]); + sb.Append(", "); + } + + return sb.ToString(0, sb.Length - 2); + }); + } +} diff --git a/Penumbra/Api/Api/CollectionApi.cs b/Penumbra/Api/Api/CollectionApi.cs new file mode 100644 index 00000000..de704460 --- /dev/null +++ b/Penumbra/Api/Api/CollectionApi.cs @@ -0,0 +1,141 @@ +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Collections.Manager; + +namespace Penumbra.Api.Api; + +public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : IPenumbraApiCollection, IApiService +{ + public Dictionary GetCollections() + => collections.Storage.ToDictionary(c => c.Id, c => c.Name); + + public Dictionary GetChangedItemsForCollection(Guid collectionId) + { + try + { + if (!collections.Storage.ById(collectionId, out var collection)) + collection = ModCollection.Empty; + + if (collection.HasCache) + return collection.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Item2); + + Penumbra.Log.Warning($"Collection {collectionId} does not exist or is not loaded."); + return []; + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not obtain Changed Items for {collectionId}:\n{e}"); + throw; + } + } + + public (Guid Id, string Name)? GetCollection(ApiCollectionType type) + { + if (!Enum.IsDefined(type)) + return null; + + var collection = collections.Active.ByType((CollectionType)type); + return collection == null ? null : (collection.Id, collection.Name); + } + + internal (Guid Id, string Name)? GetCollection(byte type) + => GetCollection((ApiCollectionType)type); + + public (bool ObjectValid, bool IndividualSet, (Guid Id, string Name) EffectiveCollection) GetCollectionForObject(int gameObjectIdx) + { + var id = helpers.AssociatedIdentifier(gameObjectIdx); + if (!id.IsValid) + return (false, false, (collections.Active.Default.Id, collections.Active.Default.Name)); + + if (collections.Active.Individuals.TryGetValue(id, out var collection)) + return (true, true, (collection.Id, collection.Name)); + + helpers.AssociatedCollection(gameObjectIdx, out collection); + return (true, false, (collection.Id, collection.Name)); + } + + public Guid[] GetCollectionByName(string name) + => collections.Storage.Where(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase)).Select(c => c.Id).ToArray(); + + public (PenumbraApiEc, (Guid Id, string Name)? OldCollection) SetCollection(ApiCollectionType type, Guid? collectionId, + bool allowCreateNew, bool allowDelete) + { + if (!Enum.IsDefined(type)) + return (PenumbraApiEc.InvalidArgument, null); + + var oldCollection = collections.Active.ByType((CollectionType)type); + var old = oldCollection != null ? (oldCollection.Id, oldCollection.Name) : new ValueTuple?(); + if (collectionId == null) + { + if (old == null) + return (PenumbraApiEc.NothingChanged, old); + + if (!allowDelete || type is ApiCollectionType.Current or ApiCollectionType.Default or ApiCollectionType.Interface) + return (PenumbraApiEc.AssignmentDeletionDisallowed, old); + + collections.Active.RemoveSpecialCollection((CollectionType)type); + return (PenumbraApiEc.Success, old); + } + + if (!collections.Storage.ById(collectionId.Value, out var collection)) + return (PenumbraApiEc.CollectionMissing, old); + + if (old == null) + { + if (!allowCreateNew) + return (PenumbraApiEc.AssignmentCreationDisallowed, old); + + collections.Active.CreateSpecialCollection((CollectionType)type); + } + else if (old.Value.Item1 == collection.Id) + { + return (PenumbraApiEc.NothingChanged, old); + } + + collections.Active.SetCollection(collection, (CollectionType)type); + return (PenumbraApiEc.Success, old); + } + + public (PenumbraApiEc, (Guid Id, string Name)? OldCollection) SetCollectionForObject(int gameObjectIdx, Guid? collectionId, + bool allowCreateNew, bool allowDelete) + { + var id = helpers.AssociatedIdentifier(gameObjectIdx); + if (!id.IsValid) + return (PenumbraApiEc.InvalidIdentifier, (collections.Active.Default.Id, collections.Active.Default.Name)); + + var oldCollection = collections.Active.Individuals.TryGetValue(id, out var c) ? c : null; + var old = oldCollection != null ? (oldCollection.Id, oldCollection.Name) : new ValueTuple?(); + if (collectionId == null) + { + if (old == null) + return (PenumbraApiEc.NothingChanged, old); + + if (!allowDelete) + return (PenumbraApiEc.AssignmentDeletionDisallowed, old); + + var idx = collections.Active.Individuals.Index(id); + collections.Active.RemoveIndividualCollection(idx); + return (PenumbraApiEc.Success, old); + } + + if (!collections.Storage.ById(collectionId.Value, out var collection)) + return (PenumbraApiEc.CollectionMissing, old); + + if (old == null) + { + if (!allowCreateNew) + return (PenumbraApiEc.AssignmentCreationDisallowed, old); + + var ids = collections.Active.Individuals.GetGroup(id); + collections.Active.CreateIndividualCollection(ids); + } + else if (old.Value.Item1 == collection.Id) + { + return (PenumbraApiEc.NothingChanged, old); + } + + collections.Active.SetCollection(collection, CollectionType.Individual, collections.Active.Individuals.Index(id)); + return (PenumbraApiEc.Success, old); + } +} diff --git a/Penumbra/Api/Api/EditingApi.cs b/Penumbra/Api/Api/EditingApi.cs new file mode 100644 index 00000000..93345053 --- /dev/null +++ b/Penumbra/Api/Api/EditingApi.cs @@ -0,0 +1,40 @@ +using OtterGui.Services; +using Penumbra.Import.Textures; +using TextureType = Penumbra.Api.Enums.TextureType; + +namespace Penumbra.Api.Api; + +public class EditingApi(TextureManager textureManager) : IPenumbraApiEditing, IApiService +{ + public Task ConvertTextureFile(string inputFile, string outputFile, TextureType textureType, bool mipMaps) + => textureType switch + { + TextureType.Png => textureManager.SavePng(inputFile, outputFile), + TextureType.AsIsTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, inputFile, outputFile), + TextureType.AsIsDds => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, inputFile, outputFile), + TextureType.RgbaTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, inputFile, outputFile), + TextureType.RgbaDds => textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, false, inputFile, outputFile), + TextureType.Bc3Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, true, inputFile, outputFile), + TextureType.Bc3Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, inputFile, outputFile), + TextureType.Bc7Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, inputFile, outputFile), + TextureType.Bc7Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, inputFile, outputFile), + _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), + }; + + // @formatter:off + public Task ConvertTextureData(byte[] rgbaData, int width, string outputFile, TextureType textureType, bool mipMaps) + => textureType switch + { + TextureType.Png => textureManager.SavePng(new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.AsIsTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.AsIsDds => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.RgbaTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.RgbaDds => textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc3Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc3Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc7Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc7Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), + }; + // @formatter:on +} diff --git a/Penumbra/Api/Api/GameStateApi.cs b/Penumbra/Api/Api/GameStateApi.cs new file mode 100644 index 00000000..becb55ee --- /dev/null +++ b/Penumbra/Api/Api/GameStateApi.cs @@ -0,0 +1,82 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Structs; +using Penumbra.Services; +using Penumbra.String.Classes; + +namespace Penumbra.Api.Api; + +public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable +{ + private readonly CommunicatorService _communicator; + private readonly CollectionResolver _collectionResolver; + private readonly CutsceneService _cutsceneService; + private readonly ResourceLoader _resourceLoader; + + public unsafe GameStateApi(CommunicatorService communicator, CollectionResolver collectionResolver, CutsceneService cutsceneService, + ResourceLoader resourceLoader) + { + _communicator = communicator; + _collectionResolver = collectionResolver; + _cutsceneService = cutsceneService; + _resourceLoader = resourceLoader; + _resourceLoader.ResourceLoaded += OnResourceLoaded; + _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); + } + + public unsafe void Dispose() + { + _resourceLoader.ResourceLoaded -= OnResourceLoaded; + _communicator.CreatedCharacterBase.Unsubscribe(OnCreatedCharacterBase); + } + + public event CreatedCharacterBaseDelegate? CreatedCharacterBase; + public event GameObjectResourceResolvedDelegate? GameObjectResourceResolved; + + public event CreatingCharacterBaseDelegate? CreatingCharacterBase + { + add + { + if (value == null) + return; + + _communicator.CreatingCharacterBase.Subscribe(new Action(value), + Communication.CreatingCharacterBase.Priority.Api); + } + remove + { + if (value == null) + return; + + _communicator.CreatingCharacterBase.Unsubscribe(new Action(value)); + } + } + + public unsafe (nint GameObject, (Guid Id, string Name) Collection) GetDrawObjectInfo(nint drawObject) + { + var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + return (data.AssociatedGameObject, (data.ModCollection.Id, data.ModCollection.Name)); + } + + public int GetCutsceneParentIndex(int actorIdx) + => _cutsceneService.GetParentIndex(actorIdx); + + public PenumbraApiEc SetCutsceneParentIndex(int copyIdx, int newParentIdx) + => _cutsceneService.SetParentIndex(copyIdx, newParentIdx) + ? PenumbraApiEc.Success + : PenumbraApiEc.InvalidArgument; + + private unsafe void OnResourceLoaded(ResourceHandle* handle, Utf8GamePath originalPath, FullPath? manipulatedPath, ResolveData resolveData) + { + if (resolveData.AssociatedGameObject != nint.Zero) + GameObjectResourceResolved?.Invoke(resolveData.AssociatedGameObject, originalPath.ToString(), + manipulatedPath?.ToString() ?? originalPath.ToString()); + } + + private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) + => CreatedCharacterBase?.Invoke(gameObject, collection.Id, drawObject); +} diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs new file mode 100644 index 00000000..c467df58 --- /dev/null +++ b/Penumbra/Api/Api/MetaApi.cs @@ -0,0 +1,23 @@ +using OtterGui; +using OtterGui.Services; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Api.Api; + +public class MetaApi(CollectionResolver collectionResolver, ApiHelpers helpers) : IPenumbraApiMeta, IApiService +{ + public string GetPlayerMetaManipulations() + { + var collection = collectionResolver.PlayerCollection(); + var set = collection.MetaCache?.Manipulations.ToArray() ?? []; + return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); + } + + public string GetMetaManipulations(int gameObjectIdx) + { + helpers.AssociatedCollection(gameObjectIdx, out var collection); + var set = collection.MetaCache?.Manipulations.ToArray() ?? []; + return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); + } +} diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs new file mode 100644 index 00000000..2604a49d --- /dev/null +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -0,0 +1,282 @@ +using OtterGui; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.Communication; +using Penumbra.Interop.PathResolving; +using Penumbra.Mods; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Manager; +using Penumbra.Mods.Subclasses; +using Penumbra.Services; + +namespace Penumbra.Api.Api; + +public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable +{ + private readonly CollectionResolver _collectionResolver; + private readonly ModManager _modManager; + private readonly CollectionManager _collectionManager; + private readonly CollectionEditor _collectionEditor; + private readonly CommunicatorService _communicator; + + public ModSettingsApi(CollectionResolver collectionResolver, + ModManager modManager, + CollectionManager collectionManager, + CollectionEditor collectionEditor, + CommunicatorService communicator) + { + _collectionResolver = collectionResolver; + _modManager = modManager; + _collectionManager = collectionManager; + _collectionEditor = collectionEditor; + _communicator = communicator; + _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ApiModSettings); + _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); + _communicator.ModOptionChanged.Subscribe(OnModOptionEdited, ModOptionChanged.Priority.Api); + _communicator.ModFileChanged.Subscribe(OnModFileChanged, ModFileChanged.Priority.Api); + } + + public void Dispose() + { + _communicator.ModPathChanged.Unsubscribe(OnModPathChange); + _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); + _communicator.ModOptionChanged.Unsubscribe(OnModOptionEdited); + _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); + } + + public event ModSettingChangedDelegate? ModSettingChanged; + + public AvailableModSettings? GetAvailableModSettings(string modDirectory, string modName) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return null; + + var dict = new Dictionary(mod.Groups.Count); + foreach (var g in mod.Groups) + dict.Add(g.Name, (g.Select(o => o.Name).ToArray(), (int)g.Type)); + return new AvailableModSettings(dict); + } + + public Dictionary? GetAvailableModSettingsBase(string modDirectory, string modName) + => _modManager.TryGetMod(modDirectory, modName, out var mod) + ? mod.Groups.ToDictionary(g => g.Name, g => (g.Select(o => o.Name).ToArray(), (int)g.Type)) + : null; + + public (PenumbraApiEc, (bool, int, Dictionary>, bool)?) GetCurrentModSettings(Guid collectionId, string modDirectory, + string modName, bool ignoreInheritance) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return (PenumbraApiEc.ModMissing, null); + + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return (PenumbraApiEc.CollectionMissing, null); + + var settings = collection.Id == Guid.Empty + ? null + : ignoreInheritance + ? collection.Settings[mod.Index] + : collection[mod.Index].Settings; + if (settings == null) + return (PenumbraApiEc.Success, null); + + var (enabled, priority, dict) = settings.ConvertToShareable(mod); + return (PenumbraApiEc.Success, + (enabled, priority.Value, dict, collection.Settings[mod.Index] == null)); + } + + public PenumbraApiEc TryInheritMod(Guid collectionId, string modDirectory, string modName, bool inherit) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Inherit", + inherit.ToString()); + + if (collectionId == Guid.Empty) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + var ret = _collectionEditor.SetModInheritance(collection, mod, inherit) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc TrySetMod(Guid collectionId, string modDirectory, string modName, bool enabled) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Enabled", enabled); + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + var ret = _collectionEditor.SetModState(collection, mod, enabled) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc TrySetModPriority(Guid collectionId, string modDirectory, string modName, int priority) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Priority", priority); + + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + var ret = _collectionEditor.SetModPriority(collection, mod, new ModPriority(priority)) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc TrySetModSetting(Guid collectionId, string modDirectory, string modName, string optionGroupName, string optionName) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", + optionGroupName, "OptionName", optionName); + + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); + if (groupIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionGroupMissing, args); + + var optionIdx = mod.Groups[groupIdx].IndexOf(o => o.Name == optionName); + if (optionIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); + + var setting = mod.Groups[groupIdx] switch + { + MultiModGroup => Setting.Multi(optionIdx), + SingleModGroup => Setting.Single(optionIdx), + _ => Setting.Zero, + }; + var ret = _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc TrySetModSettings(Guid collectionId, string modDirectory, string modName, string optionGroupName, + IReadOnlyList optionNames) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", + optionGroupName, "#optionNames", optionNames.Count); + + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); + if (groupIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionGroupMissing, args); + + var setting = Setting.Zero; + switch (mod.Groups[groupIdx]) + { + case SingleModGroup single: + { + var optionIdx = optionNames.Count == 0 ? -1 : single.IndexOf(o => o.Name == optionNames[^1]); + if (optionIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); + + setting = Setting.Single(optionIdx); + break; + } + case MultiModGroup multi: + { + foreach (var name in optionNames) + { + var optionIdx = multi.IndexOf(o => o.Name == name); + if (optionIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); + + setting |= Setting.Multi(optionIdx); + } + + break; + } + } + + var ret = _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc CopyModSettings(Guid? collectionId, string modDirectoryFrom, string modDirectoryTo) + { + var args = ApiHelpers.Args("CollectionId", collectionId.HasValue ? collectionId.Value.ToString() : "NULL", + "From", modDirectoryFrom, "To", modDirectoryTo); + var sourceMod = _modManager.FirstOrDefault(m => string.Equals(m.ModPath.Name, modDirectoryFrom, StringComparison.OrdinalIgnoreCase)); + var targetMod = _modManager.FirstOrDefault(m => string.Equals(m.ModPath.Name, modDirectoryTo, StringComparison.OrdinalIgnoreCase)); + if (collectionId == null) + foreach (var collection in _collectionManager.Storage) + _collectionEditor.CopyModSettings(collection, sourceMod, modDirectoryFrom, targetMod, modDirectoryTo); + else if (_collectionManager.Storage.ById(collectionId.Value, out var collection)) + _collectionEditor.CopyModSettings(collection, sourceMod, modDirectoryFrom, targetMod, modDirectoryTo); + else + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return ApiHelpers.Return(PenumbraApiEc.Success, args); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void TriggerSettingEdited(Mod mod) + { + var collection = _collectionResolver.PlayerCollection(); + var (settings, parent) = collection[mod.Index]; + if (settings is { Enabled: true }) + ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Id, mod.Identifier, parent != collection); + } + + private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) + { + if (type == ModPathChangeType.Reloaded) + TriggerSettingEdited(mod); + } + + private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting _1, int _2, bool inherited) + => ModSettingChanged?.Invoke(type, collection.Id, mod?.ModPath.Name ?? string.Empty, inherited); + + private void OnModOptionEdited(ModOptionChangeType type, Mod mod, int groupIndex, int optionIndex, int moveIndex) + { + switch (type) + { + case ModOptionChangeType.GroupDeleted: + case ModOptionChangeType.GroupMoved: + case ModOptionChangeType.GroupTypeChanged: + case ModOptionChangeType.PriorityChanged: + case ModOptionChangeType.OptionDeleted: + case ModOptionChangeType.OptionMoved: + case ModOptionChangeType.OptionFilesChanged: + case ModOptionChangeType.OptionFilesAdded: + case ModOptionChangeType.OptionSwapsChanged: + case ModOptionChangeType.OptionMetaChanged: + TriggerSettingEdited(mod); + break; + } + } + + private void OnModFileChanged(Mod mod, FileRegistry file) + { + if (file.CurrentUsage == 0) + return; + + TriggerSettingEdited(mod); + } +} diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs new file mode 100644 index 00000000..c1e0c684 --- /dev/null +++ b/Penumbra/Api/Api/ModsApi.cs @@ -0,0 +1,132 @@ +using OtterGui.Compression; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Communication; +using Penumbra.Mods; +using Penumbra.Mods.Manager; +using Penumbra.Services; + +namespace Penumbra.Api.Api; + +public class ModsApi : IPenumbraApiMods, IApiService, IDisposable +{ + private readonly CommunicatorService _communicator; + private readonly ModManager _modManager; + private readonly ModImportManager _modImportManager; + private readonly Configuration _config; + private readonly ModFileSystem _modFileSystem; + + public ModsApi(ModManager modManager, ModImportManager modImportManager, Configuration config, ModFileSystem modFileSystem, + CommunicatorService communicator) + { + _modManager = modManager; + _modImportManager = modImportManager; + _config = config; + _modFileSystem = modFileSystem; + _communicator = communicator; + _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ApiMods); + } + + private void OnModPathChanged(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) + { + switch (type) + { + case ModPathChangeType.Deleted when oldDirectory != null: + ModDeleted?.Invoke(oldDirectory.Name); + break; + case ModPathChangeType.Added when newDirectory != null: + ModAdded?.Invoke(newDirectory.Name); + break; + case ModPathChangeType.Moved when newDirectory != null && oldDirectory != null: + ModMoved?.Invoke(oldDirectory.Name, newDirectory.Name); + break; + } + } + + public void Dispose() + => _communicator.ModPathChanged.Unsubscribe(OnModPathChanged); + + public Dictionary GetModList() + => _modManager.ToDictionary(m => m.ModPath.Name, m => m.Name.Text); + + public PenumbraApiEc InstallMod(string modFilePackagePath) + { + if (!File.Exists(modFilePackagePath)) + return ApiHelpers.Return(PenumbraApiEc.FileMissing, ApiHelpers.Args("ModFilePackagePath", modFilePackagePath)); + + _modImportManager.AddUnpack(modFilePackagePath); + return ApiHelpers.Return(PenumbraApiEc.Success, ApiHelpers.Args("ModFilePackagePath", modFilePackagePath)); + } + + public PenumbraApiEc ReloadMod(string modDirectory, string modName) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, ApiHelpers.Args("ModDirectory", modDirectory, "ModName", modName)); + + _modManager.ReloadMod(mod); + return ApiHelpers.Return(PenumbraApiEc.Success, ApiHelpers.Args("ModDirectory", modDirectory, "ModName", modName)); + } + + public PenumbraApiEc AddMod(string modDirectory) + { + var args = ApiHelpers.Args("ModDirectory", modDirectory); + + var dir = new DirectoryInfo(Path.Join(_modManager.BasePath.FullName, Path.GetFileName(modDirectory))); + if (!dir.Exists) + return ApiHelpers.Return(PenumbraApiEc.FileMissing, args); + + if (_modManager.BasePath.FullName != dir.Parent?.FullName) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + _modManager.AddMod(dir); + if (_config.UseFileSystemCompression) + new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), + CompressionAlgorithm.Xpress8K); + return ApiHelpers.Return(PenumbraApiEc.Success, args); + } + + public PenumbraApiEc DeleteMod(string modDirectory, string modName) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.NothingChanged, ApiHelpers.Args("ModDirectory", modDirectory, "ModName", modName)); + + _modManager.DeleteMod(mod); + return ApiHelpers.Return(PenumbraApiEc.Success, ApiHelpers.Args("ModDirectory", modDirectory, "ModName", modName)); + } + + public event Action? ModDeleted; + public event Action? ModAdded; + public event Action? ModMoved; + + public (PenumbraApiEc, string, bool, bool) GetModPath(string modDirectory, string modName) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod) + || !_modFileSystem.FindLeaf(mod, out var leaf)) + return (PenumbraApiEc.ModMissing, string.Empty, false, false); + + var fullPath = leaf.FullName(); + var isDefault = ModFileSystem.ModHasDefaultPath(mod, fullPath); + var isNameDefault = isDefault || ModFileSystem.ModHasDefaultPath(mod, leaf.Name); + return (PenumbraApiEc.Success, fullPath, !isDefault, !isNameDefault ); + } + + public PenumbraApiEc SetModPath(string modDirectory, string modName, string newPath) + { + if (newPath.Length == 0) + return PenumbraApiEc.InvalidArgument; + + if (!_modManager.TryGetMod(modDirectory, modName, out var mod) + || !_modFileSystem.FindLeaf(mod, out var leaf)) + return PenumbraApiEc.ModMissing; + + try + { + _modFileSystem.RenameAndMove(leaf, newPath); + return PenumbraApiEc.Success; + } + catch + { + return PenumbraApiEc.PathRenameFailed; + } + } +} diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs new file mode 100644 index 00000000..1d5b1537 --- /dev/null +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -0,0 +1,40 @@ +using OtterGui.Services; + +namespace Penumbra.Api.Api; + +public class PenumbraApi( + CollectionApi collection, + EditingApi editing, + GameStateApi gameState, + MetaApi meta, + ModsApi mods, + ModSettingsApi modSettings, + PluginStateApi pluginState, + RedrawApi redraw, + ResolveApi resolve, + ResourceTreeApi resourceTree, + TemporaryApi temporary, + UiApi ui) : IDisposable, IApiService, IPenumbraApi +{ + public void Dispose() + { + Valid = false; + } + + public (int Breaking, int Feature) ApiVersion + => (5, 0); + + public bool Valid { get; private set; } = true; + public IPenumbraApiCollection Collection { get; } = collection; + public IPenumbraApiEditing Editing { get; } = editing; + public IPenumbraApiGameState GameState { get; } = gameState; + public IPenumbraApiMeta Meta { get; } = meta; + public IPenumbraApiMods Mods { get; } = mods; + public IPenumbraApiModSettings ModSettings { get; } = modSettings; + public IPenumbraApiPluginState PluginState { get; } = pluginState; + public IPenumbraApiRedraw Redraw { get; } = redraw; + public IPenumbraApiResolve Resolve { get; } = resolve; + public IPenumbraApiResourceTree ResourceTree { get; } = resourceTree; + public IPenumbraApiTemporary Temporary { get; } = temporary; + public IPenumbraApiUi Ui { get; } = ui; +} diff --git a/Penumbra/Api/Api/PluginStateApi.cs b/Penumbra/Api/Api/PluginStateApi.cs new file mode 100644 index 00000000..2e87486f --- /dev/null +++ b/Penumbra/Api/Api/PluginStateApi.cs @@ -0,0 +1,30 @@ +using Newtonsoft.Json; +using OtterGui.Services; +using Penumbra.Communication; +using Penumbra.Services; + +namespace Penumbra.Api.Api; + +public class PluginStateApi(Configuration config, CommunicatorService communicator) : IPenumbraApiPluginState, IApiService +{ + public string GetModDirectory() + => config.ModDirectory; + + public string GetConfiguration() + => JsonConvert.SerializeObject(config, Formatting.Indented); + + public event Action? ModDirectoryChanged + { + add => communicator.ModDirectoryChanged.Subscribe(value!, Communication.ModDirectoryChanged.Priority.Api); + remove => communicator.ModDirectoryChanged.Unsubscribe(value!); + } + + public bool GetEnabledState() + => config.EnableMods; + + public event Action? EnabledChange + { + add => communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); + remove => communicator.EnabledChanged.Unsubscribe(value!); + } +} diff --git a/Penumbra/Api/Api/RedrawApi.cs b/Penumbra/Api/Api/RedrawApi.cs new file mode 100644 index 00000000..03b42493 --- /dev/null +++ b/Penumbra/Api/Api/RedrawApi.cs @@ -0,0 +1,27 @@ +using Dalamud.Game.ClientState.Objects.Types; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Interop.Services; + +namespace Penumbra.Api.Api; + +public class RedrawApi(RedrawService redrawService) : IPenumbraApiRedraw, IApiService +{ + public void RedrawObject(int gameObjectIndex, RedrawType setting) + => redrawService.RedrawObject(gameObjectIndex, setting); + + public void RedrawObject(string name, RedrawType setting) + => redrawService.RedrawObject(name, setting); + + public void RedrawObject(GameObject? gameObject, RedrawType setting) + => redrawService.RedrawObject(gameObject, setting); + + public void RedrawAll(RedrawType setting) + => redrawService.RedrawAll(setting); + + public event GameObjectRedrawnDelegate? GameObjectRedrawn + { + add => redrawService.GameObjectRedrawn += value; + remove => redrawService.GameObjectRedrawn -= value; + } +} diff --git a/Penumbra/Api/Api/ResolveApi.cs b/Penumbra/Api/Api/ResolveApi.cs new file mode 100644 index 00000000..ec57eba7 --- /dev/null +++ b/Penumbra/Api/Api/ResolveApi.cs @@ -0,0 +1,101 @@ +using Dalamud.Plugin.Services; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.Interop.PathResolving; +using Penumbra.Mods.Manager; +using Penumbra.String.Classes; + +namespace Penumbra.Api.Api; + +public class ResolveApi( + ModManager modManager, + CollectionManager collectionManager, + Configuration config, + CollectionResolver collectionResolver, + ApiHelpers helpers, + IFramework framework) : IPenumbraApiResolve, IApiService +{ + public string ResolveDefaultPath(string gamePath) + => ResolvePath(gamePath, modManager, collectionManager.Active.Default); + + public string ResolveInterfacePath(string gamePath) + => ResolvePath(gamePath, modManager, collectionManager.Active.Interface); + + public string ResolveGameObjectPath(string gamePath, int gameObjectIdx) + { + helpers.AssociatedCollection(gameObjectIdx, out var collection); + return ResolvePath(gamePath, modManager, collection); + } + + public string ResolvePlayerPath(string gamePath) + => ResolvePath(gamePath, modManager, collectionResolver.PlayerCollection()); + + public string[] ReverseResolveGameObjectPath(string moddedPath, int gameObjectIdx) + { + if (!config.EnableMods) + return [moddedPath]; + + helpers.AssociatedCollection(gameObjectIdx, out var collection); + var ret = collection.ReverseResolvePath(new FullPath(moddedPath)); + return ret.Select(r => r.ToString()).ToArray(); + } + + public string[] ReverseResolvePlayerPath(string moddedPath) + { + if (!config.EnableMods) + return [moddedPath]; + + var ret = collectionResolver.PlayerCollection().ReverseResolvePath(new FullPath(moddedPath)); + return ret.Select(r => r.ToString()).ToArray(); + } + + public (string[], string[][]) ResolvePlayerPaths(string[] forward, string[] reverse) + { + if (!config.EnableMods) + return (forward, reverse.Select(p => new[] + { + p, + }).ToArray()); + + var playerCollection = collectionResolver.PlayerCollection(); + var resolved = forward.Select(p => ResolvePath(p, modManager, playerCollection)).ToArray(); + var reverseResolved = playerCollection.ReverseResolvePaths(reverse); + return (resolved, reverseResolved.Select(a => a.Select(p => p.ToString()).ToArray()).ToArray()); + } + + public async Task<(string[], string[][])> ResolvePlayerPathsAsync(string[] forward, string[] reverse) + { + if (!config.EnableMods) + return (forward, reverse.Select(p => new[] + { + p, + }).ToArray()); + + return await Task.Run(async () => + { + var playerCollection = await framework.RunOnFrameworkThread(collectionResolver.PlayerCollection).ConfigureAwait(false); + var forwardTask = Task.Run(() => + { + var forwardRet = new string[forward.Length]; + Parallel.For(0, forward.Length, idx => forwardRet[idx] = ResolvePath(forward[idx], modManager, playerCollection)); + return forwardRet; + }).ConfigureAwait(false); + var reverseTask = Task.Run(() => playerCollection.ReverseResolvePaths(reverse)).ConfigureAwait(false); + var reverseResolved = (await reverseTask).Select(a => a.Select(p => p.ToString()).ToArray()).ToArray(); + return (await forwardTask, reverseResolved); + }).ConfigureAwait(false); + } + + /// Resolve a path given by string for a specific collection. + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private string ResolvePath(string path, ModManager _, ModCollection collection) + { + if (!config.EnableMods) + return path; + + var gamePath = Utf8GamePath.FromString(path, out var p, true) ? p : Utf8GamePath.Empty; + var ret = collection.ResolvePath(gamePath); + return ret?.ToString() ?? path; + } +} diff --git a/Penumbra/Api/Api/ResourceTreeApi.cs b/Penumbra/Api/Api/ResourceTreeApi.cs new file mode 100644 index 00000000..6e9aaa48 --- /dev/null +++ b/Penumbra/Api/Api/ResourceTreeApi.cs @@ -0,0 +1,63 @@ +using Dalamud.Game.ClientState.Objects.Types; +using Newtonsoft.Json.Linq; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.GameData.Interop; +using Penumbra.Interop.ResourceTree; + +namespace Penumbra.Api.Api; + +public class ResourceTreeApi(ResourceTreeFactory resourceTreeFactory, ObjectManager objects) : IPenumbraApiResourceTree, IApiService +{ + public Dictionary>?[] GetGameObjectResourcePaths(params ushort[] gameObjects) + { + var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); + var resourceTrees = resourceTreeFactory.FromCharacters(characters, 0); + var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); + + return Array.ConvertAll(gameObjects, obj => pathDictionaries.GetValueOrDefault(obj)); + } + + public Dictionary>> GetPlayerResourcePaths() + { + var resourceTrees = resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly); + return ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); + } + + public GameResourceDict?[] GetGameObjectResourcesOfType(ResourceType type, bool withUiData, + params ushort[] gameObjects) + { + var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); + var resourceTrees = resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); + var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); + + return Array.ConvertAll(gameObjects, obj => resDictionaries.GetValueOrDefault(obj)); + } + + public Dictionary GetPlayerResourcesOfType(ResourceType type, + bool withUiData) + { + var resourceTrees = resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly + | (withUiData ? ResourceTreeFactory.Flags.WithUiData : 0)); + return ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); + } + + public JObject?[] GetGameObjectResourceTrees(bool withUiData, params ushort[] gameObjects) + { + var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); + var resourceTrees = resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); + var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); + + return Array.ConvertAll(gameObjects, obj => resDictionary.GetValueOrDefault(obj)); + } + + public Dictionary GetPlayerResourceTrees(bool withUiData) + { + var resourceTrees = resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly + | (withUiData ? ResourceTreeFactory.Flags.WithUiData : 0)); + var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); + + return resDictionary; + } +} diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs new file mode 100644 index 00000000..b4ffa8f4 --- /dev/null +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -0,0 +1,190 @@ +using OtterGui; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Actors; +using Penumbra.GameData.Interop; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Subclasses; +using Penumbra.String.Classes; + +namespace Penumbra.Api.Api; + +public class TemporaryApi( + TempCollectionManager tempCollections, + ObjectManager objects, + ActorManager actors, + CollectionManager collectionManager, + TempModManager tempMods) : IPenumbraApiTemporary, IApiService +{ + public Guid CreateTemporaryCollection(string name) + => tempCollections.CreateTemporaryCollection(name); + + public PenumbraApiEc DeleteTemporaryCollection(Guid collectionId) + => tempCollections.RemoveTemporaryCollection(collectionId) + ? PenumbraApiEc.Success + : PenumbraApiEc.CollectionMissing; + + public PenumbraApiEc AssignTemporaryCollection(Guid collectionId, int actorIndex, bool forceAssignment) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ActorIndex", actorIndex, "Forced", forceAssignment); + if (actorIndex < 0 || actorIndex >= objects.TotalCount) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + var identifier = actors.FromObject(objects[actorIndex], out _, false, false, true); + if (!identifier.IsValid) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + if (!tempCollections.CollectionById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (forceAssignment) + { + if (tempCollections.Collections.ContainsKey(identifier) && !tempCollections.Collections.Delete(identifier)) + return ApiHelpers.Return(PenumbraApiEc.AssignmentDeletionFailed, args); + } + else if (tempCollections.Collections.ContainsKey(identifier) + || collectionManager.Active.Individuals.ContainsKey(identifier)) + { + return ApiHelpers.Return(PenumbraApiEc.CharacterCollectionExists, args); + } + + var group = tempCollections.Collections.GetGroup(identifier); + var ret = tempCollections.AddIdentifier(collection, group) + ? PenumbraApiEc.Success + : PenumbraApiEc.UnknownError; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc AddTemporaryModAll(string tag, Dictionary paths, string manipString, int priority) + { + var args = ApiHelpers.Args("Tag", tag, "#Paths", paths.Count, "ManipString", manipString, "Priority", priority); + if (!ConvertPaths(paths, out var p)) + return ApiHelpers.Return(PenumbraApiEc.InvalidGamePath, args); + + if (!ConvertManips(manipString, out var m)) + return ApiHelpers.Return(PenumbraApiEc.InvalidManipulation, args); + + var ret = tempMods.Register(tag, null, p, m, new ModPriority(priority)) switch + { + RedirectResult.Success => PenumbraApiEc.Success, + _ => PenumbraApiEc.UnknownError, + }; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc AddTemporaryMod(string tag, Guid collectionId, Dictionary paths, string manipString, int priority) + { + var args = ApiHelpers.Args("Tag", tag, "CollectionId", collectionId, "#Paths", paths.Count, "ManipString", + manipString, "Priority", priority); + + if (collectionId == Guid.Empty) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + if (!tempCollections.CollectionById(collectionId, out var collection) + && !collectionManager.Storage.ById(collectionId, out collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + if (!ConvertPaths(paths, out var p)) + return ApiHelpers.Return(PenumbraApiEc.InvalidGamePath, args); + + if (!ConvertManips(manipString, out var m)) + return ApiHelpers.Return(PenumbraApiEc.InvalidManipulation, args); + + var ret = tempMods.Register(tag, collection, p, m, new ModPriority(priority)) switch + { + RedirectResult.Success => PenumbraApiEc.Success, + _ => PenumbraApiEc.UnknownError, + }; + return ApiHelpers.Return(ret, args); + } + + public PenumbraApiEc RemoveTemporaryModAll(string tag, int priority) + { + var ret = tempMods.Unregister(tag, null, new ModPriority(priority)) switch + { + RedirectResult.Success => PenumbraApiEc.Success, + RedirectResult.NotRegistered => PenumbraApiEc.NothingChanged, + _ => PenumbraApiEc.UnknownError, + }; + return ApiHelpers.Return(ret, ApiHelpers.Args("Tag", tag, "Priority", priority)); + } + + public PenumbraApiEc RemoveTemporaryMod(string tag, Guid collectionId, int priority) + { + var args = ApiHelpers.Args("Tag", tag, "CollectionId", collectionId, "Priority", priority); + + if (!tempCollections.CollectionById(collectionId, out var collection) + && !collectionManager.Storage.ById(collectionId, out collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + var ret = tempMods.Unregister(tag, collection, new ModPriority(priority)) switch + { + RedirectResult.Success => PenumbraApiEc.Success, + RedirectResult.NotRegistered => PenumbraApiEc.NothingChanged, + _ => PenumbraApiEc.UnknownError, + }; + return ApiHelpers.Return(ret, args); + } + + /// + /// Convert a dictionary of strings to a dictionary of game paths to full paths. + /// Only returns true if all paths can successfully be converted and added. + /// + private static bool ConvertPaths(IReadOnlyDictionary redirections, + [NotNullWhen(true)] out Dictionary? paths) + { + paths = new Dictionary(redirections.Count); + foreach (var (gString, fString) in redirections) + { + if (!Utf8GamePath.FromString(gString, out var path, false)) + { + paths = null; + return false; + } + + var fullPath = new FullPath(fString); + if (!paths.TryAdd(path, fullPath)) + { + paths = null; + return false; + } + } + + return true; + } + + /// + /// Convert manipulations from a transmitted base64 string to actual manipulations. + /// The empty string is treated as an empty set. + /// Only returns true if all conversions are successful and distinct. + /// + private static bool ConvertManips(string manipString, + [NotNullWhen(true)] out HashSet? manips) + { + if (manipString.Length == 0) + { + manips = []; + return true; + } + + if (Functions.FromCompressedBase64(manipString, out var manipArray) != MetaManipulation.CurrentVersion) + { + manips = null; + return false; + } + + manips = new HashSet(manipArray!.Length); + foreach (var manip in manipArray.Where(m => m.Validate())) + { + if (manips.Add(manip)) + continue; + + Penumbra.Log.Warning($"Manipulation {manip} {manip.EntryToString()} is invalid and was skipped."); + manips = null; + return false; + } + + return true; + } +} diff --git a/Penumbra/Api/Api/UiApi.cs b/Penumbra/Api/Api/UiApi.cs new file mode 100644 index 00000000..cf3cd8f2 --- /dev/null +++ b/Penumbra/Api/Api/UiApi.cs @@ -0,0 +1,101 @@ +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Communication; +using Penumbra.GameData.Enums; +using Penumbra.Mods.Manager; +using Penumbra.Services; +using Penumbra.UI; + +namespace Penumbra.Api.Api; + +public class UiApi : IPenumbraApiUi, IApiService, IDisposable +{ + private readonly CommunicatorService _communicator; + private readonly ConfigWindow _configWindow; + private readonly ModManager _modManager; + + public UiApi(CommunicatorService communicator, ConfigWindow configWindow, ModManager modManager) + { + _communicator = communicator; + _configWindow = configWindow; + _modManager = modManager; + _communicator.ChangedItemHover.Subscribe(OnChangedItemHover, ChangedItemHover.Priority.Default); + _communicator.ChangedItemClick.Subscribe(OnChangedItemClick, ChangedItemClick.Priority.Default); + } + + public void Dispose() + { + _communicator.ChangedItemHover.Unsubscribe(OnChangedItemHover); + _communicator.ChangedItemClick.Unsubscribe(OnChangedItemClick); + } + + public event Action? ChangedItemTooltip; + + public event Action? ChangedItemClicked; + + public event Action? PreSettingsTabBarDraw + { + add => _communicator.PreSettingsTabBarDraw.Subscribe(value!, Communication.PreSettingsTabBarDraw.Priority.Default); + remove => _communicator.PreSettingsTabBarDraw.Unsubscribe(value!); + } + + public event Action? PreSettingsPanelDraw + { + add => _communicator.PreSettingsPanelDraw.Subscribe(value!, Communication.PreSettingsPanelDraw.Priority.Default); + remove => _communicator.PreSettingsPanelDraw.Unsubscribe(value!); + } + + public event Action? PostEnabledDraw + { + add => _communicator.PostEnabledDraw.Subscribe(value!, Communication.PostEnabledDraw.Priority.Default); + remove => _communicator.PostEnabledDraw.Unsubscribe(value!); + } + + public event Action? PostSettingsPanelDraw + { + add => _communicator.PostSettingsPanelDraw.Subscribe(value!, Communication.PostSettingsPanelDraw.Priority.Default); + remove => _communicator.PostSettingsPanelDraw.Unsubscribe(value!); + } + + public PenumbraApiEc OpenMainWindow(TabType tab, string modDirectory, string modName) + { + _configWindow.IsOpen = true; + if (!Enum.IsDefined(tab)) + return PenumbraApiEc.InvalidArgument; + + if (tab == TabType.Mods && (modDirectory.Length > 0 || modName.Length > 0)) + { + if (_modManager.TryGetMod(modDirectory, modName, out var mod)) + _communicator.SelectTab.Invoke(tab, mod); + else + return PenumbraApiEc.ModMissing; + } + else if (tab != TabType.None) + { + _communicator.SelectTab.Invoke(tab, null); + } + + return PenumbraApiEc.Success; + } + + public void CloseMainWindow() + => _configWindow.IsOpen = false; + + private void OnChangedItemClick(MouseButton button, object? data) + { + if (ChangedItemClicked == null) + return; + + var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(data); + ChangedItemClicked.Invoke(button, type, id); + } + + private void OnChangedItemHover(object? data) + { + if (ChangedItemTooltip == null) + return; + + var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(data); + ChangedItemTooltip.Invoke(type, id); + } +} diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index 0374e31a..1c2cebcc 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -1,4 +1,5 @@ using Dalamud.Plugin.Services; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -9,7 +10,7 @@ using Penumbra.String.Classes; namespace Penumbra.Api; -public class DalamudSubstitutionProvider : IDisposable +public class DalamudSubstitutionProvider : IDisposable, IApiService { private readonly ITextureSubstitutionProvider _substitution; private readonly ActiveCollectionData _activeCollectionData; diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index e23f8b4f..859c46b4 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -1,11 +1,13 @@ using EmbedIO; using EmbedIO.Routing; using EmbedIO.WebApi; +using OtterGui.Services; +using Penumbra.Api.Api; using Penumbra.Api.Enums; namespace Penumbra.Api; -public class HttpApi : IDisposable +public class HttpApi : IDisposable, IApiService { private partial class Controller : WebApiController { @@ -67,7 +69,7 @@ public class HttpApi : IDisposable public partial object? GetMods() { Penumbra.Log.Debug($"[HTTP] {nameof(GetMods)} triggered."); - return _api.GetModList(); + return _api.Mods.GetModList(); } public async partial Task Redraw() @@ -75,17 +77,15 @@ public class HttpApi : IDisposable var data = await HttpContext.GetRequestDataAsync(); Penumbra.Log.Debug($"[HTTP] {nameof(Redraw)} triggered with {data}."); if (data.ObjectTableIndex >= 0) - _api.RedrawObject(data.ObjectTableIndex, data.Type); - else if (data.Name.Length > 0) - _api.RedrawObject(data.Name, data.Type); + _api.Redraw.RedrawObject(data.ObjectTableIndex, data.Type); else - _api.RedrawAll(data.Type); + _api.Redraw.RedrawAll(data.Type); } public partial void RedrawAll() { Penumbra.Log.Debug($"[HTTP] {nameof(RedrawAll)} triggered."); - _api.RedrawAll(RedrawType.Redraw); + _api.Redraw.RedrawAll(RedrawType.Redraw); } public async partial Task ReloadMod() @@ -95,10 +95,10 @@ public class HttpApi : IDisposable // Add the mod if it is not already loaded and if the directory name is given. // AddMod returns Success if the mod is already loaded. if (data.Path.Length != 0) - _api.AddMod(data.Path); + _api.Mods.AddMod(data.Path); // Reload the mod by path or name, which will also remove no-longer existing mods. - _api.ReloadMod(data.Path, data.Name); + _api.Mods.ReloadMod(data.Path, data.Name); } public async partial Task InstallMod() @@ -106,13 +106,13 @@ public class HttpApi : IDisposable var data = await HttpContext.GetRequestDataAsync(); Penumbra.Log.Debug($"[HTTP] {nameof(InstallMod)} triggered with {data}."); if (data.Path.Length != 0) - _api.InstallMod(data.Path); + _api.Mods.InstallMod(data.Path); } public partial void OpenWindow() { Penumbra.Log.Debug($"[HTTP] {nameof(OpenWindow)} triggered."); - _api.OpenMainWindow(TabType.Mods, string.Empty, string.Empty); + _api.Ui.OpenMainWindow(TabType.Mods, string.Empty, string.Empty); } private record ModReloadData(string Path, string Name) diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs new file mode 100644 index 00000000..293af588 --- /dev/null +++ b/Penumbra/Api/IpcProviders.cs @@ -0,0 +1,118 @@ +using Dalamud.Plugin; +using OtterGui.Services; +using Penumbra.Api.Api; +using Penumbra.Api.Helpers; + +namespace Penumbra.Api; + +public sealed class IpcProviders : IDisposable, IApiService +{ + private readonly List _providers; + + private readonly EventProvider _disposedProvider; + private readonly EventProvider _initializedProvider; + + public IpcProviders(DalamudPluginInterface pi, IPenumbraApi api) + { + _disposedProvider = IpcSubscribers.Disposed.Provider(pi); + _initializedProvider = IpcSubscribers.Initialized.Provider(pi); + _providers = + [ + IpcSubscribers.GetCollections.Provider(pi, api.Collection), + IpcSubscribers.GetChangedItemsForCollection.Provider(pi, api.Collection), + IpcSubscribers.GetCollection.Provider(pi, api.Collection), + IpcSubscribers.GetCollectionForObject.Provider(pi, api.Collection), + IpcSubscribers.SetCollection.Provider(pi, api.Collection), + IpcSubscribers.SetCollectionForObject.Provider(pi, api.Collection), + + IpcSubscribers.ConvertTextureFile.Provider(pi, api.Editing), + IpcSubscribers.ConvertTextureData.Provider(pi, api.Editing), + + IpcSubscribers.GetDrawObjectInfo.Provider(pi, api.GameState), + IpcSubscribers.GetCutsceneParentIndex.Provider(pi, api.GameState), + IpcSubscribers.SetCutsceneParentIndex.Provider(pi, api.GameState), + IpcSubscribers.CreatingCharacterBase.Provider(pi, api.GameState), + IpcSubscribers.CreatedCharacterBase.Provider(pi, api.GameState), + IpcSubscribers.GameObjectResourcePathResolved.Provider(pi, api.GameState), + + IpcSubscribers.GetPlayerMetaManipulations.Provider(pi, api.Meta), + IpcSubscribers.GetMetaManipulations.Provider(pi, api.Meta), + + IpcSubscribers.GetModList.Provider(pi, api.Mods), + IpcSubscribers.InstallMod.Provider(pi, api.Mods), + IpcSubscribers.ReloadMod.Provider(pi, api.Mods), + IpcSubscribers.AddMod.Provider(pi, api.Mods), + IpcSubscribers.DeleteMod.Provider(pi, api.Mods), + IpcSubscribers.ModDeleted.Provider(pi, api.Mods), + IpcSubscribers.ModAdded.Provider(pi, api.Mods), + IpcSubscribers.ModMoved.Provider(pi, api.Mods), + IpcSubscribers.GetModPath.Provider(pi, api.Mods), + IpcSubscribers.SetModPath.Provider(pi, api.Mods), + + IpcSubscribers.GetAvailableModSettings.Provider(pi, api.ModSettings), + IpcSubscribers.GetCurrentModSettings.Provider(pi, api.ModSettings), + IpcSubscribers.TryInheritMod.Provider(pi, api.ModSettings), + IpcSubscribers.TrySetMod.Provider(pi, api.ModSettings), + IpcSubscribers.TrySetModPriority.Provider(pi, api.ModSettings), + IpcSubscribers.TrySetModSetting.Provider(pi, api.ModSettings), + IpcSubscribers.TrySetModSettings.Provider(pi, api.ModSettings), + IpcSubscribers.ModSettingChanged.Provider(pi, api.ModSettings), + IpcSubscribers.CopyModSettings.Provider(pi, api.ModSettings), + + IpcSubscribers.ApiVersion.Provider(pi, api), + IpcSubscribers.GetModDirectory.Provider(pi, api.PluginState), + IpcSubscribers.GetConfiguration.Provider(pi, api.PluginState), + IpcSubscribers.ModDirectoryChanged.Provider(pi, api.PluginState), + IpcSubscribers.GetEnabledState.Provider(pi, api.PluginState), + IpcSubscribers.EnabledChange.Provider(pi, api.PluginState), + + IpcSubscribers.RedrawObject.Provider(pi, api.Redraw), + IpcSubscribers.RedrawAll.Provider(pi, api.Redraw), + IpcSubscribers.GameObjectRedrawn.Provider(pi, api.Redraw), + + IpcSubscribers.ResolveDefaultPath.Provider(pi, api.Resolve), + IpcSubscribers.ResolveInterfacePath.Provider(pi, api.Resolve), + IpcSubscribers.ResolveGameObjectPath.Provider(pi, api.Resolve), + IpcSubscribers.ResolvePlayerPath.Provider(pi, api.Resolve), + IpcSubscribers.ReverseResolveGameObjectPath.Provider(pi, api.Resolve), + IpcSubscribers.ReverseResolvePlayerPath.Provider(pi, api.Resolve), + IpcSubscribers.ResolvePlayerPaths.Provider(pi, api.Resolve), + IpcSubscribers.ResolvePlayerPathsAsync.Provider(pi, api.Resolve), + + IpcSubscribers.GetGameObjectResourcePaths.Provider(pi, api.ResourceTree), + IpcSubscribers.GetPlayerResourcePaths.Provider(pi, api.ResourceTree), + IpcSubscribers.GetGameObjectResourcesOfType.Provider(pi, api.ResourceTree), + IpcSubscribers.GetPlayerResourcesOfType.Provider(pi, api.ResourceTree), + IpcSubscribers.GetGameObjectResourceTrees.Provider(pi, api.ResourceTree), + IpcSubscribers.GetPlayerResourceTrees.Provider(pi, api.ResourceTree), + + IpcSubscribers.CreateTemporaryCollection.Provider(pi, api.Temporary), + IpcSubscribers.DeleteTemporaryCollection.Provider(pi, api.Temporary), + IpcSubscribers.AssignTemporaryCollection.Provider(pi, api.Temporary), + IpcSubscribers.AddTemporaryModAll.Provider(pi, api.Temporary), + IpcSubscribers.AddTemporaryMod.Provider(pi, api.Temporary), + IpcSubscribers.RemoveTemporaryModAll.Provider(pi, api.Temporary), + IpcSubscribers.RemoveTemporaryMod.Provider(pi, api.Temporary), + + IpcSubscribers.ChangedItemTooltip.Provider(pi, api.Ui), + IpcSubscribers.ChangedItemClicked.Provider(pi, api.Ui), + IpcSubscribers.PreSettingsTabBarDraw.Provider(pi, api.Ui), + IpcSubscribers.PreSettingsPanelDraw.Provider(pi, api.Ui), + IpcSubscribers.PostEnabledDraw.Provider(pi, api.Ui), + IpcSubscribers.PostSettingsPanelDraw.Provider(pi, api.Ui), + IpcSubscribers.OpenMainWindow.Provider(pi, api.Ui), + IpcSubscribers.CloseMainWindow.Provider(pi, api.Ui), + ]; + _initializedProvider.Invoke(); + } + + public void Dispose() + { + foreach (var provider in _providers) + provider.Dispose(); + _providers.Clear(); + _initializedProvider.Dispose(); + _disposedProvider.Invoke(); + _disposedProvider.Dispose(); + } +} diff --git a/Penumbra/Api/IpcTester.cs b/Penumbra/Api/IpcTester.cs deleted file mode 100644 index 898c5de3..00000000 --- a/Penumbra/Api/IpcTester.cs +++ /dev/null @@ -1,1762 +0,0 @@ -using Dalamud.Game.ClientState.Objects.Enums; -using Dalamud.Interface; -using Dalamud.Interface.Utility; -using Dalamud.Plugin; -using ImGuiNET; -using OtterGui; -using OtterGui.Raii; -using Penumbra.Mods; -using Dalamud.Utility; -using Penumbra.Api.Enums; -using Penumbra.Api.Helpers; -using Penumbra.String; -using Penumbra.String.Classes; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Manager; -using Penumbra.Services; -using Penumbra.UI; -using Penumbra.Collections.Manager; -using Dalamud.Plugin.Services; -using Penumbra.GameData.Structs; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Interop; - -namespace Penumbra.Api; - -public class IpcTester : IDisposable -{ - private readonly PenumbraIpcProviders _ipcProviders; - private bool _subscribed = true; - - private readonly PluginState _pluginState; - private readonly IpcConfiguration _ipcConfiguration; - private readonly Ui _ui; - private readonly Redrawing _redrawing; - private readonly GameState _gameState; - private readonly Resolve _resolve; - private readonly Collections _collections; - private readonly Meta _meta; - private readonly Mods _mods; - private readonly ModSettings _modSettings; - private readonly Editing _editing; - private readonly Temporary _temporary; - private readonly ResourceTree _resourceTree; - - public IpcTester(Configuration config, DalamudPluginInterface pi, ObjectManager objects, IClientState clientState, - PenumbraIpcProviders ipcProviders, ModManager modManager, CollectionManager collections, TempModManager tempMods, - TempCollectionManager tempCollections, SaveService saveService) - { - _ipcProviders = ipcProviders; - _pluginState = new PluginState(pi); - _ipcConfiguration = new IpcConfiguration(pi); - _ui = new Ui(pi); - _redrawing = new Redrawing(pi, objects, clientState); - _gameState = new GameState(pi); - _resolve = new Resolve(pi); - _collections = new Collections(pi); - _meta = new Meta(pi); - _mods = new Mods(pi); - _modSettings = new ModSettings(pi); - _editing = new Editing(pi); - _temporary = new Temporary(pi, modManager, collections, tempMods, tempCollections, saveService, config); - _resourceTree = new ResourceTree(pi, objects); - UnsubscribeEvents(); - } - - public void Draw() - { - try - { - SubscribeEvents(); - ImGui.TextUnformatted($"API Version: {_ipcProviders.Api.ApiVersion.Breaking}.{_ipcProviders.Api.ApiVersion.Feature:D4}"); - _pluginState.Draw(); - _ipcConfiguration.Draw(); - _ui.Draw(); - _redrawing.Draw(); - _gameState.Draw(); - _resolve.Draw(); - _collections.Draw(); - _meta.Draw(); - _mods.Draw(); - _modSettings.Draw(); - _editing.Draw(); - _temporary.Draw(); - _temporary.DrawCollections(); - _temporary.DrawMods(); - _resourceTree.Draw(); - } - catch (Exception e) - { - Penumbra.Log.Error($"Error during IPC Tests:\n{e}"); - } - } - - private void SubscribeEvents() - { - if (!_subscribed) - { - _pluginState.Initialized.Enable(); - _pluginState.Disposed.Enable(); - _pluginState.EnabledChange.Enable(); - _redrawing.Redrawn.Enable(); - _ui.PreSettingsDraw.Enable(); - _ui.PostSettingsDraw.Enable(); - _modSettings.SettingChanged.Enable(); - _gameState.CharacterBaseCreating.Enable(); - _gameState.CharacterBaseCreated.Enable(); - _ipcConfiguration.ModDirectoryChanged.Enable(); - _gameState.GameObjectResourcePathResolved.Enable(); - _mods.DeleteSubscriber.Enable(); - _mods.AddSubscriber.Enable(); - _mods.MoveSubscriber.Enable(); - _subscribed = true; - } - } - - public void UnsubscribeEvents() - { - if (_subscribed) - { - _pluginState.Initialized.Disable(); - _pluginState.Disposed.Disable(); - _pluginState.EnabledChange.Disable(); - _redrawing.Redrawn.Disable(); - _ui.PreSettingsDraw.Disable(); - _ui.PostSettingsDraw.Disable(); - _ui.Tooltip.Disable(); - _ui.Click.Disable(); - _modSettings.SettingChanged.Disable(); - _gameState.CharacterBaseCreating.Disable(); - _gameState.CharacterBaseCreated.Disable(); - _ipcConfiguration.ModDirectoryChanged.Disable(); - _gameState.GameObjectResourcePathResolved.Disable(); - _mods.DeleteSubscriber.Disable(); - _mods.AddSubscriber.Disable(); - _mods.MoveSubscriber.Disable(); - _subscribed = false; - } - } - - public void Dispose() - { - _pluginState.Initialized.Dispose(); - _pluginState.Disposed.Dispose(); - _pluginState.EnabledChange.Dispose(); - _redrawing.Redrawn.Dispose(); - _ui.PreSettingsDraw.Dispose(); - _ui.PostSettingsDraw.Dispose(); - _ui.Tooltip.Dispose(); - _ui.Click.Dispose(); - _modSettings.SettingChanged.Dispose(); - _gameState.CharacterBaseCreating.Dispose(); - _gameState.CharacterBaseCreated.Dispose(); - _ipcConfiguration.ModDirectoryChanged.Dispose(); - _gameState.GameObjectResourcePathResolved.Dispose(); - _mods.DeleteSubscriber.Dispose(); - _mods.AddSubscriber.Dispose(); - _mods.MoveSubscriber.Dispose(); - _subscribed = false; - } - - private static void DrawIntro(string label, string info) - { - ImGui.TableNextColumn(); - ImGui.TextUnformatted(label); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(info); - ImGui.TableNextColumn(); - } - - - private class PluginState - { - private readonly DalamudPluginInterface _pi; - public readonly EventSubscriber Initialized; - public readonly EventSubscriber Disposed; - public readonly EventSubscriber EnabledChange; - - private readonly List _initializedList = new(); - private readonly List _disposedList = new(); - - private DateTimeOffset _lastEnabledChange = DateTimeOffset.UnixEpoch; - private bool? _lastEnabledValue; - - public PluginState(DalamudPluginInterface pi) - { - _pi = pi; - Initialized = Ipc.Initialized.Subscriber(pi, AddInitialized); - Disposed = Ipc.Disposed.Subscriber(pi, AddDisposed); - EnabledChange = Ipc.EnabledChange.Subscriber(pi, SetLastEnabled); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("Plugin State"); - if (!_) - return; - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - void DrawList(string label, string text, List list) - { - DrawIntro(label, text); - if (list.Count == 0) - { - ImGui.TextUnformatted("Never"); - } - else - { - ImGui.TextUnformatted(list[^1].LocalDateTime.ToString(CultureInfo.CurrentCulture)); - if (list.Count > 1 && ImGui.IsItemHovered()) - ImGui.SetTooltip(string.Join("\n", - list.SkipLast(1).Select(t => t.LocalDateTime.ToString(CultureInfo.CurrentCulture)))); - } - } - - DrawList(Ipc.Initialized.Label, "Last Initialized", _initializedList); - DrawList(Ipc.Disposed.Label, "Last Disposed", _disposedList); - DrawIntro(Ipc.ApiVersions.Label, "Current Version"); - var (breaking, features) = Ipc.ApiVersions.Subscriber(_pi).Invoke(); - ImGui.TextUnformatted($"{breaking}.{features:D4}"); - DrawIntro(Ipc.GetEnabledState.Label, "Current State"); - ImGui.TextUnformatted($"{Ipc.GetEnabledState.Subscriber(_pi).Invoke()}"); - DrawIntro(Ipc.EnabledChange.Label, "Last Change"); - ImGui.TextUnformatted(_lastEnabledValue is { } v ? $"{_lastEnabledChange} (to {v})" : "Never"); - } - - private void AddInitialized() - => _initializedList.Add(DateTimeOffset.UtcNow); - - private void AddDisposed() - => _disposedList.Add(DateTimeOffset.UtcNow); - - private void SetLastEnabled(bool val) - => (_lastEnabledChange, _lastEnabledValue) = (DateTimeOffset.Now, val); - } - - private class IpcConfiguration - { - private readonly DalamudPluginInterface _pi; - public readonly EventSubscriber ModDirectoryChanged; - - private string _currentConfiguration = string.Empty; - private string _lastModDirectory = string.Empty; - private bool _lastModDirectoryValid; - private DateTimeOffset _lastModDirectoryTime = DateTimeOffset.MinValue; - - public IpcConfiguration(DalamudPluginInterface pi) - { - _pi = pi; - ModDirectoryChanged = Ipc.ModDirectoryChanged.Subscriber(pi, UpdateModDirectoryChanged); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("Configuration"); - if (!_) - return; - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.GetModDirectory.Label, "Current Mod Directory"); - ImGui.TextUnformatted(Ipc.GetModDirectory.Subscriber(_pi).Invoke()); - DrawIntro(Ipc.ModDirectoryChanged.Label, "Last Mod Directory Change"); - ImGui.TextUnformatted(_lastModDirectoryTime > DateTimeOffset.MinValue - ? $"{_lastModDirectory} ({(_lastModDirectoryValid ? "Valid" : "Invalid")}) at {_lastModDirectoryTime}" - : "None"); - DrawIntro(Ipc.GetConfiguration.Label, "Configuration"); - if (ImGui.Button("Get")) - { - _currentConfiguration = Ipc.GetConfiguration.Subscriber(_pi).Invoke(); - ImGui.OpenPopup("Config Popup"); - } - - DrawConfigPopup(); - } - - private void DrawConfigPopup() - { - ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); - using var popup = ImRaii.Popup("Config Popup"); - if (!popup) - return; - - using (ImRaii.PushFont(UiBuilder.MonoFont)) - { - ImGuiUtil.TextWrapped(_currentConfiguration); - } - - if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) - ImGui.CloseCurrentPopup(); - } - - private void UpdateModDirectoryChanged(string path, bool valid) - => (_lastModDirectory, _lastModDirectoryValid, _lastModDirectoryTime) = (path, valid, DateTimeOffset.Now); - } - - private class Ui - { - private readonly DalamudPluginInterface _pi; - public readonly EventSubscriber PreSettingsDraw; - public readonly EventSubscriber PostSettingsDraw; - public readonly EventSubscriber Tooltip; - public readonly EventSubscriber Click; - - private string _lastDrawnMod = string.Empty; - private DateTimeOffset _lastDrawnModTime = DateTimeOffset.MinValue; - private bool _subscribedToTooltip; - private bool _subscribedToClick; - private string _lastClicked = string.Empty; - private string _lastHovered = string.Empty; - private TabType _selectTab = TabType.None; - private string _modName = string.Empty; - private PenumbraApiEc _ec = PenumbraApiEc.Success; - - public Ui(DalamudPluginInterface pi) - { - _pi = pi; - PreSettingsDraw = Ipc.PreSettingsDraw.Subscriber(pi, UpdateLastDrawnMod); - PostSettingsDraw = Ipc.PostSettingsDraw.Subscriber(pi, UpdateLastDrawnMod); - Tooltip = Ipc.ChangedItemTooltip.Subscriber(pi, AddedTooltip); - Click = Ipc.ChangedItemClick.Subscriber(pi, AddedClick); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("UI"); - if (!_) - return; - - using (var combo = ImRaii.Combo("Tab to Open at", _selectTab.ToString())) - { - if (combo) - foreach (var val in Enum.GetValues()) - { - if (ImGui.Selectable(val.ToString(), _selectTab == val)) - _selectTab = val; - } - } - - ImGui.InputTextWithHint("##openMod", "Mod to Open at...", ref _modName, 256); - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.PostSettingsDraw.Label, "Last Drawn Mod"); - ImGui.TextUnformatted(_lastDrawnMod.Length > 0 ? $"{_lastDrawnMod} at {_lastDrawnModTime}" : "None"); - - DrawIntro(Ipc.ChangedItemTooltip.Label, "Add Tooltip"); - if (ImGui.Checkbox("##tooltip", ref _subscribedToTooltip)) - { - if (_subscribedToTooltip) - Tooltip.Enable(); - else - Tooltip.Disable(); - } - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastHovered); - - DrawIntro(Ipc.ChangedItemClick.Label, "Subscribe Click"); - if (ImGui.Checkbox("##click", ref _subscribedToClick)) - { - if (_subscribedToClick) - Click.Enable(); - else - Click.Disable(); - } - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastClicked); - DrawIntro(Ipc.OpenMainWindow.Label, "Open Mod Window"); - if (ImGui.Button("Open##window")) - _ec = Ipc.OpenMainWindow.Subscriber(_pi).Invoke(_selectTab, _modName, _modName); - - ImGui.SameLine(); - ImGui.TextUnformatted(_ec.ToString()); - - DrawIntro(Ipc.CloseMainWindow.Label, "Close Mod Window"); - if (ImGui.Button("Close##window")) - Ipc.CloseMainWindow.Subscriber(_pi).Invoke(); - } - - private void UpdateLastDrawnMod(string name) - => (_lastDrawnMod, _lastDrawnModTime) = (name, DateTimeOffset.Now); - - private void AddedTooltip(ChangedItemType type, uint id) - { - _lastHovered = $"{type} {id} at {DateTime.UtcNow.ToLocalTime().ToString(CultureInfo.CurrentCulture)}"; - ImGui.TextUnformatted("IPC Test Successful"); - } - - private void AddedClick(MouseButton button, ChangedItemType type, uint id) - { - _lastClicked = $"{button}-click on {type} {id} at {DateTime.UtcNow.ToLocalTime().ToString(CultureInfo.CurrentCulture)}"; - } - } - - private class Redrawing - { - private readonly DalamudPluginInterface _pi; - private readonly IClientState _clientState; - private readonly ObjectManager _objects; - public readonly EventSubscriber Redrawn; - - private string _redrawName = string.Empty; - private int _redrawIndex; - private string _lastRedrawnString = "None"; - - public Redrawing(DalamudPluginInterface pi, ObjectManager objects, IClientState clientState) - { - _pi = pi; - _objects = objects; - _clientState = clientState; - Redrawn = Ipc.GameObjectRedrawn.Subscriber(_pi, SetLastRedrawn); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("Redrawing"); - if (!_) - return; - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.RedrawObjectByName.Label, "Redraw by Name"); - ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - ImGui.InputTextWithHint("##redrawName", "Name...", ref _redrawName, 32); - ImGui.SameLine(); - if (ImGui.Button("Redraw##Name")) - Ipc.RedrawObjectByName.Subscriber(_pi).Invoke(_redrawName, RedrawType.Redraw); - - DrawIntro(Ipc.RedrawObject.Label, "Redraw Player Character"); - if (ImGui.Button("Redraw##pc") && _clientState.LocalPlayer != null) - Ipc.RedrawObject.Subscriber(_pi).Invoke(_clientState.LocalPlayer, RedrawType.Redraw); - - DrawIntro(Ipc.RedrawObjectByIndex.Label, "Redraw by Index"); - var tmp = _redrawIndex; - ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.TotalCount)) - _redrawIndex = Math.Clamp(tmp, 0, _objects.TotalCount); - - ImGui.SameLine(); - if (ImGui.Button("Redraw##Index")) - Ipc.RedrawObjectByIndex.Subscriber(_pi).Invoke(_redrawIndex, RedrawType.Redraw); - - DrawIntro(Ipc.RedrawAll.Label, "Redraw All"); - if (ImGui.Button("Redraw##All")) - Ipc.RedrawAll.Subscriber(_pi).Invoke(RedrawType.Redraw); - - DrawIntro(Ipc.GameObjectRedrawn.Label, "Last Redrawn Object:"); - ImGui.TextUnformatted(_lastRedrawnString); - } - - private void SetLastRedrawn(IntPtr address, int index) - { - if (index < 0 - || index > _objects.TotalCount - || address == IntPtr.Zero - || _objects[index].Address != address) - _lastRedrawnString = "Invalid"; - - _lastRedrawnString = $"{_objects[index].Utf8Name} (0x{address:X}, {index})"; - } - } - - private class GameState - { - private readonly DalamudPluginInterface _pi; - public readonly EventSubscriber CharacterBaseCreating; - public readonly EventSubscriber CharacterBaseCreated; - public readonly EventSubscriber GameObjectResourcePathResolved; - - - private string _lastCreatedGameObjectName = string.Empty; - private IntPtr _lastCreatedDrawObject = IntPtr.Zero; - private DateTimeOffset _lastCreatedGameObjectTime = DateTimeOffset.MaxValue; - private string _lastResolvedGamePath = string.Empty; - private string _lastResolvedFullPath = string.Empty; - private string _lastResolvedObject = string.Empty; - private DateTimeOffset _lastResolvedGamePathTime = DateTimeOffset.MaxValue; - private string _currentDrawObjectString = string.Empty; - private IntPtr _currentDrawObject = IntPtr.Zero; - private int _currentCutsceneActor; - private int _currentCutsceneParent; - private PenumbraApiEc _cutsceneError = PenumbraApiEc.Success; - - public GameState(DalamudPluginInterface pi) - { - _pi = pi; - CharacterBaseCreating = Ipc.CreatingCharacterBase.Subscriber(pi, UpdateLastCreated); - CharacterBaseCreated = Ipc.CreatedCharacterBase.Subscriber(pi, UpdateLastCreated2); - GameObjectResourcePathResolved = Ipc.GameObjectResourcePathResolved.Subscriber(pi, UpdateGameObjectResourcePath); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("Game State"); - if (!_) - return; - - if (ImGui.InputTextWithHint("##drawObject", "Draw Object Address..", ref _currentDrawObjectString, 16, - ImGuiInputTextFlags.CharsHexadecimal)) - _currentDrawObject = IntPtr.TryParse(_currentDrawObjectString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, - out var tmp) - ? tmp - : IntPtr.Zero; - - ImGui.InputInt("Cutscene Actor", ref _currentCutsceneActor, 0); - ImGui.InputInt("Cutscene Parent", ref _currentCutsceneParent, 0); - if (_cutsceneError is not PenumbraApiEc.Success) - { - ImGui.SameLine(); - ImGui.TextUnformatted("Invalid Argument on last Call"); - } - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.GetDrawObjectInfo.Label, "Draw Object Info"); - if (_currentDrawObject == IntPtr.Zero) - { - ImGui.TextUnformatted("Invalid"); - } - else - { - var (ptr, collection) = Ipc.GetDrawObjectInfo.Subscriber(_pi).Invoke(_currentDrawObject); - ImGui.TextUnformatted(ptr == IntPtr.Zero ? $"No Actor Associated, {collection}" : $"{ptr:X}, {collection}"); - } - - DrawIntro(Ipc.GetCutsceneParentIndex.Label, "Cutscene Parent"); - ImGui.TextUnformatted(Ipc.GetCutsceneParentIndex.Subscriber(_pi).Invoke(_currentCutsceneActor).ToString()); - - DrawIntro(Ipc.SetCutsceneParentIndex.Label, "Cutscene Parent"); - if (ImGui.Button("Set Parent")) - _cutsceneError = Ipc.SetCutsceneParentIndex.Subscriber(_pi).Invoke(_currentCutsceneActor, _currentCutsceneParent); - - DrawIntro(Ipc.CreatingCharacterBase.Label, "Last Drawobject created"); - if (_lastCreatedGameObjectTime < DateTimeOffset.Now) - ImGui.TextUnformatted(_lastCreatedDrawObject != IntPtr.Zero - ? $"0x{_lastCreatedDrawObject:X} for <{_lastCreatedGameObjectName}> at {_lastCreatedGameObjectTime}" - : $"NULL for <{_lastCreatedGameObjectName}> at {_lastCreatedGameObjectTime}"); - - DrawIntro(Ipc.GameObjectResourcePathResolved.Label, "Last GamePath resolved"); - if (_lastResolvedGamePathTime < DateTimeOffset.Now) - ImGui.TextUnformatted( - $"{_lastResolvedGamePath} -> {_lastResolvedFullPath} for <{_lastResolvedObject}> at {_lastResolvedGamePathTime}"); - } - - private void UpdateLastCreated(IntPtr gameObject, string _, IntPtr _2, IntPtr _3, IntPtr _4) - { - _lastCreatedGameObjectName = GetObjectName(gameObject); - _lastCreatedGameObjectTime = DateTimeOffset.Now; - _lastCreatedDrawObject = IntPtr.Zero; - } - - private void UpdateLastCreated2(IntPtr gameObject, string _, IntPtr drawObject) - { - _lastCreatedGameObjectName = GetObjectName(gameObject); - _lastCreatedGameObjectTime = DateTimeOffset.Now; - _lastCreatedDrawObject = drawObject; - } - - private void UpdateGameObjectResourcePath(IntPtr gameObject, string gamePath, string fullPath) - { - _lastResolvedObject = GetObjectName(gameObject); - _lastResolvedGamePath = gamePath; - _lastResolvedFullPath = fullPath; - _lastResolvedGamePathTime = DateTimeOffset.Now; - } - - private static unsafe string GetObjectName(IntPtr gameObject) - { - var obj = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)gameObject; - var name = obj != null ? obj->Name : null; - return name != null && *name != 0 ? new ByteString(name).ToString() : "Unknown"; - } - } - - private class Resolve(DalamudPluginInterface pi) - { - private string _currentResolvePath = string.Empty; - private string _currentResolveCharacter = string.Empty; - private string _currentReversePath = string.Empty; - private int _currentReverseIdx; - private Task<(string[], string[][])> _task = Task.FromResult<(string[], string[][])>(([], [])); - - public void Draw() - { - using var tree = ImRaii.TreeNode("Resolving"); - if (!tree) - return; - - ImGui.InputTextWithHint("##resolvePath", "Resolve this game path...", ref _currentResolvePath, Utf8GamePath.MaxGamePathLength); - ImGui.InputTextWithHint("##resolveCharacter", "Character Name (leave blank for default)...", ref _currentResolveCharacter, 32); - ImGui.InputTextWithHint("##resolveInversePath", "Reverse-resolve this path...", ref _currentReversePath, - Utf8GamePath.MaxGamePathLength); - ImGui.InputInt("##resolveIdx", ref _currentReverseIdx, 0, 0); - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.ResolveDefaultPath.Label, "Default Collection Resolve"); - if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveDefaultPath.Subscriber(pi).Invoke(_currentResolvePath)); - - DrawIntro(Ipc.ResolveInterfacePath.Label, "Interface Collection Resolve"); - if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveInterfacePath.Subscriber(pi).Invoke(_currentResolvePath)); - - DrawIntro(Ipc.ResolvePlayerPath.Label, "Player Collection Resolve"); - if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolvePlayerPath.Subscriber(pi).Invoke(_currentResolvePath)); - - DrawIntro(Ipc.ResolveCharacterPath.Label, "Character Collection Resolve"); - if (_currentResolvePath.Length != 0 && _currentResolveCharacter.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveCharacterPath.Subscriber(pi).Invoke(_currentResolvePath, _currentResolveCharacter)); - - DrawIntro(Ipc.ResolveGameObjectPath.Label, "Game Object Collection Resolve"); - if (_currentResolvePath.Length != 0) - ImGui.TextUnformatted(Ipc.ResolveGameObjectPath.Subscriber(pi).Invoke(_currentResolvePath, _currentReverseIdx)); - - DrawIntro(Ipc.ReverseResolvePath.Label, "Reversed Game Paths"); - if (_currentReversePath.Length > 0) - { - var list = Ipc.ReverseResolvePath.Subscriber(pi).Invoke(_currentReversePath, _currentResolveCharacter); - if (list.Length > 0) - { - ImGui.TextUnformatted(list[0]); - if (list.Length > 1 && ImGui.IsItemHovered()) - ImGui.SetTooltip(string.Join("\n", list.Skip(1))); - } - } - - DrawIntro(Ipc.ReverseResolvePlayerPath.Label, "Reversed Game Paths (Player)"); - if (_currentReversePath.Length > 0) - { - var list = Ipc.ReverseResolvePlayerPath.Subscriber(pi).Invoke(_currentReversePath); - if (list.Length > 0) - { - ImGui.TextUnformatted(list[0]); - if (list.Length > 1 && ImGui.IsItemHovered()) - ImGui.SetTooltip(string.Join("\n", list.Skip(1))); - } - } - - DrawIntro(Ipc.ReverseResolveGameObjectPath.Label, "Reversed Game Paths (Game Object)"); - if (_currentReversePath.Length > 0) - { - var list = Ipc.ReverseResolveGameObjectPath.Subscriber(pi).Invoke(_currentReversePath, _currentReverseIdx); - if (list.Length > 0) - { - ImGui.TextUnformatted(list[0]); - if (list.Length > 1 && ImGui.IsItemHovered()) - ImGui.SetTooltip(string.Join("\n", list.Skip(1))); - } - } - - var forwardArray = _currentResolvePath.Length > 0 - ? [_currentResolvePath] - : Array.Empty(); - var reverseArray = _currentReversePath.Length > 0 - ? [_currentReversePath] - : Array.Empty(); - - DrawIntro(Ipc.ResolvePlayerPaths.Label, "Resolved Paths (Player)"); - if (forwardArray.Length > 0 || reverseArray.Length > 0) - { - var ret = Ipc.ResolvePlayerPaths.Subscriber(pi).Invoke(forwardArray, reverseArray); - ImGui.TextUnformatted(ConvertText(ret)); - } - - DrawIntro(Ipc.ResolvePlayerPathsAsync.Label, "Resolved Paths Async (Player)"); - if (ImGui.Button("Start")) - _task = Ipc.ResolvePlayerPathsAsync.Subscriber(pi).Invoke(forwardArray, reverseArray); - var hovered = ImGui.IsItemHovered(); - ImGui.SameLine(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(_task.Status.ToString()); - if ((hovered || ImGui.IsItemHovered()) && _task.IsCompletedSuccessfully) - ImGui.SetTooltip(ConvertText(_task.Result)); - return; - - static string ConvertText((string[], string[][]) data) - { - var text = string.Empty; - if (data.Item1.Length > 0) - { - if (data.Item2.Length > 0) - text = $"Forward: {data.Item1[0]} | Reverse: {string.Join("; ", data.Item2[0])}."; - else - text = $"Forward: {data.Item1[0]}."; - } - else if (data.Item2.Length > 0) - { - text = $"Reverse: {string.Join("; ", data.Item2[0])}."; - } - - return text; - } - } - } - - private class Collections - { - private readonly DalamudPluginInterface _pi; - - private int _objectIdx; - private string _collectionName = string.Empty; - private bool _allowCreation = true; - private bool _allowDeletion = true; - private ApiCollectionType _type = ApiCollectionType.Current; - - private string _characterCollectionName = string.Empty; - private IList _collections = []; - private string _changedItemCollection = string.Empty; - private IReadOnlyDictionary _changedItems = new Dictionary(); - private PenumbraApiEc _returnCode = PenumbraApiEc.Success; - private string? _oldCollection; - - public Collections(DalamudPluginInterface pi) - => _pi = pi; - - public void Draw() - { - using var _ = ImRaii.TreeNode("Collections"); - if (!_) - return; - - ImGuiUtil.GenericEnumCombo("Collection Type", 200, _type, out _type, t => ((CollectionType)t).ToName()); - ImGui.InputInt("Object Index##Collections", ref _objectIdx, 0, 0); - ImGui.InputText("Collection Name##Collections", ref _collectionName, 64); - ImGui.Checkbox("Allow Assignment Creation", ref _allowCreation); - ImGui.SameLine(); - ImGui.Checkbox("Allow Assignment Deletion", ref _allowDeletion); - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro("Last Return Code", _returnCode.ToString()); - if (_oldCollection != null) - ImGui.TextUnformatted(_oldCollection.Length == 0 ? "Created" : _oldCollection); - - DrawIntro(Ipc.GetCurrentCollectionName.Label, "Current Collection"); - ImGui.TextUnformatted(Ipc.GetCurrentCollectionName.Subscriber(_pi).Invoke()); - DrawIntro(Ipc.GetDefaultCollectionName.Label, "Default Collection"); - ImGui.TextUnformatted(Ipc.GetDefaultCollectionName.Subscriber(_pi).Invoke()); - DrawIntro(Ipc.GetInterfaceCollectionName.Label, "Interface Collection"); - ImGui.TextUnformatted(Ipc.GetInterfaceCollectionName.Subscriber(_pi).Invoke()); - DrawIntro(Ipc.GetCharacterCollectionName.Label, "Character"); - ImGui.SetNextItemWidth(200 * UiHelpers.Scale); - ImGui.InputTextWithHint("##characterCollectionName", "Character Name...", ref _characterCollectionName, 64); - var (c, s) = Ipc.GetCharacterCollectionName.Subscriber(_pi).Invoke(_characterCollectionName); - ImGui.SameLine(); - ImGui.TextUnformatted($"{c}, {(s ? "Custom" : "Default")}"); - - DrawIntro(Ipc.GetCollections.Label, "Collections"); - if (ImGui.Button("Get##Collections")) - { - _collections = Ipc.GetCollections.Subscriber(_pi).Invoke(); - ImGui.OpenPopup("Collections"); - } - - DrawIntro(Ipc.GetCollectionForType.Label, "Get Special Collection"); - var name = Ipc.GetCollectionForType.Subscriber(_pi).Invoke(_type); - ImGui.TextUnformatted(name.Length == 0 ? "Unassigned" : name); - DrawIntro(Ipc.SetCollectionForType.Label, "Set Special Collection"); - if (ImGui.Button("Set##TypeCollection")) - (_returnCode, _oldCollection) = - Ipc.SetCollectionForType.Subscriber(_pi).Invoke(_type, _collectionName, _allowCreation, _allowDeletion); - - DrawIntro(Ipc.GetCollectionForObject.Label, "Get Object Collection"); - (var valid, var individual, name) = Ipc.GetCollectionForObject.Subscriber(_pi).Invoke(_objectIdx); - ImGui.TextUnformatted( - $"{(valid ? "Valid" : "Invalid")} Object, {(name.Length == 0 ? "Unassigned" : name)}{(individual ? " (Individual Assignment)" : string.Empty)}"); - DrawIntro(Ipc.SetCollectionForObject.Label, "Set Object Collection"); - if (ImGui.Button("Set##ObjectCollection")) - (_returnCode, _oldCollection) = Ipc.SetCollectionForObject.Subscriber(_pi) - .Invoke(_objectIdx, _collectionName, _allowCreation, _allowDeletion); - - if (_returnCode == PenumbraApiEc.NothingChanged && _oldCollection.IsNullOrEmpty()) - _oldCollection = null; - - DrawIntro(Ipc.GetChangedItems.Label, "Changed Item List"); - ImGui.SetNextItemWidth(200 * UiHelpers.Scale); - ImGui.InputTextWithHint("##changedCollection", "Collection Name...", ref _changedItemCollection, 64); - ImGui.SameLine(); - if (ImGui.Button("Get")) - { - _changedItems = Ipc.GetChangedItems.Subscriber(_pi).Invoke(_changedItemCollection); - ImGui.OpenPopup("Changed Item List"); - } - - DrawChangedItemPopup(); - DrawCollectionPopup(); - } - - private void DrawChangedItemPopup() - { - ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); - using var p = ImRaii.Popup("Changed Item List"); - if (!p) - return; - - foreach (var item in _changedItems) - ImGui.TextUnformatted(item.Key); - - if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) - ImGui.CloseCurrentPopup(); - } - - private void DrawCollectionPopup() - { - ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); - using var p = ImRaii.Popup("Collections"); - if (!p) - return; - - foreach (var collection in _collections) - ImGui.TextUnformatted(collection); - - if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) - ImGui.CloseCurrentPopup(); - } - } - - private class Meta - { - private readonly DalamudPluginInterface _pi; - - private string _characterName = string.Empty; - private int _gameObjectIndex; - - public Meta(DalamudPluginInterface pi) - => _pi = pi; - - public void Draw() - { - using var _ = ImRaii.TreeNode("Meta"); - if (!_) - return; - - ImGui.InputTextWithHint("##characterName", "Character Name...", ref _characterName, 64); - ImGui.InputInt("##metaIdx", ref _gameObjectIndex, 0, 0); - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.GetMetaManipulations.Label, "Meta Manipulations"); - if (ImGui.Button("Copy to Clipboard")) - { - var base64 = Ipc.GetMetaManipulations.Subscriber(_pi).Invoke(_characterName); - ImGui.SetClipboardText(base64); - } - - DrawIntro(Ipc.GetPlayerMetaManipulations.Label, "Player Meta Manipulations"); - if (ImGui.Button("Copy to Clipboard##Player")) - { - var base64 = Ipc.GetPlayerMetaManipulations.Subscriber(_pi).Invoke(); - ImGui.SetClipboardText(base64); - } - - DrawIntro(Ipc.GetGameObjectMetaManipulations.Label, "Game Object Manipulations"); - if (ImGui.Button("Copy to Clipboard##GameObject")) - { - var base64 = Ipc.GetGameObjectMetaManipulations.Subscriber(_pi).Invoke(_gameObjectIndex); - ImGui.SetClipboardText(base64); - } - } - } - - private class Mods - { - private readonly DalamudPluginInterface _pi; - - private string _modDirectory = string.Empty; - private string _modName = string.Empty; - private string _pathInput = string.Empty; - private string _newInstallPath = string.Empty; - private PenumbraApiEc _lastReloadEc; - private PenumbraApiEc _lastAddEc; - private PenumbraApiEc _lastDeleteEc; - private PenumbraApiEc _lastSetPathEc; - private PenumbraApiEc _lastInstallEc; - private IList<(string, string)> _mods = new List<(string, string)>(); - - public readonly EventSubscriber DeleteSubscriber; - public readonly EventSubscriber AddSubscriber; - public readonly EventSubscriber MoveSubscriber; - - private DateTimeOffset _lastDeletedModTime = DateTimeOffset.UnixEpoch; - private string _lastDeletedMod = string.Empty; - private DateTimeOffset _lastAddedModTime = DateTimeOffset.UnixEpoch; - private string _lastAddedMod = string.Empty; - private DateTimeOffset _lastMovedModTime = DateTimeOffset.UnixEpoch; - private string _lastMovedModFrom = string.Empty; - private string _lastMovedModTo = string.Empty; - - public Mods(DalamudPluginInterface pi) - { - _pi = pi; - DeleteSubscriber = Ipc.ModDeleted.Subscriber(pi, s => - { - _lastDeletedModTime = DateTimeOffset.UtcNow; - _lastDeletedMod = s; - }); - AddSubscriber = Ipc.ModAdded.Subscriber(pi, s => - { - _lastAddedModTime = DateTimeOffset.UtcNow; - _lastAddedMod = s; - }); - MoveSubscriber = Ipc.ModMoved.Subscriber(pi, (s1, s2) => - { - _lastMovedModTime = DateTimeOffset.UtcNow; - _lastMovedModFrom = s1; - _lastMovedModTo = s2; - }); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("Mods"); - if (!_) - return; - - ImGui.InputTextWithHint("##install", "Install File Path...", ref _newInstallPath, 100); - ImGui.InputTextWithHint("##modDir", "Mod Directory Name...", ref _modDirectory, 100); - ImGui.InputTextWithHint("##modName", "Mod Name...", ref _modName, 100); - ImGui.InputTextWithHint("##path", "New Path...", ref _pathInput, 100); - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.GetMods.Label, "Mods"); - if (ImGui.Button("Get##Mods")) - { - _mods = Ipc.GetMods.Subscriber(_pi).Invoke(); - ImGui.OpenPopup("Mods"); - } - - DrawIntro(Ipc.ReloadMod.Label, "Reload Mod"); - if (ImGui.Button("Reload")) - _lastReloadEc = Ipc.ReloadMod.Subscriber(_pi).Invoke(_modDirectory, _modName); - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastReloadEc.ToString()); - - DrawIntro(Ipc.InstallMod.Label, "Install Mod"); - if (ImGui.Button("Install")) - _lastInstallEc = Ipc.InstallMod.Subscriber(_pi).Invoke(_newInstallPath); - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastInstallEc.ToString()); - - DrawIntro(Ipc.AddMod.Label, "Add Mod"); - if (ImGui.Button("Add")) - _lastAddEc = Ipc.AddMod.Subscriber(_pi).Invoke(_modDirectory); - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastAddEc.ToString()); - - DrawIntro(Ipc.DeleteMod.Label, "Delete Mod"); - if (ImGui.Button("Delete")) - _lastDeleteEc = Ipc.DeleteMod.Subscriber(_pi).Invoke(_modDirectory, _modName); - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastDeleteEc.ToString()); - - DrawIntro(Ipc.GetModPath.Label, "Current Path"); - var (ec, path, def) = Ipc.GetModPath.Subscriber(_pi).Invoke(_modDirectory, _modName); - ImGui.TextUnformatted($"{path} ({(def ? "Custom" : "Default")}) [{ec}]"); - - DrawIntro(Ipc.SetModPath.Label, "Set Path"); - if (ImGui.Button("Set")) - _lastSetPathEc = Ipc.SetModPath.Subscriber(_pi).Invoke(_modDirectory, _modName, _pathInput); - - ImGui.SameLine(); - ImGui.TextUnformatted(_lastSetPathEc.ToString()); - - DrawIntro(Ipc.ModDeleted.Label, "Last Mod Deleted"); - if (_lastDeletedModTime > DateTimeOffset.UnixEpoch) - ImGui.TextUnformatted($"{_lastDeletedMod} at {_lastDeletedModTime}"); - - DrawIntro(Ipc.ModAdded.Label, "Last Mod Added"); - if (_lastAddedModTime > DateTimeOffset.UnixEpoch) - ImGui.TextUnformatted($"{_lastAddedMod} at {_lastAddedModTime}"); - - DrawIntro(Ipc.ModMoved.Label, "Last Mod Moved"); - if (_lastMovedModTime > DateTimeOffset.UnixEpoch) - ImGui.TextUnformatted($"{_lastMovedModFrom} -> {_lastMovedModTo} at {_lastMovedModTime}"); - - DrawModsPopup(); - } - - private void DrawModsPopup() - { - ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); - using var p = ImRaii.Popup("Mods"); - if (!p) - return; - - foreach (var (modDir, modName) in _mods) - ImGui.TextUnformatted($"{modDir}: {modName}"); - - if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) - ImGui.CloseCurrentPopup(); - } - } - - private class ModSettings - { - private readonly DalamudPluginInterface _pi; - public readonly EventSubscriber SettingChanged; - - private PenumbraApiEc _lastSettingsError = PenumbraApiEc.Success; - private ModSettingChange _lastSettingChangeType; - private string _lastSettingChangeCollection = string.Empty; - private string _lastSettingChangeMod = string.Empty; - private bool _lastSettingChangeInherited; - private DateTimeOffset _lastSettingChange; - - private string _settingsModDirectory = string.Empty; - private string _settingsModName = string.Empty; - private string _settingsCollection = string.Empty; - private bool _settingsAllowInheritance = true; - private bool _settingsInherit; - private bool _settingsEnabled; - private int _settingsPriority; - private IDictionary, GroupType)>? _availableSettings; - private IDictionary>? _currentSettings; - - public ModSettings(DalamudPluginInterface pi) - { - _pi = pi; - SettingChanged = Ipc.ModSettingChanged.Subscriber(pi, UpdateLastModSetting); - } - - public void Draw() - { - using var _ = ImRaii.TreeNode("Mod Settings"); - if (!_) - return; - - ImGui.InputTextWithHint("##settingsDir", "Mod Directory Name...", ref _settingsModDirectory, 100); - ImGui.InputTextWithHint("##settingsName", "Mod Name...", ref _settingsModName, 100); - ImGui.InputTextWithHint("##settingsCollection", "Collection...", ref _settingsCollection, 100); - ImGui.Checkbox("Allow Inheritance", ref _settingsAllowInheritance); - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro("Last Error", _lastSettingsError.ToString()); - DrawIntro(Ipc.ModSettingChanged.Label, "Last Mod Setting Changed"); - ImGui.TextUnformatted(_lastSettingChangeMod.Length > 0 - ? $"{_lastSettingChangeType} of {_lastSettingChangeMod} in {_lastSettingChangeCollection}{(_lastSettingChangeInherited ? " (Inherited)" : string.Empty)} at {_lastSettingChange}" - : "None"); - DrawIntro(Ipc.GetAvailableModSettings.Label, "Get Available Settings"); - if (ImGui.Button("Get##Available")) - { - _availableSettings = Ipc.GetAvailableModSettings.Subscriber(_pi).Invoke(_settingsModDirectory, _settingsModName); - _lastSettingsError = _availableSettings == null ? PenumbraApiEc.ModMissing : PenumbraApiEc.Success; - } - - - DrawIntro(Ipc.GetCurrentModSettings.Label, "Get Current Settings"); - if (ImGui.Button("Get##Current")) - { - var ret = Ipc.GetCurrentModSettings.Subscriber(_pi) - .Invoke(_settingsCollection, _settingsModDirectory, _settingsModName, _settingsAllowInheritance); - _lastSettingsError = ret.Item1; - if (ret.Item1 == PenumbraApiEc.Success) - { - _settingsEnabled = ret.Item2?.Item1 ?? false; - _settingsInherit = ret.Item2?.Item4 ?? false; - _settingsPriority = ret.Item2?.Item2 ?? 0; - _currentSettings = ret.Item2?.Item3; - } - else - { - _currentSettings = null; - } - } - - DrawIntro(Ipc.TryInheritMod.Label, "Inherit Mod"); - ImGui.Checkbox("##inherit", ref _settingsInherit); - ImGui.SameLine(); - if (ImGui.Button("Set##Inherit")) - _lastSettingsError = Ipc.TryInheritMod.Subscriber(_pi) - .Invoke(_settingsCollection, _settingsModDirectory, _settingsModName, _settingsInherit); - - DrawIntro(Ipc.TrySetMod.Label, "Set Enabled"); - ImGui.Checkbox("##enabled", ref _settingsEnabled); - ImGui.SameLine(); - if (ImGui.Button("Set##Enabled")) - _lastSettingsError = Ipc.TrySetMod.Subscriber(_pi) - .Invoke(_settingsCollection, _settingsModDirectory, _settingsModName, _settingsEnabled); - - DrawIntro(Ipc.TrySetModPriority.Label, "Set Priority"); - ImGui.SetNextItemWidth(200 * UiHelpers.Scale); - ImGui.DragInt("##Priority", ref _settingsPriority); - ImGui.SameLine(); - if (ImGui.Button("Set##Priority")) - _lastSettingsError = Ipc.TrySetModPriority.Subscriber(_pi) - .Invoke(_settingsCollection, _settingsModDirectory, _settingsModName, _settingsPriority); - - DrawIntro(Ipc.CopyModSettings.Label, "Copy Mod Settings"); - if (ImGui.Button("Copy Settings")) - _lastSettingsError = Ipc.CopyModSettings.Subscriber(_pi).Invoke(_settingsCollection, _settingsModDirectory, _settingsModName); - - ImGuiUtil.HoverTooltip("Copy settings from Mod Directory Name to Mod Name (as directory) in collection."); - - DrawIntro(Ipc.TrySetModSetting.Label, "Set Setting(s)"); - if (_availableSettings == null) - return; - - foreach (var (group, (list, type)) in _availableSettings) - { - using var id = ImRaii.PushId(group); - var preview = list.Count > 0 ? list[0] : string.Empty; - IList current; - if (_currentSettings != null && _currentSettings.TryGetValue(group, out current!) && current.Count > 0) - { - preview = current[0]; - } - else - { - current = new List(); - if (_currentSettings != null) - _currentSettings[group] = current; - } - - ImGui.SetNextItemWidth(200 * UiHelpers.Scale); - using (var c = ImRaii.Combo("##group", preview)) - { - if (c) - foreach (var s in list) - { - var contained = current.Contains(s); - if (ImGui.Checkbox(s, ref contained)) - { - if (contained) - current.Add(s); - else - current.Remove(s); - } - } - } - - ImGui.SameLine(); - if (ImGui.Button("Set##setting")) - { - if (type == GroupType.Single) - _lastSettingsError = Ipc.TrySetModSetting.Subscriber(_pi).Invoke(_settingsCollection, - _settingsModDirectory, _settingsModName, group, current.Count > 0 ? current[0] : string.Empty); - else - _lastSettingsError = Ipc.TrySetModSettings.Subscriber(_pi).Invoke(_settingsCollection, - _settingsModDirectory, _settingsModName, group, current.ToArray()); - } - - ImGui.SameLine(); - ImGui.TextUnformatted(group); - } - } - - private void UpdateLastModSetting(ModSettingChange type, string collection, string mod, bool inherited) - { - _lastSettingChangeType = type; - _lastSettingChangeCollection = collection; - _lastSettingChangeMod = mod; - _lastSettingChangeInherited = inherited; - _lastSettingChange = DateTimeOffset.Now; - } - } - - private class Editing - { - private readonly DalamudPluginInterface _pi; - - private string _inputPath = string.Empty; - private string _inputPath2 = string.Empty; - private string _outputPath = string.Empty; - private string _outputPath2 = string.Empty; - - private TextureType _typeSelector; - private bool _mipMaps = true; - - private Task? _task1; - private Task? _task2; - - public Editing(DalamudPluginInterface pi) - => _pi = pi; - - public void Draw() - { - using var _ = ImRaii.TreeNode("Editing"); - if (!_) - return; - - ImGui.InputTextWithHint("##inputPath", "Input Texture Path...", ref _inputPath, 256); - ImGui.InputTextWithHint("##outputPath", "Output Texture Path...", ref _outputPath, 256); - ImGui.InputTextWithHint("##inputPath2", "Input Texture Path 2...", ref _inputPath2, 256); - ImGui.InputTextWithHint("##outputPath2", "Output Texture Path 2...", ref _outputPath2, 256); - TypeCombo(); - ImGui.Checkbox("Add MipMaps", ref _mipMaps); - - using var table = ImRaii.Table("...", 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.ConvertTextureFile.Label, "Convert Texture 1"); - if (ImGuiUtil.DrawDisabledButton("Save 1", Vector2.Zero, string.Empty, _task1 is { IsCompleted: false })) - _task1 = Ipc.ConvertTextureFile.Subscriber(_pi).Invoke(_inputPath, _outputPath, _typeSelector, _mipMaps); - ImGui.SameLine(); - ImGui.TextUnformatted(_task1 == null ? "Not Initiated" : _task1.Status.ToString()); - if (ImGui.IsItemHovered() && _task1?.Status == TaskStatus.Faulted) - ImGui.SetTooltip(_task1.Exception?.ToString()); - - DrawIntro(Ipc.ConvertTextureFile.Label, "Convert Texture 2"); - if (ImGuiUtil.DrawDisabledButton("Save 2", Vector2.Zero, string.Empty, _task2 is { IsCompleted: false })) - _task2 = Ipc.ConvertTextureFile.Subscriber(_pi).Invoke(_inputPath2, _outputPath2, _typeSelector, _mipMaps); - ImGui.SameLine(); - ImGui.TextUnformatted(_task2 == null ? "Not Initiated" : _task2.Status.ToString()); - if (ImGui.IsItemHovered() && _task2?.Status == TaskStatus.Faulted) - ImGui.SetTooltip(_task2.Exception?.ToString()); - } - - private void TypeCombo() - { - using var combo = ImRaii.Combo("Convert To", _typeSelector.ToString()); - if (!combo) - return; - - foreach (var value in Enum.GetValues()) - { - if (ImGui.Selectable(value.ToString(), _typeSelector == value)) - _typeSelector = value; - } - } - } - - private class Temporary - { - private readonly DalamudPluginInterface _pi; - private readonly ModManager _modManager; - private readonly CollectionManager _collections; - private readonly TempModManager _tempMods; - private readonly TempCollectionManager _tempCollections; - private readonly SaveService _saveService; - private readonly Configuration _config; - - public Temporary(DalamudPluginInterface pi, ModManager modManager, CollectionManager collections, TempModManager tempMods, - TempCollectionManager tempCollections, SaveService saveService, Configuration config) - { - _pi = pi; - _modManager = modManager; - _collections = collections; - _tempMods = tempMods; - _tempCollections = tempCollections; - _saveService = saveService; - _config = config; - } - - public string LastCreatedCollectionName = string.Empty; - - private string _tempCollectionName = string.Empty; - private string _tempCharacterName = string.Empty; - private string _tempModName = string.Empty; - private string _tempGamePath = "test/game/path.mtrl"; - private string _tempFilePath = "test/success.mtrl"; - private string _tempManipulation = string.Empty; - private PenumbraApiEc _lastTempError; - private int _tempActorIndex; - private bool _forceOverwrite; - - public void Draw() - { - using var _ = ImRaii.TreeNode("Temporary"); - if (!_) - return; - - ImGui.InputTextWithHint("##tempCollection", "Collection Name...", ref _tempCollectionName, 128); - ImGui.InputTextWithHint("##tempCollectionChar", "Collection Character...", ref _tempCharacterName, 32); - ImGui.InputInt("##tempActorIndex", ref _tempActorIndex, 0, 0); - ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); - ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); - ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); - ImGui.InputTextWithHint("##tempManip", "Manipulation Base64 String...", ref _tempManipulation, 256); - ImGui.Checkbox("Force Character Collection Overwrite", ref _forceOverwrite); - - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro("Last Error", _lastTempError.ToString()); - DrawIntro("Last Created Collection", LastCreatedCollectionName); - DrawIntro(Ipc.CreateTemporaryCollection.Label, "Create Temporary Collection"); -#pragma warning disable 0612 - if (ImGui.Button("Create##Collection")) - (_lastTempError, LastCreatedCollectionName) = Ipc.CreateTemporaryCollection.Subscriber(_pi) - .Invoke(_tempCollectionName, _tempCharacterName, _forceOverwrite); - - DrawIntro(Ipc.CreateNamedTemporaryCollection.Label, "Create Named Temporary Collection"); - if (ImGui.Button("Create##NamedCollection")) - _lastTempError = Ipc.CreateNamedTemporaryCollection.Subscriber(_pi).Invoke(_tempCollectionName); - - DrawIntro(Ipc.RemoveTemporaryCollection.Label, "Remove Temporary Collection from Character"); - if (ImGui.Button("Delete##Collection")) - _lastTempError = Ipc.RemoveTemporaryCollection.Subscriber(_pi).Invoke(_tempCharacterName); -#pragma warning restore 0612 - DrawIntro(Ipc.RemoveTemporaryCollectionByName.Label, "Remove Temporary Collection"); - if (ImGui.Button("Delete##NamedCollection")) - _lastTempError = Ipc.RemoveTemporaryCollectionByName.Subscriber(_pi).Invoke(_tempCollectionName); - - DrawIntro(Ipc.AssignTemporaryCollection.Label, "Assign Temporary Collection"); - if (ImGui.Button("Assign##NamedCollection")) - _lastTempError = Ipc.AssignTemporaryCollection.Subscriber(_pi).Invoke(_tempCollectionName, _tempActorIndex, _forceOverwrite); - - DrawIntro(Ipc.AddTemporaryMod.Label, "Add Temporary Mod to specific Collection"); - if (ImGui.Button("Add##Mod")) - _lastTempError = Ipc.AddTemporaryMod.Subscriber(_pi).Invoke(_tempModName, _tempCollectionName, - new Dictionary { { _tempGamePath, _tempFilePath } }, - _tempManipulation.Length > 0 ? _tempManipulation : string.Empty, int.MaxValue); - - DrawIntro(Ipc.CreateTemporaryCollection.Label, "Copy Existing Collection"); - if (ImGuiUtil.DrawDisabledButton("Copy##Collection", Vector2.Zero, - "Copies the effective list from the collection named in Temporary Mod Name...", - !_collections.Storage.ByName(_tempModName, out var copyCollection)) - && copyCollection is { HasCache: true }) - { - var files = copyCollection.ResolvedFiles.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.Path.ToString()); - var manips = Functions.ToCompressedBase64(copyCollection.MetaCache?.Manipulations.ToArray() ?? Array.Empty(), - MetaManipulation.CurrentVersion); - _lastTempError = Ipc.AddTemporaryMod.Subscriber(_pi).Invoke(_tempModName, _tempCollectionName, files, manips, 999); - } - - DrawIntro(Ipc.AddTemporaryModAll.Label, "Add Temporary Mod to all Collections"); - if (ImGui.Button("Add##All")) - _lastTempError = Ipc.AddTemporaryModAll.Subscriber(_pi).Invoke(_tempModName, - new Dictionary { { _tempGamePath, _tempFilePath } }, - _tempManipulation.Length > 0 ? _tempManipulation : string.Empty, int.MaxValue); - - DrawIntro(Ipc.RemoveTemporaryMod.Label, "Remove Temporary Mod from specific Collection"); - if (ImGui.Button("Remove##Mod")) - _lastTempError = Ipc.RemoveTemporaryMod.Subscriber(_pi).Invoke(_tempModName, _tempCollectionName, int.MaxValue); - - DrawIntro(Ipc.RemoveTemporaryModAll.Label, "Remove Temporary Mod from all Collections"); - if (ImGui.Button("Remove##ModAll")) - _lastTempError = Ipc.RemoveTemporaryModAll.Subscriber(_pi).Invoke(_tempModName, int.MaxValue); - } - - public void DrawCollections() - { - using var collTree = ImRaii.TreeNode("Temporary Collections##TempCollections"); - if (!collTree) - return; - - using var table = ImRaii.Table("##collTree", 5); - if (!table) - return; - - foreach (var collection in _tempCollections.Values) - { - ImGui.TableNextColumn(); - var character = _tempCollections.Collections.Where(p => p.Collection == collection).Select(p => p.DisplayName) - .FirstOrDefault() - ?? "Unknown"; - if (ImGui.Button($"Save##{collection.Name}")) - TemporaryMod.SaveTempCollection(_config, _saveService, _modManager, collection, character); - - ImGuiUtil.DrawTableColumn(collection.Name); - ImGuiUtil.DrawTableColumn(collection.ResolvedFiles.Count.ToString()); - ImGuiUtil.DrawTableColumn(collection.MetaCache?.Count.ToString() ?? "0"); - ImGuiUtil.DrawTableColumn(string.Join(", ", - _tempCollections.Collections.Where(p => p.Collection == collection).Select(c => c.DisplayName))); - } - } - - public void DrawMods() - { - using var modTree = ImRaii.TreeNode("Temporary Mods##TempMods"); - if (!modTree) - return; - - using var table = ImRaii.Table("##modTree", 5); - - void PrintList(string collectionName, IReadOnlyList list) - { - foreach (var mod in list) - { - ImGui.TableNextColumn(); - ImGui.TextUnformatted(mod.Name); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(mod.Priority.ToString()); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(collectionName); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(mod.Default.Files.Count.ToString()); - if (ImGui.IsItemHovered()) - { - using var tt = ImRaii.Tooltip(); - foreach (var (path, file) in mod.Default.Files) - ImGui.TextUnformatted($"{path} -> {file}"); - } - - ImGui.TableNextColumn(); - ImGui.TextUnformatted(mod.TotalManipulations.ToString()); - if (ImGui.IsItemHovered()) - { - using var tt = ImRaii.Tooltip(); - foreach (var manip in mod.Default.Manipulations) - ImGui.TextUnformatted(manip.ToString()); - } - } - } - - if (table) - { - PrintList("All", _tempMods.ModsForAllCollections); - foreach (var (collection, list) in _tempMods.Mods) - PrintList(collection.Name, list); - } - } - } - - private class ResourceTree(DalamudPluginInterface pi, ObjectManager objects) - { - private readonly Stopwatch _stopwatch = new(); - - private string _gameObjectIndices = "0"; - private ResourceType _type = ResourceType.Mtrl; - private bool _withUiData; - - private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcePaths; - private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcePaths; - private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcesOfType; - private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcesOfType; - private (string, Ipc.ResourceTree?)[]? _lastGameObjectResourceTrees; - private (string, Ipc.ResourceTree)[]? _lastPlayerResourceTrees; - private TimeSpan _lastCallDuration; - - public void Draw() - { - using var _ = ImRaii.TreeNode("Resource Tree"); - if (!_) - return; - - ImGui.InputText("GameObject indices", ref _gameObjectIndices, 511); - ImGuiUtil.GenericEnumCombo("Resource type", ImGui.CalcItemWidth(), _type, out _type, Enum.GetValues()); - ImGui.Checkbox("Also get names and icons", ref _withUiData); - - using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - DrawIntro(Ipc.GetGameObjectResourcePaths.Label, "Get GameObject resource paths"); - if (ImGui.Button("Get##GameObjectResourcePaths")) - { - var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourcePaths.Subscriber(pi); - _stopwatch.Restart(); - var resourcePaths = subscriber.Invoke(gameObjects); - - _lastCallDuration = _stopwatch.Elapsed; - _lastGameObjectResourcePaths = gameObjects - .Select(i => GameObjectToString(i)) - .Zip(resourcePaths) - .ToArray(); - - ImGui.OpenPopup(nameof(Ipc.GetGameObjectResourcePaths)); - } - - DrawIntro(Ipc.GetPlayerResourcePaths.Label, "Get local player resource paths"); - if (ImGui.Button("Get##PlayerResourcePaths")) - { - var subscriber = Ipc.GetPlayerResourcePaths.Subscriber(pi); - _stopwatch.Restart(); - var resourcePaths = subscriber.Invoke(); - - _lastCallDuration = _stopwatch.Elapsed; - _lastPlayerResourcePaths = resourcePaths - .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) - .ToArray(); - - ImGui.OpenPopup(nameof(Ipc.GetPlayerResourcePaths)); - } - - DrawIntro(Ipc.GetGameObjectResourcesOfType.Label, "Get GameObject resources of type"); - if (ImGui.Button("Get##GameObjectResourcesOfType")) - { - var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourcesOfType.Subscriber(pi); - _stopwatch.Restart(); - var resourcesOfType = subscriber.Invoke(_type, _withUiData, gameObjects); - - _lastCallDuration = _stopwatch.Elapsed; - _lastGameObjectResourcesOfType = gameObjects - .Select(i => GameObjectToString(i)) - .Zip(resourcesOfType) - .ToArray(); - - ImGui.OpenPopup(nameof(Ipc.GetGameObjectResourcesOfType)); - } - - DrawIntro(Ipc.GetPlayerResourcesOfType.Label, "Get local player resources of type"); - if (ImGui.Button("Get##PlayerResourcesOfType")) - { - var subscriber = Ipc.GetPlayerResourcesOfType.Subscriber(pi); - _stopwatch.Restart(); - var resourcesOfType = subscriber.Invoke(_type, _withUiData); - - _lastCallDuration = _stopwatch.Elapsed; - _lastPlayerResourcesOfType = resourcesOfType - .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) - .ToArray(); - - ImGui.OpenPopup(nameof(Ipc.GetPlayerResourcesOfType)); - } - - DrawIntro(Ipc.GetGameObjectResourceTrees.Label, "Get GameObject resource trees"); - if (ImGui.Button("Get##GameObjectResourceTrees")) - { - var gameObjects = GetSelectedGameObjects(); - var subscriber = Ipc.GetGameObjectResourceTrees.Subscriber(pi); - _stopwatch.Restart(); - var trees = subscriber.Invoke(_withUiData, gameObjects); - - _lastCallDuration = _stopwatch.Elapsed; - _lastGameObjectResourceTrees = gameObjects - .Select(i => GameObjectToString(i)) - .Zip(trees) - .ToArray(); - - ImGui.OpenPopup(nameof(Ipc.GetGameObjectResourceTrees)); - } - - DrawIntro(Ipc.GetPlayerResourceTrees.Label, "Get local player resource trees"); - if (ImGui.Button("Get##PlayerResourceTrees")) - { - var subscriber = Ipc.GetPlayerResourceTrees.Subscriber(pi); - _stopwatch.Restart(); - var trees = subscriber.Invoke(_withUiData); - - _lastCallDuration = _stopwatch.Elapsed; - _lastPlayerResourceTrees = trees - .Select(pair => (GameObjectToString(pair.Key), pair.Value)) - .ToArray(); - - ImGui.OpenPopup(nameof(Ipc.GetPlayerResourceTrees)); - } - - DrawPopup(nameof(Ipc.GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths, _lastCallDuration); - DrawPopup(nameof(Ipc.GetPlayerResourcePaths), ref _lastPlayerResourcePaths, DrawResourcePaths, _lastCallDuration); - - DrawPopup(nameof(Ipc.GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType, _lastCallDuration); - DrawPopup(nameof(Ipc.GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, _lastCallDuration); - - DrawPopup(nameof(Ipc.GetGameObjectResourceTrees), ref _lastGameObjectResourceTrees, DrawResourceTrees, _lastCallDuration); - DrawPopup(nameof(Ipc.GetPlayerResourceTrees), ref _lastPlayerResourceTrees, DrawResourceTrees!, _lastCallDuration); - } - - private static void DrawPopup(string popupId, ref T? result, Action drawResult, TimeSpan duration) where T : class - { - ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(1000, 500)); - using var popup = ImRaii.Popup(popupId); - if (!popup) - { - result = null; - return; - } - - if (result == null) - { - ImGui.CloseCurrentPopup(); - return; - } - - drawResult(result); - - ImGui.TextUnformatted($"Invoked in {duration.TotalMilliseconds} ms"); - - if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) - { - result = null; - ImGui.CloseCurrentPopup(); - } - } - - private static void DrawWithHeaders((string, T?)[] result, Action drawItem) where T : class - { - var firstSeen = new Dictionary(); - foreach (var (label, item) in result) - { - if (item == null) - { - ImRaii.TreeNode($"{label}: null", ImGuiTreeNodeFlags.Leaf).Dispose(); - continue; - } - - if (firstSeen.TryGetValue(item, out var firstLabel)) - { - ImRaii.TreeNode($"{label}: same as {firstLabel}", ImGuiTreeNodeFlags.Leaf).Dispose(); - continue; - } - - firstSeen.Add(item, label); - - using var header = ImRaii.TreeNode(label); - if (!header) - continue; - - drawItem(item); - } - } - - private static void DrawResourcePaths((string, IReadOnlyDictionary?)[] result) - { - DrawWithHeaders(result, paths => - { - using var table = ImRaii.Table(string.Empty, 2, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.6f); - ImGui.TableSetupColumn("Game Paths", ImGuiTableColumnFlags.WidthStretch, 0.4f); - ImGui.TableHeadersRow(); - - foreach (var (actualPath, gamePaths) in paths) - { - ImGui.TableNextColumn(); - ImGui.TextUnformatted(actualPath); - ImGui.TableNextColumn(); - foreach (var gamePath in gamePaths) - ImGui.TextUnformatted(gamePath); - } - }); - } - - private void DrawResourcesOfType((string, IReadOnlyDictionary?)[] result) - { - DrawWithHeaders(result, resources => - { - using var table = ImRaii.Table(string.Empty, _withUiData ? 3 : 2, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.15f); - ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUiData ? 0.55f : 0.85f); - if (_withUiData) - ImGui.TableSetupColumn("Icon & Name", ImGuiTableColumnFlags.WidthStretch, 0.3f); - ImGui.TableHeadersRow(); - - foreach (var (resourceHandle, (actualPath, name, icon)) in resources) - { - ImGui.TableNextColumn(); - TextUnformattedMono($"0x{resourceHandle:X}"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(actualPath); - if (_withUiData) - { - ImGui.TableNextColumn(); - TextUnformattedMono(icon.ToString()); - ImGui.SameLine(); - ImGui.TextUnformatted(name); - } - } - }); - } - - private void DrawResourceTrees((string, Ipc.ResourceTree?)[] result) - { - DrawWithHeaders(result, tree => - { - ImGui.TextUnformatted($"Name: {tree.Name}\nRaceCode: {(GenderRace)tree.RaceCode}"); - - using var table = ImRaii.Table(string.Empty, _withUiData ? 7 : 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.Resizable); - if (!table) - return; - - if (_withUiData) - { - ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch, 0.5f); - ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.1f); - ImGui.TableSetupColumn("Icon", ImGuiTableColumnFlags.WidthStretch, 0.15f); - } - else - { - ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.5f); - } - - ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); - ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); - ImGui.TableSetupColumn("Object Address", ImGuiTableColumnFlags.WidthStretch, 0.2f); - ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.2f); - ImGui.TableHeadersRow(); - - void DrawNode(Ipc.ResourceNode node) - { - ImGui.TableNextRow(); - ImGui.TableNextColumn(); - var hasChildren = node.Children.Any(); - using var treeNode = ImRaii.TreeNode( - $"{(_withUiData ? node.Name ?? "Unknown" : node.Type)}##{node.ObjectAddress:X8}", - hasChildren - ? ImGuiTreeNodeFlags.SpanFullWidth - : ImGuiTreeNodeFlags.SpanFullWidth | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen); - if (_withUiData) - { - ImGui.TableNextColumn(); - TextUnformattedMono(node.Type.ToString()); - ImGui.TableNextColumn(); - TextUnformattedMono(node.Icon.ToString()); - } - - ImGui.TableNextColumn(); - ImGui.TextUnformatted(node.GamePath ?? "Unknown"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(node.ActualPath); - ImGui.TableNextColumn(); - TextUnformattedMono($"0x{node.ObjectAddress:X8}"); - ImGui.TableNextColumn(); - TextUnformattedMono($"0x{node.ResourceHandle:X8}"); - - if (treeNode) - foreach (var child in node.Children) - DrawNode(child); - } - - foreach (var node in tree.Nodes) - DrawNode(node); - }); - } - - private static void TextUnformattedMono(string text) - { - using var _ = ImRaii.PushFont(UiBuilder.MonoFont); - ImGui.TextUnformatted(text); - } - - private ushort[] GetSelectedGameObjects() - => _gameObjectIndices.Split(',') - .SelectWhere(index => (ushort.TryParse(index.Trim(), out var i), i)) - .ToArray(); - - private unsafe string GameObjectToString(ObjectIndex gameObjectIndex) - { - var gameObject = objects[gameObjectIndex]; - - return gameObject.Valid - ? $"[{gameObjectIndex}] {gameObject.Utf8Name} ({(ObjectKind)gameObject.AsObject->ObjectKind})" - : $"[{gameObjectIndex}] null"; - } - } -} diff --git a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs new file mode 100644 index 00000000..12314f0c --- /dev/null +++ b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs @@ -0,0 +1,166 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility; +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.IpcSubscribers; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Enums; +using ImGuiClip = OtterGui.ImGuiClip; + +namespace Penumbra.Api.IpcTester; + +public class CollectionsIpcTester(DalamudPluginInterface pi) : IUiService +{ + private int _objectIdx; + private string _collectionIdString = string.Empty; + private Guid? _collectionId = null; + private bool _allowCreation = true; + private bool _allowDeletion = true; + private ApiCollectionType _type = ApiCollectionType.Yourself; + + private Dictionary _collections = []; + private (string, ChangedItemType, uint)[] _changedItems = []; + private PenumbraApiEc _returnCode = PenumbraApiEc.Success; + private (Guid Id, string Name)? _oldCollection; + + public void Draw() + { + using var _ = ImRaii.TreeNode("Collections"); + if (!_) + return; + + ImGuiUtil.GenericEnumCombo("Collection Type", 200, _type, out _type, t => ((CollectionType)t).ToName()); + ImGui.InputInt("Object Index##Collections", ref _objectIdx, 0, 0); + ImGuiUtil.GuidInput("Collection Id##Collections", "Collection GUID...", string.Empty, ref _collectionId, ref _collectionIdString); + ImGui.Checkbox("Allow Assignment Creation", ref _allowCreation); + ImGui.SameLine(); + ImGui.Checkbox("Allow Assignment Deletion", ref _allowDeletion); + + using var table = ImRaii.Table(string.Empty, 4, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro("Last Return Code", _returnCode.ToString()); + if (_oldCollection != null) + ImGui.TextUnformatted(!_oldCollection.HasValue ? "Created" : _oldCollection.ToString()); + + IpcTester.DrawIntro(GetCollection.Label, "Current Collection"); + DrawCollection(new GetCollection(pi).Invoke(ApiCollectionType.Current)); + + IpcTester.DrawIntro(GetCollection.Label, "Default Collection"); + DrawCollection(new GetCollection(pi).Invoke(ApiCollectionType.Default)); + + IpcTester.DrawIntro(GetCollection.Label, "Interface Collection"); + DrawCollection(new GetCollection(pi).Invoke(ApiCollectionType.Interface)); + + IpcTester.DrawIntro(GetCollection.Label, "Special Collection"); + DrawCollection(new GetCollection(pi).Invoke(_type)); + + IpcTester.DrawIntro(GetCollections.Label, "Collections"); + DrawCollectionPopup(); + if (ImGui.Button("Get##Collections")) + { + _collections = new GetCollections(pi).Invoke(); + ImGui.OpenPopup("Collections"); + } + + IpcTester.DrawIntro(GetCollectionForObject.Label, "Get Object Collection"); + var (valid, individual, effectiveCollection) = new GetCollectionForObject(pi).Invoke(_objectIdx); + DrawCollection(effectiveCollection); + ImGui.SameLine(); + ImGui.TextUnformatted($"({(valid ? "Valid" : "Invalid")} Object{(individual ? ", Individual Assignment)" : ")")}"); + + IpcTester.DrawIntro(SetCollection.Label, "Set Special Collection"); + if (ImGui.Button("Set##SpecialCollection")) + (_returnCode, _oldCollection) = + new SetCollection(pi).Invoke(_type, _collectionId.GetValueOrDefault(Guid.Empty), _allowCreation, _allowDeletion); + ImGui.TableNextColumn(); + if (ImGui.Button("Remove##SpecialCollection")) + (_returnCode, _oldCollection) = new SetCollection(pi).Invoke(_type, null, _allowCreation, _allowDeletion); + + IpcTester.DrawIntro(SetCollectionForObject.Label, "Set Object Collection"); + if (ImGui.Button("Set##ObjectCollection")) + (_returnCode, _oldCollection) = new SetCollectionForObject(pi).Invoke(_objectIdx, _collectionId.GetValueOrDefault(Guid.Empty), + _allowCreation, _allowDeletion); + ImGui.TableNextColumn(); + if (ImGui.Button("Remove##ObjectCollection")) + (_returnCode, _oldCollection) = new SetCollectionForObject(pi).Invoke(_objectIdx, null, _allowCreation, _allowDeletion); + + IpcTester.DrawIntro(GetChangedItemsForCollection.Label, "Changed Item List"); + DrawChangedItemPopup(); + if (ImGui.Button("Get##ChangedItems")) + { + var items = new GetChangedItemsForCollection(pi).Invoke(_collectionId.GetValueOrDefault(Guid.Empty)); + _changedItems = items.Select(kvp => + { + var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(kvp.Value); + return (kvp.Key, type, id); + }).ToArray(); + ImGui.OpenPopup("Changed Item List"); + } + } + + private void DrawChangedItemPopup() + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); + using var p = ImRaii.Popup("Changed Item List"); + if (!p) + return; + + using (var t = ImRaii.Table("##ChangedItems", 3, ImGuiTableFlags.SizingFixedFit)) + { + if (t) + ImGuiClip.ClippedDraw(_changedItems, t => + { + ImGuiUtil.DrawTableColumn(t.Item1); + ImGuiUtil.DrawTableColumn(t.Item2.ToString()); + ImGuiUtil.DrawTableColumn(t.Item3.ToString()); + }, ImGui.GetTextLineHeightWithSpacing()); + } + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + ImGui.CloseCurrentPopup(); + } + + private void DrawCollectionPopup() + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); + using var p = ImRaii.Popup("Collections"); + if (!p) + return; + + using (var t = ImRaii.Table("collections", 2, ImGuiTableFlags.SizingFixedFit)) + { + if (t) + foreach (var collection in _collections) + { + ImGui.TableNextColumn(); + DrawCollection((collection.Key, collection.Value)); + } + } + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + ImGui.CloseCurrentPopup(); + } + + private static void DrawCollection((Guid Id, string Name)? collection) + { + if (collection == null) + { + ImGui.TextUnformatted(""); + ImGui.TableNextColumn(); + return; + } + + ImGui.TextUnformatted(collection.Value.Name); + ImGui.TableNextColumn(); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImGuiUtil.CopyOnClickSelectable(collection.Value.Id.ToString()); + } + } +} diff --git a/Penumbra/Api/IpcTester/EditingIpcTester.cs b/Penumbra/Api/IpcTester/EditingIpcTester.cs new file mode 100644 index 00000000..94b1e4e8 --- /dev/null +++ b/Penumbra/Api/IpcTester/EditingIpcTester.cs @@ -0,0 +1,70 @@ +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.IpcSubscribers; + +namespace Penumbra.Api.IpcTester; + +public class EditingIpcTester(DalamudPluginInterface pi) : IUiService +{ + private string _inputPath = string.Empty; + private string _inputPath2 = string.Empty; + private string _outputPath = string.Empty; + private string _outputPath2 = string.Empty; + + private TextureType _typeSelector; + private bool _mipMaps = true; + + private Task? _task1; + private Task? _task2; + + public void Draw() + { + using var _ = ImRaii.TreeNode("Editing"); + if (!_) + return; + + ImGui.InputTextWithHint("##inputPath", "Input Texture Path...", ref _inputPath, 256); + ImGui.InputTextWithHint("##outputPath", "Output Texture Path...", ref _outputPath, 256); + ImGui.InputTextWithHint("##inputPath2", "Input Texture Path 2...", ref _inputPath2, 256); + ImGui.InputTextWithHint("##outputPath2", "Output Texture Path 2...", ref _outputPath2, 256); + TypeCombo(); + ImGui.Checkbox("Add MipMaps", ref _mipMaps); + + using var table = ImRaii.Table("...", 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(ConvertTextureFile.Label, (string)"Convert Texture 1"); + if (ImGuiUtil.DrawDisabledButton("Save 1", Vector2.Zero, string.Empty, _task1 is { IsCompleted: false })) + _task1 = new ConvertTextureFile(pi).Invoke(_inputPath, _outputPath, _typeSelector, _mipMaps); + ImGui.SameLine(); + ImGui.TextUnformatted(_task1 == null ? "Not Initiated" : _task1.Status.ToString()); + if (ImGui.IsItemHovered() && _task1?.Status == TaskStatus.Faulted) + ImGui.SetTooltip(_task1.Exception?.ToString()); + + IpcTester.DrawIntro(ConvertTextureFile.Label, (string)"Convert Texture 2"); + if (ImGuiUtil.DrawDisabledButton("Save 2", Vector2.Zero, string.Empty, _task2 is { IsCompleted: false })) + _task2 = new ConvertTextureFile(pi).Invoke(_inputPath2, _outputPath2, _typeSelector, _mipMaps); + ImGui.SameLine(); + ImGui.TextUnformatted(_task2 == null ? "Not Initiated" : _task2.Status.ToString()); + if (ImGui.IsItemHovered() && _task2?.Status == TaskStatus.Faulted) + ImGui.SetTooltip(_task2.Exception?.ToString()); + } + + private void TypeCombo() + { + using var combo = ImRaii.Combo("Convert To", _typeSelector.ToString()); + if (!combo) + return; + + foreach (var value in Enum.GetValues()) + { + if (ImGui.Selectable(value.ToString(), _typeSelector == value)) + _typeSelector = value; + } + } +} diff --git a/Penumbra/Api/IpcTester/GameStateIpcTester.cs b/Penumbra/Api/IpcTester/GameStateIpcTester.cs new file mode 100644 index 00000000..2c41b882 --- /dev/null +++ b/Penumbra/Api/IpcTester/GameStateIpcTester.cs @@ -0,0 +1,137 @@ +using Dalamud.Interface; +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; +using Penumbra.String; + +namespace Penumbra.Api.IpcTester; + +public class GameStateIpcTester : IUiService, IDisposable +{ + private readonly DalamudPluginInterface _pi; + public readonly EventSubscriber CharacterBaseCreating; + public readonly EventSubscriber CharacterBaseCreated; + public readonly EventSubscriber GameObjectResourcePathResolved; + + private string _lastCreatedGameObjectName = string.Empty; + private nint _lastCreatedDrawObject = nint.Zero; + private DateTimeOffset _lastCreatedGameObjectTime = DateTimeOffset.MaxValue; + private string _lastResolvedGamePath = string.Empty; + private string _lastResolvedFullPath = string.Empty; + private string _lastResolvedObject = string.Empty; + private DateTimeOffset _lastResolvedGamePathTime = DateTimeOffset.MaxValue; + private string _currentDrawObjectString = string.Empty; + private nint _currentDrawObject = nint.Zero; + private int _currentCutsceneActor; + private int _currentCutsceneParent; + private PenumbraApiEc _cutsceneError = PenumbraApiEc.Success; + + public GameStateIpcTester(DalamudPluginInterface pi) + { + _pi = pi; + CharacterBaseCreating = CreatingCharacterBase.Subscriber(pi, UpdateLastCreated); + CharacterBaseCreated = CreatedCharacterBase.Subscriber(pi, UpdateLastCreated2); + GameObjectResourcePathResolved = IpcSubscribers.GameObjectResourcePathResolved.Subscriber(pi, UpdateGameObjectResourcePath); + } + + public void Dispose() + { + CharacterBaseCreating.Dispose(); + CharacterBaseCreated.Dispose(); + GameObjectResourcePathResolved.Dispose(); + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("Game State"); + if (!_) + return; + + if (ImGui.InputTextWithHint("##drawObject", "Draw Object Address..", ref _currentDrawObjectString, 16, + ImGuiInputTextFlags.CharsHexadecimal)) + _currentDrawObject = nint.TryParse(_currentDrawObjectString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, + out var tmp) + ? tmp + : nint.Zero; + + ImGui.InputInt("Cutscene Actor", ref _currentCutsceneActor, 0); + ImGui.InputInt("Cutscene Parent", ref _currentCutsceneParent, 0); + if (_cutsceneError is not PenumbraApiEc.Success) + { + ImGui.SameLine(); + ImGui.TextUnformatted("Invalid Argument on last Call"); + } + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(GetDrawObjectInfo.Label, "Draw Object Info"); + if (_currentDrawObject == nint.Zero) + { + ImGui.TextUnformatted("Invalid"); + } + else + { + var (ptr, (collectionId, collectionName)) = new GetDrawObjectInfo(_pi).Invoke(_currentDrawObject); + ImGui.TextUnformatted(ptr == nint.Zero ? $"No Actor Associated, {collectionName}" : $"{ptr:X}, {collectionName}"); + ImGui.SameLine(); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImGui.TextUnformatted(collectionId.ToString()); + } + } + + IpcTester.DrawIntro(GetCutsceneParentIndex.Label, "Cutscene Parent"); + ImGui.TextUnformatted(new GetCutsceneParentIndex(_pi).Invoke(_currentCutsceneActor).ToString()); + + IpcTester.DrawIntro(SetCutsceneParentIndex.Label, "Cutscene Parent"); + if (ImGui.Button("Set Parent")) + _cutsceneError = new SetCutsceneParentIndex(_pi) + .Invoke(_currentCutsceneActor, _currentCutsceneParent); + + IpcTester.DrawIntro(CreatingCharacterBase.Label, "Last Drawobject created"); + if (_lastCreatedGameObjectTime < DateTimeOffset.Now) + ImGui.TextUnformatted(_lastCreatedDrawObject != nint.Zero + ? $"0x{_lastCreatedDrawObject:X} for <{_lastCreatedGameObjectName}> at {_lastCreatedGameObjectTime}" + : $"NULL for <{_lastCreatedGameObjectName}> at {_lastCreatedGameObjectTime}"); + + IpcTester.DrawIntro(IpcSubscribers.GameObjectResourcePathResolved.Label, "Last GamePath resolved"); + if (_lastResolvedGamePathTime < DateTimeOffset.Now) + ImGui.TextUnformatted( + $"{_lastResolvedGamePath} -> {_lastResolvedFullPath} for <{_lastResolvedObject}> at {_lastResolvedGamePathTime}"); + } + + private void UpdateLastCreated(nint gameObject, Guid _, nint _2, nint _3, nint _4) + { + _lastCreatedGameObjectName = GetObjectName(gameObject); + _lastCreatedGameObjectTime = DateTimeOffset.Now; + _lastCreatedDrawObject = nint.Zero; + } + + private void UpdateLastCreated2(nint gameObject, Guid _, nint drawObject) + { + _lastCreatedGameObjectName = GetObjectName(gameObject); + _lastCreatedGameObjectTime = DateTimeOffset.Now; + _lastCreatedDrawObject = drawObject; + } + + private void UpdateGameObjectResourcePath(nint gameObject, string gamePath, string fullPath) + { + _lastResolvedObject = GetObjectName(gameObject); + _lastResolvedGamePath = gamePath; + _lastResolvedFullPath = fullPath; + _lastResolvedGamePathTime = DateTimeOffset.Now; + } + + private static unsafe string GetObjectName(nint gameObject) + { + var obj = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)gameObject; + var name = obj != null ? obj->Name : null; + return name != null && *name != 0 ? new ByteString(name).ToString() : "Unknown"; + } +} diff --git a/Penumbra/Api/IpcTester/IpcTester.cs b/Penumbra/Api/IpcTester/IpcTester.cs new file mode 100644 index 00000000..201e7068 --- /dev/null +++ b/Penumbra/Api/IpcTester/IpcTester.cs @@ -0,0 +1,133 @@ +using Dalamud.Plugin.Services; +using FFXIVClientStructs.FFXIV.Client.System.Framework; +using ImGuiNET; +using OtterGui.Services; +using Penumbra.Api.Api; + +namespace Penumbra.Api.IpcTester; + +public class IpcTester( + IpcProviders ipcProviders, + IPenumbraApi api, + PluginStateIpcTester pluginStateIpcTester, + UiIpcTester uiIpcTester, + RedrawingIpcTester redrawingIpcTester, + GameStateIpcTester gameStateIpcTester, + ResolveIpcTester resolveIpcTester, + CollectionsIpcTester collectionsIpcTester, + MetaIpcTester metaIpcTester, + ModsIpcTester modsIpcTester, + ModSettingsIpcTester modSettingsIpcTester, + EditingIpcTester editingIpcTester, + TemporaryIpcTester temporaryIpcTester, + ResourceTreeIpcTester resourceTreeIpcTester, + IFramework framework) : IUiService +{ + private readonly IpcProviders _ipcProviders = ipcProviders; + private DateTime _lastUpdate; + private bool _subscribed = false; + + public void Draw() + { + try + { + _lastUpdate = framework.LastUpdateUTC.AddSeconds(1); + Subscribe(); + + ImGui.TextUnformatted($"API Version: {api.ApiVersion.Breaking}.{api.ApiVersion.Feature:D4}"); + collectionsIpcTester.Draw(); + editingIpcTester.Draw(); + gameStateIpcTester.Draw(); + metaIpcTester.Draw(); + modSettingsIpcTester.Draw(); + modsIpcTester.Draw(); + pluginStateIpcTester.Draw(); + redrawingIpcTester.Draw(); + resolveIpcTester.Draw(); + resourceTreeIpcTester.Draw(); + uiIpcTester.Draw(); + temporaryIpcTester.Draw(); + temporaryIpcTester.DrawCollections(); + temporaryIpcTester.DrawMods(); + } + catch (Exception e) + { + Penumbra.Log.Error($"Error during IPC Tests:\n{e}"); + } + } + + internal static void DrawIntro(string label, string info) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(label); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(info); + ImGui.TableNextColumn(); + } + + private void Subscribe() + { + if (_subscribed) + return; + + Penumbra.Log.Debug("[IPCTester] Subscribed to IPC events for IPC tester."); + gameStateIpcTester.GameObjectResourcePathResolved.Enable(); + gameStateIpcTester.CharacterBaseCreated.Enable(); + gameStateIpcTester.CharacterBaseCreating.Enable(); + modSettingsIpcTester.SettingChanged.Enable(); + modsIpcTester.DeleteSubscriber.Enable(); + modsIpcTester.AddSubscriber.Enable(); + modsIpcTester.MoveSubscriber.Enable(); + pluginStateIpcTester.ModDirectoryChanged.Enable(); + pluginStateIpcTester.Initialized.Enable(); + pluginStateIpcTester.Disposed.Enable(); + pluginStateIpcTester.EnabledChange.Enable(); + redrawingIpcTester.Redrawn.Enable(); + uiIpcTester.PreSettingsTabBar.Enable(); + uiIpcTester.PreSettingsPanel.Enable(); + uiIpcTester.PostEnabled.Enable(); + uiIpcTester.PostSettingsPanelDraw.Enable(); + uiIpcTester.ChangedItemTooltip.Enable(); + uiIpcTester.ChangedItemClicked.Enable(); + + framework.Update += CheckUnsubscribe; + _subscribed = true; + } + + private void CheckUnsubscribe(IFramework framework1) + { + if (_lastUpdate > framework.LastUpdateUTC) + return; + + Unsubscribe(); + framework.Update -= CheckUnsubscribe; + } + + private void Unsubscribe() + { + if (!_subscribed) + return; + + Penumbra.Log.Debug("[IPCTester] Unsubscribed from IPC events for IPC tester."); + _subscribed = false; + gameStateIpcTester.GameObjectResourcePathResolved.Disable(); + gameStateIpcTester.CharacterBaseCreated.Disable(); + gameStateIpcTester.CharacterBaseCreating.Disable(); + modSettingsIpcTester.SettingChanged.Disable(); + modsIpcTester.DeleteSubscriber.Disable(); + modsIpcTester.AddSubscriber.Disable(); + modsIpcTester.MoveSubscriber.Disable(); + pluginStateIpcTester.ModDirectoryChanged.Disable(); + pluginStateIpcTester.Initialized.Disable(); + pluginStateIpcTester.Disposed.Disable(); + pluginStateIpcTester.EnabledChange.Disable(); + redrawingIpcTester.Redrawn.Disable(); + uiIpcTester.PreSettingsTabBar.Disable(); + uiIpcTester.PreSettingsPanel.Disable(); + uiIpcTester.PostEnabled.Disable(); + uiIpcTester.PostSettingsPanelDraw.Disable(); + uiIpcTester.ChangedItemTooltip.Disable(); + uiIpcTester.ChangedItemClicked.Disable(); + } +} diff --git a/Penumbra/Api/IpcTester/MetaIpcTester.cs b/Penumbra/Api/IpcTester/MetaIpcTester.cs new file mode 100644 index 00000000..3fa7de7f --- /dev/null +++ b/Penumbra/Api/IpcTester/MetaIpcTester.cs @@ -0,0 +1,38 @@ +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.IpcSubscribers; + +namespace Penumbra.Api.IpcTester; + +public class MetaIpcTester(DalamudPluginInterface pi) : IUiService +{ + private int _gameObjectIndex; + + public void Draw() + { + using var _ = ImRaii.TreeNode("Meta"); + if (!_) + return; + + ImGui.InputInt("##metaIdx", ref _gameObjectIndex, 0, 0); + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(GetPlayerMetaManipulations.Label, "Player Meta Manipulations"); + if (ImGui.Button("Copy to Clipboard##Player")) + { + var base64 = new GetPlayerMetaManipulations(pi).Invoke(); + ImGui.SetClipboardText(base64); + } + + IpcTester.DrawIntro(GetMetaManipulations.Label, "Game Object Manipulations"); + if (ImGui.Button("Copy to Clipboard##GameObject")) + { + var base64 = new GetMetaManipulations(pi).Invoke(_gameObjectIndex); + ImGui.SetClipboardText(base64); + } + } +} diff --git a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs new file mode 100644 index 00000000..c33fcdee --- /dev/null +++ b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs @@ -0,0 +1,181 @@ +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; +using Penumbra.UI; + +namespace Penumbra.Api.IpcTester; + +public class ModSettingsIpcTester : IUiService, IDisposable +{ + private readonly DalamudPluginInterface _pi; + public readonly EventSubscriber SettingChanged; + + private PenumbraApiEc _lastSettingsError = PenumbraApiEc.Success; + private ModSettingChange _lastSettingChangeType; + private Guid _lastSettingChangeCollection = Guid.Empty; + private string _lastSettingChangeMod = string.Empty; + private bool _lastSettingChangeInherited; + private DateTimeOffset _lastSettingChange; + + private string _settingsModDirectory = string.Empty; + private string _settingsModName = string.Empty; + private Guid? _settingsCollection; + private string _settingsCollectionName = string.Empty; + private bool _settingsIgnoreInheritance; + private bool _settingsInherit; + private bool _settingsEnabled; + private int _settingsPriority; + private IReadOnlyDictionary? _availableSettings; + private Dictionary>? _currentSettings; + + public ModSettingsIpcTester(DalamudPluginInterface pi) + { + _pi = pi; + SettingChanged = ModSettingChanged.Subscriber(pi, UpdateLastModSetting); + } + + public void Dispose() + { + SettingChanged.Dispose(); + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("Mod Settings"); + if (!_) + return; + + ImGui.InputTextWithHint("##settingsDir", "Mod Directory Name...", ref _settingsModDirectory, 100); + ImGui.InputTextWithHint("##settingsName", "Mod Name...", ref _settingsModName, 100); + ImGuiUtil.GuidInput("##settingsCollection", "Collection...", string.Empty, ref _settingsCollection, ref _settingsCollectionName); + ImGui.Checkbox("Ignore Inheritance", ref _settingsIgnoreInheritance); + var collection = _settingsCollection.GetValueOrDefault(Guid.Empty); + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro("Last Error", _lastSettingsError.ToString()); + + IpcTester.DrawIntro(ModSettingChanged.Label, "Last Mod Setting Changed"); + ImGui.TextUnformatted(_lastSettingChangeMod.Length > 0 + ? $"{_lastSettingChangeType} of {_lastSettingChangeMod} in {_lastSettingChangeCollection}{(_lastSettingChangeInherited ? " (Inherited)" : string.Empty)} at {_lastSettingChange}" + : "None"); + + IpcTester.DrawIntro(GetAvailableModSettings.Label, "Get Available Settings"); + if (ImGui.Button("Get##Available")) + { + _availableSettings = new GetAvailableModSettings(_pi).Invoke(_settingsModDirectory, _settingsModName); + _lastSettingsError = _availableSettings == null ? PenumbraApiEc.ModMissing : PenumbraApiEc.Success; + } + + IpcTester.DrawIntro(GetCurrentModSettings.Label, "Get Current Settings"); + if (ImGui.Button("Get##Current")) + { + var ret = new GetCurrentModSettings(_pi) + .Invoke(collection, _settingsModDirectory, _settingsModName, _settingsIgnoreInheritance); + _lastSettingsError = ret.Item1; + if (ret.Item1 == PenumbraApiEc.Success) + { + _settingsEnabled = ret.Item2?.Item1 ?? false; + _settingsInherit = ret.Item2?.Item4 ?? true; + _settingsPriority = ret.Item2?.Item2 ?? 0; + _currentSettings = ret.Item2?.Item3; + } + else + { + _currentSettings = null; + } + } + + IpcTester.DrawIntro(TryInheritMod.Label, "Inherit Mod"); + ImGui.Checkbox("##inherit", ref _settingsInherit); + ImGui.SameLine(); + if (ImGui.Button("Set##Inherit")) + _lastSettingsError = new TryInheritMod(_pi) + .Invoke(collection, _settingsModDirectory, _settingsInherit, _settingsModName); + + IpcTester.DrawIntro(TrySetMod.Label, "Set Enabled"); + ImGui.Checkbox("##enabled", ref _settingsEnabled); + ImGui.SameLine(); + if (ImGui.Button("Set##Enabled")) + _lastSettingsError = new TrySetMod(_pi) + .Invoke(collection, _settingsModDirectory, _settingsEnabled, _settingsModName); + + IpcTester.DrawIntro(TrySetModPriority.Label, "Set Priority"); + ImGui.SetNextItemWidth(200 * UiHelpers.Scale); + ImGui.DragInt("##Priority", ref _settingsPriority); + ImGui.SameLine(); + if (ImGui.Button("Set##Priority")) + _lastSettingsError = new TrySetModPriority(_pi) + .Invoke(collection, _settingsModDirectory, _settingsPriority, _settingsModName); + + IpcTester.DrawIntro(CopyModSettings.Label, "Copy Mod Settings"); + if (ImGui.Button("Copy Settings")) + _lastSettingsError = new CopyModSettings(_pi) + .Invoke(_settingsCollection, _settingsModDirectory, _settingsModName); + + ImGuiUtil.HoverTooltip("Copy settings from Mod Directory Name to Mod Name (as directory) in collection."); + + IpcTester.DrawIntro(TrySetModSetting.Label, "Set Setting(s)"); + if (_availableSettings == null) + return; + + foreach (var (group, (list, type)) in _availableSettings) + { + using var id = ImRaii.PushId(group); + var preview = list.Length > 0 ? list[0] : string.Empty; + if (_currentSettings != null && _currentSettings.TryGetValue(group, out var current) && current.Count > 0) + { + preview = current[0]; + } + else + { + current = []; + if (_currentSettings != null) + _currentSettings[group] = current; + } + + ImGui.SetNextItemWidth(200 * UiHelpers.Scale); + using (var c = ImRaii.Combo("##group", preview)) + { + if (c) + foreach (var s in list) + { + var contained = current.Contains(s); + if (ImGui.Checkbox(s, ref contained)) + { + if (contained) + current.Add(s); + else + current.Remove(s); + } + } + } + + ImGui.SameLine(); + if (ImGui.Button("Set##setting")) + _lastSettingsError = type == GroupType.Single + ? new TrySetModSetting(_pi).Invoke(collection, _settingsModDirectory, group, current.Count > 0 ? current[0] : string.Empty, + _settingsModName) + : new TrySetModSettings(_pi).Invoke(collection, _settingsModDirectory, group, current.ToArray(), _settingsModName); + + ImGui.SameLine(); + ImGui.TextUnformatted(group); + } + } + + private void UpdateLastModSetting(ModSettingChange type, Guid collection, string mod, bool inherited) + { + _lastSettingChangeType = type; + _lastSettingChangeCollection = collection; + _lastSettingChangeMod = mod; + _lastSettingChangeInherited = inherited; + _lastSettingChange = DateTimeOffset.Now; + } +} diff --git a/Penumbra/Api/IpcTester/ModsIpcTester.cs b/Penumbra/Api/IpcTester/ModsIpcTester.cs new file mode 100644 index 00000000..878a8214 --- /dev/null +++ b/Penumbra/Api/IpcTester/ModsIpcTester.cs @@ -0,0 +1,154 @@ +using Dalamud.Interface.Utility; +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; + +namespace Penumbra.Api.IpcTester; + +public class ModsIpcTester : IUiService, IDisposable +{ + private readonly DalamudPluginInterface _pi; + + private string _modDirectory = string.Empty; + private string _modName = string.Empty; + private string _pathInput = string.Empty; + private string _newInstallPath = string.Empty; + private PenumbraApiEc _lastReloadEc; + private PenumbraApiEc _lastAddEc; + private PenumbraApiEc _lastDeleteEc; + private PenumbraApiEc _lastSetPathEc; + private PenumbraApiEc _lastInstallEc; + private Dictionary _mods = []; + + public readonly EventSubscriber DeleteSubscriber; + public readonly EventSubscriber AddSubscriber; + public readonly EventSubscriber MoveSubscriber; + + private DateTimeOffset _lastDeletedModTime = DateTimeOffset.UnixEpoch; + private string _lastDeletedMod = string.Empty; + private DateTimeOffset _lastAddedModTime = DateTimeOffset.UnixEpoch; + private string _lastAddedMod = string.Empty; + private DateTimeOffset _lastMovedModTime = DateTimeOffset.UnixEpoch; + private string _lastMovedModFrom = string.Empty; + private string _lastMovedModTo = string.Empty; + + public ModsIpcTester(DalamudPluginInterface pi) + { + _pi = pi; + DeleteSubscriber = ModDeleted.Subscriber(pi, s => + { + _lastDeletedModTime = DateTimeOffset.UtcNow; + _lastDeletedMod = s; + }); + AddSubscriber = ModAdded.Subscriber(pi, s => + { + _lastAddedModTime = DateTimeOffset.UtcNow; + _lastAddedMod = s; + }); + MoveSubscriber = ModMoved.Subscriber(pi, (s1, s2) => + { + _lastMovedModTime = DateTimeOffset.UtcNow; + _lastMovedModFrom = s1; + _lastMovedModTo = s2; + }); + } + + public void Dispose() + { + DeleteSubscriber.Dispose(); + AddSubscriber.Dispose(); + MoveSubscriber.Dispose(); + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("Mods"); + if (!_) + return; + + ImGui.InputTextWithHint("##install", "Install File Path...", ref _newInstallPath, 100); + ImGui.InputTextWithHint("##modDir", "Mod Directory Name...", ref _modDirectory, 100); + ImGui.InputTextWithHint("##modName", "Mod Name...", ref _modName, 100); + ImGui.InputTextWithHint("##path", "New Path...", ref _pathInput, 100); + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(GetModList.Label, "Mods"); + DrawModsPopup(); + if (ImGui.Button("Get##Mods")) + { + _mods = new GetModList(_pi).Invoke(); + ImGui.OpenPopup("Mods"); + } + + IpcTester.DrawIntro(ReloadMod.Label, "Reload Mod"); + if (ImGui.Button("Reload")) + _lastReloadEc = new ReloadMod(_pi).Invoke(_modDirectory, _modName); + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastReloadEc.ToString()); + + IpcTester.DrawIntro(InstallMod.Label, "Install Mod"); + if (ImGui.Button("Install")) + _lastInstallEc = new InstallMod(_pi).Invoke(_newInstallPath); + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastInstallEc.ToString()); + + IpcTester.DrawIntro(AddMod.Label, "Add Mod"); + if (ImGui.Button("Add")) + _lastAddEc = new AddMod(_pi).Invoke(_modDirectory); + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastAddEc.ToString()); + + IpcTester.DrawIntro(DeleteMod.Label, "Delete Mod"); + if (ImGui.Button("Delete")) + _lastDeleteEc = new DeleteMod(_pi).Invoke(_modDirectory, _modName); + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastDeleteEc.ToString()); + + IpcTester.DrawIntro(GetModPath.Label, "Current Path"); + var (ec, path, def, nameDef) = new GetModPath(_pi).Invoke(_modDirectory, _modName); + ImGui.TextUnformatted($"{path} ({(def ? "Custom" : "Default")} Path, {(nameDef ? "Custom" : "Default")} Name) [{ec}]"); + + IpcTester.DrawIntro(SetModPath.Label, "Set Path"); + if (ImGui.Button("Set")) + _lastSetPathEc = new SetModPath(_pi).Invoke(_modDirectory, _pathInput, _modName); + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastSetPathEc.ToString()); + + IpcTester.DrawIntro(ModDeleted.Label, "Last Mod Deleted"); + if (_lastDeletedModTime > DateTimeOffset.UnixEpoch) + ImGui.TextUnformatted($"{_lastDeletedMod} at {_lastDeletedModTime}"); + + IpcTester.DrawIntro(ModAdded.Label, "Last Mod Added"); + if (_lastAddedModTime > DateTimeOffset.UnixEpoch) + ImGui.TextUnformatted($"{_lastAddedMod} at {_lastAddedModTime}"); + + IpcTester.DrawIntro(ModMoved.Label, "Last Mod Moved"); + if (_lastMovedModTime > DateTimeOffset.UnixEpoch) + ImGui.TextUnformatted($"{_lastMovedModFrom} -> {_lastMovedModTo} at {_lastMovedModTime}"); + } + + private void DrawModsPopup() + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); + using var p = ImRaii.Popup("Mods"); + if (!p) + return; + + foreach (var (modDir, modName) in _mods) + ImGui.TextUnformatted($"{modDir}: {modName}"); + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + ImGui.CloseCurrentPopup(); + } +} diff --git a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs new file mode 100644 index 00000000..0588e5bd --- /dev/null +++ b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs @@ -0,0 +1,132 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility; +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; + +namespace Penumbra.Api.IpcTester; + +public class PluginStateIpcTester : IUiService, IDisposable +{ + private readonly DalamudPluginInterface _pi; + public readonly EventSubscriber ModDirectoryChanged; + public readonly EventSubscriber Initialized; + public readonly EventSubscriber Disposed; + public readonly EventSubscriber EnabledChange; + + private string _currentConfiguration = string.Empty; + private string _lastModDirectory = string.Empty; + private bool _lastModDirectoryValid; + private DateTimeOffset _lastModDirectoryTime = DateTimeOffset.MinValue; + + private readonly List _initializedList = []; + private readonly List _disposedList = []; + + private DateTimeOffset _lastEnabledChange = DateTimeOffset.UnixEpoch; + private bool? _lastEnabledValue; + + public PluginStateIpcTester(DalamudPluginInterface pi) + { + _pi = pi; + ModDirectoryChanged = IpcSubscribers.ModDirectoryChanged.Subscriber(pi, UpdateModDirectoryChanged); + Initialized = IpcSubscribers.Initialized.Subscriber(pi, AddInitialized); + Disposed = IpcSubscribers.Disposed.Subscriber(pi, AddDisposed); + EnabledChange = IpcSubscribers.EnabledChange.Subscriber(pi, SetLastEnabled); + } + + public void Dispose() + { + ModDirectoryChanged.Dispose(); + Initialized.Dispose(); + Disposed.Dispose(); + EnabledChange.Dispose(); + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("Plugin State"); + if (!_) + return; + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + DrawList(IpcSubscribers.Initialized.Label, "Last Initialized", _initializedList); + DrawList(IpcSubscribers.Disposed.Label, "Last Disposed", _disposedList); + + IpcTester.DrawIntro(ApiVersion.Label, "Current Version"); + var (breaking, features) = new ApiVersion(_pi).Invoke(); + ImGui.TextUnformatted($"{breaking}.{features:D4}"); + + IpcTester.DrawIntro(GetEnabledState.Label, "Current State"); + ImGui.TextUnformatted($"{new GetEnabledState(_pi).Invoke()}"); + + IpcTester.DrawIntro(IpcSubscribers.EnabledChange.Label, "Last Change"); + ImGui.TextUnformatted(_lastEnabledValue is { } v ? $"{_lastEnabledChange} (to {v})" : "Never"); + + DrawConfigPopup(); + IpcTester.DrawIntro(GetConfiguration.Label, "Configuration"); + if (ImGui.Button("Get")) + { + _currentConfiguration = new GetConfiguration(_pi).Invoke(); + ImGui.OpenPopup("Config Popup"); + } + + IpcTester.DrawIntro(GetModDirectory.Label, "Current Mod Directory"); + ImGui.TextUnformatted(new GetModDirectory(_pi).Invoke()); + + IpcTester.DrawIntro(IpcSubscribers.ModDirectoryChanged.Label, "Last Mod Directory Change"); + ImGui.TextUnformatted(_lastModDirectoryTime > DateTimeOffset.MinValue + ? $"{_lastModDirectory} ({(_lastModDirectoryValid ? "Valid" : "Invalid")}) at {_lastModDirectoryTime}" + : "None"); + + void DrawList(string label, string text, List list) + { + IpcTester.DrawIntro(label, text); + if (list.Count == 0) + { + ImGui.TextUnformatted("Never"); + } + else + { + ImGui.TextUnformatted(list[^1].LocalDateTime.ToString(CultureInfo.CurrentCulture)); + if (list.Count > 1 && ImGui.IsItemHovered()) + ImGui.SetTooltip(string.Join("\n", + list.SkipLast(1).Select(t => t.LocalDateTime.ToString(CultureInfo.CurrentCulture)))); + } + } + } + + private void DrawConfigPopup() + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); + using var popup = ImRaii.Popup("Config Popup"); + if (!popup) + return; + + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImGuiUtil.TextWrapped(_currentConfiguration); + } + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + ImGui.CloseCurrentPopup(); + } + + private void UpdateModDirectoryChanged(string path, bool valid) + => (_lastModDirectory, _lastModDirectoryValid, _lastModDirectoryTime) = (path, valid, DateTimeOffset.Now); + + private void AddInitialized() + => _initializedList.Add(DateTimeOffset.UtcNow); + + private void AddDisposed() + => _disposedList.Add(DateTimeOffset.UtcNow); + + private void SetLastEnabled(bool val) + => (_lastEnabledChange, _lastEnabledValue) = (DateTimeOffset.Now, val); +} diff --git a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs new file mode 100644 index 00000000..281c7ad4 --- /dev/null +++ b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs @@ -0,0 +1,72 @@ +using Dalamud.Plugin; +using Dalamud.Plugin.Services; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; +using Penumbra.GameData.Interop; +using Penumbra.UI; + +namespace Penumbra.Api.IpcTester; + +public class RedrawingIpcTester : IUiService, IDisposable +{ + private readonly DalamudPluginInterface _pi; + private readonly ObjectManager _objects; + public readonly EventSubscriber Redrawn; + + private int _redrawIndex; + private string _lastRedrawnString = "None"; + + public RedrawingIpcTester(DalamudPluginInterface pi, ObjectManager objects) + { + _pi = pi; + _objects = objects; + Redrawn = GameObjectRedrawn.Subscriber(_pi, SetLastRedrawn); + } + + public void Dispose() + { + Redrawn.Dispose(); + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("Redrawing"); + if (!_) + return; + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(RedrawObject.Label, "Redraw by Index"); + var tmp = _redrawIndex; + ImGui.SetNextItemWidth(100 * UiHelpers.Scale); + if (ImGui.DragInt("##redrawIndex", ref tmp, 0.1f, 0, _objects.TotalCount)) + _redrawIndex = Math.Clamp(tmp, 0, _objects.TotalCount); + ImGui.SameLine(); + if (ImGui.Button("Redraw##Index")) + new RedrawObject(_pi).Invoke(_redrawIndex); + + IpcTester.DrawIntro(RedrawAll.Label, "Redraw All"); + if (ImGui.Button("Redraw##All")) + new RedrawAll(_pi).Invoke(); + + IpcTester.DrawIntro(GameObjectRedrawn.Label, "Last Redrawn Object:"); + ImGui.TextUnformatted(_lastRedrawnString); + } + + private void SetLastRedrawn(nint address, int index) + { + if (index < 0 + || index > _objects.TotalCount + || address == nint.Zero + || _objects[index].Address != address) + _lastRedrawnString = "Invalid"; + + _lastRedrawnString = $"{_objects[index].Utf8Name} (0x{address:X}, {index})"; + } +} diff --git a/Penumbra/Api/IpcTester/ResolveIpcTester.cs b/Penumbra/Api/IpcTester/ResolveIpcTester.cs new file mode 100644 index 00000000..978ed8d6 --- /dev/null +++ b/Penumbra/Api/IpcTester/ResolveIpcTester.cs @@ -0,0 +1,114 @@ +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.IpcSubscribers; +using Penumbra.String.Classes; + +namespace Penumbra.Api.IpcTester; + +public class ResolveIpcTester(DalamudPluginInterface pi) : IUiService +{ + private string _currentResolvePath = string.Empty; + private string _currentReversePath = string.Empty; + private int _currentReverseIdx; + private Task<(string[], string[][])> _task = Task.FromResult<(string[], string[][])>(([], [])); + + public void Draw() + { + using var tree = ImRaii.TreeNode("Resolving"); + if (!tree) + return; + + ImGui.InputTextWithHint("##resolvePath", "Resolve this game path...", ref _currentResolvePath, Utf8GamePath.MaxGamePathLength); + ImGui.InputTextWithHint("##resolveInversePath", "Reverse-resolve this path...", ref _currentReversePath, + Utf8GamePath.MaxGamePathLength); + ImGui.InputInt("##resolveIdx", ref _currentReverseIdx, 0, 0); + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(ResolveDefaultPath.Label, "Default Collection Resolve"); + if (_currentResolvePath.Length != 0) + ImGui.TextUnformatted(new ResolveDefaultPath(pi).Invoke(_currentResolvePath)); + + IpcTester.DrawIntro(ResolveInterfacePath.Label, "Interface Collection Resolve"); + if (_currentResolvePath.Length != 0) + ImGui.TextUnformatted(new ResolveInterfacePath(pi).Invoke(_currentResolvePath)); + + IpcTester.DrawIntro(ResolvePlayerPath.Label, "Player Collection Resolve"); + if (_currentResolvePath.Length != 0) + ImGui.TextUnformatted(new ResolvePlayerPath(pi).Invoke(_currentResolvePath)); + + IpcTester.DrawIntro(ResolveGameObjectPath.Label, "Game Object Collection Resolve"); + if (_currentResolvePath.Length != 0) + ImGui.TextUnformatted(new ResolveGameObjectPath(pi).Invoke(_currentResolvePath, _currentReverseIdx)); + + IpcTester.DrawIntro(ReverseResolvePlayerPath.Label, "Reversed Game Paths (Player)"); + if (_currentReversePath.Length > 0) + { + var list = new ReverseResolvePlayerPath(pi).Invoke(_currentReversePath); + if (list.Length > 0) + { + ImGui.TextUnformatted(list[0]); + if (list.Length > 1 && ImGui.IsItemHovered()) + ImGui.SetTooltip(string.Join("\n", list.Skip(1))); + } + } + + IpcTester.DrawIntro(ReverseResolveGameObjectPath.Label, "Reversed Game Paths (Game Object)"); + if (_currentReversePath.Length > 0) + { + var list = new ReverseResolveGameObjectPath(pi).Invoke(_currentReversePath, _currentReverseIdx); + if (list.Length > 0) + { + ImGui.TextUnformatted(list[0]); + if (list.Length > 1 && ImGui.IsItemHovered()) + ImGui.SetTooltip(string.Join("\n", list.Skip(1))); + } + } + + var forwardArray = _currentResolvePath.Length > 0 + ? [_currentResolvePath] + : Array.Empty(); + var reverseArray = _currentReversePath.Length > 0 + ? [_currentReversePath] + : Array.Empty(); + + IpcTester.DrawIntro(ResolvePlayerPaths.Label, "Resolved Paths (Player)"); + if (forwardArray.Length > 0 || reverseArray.Length > 0) + { + var ret = new ResolvePlayerPaths(pi).Invoke(forwardArray, reverseArray); + ImGui.TextUnformatted(ConvertText(ret)); + } + + IpcTester.DrawIntro(ResolvePlayerPathsAsync.Label, "Resolved Paths Async (Player)"); + if (ImGui.Button("Start")) + _task = new ResolvePlayerPathsAsync(pi).Invoke(forwardArray, reverseArray); + var hovered = ImGui.IsItemHovered(); + ImGui.SameLine(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted(_task.Status.ToString()); + if ((hovered || ImGui.IsItemHovered()) && _task.IsCompletedSuccessfully) + ImGui.SetTooltip(ConvertText(_task.Result)); + return; + + static string ConvertText((string[], string[][]) data) + { + var text = string.Empty; + if (data.Item1.Length > 0) + { + if (data.Item2.Length > 0) + text = $"Forward: {data.Item1[0]} | Reverse: {string.Join("; ", data.Item2[0])}."; + else + text = $"Forward: {data.Item1[0]}."; + } + else if (data.Item2.Length > 0) + { + text = $"Reverse: {string.Join("; ", data.Item2[0])}."; + } + + return text; + } + } +} diff --git a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs new file mode 100644 index 00000000..1f57fc9d --- /dev/null +++ b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs @@ -0,0 +1,349 @@ +using Dalamud.Game.ClientState.Objects.Enums; +using Dalamud.Interface; +using Dalamud.Interface.Utility; +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; +using Penumbra.GameData.Structs; + +namespace Penumbra.Api.IpcTester; + +public class ResourceTreeIpcTester(DalamudPluginInterface pi, ObjectManager objects) : IUiService +{ + private readonly Stopwatch _stopwatch = new(); + + private string _gameObjectIndices = "0"; + private ResourceType _type = ResourceType.Mtrl; + private bool _withUiData; + + private (string, Dictionary>?)[]? _lastGameObjectResourcePaths; + private (string, Dictionary>?)[]? _lastPlayerResourcePaths; + private (string, IReadOnlyDictionary?)[]? _lastGameObjectResourcesOfType; + private (string, IReadOnlyDictionary?)[]? _lastPlayerResourcesOfType; + private (string, ResourceTreeDto?)[]? _lastGameObjectResourceTrees; + private (string, ResourceTreeDto)[]? _lastPlayerResourceTrees; + private TimeSpan _lastCallDuration; + + public void Draw() + { + using var _ = ImRaii.TreeNode("Resource Tree"); + if (!_) + return; + + ImGui.InputText("GameObject indices", ref _gameObjectIndices, 511); + ImGuiUtil.GenericEnumCombo("Resource type", ImGui.CalcItemWidth(), _type, out _type, Enum.GetValues()); + ImGui.Checkbox("Also get names and icons", ref _withUiData); + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(GetGameObjectResourcePaths.Label, "Get GameObject resource paths"); + if (ImGui.Button("Get##GameObjectResourcePaths")) + { + var gameObjects = GetSelectedGameObjects(); + var subscriber = new GetGameObjectResourcePaths(pi); + _stopwatch.Restart(); + var resourcePaths = subscriber.Invoke(gameObjects); + + _lastCallDuration = _stopwatch.Elapsed; + _lastGameObjectResourcePaths = gameObjects + .Select(i => GameObjectToString(i)) + .Zip(resourcePaths) + .ToArray(); + + ImGui.OpenPopup(nameof(GetGameObjectResourcePaths)); + } + + IpcTester.DrawIntro(GetPlayerResourcePaths.Label, "Get local player resource paths"); + if (ImGui.Button("Get##PlayerResourcePaths")) + { + var subscriber = new GetPlayerResourcePaths(pi); + _stopwatch.Restart(); + var resourcePaths = subscriber.Invoke(); + + _lastCallDuration = _stopwatch.Elapsed; + _lastPlayerResourcePaths = resourcePaths + .Select(pair => (GameObjectToString(pair.Key), pair.Value)) + .ToArray()!; + + ImGui.OpenPopup(nameof(GetPlayerResourcePaths)); + } + + IpcTester.DrawIntro(GetGameObjectResourcesOfType.Label, "Get GameObject resources of type"); + if (ImGui.Button("Get##GameObjectResourcesOfType")) + { + var gameObjects = GetSelectedGameObjects(); + var subscriber = new GetGameObjectResourcesOfType(pi); + _stopwatch.Restart(); + var resourcesOfType = subscriber.Invoke(_type, _withUiData, gameObjects); + + _lastCallDuration = _stopwatch.Elapsed; + _lastGameObjectResourcesOfType = gameObjects + .Select(i => GameObjectToString(i)) + .Zip(resourcesOfType) + .ToArray(); + + ImGui.OpenPopup(nameof(GetGameObjectResourcesOfType)); + } + + IpcTester.DrawIntro(GetPlayerResourcesOfType.Label, "Get local player resources of type"); + if (ImGui.Button("Get##PlayerResourcesOfType")) + { + var subscriber = new GetPlayerResourcesOfType(pi); + _stopwatch.Restart(); + var resourcesOfType = subscriber.Invoke(_type, _withUiData); + + _lastCallDuration = _stopwatch.Elapsed; + _lastPlayerResourcesOfType = resourcesOfType + .Select(pair => (GameObjectToString(pair.Key), (IReadOnlyDictionary?)pair.Value)) + .ToArray(); + + ImGui.OpenPopup(nameof(GetPlayerResourcesOfType)); + } + + IpcTester.DrawIntro(GetGameObjectResourceTrees.Label, "Get GameObject resource trees"); + if (ImGui.Button("Get##GameObjectResourceTrees")) + { + var gameObjects = GetSelectedGameObjects(); + var subscriber = new GetGameObjectResourceTrees(pi); + _stopwatch.Restart(); + var trees = subscriber.Invoke(_withUiData, gameObjects); + + _lastCallDuration = _stopwatch.Elapsed; + _lastGameObjectResourceTrees = gameObjects + .Select(i => GameObjectToString(i)) + .Zip(trees) + .ToArray(); + + ImGui.OpenPopup(nameof(GetGameObjectResourceTrees)); + } + + IpcTester.DrawIntro(GetPlayerResourceTrees.Label, "Get local player resource trees"); + if (ImGui.Button("Get##PlayerResourceTrees")) + { + var subscriber = new GetPlayerResourceTrees(pi); + _stopwatch.Restart(); + var trees = subscriber.Invoke(_withUiData); + + _lastCallDuration = _stopwatch.Elapsed; + _lastPlayerResourceTrees = trees + .Select(pair => (GameObjectToString(pair.Key), pair.Value)) + .ToArray(); + + ImGui.OpenPopup(nameof(GetPlayerResourceTrees)); + } + + DrawPopup(nameof(GetGameObjectResourcePaths), ref _lastGameObjectResourcePaths, DrawResourcePaths, + _lastCallDuration); + DrawPopup(nameof(GetPlayerResourcePaths), ref _lastPlayerResourcePaths!, DrawResourcePaths, _lastCallDuration); + + DrawPopup(nameof(GetGameObjectResourcesOfType), ref _lastGameObjectResourcesOfType, DrawResourcesOfType, + _lastCallDuration); + DrawPopup(nameof(GetPlayerResourcesOfType), ref _lastPlayerResourcesOfType, DrawResourcesOfType, + _lastCallDuration); + + DrawPopup(nameof(GetGameObjectResourceTrees), ref _lastGameObjectResourceTrees, DrawResourceTrees, + _lastCallDuration); + DrawPopup(nameof(GetPlayerResourceTrees), ref _lastPlayerResourceTrees, DrawResourceTrees!, _lastCallDuration); + } + + private static void DrawPopup(string popupId, ref T? result, Action drawResult, TimeSpan duration) where T : class + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(1000, 500)); + using var popup = ImRaii.Popup(popupId); + if (!popup) + { + result = null; + return; + } + + if (result == null) + { + ImGui.CloseCurrentPopup(); + return; + } + + drawResult(result); + + ImGui.TextUnformatted($"Invoked in {duration.TotalMilliseconds} ms"); + + if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) + { + result = null; + ImGui.CloseCurrentPopup(); + } + } + + private static void DrawWithHeaders((string, T?)[] result, Action drawItem) where T : class + { + var firstSeen = new Dictionary(); + foreach (var (label, item) in result) + { + if (item == null) + { + ImRaii.TreeNode($"{label}: null", ImGuiTreeNodeFlags.Leaf).Dispose(); + continue; + } + + if (firstSeen.TryGetValue(item, out var firstLabel)) + { + ImRaii.TreeNode($"{label}: same as {firstLabel}", ImGuiTreeNodeFlags.Leaf).Dispose(); + continue; + } + + firstSeen.Add(item, label); + + using var header = ImRaii.TreeNode(label); + if (!header) + continue; + + drawItem(item); + } + } + + private static void DrawResourcePaths((string, Dictionary>?)[] result) + { + DrawWithHeaders(result, paths => + { + using var table = ImRaii.Table(string.Empty, 2, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.6f); + ImGui.TableSetupColumn("Game Paths", ImGuiTableColumnFlags.WidthStretch, 0.4f); + ImGui.TableHeadersRow(); + + foreach (var (actualPath, gamePaths) in paths) + { + ImGui.TableNextColumn(); + ImGui.TextUnformatted(actualPath); + ImGui.TableNextColumn(); + foreach (var gamePath in gamePaths) + ImGui.TextUnformatted(gamePath); + } + }); + } + + private void DrawResourcesOfType((string, IReadOnlyDictionary?)[] result) + { + DrawWithHeaders(result, resources => + { + using var table = ImRaii.Table(string.Empty, _withUiData ? 3 : 2, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.15f); + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, _withUiData ? 0.55f : 0.85f); + if (_withUiData) + ImGui.TableSetupColumn("Icon & Name", ImGuiTableColumnFlags.WidthStretch, 0.3f); + ImGui.TableHeadersRow(); + + foreach (var (resourceHandle, (actualPath, name, icon)) in resources) + { + ImGui.TableNextColumn(); + TextUnformattedMono($"0x{resourceHandle:X}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(actualPath); + if (_withUiData) + { + ImGui.TableNextColumn(); + TextUnformattedMono(icon.ToString()); + ImGui.SameLine(); + ImGui.TextUnformatted(name); + } + } + }); + } + + private void DrawResourceTrees((string, ResourceTreeDto?)[] result) + { + DrawWithHeaders(result, tree => + { + ImGui.TextUnformatted($"Name: {tree.Name}\nRaceCode: {(GenderRace)tree.RaceCode}"); + + using var table = ImRaii.Table(string.Empty, _withUiData ? 7 : 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.Resizable); + if (!table) + return; + + if (_withUiData) + { + ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.1f); + ImGui.TableSetupColumn("Icon", ImGuiTableColumnFlags.WidthStretch, 0.15f); + } + else + { + ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthStretch, 0.5f); + } + + ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); + ImGui.TableSetupColumn("Object Address", ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImGui.TableSetupColumn("Resource Handle", ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImGui.TableHeadersRow(); + + void DrawNode(ResourceNodeDto node) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + var hasChildren = node.Children.Any(); + using var treeNode = ImRaii.TreeNode( + $"{(_withUiData ? node.Name ?? "Unknown" : node.Type)}##{node.ObjectAddress:X8}", + hasChildren + ? ImGuiTreeNodeFlags.SpanFullWidth + : ImGuiTreeNodeFlags.SpanFullWidth | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.NoTreePushOnOpen); + if (_withUiData) + { + ImGui.TableNextColumn(); + TextUnformattedMono(node.Type.ToString()); + ImGui.TableNextColumn(); + TextUnformattedMono(node.Icon.ToString()); + } + + ImGui.TableNextColumn(); + ImGui.TextUnformatted(node.GamePath ?? "Unknown"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(node.ActualPath); + ImGui.TableNextColumn(); + TextUnformattedMono($"0x{node.ObjectAddress:X8}"); + ImGui.TableNextColumn(); + TextUnformattedMono($"0x{node.ResourceHandle:X8}"); + + if (treeNode) + foreach (var child in node.Children) + DrawNode(child); + } + + foreach (var node in tree.Nodes) + DrawNode(node); + }); + } + + private static void TextUnformattedMono(string text) + { + using var _ = ImRaii.PushFont(UiBuilder.MonoFont); + ImGui.TextUnformatted(text); + } + + private ushort[] GetSelectedGameObjects() + => _gameObjectIndices.Split(',') + .SelectWhere(index => (ushort.TryParse(index.Trim(), out var i), i)) + .ToArray(); + + private unsafe string GameObjectToString(ObjectIndex gameObjectIndex) + { + var gameObject = objects[gameObjectIndex]; + + return gameObject.Valid + ? $"[{gameObjectIndex}] {gameObject.Utf8Name} ({(ObjectKind)gameObject.AsObject->ObjectKind})" + : $"[{gameObjectIndex}] null"; + } +} diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs new file mode 100644 index 00000000..a8405eb2 --- /dev/null +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -0,0 +1,203 @@ +using Dalamud.Interface; +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.IpcSubscribers; +using Penumbra.Collections.Manager; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods; +using Penumbra.Mods.Manager; +using Penumbra.Services; + +namespace Penumbra.Api.IpcTester; + +public class TemporaryIpcTester( + DalamudPluginInterface pi, + ModManager modManager, + CollectionManager collections, + TempModManager tempMods, + TempCollectionManager tempCollections, + SaveService saveService, + Configuration config) + : IUiService +{ + public Guid LastCreatedCollectionId = Guid.Empty; + + private Guid? _tempGuid; + private string _tempCollectionName = string.Empty; + private string _tempCollectionGuidName = string.Empty; + private string _tempModName = string.Empty; + private string _tempGamePath = "test/game/path.mtrl"; + private string _tempFilePath = "test/success.mtrl"; + private string _tempManipulation = string.Empty; + private PenumbraApiEc _lastTempError; + private int _tempActorIndex; + private bool _forceOverwrite; + + public void Draw() + { + using var _ = ImRaii.TreeNode("Temporary"); + if (!_) + return; + + ImGui.InputTextWithHint("##tempCollection", "Collection Name...", ref _tempCollectionName, 128); + ImGuiUtil.GuidInput("##guid", "Collection GUID...", string.Empty, ref _tempGuid, ref _tempCollectionGuidName); + ImGui.InputInt("##tempActorIndex", ref _tempActorIndex, 0, 0); + ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); + ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); + ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); + ImGui.InputTextWithHint("##tempManip", "Manipulation Base64 String...", ref _tempManipulation, 256); + ImGui.Checkbox("Force Character Collection Overwrite", ref _forceOverwrite); + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro("Last Error", _lastTempError.ToString()); + ImGuiUtil.DrawTableColumn("Last Created Collection"); + ImGui.TableNextColumn(); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImGuiUtil.CopyOnClickSelectable(LastCreatedCollectionId.ToString()); + } + + IpcTester.DrawIntro(CreateTemporaryCollection.Label, "Create Temporary Collection"); + if (ImGui.Button("Create##Collection")) + { + LastCreatedCollectionId = new CreateTemporaryCollection(pi).Invoke(_tempCollectionName); + if (_tempGuid == null) + { + _tempGuid = LastCreatedCollectionId; + _tempCollectionGuidName = LastCreatedCollectionId.ToString(); + } + } + + var guid = _tempGuid.GetValueOrDefault(Guid.Empty); + + IpcTester.DrawIntro(DeleteTemporaryCollection.Label, "Delete Temporary Collection"); + if (ImGui.Button("Delete##Collection")) + _lastTempError = new DeleteTemporaryCollection(pi).Invoke(guid); + ImGui.SameLine(); + if (ImGui.Button("Delete Last##Collection")) + _lastTempError = new DeleteTemporaryCollection(pi).Invoke(LastCreatedCollectionId); + + IpcTester.DrawIntro(AssignTemporaryCollection.Label, "Assign Temporary Collection"); + if (ImGui.Button("Assign##NamedCollection")) + _lastTempError = new AssignTemporaryCollection(pi).Invoke(guid, _tempActorIndex, _forceOverwrite); + + IpcTester.DrawIntro(AddTemporaryMod.Label, "Add Temporary Mod to specific Collection"); + if (ImGui.Button("Add##Mod")) + _lastTempError = new AddTemporaryMod(pi).Invoke(_tempModName, guid, + new Dictionary { { _tempGamePath, _tempFilePath } }, + _tempManipulation.Length > 0 ? _tempManipulation : string.Empty, int.MaxValue); + + IpcTester.DrawIntro(CreateTemporaryCollection.Label, "Copy Existing Collection"); + if (ImGuiUtil.DrawDisabledButton("Copy##Collection", Vector2.Zero, + "Copies the effective list from the collection named in Temporary Mod Name...", + !collections.Storage.ByName(_tempModName, out var copyCollection)) + && copyCollection is { HasCache: true }) + { + var files = copyCollection.ResolvedFiles.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.Path.ToString()); + var manips = Functions.ToCompressedBase64(copyCollection.MetaCache?.Manipulations.ToArray() ?? Array.Empty(), + MetaManipulation.CurrentVersion); + _lastTempError = new AddTemporaryMod(pi).Invoke(_tempModName, guid, files, manips, 999); + } + + IpcTester.DrawIntro(AddTemporaryModAll.Label, "Add Temporary Mod to all Collections"); + if (ImGui.Button("Add##All")) + _lastTempError = new AddTemporaryModAll(pi).Invoke(_tempModName, + new Dictionary { { _tempGamePath, _tempFilePath } }, + _tempManipulation.Length > 0 ? _tempManipulation : string.Empty, int.MaxValue); + + IpcTester.DrawIntro(RemoveTemporaryMod.Label, "Remove Temporary Mod from specific Collection"); + if (ImGui.Button("Remove##Mod")) + _lastTempError = new RemoveTemporaryMod(pi).Invoke(_tempModName, guid, int.MaxValue); + + IpcTester.DrawIntro(RemoveTemporaryModAll.Label, "Remove Temporary Mod from all Collections"); + if (ImGui.Button("Remove##ModAll")) + _lastTempError = new RemoveTemporaryModAll(pi).Invoke(_tempModName, int.MaxValue); + } + + public void DrawCollections() + { + using var collTree = ImRaii.TreeNode("Temporary Collections##TempCollections"); + if (!collTree) + return; + + using var table = ImRaii.Table("##collTree", 6, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + foreach (var (collection, idx) in tempCollections.Values.WithIndex()) + { + using var id = ImRaii.PushId(idx); + ImGui.TableNextColumn(); + var character = tempCollections.Collections.Where(p => p.Collection == collection).Select(p => p.DisplayName) + .FirstOrDefault() + ?? "Unknown"; + if (ImGui.Button("Save##Collection")) + TemporaryMod.SaveTempCollection(config, saveService, modManager, collection, character); + + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImGui.TableNextColumn(); + ImGuiUtil.CopyOnClickSelectable(collection.Identifier); + } + + ImGuiUtil.DrawTableColumn(collection.Name); + ImGuiUtil.DrawTableColumn(collection.ResolvedFiles.Count.ToString()); + ImGuiUtil.DrawTableColumn(collection.MetaCache?.Count.ToString() ?? "0"); + ImGuiUtil.DrawTableColumn(string.Join(", ", + tempCollections.Collections.Where(p => p.Collection == collection).Select(c => c.DisplayName))); + } + } + + public void DrawMods() + { + using var modTree = ImRaii.TreeNode("Temporary Mods##TempMods"); + if (!modTree) + return; + + using var table = ImRaii.Table("##modTree", 5, ImGuiTableFlags.SizingFixedFit); + + void PrintList(string collectionName, IReadOnlyList list) + { + foreach (var mod in list) + { + ImGui.TableNextColumn(); + ImGui.TextUnformatted(mod.Name); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(mod.Priority.ToString()); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(collectionName); + ImGui.TableNextColumn(); + ImGui.TextUnformatted(mod.Default.Files.Count.ToString()); + if (ImGui.IsItemHovered()) + { + using var tt = ImRaii.Tooltip(); + foreach (var (path, file) in mod.Default.Files) + ImGui.TextUnformatted($"{path} -> {file}"); + } + + ImGui.TableNextColumn(); + ImGui.TextUnformatted(mod.TotalManipulations.ToString()); + if (ImGui.IsItemHovered()) + { + using var tt = ImRaii.Tooltip(); + foreach (var manip in mod.Default.Manipulations) + ImGui.TextUnformatted(manip.ToString()); + } + } + } + + if (table) + { + PrintList("All", tempMods.ModsForAllCollections); + foreach (var (collection, list) in tempMods.Mods) + PrintList(collection.Name, list); + } + } +} diff --git a/Penumbra/Api/IpcTester/UiIpcTester.cs b/Penumbra/Api/IpcTester/UiIpcTester.cs new file mode 100644 index 00000000..29ddc22e --- /dev/null +++ b/Penumbra/Api/IpcTester/UiIpcTester.cs @@ -0,0 +1,128 @@ +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Api.Helpers; +using Penumbra.Api.IpcSubscribers; +using Penumbra.Communication; + +namespace Penumbra.Api.IpcTester; + +public class UiIpcTester : IUiService, IDisposable +{ + private readonly DalamudPluginInterface _pi; + public readonly EventSubscriber PreSettingsTabBar; + public readonly EventSubscriber PreSettingsPanel; + public readonly EventSubscriber PostEnabled; + public readonly EventSubscriber PostSettingsPanelDraw; + public readonly EventSubscriber ChangedItemTooltip; + public readonly EventSubscriber ChangedItemClicked; + + private string _lastDrawnMod = string.Empty; + private DateTimeOffset _lastDrawnModTime = DateTimeOffset.MinValue; + private bool _subscribedToTooltip; + private bool _subscribedToClick; + private string _lastClicked = string.Empty; + private string _lastHovered = string.Empty; + private TabType _selectTab = TabType.None; + private string _modName = string.Empty; + private PenumbraApiEc _ec = PenumbraApiEc.Success; + + public UiIpcTester(DalamudPluginInterface pi) + { + _pi = pi; + PreSettingsTabBar = IpcSubscribers.PreSettingsTabBarDraw.Subscriber(pi, UpdateLastDrawnMod); + PreSettingsPanel = IpcSubscribers.PreSettingsPanelDraw.Subscriber(pi, UpdateLastDrawnMod); + PostEnabled = IpcSubscribers.PostEnabledDraw.Subscriber(pi, UpdateLastDrawnMod); + PostSettingsPanelDraw = IpcSubscribers.PostSettingsPanelDraw.Subscriber(pi, UpdateLastDrawnMod); + ChangedItemTooltip = IpcSubscribers.ChangedItemTooltip.Subscriber(pi, AddedTooltip); + ChangedItemClicked = IpcSubscribers.ChangedItemClicked.Subscriber(pi, AddedClick); + } + + public void Dispose() + { + PreSettingsTabBar.Dispose(); + PreSettingsPanel.Dispose(); + PostEnabled.Dispose(); + PostSettingsPanelDraw.Dispose(); + ChangedItemTooltip.Dispose(); + ChangedItemClicked.Dispose(); + } + + public void Draw() + { + using var _ = ImRaii.TreeNode("UI"); + if (!_) + return; + + using (var combo = ImRaii.Combo("Tab to Open at", _selectTab.ToString())) + { + if (combo) + foreach (var val in Enum.GetValues()) + { + if (ImGui.Selectable(val.ToString(), _selectTab == val)) + _selectTab = val; + } + } + + ImGui.InputTextWithHint("##openMod", "Mod to Open at...", ref _modName, 256); + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + IpcTester.DrawIntro(IpcSubscribers.PostSettingsPanelDraw.Label, "Last Drawn Mod"); + ImGui.TextUnformatted(_lastDrawnMod.Length > 0 ? $"{_lastDrawnMod} at {_lastDrawnModTime}" : "None"); + + IpcTester.DrawIntro(IpcSubscribers.ChangedItemTooltip.Label, "Add Tooltip"); + if (ImGui.Checkbox("##tooltip", ref _subscribedToTooltip)) + { + if (_subscribedToTooltip) + ChangedItemTooltip.Enable(); + else + ChangedItemTooltip.Disable(); + } + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastHovered); + + IpcTester.DrawIntro(IpcSubscribers.ChangedItemClicked.Label, "Subscribe Click"); + if (ImGui.Checkbox("##click", ref _subscribedToClick)) + { + if (_subscribedToClick) + ChangedItemClicked.Enable(); + else + ChangedItemClicked.Disable(); + } + + ImGui.SameLine(); + ImGui.TextUnformatted(_lastClicked); + IpcTester.DrawIntro(OpenMainWindow.Label, "Open Mod Window"); + if (ImGui.Button("Open##window")) + _ec = new OpenMainWindow(_pi).Invoke(_selectTab, _modName, _modName); + + ImGui.SameLine(); + ImGui.TextUnformatted(_ec.ToString()); + + IpcTester.DrawIntro(CloseMainWindow.Label, "Close Mod Window"); + if (ImGui.Button("Close##window")) + new CloseMainWindow(_pi).Invoke(); + } + + private void UpdateLastDrawnMod(string name) + => (_lastDrawnMod, _lastDrawnModTime) = (name, DateTimeOffset.Now); + + private void UpdateLastDrawnMod(string name, float _1, float _2) + => (_lastDrawnMod, _lastDrawnModTime) = (name, DateTimeOffset.Now); + + private void AddedTooltip(ChangedItemType type, uint id) + { + _lastHovered = $"{type} {id} at {DateTime.UtcNow.ToLocalTime().ToString(CultureInfo.CurrentCulture)}"; + ImGui.TextUnformatted("IPC Test Successful"); + } + + private void AddedClick(MouseButton button, ChangedItemType type, uint id) + { + _lastClicked = $"{button}-click on {type} {id} at {DateTime.UtcNow.ToLocalTime().ToString(CultureInfo.CurrentCulture)}"; + } +} diff --git a/Penumbra/Api/PenumbraApi.cs b/Penumbra/Api/PenumbraApi.cs deleted file mode 100644 index dc1e8472..00000000 --- a/Penumbra/Api/PenumbraApi.cs +++ /dev/null @@ -1,1374 +0,0 @@ -using Dalamud.Game.ClientState.Objects.Types; -using Dalamud.Plugin.Services; -using Lumina.Data; -using Newtonsoft.Json; -using OtterGui; -using Penumbra.Collections; -using Penumbra.Interop.PathResolving; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Compression; -using OtterGui.Log; -using Penumbra.Api.Enums; -using Penumbra.GameData.Actors; -using Penumbra.Interop.ResourceLoading; -using Penumbra.Mods.Manager; -using Penumbra.String; -using Penumbra.String.Classes; -using Penumbra.Services; -using Penumbra.Collections.Manager; -using Penumbra.Communication; -using Penumbra.GameData.Interop; -using Penumbra.Import.Textures; -using Penumbra.Interop.Services; -using Penumbra.UI; -using TextureType = Penumbra.Api.Enums.TextureType; -using Penumbra.Interop.ResourceTree; -using Penumbra.Mods.Editor; -using Penumbra.Mods.Subclasses; - -namespace Penumbra.Api; - -public class PenumbraApi : IDisposable, IPenumbraApi -{ - public (int, int) ApiVersion - => (4, 24); - - public event Action? PreSettingsTabBarDraw - { - add => _communicator.PreSettingsTabBarDraw.Subscribe(value!, Communication.PreSettingsTabBarDraw.Priority.Default); - remove => _communicator.PreSettingsTabBarDraw.Unsubscribe(value!); - } - - public event Action? PreSettingsPanelDraw - { - add => _communicator.PreSettingsPanelDraw.Subscribe(value!, Communication.PreSettingsPanelDraw.Priority.Default); - remove => _communicator.PreSettingsPanelDraw.Unsubscribe(value!); - } - - public event Action? PostEnabledDraw - { - add => _communicator.PostEnabledDraw.Subscribe(value!, Communication.PostEnabledDraw.Priority.Default); - remove => _communicator.PostEnabledDraw.Unsubscribe(value!); - } - - public event Action? PostSettingsPanelDraw - { - add => _communicator.PostSettingsPanelDraw.Subscribe(value!, Communication.PostSettingsPanelDraw.Priority.Default); - remove => _communicator.PostSettingsPanelDraw.Unsubscribe(value!); - } - - public event GameObjectRedrawnDelegate? GameObjectRedrawn - { - add - { - CheckInitialized(); - _redrawService.GameObjectRedrawn += value; - } - remove - { - CheckInitialized(); - _redrawService.GameObjectRedrawn -= value; - } - } - - public event ModSettingChangedDelegate? ModSettingChanged; - - public event CreatingCharacterBaseDelegate? CreatingCharacterBase - { - add - { - if (value == null) - return; - - CheckInitialized(); - _communicator.CreatingCharacterBase.Subscribe(new Action(value), - Communication.CreatingCharacterBase.Priority.Api); - } - remove - { - if (value == null) - return; - - CheckInitialized(); - _communicator.CreatingCharacterBase.Unsubscribe(new Action(value)); - } - } - - public event CreatedCharacterBaseDelegate? CreatedCharacterBase; - - public bool Valid - => _lumina != null; - - private CommunicatorService _communicator; - private Lumina.GameData? _lumina; - - private IDataManager _gameData; - private IFramework _framework; - private ObjectManager _objects; - private ModManager _modManager; - private ResourceLoader _resourceLoader; - private Configuration _config; - private CollectionManager _collectionManager; - private TempCollectionManager _tempCollections; - private TempModManager _tempMods; - private ActorManager _actors; - private CollectionResolver _collectionResolver; - private CutsceneService _cutsceneService; - private ModImportManager _modImportManager; - private CollectionEditor _collectionEditor; - private RedrawService _redrawService; - private ModFileSystem _modFileSystem; - private ConfigWindow _configWindow; - private TextureManager _textureManager; - private ResourceTreeFactory _resourceTreeFactory; - - public unsafe PenumbraApi(CommunicatorService communicator, IDataManager gameData, IFramework framework, ObjectManager objects, - ModManager modManager, ResourceLoader resourceLoader, Configuration config, CollectionManager collectionManager, - TempCollectionManager tempCollections, TempModManager tempMods, ActorManager actors, CollectionResolver collectionResolver, - CutsceneService cutsceneService, ModImportManager modImportManager, CollectionEditor collectionEditor, RedrawService redrawService, - ModFileSystem modFileSystem, ConfigWindow configWindow, TextureManager textureManager, ResourceTreeFactory resourceTreeFactory) - { - _communicator = communicator; - _gameData = gameData; - _framework = framework; - _objects = objects; - _modManager = modManager; - _resourceLoader = resourceLoader; - _config = config; - _collectionManager = collectionManager; - _tempCollections = tempCollections; - _tempMods = tempMods; - _actors = actors; - _collectionResolver = collectionResolver; - _cutsceneService = cutsceneService; - _modImportManager = modImportManager; - _collectionEditor = collectionEditor; - _redrawService = redrawService; - _modFileSystem = modFileSystem; - _configWindow = configWindow; - _textureManager = textureManager; - _resourceTreeFactory = resourceTreeFactory; - _lumina = gameData.GameData; - - _resourceLoader.ResourceLoaded += OnResourceLoaded; - _communicator.ModPathChanged.Subscribe(ModPathChangeSubscriber, ModPathChanged.Priority.Api); - _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); - _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); - _communicator.ModOptionChanged.Subscribe(OnModOptionEdited, ModOptionChanged.Priority.Api); - _communicator.ModFileChanged.Subscribe(OnModFileChanged, ModFileChanged.Priority.Api); - } - - public unsafe void Dispose() - { - if (!Valid) - return; - - _resourceLoader.ResourceLoaded -= OnResourceLoaded; - _communicator.ModPathChanged.Unsubscribe(ModPathChangeSubscriber); - _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); - _communicator.CreatedCharacterBase.Unsubscribe(OnCreatedCharacterBase); - _communicator.ModOptionChanged.Unsubscribe(OnModOptionEdited); - _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); - _lumina = null; - _communicator = null!; - _modManager = null!; - _resourceLoader = null!; - _config = null!; - _collectionManager = null!; - _tempCollections = null!; - _tempMods = null!; - _actors = null!; - _collectionResolver = null!; - _cutsceneService = null!; - _modImportManager = null!; - _collectionEditor = null!; - _redrawService = null!; - _modFileSystem = null!; - _configWindow = null!; - _textureManager = null!; - _resourceTreeFactory = null!; - _framework = null!; - } - - public event ChangedItemClick? ChangedItemClicked - { - add => _communicator.ChangedItemClick.Subscribe(new Action(value!), - Communication.ChangedItemClick.Priority.Default); - remove => _communicator.ChangedItemClick.Unsubscribe(new Action(value!)); - } - - public string GetModDirectory() - { - CheckInitialized(); - return _config.ModDirectory; - } - - private unsafe void OnResourceLoaded(ResourceHandle* _, Utf8GamePath originalPath, FullPath? manipulatedPath, - ResolveData resolveData) - { - if (resolveData.AssociatedGameObject != nint.Zero) - GameObjectResourceResolved?.Invoke(resolveData.AssociatedGameObject, originalPath.ToString(), - manipulatedPath?.ToString() ?? originalPath.ToString()); - } - - public event Action? ModDirectoryChanged - { - add - { - CheckInitialized(); - _communicator.ModDirectoryChanged.Subscribe(value!, Communication.ModDirectoryChanged.Priority.Api); - } - remove - { - CheckInitialized(); - _communicator.ModDirectoryChanged.Unsubscribe(value!); - } - } - - public bool GetEnabledState() - => _config.EnableMods; - - public event Action? EnabledChange - { - add - { - CheckInitialized(); - _communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); - } - remove - { - CheckInitialized(); - _communicator.EnabledChanged.Unsubscribe(value!); - } - } - - public string GetConfiguration() - { - CheckInitialized(); - return JsonConvert.SerializeObject(_config, Formatting.Indented); - } - - public event ChangedItemHover? ChangedItemTooltip - { - add => _communicator.ChangedItemHover.Subscribe(new Action(value!), Communication.ChangedItemHover.Priority.Default); - remove => _communicator.ChangedItemHover.Unsubscribe(new Action(value!)); - } - - public event GameObjectResourceResolvedDelegate? GameObjectResourceResolved; - - public PenumbraApiEc OpenMainWindow(TabType tab, string modDirectory, string modName) - { - CheckInitialized(); - if (_configWindow == null) - return PenumbraApiEc.SystemDisposed; - - _configWindow.IsOpen = true; - - if (!Enum.IsDefined(tab)) - return PenumbraApiEc.InvalidArgument; - - if (tab == TabType.Mods && (modDirectory.Length > 0 || modName.Length > 0)) - { - if (_modManager.TryGetMod(modDirectory, modName, out var mod)) - _communicator.SelectTab.Invoke(tab, mod); - else - return PenumbraApiEc.ModMissing; - } - else if (tab != TabType.None) - { - _communicator.SelectTab.Invoke(tab, null); - } - - return PenumbraApiEc.Success; - } - - public void CloseMainWindow() - { - CheckInitialized(); - if (_configWindow == null) - return; - - _configWindow.IsOpen = false; - } - - public void RedrawObject(int tableIndex, RedrawType setting) - { - CheckInitialized(); - _redrawService.RedrawObject(tableIndex, setting); - } - - public void RedrawObject(string name, RedrawType setting) - { - CheckInitialized(); - _redrawService.RedrawObject(name, setting); - } - - public void RedrawObject(GameObject? gameObject, RedrawType setting) - { - CheckInitialized(); - _redrawService.RedrawObject(gameObject, setting); - } - - public void RedrawAll(RedrawType setting) - { - CheckInitialized(); - _redrawService.RedrawAll(setting); - } - - public string ResolveDefaultPath(string path) - { - CheckInitialized(); - return ResolvePath(path, _modManager, _collectionManager.Active.Default); - } - - public string ResolveInterfacePath(string path) - { - CheckInitialized(); - return ResolvePath(path, _modManager, _collectionManager.Active.Interface); - } - - public string ResolvePlayerPath(string path) - { - CheckInitialized(); - return ResolvePath(path, _modManager, _collectionResolver.PlayerCollection()); - } - - // TODO: cleanup when incrementing API level - public string ResolvePath(string path, string characterName) - => ResolvePath(path, characterName, ushort.MaxValue); - - public string ResolveGameObjectPath(string path, int gameObjectIdx) - { - CheckInitialized(); - AssociatedCollection(gameObjectIdx, out var collection); - return ResolvePath(path, _modManager, collection); - } - - public string ResolvePath(string path, string characterName, ushort worldId) - { - CheckInitialized(); - return ResolvePath(path, _modManager, - _collectionManager.Active.Individual(NameToIdentifier(characterName, worldId))); - } - - // TODO: cleanup when incrementing API level - public string[] ReverseResolvePath(string path, string characterName) - => ReverseResolvePath(path, characterName, ushort.MaxValue); - - public string[] ReverseResolvePath(string path, string characterName, ushort worldId) - { - CheckInitialized(); - if (!_config.EnableMods) - return [path]; - - var ret = _collectionManager.Active.Individual(NameToIdentifier(characterName, worldId)).ReverseResolvePath(new FullPath(path)); - return ret.Select(r => r.ToString()).ToArray(); - } - - public string[] ReverseResolveGameObjectPath(string path, int gameObjectIdx) - { - CheckInitialized(); - if (!_config.EnableMods) - return [path]; - - AssociatedCollection(gameObjectIdx, out var collection); - var ret = collection.ReverseResolvePath(new FullPath(path)); - return ret.Select(r => r.ToString()).ToArray(); - } - - public string[] ReverseResolvePlayerPath(string path) - { - CheckInitialized(); - if (!_config.EnableMods) - return [path]; - - var ret = _collectionResolver.PlayerCollection().ReverseResolvePath(new FullPath(path)); - return ret.Select(r => r.ToString()).ToArray(); - } - - public (string[], string[][]) ResolvePlayerPaths(string[] forward, string[] reverse) - { - CheckInitialized(); - if (!_config.EnableMods) - return (forward, reverse.Select(p => new[] - { - p, - }).ToArray()); - - var playerCollection = _collectionResolver.PlayerCollection(); - var resolved = forward.Select(p => ResolvePath(p, _modManager, playerCollection)).ToArray(); - var reverseResolved = playerCollection.ReverseResolvePaths(reverse); - return (resolved, reverseResolved.Select(a => a.Select(p => p.ToString()).ToArray()).ToArray()); - } - - public async Task<(string[], string[][])> ResolvePlayerPathsAsync(string[] forward, string[] reverse) - { - CheckInitialized(); - if (!_config.EnableMods) - return (forward, reverse.Select(p => new[] - { - p, - }).ToArray()); - - return await Task.Run(async () => - { - var playerCollection = await _framework.RunOnFrameworkThread(_collectionResolver.PlayerCollection).ConfigureAwait(false); - var forwardTask = Task.Run(() => - { - var forwardRet = new string[forward.Length]; - Parallel.For(0, forward.Length, idx => forwardRet[idx] = ResolvePath(forward[idx], _modManager, playerCollection)); - return forwardRet; - }).ConfigureAwait(false); - var reverseTask = Task.Run(() => playerCollection.ReverseResolvePaths(reverse)).ConfigureAwait(false); - var reverseResolved = (await reverseTask).Select(a => a.Select(p => p.ToString()).ToArray()).ToArray(); - return (await forwardTask, reverseResolved); - }); - } - - public T? GetFile(string gamePath) where T : FileResource - => GetFileIntern(ResolveDefaultPath(gamePath)); - - public T? GetFile(string gamePath, string characterName) where T : FileResource - => GetFileIntern(ResolvePath(gamePath, characterName)); - - public IReadOnlyDictionary GetChangedItemsForCollection(string collectionName) - { - CheckInitialized(); - try - { - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - collection = ModCollection.Empty; - - if (collection.HasCache) - return collection.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Item2); - - Penumbra.Log.Warning($"Collection {collectionName} does not exist or is not loaded."); - return new Dictionary(); - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not obtain Changed Items for {collectionName}:\n{e}"); - throw; - } - } - - public string GetCollectionForType(ApiCollectionType type) - { - CheckInitialized(); - if (!Enum.IsDefined(type)) - return string.Empty; - - var collection = _collectionManager.Active.ByType((CollectionType)type); - return collection?.Name ?? string.Empty; - } - - public (PenumbraApiEc, string OldCollection) SetCollectionForType(ApiCollectionType type, string collectionName, bool allowCreateNew, - bool allowDelete) - { - CheckInitialized(); - if (!Enum.IsDefined(type)) - return (PenumbraApiEc.InvalidArgument, string.Empty); - - var oldCollection = _collectionManager.Active.ByType((CollectionType)type)?.Name ?? string.Empty; - - if (collectionName.Length == 0) - { - if (oldCollection.Length == 0) - return (PenumbraApiEc.NothingChanged, oldCollection); - - if (!allowDelete || type is ApiCollectionType.Current or ApiCollectionType.Default or ApiCollectionType.Interface) - return (PenumbraApiEc.AssignmentDeletionDisallowed, oldCollection); - - _collectionManager.Active.RemoveSpecialCollection((CollectionType)type); - return (PenumbraApiEc.Success, oldCollection); - } - - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return (PenumbraApiEc.CollectionMissing, oldCollection); - - if (oldCollection.Length == 0) - { - if (!allowCreateNew) - return (PenumbraApiEc.AssignmentCreationDisallowed, oldCollection); - - _collectionManager.Active.CreateSpecialCollection((CollectionType)type); - } - else if (oldCollection == collection.Name) - { - return (PenumbraApiEc.NothingChanged, oldCollection); - } - - _collectionManager.Active.SetCollection(collection, (CollectionType)type); - return (PenumbraApiEc.Success, oldCollection); - } - - public (bool ObjectValid, bool IndividualSet, string EffectiveCollection) GetCollectionForObject(int gameObjectIdx) - { - CheckInitialized(); - var id = AssociatedIdentifier(gameObjectIdx); - if (!id.IsValid) - return (false, false, _collectionManager.Active.Default.Name); - - if (_collectionManager.Active.Individuals.TryGetValue(id, out var collection)) - return (true, true, collection.Name); - - AssociatedCollection(gameObjectIdx, out collection); - return (true, false, collection.Name); - } - - public (PenumbraApiEc, string OldCollection) SetCollectionForObject(int gameObjectIdx, string collectionName, bool allowCreateNew, - bool allowDelete) - { - CheckInitialized(); - var id = AssociatedIdentifier(gameObjectIdx); - if (!id.IsValid) - return (PenumbraApiEc.InvalidIdentifier, _collectionManager.Active.Default.Name); - - var oldCollection = _collectionManager.Active.Individuals.TryGetValue(id, out var c) ? c.Name : string.Empty; - - if (collectionName.Length == 0) - { - if (oldCollection.Length == 0) - return (PenumbraApiEc.NothingChanged, oldCollection); - - if (!allowDelete) - return (PenumbraApiEc.AssignmentDeletionDisallowed, oldCollection); - - var idx = _collectionManager.Active.Individuals.Index(id); - _collectionManager.Active.RemoveIndividualCollection(idx); - return (PenumbraApiEc.Success, oldCollection); - } - - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return (PenumbraApiEc.CollectionMissing, oldCollection); - - if (oldCollection.Length == 0) - { - if (!allowCreateNew) - return (PenumbraApiEc.AssignmentCreationDisallowed, oldCollection); - - var ids = _collectionManager.Active.Individuals.GetGroup(id); - _collectionManager.Active.CreateIndividualCollection(ids); - } - else if (oldCollection == collection.Name) - { - return (PenumbraApiEc.NothingChanged, oldCollection); - } - - _collectionManager.Active.SetCollection(collection, CollectionType.Individual, _collectionManager.Active.Individuals.Index(id)); - return (PenumbraApiEc.Success, oldCollection); - } - - public IList GetCollections() - { - CheckInitialized(); - return _collectionManager.Storage.Select(c => c.Name).ToArray(); - } - - public string GetCurrentCollection() - { - CheckInitialized(); - return _collectionManager.Active.Current.Name; - } - - public string GetDefaultCollection() - { - CheckInitialized(); - return _collectionManager.Active.Default.Name; - } - - public string GetInterfaceCollection() - { - CheckInitialized(); - return _collectionManager.Active.Interface.Name; - } - - // TODO: cleanup when incrementing API level - public (string, bool) GetCharacterCollection(string characterName) - => GetCharacterCollection(characterName, ushort.MaxValue); - - public (string, bool) GetCharacterCollection(string characterName, ushort worldId) - { - CheckInitialized(); - return _collectionManager.Active.Individuals.TryGetCollection(NameToIdentifier(characterName, worldId), out var collection) - ? (collection.Name, true) - : (_collectionManager.Active.Default.Name, false); - } - - public unsafe (nint, string) GetDrawObjectInfo(nint drawObject) - { - CheckInitialized(); - var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - return (data.AssociatedGameObject, data.ModCollection.Name); - } - - public int GetCutsceneParentIndex(int actorIdx) - { - CheckInitialized(); - return _cutsceneService.GetParentIndex(actorIdx); - } - - public PenumbraApiEc SetCutsceneParentIndex(int copyIdx, int newParentIdx) - { - CheckInitialized(); - if (_cutsceneService.SetParentIndex(copyIdx, newParentIdx)) - return PenumbraApiEc.Success; - - return PenumbraApiEc.InvalidArgument; - } - - public IList<(string, string)> GetModList() - { - CheckInitialized(); - return _modManager.Select(m => (m.ModPath.Name, m.Name.Text)).ToArray(); - } - - public IDictionary, GroupType)>? GetAvailableModSettings(string modDirectory, string modName) - { - CheckInitialized(); - return _modManager.TryGetMod(modDirectory, modName, out var mod) - ? mod.Groups.ToDictionary(g => g.Name, g => ((IList)g.Select(o => o.Name).ToList(), g.Type)) - : null; - } - - public (PenumbraApiEc, (bool, int, IDictionary>, bool)?) GetCurrentModSettings(string collectionName, - string modDirectory, string modName, bool allowInheritance) - { - CheckInitialized(); - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return (PenumbraApiEc.CollectionMissing, null); - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return (PenumbraApiEc.ModMissing, null); - - var settings = allowInheritance ? collection.Settings[mod.Index] : collection[mod.Index].Settings; - if (settings == null) - return (PenumbraApiEc.Success, null); - - var shareSettings = settings.ConvertToShareable(mod); - return (PenumbraApiEc.Success, - (shareSettings.Enabled, shareSettings.Priority.Value, shareSettings.Settings, collection.Settings[mod.Index] != null)); - } - - public PenumbraApiEc ReloadMod(string modDirectory, string modName) - { - CheckInitialized(); - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return Return(PenumbraApiEc.ModMissing, Args("ModDirectory", modDirectory, "ModName", modName)); - - _modManager.ReloadMod(mod); - return Return(PenumbraApiEc.Success, Args("ModDirectory", modDirectory, "ModName", modName)); - } - - public PenumbraApiEc InstallMod(string modFilePackagePath) - { - if (File.Exists(modFilePackagePath)) - { - _modImportManager.AddUnpack(modFilePackagePath); - return Return(PenumbraApiEc.Success, Args("ModFilePackagePath", modFilePackagePath)); - } - else - { - return Return(PenumbraApiEc.FileMissing, Args("ModFilePackagePath", modFilePackagePath)); - } - } - - public PenumbraApiEc AddMod(string modDirectory) - { - CheckInitialized(); - var dir = new DirectoryInfo(Path.Join(_modManager.BasePath.FullName, Path.GetFileName(modDirectory))); - if (!dir.Exists) - return Return(PenumbraApiEc.FileMissing, Args("ModDirectory", modDirectory)); - - - _modManager.AddMod(dir); - if (_config.UseFileSystemCompression) - new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), - CompressionAlgorithm.Xpress8K); - return Return(PenumbraApiEc.Success, Args("ModDirectory", modDirectory)); - } - - public PenumbraApiEc DeleteMod(string modDirectory, string modName) - { - CheckInitialized(); - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return Return(PenumbraApiEc.NothingChanged, Args("ModDirectory", modDirectory, "ModName", modName)); - - _modManager.DeleteMod(mod); - return Return(PenumbraApiEc.Success, Args("ModDirectory", modDirectory, "ModName", modName)); - } - - public event Action? ModDeleted; - public event Action? ModAdded; - public event Action? ModMoved; - - private void ModPathChangeSubscriber(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, - DirectoryInfo? newDirectory) - { - switch (type) - { - case ModPathChangeType.Reloaded: - TriggerSettingEdited(mod); - break; - case ModPathChangeType.Deleted when oldDirectory != null: - ModDeleted?.Invoke(oldDirectory.Name); - break; - case ModPathChangeType.Added when newDirectory != null: - ModAdded?.Invoke(newDirectory.Name); - break; - case ModPathChangeType.Moved when newDirectory != null && oldDirectory != null: - ModMoved?.Invoke(oldDirectory.Name, newDirectory.Name); - break; - } - } - - public (PenumbraApiEc, string, bool) GetModPath(string modDirectory, string modName) - { - CheckInitialized(); - if (!_modManager.TryGetMod(modDirectory, modName, out var mod) - || !_modFileSystem.FindLeaf(mod, out var leaf)) - return (PenumbraApiEc.ModMissing, string.Empty, false); - - var fullPath = leaf.FullName(); - - return (PenumbraApiEc.Success, fullPath, !ModFileSystem.ModHasDefaultPath(mod, fullPath)); - } - - public PenumbraApiEc SetModPath(string modDirectory, string modName, string newPath) - { - CheckInitialized(); - if (newPath.Length == 0) - return PenumbraApiEc.InvalidArgument; - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod) - || !_modFileSystem.FindLeaf(mod, out var leaf)) - return PenumbraApiEc.ModMissing; - - try - { - _modFileSystem.RenameAndMove(leaf, newPath); - return PenumbraApiEc.Success; - } - catch - { - return PenumbraApiEc.PathRenameFailed; - } - } - - public PenumbraApiEc TryInheritMod(string collectionName, string modDirectory, string modName, bool inherit) - { - CheckInitialized(); - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return PenumbraApiEc.CollectionMissing; - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.ModMissing; - - - return _collectionEditor.SetModInheritance(collection, mod, inherit) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged; - } - - public PenumbraApiEc TrySetMod(string collectionName, string modDirectory, string modName, bool enabled) - { - CheckInitialized(); - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return PenumbraApiEc.CollectionMissing; - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.ModMissing; - - return _collectionEditor.SetModState(collection, mod, enabled) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged; - } - - public PenumbraApiEc TrySetModPriority(string collectionName, string modDirectory, string modName, int priority) - { - CheckInitialized(); - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return PenumbraApiEc.CollectionMissing; - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return PenumbraApiEc.ModMissing; - - return _collectionEditor.SetModPriority(collection, mod, new ModPriority(priority)) - ? PenumbraApiEc.Success - : PenumbraApiEc.NothingChanged; - } - - public PenumbraApiEc TrySetModSetting(string collectionName, string modDirectory, string modName, string optionGroupName, - string optionName) - { - CheckInitialized(); - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return Return(PenumbraApiEc.CollectionMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "OptionName", optionName)); - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return Return(PenumbraApiEc.ModMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "OptionName", optionName)); - - var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); - if (groupIdx < 0) - return Return(PenumbraApiEc.OptionGroupMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "OptionName", optionName)); - - var optionIdx = mod.Groups[groupIdx].IndexOf(o => o.Name == optionName); - if (optionIdx < 0) - return Return(PenumbraApiEc.OptionMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "OptionName", optionName)); - - var setting = mod.Groups[groupIdx].Type switch - { - GroupType.Multi => Setting.Multi(optionIdx), - GroupType.Single => Setting.Single(optionIdx), - _ => Setting.Zero, - }; - - return Return( - _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "OptionName", optionName)); - } - - public PenumbraApiEc TrySetModSettings(string collectionName, string modDirectory, string modName, string optionGroupName, - IReadOnlyList optionNames) - { - CheckInitialized(); - if (!_collectionManager.Storage.ByName(collectionName, out var collection)) - return Return(PenumbraApiEc.CollectionMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "#optionNames", optionNames.Count.ToString())); - - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return Return(PenumbraApiEc.ModMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "#optionNames", optionNames.Count.ToString())); - - var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); - if (groupIdx < 0) - return Return(PenumbraApiEc.OptionGroupMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "#optionNames", optionNames.Count.ToString())); - - var group = mod.Groups[groupIdx]; - - var setting = Setting.Zero; - if (group.Type == GroupType.Single) - { - var optionIdx = optionNames.Count == 0 ? -1 : group.IndexOf(o => o.Name == optionNames[^1]); - if (optionIdx < 0) - return Return(PenumbraApiEc.OptionMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "#optionNames", optionNames.Count.ToString())); - - setting = Setting.Single(optionIdx); - } - else - { - foreach (var name in optionNames) - { - var optionIdx = group.IndexOf(o => o.Name == name); - if (optionIdx < 0) - return Return(PenumbraApiEc.OptionMissing, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", - optionGroupName, "#optionNames", optionNames.Count.ToString())); - - setting |= Setting.Multi(optionIdx); - } - } - - return Return( - _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, - Args("CollectionName", collectionName, "ModDirectory", modDirectory, "ModName", modName, "OptionGroupName", optionGroupName, - "#optionNames", optionNames.Count.ToString())); - } - - - public PenumbraApiEc CopyModSettings(string? collectionName, string modDirectoryFrom, string modDirectoryTo) - { - CheckInitialized(); - - var sourceMod = _modManager.FirstOrDefault(m => string.Equals(m.ModPath.Name, modDirectoryFrom, StringComparison.OrdinalIgnoreCase)); - var targetMod = _modManager.FirstOrDefault(m => string.Equals(m.ModPath.Name, modDirectoryTo, StringComparison.OrdinalIgnoreCase)); - if (string.IsNullOrEmpty(collectionName)) - foreach (var collection in _collectionManager.Storage) - _collectionEditor.CopyModSettings(collection, sourceMod, modDirectoryFrom, targetMod, modDirectoryTo); - else if (_collectionManager.Storage.ByName(collectionName, out var collection)) - _collectionEditor.CopyModSettings(collection, sourceMod, modDirectoryFrom, targetMod, modDirectoryTo); - else - return PenumbraApiEc.CollectionMissing; - - return PenumbraApiEc.Success; - } - - public (PenumbraApiEc, string) CreateTemporaryCollection(string tag, string character, bool forceOverwriteCharacter) - { - CheckInitialized(); - - if (!ActorIdentifierFactory.VerifyPlayerName(character.AsSpan()) || tag.Length == 0) - return (PenumbraApiEc.InvalidArgument, string.Empty); - - var identifier = NameToIdentifier(character, ushort.MaxValue); - if (!identifier.IsValid) - return (PenumbraApiEc.InvalidArgument, string.Empty); - - if (!forceOverwriteCharacter && _collectionManager.Active.Individuals.ContainsKey(identifier) - || _tempCollections.Collections.ContainsKey(identifier)) - return (PenumbraApiEc.CharacterCollectionExists, string.Empty); - - var name = $"{tag}_{character}"; - var ret = CreateNamedTemporaryCollection(name); - if (ret != PenumbraApiEc.Success) - return (ret, name); - - if (_tempCollections.AddIdentifier(name, identifier)) - return (PenumbraApiEc.Success, name); - - _tempCollections.RemoveTemporaryCollection(name); - return (PenumbraApiEc.UnknownError, string.Empty); - } - - public PenumbraApiEc CreateNamedTemporaryCollection(string name) - { - CheckInitialized(); - if (name.Length == 0 || ModCreator.ReplaceBadXivSymbols(name, _config.ReplaceNonAsciiOnImport) != name || name.Contains('|')) - return PenumbraApiEc.InvalidArgument; - - return _tempCollections.CreateTemporaryCollection(name).Length > 0 - ? PenumbraApiEc.Success - : PenumbraApiEc.CollectionExists; - } - - public PenumbraApiEc AssignTemporaryCollection(string collectionName, int actorIndex, bool forceAssignment) - { - CheckInitialized(); - - if (actorIndex < 0 || actorIndex >= _objects.TotalCount) - return PenumbraApiEc.InvalidArgument; - - var identifier = _actors.FromObject(_objects[actorIndex], out _, false, false, true); - if (!identifier.IsValid) - return PenumbraApiEc.InvalidArgument; - - if (!_tempCollections.CollectionByName(collectionName, out var collection)) - return PenumbraApiEc.CollectionMissing; - - if (forceAssignment) - { - if (_tempCollections.Collections.ContainsKey(identifier) && !_tempCollections.Collections.Delete(identifier)) - return PenumbraApiEc.AssignmentDeletionFailed; - } - else if (_tempCollections.Collections.ContainsKey(identifier) - || _collectionManager.Active.Individuals.ContainsKey(identifier)) - { - return PenumbraApiEc.CharacterCollectionExists; - } - - var group = _tempCollections.Collections.GetGroup(identifier); - return _tempCollections.AddIdentifier(collection, group) - ? PenumbraApiEc.Success - : PenumbraApiEc.UnknownError; - } - - public PenumbraApiEc RemoveTemporaryCollection(string character) - { - CheckInitialized(); - return _tempCollections.RemoveByCharacterName(character) - ? PenumbraApiEc.Success - : PenumbraApiEc.NothingChanged; - } - - public PenumbraApiEc RemoveTemporaryCollectionByName(string name) - { - CheckInitialized(); - return _tempCollections.RemoveTemporaryCollection(name) - ? PenumbraApiEc.Success - : PenumbraApiEc.NothingChanged; - } - - public PenumbraApiEc AddTemporaryModAll(string tag, Dictionary paths, string manipString, int priority) - { - CheckInitialized(); - if (!ConvertPaths(paths, out var p)) - return PenumbraApiEc.InvalidGamePath; - - if (!ConvertManips(manipString, out var m)) - return PenumbraApiEc.InvalidManipulation; - - return _tempMods.Register(tag, null, p, m, new ModPriority(priority)) switch - { - RedirectResult.Success => PenumbraApiEc.Success, - _ => PenumbraApiEc.UnknownError, - }; - } - - public PenumbraApiEc AddTemporaryMod(string tag, string collectionName, Dictionary paths, string manipString, - int priority) - { - CheckInitialized(); - if (!_tempCollections.CollectionByName(collectionName, out var collection) - && !_collectionManager.Storage.ByName(collectionName, out collection)) - return PenumbraApiEc.CollectionMissing; - - if (!ConvertPaths(paths, out var p)) - return PenumbraApiEc.InvalidGamePath; - - if (!ConvertManips(manipString, out var m)) - return PenumbraApiEc.InvalidManipulation; - - return _tempMods.Register(tag, collection, p, m, new ModPriority(priority)) switch - { - RedirectResult.Success => PenumbraApiEc.Success, - _ => PenumbraApiEc.UnknownError, - }; - } - - public PenumbraApiEc RemoveTemporaryModAll(string tag, int priority) - { - CheckInitialized(); - return _tempMods.Unregister(tag, null, new ModPriority(priority)) switch - { - RedirectResult.Success => PenumbraApiEc.Success, - RedirectResult.NotRegistered => PenumbraApiEc.NothingChanged, - _ => PenumbraApiEc.UnknownError, - }; - } - - public PenumbraApiEc RemoveTemporaryMod(string tag, string collectionName, int priority) - { - CheckInitialized(); - if (!_tempCollections.CollectionByName(collectionName, out var collection) - && !_collectionManager.Storage.ByName(collectionName, out collection)) - return PenumbraApiEc.CollectionMissing; - - return _tempMods.Unregister(tag, collection, new ModPriority(priority)) switch - { - RedirectResult.Success => PenumbraApiEc.Success, - RedirectResult.NotRegistered => PenumbraApiEc.NothingChanged, - _ => PenumbraApiEc.UnknownError, - }; - } - - public string GetPlayerMetaManipulations() - { - CheckInitialized(); - var collection = _collectionResolver.PlayerCollection(); - var set = collection.MetaCache?.Manipulations.ToArray() ?? Array.Empty(); - return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); - } - - public Task ConvertTextureFile(string inputFile, string outputFile, TextureType textureType, bool mipMaps) - => textureType switch - { - TextureType.Png => _textureManager.SavePng(inputFile, outputFile), - TextureType.AsIsTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, inputFile, outputFile), - TextureType.AsIsDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, inputFile, outputFile), - TextureType.RgbaTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, inputFile, outputFile), - TextureType.RgbaDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, false, inputFile, outputFile), - TextureType.Bc3Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, true, inputFile, outputFile), - TextureType.Bc3Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, inputFile, outputFile), - TextureType.Bc7Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, inputFile, outputFile), - TextureType.Bc7Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, inputFile, outputFile), - _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), - }; - - // @formatter:off - public Task ConvertTextureData(byte[] rgbaData, int width, string outputFile, TextureType textureType, bool mipMaps) - => textureType switch - { - TextureType.Png => _textureManager.SavePng(new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.AsIsTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.AsIsDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.RgbaTex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.RgbaDds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.Bc3Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.Bc3Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.Bc7Tex => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - TextureType.Bc7Dds => _textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), - _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), - }; - // @formatter:on - - public IReadOnlyDictionary?[] GetGameObjectResourcePaths(ushort[] gameObjects) - { - var characters = gameObjects.Select(index => _objects.GetDalamudObject((int)index)).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, 0); - var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); - - return Array.ConvertAll(gameObjects, obj => pathDictionaries.GetValueOrDefault(obj)); - } - - public IReadOnlyDictionary> GetPlayerResourcePaths() - { - var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly); - var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); - - return pathDictionaries.AsReadOnly(); - } - - public IReadOnlyDictionary?[] GetGameObjectResourcesOfType(ResourceType type, bool withUiData, - params ushort[] gameObjects) - { - var characters = gameObjects.Select(index => _objects.GetDalamudObject((int)index)).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); - var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); - - return Array.ConvertAll(gameObjects, obj => resDictionaries.GetValueOrDefault(obj)); - } - - public IReadOnlyDictionary> GetPlayerResourcesOfType(ResourceType type, - bool withUiData) - { - var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly - | (withUiData ? ResourceTreeFactory.Flags.WithUiData : 0)); - var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); - - return resDictionaries.AsReadOnly(); - } - - public Ipc.ResourceTree?[] GetGameObjectResourceTrees(bool withUiData, params ushort[] gameObjects) - { - var characters = gameObjects.Select(index => _objects.GetDalamudObject((int)index)).OfType(); - var resourceTrees = _resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); - var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); - - return Array.ConvertAll(gameObjects, obj => resDictionary.GetValueOrDefault(obj)); - } - - public IReadOnlyDictionary GetPlayerResourceTrees(bool withUiData) - { - var resourceTrees = _resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly - | (withUiData ? ResourceTreeFactory.Flags.WithUiData : 0)); - var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); - - return resDictionary.AsReadOnly(); - } - - // TODO: cleanup when incrementing API - public string GetMetaManipulations(string characterName) - => GetMetaManipulations(characterName, ushort.MaxValue); - - public string GetMetaManipulations(string characterName, ushort worldId) - { - CheckInitialized(); - var identifier = NameToIdentifier(characterName, worldId); - var collection = _tempCollections.Collections.TryGetCollection(identifier, out var c) - ? c - : _collectionManager.Active.Individual(identifier); - var set = collection.MetaCache?.Manipulations.ToArray() ?? []; - return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); - } - - public string GetGameObjectMetaManipulations(int gameObjectIdx) - { - CheckInitialized(); - AssociatedCollection(gameObjectIdx, out var collection); - var set = collection.MetaCache?.Manipulations.ToArray() ?? []; - return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void CheckInitialized() - { - if (!Valid) - throw new Exception("PluginShare is not initialized."); - } - - // Return the collection associated to a current game object. If it does not exist, return the default collection. - // If the index is invalid, returns false and the default collection. - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private unsafe bool AssociatedCollection(int gameObjectIdx, out ModCollection collection) - { - collection = _collectionManager.Active.Default; - if (gameObjectIdx < 0 || gameObjectIdx >= _objects.TotalCount) - return false; - - var ptr = _objects[gameObjectIdx]; - var data = _collectionResolver.IdentifyCollection(ptr.AsObject, false); - if (data.Valid) - collection = data.ModCollection; - - return true; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private ActorIdentifier AssociatedIdentifier(int gameObjectIdx) - { - if (gameObjectIdx < 0 || gameObjectIdx >= _objects.TotalCount) - return ActorIdentifier.Invalid; - - var ptr = _objects[gameObjectIdx]; - return _actors.FromObject(ptr, out _, false, true, true); - } - - // Resolve a path given by string for a specific collection. - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private string ResolvePath(string path, ModManager _, ModCollection collection) - { - if (!_config.EnableMods) - return path; - - var gamePath = Utf8GamePath.FromString(path, out var p, true) ? p : Utf8GamePath.Empty; - var ret = collection.ResolvePath(gamePath); - return ret?.ToString() ?? path; - } - - // Get a file for a resolved path. - private T? GetFileIntern(string resolvedPath) where T : FileResource - { - CheckInitialized(); - try - { - return Path.IsPathRooted(resolvedPath) - ? _lumina?.GetFileFromDisk(resolvedPath) - : _gameData.GetFile(resolvedPath); - } - catch (Exception e) - { - Penumbra.Log.Warning($"Could not load file {resolvedPath}:\n{e}"); - return null; - } - } - - - // Convert a dictionary of strings to a dictionary of gamepaths to full paths. - // Only returns true if all paths can successfully be converted and added. - private static bool ConvertPaths(IReadOnlyDictionary redirections, - [NotNullWhen(true)] out Dictionary? paths) - { - paths = new Dictionary(redirections.Count); - foreach (var (gString, fString) in redirections) - { - if (!Utf8GamePath.FromString(gString, out var path, false)) - { - paths = null; - return false; - } - - var fullPath = new FullPath(fString); - if (!paths.TryAdd(path, fullPath)) - { - paths = null; - return false; - } - } - - return true; - } - - // Convert manipulations from a transmitted base64 string to actual manipulations. - // The empty string is treated as an empty set. - // Only returns true if all conversions are successful and distinct. - private static bool ConvertManips(string manipString, - [NotNullWhen(true)] out HashSet? manips) - { - if (manipString.Length == 0) - { - manips = new HashSet(); - return true; - } - - if (Functions.FromCompressedBase64(manipString, out var manipArray) != MetaManipulation.CurrentVersion) - { - manips = null; - return false; - } - - manips = new HashSet(manipArray!.Length); - foreach (var manip in manipArray.Where(m => m.Validate())) - { - if (manips.Add(manip)) - continue; - - Penumbra.Log.Warning($"Manipulation {manip} {manip.EntryToString()} is invalid and was skipped."); - manips = null; - return false; - } - - return true; - } - - // TODO: replace all usages with ActorIdentifier stuff when incrementing API - private ActorIdentifier NameToIdentifier(string name, ushort worldId) - { - // Verified to be valid name beforehand. - var b = ByteString.FromStringUnsafe(name, false); - return _actors.CreatePlayer(b, worldId); - } - - private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting _1, int _2, bool inherited) - => ModSettingChanged?.Invoke(type, collection.Name, mod?.ModPath.Name ?? string.Empty, inherited); - - private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) - => CreatedCharacterBase?.Invoke(gameObject, collection.Name, drawObject); - - private void OnModOptionEdited(ModOptionChangeType type, Mod mod, int groupIndex, int optionIndex, int moveIndex) - { - switch (type) - { - case ModOptionChangeType.GroupDeleted: - case ModOptionChangeType.GroupMoved: - case ModOptionChangeType.GroupTypeChanged: - case ModOptionChangeType.PriorityChanged: - case ModOptionChangeType.OptionDeleted: - case ModOptionChangeType.OptionMoved: - case ModOptionChangeType.OptionFilesChanged: - case ModOptionChangeType.OptionFilesAdded: - case ModOptionChangeType.OptionSwapsChanged: - case ModOptionChangeType.OptionMetaChanged: - TriggerSettingEdited(mod); - break; - } - } - - private void OnModFileChanged(Mod mod, FileRegistry file) - { - if (file.CurrentUsage == 0) - return; - - TriggerSettingEdited(mod); - } - - private void TriggerSettingEdited(Mod mod) - { - var collection = _collectionResolver.PlayerCollection(); - var (settings, parent) = collection[mod.Index]; - if (settings is { Enabled: true }) - ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Name, mod.Identifier, parent != collection); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static LazyString Args(params string[] arguments) - { - if (arguments.Length == 0) - return new LazyString(() => "no arguments"); - - return new LazyString(() => - { - var sb = new StringBuilder(); - for (var i = 0; i < arguments.Length / 2; ++i) - { - sb.Append(arguments[2 * i]); - sb.Append(" = "); - sb.Append(arguments[2 * i + 1]); - sb.Append(", "); - } - - return sb.ToString(0, sb.Length - 2); - }); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static PenumbraApiEc Return(PenumbraApiEc ec, LazyString args, [CallerMemberName] string name = "Unknown") - { - Penumbra.Log.Debug( - $"[{name}] Called with {args}, returned {ec}."); - return ec; - } -} diff --git a/Penumbra/Api/PenumbraIpcProviders.cs b/Penumbra/Api/PenumbraIpcProviders.cs deleted file mode 100644 index 78887156..00000000 --- a/Penumbra/Api/PenumbraIpcProviders.cs +++ /dev/null @@ -1,435 +0,0 @@ -using Dalamud.Game.ClientState.Objects.Types; -using Dalamud.Plugin; -using Penumbra.GameData.Enums; -using Penumbra.Api.Enums; -using Penumbra.Api.Helpers; -using Penumbra.Collections.Manager; -using Penumbra.Mods.Manager; -using Penumbra.Services; -using Penumbra.Util; - -namespace Penumbra.Api; - -using CurrentSettings = ValueTuple>, bool)?>; - -public class PenumbraIpcProviders : IDisposable -{ - internal readonly IPenumbraApi Api; - - // Plugin State - internal readonly EventProvider Initialized; - internal readonly EventProvider Disposed; - internal readonly FuncProvider ApiVersion; - internal readonly FuncProvider<(int Breaking, int Features)> ApiVersions; - internal readonly FuncProvider GetEnabledState; - internal readonly EventProvider EnabledChange; - - // Configuration - internal readonly FuncProvider GetModDirectory; - internal readonly FuncProvider GetConfiguration; - internal readonly EventProvider ModDirectoryChanged; - - // UI - internal readonly EventProvider PreSettingsTabBarDraw; - internal readonly EventProvider PreSettingsDraw; - internal readonly EventProvider PostEnabledDraw; - internal readonly EventProvider PostSettingsDraw; - internal readonly EventProvider ChangedItemTooltip; - internal readonly EventProvider ChangedItemClick; - internal readonly FuncProvider OpenMainWindow; - internal readonly ActionProvider CloseMainWindow; - - // Redrawing - internal readonly ActionProvider RedrawAll; - internal readonly ActionProvider RedrawObject; - internal readonly ActionProvider RedrawObjectByIndex; - internal readonly ActionProvider RedrawObjectByName; - internal readonly EventProvider GameObjectRedrawn; - - // Game State - internal readonly FuncProvider GetDrawObjectInfo; - internal readonly FuncProvider GetCutsceneParentIndex; - internal readonly FuncProvider SetCutsceneParentIndex; - internal readonly EventProvider CreatingCharacterBase; - internal readonly EventProvider CreatedCharacterBase; - internal readonly EventProvider GameObjectResourcePathResolved; - - // Resolve - internal readonly FuncProvider ResolveDefaultPath; - internal readonly FuncProvider ResolveInterfacePath; - internal readonly FuncProvider ResolvePlayerPath; - internal readonly FuncProvider ResolveGameObjectPath; - internal readonly FuncProvider ResolveCharacterPath; - internal readonly FuncProvider ReverseResolvePath; - internal readonly FuncProvider ReverseResolveGameObjectPath; - internal readonly FuncProvider ReverseResolvePlayerPath; - internal readonly FuncProvider ResolvePlayerPaths; - internal readonly FuncProvider> ResolvePlayerPathsAsync; - - // Collections - internal readonly FuncProvider> GetCollections; - internal readonly FuncProvider GetCurrentCollectionName; - internal readonly FuncProvider GetDefaultCollectionName; - internal readonly FuncProvider GetInterfaceCollectionName; - internal readonly FuncProvider GetCharacterCollectionName; - internal readonly FuncProvider GetCollectionForType; - internal readonly FuncProvider SetCollectionForType; - internal readonly FuncProvider GetCollectionForObject; - internal readonly FuncProvider SetCollectionForObject; - internal readonly FuncProvider> GetChangedItems; - - // Meta - internal readonly FuncProvider GetPlayerMetaManipulations; - internal readonly FuncProvider GetMetaManipulations; - internal readonly FuncProvider GetGameObjectMetaManipulations; - - // Mods - internal readonly FuncProvider> GetMods; - internal readonly FuncProvider ReloadMod; - internal readonly FuncProvider InstallMod; - internal readonly FuncProvider AddMod; - internal readonly FuncProvider DeleteMod; - internal readonly FuncProvider GetModPath; - internal readonly FuncProvider SetModPath; - internal readonly EventProvider ModDeleted; - internal readonly EventProvider ModAdded; - internal readonly EventProvider ModMoved; - - // ModSettings - internal readonly FuncProvider, GroupType)>?> GetAvailableModSettings; - internal readonly FuncProvider GetCurrentModSettings; - internal readonly FuncProvider TryInheritMod; - internal readonly FuncProvider TrySetMod; - internal readonly FuncProvider TrySetModPriority; - internal readonly FuncProvider TrySetModSetting; - internal readonly FuncProvider, PenumbraApiEc> TrySetModSettings; - internal readonly EventProvider ModSettingChanged; - internal readonly FuncProvider CopyModSettings; - - // Editing - internal readonly FuncProvider ConvertTextureFile; - internal readonly FuncProvider ConvertTextureData; - - // Temporary - internal readonly FuncProvider CreateTemporaryCollection; - internal readonly FuncProvider RemoveTemporaryCollection; - internal readonly FuncProvider CreateNamedTemporaryCollection; - internal readonly FuncProvider RemoveTemporaryCollectionByName; - internal readonly FuncProvider AssignTemporaryCollection; - internal readonly FuncProvider, string, int, PenumbraApiEc> AddTemporaryModAll; - internal readonly FuncProvider, string, int, PenumbraApiEc> AddTemporaryMod; - internal readonly FuncProvider RemoveTemporaryModAll; - internal readonly FuncProvider RemoveTemporaryMod; - - // Resource Tree - internal readonly FuncProvider?[]> GetGameObjectResourcePaths; - internal readonly FuncProvider>> GetPlayerResourcePaths; - - internal readonly FuncProvider?[]> - GetGameObjectResourcesOfType; - - internal readonly - FuncProvider>> - GetPlayerResourcesOfType; - - internal readonly FuncProvider GetGameObjectResourceTrees; - internal readonly FuncProvider> GetPlayerResourceTrees; - - public PenumbraIpcProviders(DalamudPluginInterface pi, IPenumbraApi api, ModManager modManager, CollectionManager collections, - TempModManager tempMods, TempCollectionManager tempCollections, SaveService saveService, Configuration config) - { - Api = api; - - // Plugin State - Initialized = Ipc.Initialized.Provider(pi); - Disposed = Ipc.Disposed.Provider(pi); - ApiVersion = Ipc.ApiVersion.Provider(pi, DeprecatedVersion); - ApiVersions = Ipc.ApiVersions.Provider(pi, () => Api.ApiVersion); - GetEnabledState = Ipc.GetEnabledState.Provider(pi, Api.GetEnabledState); - EnabledChange = - Ipc.EnabledChange.Provider(pi, () => Api.EnabledChange += EnabledChangeEvent, () => Api.EnabledChange -= EnabledChangeEvent); - - // Configuration - GetModDirectory = Ipc.GetModDirectory.Provider(pi, Api.GetModDirectory); - GetConfiguration = Ipc.GetConfiguration.Provider(pi, Api.GetConfiguration); - ModDirectoryChanged = Ipc.ModDirectoryChanged.Provider(pi, a => Api.ModDirectoryChanged += a, a => Api.ModDirectoryChanged -= a); - - // UI - PreSettingsTabBarDraw = - Ipc.PreSettingsTabBarDraw.Provider(pi, a => Api.PreSettingsTabBarDraw += a, a => Api.PreSettingsTabBarDraw -= a); - PreSettingsDraw = Ipc.PreSettingsDraw.Provider(pi, a => Api.PreSettingsPanelDraw += a, a => Api.PreSettingsPanelDraw -= a); - PostEnabledDraw = - Ipc.PostEnabledDraw.Provider(pi, a => Api.PostEnabledDraw += a, a => Api.PostEnabledDraw -= a); - PostSettingsDraw = Ipc.PostSettingsDraw.Provider(pi, a => Api.PostSettingsPanelDraw += a, a => Api.PostSettingsPanelDraw -= a); - ChangedItemTooltip = - Ipc.ChangedItemTooltip.Provider(pi, () => Api.ChangedItemTooltip += OnTooltip, () => Api.ChangedItemTooltip -= OnTooltip); - ChangedItemClick = Ipc.ChangedItemClick.Provider(pi, () => Api.ChangedItemClicked += OnClick, () => Api.ChangedItemClicked -= OnClick); - OpenMainWindow = Ipc.OpenMainWindow.Provider(pi, Api.OpenMainWindow); - CloseMainWindow = Ipc.CloseMainWindow.Provider(pi, Api.CloseMainWindow); - - // Redrawing - RedrawAll = Ipc.RedrawAll.Provider(pi, Api.RedrawAll); - RedrawObject = Ipc.RedrawObject.Provider(pi, Api.RedrawObject); - RedrawObjectByIndex = Ipc.RedrawObjectByIndex.Provider(pi, Api.RedrawObject); - RedrawObjectByName = Ipc.RedrawObjectByName.Provider(pi, Api.RedrawObject); - GameObjectRedrawn = Ipc.GameObjectRedrawn.Provider(pi, () => Api.GameObjectRedrawn += OnGameObjectRedrawn, - () => Api.GameObjectRedrawn -= OnGameObjectRedrawn); - - // Game State - GetDrawObjectInfo = Ipc.GetDrawObjectInfo.Provider(pi, Api.GetDrawObjectInfo); - GetCutsceneParentIndex = Ipc.GetCutsceneParentIndex.Provider(pi, Api.GetCutsceneParentIndex); - SetCutsceneParentIndex = Ipc.SetCutsceneParentIndex.Provider(pi, Api.SetCutsceneParentIndex); - CreatingCharacterBase = Ipc.CreatingCharacterBase.Provider(pi, - () => Api.CreatingCharacterBase += CreatingCharacterBaseEvent, - () => Api.CreatingCharacterBase -= CreatingCharacterBaseEvent); - CreatedCharacterBase = Ipc.CreatedCharacterBase.Provider(pi, - () => Api.CreatedCharacterBase += CreatedCharacterBaseEvent, - () => Api.CreatedCharacterBase -= CreatedCharacterBaseEvent); - GameObjectResourcePathResolved = Ipc.GameObjectResourcePathResolved.Provider(pi, - () => Api.GameObjectResourceResolved += GameObjectResourceResolvedEvent, - () => Api.GameObjectResourceResolved -= GameObjectResourceResolvedEvent); - - // Resolve - ResolveDefaultPath = Ipc.ResolveDefaultPath.Provider(pi, Api.ResolveDefaultPath); - ResolveInterfacePath = Ipc.ResolveInterfacePath.Provider(pi, Api.ResolveInterfacePath); - ResolvePlayerPath = Ipc.ResolvePlayerPath.Provider(pi, Api.ResolvePlayerPath); - ResolveGameObjectPath = Ipc.ResolveGameObjectPath.Provider(pi, Api.ResolveGameObjectPath); - ResolveCharacterPath = Ipc.ResolveCharacterPath.Provider(pi, Api.ResolvePath); - ReverseResolvePath = Ipc.ReverseResolvePath.Provider(pi, Api.ReverseResolvePath); - ReverseResolveGameObjectPath = Ipc.ReverseResolveGameObjectPath.Provider(pi, Api.ReverseResolveGameObjectPath); - ReverseResolvePlayerPath = Ipc.ReverseResolvePlayerPath.Provider(pi, Api.ReverseResolvePlayerPath); - ResolvePlayerPaths = Ipc.ResolvePlayerPaths.Provider(pi, Api.ResolvePlayerPaths); - ResolvePlayerPathsAsync = Ipc.ResolvePlayerPathsAsync.Provider(pi, Api.ResolvePlayerPathsAsync); - - // Collections - GetCollections = Ipc.GetCollections.Provider(pi, Api.GetCollections); - GetCurrentCollectionName = Ipc.GetCurrentCollectionName.Provider(pi, Api.GetCurrentCollection); - GetDefaultCollectionName = Ipc.GetDefaultCollectionName.Provider(pi, Api.GetDefaultCollection); - GetInterfaceCollectionName = Ipc.GetInterfaceCollectionName.Provider(pi, Api.GetInterfaceCollection); - GetCharacterCollectionName = Ipc.GetCharacterCollectionName.Provider(pi, Api.GetCharacterCollection); - GetCollectionForType = Ipc.GetCollectionForType.Provider(pi, Api.GetCollectionForType); - SetCollectionForType = Ipc.SetCollectionForType.Provider(pi, Api.SetCollectionForType); - GetCollectionForObject = Ipc.GetCollectionForObject.Provider(pi, Api.GetCollectionForObject); - SetCollectionForObject = Ipc.SetCollectionForObject.Provider(pi, Api.SetCollectionForObject); - GetChangedItems = Ipc.GetChangedItems.Provider(pi, Api.GetChangedItemsForCollection); - - // Meta - GetPlayerMetaManipulations = Ipc.GetPlayerMetaManipulations.Provider(pi, Api.GetPlayerMetaManipulations); - GetMetaManipulations = Ipc.GetMetaManipulations.Provider(pi, Api.GetMetaManipulations); - GetGameObjectMetaManipulations = Ipc.GetGameObjectMetaManipulations.Provider(pi, Api.GetGameObjectMetaManipulations); - - // Mods - GetMods = Ipc.GetMods.Provider(pi, Api.GetModList); - ReloadMod = Ipc.ReloadMod.Provider(pi, Api.ReloadMod); - InstallMod = Ipc.InstallMod.Provider(pi, Api.InstallMod); - AddMod = Ipc.AddMod.Provider(pi, Api.AddMod); - DeleteMod = Ipc.DeleteMod.Provider(pi, Api.DeleteMod); - GetModPath = Ipc.GetModPath.Provider(pi, Api.GetModPath); - SetModPath = Ipc.SetModPath.Provider(pi, Api.SetModPath); - ModDeleted = Ipc.ModDeleted.Provider(pi, () => Api.ModDeleted += ModDeletedEvent, () => Api.ModDeleted -= ModDeletedEvent); - ModAdded = Ipc.ModAdded.Provider(pi, () => Api.ModAdded += ModAddedEvent, () => Api.ModAdded -= ModAddedEvent); - ModMoved = Ipc.ModMoved.Provider(pi, () => Api.ModMoved += ModMovedEvent, () => Api.ModMoved -= ModMovedEvent); - - // ModSettings - GetAvailableModSettings = Ipc.GetAvailableModSettings.Provider(pi, Api.GetAvailableModSettings); - GetCurrentModSettings = Ipc.GetCurrentModSettings.Provider(pi, Api.GetCurrentModSettings); - TryInheritMod = Ipc.TryInheritMod.Provider(pi, Api.TryInheritMod); - TrySetMod = Ipc.TrySetMod.Provider(pi, Api.TrySetMod); - TrySetModPriority = Ipc.TrySetModPriority.Provider(pi, Api.TrySetModPriority); - TrySetModSetting = Ipc.TrySetModSetting.Provider(pi, Api.TrySetModSetting); - TrySetModSettings = Ipc.TrySetModSettings.Provider(pi, Api.TrySetModSettings); - ModSettingChanged = Ipc.ModSettingChanged.Provider(pi, - () => Api.ModSettingChanged += ModSettingChangedEvent, - () => Api.ModSettingChanged -= ModSettingChangedEvent); - CopyModSettings = Ipc.CopyModSettings.Provider(pi, Api.CopyModSettings); - - // Editing - ConvertTextureFile = Ipc.ConvertTextureFile.Provider(pi, Api.ConvertTextureFile); - ConvertTextureData = Ipc.ConvertTextureData.Provider(pi, Api.ConvertTextureData); - - // Temporary - CreateTemporaryCollection = Ipc.CreateTemporaryCollection.Provider(pi, Api.CreateTemporaryCollection); - RemoveTemporaryCollection = Ipc.RemoveTemporaryCollection.Provider(pi, Api.RemoveTemporaryCollection); - CreateNamedTemporaryCollection = Ipc.CreateNamedTemporaryCollection.Provider(pi, Api.CreateNamedTemporaryCollection); - RemoveTemporaryCollectionByName = Ipc.RemoveTemporaryCollectionByName.Provider(pi, Api.RemoveTemporaryCollectionByName); - AssignTemporaryCollection = Ipc.AssignTemporaryCollection.Provider(pi, Api.AssignTemporaryCollection); - AddTemporaryModAll = Ipc.AddTemporaryModAll.Provider(pi, Api.AddTemporaryModAll); - AddTemporaryMod = Ipc.AddTemporaryMod.Provider(pi, Api.AddTemporaryMod); - RemoveTemporaryModAll = Ipc.RemoveTemporaryModAll.Provider(pi, Api.RemoveTemporaryModAll); - RemoveTemporaryMod = Ipc.RemoveTemporaryMod.Provider(pi, Api.RemoveTemporaryMod); - - // ResourceTree - GetGameObjectResourcePaths = Ipc.GetGameObjectResourcePaths.Provider(pi, Api.GetGameObjectResourcePaths); - GetPlayerResourcePaths = Ipc.GetPlayerResourcePaths.Provider(pi, Api.GetPlayerResourcePaths); - GetGameObjectResourcesOfType = Ipc.GetGameObjectResourcesOfType.Provider(pi, Api.GetGameObjectResourcesOfType); - GetPlayerResourcesOfType = Ipc.GetPlayerResourcesOfType.Provider(pi, Api.GetPlayerResourcesOfType); - GetGameObjectResourceTrees = Ipc.GetGameObjectResourceTrees.Provider(pi, Api.GetGameObjectResourceTrees); - GetPlayerResourceTrees = Ipc.GetPlayerResourceTrees.Provider(pi, Api.GetPlayerResourceTrees); - - Initialized.Invoke(); - } - - public void Dispose() - { - // Plugin State - Initialized.Dispose(); - ApiVersion.Dispose(); - ApiVersions.Dispose(); - GetEnabledState.Dispose(); - EnabledChange.Dispose(); - - // Configuration - GetModDirectory.Dispose(); - GetConfiguration.Dispose(); - ModDirectoryChanged.Dispose(); - - // UI - PreSettingsTabBarDraw.Dispose(); - PreSettingsDraw.Dispose(); - PostEnabledDraw.Dispose(); - PostSettingsDraw.Dispose(); - ChangedItemTooltip.Dispose(); - ChangedItemClick.Dispose(); - OpenMainWindow.Dispose(); - CloseMainWindow.Dispose(); - - // Redrawing - RedrawAll.Dispose(); - RedrawObject.Dispose(); - RedrawObjectByIndex.Dispose(); - RedrawObjectByName.Dispose(); - GameObjectRedrawn.Dispose(); - - // Game State - GetDrawObjectInfo.Dispose(); - GetCutsceneParentIndex.Dispose(); - SetCutsceneParentIndex.Dispose(); - CreatingCharacterBase.Dispose(); - CreatedCharacterBase.Dispose(); - GameObjectResourcePathResolved.Dispose(); - - // Resolve - ResolveDefaultPath.Dispose(); - ResolveInterfacePath.Dispose(); - ResolvePlayerPath.Dispose(); - ResolveGameObjectPath.Dispose(); - ResolveCharacterPath.Dispose(); - ReverseResolvePath.Dispose(); - ReverseResolveGameObjectPath.Dispose(); - ReverseResolvePlayerPath.Dispose(); - ResolvePlayerPaths.Dispose(); - ResolvePlayerPathsAsync.Dispose(); - - // Collections - GetCollections.Dispose(); - GetCurrentCollectionName.Dispose(); - GetDefaultCollectionName.Dispose(); - GetInterfaceCollectionName.Dispose(); - GetCharacterCollectionName.Dispose(); - GetCollectionForType.Dispose(); - SetCollectionForType.Dispose(); - GetCollectionForObject.Dispose(); - SetCollectionForObject.Dispose(); - GetChangedItems.Dispose(); - - // Meta - GetPlayerMetaManipulations.Dispose(); - GetMetaManipulations.Dispose(); - GetGameObjectMetaManipulations.Dispose(); - - // Mods - GetMods.Dispose(); - ReloadMod.Dispose(); - InstallMod.Dispose(); - AddMod.Dispose(); - DeleteMod.Dispose(); - GetModPath.Dispose(); - SetModPath.Dispose(); - ModDeleted.Dispose(); - ModAdded.Dispose(); - ModMoved.Dispose(); - - // ModSettings - GetAvailableModSettings.Dispose(); - GetCurrentModSettings.Dispose(); - TryInheritMod.Dispose(); - TrySetMod.Dispose(); - TrySetModPriority.Dispose(); - TrySetModSetting.Dispose(); - TrySetModSettings.Dispose(); - ModSettingChanged.Dispose(); - CopyModSettings.Dispose(); - - // Temporary - CreateTemporaryCollection.Dispose(); - RemoveTemporaryCollection.Dispose(); - CreateNamedTemporaryCollection.Dispose(); - RemoveTemporaryCollectionByName.Dispose(); - AssignTemporaryCollection.Dispose(); - AddTemporaryModAll.Dispose(); - AddTemporaryMod.Dispose(); - RemoveTemporaryModAll.Dispose(); - RemoveTemporaryMod.Dispose(); - - // Editing - ConvertTextureFile.Dispose(); - ConvertTextureData.Dispose(); - - // Resource Tree - GetGameObjectResourcePaths.Dispose(); - GetPlayerResourcePaths.Dispose(); - GetGameObjectResourcesOfType.Dispose(); - GetPlayerResourcesOfType.Dispose(); - GetGameObjectResourceTrees.Dispose(); - GetPlayerResourceTrees.Dispose(); - - Disposed.Invoke(); - Disposed.Dispose(); - } - - // Wrappers - private int DeprecatedVersion() - { - Penumbra.Log.Warning($"{Ipc.ApiVersion.Label} is outdated. Please use {Ipc.ApiVersions.Label} instead."); - return Api.ApiVersion.Breaking; - } - - private void OnClick(MouseButton click, object? item) - { - var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(item); - ChangedItemClick.Invoke(click, type, id); - } - - private void OnTooltip(object? item) - { - var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(item); - ChangedItemTooltip.Invoke(type, id); - } - - private void EnabledChangeEvent(bool value) - => EnabledChange.Invoke(value); - - private void OnGameObjectRedrawn(IntPtr objectAddress, int objectTableIndex) - => GameObjectRedrawn.Invoke(objectAddress, objectTableIndex); - - private void CreatingCharacterBaseEvent(IntPtr gameObject, string collectionName, IntPtr modelId, IntPtr customize, IntPtr equipData) - => CreatingCharacterBase.Invoke(gameObject, collectionName, modelId, customize, equipData); - - private void CreatedCharacterBaseEvent(IntPtr gameObject, string collectionName, IntPtr drawObject) - => CreatedCharacterBase.Invoke(gameObject, collectionName, drawObject); - - private void GameObjectResourceResolvedEvent(IntPtr gameObject, string gamePath, string localPath) - => GameObjectResourcePathResolved.Invoke(gameObject, gamePath, localPath); - - private void ModSettingChangedEvent(ModSettingChange type, string collection, string mod, bool inherited) - => ModSettingChanged.Invoke(type, collection, mod, inherited); - - private void ModDeletedEvent(string name) - => ModDeleted.Invoke(name); - - private void ModAddedEvent(string name) - => ModAdded.Invoke(name); - - private void ModMovedEvent(string from, string to) - => ModMoved.Invoke(from, to); -} diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 72f0fb59..e1b32204 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -243,14 +243,14 @@ public sealed class CollectionCache : IDisposable continue; var config = settings.Settings[groupIndex]; - switch (group.Type) + switch (group) { - case GroupType.Single: - AddSubMod(group[config.AsIndex], mod); + case SingleModGroup single: + AddSubMod(single[config.AsIndex], mod); break; - case GroupType.Multi: + case MultiModGroup multi: { - foreach (var (option, _) in group.WithIndex() + foreach (var (option, _) in multi.WithIndex() .Where(p => config.HasFlag(p.Index)) .OrderByDescending(p => group.OptionPriority(p.Index))) AddSubMod(option, mod); diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index f6c6e14a..4b5c4337 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -119,7 +119,7 @@ public class CollectionCacheManager : IDisposable /// Does not create caches. /// public void CalculateEffectiveFileList(ModCollection collection) - => _framework.RegisterImportant(nameof(CalculateEffectiveFileList) + collection.Name, + => _framework.RegisterImportant(nameof(CalculateEffectiveFileList) + collection.Identifier, () => CalculateEffectiveFileListInternal(collection)); private void CalculateEffectiveFileListInternal(ModCollection collection) diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 3b865d4b..bc928360 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -116,7 +116,7 @@ public readonly struct ImcCache : IDisposable } private static FullPath CreateImcPath(ModCollection collection, Utf8GamePath path) - => new($"|{collection.Name}_{collection.ChangeCounter}|{path}"); + => new($"|{collection.Id.OptimizedString()}_{collection.ChangeCounter}|{path}"); public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out ImcFile? file) => _imcFiles.TryGetValue(path, out file); diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 38679612..4e8ebe36 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -22,7 +22,7 @@ public class ActiveCollectionData public class ActiveCollections : ISavable, IDisposable { - public const int Version = 1; + public const int Version = 2; private readonly CollectionStorage _storage; private readonly CommunicatorService _communicator; @@ -261,16 +261,17 @@ public class ActiveCollections : ISavable, IDisposable var jObj = new JObject { { nameof(Version), Version }, - { nameof(Default), Default.Name }, - { nameof(Interface), Interface.Name }, - { nameof(Current), Current.Name }, + { nameof(Default), Default.Id }, + { nameof(Interface), Interface.Id }, + { nameof(Current), Current.Id }, }; foreach (var (type, collection) in SpecialCollections.WithIndex().Where(p => p.Value != null) .Select(p => ((CollectionType)p.Index, p.Value!))) - jObj.Add(type.ToString(), collection.Name); + jObj.Add(type.ToString(), collection.Id); jObj.Add(nameof(Individuals), Individuals.ToJObject()); - using var j = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + using var j = new JsonTextWriter(writer); + j.Formatting = Formatting.Indented; jObj.WriteTo(j); } @@ -319,22 +320,16 @@ public class ActiveCollections : ISavable, IDisposable } } - /// - /// Load default, current, special, and character collections from config. - /// If a collection does not exist anymore, reset it to an appropriate default. - /// - private void LoadCollections() + private bool LoadCollectionsV1(JObject jObject) { - Penumbra.Log.Debug("[Collections] Reading collection assignments..."); - var configChanged = !Load(_saveService.FileNames, out var jObject); - - // Load the default collection. If the string does not exist take the Default name if no file existed or the Empty name if one existed. - var defaultName = jObject[nameof(Default)]?.ToObject() - ?? (configChanged ? ModCollection.DefaultCollectionName : ModCollection.Empty.Name); + var configChanged = false; + // Load the default collection. If the name does not exist take the empty collection. + var defaultName = jObject[nameof(Default)]?.ToObject() ?? ModCollection.Empty.Name; if (!_storage.ByName(defaultName, out var defaultCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.DefaultCollection} {defaultName} is not available, reset to {ModCollection.Empty.Name}.", NotificationType.Warning); + $"Last choice of {TutorialService.DefaultCollection} {defaultName} is not available, reset to {ModCollection.Empty.Name}.", + NotificationType.Warning); Default = ModCollection.Empty; configChanged = true; } @@ -348,7 +343,8 @@ public class ActiveCollections : ISavable, IDisposable if (!_storage.ByName(interfaceName, out var interfaceCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.InterfaceCollection} {interfaceName} is not available, reset to {ModCollection.Empty.Name}.", NotificationType.Warning); + $"Last choice of {TutorialService.InterfaceCollection} {interfaceName} is not available, reset to {ModCollection.Empty.Name}.", + NotificationType.Warning); Interface = ModCollection.Empty; configChanged = true; } @@ -362,7 +358,8 @@ public class ActiveCollections : ISavable, IDisposable if (!_storage.ByName(currentName, out var currentCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.SelectedCollection} {currentName} is not available, reset to {ModCollection.DefaultCollectionName}.", NotificationType.Warning); + $"Last choice of {TutorialService.SelectedCollection} {currentName} is not available, reset to {ModCollection.DefaultCollectionName}.", + NotificationType.Warning); Current = _storage.DefaultNamed; configChanged = true; } @@ -393,11 +390,124 @@ public class ActiveCollections : ISavable, IDisposable Penumbra.Log.Debug("[Collections] Loaded non-individual collection assignments."); configChanged |= ActiveCollectionMigration.MigrateIndividualCollections(_storage, Individuals, jObject); - configChanged |= Individuals.ReadJObject(_saveService, this, jObject[nameof(Individuals)] as JArray, _storage); + configChanged |= Individuals.ReadJObject(_saveService, this, jObject[nameof(Individuals)] as JArray, _storage, 1); - // Save any changes. - if (configChanged) - _saveService.ImmediateSave(this); + return configChanged; + } + + private bool LoadCollectionsV2(JObject jObject) + { + var configChanged = false; + // Load the default collection. If the guid does not exist take the empty collection. + var defaultId = jObject[nameof(Default)]?.ToObject() ?? Guid.Empty; + if (!_storage.ById(defaultId, out var defaultCollection)) + { + Penumbra.Messager.NotificationMessage( + $"Last choice of {TutorialService.DefaultCollection} {defaultId} is not available, reset to {ModCollection.Empty.Name}.", + NotificationType.Warning); + Default = ModCollection.Empty; + configChanged = true; + } + else + { + Default = defaultCollection; + } + + // Load the interface collection. If no string is set, use the name of whatever was set as Default. + var interfaceId = jObject[nameof(Interface)]?.ToObject() ?? Default.Id; + if (!_storage.ById(interfaceId, out var interfaceCollection)) + { + Penumbra.Messager.NotificationMessage( + $"Last choice of {TutorialService.InterfaceCollection} {interfaceId} is not available, reset to {ModCollection.Empty.Name}.", + NotificationType.Warning); + Interface = ModCollection.Empty; + configChanged = true; + } + else + { + Interface = interfaceCollection; + } + + // Load the current collection. + var currentId = jObject[nameof(Current)]?.ToObject() ?? _storage.DefaultNamed.Id; + if (!_storage.ById(currentId, out var currentCollection)) + { + Penumbra.Messager.NotificationMessage( + $"Last choice of {TutorialService.SelectedCollection} {currentId} is not available, reset to {ModCollection.DefaultCollectionName}.", + NotificationType.Warning); + Current = _storage.DefaultNamed; + configChanged = true; + } + else + { + Current = currentCollection; + } + + // Load special collections. + foreach (var (type, name, _) in CollectionTypeExtensions.Special) + { + var typeId = jObject[type.ToString()]?.ToObject(); + if (typeId == null) + continue; + + if (!_storage.ById(typeId.Value, out var typeCollection)) + { + Penumbra.Messager.NotificationMessage($"Last choice of {name} Collection {typeId.Value} is not available, removed.", + NotificationType.Warning); + configChanged = true; + } + else + { + SpecialCollections[(int)type] = typeCollection; + } + } + + Penumbra.Log.Debug("[Collections] Loaded non-individual collection assignments."); + + configChanged |= ActiveCollectionMigration.MigrateIndividualCollections(_storage, Individuals, jObject); + configChanged |= Individuals.ReadJObject(_saveService, this, jObject[nameof(Individuals)] as JArray, _storage, 2); + + return configChanged; + } + + private bool LoadCollectionsNew() + { + Current = _storage.DefaultNamed; + Default = _storage.DefaultNamed; + Interface = _storage.DefaultNamed; + return true; + } + + /// + /// Load default, current, special, and character collections from config. + /// If a collection does not exist anymore, reset it to an appropriate default. + /// + private void LoadCollections() + { + Penumbra.Log.Debug("[Collections] Reading collection assignments..."); + var configChanged = !Load(_saveService.FileNames, out var jObject); + var version = jObject["Version"]?.ToObject() ?? 0; + var changed = false; + switch (version) + { + case 1: + changed = LoadCollectionsV1(jObject); + break; + case 2: + changed = LoadCollectionsV2(jObject); + break; + case 0 when configChanged: + changed = LoadCollectionsNew(); + break; + case 0: + Penumbra.Messager.NotificationMessage("Active Collections File has unknown version and will be reset.", + NotificationType.Warning); + changed = LoadCollectionsNew(); + break; + } + + if (changed) + _saveService.ImmediateSaveSync(this); } /// @@ -410,7 +520,7 @@ public class ActiveCollections : ISavable, IDisposable var jObj = BackupService.GetJObjectForFile(fileNames, file); if (jObj == null) { - ret = new JObject(); + ret = []; return false; } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index d0b61e57..2da2a569 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,7 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; -using OtterGui.Filesystem; using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -48,6 +47,25 @@ public class CollectionStorage : IReadOnlyList, IDisposable return true; } + /// Find a collection by its id. If the GUID is empty, the empty collection is returned. + public bool ById(Guid id, [NotNullWhen(true)] out ModCollection? collection) + { + if (id != Guid.Empty) + return _collections.FindFirst(c => c.Id == id, out collection); + + collection = ModCollection.Empty; + return true; + } + + /// Find a collection by an identifier, which is interpreted as a GUID first and if it does not correspond to one, as a name. + public bool ByIdentifier(string identifier, [NotNullWhen(true)] out ModCollection? collection) + { + if (Guid.TryParse(identifier, out var guid)) + return ById(guid, out collection); + + return ByName(identifier, out collection); + } + public CollectionStorage(CommunicatorService communicator, SaveService saveService, ModStorage modStorage) { _communicator = communicator; @@ -70,31 +88,6 @@ public class CollectionStorage : IReadOnlyList, IDisposable _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); } - /// - /// Returns true if the name is not empty, it is not the name of the empty collection - /// and no existing collection results in the same filename as name. Also returns the fixed name. - /// - public bool CanAddCollection(string name, out string fixedName) - { - if (!IsValidName(name)) - { - fixedName = string.Empty; - return false; - } - - name = name.ToLowerInvariant(); - if (name.Length == 0 - || name == ModCollection.Empty.Name.ToLowerInvariant() - || _collections.Any(c => c.Name.ToLowerInvariant() == name)) - { - fixedName = string.Empty; - return false; - } - - fixedName = name; - return true; - } - /// /// Add a new collection of the given name. /// If duplicate is not-null, the new collection will be a duplicate of it. @@ -104,14 +97,6 @@ public class CollectionStorage : IReadOnlyList, IDisposable /// public bool AddCollection(string name, ModCollection? duplicate) { - if (!CanAddCollection(name, out var fixedName)) - { - Penumbra.Messager.NotificationMessage( - $"The new collection {name} would lead to the same path {fixedName} as one that already exists.", NotificationType.Warning, - false); - return false; - } - var newCollection = duplicate?.Duplicate(name, _collections.Count) ?? ModCollection.CreateEmpty(name, _collections.Count, _modStorage.Count); _collections.Add(newCollection); @@ -166,16 +151,9 @@ public class CollectionStorage : IReadOnlyList, IDisposable _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); } - /// - /// Check if a name is valid to use for a collection. - /// Does not check for uniqueness. - /// - private static bool IsValidName(string name) - => name.Length is > 0 and < 64 && name.All(c => !c.IsInvalidAscii() && c is not '|' && !c.IsInvalidInPath()); - /// /// Read all collection files in the Collection Directory. - /// Ensure that the default named collection exists, and apply inheritances afterwards. + /// Ensure that the default named collection exists, and apply inheritances afterward. /// Duplicate collection files are not deleted, just not added here. /// private void ReadCollections(out ModCollection defaultNamedCollection) @@ -183,29 +161,46 @@ public class CollectionStorage : IReadOnlyList, IDisposable Penumbra.Log.Debug("[Collections] Reading saved collections..."); foreach (var file in _saveService.FileNames.CollectionFiles) { - if (!ModCollectionSave.LoadFromFile(file, out var name, out var version, out var settings, out var inheritance)) + if (!ModCollectionSave.LoadFromFile(file, out var id, out var name, out var version, out var settings, out var inheritance)) continue; - if (!IsValidName(name)) + if (id == Guid.Empty) { - // TODO: handle better. - Penumbra.Messager.NotificationMessage($"Collection of unsupported name found: {name} is not a valid collection name.", + Penumbra.Messager.NotificationMessage("Collection without ID found.", NotificationType.Warning); + continue; + } + + if (ById(id, out _)) + { + Penumbra.Messager.NotificationMessage($"Duplicate collection found: {id} already exists. Import skipped.", NotificationType.Warning); continue; } - if (ByName(name, out _)) - { - Penumbra.Messager.NotificationMessage($"Duplicate collection found: {name} already exists. Import skipped.", - NotificationType.Warning); - continue; - } - - var collection = ModCollection.CreateFromData(_saveService, _modStorage, name, version, Count, settings, inheritance); + var collection = ModCollection.CreateFromData(_saveService, _modStorage, id, name, version, Count, settings, inheritance); var correctName = _saveService.FileNames.CollectionFile(collection); if (file.FullName != correctName) - Penumbra.Messager.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Name}.", - NotificationType.Warning); + try + { + if (version >= 2) + { + File.Move(file.FullName, correctName, false); + Penumbra.Messager.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Identifier}, renamed.", + NotificationType.Warning); + } + else + { + _saveService.ImmediateSaveSync(new ModCollectionSave(_modStorage, collection)); + File.Delete(file.FullName); + Penumbra.Log.Information($"Migrated collection {name} to Guid {id}."); + } + } + catch (Exception e) + { + Penumbra.Messager.NotificationMessage(e, + $"Collection {file.Name} does not correspond to {collection.Identifier}, but could not rename.", NotificationType.Error); + } + _collections.Add(collection); } diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index 21a8cf8a..8a717b35 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -18,7 +18,7 @@ public partial class IndividualCollections foreach (var (name, identifiers, collection) in Assignments) { var tmp = identifiers[0].ToJson(); - tmp.Add("Collection", collection.Name); + tmp.Add("Collection", collection.Id); tmp.Add("Display", name); ret.Add(tmp); } @@ -26,18 +26,28 @@ public partial class IndividualCollections return ret; } - public bool ReadJObject(SaveService saver, ActiveCollections parent, JArray? obj, CollectionStorage storage) + public bool ReadJObject(SaveService saver, ActiveCollections parent, JArray? obj, CollectionStorage storage, int version) { if (_actors.Awaiter.IsCompletedSuccessfully) { - var ret = ReadJObjectInternal(obj, storage); + var ret = version switch + { + 1 => ReadJObjectInternalV1(obj, storage), + 2 => ReadJObjectInternalV2(obj, storage), + _ => true, + }; return ret; } Penumbra.Log.Debug("[Collections] Delayed reading individual assignments until actor service is ready..."); _actors.Awaiter.ContinueWith(_ => { - if (ReadJObjectInternal(obj, storage)) + if (version switch + { + 1 => ReadJObjectInternalV1(obj, storage), + 2 => ReadJObjectInternalV2(obj, storage), + _ => true, + }) saver.ImmediateSave(parent); IsLoaded = true; Loaded.Invoke(); @@ -45,7 +55,55 @@ public partial class IndividualCollections return false; } - private bool ReadJObjectInternal(JArray? obj, CollectionStorage storage) + private bool ReadJObjectInternalV1(JArray? obj, CollectionStorage storage) + { + Penumbra.Log.Debug("[Collections] Reading individual assignments..."); + if (obj == null) + { + Penumbra.Log.Debug($"[Collections] Finished reading {Count} individual assignments..."); + return true; + } + + foreach (var data in obj) + { + try + { + var identifier = _actors.FromJson(data as JObject); + var group = GetGroup(identifier); + if (group.Length == 0 || group.Any(i => !i.IsValid)) + { + Penumbra.Messager.NotificationMessage("Could not load an unknown individual collection, removed.", + NotificationType.Error); + continue; + } + + var collectionName = data["Collection"]?.ToObject() ?? string.Empty; + if (collectionName.Length == 0 || !storage.ByName(collectionName, out var collection)) + { + Penumbra.Messager.NotificationMessage( + $"Could not load the collection \"{collectionName}\" as individual collection for {identifier}, set to None.", + NotificationType.Warning); + continue; + } + + if (!Add(group, collection)) + { + Penumbra.Messager.NotificationMessage($"Could not add an individual collection for {identifier}, removed.", + NotificationType.Warning); + } + } + catch (Exception e) + { + Penumbra.Messager.NotificationMessage(e, $"Could not load an unknown individual collection, removed.", NotificationType.Error); + } + } + + Penumbra.Log.Debug($"Finished reading {Count} individual assignments..."); + + return true; + } + + private bool ReadJObjectInternalV2(JArray? obj, CollectionStorage storage) { Penumbra.Log.Debug("[Collections] Reading individual assignments..."); if (obj == null) @@ -64,17 +122,17 @@ public partial class IndividualCollections if (group.Length == 0 || group.Any(i => !i.IsValid)) { changes = true; - Penumbra.Messager.NotificationMessage("Could not load an unknown individual collection, removed.", + Penumbra.Messager.NotificationMessage("Could not load an unknown individual collection, removed assignment.", NotificationType.Error); continue; } - var collectionName = data["Collection"]?.ToObject() ?? string.Empty; - if (collectionName.Length == 0 || !storage.ByName(collectionName, out var collection)) + var collectionId = data["Collection"]?.ToObject(); + if (!collectionId.HasValue || !storage.ById(collectionId.Value, out var collection)) { changes = true; Penumbra.Messager.NotificationMessage( - $"Could not load the collection \"{collectionName}\" as individual collection for {identifier}, set to None.", + $"Could not load the collection {collectionId} as individual collection for {identifier}, removed assignment.", NotificationType.Warning); continue; } @@ -82,14 +140,14 @@ public partial class IndividualCollections if (!Add(group, collection)) { changes = true; - Penumbra.Messager.NotificationMessage($"Could not add an individual collection for {identifier}, removed.", + Penumbra.Messager.NotificationMessage($"Could not add an individual collection for {identifier}, removed assignment.", NotificationType.Warning); } } catch (Exception e) { changes = true; - Penumbra.Messager.NotificationMessage(e, $"Could not load an unknown individual collection, removed.", NotificationType.Error); + Penumbra.Messager.NotificationMessage(e, $"Could not load an unknown individual collection, removed assignment.", NotificationType.Error); } } @@ -100,14 +158,6 @@ public partial class IndividualCollections internal void Migrate0To1(Dictionary old) { - static bool FindDataId(string name, NameDictionary data, out NpcId dataId) - { - var kvp = data.FirstOrDefault(kvp => kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase), - new KeyValuePair(uint.MaxValue, string.Empty)); - dataId = kvp.Key; - return kvp.Value.Length > 0; - } - foreach (var (name, collection) in old) { var kind = ObjectKind.None; @@ -155,5 +205,15 @@ public partial class IndividualCollections NotificationType.Error); } } + + return; + + static bool FindDataId(string name, NameDictionary data, out NpcId dataId) + { + var kvp = data.FirstOrDefault(kvp => kvp.Value.Equals(name, StringComparison.OrdinalIgnoreCase), + new KeyValuePair(uint.MaxValue, string.Empty)); + dataId = kvp.Key; + return kvp.Value.Length > 0; + } } } diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index 771f9463..6003b5f9 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -138,7 +138,7 @@ public class InheritanceManager : IDisposable var changes = false; foreach (var subCollectionName in collection.InheritanceByName) { - if (_storage.ByName(subCollectionName, out var subCollection)) + if (Guid.TryParse(subCollectionName, out var guid) && _storage.ById(guid, out var subCollection)) { if (AddInheritance(collection, subCollection, false)) continue; @@ -146,6 +146,15 @@ public class InheritanceManager : IDisposable changes = true; Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", NotificationType.Warning); } + else if (_storage.ByName(subCollectionName, out subCollection)) + { + changes = true; + Penumbra.Log.Information($"Migrating inheritance for {collection.AnonymizedName} from name to GUID."); + if (AddInheritance(collection, subCollection, false)) + continue; + + Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", NotificationType.Warning); + } else { Penumbra.Messager.NotificationMessage( diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index 5d9de13d..de08c6a2 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -1,3 +1,4 @@ +using OtterGui; using Penumbra.Api; using Penumbra.Communication; using Penumbra.GameData.Actors; @@ -9,13 +10,13 @@ namespace Penumbra.Collections.Manager; public class TempCollectionManager : IDisposable { - public int GlobalChangeCounter { get; private set; } = 0; + public int GlobalChangeCounter { get; private set; } public readonly IndividualCollections Collections; - private readonly CommunicatorService _communicator; - private readonly CollectionStorage _storage; - private readonly ActorManager _actors; - private readonly Dictionary _customCollections = new(); + private readonly CommunicatorService _communicator; + private readonly CollectionStorage _storage; + private readonly ActorManager _actors; + private readonly Dictionary _customCollections = []; public TempCollectionManager(Configuration config, CommunicatorService communicator, ActorManager actors, CollectionStorage storage) { @@ -42,36 +43,36 @@ public class TempCollectionManager : IDisposable => _customCollections.Values; public bool CollectionByName(string name, [NotNullWhen(true)] out ModCollection? collection) - => _customCollections.TryGetValue(name.ToLowerInvariant(), out collection); + => _customCollections.Values.FindFirst(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase), out collection); - public string CreateTemporaryCollection(string name) + public bool CollectionById(Guid id, [NotNullWhen(true)] out ModCollection? collection) + => _customCollections.TryGetValue(id, out collection); + + public Guid CreateTemporaryCollection(string name) { - if (_storage.ByName(name, out _)) - return string.Empty; - if (GlobalChangeCounter == int.MaxValue) GlobalChangeCounter = 0; var collection = ModCollection.CreateTemporary(name, ~Count, GlobalChangeCounter++); - Penumbra.Log.Debug($"Creating temporary collection {collection.AnonymizedName}."); - if (_customCollections.TryAdd(collection.Name.ToLowerInvariant(), collection)) + Penumbra.Log.Debug($"Creating temporary collection {collection.Name} with {collection.Id}."); + if (_customCollections.TryAdd(collection.Id, collection)) { // Temporary collection created. _communicator.CollectionChange.Invoke(CollectionType.Temporary, null, collection, string.Empty); - return collection.Name; + return collection.Id; } - return string.Empty; + return Guid.Empty; } - public bool RemoveTemporaryCollection(string collectionName) + public bool RemoveTemporaryCollection(Guid collectionId) { - if (!_customCollections.Remove(collectionName.ToLowerInvariant(), out var collection)) + if (!_customCollections.Remove(collectionId, out var collection)) { - Penumbra.Log.Debug($"Tried to delete temporary collection {collectionName.ToLowerInvariant()}, but did not exist."); + Penumbra.Log.Debug($"Tried to delete temporary collection {collectionId}, but did not exist."); return false; } - Penumbra.Log.Debug($"Deleted temporary collection {collection.AnonymizedName}."); + Penumbra.Log.Debug($"Deleted temporary collection {collection.Id}."); GlobalChangeCounter += Math.Max(collection.ChangeCounter + 1 - GlobalChangeCounter, 0); for (var i = 0; i < Collections.Count; ++i) { @@ -80,7 +81,7 @@ public class TempCollectionManager : IDisposable // Temporary collection assignment removed. _communicator.CollectionChange.Invoke(CollectionType.Temporary, collection, null, Collections[i].DisplayName); - Penumbra.Log.Verbose($"Unassigned temporary collection {collection.AnonymizedName} from {Collections[i].DisplayName}."); + Penumbra.Log.Verbose($"Unassigned temporary collection {collection.Id} from {Collections[i].DisplayName}."); Collections.Delete(i--); } @@ -98,32 +99,32 @@ public class TempCollectionManager : IDisposable return true; } - public bool AddIdentifier(string collectionName, params ActorIdentifier[] identifiers) + public bool AddIdentifier(Guid collectionId, params ActorIdentifier[] identifiers) { - if (!_customCollections.TryGetValue(collectionName.ToLowerInvariant(), out var collection)) + if (!_customCollections.TryGetValue(collectionId, out var collection)) return false; return AddIdentifier(collection, identifiers); } - public bool AddIdentifier(string collectionName, string characterName, ushort worldId = ushort.MaxValue) + public bool AddIdentifier(Guid collectionId, string characterName, ushort worldId = ushort.MaxValue) { - if (!ByteString.FromString(characterName, out var byteString, false)) + if (!ByteString.FromString(characterName, out var byteString)) return false; var identifier = _actors.CreatePlayer(byteString, worldId); if (!identifier.IsValid) return false; - return AddIdentifier(collectionName, identifier); + return AddIdentifier(collectionId, identifier); } internal bool RemoveByCharacterName(string characterName, ushort worldId = ushort.MaxValue) { - if (!ByteString.FromString(characterName, out var byteString, false)) + if (!ByteString.FromString(characterName, out var byteString)) return false; var identifier = _actors.CreatePlayer(byteString, worldId); - return Collections.TryGetValue(identifier, out var collection) && RemoveTemporaryCollection(collection.Name); + return Collections.TryGetValue(identifier, out var collection) && RemoveTemporaryCollection(collection.Id); } } diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index b63be6cd..c1143c71 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -17,7 +17,7 @@ namespace Penumbra.Collections; /// public partial class ModCollection { - public const int CurrentVersion = 1; + public const int CurrentVersion = 2; public const string DefaultCollectionName = "Default"; public const string EmptyCollectionName = "None"; @@ -27,15 +27,23 @@ public partial class ModCollection /// public static readonly ModCollection Empty = CreateEmpty(EmptyCollectionName, 0, 0); - /// The name of a collection can not contain characters invalid in a path. - public string Name { get; internal init; } + /// The name of a collection. + public string Name { get; set; } = string.Empty; + + public Guid Id { get; } + + public string Identifier + => Id.ToString(); + + public string ShortIdentifier + => Identifier[..8]; public override string ToString() - => Name; + => Name.Length > 0 ? Name : ShortIdentifier; /// Get the first two letters of a collection name and its Index (or None if it is the empty collection). public string AnonymizedName - => this == Empty ? Empty.Name : Name.Length > 2 ? $"{Name[..2]}... ({Index})" : $"{Name} ({Index})"; + => this == Empty ? Empty.Name : Name == DefaultCollectionName ? Name : ShortIdentifier; /// The index of the collection is set and kept up-to-date by the CollectionManager. public int Index { get; internal set; } @@ -112,16 +120,16 @@ public partial class ModCollection public ModCollection Duplicate(string name, int index) { Debug.Assert(index > 0, "Collection duplicated with non-positive index."); - return new ModCollection(name, index, 0, CurrentVersion, Settings.Select(s => s?.DeepCopy()).ToList(), + return new ModCollection(Guid.NewGuid(), name, index, 0, CurrentVersion, Settings.Select(s => s?.DeepCopy()).ToList(), [.. DirectlyInheritsFrom], UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); } /// Constructor for reading from files. - public static ModCollection CreateFromData(SaveService saver, ModStorage mods, string name, int version, int index, + public static ModCollection CreateFromData(SaveService saver, ModStorage mods, Guid id, string name, int version, int index, Dictionary allSettings, IReadOnlyList inheritances) { Debug.Assert(index > 0, "Collection read with non-positive index."); - var ret = new ModCollection(name, index, 0, version, new List(), new List(), allSettings) + var ret = new ModCollection(id, name, index, 0, version, [], [], allSettings) { InheritanceByName = inheritances, }; @@ -134,8 +142,7 @@ public partial class ModCollection public static ModCollection CreateTemporary(string name, int index, int changeCounter) { Debug.Assert(index < 0, "Temporary collection created with non-negative index."); - var ret = new ModCollection(name, index, changeCounter, CurrentVersion, new List(), new List(), - new Dictionary()); + var ret = new ModCollection(Guid.NewGuid(), name, index, changeCounter, CurrentVersion, [], [], []); return ret; } @@ -143,9 +150,8 @@ public partial class ModCollection public static ModCollection CreateEmpty(string name, int index, int modCount) { Debug.Assert(index >= 0, "Empty collection created with negative index."); - return new ModCollection(name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?)null, modCount).ToList(), - new List(), - new Dictionary()); + return new ModCollection(Guid.Empty, name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], + []); } /// Add settings for a new appended mod, by checking if the mod had settings from a previous deletion. @@ -193,10 +199,11 @@ public partial class ModCollection saver.ImmediateSave(new ModCollectionSave(mods, this)); } - private ModCollection(string name, int index, int changeCounter, int version, List appliedSettings, + private ModCollection(Guid id, string name, int index, int changeCounter, int version, List appliedSettings, List inheritsFrom, Dictionary settings) { Name = name; + Id = id; Index = index; ChangeCounter = changeCounter; Settings = appliedSettings; diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index f2cb4ada..acc38d83 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -28,6 +28,8 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection j.WriteStartObject(); j.WritePropertyName("Version"); j.WriteValue(ModCollection.CurrentVersion); + j.WritePropertyName(nameof(ModCollection.Id)); + j.WriteValue(modCollection.Identifier); j.WritePropertyName(nameof(ModCollection.Name)); j.WriteValue(modCollection.Name); j.WritePropertyName(nameof(ModCollection.Settings)); @@ -55,20 +57,20 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection // Inherit by collection name. j.WritePropertyName("Inheritance"); - x.Serialize(j, modCollection.InheritanceByName ?? modCollection.DirectlyInheritsFrom.Select(c => c.Name)); + x.Serialize(j, modCollection.InheritanceByName ?? modCollection.DirectlyInheritsFrom.Select(c => c.Identifier)); j.WriteEndObject(); } - public static bool LoadFromFile(FileInfo file, out string name, out int version, out Dictionary settings, + public static bool LoadFromFile(FileInfo file, out Guid id, out string name, out int version, out Dictionary settings, out IReadOnlyList inheritance) { - settings = new Dictionary(); - inheritance = Array.Empty(); + settings = []; + inheritance = []; if (!file.Exists) { Penumbra.Log.Error("Could not read collection because file does not exist."); - name = string.Empty; - + name = string.Empty; + id = Guid.Empty; version = 0; return false; } @@ -76,8 +78,9 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection try { var obj = JObject.Parse(File.ReadAllText(file.FullName)); - name = obj[nameof(ModCollection.Name)]?.ToObject() ?? string.Empty; version = obj["Version"]?.ToObject() ?? 0; + name = obj[nameof(ModCollection.Name)]?.ToObject() ?? string.Empty; + id = obj[nameof(ModCollection.Id)]?.ToObject() ?? (version == 1 ? Guid.NewGuid() : Guid.Empty); // Custom deserialization that is converted with the constructor. settings = obj[nameof(ModCollection.Settings)]?.ToObject>() ?? settings; inheritance = obj["Inheritance"]?.ToObject>() ?? inheritance; @@ -87,6 +90,7 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection { name = string.Empty; version = 0; + id = Guid.Empty; Penumbra.Log.Error($"Could not read collection information from file:\n{e}"); return false; } diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 537b08da..4e1d6453 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -513,7 +513,7 @@ public class CommandHandler : IDisposable collection = string.Equals(lowerName, ModCollection.Empty.Name, StringComparison.OrdinalIgnoreCase) ? ModCollection.Empty - : _collectionManager.Storage.ByName(lowerName, out var c) + : _collectionManager.Storage.ByIdentifier(lowerName, out var c) ? c : null; if (collection != null) diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index 754570e2..554e2221 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api.Api; using Penumbra.Api.Enums; namespace Penumbra.Communication; @@ -14,7 +15,7 @@ public sealed class ChangedItemClick() : EventWrapper + /// Default = 0, /// diff --git a/Penumbra/Communication/ChangedItemHover.cs b/Penumbra/Communication/ChangedItemHover.cs index 10607da4..2dcced35 100644 --- a/Penumbra/Communication/ChangedItemHover.cs +++ b/Penumbra/Communication/ChangedItemHover.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api.Api; namespace Penumbra.Communication; @@ -12,7 +13,7 @@ public sealed class ChangedItemHover() : EventWrapper + /// Default = 0, /// diff --git a/Penumbra/Communication/CreatedCharacterBase.cs b/Penumbra/Communication/CreatedCharacterBase.cs index 397f7bfd..8992f9fc 100644 --- a/Penumbra/Communication/CreatedCharacterBase.cs +++ b/Penumbra/Communication/CreatedCharacterBase.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Collections; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/CreatingCharacterBase.cs b/Penumbra/Communication/CreatingCharacterBase.cs index 2f249c14..8a906ca0 100644 --- a/Penumbra/Communication/CreatingCharacterBase.cs +++ b/Penumbra/Communication/CreatingCharacterBase.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Services; namespace Penumbra.Communication; @@ -14,7 +15,7 @@ namespace Penumbra.Communication; /// Parameter is a pointer to the equip data array. /// public sealed class CreatingCharacterBase() - : EventWrapper(nameof(CreatingCharacterBase)) + : EventWrapper(nameof(CreatingCharacterBase)) { public enum Priority { diff --git a/Penumbra/Communication/EnabledChanged.cs b/Penumbra/Communication/EnabledChanged.cs index be6343b7..846b1a58 100644 --- a/Penumbra/Communication/EnabledChanged.cs +++ b/Penumbra/Communication/EnabledChanged.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.IpcSubscribers; namespace Penumbra.Communication; @@ -13,7 +14,7 @@ public sealed class EnabledChanged() : EventWrapper + /// Api = int.MinValue, /// diff --git a/Penumbra/Communication/ModDirectoryChanged.cs b/Penumbra/Communication/ModDirectoryChanged.cs index 20d13b20..02293873 100644 --- a/Penumbra/Communication/ModDirectoryChanged.cs +++ b/Penumbra/Communication/ModDirectoryChanged.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; namespace Penumbra.Communication; diff --git a/Penumbra/Communication/ModFileChanged.cs b/Penumbra/Communication/ModFileChanged.cs index 8b4b6f5d..8cda48e9 100644 --- a/Penumbra/Communication/ModFileChanged.cs +++ b/Penumbra/Communication/ModFileChanged.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Mods; using Penumbra.Mods.Editor; diff --git a/Penumbra/Communication/ModOptionChanged.cs b/Penumbra/Communication/ModOptionChanged.cs index f02b17dc..0df58b5f 100644 --- a/Penumbra/Communication/ModOptionChanged.cs +++ b/Penumbra/Communication/ModOptionChanged.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Mods; using Penumbra.Mods.Manager; diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index 01c8fa64..1e4f8d36 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -19,8 +20,11 @@ public sealed class ModPathChanged() { public enum Priority { - /// - Api = int.MinValue, + /// + ApiMods = int.MinValue, + + /// + ApiModSettings = int.MinValue, /// EphemeralConfig = -500, diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index 412b3003..968f78a7 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Mods; diff --git a/Penumbra/Communication/PostEnabledDraw.cs b/Penumbra/Communication/PostEnabledDraw.cs index 68637442..e21f0183 100644 --- a/Penumbra/Communication/PostEnabledDraw.cs +++ b/Penumbra/Communication/PostEnabledDraw.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api.Api; namespace Penumbra.Communication; @@ -12,7 +13,7 @@ public sealed class PostEnabledDraw() : EventWrapper + /// Default = 0, } } diff --git a/Penumbra/Communication/PostSettingsPanelDraw.cs b/Penumbra/Communication/PostSettingsPanelDraw.cs index a918b610..525ac73e 100644 --- a/Penumbra/Communication/PostSettingsPanelDraw.cs +++ b/Penumbra/Communication/PostSettingsPanelDraw.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api.Api; namespace Penumbra.Communication; @@ -12,7 +13,7 @@ public sealed class PostSettingsPanelDraw() : EventWrapper + /// Default = 0, } } diff --git a/Penumbra/Communication/PreSettingsPanelDraw.cs b/Penumbra/Communication/PreSettingsPanelDraw.cs index cda00d78..33f6b4e1 100644 --- a/Penumbra/Communication/PreSettingsPanelDraw.cs +++ b/Penumbra/Communication/PreSettingsPanelDraw.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api.Api; namespace Penumbra.Communication; @@ -12,7 +13,7 @@ public sealed class PreSettingsPanelDraw() : EventWrapper + /// Default = 0, } } diff --git a/Penumbra/Communication/PreSettingsTabBarDraw.cs b/Penumbra/Communication/PreSettingsTabBarDraw.cs index 2c14cdf1..8614bbbe 100644 --- a/Penumbra/Communication/PreSettingsTabBarDraw.cs +++ b/Penumbra/Communication/PreSettingsTabBarDraw.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using Penumbra.Api.Api; namespace Penumbra.Communication; @@ -14,7 +15,7 @@ public sealed class PreSettingsTabBarDraw() : EventWrapper + /// Default = 0, } } diff --git a/Penumbra/GuidExtensions.cs b/Penumbra/GuidExtensions.cs new file mode 100644 index 00000000..fcbc8a3b --- /dev/null +++ b/Penumbra/GuidExtensions.cs @@ -0,0 +1,254 @@ +using System.Collections.Frozen; +using OtterGui; + +namespace Penumbra; + +public static class GuidExtensions +{ + private const string Chars = + "0123456789" + + "abcdefghij" + + "klmnopqrst" + + "uv"; + + private static ReadOnlySpan Bytes + => "0123456789abcdefghijklmnopqrstuv"u8; + + private static readonly FrozenDictionary + ReverseChars = Chars.WithIndex().ToFrozenDictionary(t => t.Value, t => (byte)t.Index); + + private static readonly FrozenDictionary ReverseBytes = + ReverseChars.ToFrozenDictionary(kvp => (byte)kvp.Key, kvp => kvp.Value); + + public static unsafe string OptimizedString(this Guid guid) + { + var bytes = stackalloc ulong[2]; + if (!guid.TryWriteBytes(new Span(bytes, 16))) + return guid.ToString("N"); + + var u1 = bytes[0]; + var u2 = bytes[1]; + Span text = + [ + Chars[(int)(u1 & 0x1F)], + Chars[(int)((u1 >> 5) & 0x1F)], + Chars[(int)((u1 >> 10) & 0x1F)], + Chars[(int)((u1 >> 15) & 0x1F)], + Chars[(int)((u1 >> 20) & 0x1F)], + Chars[(int)((u1 >> 25) & 0x1F)], + Chars[(int)((u1 >> 30) & 0x1F)], + Chars[(int)((u1 >> 35) & 0x1F)], + Chars[(int)((u1 >> 40) & 0x1F)], + Chars[(int)((u1 >> 45) & 0x1F)], + Chars[(int)((u1 >> 50) & 0x1F)], + Chars[(int)((u1 >> 55) & 0x1F)], + Chars[(int)((u1 >> 60) | ((u2 & 0x01) << 4))], + Chars[(int)((u2 >> 1) & 0x1F)], + Chars[(int)((u2 >> 6) & 0x1F)], + Chars[(int)((u2 >> 11) & 0x1F)], + Chars[(int)((u2 >> 16) & 0x1F)], + Chars[(int)((u2 >> 21) & 0x1F)], + Chars[(int)((u2 >> 26) & 0x1F)], + Chars[(int)((u2 >> 31) & 0x1F)], + Chars[(int)((u2 >> 36) & 0x1F)], + Chars[(int)((u2 >> 41) & 0x1F)], + Chars[(int)((u2 >> 46) & 0x1F)], + Chars[(int)((u2 >> 51) & 0x1F)], + Chars[(int)((u2 >> 56) & 0x1F)], + Chars[(int)((u2 >> 61) & 0x1F)], + ]; + return new string(text); + } + + public static unsafe bool FromOptimizedString(ReadOnlySpan text, out Guid guid) + { + if (text.Length != 26) + return Return(out guid); + + var bytes = stackalloc ulong[2]; + if (!ReverseChars.TryGetValue(text[0], out var b0)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[1], out var b1)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[2], out var b2)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[3], out var b3)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[4], out var b4)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[5], out var b5)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[6], out var b6)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[7], out var b7)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[8], out var b8)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[9], out var b9)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[10], out var b10)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[11], out var b11)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[12], out var b12)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[13], out var b13)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[14], out var b14)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[15], out var b15)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[16], out var b16)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[17], out var b17)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[18], out var b18)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[19], out var b19)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[20], out var b20)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[21], out var b21)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[22], out var b22)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[23], out var b23)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[24], out var b24)) + return Return(out guid); + if (!ReverseChars.TryGetValue(text[25], out var b25)) + return Return(out guid); + + bytes[0] = b0 + | ((ulong)b1 << 5) + | ((ulong)b2 << 10) + | ((ulong)b3 << 15) + | ((ulong)b4 << 20) + | ((ulong)b5 << 25) + | ((ulong)b6 << 30) + | ((ulong)b7 << 35) + | ((ulong)b8 << 40) + | ((ulong)b9 << 45) + | ((ulong)b10 << 50) + | ((ulong)b11 << 55) + | ((ulong)b12 << 60); + bytes[1] = ((ulong)b12 >> 4) + | ((ulong)b13 << 1) + | ((ulong)b14 << 6) + | ((ulong)b15 << 11) + | ((ulong)b16 << 16) + | ((ulong)b17 << 21) + | ((ulong)b18 << 26) + | ((ulong)b19 << 31) + | ((ulong)b20 << 36) + | ((ulong)b21 << 41) + | ((ulong)b22 << 46) + | ((ulong)b23 << 51) + | ((ulong)b24 << 56) + | ((ulong)b25 << 61); + guid = new Guid(new Span(bytes, 16)); + return true; + + static bool Return(out Guid guid) + { + guid = Guid.Empty; + return false; + } + } + + public static unsafe bool FromOptimizedString(ReadOnlySpan text, out Guid guid) + { + if (text.Length != 26) + return Return(out guid); + + var bytes = stackalloc ulong[2]; + if (!ReverseBytes.TryGetValue(text[0], out var b0)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[1], out var b1)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[2], out var b2)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[3], out var b3)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[4], out var b4)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[5], out var b5)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[6], out var b6)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[7], out var b7)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[8], out var b8)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[9], out var b9)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[10], out var b10)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[11], out var b11)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[12], out var b12)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[13], out var b13)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[14], out var b14)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[15], out var b15)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[16], out var b16)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[17], out var b17)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[18], out var b18)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[19], out var b19)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[20], out var b20)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[21], out var b21)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[22], out var b22)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[23], out var b23)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[24], out var b24)) + return Return(out guid); + if (!ReverseBytes.TryGetValue(text[25], out var b25)) + return Return(out guid); + + bytes[0] = b0 + | ((ulong)b1 << 5) + | ((ulong)b2 << 10) + | ((ulong)b3 << 15) + | ((ulong)b4 << 20) + | ((ulong)b5 << 25) + | ((ulong)b6 << 30) + | ((ulong)b7 << 35) + | ((ulong)b8 << 40) + | ((ulong)b9 << 45) + | ((ulong)b10 << 50) + | ((ulong)b11 << 55) + | ((ulong)b12 << 60); + bytes[1] = ((ulong)b12 >> 4) + | ((ulong)b13 << 1) + | ((ulong)b14 << 6) + | ((ulong)b15 << 11) + | ((ulong)b16 << 16) + | ((ulong)b17 << 21) + | ((ulong)b18 << 26) + | ((ulong)b19 << 31) + | ((ulong)b20 << 36) + | ((ulong)b21 << 41) + | ((ulong)b22 << 46) + | ((ulong)b23 << 51) + | ((ulong)b24 << 56) + | ((ulong)b25 << 61); + guid = new Guid(new Span(bytes, 16)); + return true; + + static bool Return(out Guid guid) + { + guid = Guid.Empty; + return false; + } + } +} diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index a3400540..5f07ffc5 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -130,7 +130,7 @@ public sealed unsafe class MetaState : IDisposable _lastCreatedCollection = _collectionResolver.IdentifyLastGameObjectCollection(true); if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero) _communicator.CreatingCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, - _lastCreatedCollection.ModCollection.Name, (nint)modelCharaId, (nint)customize, (nint)equipData); + _lastCreatedCollection.ModCollection.Id, (nint)modelCharaId, (nint)customize, (nint)equipData); var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, UsesDecal(*(uint*)modelCharaId, (nint)customize)); diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 7c16b97b..5c3d8d19 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,3 +1,4 @@ +using System.Runtime; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -43,8 +44,8 @@ public class PathResolver : IDisposable } /// Obtain a temporary or permanent collection by name. - public bool CollectionByName(string name, [NotNullWhen(true)] out ModCollection? collection) - => _tempCollections.CollectionByName(name, out collection) || _collectionManager.Storage.ByName(name, out collection); + public bool CollectionById(Guid id, [NotNullWhen(true)] out ModCollection? collection) + => _tempCollections.CollectionById(id, out collection) || _collectionManager.Storage.ById(id, out collection); /// Try to resolve the given game path to the replaced path. public (FullPath?, ResolveData) ResolvePath(Utf8GamePath path, ResourceCategory category, ResourceType resourceType) @@ -136,9 +137,10 @@ public class PathResolver : IDisposable return; var lastUnderscore = additionalData.LastIndexOf((byte)'_'); - var name = lastUnderscore == -1 ? additionalData.ToString() : additionalData.Substring(0, lastUnderscore).ToString(); + var idString = lastUnderscore == -1 ? additionalData : additionalData.Substring(0, lastUnderscore); if (Utf8GamePath.FromByteString(path, out var gamePath) - && CollectionByName(name, out var collection) + && GuidExtensions.FromOptimizedString(idString.Span, out var id) + && CollectionById(id, out var collection) && collection.HasCache && collection.GetImcFile(gamePath, out var file)) { diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 2359c36e..844baaa9 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -76,7 +76,7 @@ public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection> GetResourcePathDictionaries(IEnumerable<(Character, ResourceTree)> resourceTrees) + public static Dictionary>> GetResourcePathDictionaries( + IEnumerable<(Character, ResourceTree)> resourceTrees) { var pathDictionaries = new Dictionary>>(4); @@ -23,8 +25,7 @@ internal static class ResourceTreeApiHelper CollectResourcePaths(pathDictionary, resourceTree); } - return pathDictionaries.ToDictionary(pair => pair.Key, - pair => (IReadOnlyDictionary)pair.Value.ToDictionary(pair => pair.Key, pair => pair.Value.ToArray()).AsReadOnly()); + return pathDictionaries; } private static void CollectResourcePaths(Dictionary> pathDictionary, ResourceTree resourceTree) @@ -37,7 +38,7 @@ internal static class ResourceTreeApiHelper var fullPath = node.FullPath.ToPath(); if (!pathDictionary.TryGetValue(fullPath, out var gamePaths)) { - gamePaths = new(); + gamePaths = []; pathDictionary.Add(fullPath, gamePaths); } @@ -46,17 +47,17 @@ internal static class ResourceTreeApiHelper } } - public static Dictionary> GetResourcesOfType(IEnumerable<(Character, ResourceTree)> resourceTrees, + public static Dictionary GetResourcesOfType(IEnumerable<(Character, ResourceTree)> resourceTrees, ResourceType type) { - var resDictionaries = new Dictionary>(4); + var resDictionaries = new Dictionary(4); foreach (var (gameObject, resourceTree) in resourceTrees) { if (resDictionaries.ContainsKey(gameObject.ObjectIndex)) continue; - var resDictionary = new Dictionary(); - resDictionaries.Add(gameObject.ObjectIndex, resDictionary); + var resDictionary = new Dictionary(); + resDictionaries.Add(gameObject.ObjectIndex, new GameResourceDict(resDictionary)); foreach (var node in resourceTree.FlatNodes) { @@ -66,38 +67,16 @@ internal static class ResourceTreeApiHelper continue; var fullPath = node.FullPath.ToPath(); - resDictionary.Add(node.ResourceHandle, (fullPath, node.Name ?? string.Empty, ChangedItemDrawer.ToApiIcon(node.Icon))); + resDictionary.Add(node.ResourceHandle, (fullPath, node.Name ?? string.Empty, (uint)ChangedItemDrawer.ToApiIcon(node.Icon))); } } - return resDictionaries.ToDictionary(pair => pair.Key, - pair => (IReadOnlyDictionary)pair.Value.AsReadOnly()); + return resDictionaries; } - public static Dictionary EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) + public static Dictionary EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) { - static Ipc.ResourceNode GetIpcNode(ResourceNode node) => - new() - { - Type = node.Type, - Icon = ChangedItemDrawer.ToApiIcon(node.Icon), - Name = node.Name, - GamePath = node.GamePath.Equals(Utf8GamePath.Empty) ? null : node.GamePath.ToString(), - ActualPath = node.FullPath.ToString(), - ObjectAddress = node.ObjectAddress, - ResourceHandle = node.ResourceHandle, - Children = node.Children.Select(GetIpcNode).ToList(), - }; - - static Ipc.ResourceTree GetIpcTree(ResourceTree tree) => - new() - { - Name = tree.Name, - RaceCode = (ushort)tree.RaceCode, - Nodes = tree.Nodes.Select(GetIpcNode).ToList(), - }; - - var resDictionary = new Dictionary(4); + var resDictionary = new Dictionary(4); foreach (var (gameObject, resourceTree) in resourceTrees) { if (resDictionary.ContainsKey(gameObject.ObjectIndex)) @@ -107,5 +86,38 @@ internal static class ResourceTreeApiHelper } return resDictionary; + + static JObject GetIpcTree(ResourceTree tree) + { + var ret = new JObject + { + [nameof(ResourceTreeDto.Name)] = tree.Name, + [nameof(ResourceTreeDto.RaceCode)] = (ushort)tree.RaceCode, + }; + var children = new JArray(); + foreach (var child in tree.Nodes) + children.Add(GetIpcNode(child)); + ret[nameof(ResourceTreeDto.Nodes)] = children; + return ret; + } + + static JObject GetIpcNode(ResourceNode node) + { + var ret = new JObject + { + [nameof(ResourceNodeDto.Type)] = new JValue(node.Type), + [nameof(ResourceNodeDto.Icon)] = new JValue(ChangedItemDrawer.ToApiIcon(node.Icon)), + [nameof(ResourceNodeDto.Name)] = node.Name, + [nameof(ResourceNodeDto.GamePath)] = node.GamePath.Equals(Utf8GamePath.Empty) ? null : node.GamePath.ToString(), + [nameof(ResourceNodeDto.ActualPath)] = node.FullPath.ToString(), + [nameof(ResourceNodeDto.ObjectAddress)] = node.ObjectAddress, + [nameof(ResourceNodeDto.ResourceHandle)] = node.ResourceHandle, + }; + var children = new JArray(); + foreach (var child in node.Children) + children.Add(GetIpcNode(child)); + ret[nameof(ResourceNodeDto.Children)] = children; + return ret; + } } } diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 0ffdc4af..9efb8a3f 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -272,22 +272,19 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS return; var group = mod.Groups[groupIdx]; - if (group.Type is GroupType.Multi && group.Count >= IModGroup.MaxMultiOptions) - { - Penumbra.Log.Error( - $"Could not add option {option.Name} to {group.Name} for mod {mod.Name}, " - + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); - return; - } - - o.SetPosition(groupIdx, group.Count); - switch (group) { + case MultiModGroup { Count: >= IModGroup.MaxMultiOptions }: + Penumbra.Log.Error( + $"Could not add option {option.Name} to {group.Name} for mod {mod.Name}, " + + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); + return; case SingleModGroup s: + o.SetPosition(groupIdx, s.Count); s.OptionData.Add(o); break; case MultiModGroup m: + o.SetPosition(groupIdx, m.Count); m.PrioritizedOptions.Add((o, priority)); break; } diff --git a/Penumbra/Mods/Manager/ModStorage.cs b/Penumbra/Mods/Manager/ModStorage.cs index 1e5df6b9..65b8ddd9 100644 --- a/Penumbra/Mods/Manager/ModStorage.cs +++ b/Penumbra/Mods/Manager/ModStorage.cs @@ -19,7 +19,7 @@ public class ModCombo : FilterComboCache public class ModStorage : IReadOnlyList { /// The actual list of mods. - protected readonly List Mods = new(); + protected readonly List Mods = []; public int Count => Mods.Count; diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index e9e2a93b..2daf31e6 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -4,9 +4,9 @@ using Penumbra.Services; namespace Penumbra.Mods.Subclasses; -public interface IModGroup : IEnumerable +public interface IModGroup : IReadOnlyCollection { - public const int MaxMultiOptions = 32; + public const int MaxMultiOptions = 63; public string Name { get; } public string Description { get; } @@ -18,15 +18,7 @@ public interface IModGroup : IEnumerable public ISubMod this[Index idx] { get; } - public int Count { get; } - - public bool IsOption - => Type switch - { - GroupType.Single => Count > 1, - GroupType.Multi => Count > 0, - _ => false, - }; + public bool IsOption { get; } public IModGroup Convert(GroupType type); public bool MoveOption(int optionIdxFrom, int optionIdxTo); @@ -94,11 +86,13 @@ public readonly struct ModSaveGroup : ISavable j.WritePropertyName("Options"); j.WriteStartArray(); for (var idx = 0; idx < _group.Count; ++idx) + { ISubMod.WriteSubMod(j, serializer, _group[idx], _basePath, _group.Type switch { GroupType.Multi => _group.OptionPriority(idx), - _ => null, + _ => null, }); + } j.WriteEndArray(); j.WriteEndObject(); diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index b79b3242..380b242c 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -12,7 +12,7 @@ public class ModSettings { public static readonly ModSettings Empty = new(); public SettingList Settings { get; private init; } = []; - public ModPriority Priority { get; set; } + public ModPriority Priority { get; set; } public bool Enabled { get; set; } // Create an independent copy of the current settings. @@ -152,7 +152,7 @@ public class ModSettings public struct SavedSettings { public Dictionary Settings; - public ModPriority Priority; + public ModPriority Priority; public bool Enabled; public SavedSettings DeepCopy() @@ -203,9 +203,9 @@ public class ModSettings // Return the settings for a given mod in a shareable format, using the names of groups and options instead of indices. // Does not repair settings but ignores settings not fitting to the given mod. - public (bool Enabled, ModPriority Priority, Dictionary> Settings) ConvertToShareable(Mod mod) + public (bool Enabled, ModPriority Priority, Dictionary> Settings) ConvertToShareable(Mod mod) { - var dict = new Dictionary>(Settings.Count); + var dict = new Dictionary>(Settings.Count); foreach (var (setting, idx) in Settings.WithIndex()) { if (idx >= mod.Groups.Count) diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 444e8e2c..7479cd54 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -25,6 +25,9 @@ public sealed class MultiModGroup : IModGroup public ISubMod this[Index idx] => PrioritizedOptions[idx].Mod; + public bool IsOption + => Count > 0; + [JsonIgnore] public int Count => PrioritizedOptions.Count; diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index 0bfa04f4..74769c7e 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -25,6 +25,9 @@ public sealed class SingleModGroup : IModGroup public ISubMod this[Index idx] => OptionData[idx]; + public bool IsOption + => Count > 1; + [JsonIgnore] public int Count => OptionData.Count; diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 4de2ac13..6be07881 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -53,7 +53,7 @@ public class TemporaryMod : IMod dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Name, config.ReplaceNonAsciiOnImport, true); var fileDir = Directory.CreateDirectory(Path.Combine(dir.FullName, "files")); modManager.DataEditor.CreateMeta(dir, collection.Name, character ?? config.DefaultModAuthor, - $"Mod generated from temporary collection {collection.Name} for {character ?? "Unknown Character"}.", null, null); + $"Mod generated from temporary collection {collection.Id} for {character ?? "Unknown Character"} with name {collection.Name}.", null, null); var mod = new Mod(dir); var defaultMod = mod.Default; foreach (var (gamePath, fullPath) in collection.ResolvedFiles) @@ -86,11 +86,11 @@ public class TemporaryMod : IMod saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir); - Penumbra.Log.Information($"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Name}."); + Penumbra.Log.Information($"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identifier}."); } catch (Exception e) { - Penumbra.Log.Error($"Could not save temporary collection {collection.Name} to permanent Mod:\n{e}"); + Penumbra.Log.Error($"Could not save temporary collection {collection.Identifier} to permanent Mod:\n{e}"); if (dir != null && Directory.Exists(dir.FullName)) { try diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b76780c0..42be0aa3 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -20,6 +20,7 @@ using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; using Penumbra.GameData.Enums; using Penumbra.UI; +using IPenumbraApi = Penumbra.Api.Api.IPenumbraApi; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra; @@ -105,8 +106,7 @@ public class Penumbra : IDalamudPlugin private void SetupApi() { - var api = _services.GetService(); - _services.GetService(); + _services.GetService(); _communicatorService.ChangedItemHover.Subscribe(it => { if (it is (Item, FullEquipType)) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index b07917e8..c8961579 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,4 +1,4 @@ - + net8.0-windows preview diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index d1e952f1..e775d81a 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -223,7 +223,7 @@ public class ConfigMigrationService(SaveService saveService) : IService try { var jObject = JObject.Parse(File.ReadAllText(collection.FullName)); - if (jObject[nameof(ModCollection.Name)]?.ToObject() == ForcedCollection) + if (jObject["Name"]?.ToObject() == ForcedCollection) continue; jObject[nameof(ModCollection.DirectlyInheritsFrom)] = JToken.FromObject(new List { ForcedCollection }); @@ -365,7 +365,7 @@ public class ConfigMigrationService(SaveService saveService) : IService dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value with { Priority = maxPriority - kvp.Value.Priority }); var emptyStorage = new ModStorage(); - var collection = ModCollection.CreateFromData(saveService, emptyStorage, ModCollection.DefaultCollectionName, 0, 1, dict, []); + var collection = ModCollection.CreateFromData(saveService, emptyStorage, Guid.NewGuid(), ModCollection.DefaultCollectionName, 0, 1, dict, []); saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 078b812b..6805e7db 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -239,7 +239,7 @@ public sealed class CrashHandlerService : IDisposable, IService var name = GetActorName(character); lock (_eventWriter) { - _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Name, type); + _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Id, type); } } catch (Exception ex) @@ -248,7 +248,7 @@ public sealed class CrashHandlerService : IDisposable, IService } } - private void OnCreatingCharacterBase(nint address, string collection, nint _1, nint _2, nint _3) + private void OnCreatingCharacterBase(nint address, Guid collection, nint _1, nint _2, nint _3) { if (_eventWriter == null) return; @@ -293,7 +293,7 @@ public sealed class CrashHandlerService : IDisposable, IService var name = GetActorName(resolveData.AssociatedGameObject); lock (_eventWriter) { - _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Name, + _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Id, manipulatedPath.Value.InternalName.Span, originalPath.Path.Span); } } diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 40c63f15..e1c482f7 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -24,7 +24,7 @@ public class FilenameService(DalamudPluginInterface pi) : IService /// Obtain the path of a collection file given its name. public string CollectionFile(ModCollection collection) - => CollectionFile(collection.Name); + => CollectionFile(collection.Identifier); /// Obtain the path of a collection file given its name. public string CollectionFile(string collectionName) diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 9e6071b4..e758aa35 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -9,6 +9,7 @@ using OtterGui.Classes; using OtterGui.Log; using OtterGui.Services; using Penumbra.Api; +using Penumbra.Api.Api; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; @@ -30,8 +31,10 @@ using Penumbra.UI.ModsTab; using Penumbra.UI.ResourceWatcher; using Penumbra.UI.Tabs; using Penumbra.UI.Tabs.Debug; +using IPenumbraApi = Penumbra.Api.Api.IPenumbraApi; using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; +using Penumbra.Api.IpcTester; namespace Penumbra.Services; @@ -195,10 +198,5 @@ public static class StaticServiceManager .AddSingleton(); private static ServiceManager AddApi(this ServiceManager services) - => services.AddSingleton() - .AddSingleton(x => x.GetRequiredService()) - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); + => services.AddSingleton(x => x.GetRequiredService()); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 9a38a5d5..10956deb 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -25,8 +25,8 @@ public partial class ModEditWindow var resources = ResourceTreeApiHelper .GetResourcesOfType(_resourceTreeFactory.FromObjectTable(ResourceTreeFactory.Flags.LocalPlayerRelatedOnly), type) .Values - .SelectMany(resources => resources.Values) - .Select(resource => resource.Item1); + .SelectMany(r => r.Values) + .Select(r => r.Item1); return new HashSet(resources, StringComparer.OrdinalIgnoreCase); } diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 4d922af5..cbeabbd6 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -2,11 +2,13 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.GameFonts; +using Dalamud.Interface.Internal.Notifications; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Utility; using Dalamud.Plugin; using ImGuiNET; using OtterGui; +using OtterGui.Classes; using OtterGui.Raii; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -28,8 +30,8 @@ public sealed class CollectionPanel : IDisposable private readonly IndividualAssignmentUi _individualAssignmentUi; private readonly InheritanceUi _inheritanceUi; private readonly ModStorage _mods; - - private readonly IFontHandle _nameFont; + private readonly FilenameService _fileNames; + private readonly IFontHandle _nameFont; private static readonly IReadOnlyDictionary Buttons = CreateButtons(); private static readonly IReadOnlyList<(CollectionType, bool, bool, string, uint)> AdvancedTree = CreateTree(); @@ -38,7 +40,7 @@ public sealed class CollectionPanel : IDisposable private int _draggedIndividualAssignment = -1; public CollectionPanel(DalamudPluginInterface pi, CommunicatorService communicator, CollectionManager manager, - CollectionSelector selector, ActorManager actors, ITargetManager targets, ModStorage mods) + CollectionSelector selector, ActorManager actors, ITargetManager targets, ModStorage mods, FilenameService fileNames) { _collections = manager.Storage; _active = manager.Active; @@ -46,6 +48,7 @@ public sealed class CollectionPanel : IDisposable _actors = actors; _targets = targets; _mods = mods; + _fileNames = fileNames; _individualAssignmentUi = new IndividualAssignmentUi(communicator, actors, manager); _inheritanceUi = new InheritanceUi(manager, _selector); _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); @@ -206,12 +209,57 @@ public sealed class CollectionPanel : IDisposable var collection = _active.Current; DrawCollectionName(collection); DrawStatistics(collection); + DrawCollectionData(collection); _inheritanceUi.Draw(); ImGui.Separator(); DrawInactiveSettingsList(collection); DrawSettingsList(collection); } + private void DrawCollectionData(ModCollection collection) + { + ImGui.Dummy(Vector2.Zero); + ImGui.BeginGroup(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("Name"); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("Identifier"); + ImGui.EndGroup(); + ImGui.SameLine(); + ImGui.BeginGroup(); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); + var name = collection.Name; + var identifier = collection.Identifier; + var width = ImGui.GetContentRegionAvail().X; + var fileName = _fileNames.CollectionFile(collection); + ImGui.SetNextItemWidth(width); + ImGui.InputText("##name", ref name, 128); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + if (ImGui.Button(collection.Identifier, new Vector2(width, 0))) + try + { + Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, $"Could not open file {fileName}.", $"Could not open file {fileName}", + NotificationType.Warning); + } + } + + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImGui.SetClipboardText(identifier); + + ImGuiUtil.HoverTooltip( + $"Open the file\n\t{fileName}\ncontaining this design in the .json-editor of your choice.\n\nRight-Click to copy identifier to clipboard."); + + ImGui.EndGroup(); + ImGui.Dummy(Vector2.Zero); + ImGui.Separator(); + ImGui.Dummy(Vector2.Zero); + } + private void DrawContext(bool open, ModCollection? collection, CollectionType type, ActorIdentifier identifier, string text, char suffix) { var label = $"{type}{text}{suffix}"; diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index e568ecaf..fac85d4d 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -24,7 +24,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl public CollectionSelector(Configuration config, CommunicatorService communicator, CollectionStorage storage, ActiveCollections active, TutorialService tutorial) - : base(new List(), Flags.Delete | Flags.Add | Flags.Duplicate | Flags.Filter) + : base([], Flags.Delete | Flags.Add | Flags.Duplicate | Flags.Filter) { _config = config; _communicator = communicator; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 3c6a3ed9..fe1471b3 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -41,12 +41,12 @@ public sealed class CollectionsTab : IDisposable, ITab } public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, - CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial) + CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial, FilenameService fileNames) { _config = configuration.Ephemeral; _tutorial = tutorial; _selector = new CollectionSelector(configuration, communicator, collectionManager.Storage, collectionManager.Active, _tutorial); - _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage); + _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage, fileNames); } public void Dispose() diff --git a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs index 78014054..4649e548 100644 --- a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs +++ b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs @@ -55,7 +55,7 @@ public static class CrashDataExtensions ImGuiUtil.DrawTableColumn(character.Age.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn(character.ThreadId.ToString()); ImGuiUtil.DrawTableColumn(character.CharacterName); - ImGuiUtil.DrawTableColumn(character.CollectionName); + ImGuiUtil.DrawTableColumn(character.CollectionId.ToString()); ImGuiUtil.DrawTableColumn(character.CharacterAddress); ImGuiUtil.DrawTableColumn(character.Timestamp.ToString()); }, ImGui.GetTextLineHeightWithSpacing()); @@ -79,7 +79,7 @@ public static class CrashDataExtensions ImGuiUtil.DrawTableColumn(file.ActualFileName); ImGuiUtil.DrawTableColumn(file.RequestedFileName); ImGuiUtil.DrawTableColumn(file.CharacterName); - ImGuiUtil.DrawTableColumn(file.CollectionName); + ImGuiUtil.DrawTableColumn(file.CollectionId.ToString()); ImGuiUtil.DrawTableColumn(file.CharacterAddress); ImGuiUtil.DrawTableColumn(file.Timestamp.ToString()); }, ImGui.GetTextLineHeightWithSpacing()); @@ -102,7 +102,7 @@ public static class CrashDataExtensions ImGuiUtil.DrawTableColumn(vfx.ThreadId.ToString()); ImGuiUtil.DrawTableColumn(vfx.InvocationType); ImGuiUtil.DrawTableColumn(vfx.CharacterName); - ImGuiUtil.DrawTableColumn(vfx.CollectionName); + ImGuiUtil.DrawTableColumn(vfx.CollectionId.ToString()); ImGuiUtil.DrawTableColumn(vfx.CharacterAddress); ImGuiUtil.DrawTableColumn(vfx.Timestamp.ToString()); }, ImGui.GetTextLineHeightWithSpacing()); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 9a956d2d..1813a7e3 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -40,6 +40,7 @@ using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using ObjectKind = Dalamud.Game.ClientState.Objects.Enums.ObjectKind; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using ImGuiClip = OtterGui.ImGuiClip; +using Penumbra.Api.IpcTester; namespace Penumbra.UI.Tabs.Debug; @@ -76,7 +77,6 @@ public class DebugTab : Window, ITab private readonly CharacterUtility _characterUtility; private readonly ResidentResourceManager _residentResources; private readonly ResourceManagerService _resourceManager; - private readonly PenumbraIpcProviders _ipc; private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; private readonly PathState _pathState; @@ -100,7 +100,7 @@ public class DebugTab : Window, ITab IClientState clientState, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, CharacterUtility characterUtility, ResidentResourceManager residentResources, - ResourceManagerService resourceManager, PenumbraIpcProviders ipc, CollectionResolver collectionResolver, + ResourceManagerService resourceManager, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, @@ -124,7 +124,6 @@ public class DebugTab : Window, ITab _characterUtility = characterUtility; _residentResources = residentResources; _resourceManager = resourceManager; - _ipc = ipc; _collectionResolver = collectionResolver; _drawObjectState = drawObjectState; _pathState = pathState; @@ -440,7 +439,9 @@ public class DebugTab : Window, ITab : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); var identifier = _actors.FromObject(obj, out _, false, true, false); ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); - var id = obj.AsObject->ObjectKind ==(byte) ObjectKind.BattleNpc ? $"{identifier.DataId} | {obj.AsObject->DataID}" : identifier.DataId.ToString(); + var id = obj.AsObject->ObjectKind == (byte)ObjectKind.BattleNpc + ? $"{identifier.DataId} | {obj.AsObject->DataID}" + : identifier.DataId.ToString(); ImGuiUtil.DrawTableColumn(id); } @@ -969,13 +970,8 @@ public class DebugTab : Window, ITab /// Draw information about IPC options and availability. private void DrawDebugTabIpc() { - if (!ImGui.CollapsingHeader("IPC")) - { - _ipcTester.UnsubscribeEvents(); - return; - } - - _ipcTester.Draw(); + if (ImGui.CollapsingHeader("IPC")) + _ipcTester.Draw(); } /// Helper to print a property and its value in a 2-column table. From 1ef9346eab9e827bf31664dae0171656d2cae1af Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 12:42:16 +0200 Subject: [PATCH 0542/1381] Allow renaming of collection. --- .../Collections/ModCollection.Cache.Access.cs | 2 +- Penumbra/Collections/ModCollection.cs | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 37 ++++++++++++------- Penumbra/UI/CollectionTab/InheritanceUi.cs | 29 +++++---------- 4 files changed, 36 insertions(+), 34 deletions(-) diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 7c29676d..b073e731 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -77,7 +77,7 @@ public partial class ModCollection else { _cache.Meta.SetFiles(); - Penumbra.Log.Debug($"Set CharacterUtility resources for collection {Name}."); + Penumbra.Log.Debug($"Set CharacterUtility resources for collection {Identifier}."); } } diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index c1143c71..327d6544 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -28,7 +28,7 @@ public partial class ModCollection public static readonly ModCollection Empty = CreateEmpty(EmptyCollectionName, 0, 0); /// The name of a collection. - public string Name { get; set; } = string.Empty; + public string Name { get; set; } public Guid Id { get; } diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index cbeabbd6..8625335e 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -35,7 +35,8 @@ public sealed class CollectionPanel : IDisposable private static readonly IReadOnlyDictionary Buttons = CreateButtons(); private static readonly IReadOnlyList<(CollectionType, bool, bool, string, uint)> AdvancedTree = CreateTree(); - private readonly List<(CollectionType Type, ActorIdentifier Identifier)> _inUseCache = new(); + private readonly List<(CollectionType Type, ActorIdentifier Identifier)> _inUseCache = []; + private string? _newName; private int _draggedIndividualAssignment = -1; @@ -93,6 +94,18 @@ public sealed class CollectionPanel : IDisposable var first = true; + Button(CollectionType.NonPlayerChild); + Button(CollectionType.NonPlayerElderly); + foreach (var race in Enum.GetValues().Skip(1)) + { + Button(CollectionTypeExtensions.FromParts(race, Gender.Male, false)); + Button(CollectionTypeExtensions.FromParts(race, Gender.Female, false)); + Button(CollectionTypeExtensions.FromParts(race, Gender.Male, true)); + Button(CollectionTypeExtensions.FromParts(race, Gender.Female, true)); + } + + return; + void Button(CollectionType type) { var (name, border) = Buttons[type]; @@ -112,16 +125,6 @@ public sealed class CollectionPanel : IDisposable if (ImGui.GetContentRegionAvail().X < buttonWidth.X + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X) ImGui.NewLine(); } - - Button(CollectionType.NonPlayerChild); - Button(CollectionType.NonPlayerElderly); - foreach (var race in Enum.GetValues().Skip(1)) - { - Button(CollectionTypeExtensions.FromParts(race, Gender.Male, false)); - Button(CollectionTypeExtensions.FromParts(race, Gender.Female, false)); - Button(CollectionTypeExtensions.FromParts(race, Gender.Male, true)); - Button(CollectionTypeExtensions.FromParts(race, Gender.Female, true)); - } } /// Draw the panel containing new and existing individual assignments. @@ -228,12 +231,20 @@ public sealed class CollectionPanel : IDisposable ImGui.SameLine(); ImGui.BeginGroup(); using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); - var name = collection.Name; + var name = _newName ?? collection.Name; var identifier = collection.Identifier; var width = ImGui.GetContentRegionAvail().X; var fileName = _fileNames.CollectionFile(collection); ImGui.SetNextItemWidth(width); - ImGui.InputText("##name", ref name, 128); + if (ImGui.InputText("##name", ref name, 128)) + _newName = name; + if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null) + { + collection.Name = _newName; + _newName = null; + } + else if (ImGui.IsItemDeactivated()) + _newName = null; using (ImRaii.PushFont(UiBuilder.MonoFont)) { if (ImGui.Button(collection.Identifier, new Vector2(width, 0))) diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index 88344e6a..2290592d 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -2,30 +2,21 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.UI.Classes; namespace Penumbra.UI.CollectionTab; -public class InheritanceUi +public class InheritanceUi(CollectionManager collectionManager, CollectionSelector selector) : IUiService { private const int InheritedCollectionHeight = 9; private const string InheritanceDragDropLabel = "##InheritanceMove"; - private readonly CollectionStorage _collections; - private readonly ActiveCollections _active; - private readonly InheritanceManager _inheritance; - private readonly CollectionSelector _selector; - - public InheritanceUi(CollectionManager collectionManager, CollectionSelector selector) - { - _selector = selector; - _collections = collectionManager.Storage; - _active = collectionManager.Active; - _inheritance = collectionManager.Inheritances; - } - + private readonly CollectionStorage _collections = collectionManager.Storage; + private readonly ActiveCollections _active = collectionManager.Active; + private readonly InheritanceManager _inheritance = collectionManager.Inheritances; /// Draw the whole inheritance block. public void Draw() @@ -59,7 +50,7 @@ public class InheritanceUi private (int, int)? _inheritanceAction; private ModCollection? _newCurrentCollection; - private void DrawRightText() + private static void DrawRightText() { using var group = ImRaii.Group(); ImGuiUtil.TextWrapped( @@ -68,7 +59,7 @@ public class InheritanceUi "You can select inheritances from the combo below to add them.\nSince the order of inheritances is important, you can reorder them here via drag and drop.\nYou can also delete inheritances by dragging them onto the trash can."); } - private void DrawHelpPopup() + private static void DrawHelpPopup() => ImGuiUtil.HelpPopup("InheritanceHelp", new Vector2(1000 * UiHelpers.Scale, 20 * ImGui.GetTextLineHeightWithSpacing()), () => { ImGui.NewLine(); @@ -123,7 +114,7 @@ public class InheritanceUi _seenInheritedCollections.Contains(inheritance)); _seenInheritedCollections.Add(inheritance); - ImRaii.TreeNode($"{Name(inheritance)}###{inheritance.Name}", + ImRaii.TreeNode($"{Name(inheritance)}###{inheritance.Id}", ImGuiTreeNodeFlags.NoTreePushOnOpen | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); var (minRect, maxRect) = (ImGui.GetItemRectMin(), ImGui.GetItemRectMax()); DrawInheritanceTreeClicks(inheritance, false); @@ -134,7 +125,7 @@ public class InheritanceUi // Draw the notch and increase the line length. var midPoint = (minRect.Y + maxRect.Y) / 2f - 1f; - drawList.AddLine(new Vector2(lineStart.X, midPoint), new Vector2(lineStart.X + lineSize, midPoint), Colors.MetaInfoText, + drawList.AddLine(lineStart with { Y = midPoint }, new Vector2(lineStart.X + lineSize, midPoint), Colors.MetaInfoText, UiHelpers.Scale); lineEnd.Y = midPoint; } @@ -321,5 +312,5 @@ public class InheritanceUi } private string Name(ModCollection collection) - => _selector.IncognitoMode ? collection.AnonymizedName : collection.Name; + => selector.IncognitoMode ? collection.AnonymizedName : collection.Name; } From 791583e183d4afd0a72e047d988f8ad5cb62a728 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 12:51:33 +0200 Subject: [PATCH 0543/1381] Silence readme warnings. --- Penumbra.Api | 2 +- Penumbra.String | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index e5c8f544..9bbc3b98 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit e5c8f5446879e2e0e541eb4d8fee15e98b1885bc +Subproject commit 9bbc3b98efc2af3707adc75b716d4f3072908e31 diff --git a/Penumbra.String b/Penumbra.String index 14e00f77..caa58c5c 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 14e00f77d42bc677e02325660db765ef11932560 +Subproject commit caa58c5c92710e69ce07b9d736ebe2d228cb4488 From e4f9150c9fc22ab85582f13a5dc866b115e61626 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 14:30:47 +0200 Subject: [PATCH 0544/1381] Fix? --- Penumbra.Api | 2 +- Penumbra/Api/Api/PluginStateApi.cs | 8 ++++---- Penumbra/Communication/ModDirectoryChanged.cs | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 9bbc3b98..cd56068a 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 9bbc3b98efc2af3707adc75b716d4f3072908e31 +Subproject commit cd56068aac3762c7b011d13a04637a3c3f09775f diff --git a/Penumbra/Api/Api/PluginStateApi.cs b/Penumbra/Api/Api/PluginStateApi.cs index 2e87486f..e1eec1b2 100644 --- a/Penumbra/Api/Api/PluginStateApi.cs +++ b/Penumbra/Api/Api/PluginStateApi.cs @@ -13,16 +13,16 @@ public class PluginStateApi(Configuration config, CommunicatorService communicat public string GetConfiguration() => JsonConvert.SerializeObject(config, Formatting.Indented); - public event Action? ModDirectoryChanged + public event Action ModDirectoryChanged { - add => communicator.ModDirectoryChanged.Subscribe(value!, Communication.ModDirectoryChanged.Priority.Api); - remove => communicator.ModDirectoryChanged.Unsubscribe(value!); + add => communicator.ModDirectoryChanged.Subscribe(value, Communication.ModDirectoryChanged.Priority.Api); + remove => communicator.ModDirectoryChanged.Unsubscribe(value); } public bool GetEnabledState() => config.EnableMods; - public event Action? EnabledChange + public event Action EnabledChange { add => communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); remove => communicator.EnabledChanged.Unsubscribe(value!); diff --git a/Penumbra/Communication/ModDirectoryChanged.cs b/Penumbra/Communication/ModDirectoryChanged.cs index 02293873..9c64573f 100644 --- a/Penumbra/Communication/ModDirectoryChanged.cs +++ b/Penumbra/Communication/ModDirectoryChanged.cs @@ -1,5 +1,4 @@ using OtterGui.Classes; -using Penumbra.Api; using Penumbra.Api.Api; namespace Penumbra.Communication; @@ -15,7 +14,7 @@ public sealed class ModDirectoryChanged() : EventWrapper + /// Api = 0, /// From d5ed4a38e4b760b369cc2cbe773a9d017ff464d6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 14:39:12 +0200 Subject: [PATCH 0545/1381] Fix2? --- Penumbra.Api | 2 +- Penumbra/Api/Api/PluginStateApi.cs | 43 ++++++++++++++++++++---------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index cd56068a..a8e2fe02 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit cd56068aac3762c7b011d13a04637a3c3f09775f +Subproject commit a8e2fe0219b8fd1f787171f11e33571317e531c1 diff --git a/Penumbra/Api/Api/PluginStateApi.cs b/Penumbra/Api/Api/PluginStateApi.cs index e1eec1b2..e053e56f 100644 --- a/Penumbra/Api/Api/PluginStateApi.cs +++ b/Penumbra/Api/Api/PluginStateApi.cs @@ -5,26 +5,41 @@ using Penumbra.Services; namespace Penumbra.Api.Api; -public class PluginStateApi(Configuration config, CommunicatorService communicator) : IPenumbraApiPluginState, IApiService +public sealed class PluginStateApi : IPenumbraApiPluginState, IApiService, IDisposable { + private readonly Configuration _config; + private readonly CommunicatorService _communicator; + + public PluginStateApi(Configuration config, CommunicatorService communicator) + { + _config = config; + _communicator = communicator; + _communicator.ModDirectoryChanged.Subscribe(OnModDirectoryChanged, Communication.ModDirectoryChanged.Priority.Api); + _communicator.EnabledChanged.Subscribe(OnEnabledChanged, EnabledChanged.Priority.Api); + } + + public void Dispose() + { + _communicator.ModDirectoryChanged.Unsubscribe(OnModDirectoryChanged); + _communicator.EnabledChanged.Unsubscribe(OnEnabledChanged); + } + public string GetModDirectory() - => config.ModDirectory; + => _config.ModDirectory; public string GetConfiguration() - => JsonConvert.SerializeObject(config, Formatting.Indented); + => JsonConvert.SerializeObject(_config, Formatting.Indented); - public event Action ModDirectoryChanged - { - add => communicator.ModDirectoryChanged.Subscribe(value, Communication.ModDirectoryChanged.Priority.Api); - remove => communicator.ModDirectoryChanged.Unsubscribe(value); - } + public event Action? ModDirectoryChanged; public bool GetEnabledState() - => config.EnableMods; + => _config.EnableMods; - public event Action EnabledChange - { - add => communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); - remove => communicator.EnabledChanged.Unsubscribe(value!); - } + public event Action? EnabledChange; + + private void OnModDirectoryChanged(string modDirectory, bool valid) + => ModDirectoryChanged?.Invoke(modDirectory, valid); + + private void OnEnabledChanged(bool value) + => EnabledChange?.Invoke(value); } From d9bd05c9ecf675da9d2d793b1c0654c8a6c5a613 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 14:45:25 +0200 Subject: [PATCH 0546/1381] Fix issue with Hex viewer. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 9599c806..a50d2aed 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9599c806877e2972f964dfa68e5207cf3a8f2b84 +Subproject commit a50d2aedbb7b2e37d30987bd0b3b96a832fdc0af From 6b5321dad8103ca3a9077f511f47047e90ccdddf Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Apr 2024 14:46:26 +0200 Subject: [PATCH 0547/1381] Test subscription like before but without primary constructor. --- Penumbra/Api/Api/PluginStateApi.cs | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/Penumbra/Api/Api/PluginStateApi.cs b/Penumbra/Api/Api/PluginStateApi.cs index e053e56f..d69df448 100644 --- a/Penumbra/Api/Api/PluginStateApi.cs +++ b/Penumbra/Api/Api/PluginStateApi.cs @@ -5,7 +5,7 @@ using Penumbra.Services; namespace Penumbra.Api.Api; -public sealed class PluginStateApi : IPenumbraApiPluginState, IApiService, IDisposable +public class PluginStateApi : IPenumbraApiPluginState, IApiService { private readonly Configuration _config; private readonly CommunicatorService _communicator; @@ -14,14 +14,6 @@ public sealed class PluginStateApi : IPenumbraApiPluginState, IApiService, IDisp { _config = config; _communicator = communicator; - _communicator.ModDirectoryChanged.Subscribe(OnModDirectoryChanged, Communication.ModDirectoryChanged.Priority.Api); - _communicator.EnabledChanged.Subscribe(OnEnabledChanged, EnabledChanged.Priority.Api); - } - - public void Dispose() - { - _communicator.ModDirectoryChanged.Unsubscribe(OnModDirectoryChanged); - _communicator.EnabledChanged.Unsubscribe(OnEnabledChanged); } public string GetModDirectory() @@ -30,16 +22,18 @@ public sealed class PluginStateApi : IPenumbraApiPluginState, IApiService, IDisp public string GetConfiguration() => JsonConvert.SerializeObject(_config, Formatting.Indented); - public event Action? ModDirectoryChanged; + public event Action? ModDirectoryChanged + { + add => _communicator.ModDirectoryChanged.Subscribe(value!, Communication.ModDirectoryChanged.Priority.Api); + remove => _communicator.ModDirectoryChanged.Unsubscribe(value!); + } public bool GetEnabledState() => _config.EnableMods; - public event Action? EnabledChange; - - private void OnModDirectoryChanged(string modDirectory, bool valid) - => ModDirectoryChanged?.Invoke(modDirectory, valid); - - private void OnEnabledChanged(bool value) - => EnabledChange?.Invoke(value); + public event Action? EnabledChange + { + add => _communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); + remove => _communicator.EnabledChanged.Unsubscribe(value!); + } } From 42ad941ec22906f2d631ca22dd7dba16b16bca18 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 13 Apr 2024 16:05:44 +0200 Subject: [PATCH 0548/1381] Add GetCollectionsByIdentifier. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ApiHelpers.cs | 6 ++++-- Penumbra/Api/Api/CollectionApi.cs | 19 +++++++++++++++++ Penumbra/Api/IpcProviders.cs | 1 + .../Api/IpcTester/CollectionsIpcTester.cs | 21 ++++++++++++++++++- 5 files changed, 45 insertions(+), 4 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index a8e2fe02..2f76f42e 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit a8e2fe0219b8fd1f787171f11e33571317e531c1 +Subproject commit 2f76f42e54141258d89300aa78d42fb3f1878092 diff --git a/Penumbra/Api/Api/ApiHelpers.cs b/Penumbra/Api/Api/ApiHelpers.cs index 32a3956f..92a30bce 100644 --- a/Penumbra/Api/Api/ApiHelpers.cs +++ b/Penumbra/Api/Api/ApiHelpers.cs @@ -48,8 +48,10 @@ public class ApiHelpers( [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] internal static PenumbraApiEc Return(PenumbraApiEc ec, LazyString args, [CallerMemberName] string name = "Unknown") { - Penumbra.Log.Debug( - $"[{name}] Called with {args}, returned {ec}."); + if (ec is PenumbraApiEc.Success or PenumbraApiEc.NothingChanged) + Penumbra.Log.Verbose($"[{name}] Called with {args}, returned {ec}."); + else + Penumbra.Log.Debug($"[{name}] Called with {args}, returned {ec}."); return ec; } diff --git a/Penumbra/Api/Api/CollectionApi.cs b/Penumbra/Api/Api/CollectionApi.cs index de704460..e99850a6 100644 --- a/Penumbra/Api/Api/CollectionApi.cs +++ b/Penumbra/Api/Api/CollectionApi.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -10,6 +11,24 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : public Dictionary GetCollections() => collections.Storage.ToDictionary(c => c.Id, c => c.Name); + public List<(Guid Id, string Name)> GetCollectionsByIdentifier(string identifier) + { + if (identifier.Length == 0) + return []; + + var list = new List<(Guid Id, string Name)>(4); + if (Guid.TryParse(identifier, out var guid) && collections.Storage.ById(guid, out var collection) && collection != ModCollection.Empty) + list.Add((collection.Id, collection.Name)); + else if (identifier.Length >= 8) + list.AddRange(collections.Storage.Where(c => c.Identifier.StartsWith(identifier, StringComparison.OrdinalIgnoreCase)) + .Select(c => (c.Id, c.Name))); + + list.AddRange(collections.Storage + .Where(c => string.Equals(c.Name, identifier, StringComparison.OrdinalIgnoreCase) && !list.Contains((c.Id, c.Name))) + .Select(c => (c.Id, c.Name))); + return list; + } + public Dictionary GetChangedItemsForCollection(Guid collectionId) { try diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 293af588..cc98ef0d 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -19,6 +19,7 @@ public sealed class IpcProviders : IDisposable, IApiService _providers = [ IpcSubscribers.GetCollections.Provider(pi, api.Collection), + IpcSubscribers.GetCollectionsByIdentifier.Provider(pi, api.Collection), IpcSubscribers.GetChangedItemsForCollection.Provider(pi, api.Collection), IpcSubscribers.GetCollection.Provider(pi, api.Collection), IpcSubscribers.GetCollectionForObject.Provider(pi, api.Collection), diff --git a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs index 12314f0c..2679bc69 100644 --- a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs +++ b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs @@ -35,7 +35,7 @@ public class CollectionsIpcTester(DalamudPluginInterface pi) : IUiService ImGuiUtil.GenericEnumCombo("Collection Type", 200, _type, out _type, t => ((CollectionType)t).ToName()); ImGui.InputInt("Object Index##Collections", ref _objectIdx, 0, 0); - ImGuiUtil.GuidInput("Collection Id##Collections", "Collection GUID...", string.Empty, ref _collectionId, ref _collectionIdString); + ImGuiUtil.GuidInput("Collection Id##Collections", "Collection Identifier...", string.Empty, ref _collectionId, ref _collectionIdString); ImGui.Checkbox("Allow Assignment Creation", ref _allowCreation); ImGui.SameLine(); ImGui.Checkbox("Allow Assignment Deletion", ref _allowDeletion); @@ -48,6 +48,25 @@ public class CollectionsIpcTester(DalamudPluginInterface pi) : IUiService if (_oldCollection != null) ImGui.TextUnformatted(!_oldCollection.HasValue ? "Created" : _oldCollection.ToString()); + IpcTester.DrawIntro(GetCollectionsByIdentifier.Label, "Collection Identifier"); + var collectionList = new GetCollectionsByIdentifier(pi).Invoke(_collectionIdString); + if (collectionList.Count == 0) + { + DrawCollection(null); + } + else + { + DrawCollection(collectionList[0]); + foreach (var pair in collectionList.Skip(1)) + { + ImGui.TableNextRow(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + DrawCollection(pair); + } + } + IpcTester.DrawIntro(GetCollection.Label, "Current Collection"); DrawCollection(new GetCollection(pi).Invoke(ApiCollectionType.Current)); From 94b53ce7fab320286a08c2533fc400e0055eccd4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 13 Apr 2024 16:06:04 +0200 Subject: [PATCH 0549/1381] Meh. --- Penumbra/Api/Api/CollectionApi.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Penumbra/Api/Api/CollectionApi.cs b/Penumbra/Api/Api/CollectionApi.cs index e99850a6..ff393aaf 100644 --- a/Penumbra/Api/Api/CollectionApi.cs +++ b/Penumbra/Api/Api/CollectionApi.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; From d4183a03c0734fb72e810fdbcfc2f3b33495ed1c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Apr 2024 15:00:48 +0200 Subject: [PATCH 0550/1381] Fix bug with new empty collections. --- Penumbra/Collections/ModCollection.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index 327d6544..e666b151 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -25,7 +25,7 @@ public partial class ModCollection /// Create the always available Empty Collection that will always sit at index 0, /// can not be deleted and does never create a cache. /// - public static readonly ModCollection Empty = CreateEmpty(EmptyCollectionName, 0, 0); + public static readonly ModCollection Empty = new(Guid.Empty, EmptyCollectionName, 0, 0, CurrentVersion, [], [], []); /// The name of a collection. public string Name { get; set; } @@ -150,7 +150,7 @@ public partial class ModCollection public static ModCollection CreateEmpty(string name, int index, int modCount) { Debug.Assert(index >= 0, "Empty collection created with negative index."); - return new ModCollection(Guid.Empty, name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], + return new ModCollection(Guid.NewGuid(), name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], []); } From aeccf2b1c60074a49ec01b6430d9806323c89079 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Apr 2024 15:38:14 +0200 Subject: [PATCH 0551/1381] Update Submodules. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index a50d2aed..3460a817 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit a50d2aedbb7b2e37d30987bd0b3b96a832fdc0af +Subproject commit 3460a817fc5e01a6b60eb834c3c59031938388fc diff --git a/Penumbra.Api b/Penumbra.Api index 2f76f42e..0c8578cf 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 2f76f42e54141258d89300aa78d42fb3f1878092 +Subproject commit 0c8578cfa12bf0591ed204fd89b30b66719f678f diff --git a/Penumbra.GameData b/Penumbra.GameData index 60222d79..fe9d563d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 60222d79420662fb8e9960a66e262a380fcaf186 +Subproject commit fe9d563d9845630673cf098f7a6bfbd26e600fb4 From 0fa62f40d76c1fbbddf9f4c569a7195db811ee82 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Apr 2024 16:57:23 +0200 Subject: [PATCH 0552/1381] Add Versions provider. --- Penumbra/Api/IpcProviders.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index cc98ef0d..21fe0a7c 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -61,6 +61,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.CopyModSettings.Provider(pi, api.ModSettings), IpcSubscribers.ApiVersion.Provider(pi, api), + new FuncProvider<(int Major, int Minor)>(pi, "Penumbra.ApiVersions", () => api.ApiVersion), // backward compatibility IpcSubscribers.GetModDirectory.Provider(pi, api.PluginState), IpcSubscribers.GetConfiguration.Provider(pi, api.PluginState), IpcSubscribers.ModDirectoryChanged.Provider(pi, api.PluginState), From 1641166d6e168d8b7e185ae0762e574cddf63201 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Apr 2024 18:15:26 +0200 Subject: [PATCH 0553/1381] Disable IPC listeners by default. --- Penumbra/Api/IpcTester/GameStateIpcTester.cs | 7 +++++-- Penumbra/Api/IpcTester/ModSettingsIpcTester.cs | 1 + Penumbra/Api/IpcTester/ModsIpcTester.cs | 6 ++++++ Penumbra/Api/IpcTester/PluginStateIpcTester.cs | 2 ++ Penumbra/Api/IpcTester/RedrawingIpcTester.cs | 7 ++++--- Penumbra/Api/IpcTester/UiIpcTester.cs | 7 ++++++- 6 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Penumbra/Api/IpcTester/GameStateIpcTester.cs b/Penumbra/Api/IpcTester/GameStateIpcTester.cs index 2c41b882..93806162 100644 --- a/Penumbra/Api/IpcTester/GameStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/GameStateIpcTester.cs @@ -33,9 +33,12 @@ public class GameStateIpcTester : IUiService, IDisposable public GameStateIpcTester(DalamudPluginInterface pi) { _pi = pi; - CharacterBaseCreating = CreatingCharacterBase.Subscriber(pi, UpdateLastCreated); - CharacterBaseCreated = CreatedCharacterBase.Subscriber(pi, UpdateLastCreated2); + CharacterBaseCreating = IpcSubscribers.CreatingCharacterBase.Subscriber(pi, UpdateLastCreated); + CharacterBaseCreated = IpcSubscribers.CreatedCharacterBase.Subscriber(pi, UpdateLastCreated2); GameObjectResourcePathResolved = IpcSubscribers.GameObjectResourcePathResolved.Subscriber(pi, UpdateGameObjectResourcePath); + CharacterBaseCreating.Disable(); + CharacterBaseCreated.Disable(); + GameObjectResourcePathResolved.Disable(); } public void Dispose() diff --git a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs index c33fcdee..b117d603 100644 --- a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs @@ -37,6 +37,7 @@ public class ModSettingsIpcTester : IUiService, IDisposable { _pi = pi; SettingChanged = ModSettingChanged.Subscriber(pi, UpdateLastModSetting); + SettingChanged.Disable(); } public void Dispose() diff --git a/Penumbra/Api/IpcTester/ModsIpcTester.cs b/Penumbra/Api/IpcTester/ModsIpcTester.cs index 878a8214..43f397e5 100644 --- a/Penumbra/Api/IpcTester/ModsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModsIpcTester.cs @@ -55,13 +55,19 @@ public class ModsIpcTester : IUiService, IDisposable _lastMovedModFrom = s1; _lastMovedModTo = s2; }); + DeleteSubscriber.Disable(); + AddSubscriber.Disable(); + MoveSubscriber.Disable(); } public void Dispose() { DeleteSubscriber.Dispose(); + DeleteSubscriber.Disable(); AddSubscriber.Dispose(); + AddSubscriber.Disable(); MoveSubscriber.Dispose(); + MoveSubscriber.Disable(); } public void Draw() diff --git a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs index 0588e5bd..984f17b1 100644 --- a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs @@ -36,6 +36,8 @@ public class PluginStateIpcTester : IUiService, IDisposable Initialized = IpcSubscribers.Initialized.Subscriber(pi, AddInitialized); Disposed = IpcSubscribers.Disposed.Subscriber(pi, AddDisposed); EnabledChange = IpcSubscribers.EnabledChange.Subscriber(pi, SetLastEnabled); + ModDirectoryChanged.Disable(); + EnabledChange.Disable(); } public void Dispose() diff --git a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs index 281c7ad4..801f0b97 100644 --- a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs +++ b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs @@ -22,9 +22,10 @@ public class RedrawingIpcTester : IUiService, IDisposable public RedrawingIpcTester(DalamudPluginInterface pi, ObjectManager objects) { - _pi = pi; - _objects = objects; - Redrawn = GameObjectRedrawn.Subscriber(_pi, SetLastRedrawn); + _pi = pi; + _objects = objects; + Redrawn = GameObjectRedrawn.Subscriber(_pi, SetLastRedrawn); + Redrawn.Disable(); } public void Dispose() diff --git a/Penumbra/Api/IpcTester/UiIpcTester.cs b/Penumbra/Api/IpcTester/UiIpcTester.cs index 29ddc22e..d95b79b8 100644 --- a/Penumbra/Api/IpcTester/UiIpcTester.cs +++ b/Penumbra/Api/IpcTester/UiIpcTester.cs @@ -5,7 +5,6 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; using Penumbra.Api.IpcSubscribers; -using Penumbra.Communication; namespace Penumbra.Api.IpcTester; @@ -38,6 +37,12 @@ public class UiIpcTester : IUiService, IDisposable PostSettingsPanelDraw = IpcSubscribers.PostSettingsPanelDraw.Subscriber(pi, UpdateLastDrawnMod); ChangedItemTooltip = IpcSubscribers.ChangedItemTooltip.Subscriber(pi, AddedTooltip); ChangedItemClicked = IpcSubscribers.ChangedItemClicked.Subscriber(pi, AddedClick); + PreSettingsTabBar.Disable(); + PreSettingsPanel.Disable(); + PostEnabled.Disable(); + PostSettingsPanelDraw.Disable(); + ChangedItemTooltip.Disable(); + ChangedItemClicked.Disable(); } public void Dispose() From fd1f9b95d60b85d036f27addd3f7a965e815be75 Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 18 Apr 2024 21:23:18 +1000 Subject: [PATCH 0554/1381] Add Single2 support for UVs --- Penumbra/Import/Models/Export/MeshExporter.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index d3ca87dc..c2562293 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -312,6 +312,7 @@ public class MeshExporter { return type switch { + MdlFile.VertexType.Single2 => new Vector2(reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.UByte4 => reader.ReadBytes(4), @@ -379,6 +380,7 @@ public class MeshExporter { MdlFile.VertexType.Half2 => 1, MdlFile.VertexType.Half4 => 2, + MdlFile.VertexType.Single2 => 1, MdlFile.VertexType.Single4 => 2, _ => throw _notifier.Exception($"Unexpected UV vertex type {type}."), }; From dbfaf37800f20c202f8d01a6dacf6348ecdb7a9f Mon Sep 17 00:00:00 2001 From: ackwell Date: Thu, 18 Apr 2024 21:47:07 +1000 Subject: [PATCH 0555/1381] Export to .glb --- Penumbra/Import/Models/ModelManager.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 1a52c4dd..485a76a7 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -213,7 +213,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect Penumbra.Log.Debug("[GLTF Export] Saving..."); var gltfModel = scene.ToGltf2(); - gltfModel.SaveGLTF(outputPath); + gltfModel.Save(outputPath); Penumbra.Log.Debug("[GLTF Export] Done."); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 03f276ea..6cd9b912 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -145,8 +145,8 @@ public partial class ModEditWindow if (ImGuiUtil.DrawDisabledButton("Export to glTF", Vector2.Zero, "Exports this mdl file to glTF, for use in 3D authoring applications.", tab.PendingIo || gamePath.IsEmpty)) - _fileDialog.OpenSavePicker("Save model as glTF.", ".gltf", Path.GetFileNameWithoutExtension(gamePath.Filename().ToString()), - ".gltf", (valid, path) => + _fileDialog.OpenSavePicker("Save model as glTF.", ".glb", Path.GetFileNameWithoutExtension(gamePath.Filename().ToString()), + ".glb", (valid, path) => { if (!valid) return; From aeb7bd5431d0e3822010305ebeeb87de5b52604b Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 19 Apr 2024 00:34:08 +1000 Subject: [PATCH 0556/1381] Ensure materials contain at least one / --- .../ModEditWindow.Models.MdlTab.cs | 13 ++++- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 54 +++++++++++++------ 2 files changed, 49 insertions(+), 18 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index cca8fe10..b8c0176a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -49,7 +49,7 @@ public partial class ModEditWindow /// public bool Valid - => Mdl.Valid; + => Mdl.Valid && Mdl.Materials.All(ValidateMaterial); /// public byte[] Write() @@ -285,6 +285,17 @@ public partial class ModEditWindow : _edit._gameData.GetFile(resolvedPath.InternalName.ToString())?.Data; } + /// Validate the specified material. + /// + /// While materials can be relative (`/mt_...`) or absolute (`bg/...`), + /// they invariably must contain at least one directory seperator. + /// Missing this can lead to a crash. + /// + public bool ValidateMaterial(string material) + { + return material.Contains('/'); + } + /// Remove the material given by the index. /// Meshes using the removed material are redirected to material 0, and those after the index are corrected. public void RemoveMaterial(int materialIndex) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 6cd9b912..1cfa7585 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Components; using ImGuiNET; using OtterGui; using OtterGui.Custom; @@ -295,7 +296,7 @@ public partial class ModEditWindow if (!ImGui.CollapsingHeader("Materials")) return false; - using var table = ImRaii.Table(string.Empty, disabled ? 2 : 3, ImGuiTableFlags.SizingFixedFit); + using var table = ImRaii.Table(string.Empty, disabled ? 2 : 4, ImGuiTableFlags.SizingFixedFit); if (!table) return false; @@ -305,7 +306,10 @@ public partial class ModEditWindow ImGui.TableSetupColumn("index", ImGuiTableColumnFlags.WidthFixed, 80 * UiHelpers.Scale); ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthStretch, 1); if (!disabled) + { ImGui.TableSetupColumn("actions", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); + ImGui.TableSetupColumn("help", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); + } var inputFlags = disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None; for (var materialIndex = 0; materialIndex < materials.Length; materialIndex++) @@ -321,12 +325,15 @@ public partial class ModEditWindow ImGui.InputTextWithHint("##newMaterial", "Add new material...", ref _modelNewMaterial, Utf8GamePath.MaxGamePathLength, inputFlags); var validName = _modelNewMaterial.Length > 0 && _modelNewMaterial[0] == '/'; ImGui.TableNextColumn(); - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, string.Empty, !validName, true)) - return ret; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, string.Empty, !validName, true)) + { + ret |= true; + tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); + _modelNewMaterial = string.Empty; + } + ImGui.TableNextColumn(); - tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); - _modelNewMaterial = string.Empty; - return true; + return ret; } private bool DrawMaterialRow(MdlTab tab, bool disabled, string[] materials, int materialIndex, ImGuiInputTextFlags inputFlags) @@ -353,20 +360,33 @@ public partial class ModEditWindow return ret; ImGui.TableNextColumn(); - // Need to have at least one material. - if (materials.Length <= 1) - return ret; + if (materials.Length > 1) + { + var tt = "Delete this material.\nAny meshes targeting this material will be updated to use material #1."; + var modifierActive = _config.DeleteModModifier.IsActive(); + if (!modifierActive) + tt += $"\nHold {_config.DeleteModModifier} to delete."; - var tt = "Delete this material.\nAny meshes targeting this material will be updated to use material #1."; - var modifierActive = _config.DeleteModModifier.IsActive(); - if (!modifierActive) - tt += $"\nHold {_config.DeleteModModifier} to delete."; - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, tt, !modifierActive, true)) - return ret; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, tt, !modifierActive, true)) + { + tab.RemoveMaterial(materialIndex); + ret |= true; + } + } - tab.RemoveMaterial(materialIndex); - return true; + ImGui.TableNextColumn(); + // Add markers to invalid materials. + if (!tab.ValidateMaterial(temp)) + using (var colorHandle = ImRaii.PushColor(ImGuiCol.TextDisabled, 0xFF0000FF, true)) + { + ImGuiComponents.HelpMarker( + "Materials must be either relative (e.g. \"/filename.mtrl\")\n" + + "or absolute (e.g. \"chara/full/path/to/filename.mtrl\").", + FontAwesomeIcon.TimesCircle); + } + + return ret; } private bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) From ef1bbb6d9d8443791a0c4d534bf373f0e490e966 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Apr 2024 15:40:12 +0200 Subject: [PATCH 0557/1381] I don't know what I'm doing --- Penumbra.GameData | 2 +- .../Import/Models/Export/MaterialExporter.cs | 3 +- Penumbra/Import/Models/Export/MeshExporter.cs | 19 +++++----- Penumbra/Import/Models/Import/MeshImporter.cs | 13 ++++--- .../Import/Models/Import/ModelImporter.cs | 34 +++++++++--------- .../LiveColorTablePreviewer.cs | 7 ++-- .../ModEditWindow.Materials.ColorTable.cs | 35 ++++++++++--------- .../ModEditWindow.Materials.MtrlTab.cs | 9 ++--- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 2 +- 9 files changed, 65 insertions(+), 59 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fe9d563d..845d1f99 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fe9d563d9845630673cf098f7a6bfbd26e600fb4 +Subproject commit 845d1f99a752f4d23288a316e42d4bfa32fa987f diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 2fa4e1b2..73a5e725 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -1,5 +1,6 @@ using Lumina.Data.Parsing; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.MaterialStructs; using SharpGLTF.Materials; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; @@ -102,7 +103,7 @@ public class MaterialExporter // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. - private readonly struct ProcessCharacterNormalOperation(Image normal, MtrlFile.ColorTable table) : IRowOperation + private readonly struct ProcessCharacterNormalOperation(Image normal, ColorTable table) : IRowOperation { public Image Normal { get; } = normal.Clone(); public Image BaseColor { get; } = new(normal.Width, normal.Height); diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index d3ca87dc..f372f665 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -3,6 +3,7 @@ using Lumina.Data.Parsing; using Lumina.Extensions; using OtterGui; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; using SharpGLTF.IO; @@ -55,7 +56,7 @@ public class MeshExporter private readonly byte _lod; private readonly ushort _meshIndex; - private MdlStructs.MeshStruct XivMesh + private MeshStruct XivMesh => _mdl.Meshes[_meshIndex]; private readonly MaterialBuilder _material; @@ -109,8 +110,8 @@ public class MeshExporter var xivBoneTable = _mdl.BoneTables[XivMesh.BoneTableIndex]; var indexMap = new Dictionary(); - - foreach (var (xivBoneIndex, tableIndex) in xivBoneTable.BoneIndex.Take(xivBoneTable.BoneCount).WithIndex()) + // #TODO @ackwell maybe fix for V6 Models, I think this works fine. + foreach (var (xivBoneIndex, tableIndex) in xivBoneTable.BoneIndex.Take((int)xivBoneTable.BoneCount).WithIndex()) { var boneName = _mdl.Bones[xivBoneIndex]; if (!skeleton.Names.TryGetValue(boneName, out var gltfBoneIndex)) @@ -238,19 +239,15 @@ public class MeshExporter { "targetNames", shapeNames }, }); - string[] attributes = []; - var maxAttribute = 31 - BitOperations.LeadingZeroCount(attributeMask); + string[] attributes = []; + var maxAttribute = 31 - BitOperations.LeadingZeroCount(attributeMask); if (maxAttribute < _mdl.Attributes.Length) - { attributes = Enumerable.Range(0, 32) .Where(index => ((attributeMask >> index) & 1) == 1) .Select(index => _mdl.Attributes[index]) .ToArray(); - } else - { _notifier.Warning("Invalid attribute data, ignoring."); - } return new MeshData { @@ -278,7 +275,7 @@ public class MeshExporter for (var streamIndex = 0; streamIndex < MaximumMeshBufferStreams; streamIndex++) { streams[streamIndex] = new BinaryReader(new MemoryStream(_mdl.RemainingData)); - streams[streamIndex].Seek(_mdl.VertexOffset[_lod] + XivMesh.VertexBufferOffset[streamIndex]); + streams[streamIndex].Seek(_mdl.VertexOffset[_lod] + XivMesh.VertexBufferOffset(streamIndex)); } var sortedElements = _mdl.VertexDeclarations[_meshIndex].VertexElements @@ -315,7 +312,7 @@ public class MeshExporter MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.UByte4 => reader.ReadBytes(4), - MdlFile.VertexType.NByte4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, + MdlFile.VertexType.NByte4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 1d4b223d..3a11cb04 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -1,5 +1,6 @@ using Lumina.Data.Parsing; using OtterGui; +using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; @@ -8,7 +9,7 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) { public struct Mesh { - public MdlStructs.MeshStruct MeshStruct; + public MeshStruct MeshStruct; public List SubMeshStructs; public string? Material; @@ -69,10 +70,14 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) return new Mesh { - MeshStruct = new MdlStructs.MeshStruct + MeshStruct = new MeshStruct { - VertexBufferOffset = [0, (uint)_streams[0].Count, (uint)(_streams[0].Count + _streams[1].Count)], - VertexBufferStride = _strides, + VertexBufferOffset1 = 0, + VertexBufferOffset2 = (uint)_streams[0].Count, + VertexBufferOffset3 = (uint)(_streams[0].Count + _streams[1].Count), + VertexBufferStride1 = _strides[0], + VertexBufferStride2 = _strides[1], + VertexBufferStride3 = _strides[2], VertexCount = _vertexCount, VertexStreamCount = (byte)_vertexDeclaration.Value.VertexElements .Select(element => element.Stream + 1) diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 8f917b0e..eedd12ab 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -1,6 +1,7 @@ using Lumina.Data.Parsing; using OtterGui; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; @@ -14,10 +15,11 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) } // NOTE: This is intended to match TexTool's grouping regex, ".*[_ ^]([0-9]+)[\\.\\-]?([0-9]+)?$" - [GeneratedRegex(@"[_ ^](?'Mesh'[0-9]+)[.-]?(?'SubMesh'[0-9]+)?$", RegexOptions.Compiled | RegexOptions.NonBacktracking | RegexOptions.ExplicitCapture)] + [GeneratedRegex(@"[_ ^](?'Mesh'[0-9]+)[.-]?(?'SubMesh'[0-9]+)?$", + RegexOptions.Compiled | RegexOptions.NonBacktracking | RegexOptions.ExplicitCapture)] private static partial Regex MeshNameGroupingRegex(); - private readonly List _meshes = []; + private readonly List _meshes = []; private readonly List _subMeshes = []; private readonly List _materials = []; @@ -27,10 +29,10 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) private readonly List _indices = []; - private readonly List _bones = []; - private readonly List _boneTables = []; + private readonly List _bones = []; + private readonly List _boneTables = []; - private readonly BoundingBox _boundingBox = new BoundingBox(); + private readonly BoundingBox _boundingBox = new(); private readonly List _metaAttributes = []; @@ -95,9 +97,7 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) IndexBufferSize = (uint)indexBuffer.Length, }, ], - - Materials = [.. materials], - + Materials = [.. materials], BoundingBoxes = _boundingBox.ToStruct(), // TODO: Would be good to calculate all of this up the tree. @@ -132,9 +132,9 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) private void BuildMeshForGroup(IEnumerable subMeshNodes, int index) { // Record some offsets we'll be using later, before they get mutated with mesh values. - var subMeshOffset = _subMeshes.Count; - var vertexOffset = _vertexBuffer.Count; - var indexOffset = _indices.Count; + var subMeshOffset = _subMeshes.Count; + var vertexOffset = _vertexBuffer.Count; + var indexOffset = _indices.Count; var mesh = MeshImporter.Import(subMeshNodes, notifier.WithContext($"Mesh {index}")); var meshStartIndex = (uint)(mesh.MeshStruct.StartIndex + indexOffset); @@ -154,9 +154,9 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) SubMeshIndex = (ushort)(mesh.MeshStruct.SubMeshIndex + subMeshOffset), BoneTableIndex = boneTableIndex, StartIndex = meshStartIndex, - VertexBufferOffset = mesh.MeshStruct.VertexBufferOffset - .Select(offset => (uint)(offset + vertexOffset)) - .ToArray(), + VertexBufferOffset1 = (uint)(mesh.MeshStruct.VertexBufferOffset1 + vertexOffset), + VertexBufferOffset2 = (uint)(mesh.MeshStruct.VertexBufferOffset2 + vertexOffset), + VertexBufferOffset3 = (uint)(mesh.MeshStruct.VertexBufferOffset3 + vertexOffset), }); _boundingBox.Merge(mesh.BoundingBox); @@ -196,7 +196,8 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) // arrays, values is practically guaranteed to be the highest of the // group, so a failure on any of them will be a failure on it. if (_shapeValues.Count > ushort.MaxValue) - throw notifier.Exception($"Importing this file would require more than the maximum of {ushort.MaxValue} shape values.\nTry removing or applying shape keys that do not need to be changed at runtime in-game."); + throw notifier.Exception( + $"Importing this file would require more than the maximum of {ushort.MaxValue} shape values.\nTry removing or applying shape keys that do not need to be changed at runtime in-game."); } private ushort GetMaterialIndex(string materialName) @@ -216,6 +217,7 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) return (ushort)count; } + // #TODO @ackwell fix for V6 Models private ushort BuildBoneTable(List boneNames) { var boneIndices = new List(); @@ -238,7 +240,7 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); var boneTableIndex = _boneTables.Count; - _boneTables.Add(new MdlStructs.BoneTableStruct() + _boneTables.Add(new BoneTableStruct() { BoneIndex = boneIndicesArray, BoneCount = (byte)boneIndices.Count, diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index 4d35e68a..f211e0bc 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -1,6 +1,5 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; -using Penumbra.GameData.Files; using Penumbra.GameData.Interop; using Penumbra.Interop.SafeHandles; @@ -9,7 +8,7 @@ namespace Penumbra.Interop.MaterialPreview; public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase { public const int TextureWidth = 4; - public const int TextureHeight = MtrlFile.ColorTable.NumRows; + public const int TextureHeight = GameData.Files.MaterialStructs.ColorTable.NumUsedRows; public const int TextureLength = TextureWidth * TextureHeight * 4; private readonly IFramework _framework; @@ -17,7 +16,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase private readonly Texture** _colorTableTexture; private readonly SafeTextureHandle _originalColorTableTexture; - private bool _updatePending; + private bool _updatePending; public Half[] ColorTable { get; } @@ -40,7 +39,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (_originalColorTableTexture == null) throw new InvalidOperationException("Material doesn't have a color table"); - ColorTable = new Half[TextureLength]; + ColorTable = new Half[TextureLength]; _updatePending = true; framework.Update += OnFrameworkUpdate; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index a4e25f77..54c0eff6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -4,6 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.MaterialStructs; using Penumbra.String.Functions; namespace Penumbra.UI.AdvancedWindow; @@ -74,7 +75,7 @@ public partial class ModEditWindow ImGui.TableHeader("Dye Preview"); } - for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) + for (var i = 0; i < ColorTable.NumUsedRows; ++i) { ret |= DrawColorTableRow(tab, i, disabled); ImGui.TableNextRow(); @@ -115,8 +116,8 @@ public partial class ModEditWindow { var ret = false; if (tab.Mtrl.HasDyeTable) - for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) - ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId); + for (var i = 0; i < ColorTable.NumUsedRows; ++i) + ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId, 0); tab.UpdateColorTablePreview(); @@ -140,21 +141,21 @@ public partial class ModEditWindow { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - if (data.Length < Marshal.SizeOf()) + if (data.Length < Marshal.SizeOf()) return false; ref var rows = ref tab.Mtrl.Table; fixed (void* ptr = data, output = &rows) { - MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); - if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() + MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); + if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() && tab.Mtrl.HasDyeTable) { ref var dyeRows = ref tab.Mtrl.DyeTable; fixed (void* output2 = &dyeRows) { - MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), - Marshal.SizeOf()); + MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), + Marshal.SizeOf()); } } } @@ -169,7 +170,7 @@ public partial class ModEditWindow } } - private static unsafe void ColorTableCopyClipboardButton(MtrlFile.ColorTable.Row row, MtrlFile.ColorDyeTable.Row dye) + private static unsafe void ColorTableCopyClipboardButton(ColorTable.Row row, ColorDyeTable.Row dye) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, "Export this row to your clipboard.", false, true)) @@ -177,11 +178,11 @@ public partial class ModEditWindow try { - var data = new byte[MtrlFile.ColorTable.Row.Size + 2]; + var data = new byte[ColorTable.Row.Size + 2]; fixed (byte* ptr = data) { - MemoryUtility.MemCpyUnchecked(ptr, &row, MtrlFile.ColorTable.Row.Size); - MemoryUtility.MemCpyUnchecked(ptr + MtrlFile.ColorTable.Row.Size, &dye, 2); + MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTable.Row.Size); + MemoryUtility.MemCpyUnchecked(ptr + ColorTable.Row.Size, &dye, 2); } var text = Convert.ToBase64String(data); @@ -217,15 +218,15 @@ public partial class ModEditWindow { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - if (data.Length != MtrlFile.ColorTable.Row.Size + 2 + if (data.Length != ColorTable.Row.Size + 2 || !tab.Mtrl.HasTable) return false; fixed (byte* ptr = data) { - tab.Mtrl.Table[rowIdx] = *(MtrlFile.ColorTable.Row*)ptr; + tab.Mtrl.Table[rowIdx] = *(ColorTable.Row*)ptr; if (tab.Mtrl.HasDyeTable) - tab.Mtrl.DyeTable[rowIdx] = *(MtrlFile.ColorDyeTable.Row*)(ptr + MtrlFile.ColorTable.Row.Size); + tab.Mtrl.DyeTable[rowIdx] = *(ColorDyeTable.Row*)(ptr + ColorTable.Row.Size); } tab.UpdateColorTableRowPreview(rowIdx); @@ -451,7 +452,7 @@ public partial class ModEditWindow return ret; } - private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, MtrlFile.ColorDyeTable.Row dye, float floatSize) + private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, ColorDyeTable.Row dye, float floatSize) { var stain = _stainService.StainCombo.CurrentSelection.Key; if (stain == 0 || !_stainService.StmFile.Entries.TryGetValue(dye.Template, out var entry)) @@ -463,7 +464,7 @@ public partial class ModEditWindow var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Apply the selected dye to this row.", disabled, true); - ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, rowIdx, stain); + ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, rowIdx, stain, 0); if (ret) tab.UpdateColorTableRowPreview(rowIdx); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index b4801f5f..9421493e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -8,6 +8,7 @@ using OtterGui.Classes; using OtterGui.Raii; using Penumbra.GameData.Data; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.MaterialStructs; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.Objects; using Penumbra.Interop.MaterialPreview; @@ -601,7 +602,7 @@ public partial class ModEditWindow var stm = _edit._stainService.StmFile; var dye = Mtrl.DyeTable[rowIdx]; if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) - row.ApplyDyeTemplate(dye, dyes); + row.ApplyDyeTemplate(dye, dyes, default); } if (HighlightedColorTableRow == rowIdx) @@ -628,12 +629,12 @@ public partial class ModEditWindow { var stm = _edit._stainService.StmFile; var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; - for (var i = 0; i < MtrlFile.ColorTable.NumRows; ++i) + for (var i = 0; i < ColorTable.NumUsedRows; ++i) { ref var row = ref rows[i]; var dye = Mtrl.DyeTable[i]; if (stm.TryGetValue(dye.Template, stainId, out var dyes)) - row.ApplyDyeTemplate(dye, dyes); + row.ApplyDyeTemplate(dye, dyes, default); } } @@ -647,7 +648,7 @@ public partial class ModEditWindow } } - private static void ApplyHighlight(ref MtrlFile.ColorTable.Row row, float time) + private static void ApplyHighlight(ref ColorTable.Row row, float time) { var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; var baseColor = ColorId.InGameHighlight.Value(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 03f276ea..80b1a5d5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -483,7 +483,7 @@ public partial class ModEditWindow if (table) { ImGuiUtil.DrawTableColumn("Version"); - ImGuiUtil.DrawTableColumn(_lastFile.Version.ToString()); + ImGuiUtil.DrawTableColumn($"0x{_lastFile.Version:X}"); ImGuiUtil.DrawTableColumn("Radius"); ImGuiUtil.DrawTableColumn(_lastFile.Radius.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("Model Clip Out Distance"); From 624dd40d58bc3817c3fbd271564042c58ad72439 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Apr 2024 15:46:52 +0200 Subject: [PATCH 0558/1381] Handle writing. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 845d1f99..aff136e2 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 845d1f99a752f4d23288a316e42d4bfa32fa987f +Subproject commit aff136e2ff79990989cbe1c518a79b7b83e294a5 From 75cfffeba73e80f970d617e7d36622e709e444c3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Apr 2024 15:51:23 +0200 Subject: [PATCH 0559/1381] Oops. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index aff136e2..9208c9c2 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit aff136e2ff79990989cbe1c518a79b7b83e294a5 +Subproject commit 9208c9c242244beeb3c1fb826582d72da09831af From ceb3d39a9ac71373acc3e2d33623876488c872e8 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Apr 2024 01:22:03 +1000 Subject: [PATCH 0560/1381] Normalise _FFXIV_COLOR values Fixes xivdev/Penumbra#411 --- Penumbra/Import/Models/Export/VertexFragment.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index 08b2a214..7a82e994 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -12,7 +12,7 @@ and there's reason to overhaul the export pipeline. public struct VertexColorFfxiv : IVertexCustom { // NOTE: We only realistically require UNSIGNED_BYTE for this, however Blender 3.6 errors on that (fixed in 4.0). - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, false)] + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, true)] public Vector4 FfxivColor; public int MaxColors => 0; @@ -81,7 +81,7 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom [VertexAttribute("TEXCOORD_0")] public Vector2 TexCoord0; - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, false)] + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, true)] public Vector4 FfxivColor; public int MaxColors => 0; @@ -163,7 +163,7 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom [VertexAttribute("TEXCOORD_1")] public Vector2 TexCoord1; - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, false)] + [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, true)] public Vector4 FfxivColor; public int MaxColors => 0; From 8fc7de64d9d23c9874861567dd6ada6a0f246d57 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Apr 2024 17:55:28 +0200 Subject: [PATCH 0561/1381] Start group rework. --- Penumbra/Collections/Cache/CollectionCache.cs | 50 +++++-------------- .../Collections/Cache/CollectionModData.cs | 10 ++-- Penumbra/Mods/Editor/IMod.cs | 14 +++++- Penumbra/Mods/Mod.cs | 19 +++++++ Penumbra/Mods/Subclasses/IModGroup.cs | 4 ++ Penumbra/Mods/Subclasses/ISubMod.cs | 10 ++++ Penumbra/Mods/Subclasses/MultiModGroup.cs | 11 ++++ Penumbra/Mods/Subclasses/SingleModGroup.cs | 5 ++ Penumbra/Mods/TemporaryMod.cs | 28 ++++++++++- 9 files changed, 106 insertions(+), 45 deletions(-) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index e1b32204..ded1dc73 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -2,12 +2,10 @@ using OtterGui; using OtterGui.Classes; using Penumbra.Meta.Manipulations; using Penumbra.Mods; -using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; namespace Penumbra.Collections.Cache; @@ -231,37 +229,12 @@ public sealed class CollectionCache : IDisposable /// Add all files and possibly manipulations of a given mod according to its settings in this collection. internal void AddModSync(IMod mod, bool addMetaChanges) { - if (mod.Index >= 0) - { - var settings = _collection[mod.Index].Settings; - if (settings is not { Enabled: true }) - return; + var files = GetFiles(mod); + foreach (var (path, file) in files.FileRedirections) + AddFile(path, file, mod); - foreach (var (group, groupIndex) in mod.Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) - { - if (group.Count == 0) - continue; - - var config = settings.Settings[groupIndex]; - switch (group) - { - case SingleModGroup single: - AddSubMod(single[config.AsIndex], mod); - break; - case MultiModGroup multi: - { - foreach (var (option, _) in multi.WithIndex() - .Where(p => config.HasFlag(p.Index)) - .OrderByDescending(p => group.OptionPriority(p.Index))) - AddSubMod(option, mod); - - break; - } - } - } - } - - AddSubMod(mod.Default, mod); + foreach (var manip in files.Manipulations) + AddManipulation(manip, mod); if (addMetaChanges) { @@ -273,14 +246,15 @@ public sealed class CollectionCache : IDisposable } } - // Add all files and possibly manipulations of a specific submod - private void AddSubMod(ISubMod subMod, IMod parentMod) + private AppliedModData GetFiles(IMod mod) { - foreach (var (path, file) in subMod.Files.Concat(subMod.FileSwaps)) - AddFile(path, file, parentMod); + if (mod.Index < 0) + return mod.GetData(); - foreach (var manip in subMod.Manipulations) - AddManipulation(manip, parentMod); + var settings = _collection[mod.Index].Settings; + return settings is not { Enabled: true } + ? AppliedModData.Empty + : mod.GetData(settings); } /// Invoke only if not in a full recalculation. diff --git a/Penumbra/Collections/Cache/CollectionModData.cs b/Penumbra/Collections/Cache/CollectionModData.cs index 3a3afad2..d0a3bc76 100644 --- a/Penumbra/Collections/Cache/CollectionModData.cs +++ b/Penumbra/Collections/Cache/CollectionModData.cs @@ -1,10 +1,12 @@ using Penumbra.Meta.Manipulations; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; +/// +/// Contains associations between a mod and the paths and meta manipulations affected by that mod. +/// public class CollectionModData { private readonly Dictionary, HashSet)> _data = new(); @@ -17,7 +19,7 @@ public class CollectionModData if (_data.Remove(mod, out var data)) return data; - return (Array.Empty(), Array.Empty()); + return ([], []); } public void AddPath(IMod mod, Utf8GamePath path) @@ -28,7 +30,7 @@ public class CollectionModData } else { - data = (new HashSet { path }, new HashSet()); + data = ([path], []); _data.Add(mod, data); } } @@ -41,7 +43,7 @@ public class CollectionModData } else { - data = (new HashSet(), new HashSet { manipulation }); + data = ([], [manipulation]); _data.Add(mod, data); } } diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index d3bc19b0..8b5b65e1 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -1,15 +1,27 @@ using OtterGui.Classes; +using Penumbra.Meta.Manipulations; using Penumbra.Mods.Subclasses; +using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; +public record struct AppliedModData( + IReadOnlyCollection> FileRedirections, + IReadOnlyCollection Manipulations) +{ + public static readonly AppliedModData Empty = new([], []); +} + public interface IMod { LowerString Name { get; } - public int Index { get; } + public int Index { get; } public ModPriority Priority { get; } + public AppliedModData GetData(ModSettings? settings = null); + + public ISubMod Default { get; } public IReadOnlyList Groups { get; } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index b7d1186d..3c996c8f 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,5 +1,7 @@ using OtterGui; using OtterGui.Classes; +using Penumbra.Collections.Cache; +using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; @@ -59,6 +61,23 @@ public sealed class Mod : IMod public readonly SubMod Default; public readonly List Groups = []; + public AppliedModData GetData(ModSettings? settings = null) + { + if (settings is not { Enabled: true }) + return AppliedModData.Empty; + + var dictRedirections = new Dictionary(TotalFileCount); + var setManips = new HashSet(TotalManipulations); + foreach (var (group, groupIndex) in Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) + { + var config = settings.Settings[groupIndex]; + group.AddData(config, dictRedirections, setManips); + } + + ((ISubMod)Default).AddData(dictRedirections, setManips); + return new AppliedModData(dictRedirections, setManips); + } + ISubMod IMod.Default => Default; diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 2daf31e6..57ef4e98 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -1,6 +1,8 @@ using Newtonsoft.Json; using Penumbra.Api.Enums; +using Penumbra.Meta.Manipulations; using Penumbra.Services; +using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; @@ -24,6 +26,8 @@ public interface IModGroup : IReadOnlyCollection public bool MoveOption(int optionIdxFrom, int optionIdxTo); public void UpdatePositions(int from = 0); + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); + /// Ensure that a value is valid for a group. public Setting FixSetting(Setting setting); } diff --git a/Penumbra/Mods/Subclasses/ISubMod.cs b/Penumbra/Mods/Subclasses/ISubMod.cs index 29323c1d..e997e07d 100644 --- a/Penumbra/Mods/Subclasses/ISubMod.cs +++ b/Penumbra/Mods/Subclasses/ISubMod.cs @@ -14,6 +14,16 @@ public interface ISubMod public IReadOnlyDictionary FileSwaps { get; } public IReadOnlySet Manipulations { get; } + public void AddData(Dictionary redirections, HashSet manipulations) + { + foreach (var (path, file) in Files) + redirections.TryAdd(path, file); + + foreach (var (path, file) in FileSwaps) + redirections.TryAdd(path, file); + manipulations.UnionWith(Manipulations); + } + public bool IsDefault { get; } public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, ISubMod mod, DirectoryInfo basePath, ModPriority? priority) diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 7479cd54..266d3037 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -5,6 +5,8 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; +using Penumbra.Meta.Manipulations; +using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; @@ -110,6 +112,15 @@ public sealed class MultiModGroup : IModGroup o.SetPosition(o.GroupIdx, i); } + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + { + foreach (var (option, index) in PrioritizedOptions.WithIndex().OrderByDescending(o => o.Value.Priority)) + { + if (setting.HasFlag(index)) + ((ISubMod)option.Mod).AddData(redirections, manipulations); + } + } + public Setting FixSetting(Setting setting) => new(setting.Value & ((1ul << Count) - 1)); } diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index 74769c7e..f797a709 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -3,6 +3,8 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; +using Penumbra.Meta.Manipulations; +using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; @@ -114,6 +116,9 @@ public sealed class SingleModGroup : IModGroup o.SetPosition(o.GroupIdx, i); } + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + => this[setting.AsIndex].AddData(redirections, manipulations); + public Setting FixSetting(Setting setting) => Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(Count - 1))); } diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 6be07881..8f27e201 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -20,6 +20,28 @@ public class TemporaryMod : IMod public readonly SubMod Default; + public AppliedModData GetData(ModSettings? settings = null) + { + Dictionary dict; + if (Default.FileSwapData.Count == 0) + { + dict = Default.FileData; + } + else if (Default.FileData.Count == 0) + { + dict = Default.FileSwapData; + } + else + { + // Need to ensure uniqueness. + dict = new Dictionary(Default.FileData.Count + Default.FileSwaps.Count); + foreach (var (gamePath, file) in Default.FileData.Concat(Default.FileSwaps)) + dict.TryAdd(gamePath, file); + } + + return new AppliedModData(dict, Default.Manipulations); + } + ISubMod IMod.Default => Default; @@ -53,7 +75,8 @@ public class TemporaryMod : IMod dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Name, config.ReplaceNonAsciiOnImport, true); var fileDir = Directory.CreateDirectory(Path.Combine(dir.FullName, "files")); modManager.DataEditor.CreateMeta(dir, collection.Name, character ?? config.DefaultModAuthor, - $"Mod generated from temporary collection {collection.Id} for {character ?? "Unknown Character"} with name {collection.Name}.", null, null); + $"Mod generated from temporary collection {collection.Id} for {character ?? "Unknown Character"} with name {collection.Name}.", + null, null); var mod = new Mod(dir); var defaultMod = mod.Default; foreach (var (gamePath, fullPath) in collection.ResolvedFiles) @@ -86,7 +109,8 @@ public class TemporaryMod : IMod saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir); - Penumbra.Log.Information($"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identifier}."); + Penumbra.Log.Information( + $"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identifier}."); } catch (Exception e) { From 9f4c6767f822be23632b39e3ab73792d19290ec3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Apr 2024 18:28:25 +0200 Subject: [PATCH 0562/1381] Remove ISubMod. --- Penumbra/Import/TexToolsImporter.ModPack.cs | 2 +- Penumbra/Mods/Editor/DuplicateManager.cs | 7 +- Penumbra/Mods/Editor/FileRegistry.cs | 2 +- Penumbra/Mods/Editor/IMod.cs | 12 ++-- Penumbra/Mods/Editor/ModEditor.cs | 4 +- Penumbra/Mods/Editor/ModFileCollection.cs | 14 ++-- Penumbra/Mods/Editor/ModFileEditor.cs | 16 ++--- Penumbra/Mods/Editor/ModMerger.cs | 2 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 +- Penumbra/Mods/Editor/ModSwapEditor.cs | 2 +- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 15 ++--- Penumbra/Mods/Manager/ModOptionEditor.cs | 15 ++--- Penumbra/Mods/Mod.cs | 13 ++-- Penumbra/Mods/ModCreator.cs | 8 +-- Penumbra/Mods/Subclasses/IModGroup.cs | 12 ++-- Penumbra/Mods/Subclasses/ISubMod.cs | 67 ------------------- Penumbra/Mods/Subclasses/ModSettings.cs | 35 +--------- Penumbra/Mods/Subclasses/MultiModGroup.cs | 6 +- Penumbra/Mods/Subclasses/SingleModGroup.cs | 4 +- Penumbra/Mods/Subclasses/SubMod.cs | 58 ++++++++++++++-- Penumbra/Mods/TemporaryMod.cs | 5 +- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 4 +- .../ModEditWindow.QuickImport.cs | 2 +- 23 files changed, 123 insertions(+), 184 deletions(-) delete mode 100644 Penumbra/Mods/Subclasses/ISubMod.cs diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 099b133c..f4b7d47e 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -152,7 +152,7 @@ public partial class TexToolsImporter } // Iterate through all pages - var options = new List(); + var options = new List(); var groupPriority = ModPriority.Default; var groupNames = new HashSet(); foreach (var page in modList.ModPackPages) diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index c8530936..938199aa 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -29,7 +29,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co Worker = Task.Run(() => CheckDuplicates(filesTmp, _cancellationTokenSource.Token), _cancellationTokenSource.Token); } - public void DeleteDuplicates(ModFileCollection files, Mod mod, ISubMod option, bool useModManager) + public void DeleteDuplicates(ModFileCollection files, Mod mod, SubMod option, bool useModManager) { if (!Worker.IsCompleted || _duplicates.Count == 0) return; @@ -72,7 +72,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co return; - void HandleSubMod(ISubMod subMod, int groupIdx, int optionIdx) + void HandleSubMod(SubMod subMod, int groupIdx, int optionIdx) { var changes = false; var dict = subMod.Files.ToDictionary(kvp => kvp.Key, @@ -86,8 +86,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co } else { - var sub = (SubMod)subMod; - sub.FileData = dict; + subMod.FileData = dict; saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); } } diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 96d027b3..427c58ca 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -5,7 +5,7 @@ namespace Penumbra.Mods.Editor; public class FileRegistry : IEquatable { - public readonly List<(ISubMod, Utf8GamePath)> SubModUsage = []; + public readonly List<(SubMod, Utf8GamePath)> SubModUsage = []; public FullPath File { get; private init; } public Utf8RelPath RelPath { get; private init; } public long FileSize { get; private init; } diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index 8b5b65e1..c4c4be2f 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -6,8 +6,8 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; public record struct AppliedModData( - IReadOnlyCollection> FileRedirections, - IReadOnlyCollection Manipulations) + Dictionary FileRedirections, + HashSet Manipulations) { public static readonly AppliedModData Empty = new([], []); } @@ -19,14 +19,10 @@ public interface IMod public int Index { get; } public ModPriority Priority { get; } + public IReadOnlyList Groups { get; } + public AppliedModData GetData(ModSettings? settings = null); - - public ISubMod Default { get; } - public IReadOnlyList Groups { get; } - - public IEnumerable AllSubMods { get; } - // Cache public int TotalManipulations { get; } } diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index b22aea17..d9781c06 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -29,7 +29,7 @@ public class ModEditor( public int OptionIdx { get; private set; } public IModGroup? Group { get; private set; } - public ISubMod? Option { get; private set; } + public SubMod? Option { get; private set; } public void LoadMod(Mod mod) => LoadMod(mod, -1, 0); @@ -104,7 +104,7 @@ public class ModEditor( => Clear(); /// Apply a option action to all available option in a mod, including the default option. - public static void ApplyToAllOptions(Mod mod, Action action) + public static void ApplyToAllOptions(Mod mod, Action action) { action(mod.Default, -1, 0); foreach (var (group, groupIdx) in mod.Groups.WithIndex()) diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 2f8bdfb1..9dd78217 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -38,13 +38,13 @@ public class ModFileCollection : IDisposable public bool Ready { get; private set; } = true; - public void UpdateAll(Mod mod, ISubMod option) + public void UpdateAll(Mod mod, SubMod option) { UpdateFiles(mod, new CancellationToken()); UpdatePaths(mod, option, false, new CancellationToken()); } - public void UpdatePaths(Mod mod, ISubMod option) + public void UpdatePaths(Mod mod, SubMod option) => UpdatePaths(mod, option, true, new CancellationToken()); public void Clear() @@ -59,7 +59,7 @@ public class ModFileCollection : IDisposable public void ClearMissingFiles() => _missing.Clear(); - public void RemoveUsedPath(ISubMod option, FileRegistry? file, Utf8GamePath gamePath) + public void RemoveUsedPath(SubMod option, FileRegistry? file, Utf8GamePath gamePath) { _usedPaths.Remove(gamePath); if (file != null) @@ -69,10 +69,10 @@ public class ModFileCollection : IDisposable } } - public void RemoveUsedPath(ISubMod option, FullPath file, Utf8GamePath gamePath) + public void RemoveUsedPath(SubMod option, FullPath file, Utf8GamePath gamePath) => RemoveUsedPath(option, _available.FirstOrDefault(f => f.File.Equals(file)), gamePath); - public void AddUsedPath(ISubMod option, FileRegistry? file, Utf8GamePath gamePath) + public void AddUsedPath(SubMod option, FileRegistry? file, Utf8GamePath gamePath) { _usedPaths.Add(gamePath); if (file == null) @@ -82,7 +82,7 @@ public class ModFileCollection : IDisposable file.SubModUsage.Add((option, gamePath)); } - public void AddUsedPath(ISubMod option, FullPath file, Utf8GamePath gamePath) + public void AddUsedPath(SubMod option, FullPath file, Utf8GamePath gamePath) => AddUsedPath(option, _available.FirstOrDefault(f => f.File.Equals(file)), gamePath); public void ChangeUsedPath(FileRegistry file, int pathIdx, Utf8GamePath gamePath) @@ -154,7 +154,7 @@ public class ModFileCollection : IDisposable _usedPaths.Clear(); } - private void UpdatePaths(Mod mod, ISubMod option, bool clearRegistries, CancellationToken tok) + private void UpdatePaths(Mod mod, SubMod option, bool clearRegistries, CancellationToken tok) { tok.ThrowIfCancellationRequested(); ClearPaths(clearRegistries, tok); diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 30e97093..4bdf4b1b 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -30,16 +30,16 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu return num; } - public void Revert(Mod mod, ISubMod option) + public void Revert(Mod mod, SubMod option) { files.UpdateAll(mod, option); Changes = false; } /// Remove all path redirections where the pointed-to file does not exist. - public void RemoveMissingPaths(Mod mod, ISubMod option) + public void RemoveMissingPaths(Mod mod, SubMod option) { - void HandleSubMod(ISubMod subMod, int groupIdx, int optionIdx) + void HandleSubMod(SubMod subMod, int groupIdx, int optionIdx) { var newDict = subMod.Files.Where(kvp => CheckAgainstMissing(mod, subMod, kvp.Value, kvp.Key, subMod == option)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); @@ -61,7 +61,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu /// If path is empty, it will be deleted instead. /// If pathIdx is equal to the total number of paths, path will be added, otherwise replaced. /// - public bool SetGamePath(ISubMod option, int fileIdx, int pathIdx, Utf8GamePath path) + public bool SetGamePath(SubMod option, int fileIdx, int pathIdx, Utf8GamePath path) { if (!CanAddGamePath(path) || fileIdx < 0 || fileIdx > files.Available.Count) return false; @@ -84,7 +84,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu /// Transform a set of files to the appropriate game paths with the given number of folders skipped, /// and add them to the given option. /// - public int AddPathsToSelected(ISubMod option, IEnumerable files1, int skipFolders = 0) + public int AddPathsToSelected(SubMod option, IEnumerable files1, int skipFolders = 0) { var failed = 0; foreach (var file in files1) @@ -111,7 +111,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu } /// Remove all paths in the current option from the given files. - public void RemovePathsFromSelected(ISubMod option, IEnumerable files1) + public void RemovePathsFromSelected(SubMod option, IEnumerable files1) { foreach (var file in files1) { @@ -129,7 +129,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu } /// Delete all given files from your filesystem - public void DeleteFiles(Mod mod, ISubMod option, IEnumerable files1) + public void DeleteFiles(Mod mod, SubMod option, IEnumerable files1) { var deletions = 0; foreach (var file in files1) @@ -155,7 +155,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu } - private bool CheckAgainstMissing(Mod mod, ISubMod option, FullPath file, Utf8GamePath key, bool removeUsed) + private bool CheckAgainstMissing(Mod mod, SubMod option, FullPath file, Utf8GamePath key, bool removeUsed) { if (!files.Missing.Contains(file)) return true; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 842b1bb3..25590c49 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -151,7 +151,7 @@ public class ModMerger : IDisposable MergeIntoOption(MergeFromMod!.AllSubMods.Reverse(), option, true); } - private void MergeIntoOption(IEnumerable mergeOptions, SubMod option, bool fromFileToFile) + private void MergeIntoOption(IEnumerable mergeOptions, SubMod option, bool fromFileToFile) { var redirections = option.FileData.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); var swaps = option.FileSwapData.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 31aefdf5..a6218c6f 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -103,7 +103,7 @@ public class ModMetaEditor(ModManager modManager) Changes = true; } - public void Load(Mod mod, ISubMod currentOption) + public void Load(Mod mod, SubMod currentOption) { OtherImcCount = 0; OtherEqpCount = 0; diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index ada06264..0d5f05a9 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -11,7 +11,7 @@ public class ModSwapEditor(ModManager modManager) public IReadOnlyDictionary Swaps => _swaps; - public void Revert(ISubMod option) + public void Revert(SubMod option) { _swaps.SetTo(option.FileSwaps); Changes = false; diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index e229738d..21b9ef2c 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -5,6 +5,7 @@ using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; using Penumbra.Meta; +using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.Subclasses; @@ -15,14 +16,13 @@ public class ItemSwapContainer private readonly MetaFileManager _manager; private readonly ObjectIdentification _identifier; - private Dictionary _modRedirections = []; - private HashSet _modManipulations = []; + private AppliedModData _appliedModData = AppliedModData.Empty; public IReadOnlyDictionary ModRedirections - => _modRedirections; + => _appliedModData.FileRedirections; public IReadOnlySet ModManipulations - => _modManipulations; + => _appliedModData.Manipulations; public readonly List Swaps = []; @@ -97,12 +97,11 @@ public class ItemSwapContainer Clear(); if (mod == null || mod.Index < 0) { - _modRedirections = []; - _modManipulations = []; + _appliedModData = AppliedModData.Empty; } else { - (_modRedirections, _modManipulations) = ModSettings.GetResolveData(mod, settings); + _appliedModData = ModSettings.GetResolveData(mod, settings); } } @@ -120,7 +119,7 @@ public class ItemSwapContainer private Func MetaResolver(ModCollection? collection) { - var set = collection?.MetaCache?.Manipulations.ToHashSet() ?? _modManipulations; + var set = collection?.MetaCache?.Manipulations.ToHashSet() ?? _appliedModData.Manipulations; return m => set.TryGetValue(m, out var a) ? a : m; } diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 9efb8a3f..07c6f38e 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -262,15 +262,12 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Add an existing option to a given group with default priority. - public void AddOption(Mod mod, int groupIdx, ISubMod option) + public void AddOption(Mod mod, int groupIdx, SubMod option) => AddOption(mod, groupIdx, option, ModPriority.Default); /// Add an existing option to a given group with a given priority. - public void AddOption(Mod mod, int groupIdx, ISubMod option, ModPriority priority) + public void AddOption(Mod mod, int groupIdx, SubMod option, ModPriority priority) { - if (option is not SubMod o) - return; - var group = mod.Groups[groupIdx]; switch (group) { @@ -280,12 +277,12 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); return; case SingleModGroup s: - o.SetPosition(groupIdx, s.Count); - s.OptionData.Add(o); + option.SetPosition(groupIdx, s.Count); + s.OptionData.Add(option); break; case MultiModGroup m: - o.SetPosition(groupIdx, m.Count); - m.PrioritizedOptions.Add((o, priority)); + option.SetPosition(groupIdx, m.Count); + m.PrioritizedOptions.Add((option, priority)); break; } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 3c996c8f..25f3c510 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -32,6 +32,9 @@ public sealed class Mod : IMod public ModPriority Priority => ModPriority.Default; + IReadOnlyList IMod.Groups + => Groups; + internal Mod(DirectoryInfo modPath) { ModPath = modPath; @@ -74,18 +77,12 @@ public sealed class Mod : IMod group.AddData(config, dictRedirections, setManips); } - ((ISubMod)Default).AddData(dictRedirections, setManips); + Default.AddData(dictRedirections, setManips); return new AppliedModData(dictRedirections, setManips); } - ISubMod IMod.Default - => Default; - - IReadOnlyList IMod.Groups - => Groups; - public IEnumerable AllSubMods - => Groups.SelectMany(o => o).OfType().Prepend(Default); + => Groups.SelectMany(o => o).Prepend(Default); public List FindUnusedFiles() { diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 2bcdd3b1..661dd6fb 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -235,7 +235,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, /// Create a file for an option group from given data. public void CreateOptionGroup(DirectoryInfo baseFolder, GroupType type, string name, - ModPriority priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) + ModPriority priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) { switch (type) { @@ -248,7 +248,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, Priority = priority, DefaultSettings = defaultSettings, }; - group.PrioritizedOptions.AddRange(subMods.OfType().Select((s, idx) => (s, new ModPriority(idx)))); + group.PrioritizedOptions.AddRange(subMods.Select((s, idx) => (s, new ModPriority(idx)))); _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } @@ -269,7 +269,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, } /// Create the data for a given sub mod from its data and the folder it is based on. - public ISubMod CreateSubMod(DirectoryInfo baseFolder, DirectoryInfo optionFolder, OptionList option) + public SubMod CreateSubMod(DirectoryInfo baseFolder, DirectoryInfo optionFolder, OptionList option) { var list = optionFolder.EnumerateNonHiddenFiles() .Select(f => (Utf8GamePath.FromFile(f, optionFolder, out var gamePath, true), gamePath, new FullPath(f))) @@ -288,7 +288,7 @@ public partial class ModCreator(SaveService _saveService, Configuration config, } /// Create an empty sub mod for single groups with None options. - internal static ISubMod CreateEmptySubMod(string name) + internal static SubMod CreateEmptySubMod(string name) => new SubMod(null!) // Mod is irrelevant here, only used for saving. { Name = name, diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 57ef4e98..3f363542 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -6,7 +6,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; -public interface IModGroup : IReadOnlyCollection +public interface IModGroup : IReadOnlyCollection { public const int MaxMultiOptions = 63; @@ -18,7 +18,7 @@ public interface IModGroup : IReadOnlyCollection public ModPriority OptionPriority(Index optionIdx); - public ISubMod this[Index idx] { get; } + public SubMod this[Index idx] { get; } public bool IsOption { get; } @@ -37,7 +37,7 @@ public readonly struct ModSaveGroup : ISavable private readonly DirectoryInfo _basePath; private readonly IModGroup? _group; private readonly int _groupIdx; - private readonly ISubMod? _defaultMod; + private readonly SubMod? _defaultMod; private readonly bool _onlyAscii; public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) @@ -59,7 +59,7 @@ public readonly struct ModSaveGroup : ISavable _onlyAscii = onlyAscii; } - public ModSaveGroup(DirectoryInfo basePath, ISubMod @default, bool onlyAscii) + public ModSaveGroup(DirectoryInfo basePath, SubMod @default, bool onlyAscii) { _basePath = basePath; _groupIdx = -1; @@ -91,7 +91,7 @@ public readonly struct ModSaveGroup : ISavable j.WriteStartArray(); for (var idx = 0; idx < _group.Count; ++idx) { - ISubMod.WriteSubMod(j, serializer, _group[idx], _basePath, _group.Type switch + SubMod.WriteSubMod(j, serializer, _group[idx], _basePath, _group.Type switch { GroupType.Multi => _group.OptionPriority(idx), _ => null, @@ -103,7 +103,7 @@ public readonly struct ModSaveGroup : ISavable } else { - ISubMod.WriteSubMod(j, serializer, _defaultMod!, _basePath, null); + SubMod.WriteSubMod(j, serializer, _defaultMod!, _basePath, null); } } } diff --git a/Penumbra/Mods/Subclasses/ISubMod.cs b/Penumbra/Mods/Subclasses/ISubMod.cs deleted file mode 100644 index e997e07d..00000000 --- a/Penumbra/Mods/Subclasses/ISubMod.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Newtonsoft.Json; -using Penumbra.Meta.Manipulations; -using Penumbra.String.Classes; - -namespace Penumbra.Mods.Subclasses; - -public interface ISubMod -{ - public string Name { get; } - public string FullName { get; } - public string Description { get; } - - public IReadOnlyDictionary Files { get; } - public IReadOnlyDictionary FileSwaps { get; } - public IReadOnlySet Manipulations { get; } - - public void AddData(Dictionary redirections, HashSet manipulations) - { - foreach (var (path, file) in Files) - redirections.TryAdd(path, file); - - foreach (var (path, file) in FileSwaps) - redirections.TryAdd(path, file); - manipulations.UnionWith(Manipulations); - } - - public bool IsDefault { get; } - - public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, ISubMod mod, DirectoryInfo basePath, ModPriority? priority) - { - j.WriteStartObject(); - j.WritePropertyName(nameof(Name)); - j.WriteValue(mod.Name); - j.WritePropertyName(nameof(Description)); - j.WriteValue(mod.Description); - if (priority != null) - { - j.WritePropertyName(nameof(IModGroup.Priority)); - j.WriteValue(priority.Value.Value); - } - - j.WritePropertyName(nameof(mod.Files)); - j.WriteStartObject(); - foreach (var (gamePath, file) in mod.Files) - { - if (file.ToRelPath(basePath, out var relPath)) - { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(relPath.ToString()); - } - } - - j.WriteEndObject(); - j.WritePropertyName(nameof(mod.FileSwaps)); - j.WriteStartObject(); - foreach (var (gamePath, file) in mod.FileSwaps) - { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(file.ToString()); - } - - j.WriteEndObject(); - j.WritePropertyName(nameof(mod.Manipulations)); - serializer.Serialize(j, mod.Manipulations); - j.WriteEndObject(); - } -} diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index 380b242c..81a3bb41 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -2,6 +2,7 @@ using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.String.Classes; @@ -34,44 +35,14 @@ public class ModSettings }; // Return everything required to resolve things for a single mod with given settings (which can be null, in which case the default is used. - public static (Dictionary, HashSet) GetResolveData(Mod mod, ModSettings? settings) + public static AppliedModData GetResolveData(Mod mod, ModSettings? settings) { if (settings == null) settings = DefaultSettings(mod); else settings.Settings.FixSize(mod); - var dict = new Dictionary(); - var set = new HashSet(); - - foreach (var (group, index) in mod.Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) - { - if (group.Type is GroupType.Single) - { - if (group.Count > 0) - AddOption(group[settings.Settings[index].AsIndex]); - } - else - { - foreach (var (option, optionIdx) in group.WithIndex().OrderByDescending(o => group.OptionPriority(o.Index))) - { - if (settings.Settings[index].HasFlag(optionIdx)) - AddOption(option); - } - } - } - - AddOption(mod.Default); - return (dict, set); - - void AddOption(ISubMod option) - { - foreach (var (path, file) in option.Files.Concat(option.FileSwaps)) - dict.TryAdd(path, file); - - foreach (var manip in option.Manipulations) - set.Add(manip); - } + return mod.GetData(settings); } // Automatically react to changes in a mods available options. diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 266d3037..1600072e 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -24,7 +24,7 @@ public sealed class MultiModGroup : IModGroup public ModPriority OptionPriority(Index idx) => PrioritizedOptions[idx].Priority; - public ISubMod this[Index idx] + public SubMod this[Index idx] => PrioritizedOptions[idx].Mod; public bool IsOption @@ -36,7 +36,7 @@ public sealed class MultiModGroup : IModGroup public readonly List<(SubMod Mod, ModPriority Priority)> PrioritizedOptions = []; - public IEnumerator GetEnumerator() + public IEnumerator GetEnumerator() => PrioritizedOptions.Select(o => o.Mod).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() @@ -117,7 +117,7 @@ public sealed class MultiModGroup : IModGroup foreach (var (option, index) in PrioritizedOptions.WithIndex().OrderByDescending(o => o.Value.Priority)) { if (setting.HasFlag(index)) - ((ISubMod)option.Mod).AddData(redirections, manipulations); + option.Mod.AddData(redirections, manipulations); } } diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index f797a709..2d49fd1f 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -24,7 +24,7 @@ public sealed class SingleModGroup : IModGroup public ModPriority OptionPriority(Index _) => Priority; - public ISubMod this[Index idx] + public SubMod this[Index idx] => OptionData[idx]; public bool IsOption @@ -34,7 +34,7 @@ public sealed class SingleModGroup : IModGroup public int Count => OptionData.Count; - public IEnumerator GetEnumerator() + public IEnumerator GetEnumerator() => OptionData.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs index 4f35cd33..386910e5 100644 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; @@ -15,7 +16,7 @@ namespace Penumbra.Mods.Subclasses; /// Nothing is checked for existence or validity when loading. /// Objects are also not checked for uniqueness, the first appearance of a game path or meta path decides. /// -public sealed class SubMod : ISubMod +public sealed class SubMod { public string Name { get; set; } = "Default"; @@ -29,7 +30,17 @@ public sealed class SubMod : ISubMod internal int OptionIdx { get; private set; } public bool IsDefault - => GroupIdx < 0; + => GroupIdx < 0; + + public void AddData(Dictionary redirections, HashSet manipulations) + { + foreach (var (path, file) in Files) + redirections.TryAdd(path, file); + + foreach (var (path, file) in FileSwaps) + redirections.TryAdd(path, file); + manipulations.UnionWith(Manipulations); + } public Dictionary FileData = []; public Dictionary FileSwapData = []; @@ -60,8 +71,8 @@ public sealed class SubMod : ISubMod ManipulationData.Clear(); // Every option has a name, but priorities are only relevant for multi group options. - Name = json[nameof(ISubMod.Name)]?.ToObject() ?? string.Empty; - Description = json[nameof(ISubMod.Description)]?.ToObject() ?? string.Empty; + Name = json[nameof(Name)]?.ToObject() ?? string.Empty; + Description = json[nameof(Description)]?.ToObject() ?? string.Empty; priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; var files = (JObject?)json[nameof(Files)]; @@ -104,4 +115,43 @@ public sealed class SubMod : ISubMod } } } + + public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, SubMod mod, DirectoryInfo basePath, ModPriority? priority) + { + j.WriteStartObject(); + j.WritePropertyName(nameof(Name)); + j.WriteValue(mod.Name); + j.WritePropertyName(nameof(Description)); + j.WriteValue(mod.Description); + if (priority != null) + { + j.WritePropertyName(nameof(IModGroup.Priority)); + j.WriteValue(priority.Value.Value); + } + + j.WritePropertyName(nameof(mod.Files)); + j.WriteStartObject(); + foreach (var (gamePath, file) in mod.Files) + { + if (file.ToRelPath(basePath, out var relPath)) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(relPath.ToString()); + } + } + + j.WriteEndObject(); + j.WritePropertyName(nameof(mod.FileSwaps)); + j.WriteStartObject(); + foreach (var (gamePath, file) in mod.FileSwaps) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(file.ToString()); + } + + j.WriteEndObject(); + j.WritePropertyName(nameof(mod.Manipulations)); + serializer.Serialize(j, mod.Manipulations); + j.WriteEndObject(); + } } diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 8f27e201..41c1211f 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -39,12 +39,9 @@ public class TemporaryMod : IMod dict.TryAdd(gamePath, file); } - return new AppliedModData(dict, Default.Manipulations); + return new AppliedModData(dict, Default.ManipulationData); } - ISubMod IMod.Default - => Default; - public IReadOnlyList Groups => Array.Empty(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index c8db7770..f765b47e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -192,7 +192,7 @@ public partial class ModEditWindow ImGuiUtil.RightAlign(rightText); } - private void PrintGamePath(int i, int j, FileRegistry registry, ISubMod subMod, Utf8GamePath gamePath) + private void PrintGamePath(int i, int j, FileRegistry registry, SubMod subMod, Utf8GamePath gamePath) { using var id = ImRaii.PushId(j); ImGui.TableNextColumn(); @@ -228,7 +228,7 @@ public partial class ModEditWindow } } - private void PrintNewGamePath(int i, FileRegistry registry, ISubMod subMod) + private void PrintNewGamePath(int i, FileRegistry registry, SubMod subMod) { var tmp = _fileIdx == i && _pathIdx == -1 ? _gamePathEdit : string.Empty; var pos = ImGui.GetCursorPosX() - ImGui.GetFrameHeight(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 10956deb..4ecacece 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -227,7 +227,7 @@ public partial class ModEditWindow return fileRegistry; } - private static (DirectoryInfo, int) GetPreferredPath(Mod mod, ISubMod subMod, bool replaceNonAscii) + private static (DirectoryInfo, int) GetPreferredPath(Mod mod, SubMod subMod, bool replaceNonAscii) { var path = mod.ModPath; var subDirs = 0; From 2d5afde61274f3602f15252eb64efbcb899c5cae Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Apr 2024 11:02:30 +0200 Subject: [PATCH 0563/1381] Fix group priority writing. --- Penumbra/Mods/Subclasses/IModGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 3f363542..7554f6dc 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -82,7 +82,7 @@ public readonly struct ModSaveGroup : ISavable j.WritePropertyName(nameof(_group.Description)); j.WriteValue(_group.Description); j.WritePropertyName(nameof(_group.Priority)); - j.WriteValue(_group.Priority); + j.WriteValue(_group.Priority.Value); j.WritePropertyName(nameof(Type)); j.WriteValue(_group.Type.ToString()); j.WritePropertyName(nameof(_group.DefaultSettings)); From f86f29b44a4d3dc78929107a9c99538b0d314d6a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Apr 2024 11:03:50 +0200 Subject: [PATCH 0564/1381] Some fixes. --- Penumbra/Mods/Manager/ModOptionEditor.cs | 4 +-- Penumbra/Mods/Subclasses/IModGroup.cs | 33 ++++++++++++++---------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 07c6f38e..9d942574 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -158,10 +158,10 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS { var group = mod.Groups[groupIdx]; var option = group[optionIdx]; - if (option.Description == newDescription || option is not SubMod s) + if (option.Description == newDescription) return; - s.Description = newDescription; + option.Description = newDescription; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 7554f6dc..38f070b3 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -72,8 +72,9 @@ public readonly struct ModSaveGroup : ISavable public void Save(StreamWriter writer) { - using var j = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; - var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + using var j = new JsonTextWriter(writer); + j.Formatting = Formatting.Indented; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; if (_groupIdx >= 0) { j.WriteStartObject(); @@ -87,19 +88,25 @@ public readonly struct ModSaveGroup : ISavable j.WriteValue(_group.Type.ToString()); j.WritePropertyName(nameof(_group.DefaultSettings)); j.WriteValue(_group.DefaultSettings.Value); - j.WritePropertyName("Options"); - j.WriteStartArray(); - for (var idx = 0; idx < _group.Count; ++idx) + switch (_group) { - SubMod.WriteSubMod(j, serializer, _group[idx], _basePath, _group.Type switch - { - GroupType.Multi => _group.OptionPriority(idx), - _ => null, - }); + case SingleModGroup single: + j.WritePropertyName("Options"); + j.WriteStartArray(); + foreach (var option in single.OptionData) + SubMod.WriteSubMod(j, serializer, option, _basePath, null); + j.WriteEndArray(); + j.WriteEndObject(); + break; + case MultiModGroup multi: + j.WritePropertyName("Options"); + j.WriteStartArray(); + foreach (var (option, priority) in multi.PrioritizedOptions) + SubMod.WriteSubMod(j, serializer, option, _basePath, priority); + j.WriteEndArray(); + j.WriteEndObject(); + break; } - - j.WriteEndArray(); - j.WriteEndObject(); } else { From b99a809eba50019fad9aa7e1b25ce73c5ebca6fa Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Apr 2024 11:26:12 +0200 Subject: [PATCH 0565/1381] Remove OptionPriority from general option groups. --- Penumbra/Mods/Subclasses/IModGroup.cs | 4 ++-- Penumbra/Mods/Subclasses/MultiModGroup.cs | 6 ++++-- Penumbra/Mods/Subclasses/SingleModGroup.cs | 6 ++++-- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 13 ++++++++----- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 10 +++++++--- 5 files changed, 25 insertions(+), 14 deletions(-) diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 38f070b3..96d7c6b7 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -16,7 +16,7 @@ public interface IModGroup : IReadOnlyCollection public ModPriority Priority { get; } public Setting DefaultSettings { get; set; } - public ModPriority OptionPriority(Index optionIdx); + public FullPath? FindBestMatch(Utf8GamePath gamePath); public SubMod this[Index idx] { get; } @@ -37,7 +37,7 @@ public readonly struct ModSaveGroup : ISavable private readonly DirectoryInfo _basePath; private readonly IModGroup? _group; private readonly int _groupIdx; - private readonly SubMod? _defaultMod; + private readonly SubMod? _defaultMod; private readonly bool _onlyAscii; public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 1600072e..02ae07f4 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -21,8 +21,10 @@ public sealed class MultiModGroup : IModGroup public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } - public ModPriority OptionPriority(Index idx) - => PrioritizedOptions[idx].Priority; + public FullPath? FindBestMatch(Utf8GamePath gamePath) + => PrioritizedOptions.OrderByDescending(o => o.Priority) + .SelectWhere(o => (o.Mod.FileData.TryGetValue(gamePath, out var file) || o.Mod.FileSwapData.TryGetValue(gamePath, out file), file)) + .FirstOrDefault(); public SubMod this[Index idx] => PrioritizedOptions[idx].Mod; diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index 2d49fd1f..b854d2b1 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -21,8 +21,10 @@ public sealed class SingleModGroup : IModGroup public readonly List OptionData = []; - public ModPriority OptionPriority(Index _) - => Priority; + public FullPath? FindBestMatch(Utf8GamePath gamePath) + => OptionData + .SelectWhere(m => (m.FileData.TryGetValue(gamePath, out var file) || m.FileSwapData.TryGetValue(gamePath, out file), file)) + .FirstOrDefault(); public SubMod this[Index idx] => OptionData[idx]; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 6cf24f62..a70da628 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -540,14 +540,17 @@ public partial class ModEditWindow : Window, IDisposable return currentFile.Value; if (Mod != null) - foreach (var option in Mod.Groups.OrderByDescending(g => g.Priority) - .SelectMany(g => g.WithIndex().OrderByDescending(o => g.OptionPriority(o.Index)).Select(g => g.Value)) - .Append(Mod.Default)) + { + foreach (var option in Mod.Groups.OrderByDescending(g => g.Priority)) { - if (option.Files.TryGetValue(path, out var value) || option.FileSwaps.TryGetValue(path, out value)) - return value; + if (option.FindBestMatch(path) is { } fullPath) + return fullPath; } + if (Mod.Default.Files.TryGetValue(path, out var value) || Mod.Default.FileSwaps.TryGetValue(path, out value)) + return value; + } + return new FullPath(path); } diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 80af7b15..b002dedd 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -532,10 +532,10 @@ public class ModPanelEditTab( panel._delayedActions.Enqueue(() => panel._modManager.OptionEditor.DeleteOption(panel._mod, groupIdx, optionIdx)); ImGui.TableNextColumn(); - if (group.Type != GroupType.Multi) + if (group is not MultiModGroup multi) return; - if (Input.Priority("##Priority", groupIdx, optionIdx, group.OptionPriority(optionIdx), out var priority, + if (Input.Priority("##Priority", groupIdx, optionIdx, multi.PrioritizedOptions[optionIdx].Priority, out var priority, 50 * UiHelpers.Scale)) panel._modManager.OptionEditor.ChangeOptionPriority(panel._mod, groupIdx, optionIdx, priority); @@ -613,7 +613,11 @@ public class ModPanelEditTab( var sourceGroup = panel._mod.Groups[sourceGroupIdx]; var currentCount = group.Count; var option = sourceGroup[sourceOption]; - var priority = sourceGroup.OptionPriority(_dragDropOptionIdx); + var priority = sourceGroup switch + { + MultiModGroup multi => multi.PrioritizedOptions[_dragDropOptionIdx].Priority, + _ => ModPriority.Default, + }; panel._delayedActions.Enqueue(() => { panel._modManager.OptionEditor.DeleteOption(panel._mod, sourceGroupIdx, sourceOption); From 4a6d94f0fb817810d14a9920130db7bada5ff47c Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Apr 2024 20:02:43 +1000 Subject: [PATCH 0566/1381] Avoid inclusion of zero-weighted bones in name mapping --- Penumbra/Import/Models/Import/MeshImporter.cs | 18 ++++++++++++++---- .../Import/Models/Import/VertexAttribute.cs | 19 +++++++++++-------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 1d4b223d..5d5df948 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -189,15 +189,25 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) foreach (var (primitive, primitiveIndex) in node.Mesh.Primitives.WithIndex()) { // Per glTF specification, an asset with a skin MUST contain skinning attributes on its meshes. - var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0") - ?? throw notifier.Exception($"Primitive {primitiveIndex} is skinned but does not contain skinning vertex attributes."); + var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0")?.AsVector4Array(); + var weightsAccessor = primitive.GetVertexAccessor("WEIGHTS_0")?.AsVector4Array(); + + if (jointsAccessor == null || weightsAccessor == null) + throw notifier.Exception($"Primitive {primitiveIndex} is skinned but does not contain skinning vertex attributes."); // Build a set of joints that are referenced by this mesh. - // TODO: Would be neat to omit 0-weighted joints here, but doing so will require some further work on bone mapping behavior to ensure the unweighted joints can still be resolved to valid bone indices during vertex data construction. - foreach (var joints in jointsAccessor.AsVector4Array()) + for (var i = 0; i < jointsAccessor.Count; i++) { + var joints = jointsAccessor[i]; + var weights = weightsAccessor[i]; for (var index = 0; index < 4; index++) + { + // If a joint has absolutely no weight, we omit the bone entirely. + if (weights[index] == 0) + continue; + usedJoints.Add((ushort)joints[index]); + } } } diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 3cfedd6f..b7f5dcf1 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -144,10 +144,10 @@ public class VertexAttribute public static VertexAttribute? BlendIndex(Accessors accessors, IDictionary? boneMap, IoNotifier notifier) { - if (!accessors.TryGetValue("JOINTS_0", out var accessor)) + if (!accessors.TryGetValue("JOINTS_0", out var jointsAccessor)) return null; - if (!accessors.ContainsKey("WEIGHTS_0")) + if (!accessors.TryGetValue("WEIGHTS_0", out var weightsAccessor)) throw notifier.Exception("Mesh contained JOINTS_0 attribute but no corresponding WEIGHTS_0 attribute."); if (boneMap == null) @@ -160,18 +160,21 @@ public class VertexAttribute Usage = (byte)MdlFile.VertexUsage.BlendIndices, }; - var values = accessor.AsVector4Array(); + var joints = jointsAccessor.AsVector4Array(); + var weights = weightsAccessor.AsVector4Array(); return new VertexAttribute( element, index => { - var gltfIndices = values[index]; + var gltfIndices = joints[index]; + var gltfWeights = weights[index]; + return BuildUByte4(new Vector4( - boneMap[(ushort)gltfIndices.X], - boneMap[(ushort)gltfIndices.Y], - boneMap[(ushort)gltfIndices.Z], - boneMap[(ushort)gltfIndices.W] + gltfWeights.X == 0 ? 0 : boneMap[(ushort)gltfIndices.X], + gltfWeights.Y == 0 ? 0 : boneMap[(ushort)gltfIndices.Y], + gltfWeights.Z == 0 ? 0 : boneMap[(ushort)gltfIndices.Z], + gltfWeights.W == 0 ? 0 : boneMap[(ushort)gltfIndices.W] )); } ); From 11acd7d3f46534ce445ef3700849f1f2c706491e Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Apr 2024 20:53:55 +1000 Subject: [PATCH 0567/1381] Prevent import failure when no materials are present --- Penumbra/Import/Models/Import/PrimitiveImporter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Import/Models/Import/PrimitiveImporter.cs b/Penumbra/Import/Models/Import/PrimitiveImporter.cs index 0c2968df..5df7597e 100644 --- a/Penumbra/Import/Models/Import/PrimitiveImporter.cs +++ b/Penumbra/Import/Models/Import/PrimitiveImporter.cs @@ -65,7 +65,7 @@ public class PrimitiveImporter ArgumentNullException.ThrowIfNull(_indices); ArgumentNullException.ThrowIfNull(_shapeValues); - var material = _primitive.Material.Name; + var material = _primitive.Material?.Name; if (material == "") material = null; From cc2f72b73df1218c094c45f9cfea3e5fa17ce534 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 20 Apr 2024 20:55:04 +1000 Subject: [PATCH 0568/1381] Use bg/ for absolute path example --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 1cfa7585..1f4607cf 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -382,7 +382,7 @@ public partial class ModEditWindow { ImGuiComponents.HelpMarker( "Materials must be either relative (e.g. \"/filename.mtrl\")\n" - + "or absolute (e.g. \"chara/full/path/to/filename.mtrl\").", + + "or absolute (e.g. \"bg/full/path/to/filename.mtrl\").", FontAwesomeIcon.TimesCircle); } From 1bc3bb17c9b8a95cbe6c3edd8cf7912f45b174f2 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 22 Apr 2024 23:45:30 +1000 Subject: [PATCH 0569/1381] Fix havok parsing for non-ANSI user paths Also improve parsing because otter is better at c# than me --- Penumbra/Import/Models/HavokConverter.cs | 10 ++++------ Penumbra/Import/Models/SkeletonConverter.cs | 5 ++--- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/Penumbra/Import/Models/HavokConverter.cs b/Penumbra/Import/Models/HavokConverter.cs index 89f9ac4f..38c8749a 100644 --- a/Penumbra/Import/Models/HavokConverter.cs +++ b/Penumbra/Import/Models/HavokConverter.cs @@ -71,8 +71,7 @@ public static unsafe class HavokConverter /// Path to a file on the filesystem. private static hkResource* Read(string filePath) { - var path = Marshal.StringToHGlobalAnsi(filePath); - + var path = Encoding.UTF8.GetBytes(filePath); var builtinTypeRegistry = hkBuiltinTypeRegistry.Instance(); var loadOptions = stackalloc hkSerializeUtil.LoadOptions[1]; @@ -81,8 +80,7 @@ public static unsafe class HavokConverter loadOptions->TypeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); // TODO: probably can use LoadFromBuffer for this. - var resource = hkSerializeUtil.LoadFromFile((byte*)path, null, loadOptions); - return resource; + return hkSerializeUtil.LoadFromFile(path, null, loadOptions); } /// Serializes an hkResource* to a temporary file. @@ -94,9 +92,9 @@ public static unsafe class HavokConverter ) { var tempFile = CreateTempFile(); - var path = Marshal.StringToHGlobalAnsi(tempFile); + var path = Encoding.UTF8.GetBytes(tempFile); var oStream = new hkOstream(); - oStream.Ctor((byte*)path); + oStream.Ctor(path); var result = stackalloc hkResult[1]; diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs index 7058a159..25e74332 100644 --- a/Penumbra/Import/Models/SkeletonConverter.cs +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -84,9 +84,8 @@ public static class SkeletonConverter .Where(n => n.NodeType != XmlNodeType.Comment) .Select(n => { - var text = n.InnerText.Trim()[1..]; - // TODO: surely there's a less shit way to do this I mean seriously - return BitConverter.ToSingle(BitConverter.GetBytes(int.Parse(text, NumberStyles.HexNumber))); + var text = n.InnerText.AsSpan().Trim()[1..]; + return BitConverter.Int32BitsToSingle(int.Parse(text, NumberStyles.HexNumber)); }) .ToArray(); From c276f922a53fc5798a9ae71673614a54bc88d9df Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Apr 2024 18:22:03 +0200 Subject: [PATCH 0570/1381] Update API. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 0c8578cf..590629df 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 0c8578cfa12bf0591ed204fd89b30b66719f678f +Subproject commit 590629df33f9ad92baddd1d65ec8c986f18d608a From b34114400fab2f83b119ddb1ac2d8c2ff7e4a708 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 23 Apr 2024 15:09:53 +0200 Subject: [PATCH 0571/1381] Fix Havok ANSI / UTF8 Issue. --- Penumbra/Import/Models/HavokConverter.cs | 10 ++++------ Penumbra/Import/Models/SkeletonConverter.cs | 5 ++--- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/Penumbra/Import/Models/HavokConverter.cs b/Penumbra/Import/Models/HavokConverter.cs index 89f9ac4f..dc9d3e6a 100644 --- a/Penumbra/Import/Models/HavokConverter.cs +++ b/Penumbra/Import/Models/HavokConverter.cs @@ -71,8 +71,7 @@ public static unsafe class HavokConverter /// Path to a file on the filesystem. private static hkResource* Read(string filePath) { - var path = Marshal.StringToHGlobalAnsi(filePath); - + var path = Encoding.UTF8.GetBytes(filePath); var builtinTypeRegistry = hkBuiltinTypeRegistry.Instance(); var loadOptions = stackalloc hkSerializeUtil.LoadOptions[1]; @@ -81,8 +80,7 @@ public static unsafe class HavokConverter loadOptions->TypeInfoRegistry = builtinTypeRegistry->GetTypeInfoRegistry(); // TODO: probably can use LoadFromBuffer for this. - var resource = hkSerializeUtil.LoadFromFile((byte*)path, null, loadOptions); - return resource; + return hkSerializeUtil.LoadFromFile(path, null, loadOptions); } /// Serializes an hkResource* to a temporary file. @@ -94,9 +92,9 @@ public static unsafe class HavokConverter ) { var tempFile = CreateTempFile(); - var path = Marshal.StringToHGlobalAnsi(tempFile); + var path = Encoding.UTF8.GetBytes(tempFile); var oStream = new hkOstream(); - oStream.Ctor((byte*)path); + oStream.Ctor(path); var result = stackalloc hkResult[1]; diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs index 7058a159..25e74332 100644 --- a/Penumbra/Import/Models/SkeletonConverter.cs +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -84,9 +84,8 @@ public static class SkeletonConverter .Where(n => n.NodeType != XmlNodeType.Comment) .Select(n => { - var text = n.InnerText.Trim()[1..]; - // TODO: surely there's a less shit way to do this I mean seriously - return BitConverter.ToSingle(BitConverter.GetBytes(int.Parse(text, NumberStyles.HexNumber))); + var text = n.InnerText.AsSpan().Trim()[1..]; + return BitConverter.Int32BitsToSingle(int.Parse(text, NumberStyles.HexNumber)); }) .ToArray(); From e21c9fb6d1d71e0f952d416a8d1b0e817e450826 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 23 Apr 2024 15:11:09 +0200 Subject: [PATCH 0572/1381] Fix some IPC stuff. --- Penumbra/Api/IpcProviders.cs | 5 +++-- Penumbra/Api/IpcTester/UiIpcTester.cs | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 21fe0a7c..ebf71176 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -62,6 +62,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ApiVersion.Provider(pi, api), new FuncProvider<(int Major, int Minor)>(pi, "Penumbra.ApiVersions", () => api.ApiVersion), // backward compatibility + new FuncProvider(pi, "Penumbra.ApiVersion", () => api.ApiVersion.Breaking), // backward compatibility IpcSubscribers.GetModDirectory.Provider(pi, api.PluginState), IpcSubscribers.GetConfiguration.Provider(pi, api.PluginState), IpcSubscribers.ModDirectoryChanged.Provider(pi, api.PluginState), @@ -99,9 +100,9 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ChangedItemTooltip.Provider(pi, api.Ui), IpcSubscribers.ChangedItemClicked.Provider(pi, api.Ui), IpcSubscribers.PreSettingsTabBarDraw.Provider(pi, api.Ui), - IpcSubscribers.PreSettingsPanelDraw.Provider(pi, api.Ui), + IpcSubscribers.PreSettingsDraw.Provider(pi, api.Ui), IpcSubscribers.PostEnabledDraw.Provider(pi, api.Ui), - IpcSubscribers.PostSettingsPanelDraw.Provider(pi, api.Ui), + IpcSubscribers.PostSettingsDraw.Provider(pi, api.Ui), IpcSubscribers.OpenMainWindow.Provider(pi, api.Ui), IpcSubscribers.CloseMainWindow.Provider(pi, api.Ui), ]; diff --git a/Penumbra/Api/IpcTester/UiIpcTester.cs b/Penumbra/Api/IpcTester/UiIpcTester.cs index d95b79b8..a2c36938 100644 --- a/Penumbra/Api/IpcTester/UiIpcTester.cs +++ b/Penumbra/Api/IpcTester/UiIpcTester.cs @@ -32,9 +32,9 @@ public class UiIpcTester : IUiService, IDisposable { _pi = pi; PreSettingsTabBar = IpcSubscribers.PreSettingsTabBarDraw.Subscriber(pi, UpdateLastDrawnMod); - PreSettingsPanel = IpcSubscribers.PreSettingsPanelDraw.Subscriber(pi, UpdateLastDrawnMod); + PreSettingsPanel = IpcSubscribers.PreSettingsDraw.Subscriber(pi, UpdateLastDrawnMod); PostEnabled = IpcSubscribers.PostEnabledDraw.Subscriber(pi, UpdateLastDrawnMod); - PostSettingsPanelDraw = IpcSubscribers.PostSettingsPanelDraw.Subscriber(pi, UpdateLastDrawnMod); + PostSettingsPanelDraw = IpcSubscribers.PostSettingsDraw.Subscriber(pi, UpdateLastDrawnMod); ChangedItemTooltip = IpcSubscribers.ChangedItemTooltip.Subscriber(pi, AddedTooltip); ChangedItemClicked = IpcSubscribers.ChangedItemClicked.Subscriber(pi, AddedClick); PreSettingsTabBar.Disable(); @@ -76,7 +76,7 @@ public class UiIpcTester : IUiService, IDisposable if (!table) return; - IpcTester.DrawIntro(IpcSubscribers.PostSettingsPanelDraw.Label, "Last Drawn Mod"); + IpcTester.DrawIntro(IpcSubscribers.PostSettingsDraw.Label, "Last Drawn Mod"); ImGui.TextUnformatted(_lastDrawnMod.Length > 0 ? $"{_lastDrawnMod} at {_lastDrawnModTime}" : "None"); IpcTester.DrawIntro(IpcSubscribers.ChangedItemTooltip.Label, "Add Tooltip"); From 792a04337f31f2c53ff562c3d8116821192fe58e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 23 Apr 2024 15:50:09 +0200 Subject: [PATCH 0573/1381] Add a try-catch when scanning for mods. --- Penumbra/Mods/Manager/ModManager.cs | 36 ++++++++++++++++++----------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 40585520..d912e292 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,3 +1,4 @@ +using System.Security.AccessControl; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Services; @@ -311,22 +312,31 @@ public sealed class ModManager : ModStorage, IDisposable /// private void ScanMods() { - var options = new ParallelOptions() + try { - MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount / 2), - }; - var queue = new ConcurrentQueue(); - Parallel.ForEach(BasePath.EnumerateDirectories(), options, dir => - { - var mod = Creator.LoadMod(dir, false); - if (mod != null) - queue.Enqueue(mod); - }); + var options = new ParallelOptions() + { + MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount / 2), + }; + var queue = new ConcurrentQueue(); + Parallel.ForEach(BasePath.EnumerateDirectories(), options, dir => + { + var mod = Creator.LoadMod(dir, false); + if (mod != null) + queue.Enqueue(mod); + }); - foreach (var mod in queue) + foreach (var mod in queue) + { + mod.Index = Count; + Mods.Add(mod); + } + } + catch (Exception ex) { - mod.Index = Count; - Mods.Add(mod); + Valid = false; + _communicator.ModDirectoryChanged.Invoke(BasePath.FullName, false); + Penumbra.Log.Error($"Could not scan for mods:\n{ex}"); } } } From 07afbfb22974c4ca49d76bce109ff0a301d17b60 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 23 Apr 2024 17:41:55 +0200 Subject: [PATCH 0574/1381] Rework options, pre-submod types. --- Penumbra/Api/Api/ModSettingsApi.cs | 10 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 2 +- Penumbra/Meta/MetaFileManager.cs | 8 +- Penumbra/Mods/Editor/ModEditor.cs | 30 +++- Penumbra/Mods/Editor/ModFileEditor.cs | 3 +- Penumbra/Mods/Editor/ModMerger.cs | 38 ++++-- Penumbra/Mods/Editor/ModNormalizer.cs | 72 +++++++--- Penumbra/Mods/Manager/ModCacheManager.cs | 10 +- Penumbra/Mods/Manager/ModMigration.cs | 12 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 128 ++++++++---------- Penumbra/Mods/Mod.cs | 9 +- Penumbra/Mods/ModCreator.cs | 45 +++--- Penumbra/Mods/Subclasses/IModDataContainer.cs | 80 +++++++++++ Penumbra/Mods/Subclasses/IModGroup.cs | 14 +- Penumbra/Mods/Subclasses/IModOption.cs | 25 ++++ Penumbra/Mods/Subclasses/ModSettings.cs | 18 +-- Penumbra/Mods/Subclasses/MultiModGroup.cs | 86 ++++++++---- Penumbra/Mods/Subclasses/SingleModGroup.cs | 82 +++++++---- Penumbra/Mods/Subclasses/SubMod.cs | 110 +++++++++++++-- Penumbra/Mods/TemporaryMod.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 17 ++- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 10 +- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 20 ++- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 50 ++++--- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 39 +++--- 25 files changed, 620 insertions(+), 300 deletions(-) create mode 100644 Penumbra/Mods/Subclasses/IModDataContainer.cs create mode 100644 Penumbra/Mods/Subclasses/IModOption.cs diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 2604a49d..5ed26ce5 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -56,13 +56,13 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable var dict = new Dictionary(mod.Groups.Count); foreach (var g in mod.Groups) - dict.Add(g.Name, (g.Select(o => o.Name).ToArray(), (int)g.Type)); + dict.Add(g.Name, (g.Options.Select(o => o.Name).ToArray(), (int)g.Type)); return new AvailableModSettings(dict); } public Dictionary? GetAvailableModSettingsBase(string modDirectory, string modName) => _modManager.TryGetMod(modDirectory, modName, out var mod) - ? mod.Groups.ToDictionary(g => g.Name, g => (g.Select(o => o.Name).ToArray(), (int)g.Type)) + ? mod.Groups.ToDictionary(g => g.Name, g => (g.Options.Select(o => o.Name).ToArray(), (int)g.Type)) : null; public (PenumbraApiEc, (bool, int, Dictionary>, bool)?) GetCurrentModSettings(Guid collectionId, string modDirectory, @@ -153,7 +153,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable if (groupIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionGroupMissing, args); - var optionIdx = mod.Groups[groupIdx].IndexOf(o => o.Name == optionName); + var optionIdx = mod.Groups[groupIdx].Options.IndexOf(o => o.Name == optionName); if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); @@ -190,7 +190,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable { case SingleModGroup single: { - var optionIdx = optionNames.Count == 0 ? -1 : single.IndexOf(o => o.Name == optionNames[^1]); + var optionIdx = optionNames.Count == 0 ? -1 : single.OptionData.IndexOf(o => o.Name == optionNames[^1]); if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); @@ -201,7 +201,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable { foreach (var name in optionNames) { - var optionIdx = multi.IndexOf(o => o.Name == name); + var optionIdx = multi.PrioritizedOptions.IndexOf(o => o.Mod.Name == name); if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index f4b7d47e..7d9388a9 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -203,7 +203,7 @@ public partial class TexToolsImporter { var option = group.OptionList[idx]; _currentOptionName = option.Name; - options.Insert(idx, ModCreator.CreateEmptySubMod(option.Name)); + options.Insert(idx, SubMod.CreateForSaving(option.Name)); if (option.IsChecked) defaultSettings = Setting.Single(idx); } diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 5283f77e..b1823bd7 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -54,7 +54,13 @@ public unsafe class MetaFileManager if (!dir.Exists) dir.Create(); - foreach (var option in group.OfType()) + var optionEnumerator = group switch + { + SingleModGroup single => single.OptionData, + MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), + _ => [], + }; + foreach (var option in optionEnumerator) { var optionDir = ModCreator.NewOptionDirectory(dir, option.Name, Config.ReplaceNonAsciiOnImport); if (!optionDir.Exists) diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index d9781c06..0a96e0fd 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -1,3 +1,4 @@ +using System; using OtterGui; using OtterGui.Compression; using Penumbra.Mods.Subclasses; @@ -72,12 +73,18 @@ public class ModEditor( if (groupIdx >= 0) { Group = Mod.Groups[groupIdx]; - if (optionIdx >= 0 && optionIdx < Group.Count) + switch(Group) { - Option = Group[optionIdx]; - GroupIdx = groupIdx; - OptionIdx = optionIdx; - return; + case SingleModGroup single when optionIdx >= 0 && optionIdx < single.OptionData.Count: + Option = single.OptionData[optionIdx]; + GroupIdx = groupIdx; + OptionIdx = optionIdx; + return; + case MultiModGroup multi when optionIdx >= 0 && optionIdx < multi.PrioritizedOptions.Count: + Option = multi.PrioritizedOptions[optionIdx].Mod; + GroupIdx = groupIdx; + OptionIdx = optionIdx; + return; } } } @@ -109,8 +116,17 @@ public class ModEditor( action(mod.Default, -1, 0); foreach (var (group, groupIdx) in mod.Groups.WithIndex()) { - for (var optionIdx = 0; optionIdx < group.Count; ++optionIdx) - action(group[optionIdx], groupIdx, optionIdx); + switch (group) + { + case SingleModGroup single: + for (var optionIdx = 0; optionIdx < single.OptionData.Count; ++optionIdx) + action(single.OptionData[optionIdx], groupIdx, optionIdx); + break; + case MultiModGroup multi: + for (var optionIdx = 0; optionIdx < multi.PrioritizedOptions.Count; ++optionIdx) + action(multi.PrioritizedOptions[optionIdx].Mod, groupIdx, optionIdx); + break; + } } } diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 4bdf4b1b..51615b05 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -24,7 +24,8 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu num += dict.TryAdd(path.Item2, file.File) ? 0 : 1; } - modManager.OptionEditor.OptionSetFiles(mod, option.GroupIdx, option.OptionIdx, dict); + var (groupIdx, optionIdx) = option.GetIndices(); + modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict); files.UpdatePaths(mod, option); Changes = false; return num; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 25590c49..74e9007c 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -1,5 +1,6 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; +using ImGuizmoNET; using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; @@ -104,9 +105,16 @@ public class ModMerger : IDisposable ((List)Warnings).Add( $"The merged group {group.Name} already existed, but has a different type {group.Type} than the original group of type {originalGroup.Type}."); - foreach (var originalOption in originalGroup) + var optionEnumerator = group switch { - var (option, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, originalOption.Name); + SingleModGroup single => single.OptionData, + MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), + _ => [], + }; + + foreach (var originalOption in optionEnumerator) + { + var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, originalOption.Name); if (optionCreated) { _createdOptions.Add(option); @@ -138,7 +146,7 @@ public class ModMerger : IDisposable var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, GroupType.Multi, groupName, SaveType.None); if (groupCreated) _createdGroups.Add(groupIdx); - var (option, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName, SaveType.None); + var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName, SaveType.None); if (optionCreated) _createdOptions.Add(option); var dir = ModCreator.NewOptionDirectory(MergeToMod!.ModPath, groupName, _config.ReplaceNonAsciiOnImport); @@ -184,9 +192,10 @@ public class ModMerger : IDisposable } } - _editor.OptionSetFiles(MergeToMod!, option.GroupIdx, option.OptionIdx, redirections, SaveType.None); - _editor.OptionSetFileSwaps(MergeToMod!, option.GroupIdx, option.OptionIdx, swaps, SaveType.None); - _editor.OptionSetManipulations(MergeToMod!, option.GroupIdx, option.OptionIdx, manips, SaveType.ImmediateSync); + var (groupIdx, optionIdx) = option.GetIndices(); + _editor.OptionSetFiles(MergeToMod!, groupIdx, optionIdx, redirections, SaveType.None); + _editor.OptionSetFileSwaps(MergeToMod!, groupIdx, optionIdx, swaps, SaveType.None); + _editor.OptionSetManipulations(MergeToMod!, groupIdx, optionIdx, manips, SaveType.ImmediateSync); return; bool GetFullPath(FullPath input, out FullPath ret) @@ -251,7 +260,7 @@ public class ModMerger : IDisposable Mod? result = null; try { - dir = _creator.CreateEmptyMod(_mods.BasePath, modName, $"Split off from {mods[0].ParentMod.Name}."); + dir = _creator.CreateEmptyMod(_mods.BasePath, modName, $"Split off from {mods[0].Mod.Name}."); if (dir == null) throw new Exception($"Could not split off mods, unable to create new mod with name {modName}."); @@ -268,7 +277,6 @@ public class ModMerger : IDisposable { foreach (var originalOption in mods) { - var originalGroup = originalOption.ParentMod.Groups[originalOption.GroupIdx]; if (originalOption.IsDefault) { var files = CopySubModFiles(mods[0], dir); @@ -278,13 +286,14 @@ public class ModMerger : IDisposable } else { + var originalGroup = originalOption.Group; var (group, groupIdx, _) = _editor.FindOrAddModGroup(result, originalGroup.Type, originalGroup.Name); - var (option, _) = _editor.FindOrAddOption(result, groupIdx, originalOption.Name); + var (option, optionIdx, _) = _editor.FindOrAddOption(result, groupIdx, originalOption.Name); var folder = Path.Combine(dir.FullName, group.Name, option.Name); var files = CopySubModFiles(originalOption, new DirectoryInfo(folder)); - _editor.OptionSetFiles(result, groupIdx, option.OptionIdx, files); - _editor.OptionSetFileSwaps(result, groupIdx, option.OptionIdx, originalOption.FileSwapData); - _editor.OptionSetManipulations(result, groupIdx, option.OptionIdx, originalOption.ManipulationData); + _editor.OptionSetFiles(result, groupIdx, optionIdx, files); + _editor.OptionSetFileSwaps(result, groupIdx, optionIdx, originalOption.FileSwapData); + _editor.OptionSetManipulations(result, groupIdx, optionIdx, originalOption.ManipulationData); } } } @@ -309,7 +318,7 @@ public class ModMerger : IDisposable private static Dictionary CopySubModFiles(SubMod option, DirectoryInfo newMod) { var ret = new Dictionary(option.FileData.Count); - var parentPath = ((Mod)option.ParentMod).ModPath.FullName; + var parentPath = ((Mod)option.Mod).ModPath.FullName; foreach (var (path, file) in option.FileData) { var target = Path.GetRelativePath(parentPath, file.FullName); @@ -339,7 +348,8 @@ public class ModMerger : IDisposable { foreach (var option in _createdOptions) { - _editor.DeleteOption(MergeToMod!, option.GroupIdx, option.OptionIdx); + var (groupIdx, optionIdx) = option.GetIndices(); + _editor.DeleteOption(MergeToMod!, groupIdx, optionIdx); Penumbra.Log.Verbose($"[Merger] Removed option {option.FullName}."); } diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index a9a31212..9698fdcb 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -167,28 +167,27 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) // Normalize all other options. foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) { - _redirections[groupIdx + 1].EnsureCapacity(group.Count); - for (var i = _redirections[groupIdx + 1].Count; i < group.Count; ++i) - _redirections[groupIdx + 1].Add([]); - var groupDir = ModCreator.CreateModFolder(directory, group.Name, _config.ReplaceNonAsciiOnImport, true); - foreach (var option in group.OfType()) + switch (group) { - var optionDir = ModCreator.CreateModFolder(groupDir, option.Name, _config.ReplaceNonAsciiOnImport, true); + case SingleModGroup single: + _redirections[groupIdx + 1].EnsureCapacity(single.OptionData.Count); + for (var i = _redirections[groupIdx + 1].Count; i < single.OptionData.Count; ++i) + _redirections[groupIdx + 1].Add([]); - newDict = _redirections[groupIdx + 1][option.OptionIdx]; - newDict.Clear(); - newDict.EnsureCapacity(option.FileData.Count); - foreach (var (gamePath, fullPath) in option.FileData) - { - var relPath = new Utf8RelPath(gamePath).ToString(); - var newFullPath = Path.Combine(optionDir.FullName, relPath); - var redirectPath = new FullPath(Path.Combine(Mod.ModPath.FullName, groupDir.Name, optionDir.Name, relPath)); - Directory.CreateDirectory(Path.GetDirectoryName(newFullPath)!); - File.Copy(fullPath.FullName, newFullPath, true); - newDict.Add(gamePath, redirectPath); - ++Step; - } + foreach (var (option, optionIdx) in single.OptionData.WithIndex()) + HandleSubMod(groupDir, option, _redirections[groupIdx + 1][optionIdx]); + + break; + case MultiModGroup multi: + _redirections[groupIdx + 1].EnsureCapacity(multi.PrioritizedOptions.Count); + for (var i = _redirections[groupIdx + 1].Count; i < multi.PrioritizedOptions.Count; ++i) + _redirections[groupIdx + 1].Add([]); + + foreach (var ((option, _), optionIdx) in multi.PrioritizedOptions.WithIndex()) + HandleSubMod(groupDir, option, _redirections[groupIdx + 1][optionIdx]); + + break; } } @@ -200,6 +199,24 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) } return false; + + void HandleSubMod(DirectoryInfo groupDir, SubMod option, Dictionary newDict) + { + var optionDir = ModCreator.CreateModFolder(groupDir, option.Name, _config.ReplaceNonAsciiOnImport, true); + + newDict.Clear(); + newDict.EnsureCapacity(option.FileData.Count); + foreach (var (gamePath, fullPath) in option.FileData) + { + var relPath = new Utf8RelPath(gamePath).ToString(); + var newFullPath = Path.Combine(optionDir.FullName, relPath); + var redirectPath = new FullPath(Path.Combine(Mod.ModPath.FullName, groupDir.Name, optionDir.Name, relPath)); + Directory.CreateDirectory(Path.GetDirectoryName(newFullPath)!); + File.Copy(fullPath.FullName, newFullPath, true); + newDict.Add(gamePath, redirectPath); + ++Step; + } + } } private bool MoveOldFiles() @@ -274,9 +291,20 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) private void ApplyRedirections() { - foreach (var option in Mod.AllSubMods) - _modManager.OptionEditor.OptionSetFiles(Mod, option.GroupIdx, option.OptionIdx, - _redirections[option.GroupIdx + 1][option.OptionIdx]); + foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) + { + switch (group) + { + case SingleModGroup single: + foreach (var (_, optionIdx) in single.OptionData.WithIndex()) + _modManager.OptionEditor.OptionSetFiles(Mod, groupIdx, optionIdx, _redirections[groupIdx + 1][optionIdx]); + break; + case MultiModGroup multi: + foreach (var (_, optionIdx) in multi.PrioritizedOptions.WithIndex()) + _modManager.OptionEditor.OptionSetFiles(Mod, groupIdx, optionIdx, _redirections[groupIdx + 1][optionIdx]); + break; + } + } ++Step; } diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 99ad1a4f..df243781 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -2,6 +2,7 @@ using Penumbra.Communication; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Subclasses; using Penumbra.Services; namespace Penumbra.Mods.Manager; @@ -211,7 +212,14 @@ public class ModCacheManager : IDisposable foreach (var group in mod.Groups) { mod.HasOptions |= group.IsOption; - foreach (var s in group) + var optionEnumerator = group switch + { + SingleModGroup single => single.OptionData, + MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), + _ => [], + }; + + foreach (var s in optionEnumerator) { mod.TotalFileCount += s.Files.Count; mod.TotalSwapCount += s.FileSwaps.Count; diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 295afd7b..9c8ced89 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -126,7 +126,7 @@ public static partial class ModMigration case GroupType.Multi: var optionPriority = ModPriority.Default; - var newMultiGroup = new MultiModGroup() + var newMultiGroup = new MultiModGroup(mod) { Name = group.GroupName, Priority = priority++, @@ -134,7 +134,7 @@ public static partial class ModMigration }; mod.Groups.Add(newMultiGroup); foreach (var option in group.Options) - newMultiGroup.PrioritizedOptions.Add((SubModFromOption(creator, mod, option, seenMetaFiles), optionPriority++)); + newMultiGroup.PrioritizedOptions.Add((SubModFromOption(creator, mod, newMultiGroup, option, seenMetaFiles), optionPriority++)); break; case GroupType.Single: @@ -144,7 +144,7 @@ public static partial class ModMigration return; } - var newSingleGroup = new SingleModGroup() + var newSingleGroup = new SingleModGroup(mod) { Name = group.GroupName, Priority = priority++, @@ -152,7 +152,7 @@ public static partial class ModMigration }; mod.Groups.Add(newSingleGroup); foreach (var option in group.Options) - newSingleGroup.OptionData.Add(SubModFromOption(creator, mod, option, seenMetaFiles)); + newSingleGroup.OptionData.Add(SubModFromOption(creator, mod, newSingleGroup, option, seenMetaFiles)); break; } @@ -171,9 +171,9 @@ public static partial class ModMigration } } - private static SubMod SubModFromOption(ModCreator creator, Mod mod, OptionV0 option, HashSet seenMetaFiles) + private static SubMod SubModFromOption(ModCreator creator, Mod mod, IModGroup group, OptionV0 option, HashSet seenMetaFiles) { - var subMod = new SubMod(mod) { Name = option.OptionName }; + var subMod = new SubMod(mod, group) { Name = option.OptionName }; AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); creator.IncorporateMetaChanges(subMod, mod.ModPath, false); return subMod; diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 9d942574..e78b6209 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -87,12 +87,12 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; mod.Groups.Add(type == GroupType.Multi - ? new MultiModGroup + ? new MultiModGroup(mod) { Name = newName, Priority = maxPriority, } - : new SingleModGroup + : new SingleModGroup(mod) { Name = newName, Priority = maxPriority, @@ -120,7 +120,6 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS { communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, -1, -1); mod.Groups.RemoveAt(groupIdx); - UpdateSubModPositions(mod, groupIdx); saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, groupIdx, -1, -1); } @@ -131,7 +130,6 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS if (!mod.Groups.Move(groupIdxFrom, groupIdxTo)) return; - UpdateSubModPositions(mod, Math.Min(groupIdxFrom, groupIdxTo)); saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, groupIdxFrom, -1, groupIdxTo); } @@ -156,12 +154,9 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS /// Change the description of the given option. public void ChangeOptionDescription(Mod mod, int groupIdx, int optionIdx, string newDescription) { - var group = mod.Groups[groupIdx]; - var option = group[optionIdx]; - if (option.Description == newDescription) + if (!mod.Groups[groupIdx].ChangeOptionDescription(optionIdx, newDescription)) return; - option.Description = newDescription; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } @@ -173,12 +168,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS if (group.Priority == newPriority) return; - var _ = group switch - { - SingleModGroup s => s.Priority = newPriority, - MultiModGroup m => m.Priority = newPriority, - _ => newPriority, - }; + group.Priority = newPriority; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, -1, -1); } @@ -188,14 +178,11 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS { switch (mod.Groups[groupIdx]) { - case SingleModGroup: - ChangeGroupPriority(mod, groupIdx, newPriority); - break; - case MultiModGroup m: - if (m.PrioritizedOptions[optionIdx].Priority == newPriority) + case MultiModGroup multi: + if (multi.PrioritizedOptions[optionIdx].Priority == newPriority) return; - m.PrioritizedOptions[optionIdx] = (m.PrioritizedOptions[optionIdx].Mod, newPriority); + multi.PrioritizedOptions[optionIdx] = (multi.PrioritizedOptions[optionIdx].Mod, newPriority); saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, optionIdx, -1); return; @@ -205,60 +192,63 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS /// Rename the given option. public void RenameOption(Mod mod, int groupIdx, int optionIdx, string newName) { - switch (mod.Groups[groupIdx]) - { - case SingleModGroup s: - if (s.OptionData[optionIdx].Name == newName) - return; - - s.OptionData[optionIdx].Name = newName; - break; - case MultiModGroup m: - var option = m.PrioritizedOptions[optionIdx].Mod; - if (option.Name == newName) - return; - - option.Name = newName; - break; - } + if (!mod.Groups[groupIdx].ChangeOptionName(optionIdx, newName)) + return; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } /// Add a new empty option of the given name for the given group. - public void AddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) + public int AddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) { - var group = mod.Groups[groupIdx]; - var subMod = new SubMod(mod) { Name = newName }; - subMod.SetPosition(groupIdx, group.Count); - switch (group) - { - case SingleModGroup s: - s.OptionData.Add(subMod); - break; - case MultiModGroup m: - m.PrioritizedOptions.Add((subMod, ModPriority.Default)); - break; - } + var group = mod.Groups[groupIdx]; + var idx = group.AddOption(mod, newName); + if (idx < 0) + return -1; saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); + return idx; } /// Add a new empty option of the given name for the given group if it does not exist already. - public (SubMod, bool) FindOrAddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) + public (SubMod, int, bool) FindOrAddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) { var group = mod.Groups[groupIdx]; - var idx = group.IndexOf(o => o.Name == newName); - if (idx >= 0) - return ((SubMod)group[idx], false); + switch (group) + { + case SingleModGroup single: + { + var idx = single.OptionData.IndexOf(o => o.Name == newName); + if (idx >= 0) + return (single.OptionData[idx], idx, false); - AddOption(mod, groupIdx, newName, saveType); - if (group[^1].Name != newName) - throw new Exception($"Could not create new option with name {newName} in {group.Name}."); + idx = single.AddOption(mod, newName); + if (idx < 0) + throw new Exception($"Could not create new option with name {newName} in {group.Name}."); - return ((SubMod)group[^1], true); + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); + return (single.OptionData[^1], single.OptionData.Count - 1, true); + } + case MultiModGroup multi: + { + var idx = multi.PrioritizedOptions.IndexOf(o => o.Mod.Name == newName); + if (idx >= 0) + return (multi.PrioritizedOptions[idx].Mod, idx, false); + + idx = multi.AddOption(mod, newName); + if (idx < 0) + throw new Exception($"Could not create new option with name {newName} in {group.Name}."); + + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); + return (multi.PrioritizedOptions[^1].Mod, multi.PrioritizedOptions.Count - 1, true); + } + } + + throw new Exception($"{nameof(FindOrAddOption)} is not supported for mod groups of type {group.GetType()}."); } /// Add an existing option to a given group with default priority. @@ -269,25 +259,28 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS public void AddOption(Mod mod, int groupIdx, SubMod option, ModPriority priority) { var group = mod.Groups[groupIdx]; + int idx; switch (group) { - case MultiModGroup { Count: >= IModGroup.MaxMultiOptions }: + case MultiModGroup { PrioritizedOptions.Count: >= IModGroup.MaxMultiOptions }: Penumbra.Log.Error( $"Could not add option {option.Name} to {group.Name} for mod {mod.Name}, " + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); return; case SingleModGroup s: - option.SetPosition(groupIdx, s.Count); + idx = s.OptionData.Count; s.OptionData.Add(option); break; case MultiModGroup m: - option.SetPosition(groupIdx, m.Count); + idx = m.PrioritizedOptions.Count; m.PrioritizedOptions.Add((option, priority)); break; + default: + return; } saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, group.Count - 1, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); } /// Delete the given option from the given group. @@ -306,7 +299,6 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS break; } - group.UpdatePositions(optionIdx); saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionDeleted, mod, groupIdx, optionIdx, -1); } @@ -396,16 +388,6 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS return false; } - /// Update the indices stored in options from a given group on. - private static void UpdateSubModPositions(Mod mod, int fromGroup) - { - foreach (var (group, groupIdx) in mod.Groups.WithIndex().Skip(fromGroup)) - { - foreach (var (o, optionIdx) in group.OfType().WithIndex()) - o.SetPosition(groupIdx, optionIdx); - } - } - /// Get the correct option for the given group and option index. private static SubMod GetSubMod(Mod mod, int groupIdx, int optionIdx) { diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 25f3c510..71f64205 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -38,7 +38,7 @@ public sealed class Mod : IMod internal Mod(DirectoryInfo modPath) { ModPath = modPath; - Default = new SubMod(this); + Default = SubMod.CreateDefault(this); } public override string ToString() @@ -82,7 +82,12 @@ public sealed class Mod : IMod } public IEnumerable AllSubMods - => Groups.SelectMany(o => o).Prepend(Default); + => Groups.SelectMany(o => o switch + { + SingleModGroup single => single.OptionData, + MultiModGroup multi => multi.PrioritizedOptions.Select(s => s.Mod), + _ => [], + }).Prepend(Default); public List FindUnusedFiles() { diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 661dd6fb..4d32f395 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -16,7 +16,11 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; -public partial class ModCreator(SaveService _saveService, Configuration config, ModDataEditor _dataEditor, MetaFileManager _metaFileManager, +public partial class ModCreator( + SaveService _saveService, + Configuration config, + ModDataEditor _dataEditor, + MetaFileManager _metaFileManager, GamePathParser _gamePathParser) { public readonly Configuration Config = config; @@ -106,7 +110,6 @@ public partial class ModCreator(SaveService _saveService, Configuration config, public void LoadDefaultOption(Mod mod) { var defaultFile = _saveService.FileNames.OptionGroupFile(mod, -1, Config.ReplaceNonAsciiOnImport); - mod.Default.SetPosition(-1, 0); try { if (!File.Exists(defaultFile)) @@ -241,27 +244,21 @@ public partial class ModCreator(SaveService _saveService, Configuration config, { case GroupType.Multi: { - var group = new MultiModGroup() - { - Name = name, - Description = desc, - Priority = priority, - DefaultSettings = defaultSettings, - }; + var group = MultiModGroup.CreateForSaving(name); + group.Description = desc; + group.Priority = priority; + group.DefaultSettings = defaultSettings; group.PrioritizedOptions.AddRange(subMods.Select((s, idx) => (s, new ModPriority(idx)))); _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } case GroupType.Single: { - var group = new SingleModGroup() - { - Name = name, - Description = desc, - Priority = priority, - DefaultSettings = defaultSettings, - }; - group.OptionData.AddRange(subMods.OfType()); + var group = SingleModGroup.CreateForSaving(name); + group.Description = desc; + group.Priority = priority; + group.DefaultSettings = defaultSettings; + group.OptionData.AddRange(subMods); _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } @@ -275,11 +272,8 @@ public partial class ModCreator(SaveService _saveService, Configuration config, .Select(f => (Utf8GamePath.FromFile(f, optionFolder, out var gamePath, true), gamePath, new FullPath(f))) .Where(t => t.Item1); - var mod = new SubMod(null!) // Mod is irrelevant here, only used for saving. - { - Name = option.Name, - Description = option.Description, - }; + var mod = SubMod.CreateForSaving(option.Name); + mod.Description = option.Description; foreach (var (_, gamePath, file) in list) mod.FileData.TryAdd(gamePath, file); @@ -287,13 +281,6 @@ public partial class ModCreator(SaveService _saveService, Configuration config, return mod; } - /// Create an empty sub mod for single groups with None options. - internal static SubMod CreateEmptySubMod(string name) - => new SubMod(null!) // Mod is irrelevant here, only used for saving. - { - Name = name, - }; - /// /// Create the default data file from all unused files that were not handled before /// and are used in sub mods. diff --git a/Penumbra/Mods/Subclasses/IModDataContainer.cs b/Penumbra/Mods/Subclasses/IModDataContainer.cs new file mode 100644 index 00000000..d0b444b8 --- /dev/null +++ b/Penumbra/Mods/Subclasses/IModDataContainer.cs @@ -0,0 +1,80 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.Meta.Manipulations; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.Subclasses; + +public interface IModDataContainer +{ + public Dictionary Files { get; set; } + public Dictionary FileSwaps { get; set; } + public HashSet Manipulations { get; set; } + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + { + foreach (var (path, file) in Files) + redirections.TryAdd(path, file); + + foreach (var (path, file) in FileSwaps) + redirections.TryAdd(path, file); + manipulations.UnionWith(Manipulations); + } + + public static void Load(JToken json, IModDataContainer data, DirectoryInfo basePath) + { + data.Files.Clear(); + data.FileSwaps.Clear(); + data.Manipulations.Clear(); + + var files = (JObject?)json[nameof(Files)]; + if (files != null) + foreach (var property in files.Properties()) + { + if (Utf8GamePath.FromString(property.Name, out var p, true)) + data.Files.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); + } + + var swaps = (JObject?)json[nameof(FileSwaps)]; + if (swaps != null) + foreach (var property in swaps.Properties()) + { + if (Utf8GamePath.FromString(property.Name, out var p, true)) + data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); + } + + var manips = json[nameof(Manipulations)]; + if (manips != null) + foreach (var s in manips.Children().Select(c => c.ToObject()) + .Where(m => m.Validate())) + data.Manipulations.Add(s); + } + + public static void WriteModData(JsonWriter j, JsonSerializer serializer, IModDataContainer data, DirectoryInfo basePath) + { + j.WritePropertyName(nameof(data.Files)); + j.WriteStartObject(); + foreach (var (gamePath, file) in data.Files) + { + if (file.ToRelPath(basePath, out var relPath)) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(relPath.ToString()); + } + } + + j.WriteEndObject(); + j.WritePropertyName(nameof(data.FileSwaps)); + j.WriteStartObject(); + foreach (var (gamePath, file) in data.FileSwaps) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(file.ToString()); + } + + j.WriteEndObject(); + j.WritePropertyName(nameof(data.Manipulations)); + serializer.Serialize(j, data.Manipulations); + j.WriteEndObject(); + } +} diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index 96d7c6b7..a046ade0 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -6,25 +6,27 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; -public interface IModGroup : IReadOnlyCollection +public interface IModGroup { public const int MaxMultiOptions = 63; + public Mod Mod { get; } public string Name { get; } public string Description { get; } public GroupType Type { get; } - public ModPriority Priority { get; } + public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } public FullPath? FindBestMatch(Utf8GamePath gamePath); + public int AddOption(Mod mod, string name, string description = ""); + public bool ChangeOptionDescription(int optionIndex, string newDescription); + public bool ChangeOptionName(int optionIndex, string newName); - public SubMod this[Index idx] { get; } - - public bool IsOption { get; } + public IReadOnlyList Options { get; } + public bool IsOption { get; } public IModGroup Convert(GroupType type); public bool MoveOption(int optionIdxFrom, int optionIdxTo); - public void UpdatePositions(int from = 0); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); diff --git a/Penumbra/Mods/Subclasses/IModOption.cs b/Penumbra/Mods/Subclasses/IModOption.cs new file mode 100644 index 00000000..bb52a2cd --- /dev/null +++ b/Penumbra/Mods/Subclasses/IModOption.cs @@ -0,0 +1,25 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Penumbra.Mods.Subclasses; + +public interface IModOption +{ + public string Name { get; set; } + public string FullName { get; } + public string Description { get; set; } + + public static void Load(JToken json, IModOption option) + { + option.Name = json[nameof(Name)]?.ToObject() ?? string.Empty; + option.Description = json[nameof(Description)]?.ToObject() ?? string.Empty; + } + + public static void WriteModOption(JsonWriter j, IModOption option) + { + j.WritePropertyName(nameof(Name)); + j.WriteValue(option.Name); + j.WritePropertyName(nameof(Description)); + j.WriteValue(option.Description); + } +} diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Subclasses/ModSettings.cs index 81a3bb41..2ddabdb8 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Subclasses/ModSettings.cs @@ -68,7 +68,7 @@ public class ModSettings var config = Settings[groupIdx]; Settings[groupIdx] = group.Type switch { - GroupType.Single => config.TurnMulti(group.Count), + GroupType.Single => config.TurnMulti(group.Options.Count), GroupType.Multi => Setting.Multi((int)config.Value), _ => config, }; @@ -182,15 +182,15 @@ public class ModSettings if (idx >= mod.Groups.Count) break; - var group = mod.Groups[idx]; - if (group.Type == GroupType.Single && setting.Value < (ulong)group.Count) + switch (mod.Groups[idx]) { - dict.Add(group.Name, [group[(int)setting.Value].Name]); - } - else - { - var list = group.Where((_, optionIdx) => (setting.Value & (1ul << optionIdx)) != 0).Select(o => o.Name).ToList(); - dict.Add(group.Name, list); + case SingleModGroup single when setting.Value < (ulong)single.Options.Count: + dict.Add(single.Name, [single.Options[setting.AsIndex].Name]); + break; + case MultiModGroup multi: + var list = multi.Options.WithIndex().Where(p => setting.HasFlag(p.Index)).Select(p => p.Value.Name).ToList(); + dict.Add(multi.Name, list); + break; } } diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 02ae07f4..4ec2c72a 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -1,5 +1,4 @@ using Dalamud.Interface.Internal.Notifications; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; @@ -11,11 +10,12 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; /// Groups that allow all available options to be selected at once. -public sealed class MultiModGroup : IModGroup +public sealed class MultiModGroup(Mod mod) : IModGroup { public GroupType Type => GroupType.Multi; + public Mod Mod { get; set; } = mod; public string Name { get; set; } = "Group"; public string Description { get; set; } = "A non-exclusive group of settings."; public ModPriority Priority { get; set; } @@ -26,27 +26,58 @@ public sealed class MultiModGroup : IModGroup .SelectWhere(o => (o.Mod.FileData.TryGetValue(gamePath, out var file) || o.Mod.FileSwapData.TryGetValue(gamePath, out file), file)) .FirstOrDefault(); - public SubMod this[Index idx] - => PrioritizedOptions[idx].Mod; + public int AddOption(Mod mod, string name, string description = "") + { + var groupIdx = mod.Groups.IndexOf(this); + if (groupIdx < 0) + return -1; + + var subMod = new SubMod(mod, this) + { + Name = name, + Description = description, + }; + PrioritizedOptions.Add((subMod, ModPriority.Default)); + return PrioritizedOptions.Count - 1; + } + + public bool ChangeOptionDescription(int optionIndex, string newDescription) + { + if (optionIndex < 0 || optionIndex >= PrioritizedOptions.Count) + return false; + + var option = PrioritizedOptions[optionIndex].Mod; + if (option.Description == newDescription) + return false; + + option.Description = newDescription; + return true; + } + + public bool ChangeOptionName(int optionIndex, string newName) + { + if (optionIndex < 0 || optionIndex >= PrioritizedOptions.Count) + return false; + + var option = PrioritizedOptions[optionIndex].Mod; + if (option.Name == newName) + return false; + + option.Name = newName; + return true; + } + + public IReadOnlyList Options + => PrioritizedOptions.Select(p => p.Mod).ToArray(); public bool IsOption - => Count > 0; - - [JsonIgnore] - public int Count - => PrioritizedOptions.Count; + => PrioritizedOptions.Count > 0; public readonly List<(SubMod Mod, ModPriority Priority)> PrioritizedOptions = []; - public IEnumerator GetEnumerator() - => PrioritizedOptions.Select(o => o.Mod).GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() - => GetEnumerator(); - public static MultiModGroup? Load(Mod mod, JObject json, int groupIdx) { - var ret = new MultiModGroup() + var ret = new MultiModGroup(mod) { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, @@ -68,8 +99,7 @@ public sealed class MultiModGroup : IModGroup break; } - var subMod = new SubMod(mod); - subMod.SetPosition(groupIdx, ret.PrioritizedOptions.Count); + var subMod = new SubMod(mod, ret); subMod.Load(mod.ModPath, child, out var priority); ret.PrioritizedOptions.Add((subMod, priority)); } @@ -85,12 +115,12 @@ public sealed class MultiModGroup : IModGroup { case GroupType.Multi: return this; case GroupType.Single: - var multi = new SingleModGroup() + var multi = new SingleModGroup(Mod) { Name = Name, Description = Description, Priority = Priority, - DefaultSettings = DefaultSettings.TurnMulti(Count), + DefaultSettings = DefaultSettings.TurnMulti(PrioritizedOptions.Count), }; multi.OptionData.AddRange(PrioritizedOptions.Select(p => p.Mod)); return multi; @@ -104,16 +134,9 @@ public sealed class MultiModGroup : IModGroup return false; DefaultSettings = DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); - UpdatePositions(Math.Min(optionIdxFrom, optionIdxTo)); return true; } - public void UpdatePositions(int from = 0) - { - foreach (var ((o, _), i) in PrioritizedOptions.WithIndex().Skip(from)) - o.SetPosition(o.GroupIdx, i); - } - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { foreach (var (option, index) in PrioritizedOptions.WithIndex().OrderByDescending(o => o.Value.Priority)) @@ -124,5 +147,12 @@ public sealed class MultiModGroup : IModGroup } public Setting FixSetting(Setting setting) - => new(setting.Value & ((1ul << Count) - 1)); + => new(setting.Value & ((1ul << PrioritizedOptions.Count) - 1)); + + /// Create a group without a mod only for saving it in the creator. + internal static MultiModGroup CreateForSaving(string name) + => new(null!) + { + Name = name, + }; } diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index b854d2b1..994a1f96 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -1,4 +1,3 @@ -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Filesystem; @@ -9,11 +8,12 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; /// Groups that allow only one of their available options to be selected. -public sealed class SingleModGroup : IModGroup +public sealed class SingleModGroup(Mod mod) : IModGroup { public GroupType Type => GroupType.Single; + public Mod Mod { get; set; } = mod; public string Name { get; set; } = "Option"; public string Description { get; set; } = "A mutually exclusive group of settings."; public ModPriority Priority { get; set; } @@ -26,26 +26,53 @@ public sealed class SingleModGroup : IModGroup .SelectWhere(m => (m.FileData.TryGetValue(gamePath, out var file) || m.FileSwapData.TryGetValue(gamePath, out file), file)) .FirstOrDefault(); - public SubMod this[Index idx] - => OptionData[idx]; + public int AddOption(Mod mod, string name, string description = "") + { + var subMod = new SubMod(mod, this) + { + Name = name, + Description = description, + }; + OptionData.Add(subMod); + return OptionData.Count - 1; + } + + public bool ChangeOptionDescription(int optionIndex, string newDescription) + { + if (optionIndex < 0 || optionIndex >= OptionData.Count) + return false; + + var option = OptionData[optionIndex]; + if (option.Description == newDescription) + return false; + + option.Description = newDescription; + return true; + } + + public bool ChangeOptionName(int optionIndex, string newName) + { + if (optionIndex < 0 || optionIndex >= OptionData.Count) + return false; + + var option = OptionData[optionIndex]; + if (option.Name == newName) + return false; + + option.Name = newName; + return true; + } + + public IReadOnlyList Options + => OptionData; public bool IsOption - => Count > 1; - - [JsonIgnore] - public int Count - => OptionData.Count; - - public IEnumerator GetEnumerator() - => OptionData.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() - => GetEnumerator(); + => OptionData.Count > 1; public static SingleModGroup? Load(Mod mod, JObject json, int groupIdx) { var options = json["Options"]; - var ret = new SingleModGroup + var ret = new SingleModGroup(mod) { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, @@ -58,8 +85,7 @@ public sealed class SingleModGroup : IModGroup if (options != null) foreach (var child in options.Children()) { - var subMod = new SubMod(mod); - subMod.SetPosition(groupIdx, ret.OptionData.Count); + var subMod = new SubMod(mod, ret); subMod.Load(mod.ModPath, child, out _); ret.OptionData.Add(subMod); } @@ -74,7 +100,7 @@ public sealed class SingleModGroup : IModGroup { case GroupType.Single: return this; case GroupType.Multi: - var multi = new MultiModGroup() + var multi = new MultiModGroup(Mod) { Name = Name, Description = Description, @@ -108,19 +134,19 @@ public sealed class SingleModGroup : IModGroup DefaultSettings = Setting.Single(currentIndex + 1); } - UpdatePositions(Math.Min(optionIdxFrom, optionIdxTo)); return true; } - public void UpdatePositions(int from = 0) - { - foreach (var (o, i) in OptionData.WithIndex().Skip(from)) - o.SetPosition(o.GroupIdx, i); - } - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) - => this[setting.AsIndex].AddData(redirections, manipulations); + => OptionData[setting.AsIndex].AddData(redirections, manipulations); public Setting FixSetting(Setting setting) - => Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(Count - 1))); + => OptionData.Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(OptionData.Count - 1))); + + /// Create a group without a mod only for saving it in the creator. + internal static SingleModGroup CreateForSaving(string name) + => new(null!) + { + Name = name, + }; } diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs index 386910e5..bc93fcc4 100644 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -1,11 +1,62 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using OtterGui; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; +public class SingleSubMod(Mod mod, SingleModGroup group) : IModOption, IModDataContainer +{ + internal readonly Mod Mod = mod; + internal readonly SingleModGroup Group = group; + + public string Name { get; set; } = "Option"; + + public string FullName + => $"{Group.Name}: {Name}"; + + public string Description { get; set; } = string.Empty; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; +} + +public class MultiSubMod(Mod mod, MultiModGroup group) : IModOption, IModDataContainer +{ + internal readonly Mod Mod = mod; + internal readonly MultiModGroup Group = group; + + public string Name { get; set; } = "Option"; + + public string FullName + => $"{Group.Name}: {Name}"; + + public string Description { get; set; } = string.Empty; + public ModPriority Priority { get; set; } = ModPriority.Default; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; +} + +public class DefaultSubMod(IMod mod) : IModDataContainer +{ + public string FullName + => "Default Option"; + + public string Description + => string.Empty; + + internal readonly IMod Mod = mod; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; +} + /// /// A sub mod is a collection of /// - file replacements @@ -16,21 +67,51 @@ namespace Penumbra.Mods.Subclasses; /// Nothing is checked for existence or validity when loading. /// Objects are also not checked for uniqueness, the first appearance of a game path or meta path decides. /// -public sealed class SubMod +public sealed class SubMod(IMod mod, IModGroup group) : IModOption { public string Name { get; set; } = "Default"; public string FullName - => GroupIdx < 0 ? "Default Option" : $"{ParentMod.Groups[GroupIdx].Name}: {Name}"; + => Group == null ? "Default Option" : $"{Group.Name}: {Name}"; public string Description { get; set; } = string.Empty; - internal IMod ParentMod { get; private init; } - internal int GroupIdx { get; private set; } - internal int OptionIdx { get; private set; } + internal readonly IMod Mod = mod; + internal readonly IModGroup? Group = group; + internal (int GroupIdx, int OptionIdx) GetIndices() + { + if (IsDefault) + return (-1, 0); + + var groupIdx = Mod.Groups.IndexOf(Group); + if (groupIdx < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} is not contained in Mod {Mod.Name}."); + + return (groupIdx, GetOptionIndex()); + } + + private int GetOptionIndex() + { + var optionIndex = Group switch + { + null => 0, + SingleModGroup single => single.OptionData.IndexOf(this), + MultiModGroup multi => multi.PrioritizedOptions.IndexOf(p => p.Mod == this), + _ => throw new Exception($"Group {Group.Name} from SubMod {Name} has unknown type {typeof(Group)}"), + }; + if (optionIndex < 0) + throw new Exception($"Group {Group!.Name} from SubMod {Name} does not contain this SubMod."); + + return optionIndex; + } + + public static SubMod CreateDefault(IMod mod) + => new(mod, null!); + + [MemberNotNullWhen(false, nameof(Group))] public bool IsDefault - => GroupIdx < 0; + => Group == null; public void AddData(Dictionary redirections, HashSet manipulations) { @@ -46,9 +127,6 @@ public sealed class SubMod public Dictionary FileSwapData = []; public HashSet ManipulationData = []; - public SubMod(IMod parentMod) - => ParentMod = parentMod; - public IReadOnlyDictionary Files => FileData; @@ -58,12 +136,6 @@ public sealed class SubMod public IReadOnlySet Manipulations => ManipulationData; - public void SetPosition(int groupIdx, int optionIdx) - { - GroupIdx = groupIdx; - OptionIdx = optionIdx; - } - public void Load(DirectoryInfo basePath, JToken json, out ModPriority priority) { FileData.Clear(); @@ -116,6 +188,14 @@ public sealed class SubMod } } + /// Create a sub mod without a mod or group only for saving it in the creator. + internal static SubMod CreateForSaving(string name) + => new(null!, null!) + { + Name = name, + }; + + public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, SubMod mod, DirectoryInfo basePath, ModPriority? priority) { j.WriteStartObject(); diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 41c1211f..a599b3bb 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -49,7 +49,7 @@ public class TemporaryMod : IMod => [Default]; public TemporaryMod() - => Default = new SubMod(this); + => Default = SubMod.CreateDefault(this); public void SetFile(Utf8GamePath gamePath, FullPath fullPath) => Default.FileData[gamePath] = fullPath; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 7b5ce2dc..5125a5b2 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -253,7 +253,7 @@ public class ItemSwapTab : IDisposable, ITab _subModValid = _mod != null && _newGroupName.Length > 0 && _newOptionName.Length > 0 - && (_selectedGroup?.All(o => o.Name != _newOptionName) ?? true); + && (_selectedGroup?.Options.All(o => o.Name != _newOptionName) ?? true); } private void CreateMod() @@ -275,7 +275,7 @@ public class ItemSwapTab : IDisposable, ITab var groupCreated = false; var dirCreated = false; - var optionCreated = false; + var optionCreated = -1; DirectoryInfo? optionFolderName = null; try { @@ -294,14 +294,17 @@ public class ItemSwapTab : IDisposable, ITab groupCreated = true; } - _modManager.OptionEditor.AddOption(_mod, _mod.Groups.IndexOf(_selectedGroup), _newOptionName); - optionCreated = true; + var optionIdx = _modManager.OptionEditor.AddOption(_mod, _mod.Groups.IndexOf(_selectedGroup), _newOptionName); + if (optionIdx < 0) + throw new Exception($"Failure creating mod option."); + + optionCreated = optionIdx; optionFolderName = Directory.CreateDirectory(optionFolderName.FullName); dirCreated = true; if (!_swapData.WriteMod(_modManager, _mod, _useFileSwaps ? ItemSwapContainer.WriteType.UseSwaps : ItemSwapContainer.WriteType.NoSwaps, optionFolderName, - _mod.Groups.IndexOf(_selectedGroup), _selectedGroup.Count - 1)) + _mod.Groups.IndexOf(_selectedGroup), optionIdx)) throw new Exception("Failure writing files for mod swap."); } } @@ -310,8 +313,8 @@ public class ItemSwapTab : IDisposable, ITab Penumbra.Messager.NotificationMessage(e, "Could not create new Swap Option.", NotificationType.Error, false); try { - if (optionCreated && _selectedGroup != null) - _modManager.OptionEditor.DeleteOption(_mod, _mod.Groups.IndexOf(_selectedGroup), _selectedGroup.Count - 1); + if (optionCreated >= 0 && _selectedGroup != null) + _modManager.OptionEditor.DeleteOption(_mod, _mod.Groups.IndexOf(_selectedGroup), optionCreated); if (groupCreated) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index a70da628..3f5f6c37 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -78,7 +78,10 @@ public partial class ModEditWindow : Window, IDisposable } public void ChangeOption(SubMod? subMod) - => _editor.LoadOption(subMod?.GroupIdx ?? -1, subMod?.OptionIdx ?? 0); + { + var (groupIdx, optionIdx) = subMod?.GetIndices() ?? (-1, 0); + _editor.LoadOption(groupIdx, optionIdx); + } public void UpdateModels() { @@ -428,7 +431,8 @@ public partial class ModEditWindow : Window, IDisposable using var id = ImRaii.PushId(idx); if (ImGui.Selectable(option.FullName, option == _editor.Option)) { - _editor.LoadOption(option.GroupIdx, option.OptionIdx); + var (groupIdx, optionIdx) = option.GetIndices(); + _editor.LoadOption(groupIdx, optionIdx); ret = true; } } @@ -565,7 +569,7 @@ public partial class ModEditWindow : Window, IDisposable } if (Mod != null) - foreach (var option in Mod.Groups.SelectMany(g => g).Append(Mod.Default)) + foreach (var option in Mod.AllSubMods) { foreach (var path in option.Files.Keys) { diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index 1df814da..c34c7ef0 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -71,7 +71,7 @@ public class ModMergeTab(ModMerger modMerger) color = color == Colors.DiscordColor ? Colors.DiscordColor - : group == null || group.Any(o => o.Name == modMerger.OptionName) + : group == null || group.Options.Any(o => o.Name == modMerger.OptionName) ? Colors.PressEnterWarningBg : Colors.DiscordColor; c.Push(ImGuiCol.Border, color); @@ -184,18 +184,26 @@ public class ModMergeTab(ModMerger modMerger) else { ImGuiUtil.DrawTableColumn(option.Name); - var group = option.ParentMod.Groups[option.GroupIdx]; + var group = option.Group; + var optionEnumerator = group switch + { + SingleModGroup single => single.OptionData, + MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), + _ => [], + }; ImGui.TableNextColumn(); ImGui.Selectable(group.Name, false); if (ImGui.BeginPopupContextItem("##groupContext")) { if (ImGui.MenuItem("Select All")) - foreach (var opt in group) - Handle((SubMod)opt, true); + // ReSharper disable once PossibleMultipleEnumeration + foreach (var opt in optionEnumerator) + Handle(opt, true); if (ImGui.MenuItem("Unselect All")) - foreach (var opt in group) - Handle((SubMod)opt, false); + // ReSharper disable once PossibleMultipleEnumeration + foreach (var opt in optionEnumerator) + Handle(opt, false); ImGui.EndPopup(); } } diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index b002dedd..0dc694d8 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -324,7 +324,7 @@ public class ModPanelEditTab( ? mod.Description : optionIdx < 0 ? mod.Groups[groupIdx].Description - : mod.Groups[groupIdx][optionIdx].Description; + : mod.Groups[groupIdx].Options[optionIdx].Description; _oldDescription = _newDescription; _mod = mod; @@ -479,17 +479,24 @@ public class ModPanelEditTab( ImGui.TableSetupColumn("delete", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); ImGui.TableSetupColumn("priority", ImGuiTableColumnFlags.WidthFixed, 50 * UiHelpers.Scale); - var group = panel._mod.Groups[groupIdx]; - for (var optionIdx = 0; optionIdx < group.Count; ++optionIdx) - EditOption(panel, group, groupIdx, optionIdx); - + switch (panel._mod.Groups[groupIdx]) + { + case SingleModGroup single: + for (var optionIdx = 0; optionIdx < single.OptionData.Count; ++optionIdx) + EditOption(panel, single, groupIdx, optionIdx); + break; + case MultiModGroup multi: + for (var optionIdx = 0; optionIdx < multi.PrioritizedOptions.Count; ++optionIdx) + EditOption(panel, multi, groupIdx, optionIdx); + break; + } DrawNewOption(panel, groupIdx, UiHelpers.IconButtonSize); } /// Draw a line for a single option. private static void EditOption(ModPanelEditTab panel, IModGroup group, int groupIdx, int optionIdx) { - var option = group[optionIdx]; + var option = group.Options[optionIdx]; using var id = ImRaii.PushId(optionIdx); ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); @@ -547,10 +554,16 @@ public class ModPanelEditTab( { var mod = panel._mod; var group = mod.Groups[groupIdx]; + var count = group switch + { + SingleModGroup single => single.OptionData.Count, + MultiModGroup multi => multi.PrioritizedOptions.Count, + _ => throw new Exception($"Dragging options to an option group of type {group.GetType()} is not supported."), + }; ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); - ImGui.Selectable($"Option #{group.Count + 1}"); - Target(panel, group, groupIdx, group.Count); + ImGui.Selectable($"Option #{count + 1}"); + Target(panel, group, groupIdx, count); ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); @@ -562,7 +575,7 @@ public class ModPanelEditTab( } ImGui.TableNextColumn(); - var canAddGroup = mod.Groups[groupIdx].Type != GroupType.Multi || mod.Groups[groupIdx].Count < IModGroup.MaxMultiOptions; + var canAddGroup = mod.Groups[groupIdx].Type != GroupType.Multi || count < IModGroup.MaxMultiOptions; var validName = _newOptionName.Length > 0 && _newOptionNameIdx == groupIdx; var tt = canAddGroup ? validName ? "Add a new option to this group." : "Please enter a name for the new option." @@ -588,7 +601,7 @@ public class ModPanelEditTab( _dragDropOptionIdx = optionIdx; } - ImGui.TextUnformatted($"Dragging option {group[optionIdx].Name} from group {group.Name}..."); + ImGui.TextUnformatted($"Dragging option {group.Options[optionIdx].Name} from group {group.Name}..."); } private static void Target(ModPanelEditTab panel, IModGroup group, int groupIdx, int optionIdx) @@ -611,12 +624,17 @@ public class ModPanelEditTab( var sourceGroupIdx = _dragDropGroupIdx; var sourceOption = _dragDropOptionIdx; var sourceGroup = panel._mod.Groups[sourceGroupIdx]; - var currentCount = group.Count; - var option = sourceGroup[sourceOption]; - var priority = sourceGroup switch + var currentCount = group switch { - MultiModGroup multi => multi.PrioritizedOptions[_dragDropOptionIdx].Priority, - _ => ModPriority.Default, + SingleModGroup single => single.OptionData.Count, + MultiModGroup multi => multi.PrioritizedOptions.Count, + _ => throw new Exception($"Dragging options to an option group of type {group.GetType()} is not supported."), + }; + var (option, priority) = sourceGroup switch + { + SingleModGroup single => (single.OptionData[_dragDropOptionIdx], ModPriority.Default), + MultiModGroup multi => multi.PrioritizedOptions[_dragDropOptionIdx], + _ => throw new Exception($"Dragging options from an option group of type {sourceGroup.GetType()} is not supported."), }; panel._delayedActions.Enqueue(() => { @@ -651,7 +669,7 @@ public class ModPanelEditTab( if (ImGui.Selectable(GroupTypeName(GroupType.Single), group.Type == GroupType.Single)) _modManager.OptionEditor.ChangeModGroupType(_mod, groupIdx, GroupType.Single); - var canSwitchToMulti = group.Count <= IModGroup.MaxMultiOptions; + var canSwitchToMulti = group.Options.Count <= IModGroup.MaxMultiOptions; using var style = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f, !canSwitchToMulti); if (ImGui.Selectable(GroupTypeName(GroupType.Multi), group.Type == GroupType.Multi) && canSwitchToMulti) _modManager.OptionEditor.ChangeModGroupType(_mod, groupIdx, GroupType.Multi); diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 1107aa20..cb76088c 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -75,7 +75,7 @@ public class ModPanelSettingsTab : ITab { var useDummy = true; foreach (var (group, idx) in _selector.Selected!.Groups.WithIndex() - .Where(g => g.Value.Type == GroupType.Single && g.Value.Count > _config.SingleGroupRadioMax)) + .Where(g => g.Value.Type == GroupType.Single && g.Value.Options.Count > _config.SingleGroupRadioMax)) { ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); useDummy = false; @@ -92,7 +92,7 @@ public class ModPanelSettingsTab : ITab case GroupType.Multi: DrawMultiGroup(group, idx); break; - case GroupType.Single when group.Count <= _config.SingleGroupRadioMax: + case GroupType.Single when group.Options.Count <= _config.SingleGroupRadioMax: DrawSingleGroupRadio(group, idx); break; } @@ -181,13 +181,14 @@ public class ModPanelSettingsTab : ITab using var id = ImRaii.PushId(groupIdx); var selectedOption = _empty ? group.DefaultSettings.AsIndex : _settings.Settings[groupIdx].AsIndex; ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); - using (var combo = ImRaii.Combo(string.Empty, group[selectedOption].Name)) + var options = group.Options; + using (var combo = ImRaii.Combo(string.Empty, options[selectedOption].Name)) { if (combo) - for (var idx2 = 0; idx2 < group.Count; ++idx2) + for (var idx2 = 0; idx2 < options.Count; ++idx2) { id.Push(idx2); - var option = group[idx2]; + var option = options[idx2]; if (ImGui.Selectable(option.Name, idx2 == selectedOption)) _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, Setting.Single(idx2)); @@ -213,18 +214,18 @@ public class ModPanelSettingsTab : ITab using var id = ImRaii.PushId(groupIdx); var selectedOption = _empty ? group.DefaultSettings.AsIndex : _settings.Settings[groupIdx].AsIndex; var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - - DrawCollapseHandling(group, minWidth, DrawOptions); + var options = group.Options; + DrawCollapseHandling(options, minWidth, DrawOptions); Widget.EndFramedGroup(); return; void DrawOptions() { - for (var idx = 0; idx < group.Count; ++idx) + for (var idx = 0; idx < group.Options.Count; ++idx) { using var i = ImRaii.PushId(idx); - var option = group[idx]; + var option = options[idx]; if (ImGui.RadioButton(option.Name, selectedOption == idx)) _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, Setting.Single(idx)); @@ -239,9 +240,9 @@ public class ModPanelSettingsTab : ITab } - private void DrawCollapseHandling(IModGroup group, float minWidth, Action draw) + private void DrawCollapseHandling(IReadOnlyList options, float minWidth, Action draw) { - if (group.Count <= _config.OptionGroupCollapsibleMin) + if (options.Count <= _config.OptionGroupCollapsibleMin) { draw(); } @@ -249,8 +250,8 @@ public class ModPanelSettingsTab : ITab { var collapseId = ImGui.GetID("Collapse"); var shown = ImGui.GetStateStorage().GetBool(collapseId, true); - var buttonTextShow = $"Show {group.Count} Options"; - var buttonTextHide = $"Hide {group.Count} Options"; + var buttonTextShow = $"Show {options.Count} Options"; + var buttonTextHide = $"Hide {options.Count} Options"; var buttonWidth = Math.Max(ImGui.CalcTextSize(buttonTextShow).X, ImGui.CalcTextSize(buttonTextHide).X) + 2 * ImGui.GetStyle().FramePadding.X; minWidth = Math.Max(buttonWidth, minWidth); @@ -274,7 +275,7 @@ public class ModPanelSettingsTab : ITab } else { - var optionWidth = group.Max(o => ImGui.CalcTextSize(o.Name).X) + var optionWidth = options.Max(o => ImGui.CalcTextSize(o.Name).X) + ImGui.GetStyle().ItemInnerSpacing.X + ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X; @@ -294,8 +295,8 @@ public class ModPanelSettingsTab : ITab using var id = ImRaii.PushId(groupIdx); var flags = _empty ? group.DefaultSettings : _settings.Settings[groupIdx]; var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - - DrawCollapseHandling(group, minWidth, DrawOptions); + var options = group.Options; + DrawCollapseHandling(options, minWidth, DrawOptions); Widget.EndFramedGroup(); var label = $"##multi{groupIdx}"; @@ -307,10 +308,10 @@ public class ModPanelSettingsTab : ITab void DrawOptions() { - for (var idx = 0; idx < group.Count; ++idx) + for (var idx = 0; idx < options.Count; ++idx) { using var i = ImRaii.PushId(idx); - var option = group[idx]; + var option = options[idx]; var setting = flags.HasFlag(idx); if (ImGui.Checkbox(option.Name, ref setting)) @@ -339,7 +340,7 @@ public class ModPanelSettingsTab : ITab ImGui.Separator(); if (ImGui.Selectable("Enable All")) _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, - Setting.AllBits(group.Count)); + Setting.AllBits(group.Options.Count)); if (ImGui.Selectable("Disable All")) _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, Setting.Zero); From 6b1743b776da300fbe1b80a16e662b66ea519a42 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 24 Apr 2024 23:04:04 +0200 Subject: [PATCH 0575/1381] This sucks so hard... --- Penumbra/Api/Api/ModSettingsApi.cs | 2 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 6 +- Penumbra/Meta/MetaFileManager.cs | 14 +- Penumbra/Mods/Editor/DuplicateManager.cs | 6 +- Penumbra/Mods/Editor/FileRegistry.cs | 12 +- Penumbra/Mods/Editor/ModEditor.cs | 63 +-- Penumbra/Mods/Editor/ModFileCollection.cs | 16 +- Penumbra/Mods/Editor/ModFileEditor.cs | 22 +- Penumbra/Mods/Editor/ModMerger.cs | 79 ++- Penumbra/Mods/Editor/ModMetaEditor.cs | 4 +- Penumbra/Mods/Editor/ModNormalizer.cs | 38 +- Penumbra/Mods/Editor/ModSwapEditor.cs | 2 +- Penumbra/Mods/Manager/ModCacheManager.cs | 29 +- Penumbra/Mods/Manager/ModMigration.cs | 39 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 144 +++--- Penumbra/Mods/Mod.cs | 19 +- Penumbra/Mods/ModCreator.cs | 41 +- Penumbra/Mods/Subclasses/IModDataContainer.cs | 48 ++ Penumbra/Mods/Subclasses/IModGroup.cs | 126 +++-- Penumbra/Mods/Subclasses/IModOption.cs | 2 + Penumbra/Mods/Subclasses/MultiModGroup.cs | 122 ++--- Penumbra/Mods/Subclasses/SingleModGroup.cs | 75 +-- Penumbra/Mods/Subclasses/SubMod.cs | 477 +++++++++++------- Penumbra/Mods/TemporaryMod.cs | 35 +- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 15 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 2 +- .../ModEditWindow.Models.MdlTab.cs | 4 +- .../ModEditWindow.QuickImport.cs | 12 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 28 +- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 33 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 28 +- Penumbra/UI/ModsTab/ModPanelTabBar.cs | 2 +- 33 files changed, 852 insertions(+), 695 deletions(-) diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 5ed26ce5..e145e027 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -201,7 +201,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable { foreach (var name in optionNames) { - var optionIdx = multi.PrioritizedOptions.IndexOf(o => o.Mod.Name == name); + var optionIdx = multi.OptionData.IndexOf(o => o.Mod.Name == name); if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 7d9388a9..b9cdda71 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -152,7 +152,7 @@ public partial class TexToolsImporter } // Iterate through all pages - var options = new List(); + var options = new List(); var groupPriority = ModPriority.Default; var groupNames = new HashSet(); foreach (var page in modList.ModPackPages) @@ -183,7 +183,7 @@ public partial class TexToolsImporter var optionFolder = ModCreator.NewSubFolderName(groupFolder, option.Name, _config.ReplaceNonAsciiOnImport) ?? new DirectoryInfo(Path.Combine(groupFolder.FullName, $"Option {i + optionIdx + 1}")); ExtractSimpleModList(optionFolder, option.ModsJsons); - options.Add(_modManager.Creator.CreateSubMod(_currentModDirectory, optionFolder, option)); + options.Add(_modManager.Creator.CreateSubMod(_currentModDirectory, optionFolder, option, new ModPriority(i))); if (option.IsChecked) defaultSettings = group.SelectionType == GroupType.Multi ? defaultSettings!.Value | Setting.Multi(i) @@ -203,7 +203,7 @@ public partial class TexToolsImporter { var option = group.OptionList[idx]; _currentOptionName = option.Name; - options.Insert(idx, SubMod.CreateForSaving(option.Name)); + options.Insert(idx, MultiSubMod.CreateForSaving(option.Name, option.Description, ModPriority.Default)); if (option.IsChecked) defaultSettings = Setting.Single(idx); } diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index b1823bd7..0e2e638b 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -50,17 +50,15 @@ public unsafe class MetaFileManager TexToolsMeta.WriteTexToolsMeta(this, mod.Default.Manipulations, mod.ModPath); foreach (var group in mod.Groups) { + if (group is not ITexToolsGroup texToolsGroup) + continue; + var dir = ModCreator.NewOptionDirectory(mod.ModPath, group.Name, Config.ReplaceNonAsciiOnImport); if (!dir.Exists) dir.Create(); - var optionEnumerator = group switch - { - SingleModGroup single => single.OptionData, - MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), - _ => [], - }; - foreach (var option in optionEnumerator) + + foreach (var option in texToolsGroup.OptionData) { var optionDir = ModCreator.NewOptionDirectory(dir, option.Name, Config.ReplaceNonAsciiOnImport); if (!optionDir.Exists) @@ -99,7 +97,7 @@ public unsafe class MetaFileManager return; ResidentResources.Reload(); - if (collection?._cache == null) + if (collection._cache == null) CharacterUtility.ResetAll(); else collection._cache.Meta.SetFiles(); diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 938199aa..92ec58b9 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -29,7 +29,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co Worker = Task.Run(() => CheckDuplicates(filesTmp, _cancellationTokenSource.Token), _cancellationTokenSource.Token); } - public void DeleteDuplicates(ModFileCollection files, Mod mod, SubMod option, bool useModManager) + public void DeleteDuplicates(ModFileCollection files, Mod mod, IModDataContainer option, bool useModManager) { if (!Worker.IsCompleted || _duplicates.Count == 0) return; @@ -72,7 +72,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co return; - void HandleSubMod(SubMod subMod, int groupIdx, int optionIdx) + void HandleSubMod(IModDataContainer subMod, int groupIdx, int optionIdx) { var changes = false; var dict = subMod.Files.ToDictionary(kvp => kvp.Key, @@ -86,7 +86,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co } else { - subMod.FileData = dict; + subMod.Files = dict; saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); } } diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 427c58ca..44d349ce 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -5,12 +5,12 @@ namespace Penumbra.Mods.Editor; public class FileRegistry : IEquatable { - public readonly List<(SubMod, Utf8GamePath)> SubModUsage = []; - public FullPath File { get; private init; } - public Utf8RelPath RelPath { get; private init; } - public long FileSize { get; private init; } - public int CurrentUsage; - public bool IsOnPlayer; + public readonly List<(IModDataContainer, Utf8GamePath)> SubModUsage = []; + public FullPath File { get; private init; } + public Utf8RelPath RelPath { get; private init; } + public long FileSize { get; private init; } + public int CurrentUsage; + public bool IsOnPlayer; public static bool FromFile(DirectoryInfo modPath, FileInfo file, [NotNullWhen(true)] out FileRegistry? registry) { diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index 0a96e0fd..1118f890 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -1,4 +1,3 @@ -using System; using OtterGui; using OtterGui.Compression; using Penumbra.Mods.Subclasses; @@ -25,20 +24,20 @@ public class ModEditor( public readonly MdlMaterialEditor MdlMaterialEditor = mdlMaterialEditor; public readonly FileCompactor Compactor = compactor; - public Mod? Mod { get; private set; } - public int GroupIdx { get; private set; } - public int OptionIdx { get; private set; } + public Mod? Mod { get; private set; } + public int GroupIdx { get; private set; } + public int DataIdx { get; private set; } - public IModGroup? Group { get; private set; } - public SubMod? Option { get; private set; } + public IModGroup? Group { get; private set; } + public IModDataContainer? Option { get; private set; } public void LoadMod(Mod mod) => LoadMod(mod, -1, 0); - public void LoadMod(Mod mod, int groupIdx, int optionIdx) + public void LoadMod(Mod mod, int groupIdx, int dataIdx) { Mod = mod; - LoadOption(groupIdx, optionIdx, true); + LoadOption(groupIdx, dataIdx, true); Files.UpdateAll(mod, Option!); SwapEditor.Revert(Option!); MetaEditor.Load(Mod!, Option!); @@ -46,9 +45,9 @@ public class ModEditor( MdlMaterialEditor.ScanModels(Mod!); } - public void LoadOption(int groupIdx, int optionIdx) + public void LoadOption(int groupIdx, int dataIdx) { - LoadOption(groupIdx, optionIdx, true); + LoadOption(groupIdx, dataIdx, true); SwapEditor.Revert(Option!); Files.UpdatePaths(Mod!, Option!); MetaEditor.Load(Mod!, Option!); @@ -57,44 +56,38 @@ public class ModEditor( } /// Load the correct option by indices for the currently loaded mod if possible, unload if not. - private void LoadOption(int groupIdx, int optionIdx, bool message) + private void LoadOption(int groupIdx, int dataIdx, bool message) { if (Mod != null && Mod.Groups.Count > groupIdx) { - if (groupIdx == -1 && optionIdx == 0) + if (groupIdx == -1 && dataIdx == 0) { - Group = null; - Option = Mod.Default; - GroupIdx = groupIdx; - OptionIdx = optionIdx; + Group = null; + Option = Mod.Default; + GroupIdx = groupIdx; + DataIdx = dataIdx; return; } if (groupIdx >= 0) { Group = Mod.Groups[groupIdx]; - switch(Group) + if (dataIdx >= 0 && dataIdx < Group.DataContainers.Count) { - case SingleModGroup single when optionIdx >= 0 && optionIdx < single.OptionData.Count: - Option = single.OptionData[optionIdx]; - GroupIdx = groupIdx; - OptionIdx = optionIdx; - return; - case MultiModGroup multi when optionIdx >= 0 && optionIdx < multi.PrioritizedOptions.Count: - Option = multi.PrioritizedOptions[optionIdx].Mod; - GroupIdx = groupIdx; - OptionIdx = optionIdx; - return; + Option = Group.DataContainers[dataIdx]; + GroupIdx = groupIdx; + DataIdx = dataIdx; + return; } } } - Group = null; - Option = Mod?.Default; - GroupIdx = -1; - OptionIdx = 0; + Group = null; + Option = Mod?.Default; + GroupIdx = -1; + DataIdx = 0; if (message) - Penumbra.Log.Error($"Loading invalid option {groupIdx} {optionIdx} for Mod {Mod?.Name ?? "Unknown"}."); + Penumbra.Log.Error($"Loading invalid option {groupIdx} {dataIdx} for Mod {Mod?.Name ?? "Unknown"}."); } public void Clear() @@ -111,7 +104,7 @@ public class ModEditor( => Clear(); /// Apply a option action to all available option in a mod, including the default option. - public static void ApplyToAllOptions(Mod mod, Action action) + public static void ApplyToAllOptions(Mod mod, Action action) { action(mod.Default, -1, 0); foreach (var (group, groupIdx) in mod.Groups.WithIndex()) @@ -123,8 +116,8 @@ public class ModEditor( action(single.OptionData[optionIdx], groupIdx, optionIdx); break; case MultiModGroup multi: - for (var optionIdx = 0; optionIdx < multi.PrioritizedOptions.Count; ++optionIdx) - action(multi.PrioritizedOptions[optionIdx].Mod, groupIdx, optionIdx); + for (var optionIdx = 0; optionIdx < multi.OptionData.Count; ++optionIdx) + action(multi.OptionData[optionIdx], groupIdx, optionIdx); break; } } diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 9dd78217..ede35914 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -38,13 +38,13 @@ public class ModFileCollection : IDisposable public bool Ready { get; private set; } = true; - public void UpdateAll(Mod mod, SubMod option) + public void UpdateAll(Mod mod, IModDataContainer option) { UpdateFiles(mod, new CancellationToken()); UpdatePaths(mod, option, false, new CancellationToken()); } - public void UpdatePaths(Mod mod, SubMod option) + public void UpdatePaths(Mod mod, IModDataContainer option) => UpdatePaths(mod, option, true, new CancellationToken()); public void Clear() @@ -59,7 +59,7 @@ public class ModFileCollection : IDisposable public void ClearMissingFiles() => _missing.Clear(); - public void RemoveUsedPath(SubMod option, FileRegistry? file, Utf8GamePath gamePath) + public void RemoveUsedPath(IModDataContainer option, FileRegistry? file, Utf8GamePath gamePath) { _usedPaths.Remove(gamePath); if (file != null) @@ -69,10 +69,10 @@ public class ModFileCollection : IDisposable } } - public void RemoveUsedPath(SubMod option, FullPath file, Utf8GamePath gamePath) + public void RemoveUsedPath(IModDataContainer option, FullPath file, Utf8GamePath gamePath) => RemoveUsedPath(option, _available.FirstOrDefault(f => f.File.Equals(file)), gamePath); - public void AddUsedPath(SubMod option, FileRegistry? file, Utf8GamePath gamePath) + public void AddUsedPath(IModDataContainer option, FileRegistry? file, Utf8GamePath gamePath) { _usedPaths.Add(gamePath); if (file == null) @@ -82,7 +82,7 @@ public class ModFileCollection : IDisposable file.SubModUsage.Add((option, gamePath)); } - public void AddUsedPath(SubMod option, FullPath file, Utf8GamePath gamePath) + public void AddUsedPath(IModDataContainer option, FullPath file, Utf8GamePath gamePath) => AddUsedPath(option, _available.FirstOrDefault(f => f.File.Equals(file)), gamePath); public void ChangeUsedPath(FileRegistry file, int pathIdx, Utf8GamePath gamePath) @@ -154,14 +154,14 @@ public class ModFileCollection : IDisposable _usedPaths.Clear(); } - private void UpdatePaths(Mod mod, SubMod option, bool clearRegistries, CancellationToken tok) + private void UpdatePaths(Mod mod, IModDataContainer option, bool clearRegistries, CancellationToken tok) { tok.ThrowIfCancellationRequested(); ClearPaths(clearRegistries, tok); tok.ThrowIfCancellationRequested(); - foreach (var subMod in mod.AllSubMods) + foreach (var subMod in mod.AllDataContainers) { foreach (var (gamePath, file) in subMod.Files) { diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 51615b05..11e35334 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -14,7 +14,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu Changes = false; } - public int Apply(Mod mod, SubMod option) + public int Apply(Mod mod, IModDataContainer option) { var dict = new Dictionary(); var num = 0; @@ -24,23 +24,23 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu num += dict.TryAdd(path.Item2, file.File) ? 0 : 1; } - var (groupIdx, optionIdx) = option.GetIndices(); - modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict); + var (groupIdx, dataIdx) = option.GetDataIndices(); + modManager.OptionEditor.OptionSetFiles(mod, groupIdx, dataIdx, dict); files.UpdatePaths(mod, option); Changes = false; return num; } - public void Revert(Mod mod, SubMod option) + public void Revert(Mod mod, IModDataContainer option) { files.UpdateAll(mod, option); Changes = false; } /// Remove all path redirections where the pointed-to file does not exist. - public void RemoveMissingPaths(Mod mod, SubMod option) + public void RemoveMissingPaths(Mod mod, IModDataContainer option) { - void HandleSubMod(SubMod subMod, int groupIdx, int optionIdx) + void HandleSubMod(IModDataContainer subMod, int groupIdx, int optionIdx) { var newDict = subMod.Files.Where(kvp => CheckAgainstMissing(mod, subMod, kvp.Value, kvp.Key, subMod == option)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); @@ -62,7 +62,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu /// If path is empty, it will be deleted instead. /// If pathIdx is equal to the total number of paths, path will be added, otherwise replaced. /// - public bool SetGamePath(SubMod option, int fileIdx, int pathIdx, Utf8GamePath path) + public bool SetGamePath(IModDataContainer option, int fileIdx, int pathIdx, Utf8GamePath path) { if (!CanAddGamePath(path) || fileIdx < 0 || fileIdx > files.Available.Count) return false; @@ -85,7 +85,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu /// Transform a set of files to the appropriate game paths with the given number of folders skipped, /// and add them to the given option. /// - public int AddPathsToSelected(SubMod option, IEnumerable files1, int skipFolders = 0) + public int AddPathsToSelected(IModDataContainer option, IEnumerable files1, int skipFolders = 0) { var failed = 0; foreach (var file in files1) @@ -112,7 +112,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu } /// Remove all paths in the current option from the given files. - public void RemovePathsFromSelected(SubMod option, IEnumerable files1) + public void RemovePathsFromSelected(IModDataContainer option, IEnumerable files1) { foreach (var file in files1) { @@ -130,7 +130,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu } /// Delete all given files from your filesystem - public void DeleteFiles(Mod mod, SubMod option, IEnumerable files1) + public void DeleteFiles(Mod mod, IModDataContainer option, IEnumerable files1) { var deletions = 0; foreach (var file in files1) @@ -156,7 +156,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu } - private bool CheckAgainstMissing(Mod mod, SubMod option, FullPath file, Utf8GamePath key, bool removeUsed) + private bool CheckAgainstMissing(Mod mod, IModDataContainer option, FullPath file, Utf8GamePath key, bool removeUsed) { if (!files.Missing.Contains(file)) return true; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 74e9007c..541c84ae 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -1,6 +1,5 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; -using ImGuizmoNET; using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; @@ -33,9 +32,9 @@ public class ModMerger : IDisposable private readonly Dictionary _fileToFile = []; private readonly HashSet _createdDirectories = []; private readonly HashSet _createdGroups = []; - private readonly HashSet _createdOptions = []; + private readonly HashSet _createdOptions = []; - public readonly HashSet SelectedOptions = []; + public readonly HashSet SelectedOptions = []; public readonly IReadOnlyList Warnings = []; public Exception? Error { get; private set; } @@ -94,7 +93,7 @@ public class ModMerger : IDisposable private void MergeWithOptions() { - MergeIntoOption(Enumerable.Repeat(MergeFromMod!.Default, 1), MergeToMod!.Default, false); + MergeIntoOption([MergeFromMod!.Default], MergeToMod!.Default, false); foreach (var originalGroup in MergeFromMod!.Groups) { @@ -105,20 +104,13 @@ public class ModMerger : IDisposable ((List)Warnings).Add( $"The merged group {group.Name} already existed, but has a different type {group.Type} than the original group of type {originalGroup.Type}."); - var optionEnumerator = group switch + foreach (var originalOption in group.DataContainers) { - SingleModGroup single => single.OptionData, - MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), - _ => [], - }; - - foreach (var originalOption in optionEnumerator) - { - var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, originalOption.Name); + var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, originalOption.GetName()); if (optionCreated) { - _createdOptions.Add(option); - MergeIntoOption(Enumerable.Repeat(originalOption, 1), option, false); + _createdOptions.Add((IModDataOption)option); + MergeIntoOption([originalOption], (IModDataOption)option, false); } else { @@ -136,7 +128,7 @@ public class ModMerger : IDisposable if (groupName.Length == 0 && optionName.Length == 0) { CopyFiles(MergeToMod!.ModPath); - MergeIntoOption(MergeFromMod!.AllSubMods.Reverse(), MergeToMod!.Default, true); + MergeIntoOption(MergeFromMod!.AllDataContainers.Reverse(), MergeToMod!.Default, true); } else if (groupName.Length * optionName.Length == 0) { @@ -148,7 +140,7 @@ public class ModMerger : IDisposable _createdGroups.Add(groupIdx); var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName, SaveType.None); if (optionCreated) - _createdOptions.Add(option); + _createdOptions.Add((IModDataOption)option); var dir = ModCreator.NewOptionDirectory(MergeToMod!.ModPath, groupName, _config.ReplaceNonAsciiOnImport); if (!dir.Exists) _createdDirectories.Add(dir.FullName); @@ -156,14 +148,14 @@ public class ModMerger : IDisposable if (!dir.Exists) _createdDirectories.Add(dir.FullName); CopyFiles(dir); - MergeIntoOption(MergeFromMod!.AllSubMods.Reverse(), option, true); + MergeIntoOption(MergeFromMod!.AllDataContainers.Reverse(), (IModDataOption)option, true); } - private void MergeIntoOption(IEnumerable mergeOptions, SubMod option, bool fromFileToFile) + private void MergeIntoOption(IEnumerable mergeOptions, IModDataContainer option, bool fromFileToFile) { - var redirections = option.FileData.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - var swaps = option.FileSwapData.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - var manips = option.ManipulationData.ToHashSet(); + var redirections = option.Files.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + var swaps = option.FileSwaps.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + var manips = option.Manipulations.ToHashSet(); foreach (var originalOption in mergeOptions) { @@ -171,31 +163,31 @@ public class ModMerger : IDisposable { if (!manips.Add(manip)) throw new Exception( - $"Could not add meta manipulation {manip} from {originalOption.FullName} to {option.FullName} because another manipulation of the same data already exists in this option."); + $"Could not add meta manipulation {manip} from {originalOption.GetFullName()} to {option.GetFullName()} because another manipulation of the same data already exists in this option."); } foreach (var (swapA, swapB) in originalOption.FileSwaps) { if (!swaps.TryAdd(swapA, swapB)) throw new Exception( - $"Could not add file swap {swapB} -> {swapA} from {originalOption.FullName} to {option.FullName} because another swap of the key already exists."); + $"Could not add file swap {swapB} -> {swapA} from {originalOption.GetFullName()} to {option.GetFullName()} because another swap of the key already exists."); } foreach (var (gamePath, path) in originalOption.Files) { if (!GetFullPath(path, out var newFile)) throw new Exception( - $"Could not add file redirection {path} -> {gamePath} from {originalOption.FullName} to {option.FullName} because the file does not exist in the new mod."); + $"Could not add file redirection {path} -> {gamePath} from {originalOption.GetFullName()} to {option.GetFullName()} because the file does not exist in the new mod."); if (!redirections.TryAdd(gamePath, newFile)) throw new Exception( - $"Could not add file redirection {path} -> {gamePath} from {originalOption.FullName} to {option.FullName} because a redirection for the game path already exists."); + $"Could not add file redirection {path} -> {gamePath} from {originalOption.GetFullName()} to {option.GetFullName()} because a redirection for the game path already exists."); } } - var (groupIdx, optionIdx) = option.GetIndices(); - _editor.OptionSetFiles(MergeToMod!, groupIdx, optionIdx, redirections, SaveType.None); - _editor.OptionSetFileSwaps(MergeToMod!, groupIdx, optionIdx, swaps, SaveType.None); - _editor.OptionSetManipulations(MergeToMod!, groupIdx, optionIdx, manips, SaveType.ImmediateSync); + var (groupIdx, dataIdx) = option.GetDataIndices(); + _editor.OptionSetFiles(MergeToMod!, groupIdx, dataIdx, redirections, SaveType.None); + _editor.OptionSetFileSwaps(MergeToMod!, groupIdx, dataIdx, swaps, SaveType.None); + _editor.OptionSetManipulations(MergeToMod!, groupIdx, dataIdx, manips, SaveType.ImmediateSync); return; bool GetFullPath(FullPath input, out FullPath ret) @@ -270,30 +262,29 @@ public class ModMerger : IDisposable { var files = CopySubModFiles(mods[0], dir); _editor.OptionSetFiles(result, -1, 0, files); - _editor.OptionSetFileSwaps(result, -1, 0, mods[0].FileSwapData); - _editor.OptionSetManipulations(result, -1, 0, mods[0].ManipulationData); + _editor.OptionSetFileSwaps(result, -1, 0, mods[0].FileSwaps); + _editor.OptionSetManipulations(result, -1, 0, mods[0].Manipulations); } else { foreach (var originalOption in mods) { - if (originalOption.IsDefault) + if (originalOption.Group is not {} originalGroup) { var files = CopySubModFiles(mods[0], dir); _editor.OptionSetFiles(result, -1, 0, files); - _editor.OptionSetFileSwaps(result, -1, 0, mods[0].FileSwapData); - _editor.OptionSetManipulations(result, -1, 0, mods[0].ManipulationData); + _editor.OptionSetFileSwaps(result, -1, 0, mods[0].FileSwaps); + _editor.OptionSetManipulations(result, -1, 0, mods[0].Manipulations); } else { - var originalGroup = originalOption.Group; - var (group, groupIdx, _) = _editor.FindOrAddModGroup(result, originalGroup.Type, originalGroup.Name); - var (option, optionIdx, _) = _editor.FindOrAddOption(result, groupIdx, originalOption.Name); + var (group, groupIdx, _) = _editor.FindOrAddModGroup(result, originalGroup.Type, originalGroup.Name); + var (option, optionIdx, _) = _editor.FindOrAddOption(result, groupIdx, originalOption.GetName()); var folder = Path.Combine(dir.FullName, group.Name, option.Name); var files = CopySubModFiles(originalOption, new DirectoryInfo(folder)); _editor.OptionSetFiles(result, groupIdx, optionIdx, files); - _editor.OptionSetFileSwaps(result, groupIdx, optionIdx, originalOption.FileSwapData); - _editor.OptionSetManipulations(result, groupIdx, optionIdx, originalOption.ManipulationData); + _editor.OptionSetFileSwaps(result, groupIdx, optionIdx, originalOption.FileSwaps); + _editor.OptionSetManipulations(result, groupIdx, optionIdx, originalOption.Manipulations); } } } @@ -315,11 +306,11 @@ public class ModMerger : IDisposable } } - private static Dictionary CopySubModFiles(SubMod option, DirectoryInfo newMod) + private static Dictionary CopySubModFiles(IModDataContainer option, DirectoryInfo newMod) { - var ret = new Dictionary(option.FileData.Count); + var ret = new Dictionary(option.Files.Count); var parentPath = ((Mod)option.Mod).ModPath.FullName; - foreach (var (path, file) in option.FileData) + foreach (var (path, file) in option.Files) { var target = Path.GetRelativePath(parentPath, file.FullName); target = Path.Combine(newMod.FullName, target); @@ -348,7 +339,7 @@ public class ModMerger : IDisposable { foreach (var option in _createdOptions) { - var (groupIdx, optionIdx) = option.GetIndices(); + var (groupIdx, optionIdx) = option.GetOptionIndices(); _editor.DeleteOption(MergeToMod!, groupIdx, optionIdx); Penumbra.Log.Verbose($"[Merger] Removed option {option.FullName}."); } diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index a6218c6f..88e48f0f 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -103,7 +103,7 @@ public class ModMetaEditor(ModManager modManager) Changes = true; } - public void Load(Mod mod, SubMod currentOption) + public void Load(Mod mod, IModDataContainer currentOption) { OtherImcCount = 0; OtherEqpCount = 0; @@ -111,7 +111,7 @@ public class ModMetaEditor(ModManager modManager) OtherGmpCount = 0; OtherEstCount = 0; OtherRspCount = 0; - foreach (var option in mod.AllSubMods) + foreach (var option in mod.AllDataContainers) { if (option == currentOption) continue; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 9698fdcb..db00a1c7 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,3 +1,4 @@ +using System; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; @@ -168,27 +169,11 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) { var groupDir = ModCreator.CreateModFolder(directory, group.Name, _config.ReplaceNonAsciiOnImport, true); - switch (group) - { - case SingleModGroup single: - _redirections[groupIdx + 1].EnsureCapacity(single.OptionData.Count); - for (var i = _redirections[groupIdx + 1].Count; i < single.OptionData.Count; ++i) - _redirections[groupIdx + 1].Add([]); - - foreach (var (option, optionIdx) in single.OptionData.WithIndex()) - HandleSubMod(groupDir, option, _redirections[groupIdx + 1][optionIdx]); - - break; - case MultiModGroup multi: - _redirections[groupIdx + 1].EnsureCapacity(multi.PrioritizedOptions.Count); - for (var i = _redirections[groupIdx + 1].Count; i < multi.PrioritizedOptions.Count; ++i) - _redirections[groupIdx + 1].Add([]); - - foreach (var ((option, _), optionIdx) in multi.PrioritizedOptions.WithIndex()) - HandleSubMod(groupDir, option, _redirections[groupIdx + 1][optionIdx]); - - break; - } + _redirections[groupIdx + 1].EnsureCapacity(group.DataContainers.Count); + for (var i = _redirections[groupIdx + 1].Count; i < group.DataContainers.Count; ++i) + _redirections[groupIdx + 1].Add([]); + foreach (var (data, dataIdx) in group.DataContainers.WithIndex()) + HandleSubMod(groupDir, data, _redirections[groupIdx + 1][dataIdx]); } return true; @@ -200,13 +185,14 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) return false; - void HandleSubMod(DirectoryInfo groupDir, SubMod option, Dictionary newDict) + void HandleSubMod(DirectoryInfo groupDir, IModDataContainer option, Dictionary newDict) { - var optionDir = ModCreator.CreateModFolder(groupDir, option.Name, _config.ReplaceNonAsciiOnImport, true); + var name = option.GetName(); + var optionDir = ModCreator.CreateModFolder(groupDir, name, _config.ReplaceNonAsciiOnImport, true); newDict.Clear(); - newDict.EnsureCapacity(option.FileData.Count); - foreach (var (gamePath, fullPath) in option.FileData) + newDict.EnsureCapacity(option.Files.Count); + foreach (var (gamePath, fullPath) in option.Files) { var relPath = new Utf8RelPath(gamePath).ToString(); var newFullPath = Path.Combine(optionDir.FullName, relPath); @@ -300,7 +286,7 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) _modManager.OptionEditor.OptionSetFiles(Mod, groupIdx, optionIdx, _redirections[groupIdx + 1][optionIdx]); break; case MultiModGroup multi: - foreach (var (_, optionIdx) in multi.PrioritizedOptions.WithIndex()) + foreach (var (_, optionIdx) in multi.OptionData.WithIndex()) _modManager.OptionEditor.OptionSetFiles(Mod, groupIdx, optionIdx, _redirections[groupIdx + 1][optionIdx]); break; } diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index 0d5f05a9..64788cf3 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -11,7 +11,7 @@ public class ModSwapEditor(ModManager modManager) public IReadOnlyDictionary Swaps => _swaps; - public void Revert(SubMod option) + public void Revert(IModDataContainer option) { _swaps.SetTo(option.FileSwaps); Changes = false; diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index df243781..4f9e8648 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -176,13 +176,13 @@ public class ModCacheManager : IDisposable } private static void UpdateFileCount(Mod mod) - => mod.TotalFileCount = mod.AllSubMods.Sum(s => s.Files.Count); + => mod.TotalFileCount = mod.AllDataContainers.Sum(s => s.Files.Count); private static void UpdateSwapCount(Mod mod) - => mod.TotalSwapCount = mod.AllSubMods.Sum(s => s.FileSwaps.Count); + => mod.TotalSwapCount = mod.AllDataContainers.Sum(s => s.FileSwaps.Count); private static void UpdateMetaCount(Mod mod) - => mod.TotalManipulations = mod.AllSubMods.Sum(s => s.Manipulations.Count); + => mod.TotalManipulations = mod.AllDataContainers.Sum(s => s.Manipulations.Count); private static void UpdateHasOptions(Mod mod) => mod.HasOptions = mod.Groups.Any(o => o.IsOption); @@ -194,10 +194,10 @@ public class ModCacheManager : IDisposable { var changedItems = (SortedList)mod.ChangedItems; changedItems.Clear(); - foreach (var gamePath in mod.AllSubMods.SelectMany(m => m.Files.Keys.Concat(m.FileSwaps.Keys))) + foreach (var gamePath in mod.AllDataContainers.SelectMany(m => m.Files.Keys.Concat(m.FileSwaps.Keys))) _identifier.Identify(changedItems, gamePath.ToString()); - foreach (var manip in mod.AllSubMods.SelectMany(m => m.Manipulations)) + foreach (var manip in mod.AllDataContainers.SelectMany(m => m.Manipulations)) ComputeChangedItems(_identifier, changedItems, manip); mod.LowerChangedItemsString = string.Join("\0", mod.ChangedItems.Keys.Select(k => k.ToLowerInvariant())); @@ -211,20 +211,11 @@ public class ModCacheManager : IDisposable mod.HasOptions = false; foreach (var group in mod.Groups) { - mod.HasOptions |= group.IsOption; - var optionEnumerator = group switch - { - SingleModGroup single => single.OptionData, - MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), - _ => [], - }; - - foreach (var s in optionEnumerator) - { - mod.TotalFileCount += s.Files.Count; - mod.TotalSwapCount += s.FileSwaps.Count; - mod.TotalManipulations += s.Manipulations.Count; - } + mod.HasOptions |= group.IsOption; + var (files, swaps, manips) = group.GetCounts(); + mod.TotalFileCount += files; + mod.TotalSwapCount += swaps; + mod.TotalManipulations += manips; } } diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 9c8ced89..8c4a5674 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -71,14 +71,14 @@ public static partial class ModMigration foreach (var unusedFile in mod.FindUnusedFiles().Where(f => !seenMetaFiles.Contains(f))) { if (unusedFile.ToGamePath(mod.ModPath, out var gamePath) - && !mod.Default.FileData.TryAdd(gamePath, unusedFile)) - Penumbra.Log.Error($"Could not add {gamePath} because it already points to {mod.Default.FileData[gamePath]}."); + && !mod.Default.Files.TryAdd(gamePath, unusedFile)) + Penumbra.Log.Error($"Could not add {gamePath} because it already points to {mod.Default.Files[gamePath]}."); } - mod.Default.FileSwapData.Clear(); - mod.Default.FileSwapData.EnsureCapacity(swaps.Count); + mod.Default.FileSwaps.Clear(); + mod.Default.FileSwaps.EnsureCapacity(swaps.Count); foreach (var (gamePath, swapPath) in swaps) - mod.Default.FileSwapData.Add(gamePath, swapPath); + mod.Default.FileSwaps.Add(gamePath, swapPath); creator.IncorporateMetaChanges(mod.Default, mod.ModPath, true); foreach (var (_, index) in mod.Groups.WithIndex()) @@ -134,7 +134,7 @@ public static partial class ModMigration }; mod.Groups.Add(newMultiGroup); foreach (var option in group.Options) - newMultiGroup.PrioritizedOptions.Add((SubModFromOption(creator, mod, newMultiGroup, option, seenMetaFiles), optionPriority++)); + newMultiGroup.OptionData.Add(SubModFromOption(creator, mod, newMultiGroup, option, optionPriority++, seenMetaFiles)); break; case GroupType.Single: @@ -158,22 +158,41 @@ public static partial class ModMigration } } - private static void AddFilesToSubMod(SubMod mod, DirectoryInfo basePath, OptionV0 option, HashSet seenMetaFiles) + private static void AddFilesToSubMod(IModDataContainer mod, DirectoryInfo basePath, OptionV0 option, HashSet seenMetaFiles) { foreach (var (relPath, gamePaths) in option.OptionFiles) { var fullPath = new FullPath(basePath, relPath); foreach (var gamePath in gamePaths) - mod.FileData.TryAdd(gamePath, fullPath); + mod.Files.TryAdd(gamePath, fullPath); if (fullPath.Extension is ".meta" or ".rgsp") seenMetaFiles.Add(fullPath); } } - private static SubMod SubModFromOption(ModCreator creator, Mod mod, IModGroup group, OptionV0 option, HashSet seenMetaFiles) + private static SingleSubMod SubModFromOption(ModCreator creator, Mod mod, SingleModGroup group, OptionV0 option, + HashSet seenMetaFiles) { - var subMod = new SubMod(mod, group) { Name = option.OptionName }; + var subMod = new SingleSubMod(mod, group) + { + Name = option.OptionName, + Description = option.OptionDesc, + }; + AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); + creator.IncorporateMetaChanges(subMod, mod.ModPath, false); + return subMod; + } + + private static MultiSubMod SubModFromOption(ModCreator creator, Mod mod, MultiModGroup group, OptionV0 option, + ModPriority priority, HashSet seenMetaFiles) + { + var subMod = new MultiSubMod(mod, group) + { + Name = option.OptionName, + Description = option.OptionDesc, + Priority = priority, + }; AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); creator.IncorporateMetaChanges(subMod, mod.ModPath, false); return subMod; diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index e78b6209..4d3a5717 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -1,4 +1,3 @@ -using System.Security.AccessControl; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; @@ -179,10 +178,10 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS switch (mod.Groups[groupIdx]) { case MultiModGroup multi: - if (multi.PrioritizedOptions[optionIdx].Priority == newPriority) + if (multi.OptionData[optionIdx].Priority == newPriority) return; - multi.PrioritizedOptions[optionIdx] = (multi.PrioritizedOptions[optionIdx].Mod, newPriority); + multi.OptionData[optionIdx].Priority = newPriority; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, optionIdx, -1); return; @@ -213,70 +212,62 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Add a new empty option of the given name for the given group if it does not exist already. - public (SubMod, int, bool) FindOrAddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) + public (IModOption, int, bool) FindOrAddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) { var group = mod.Groups[groupIdx]; - switch (group) - { - case SingleModGroup single: - { - var idx = single.OptionData.IndexOf(o => o.Name == newName); - if (idx >= 0) - return (single.OptionData[idx], idx, false); + var idx = group.Options.IndexOf(o => o.Name == newName); + if (idx >= 0) + return (group.Options[idx], idx, false); - idx = single.AddOption(mod, newName); - if (idx < 0) - throw new Exception($"Could not create new option with name {newName} in {group.Name}."); + idx = group.AddOption(mod, newName); + if (idx < 0) + throw new Exception($"Could not create new option with name {newName} in {group.Name}."); - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); - return (single.OptionData[^1], single.OptionData.Count - 1, true); - } - case MultiModGroup multi: - { - var idx = multi.PrioritizedOptions.IndexOf(o => o.Mod.Name == newName); - if (idx >= 0) - return (multi.PrioritizedOptions[idx].Mod, idx, false); - - idx = multi.AddOption(mod, newName); - if (idx < 0) - throw new Exception($"Could not create new option with name {newName} in {group.Name}."); - - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); - return (multi.PrioritizedOptions[^1].Mod, multi.PrioritizedOptions.Count - 1, true); - } - } - - throw new Exception($"{nameof(FindOrAddOption)} is not supported for mod groups of type {group.GetType()}."); + saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); + return (group.Options[idx], idx, true); } - /// Add an existing option to a given group with default priority. - public void AddOption(Mod mod, int groupIdx, SubMod option) - => AddOption(mod, groupIdx, option, ModPriority.Default); - - /// Add an existing option to a given group with a given priority. - public void AddOption(Mod mod, int groupIdx, SubMod option, ModPriority priority) + /// Add an existing option to a given group. + public void AddOption(Mod mod, int groupIdx, IModOption option) { var group = mod.Groups[groupIdx]; int idx; switch (group) { - case MultiModGroup { PrioritizedOptions.Count: >= IModGroup.MaxMultiOptions }: + case MultiModGroup { OptionData.Count: >= IModGroup.MaxMultiOptions }: Penumbra.Log.Error( $"Could not add option {option.Name} to {group.Name} for mod {mod.Name}, " + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); return; case SingleModGroup s: + { idx = s.OptionData.Count; - s.OptionData.Add(option); + var newOption = new SingleSubMod(s.Mod, s) + { + Name = option.Name, + Description = option.Description, + }; + if (option is IModDataContainer data) + IModDataContainer.Clone(data, newOption); + s.OptionData.Add(newOption); break; + } case MultiModGroup m: - idx = m.PrioritizedOptions.Count; - m.PrioritizedOptions.Add((option, priority)); + { + idx = m.OptionData.Count; + var newOption = new MultiSubMod(m.Mod, m) + { + Name = option.Name, + Description = option.Description, + Priority = option is MultiSubMod s ? s.Priority : ModPriority.Default, + }; + if (option is IModDataContainer data) + IModDataContainer.Clone(data, newOption); + m.OptionData.Add(newOption); break; - default: - return; + } + default: return; } saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); @@ -295,7 +286,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS break; case MultiModGroup m: - m.PrioritizedOptions.RemoveAt(optionIdx); + m.OptionData.RemoveAt(optionIdx); break; } @@ -315,59 +306,59 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Set the meta manipulations for a given option. Replaces existing manipulations. - public void OptionSetManipulations(Mod mod, int groupIdx, int optionIdx, HashSet manipulations, + public void OptionSetManipulations(Mod mod, int groupIdx, int dataContainerIdx, HashSet manipulations, SaveType saveType = SaveType.Queue) { - var subMod = GetSubMod(mod, groupIdx, optionIdx); + var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); if (subMod.Manipulations.Count == manipulations.Count && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) return; - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); - subMod.ManipulationData.SetTo(manipulations); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, dataContainerIdx, -1); + subMod.Manipulations.SetTo(manipulations); saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, dataContainerIdx, -1); } /// Set the file redirections for a given option. Replaces existing redirections. - public void OptionSetFiles(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary replacements, + public void OptionSetFiles(Mod mod, int groupIdx, int dataContainerIdx, IReadOnlyDictionary replacements, SaveType saveType = SaveType.Queue) { - var subMod = GetSubMod(mod, groupIdx, optionIdx); - if (subMod.FileData.SetEquals(replacements)) + var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); + if (subMod.Files.SetEquals(replacements)) return; - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); - subMod.FileData.SetTo(replacements); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, dataContainerIdx, -1); + subMod.Files.SetTo(replacements); saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, dataContainerIdx, -1); } /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. - public void OptionAddFiles(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary additions) + public void OptionAddFiles(Mod mod, int groupIdx, int dataContainerIdx, IReadOnlyDictionary additions) { - var subMod = GetSubMod(mod, groupIdx, optionIdx); - var oldCount = subMod.FileData.Count; - subMod.FileData.AddFrom(additions); - if (oldCount != subMod.FileData.Count) + var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); + var oldCount = subMod.Files.Count; + subMod.Files.AddFrom(additions); + if (oldCount != subMod.Files.Count) { saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, mod, groupIdx, dataContainerIdx, -1); } } /// Set the file swaps for a given option. Replaces existing swaps. - public void OptionSetFileSwaps(Mod mod, int groupIdx, int optionIdx, IReadOnlyDictionary swaps, + public void OptionSetFileSwaps(Mod mod, int groupIdx, int dataContainerIdx, IReadOnlyDictionary swaps, SaveType saveType = SaveType.Queue) { - var subMod = GetSubMod(mod, groupIdx, optionIdx); - if (subMod.FileSwapData.SetEquals(swaps)) + var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); + if (subMod.FileSwaps.SetEquals(swaps)) return; - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); - subMod.FileSwapData.SetTo(swaps); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, dataContainerIdx, -1); + subMod.FileSwaps.SetTo(swaps); saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, optionIdx, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, dataContainerIdx, -1); } @@ -389,17 +380,12 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS } /// Get the correct option for the given group and option index. - private static SubMod GetSubMod(Mod mod, int groupIdx, int optionIdx) + private static IModDataContainer GetSubMod(Mod mod, int groupIdx, int dataContainerIdx) { - if (groupIdx == -1 && optionIdx == 0) + if (groupIdx == -1 && dataContainerIdx == 0) return mod.Default; - return mod.Groups[groupIdx] switch - { - SingleModGroup s => s.OptionData[optionIdx], - MultiModGroup m => m.PrioritizedOptions[optionIdx].Mod, - _ => throw new InvalidOperationException(), - }; + return mod.Groups[groupIdx].DataContainers[dataContainerIdx]; } } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 71f64205..5c02213e 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -38,7 +38,7 @@ public sealed class Mod : IMod internal Mod(DirectoryInfo modPath) { ModPath = modPath; - Default = SubMod.CreateDefault(this); + Default = new DefaultSubMod(this); } public override string ToString() @@ -61,8 +61,8 @@ public sealed class Mod : IMod // Options - public readonly SubMod Default; - public readonly List Groups = []; + public readonly DefaultSubMod Default; + public readonly List Groups = []; public AppliedModData GetData(ModSettings? settings = null) { @@ -77,21 +77,16 @@ public sealed class Mod : IMod group.AddData(config, dictRedirections, setManips); } - Default.AddData(dictRedirections, setManips); + Default.AddDataTo(dictRedirections, setManips); return new AppliedModData(dictRedirections, setManips); } - public IEnumerable AllSubMods - => Groups.SelectMany(o => o switch - { - SingleModGroup single => single.OptionData, - MultiModGroup multi => multi.PrioritizedOptions.Select(s => s.Mod), - _ => [], - }).Prepend(Default); + public IEnumerable AllDataContainers + => Groups.SelectMany(o => o.DataContainers).Prepend(Default); public List FindUnusedFiles() { - var modFiles = AllSubMods.SelectMany(o => o.Files) + var modFiles = AllDataContainers.SelectMany(o => o.Files) .Select(p => p.Value) .ToHashSet(); return ModPath.EnumerateDirectories() diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 4d32f395..c1236037 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -112,10 +112,8 @@ public partial class ModCreator( var defaultFile = _saveService.FileNames.OptionGroupFile(mod, -1, Config.ReplaceNonAsciiOnImport); try { - if (!File.Exists(defaultFile)) - mod.Default.Load(mod.ModPath, new JObject(), out _); - else - mod.Default.Load(mod.ModPath, JObject.Parse(File.ReadAllText(defaultFile)), out _); + var jObject = File.Exists(defaultFile) ? JObject.Parse(File.ReadAllText(defaultFile)) : new JObject(); + IModDataContainer.Load(jObject, mod.Default, mod.ModPath); } catch (Exception e) { @@ -154,7 +152,7 @@ public partial class ModCreator( { var changes = false; List deleteList = new(); - foreach (var subMod in mod.AllSubMods) + foreach (var subMod in mod.AllDataContainers) { var (localChanges, localDeleteList) = IncorporateMetaChanges(subMod, mod.ModPath, false); changes |= localChanges; @@ -162,7 +160,7 @@ public partial class ModCreator( deleteList.AddRange(localDeleteList); } - SubMod.DeleteDeleteList(deleteList, delete); + IModDataContainer.DeleteDeleteList(deleteList, delete); if (!changes) return; @@ -176,10 +174,10 @@ public partial class ModCreator( /// If .meta or .rgsp files are encountered, parse them and incorporate their meta changes into the mod. /// If delete is true, the files are deleted afterwards. /// - public (bool Changes, List DeleteList) IncorporateMetaChanges(SubMod option, DirectoryInfo basePath, bool delete) + public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete) { var deleteList = new List(); - var oldSize = option.ManipulationData.Count; + var oldSize = option.Manipulations.Count; var deleteString = delete ? "with deletion." : "without deletion."; foreach (var (key, file) in option.Files.ToList()) { @@ -189,7 +187,7 @@ public partial class ModCreator( { if (ext1 == ".meta" || ext2 == ".meta") { - option.FileData.Remove(key); + option.Files.Remove(key); if (!file.Exists) continue; @@ -198,11 +196,11 @@ public partial class ModCreator( Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - option.ManipulationData.UnionWith(meta.MetaManipulations); + option.Manipulations.UnionWith(meta.MetaManipulations); } else if (ext1 == ".rgsp" || ext2 == ".rgsp") { - option.FileData.Remove(key); + option.Files.Remove(key); if (!file.Exists) continue; @@ -212,7 +210,7 @@ public partial class ModCreator( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - option.ManipulationData.UnionWith(rgsp.MetaManipulations); + option.Manipulations.UnionWith(rgsp.MetaManipulations); } } catch (Exception e) @@ -221,8 +219,8 @@ public partial class ModCreator( } } - SubMod.DeleteDeleteList(deleteList, delete); - return (oldSize < option.ManipulationData.Count, deleteList); + IModDataContainer.DeleteDeleteList(deleteList, delete); + return (oldSize < option.Manipulations.Count, deleteList); } /// @@ -238,7 +236,7 @@ public partial class ModCreator( /// Create a file for an option group from given data. public void CreateOptionGroup(DirectoryInfo baseFolder, GroupType type, string name, - ModPriority priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) + ModPriority priority, int index, Setting defaultSettings, string desc, IEnumerable subMods) { switch (type) { @@ -248,7 +246,7 @@ public partial class ModCreator( group.Description = desc; group.Priority = priority; group.DefaultSettings = defaultSettings; - group.PrioritizedOptions.AddRange(subMods.Select((s, idx) => (s, new ModPriority(idx)))); + group.OptionData.AddRange(subMods.Select(s => s.Clone(null!, group))); _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } @@ -258,7 +256,7 @@ public partial class ModCreator( group.Description = desc; group.Priority = priority; group.DefaultSettings = defaultSettings; - group.OptionData.AddRange(subMods); + group.OptionData.AddRange(subMods.Select(s => s.ConvertToSingle(null!, group))); _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } @@ -266,16 +264,15 @@ public partial class ModCreator( } /// Create the data for a given sub mod from its data and the folder it is based on. - public SubMod CreateSubMod(DirectoryInfo baseFolder, DirectoryInfo optionFolder, OptionList option) + public MultiSubMod CreateSubMod(DirectoryInfo baseFolder, DirectoryInfo optionFolder, OptionList option, ModPriority priority) { var list = optionFolder.EnumerateNonHiddenFiles() .Select(f => (Utf8GamePath.FromFile(f, optionFolder, out var gamePath, true), gamePath, new FullPath(f))) .Where(t => t.Item1); - var mod = SubMod.CreateForSaving(option.Name); - mod.Description = option.Description; + var mod = MultiSubMod.CreateForSaving(option.Name, option.Description, priority); foreach (var (_, gamePath, file) in list) - mod.FileData.TryAdd(gamePath, file); + mod.Files.TryAdd(gamePath, file); IncorporateMetaChanges(mod, baseFolder, true); return mod; @@ -292,7 +289,7 @@ public partial class ModCreator( foreach (var file in mod.FindUnusedFiles()) { if (Utf8GamePath.FromFile(new FileInfo(file.FullName), directory, out var gamePath, true)) - mod.Default.FileData.TryAdd(gamePath, file); + mod.Default.Files.TryAdd(gamePath, file); } IncorporateMetaChanges(mod.Default, directory, true); diff --git a/Penumbra/Mods/Subclasses/IModDataContainer.cs b/Penumbra/Mods/Subclasses/IModDataContainer.cs index d0b444b8..a26beb2a 100644 --- a/Penumbra/Mods/Subclasses/IModDataContainer.cs +++ b/Penumbra/Mods/Subclasses/IModDataContainer.cs @@ -1,12 +1,16 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; public interface IModDataContainer { + public IMod Mod { get; } + public IModGroup? Group { get; } + public Dictionary Files { get; set; } public Dictionary FileSwaps { get; set; } public HashSet Manipulations { get; set; } @@ -21,6 +25,32 @@ public interface IModDataContainer manipulations.UnionWith(Manipulations); } + public string GetName() + => this switch + { + IModOption o => o.FullName, + DefaultSubMod => DefaultSubMod.FullName, + _ => $"Container {GetDataIndices().DataIndex + 1}", + }; + + public string GetFullName() + => this switch + { + IModOption o => o.FullName, + DefaultSubMod => DefaultSubMod.FullName, + _ when Group != null => $"{Group.Name}: Container {GetDataIndices().DataIndex + 1}", + _ => $"Container {GetDataIndices().DataIndex + 1}", + }; + + public static void Clone(IModDataContainer from, IModDataContainer to) + { + to.Files = new Dictionary(from.Files); + to.FileSwaps = new Dictionary(from.FileSwaps); + to.Manipulations = [.. from.Manipulations]; + } + + public (int GroupIndex, int DataIndex) GetDataIndices(); + public static void Load(JToken json, IModDataContainer data, DirectoryInfo basePath) { data.Files.Clear(); @@ -77,4 +107,22 @@ public interface IModDataContainer serializer.Serialize(j, data.Manipulations); j.WriteEndObject(); } + + internal static void DeleteDeleteList(IEnumerable deleteList, bool delete) + { + if (!delete) + return; + + foreach (var file in deleteList) + { + try + { + File.Delete(file); + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not delete incorporated meta file {file}:\n{e}"); + } + } + } } diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Subclasses/IModGroup.cs index a046ade0..5c500793 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Subclasses/IModGroup.cs @@ -1,3 +1,4 @@ +using FFXIVClientStructs.FFXIV.Client.UI.Agent; using Newtonsoft.Json; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; @@ -6,6 +7,11 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; +public interface ITexToolsGroup +{ + public IReadOnlyList OptionData { get; } +} + public interface IModGroup { public const int MaxMultiOptions = 63; @@ -19,28 +25,89 @@ public interface IModGroup public FullPath? FindBestMatch(Utf8GamePath gamePath); public int AddOption(Mod mod, string name, string description = ""); - public bool ChangeOptionDescription(int optionIndex, string newDescription); - public bool ChangeOptionName(int optionIndex, string newName); - public IReadOnlyList Options { get; } - public bool IsOption { get; } + public IReadOnlyList Options { get; } + public IReadOnlyList DataContainers { get; } + public bool IsOption { get; } public IModGroup Convert(GroupType type); public bool MoveOption(int optionIdxFrom, int optionIdxTo); + public int GetIndex(); + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); /// Ensure that a value is valid for a group. public Setting FixSetting(Setting setting); + + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null); + + public bool ChangeOptionDescription(int optionIndex, string newDescription) + { + if (optionIndex < 0 || optionIndex >= Options.Count) + return false; + + var option = Options[optionIndex]; + if (option.Description == newDescription) + return false; + + option.Description = newDescription; + return true; + } + + public bool ChangeOptionName(int optionIndex, string newName) + { + if (optionIndex < 0 || optionIndex >= Options.Count) + return false; + + var option = Options[optionIndex]; + if (option.Name == newName) + return false; + + option.Name = newName; + return true; + } + + public static void WriteJsonBase(JsonTextWriter jWriter, IModGroup group) + { + jWriter.WriteStartObject(); + jWriter.WritePropertyName(nameof(group.Name)); + jWriter.WriteValue(group!.Name); + jWriter.WritePropertyName(nameof(group.Description)); + jWriter.WriteValue(group.Description); + jWriter.WritePropertyName(nameof(group.Priority)); + jWriter.WriteValue(group.Priority.Value); + jWriter.WritePropertyName(nameof(group.Type)); + jWriter.WriteValue(group.Type.ToString()); + jWriter.WritePropertyName(nameof(group.DefaultSettings)); + jWriter.WriteValue(group.DefaultSettings.Value); + } + + public (int Redirections, int Swaps, int Manips) GetCounts(); + + public static (int Redirections, int Swaps, int Manips) GetCountsBase(IModGroup group) + { + var redirectionCount = 0; + var swapCount = 0; + var manipCount = 0; + foreach (var option in group.DataContainers) + { + redirectionCount += option.Files.Count; + swapCount += option.FileSwaps.Count; + manipCount += option.Manipulations.Count; + } + + return (redirectionCount, swapCount, manipCount); + } } public readonly struct ModSaveGroup : ISavable { - private readonly DirectoryInfo _basePath; - private readonly IModGroup? _group; - private readonly int _groupIdx; - private readonly SubMod? _defaultMod; - private readonly bool _onlyAscii; + private readonly DirectoryInfo _basePath; + private readonly IModGroup? _group; + private readonly int _groupIdx; + private readonly DefaultSubMod? _defaultMod; + private readonly bool _onlyAscii; public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) { @@ -61,7 +128,7 @@ public readonly struct ModSaveGroup : ISavable _onlyAscii = onlyAscii; } - public ModSaveGroup(DirectoryInfo basePath, SubMod @default, bool onlyAscii) + public ModSaveGroup(DirectoryInfo basePath, DefaultSubMod @default, bool onlyAscii) { _basePath = basePath; _groupIdx = -1; @@ -77,42 +144,11 @@ public readonly struct ModSaveGroup : ISavable using var j = new JsonTextWriter(writer); j.Formatting = Formatting.Indented; var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + j.WriteStartObject(); if (_groupIdx >= 0) - { - j.WriteStartObject(); - j.WritePropertyName(nameof(_group.Name)); - j.WriteValue(_group!.Name); - j.WritePropertyName(nameof(_group.Description)); - j.WriteValue(_group.Description); - j.WritePropertyName(nameof(_group.Priority)); - j.WriteValue(_group.Priority.Value); - j.WritePropertyName(nameof(Type)); - j.WriteValue(_group.Type.ToString()); - j.WritePropertyName(nameof(_group.DefaultSettings)); - j.WriteValue(_group.DefaultSettings.Value); - switch (_group) - { - case SingleModGroup single: - j.WritePropertyName("Options"); - j.WriteStartArray(); - foreach (var option in single.OptionData) - SubMod.WriteSubMod(j, serializer, option, _basePath, null); - j.WriteEndArray(); - j.WriteEndObject(); - break; - case MultiModGroup multi: - j.WritePropertyName("Options"); - j.WriteStartArray(); - foreach (var (option, priority) in multi.PrioritizedOptions) - SubMod.WriteSubMod(j, serializer, option, _basePath, priority); - j.WriteEndArray(); - j.WriteEndObject(); - break; - } - } + _group!.WriteJson(j, serializer); else - { - SubMod.WriteSubMod(j, serializer, _defaultMod!, _basePath, null); - } + IModDataContainer.WriteModData(j, serializer, _defaultMod!, _basePath); + j.WriteEndObject(); } } diff --git a/Penumbra/Mods/Subclasses/IModOption.cs b/Penumbra/Mods/Subclasses/IModOption.cs index bb52a2cd..f66ce44e 100644 --- a/Penumbra/Mods/Subclasses/IModOption.cs +++ b/Penumbra/Mods/Subclasses/IModOption.cs @@ -15,6 +15,8 @@ public interface IModOption option.Description = json[nameof(Description)]?.ToObject() ?? string.Empty; } + public (int GroupIndex, int OptionIndex) GetOptionIndices(); + public static void WriteModOption(JsonWriter j, IModOption option) { j.WritePropertyName(nameof(Name)); diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Subclasses/MultiModGroup.cs index 4ec2c72a..f194350a 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Subclasses/MultiModGroup.cs @@ -1,4 +1,5 @@ using Dalamud.Interface.Internal.Notifications; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; @@ -10,20 +11,30 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; /// Groups that allow all available options to be selected at once. -public sealed class MultiModGroup(Mod mod) : IModGroup +public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup { public GroupType Type => GroupType.Multi; - public Mod Mod { get; set; } = mod; - public string Name { get; set; } = "Group"; - public string Description { get; set; } = "A non-exclusive group of settings."; - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; set; } = mod; + public string Name { get; set; } = "Group"; + public string Description { get; set; } = "A non-exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } + public readonly List OptionData = []; + + public IReadOnlyList Options + => OptionData; + + public IReadOnlyList DataContainers + => OptionData; + + public bool IsOption + => OptionData.Count > 0; public FullPath? FindBestMatch(Utf8GamePath gamePath) - => PrioritizedOptions.OrderByDescending(o => o.Priority) - .SelectWhere(o => (o.Mod.FileData.TryGetValue(gamePath, out var file) || o.Mod.FileSwapData.TryGetValue(gamePath, out file), file)) + => OptionData.OrderByDescending(o => o.Priority) + .SelectWhere(o => (o.Files.TryGetValue(gamePath, out var file) || o.FileSwaps.TryGetValue(gamePath, out file), file)) .FirstOrDefault(); public int AddOption(Mod mod, string name, string description = "") @@ -32,49 +43,15 @@ public sealed class MultiModGroup(Mod mod) : IModGroup if (groupIdx < 0) return -1; - var subMod = new SubMod(mod, this) + var subMod = new MultiSubMod(mod, this) { Name = name, Description = description, }; - PrioritizedOptions.Add((subMod, ModPriority.Default)); - return PrioritizedOptions.Count - 1; + OptionData.Add(subMod); + return OptionData.Count - 1; } - public bool ChangeOptionDescription(int optionIndex, string newDescription) - { - if (optionIndex < 0 || optionIndex >= PrioritizedOptions.Count) - return false; - - var option = PrioritizedOptions[optionIndex].Mod; - if (option.Description == newDescription) - return false; - - option.Description = newDescription; - return true; - } - - public bool ChangeOptionName(int optionIndex, string newName) - { - if (optionIndex < 0 || optionIndex >= PrioritizedOptions.Count) - return false; - - var option = PrioritizedOptions[optionIndex].Mod; - if (option.Name == newName) - return false; - - option.Name = newName; - return true; - } - - public IReadOnlyList Options - => PrioritizedOptions.Select(p => p.Mod).ToArray(); - - public bool IsOption - => PrioritizedOptions.Count > 0; - - public readonly List<(SubMod Mod, ModPriority Priority)> PrioritizedOptions = []; - public static MultiModGroup? Load(Mod mod, JObject json, int groupIdx) { var ret = new MultiModGroup(mod) @@ -91,7 +68,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup if (options != null) foreach (var child in options.Children()) { - if (ret.PrioritizedOptions.Count == IModGroup.MaxMultiOptions) + if (ret.OptionData.Count == IModGroup.MaxMultiOptions) { Penumbra.Messager.NotificationMessage( $"Multi Group {ret.Name} in {mod.Name} has more than {IModGroup.MaxMultiOptions} options, ignoring excessive options.", @@ -99,9 +76,8 @@ public sealed class MultiModGroup(Mod mod) : IModGroup break; } - var subMod = new SubMod(mod, ret); - subMod.Load(mod.ModPath, child, out var priority); - ret.PrioritizedOptions.Add((subMod, priority)); + var subMod = new MultiSubMod(mod, ret, child); + ret.OptionData.Add(subMod); } ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); @@ -115,39 +91,68 @@ public sealed class MultiModGroup(Mod mod) : IModGroup { case GroupType.Multi: return this; case GroupType.Single: - var multi = new SingleModGroup(Mod) + var single = new SingleModGroup(Mod) { Name = Name, Description = Description, Priority = Priority, - DefaultSettings = DefaultSettings.TurnMulti(PrioritizedOptions.Count), + DefaultSettings = DefaultSettings.TurnMulti(OptionData.Count), }; - multi.OptionData.AddRange(PrioritizedOptions.Select(p => p.Mod)); - return multi; + single.OptionData.AddRange(OptionData.Select(o => o.ConvertToSingle(Mod, single))); + return single; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } } public bool MoveOption(int optionIdxFrom, int optionIdxTo) { - if (!PrioritizedOptions.Move(optionIdxFrom, optionIdxTo)) + if (!OptionData.Move(optionIdxFrom, optionIdxTo)) return false; DefaultSettings = DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); return true; } + public int GetIndex() + { + var groupIndex = Mod.Groups.IndexOf(this); + if (groupIndex < 0) + throw new Exception($"Mod {Mod.Name} from Group {Name} does not contain this group."); + + return groupIndex; + } + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { - foreach (var (option, index) in PrioritizedOptions.WithIndex().OrderByDescending(o => o.Value.Priority)) + foreach (var (option, index) in OptionData.WithIndex().OrderByDescending(o => o.Value.Priority)) { if (setting.HasFlag(index)) - option.Mod.AddData(redirections, manipulations); + option.AddDataTo(redirections, manipulations); } } + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) + { + IModGroup.WriteJsonBase(jWriter, this); + jWriter.WritePropertyName("Options"); + jWriter.WriteStartArray(); + foreach (var option in OptionData) + { + IModOption.WriteModOption(jWriter, option); + jWriter.WritePropertyName(nameof(option.Priority)); + jWriter.WriteValue(option.Priority.Value); + IModDataContainer.WriteModData(jWriter, serializer, option, basePath ?? Mod.ModPath); + } + + jWriter.WriteEndArray(); + jWriter.WriteEndObject(); + } + + public (int Redirections, int Swaps, int Manips) GetCounts() + => IModGroup.GetCountsBase(this); + public Setting FixSetting(Setting setting) - => new(setting.Value & ((1ul << PrioritizedOptions.Count) - 1)); + => new(setting.Value & ((1ul << OptionData.Count) - 1)); /// Create a group without a mod only for saving it in the creator. internal static MultiModGroup CreateForSaving(string name) @@ -155,4 +160,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup { Name = name, }; + + IReadOnlyList ITexToolsGroup.OptionData + => OptionData; } diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Subclasses/SingleModGroup.cs index 994a1f96..d1a3b6d1 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Subclasses/SingleModGroup.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Filesystem; @@ -8,7 +9,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; /// Groups that allow only one of their available options to be selected. -public sealed class SingleModGroup(Mod mod) : IModGroup +public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup { public GroupType Type => GroupType.Single; @@ -19,16 +20,19 @@ public sealed class SingleModGroup(Mod mod) : IModGroup public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } - public readonly List OptionData = []; + public readonly List OptionData = []; + + IReadOnlyList ITexToolsGroup.OptionData + => OptionData; public FullPath? FindBestMatch(Utf8GamePath gamePath) => OptionData - .SelectWhere(m => (m.FileData.TryGetValue(gamePath, out var file) || m.FileSwapData.TryGetValue(gamePath, out file), file)) + .SelectWhere(m => (m.Files.TryGetValue(gamePath, out var file) || m.FileSwaps.TryGetValue(gamePath, out file), file)) .FirstOrDefault(); public int AddOption(Mod mod, string name, string description = "") { - var subMod = new SubMod(mod, this) + var subMod = new SingleSubMod(mod, this) { Name = name, Description = description, @@ -37,35 +41,12 @@ public sealed class SingleModGroup(Mod mod) : IModGroup return OptionData.Count - 1; } - public bool ChangeOptionDescription(int optionIndex, string newDescription) - { - if (optionIndex < 0 || optionIndex >= OptionData.Count) - return false; - - var option = OptionData[optionIndex]; - if (option.Description == newDescription) - return false; - - option.Description = newDescription; - return true; - } - - public bool ChangeOptionName(int optionIndex, string newName) - { - if (optionIndex < 0 || optionIndex >= OptionData.Count) - return false; - - var option = OptionData[optionIndex]; - if (option.Name == newName) - return false; - - option.Name = newName; - return true; - } - public IReadOnlyList Options => OptionData; + public IReadOnlyList DataContainers + => OptionData; + public bool IsOption => OptionData.Count > 1; @@ -85,8 +66,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup if (options != null) foreach (var child in options.Children()) { - var subMod = new SubMod(mod, ret); - subMod.Load(mod.ModPath, child, out _); + var subMod = new SingleSubMod(mod, ret, child); ret.OptionData.Add(subMod); } @@ -107,7 +87,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup Priority = Priority, DefaultSettings = Setting.Multi((int)DefaultSettings.Value), }; - multi.PrioritizedOptions.AddRange(OptionData.Select((o, i) => (o, new ModPriority(i)))); + multi.OptionData.AddRange(OptionData.Select((o, i) => o.ConvertToMulti(Mod, multi, new ModPriority(i)))); return multi; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } @@ -137,12 +117,39 @@ public sealed class SingleModGroup(Mod mod) : IModGroup return true; } + public int GetIndex() + { + var groupIndex = Mod.Groups.IndexOf(this); + if (groupIndex < 0) + throw new Exception($"Mod {Mod.Name} from Group {Name} does not contain this group."); + + return groupIndex; + } + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) - => OptionData[setting.AsIndex].AddData(redirections, manipulations); + => OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); public Setting FixSetting(Setting setting) => OptionData.Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(OptionData.Count - 1))); + public (int Redirections, int Swaps, int Manips) GetCounts() + => IModGroup.GetCountsBase(this); + + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) + { + IModGroup.WriteJsonBase(jWriter, this); + jWriter.WritePropertyName("Options"); + jWriter.WriteStartArray(); + foreach (var option in OptionData) + { + IModOption.WriteModOption(jWriter, option); + IModDataContainer.WriteModData(jWriter, serializer, option, basePath ?? Mod.ModPath); + } + + jWriter.WriteEndArray(); + jWriter.WriteEndObject(); + } + /// Create a group without a mod only for saving it in the creator. internal static SingleModGroup CreateForSaving(string name) => new(null!) diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs index bc93fcc4..a2425eb7 100644 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ b/Penumbra/Mods/Subclasses/SubMod.cs @@ -7,7 +7,9 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Subclasses; -public class SingleSubMod(Mod mod, SingleModGroup group) : IModOption, IModDataContainer +public interface IModDataOption : IModOption, IModDataContainer; + +public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption { internal readonly Mod Mod = mod; internal readonly SingleModGroup Group = group; @@ -19,12 +21,68 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModOption, IModDataC public string Description { get; set; } = string.Empty; + IMod IModDataContainer.Mod + => Mod; + + IModGroup IModDataContainer.Group + => Group; + public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; public HashSet Manipulations { get; set; } = []; + + public SingleSubMod(Mod mod, SingleModGroup group, JToken json) + : this(mod, group) + { + IModOption.Load(json, this); + IModDataContainer.Load(json, this, mod.ModPath); + } + + public SingleSubMod Clone(Mod mod, SingleModGroup group) + { + var ret = new SingleSubMod(mod, group) + { + Name = Name, + Description = Description, + }; + IModDataContainer.Clone(this, ret); + + return ret; + } + + public MultiSubMod ConvertToMulti(Mod mod, MultiModGroup group, ModPriority priority) + { + var ret = new MultiSubMod(mod, group) + { + Name = Name, + Description = Description, + Priority = priority, + }; + IModDataContainer.Clone(this, ret); + + return ret; + } + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), GetDataIndex()); + + public (int GroupIndex, int OptionIndex) GetOptionIndices() + => (Group.GetIndex(), GetDataIndex()); + + private int GetDataIndex() + { + var dataIndex = Group.DataContainers.IndexOf(this); + if (dataIndex < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); + + return dataIndex; + } } -public class MultiSubMod(Mod mod, MultiModGroup group) : IModOption, IModDataContainer +public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption { internal readonly Mod Mod = mod; internal readonly MultiModGroup Group = group; @@ -40,12 +98,76 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModOption, IModDataCon public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; public HashSet Manipulations { get; set; } = []; + + IMod IModDataContainer.Mod + => Mod; + + IModGroup IModDataContainer.Group + => Group; + + + public MultiSubMod(Mod mod, MultiModGroup group, JToken json) + : this(mod, group) + { + IModOption.Load(json, this); + IModDataContainer.Load(json, this, mod.ModPath); + Priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; + } + + public MultiSubMod Clone(Mod mod, MultiModGroup group) + { + var ret = new MultiSubMod(mod, group) + { + Name = Name, + Description = Description, + Priority = Priority, + }; + IModDataContainer.Clone(this, ret); + + return ret; + } + + public SingleSubMod ConvertToSingle(Mod mod, SingleModGroup group) + { + var ret = new SingleSubMod(mod, group) + { + Name = Name, + Description = Description, + }; + IModDataContainer.Clone(this, ret); + return ret; + } + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + + public static MultiSubMod CreateForSaving(string name, string description, ModPriority priority) + => new(null!, null!) + { + Name = name, + Description = description, + Priority = priority, + }; + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), GetDataIndex()); + + public (int GroupIndex, int OptionIndex) GetOptionIndices() + => (Group.GetIndex(), GetDataIndex()); + + private int GetDataIndex() + { + var dataIndex = Group.DataContainers.IndexOf(this); + if (dataIndex < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); + + return dataIndex; + } } public class DefaultSubMod(IMod mod) : IModDataContainer { - public string FullName - => "Default Option"; + public const string FullName = "Default Option"; public string Description => string.Empty; @@ -55,183 +177,176 @@ public class DefaultSubMod(IMod mod) : IModDataContainer public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; public HashSet Manipulations { get; set; } = []; + + IMod IModDataContainer.Mod + => Mod; + + IModGroup? IModDataContainer.Group + => null; + + + public DefaultSubMod(Mod mod, JToken json) + : this(mod) + { + IModDataContainer.Load(json, this, mod.ModPath); + } + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (-1, 0); } -/// -/// A sub mod is a collection of -/// - file replacements -/// - file swaps -/// - meta manipulations -/// that can be used either as an option or as the default data for a mod. -/// It can be loaded and reloaded from Json. -/// Nothing is checked for existence or validity when loading. -/// Objects are also not checked for uniqueness, the first appearance of a game path or meta path decides. -/// -public sealed class SubMod(IMod mod, IModGroup group) : IModOption -{ - public string Name { get; set; } = "Default"; - public string FullName - => Group == null ? "Default Option" : $"{Group.Name}: {Name}"; - - public string Description { get; set; } = string.Empty; - - internal readonly IMod Mod = mod; - internal readonly IModGroup? Group = group; - - internal (int GroupIdx, int OptionIdx) GetIndices() - { - if (IsDefault) - return (-1, 0); - - var groupIdx = Mod.Groups.IndexOf(Group); - if (groupIdx < 0) - throw new Exception($"Group {Group.Name} from SubMod {Name} is not contained in Mod {Mod.Name}."); - - return (groupIdx, GetOptionIndex()); - } - - private int GetOptionIndex() - { - var optionIndex = Group switch - { - null => 0, - SingleModGroup single => single.OptionData.IndexOf(this), - MultiModGroup multi => multi.PrioritizedOptions.IndexOf(p => p.Mod == this), - _ => throw new Exception($"Group {Group.Name} from SubMod {Name} has unknown type {typeof(Group)}"), - }; - if (optionIndex < 0) - throw new Exception($"Group {Group!.Name} from SubMod {Name} does not contain this SubMod."); - - return optionIndex; - } - - public static SubMod CreateDefault(IMod mod) - => new(mod, null!); - - [MemberNotNullWhen(false, nameof(Group))] - public bool IsDefault - => Group == null; - - public void AddData(Dictionary redirections, HashSet manipulations) - { - foreach (var (path, file) in Files) - redirections.TryAdd(path, file); - - foreach (var (path, file) in FileSwaps) - redirections.TryAdd(path, file); - manipulations.UnionWith(Manipulations); - } - - public Dictionary FileData = []; - public Dictionary FileSwapData = []; - public HashSet ManipulationData = []; - - public IReadOnlyDictionary Files - => FileData; - - public IReadOnlyDictionary FileSwaps - => FileSwapData; - - public IReadOnlySet Manipulations - => ManipulationData; - - public void Load(DirectoryInfo basePath, JToken json, out ModPriority priority) - { - FileData.Clear(); - FileSwapData.Clear(); - ManipulationData.Clear(); - - // Every option has a name, but priorities are only relevant for multi group options. - Name = json[nameof(Name)]?.ToObject() ?? string.Empty; - Description = json[nameof(Description)]?.ToObject() ?? string.Empty; - priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; - - var files = (JObject?)json[nameof(Files)]; - if (files != null) - foreach (var property in files.Properties()) - { - if (Utf8GamePath.FromString(property.Name, out var p, true)) - FileData.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); - } - - var swaps = (JObject?)json[nameof(FileSwaps)]; - if (swaps != null) - foreach (var property in swaps.Properties()) - { - if (Utf8GamePath.FromString(property.Name, out var p, true)) - FileSwapData.TryAdd(p, new FullPath(property.Value.ToObject()!)); - } - - var manips = json[nameof(Manipulations)]; - if (manips != null) - foreach (var s in manips.Children().Select(c => c.ToObject()) - .Where(m => m.Validate())) - ManipulationData.Add(s); - } - - internal static void DeleteDeleteList(IEnumerable deleteList, bool delete) - { - if (!delete) - return; - - foreach (var file in deleteList) - { - try - { - File.Delete(file); - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not delete incorporated meta file {file}:\n{e}"); - } - } - } - - /// Create a sub mod without a mod or group only for saving it in the creator. - internal static SubMod CreateForSaving(string name) - => new(null!, null!) - { - Name = name, - }; - - - public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, SubMod mod, DirectoryInfo basePath, ModPriority? priority) - { - j.WriteStartObject(); - j.WritePropertyName(nameof(Name)); - j.WriteValue(mod.Name); - j.WritePropertyName(nameof(Description)); - j.WriteValue(mod.Description); - if (priority != null) - { - j.WritePropertyName(nameof(IModGroup.Priority)); - j.WriteValue(priority.Value.Value); - } - - j.WritePropertyName(nameof(mod.Files)); - j.WriteStartObject(); - foreach (var (gamePath, file) in mod.Files) - { - if (file.ToRelPath(basePath, out var relPath)) - { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(relPath.ToString()); - } - } - - j.WriteEndObject(); - j.WritePropertyName(nameof(mod.FileSwaps)); - j.WriteStartObject(); - foreach (var (gamePath, file) in mod.FileSwaps) - { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(file.ToString()); - } - - j.WriteEndObject(); - j.WritePropertyName(nameof(mod.Manipulations)); - serializer.Serialize(j, mod.Manipulations); - j.WriteEndObject(); - } -} +//public sealed class SubMod(IMod mod, IModGroup group) : IModOption +//{ +// public string Name { get; set; } = "Default"; +// +// public string FullName +// => Group == null ? "Default Option" : $"{Group.Name}: {Name}"; +// +// public string Description { get; set; } = string.Empty; +// +// internal readonly IMod Mod = mod; +// internal readonly IModGroup? Group = group; +// +// internal (int GroupIdx, int OptionIdx) GetIndices() +// { +// if (IsDefault) +// return (-1, 0); +// +// var groupIdx = Mod.Groups.IndexOf(Group); +// if (groupIdx < 0) +// throw new Exception($"Group {Group.Name} from SubMod {Name} is not contained in Mod {Mod.Name}."); +// +// return (groupIdx, GetOptionIndex()); +// } +// +// private int GetOptionIndex() +// { +// var optionIndex = Group switch +// { +// null => 0, +// SingleModGroup single => single.OptionData.IndexOf(this), +// MultiModGroup multi => multi.OptionData.IndexOf(p => p.Mod == this), +// _ => throw new Exception($"Group {Group.Name} from SubMod {Name} has unknown type {typeof(Group)}"), +// }; +// if (optionIndex < 0) +// throw new Exception($"Group {Group!.Name} from SubMod {Name} does not contain this SubMod."); +// +// return optionIndex; +// } +// +// public static SubMod CreateDefault(IMod mod) +// => new(mod, null!); +// +// [MemberNotNullWhen(false, nameof(Group))] +// public bool IsDefault +// => Group == null; +// +// public void AddData(Dictionary redirections, HashSet manipulations) +// { +// foreach (var (path, file) in Files) +// redirections.TryAdd(path, file); +// +// foreach (var (path, file) in FileSwaps) +// redirections.TryAdd(path, file); +// manipulations.UnionWith(Manipulations); +// } +// +// public Dictionary FileData = []; +// public Dictionary FileSwapData = []; +// public HashSet ManipulationData = []; +// +// public IReadOnlyDictionary Files +// => FileData; +// +// public IReadOnlyDictionary FileSwaps +// => FileSwapData; +// +// public IReadOnlySet Manipulations +// => ManipulationData; +// +// public void Load(DirectoryInfo basePath, JToken json, out ModPriority priority) +// { +// FileData.Clear(); +// FileSwapData.Clear(); +// ManipulationData.Clear(); +// +// // Every option has a name, but priorities are only relevant for multi group options. +// Name = json[nameof(Name)]?.ToObject() ?? string.Empty; +// Description = json[nameof(Description)]?.ToObject() ?? string.Empty; +// priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; +// +// var files = (JObject?)json[nameof(Files)]; +// if (files != null) +// foreach (var property in files.Properties()) +// { +// if (Utf8GamePath.FromString(property.Name, out var p, true)) +// FileData.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); +// } +// +// var swaps = (JObject?)json[nameof(FileSwaps)]; +// if (swaps != null) +// foreach (var property in swaps.Properties()) +// { +// if (Utf8GamePath.FromString(property.Name, out var p, true)) +// FileSwapData.TryAdd(p, new FullPath(property.Value.ToObject()!)); +// } +// +// var manips = json[nameof(Manipulations)]; +// if (manips != null) +// foreach (var s in manips.Children().Select(c => c.ToObject()) +// .Where(m => m.Validate())) +// ManipulationData.Add(s); +// } +// +// +// /// Create a sub mod without a mod or group only for saving it in the creator. +// internal static SubMod CreateForSaving(string name) +// => new(null!, null!) +// { +// Name = name, +// }; +// +// +// public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, SubMod mod, DirectoryInfo basePath, ModPriority? priority) +// { +// j.WriteStartObject(); +// j.WritePropertyName(nameof(Name)); +// j.WriteValue(mod.Name); +// j.WritePropertyName(nameof(Description)); +// j.WriteValue(mod.Description); +// if (priority != null) +// { +// j.WritePropertyName(nameof(IModGroup.Priority)); +// j.WriteValue(priority.Value.Value); +// } +// +// j.WritePropertyName(nameof(mod.Files)); +// j.WriteStartObject(); +// foreach (var (gamePath, file) in mod.Files) +// { +// if (file.ToRelPath(basePath, out var relPath)) +// { +// j.WritePropertyName(gamePath.ToString()); +// j.WriteValue(relPath.ToString()); +// } +// } +// +// j.WriteEndObject(); +// j.WritePropertyName(nameof(mod.FileSwaps)); +// j.WriteStartObject(); +// foreach (var (gamePath, file) in mod.FileSwaps) +// { +// j.WritePropertyName(gamePath.ToString()); +// j.WriteValue(file.ToString()); +// } +// +// j.WriteEndObject(); +// j.WritePropertyName(nameof(mod.Manipulations)); +// serializer.Serialize(j, mod.Manipulations); +// j.WriteEndObject(); +// } +//} diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index a599b3bb..393369d4 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -18,49 +18,46 @@ public class TemporaryMod : IMod public int TotalManipulations => Default.Manipulations.Count; - public readonly SubMod Default; + public readonly DefaultSubMod Default; public AppliedModData GetData(ModSettings? settings = null) { Dictionary dict; - if (Default.FileSwapData.Count == 0) + if (Default.FileSwaps.Count == 0) { - dict = Default.FileData; + dict = Default.Files; } - else if (Default.FileData.Count == 0) + else if (Default.Files.Count == 0) { - dict = Default.FileSwapData; + dict = Default.FileSwaps; } else { // Need to ensure uniqueness. - dict = new Dictionary(Default.FileData.Count + Default.FileSwaps.Count); - foreach (var (gamePath, file) in Default.FileData.Concat(Default.FileSwaps)) + dict = new Dictionary(Default.Files.Count + Default.FileSwaps.Count); + foreach (var (gamePath, file) in Default.Files.Concat(Default.FileSwaps)) dict.TryAdd(gamePath, file); } - return new AppliedModData(dict, Default.ManipulationData); + return new AppliedModData(dict, Default.Manipulations); } public IReadOnlyList Groups => Array.Empty(); - public IEnumerable AllSubMods - => [Default]; - public TemporaryMod() - => Default = SubMod.CreateDefault(this); + => Default = new(this); public void SetFile(Utf8GamePath gamePath, FullPath fullPath) - => Default.FileData[gamePath] = fullPath; + => Default.Files[gamePath] = fullPath; public bool SetManipulation(MetaManipulation manip) - => Default.ManipulationData.Remove(manip) | Default.ManipulationData.Add(manip); + => Default.Manipulations.Remove(manip) | Default.Manipulations.Add(manip); public void SetAll(Dictionary dict, HashSet manips) { - Default.FileData = dict; - Default.ManipulationData = manips; + Default.Files = dict; + Default.Manipulations = manips; } public static void SaveTempCollection(Configuration config, SaveService saveService, ModManager modManager, ModCollection collection, @@ -93,16 +90,16 @@ public class TemporaryMod : IMod { var target = Path.Combine(fileDir.FullName, Path.GetFileName(targetPath)); File.Copy(targetPath, target, true); - defaultMod.FileData[gamePath] = new FullPath(target); + defaultMod.Files[gamePath] = new FullPath(target); } else { - defaultMod.FileSwapData[gamePath] = new FullPath(targetPath); + defaultMod.FileSwaps[gamePath] = new FullPath(targetPath); } } foreach (var manip in collection.MetaCache?.Manipulations ?? Array.Empty()) - defaultMod.ManipulationData.Add(manip); + defaultMod.Manipulations.Add(manip); saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir); diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index c891d33a..503d64b7 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -305,7 +305,7 @@ public class FileEditor( UiHelpers.Text(gamePath.Path); ImGui.TableNextColumn(); using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ItemId.Value()); - ImGui.TextUnformatted(option.FullName); + ImGui.TextUnformatted(option.GetFullName()); } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index f765b47e..94f1d577 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -3,7 +3,6 @@ using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Subclasses; using Penumbra.String.Classes; @@ -79,7 +78,7 @@ public partial class ModEditWindow var file = f.RelPath.ToString(); return f.SubModUsage.Count == 0 ? Enumerable.Repeat((file, "Unused", string.Empty, 0x40000080u), 1) - : f.SubModUsage.Select(s => (file, s.Item2.ToString(), s.Item1.FullName, + : f.SubModUsage.Select(s => (file, s.Item2.ToString(), s.Item1.GetFullName(), _editor.Option! == s.Item1 && Mod!.HasOptions ? 0x40008000u : 0u)); }); @@ -148,13 +147,13 @@ public partial class ModEditWindow (string, int) GetMulti() { var groups = registry.SubModUsage.GroupBy(s => s.Item1).ToArray(); - return (string.Join("\n", groups.Select(g => g.Key.Name)), groups.Length); + return (string.Join("\n", groups.Select(g => g.Key.GetName())), groups.Length); } var (text, groupCount) = color switch { ColorId.ConflictingMod => (string.Empty, 0), - ColorId.NewMod => (registry.SubModUsage[0].Item1.Name, 1), + ColorId.NewMod => (registry.SubModUsage[0].Item1.GetName(), 1), ColorId.InheritedMod => GetMulti(), _ => (string.Empty, 0), }; @@ -192,7 +191,7 @@ public partial class ModEditWindow ImGuiUtil.RightAlign(rightText); } - private void PrintGamePath(int i, int j, FileRegistry registry, SubMod subMod, Utf8GamePath gamePath) + private void PrintGamePath(int i, int j, FileRegistry registry, IModDataContainer subMod, Utf8GamePath gamePath) { using var id = ImRaii.PushId(j); ImGui.TableNextColumn(); @@ -228,7 +227,7 @@ public partial class ModEditWindow } } - private void PrintNewGamePath(int i, FileRegistry registry, SubMod subMod) + private void PrintNewGamePath(int i, FileRegistry registry, IModDataContainer subMod) { var tmp = _fileIdx == i && _pathIdx == -1 ? _gamePathEdit : string.Empty; var pos = ImGui.GetCursorPosX() - ImGui.GetFrameHeight(); @@ -301,9 +300,9 @@ public partial class ModEditWindow tt = changes ? "Apply the current file setup to the currently selected option." : "No changes made."; if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, !changes)) { - var failedFiles = _editor.FileEditor.Apply(_editor.Mod!, (SubMod)_editor.Option!); + var failedFiles = _editor.FileEditor.Apply(_editor.Mod!, _editor.Option!); if (failedFiles > 0) - Penumbra.Log.Information($"Failed to apply {failedFiles} file redirections to {_editor.Option!.FullName}."); + Penumbra.Log.Information($"Failed to apply {failedFiles} file redirections to {_editor.Option!.GetFullName()}."); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index aad70cb3..92a9dd66 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -45,7 +45,7 @@ public partial class ModEditWindow var tt = setsEqual ? "No changes staged." : "Apply the currently staged changes to the option."; ImGui.NewLine(); if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, setsEqual)) - _editor.MetaEditor.Apply(_editor.Mod!, _editor.GroupIdx, _editor.OptionIdx); + _editor.MetaEditor.Apply(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx); ImGui.SameLine(); tt = setsEqual ? "No changes staged." : "Revert all currently staged changes."; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index cca8fe10..6b9965b8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -85,7 +85,7 @@ public partial class ModEditWindow { // TODO: Is it worth trying to order results based on option priorities for cases where more than one match is found? // NOTE: We're using case-insensitive comparisons, as option group paths in mods are stored in lower case, but the mod editor uses paths directly from the file system, which may be mixed case. - return mod.AllSubMods + return mod.AllDataContainers .SelectMany(m => m.Files.Concat(m.FileSwaps)) .Where(kv => kv.Value.FullName.Equals(path, StringComparison.OrdinalIgnoreCase)) .Select(kv => kv.Key) @@ -103,7 +103,7 @@ public partial class ModEditWindow return []; // Filter then prepend the current option to ensure it's chosen first. - return mod.AllSubMods + return mod.AllDataContainers .Where(subMod => subMod != option) .Prepend(option) .SelectMany(subMod => subMod.Manipulations) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 4ecacece..70854fe7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -187,8 +187,8 @@ public partial class ModEditWindow if (editor == null) return new QuickImportAction(owner._editor, FallbackOptionName, gamePath); - var subMod = editor.Option; - var optionName = subMod!.FullName; + var subMod = editor.Option!; + var optionName = subMod is IModOption o ? o.FullName : FallbackOptionName; if (gamePath.IsEmpty || file == null || editor.FileEditor.Changes) return new QuickImportAction(editor, optionName, gamePath); @@ -199,7 +199,7 @@ public partial class ModEditWindow if (mod == null) return new QuickImportAction(editor, optionName, gamePath); - var (preferredPath, subDirs) = GetPreferredPath(mod, subMod, owner._config.ReplaceNonAsciiOnImport); + var (preferredPath, subDirs) = GetPreferredPath(mod, subMod as IModOption, owner._config.ReplaceNonAsciiOnImport); var targetPath = new FullPath(Path.Combine(preferredPath.FullName, gamePath.ToString())).FullName; if (File.Exists(targetPath)) return new QuickImportAction(editor, optionName, gamePath); @@ -222,16 +222,16 @@ public partial class ModEditWindow { fileRegistry, }, _subDirs); - _editor.FileEditor.Apply(_editor.Mod!, (SubMod)_editor.Option!); + _editor.FileEditor.Apply(_editor.Mod!, _editor.Option!); return fileRegistry; } - private static (DirectoryInfo, int) GetPreferredPath(Mod mod, SubMod subMod, bool replaceNonAscii) + private static (DirectoryInfo, int) GetPreferredPath(Mod mod, IModOption? subMod, bool replaceNonAscii) { var path = mod.ModPath; var subDirs = 0; - if (subMod == mod.Default) + if (subMod == null) return (path, subDirs); var name = subMod.Name; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 3f5f6c37..21d14f78 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -77,10 +77,10 @@ public partial class ModEditWindow : Window, IDisposable _forceTextureStartPath = true; } - public void ChangeOption(SubMod? subMod) + public void ChangeOption(IModDataContainer? subMod) { - var (groupIdx, optionIdx) = subMod?.GetIndices() ?? (-1, 0); - _editor.LoadOption(groupIdx, optionIdx); + var (groupIdx, dataIdx) = subMod?.GetDataIndices() ?? (-1, 0); + _editor.LoadOption(groupIdx, dataIdx); } public void UpdateModels() @@ -111,7 +111,7 @@ public partial class ModEditWindow : Window, IDisposable }); var manipulations = 0; var subMods = 0; - var swaps = Mod!.AllSubMods.Sum(m => + var swaps = Mod!.AllDataContainers.Sum(m => { ++subMods; manipulations += m.Manipulations.Count; @@ -330,7 +330,7 @@ public partial class ModEditWindow : Window, IDisposable else if (ImGuiUtil.DrawDisabledButton("Re-Duplicate and Normalize Mod", Vector2.Zero, tt, !_allowReduplicate && !modifier)) { _editor.ModNormalizer.Normalize(Mod!); - _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(Mod!, _editor.GroupIdx, _editor.OptionIdx), TaskScheduler.Default); + _editor.ModNormalizer.Worker.ContinueWith(_ => _editor.LoadMod(Mod!, _editor.GroupIdx, _editor.DataIdx), TaskScheduler.Default); } if (!_editor.Duplicates.Worker.IsCompleted) @@ -405,7 +405,7 @@ public partial class ModEditWindow : Window, IDisposable var width = new Vector2(ImGui.GetContentRegionAvail().X / 3, 0); var ret = false; if (ImGuiUtil.DrawDisabledButton(defaultOption, width, "Switch to the default option for the mod.\nThis resets unsaved changes.", - _editor.Option!.IsDefault)) + _editor.Option is DefaultSubMod)) { _editor.LoadOption(-1, 0); ret = true; @@ -414,7 +414,7 @@ public partial class ModEditWindow : Window, IDisposable ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Refresh Data", width, "Refresh data for the current option.\nThis resets unsaved changes.", false)) { - _editor.LoadMod(_editor.Mod!, _editor.GroupIdx, _editor.OptionIdx); + _editor.LoadMod(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx); ret = true; } @@ -422,17 +422,17 @@ public partial class ModEditWindow : Window, IDisposable ImGui.SetNextItemWidth(width.X); style.Push(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); using var color = ImRaii.PushColor(ImGuiCol.Border, ColorId.FolderLine.Value()); - using var combo = ImRaii.Combo("##optionSelector", _editor.Option.FullName); + using var combo = ImRaii.Combo("##optionSelector", _editor.Option!.GetFullName()); if (!combo) return ret; - foreach (var (option, idx) in Mod!.AllSubMods.WithIndex()) + foreach (var (option, idx) in Mod!.AllDataContainers.WithIndex()) { using var id = ImRaii.PushId(idx); - if (ImGui.Selectable(option.FullName, option == _editor.Option)) + if (ImGui.Selectable(option.GetFullName(), option == _editor.Option)) { - var (groupIdx, optionIdx) = option.GetIndices(); - _editor.LoadOption(groupIdx, optionIdx); + var (groupIdx, dataIdx) = option.GetDataIndices(); + _editor.LoadOption(groupIdx, dataIdx); ret = true; } } @@ -455,7 +455,7 @@ public partial class ModEditWindow : Window, IDisposable var tt = setsEqual ? "No changes staged." : "Apply the currently staged changes to the option."; ImGui.NewLine(); if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, setsEqual)) - _editor.SwapEditor.Apply(_editor.Mod!, _editor.GroupIdx, _editor.OptionIdx); + _editor.SwapEditor.Apply(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx); ImGui.SameLine(); tt = setsEqual ? "No changes staged." : "Revert all currently staged changes."; @@ -569,7 +569,7 @@ public partial class ModEditWindow : Window, IDisposable } if (Mod != null) - foreach (var option in Mod.AllSubMods) + foreach (var option in Mod.AllDataContainers) { foreach (var path in option.Files.Keys) { diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index c34c7ef0..bed31ab8 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -50,8 +50,7 @@ public class ModMergeTab(ModMerger modMerger) ImGui.SameLine(); DrawCombo(size - ImGui.GetItemRectSize().X - ImGui.GetStyle().ItemSpacing.X); - var width = ImGui.GetItemRectSize(); - using (var g = ImRaii.Group()) + using (ImRaii.Group()) { using var disabled = ImRaii.Disabled(modMerger.MergeFromMod.HasOptions); var buttonWidth = (size - ImGui.GetStyle().ItemSpacing.X) / 2; @@ -124,13 +123,13 @@ public class ModMergeTab(ModMerger modMerger) ImGui.Dummy(Vector2.One); var buttonSize = new Vector2((size - 2 * ImGui.GetStyle().ItemSpacing.X) / 3, 0); if (ImGui.Button("Select All", buttonSize)) - modMerger.SelectedOptions.UnionWith(modMerger.MergeFromMod!.AllSubMods); + modMerger.SelectedOptions.UnionWith(modMerger.MergeFromMod!.AllDataContainers); ImGui.SameLine(); if (ImGui.Button("Unselect All", buttonSize)) modMerger.SelectedOptions.Clear(); ImGui.SameLine(); if (ImGui.Button("Invert Selection", buttonSize)) - modMerger.SelectedOptions.SymmetricExceptWith(modMerger.MergeFromMod!.AllSubMods); + modMerger.SelectedOptions.SymmetricExceptWith(modMerger.MergeFromMod!.AllDataContainers); DrawOptionTable(size); } @@ -144,7 +143,7 @@ public class ModMergeTab(ModMerger modMerger) private void DrawOptionTable(float size) { - var options = modMerger.MergeFromMod!.AllSubMods.ToList(); + var options = modMerger.MergeFromMod!.AllDataContainers.ToList(); var height = modMerger.Warnings.Count == 0 && modMerger.Error == null ? ImGui.GetContentRegionAvail().Y - 3 * ImGui.GetFrameHeightWithSpacing() : 8 * ImGui.GetFrameHeightWithSpacing(); @@ -176,47 +175,41 @@ public class ModMergeTab(ModMerger modMerger) if (ImGui.Checkbox("##check", ref selected)) Handle(option, selected); - if (option.IsDefault) + if (option.Group is not { } group) { - ImGuiUtil.DrawTableColumn(option.FullName); + ImGuiUtil.DrawTableColumn(option.GetFullName()); ImGui.TableNextColumn(); } else { - ImGuiUtil.DrawTableColumn(option.Name); - var group = option.Group; - var optionEnumerator = group switch - { - SingleModGroup single => single.OptionData, - MultiModGroup multi => multi.PrioritizedOptions.Select(o => o.Mod), - _ => [], - }; + ImGuiUtil.DrawTableColumn(option.GetName()); + ImGui.TableNextColumn(); ImGui.Selectable(group.Name, false); if (ImGui.BeginPopupContextItem("##groupContext")) { if (ImGui.MenuItem("Select All")) // ReSharper disable once PossibleMultipleEnumeration - foreach (var opt in optionEnumerator) + foreach (var opt in group.DataContainers) Handle(opt, true); if (ImGui.MenuItem("Unselect All")) // ReSharper disable once PossibleMultipleEnumeration - foreach (var opt in optionEnumerator) + foreach (var opt in group.DataContainers) Handle(opt, false); ImGui.EndPopup(); } } ImGui.TableNextColumn(); - ImGuiUtil.RightAlign(option.FileData.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); + ImGuiUtil.RightAlign(option.Files.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); ImGui.TableNextColumn(); - ImGuiUtil.RightAlign(option.FileSwapData.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); + ImGuiUtil.RightAlign(option.FileSwaps.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); ImGui.TableNextColumn(); ImGuiUtil.RightAlign(option.Manipulations.Count.ToString(), 3 * ImGuiHelpers.GlobalScale); continue; - void Handle(SubMod option2, bool selected2) + void Handle(IModDataContainer option2, bool selected2) { if (selected2) modMerger.SelectedOptions.Add(option2); diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 0dc694d8..c05f1ac1 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -486,7 +486,7 @@ public class ModPanelEditTab( EditOption(panel, single, groupIdx, optionIdx); break; case MultiModGroup multi: - for (var optionIdx = 0; optionIdx < multi.PrioritizedOptions.Count; ++optionIdx) + for (var optionIdx = 0; optionIdx < multi.OptionData.Count; ++optionIdx) EditOption(panel, multi, groupIdx, optionIdx); break; } @@ -542,7 +542,7 @@ public class ModPanelEditTab( if (group is not MultiModGroup multi) return; - if (Input.Priority("##Priority", groupIdx, optionIdx, multi.PrioritizedOptions[optionIdx].Priority, out var priority, + if (Input.Priority("##Priority", groupIdx, optionIdx, multi.OptionData[optionIdx].Priority, out var priority, 50 * UiHelpers.Scale)) panel._modManager.OptionEditor.ChangeOptionPriority(panel._mod, groupIdx, optionIdx, priority); @@ -557,7 +557,7 @@ public class ModPanelEditTab( var count = group switch { SingleModGroup single => single.OptionData.Count, - MultiModGroup multi => multi.PrioritizedOptions.Count, + MultiModGroup multi => multi.OptionData.Count, _ => throw new Exception($"Dragging options to an option group of type {group.GetType()} is not supported."), }; ImGui.TableNextColumn(); @@ -591,6 +591,9 @@ public class ModPanelEditTab( // Handle drag and drop to move options inside a group or into another group. private static void Source(IModGroup group, int groupIdx, int optionIdx) { + if (group is not ITexToolsGroup) + return; + using var source = ImRaii.DragDropSource(); if (!source) return; @@ -606,6 +609,9 @@ public class ModPanelEditTab( private static void Target(ModPanelEditTab panel, IModGroup group, int groupIdx, int optionIdx) { + if (group is not ITexToolsGroup) + return; + using var target = ImRaii.DragDropTarget(); if (!target.Success || !ImGuiUtil.IsDropping(DragDropLabel)) return; @@ -624,22 +630,12 @@ public class ModPanelEditTab( var sourceGroupIdx = _dragDropGroupIdx; var sourceOption = _dragDropOptionIdx; var sourceGroup = panel._mod.Groups[sourceGroupIdx]; - var currentCount = group switch - { - SingleModGroup single => single.OptionData.Count, - MultiModGroup multi => multi.PrioritizedOptions.Count, - _ => throw new Exception($"Dragging options to an option group of type {group.GetType()} is not supported."), - }; - var (option, priority) = sourceGroup switch - { - SingleModGroup single => (single.OptionData[_dragDropOptionIdx], ModPriority.Default), - MultiModGroup multi => multi.PrioritizedOptions[_dragDropOptionIdx], - _ => throw new Exception($"Dragging options from an option group of type {sourceGroup.GetType()} is not supported."), - }; + var currentCount = group.DataContainers.Count; + var option = ((ITexToolsGroup) sourceGroup).OptionData[_dragDropOptionIdx]; panel._delayedActions.Enqueue(() => { panel._modManager.OptionEditor.DeleteOption(panel._mod, sourceGroupIdx, sourceOption); - panel._modManager.OptionEditor.AddOption(panel._mod, groupIdx, option, priority); + panel._modManager.OptionEditor.AddOption(panel._mod, groupIdx, option); panel._modManager.OptionEditor.MoveOption(panel._mod, groupIdx, currentCount, optionIdx); }); } diff --git a/Penumbra/UI/ModsTab/ModPanelTabBar.cs b/Penumbra/UI/ModsTab/ModPanelTabBar.cs index 02ec9a32..1aaa7741 100644 --- a/Penumbra/UI/ModsTab/ModPanelTabBar.cs +++ b/Penumbra/UI/ModsTab/ModPanelTabBar.cs @@ -114,7 +114,7 @@ public class ModPanelTabBar if (ImGui.TabItemButton("Advanced Editing", ImGuiTabItemFlags.Trailing | ImGuiTabItemFlags.NoTooltip)) { _modEditWindow.ChangeMod(mod); - _modEditWindow.ChangeOption((SubMod)mod.Default); + _modEditWindow.ChangeOption(mod.Default); _modEditWindow.IsOpen = true; } From 514121d8c133baf711c19a9ca1dfa585f6043f6d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 24 Apr 2024 23:28:12 +0200 Subject: [PATCH 0576/1381] Reorder stuff. --- Penumbra/Api/Api/ModSettingsApi.cs | 3 +- Penumbra/Api/Api/TemporaryApi.cs | 2 +- Penumbra/Api/TempModManager.cs | 2 +- .../Cache/CollectionCacheManager.cs | 2 +- .../Collections/Manager/CollectionEditor.cs | 2 +- .../Collections/Manager/CollectionStorage.cs | 2 +- .../Manager/ModCollectionMigration.cs | 2 +- Penumbra/Collections/ModCollection.cs | 2 +- Penumbra/Collections/ModCollectionSave.cs | 2 +- Penumbra/Communication/ModSettingChanged.cs | 2 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 4 +- Penumbra/Meta/MetaFileManager.cs | 2 +- Penumbra/Mods/Editor/DuplicateManager.cs | 3 +- Penumbra/Mods/Editor/FileRegistry.cs | 2 +- Penumbra/Mods/Editor/IMod.cs | 3 +- Penumbra/Mods/Editor/ModEditor.cs | 3 +- Penumbra/Mods/Editor/ModFileCollection.cs | 2 +- Penumbra/Mods/Editor/ModFileEditor.cs | 2 +- Penumbra/Mods/Editor/ModMerger.cs | 2 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 +- Penumbra/Mods/Editor/ModNormalizer.cs | 3 +- Penumbra/Mods/Editor/ModSwapEditor.cs | 2 +- .../Mods/{Subclasses => Groups}/IModGroup.cs | 86 +---- Penumbra/Mods/Groups/ModSaveGroup.cs | 57 +++ .../{Subclasses => Groups}/MultiModGroup.cs | 30 +- .../{Subclasses => Groups}/SingleModGroup.cs | 28 +- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 2 +- Penumbra/Mods/Manager/ModCacheManager.cs | 1 - Penumbra/Mods/Manager/ModMigration.cs | 4 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 4 +- Penumbra/Mods/Mod.cs | 5 +- Penumbra/Mods/ModCreator.cs | 4 +- Penumbra/Mods/ModLocalData.cs | 20 +- Penumbra/Mods/ModMeta.cs | 24 +- .../{Subclasses => Settings}/ModPriority.cs | 2 +- .../{Subclasses => Settings}/ModSettings.cs | 5 +- .../Mods/{Subclasses => Settings}/Setting.cs | 2 +- .../{Subclasses => Settings}/SettingList.cs | 2 +- Penumbra/Mods/SubMods/DefaultSubMod.cs | 30 ++ .../IModDataContainer.cs | 27 +- .../{Subclasses => SubMods}/IModOption.cs | 8 +- Penumbra/Mods/SubMods/MultiSubMod.cs | 92 +++++ Penumbra/Mods/SubMods/SingleSubMod.cs | 82 ++++ Penumbra/Mods/Subclasses/SubMod.cs | 352 ------------------ Penumbra/Mods/TemporaryMod.cs | 6 +- Penumbra/Penumbra.csproj | 4 + Penumbra/Services/ConfigMigrationService.cs | 2 +- Penumbra/Services/SaveService.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 3 +- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 2 +- .../ModEditWindow.QuickImport.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 2 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 3 +- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 4 +- Penumbra/UI/ModsTab/ModPanelTabBar.cs | 1 - 58 files changed, 416 insertions(+), 539 deletions(-) rename Penumbra/Mods/{Subclasses => Groups}/IModGroup.cs (50%) create mode 100644 Penumbra/Mods/Groups/ModSaveGroup.cs rename Penumbra/Mods/{Subclasses => Groups}/MultiModGroup.cs (83%) rename Penumbra/Mods/{Subclasses => Groups}/SingleModGroup.cs (85%) rename Penumbra/Mods/{Subclasses => Settings}/ModPriority.cs (98%) rename Penumbra/Mods/{Subclasses => Settings}/ModSettings.cs (98%) rename Penumbra/Mods/{Subclasses => Settings}/Setting.cs (98%) rename Penumbra/Mods/{Subclasses => Settings}/SettingList.cs (97%) create mode 100644 Penumbra/Mods/SubMods/DefaultSubMod.cs rename Penumbra/Mods/{Subclasses => SubMods}/IModDataContainer.cs (80%) rename Penumbra/Mods/{Subclasses => SubMods}/IModOption.cs (72%) create mode 100644 Penumbra/Mods/SubMods/MultiSubMod.cs create mode 100644 Penumbra/Mods/SubMods/SingleSubMod.cs delete mode 100644 Penumbra/Mods/Subclasses/SubMod.cs diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index e145e027..039fbfa9 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -8,8 +8,9 @@ using Penumbra.Communication; using Penumbra.Interop.PathResolving; using Penumbra.Mods; using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; namespace Penumbra.Api.Api; diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index b4ffa8f4..38d080cc 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -5,7 +5,7 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.Interop; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.String.Classes; namespace Penumbra.Api.Api; diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index 7d682338..aee2b447 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -6,7 +6,7 @@ using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Collections.Manager; using Penumbra.Communication; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; namespace Penumbra.Api; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 4b5c4337..c1296414 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -8,7 +8,7 @@ using Penumbra.Interop.ResourceLoading; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 4af19e6b..0243de1e 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -2,7 +2,7 @@ using OtterGui; using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; namespace Penumbra.Collections.Manager; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 2da2a569..4e2fb7b7 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -5,7 +5,7 @@ using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; namespace Penumbra.Collections.Manager; diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index 053f0a2b..89743aa2 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -1,6 +1,6 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; using Penumbra.Util; diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index e666b151..4580e37a 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -1,7 +1,7 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Collections.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; namespace Penumbra.Collections; diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index acc38d83..e6bb069b 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -2,7 +2,7 @@ using Newtonsoft.Json.Linq; using Penumbra.Services; using Newtonsoft.Json; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; namespace Penumbra.Collections; diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index 968f78a7..a7da345b 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -4,7 +4,7 @@ using Penumbra.Api.Api; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Mods; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; namespace Penumbra.Communication; diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index b9cdda71..eb6d0b0c 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -3,7 +3,9 @@ using OtterGui; using Penumbra.Api.Enums; using Penumbra.Import.Structs; using Penumbra.Mods; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Util; using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 0e2e638b..cd99396b 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -11,7 +11,7 @@ using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta.Files; using Penumbra.Mods; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; using Penumbra.Services; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 92ec58b9..31aacbe1 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/FileRegistry.cs b/Penumbra/Mods/Editor/FileRegistry.cs index 44d349ce..a484c8c2 100644 --- a/Penumbra/Mods/Editor/FileRegistry.cs +++ b/Penumbra/Mods/Editor/FileRegistry.cs @@ -1,4 +1,4 @@ -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index c4c4be2f..d4c881e9 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index 1118f890..e1c5962f 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -1,6 +1,7 @@ using OtterGui; using OtterGui.Compression; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; +using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index ede35914..551d04cf 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -1,5 +1,5 @@ using OtterGui; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 11e35334..00685c94 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -1,5 +1,5 @@ using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 541c84ae..0f629bc7 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -5,7 +5,7 @@ using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.UI.ModsTab; diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 88e48f0f..dee700d5 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,6 +1,6 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index db00a1c7..e2088b32 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -3,8 +3,9 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; using OtterGui.Tasks; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index 64788cf3..3247cfdf 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -1,6 +1,6 @@ using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; using Penumbra.Util; diff --git a/Penumbra/Mods/Subclasses/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs similarity index 50% rename from Penumbra/Mods/Subclasses/IModGroup.cs rename to Penumbra/Mods/Groups/IModGroup.cs index 5c500793..dc5150cf 100644 --- a/Penumbra/Mods/Subclasses/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -1,11 +1,11 @@ -using FFXIVClientStructs.FFXIV.Client.UI.Agent; using Newtonsoft.Json; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; -using Penumbra.Services; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Groups; public interface ITexToolsGroup { @@ -16,22 +16,22 @@ public interface IModGroup { public const int MaxMultiOptions = 63; - public Mod Mod { get; } - public string Name { get; } - public string Description { get; } - public GroupType Type { get; } - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; } + public string Name { get; } + public string Description { get; } + public GroupType Type { get; } + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public FullPath? FindBestMatch(Utf8GamePath gamePath); - public int AddOption(Mod mod, string name, string description = ""); + public int AddOption(Mod mod, string name, string description = ""); - public IReadOnlyList Options { get; } + public IReadOnlyList Options { get; } public IReadOnlyList DataContainers { get; } - public bool IsOption { get; } + public bool IsOption { get; } public IModGroup Convert(GroupType type); - public bool MoveOption(int optionIdxFrom, int optionIdxTo); + public bool MoveOption(int optionIdxFrom, int optionIdxTo); public int GetIndex(); @@ -88,67 +88,15 @@ public interface IModGroup public static (int Redirections, int Swaps, int Manips) GetCountsBase(IModGroup group) { var redirectionCount = 0; - var swapCount = 0; - var manipCount = 0; + var swapCount = 0; + var manipCount = 0; foreach (var option in group.DataContainers) { redirectionCount += option.Files.Count; - swapCount += option.FileSwaps.Count; - manipCount += option.Manipulations.Count; + swapCount += option.FileSwaps.Count; + manipCount += option.Manipulations.Count; } return (redirectionCount, swapCount, manipCount); } } - -public readonly struct ModSaveGroup : ISavable -{ - private readonly DirectoryInfo _basePath; - private readonly IModGroup? _group; - private readonly int _groupIdx; - private readonly DefaultSubMod? _defaultMod; - private readonly bool _onlyAscii; - - public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) - { - _basePath = mod.ModPath; - _groupIdx = groupIdx; - if (_groupIdx < 0) - _defaultMod = mod.Default; - else - _group = mod.Groups[_groupIdx]; - _onlyAscii = onlyAscii; - } - - public ModSaveGroup(DirectoryInfo basePath, IModGroup group, int groupIdx, bool onlyAscii) - { - _basePath = basePath; - _group = group; - _groupIdx = groupIdx; - _onlyAscii = onlyAscii; - } - - public ModSaveGroup(DirectoryInfo basePath, DefaultSubMod @default, bool onlyAscii) - { - _basePath = basePath; - _groupIdx = -1; - _defaultMod = @default; - _onlyAscii = onlyAscii; - } - - public string ToFilename(FilenameService fileNames) - => fileNames.OptionGroupFile(_basePath.FullName, _groupIdx, _group?.Name ?? string.Empty, _onlyAscii); - - public void Save(StreamWriter writer) - { - using var j = new JsonTextWriter(writer); - j.Formatting = Formatting.Indented; - var serializer = new JsonSerializer { Formatting = Formatting.Indented }; - j.WriteStartObject(); - if (_groupIdx >= 0) - _group!.WriteJson(j, serializer); - else - IModDataContainer.WriteModData(j, serializer, _defaultMod!, _basePath); - j.WriteEndObject(); - } -} diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs new file mode 100644 index 00000000..ed81f42f --- /dev/null +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -0,0 +1,57 @@ +using Newtonsoft.Json; +using Penumbra.Mods.SubMods; +using Penumbra.Services; + +namespace Penumbra.Mods.Groups; + +public readonly struct ModSaveGroup : ISavable +{ + private readonly DirectoryInfo _basePath; + private readonly IModGroup? _group; + private readonly int _groupIdx; + private readonly DefaultSubMod? _defaultMod; + private readonly bool _onlyAscii; + + public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) + { + _basePath = mod.ModPath; + _groupIdx = groupIdx; + if (_groupIdx < 0) + _defaultMod = mod.Default; + else + _group = mod.Groups[_groupIdx]; + _onlyAscii = onlyAscii; + } + + public ModSaveGroup(DirectoryInfo basePath, IModGroup group, int groupIdx, bool onlyAscii) + { + _basePath = basePath; + _group = group; + _groupIdx = groupIdx; + _onlyAscii = onlyAscii; + } + + public ModSaveGroup(DirectoryInfo basePath, DefaultSubMod @default, bool onlyAscii) + { + _basePath = basePath; + _groupIdx = -1; + _defaultMod = @default; + _onlyAscii = onlyAscii; + } + + public string ToFilename(FilenameService fileNames) + => fileNames.OptionGroupFile(_basePath.FullName, _groupIdx, _group?.Name ?? string.Empty, _onlyAscii); + + public void Save(StreamWriter writer) + { + using var j = new JsonTextWriter(writer); + j.Formatting = Formatting.Indented; + var serializer = new JsonSerializer { Formatting = Formatting.Indented }; + j.WriteStartObject(); + if (_groupIdx >= 0) + _group!.WriteJson(j, serializer); + else + IModDataContainer.WriteModData(j, serializer, _defaultMod!, _basePath); + j.WriteEndObject(); + } +} diff --git a/Penumbra/Mods/Subclasses/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs similarity index 83% rename from Penumbra/Mods/Subclasses/MultiModGroup.cs rename to Penumbra/Mods/Groups/MultiModGroup.cs index f194350a..f39f2e70 100644 --- a/Penumbra/Mods/Subclasses/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -6,9 +6,11 @@ using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Groups; /// Groups that allow all available options to be selected at once. public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup @@ -16,11 +18,11 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public GroupType Type => GroupType.Multi; - public Mod Mod { get; set; } = mod; - public string Name { get; set; } = "Group"; - public string Description { get; set; } = "A non-exclusive group of settings."; - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; set; } = mod; + public string Name { get; set; } = "Group"; + public string Description { get; set; } = "A non-exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public readonly List OptionData = []; public IReadOnlyList Options @@ -45,7 +47,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup var subMod = new MultiSubMod(mod, this) { - Name = name, + Name = name, Description = description, }; OptionData.Add(subMod); @@ -56,9 +58,9 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup { var ret = new MultiModGroup(mod) { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) @@ -93,9 +95,9 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup case GroupType.Single: var single = new SingleModGroup(Mod) { - Name = Name, - Description = Description, - Priority = Priority, + Name = Name, + Description = Description, + Priority = Priority, DefaultSettings = DefaultSettings.TurnMulti(OptionData.Count), }; single.OptionData.AddRange(OptionData.Select(o => o.ConvertToSingle(Mod, single))); @@ -152,7 +154,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup => IModGroup.GetCountsBase(this); public Setting FixSetting(Setting setting) - => new(setting.Value & ((1ul << OptionData.Count) - 1)); + => new(setting.Value & (1ul << OptionData.Count) - 1); /// Create a group without a mod only for saving it in the creator. internal static MultiModGroup CreateForSaving(string name) diff --git a/Penumbra/Mods/Subclasses/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs similarity index 85% rename from Penumbra/Mods/Subclasses/SingleModGroup.cs rename to Penumbra/Mods/Groups/SingleModGroup.cs index d1a3b6d1..6011185a 100644 --- a/Penumbra/Mods/Subclasses/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -4,9 +4,11 @@ using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Groups; /// Groups that allow only one of their available options to be selected. public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup @@ -14,11 +16,11 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public GroupType Type => GroupType.Single; - public Mod Mod { get; set; } = mod; - public string Name { get; set; } = "Option"; - public string Description { get; set; } = "A mutually exclusive group of settings."; - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; set; } = mod; + public string Name { get; set; } = "Option"; + public string Description { get; set; } = "A mutually exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public readonly List OptionData = []; @@ -34,7 +36,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup { var subMod = new SingleSubMod(mod, this) { - Name = name, + Name = name, Description = description, }; OptionData.Add(subMod); @@ -55,9 +57,9 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup var options = json["Options"]; var ret = new SingleModGroup(mod) { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) @@ -82,9 +84,9 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup case GroupType.Multi: var multi = new MultiModGroup(Mod) { - Name = Name, - Description = Description, - Priority = Priority, + Name = Name, + Description = Description, + Priority = Priority, DefaultSettings = Setting.Multi((int)DefaultSettings.Value), }; multi.OptionData.AddRange(OptionData.Select((o, i) => o.ConvertToMulti(Mod, multi, new ModPriority(i)))); diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 21b9ef2c..1545811e 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -7,7 +7,7 @@ using Penumbra.String.Classes; using Penumbra.Meta; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; namespace Penumbra.Mods.ItemSwap; diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 4f9e8648..3ff1a333 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -2,7 +2,6 @@ using Penumbra.Communication; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Subclasses; using Penumbra.Services; namespace Penumbra.Mods.Manager; diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 8c4a5674..f160d5bd 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -2,7 +2,9 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using Penumbra.Api.Enums; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index 4d3a5717..b66fec17 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -4,7 +4,9 @@ using OtterGui.Classes; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Util; diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 5c02213e..fc84afcc 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,9 +1,10 @@ using OtterGui; using OtterGui.Classes; -using Penumbra.Collections.Cache; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.Mods; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index c1236037..e8113ee1 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -9,8 +9,10 @@ using Penumbra.GameData.Data; using Penumbra.Import; using Penumbra.Import.Structs; using Penumbra.Meta; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/ModLocalData.cs b/Penumbra/Mods/ModLocalData.cs index 51fe8d58..beda0dc7 100644 --- a/Penumbra/Mods/ModLocalData.cs +++ b/Penumbra/Mods/ModLocalData.cs @@ -5,29 +5,25 @@ using Penumbra.Services; namespace Penumbra.Mods; -public readonly struct ModLocalData : ISavable +public readonly struct ModLocalData(Mod mod) : ISavable { public const int FileVersion = 3; - private readonly Mod _mod; - - public ModLocalData(Mod mod) - => _mod = mod; - public string ToFilename(FilenameService fileNames) - => fileNames.LocalDataFile(_mod); + => fileNames.LocalDataFile(mod); public void Save(StreamWriter writer) { var jObject = new JObject { { nameof(FileVersion), JToken.FromObject(FileVersion) }, - { nameof(Mod.ImportDate), JToken.FromObject(_mod.ImportDate) }, - { nameof(Mod.LocalTags), JToken.FromObject(_mod.LocalTags) }, - { nameof(Mod.Note), JToken.FromObject(_mod.Note) }, - { nameof(Mod.Favorite), JToken.FromObject(_mod.Favorite) }, + { nameof(Mod.ImportDate), JToken.FromObject(mod.ImportDate) }, + { nameof(Mod.LocalTags), JToken.FromObject(mod.LocalTags) }, + { nameof(Mod.Note), JToken.FromObject(mod.Note) }, + { nameof(Mod.Favorite), JToken.FromObject(mod.Favorite) }, }; - using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + using var jWriter = new JsonTextWriter(writer); + jWriter.Formatting = Formatting.Indented; jObject.WriteTo(jWriter); } diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index d29cdb9c..870d6d4f 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -4,31 +4,27 @@ using Penumbra.Services; namespace Penumbra.Mods; -public readonly struct ModMeta : ISavable +public readonly struct ModMeta(Mod mod) : ISavable { public const uint FileVersion = 3; - private readonly Mod _mod; - - public ModMeta(Mod mod) - => _mod = mod; - public string ToFilename(FilenameService fileNames) - => fileNames.ModMetaPath(_mod); + => fileNames.ModMetaPath(mod); public void Save(StreamWriter writer) { var jObject = new JObject { { nameof(FileVersion), JToken.FromObject(FileVersion) }, - { nameof(Mod.Name), JToken.FromObject(_mod.Name) }, - { nameof(Mod.Author), JToken.FromObject(_mod.Author) }, - { nameof(Mod.Description), JToken.FromObject(_mod.Description) }, - { nameof(Mod.Version), JToken.FromObject(_mod.Version) }, - { nameof(Mod.Website), JToken.FromObject(_mod.Website) }, - { nameof(Mod.ModTags), JToken.FromObject(_mod.ModTags) }, + { nameof(Mod.Name), JToken.FromObject(mod.Name) }, + { nameof(Mod.Author), JToken.FromObject(mod.Author) }, + { nameof(Mod.Description), JToken.FromObject(mod.Description) }, + { nameof(Mod.Version), JToken.FromObject(mod.Version) }, + { nameof(Mod.Website), JToken.FromObject(mod.Website) }, + { nameof(Mod.ModTags), JToken.FromObject(mod.ModTags) }, }; - using var jWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented }; + using var jWriter = new JsonTextWriter(writer); + jWriter.Formatting = Formatting.Indented; jObject.WriteTo(jWriter); } } diff --git a/Penumbra/Mods/Subclasses/ModPriority.cs b/Penumbra/Mods/Settings/ModPriority.cs similarity index 98% rename from Penumbra/Mods/Subclasses/ModPriority.cs rename to Penumbra/Mods/Settings/ModPriority.cs index a99c12ed..993bd577 100644 --- a/Penumbra/Mods/Subclasses/ModPriority.cs +++ b/Penumbra/Mods/Settings/ModPriority.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Settings; [JsonConverter(typeof(Converter))] public readonly record struct ModPriority(int Value) : diff --git a/Penumbra/Mods/Subclasses/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs similarity index 98% rename from Penumbra/Mods/Subclasses/ModSettings.cs rename to Penumbra/Mods/Settings/ModSettings.cs index 2ddabdb8..db9e0521 100644 --- a/Penumbra/Mods/Subclasses/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -1,12 +1,11 @@ using OtterGui; using OtterGui.Filesystem; using Penumbra.Api.Enums; -using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; -using Penumbra.String.Classes; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Settings; /// Contains the settings for a given mod. public class ModSettings diff --git a/Penumbra/Mods/Subclasses/Setting.cs b/Penumbra/Mods/Settings/Setting.cs similarity index 98% rename from Penumbra/Mods/Subclasses/Setting.cs rename to Penumbra/Mods/Settings/Setting.cs index 18b1e4ca..231529b8 100644 --- a/Penumbra/Mods/Subclasses/Setting.cs +++ b/Penumbra/Mods/Settings/Setting.cs @@ -1,7 +1,7 @@ using Newtonsoft.Json; using OtterGui; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Settings; [JsonConverter(typeof(Converter))] public readonly record struct Setting(ulong Value) diff --git a/Penumbra/Mods/Subclasses/SettingList.cs b/Penumbra/Mods/Settings/SettingList.cs similarity index 97% rename from Penumbra/Mods/Subclasses/SettingList.cs rename to Penumbra/Mods/Settings/SettingList.cs index ea1e447f..67b1b947 100644 --- a/Penumbra/Mods/Subclasses/SettingList.cs +++ b/Penumbra/Mods/Settings/SettingList.cs @@ -1,4 +1,4 @@ -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.Settings; public class SettingList : List { diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs new file mode 100644 index 00000000..ced0cd0d --- /dev/null +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -0,0 +1,30 @@ +using Newtonsoft.Json.Linq; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + +public class DefaultSubMod(IMod mod) : IModDataContainer +{ + public const string FullName = "Default Option"; + + internal readonly IMod Mod = mod; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; + + IMod IModDataContainer.Mod + => Mod; + + IModGroup? IModDataContainer.Group + => null; + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (-1, 0); +} diff --git a/Penumbra/Mods/Subclasses/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs similarity index 80% rename from Penumbra/Mods/Subclasses/IModDataContainer.cs rename to Penumbra/Mods/SubMods/IModDataContainer.cs index a26beb2a..18b3b23f 100644 --- a/Penumbra/Mods/Subclasses/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -2,18 +2,19 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; using Penumbra.String.Classes; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.SubMods; public interface IModDataContainer { - public IMod Mod { get; } + public IMod Mod { get; } public IModGroup? Group { get; } - public Dictionary Files { get; set; } - public Dictionary FileSwaps { get; set; } - public HashSet Manipulations { get; set; } + public Dictionary Files { get; set; } + public Dictionary FileSwaps { get; set; } + public HashSet Manipulations { get; set; } public void AddDataTo(Dictionary redirections, HashSet manipulations) { @@ -28,24 +29,24 @@ public interface IModDataContainer public string GetName() => this switch { - IModOption o => o.FullName, + IModOption o => o.FullName, DefaultSubMod => DefaultSubMod.FullName, - _ => $"Container {GetDataIndices().DataIndex + 1}", + _ => $"Container {GetDataIndices().DataIndex + 1}", }; public string GetFullName() => this switch { - IModOption o => o.FullName, - DefaultSubMod => DefaultSubMod.FullName, + IModOption o => o.FullName, + DefaultSubMod => DefaultSubMod.FullName, _ when Group != null => $"{Group.Name}: Container {GetDataIndices().DataIndex + 1}", - _ => $"Container {GetDataIndices().DataIndex + 1}", + _ => $"Container {GetDataIndices().DataIndex + 1}", }; public static void Clone(IModDataContainer from, IModDataContainer to) { - to.Files = new Dictionary(from.Files); - to.FileSwaps = new Dictionary(from.FileSwaps); + to.Files = new Dictionary(from.Files); + to.FileSwaps = new Dictionary(from.FileSwaps); to.Manipulations = [.. from.Manipulations]; } @@ -126,3 +127,5 @@ public interface IModDataContainer } } } + +public interface IModDataOption : IModOption, IModDataContainer; diff --git a/Penumbra/Mods/Subclasses/IModOption.cs b/Penumbra/Mods/SubMods/IModOption.cs similarity index 72% rename from Penumbra/Mods/Subclasses/IModOption.cs rename to Penumbra/Mods/SubMods/IModOption.cs index f66ce44e..f1ce1d4c 100644 --- a/Penumbra/Mods/Subclasses/IModOption.cs +++ b/Penumbra/Mods/SubMods/IModOption.cs @@ -1,17 +1,17 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -namespace Penumbra.Mods.Subclasses; +namespace Penumbra.Mods.SubMods; public interface IModOption { - public string Name { get; set; } - public string FullName { get; } + public string Name { get; set; } + public string FullName { get; } public string Description { get; set; } public static void Load(JToken json, IModOption option) { - option.Name = json[nameof(Name)]?.ToObject() ?? string.Empty; + option.Name = json[nameof(Name)]?.ToObject() ?? string.Empty; option.Description = json[nameof(Description)]?.ToObject() ?? string.Empty; } diff --git a/Penumbra/Mods/SubMods/MultiSubMod.cs b/Penumbra/Mods/SubMods/MultiSubMod.cs new file mode 100644 index 00000000..00216b77 --- /dev/null +++ b/Penumbra/Mods/SubMods/MultiSubMod.cs @@ -0,0 +1,92 @@ +using Newtonsoft.Json.Linq; +using OtterGui; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + +public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption +{ + internal readonly Mod Mod = mod; + internal readonly MultiModGroup Group = group; + + public string Name { get; set; } = "Option"; + + public string FullName + => $"{Group.Name}: {Name}"; + + public string Description { get; set; } = string.Empty; + public ModPriority Priority { get; set; } = ModPriority.Default; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; + + IMod IModDataContainer.Mod + => Mod; + + IModGroup IModDataContainer.Group + => Group; + + + public MultiSubMod(Mod mod, MultiModGroup group, JToken json) + : this(mod, group) + { + IModOption.Load(json, this); + IModDataContainer.Load(json, this, mod.ModPath); + Priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; + } + + public MultiSubMod Clone(Mod mod, MultiModGroup group) + { + var ret = new MultiSubMod(mod, group) + { + Name = Name, + Description = Description, + Priority = Priority, + }; + IModDataContainer.Clone(this, ret); + + return ret; + } + + public SingleSubMod ConvertToSingle(Mod mod, SingleModGroup group) + { + var ret = new SingleSubMod(mod, group) + { + Name = Name, + Description = Description, + }; + IModDataContainer.Clone(this, ret); + return ret; + } + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + + public static MultiSubMod CreateForSaving(string name, string description, ModPriority priority) + => new(null!, null!) + { + Name = name, + Description = description, + Priority = priority, + }; + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), GetDataIndex()); + + public (int GroupIndex, int OptionIndex) GetOptionIndices() + => (Group.GetIndex(), GetDataIndex()); + + private int GetDataIndex() + { + var dataIndex = Group.DataContainers.IndexOf(this); + if (dataIndex < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); + + return dataIndex; + } +} diff --git a/Penumbra/Mods/SubMods/SingleSubMod.cs b/Penumbra/Mods/SubMods/SingleSubMod.cs new file mode 100644 index 00000000..499ab192 --- /dev/null +++ b/Penumbra/Mods/SubMods/SingleSubMod.cs @@ -0,0 +1,82 @@ +using Newtonsoft.Json.Linq; +using OtterGui; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + +public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption +{ + internal readonly Mod Mod = mod; + internal readonly SingleModGroup Group = group; + + public string Name { get; set; } = "Option"; + + public string FullName + => $"{Group.Name}: {Name}"; + + public string Description { get; set; } = string.Empty; + + IMod IModDataContainer.Mod + => Mod; + + IModGroup IModDataContainer.Group + => Group; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; + + public SingleSubMod(Mod mod, SingleModGroup group, JToken json) + : this(mod, group) + { + IModOption.Load(json, this); + IModDataContainer.Load(json, this, mod.ModPath); + } + + public SingleSubMod Clone(Mod mod, SingleModGroup group) + { + var ret = new SingleSubMod(mod, group) + { + Name = Name, + Description = Description, + }; + IModDataContainer.Clone(this, ret); + + return ret; + } + + public MultiSubMod ConvertToMulti(Mod mod, MultiModGroup group, ModPriority priority) + { + var ret = new MultiSubMod(mod, group) + { + Name = Name, + Description = Description, + Priority = priority, + }; + IModDataContainer.Clone(this, ret); + + return ret; + } + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), GetDataIndex()); + + public (int GroupIndex, int OptionIndex) GetOptionIndices() + => (Group.GetIndex(), GetDataIndex()); + + private int GetDataIndex() + { + var dataIndex = Group.DataContainers.IndexOf(this); + if (dataIndex < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); + + return dataIndex; + } +} diff --git a/Penumbra/Mods/Subclasses/SubMod.cs b/Penumbra/Mods/Subclasses/SubMod.cs deleted file mode 100644 index a2425eb7..00000000 --- a/Penumbra/Mods/Subclasses/SubMod.cs +++ /dev/null @@ -1,352 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using OtterGui; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Editor; -using Penumbra.String.Classes; - -namespace Penumbra.Mods.Subclasses; - -public interface IModDataOption : IModOption, IModDataContainer; - -public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption -{ - internal readonly Mod Mod = mod; - internal readonly SingleModGroup Group = group; - - public string Name { get; set; } = "Option"; - - public string FullName - => $"{Group.Name}: {Name}"; - - public string Description { get; set; } = string.Empty; - - IMod IModDataContainer.Mod - => Mod; - - IModGroup IModDataContainer.Group - => Group; - - public Dictionary Files { get; set; } = []; - public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; - - public SingleSubMod(Mod mod, SingleModGroup group, JToken json) - : this(mod, group) - { - IModOption.Load(json, this); - IModDataContainer.Load(json, this, mod.ModPath); - } - - public SingleSubMod Clone(Mod mod, SingleModGroup group) - { - var ret = new SingleSubMod(mod, group) - { - Name = Name, - Description = Description, - }; - IModDataContainer.Clone(this, ret); - - return ret; - } - - public MultiSubMod ConvertToMulti(Mod mod, MultiModGroup group, ModPriority priority) - { - var ret = new MultiSubMod(mod, group) - { - Name = Name, - Description = Description, - Priority = priority, - }; - IModDataContainer.Clone(this, ret); - - return ret; - } - - public void AddDataTo(Dictionary redirections, HashSet manipulations) - => ((IModDataContainer)this).AddDataTo(redirections, manipulations); - - public (int GroupIndex, int DataIndex) GetDataIndices() - => (Group.GetIndex(), GetDataIndex()); - - public (int GroupIndex, int OptionIndex) GetOptionIndices() - => (Group.GetIndex(), GetDataIndex()); - - private int GetDataIndex() - { - var dataIndex = Group.DataContainers.IndexOf(this); - if (dataIndex < 0) - throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); - - return dataIndex; - } -} - -public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption -{ - internal readonly Mod Mod = mod; - internal readonly MultiModGroup Group = group; - - public string Name { get; set; } = "Option"; - - public string FullName - => $"{Group.Name}: {Name}"; - - public string Description { get; set; } = string.Empty; - public ModPriority Priority { get; set; } = ModPriority.Default; - - public Dictionary Files { get; set; } = []; - public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; - - IMod IModDataContainer.Mod - => Mod; - - IModGroup IModDataContainer.Group - => Group; - - - public MultiSubMod(Mod mod, MultiModGroup group, JToken json) - : this(mod, group) - { - IModOption.Load(json, this); - IModDataContainer.Load(json, this, mod.ModPath); - Priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; - } - - public MultiSubMod Clone(Mod mod, MultiModGroup group) - { - var ret = new MultiSubMod(mod, group) - { - Name = Name, - Description = Description, - Priority = Priority, - }; - IModDataContainer.Clone(this, ret); - - return ret; - } - - public SingleSubMod ConvertToSingle(Mod mod, SingleModGroup group) - { - var ret = new SingleSubMod(mod, group) - { - Name = Name, - Description = Description, - }; - IModDataContainer.Clone(this, ret); - return ret; - } - - public void AddDataTo(Dictionary redirections, HashSet manipulations) - => ((IModDataContainer)this).AddDataTo(redirections, manipulations); - - public static MultiSubMod CreateForSaving(string name, string description, ModPriority priority) - => new(null!, null!) - { - Name = name, - Description = description, - Priority = priority, - }; - - public (int GroupIndex, int DataIndex) GetDataIndices() - => (Group.GetIndex(), GetDataIndex()); - - public (int GroupIndex, int OptionIndex) GetOptionIndices() - => (Group.GetIndex(), GetDataIndex()); - - private int GetDataIndex() - { - var dataIndex = Group.DataContainers.IndexOf(this); - if (dataIndex < 0) - throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); - - return dataIndex; - } -} - -public class DefaultSubMod(IMod mod) : IModDataContainer -{ - public const string FullName = "Default Option"; - - public string Description - => string.Empty; - - internal readonly IMod Mod = mod; - - public Dictionary Files { get; set; } = []; - public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; - - IMod IModDataContainer.Mod - => Mod; - - IModGroup? IModDataContainer.Group - => null; - - - public DefaultSubMod(Mod mod, JToken json) - : this(mod) - { - IModDataContainer.Load(json, this, mod.ModPath); - } - - public void AddDataTo(Dictionary redirections, HashSet manipulations) - => ((IModDataContainer)this).AddDataTo(redirections, manipulations); - - public (int GroupIndex, int DataIndex) GetDataIndices() - => (-1, 0); -} - - -//public sealed class SubMod(IMod mod, IModGroup group) : IModOption -//{ -// public string Name { get; set; } = "Default"; -// -// public string FullName -// => Group == null ? "Default Option" : $"{Group.Name}: {Name}"; -// -// public string Description { get; set; } = string.Empty; -// -// internal readonly IMod Mod = mod; -// internal readonly IModGroup? Group = group; -// -// internal (int GroupIdx, int OptionIdx) GetIndices() -// { -// if (IsDefault) -// return (-1, 0); -// -// var groupIdx = Mod.Groups.IndexOf(Group); -// if (groupIdx < 0) -// throw new Exception($"Group {Group.Name} from SubMod {Name} is not contained in Mod {Mod.Name}."); -// -// return (groupIdx, GetOptionIndex()); -// } -// -// private int GetOptionIndex() -// { -// var optionIndex = Group switch -// { -// null => 0, -// SingleModGroup single => single.OptionData.IndexOf(this), -// MultiModGroup multi => multi.OptionData.IndexOf(p => p.Mod == this), -// _ => throw new Exception($"Group {Group.Name} from SubMod {Name} has unknown type {typeof(Group)}"), -// }; -// if (optionIndex < 0) -// throw new Exception($"Group {Group!.Name} from SubMod {Name} does not contain this SubMod."); -// -// return optionIndex; -// } -// -// public static SubMod CreateDefault(IMod mod) -// => new(mod, null!); -// -// [MemberNotNullWhen(false, nameof(Group))] -// public bool IsDefault -// => Group == null; -// -// public void AddData(Dictionary redirections, HashSet manipulations) -// { -// foreach (var (path, file) in Files) -// redirections.TryAdd(path, file); -// -// foreach (var (path, file) in FileSwaps) -// redirections.TryAdd(path, file); -// manipulations.UnionWith(Manipulations); -// } -// -// public Dictionary FileData = []; -// public Dictionary FileSwapData = []; -// public HashSet ManipulationData = []; -// -// public IReadOnlyDictionary Files -// => FileData; -// -// public IReadOnlyDictionary FileSwaps -// => FileSwapData; -// -// public IReadOnlySet Manipulations -// => ManipulationData; -// -// public void Load(DirectoryInfo basePath, JToken json, out ModPriority priority) -// { -// FileData.Clear(); -// FileSwapData.Clear(); -// ManipulationData.Clear(); -// -// // Every option has a name, but priorities are only relevant for multi group options. -// Name = json[nameof(Name)]?.ToObject() ?? string.Empty; -// Description = json[nameof(Description)]?.ToObject() ?? string.Empty; -// priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; -// -// var files = (JObject?)json[nameof(Files)]; -// if (files != null) -// foreach (var property in files.Properties()) -// { -// if (Utf8GamePath.FromString(property.Name, out var p, true)) -// FileData.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); -// } -// -// var swaps = (JObject?)json[nameof(FileSwaps)]; -// if (swaps != null) -// foreach (var property in swaps.Properties()) -// { -// if (Utf8GamePath.FromString(property.Name, out var p, true)) -// FileSwapData.TryAdd(p, new FullPath(property.Value.ToObject()!)); -// } -// -// var manips = json[nameof(Manipulations)]; -// if (manips != null) -// foreach (var s in manips.Children().Select(c => c.ToObject()) -// .Where(m => m.Validate())) -// ManipulationData.Add(s); -// } -// -// -// /// Create a sub mod without a mod or group only for saving it in the creator. -// internal static SubMod CreateForSaving(string name) -// => new(null!, null!) -// { -// Name = name, -// }; -// -// -// public static void WriteSubMod(JsonWriter j, JsonSerializer serializer, SubMod mod, DirectoryInfo basePath, ModPriority? priority) -// { -// j.WriteStartObject(); -// j.WritePropertyName(nameof(Name)); -// j.WriteValue(mod.Name); -// j.WritePropertyName(nameof(Description)); -// j.WriteValue(mod.Description); -// if (priority != null) -// { -// j.WritePropertyName(nameof(IModGroup.Priority)); -// j.WriteValue(priority.Value.Value); -// } -// -// j.WritePropertyName(nameof(mod.Files)); -// j.WriteStartObject(); -// foreach (var (gamePath, file) in mod.Files) -// { -// if (file.ToRelPath(basePath, out var relPath)) -// { -// j.WritePropertyName(gamePath.ToString()); -// j.WriteValue(relPath.ToString()); -// } -// } -// -// j.WriteEndObject(); -// j.WritePropertyName(nameof(mod.FileSwaps)); -// j.WriteStartObject(); -// foreach (var (gamePath, file) in mod.FileSwaps) -// { -// j.WritePropertyName(gamePath.ToString()); -// j.WriteValue(file.ToString()); -// } -// -// j.WriteEndObject(); -// j.WritePropertyName(nameof(mod.Manipulations)); -// serializer.Serialize(j, mod.Manipulations); -// j.WriteEndObject(); -// } -//} diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 393369d4..d08c8b06 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -2,8 +2,10 @@ using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; @@ -46,7 +48,7 @@ public class TemporaryMod : IMod => Array.Empty(); public TemporaryMod() - => Default = new(this); + => Default = new DefaultSubMod(this); public void SetFile(Utf8GamePath gamePath, FullPath fullPath) => Default.Files[gamePath] = fullPath; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index c8961579..0ec1fd44 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -93,6 +93,10 @@ + + + + diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index e775d81a..fafaa0e5 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -10,7 +10,7 @@ using Penumbra.Interop.Services; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.UI; using Penumbra.UI.Classes; using Penumbra.UI.ResourceWatcher; diff --git a/Penumbra/Services/SaveService.cs b/Penumbra/Services/SaveService.cs index 801e0c1d..8d3cb641 100644 --- a/Penumbra/Services/SaveService.cs +++ b/Penumbra/Services/SaveService.cs @@ -2,7 +2,7 @@ using OtterGui.Classes; using OtterGui.Log; using OtterGui.Services; using Penumbra.Mods; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Groups; namespace Penumbra.Services; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 5125a5b2..77bdb161 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -13,9 +13,10 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; using Penumbra.Mods; +using Penumbra.Mods.Groups; using Penumbra.Mods.ItemSwap; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 94f1d577..107c56e6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -4,7 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using Penumbra.Mods.Editor; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 70854fe7..55b7e748 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -8,7 +8,7 @@ using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; using Penumbra.Mods; using Penumbra.Mods.Editor; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 21d14f78..dbb88fb7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -21,7 +21,7 @@ using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index bed31ab8..5dad66b4 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -4,7 +4,7 @@ using OtterGui; using OtterGui.Raii; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.SubMods; using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 11a2d96f..5b6cfa99 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -14,7 +14,7 @@ using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.Services; using Penumbra.UI.Classes; using MessageService = Penumbra.Services.MessageService; diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index b2cfaf25..5e3aac48 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -9,7 +9,7 @@ using Penumbra.Collections.Manager; using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.Mods.Editor; -using Penumbra.Mods.Subclasses; +using Penumbra.Mods.Settings; using Penumbra.String.Classes; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index c05f1ac1..afbef45d 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -11,9 +11,10 @@ using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; using Penumbra.Services; using Penumbra.UI.AdvancedWindow; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index cb76088c..1326a763 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -8,8 +8,10 @@ using Penumbra.UI.Classes; using Dalamud.Interface.Components; using Penumbra.Collections.Manager; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; using Penumbra.Services; +using Penumbra.Mods.SubMods; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/UI/ModsTab/ModPanelTabBar.cs b/Penumbra/UI/ModsTab/ModPanelTabBar.cs index 1aaa7741..8b09d8b9 100644 --- a/Penumbra/UI/ModsTab/ModPanelTabBar.cs +++ b/Penumbra/UI/ModsTab/ModPanelTabBar.cs @@ -5,7 +5,6 @@ using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Mods.Subclasses; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; From cd76c31d8ce73402b40e45d73dace053cc8a28b5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 24 Apr 2024 23:41:55 +0200 Subject: [PATCH 0577/1381] Fix stack overflow. --- Penumbra/Mods/SubMods/DefaultSubMod.cs | 2 +- Penumbra/Mods/SubMods/IModDataContainer.cs | 8 ++++---- Penumbra/Mods/SubMods/MultiSubMod.cs | 2 +- Penumbra/Mods/SubMods/SingleSubMod.cs | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index ced0cd0d..8b166505 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -23,7 +23,7 @@ public class DefaultSubMod(IMod mod) : IModDataContainer => null; public void AddDataTo(Dictionary redirections, HashSet manipulations) - => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + => IModDataContainer.AddDataTo(this, redirections, manipulations); public (int GroupIndex, int DataIndex) GetDataIndices() => (-1, 0); diff --git a/Penumbra/Mods/SubMods/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs index 18b3b23f..c9420821 100644 --- a/Penumbra/Mods/SubMods/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -16,14 +16,14 @@ public interface IModDataContainer public Dictionary FileSwaps { get; set; } public HashSet Manipulations { get; set; } - public void AddDataTo(Dictionary redirections, HashSet manipulations) + public static void AddDataTo(IModDataContainer container, Dictionary redirections, HashSet manipulations) { - foreach (var (path, file) in Files) + foreach (var (path, file) in container.Files) redirections.TryAdd(path, file); - foreach (var (path, file) in FileSwaps) + foreach (var (path, file) in container.FileSwaps) redirections.TryAdd(path, file); - manipulations.UnionWith(Manipulations); + manipulations.UnionWith(container.Manipulations); } public string GetName() diff --git a/Penumbra/Mods/SubMods/MultiSubMod.cs b/Penumbra/Mods/SubMods/MultiSubMod.cs index 00216b77..12dfcada 100644 --- a/Penumbra/Mods/SubMods/MultiSubMod.cs +++ b/Penumbra/Mods/SubMods/MultiSubMod.cs @@ -65,7 +65,7 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption } public void AddDataTo(Dictionary redirections, HashSet manipulations) - => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + => IModDataContainer.AddDataTo(this, redirections, manipulations); public static MultiSubMod CreateForSaving(string name, string description, ModPriority priority) => new(null!, null!) diff --git a/Penumbra/Mods/SubMods/SingleSubMod.cs b/Penumbra/Mods/SubMods/SingleSubMod.cs index 499ab192..ba91e271 100644 --- a/Penumbra/Mods/SubMods/SingleSubMod.cs +++ b/Penumbra/Mods/SubMods/SingleSubMod.cs @@ -63,7 +63,7 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption } public void AddDataTo(Dictionary redirections, HashSet manipulations) - => ((IModDataContainer)this).AddDataTo(redirections, manipulations); + => IModDataContainer.AddDataTo(this, redirections, manipulations); public (int GroupIndex, int DataIndex) GetDataIndices() => (Group.GetIndex(), GetDataIndex()); From 72db023804f1d7e529b2bca49e5293b884469432 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 25 Apr 2024 17:58:32 +0200 Subject: [PATCH 0578/1381] Some cleanup. --- Penumbra/Mods/Groups/ModSaveGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 6 +- Penumbra/Mods/Groups/SingleModGroup.cs | 6 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 4 +- Penumbra/Mods/Mod.cs | 2 +- Penumbra/Mods/ModCreator.cs | 40 +++++--- Penumbra/Mods/SubMods/DefaultSubMod.cs | 6 +- Penumbra/Mods/SubMods/IModDataContainer.cs | 105 ++------------------- Penumbra/Mods/SubMods/IModOption.cs | 21 +---- Penumbra/Mods/SubMods/MultiSubMod.cs | 10 +- Penumbra/Mods/SubMods/SingleSubMod.cs | 10 +- Penumbra/Mods/SubMods/SubModHelpers.cs | 105 +++++++++++++++++++++ 12 files changed, 163 insertions(+), 154 deletions(-) create mode 100644 Penumbra/Mods/SubMods/SubModHelpers.cs diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index ed81f42f..e87fc012 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -51,7 +51,7 @@ public readonly struct ModSaveGroup : ISavable if (_groupIdx >= 0) _group!.WriteJson(j, serializer); else - IModDataContainer.WriteModData(j, serializer, _defaultMod!, _basePath); + SubModHelpers.WriteModContainer(j, serializer, _defaultMod!, _basePath); j.WriteEndObject(); } } diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index f39f2e70..1c8c769c 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -54,7 +54,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup return OptionData.Count - 1; } - public static MultiModGroup? Load(Mod mod, JObject json, int groupIdx) + public static MultiModGroup? Load(Mod mod, JObject json) { var ret = new MultiModGroup(mod) { @@ -140,10 +140,10 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup jWriter.WriteStartArray(); foreach (var option in OptionData) { - IModOption.WriteModOption(jWriter, option); + SubModHelpers.WriteModOption(jWriter, option); jWriter.WritePropertyName(nameof(option.Priority)); jWriter.WriteValue(option.Priority.Value); - IModDataContainer.WriteModData(jWriter, serializer, option, basePath ?? Mod.ModPath); + SubModHelpers.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); } jWriter.WriteEndArray(); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 6011185a..11542968 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -52,7 +52,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public bool IsOption => OptionData.Count > 1; - public static SingleModGroup? Load(Mod mod, JObject json, int groupIdx) + public static SingleModGroup? Load(Mod mod, JObject json) { var options = json["Options"]; var ret = new SingleModGroup(mod) @@ -144,8 +144,8 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup jWriter.WriteStartArray(); foreach (var option in OptionData) { - IModOption.WriteModOption(jWriter, option); - IModDataContainer.WriteModData(jWriter, serializer, option, basePath ?? Mod.ModPath); + SubModHelpers.WriteModOption(jWriter, option); + SubModHelpers.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); } jWriter.WriteEndArray(); diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index b66fec17..a02c8d68 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -251,7 +251,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS Description = option.Description, }; if (option is IModDataContainer data) - IModDataContainer.Clone(data, newOption); + SubModHelpers.Clone(data, newOption); s.OptionData.Add(newOption); break; } @@ -265,7 +265,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS Priority = option is MultiSubMod s ? s.Priority : ModPriority.Default, }; if (option is IModDataContainer data) - IModDataContainer.Clone(data, newOption); + SubModHelpers.Clone(data, newOption); m.OptionData.Add(newOption); break; } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index fc84afcc..6f6eb8ce 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -78,7 +78,7 @@ public sealed class Mod : IMod group.AddData(config, dictRedirections, setManips); } - Default.AddDataTo(dictRedirections, setManips); + Default.AddTo(dictRedirections, setManips); return new AppliedModData(dictRedirections, setManips); } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index e8113ee1..0626bc9d 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -115,7 +115,7 @@ public partial class ModCreator( try { var jObject = File.Exists(defaultFile) ? JObject.Parse(File.ReadAllText(defaultFile)) : new JObject(); - IModDataContainer.Load(jObject, mod.Default, mod.ModPath); + SubModHelpers.LoadDataContainer(jObject, mod.Default, mod.ModPath); } catch (Exception e) { @@ -162,7 +162,7 @@ public partial class ModCreator( deleteList.AddRange(localDeleteList); } - IModDataContainer.DeleteDeleteList(deleteList, delete); + DeleteDeleteList(deleteList, delete); if (!changes) return; @@ -221,7 +221,7 @@ public partial class ModCreator( } } - IModDataContainer.DeleteDeleteList(deleteList, delete); + DeleteDeleteList(deleteList, delete); return (oldSize < option.Manipulations.Count, deleteList); } @@ -392,10 +392,8 @@ public partial class ModCreator( Penumbra.Log.Debug($"Writing the first {IModGroup.MaxMultiOptions} options to {Path.GetFileName(oldPath)} after split."); using (var oldFile = File.CreateText(oldPath)) { - using var j = new JsonTextWriter(oldFile) - { - Formatting = Formatting.Indented, - }; + using var j = new JsonTextWriter(oldFile); + j.Formatting = Formatting.Indented; json.WriteTo(j); } @@ -403,10 +401,8 @@ public partial class ModCreator( $"Writing the remaining {options.Count - IModGroup.MaxMultiOptions} options to {Path.GetFileName(newPath)} after split."); using (var newFile = File.CreateText(newPath)) { - using var j = new JsonTextWriter(newFile) - { - Formatting = Formatting.Indented, - }; + using var j = new JsonTextWriter(newFile); + j.Formatting = Formatting.Indented; clone.WriteTo(j); } @@ -436,8 +432,8 @@ public partial class ModCreator( var json = JObject.Parse(File.ReadAllText(file.FullName)); switch (json[nameof(Type)]?.ToObject() ?? GroupType.Single) { - case GroupType.Multi: return MultiModGroup.Load(mod, json, groupIdx); - case GroupType.Single: return SingleModGroup.Load(mod, json, groupIdx); + case GroupType.Multi: return MultiModGroup.Load(mod, json); + case GroupType.Single: return SingleModGroup.Load(mod, json); } } catch (Exception e) @@ -446,5 +442,23 @@ public partial class ModCreator( } return null; + } + + internal static void DeleteDeleteList(IEnumerable deleteList, bool delete) + { + if (!delete) + return; + + foreach (var file in deleteList) + { + try + { + File.Delete(file); + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not delete incorporated meta file {file}:\n{e}"); + } + } } } diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 8b166505..8b00e2ae 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -22,9 +22,9 @@ public class DefaultSubMod(IMod mod) : IModDataContainer IModGroup? IModDataContainer.Group => null; - public void AddDataTo(Dictionary redirections, HashSet manipulations) - => IModDataContainer.AddDataTo(this, redirections, manipulations); + public void AddTo(Dictionary redirections, HashSet manipulations) + => SubModHelpers.AddContainerTo(this, redirections, manipulations); public (int GroupIndex, int DataIndex) GetDataIndices() => (-1, 0); -} +} diff --git a/Penumbra/Mods/SubMods/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs index c9420821..1e676816 100644 --- a/Penumbra/Mods/SubMods/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -1,5 +1,3 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; @@ -7,6 +5,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.SubMods; + public interface IModDataContainer { public IMod Mod { get; } @@ -16,116 +15,24 @@ public interface IModDataContainer public Dictionary FileSwaps { get; set; } public HashSet Manipulations { get; set; } - public static void AddDataTo(IModDataContainer container, Dictionary redirections, HashSet manipulations) - { - foreach (var (path, file) in container.Files) - redirections.TryAdd(path, file); - - foreach (var (path, file) in container.FileSwaps) - redirections.TryAdd(path, file); - manipulations.UnionWith(container.Manipulations); - } - public string GetName() => this switch { - IModOption o => o.FullName, + IModOption o => o.FullName, DefaultSubMod => DefaultSubMod.FullName, - _ => $"Container {GetDataIndices().DataIndex + 1}", + _ => $"Container {GetDataIndices().DataIndex + 1}", }; public string GetFullName() => this switch { - IModOption o => o.FullName, - DefaultSubMod => DefaultSubMod.FullName, + IModOption o => o.FullName, + DefaultSubMod => DefaultSubMod.FullName, _ when Group != null => $"{Group.Name}: Container {GetDataIndices().DataIndex + 1}", - _ => $"Container {GetDataIndices().DataIndex + 1}", + _ => $"Container {GetDataIndices().DataIndex + 1}", }; - public static void Clone(IModDataContainer from, IModDataContainer to) - { - to.Files = new Dictionary(from.Files); - to.FileSwaps = new Dictionary(from.FileSwaps); - to.Manipulations = [.. from.Manipulations]; - } - public (int GroupIndex, int DataIndex) GetDataIndices(); - - public static void Load(JToken json, IModDataContainer data, DirectoryInfo basePath) - { - data.Files.Clear(); - data.FileSwaps.Clear(); - data.Manipulations.Clear(); - - var files = (JObject?)json[nameof(Files)]; - if (files != null) - foreach (var property in files.Properties()) - { - if (Utf8GamePath.FromString(property.Name, out var p, true)) - data.Files.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); - } - - var swaps = (JObject?)json[nameof(FileSwaps)]; - if (swaps != null) - foreach (var property in swaps.Properties()) - { - if (Utf8GamePath.FromString(property.Name, out var p, true)) - data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); - } - - var manips = json[nameof(Manipulations)]; - if (manips != null) - foreach (var s in manips.Children().Select(c => c.ToObject()) - .Where(m => m.Validate())) - data.Manipulations.Add(s); - } - - public static void WriteModData(JsonWriter j, JsonSerializer serializer, IModDataContainer data, DirectoryInfo basePath) - { - j.WritePropertyName(nameof(data.Files)); - j.WriteStartObject(); - foreach (var (gamePath, file) in data.Files) - { - if (file.ToRelPath(basePath, out var relPath)) - { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(relPath.ToString()); - } - } - - j.WriteEndObject(); - j.WritePropertyName(nameof(data.FileSwaps)); - j.WriteStartObject(); - foreach (var (gamePath, file) in data.FileSwaps) - { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(file.ToString()); - } - - j.WriteEndObject(); - j.WritePropertyName(nameof(data.Manipulations)); - serializer.Serialize(j, data.Manipulations); - j.WriteEndObject(); - } - - internal static void DeleteDeleteList(IEnumerable deleteList, bool delete) - { - if (!delete) - return; - - foreach (var file in deleteList) - { - try - { - File.Delete(file); - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not delete incorporated meta file {file}:\n{e}"); - } - } - } } public interface IModDataOption : IModOption, IModDataContainer; diff --git a/Penumbra/Mods/SubMods/IModOption.cs b/Penumbra/Mods/SubMods/IModOption.cs index f1ce1d4c..83d632a0 100644 --- a/Penumbra/Mods/SubMods/IModOption.cs +++ b/Penumbra/Mods/SubMods/IModOption.cs @@ -1,27 +1,10 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - namespace Penumbra.Mods.SubMods; public interface IModOption { - public string Name { get; set; } - public string FullName { get; } + public string Name { get; set; } + public string FullName { get; } public string Description { get; set; } - public static void Load(JToken json, IModOption option) - { - option.Name = json[nameof(Name)]?.ToObject() ?? string.Empty; - option.Description = json[nameof(Description)]?.ToObject() ?? string.Empty; - } - public (int GroupIndex, int OptionIndex) GetOptionIndices(); - - public static void WriteModOption(JsonWriter j, IModOption option) - { - j.WritePropertyName(nameof(Name)); - j.WriteValue(option.Name); - j.WritePropertyName(nameof(Description)); - j.WriteValue(option.Description); - } } diff --git a/Penumbra/Mods/SubMods/MultiSubMod.cs b/Penumbra/Mods/SubMods/MultiSubMod.cs index 12dfcada..ccb787a5 100644 --- a/Penumbra/Mods/SubMods/MultiSubMod.cs +++ b/Penumbra/Mods/SubMods/MultiSubMod.cs @@ -35,8 +35,8 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption public MultiSubMod(Mod mod, MultiModGroup group, JToken json) : this(mod, group) { - IModOption.Load(json, this); - IModDataContainer.Load(json, this, mod.ModPath); + SubModHelpers.LoadOptionData(json, this); + SubModHelpers.LoadDataContainer(json, this, mod.ModPath); Priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; } @@ -48,7 +48,7 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption Description = Description, Priority = Priority, }; - IModDataContainer.Clone(this, ret); + SubModHelpers.Clone(this, ret); return ret; } @@ -60,12 +60,12 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption Name = Name, Description = Description, }; - IModDataContainer.Clone(this, ret); + SubModHelpers.Clone(this, ret); return ret; } public void AddDataTo(Dictionary redirections, HashSet manipulations) - => IModDataContainer.AddDataTo(this, redirections, manipulations); + => SubModHelpers.AddContainerTo(this, redirections, manipulations); public static MultiSubMod CreateForSaving(string name, string description, ModPriority priority) => new(null!, null!) diff --git a/Penumbra/Mods/SubMods/SingleSubMod.cs b/Penumbra/Mods/SubMods/SingleSubMod.cs index ba91e271..e6740a47 100644 --- a/Penumbra/Mods/SubMods/SingleSubMod.cs +++ b/Penumbra/Mods/SubMods/SingleSubMod.cs @@ -33,8 +33,8 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption public SingleSubMod(Mod mod, SingleModGroup group, JToken json) : this(mod, group) { - IModOption.Load(json, this); - IModDataContainer.Load(json, this, mod.ModPath); + SubModHelpers.LoadOptionData(json, this); + SubModHelpers.LoadDataContainer(json, this, mod.ModPath); } public SingleSubMod Clone(Mod mod, SingleModGroup group) @@ -44,7 +44,7 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption Name = Name, Description = Description, }; - IModDataContainer.Clone(this, ret); + SubModHelpers.Clone(this, ret); return ret; } @@ -57,13 +57,13 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption Description = Description, Priority = priority, }; - IModDataContainer.Clone(this, ret); + SubModHelpers.Clone(this, ret); return ret; } public void AddDataTo(Dictionary redirections, HashSet manipulations) - => IModDataContainer.AddDataTo(this, redirections, manipulations); + => SubModHelpers.AddContainerTo(this, redirections, manipulations); public (int GroupIndex, int DataIndex) GetDataIndices() => (Group.GetIndex(), GetDataIndex()); diff --git a/Penumbra/Mods/SubMods/SubModHelpers.cs b/Penumbra/Mods/SubMods/SubModHelpers.cs new file mode 100644 index 00000000..9992b6e8 --- /dev/null +++ b/Penumbra/Mods/SubMods/SubModHelpers.cs @@ -0,0 +1,105 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.ItemSwap; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + +public static class SubModHelpers +{ + /// Add all unique meta manipulations, file redirections and then file swaps from a ModDataContainer to the given sets. Skip any keys that are already contained. + public static void AddContainerTo(IModDataContainer container, Dictionary redirections, + HashSet manipulations) + { + foreach (var (path, file) in container.Files) + redirections.TryAdd(path, file); + + foreach (var (path, file) in container.FileSwaps) + redirections.TryAdd(path, file); + manipulations.UnionWith(container.Manipulations); + } + + /// Replace all data of with the data of . + public static void Clone(IModDataContainer from, IModDataContainer to) + { + to.Files = new Dictionary(from.Files); + to.FileSwaps = new Dictionary(from.FileSwaps); + to.Manipulations = [.. from.Manipulations]; + } + + /// Load all file redirections, file swaps and meta manipulations from a JToken of that option into a data container. + public static void LoadDataContainer(JToken json, IModDataContainer data, DirectoryInfo basePath) + { + data.Files.Clear(); + data.FileSwaps.Clear(); + data.Manipulations.Clear(); + + var files = (JObject?)json[nameof(data.Files)]; + if (files != null) + foreach (var property in files.Properties()) + { + if (Utf8GamePath.FromString(property.Name, out var p, true)) + data.Files.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); + } + + var swaps = (JObject?)json[nameof(data.FileSwaps)]; + if (swaps != null) + foreach (var property in swaps.Properties()) + { + if (Utf8GamePath.FromString(property.Name, out var p, true)) + data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); + } + + var manips = json[nameof(data.Manipulations)]; + if (manips != null) + foreach (var s in manips.Children().Select(c => c.ToObject()) + .Where(m => m.Validate())) + data.Manipulations.Add(s); + } + + /// Load the relevant data for a selectable option from a JToken of that option. + public static void LoadOptionData(JToken json, IModOption option) + { + option.Name = json[nameof(option.Name)]?.ToObject() ?? string.Empty; + option.Description = json[nameof(option.Description)]?.ToObject() ?? string.Empty; + } + + /// Write file redirections, file swaps and meta manipulations from a data container on a JsonWriter. + public static void WriteModContainer(JsonWriter j, JsonSerializer serializer, IModDataContainer data, DirectoryInfo basePath) + { + j.WritePropertyName(nameof(data.Files)); + j.WriteStartObject(); + foreach (var (gamePath, file) in data.Files) + { + if (file.ToRelPath(basePath, out var relPath)) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(relPath.ToString()); + } + } + + j.WriteEndObject(); + j.WritePropertyName(nameof(data.FileSwaps)); + j.WriteStartObject(); + foreach (var (gamePath, file) in data.FileSwaps) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(file.ToString()); + } + + j.WriteEndObject(); + j.WritePropertyName(nameof(data.Manipulations)); + serializer.Serialize(j, data.Manipulations); + j.WriteEndObject(); + } + + /// Write the data for a selectable mod option on a JsonWriter. + public static void WriteModOption(JsonWriter j, IModOption option) + { + j.WritePropertyName(nameof(option.Name)); + j.WriteValue(option.Name); + j.WritePropertyName(nameof(option.Description)); + j.WriteValue(option.Description); + } +} From 0fd14ffefc11475920e7a7f1cf00c70e8ba46e22 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 25 Apr 2024 18:14:21 +0200 Subject: [PATCH 0579/1381] More cleanup. --- Penumbra/Mods/SubMods/DefaultSubMod.cs | 7 ++- Penumbra/Mods/SubMods/IModDataContainer.cs | 21 +------ Penumbra/Mods/SubMods/MultiSubMod.cs | 64 ++++------------------ Penumbra/Mods/SubMods/OptionSubMod.cs | 57 +++++++++++++++++++ Penumbra/Mods/SubMods/SingleSubMod.cs | 64 ++++------------------ Penumbra/Mods/SubMods/SubModHelpers.cs | 5 +- 6 files changed, 89 insertions(+), 129 deletions(-) create mode 100644 Penumbra/Mods/SubMods/OptionSubMod.cs diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 8b00e2ae..1eddcef6 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -1,4 +1,3 @@ -using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; @@ -25,6 +24,12 @@ public class DefaultSubMod(IMod mod) : IModDataContainer public void AddTo(Dictionary redirections, HashSet manipulations) => SubModHelpers.AddContainerTo(this, redirections, manipulations); + public string GetName() + => FullName; + + public string GetFullName() + => FullName; + public (int GroupIndex, int DataIndex) GetDataIndices() => (-1, 0); } diff --git a/Penumbra/Mods/SubMods/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs index 1e676816..a6ab491f 100644 --- a/Penumbra/Mods/SubMods/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -15,24 +15,7 @@ public interface IModDataContainer public Dictionary FileSwaps { get; set; } public HashSet Manipulations { get; set; } - public string GetName() - => this switch - { - IModOption o => o.FullName, - DefaultSubMod => DefaultSubMod.FullName, - _ => $"Container {GetDataIndices().DataIndex + 1}", - }; - - public string GetFullName() - => this switch - { - IModOption o => o.FullName, - DefaultSubMod => DefaultSubMod.FullName, - _ when Group != null => $"{Group.Name}: Container {GetDataIndices().DataIndex + 1}", - _ => $"Container {GetDataIndices().DataIndex + 1}", - }; - + public string GetName(); + public string GetFullName(); public (int GroupIndex, int DataIndex) GetDataIndices(); } - -public interface IModDataOption : IModOption, IModDataContainer; diff --git a/Penumbra/Mods/SubMods/MultiSubMod.cs b/Penumbra/Mods/SubMods/MultiSubMod.cs index ccb787a5..c43d4b9e 100644 --- a/Penumbra/Mods/SubMods/MultiSubMod.cs +++ b/Penumbra/Mods/SubMods/MultiSubMod.cs @@ -1,37 +1,13 @@ -using Newtonsoft.Json.Linq; -using OtterGui; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Editor; +using Newtonsoft.Json.Linq; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; -using Penumbra.String.Classes; - -namespace Penumbra.Mods.SubMods; - -public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption + +namespace Penumbra.Mods.SubMods; + +public class MultiSubMod(Mod mod, MultiModGroup group) : OptionSubMod(mod, group) { - internal readonly Mod Mod = mod; - internal readonly MultiModGroup Group = group; - - public string Name { get; set; } = "Option"; - - public string FullName - => $"{Group.Name}: {Name}"; - - public string Description { get; set; } = string.Empty; public ModPriority Priority { get; set; } = ModPriority.Default; - public Dictionary Files { get; set; } = []; - public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; - - IMod IModDataContainer.Mod - => Mod; - - IModGroup IModDataContainer.Group - => Group; - - public MultiSubMod(Mod mod, MultiModGroup group, JToken json) : this(mod, group) { @@ -44,9 +20,9 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption { var ret = new MultiSubMod(mod, group) { - Name = Name, + Name = Name, Description = Description, - Priority = Priority, + Priority = Priority, }; SubModHelpers.Clone(this, ret); @@ -57,36 +33,18 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : IModDataOption { var ret = new SingleSubMod(mod, group) { - Name = Name, + Name = Name, Description = Description, }; SubModHelpers.Clone(this, ret); return ret; } - public void AddDataTo(Dictionary redirections, HashSet manipulations) - => SubModHelpers.AddContainerTo(this, redirections, manipulations); - public static MultiSubMod CreateForSaving(string name, string description, ModPriority priority) => new(null!, null!) { - Name = name, + Name = name, Description = description, - Priority = priority, + Priority = priority, }; - - public (int GroupIndex, int DataIndex) GetDataIndices() - => (Group.GetIndex(), GetDataIndex()); - - public (int GroupIndex, int OptionIndex) GetOptionIndices() - => (Group.GetIndex(), GetDataIndex()); - - private int GetDataIndex() - { - var dataIndex = Group.DataContainers.IndexOf(this); - if (dataIndex < 0) - throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); - - return dataIndex; - } -} +} diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs new file mode 100644 index 00000000..79c50e51 --- /dev/null +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -0,0 +1,57 @@ +using OtterGui; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + +public interface IModDataOption : IModDataContainer, IModOption; + +public abstract class OptionSubMod(Mod mod, T group) : IModDataOption + where T : IModGroup +{ + internal readonly Mod Mod = mod; + internal readonly IModGroup Group = group; + + public string Name { get; set; } = "Option"; + + public string FullName + => $"{Group!.Name}: {Name}"; + + public string Description { get; set; } = string.Empty; + + IMod IModDataContainer.Mod + => Mod; + + IModGroup IModDataContainer.Group + => Group; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; + + public void AddDataTo(Dictionary redirections, HashSet manipulations) + => SubModHelpers.AddContainerTo(this, redirections, manipulations); + + public string GetName() + => Name; + + public string GetFullName() + => FullName; + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), GetDataIndex()); + + public (int GroupIndex, int OptionIndex) GetOptionIndices() + => (Group.GetIndex(), GetDataIndex()); + + private int GetDataIndex() + { + var dataIndex = Group.DataContainers.IndexOf(this); + if (dataIndex < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); + + return dataIndex; + } +} diff --git a/Penumbra/Mods/SubMods/SingleSubMod.cs b/Penumbra/Mods/SubMods/SingleSubMod.cs index e6740a47..5d68e401 100644 --- a/Penumbra/Mods/SubMods/SingleSubMod.cs +++ b/Penumbra/Mods/SubMods/SingleSubMod.cs @@ -1,37 +1,13 @@ -using Newtonsoft.Json.Linq; -using OtterGui; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Editor; +using Newtonsoft.Json.Linq; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; -using Penumbra.String.Classes; - -namespace Penumbra.Mods.SubMods; - -public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption + +namespace Penumbra.Mods.SubMods; + +public class SingleSubMod(Mod mod, SingleModGroup singleGroup) : OptionSubMod(mod, singleGroup) { - internal readonly Mod Mod = mod; - internal readonly SingleModGroup Group = group; - - public string Name { get; set; } = "Option"; - - public string FullName - => $"{Group.Name}: {Name}"; - - public string Description { get; set; } = string.Empty; - - IMod IModDataContainer.Mod - => Mod; - - IModGroup IModDataContainer.Group - => Group; - - public Dictionary Files { get; set; } = []; - public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; - - public SingleSubMod(Mod mod, SingleModGroup group, JToken json) - : this(mod, group) + public SingleSubMod(Mod mod, SingleModGroup singleGroup, JToken json) + : this(mod, singleGroup) { SubModHelpers.LoadOptionData(json, this); SubModHelpers.LoadDataContainer(json, this, mod.ModPath); @@ -41,7 +17,7 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption { var ret = new SingleSubMod(mod, group) { - Name = Name, + Name = Name, Description = Description, }; SubModHelpers.Clone(this, ret); @@ -53,30 +29,12 @@ public class SingleSubMod(Mod mod, SingleModGroup group) : IModDataOption { var ret = new MultiSubMod(mod, group) { - Name = Name, + Name = Name, Description = Description, - Priority = priority, + Priority = priority, }; SubModHelpers.Clone(this, ret); return ret; } - - public void AddDataTo(Dictionary redirections, HashSet manipulations) - => SubModHelpers.AddContainerTo(this, redirections, manipulations); - - public (int GroupIndex, int DataIndex) GetDataIndices() - => (Group.GetIndex(), GetDataIndex()); - - public (int GroupIndex, int OptionIndex) GetOptionIndices() - => (Group.GetIndex(), GetDataIndex()); - - private int GetDataIndex() - { - var dataIndex = Group.DataContainers.IndexOf(this); - if (dataIndex < 0) - throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); - - return dataIndex; - } -} +} diff --git a/Penumbra/Mods/SubMods/SubModHelpers.cs b/Penumbra/Mods/SubMods/SubModHelpers.cs index 9992b6e8..2a09fbc3 100644 --- a/Penumbra/Mods/SubMods/SubModHelpers.cs +++ b/Penumbra/Mods/SubMods/SubModHelpers.cs @@ -1,7 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.ItemSwap; using Penumbra.String.Classes; namespace Penumbra.Mods.SubMods; @@ -92,9 +91,9 @@ public static class SubModHelpers j.WritePropertyName(nameof(data.Manipulations)); serializer.Serialize(j, data.Manipulations); j.WriteEndObject(); - } + } - /// Write the data for a selectable mod option on a JsonWriter. + /// Write the data for a selectable mod option on a JsonWriter. public static void WriteModOption(JsonWriter j, IModOption option) { j.WritePropertyName(nameof(option.Name)); From 06953c175dbb1e733612c02e8bf815ed82247d29 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 25 Apr 2024 18:18:57 +0200 Subject: [PATCH 0580/1381] mooooore --- Penumbra/Mods/Groups/IModGroup.cs | 15 --------------- Penumbra/Mods/Groups/ModSaveGroup.cs | 15 +++++++++++++++ Penumbra/Mods/Groups/MultiModGroup.cs | 4 +++- Penumbra/Mods/Groups/SingleModGroup.cs | 4 +++- Penumbra/Mods/SubMods/DefaultSubMod.cs | 20 ++++++++++---------- 5 files changed, 31 insertions(+), 27 deletions(-) diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index dc5150cf..0cabc9f3 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -68,21 +68,6 @@ public interface IModGroup return true; } - public static void WriteJsonBase(JsonTextWriter jWriter, IModGroup group) - { - jWriter.WriteStartObject(); - jWriter.WritePropertyName(nameof(group.Name)); - jWriter.WriteValue(group!.Name); - jWriter.WritePropertyName(nameof(group.Description)); - jWriter.WriteValue(group.Description); - jWriter.WritePropertyName(nameof(group.Priority)); - jWriter.WriteValue(group.Priority.Value); - jWriter.WritePropertyName(nameof(group.Type)); - jWriter.WriteValue(group.Type.ToString()); - jWriter.WritePropertyName(nameof(group.DefaultSettings)); - jWriter.WriteValue(group.DefaultSettings.Value); - } - public (int Redirections, int Swaps, int Manips) GetCounts(); public static (int Redirections, int Swaps, int Manips) GetCountsBase(IModGroup group) diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index e87fc012..92ccb36e 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -54,4 +54,19 @@ public readonly struct ModSaveGroup : ISavable SubModHelpers.WriteModContainer(j, serializer, _defaultMod!, _basePath); j.WriteEndObject(); } + + public static void WriteJsonBase(JsonTextWriter jWriter, IModGroup group) + { + jWriter.WriteStartObject(); + jWriter.WritePropertyName(nameof(group.Name)); + jWriter.WriteValue(group!.Name); + jWriter.WritePropertyName(nameof(group.Description)); + jWriter.WriteValue(group.Description); + jWriter.WritePropertyName(nameof(group.Priority)); + jWriter.WriteValue(group.Priority.Value); + jWriter.WritePropertyName(nameof(group.Type)); + jWriter.WriteValue(group.Type.ToString()); + jWriter.WritePropertyName(nameof(group.DefaultSettings)); + jWriter.WriteValue(group.DefaultSettings.Value); + } } diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 1c8c769c..7e900ef5 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -135,15 +135,17 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) { - IModGroup.WriteJsonBase(jWriter, this); + ModSaveGroup.WriteJsonBase(jWriter, this); jWriter.WritePropertyName("Options"); jWriter.WriteStartArray(); foreach (var option in OptionData) { + jWriter.WriteStartObject(); SubModHelpers.WriteModOption(jWriter, option); jWriter.WritePropertyName(nameof(option.Priority)); jWriter.WriteValue(option.Priority.Value); SubModHelpers.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); + jWriter.WriteEndObject(); } jWriter.WriteEndArray(); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 11542968..6aa9160e 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -139,13 +139,15 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) { - IModGroup.WriteJsonBase(jWriter, this); + ModSaveGroup.WriteJsonBase(jWriter, this); jWriter.WritePropertyName("Options"); jWriter.WriteStartArray(); foreach (var option in OptionData) { + jWriter.WriteStartObject(); SubModHelpers.WriteModOption(jWriter, option); SubModHelpers.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); + jWriter.WriteEndObject(); } jWriter.WriteEndArray(); diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 1eddcef6..980b805d 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -1,19 +1,19 @@ -using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Editor; -using Penumbra.Mods.Groups; -using Penumbra.String.Classes; - -namespace Penumbra.Mods.SubMods; - +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + public class DefaultSubMod(IMod mod) : IModDataContainer { public const string FullName = "Default Option"; internal readonly IMod Mod = mod; - public Dictionary Files { get; set; } = []; - public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public HashSet Manipulations { get; set; } = []; IMod IModDataContainer.Mod => Mod; From a72be22d3b295250716408fa0d01976f44a6e7b3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 26 Apr 2024 10:56:06 +0200 Subject: [PATCH 0581/1381] Make sure HS image does not displace the settings entirely. --- Penumbra/UI/ModsTab/ModPanelHeader.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index 05f47809..a8b393b1 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -18,6 +18,7 @@ public class ModPanelHeader : IDisposable private readonly IFontHandle _nameFont; private readonly CommunicatorService _communicator; + private float _lastPreSettingsHeight = 0; public ModPanelHeader(DalamudPluginInterface pi, CommunicatorService communicator) { @@ -32,6 +33,11 @@ public class ModPanelHeader : IDisposable /// public void Draw() { + var height = ImGui.GetContentRegionAvail().Y; + var maxHeight = 3 * height / 4; + using var child = _lastPreSettingsHeight > maxHeight && _communicator.PreSettingsTabBarDraw.HasSubscribers + ? ImRaii.Child("HeaderChild", new Vector2(ImGui.GetContentRegionAvail().X, maxHeight), false) + : null; using (ImRaii.Group()) { var offset = DrawModName(); @@ -40,6 +46,7 @@ public class ModPanelHeader : IDisposable } _communicator.PreSettingsTabBarDraw.Invoke(_mod.Identifier, ImGui.GetItemRectSize().X, _nameWidth); + _lastPreSettingsHeight = ImGui.GetCursorPosY(); } /// @@ -48,6 +55,7 @@ public class ModPanelHeader : IDisposable /// public void UpdateModData(Mod mod) { + _lastPreSettingsHeight = 0; _mod = mod; // Name var name = $" {mod.Name} "; From e40c4999b6d18deab2bf98a60cd9cf5d1ac2b198 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 26 Apr 2024 10:56:36 +0200 Subject: [PATCH 0582/1381] Improve collection migration maybe. --- .../Collections/Manager/CollectionStorage.cs | 30 +++++++++++++++---- .../Manager/ModCollectionMigration.cs | 2 -- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 4e2fb7b7..1fe5b227 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -184,21 +184,39 @@ public class CollectionStorage : IReadOnlyList, IDisposable { if (version >= 2) { - File.Move(file.FullName, correctName, false); - Penumbra.Messager.NotificationMessage($"Collection {file.Name} does not correspond to {collection.Identifier}, renamed.", - NotificationType.Warning); + try + { + File.Move(file.FullName, correctName, false); + Penumbra.Messager.NotificationMessage( + $"Collection {file.Name} does not correspond to {collection.Identifier}, renamed.", + NotificationType.Warning); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage( + $"Collection {file.Name} does not correspond to {collection.Identifier}, rename failed:\n{ex}", + NotificationType.Warning); + } } else { _saveService.ImmediateSaveSync(new ModCollectionSave(_modStorage, collection)); - File.Delete(file.FullName); - Penumbra.Log.Information($"Migrated collection {name} to Guid {id}."); + try + { + File.Move(file.FullName, file.FullName + ".bak", true); + Penumbra.Log.Information($"Migrated collection {name} to Guid {id} with backup of old file."); + } + catch (Exception ex) + { + Penumbra.Log.Information($"Migrated collection {name} to Guid {id}, rename of old file failed:\n{ex}"); + } } } catch (Exception e) { Penumbra.Messager.NotificationMessage(e, - $"Collection {file.Name} does not correspond to {collection.Identifier}, but could not rename.", NotificationType.Error); + $"Collection {file.Name} does not correspond to {collection.Identifier}, but could not rename.", + NotificationType.Error); } _collections.Add(collection); diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index 89743aa2..fe61285d 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -1,8 +1,6 @@ -using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; using Penumbra.Services; -using Penumbra.Util; namespace Penumbra.Collections.Manager; From 297be487b50066c4a79c4cff03af18fa452b0672 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 26 Apr 2024 10:57:09 +0200 Subject: [PATCH 0583/1381] More cleanup on groups. --- .../Communication/PreSettingsTabBarDraw.cs | 3 +- Penumbra/Mods/Groups/IModGroup.cs | 61 +++---------------- Penumbra/Mods/Groups/ModGroup.cs | 42 +++++++++++++ Penumbra/Mods/Groups/ModSaveGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 6 +- Penumbra/Mods/Groups/SingleModGroup.cs | 6 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 42 +++++-------- Penumbra/Mods/Manager/ModStorage.cs | 6 +- Penumbra/Mods/ModCreator.cs | 2 +- Penumbra/Mods/SubMods/DefaultSubMod.cs | 2 +- Penumbra/Mods/SubMods/MultiSubMod.cs | 8 +-- Penumbra/Mods/SubMods/OptionSubMod.cs | 2 +- Penumbra/Mods/SubMods/SingleSubMod.cs | 8 +-- .../SubMods/{SubModHelpers.cs => SubMod.cs} | 19 +++++- 14 files changed, 107 insertions(+), 102 deletions(-) create mode 100644 Penumbra/Mods/Groups/ModGroup.cs rename Penumbra/Mods/SubMods/{SubModHelpers.cs => SubMod.cs} (87%) diff --git a/Penumbra/Communication/PreSettingsTabBarDraw.cs b/Penumbra/Communication/PreSettingsTabBarDraw.cs index 8614bbbe..e1d67297 100644 --- a/Penumbra/Communication/PreSettingsTabBarDraw.cs +++ b/Penumbra/Communication/PreSettingsTabBarDraw.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api.Api; +using Penumbra.Api.IpcSubscribers; namespace Penumbra.Communication; @@ -15,7 +16,7 @@ public sealed class PreSettingsTabBarDraw() : EventWrapper + /// Default = 0, } } diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index 0cabc9f3..b13799cd 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -16,22 +16,22 @@ public interface IModGroup { public const int MaxMultiOptions = 63; - public Mod Mod { get; } - public string Name { get; } - public string Description { get; } - public GroupType Type { get; } - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; } + public string Name { get; } + public string Description { get; set; } + public GroupType Type { get; } + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public FullPath? FindBestMatch(Utf8GamePath gamePath); - public int AddOption(Mod mod, string name, string description = ""); + public int AddOption(Mod mod, string name, string description = ""); - public IReadOnlyList Options { get; } + public IReadOnlyList Options { get; } public IReadOnlyList DataContainers { get; } - public bool IsOption { get; } + public bool IsOption { get; } public IModGroup Convert(GroupType type); - public bool MoveOption(int optionIdxFrom, int optionIdxTo); + public bool MoveOption(int optionIdxFrom, int optionIdxTo); public int GetIndex(); @@ -42,46 +42,5 @@ public interface IModGroup public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null); - public bool ChangeOptionDescription(int optionIndex, string newDescription) - { - if (optionIndex < 0 || optionIndex >= Options.Count) - return false; - - var option = Options[optionIndex]; - if (option.Description == newDescription) - return false; - - option.Description = newDescription; - return true; - } - - public bool ChangeOptionName(int optionIndex, string newName) - { - if (optionIndex < 0 || optionIndex >= Options.Count) - return false; - - var option = Options[optionIndex]; - if (option.Name == newName) - return false; - - option.Name = newName; - return true; - } - public (int Redirections, int Swaps, int Manips) GetCounts(); - - public static (int Redirections, int Swaps, int Manips) GetCountsBase(IModGroup group) - { - var redirectionCount = 0; - var swapCount = 0; - var manipCount = 0; - foreach (var option in group.DataContainers) - { - redirectionCount += option.Files.Count; - swapCount += option.FileSwaps.Count; - manipCount += option.Manipulations.Count; - } - - return (redirectionCount, swapCount, manipCount); - } } diff --git a/Penumbra/Mods/Groups/ModGroup.cs b/Penumbra/Mods/Groups/ModGroup.cs new file mode 100644 index 00000000..da302714 --- /dev/null +++ b/Penumbra/Mods/Groups/ModGroup.cs @@ -0,0 +1,42 @@ +using Penumbra.Api.Enums; +using Penumbra.Mods.Settings; + +namespace Penumbra.Mods.Groups; + +public static class ModGroup +{ + public static IModGroup Create(Mod mod, GroupType type, string name) + { + var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; + return type switch + { + GroupType.Single => new SingleModGroup(mod) + { + Name = name, + Priority = maxPriority, + }, + GroupType.Multi => new MultiModGroup(mod) + { + Name = name, + Priority = maxPriority, + }, + _ => throw new ArgumentOutOfRangeException(nameof(type), type, null), + }; + } + + + public static (int Redirections, int Swaps, int Manips) GetCountsBase(IModGroup group) + { + var redirectionCount = 0; + var swapCount = 0; + var manipCount = 0; + foreach (var option in group.DataContainers) + { + redirectionCount += option.Files.Count; + swapCount += option.FileSwaps.Count; + manipCount += option.Manipulations.Count; + } + + return (redirectionCount, swapCount, manipCount); + } +} diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index 92ccb36e..332879cb 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -51,7 +51,7 @@ public readonly struct ModSaveGroup : ISavable if (_groupIdx >= 0) _group!.WriteJson(j, serializer); else - SubModHelpers.WriteModContainer(j, serializer, _defaultMod!, _basePath); + SubMod.WriteModContainer(j, serializer, _defaultMod!, _basePath); j.WriteEndObject(); } diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 7e900ef5..6b352f66 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -141,10 +141,10 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup foreach (var option in OptionData) { jWriter.WriteStartObject(); - SubModHelpers.WriteModOption(jWriter, option); + SubMod.WriteModOption(jWriter, option); jWriter.WritePropertyName(nameof(option.Priority)); jWriter.WriteValue(option.Priority.Value); - SubModHelpers.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); + SubMod.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); jWriter.WriteEndObject(); } @@ -153,7 +153,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup } public (int Redirections, int Swaps, int Manips) GetCounts() - => IModGroup.GetCountsBase(this); + => ModGroup.GetCountsBase(this); public Setting FixSetting(Setting setting) => new(setting.Value & (1ul << OptionData.Count) - 1); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 6aa9160e..ac85e2bc 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -135,7 +135,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup => OptionData.Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(OptionData.Count - 1))); public (int Redirections, int Swaps, int Manips) GetCounts() - => IModGroup.GetCountsBase(this); + => ModGroup.GetCountsBase(this); public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) { @@ -145,8 +145,8 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup foreach (var option in OptionData) { jWriter.WriteStartObject(); - SubModHelpers.WriteModOption(jWriter, option); - SubModHelpers.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); + SubMod.WriteModOption(jWriter, option); + SubMod.WriteModContainer(jWriter, serializer, option, basePath ?? Mod.ModPath); jWriter.WriteEndObject(); } diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index a02c8d68..c6122ea8 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -68,7 +68,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS return; saveService.ImmediateDelete(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - var _ = group switch + _ = group switch { SingleModGroup s => s.Name = newName, MultiModGroup m => m.Name = newName, @@ -85,21 +85,11 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS if (!VerifyFileName(mod, null, newName, true)) return; - var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; - - mod.Groups.Add(type == GroupType.Multi - ? new MultiModGroup(mod) - { - Name = newName, - Priority = maxPriority, - } - : new SingleModGroup(mod) - { - Name = newName, - Priority = maxPriority, - }); - saveService.Save(saveType, new ModSaveGroup(mod, mod.Groups.Count - 1, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, mod.Groups.Count - 1, -1, -1); + var idx = mod.Groups.Count; + var group = ModGroup.Create(mod, type, newName); + mod.Groups.Add(group); + saveService.Save(saveType, new ModSaveGroup(mod, idx, config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, idx, -1, -1); } /// Add a new mod, empty option group of the given type and name if it does not exist already. @@ -142,12 +132,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS if (group.Description == newDescription) return; - var _ = group switch - { - SingleModGroup s => s.Description = newDescription, - MultiModGroup m => m.Description = newDescription, - _ => newDescription, - }; + group.Description = newDescription; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, -1, -1); } @@ -155,9 +140,11 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS /// Change the description of the given option. public void ChangeOptionDescription(Mod mod, int groupIdx, int optionIdx, string newDescription) { - if (!mod.Groups[groupIdx].ChangeOptionDescription(optionIdx, newDescription)) + var option = mod.Groups[groupIdx].Options[optionIdx]; + if (option.Description == newDescription) return; + option.Description = newDescription; saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } @@ -193,9 +180,12 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS /// Rename the given option. public void RenameOption(Mod mod, int groupIdx, int optionIdx, string newName) { - if (!mod.Groups[groupIdx].ChangeOptionName(optionIdx, newName)) + var option = mod.Groups[groupIdx].Options[optionIdx]; + if (option.Name == newName) return; + option.Name = newName; + saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); } @@ -251,7 +241,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS Description = option.Description, }; if (option is IModDataContainer data) - SubModHelpers.Clone(data, newOption); + SubMod.Clone(data, newOption); s.OptionData.Add(newOption); break; } @@ -265,7 +255,7 @@ public class ModOptionEditor(CommunicatorService communicator, SaveService saveS Priority = option is MultiSubMod s ? s.Priority : ModPriority.Default, }; if (option is IModDataContainer data) - SubModHelpers.Clone(data, newOption); + SubMod.Clone(data, newOption); m.OptionData.Add(newOption); break; } diff --git a/Penumbra/Mods/Manager/ModStorage.cs b/Penumbra/Mods/Manager/ModStorage.cs index 65b8ddd9..acb2c1ab 100644 --- a/Penumbra/Mods/Manager/ModStorage.cs +++ b/Penumbra/Mods/Manager/ModStorage.cs @@ -3,17 +3,13 @@ using OtterGui.Widgets; namespace Penumbra.Mods.Manager; -public class ModCombo : FilterComboCache +public class ModCombo(Func> generator) : FilterComboCache(generator, MouseWheelType.None, Penumbra.Log) { protected override bool IsVisible(int globalIndex, LowerString filter) => Items[globalIndex].Name.Contains(filter); protected override string ToString(Mod obj) => obj.Name.Text; - - public ModCombo(Func> generator) - : base(generator, MouseWheelType.None, Penumbra.Log) - { } } public class ModStorage : IReadOnlyList diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 0626bc9d..40f943c8 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -115,7 +115,7 @@ public partial class ModCreator( try { var jObject = File.Exists(defaultFile) ? JObject.Parse(File.ReadAllText(defaultFile)) : new JObject(); - SubModHelpers.LoadDataContainer(jObject, mod.Default, mod.ModPath); + SubMod.LoadDataContainer(jObject, mod.Default, mod.ModPath); } catch (Exception e) { diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 980b805d..1a234879 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -22,7 +22,7 @@ public class DefaultSubMod(IMod mod) : IModDataContainer => null; public void AddTo(Dictionary redirections, HashSet manipulations) - => SubModHelpers.AddContainerTo(this, redirections, manipulations); + => SubMod.AddContainerTo(this, redirections, manipulations); public string GetName() => FullName; diff --git a/Penumbra/Mods/SubMods/MultiSubMod.cs b/Penumbra/Mods/SubMods/MultiSubMod.cs index c43d4b9e..3bcaffab 100644 --- a/Penumbra/Mods/SubMods/MultiSubMod.cs +++ b/Penumbra/Mods/SubMods/MultiSubMod.cs @@ -11,8 +11,8 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : OptionSubMod() ?? ModPriority.Default; } @@ -24,7 +24,7 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : OptionSubMod(Mod mod, T group) : IModDataOption public HashSet Manipulations { get; set; } = []; public void AddDataTo(Dictionary redirections, HashSet manipulations) - => SubModHelpers.AddContainerTo(this, redirections, manipulations); + => SubMod.AddContainerTo(this, redirections, manipulations); public string GetName() => Name; diff --git a/Penumbra/Mods/SubMods/SingleSubMod.cs b/Penumbra/Mods/SubMods/SingleSubMod.cs index 5d68e401..98c56151 100644 --- a/Penumbra/Mods/SubMods/SingleSubMod.cs +++ b/Penumbra/Mods/SubMods/SingleSubMod.cs @@ -9,8 +9,8 @@ public class SingleSubMod(Mod mod, SingleModGroup singleGroup) : OptionSubMod group switch + { + SingleModGroup single => new SingleSubMod(group.Mod, single) + { + Name = name, + Description = description, + }, + MultiModGroup multi => new MultiSubMod(group.Mod, multi) + { + Name = name, + Description = description, + }, + _ => throw new ArgumentOutOfRangeException(nameof(group)), + }; + /// Add all unique meta manipulations, file redirections and then file swaps from a ModDataContainer to the given sets. Skip any keys that are already contained. public static void AddContainerTo(IModDataContainer container, Dictionary redirections, HashSet manipulations) From 616db0dcc3a43fae6faeadde80260fa625d71cc9 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 26 Apr 2024 21:23:31 +1000 Subject: [PATCH 0584/1381] Add mesh vertex element readout --- Penumbra/Import/Models/Export/MeshExporter.cs | 1 - .../UI/AdvancedWindow/ModEditWindow.Models.cs | 44 ++++++++++++++++++- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 19b06d55..219a046e 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -1,5 +1,4 @@ using System.Collections.Immutable; -using Lumina.Data.Parsing; using Lumina.Extensions; using OtterGui; using Penumbra.GameData.Files; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 39924021..03b5169a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Components; using ImGuiNET; +using Lumina.Data.Parsing; using OtterGui; using OtterGui.Custom; using OtterGui.Raii; @@ -8,7 +9,6 @@ using OtterGui.Widgets; using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.Import.Models; -using Penumbra.Mods; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -421,6 +421,14 @@ public partial class ModEditWindow var file = tab.Mdl; var mesh = file.Meshes[meshIndex]; + // Vertex elements + ImGui.TableNextColumn(); + ImGui.AlignTextToFramePadding(); + ImGui.TextUnformatted("Vertex Elements"); + + ImGui.TableNextColumn(); + DrawVertexElementDetails(file.VertexDeclarations[meshIndex].VertexElements); + // Mesh material ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); @@ -436,6 +444,40 @@ public partial class ModEditWindow return ret; } + private static void DrawVertexElementDetails(MdlStructs.VertexElement[] vertexElements) + { + using var node = ImRaii.TreeNode($"Click to expand"); + if (!node) + return; + + var flags = ImGuiTableFlags.SizingFixedFit + | ImGuiTableFlags.RowBg + | ImGuiTableFlags.Borders + | ImGuiTableFlags.NoHostExtendX; + using var table = ImRaii.Table(string.Empty, 4, flags); + if (!table) + return; + + ImGui.TableSetupColumn("Usage"); + ImGui.TableSetupColumn("Type"); + ImGui.TableSetupColumn("Stream"); + ImGui.TableSetupColumn("Offset"); + + ImGui.TableHeadersRow(); + + foreach (var element in vertexElements) + { + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{(MdlFile.VertexUsage)element.Usage}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{(MdlFile.VertexType)element.Type}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{element.Stream}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{element.Offset}"); + } + } + private static bool DrawMaterialCombo(MdlTab tab, int meshIndex, bool disabled) { var mesh = tab.Mdl.Meshes[meshIndex]; From 1e5ed1c41450ba0d8b3b5dd85a8571ee49b6dd71 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 26 Apr 2024 18:43:45 +0200 Subject: [PATCH 0585/1381] Now that was a lot of work. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ModSettingsApi.cs | 3 +- .../Cache/CollectionCacheManager.cs | 4 +- .../Collections/Manager/CollectionStorage.cs | 6 +- Penumbra/Communication/ModOptionChanged.cs | 17 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 2 +- Penumbra/Mods/Editor/DuplicateManager.cs | 13 +- Penumbra/Mods/Editor/ModEditor.cs | 46 +- Penumbra/Mods/Editor/ModFileEditor.cs | 9 +- Penumbra/Mods/Editor/ModMerger.cs | 69 +-- Penumbra/Mods/Editor/ModMetaEditor.cs | 4 +- Penumbra/Mods/Editor/ModNormalizer.cs | 8 +- Penumbra/Mods/Editor/ModSwapEditor.cs | 4 +- Penumbra/Mods/Groups/IModGroup.cs | 11 +- Penumbra/Mods/Groups/ImcModGroup.cs | 158 +++++++ Penumbra/Mods/Groups/ModGroup.cs | 15 + Penumbra/Mods/Groups/ModSaveGroup.cs | 65 ++- Penumbra/Mods/Groups/MultiModGroup.cs | 78 ++-- Penumbra/Mods/Groups/SingleModGroup.cs | 91 ++-- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 11 +- Penumbra/Mods/Manager/ImcModGroupEditor.cs | 38 ++ Penumbra/Mods/Manager/ModCacheManager.cs | 4 +- Penumbra/Mods/Manager/ModGroupEditor.cs | 289 +++++++++++++ Penumbra/Mods/Manager/ModManager.cs | 9 +- Penumbra/Mods/Manager/ModMigration.cs | 16 +- Penumbra/Mods/Manager/ModOptionEditor.cs | 392 +++--------------- Penumbra/Mods/Manager/MultiModGroupEditor.cs | 84 ++++ Penumbra/Mods/Manager/SingleModGroupEditor.cs | 57 +++ Penumbra/Mods/ModCreator.cs | 20 +- Penumbra/Mods/Settings/ModSettings.cs | 44 +- Penumbra/Mods/Settings/Setting.cs | 28 ++ Penumbra/Mods/SubMods/IModOption.cs | 7 +- Penumbra/Mods/SubMods/ImcSubMod.cs | 32 ++ Penumbra/Mods/SubMods/MultiSubMod.cs | 20 +- Penumbra/Mods/SubMods/OptionSubMod.cs | 47 ++- Penumbra/Mods/SubMods/SingleSubMod.cs | 16 +- Penumbra/Mods/SubMods/SubMod.cs | 32 +- Penumbra/Penumbra.csproj | 10 +- Penumbra/Services/SaveService.cs | 9 +- Penumbra/Services/StaticServiceManager.cs | 1 - Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 35 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 6 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 4 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 132 +++--- 44 files changed, 1182 insertions(+), 766 deletions(-) create mode 100644 Penumbra/Mods/Groups/ImcModGroup.cs create mode 100644 Penumbra/Mods/Manager/ImcModGroupEditor.cs create mode 100644 Penumbra/Mods/Manager/ModGroupEditor.cs create mode 100644 Penumbra/Mods/Manager/MultiModGroupEditor.cs create mode 100644 Penumbra/Mods/Manager/SingleModGroupEditor.cs create mode 100644 Penumbra/Mods/SubMods/ImcSubMod.cs diff --git a/Penumbra.Api b/Penumbra.Api index 590629df..69d106b4 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 590629df33f9ad92baddd1d65ec8c986f18d608a +Subproject commit 69d106b457eb0f73d4b4caf1234da5631fd6fbf0 diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 039fbfa9..bfd134bb 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -11,6 +11,7 @@ using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; namespace Penumbra.Api.Api; @@ -254,7 +255,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting _1, int _2, bool inherited) => ModSettingChanged?.Invoke(type, collection.Id, mod?.ModPath.Name ?? string.Empty, inherited); - private void OnModOptionEdited(ModOptionChangeType type, Mod mod, int groupIndex, int optionIndex, int moveIndex) + private void OnModOptionEdited(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int moveIndex) { switch (type) { diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index c1296414..9c104cef 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -7,8 +7,10 @@ using Penumbra.Communication; using Penumbra.Interop.ResourceLoading; using Penumbra.Meta; using Penumbra.Mods; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; @@ -257,7 +259,7 @@ public class CollectionCacheManager : IDisposable } /// Prepare Changes by removing mods from caches with collections or add or reload mods. - private void OnModOptionChange(ModOptionChangeType type, Mod mod, int groupIdx, int optionIdx, int movedToIdx) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int movedToIdx) { if (type is ModOptionChangeType.PrepareChange) { diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 1fe5b227..bfae2dc0 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -4,8 +4,10 @@ using OtterGui.Classes; using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; namespace Penumbra.Collections.Manager; @@ -290,7 +292,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable } /// Save all collections where the mod has settings and the change requires saving. - private void OnModOptionChange(ModOptionChangeType type, Mod mod, int groupIdx, int optionIdx, int movedToIdx) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int movedToIdx) { type.HandlingInfo(out var requiresSaving, out _, out _); if (!requiresSaving) @@ -298,7 +300,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable foreach (var collection in this) { - if (collection.Settings[mod.Index]?.HandleChanges(type, mod, groupIdx, optionIdx, movedToIdx) ?? false) + if (collection.Settings[mod.Index]?.HandleChanges(type, mod, group, option, movedToIdx) ?? false) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); } } diff --git a/Penumbra/Communication/ModOptionChanged.cs b/Penumbra/Communication/ModOptionChanged.cs index 0df58b5f..a20592ec 100644 --- a/Penumbra/Communication/ModOptionChanged.cs +++ b/Penumbra/Communication/ModOptionChanged.cs @@ -1,8 +1,10 @@ using OtterGui.Classes; -using Penumbra.Api; using Penumbra.Api.Api; using Penumbra.Mods; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; +using Penumbra.Mods.SubMods; +using static Penumbra.Communication.ModOptionChanged; namespace Penumbra.Communication; @@ -11,22 +13,23 @@ namespace Penumbra.Communication; /// /// Parameter is the type option change. /// Parameter is the changed mod. -/// Parameter is the index of the changed group inside the mod. -/// Parameter is the index of the changed option inside the group or -1 if it does not concern a specific option. -/// Parameter is the index of the group an option was moved to. +/// Parameter is the changed group inside the mod. +/// Parameter is the changed option inside the group or null if it does not concern a specific option. +/// Parameter is the changed data container inside the group or null if it does not concern a specific data container. +/// Parameter is the index of the group or option moved or deleted from. /// public sealed class ModOptionChanged() - : EventWrapper(nameof(ModOptionChanged)) + : EventWrapper(nameof(ModOptionChanged)) { public enum Priority { - /// + /// Api = int.MinValue, /// CollectionCacheManager = -100, - /// + /// ModCacheManager = 0, /// diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index eb6d0b0c..2b45ecbe 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -205,7 +205,7 @@ public partial class TexToolsImporter { var option = group.OptionList[idx]; _currentOptionName = option.Name; - options.Insert(idx, MultiSubMod.CreateForSaving(option.Name, option.Description, ModPriority.Default)); + options.Insert(idx, MultiSubMod.WithoutGroup(option.Name, option.Description, ModPriority.Default)); if (option.IsChecked) defaultSettings = Setting.Single(idx); } diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 31aacbe1..84a832a2 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -60,7 +60,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co private void HandleDuplicate(Mod mod, FullPath duplicate, FullPath remaining, bool useModManager) { - ModEditor.ApplyToAllOptions(mod, HandleSubMod); + ModEditor.ApplyToAllContainers(mod, HandleSubMod); try { @@ -73,7 +73,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co return; - void HandleSubMod(IModDataContainer subMod, int groupIdx, int optionIdx) + void HandleSubMod(IModDataContainer subMod) { var changes = false; var dict = subMod.Files.ToDictionary(kvp => kvp.Key, @@ -82,14 +82,9 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co return; if (useModManager) - { - modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, dict, SaveType.ImmediateSync); - } + modManager.OptionEditor.SetFiles(subMod, dict, SaveType.ImmediateSync); else - { - subMod.Files = dict; - saveService.ImmediateSaveSync(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - } + saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, subMod, config.ReplaceNonAsciiOnImport)); } } diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index e1c5962f..37524da1 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -29,8 +29,8 @@ public class ModEditor( public int GroupIdx { get; private set; } public int DataIdx { get; private set; } - public IModGroup? Group { get; private set; } - public IModDataContainer? Option { get; private set; } + public IModGroup? Group { get; private set; } + public IModDataContainer? Option { get; private set; } public void LoadMod(Mod mod) => LoadMod(mod, -1, 0); @@ -63,10 +63,10 @@ public class ModEditor( { if (groupIdx == -1 && dataIdx == 0) { - Group = null; - Option = Mod.Default; - GroupIdx = groupIdx; - DataIdx = dataIdx; + Group = null; + Option = Mod.Default; + GroupIdx = groupIdx; + DataIdx = dataIdx; return; } @@ -75,18 +75,18 @@ public class ModEditor( Group = Mod.Groups[groupIdx]; if (dataIdx >= 0 && dataIdx < Group.DataContainers.Count) { - Option = Group.DataContainers[dataIdx]; - GroupIdx = groupIdx; - DataIdx = dataIdx; + Option = Group.DataContainers[dataIdx]; + GroupIdx = groupIdx; + DataIdx = dataIdx; return; } } } - Group = null; - Option = Mod?.Default; - GroupIdx = -1; - DataIdx = 0; + Group = null; + Option = Mod?.Default; + GroupIdx = -1; + DataIdx = 0; if (message) Penumbra.Log.Error($"Loading invalid option {groupIdx} {dataIdx} for Mod {Mod?.Name ?? "Unknown"}."); } @@ -105,23 +105,11 @@ public class ModEditor( => Clear(); /// Apply a option action to all available option in a mod, including the default option. - public static void ApplyToAllOptions(Mod mod, Action action) + public static void ApplyToAllContainers(Mod mod, Action action) { - action(mod.Default, -1, 0); - foreach (var (group, groupIdx) in mod.Groups.WithIndex()) - { - switch (group) - { - case SingleModGroup single: - for (var optionIdx = 0; optionIdx < single.OptionData.Count; ++optionIdx) - action(single.OptionData[optionIdx], groupIdx, optionIdx); - break; - case MultiModGroup multi: - for (var optionIdx = 0; optionIdx < multi.OptionData.Count; ++optionIdx) - action(multi.OptionData[optionIdx], groupIdx, optionIdx); - break; - } - } + action(mod.Default); + foreach (var container in mod.Groups.SelectMany(g => g.DataContainers)) + action(container); } // Does not delete the base directory itself even if it is completely empty at the end. diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 00685c94..e2c0b726 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -24,8 +24,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu num += dict.TryAdd(path.Item2, file.File) ? 0 : 1; } - var (groupIdx, dataIdx) = option.GetDataIndices(); - modManager.OptionEditor.OptionSetFiles(mod, groupIdx, dataIdx, dict); + modManager.OptionEditor.SetFiles(option, dict); files.UpdatePaths(mod, option); Changes = false; return num; @@ -40,15 +39,15 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu /// Remove all path redirections where the pointed-to file does not exist. public void RemoveMissingPaths(Mod mod, IModDataContainer option) { - void HandleSubMod(IModDataContainer subMod, int groupIdx, int optionIdx) + void HandleSubMod(IModDataContainer subMod) { var newDict = subMod.Files.Where(kvp => CheckAgainstMissing(mod, subMod, kvp.Value, kvp.Key, subMod == option)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (newDict.Count != subMod.Files.Count) - modManager.OptionEditor.OptionSetFiles(mod, groupIdx, optionIdx, newDict); + modManager.OptionEditor.SetFiles(subMod, newDict); } - ModEditor.ApplyToAllOptions(mod, HandleSubMod); + ModEditor.ApplyToAllContainers(mod, HandleSubMod); files.ClearMissingFiles(); } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 0f629bc7..3a6f4a81 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -16,7 +16,7 @@ public class ModMerger : IDisposable { private readonly Configuration _config; private readonly CommunicatorService _communicator; - private readonly ModOptionEditor _editor; + private readonly ModGroupEditor _editor; private readonly ModFileSystemSelector _selector; private readonly DuplicateManager _duplicates; private readonly ModManager _mods; @@ -32,14 +32,14 @@ public class ModMerger : IDisposable private readonly Dictionary _fileToFile = []; private readonly HashSet _createdDirectories = []; private readonly HashSet _createdGroups = []; - private readonly HashSet _createdOptions = []; + private readonly HashSet _createdOptions = []; public readonly HashSet SelectedOptions = []; public readonly IReadOnlyList Warnings = []; public Exception? Error { get; private set; } - public ModMerger(ModManager mods, ModOptionEditor editor, ModFileSystemSelector selector, DuplicateManager duplicates, + public ModMerger(ModManager mods, ModGroupEditor editor, ModFileSystemSelector selector, DuplicateManager duplicates, CommunicatorService communicator, ModCreator creator, Configuration config) { _editor = editor; @@ -100,22 +100,23 @@ public class ModMerger : IDisposable var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, originalGroup.Type, originalGroup.Name); if (groupCreated) _createdGroups.Add(groupIdx); - if (group.Type != originalGroup.Type) - ((List)Warnings).Add( - $"The merged group {group.Name} already existed, but has a different type {group.Type} than the original group of type {originalGroup.Type}."); + if (group == null) + throw new Exception( + $"The merged group {originalGroup.Name} already existed, but had a different type than the original group of type {originalGroup.Type}."); foreach (var originalOption in group.DataContainers) { - var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, originalOption.GetName()); + var (option, _, optionCreated) = _editor.FindOrAddOption(group, originalOption.GetName()); if (optionCreated) { - _createdOptions.Add((IModDataOption)option); - MergeIntoOption([originalOption], (IModDataOption)option, false); + _createdOptions.Add(option!); + // #TODO DataContainer <> Option. + MergeIntoOption([originalOption], (IModDataContainer)option!, false); } else { throw new Exception( - $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: The option {option.FullName} already existed."); + $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: The option {option!.FullName} already existed."); } } } @@ -138,9 +139,9 @@ public class ModMerger : IDisposable var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, GroupType.Multi, groupName, SaveType.None); if (groupCreated) _createdGroups.Add(groupIdx); - var (option, _, optionCreated) = _editor.FindOrAddOption(MergeToMod!, groupIdx, optionName, SaveType.None); + var (option, _, optionCreated) = _editor.FindOrAddOption(group!, optionName, SaveType.None); if (optionCreated) - _createdOptions.Add((IModDataOption)option); + _createdOptions.Add(option!); var dir = ModCreator.NewOptionDirectory(MergeToMod!.ModPath, groupName, _config.ReplaceNonAsciiOnImport); if (!dir.Exists) _createdDirectories.Add(dir.FullName); @@ -148,7 +149,8 @@ public class ModMerger : IDisposable if (!dir.Exists) _createdDirectories.Add(dir.FullName); CopyFiles(dir); - MergeIntoOption(MergeFromMod!.AllDataContainers.Reverse(), (IModDataOption)option, true); + // #TODO DataContainer <> Option. + MergeIntoOption(MergeFromMod!.AllDataContainers.Reverse(), (IModDataContainer)option!, true); } private void MergeIntoOption(IEnumerable mergeOptions, IModDataContainer option, bool fromFileToFile) @@ -184,10 +186,9 @@ public class ModMerger : IDisposable } } - var (groupIdx, dataIdx) = option.GetDataIndices(); - _editor.OptionSetFiles(MergeToMod!, groupIdx, dataIdx, redirections, SaveType.None); - _editor.OptionSetFileSwaps(MergeToMod!, groupIdx, dataIdx, swaps, SaveType.None); - _editor.OptionSetManipulations(MergeToMod!, groupIdx, dataIdx, manips, SaveType.ImmediateSync); + _editor.SetFiles(option, redirections, SaveType.None); + _editor.SetFileSwaps(option, swaps, SaveType.None); + _editor.SetManipulations(option, manips, SaveType.ImmediateSync); return; bool GetFullPath(FullPath input, out FullPath ret) @@ -261,30 +262,31 @@ public class ModMerger : IDisposable if (mods.Count == 1) { var files = CopySubModFiles(mods[0], dir); - _editor.OptionSetFiles(result, -1, 0, files); - _editor.OptionSetFileSwaps(result, -1, 0, mods[0].FileSwaps); - _editor.OptionSetManipulations(result, -1, 0, mods[0].Manipulations); + _editor.SetFiles(result.Default, files); + _editor.SetFileSwaps(result.Default, mods[0].FileSwaps); + _editor.SetManipulations(result.Default, mods[0].Manipulations); } else { foreach (var originalOption in mods) { - if (originalOption.Group is not {} originalGroup) + if (originalOption.Group is not { } originalGroup) { var files = CopySubModFiles(mods[0], dir); - _editor.OptionSetFiles(result, -1, 0, files); - _editor.OptionSetFileSwaps(result, -1, 0, mods[0].FileSwaps); - _editor.OptionSetManipulations(result, -1, 0, mods[0].Manipulations); + _editor.SetFiles(result.Default, files); + _editor.SetFileSwaps(result.Default, mods[0].FileSwaps); + _editor.SetManipulations(result.Default, mods[0].Manipulations); } else { - var (group, groupIdx, _) = _editor.FindOrAddModGroup(result, originalGroup.Type, originalGroup.Name); - var (option, optionIdx, _) = _editor.FindOrAddOption(result, groupIdx, originalOption.GetName()); - var folder = Path.Combine(dir.FullName, group.Name, option.Name); + // TODO DataContainer <> Option. + var (group, _, _) = _editor.FindOrAddModGroup(result, originalGroup.Type, originalGroup.Name); + var (option, _, _) = _editor.FindOrAddOption(group!, originalOption.GetName()); + var folder = Path.Combine(dir.FullName, group!.Name, option!.Name); var files = CopySubModFiles(originalOption, new DirectoryInfo(folder)); - _editor.OptionSetFiles(result, groupIdx, optionIdx, files); - _editor.OptionSetFileSwaps(result, groupIdx, optionIdx, originalOption.FileSwaps); - _editor.OptionSetManipulations(result, groupIdx, optionIdx, originalOption.Manipulations); + _editor.SetFiles((IModDataContainer)option, files); + _editor.SetFileSwaps((IModDataContainer)option, originalOption.FileSwaps); + _editor.SetManipulations((IModDataContainer)option, originalOption.Manipulations); } } } @@ -339,16 +341,15 @@ public class ModMerger : IDisposable { foreach (var option in _createdOptions) { - var (groupIdx, optionIdx) = option.GetOptionIndices(); - _editor.DeleteOption(MergeToMod!, groupIdx, optionIdx); + _editor.DeleteOption(option); Penumbra.Log.Verbose($"[Merger] Removed option {option.FullName}."); } foreach (var group in _createdGroups) { var groupName = MergeToMod!.Groups[group]; - _editor.DeleteModGroup(MergeToMod!, group); - Penumbra.Log.Verbose($"[Merger] Removed option group {groupName}."); + _editor.DeleteModGroup(groupName); + Penumbra.Log.Verbose($"[Merger] Removed option group {groupName.Name}."); } foreach (var dir in _createdDirectories) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index dee700d5..2f7fd04c 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -145,12 +145,12 @@ public class ModMetaEditor(ModManager modManager) Split(currentOption.Manipulations); } - public void Apply(Mod mod, int groupIdx, int optionIdx) + public void Apply(IModDataContainer container) { if (!Changes) return; - modManager.OptionEditor.OptionSetManipulations(mod, groupIdx, optionIdx, Recombine().ToHashSet()); + modManager.OptionEditor.SetManipulations(container, Recombine().ToHashSet()); Changes = false; } diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index e2088b32..437600c9 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -283,12 +283,12 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) switch (group) { case SingleModGroup single: - foreach (var (_, optionIdx) in single.OptionData.WithIndex()) - _modManager.OptionEditor.OptionSetFiles(Mod, groupIdx, optionIdx, _redirections[groupIdx + 1][optionIdx]); + foreach (var (option, optionIdx) in single.OptionData.WithIndex()) + _modManager.OptionEditor.SetFiles(option, _redirections[groupIdx + 1][optionIdx]); break; case MultiModGroup multi: - foreach (var (_, optionIdx) in multi.OptionData.WithIndex()) - _modManager.OptionEditor.OptionSetFiles(Mod, groupIdx, optionIdx, _redirections[groupIdx + 1][optionIdx]); + foreach (var (option, optionIdx) in multi.OptionData.WithIndex()) + _modManager.OptionEditor.SetFiles(option, _redirections[groupIdx + 1][optionIdx]); break; } } diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index 3247cfdf..0250efae 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -17,12 +17,12 @@ public class ModSwapEditor(ModManager modManager) Changes = false; } - public void Apply(Mod mod, int groupIdx, int optionIdx) + public void Apply(IModDataContainer container) { if (!Changes) return; - modManager.OptionEditor.OptionSetFileSwaps(mod, groupIdx, optionIdx, _swaps); + modManager.OptionEditor.SetFileSwaps(container, _swaps); Changes = false; } diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index b13799cd..a268ba0f 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -9,7 +9,7 @@ namespace Penumbra.Mods.Groups; public interface ITexToolsGroup { - public IReadOnlyList OptionData { get; } + public IReadOnlyList OptionData { get; } } public interface IModGroup @@ -17,22 +17,19 @@ public interface IModGroup public const int MaxMultiOptions = 63; public Mod Mod { get; } - public string Name { get; } + public string Name { get; set; } public string Description { get; set; } public GroupType Type { get; } public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } - public FullPath? FindBestMatch(Utf8GamePath gamePath); - public int AddOption(Mod mod, string name, string description = ""); + public FullPath? FindBestMatch(Utf8GamePath gamePath); + public IModOption? AddOption(string name, string description = ""); public IReadOnlyList Options { get; } public IReadOnlyList DataContainers { get; } public bool IsOption { get; } - public IModGroup Convert(GroupType type); - public bool MoveOption(int optionIdxFrom, int optionIdxTo); - public int GetIndex(); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs new file mode 100644 index 00000000..e233f82e --- /dev/null +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -0,0 +1,158 @@ +using Newtonsoft.Json; +using Penumbra.Api.Enums; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.Groups; + +public class ImcModGroup(Mod mod) : IModGroup +{ + public const int DisabledIndex = 30; + public const int NumAttributes = 10; + + public Mod Mod { get; } = mod; + public string Name { get; set; } = "Option"; + public string Description { get; set; } = "A single IMC manipulation."; + + public GroupType Type + => GroupType.Imc; + + public ModPriority Priority { get; set; } = ModPriority.Default; + public Setting DefaultSettings { get; set; } = Setting.Zero; + + public PrimaryId PrimaryId; + public SecondaryId SecondaryId; + public ObjectType ObjectType; + public BodySlot BodySlot; + public EquipSlot EquipSlot; + public Variant Variant; + + public ImcEntry DefaultEntry; + + public FullPath? FindBestMatch(Utf8GamePath gamePath) + => null; + + private bool _canBeDisabled = false; + + public bool CanBeDisabled + { + get => _canBeDisabled; + set + { + _canBeDisabled = value; + if (!value) + DefaultSettings = FixSetting(DefaultSettings); + } + } + + public IModOption? AddOption(string name, string description = "") + { + uint fullMask = GetFullMask(); + var firstUnset = (byte)BitOperations.TrailingZeroCount(~fullMask); + // All attributes handled. + if (firstUnset >= NumAttributes) + return null; + + var groupIdx = Mod.Groups.IndexOf(this); + if (groupIdx < 0) + return null; + + var subMod = new ImcSubMod(this) + { + Name = name, + Description = description, + AttributeIndex = firstUnset, + }; + OptionData.Add(subMod); + return subMod; + } + + public readonly List OptionData = []; + + public IReadOnlyList Options + => OptionData; + + public IReadOnlyList DataContainers + => []; + + public bool IsOption + => CanBeDisabled || OptionData.Count > 0; + + public int GetIndex() + => ModGroup.GetIndex(this); + + private ushort GetCurrentMask(Setting setting) + { + var mask = DefaultEntry.AttributeMask; + for (var i = 0; i < OptionData.Count; ++i) + { + if (!setting.HasFlag(i)) + continue; + + var option = OptionData[i]; + mask |= option.Attribute; + } + + return mask; + } + + private ushort GetFullMask() + => GetCurrentMask(Setting.AllBits(63)); + + private ImcManipulation GetManip(ushort mask) + => new(ObjectType, BodySlot, PrimaryId, SecondaryId.Id, Variant.Id, EquipSlot, + DefaultEntry with { AttributeMask = mask }); + + + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + { + if (CanBeDisabled && setting.HasFlag(DisabledIndex)) + return; + + var mask = GetCurrentMask(setting); + var imc = GetManip(mask); + manipulations.Add(imc); + } + + public Setting FixSetting(Setting setting) + => new(setting.Value & (((1ul << OptionData.Count) - 1) | (CanBeDisabled ? 1ul << DisabledIndex : 0))); + + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) + { + ModSaveGroup.WriteJsonBase(jWriter, this); + jWriter.WritePropertyName(nameof(ObjectType)); + jWriter.WriteValue(ObjectType.ToString()); + jWriter.WritePropertyName(nameof(BodySlot)); + jWriter.WriteValue(BodySlot.ToString()); + jWriter.WritePropertyName(nameof(EquipSlot)); + jWriter.WriteValue(EquipSlot.ToString()); + jWriter.WritePropertyName(nameof(PrimaryId)); + jWriter.WriteValue(PrimaryId.Id); + jWriter.WritePropertyName(nameof(SecondaryId)); + jWriter.WriteValue(SecondaryId.Id); + jWriter.WritePropertyName(nameof(Variant)); + jWriter.WriteValue(Variant.Id); + jWriter.WritePropertyName(nameof(DefaultEntry)); + serializer.Serialize(jWriter, DefaultEntry); + jWriter.WritePropertyName("Options"); + jWriter.WriteStartArray(); + foreach (var option in OptionData) + { + jWriter.WriteStartObject(); + SubMod.WriteModOption(jWriter, option); + jWriter.WritePropertyName(nameof(option.AttributeIndex)); + jWriter.WriteValue(option.AttributeIndex); + jWriter.WriteEndObject(); + } + + jWriter.WriteEndArray(); + jWriter.WriteEndObject(); + } + + public (int Redirections, int Swaps, int Manips) GetCounts() + => (0, 0, 1); +} diff --git a/Penumbra/Mods/Groups/ModGroup.cs b/Penumbra/Mods/Groups/ModGroup.cs index da302714..8b55a035 100644 --- a/Penumbra/Mods/Groups/ModGroup.cs +++ b/Penumbra/Mods/Groups/ModGroup.cs @@ -5,6 +5,7 @@ namespace Penumbra.Mods.Groups; public static class ModGroup { + /// Create a new mod group based on the given type. public static IModGroup Create(Mod mod, GroupType type, string name) { var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; @@ -20,6 +21,11 @@ public static class ModGroup Name = name, Priority = maxPriority, }, + GroupType.Imc => new ImcModGroup(mod) + { + Name = name, + Priority = maxPriority, + }, _ => throw new ArgumentOutOfRangeException(nameof(type), type, null), }; } @@ -38,5 +44,14 @@ public static class ModGroup } return (redirectionCount, swapCount, manipCount); + } + + public static int GetIndex(IModGroup group) + { + var groupIndex = group.Mod.Groups.IndexOf(group); + if (groupIndex < 0) + throw new Exception($"Mod {group.Mod.Name} from Group {group.Name} does not contain this group."); + + return groupIndex; } } diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index 332879cb..efdcde09 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -1,9 +1,9 @@ -using Newtonsoft.Json; -using Penumbra.Mods.SubMods; -using Penumbra.Services; - -namespace Penumbra.Mods.Groups; - +using Newtonsoft.Json; +using Penumbra.Mods.SubMods; +using Penumbra.Services; + +namespace Penumbra.Mods.Groups; + public readonly struct ModSaveGroup : ISavable { private readonly DirectoryInfo _basePath; @@ -12,25 +12,21 @@ public readonly struct ModSaveGroup : ISavable private readonly DefaultSubMod? _defaultMod; private readonly bool _onlyAscii; - public ModSaveGroup(Mod mod, int groupIdx, bool onlyAscii) - { - _basePath = mod.ModPath; - _groupIdx = groupIdx; - if (_groupIdx < 0) - _defaultMod = mod.Default; - else - _group = mod.Groups[_groupIdx]; - _onlyAscii = onlyAscii; - } - - public ModSaveGroup(DirectoryInfo basePath, IModGroup group, int groupIdx, bool onlyAscii) + private ModSaveGroup(DirectoryInfo basePath, IModGroup group, int groupIndex, bool onlyAscii) { _basePath = basePath; _group = group; - _groupIdx = groupIdx; + _groupIdx = groupIndex; _onlyAscii = onlyAscii; } + public static ModSaveGroup WithoutMod(DirectoryInfo basePath, IModGroup group, int groupIndex, bool onlyAscii) + => new(basePath, group, groupIndex, onlyAscii); + + public ModSaveGroup(IModGroup group, bool onlyAscii) + : this(group.Mod.ModPath, group, group.GetIndex(), onlyAscii) + { } + public ModSaveGroup(DirectoryInfo basePath, DefaultSubMod @default, bool onlyAscii) { _basePath = basePath; @@ -39,6 +35,33 @@ public readonly struct ModSaveGroup : ISavable _onlyAscii = onlyAscii; } + public ModSaveGroup(DirectoryInfo basePath, IModDataContainer container, bool onlyAscii) + { + _basePath = basePath; + _defaultMod = container as DefaultSubMod; + _onlyAscii = onlyAscii; + if (_defaultMod == null) + { + _groupIdx = -1; + _group = null; + } + else + { + _group = container.Group!; + _groupIdx = _group.GetIndex(); + } + } + + public ModSaveGroup(IModDataContainer container, bool onlyAscii) + { + _basePath = (container.Mod as Mod)?.ModPath + ?? throw new Exception("Invalid save group from default data container without base path."); // Should not happen. + _defaultMod = null; + _onlyAscii = onlyAscii; + _group = container.Group!; + _groupIdx = _group.GetIndex(); + } + public string ToFilename(FilenameService fileNames) => fileNames.OptionGroupFile(_basePath.FullName, _groupIdx, _group?.Name ?? string.Empty, _onlyAscii); @@ -59,7 +82,7 @@ public readonly struct ModSaveGroup : ISavable { jWriter.WriteStartObject(); jWriter.WritePropertyName(nameof(group.Name)); - jWriter.WriteValue(group!.Name); + jWriter.WriteValue(group.Name); jWriter.WritePropertyName(nameof(group.Description)); jWriter.WriteValue(group.Description); jWriter.WritePropertyName(nameof(group.Priority)); @@ -69,4 +92,4 @@ public readonly struct ModSaveGroup : ISavable jWriter.WritePropertyName(nameof(group.DefaultSettings)); jWriter.WriteValue(group.DefaultSettings.Value); } -} +} diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 6b352f66..a0034be0 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -3,7 +3,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; -using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; @@ -18,11 +17,11 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public GroupType Type => GroupType.Multi; - public Mod Mod { get; set; } = mod; - public string Name { get; set; } = "Group"; - public string Description { get; set; } = "A non-exclusive group of settings."; - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; } = mod; + public string Name { get; set; } = "Group"; + public string Description { get; set; } = "A non-exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public readonly List OptionData = []; public IReadOnlyList Options @@ -39,28 +38,28 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup .SelectWhere(o => (o.Files.TryGetValue(gamePath, out var file) || o.FileSwaps.TryGetValue(gamePath, out file), file)) .FirstOrDefault(); - public int AddOption(Mod mod, string name, string description = "") + public IModOption? AddOption(string name, string description = "") { - var groupIdx = mod.Groups.IndexOf(this); + var groupIdx = Mod.Groups.IndexOf(this); if (groupIdx < 0) - return -1; + return null; - var subMod = new MultiSubMod(mod, this) + var subMod = new MultiSubMod(this) { - Name = name, + Name = name, Description = description, }; OptionData.Add(subMod); - return OptionData.Count - 1; + return subMod; } public static MultiModGroup? Load(Mod mod, JObject json) { var ret = new MultiModGroup(mod) { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) @@ -78,7 +77,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup break; } - var subMod = new MultiSubMod(mod, ret, child); + var subMod = new MultiSubMod(ret, child); ret.OptionData.Add(subMod); } @@ -87,42 +86,21 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup return ret; } - public IModGroup Convert(GroupType type) + public SingleModGroup ConvertToSingle() { - switch (type) + var single = new SingleModGroup(Mod) { - case GroupType.Multi: return this; - case GroupType.Single: - var single = new SingleModGroup(Mod) - { - Name = Name, - Description = Description, - Priority = Priority, - DefaultSettings = DefaultSettings.TurnMulti(OptionData.Count), - }; - single.OptionData.AddRange(OptionData.Select(o => o.ConvertToSingle(Mod, single))); - return single; - default: throw new ArgumentOutOfRangeException(nameof(type), type, null); - } - } - - public bool MoveOption(int optionIdxFrom, int optionIdxTo) - { - if (!OptionData.Move(optionIdxFrom, optionIdxTo)) - return false; - - DefaultSettings = DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); - return true; + Name = Name, + Description = Description, + Priority = Priority, + DefaultSettings = DefaultSettings.TurnMulti(OptionData.Count), + }; + single.OptionData.AddRange(OptionData.Select(o => o.ConvertToSingle(single))); + return single; } public int GetIndex() - { - var groupIndex = Mod.Groups.IndexOf(this); - if (groupIndex < 0) - throw new Exception($"Mod {Mod.Name} from Group {Name} does not contain this group."); - - return groupIndex; - } + => ModGroup.GetIndex(this); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { @@ -156,15 +134,15 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup => ModGroup.GetCountsBase(this); public Setting FixSetting(Setting setting) - => new(setting.Value & (1ul << OptionData.Count) - 1); + => new(setting.Value & ((1ul << OptionData.Count) - 1)); /// Create a group without a mod only for saving it in the creator. - internal static MultiModGroup CreateForSaving(string name) + internal static MultiModGroup WithoutMod(string name) => new(null!) { Name = name, }; - IReadOnlyList ITexToolsGroup.OptionData + IReadOnlyList ITexToolsGroup.OptionData => OptionData; } diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index ac85e2bc..0776c2af 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -1,7 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; -using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; @@ -16,31 +15,28 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public GroupType Type => GroupType.Single; - public Mod Mod { get; set; } = mod; - public string Name { get; set; } = "Option"; - public string Description { get; set; } = "A mutually exclusive group of settings."; - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; } = mod; + public string Name { get; set; } = "Option"; + public string Description { get; set; } = "A mutually exclusive group of settings."; + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public readonly List OptionData = []; - IReadOnlyList ITexToolsGroup.OptionData - => OptionData; - public FullPath? FindBestMatch(Utf8GamePath gamePath) => OptionData .SelectWhere(m => (m.Files.TryGetValue(gamePath, out var file) || m.FileSwaps.TryGetValue(gamePath, out file), file)) .FirstOrDefault(); - public int AddOption(Mod mod, string name, string description = "") + public IModOption AddOption(string name, string description = "") { - var subMod = new SingleSubMod(mod, this) + var subMod = new SingleSubMod(this) { - Name = name, + Name = name, Description = description, }; OptionData.Add(subMod); - return OptionData.Count - 1; + return subMod; } public IReadOnlyList Options @@ -57,9 +53,9 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup var options = json["Options"]; var ret = new SingleModGroup(mod) { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; if (ret.Name.Length == 0) @@ -68,7 +64,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup if (options != null) foreach (var child in options.Children()) { - var subMod = new SingleSubMod(mod, ret, child); + var subMod = new SingleSubMod(ret, child); ret.OptionData.Add(subMod); } @@ -76,57 +72,21 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup return ret; } - public IModGroup Convert(GroupType type) + public MultiModGroup ConvertToMulti() { - switch (type) + var multi = new MultiModGroup(Mod) { - case GroupType.Single: return this; - case GroupType.Multi: - var multi = new MultiModGroup(Mod) - { - Name = Name, - Description = Description, - Priority = Priority, - DefaultSettings = Setting.Multi((int)DefaultSettings.Value), - }; - multi.OptionData.AddRange(OptionData.Select((o, i) => o.ConvertToMulti(Mod, multi, new ModPriority(i)))); - return multi; - default: throw new ArgumentOutOfRangeException(nameof(type), type, null); - } + Name = Name, + Description = Description, + Priority = Priority, + DefaultSettings = Setting.Multi((int)DefaultSettings.Value), + }; + multi.OptionData.AddRange(OptionData.Select((o, i) => o.ConvertToMulti(multi, new ModPriority(i)))); + return multi; } - public bool MoveOption(int optionIdxFrom, int optionIdxTo) - { - if (!OptionData.Move(optionIdxFrom, optionIdxTo)) - return false; - - var currentIndex = DefaultSettings.AsIndex; - // Update default settings with the move. - if (currentIndex == optionIdxFrom) - { - DefaultSettings = Setting.Single(optionIdxTo); - } - else if (optionIdxFrom < optionIdxTo) - { - if (currentIndex > optionIdxFrom && currentIndex <= optionIdxTo) - DefaultSettings = Setting.Single(currentIndex - 1); - } - else if (currentIndex < optionIdxFrom && currentIndex >= optionIdxTo) - { - DefaultSettings = Setting.Single(currentIndex + 1); - } - - return true; - } - - public int GetIndex() - { - var groupIndex = Mod.Groups.IndexOf(this); - if (groupIndex < 0) - throw new Exception($"Mod {Mod.Name} from Group {Name} does not contain this group."); - - return groupIndex; - } + public int GetIndex() + => ModGroup.GetIndex(this); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) => OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); @@ -160,4 +120,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup { Name = name, }; + + IReadOnlyList ITexToolsGroup.OptionData + => OptionData; } diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 1545811e..449405a0 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -1,3 +1,4 @@ +using OtterGui.Classes; using Penumbra.Collections; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; @@ -8,6 +9,7 @@ using Penumbra.Meta; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; namespace Penumbra.Mods.ItemSwap; @@ -40,8 +42,7 @@ public class ItemSwapContainer NoSwaps, } - public bool WriteMod(ModManager manager, Mod mod, WriteType writeType = WriteType.NoSwaps, DirectoryInfo? directory = null, - int groupIndex = -1, int optionIndex = 0) + public bool WriteMod(ModManager manager, Mod mod, IModDataContainer container, WriteType writeType = WriteType.NoSwaps, DirectoryInfo? directory = null) { var convertedManips = new HashSet(Swaps.Count); var convertedFiles = new Dictionary(Swaps.Count); @@ -80,9 +81,9 @@ public class ItemSwapContainer } } - manager.OptionEditor.OptionSetFiles(mod, groupIndex, optionIndex, convertedFiles); - manager.OptionEditor.OptionSetFileSwaps(mod, groupIndex, optionIndex, convertedSwaps); - manager.OptionEditor.OptionSetManipulations(mod, groupIndex, optionIndex, convertedManips); + manager.OptionEditor.SetFiles(container, convertedFiles, SaveType.None); + manager.OptionEditor.SetFileSwaps(container, convertedSwaps, SaveType.None); + manager.OptionEditor.SetManipulations(container, convertedManips, SaveType.ImmediateSync); return true; } catch (Exception e) diff --git a/Penumbra/Mods/Manager/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/ImcModGroupEditor.cs new file mode 100644 index 00000000..4e2b2194 --- /dev/null +++ b/Penumbra/Mods/Manager/ImcModGroupEditor.cs @@ -0,0 +1,38 @@ +using OtterGui.Classes; +using OtterGui.Filesystem; +using OtterGui.Services; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; + +namespace Penumbra.Mods.Manager; + +public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) + : ModOptionEditor(communicator, saveService, config), IService +{ + protected override ImcModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) + => new(mod) + { + Name = newName, + Priority = priority, + }; + + protected override ImcSubMod? CloneOption(ImcModGroup group, IModOption option) + => null; + + protected override void RemoveOption(ImcModGroup group, int optionIndex) + { + group.OptionData.RemoveAt(optionIndex); + group.DefaultSettings = group.FixSetting(group.DefaultSettings); + } + + protected override bool MoveOption(ImcModGroup group, int optionIdxFrom, int optionIdxTo) + { + if (!group.OptionData.Move(optionIdxFrom, optionIdxTo)) + return false; + + group.DefaultSettings = group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); + return true; + } +} diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 3ff1a333..0669696f 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -2,6 +2,8 @@ using Penumbra.Communication; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Groups; +using Penumbra.Mods.SubMods; using Penumbra.Services; namespace Penumbra.Mods.Manager; @@ -103,7 +105,7 @@ public class ModCacheManager : IDisposable } } - private void OnModOptionChange(ModOptionChangeType type, Mod mod, int groupIdx, int _, int _2) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int fromIdx) { switch (type) { diff --git a/Penumbra/Mods/Manager/ModGroupEditor.cs b/Penumbra/Mods/Manager/ModGroupEditor.cs new file mode 100644 index 00000000..9f41fa6f --- /dev/null +++ b/Penumbra/Mods/Manager/ModGroupEditor.cs @@ -0,0 +1,289 @@ +using System.Text.RegularExpressions; +using Dalamud.Interface.Internal.Notifications; +using OtterGui.Classes; +using OtterGui.Filesystem; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.GameData.Data; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; +using Penumbra.String.Classes; +using Penumbra.Util; +using static FFXIVClientStructs.FFXIV.Client.UI.Misc.ConfigModule; + +namespace Penumbra.Mods.Manager; + +public enum ModOptionChangeType +{ + GroupRenamed, + GroupAdded, + GroupDeleted, + GroupMoved, + GroupTypeChanged, + PriorityChanged, + OptionAdded, + OptionDeleted, + OptionMoved, + OptionFilesChanged, + OptionFilesAdded, + OptionSwapsChanged, + OptionMetaChanged, + DisplayChange, + PrepareChange, + DefaultOptionChanged, +} + +public class ModGroupEditor( + SingleModGroupEditor singleEditor, + MultiModGroupEditor multiEditor, + ImcModGroupEditor imcEditor, + CommunicatorService Communicator, + SaveService SaveService, + Configuration Config) : IService +{ + public SingleModGroupEditor SingleEditor + => singleEditor; + + public MultiModGroupEditor MultiEditor + => multiEditor; + + public ImcModGroupEditor ImcEditor + => imcEditor; + + /// Change the settings stored as default options in a mod. + public void ChangeModGroupDefaultOption(IModGroup group, Setting defaultOption) + { + if (group.DefaultSettings == defaultOption) + return; + + group.DefaultSettings = defaultOption; + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, group.Mod, group, null, null, -1); + } + + /// Rename an option group if possible. + public void RenameModGroup(IModGroup group, string newName) + { + var oldName = group.Name; + if (oldName == newName || !VerifyFileName(group.Mod, group, newName, true)) + return; + + SaveService.ImmediateDelete(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + group.Name = newName; + SaveService.ImmediateSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, group.Mod, group, null, null, -1); + } + + /// Delete a given option group. Fires an event to prepare before actually deleting. + public void DeleteModGroup(IModGroup group) + { + var mod = group.Mod; + var idx = group.GetIndex(); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, null, null, -1); + mod.Groups.RemoveAt(idx); + SaveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, null, null, null, idx); + } + + /// Move the index of a given option group. + public void MoveModGroup(IModGroup group, int groupIdxTo) + { + var mod = group.Mod; + var idxFrom = group.GetIndex(); + if (!mod.Groups.Move(idxFrom, groupIdxTo)) + return; + + SaveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, group, null, null, idxFrom); + } + + /// Change the internal priority of the given option group. + public void ChangeGroupPriority(IModGroup group, ModPriority newPriority) + { + if (group.Priority == newPriority) + return; + + group.Priority = newPriority; + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, group.Mod, group, null, null, -1); + } + + /// Change the description of the given option group. + public void ChangeGroupDescription(IModGroup group, string newDescription) + { + if (group.Description == newDescription) + return; + + group.Description = newDescription; + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, group.Mod, group, null, null, -1); + } + + /// Rename the given option. + public void RenameOption(IModOption option, string newName) + { + if (option.Name == newName) + return; + + option.Name = newName; + SaveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); + } + + /// Change the description of the given option. + public void ChangeOptionDescription(IModOption option, string newDescription) + { + if (option.Description == newDescription) + return; + + option.Description = newDescription; + SaveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); + } + + /// Set the meta manipulations for a given option. Replaces existing manipulations. + public void SetManipulations(IModDataContainer subMod, HashSet manipulations, SaveType saveType = SaveType.Queue) + { + if (subMod.Manipulations.Count == manipulations.Count + && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) + return; + + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + subMod.Manipulations.SetTo(manipulations); + SaveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + } + + /// Set the file redirections for a given option. Replaces existing redirections. + public void SetFiles(IModDataContainer subMod, IReadOnlyDictionary replacements, SaveType saveType = SaveType.Queue) + { + if (subMod.Files.SetEquals(replacements)) + return; + + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + subMod.Files.SetTo(replacements); + SaveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + } + + /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. + public void AddFiles(IModDataContainer subMod, IReadOnlyDictionary additions) + { + var oldCount = subMod.Files.Count; + subMod.Files.AddFrom(additions); + if (oldCount != subMod.Files.Count) + { + SaveService.QueueSave(new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + } + } + + /// Set the file swaps for a given option. Replaces existing swaps. + public void SetFileSwaps(IModDataContainer subMod, IReadOnlyDictionary swaps, SaveType saveType = SaveType.Queue) + { + if (subMod.FileSwaps.SetEquals(swaps)) + return; + + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + subMod.FileSwaps.SetTo(swaps); + SaveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + } + + /// Verify that a new option group name is unique in this mod. + public static bool VerifyFileName(Mod mod, IModGroup? group, string newName, bool message) + { + var path = newName.RemoveInvalidPathSymbols(); + if (path.Length != 0 + && !mod.Groups.Any(o => !ReferenceEquals(o, group) + && string.Equals(o.Name.RemoveInvalidPathSymbols(), path, StringComparison.OrdinalIgnoreCase))) + return true; + + if (message) + Penumbra.Messager.NotificationMessage( + $"Could not name option {newName} because option with same filename {path} already exists.", + NotificationType.Warning, false); + + return false; + } + + public void DeleteOption(IModOption option) + { + switch (option) + { + case SingleSubMod s: + SingleEditor.DeleteOption(s); + return; + case MultiSubMod m: + MultiEditor.DeleteOption(m); + return; + case ImcSubMod i: + ImcEditor.DeleteOption(i); + return; + } + } + + public IModOption? AddOption(IModGroup group, IModOption option) + => group switch + { + SingleModGroup s => SingleEditor.AddOption(s, option), + MultiModGroup m => MultiEditor.AddOption(m, option), + ImcModGroup i => ImcEditor.AddOption(i, option), + _ => null, + }; + + public IModOption? AddOption(IModGroup group, string newName) + => group switch + { + SingleModGroup s => SingleEditor.AddOption(s, newName), + MultiModGroup m => MultiEditor.AddOption(m, newName), + ImcModGroup i => ImcEditor.AddOption(i, newName), + _ => null, + }; + + public IModGroup? AddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) + => type switch + { + GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), + GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), + GroupType.Imc => ImcEditor.AddModGroup(mod, newName, saveType), + _ => null, + }; + + public (IModGroup?, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string name, SaveType saveType = SaveType.ImmediateSync) + => type switch + { + GroupType.Single => SingleEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), + _ => (null, -1, false), + }; + + public (IModOption?, int, bool) FindOrAddOption(IModGroup group, string name, SaveType saveType = SaveType.ImmediateSync) + => group switch + { + SingleModGroup s => SingleEditor.FindOrAddOption(s, name, saveType), + MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), + ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), + _ => (null, -1, false), + }; + + public void MoveOption(IModOption option, int toIdx) + { + switch (option) + { + case SingleSubMod s: + SingleEditor.MoveOption(s, toIdx); + return; + case MultiSubMod m: + MultiEditor.MoveOption(m, toIdx); + return; + case ImcSubMod i: + ImcEditor.MoveOption(i, toIdx); + return; + } + } +} diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index d912e292..7a266a31 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,4 +1,3 @@ -using System.Security.AccessControl; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Services; @@ -32,14 +31,14 @@ public sealed class ModManager : ModStorage, IDisposable private readonly Configuration _config; private readonly CommunicatorService _communicator; - public readonly ModCreator Creator; - public readonly ModDataEditor DataEditor; - public readonly ModOptionEditor OptionEditor; + public readonly ModCreator Creator; + public readonly ModDataEditor DataEditor; + public readonly ModGroupEditor OptionEditor; public DirectoryInfo BasePath { get; private set; } = null!; public bool Valid { get; private set; } - public ModManager(Configuration config, CommunicatorService communicator, ModDataEditor dataEditor, ModOptionEditor optionEditor, + public ModManager(Configuration config, CommunicatorService communicator, ModDataEditor dataEditor, ModGroupEditor optionEditor, ModCreator creator) { _config = config; diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index f160d5bd..c7eb7cc5 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -83,8 +83,8 @@ public static partial class ModMigration mod.Default.FileSwaps.Add(gamePath, swapPath); creator.IncorporateMetaChanges(mod.Default, mod.ModPath, true); - foreach (var (_, index) in mod.Groups.WithIndex()) - saveService.ImmediateSave(new ModSaveGroup(mod, index, creator.Config.ReplaceNonAsciiOnImport)); + foreach (var group in mod.Groups) + saveService.ImmediateSave(new ModSaveGroup(group, creator.Config.ReplaceNonAsciiOnImport)); // Delete meta files. foreach (var file in seenMetaFiles.Where(f => f.Exists)) @@ -112,7 +112,7 @@ public static partial class ModMigration } fileVersion = 1; - saveService.ImmediateSave(new ModSaveGroup(mod, -1, creator.Config.ReplaceNonAsciiOnImport)); + saveService.ImmediateSave(new ModSaveGroup(mod.ModPath, mod.Default, creator.Config.ReplaceNonAsciiOnImport)); return true; } @@ -176,7 +176,7 @@ public static partial class ModMigration private static SingleSubMod SubModFromOption(ModCreator creator, Mod mod, SingleModGroup group, OptionV0 option, HashSet seenMetaFiles) { - var subMod = new SingleSubMod(mod, group) + var subMod = new SingleSubMod(group) { Name = option.OptionName, Description = option.OptionDesc, @@ -189,7 +189,7 @@ public static partial class ModMigration private static MultiSubMod SubModFromOption(ModCreator creator, Mod mod, MultiModGroup group, OptionV0 option, ModPriority priority, HashSet seenMetaFiles) { - var subMod = new MultiSubMod(mod, group) + var subMod = new MultiSubMod(group) { Name = option.OptionName, Description = option.OptionDesc, @@ -219,7 +219,7 @@ public static partial class ModMigration [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public GroupType SelectionType = GroupType.Single; - public List Options = new(); + public List Options = []; public OptionGroupV0() { } @@ -236,12 +236,12 @@ public static partial class ModMigration var token = JToken.Load(reader); if (token.Type == JTokenType.Array) - return token.ToObject>() ?? new HashSet(); + return token.ToObject>() ?? []; var tmp = token.ToObject(); return tmp != null ? new HashSet { tmp } - : new HashSet(); + : []; } public override bool CanWrite diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/ModOptionEditor.cs index c6122ea8..7370a933 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/ModOptionEditor.cs @@ -1,384 +1,122 @@ -using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; -using OtterGui.Filesystem; -using Penumbra.Api.Enums; -using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -using Penumbra.String.Classes; -using Penumbra.Util; namespace Penumbra.Mods.Manager; -public enum ModOptionChangeType +public abstract class ModOptionEditor( + CommunicatorService communicator, + SaveService saveService, + Configuration config) + where TGroup : class, IModGroup + where TOption : class, IModOption { - GroupRenamed, - GroupAdded, - GroupDeleted, - GroupMoved, - GroupTypeChanged, - PriorityChanged, - OptionAdded, - OptionDeleted, - OptionMoved, - OptionFilesChanged, - OptionFilesAdded, - OptionSwapsChanged, - OptionMetaChanged, - DisplayChange, - PrepareChange, - DefaultOptionChanged, -} - -public class ModOptionEditor(CommunicatorService communicator, SaveService saveService, Configuration config) -{ - /// Change the type of a group given by mod and index to type, if possible. - public void ChangeModGroupType(Mod mod, int groupIdx, GroupType type) - { - var group = mod.Groups[groupIdx]; - if (group.Type == type) - return; - - mod.Groups[groupIdx] = group.Convert(type); - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, mod, groupIdx, -1, -1); - } - - /// Change the settings stored as default options in a mod. - public void ChangeModGroupDefaultOption(Mod mod, int groupIdx, Setting defaultOption) - { - var group = mod.Groups[groupIdx]; - if (group.DefaultSettings == defaultOption) - return; - - group.DefaultSettings = defaultOption; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, mod, groupIdx, -1, -1); - } - - /// Rename an option group if possible. - public void RenameModGroup(Mod mod, int groupIdx, string newName) - { - var group = mod.Groups[groupIdx]; - var oldName = group.Name; - if (oldName == newName || !VerifyFileName(mod, group, newName, true)) - return; - - saveService.ImmediateDelete(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - _ = group switch - { - SingleModGroup s => s.Name = newName, - MultiModGroup m => m.Name = newName, - _ => newName, - }; - - saveService.ImmediateSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, mod, groupIdx, -1, -1); - } + protected readonly CommunicatorService Communicator = communicator; + protected readonly SaveService SaveService = saveService; + protected readonly Configuration Config = config; /// Add a new, empty option group of the given type and name. - public void AddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) + public TGroup? AddModGroup(Mod mod, string newName, SaveType saveType = SaveType.ImmediateSync) { - if (!VerifyFileName(mod, null, newName, true)) - return; + if (!ModGroupEditor.VerifyFileName(mod, null, newName, true)) + return null; - var idx = mod.Groups.Count; - var group = ModGroup.Create(mod, type, newName); + var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; + var group = CreateGroup(mod, newName, maxPriority); mod.Groups.Add(group); - saveService.Save(saveType, new ModSaveGroup(mod, idx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, idx, -1, -1); + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, group, null, null, -1); + return group; } /// Add a new mod, empty option group of the given type and name if it does not exist already. - public (IModGroup, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) + public (TGroup, int, bool) FindOrAddModGroup(Mod mod, string newName, SaveType saveType = SaveType.ImmediateSync) { var idx = mod.Groups.IndexOf(g => g.Name == newName); if (idx >= 0) - return (mod.Groups[idx], idx, false); + { + var existingGroup = mod.Groups[idx] as TGroup + ?? throw new Exception($"Mod group with name {newName} exists, but is of the wrong type."); + return (existingGroup, idx, false); + } - AddModGroup(mod, type, newName, saveType); - if (mod.Groups[^1].Name != newName) + idx = mod.Groups.Count; + if (AddModGroup(mod, newName, saveType) is not { } group) throw new Exception($"Could not create new mod group with name {newName}."); - return (mod.Groups[^1], mod.Groups.Count - 1, true); - } - - /// Delete a given option group. Fires an event to prepare before actually deleting. - public void DeleteModGroup(Mod mod, int groupIdx) - { - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, -1, -1); - mod.Groups.RemoveAt(groupIdx); - saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, groupIdx, -1, -1); - } - - /// Move the index of a given option group. - public void MoveModGroup(Mod mod, int groupIdxFrom, int groupIdxTo) - { - if (!mod.Groups.Move(groupIdxFrom, groupIdxTo)) - return; - - saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, groupIdxFrom, -1, groupIdxTo); - } - - /// Change the description of the given option group. - public void ChangeGroupDescription(Mod mod, int groupIdx, string newDescription) - { - var group = mod.Groups[groupIdx]; - if (group.Description == newDescription) - return; - - group.Description = newDescription; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, -1, -1); - } - - /// Change the description of the given option. - public void ChangeOptionDescription(Mod mod, int groupIdx, int optionIdx, string newDescription) - { - var option = mod.Groups[groupIdx].Options[optionIdx]; - if (option.Description == newDescription) - return; - - option.Description = newDescription; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); - } - - /// Change the internal priority of the given option group. - public void ChangeGroupPriority(Mod mod, int groupIdx, ModPriority newPriority) - { - var group = mod.Groups[groupIdx]; - if (group.Priority == newPriority) - return; - - group.Priority = newPriority; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, -1, -1); - } - - /// Change the internal priority of the given option. - public void ChangeOptionPriority(Mod mod, int groupIdx, int optionIdx, ModPriority newPriority) - { - switch (mod.Groups[groupIdx]) - { - case MultiModGroup multi: - if (multi.OptionData[optionIdx].Priority == newPriority) - return; - - multi.OptionData[optionIdx].Priority = newPriority; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, mod, groupIdx, optionIdx, -1); - return; - } - } - - /// Rename the given option. - public void RenameOption(Mod mod, int groupIdx, int optionIdx, string newName) - { - var option = mod.Groups[groupIdx].Options[optionIdx]; - if (option.Name == newName) - return; - - option.Name = newName; - - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, mod, groupIdx, optionIdx, -1); + return (group, idx, true); } /// Add a new empty option of the given name for the given group. - public int AddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) + public TOption? AddOption(TGroup group, string newName, SaveType saveType = SaveType.Queue) { - var group = mod.Groups[groupIdx]; - var idx = group.AddOption(mod, newName); - if (idx < 0) - return -1; + if (group.AddOption(newName) is not TOption option) + return null; - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); - return idx; + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, group.Mod, group, option, null, -1); + return option; } /// Add a new empty option of the given name for the given group if it does not exist already. - public (IModOption, int, bool) FindOrAddOption(Mod mod, int groupIdx, string newName, SaveType saveType = SaveType.Queue) + public (TOption, int, bool) FindOrAddOption(TGroup group, string newName, SaveType saveType = SaveType.Queue) { - var group = mod.Groups[groupIdx]; - var idx = group.Options.IndexOf(o => o.Name == newName); + var idx = group.Options.IndexOf(o => o.Name == newName); if (idx >= 0) - return (group.Options[idx], idx, false); + { + var existingOption = group.Options[idx] as TOption + ?? throw new Exception($"Mod option with name {newName} exists, but is of the wrong type."); // Should never happen. + return (existingOption, idx, false); + } - idx = group.AddOption(mod, newName); - if (idx < 0) + if (AddOption(group, newName, saveType) is not { } option) throw new Exception($"Could not create new option with name {newName} in {group.Name}."); - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); - return (group.Options[idx], idx, true); + return (option, idx, true); } /// Add an existing option to a given group. - public void AddOption(Mod mod, int groupIdx, IModOption option) + public TOption? AddOption(TGroup group, IModOption option) { - var group = mod.Groups[groupIdx]; - int idx; - switch (group) - { - case MultiModGroup { OptionData.Count: >= IModGroup.MaxMultiOptions }: - Penumbra.Log.Error( - $"Could not add option {option.Name} to {group.Name} for mod {mod.Name}, " - + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); - return; - case SingleModGroup s: - { - idx = s.OptionData.Count; - var newOption = new SingleSubMod(s.Mod, s) - { - Name = option.Name, - Description = option.Description, - }; - if (option is IModDataContainer data) - SubMod.Clone(data, newOption); - s.OptionData.Add(newOption); - break; - } - case MultiModGroup m: - { - idx = m.OptionData.Count; - var newOption = new MultiSubMod(m.Mod, m) - { - Name = option.Name, - Description = option.Description, - Priority = option is MultiSubMod s ? s.Priority : ModPriority.Default, - }; - if (option is IModDataContainer data) - SubMod.Clone(data, newOption); - m.OptionData.Add(newOption); - break; - } - default: return; - } + if (CloneOption(group, option) is not { } clonedOption) + return null; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, mod, groupIdx, idx, -1); + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, group.Mod, group, clonedOption, null, -1); + return clonedOption; } /// Delete the given option from the given group. - public void DeleteOption(Mod mod, int groupIdx, int optionIdx) + public void DeleteOption(TOption option) { - var group = mod.Groups[groupIdx]; - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, optionIdx, -1); - switch (group) - { - case SingleModGroup s: - s.OptionData.RemoveAt(optionIdx); - - break; - case MultiModGroup m: - m.OptionData.RemoveAt(optionIdx); - break; - } - - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionDeleted, mod, groupIdx, optionIdx, -1); + var mod = option.Mod; + var group = option.Group; + var optionIdx = option.GetIndex(); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, option, null, -1); + RemoveOption((TGroup)group, optionIdx); + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionDeleted, mod, group, null, null, optionIdx); } /// Move an option inside the given option group. - public void MoveOption(Mod mod, int groupIdx, int optionIdxFrom, int optionIdxTo) + public void MoveOption(TOption option, int optionIdxTo) { - var group = mod.Groups[groupIdx]; - if (!group.MoveOption(optionIdxFrom, optionIdxTo)) + var idx = option.GetIndex(); + var group = (TGroup)option.Group; + if (!MoveOption(group, idx, optionIdxTo)) return; - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, mod, groupIdx, optionIdxFrom, optionIdxTo); + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, group.Mod, group, option, null, idx); } - /// Set the meta manipulations for a given option. Replaces existing manipulations. - public void OptionSetManipulations(Mod mod, int groupIdx, int dataContainerIdx, HashSet manipulations, - SaveType saveType = SaveType.Queue) - { - var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); - if (subMod.Manipulations.Count == manipulations.Count - && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) - return; - - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, dataContainerIdx, -1); - subMod.Manipulations.SetTo(manipulations); - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, mod, groupIdx, dataContainerIdx, -1); - } - - /// Set the file redirections for a given option. Replaces existing redirections. - public void OptionSetFiles(Mod mod, int groupIdx, int dataContainerIdx, IReadOnlyDictionary replacements, - SaveType saveType = SaveType.Queue) - { - var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); - if (subMod.Files.SetEquals(replacements)) - return; - - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, dataContainerIdx, -1); - subMod.Files.SetTo(replacements); - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, mod, groupIdx, dataContainerIdx, -1); - } - - /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. - public void OptionAddFiles(Mod mod, int groupIdx, int dataContainerIdx, IReadOnlyDictionary additions) - { - var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); - var oldCount = subMod.Files.Count; - subMod.Files.AddFrom(additions); - if (oldCount != subMod.Files.Count) - { - saveService.QueueSave(new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, mod, groupIdx, dataContainerIdx, -1); - } - } - - /// Set the file swaps for a given option. Replaces existing swaps. - public void OptionSetFileSwaps(Mod mod, int groupIdx, int dataContainerIdx, IReadOnlyDictionary swaps, - SaveType saveType = SaveType.Queue) - { - var subMod = GetSubMod(mod, groupIdx, dataContainerIdx); - if (subMod.FileSwaps.SetEquals(swaps)) - return; - - communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, groupIdx, dataContainerIdx, -1); - subMod.FileSwaps.SetTo(swaps); - saveService.Save(saveType, new ModSaveGroup(mod, groupIdx, config.ReplaceNonAsciiOnImport)); - communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, mod, groupIdx, dataContainerIdx, -1); - } - - - /// Verify that a new option group name is unique in this mod. - public static bool VerifyFileName(Mod mod, IModGroup? group, string newName, bool message) - { - var path = newName.RemoveInvalidPathSymbols(); - if (path.Length != 0 - && !mod.Groups.Any(o => !ReferenceEquals(o, group) - && string.Equals(o.Name.RemoveInvalidPathSymbols(), path, StringComparison.OrdinalIgnoreCase))) - return true; - - if (message) - Penumbra.Messager.NotificationMessage( - $"Could not name option {newName} because option with same filename {path} already exists.", - NotificationType.Warning, false); - - return false; - } - - /// Get the correct option for the given group and option index. - private static IModDataContainer GetSubMod(Mod mod, int groupIdx, int dataContainerIdx) - { - if (groupIdx == -1 && dataContainerIdx == 0) - return mod.Default; - - return mod.Groups[groupIdx].DataContainers[dataContainerIdx]; - } + protected abstract TGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync); + protected abstract TOption? CloneOption(TGroup group, IModOption option); + protected abstract void RemoveOption(TGroup group, int optionIndex); + protected abstract bool MoveOption(TGroup group, int optionIdxFrom, int optionIdxTo); } public static class ModOptionChangeTypeExtension diff --git a/Penumbra/Mods/Manager/MultiModGroupEditor.cs b/Penumbra/Mods/Manager/MultiModGroupEditor.cs new file mode 100644 index 00000000..e6b2bac1 --- /dev/null +++ b/Penumbra/Mods/Manager/MultiModGroupEditor.cs @@ -0,0 +1,84 @@ +using OtterGui.Classes; +using OtterGui.Filesystem; +using OtterGui.Services; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; + +namespace Penumbra.Mods.Manager; + +public sealed class MultiModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) + : ModOptionEditor(communicator, saveService, config), IService +{ + public void ChangeToSingle(MultiModGroup group) + { + var idx = group.GetIndex(); + var singleGroup = group.ConvertToSingle(); + group.Mod.Groups[idx] = singleGroup; + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, group.Mod, group, null, null, -1); + } + + /// Change the internal priority of the given option. + public void ChangeOptionPriority(MultiSubMod option, ModPriority newPriority) + { + if (option.Priority == newPriority) + return; + + option.Priority = newPriority; + SaveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, option.Mod, option.Group, option, null, -1); + } + + protected override MultiModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) + => new(mod) + { + Name = newName, + Priority = priority, + }; + + protected override MultiSubMod? CloneOption(MultiModGroup group, IModOption option) + { + if (group.OptionData.Count >= IModGroup.MaxMultiOptions) + { + Penumbra.Log.Error( + $"Could not add option {option.Name} to {group.Name} for mod {group.Mod.Name}, " + + $"since only up to {IModGroup.MaxMultiOptions} options are supported in one group."); + return null; + } + + var newOption = new MultiSubMod(group) + { + Name = option.Name, + Description = option.Description, + }; + + if (option is IModDataContainer data) + { + SubMod.Clone(data, newOption); + if (option is MultiSubMod m) + newOption.Priority = m.Priority; + else + newOption.Priority = new ModPriority(group.OptionData.Max(o => o.Priority.Value) + 1); + } + + group.OptionData.Add(newOption); + return newOption; + } + + protected override void RemoveOption(MultiModGroup group, int optionIndex) + { + group.OptionData.RemoveAt(optionIndex); + group.DefaultSettings = group.DefaultSettings.RemoveBit(optionIndex); + } + + protected override bool MoveOption(MultiModGroup group, int optionIdxFrom, int optionIdxTo) + { + if (!group.OptionData.Move(optionIdxFrom, optionIdxTo)) + return false; + + group.DefaultSettings = group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); + return true; + } +} diff --git a/Penumbra/Mods/Manager/SingleModGroupEditor.cs b/Penumbra/Mods/Manager/SingleModGroupEditor.cs new file mode 100644 index 00000000..4999ff60 --- /dev/null +++ b/Penumbra/Mods/Manager/SingleModGroupEditor.cs @@ -0,0 +1,57 @@ +using OtterGui.Classes; +using OtterGui.Filesystem; +using OtterGui.Services; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; + +namespace Penumbra.Mods.Manager; + +public sealed class SingleModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) + : ModOptionEditor(communicator, saveService, config), IService +{ + public void ChangeToMulti(SingleModGroup group) + { + var idx = group.GetIndex(); + var multiGroup = group.ConvertToMulti(); + group.Mod.Groups[idx] = multiGroup; + SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, group.Mod, multiGroup, null, null, -1); + } + + protected override SingleModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) + => new(mod) + { + Name = newName, + Priority = priority, + }; + + protected override SingleSubMod CloneOption(SingleModGroup group, IModOption option) + { + var newOption = new SingleSubMod(group) + { + Name = option.Name, + Description = option.Description, + }; + if (option is IModDataContainer data) + SubMod.Clone(data, newOption); + group.OptionData.Add(newOption); + return newOption; + } + + protected override void RemoveOption(SingleModGroup group, int optionIndex) + { + group.OptionData.RemoveAt(optionIndex); + group.DefaultSettings = group.DefaultSettings.RemoveSingle(optionIndex); + } + + protected override bool MoveOption(SingleModGroup group, int optionIdxFrom, int optionIdxTo) + { + if (!group.OptionData.Move(optionIdxFrom, optionIdxTo)) + return false; + + group.DefaultSettings = group.DefaultSettings.MoveSingle(optionIdxFrom, optionIdxTo); + return true; + } +} diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 40f943c8..47261c6d 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -90,7 +90,7 @@ public partial class ModCreator( var changes = false; foreach (var file in _saveService.FileNames.GetOptionGroupFiles(mod)) { - var group = LoadModGroup(mod, file, mod.Groups.Count); + var group = LoadModGroup(mod, file); if (group != null && mod.Groups.All(g => g.Name != group.Name)) { changes = changes @@ -244,12 +244,12 @@ public partial class ModCreator( { case GroupType.Multi: { - var group = MultiModGroup.CreateForSaving(name); + var group = MultiModGroup.WithoutMod(name); group.Description = desc; group.Priority = priority; group.DefaultSettings = defaultSettings; - group.OptionData.AddRange(subMods.Select(s => s.Clone(null!, group))); - _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); + group.OptionData.AddRange(subMods.Select(s => s.Clone(group))); + _saveService.ImmediateSaveSync(ModSaveGroup.WithoutMod(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } case GroupType.Single: @@ -258,8 +258,8 @@ public partial class ModCreator( group.Description = desc; group.Priority = priority; group.DefaultSettings = defaultSettings; - group.OptionData.AddRange(subMods.Select(s => s.ConvertToSingle(null!, group))); - _saveService.ImmediateSaveSync(new ModSaveGroup(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); + group.OptionData.AddRange(subMods.Select(s => s.ConvertToSingle(group))); + _saveService.ImmediateSaveSync(ModSaveGroup.WithoutMod(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } } @@ -272,7 +272,7 @@ public partial class ModCreator( .Select(f => (Utf8GamePath.FromFile(f, optionFolder, out var gamePath, true), gamePath, new FullPath(f))) .Where(t => t.Item1); - var mod = MultiSubMod.CreateForSaving(option.Name, option.Description, priority); + var mod = MultiSubMod.WithoutGroup(option.Name, option.Description, priority); foreach (var (_, gamePath, file) in list) mod.Files.TryAdd(gamePath, file); @@ -295,7 +295,7 @@ public partial class ModCreator( } IncorporateMetaChanges(mod.Default, directory, true); - _saveService.ImmediateSaveSync(new ModSaveGroup(mod, -1, Config.ReplaceNonAsciiOnImport)); + _saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); } /// Return the name of a new valid directory based on the base directory and the given name. @@ -422,7 +422,7 @@ public partial class ModCreator( /// Load an option group for a specific mod by its file and index. - private static IModGroup? LoadModGroup(Mod mod, FileInfo file, int groupIdx) + private static IModGroup? LoadModGroup(Mod mod, FileInfo file) { if (!File.Exists(file.FullName)) return null; @@ -442,7 +442,7 @@ public partial class ModCreator( } return null; - } + } internal static void DeleteDeleteList(IEnumerable deleteList, bool delete) { diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index db9e0521..39ee1860 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -4,6 +4,7 @@ using Penumbra.Api.Enums; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; +using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Settings; @@ -45,63 +46,64 @@ public class ModSettings } // Automatically react to changes in a mods available options. - public bool HandleChanges(ModOptionChangeType type, Mod mod, int groupIdx, int optionIdx, int movedToIdx) + public bool HandleChanges(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, int fromIdx) { switch (type) { case ModOptionChangeType.GroupRenamed: return true; case ModOptionChangeType.GroupAdded: // Add new empty setting for new mod. - Settings.Insert(groupIdx, mod.Groups[groupIdx].DefaultSettings); + Settings.Insert(group!.GetIndex(), group.DefaultSettings); return true; case ModOptionChangeType.GroupDeleted: // Remove setting for deleted mod. - Settings.RemoveAt(groupIdx); + Settings.RemoveAt(fromIdx); return true; case ModOptionChangeType.GroupTypeChanged: { // Fix settings for a changed group type. // Single -> Multi: set single as enabled, rest as disabled // Multi -> Single: set the first enabled option or 0. - var group = mod.Groups[groupIdx]; - var config = Settings[groupIdx]; - Settings[groupIdx] = group.Type switch + var idx = group!.GetIndex(); + var config = Settings[idx]; + Settings[idx] = group.Type switch { GroupType.Single => config.TurnMulti(group.Options.Count), GroupType.Multi => Setting.Multi((int)config.Value), _ => config, }; - return config != Settings[groupIdx]; + return config != Settings[idx]; } case ModOptionChangeType.OptionDeleted: { // Single -> select the previous option if any. // Multi -> excise the corresponding bit. - var group = mod.Groups[groupIdx]; - var config = Settings[groupIdx]; - Settings[groupIdx] = group.Type switch + var groupIdx = group!.GetIndex(); + var config = Settings[groupIdx]; + Settings[groupIdx] = group!.Type switch { - GroupType.Single => config.AsIndex >= optionIdx - ? config.AsIndex > 1 ? Setting.Single(config.AsIndex - 1) : Setting.Zero - : config, - GroupType.Multi => config.RemoveBit(optionIdx), - _ => config, + GroupType.Single => config.RemoveSingle(fromIdx), + GroupType.Multi => config.RemoveBit(fromIdx), + GroupType.Imc => config.RemoveBit(fromIdx), + _ => config, }; return config != Settings[groupIdx]; } case ModOptionChangeType.GroupMoved: // Move the group the same way. - return Settings.Move(groupIdx, movedToIdx); + return Settings.Move(fromIdx, group!.GetIndex()); case ModOptionChangeType.OptionMoved: { // Single -> select the moved option if it was currently selected // Multi -> move the corresponding bit - var group = mod.Groups[groupIdx]; - var config = Settings[groupIdx]; - Settings[groupIdx] = group.Type switch + var groupIdx = group!.GetIndex(); + var toIdx = option!.GetIndex(); + var config = Settings[groupIdx]; + Settings[groupIdx] = group!.Type switch { - GroupType.Single => config.AsIndex == optionIdx ? Setting.Single(movedToIdx) : config, - GroupType.Multi => config.MoveBit(optionIdx, movedToIdx), + GroupType.Single => config.MoveSingle(fromIdx, toIdx), + GroupType.Multi => config.MoveBit(fromIdx, toIdx), + GroupType.Imc => config.MoveBit(fromIdx, toIdx), _ => config, }; return config != Settings[groupIdx]; diff --git a/Penumbra/Mods/Settings/Setting.cs b/Penumbra/Mods/Settings/Setting.cs index 231529b8..059cbf51 100644 --- a/Penumbra/Mods/Settings/Setting.cs +++ b/Penumbra/Mods/Settings/Setting.cs @@ -41,6 +41,34 @@ public readonly record struct Setting(ulong Value) public Setting TurnMulti(int count) => new(Math.Max((ulong)Math.Min(count - 1, BitOperations.TrailingZeroCount(Value)), 0)); + public Setting RemoveSingle(int singleIdx) + { + var settingIndex = AsIndex; + if (settingIndex >= singleIdx) + return settingIndex > 1 ? Single(settingIndex - 1) : Zero; + + return this; + } + + public Setting MoveSingle(int singleIdxFrom, int singleIdxTo) + { + var currentIndex = AsIndex; + if (currentIndex == singleIdxFrom) + return Single(singleIdxTo); + + if (singleIdxFrom < singleIdxTo) + { + if (currentIndex > singleIdxFrom && currentIndex <= singleIdxTo) + return Single(currentIndex - 1); + } + else if (currentIndex < singleIdxFrom && currentIndex >= singleIdxTo) + { + return Single(currentIndex + 1); + } + + return this; + } + public ModPriority AsPriority => new((int)(Value & 0xFFFFFFFF)); diff --git a/Penumbra/Mods/SubMods/IModOption.cs b/Penumbra/Mods/SubMods/IModOption.cs index 83d632a0..ecfcf91a 100644 --- a/Penumbra/Mods/SubMods/IModOption.cs +++ b/Penumbra/Mods/SubMods/IModOption.cs @@ -1,10 +1,15 @@ +using Penumbra.Mods.Groups; + namespace Penumbra.Mods.SubMods; public interface IModOption { + public Mod Mod { get; } + public IModGroup Group { get; } + public string Name { get; set; } public string FullName { get; } public string Description { get; set; } - public (int GroupIndex, int OptionIndex) GetOptionIndices(); + public int GetIndex(); } diff --git a/Penumbra/Mods/SubMods/ImcSubMod.cs b/Penumbra/Mods/SubMods/ImcSubMod.cs new file mode 100644 index 00000000..167c8a6c --- /dev/null +++ b/Penumbra/Mods/SubMods/ImcSubMod.cs @@ -0,0 +1,32 @@ +using Penumbra.Mods.Groups; + +namespace Penumbra.Mods.SubMods; + +public class ImcSubMod(ImcModGroup group) : IModOption +{ + public readonly ImcModGroup Group = group; + + public Mod Mod + => Group.Mod; + + public byte AttributeIndex; + + public ushort Attribute + => (ushort)(1 << AttributeIndex); + + Mod IModOption.Mod + => Mod; + + IModGroup IModOption.Group + => Group; + + public string Name { get; set; } = "Part"; + + public string FullName + => $"{Group.Name}: {Name}"; + + public string Description { get; set; } = string.Empty; + + public int GetIndex() + => SubMod.GetIndex(this); +} diff --git a/Penumbra/Mods/SubMods/MultiSubMod.cs b/Penumbra/Mods/SubMods/MultiSubMod.cs index 3bcaffab..c01dcce9 100644 --- a/Penumbra/Mods/SubMods/MultiSubMod.cs +++ b/Penumbra/Mods/SubMods/MultiSubMod.cs @@ -4,21 +4,21 @@ using Penumbra.Mods.Settings; namespace Penumbra.Mods.SubMods; -public class MultiSubMod(Mod mod, MultiModGroup group) : OptionSubMod(mod, group) +public class MultiSubMod(MultiModGroup group) : OptionSubMod(group) { public ModPriority Priority { get; set; } = ModPriority.Default; - public MultiSubMod(Mod mod, MultiModGroup group, JToken json) - : this(mod, group) + public MultiSubMod(MultiModGroup group, JToken json) + : this(group) { SubMod.LoadOptionData(json, this); - SubMod.LoadDataContainer(json, this, mod.ModPath); + SubMod.LoadDataContainer(json, this, group.Mod.ModPath); Priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; } - public MultiSubMod Clone(Mod mod, MultiModGroup group) + public MultiSubMod Clone(MultiModGroup group) { - var ret = new MultiSubMod(mod, group) + var ret = new MultiSubMod(group) { Name = Name, Description = Description, @@ -29,9 +29,9 @@ public class MultiSubMod(Mod mod, MultiModGroup group) : OptionSubMod new(null!, null!) + public static MultiSubMod WithoutGroup(string name, string description, ModPriority priority) + => new(null!) { Name = name, Description = description, diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs index fbf03243..02d86af2 100644 --- a/Penumbra/Mods/SubMods/OptionSubMod.cs +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -1,25 +1,26 @@ -using OtterGui; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Editor; -using Penumbra.Mods.Groups; -using Penumbra.String.Classes; - +using OtterGui; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.String.Classes; + namespace Penumbra.Mods.SubMods; -public interface IModDataOption : IModDataContainer, IModOption; - -public abstract class OptionSubMod(Mod mod, T group) : IModDataOption - where T : IModGroup +public abstract class OptionSubMod(IModGroup group) : IModOption, IModDataContainer { - internal readonly Mod Mod = mod; - internal readonly IModGroup Group = group; + protected readonly IModGroup Group = group; - public string Name { get; set; } = "Option"; + public Mod Mod + => Group.Mod; + + public string Name { get; set; } = "Option"; + public string Description { get; set; } = string.Empty; public string FullName - => $"{Group!.Name}: {Name}"; + => $"{Group.Name}: {Name}"; - public string Description { get; set; } = string.Empty; + Mod IModOption.Mod + => Mod; IMod IModDataContainer.Mod => Mod; @@ -27,6 +28,9 @@ public abstract class OptionSubMod(Mod mod, T group) : IModDataOption IModGroup IModDataContainer.Group => Group; + IModGroup IModOption.Group + => Group; + public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; public HashSet Manipulations { get; set; } = []; @@ -43,8 +47,8 @@ public abstract class OptionSubMod(Mod mod, T group) : IModDataOption public (int GroupIndex, int DataIndex) GetDataIndices() => (Group.GetIndex(), GetDataIndex()); - public (int GroupIndex, int OptionIndex) GetOptionIndices() - => (Group.GetIndex(), GetDataIndex()); + public int GetIndex() + => SubMod.GetIndex(this); private int GetDataIndex() { @@ -54,4 +58,11 @@ public abstract class OptionSubMod(Mod mod, T group) : IModDataOption return dataIndex; } -} +} + +public abstract class OptionSubMod(T group) : OptionSubMod(group) + where T : IModGroup +{ + public new T Group + => (T)base.Group; +} diff --git a/Penumbra/Mods/SubMods/SingleSubMod.cs b/Penumbra/Mods/SubMods/SingleSubMod.cs index 98c56151..675f37bc 100644 --- a/Penumbra/Mods/SubMods/SingleSubMod.cs +++ b/Penumbra/Mods/SubMods/SingleSubMod.cs @@ -4,18 +4,18 @@ using Penumbra.Mods.Settings; namespace Penumbra.Mods.SubMods; -public class SingleSubMod(Mod mod, SingleModGroup singleGroup) : OptionSubMod(mod, singleGroup) +public class SingleSubMod(SingleModGroup singleGroup) : OptionSubMod(singleGroup) { - public SingleSubMod(Mod mod, SingleModGroup singleGroup, JToken json) - : this(mod, singleGroup) + public SingleSubMod(SingleModGroup singleGroup, JToken json) + : this(singleGroup) { SubMod.LoadOptionData(json, this); - SubMod.LoadDataContainer(json, this, mod.ModPath); + SubMod.LoadDataContainer(json, this, singleGroup.Mod.ModPath); } - public SingleSubMod Clone(Mod mod, SingleModGroup group) + public SingleSubMod Clone(SingleModGroup group) { - var ret = new SingleSubMod(mod, group) + var ret = new SingleSubMod(group) { Name = Name, Description = Description, @@ -25,9 +25,9 @@ public class SingleSubMod(Mod mod, SingleModGroup singleGroup) : OptionSubMod group switch - { - SingleModGroup single => new SingleSubMod(group.Mod, single) - { - Name = name, - Description = description, - }, - MultiModGroup multi => new MultiSubMod(group.Mod, multi) - { - Name = name, - Description = description, - }, - _ => throw new ArgumentOutOfRangeException(nameof(group)), - }; + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] + public static int GetIndex(IModOption option) + { + var dataIndex = option.Group.Options.IndexOf(option); + if (dataIndex < 0) + throw new Exception($"Group {option.Group.Name} from option {option.Name} does not contain this option."); + + return dataIndex; + } /// Add all unique meta manipulations, file redirections and then file swaps from a ModDataContainer to the given sets. Skip any keys that are already contained. + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void AddContainerTo(IModDataContainer container, Dictionary redirections, HashSet manipulations) { @@ -37,6 +32,7 @@ public static class SubMod } /// Replace all data of with the data of . + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void Clone(IModDataContainer from, IModDataContainer to) { to.Files = new Dictionary(from.Files); @@ -45,6 +41,7 @@ public static class SubMod } /// Load all file redirections, file swaps and meta manipulations from a JToken of that option into a data container. + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void LoadDataContainer(JToken json, IModDataContainer data, DirectoryInfo basePath) { data.Files.Clear(); @@ -75,6 +72,7 @@ public static class SubMod } /// Load the relevant data for a selectable option from a JToken of that option. + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void LoadOptionData(JToken json, IModOption option) { option.Name = json[nameof(option.Name)]?.ToObject() ?? string.Empty; @@ -82,6 +80,7 @@ public static class SubMod } /// Write file redirections, file swaps and meta manipulations from a data container on a JsonWriter. + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void WriteModContainer(JsonWriter j, JsonSerializer serializer, IModDataContainer data, DirectoryInfo basePath) { j.WritePropertyName(nameof(data.Files)); @@ -111,6 +110,7 @@ public static class SubMod } /// Write the data for a selectable mod option on a JsonWriter. + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void WriteModOption(JsonWriter j, IModOption option) { j.WritePropertyName(nameof(option.Name)); diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 0ec1fd44..2d595ec1 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -23,6 +23,12 @@ PROFILING; + + + + + + PreserveNewest @@ -93,10 +99,6 @@ - - - - diff --git a/Penumbra/Services/SaveService.cs b/Penumbra/Services/SaveService.cs index 8d3cb641..eff3295d 100644 --- a/Penumbra/Services/SaveService.cs +++ b/Penumbra/Services/SaveService.cs @@ -34,8 +34,11 @@ public sealed class SaveService(Logger log, FrameworkManager framework, Filename } } - for (var i = 0; i < mod.Groups.Count - 1; ++i) - ImmediateSave(new ModSaveGroup(mod, i, onlyAscii)); - ImmediateSaveSync(new ModSaveGroup(mod, mod.Groups.Count - 1, onlyAscii)); + if (mod.Groups.Count > 0) + { + foreach (var group in mod.Groups.SkipLast(1)) + ImmediateSave(new ModSaveGroup(group, onlyAscii)); + ImmediateSaveSync(new ModSaveGroup(mod.Groups[^1], onlyAscii)); + } } } diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index e758aa35..5fa1a848 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -121,7 +121,6 @@ public static class StaticServiceManager private static ServiceManager AddMods(this ServiceManager services) => services.AddSingleton() .AddSingleton() - .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 77bdb161..cd55beb0 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -17,6 +17,7 @@ using Penumbra.Mods.Groups; using Penumbra.Mods.ItemSwap; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.UI.Classes; @@ -264,9 +265,10 @@ public class ItemSwapTab : IDisposable, ITab return; _modManager.AddMod(newDir); - if (!_swapData.WriteMod(_modManager, _modManager[^1], + var mod = _modManager[^1]; + if (!_swapData.WriteMod(_modManager, mod, mod.Default, _useFileSwaps ? ItemSwapContainer.WriteType.UseSwaps : ItemSwapContainer.WriteType.NoSwaps)) - _modManager.DeleteMod(_modManager[^1]); + _modManager.DeleteMod(mod); } private void CreateOption() @@ -276,7 +278,7 @@ public class ItemSwapTab : IDisposable, ITab var groupCreated = false; var dirCreated = false; - var optionCreated = -1; + IModOption? createdOption = null; DirectoryInfo? optionFolderName = null; try { @@ -290,22 +292,22 @@ public class ItemSwapTab : IDisposable, ITab { if (_selectedGroup == null) { - _modManager.OptionEditor.AddModGroup(_mod, GroupType.Multi, _newGroupName); - _selectedGroup = _mod.Groups.Last(); + if (_modManager.OptionEditor.AddModGroup(_mod, GroupType.Multi, _newGroupName) is not { } group) + throw new Exception($"Failure creating option group."); + + _selectedGroup = group; groupCreated = true; } - var optionIdx = _modManager.OptionEditor.AddOption(_mod, _mod.Groups.IndexOf(_selectedGroup), _newOptionName); - if (optionIdx < 0) + if (_modManager.OptionEditor.AddOption(_selectedGroup, _newOptionName) is not { } option) throw new Exception($"Failure creating mod option."); - optionCreated = optionIdx; + createdOption = option; optionFolderName = Directory.CreateDirectory(optionFolderName.FullName); dirCreated = true; - if (!_swapData.WriteMod(_modManager, _mod, - _useFileSwaps ? ItemSwapContainer.WriteType.UseSwaps : ItemSwapContainer.WriteType.NoSwaps, - optionFolderName, - _mod.Groups.IndexOf(_selectedGroup), optionIdx)) + // #TODO ModOption <> DataContainer + if (!_swapData.WriteMod(_modManager, _mod, (IModDataContainer)option, + _useFileSwaps ? ItemSwapContainer.WriteType.UseSwaps : ItemSwapContainer.WriteType.NoSwaps, optionFolderName)) throw new Exception("Failure writing files for mod swap."); } } @@ -314,12 +316,12 @@ public class ItemSwapTab : IDisposable, ITab Penumbra.Messager.NotificationMessage(e, "Could not create new Swap Option.", NotificationType.Error, false); try { - if (optionCreated >= 0 && _selectedGroup != null) - _modManager.OptionEditor.DeleteOption(_mod, _mod.Groups.IndexOf(_selectedGroup), optionCreated); + if (createdOption != null) + _modManager.OptionEditor.DeleteOption(createdOption); if (groupCreated) { - _modManager.OptionEditor.DeleteModGroup(_mod, _mod.Groups.IndexOf(_selectedGroup!)); + _modManager.OptionEditor.DeleteModGroup(_selectedGroup!); _selectedGroup = null; } @@ -717,7 +719,8 @@ public class ItemSwapTab : IDisposable, ITab _dirty = true; } - private void OnModOptionChange(ModOptionChangeType type, Mod mod, int a, int b, int c) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, + int fromIdx) { if (type is ModOptionChangeType.PrepareChange or ModOptionChangeType.GroupAdded or ModOptionChangeType.OptionAdded || mod != _mod) return; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 92a9dd66..743310ea 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -27,7 +27,7 @@ public partial class ModEditWindow private const string GenderTooltip = "Gender"; private const string ObjectTypeTooltip = "Object Type"; private const string SecondaryIdTooltip = "Secondary ID"; - private const string PrimaryIDTooltip = "Primary ID"; + private const string PrimaryIdTooltipShort = "Primary ID"; private const string VariantIdTooltip = "Variant ID"; private const string EstTypeTooltip = "EST Type"; private const string RacialTribeTooltip = "Racial Tribe"; @@ -45,7 +45,7 @@ public partial class ModEditWindow var tt = setsEqual ? "No changes staged." : "Apply the currently staged changes to the option."; ImGui.NewLine(); if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, setsEqual)) - _editor.MetaEditor.Apply(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx); + _editor.MetaEditor.Apply(_editor.Option!); ImGui.SameLine(); tt = setsEqual ? "No changes staged." : "Revert all currently staged changes."; @@ -477,7 +477,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); ImGui.TextUnformatted(meta.PrimaryId.ToString()); - ImGuiUtil.HoverTooltip(PrimaryIDTooltip); + ImGuiUtil.HoverTooltip(PrimaryIdTooltipShort); ImGui.TableNextColumn(); ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index dbb88fb7..6b48a048 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -455,7 +455,7 @@ public partial class ModEditWindow : Window, IDisposable var tt = setsEqual ? "No changes staged." : "Apply the currently staged changes to the option."; ImGui.NewLine(); if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, setsEqual)) - _editor.SwapEditor.Apply(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx); + _editor.SwapEditor.Apply(_editor.Option!); ImGui.SameLine(); tt = setsEqual ? "No changes staged." : "Revert all currently staged changes."; @@ -627,7 +627,7 @@ public partial class ModEditWindow : Window, IDisposable public void Dispose() { _communicator.ModPathChanged.Unsubscribe(OnModPathChange); - _editor?.Dispose(); + _editor.Dispose(); _materialTab.Dispose(); _modelTab.Dispose(); _shaderPackageTab.Dispose(); diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index afbef45d..fcd76a51 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -15,6 +15,7 @@ using Penumbra.Services; using Penumbra.UI.AdvancedWindow; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; namespace Penumbra.UI.ModsTab; @@ -248,13 +249,13 @@ public class ModPanelEditTab( ImGui.SameLine(); - var nameValid = ModOptionEditor.VerifyFileName(mod, null, _newGroupName, false); + var nameValid = ModGroupEditor.VerifyFileName(mod, null, _newGroupName, false); tt = nameValid ? "Add new option group to the mod." : "Can not add a group of this name."; if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, tt, !nameValid, true)) return; - modManager.OptionEditor.AddModGroup(mod, GroupType.Single, _newGroupName); + modManager.OptionEditor.SingleEditor.AddModGroup(mod, _newGroupName); Reset(); } } @@ -364,9 +365,9 @@ public class ModPanelEditTab( break; case >= 0: if (_newDescriptionOptionIdx < 0) - modManager.OptionEditor.ChangeGroupDescription(_mod, _newDescriptionIdx, _newDescription); + modManager.OptionEditor.ChangeGroupDescription(_mod.Groups[_newDescriptionIdx], _newDescription); else - modManager.OptionEditor.ChangeOptionDescription(_mod, _newDescriptionIdx, _newDescriptionOptionIdx, + modManager.OptionEditor.ChangeOptionDescription(_mod.Groups[_newDescriptionIdx].Options[_newDescriptionOptionIdx], _newDescription); break; @@ -396,18 +397,18 @@ public class ModPanelEditTab( .Push(ImGuiStyleVar.ItemSpacing, _itemSpacing); if (Input.Text("##Name", groupIdx, Input.None, group.Name, out var newGroupName, 256, UiHelpers.InputTextWidth.X)) - _modManager.OptionEditor.RenameModGroup(_mod, groupIdx, newGroupName); + _modManager.OptionEditor.RenameModGroup(group, newGroupName); ImGuiUtil.HoverTooltip("Group Name"); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, "Delete this option group.\nHold Control while clicking to delete.", !ImGui.GetIO().KeyCtrl, true)) - _delayedActions.Enqueue(() => _modManager.OptionEditor.DeleteModGroup(_mod, groupIdx)); + _delayedActions.Enqueue(() => _modManager.OptionEditor.DeleteModGroup(group)); ImGui.SameLine(); if (Input.Priority("##Priority", groupIdx, Input.None, group.Priority, out var priority, 50 * UiHelpers.Scale)) - _modManager.OptionEditor.ChangeGroupPriority(_mod, groupIdx, priority); + _modManager.OptionEditor.ChangeGroupPriority(group, priority); ImGuiUtil.HoverTooltip("Group Priority"); @@ -417,7 +418,7 @@ public class ModPanelEditTab( var tt = groupIdx == 0 ? "Can not move this group further upwards." : $"Move this group up to group {groupIdx}."; if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowUp.ToIconString(), UiHelpers.IconButtonSize, tt, groupIdx == 0, true)) - _delayedActions.Enqueue(() => _modManager.OptionEditor.MoveModGroup(_mod, groupIdx, groupIdx - 1)); + _delayedActions.Enqueue(() => _modManager.OptionEditor.MoveModGroup(group, groupIdx - 1)); ImGui.SameLine(); tt = groupIdx == _mod.Groups.Count - 1 @@ -425,7 +426,7 @@ public class ModPanelEditTab( : $"Move this group down to group {groupIdx + 2}."; if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowDown.ToIconString(), UiHelpers.IconButtonSize, tt, groupIdx == _mod.Groups.Count - 1, true)) - _delayedActions.Enqueue(() => _modManager.OptionEditor.MoveModGroup(_mod, groupIdx, groupIdx + 1)); + _delayedActions.Enqueue(() => _modManager.OptionEditor.MoveModGroup(group, groupIdx + 1)); ImGui.SameLine(); @@ -452,17 +453,17 @@ public class ModPanelEditTab( { private const string DragDropLabel = "##DragOption"; - private static int _newOptionNameIdx = -1; - private static string _newOptionName = string.Empty; - private static int _dragDropGroupIdx = -1; - private static int _dragDropOptionIdx = -1; + private static int _newOptionNameIdx = -1; + private static string _newOptionName = string.Empty; + private static IModGroup? _dragDropGroup; + private static IModOption? _dragDropOption; public static void Reset() { - _newOptionNameIdx = -1; - _newOptionName = string.Empty; - _dragDropGroupIdx = -1; - _dragDropOptionIdx = -1; + _newOptionNameIdx = -1; + _newOptionName = string.Empty; + _dragDropGroup = null; + _dragDropOption = null; } public static void Draw(ModPanelEditTab panel, int groupIdx) @@ -482,7 +483,7 @@ public class ModPanelEditTab( switch (panel._mod.Groups[groupIdx]) { - case SingleModGroup single: + case SingleModGroup single: for (var optionIdx = 0; optionIdx < single.OptionData.Count; ++optionIdx) EditOption(panel, single, groupIdx, optionIdx); break; @@ -491,6 +492,7 @@ public class ModPanelEditTab( EditOption(panel, multi, groupIdx, optionIdx); break; } + DrawNewOption(panel, groupIdx, UiHelpers.IconButtonSize); } @@ -502,8 +504,8 @@ public class ModPanelEditTab( ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); ImGui.Selectable($"Option #{optionIdx + 1}"); - Source(group, groupIdx, optionIdx); - Target(panel, group, groupIdx, optionIdx); + Source(option); + Target(panel, group, optionIdx); ImGui.TableNextColumn(); @@ -511,7 +513,7 @@ public class ModPanelEditTab( if (group.Type == GroupType.Single) { if (ImGui.RadioButton("##default", group.DefaultSettings.AsIndex == optionIdx)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, Setting.Single(optionIdx)); + panel._modManager.OptionEditor.ChangeModGroupDefaultOption(group, Setting.Single(optionIdx)); ImGuiUtil.HoverTooltip($"Set {option.Name} as the default choice for this group."); } @@ -519,15 +521,14 @@ public class ModPanelEditTab( { var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); if (ImGui.Checkbox("##default", ref isDefaultOption)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(panel._mod, groupIdx, - group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); + panel._modManager.OptionEditor.ChangeModGroupDefaultOption(group, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); ImGuiUtil.HoverTooltip($"{(isDefaultOption ? "Disable" : "Enable")} {option.Name} per default in this group."); } ImGui.TableNextColumn(); if (Input.Text("##Name", groupIdx, optionIdx, option.Name, out var newOptionName, 256, -1)) - panel._modManager.OptionEditor.RenameOption(panel._mod, groupIdx, optionIdx, newOptionName); + panel._modManager.OptionEditor.RenameOption(option, newOptionName); ImGui.TableNextColumn(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Edit.ToIconString(), UiHelpers.IconButtonSize, "Edit option description.", @@ -537,15 +538,15 @@ public class ModPanelEditTab( ImGui.TableNextColumn(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, "Delete this option.\nHold Control while clicking to delete.", !ImGui.GetIO().KeyCtrl, true)) - panel._delayedActions.Enqueue(() => panel._modManager.OptionEditor.DeleteOption(panel._mod, groupIdx, optionIdx)); + panel._delayedActions.Enqueue(() => panel._modManager.OptionEditor.DeleteOption(option)); ImGui.TableNextColumn(); - if (group is not MultiModGroup multi) + if (option is not MultiSubMod multi) return; - if (Input.Priority("##Priority", groupIdx, optionIdx, multi.OptionData[optionIdx].Priority, out var priority, + if (Input.Priority("##Priority", groupIdx, optionIdx, multi.Priority, out var priority, 50 * UiHelpers.Scale)) - panel._modManager.OptionEditor.ChangeOptionPriority(panel._mod, groupIdx, optionIdx, priority); + panel._modManager.OptionEditor.MultiEditor.ChangeOptionPriority(multi, priority); ImGuiUtil.HoverTooltip("Option priority."); } @@ -564,7 +565,7 @@ public class ModPanelEditTab( ImGui.TableNextColumn(); ImGui.AlignTextToFramePadding(); ImGui.Selectable($"Option #{count + 1}"); - Target(panel, group, groupIdx, count); + Target(panel, group, count); ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); @@ -585,14 +586,14 @@ public class ModPanelEditTab( tt, !(canAddGroup && validName), true)) return; - panel._modManager.OptionEditor.AddOption(mod, groupIdx, _newOptionName); + panel._modManager.OptionEditor.AddOption(group, _newOptionName); _newOptionName = string.Empty; } // Handle drag and drop to move options inside a group or into another group. - private static void Source(IModGroup group, int groupIdx, int optionIdx) + private static void Source(IModOption option) { - if (group is not ITexToolsGroup) + if (option.Group is not ITexToolsGroup) return; using var source = ImRaii.DragDropSource(); @@ -601,14 +602,14 @@ public class ModPanelEditTab( if (ImGui.SetDragDropPayload(DragDropLabel, IntPtr.Zero, 0)) { - _dragDropGroupIdx = groupIdx; - _dragDropOptionIdx = optionIdx; + _dragDropGroup = option.Group; + _dragDropOption = option; } - ImGui.TextUnformatted($"Dragging option {group.Options[optionIdx].Name} from group {group.Name}..."); + ImGui.TextUnformatted($"Dragging option {option.Name} from group {option.Group.Name}..."); } - private static void Target(ModPanelEditTab panel, IModGroup group, int groupIdx, int optionIdx) + private static void Target(ModPanelEditTab panel, IModGroup group, int optionIdx) { if (group is not ITexToolsGroup) return; @@ -617,39 +618,53 @@ public class ModPanelEditTab( if (!target.Success || !ImGuiUtil.IsDropping(DragDropLabel)) return; - if (_dragDropGroupIdx >= 0 && _dragDropOptionIdx >= 0) + if (_dragDropGroup != null && _dragDropOption != null) { - if (_dragDropGroupIdx == groupIdx) + if (_dragDropGroup == group) { - var sourceOption = _dragDropOptionIdx; + var sourceOption = _dragDropOption; panel._delayedActions.Enqueue( - () => panel._modManager.OptionEditor.MoveOption(panel._mod, groupIdx, sourceOption, optionIdx)); + () => panel._modManager.OptionEditor.MoveOption(sourceOption, optionIdx)); } else { // Move from one group to another by deleting, then adding, then moving the option. - var sourceGroupIdx = _dragDropGroupIdx; - var sourceOption = _dragDropOptionIdx; - var sourceGroup = panel._mod.Groups[sourceGroupIdx]; - var currentCount = group.DataContainers.Count; - var option = ((ITexToolsGroup) sourceGroup).OptionData[_dragDropOptionIdx]; + var sourceOption = _dragDropOption; panel._delayedActions.Enqueue(() => { - panel._modManager.OptionEditor.DeleteOption(panel._mod, sourceGroupIdx, sourceOption); - panel._modManager.OptionEditor.AddOption(panel._mod, groupIdx, option); - panel._modManager.OptionEditor.MoveOption(panel._mod, groupIdx, currentCount, optionIdx); + panel._modManager.OptionEditor.DeleteOption(sourceOption); + if (panel._modManager.OptionEditor.AddOption(group, sourceOption) is { } newOption) + panel._modManager.OptionEditor.MoveOption(newOption, optionIdx); }); } } - _dragDropGroupIdx = -1; - _dragDropOptionIdx = -1; + _dragDropGroup = null; + _dragDropOption = null; } } /// Draw a combo to select single or multi group and switch between them. private void DrawGroupCombo(IModGroup group, int groupIdx) { + ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X - 2 * UiHelpers.IconButtonSize.X - 2 * ImGui.GetStyle().ItemSpacing.X); + using var combo = ImRaii.Combo("##GroupType", GroupTypeName(group.Type)); + if (!combo) + return; + + if (ImGui.Selectable(GroupTypeName(GroupType.Single), group.Type == GroupType.Single) && group is MultiModGroup m) + _modManager.OptionEditor.MultiEditor.ChangeToSingle(m); + + var canSwitchToMulti = group.Options.Count <= IModGroup.MaxMultiOptions; + using var style = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f, !canSwitchToMulti); + if (ImGui.Selectable(GroupTypeName(GroupType.Multi), group.Type == GroupType.Multi) && canSwitchToMulti && group is SingleModGroup s) + _modManager.OptionEditor.SingleEditor.ChangeToMulti(s); + + style.Pop(); + if (!canSwitchToMulti) + ImGuiUtil.HoverTooltip($"Can not convert group to multi group since it has more than {IModGroup.MaxMultiOptions} options."); + return; + static string GroupTypeName(GroupType type) => type switch { @@ -657,23 +672,6 @@ public class ModPanelEditTab( GroupType.Multi => "Multi Group", _ => "Unknown", }; - - ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X - 2 * UiHelpers.IconButtonSize.X - 2 * ImGui.GetStyle().ItemSpacing.X); - using var combo = ImRaii.Combo("##GroupType", GroupTypeName(group.Type)); - if (!combo) - return; - - if (ImGui.Selectable(GroupTypeName(GroupType.Single), group.Type == GroupType.Single)) - _modManager.OptionEditor.ChangeModGroupType(_mod, groupIdx, GroupType.Single); - - var canSwitchToMulti = group.Options.Count <= IModGroup.MaxMultiOptions; - using var style = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f, !canSwitchToMulti); - if (ImGui.Selectable(GroupTypeName(GroupType.Multi), group.Type == GroupType.Multi) && canSwitchToMulti) - _modManager.OptionEditor.ChangeModGroupType(_mod, groupIdx, GroupType.Multi); - - style.Pop(); - if (!canSwitchToMulti) - ImGuiUtil.HoverTooltip($"Can not convert group to multi group since it has more than {IModGroup.MaxMultiOptions} options."); } /// Handles input text and integers in separate fields without buffers for every single one. From cff617245356a3721d3e5849585e89856cbebcc5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Apr 2024 00:07:10 +0200 Subject: [PATCH 0586/1381] Move editors into folder. --- OtterGui | 2 +- Penumbra/Api/Api/ModSettingsApi.cs | 1 + .../Cache/CollectionCacheManager.cs | 1 + .../Collections/Manager/CollectionStorage.cs | 1 + Penumbra/Communication/ModOptionChanged.cs | 1 + Penumbra/Mods/Editor/ModMerger.cs | 1 + Penumbra/Mods/Manager/ModCacheManager.cs | 1 + Penumbra/Mods/Manager/ModManager.cs | 1 + .../{ => OptionEditor}/ImcModGroupEditor.cs | 4 +- .../{ => OptionEditor}/ModGroupEditor.cs | 37 +++++++------- .../{ => OptionEditor}/ModOptionEditor.cs | 50 +++++++++---------- .../{ => OptionEditor}/MultiModGroupEditor.cs | 8 +-- .../SingleModGroupEditor.cs | 8 +-- Penumbra/Mods/Settings/ModSettings.cs | 2 +- Penumbra/Penumbra.csproj | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 1 + Penumbra/UI/ModsTab/ModPanelEditTab.cs | 1 + Penumbra/packages.lock.json | 14 ++++-- 18 files changed, 74 insertions(+), 62 deletions(-) rename Penumbra/Mods/Manager/{ => OptionEditor}/ImcModGroupEditor.cs (91%) rename Penumbra/Mods/Manager/{ => OptionEditor}/ModGroupEditor.cs (88%) rename Penumbra/Mods/Manager/{ => OptionEditor}/ModOptionEditor.cs (73%) rename Penumbra/Mods/Manager/{ => OptionEditor}/MultiModGroupEditor.cs (92%) rename Penumbra/Mods/Manager/{ => OptionEditor}/SingleModGroupEditor.cs (90%) diff --git a/OtterGui b/OtterGui index 3460a817..20c4a6c5 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3460a817fc5e01a6b60eb834c3c59031938388fc +Subproject commit 20c4a6c53103d9fa8dec63babc628c9d01f094c0 diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index bfd134bb..56b80e63 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -10,6 +10,7 @@ using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 9c104cef..fb9ee9a3 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -9,6 +9,7 @@ using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index bfae2dc0..de5d0a14 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -6,6 +6,7 @@ using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; diff --git a/Penumbra/Communication/ModOptionChanged.cs b/Penumbra/Communication/ModOptionChanged.cs index a20592ec..67f2c0c3 100644 --- a/Penumbra/Communication/ModOptionChanged.cs +++ b/Penumbra/Communication/ModOptionChanged.cs @@ -3,6 +3,7 @@ using Penumbra.Api.Api; using Penumbra.Mods; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; using static Penumbra.Communication.ModOptionChanged; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 3a6f4a81..d6e21076 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -5,6 +5,7 @@ using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 0669696f..59c88cf0 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -3,6 +3,7 @@ using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; using Penumbra.Services; diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 7a266a31..adaca85e 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,5 +1,6 @@ using Penumbra.Communication; using Penumbra.Mods.Editor; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Services; namespace Penumbra.Mods.Manager; diff --git a/Penumbra/Mods/Manager/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs similarity index 91% rename from Penumbra/Mods/Manager/ImcModGroupEditor.cs rename to Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index 4e2b2194..1194f961 100644 --- a/Penumbra/Mods/Manager/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -6,7 +6,7 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -namespace Penumbra.Mods.Manager; +namespace Penumbra.Mods.Manager.OptionEditor; public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) : ModOptionEditor(communicator, saveService, config), IService @@ -14,7 +14,7 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ protected override ImcModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) => new(mod) { - Name = newName, + Name = newName, Priority = priority, }; diff --git a/Penumbra/Mods/Manager/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs similarity index 88% rename from Penumbra/Mods/Manager/ModGroupEditor.cs rename to Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 9f41fa6f..b2b48ac0 100644 --- a/Penumbra/Mods/Manager/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -1,10 +1,8 @@ -using System.Text.RegularExpressions; using Dalamud.Interface.Internal.Notifications; using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.Api.Enums; -using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; @@ -12,9 +10,8 @@ using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; using Penumbra.Util; -using static FFXIVClientStructs.FFXIV.Client.UI.Misc.ConfigModule; -namespace Penumbra.Mods.Manager; +namespace Penumbra.Mods.Manager.OptionEditor; public enum ModOptionChangeType { @@ -91,7 +88,7 @@ public class ModGroupEditor( /// Move the index of a given option group. public void MoveModGroup(IModGroup group, int groupIdxTo) { - var mod = group.Mod; + var mod = group.Mod; var idxFrom = group.GetIndex(); if (!mod.Groups.Move(idxFrom, groupIdxTo)) return; @@ -230,45 +227,45 @@ public class ModGroupEditor( => group switch { SingleModGroup s => SingleEditor.AddOption(s, option), - MultiModGroup m => MultiEditor.AddOption(m, option), - ImcModGroup i => ImcEditor.AddOption(i, option), - _ => null, + MultiModGroup m => MultiEditor.AddOption(m, option), + ImcModGroup i => ImcEditor.AddOption(i, option), + _ => null, }; public IModOption? AddOption(IModGroup group, string newName) => group switch { SingleModGroup s => SingleEditor.AddOption(s, newName), - MultiModGroup m => MultiEditor.AddOption(m, newName), - ImcModGroup i => ImcEditor.AddOption(i, newName), - _ => null, + MultiModGroup m => MultiEditor.AddOption(m, newName), + ImcModGroup i => ImcEditor.AddOption(i, newName), + _ => null, }; public IModGroup? AddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) => type switch { GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), - GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), - GroupType.Imc => ImcEditor.AddModGroup(mod, newName, saveType), - _ => null, + GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), + GroupType.Imc => ImcEditor.AddModGroup(mod, newName, saveType), + _ => null, }; public (IModGroup?, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string name, SaveType saveType = SaveType.ImmediateSync) => type switch { GroupType.Single => SingleEditor.FindOrAddModGroup(mod, name, saveType), - GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), - GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), - _ => (null, -1, false), + GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), + _ => (null, -1, false), }; public (IModOption?, int, bool) FindOrAddOption(IModGroup group, string name, SaveType saveType = SaveType.ImmediateSync) => group switch { SingleModGroup s => SingleEditor.FindOrAddOption(s, name, saveType), - MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), - ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), - _ => (null, -1, false), + MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), + ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), + _ => (null, -1, false), }; public void MoveOption(IModOption option, int toIdx) diff --git a/Penumbra/Mods/Manager/ModOptionEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs similarity index 73% rename from Penumbra/Mods/Manager/ModOptionEditor.cs rename to Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs index 7370a933..c067102e 100644 --- a/Penumbra/Mods/Manager/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs @@ -5,7 +5,7 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -namespace Penumbra.Mods.Manager; +namespace Penumbra.Mods.Manager.OptionEditor; public abstract class ModOptionEditor( CommunicatorService communicator, @@ -15,8 +15,8 @@ public abstract class ModOptionEditor( where TOption : class, IModOption { protected readonly CommunicatorService Communicator = communicator; - protected readonly SaveService SaveService = saveService; - protected readonly Configuration Config = config; + protected readonly SaveService SaveService = saveService; + protected readonly Configuration Config = config; /// Add a new, empty option group of the given type and name. public TGroup? AddModGroup(Mod mod, string newName, SaveType saveType = SaveType.ImmediateSync) @@ -25,7 +25,7 @@ public abstract class ModOptionEditor( return null; var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; - var group = CreateGroup(mod, newName, maxPriority); + var group = CreateGroup(mod, newName, maxPriority); mod.Groups.Add(group); SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, group, null, null, -1); @@ -92,8 +92,8 @@ public abstract class ModOptionEditor( /// Delete the given option from the given group. public void DeleteOption(TOption option) { - var mod = option.Mod; - var group = option.Group; + var mod = option.Mod; + var group = option.Group; var optionIdx = option.GetIndex(); Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, option, null, -1); RemoveOption((TGroup)group, optionIdx); @@ -104,7 +104,7 @@ public abstract class ModOptionEditor( /// Move an option inside the given option group. public void MoveOption(TOption option, int optionIdxTo) { - var idx = option.GetIndex(); + var idx = option.GetIndex(); var group = (TGroup)option.Group; if (!MoveOption(group, idx, optionIdxTo)) return; @@ -113,10 +113,10 @@ public abstract class ModOptionEditor( Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, group.Mod, group, option, null, idx); } - protected abstract TGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync); + protected abstract TGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync); protected abstract TOption? CloneOption(TGroup group, IModOption option); - protected abstract void RemoveOption(TGroup group, int optionIndex); - protected abstract bool MoveOption(TGroup group, int optionIdxFrom, int optionIdxTo); + protected abstract void RemoveOption(TGroup group, int optionIndex); + protected abstract bool MoveOption(TGroup group, int optionIdxFrom, int optionIdxTo); } public static class ModOptionChangeTypeExtension @@ -132,22 +132,22 @@ public static class ModOptionChangeTypeExtension { (requiresSaving, requiresReloading, wasPrepared) = type switch { - ModOptionChangeType.GroupRenamed => (true, false, false), - ModOptionChangeType.GroupAdded => (true, false, false), - ModOptionChangeType.GroupDeleted => (true, true, false), - ModOptionChangeType.GroupMoved => (true, false, false), - ModOptionChangeType.GroupTypeChanged => (true, true, true), - ModOptionChangeType.PriorityChanged => (true, true, true), - ModOptionChangeType.OptionAdded => (true, true, true), - ModOptionChangeType.OptionDeleted => (true, true, false), - ModOptionChangeType.OptionMoved => (true, false, false), - ModOptionChangeType.OptionFilesChanged => (false, true, false), - ModOptionChangeType.OptionFilesAdded => (false, true, true), - ModOptionChangeType.OptionSwapsChanged => (false, true, false), - ModOptionChangeType.OptionMetaChanged => (false, true, false), - ModOptionChangeType.DisplayChange => (false, false, false), + ModOptionChangeType.GroupRenamed => (true, false, false), + ModOptionChangeType.GroupAdded => (true, false, false), + ModOptionChangeType.GroupDeleted => (true, true, false), + ModOptionChangeType.GroupMoved => (true, false, false), + ModOptionChangeType.GroupTypeChanged => (true, true, true), + ModOptionChangeType.PriorityChanged => (true, true, true), + ModOptionChangeType.OptionAdded => (true, true, true), + ModOptionChangeType.OptionDeleted => (true, true, false), + ModOptionChangeType.OptionMoved => (true, false, false), + ModOptionChangeType.OptionFilesChanged => (false, true, false), + ModOptionChangeType.OptionFilesAdded => (false, true, true), + ModOptionChangeType.OptionSwapsChanged => (false, true, false), + ModOptionChangeType.OptionMetaChanged => (false, true, false), + ModOptionChangeType.DisplayChange => (false, false, false), ModOptionChangeType.DefaultOptionChanged => (true, false, false), - _ => (false, false, false), + _ => (false, false, false), }; } } diff --git a/Penumbra/Mods/Manager/MultiModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs similarity index 92% rename from Penumbra/Mods/Manager/MultiModGroupEditor.cs rename to Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs index e6b2bac1..c48d2d40 100644 --- a/Penumbra/Mods/Manager/MultiModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs @@ -6,14 +6,14 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -namespace Penumbra.Mods.Manager; +namespace Penumbra.Mods.Manager.OptionEditor; public sealed class MultiModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) : ModOptionEditor(communicator, saveService, config), IService { public void ChangeToSingle(MultiModGroup group) { - var idx = group.GetIndex(); + var idx = group.GetIndex(); var singleGroup = group.ConvertToSingle(); group.Mod.Groups[idx] = singleGroup; SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); @@ -34,7 +34,7 @@ public sealed class MultiModGroupEditor(CommunicatorService communicator, SaveSe protected override MultiModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) => new(mod) { - Name = newName, + Name = newName, Priority = priority, }; @@ -50,7 +50,7 @@ public sealed class MultiModGroupEditor(CommunicatorService communicator, SaveSe var newOption = new MultiSubMod(group) { - Name = option.Name, + Name = option.Name, Description = option.Description, }; diff --git a/Penumbra/Mods/Manager/SingleModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs similarity index 90% rename from Penumbra/Mods/Manager/SingleModGroupEditor.cs rename to Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs index 4999ff60..556416c6 100644 --- a/Penumbra/Mods/Manager/SingleModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs @@ -6,14 +6,14 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -namespace Penumbra.Mods.Manager; +namespace Penumbra.Mods.Manager.OptionEditor; public sealed class SingleModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) : ModOptionEditor(communicator, saveService, config), IService { public void ChangeToMulti(SingleModGroup group) { - var idx = group.GetIndex(); + var idx = group.GetIndex(); var multiGroup = group.ConvertToMulti(); group.Mod.Groups[idx] = multiGroup; SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); @@ -23,7 +23,7 @@ public sealed class SingleModGroupEditor(CommunicatorService communicator, SaveS protected override SingleModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) => new(mod) { - Name = newName, + Name = newName, Priority = priority, }; @@ -31,7 +31,7 @@ public sealed class SingleModGroupEditor(CommunicatorService communicator, SaveS { var newOption = new SingleSubMod(group) { - Name = option.Name, + Name = option.Name, Description = option.Description, }; if (option is IModDataContainer data) diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index 39ee1860..7fe48365 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -3,7 +3,7 @@ using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; -using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Settings; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 2d595ec1..2e53bd22 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -75,7 +75,7 @@ - + diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index cd55beb0..4db0df47 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -16,6 +16,7 @@ using Penumbra.Mods; using Penumbra.Mods.Groups; using Penumbra.Mods.ItemSwap; using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index fcd76a51..862852fa 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -16,6 +16,7 @@ using Penumbra.UI.AdvancedWindow; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; +using Penumbra.Mods.Manager.OptionEditor; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 68e1b880..b431e595 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -34,9 +34,14 @@ }, "SixLabors.ImageSharp": { "type": "Direct", - "requested": "[3.1.3, )", - "resolved": "3.1.3", - "contentHash": "wybtaqZQ1ZRZ4ZeU+9h+PaSeV14nyiGKIy7qRbDfSHzHq4ybqyOcjoifeaYbiKLO1u+PVxLBuy7MF/DMmwwbfg==" + "requested": "[3.1.4, )", + "resolved": "3.1.4", + "contentHash": "lFIdxgGDA5iYkUMRFOze7BGLcdpoLFbR+a20kc1W7NepvzU7ejtxtWOg9RvgG7kb9tBoJ3ONYOK6kLil/dgF1w==" + }, + "JetBrains.Annotations": { + "type": "Transitive", + "resolved": "2023.3.0", + "contentHash": "PHfnvdBUdGaTVG9bR/GEfxgTwWM0Z97Y6X3710wiljELBISipSfF5okn/vz+C2gfO+ihoEyVPjaJwn8ZalVukA==" }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", @@ -75,6 +80,7 @@ "ottergui": { "type": "Project", "dependencies": { + "JetBrains.Annotations": "[2023.3.0, )", "Microsoft.Extensions.DependencyInjection": "[8.0.0, )" } }, @@ -88,7 +94,7 @@ "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[1.0.15, )", + "Penumbra.Api": "[5.0.0, )", "Penumbra.String": "[1.0.4, )" } }, From 9084b43e3ebef4e00471aa8839ed29aecd0fc25a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Apr 2024 12:01:54 +0200 Subject: [PATCH 0587/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 9208c9c2..1b0b5469 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 9208c9c242244beeb3c1fb826582d72da09831af +Subproject commit 1b0b5469f792999e5b412d4f0c3ed77d9994d7b7 From 2e76148fba396e8c0e3fc0dc8ad632e0726e059d Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 3 May 2024 21:14:40 +1000 Subject: [PATCH 0588/1381] Ensure materials end in .mtrl --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index b8c0176a..b3460667 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -290,10 +290,13 @@ public partial class ModEditWindow /// While materials can be relative (`/mt_...`) or absolute (`bg/...`), /// they invariably must contain at least one directory seperator. /// Missing this can lead to a crash. + /// + /// They must also be at least one character (though this is enforced + /// by containing a `/`), and end with `.mtrl`. /// public bool ValidateMaterial(string material) { - return material.Contains('/'); + return material.Contains('/') && material.EndsWith(".mtrl"); } /// Remove the material given by the index. From c96adcf557597a712582b09eee62978ad479f2b7 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 3 May 2024 21:15:00 +1000 Subject: [PATCH 0589/1381] Prevent saving invalid files --- Penumbra/UI/AdvancedWindow/FileEditor.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index c891d33a..66f38bab 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -204,8 +204,9 @@ public class FileEditor( private void SaveButton() { + var canSave = _changed && _currentFile != null && _currentFile.Valid; if (ImGuiUtil.DrawDisabledButton("Save to File", Vector2.Zero, - $"Save the selected {fileType} file with all changes applied. This is not revertible.", !_changed)) + $"Save the selected {fileType} file with all changes applied. This is not revertible.", !canSave)) { compactor.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); if (owner.Mod != null) From 078688454a5e67a05497f92b0a834e9c5daae594 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 3 May 2024 21:17:54 +1000 Subject: [PATCH 0590/1381] Show an invalid material count --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 03b5169a..e075b592 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -293,7 +293,21 @@ public partial class ModEditWindow private bool DrawModelMaterialDetails(MdlTab tab, bool disabled) { - if (!ImGui.CollapsingHeader("Materials")) + var invalidMaterialCount = tab.Mdl.Materials.Count(material => !tab.ValidateMaterial(material)); + + var oldPos = ImGui.GetCursorPosY(); + var header = ImGui.CollapsingHeader("Materials"); + var newPos = ImGui.GetCursorPos(); + if (invalidMaterialCount > 0) + { + var text = $"{invalidMaterialCount} invalid material{(invalidMaterialCount > 1 ? "s" : "")}"; + var size = ImGui.CalcTextSize(text).X; + ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionAvail().X - size, oldPos + ImGui.GetStyle().FramePadding.Y)); + ImGuiUtil.TextColored(0xFF0000FF, text); + ImGui.SetCursorPos(newPos); + } + + if (!header) return false; using var table = ImRaii.Table(string.Empty, disabled ? 2 : 4, ImGuiTableFlags.SizingFixedFit); @@ -382,7 +396,8 @@ public partial class ModEditWindow { ImGuiComponents.HelpMarker( "Materials must be either relative (e.g. \"/filename.mtrl\")\n" - + "or absolute (e.g. \"bg/full/path/to/filename.mtrl\").", + + "or absolute (e.g. \"bg/full/path/to/filename.mtrl\"),\n" + + "and must end in \".mtrl\".", FontAwesomeIcon.TimesCircle); } From 9063d131bae492f5186b2a96d01e8135f7e2364f Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 3 May 2024 21:41:35 +1000 Subject: [PATCH 0591/1381] Use validation logic for new material field --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index e075b592..0be95c99 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -337,7 +337,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); ImGui.SetNextItemWidth(-1); ImGui.InputTextWithHint("##newMaterial", "Add new material...", ref _modelNewMaterial, Utf8GamePath.MaxGamePathLength, inputFlags); - var validName = _modelNewMaterial.Length > 0 && _modelNewMaterial[0] == '/'; + var validName = tab.ValidateMaterial(_modelNewMaterial); ImGui.TableNextColumn(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, string.Empty, !validName, true)) { @@ -346,6 +346,8 @@ public partial class ModEditWindow _modelNewMaterial = string.Empty; } ImGui.TableNextColumn(); + if (!validName && _modelNewMaterial.Length > 0) + DrawInvalidMaterialMarker(); return ret; } @@ -392,18 +394,22 @@ public partial class ModEditWindow ImGui.TableNextColumn(); // Add markers to invalid materials. if (!tab.ValidateMaterial(temp)) - using (var colorHandle = ImRaii.PushColor(ImGuiCol.TextDisabled, 0xFF0000FF, true)) - { - ImGuiComponents.HelpMarker( - "Materials must be either relative (e.g. \"/filename.mtrl\")\n" - + "or absolute (e.g. \"bg/full/path/to/filename.mtrl\"),\n" - + "and must end in \".mtrl\".", - FontAwesomeIcon.TimesCircle); - } + DrawInvalidMaterialMarker(); return ret; } + private void DrawInvalidMaterialMarker() + { + using var colorHandle = ImRaii.PushColor(ImGuiCol.TextDisabled, 0xFF0000FF, true); + + ImGuiComponents.HelpMarker( + "Materials must be either relative (e.g. \"/filename.mtrl\")\n" + + "or absolute (e.g. \"bg/full/path/to/filename.mtrl\"),\n" + + "and must end in \".mtrl\".", + FontAwesomeIcon.TimesCircle); + } + private bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) { using var lodNode = ImRaii.TreeNode($"Level of Detail #{lodIndex + 1}", ImGuiTreeNodeFlags.DefaultOpen); From 46a111d15287112a09ee3acf0b7cba0a30454ef2 Mon Sep 17 00:00:00 2001 From: ackwell Date: Fri, 3 May 2024 22:42:28 +1000 Subject: [PATCH 0592/1381] Fix marker --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 0be95c99..a7d39c6e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -401,13 +401,13 @@ public partial class ModEditWindow private void DrawInvalidMaterialMarker() { - using var colorHandle = ImRaii.PushColor(ImGuiCol.TextDisabled, 0xFF0000FF, true); + using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + ImGuiUtil.TextColored(0xFF0000FF, FontAwesomeIcon.TimesCircle.ToIconString()); - ImGuiComponents.HelpMarker( + ImGuiUtil.HoverTooltip( "Materials must be either relative (e.g. \"/filename.mtrl\")\n" + "or absolute (e.g. \"bg/full/path/to/filename.mtrl\"),\n" - + "and must end in \".mtrl\".", - FontAwesomeIcon.TimesCircle); + + "and must end in \".mtrl\"."); } private bool DrawModelLodDetails(MdlTab tab, int lodIndex, bool disabled) From 36fc251d5b4265c9fb6d0af8c9cfc88233c71697 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 3 May 2024 18:52:52 +0200 Subject: [PATCH 0593/1381] Fix a bunch of issues. --- Penumbra.GameData | 2 +- Penumbra/Mods/Groups/IModGroup.cs | 19 +- Penumbra/Mods/Groups/ImcModGroup.cs | 4 +- Penumbra/Mods/Groups/ModSaveGroup.cs | 7 +- Penumbra/Mods/Groups/MultiModGroup.cs | 4 +- Penumbra/Mods/Groups/SingleModGroup.cs | 13 +- .../OptionEditor/MultiModGroupEditor.cs | 4 +- .../OptionEditor/SingleModGroupEditor.cs | 4 +- Penumbra/Mods/SubMods/SubMod.cs | 1 - Penumbra/Services/BackupService.cs | 1 + Penumbra/Services/StaticServiceManager.cs | 1 - Penumbra/UI/ModsTab/ModGroupDrawer.cs | 233 +++++++++++++++ Penumbra/UI/ModsTab/ModGroupEditDrawer.cs | 214 ++++++++++++++ Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 272 ++---------------- 14 files changed, 513 insertions(+), 266 deletions(-) create mode 100644 Penumbra/UI/ModsTab/ModGroupDrawer.cs create mode 100644 Penumbra/UI/ModsTab/ModGroupEditDrawer.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 1b0b5469..595ac572 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1b0b5469f792999e5b412d4f0c3ed77d9994d7b7 +Subproject commit 595ac5722c9c400bea36110503ed2ae7b02d1489 diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index a268ba0f..d7138434 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -12,16 +12,23 @@ public interface ITexToolsGroup public IReadOnlyList OptionData { get; } } +public enum GroupDrawBehaviour +{ + SingleSelection, + MultiSelection, +} + public interface IModGroup { public const int MaxMultiOptions = 63; - public Mod Mod { get; } - public string Name { get; set; } - public string Description { get; set; } - public GroupType Type { get; } - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; } + public string Name { get; set; } + public string Description { get; set; } + public GroupType Type { get; } + public GroupDrawBehaviour Behaviour { get; } + public ModPriority Priority { get; set; } + public Setting DefaultSettings { get; set; } public FullPath? FindBestMatch(Utf8GamePath gamePath); public IModOption? AddOption(string name, string description = ""); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index e233f82e..e58d855a 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -21,6 +21,9 @@ public class ImcModGroup(Mod mod) : IModGroup public GroupType Type => GroupType.Imc; + public GroupDrawBehaviour Behaviour + => GroupDrawBehaviour.MultiSelection; + public ModPriority Priority { get; set; } = ModPriority.Default; public Setting DefaultSettings { get; set; } = Setting.Zero; @@ -150,7 +153,6 @@ public class ImcModGroup(Mod mod) : IModGroup } jWriter.WriteEndArray(); - jWriter.WriteEndObject(); } public (int Redirections, int Swaps, int Manips) GetCounts() diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index efdcde09..ed3c8857 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -56,10 +56,10 @@ public readonly struct ModSaveGroup : ISavable { _basePath = (container.Mod as Mod)?.ModPath ?? throw new Exception("Invalid save group from default data container without base path."); // Should not happen. - _defaultMod = null; + _defaultMod = container as DefaultSubMod; _onlyAscii = onlyAscii; - _group = container.Group!; - _groupIdx = _group.GetIndex(); + _group = container.Group; + _groupIdx = _group?.GetIndex() ?? -1; } public string ToFilename(FilenameService fileNames) @@ -80,7 +80,6 @@ public readonly struct ModSaveGroup : ISavable public static void WriteJsonBase(JsonTextWriter jWriter, IModGroup group) { - jWriter.WriteStartObject(); jWriter.WritePropertyName(nameof(group.Name)); jWriter.WriteValue(group.Name); jWriter.WritePropertyName(nameof(group.Description)); diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index a0034be0..7495c4b4 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -17,6 +17,9 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public GroupType Type => GroupType.Multi; + public GroupDrawBehaviour Behaviour + => GroupDrawBehaviour.MultiSelection; + public Mod Mod { get; } = mod; public string Name { get; set; } = "Group"; public string Description { get; set; } = "A non-exclusive group of settings."; @@ -127,7 +130,6 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup } jWriter.WriteEndArray(); - jWriter.WriteEndObject(); } public (int Redirections, int Swaps, int Manips) GetCounts() diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 0776c2af..459cec4a 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -15,7 +15,10 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public GroupType Type => GroupType.Single; - public Mod Mod { get; } = mod; + public GroupDrawBehaviour Behaviour + => GroupDrawBehaviour.SingleSelection; + + public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; public string Description { get; set; } = "A mutually exclusive group of settings."; public ModPriority Priority { get; set; } @@ -89,7 +92,12 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup => ModGroup.GetIndex(this); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) - => OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); + { + if (!IsOption) + return; + + OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); + } public Setting FixSetting(Setting setting) => OptionData.Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(OptionData.Count - 1))); @@ -111,7 +119,6 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup } jWriter.WriteEndArray(); - jWriter.WriteEndObject(); } /// Create a group without a mod only for saving it in the creator. diff --git a/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs index c48d2d40..74362325 100644 --- a/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs @@ -16,8 +16,8 @@ public sealed class MultiModGroupEditor(CommunicatorService communicator, SaveSe var idx = group.GetIndex(); var singleGroup = group.ConvertToSingle(); group.Mod.Groups[idx] = singleGroup; - SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, group.Mod, group, null, null, -1); + SaveService.QueueSave(new ModSaveGroup(singleGroup, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, singleGroup.Mod, singleGroup, null, null, -1); } /// Change the internal priority of the given option. diff --git a/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs index 556416c6..15a899a0 100644 --- a/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs @@ -16,8 +16,8 @@ public sealed class SingleModGroupEditor(CommunicatorService communicator, SaveS var idx = group.GetIndex(); var multiGroup = group.ConvertToMulti(); group.Mod.Groups[idx] = multiGroup; - SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, group.Mod, multiGroup, null, null, -1); + SaveService.QueueSave(new ModSaveGroup(multiGroup, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupTypeChanged, multiGroup.Mod, multiGroup, null, null, -1); } protected override SingleModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index a50e397f..b984b570 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -106,7 +106,6 @@ public static class SubMod j.WriteEndObject(); j.WritePropertyName(nameof(data.Manipulations)); serializer.Serialize(j, data.Manipulations); - j.WriteEndObject(); } /// Write the data for a selectable mod option on a JsonWriter. diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index a542dab5..bd5b3bcc 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -29,6 +29,7 @@ public class BackupService : IAsyncService list.Add(new FileInfo(fileNames.ConfigFile)); list.Add(new FileInfo(fileNames.FilesystemFile)); list.Add(new FileInfo(fileNames.ActiveCollectionsFile)); + list.Add(new FileInfo(fileNames.PredefinedTagFile)); return list; } diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 5fa1a848..19ae31a2 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -162,7 +162,6 @@ public static class StaticServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/Penumbra/UI/ModsTab/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/ModGroupDrawer.cs new file mode 100644 index 00000000..e9b0b396 --- /dev/null +++ b/Penumbra/UI/ModsTab/ModGroupDrawer.cs @@ -0,0 +1,233 @@ +using Dalamud.Interface.Components; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Widgets; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.Mods; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; + +namespace Penumbra.UI.ModsTab; + +public sealed class ModGroupDrawer(Configuration config, CollectionManager collectionManager) : IUiService +{ + private readonly List<(IModGroup, int)> _blockGroupCache = []; + + public void Draw(Mod mod, ModSettings settings) + { + if (mod.Groups.Count <= 0) + return; + + _blockGroupCache.Clear(); + var useDummy = true; + foreach (var (group, idx) in mod.Groups.WithIndex()) + { + if (!group.IsOption) + continue; + + switch (group.Behaviour) + { + case GroupDrawBehaviour.SingleSelection when group.Options.Count <= config.SingleGroupRadioMax: + case GroupDrawBehaviour.MultiSelection: + _blockGroupCache.Add((group, idx)); + break; + + case GroupDrawBehaviour.SingleSelection: + ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); + useDummy = false; + DrawSingleGroupCombo(group, idx, settings == ModSettings.Empty ? group.DefaultSettings : settings.Settings[idx]); + break; + } + } + + useDummy = true; + foreach (var (group, idx) in _blockGroupCache) + { + ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); + useDummy = false; + var option = settings == ModSettings.Empty ? group.DefaultSettings : settings.Settings[idx]; + if (group.Behaviour is GroupDrawBehaviour.MultiSelection) + DrawMultiGroup(group, idx, option); + else + DrawSingleGroupRadio(group, idx, option); + } + } + + /// + /// Draw a single group selector as a combo box. + /// If a description is provided, add a help marker besides it. + /// + private void DrawSingleGroupCombo(IModGroup group, int groupIdx, Setting setting) + { + using var id = ImRaii.PushId(groupIdx); + var selectedOption = setting.AsIndex; + ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); + var options = group.Options; + using (var combo = ImRaii.Combo(string.Empty, options[selectedOption].Name)) + { + if (combo) + for (var idx2 = 0; idx2 < options.Count; ++idx2) + { + id.Push(idx2); + var option = options[idx2]; + if (ImGui.Selectable(option.Name, idx2 == selectedOption)) + SetModSetting(group, groupIdx, Setting.Single(idx2)); + + if (option.Description.Length > 0) + ImGuiUtil.SelectableHelpMarker(option.Description); + + id.Pop(); + } + } + + ImGui.SameLine(); + if (group.Description.Length > 0) + ImGuiUtil.LabeledHelpMarker(group.Name, group.Description); + else + ImGui.TextUnformatted(group.Name); + } + + /// + /// Draw a single group selector as a set of radio buttons. + /// If a description is provided, add a help marker besides it. + /// + private void DrawSingleGroupRadio(IModGroup group, int groupIdx, Setting setting) + { + using var id = ImRaii.PushId(groupIdx); + var selectedOption = setting.AsIndex; + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var options = group.Options; + DrawCollapseHandling(options, minWidth, DrawOptions); + + Widget.EndFramedGroup(); + return; + + void DrawOptions() + { + for (var idx = 0; idx < group.Options.Count; ++idx) + { + using var i = ImRaii.PushId(idx); + var option = options[idx]; + if (ImGui.RadioButton(option.Name, selectedOption == idx)) + SetModSetting(group, groupIdx, Setting.Single(idx)); + + if (option.Description.Length <= 0) + continue; + + ImGui.SameLine(); + ImGuiComponents.HelpMarker(option.Description); + } + } + } + + /// + /// Draw a multi group selector as a bordered set of checkboxes. + /// If a description is provided, add a help marker in the title. + /// + private void DrawMultiGroup(IModGroup group, int groupIdx, Setting setting) + { + using var id = ImRaii.PushId(groupIdx); + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var options = group.Options; + DrawCollapseHandling(options, minWidth, DrawOptions); + + Widget.EndFramedGroup(); + var label = $"##multi{groupIdx}"; + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImGui.OpenPopup($"##multi{groupIdx}"); + + DrawMultiPopup(group, groupIdx, label); + return; + + void DrawOptions() + { + for (var idx = 0; idx < options.Count; ++idx) + { + using var i = ImRaii.PushId(idx); + var option = options[idx]; + var enabled = setting.HasFlag(idx); + + if (ImGui.Checkbox(option.Name, ref enabled)) + SetModSetting(group, groupIdx, setting.SetBit(idx, enabled)); + + if (option.Description.Length > 0) + { + ImGui.SameLine(); + ImGuiComponents.HelpMarker(option.Description); + } + } + } + } + + private void DrawMultiPopup(IModGroup group, int groupIdx, string label) + { + using var style = ImRaii.PushStyle(ImGuiStyleVar.PopupBorderSize, 1); + using var popup = ImRaii.Popup(label); + if (!popup) + return; + + ImGui.TextUnformatted(group.Name); + ImGui.Separator(); + if (ImGui.Selectable("Enable All")) + SetModSetting(group, groupIdx, Setting.AllBits(group.Options.Count)); + + if (ImGui.Selectable("Disable All")) + SetModSetting(group, groupIdx, Setting.Zero); + } + + private void DrawCollapseHandling(IReadOnlyList options, float minWidth, Action draw) + { + if (options.Count <= config.OptionGroupCollapsibleMin) + { + draw(); + } + else + { + var collapseId = ImGui.GetID("Collapse"); + var shown = ImGui.GetStateStorage().GetBool(collapseId, true); + var buttonTextShow = $"Show {options.Count} Options"; + var buttonTextHide = $"Hide {options.Count} Options"; + var buttonWidth = Math.Max(ImGui.CalcTextSize(buttonTextShow).X, ImGui.CalcTextSize(buttonTextHide).X) + + 2 * ImGui.GetStyle().FramePadding.X; + minWidth = Math.Max(buttonWidth, minWidth); + if (shown) + { + var pos = ImGui.GetCursorPos(); + ImGui.Dummy(UiHelpers.IconButtonSize); + using (var _ = ImRaii.Group()) + { + draw(); + } + + + var width = Math.Max(ImGui.GetItemRectSize().X, minWidth); + var endPos = ImGui.GetCursorPos(); + ImGui.SetCursorPos(pos); + if (ImGui.Button(buttonTextHide, new Vector2(width, 0))) + ImGui.GetStateStorage().SetBool(collapseId, !shown); + + ImGui.SetCursorPos(endPos); + } + else + { + var optionWidth = options.Max(o => ImGui.CalcTextSize(o.Name).X) + + ImGui.GetStyle().ItemInnerSpacing.X + + ImGui.GetFrameHeight() + + ImGui.GetStyle().FramePadding.X; + var width = Math.Max(optionWidth, minWidth); + if (ImGui.Button(buttonTextShow, new Vector2(width, 0))) + ImGui.GetStateStorage().SetBool(collapseId, !shown); + } + } + } + + private ModCollection Current + => collectionManager.Active.Current; + + private void SetModSetting(IModGroup group, int groupIdx, Setting setting) + => collectionManager.Editor.SetModSetting(Current, group.Mod, groupIdx, setting); +} diff --git a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs new file mode 100644 index 00000000..6b62d5b8 --- /dev/null +++ b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs @@ -0,0 +1,214 @@ +using Dalamud.Interface; +using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.Utility; +using ImGuiNET; +using OtterGui; +using OtterGui.Classes; +using OtterGui.Raii; +using OtterGui.Services; +using Penumbra.Mods; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.ModsTab; + +public sealed class ModGroupEditDrawer(ModManager modManager, Configuration config, FilenameService filenames) : IUiService +{ + private Vector2 _buttonSize; + private float _priorityWidth; + private float _groupNameWidth; + private float _spacing; + + private string? _currentGroupName; + private ModPriority? _currentGroupPriority; + private IModGroup? _currentGroupEdited; + private bool _isGroupNameValid; + private IModGroup? _deleteGroup; + private IModGroup? _moveGroup; + private int _moveTo; + + private string? _currentOptionName; + private ModPriority? _currentOptionPriority; + private IModOption? _currentOptionEdited; + private IModOption? _deleteOption; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SameLine() + => ImGui.SameLine(0, _spacing); + + public void Draw(Mod mod) + { + _buttonSize = new Vector2(ImGui.GetFrameHeight()); + _priorityWidth = 50 * ImGuiHelpers.GlobalScale; + _groupNameWidth = 350f * ImGuiHelpers.GlobalScale; + _spacing = ImGui.GetStyle().ItemInnerSpacing.X; + + + FinishGroupCleanup(); + } + + private void FinishGroupCleanup() + { + if (_deleteGroup != null) + { + modManager.OptionEditor.DeleteModGroup(_deleteGroup); + _deleteGroup = null; + } + + if (_deleteOption != null) + { + modManager.OptionEditor.DeleteOption(_deleteOption); + _deleteOption = null; + } + + if (_moveGroup != null) + { + modManager.OptionEditor.MoveModGroup(_moveGroup, _moveTo); + _moveGroup = null; + } + } + + private void DrawGroup(IModGroup group, int idx) + { + using var id = ImRaii.PushId(idx); + using var frame = ImRaii.FramedGroup($"Group #{idx + 1}"); + DrawGroupNameRow(group); + switch (group) + { + case SingleModGroup s: + DrawSingleGroup(s, idx); + break; + case MultiModGroup m: + DrawMultiGroup(m, idx); + break; + case ImcModGroup i: + DrawImcGroup(i, idx); + break; + } + } + + private void DrawGroupNameRow(IModGroup group) + { + DrawGroupName(group); + SameLine(); + DrawGroupDelete(group); + SameLine(); + DrawGroupPriority(group); + } + + private void DrawGroupName(IModGroup group) + { + var text = _currentGroupEdited == group ? _currentGroupName ?? group.Name : group.Name; + ImGui.SetNextItemWidth(_groupNameWidth); + using var border = ImRaii.PushFrameBorder(UiHelpers.ScaleX2, Colors.RegexWarningBorder, !_isGroupNameValid); + if (ImGui.InputText("##GroupName", ref text, 256)) + { + _currentGroupEdited = group; + _currentGroupName = text; + _isGroupNameValid = ModGroupEditor.VerifyFileName(group.Mod, group, text, false); + } + + if (ImGui.IsItemDeactivated()) + { + if (_currentGroupName != null && _isGroupNameValid) + modManager.OptionEditor.RenameModGroup(group, _currentGroupName); + _currentGroupName = null; + _currentGroupEdited = null; + _isGroupNameValid = true; + } + + var tt = _isGroupNameValid + ? "Group Name" + : "Current name can not be used for this group."; + ImGuiUtil.HoverTooltip(tt); + } + + private void DrawGroupDelete(IModGroup group) + { + var enabled = config.DeleteModModifier.IsActive(); + var tt = enabled + ? "Delete this option group." + : $"Delete this option group.\nHold {config.DeleteModModifier} while clicking to delete."; + + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), _buttonSize, tt, !enabled, true)) + _deleteGroup = group; + } + + private void DrawGroupPriority(IModGroup group) + { + var priority = _currentGroupEdited == group + ? (_currentGroupPriority ?? group.Priority).Value + : group.Priority.Value; + ImGui.SetNextItemWidth(_priorityWidth); + if (ImGui.InputInt("##GroupPriority", ref priority, 0, 0)) + { + _currentGroupEdited = group; + _currentGroupPriority = new ModPriority(priority); + } + + if (ImGui.IsItemDeactivated()) + { + if (_currentGroupPriority.HasValue) + modManager.OptionEditor.ChangeGroupPriority(group, _currentGroupPriority.Value); + _currentGroupEdited = null; + _currentGroupPriority = null; + } + + ImGuiUtil.HoverTooltip("Group Priority"); + } + + private void DrawGroupMoveButtons(IModGroup group, int idx) + { + var isFirst = idx == 0; + var tt = isFirst ? "Can not move this group further upwards." : $"Move this group up to group {idx}."; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowUp.ToIconString(), UiHelpers.IconButtonSize, tt, isFirst, true)) + { + _moveGroup = group; + _moveTo = idx - 1; + } + + SameLine(); + var isLast = idx == group.Mod.Groups.Count - 1; + tt = isLast + ? "Can not move this group further downwards." + : $"Move this group down to group {idx + 2}."; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowDown.ToIconString(), UiHelpers.IconButtonSize, tt, isLast, true)) + { + _moveGroup = group; + _moveTo = idx + 1; + } + } + + private void DrawGroupOpenFile(IModGroup group, int idx) + { + var fileName = filenames.OptionGroupFile(group.Mod, idx, config.ReplaceNonAsciiOnImport); + var fileExists = File.Exists(fileName); + var tt = fileExists + ? $"Open the {group.Name} json file in the text editor of your choice." + : $"The {group.Name} json file does not exist."; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileExport.ToIconString(), UiHelpers.IconButtonSize, tt, !fileExists, true)) + try + { + Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); + } + catch (Exception e) + { + Penumbra.Messager.NotificationMessage(e, "Could not open editor.", NotificationType.Error); + } + } + + + private void DrawSingleGroup(SingleModGroup group, int idx) + { } + + private void DrawMultiGroup(MultiModGroup group, int idx) + { } + + private void DrawImcGroup(ImcModGroup group, int idx) + { } +} diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 1326a763..fc5311d9 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -1,51 +1,37 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; +using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; -using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.UI.Classes; -using Dalamud.Interface.Components; using Penumbra.Collections.Manager; using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.Mods.SubMods; -using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; namespace Penumbra.UI.ModsTab; -public class ModPanelSettingsTab : ITab +public class ModPanelSettingsTab( + CollectionManager collectionManager, + ModManager modManager, + ModFileSystemSelector selector, + TutorialService tutorial, + CommunicatorService communicator, + ModGroupDrawer modGroupDrawer) + : ITab, IUiService { - private readonly Configuration _config; - private readonly CommunicatorService _communicator; - private readonly CollectionManager _collectionManager; - private readonly ModFileSystemSelector _selector; - private readonly TutorialService _tutorial; - private readonly ModManager _modManager; - private bool _inherited; private ModSettings _settings = null!; private ModCollection _collection = null!; - private bool _empty; private int? _currentPriority; - public ModPanelSettingsTab(CollectionManager collectionManager, ModManager modManager, ModFileSystemSelector selector, - TutorialService tutorial, CommunicatorService communicator, Configuration config) - { - _collectionManager = collectionManager; - _communicator = communicator; - _modManager = modManager; - _selector = selector; - _tutorial = tutorial; - _config = config; - } - public ReadOnlySpan Label => "Settings"u8; public void DrawHeader() - => _tutorial.OpenTutorial(BasicTutorialSteps.ModOptions); + => tutorial.OpenTutorial(BasicTutorialSteps.ModOptions); public void Reset() => _currentPriority = null; @@ -56,53 +42,24 @@ public class ModPanelSettingsTab : ITab if (!child) return; - _settings = _selector.SelectedSettings; - _collection = _selector.SelectedSettingCollection; - _inherited = _collection != _collectionManager.Active.Current; - _empty = _settings == ModSettings.Empty; - + _settings = selector.SelectedSettings; + _collection = selector.SelectedSettingCollection; + _inherited = _collection != collectionManager.Active.Current; DrawInheritedWarning(); UiHelpers.DefaultLineSpace(); - _communicator.PreSettingsPanelDraw.Invoke(_selector.Selected!.Identifier); + communicator.PreSettingsPanelDraw.Invoke(selector.Selected!.Identifier); DrawEnabledInput(); - _tutorial.OpenTutorial(BasicTutorialSteps.EnablingMods); + tutorial.OpenTutorial(BasicTutorialSteps.EnablingMods); ImGui.SameLine(); DrawPriorityInput(); - _tutorial.OpenTutorial(BasicTutorialSteps.Priority); + tutorial.OpenTutorial(BasicTutorialSteps.Priority); DrawRemoveSettings(); - _communicator.PostEnabledDraw.Invoke(_selector.Selected!.Identifier); - - if (_selector.Selected!.Groups.Count > 0) - { - var useDummy = true; - foreach (var (group, idx) in _selector.Selected!.Groups.WithIndex() - .Where(g => g.Value.Type == GroupType.Single && g.Value.Options.Count > _config.SingleGroupRadioMax)) - { - ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); - useDummy = false; - DrawSingleGroupCombo(group, idx); - } - - useDummy = true; - foreach (var (group, idx) in _selector.Selected!.Groups.WithIndex().Where(g => g.Value.IsOption)) - { - ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); - useDummy = false; - switch (group.Type) - { - case GroupType.Multi: - DrawMultiGroup(group, idx); - break; - case GroupType.Single when group.Options.Count <= _config.SingleGroupRadioMax: - DrawSingleGroupRadio(group, idx); - break; - } - } - } + communicator.PostEnabledDraw.Invoke(selector.Selected!.Identifier); + modGroupDrawer.Draw(selector.Selected!, _settings); UiHelpers.DefaultLineSpace(); - _communicator.PostSettingsPanelDraw.Invoke(_selector.Selected!.Identifier); + communicator.PostSettingsPanelDraw.Invoke(selector.Selected!.Identifier); } /// Draw a big red bar if the current setting is inherited. @@ -113,8 +70,8 @@ public class ModPanelSettingsTab : ITab using var color = ImRaii.PushColor(ImGuiCol.Button, Colors.PressEnterWarningBg); var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); - if (ImGui.Button($"These settings are inherited from {_collection.Name}.", width)) - _collectionManager.Editor.SetModInheritance(_collectionManager.Active.Current, _selector.Selected!, false); + if (ImUtf8.Button($"These settings are inherited from {_collection.Name}.", width)) + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selector.Selected!, false); ImGuiUtil.HoverTooltip("You can click this button to copy the current settings to the current selection.\n" + "You can also just change any setting, which will copy the settings with the single setting changed to the current selection."); @@ -127,8 +84,8 @@ public class ModPanelSettingsTab : ITab if (!ImGui.Checkbox("Enabled", ref enabled)) return; - _modManager.SetKnown(_selector.Selected!); - _collectionManager.Editor.SetModState(_collectionManager.Active.Current, _selector.Selected!, enabled); + modManager.SetKnown(selector.Selected!); + collectionManager.Editor.SetModState(collectionManager.Active.Current, selector.Selected!, enabled); } /// @@ -146,7 +103,8 @@ public class ModPanelSettingsTab : ITab if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { if (_currentPriority != _settings.Priority.Value) - _collectionManager.Editor.SetModPriority(_collectionManager.Active.Current, _selector.Selected!, new ModPriority(_currentPriority.Value)); + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selector.Selected!, + new ModPriority(_currentPriority.Value)); _currentPriority = null; } @@ -162,189 +120,15 @@ public class ModPanelSettingsTab : ITab private void DrawRemoveSettings() { const string text = "Inherit Settings"; - if (_inherited || _empty) + if (_inherited || _settings == ModSettings.Empty) return; var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0; ImGui.SameLine(ImGui.GetWindowWidth() - ImGui.CalcTextSize(text).X - ImGui.GetStyle().FramePadding.X * 2 - scroll); if (ImGui.Button(text)) - _collectionManager.Editor.SetModInheritance(_collectionManager.Active.Current, _selector.Selected!, true); + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selector.Selected!, true); ImGuiUtil.HoverTooltip("Remove current settings from this collection so that it can inherit them.\n" + "If no inherited collection has settings for this mod, it will be disabled."); } - - /// - /// Draw a single group selector as a combo box. - /// If a description is provided, add a help marker besides it. - /// - private void DrawSingleGroupCombo(IModGroup group, int groupIdx) - { - using var id = ImRaii.PushId(groupIdx); - var selectedOption = _empty ? group.DefaultSettings.AsIndex : _settings.Settings[groupIdx].AsIndex; - ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); - var options = group.Options; - using (var combo = ImRaii.Combo(string.Empty, options[selectedOption].Name)) - { - if (combo) - for (var idx2 = 0; idx2 < options.Count; ++idx2) - { - id.Push(idx2); - var option = options[idx2]; - if (ImGui.Selectable(option.Name, idx2 == selectedOption)) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, - Setting.Single(idx2)); - - if (option.Description.Length > 0) - ImGuiUtil.SelectableHelpMarker(option.Description); - - id.Pop(); - } - } - - ImGui.SameLine(); - if (group.Description.Length > 0) - ImGuiUtil.LabeledHelpMarker(group.Name, group.Description); - else - ImGui.TextUnformatted(group.Name); - } - - // Draw a single group selector as a set of radio buttons. - // If a description is provided, add a help marker besides it. - private void DrawSingleGroupRadio(IModGroup group, int groupIdx) - { - using var id = ImRaii.PushId(groupIdx); - var selectedOption = _empty ? group.DefaultSettings.AsIndex : _settings.Settings[groupIdx].AsIndex; - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - var options = group.Options; - DrawCollapseHandling(options, minWidth, DrawOptions); - - Widget.EndFramedGroup(); - return; - - void DrawOptions() - { - for (var idx = 0; idx < group.Options.Count; ++idx) - { - using var i = ImRaii.PushId(idx); - var option = options[idx]; - if (ImGui.RadioButton(option.Name, selectedOption == idx)) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, - Setting.Single(idx)); - - if (option.Description.Length <= 0) - continue; - - ImGui.SameLine(); - ImGuiComponents.HelpMarker(option.Description); - } - } - } - - - private void DrawCollapseHandling(IReadOnlyList options, float minWidth, Action draw) - { - if (options.Count <= _config.OptionGroupCollapsibleMin) - { - draw(); - } - else - { - var collapseId = ImGui.GetID("Collapse"); - var shown = ImGui.GetStateStorage().GetBool(collapseId, true); - var buttonTextShow = $"Show {options.Count} Options"; - var buttonTextHide = $"Hide {options.Count} Options"; - var buttonWidth = Math.Max(ImGui.CalcTextSize(buttonTextShow).X, ImGui.CalcTextSize(buttonTextHide).X) - + 2 * ImGui.GetStyle().FramePadding.X; - minWidth = Math.Max(buttonWidth, minWidth); - if (shown) - { - var pos = ImGui.GetCursorPos(); - ImGui.Dummy(UiHelpers.IconButtonSize); - using (var _ = ImRaii.Group()) - { - draw(); - } - - - var width = Math.Max(ImGui.GetItemRectSize().X, minWidth); - var endPos = ImGui.GetCursorPos(); - ImGui.SetCursorPos(pos); - if (ImGui.Button(buttonTextHide, new Vector2(width, 0))) - ImGui.GetStateStorage().SetBool(collapseId, !shown); - - ImGui.SetCursorPos(endPos); - } - else - { - var optionWidth = options.Max(o => ImGui.CalcTextSize(o.Name).X) - + ImGui.GetStyle().ItemInnerSpacing.X - + ImGui.GetFrameHeight() - + ImGui.GetStyle().FramePadding.X; - var width = Math.Max(optionWidth, minWidth); - if (ImGui.Button(buttonTextShow, new Vector2(width, 0))) - ImGui.GetStateStorage().SetBool(collapseId, !shown); - } - } - } - - /// - /// Draw a multi group selector as a bordered set of checkboxes. - /// If a description is provided, add a help marker in the title. - /// - private void DrawMultiGroup(IModGroup group, int groupIdx) - { - using var id = ImRaii.PushId(groupIdx); - var flags = _empty ? group.DefaultSettings : _settings.Settings[groupIdx]; - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - var options = group.Options; - DrawCollapseHandling(options, minWidth, DrawOptions); - - Widget.EndFramedGroup(); - var label = $"##multi{groupIdx}"; - if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) - ImGui.OpenPopup($"##multi{groupIdx}"); - - DrawMultiPopup(group, groupIdx, label); - return; - - void DrawOptions() - { - for (var idx = 0; idx < options.Count; ++idx) - { - using var i = ImRaii.PushId(idx); - var option = options[idx]; - var setting = flags.HasFlag(idx); - - if (ImGui.Checkbox(option.Name, ref setting)) - { - flags = flags.SetBit(idx, setting); - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, flags); - } - - if (option.Description.Length > 0) - { - ImGui.SameLine(); - ImGuiComponents.HelpMarker(option.Description); - } - } - } - } - - private void DrawMultiPopup(IModGroup group, int groupIdx, string label) - { - using var style = ImRaii.PushStyle(ImGuiStyleVar.PopupBorderSize, 1); - using var popup = ImRaii.Popup(label); - if (!popup) - return; - - ImGui.TextUnformatted(group.Name); - ImGui.Separator(); - if (ImGui.Selectable("Enable All")) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, - Setting.AllBits(group.Options.Count)); - - if (ImGui.Selectable("Disable All")) - _collectionManager.Editor.SetModSetting(_collectionManager.Active.Current, _selector.Selected!, groupIdx, Setting.Zero); - } } From 7553b5da8ac44fe4d058934033a5aa18ff32ffa1 Mon Sep 17 00:00:00 2001 From: ackwell Date: Sat, 4 May 2024 04:01:28 +1000 Subject: [PATCH 0594/1381] Fix float imprecision on blend weights --- .../Import/Models/Import/VertexAttribute.cs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index b7f5dcf1..a4651776 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -138,7 +138,27 @@ public class VertexAttribute return new VertexAttribute( element, - index => BuildNByte4(values[index]) + index => { + // Blend weights are _very_ sensitive to float imprecision - a vertex sum being off + // by one, such as 256, is enough to cause a visible defect. To avoid this, we tweak + // the converted values to have the expected sum, preferencing values with minimal differences. + var originalValues = values[index]; + var byteValues = BuildNByte4(originalValues); + + var adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + while (adjustment != 0) + { + var convertedValues = byteValues.Select(value => value * (1f / 255f)).ToArray(); + var closestIndex = Enumerable.Range(0, 4) + .Select(index => (index, delta: Math.Abs(originalValues[index] - convertedValues[index]))) + .MinBy(x => x.delta) + .index; + byteValues[closestIndex] = (byte)(byteValues[closestIndex] + Math.CopySign(1, adjustment)); + adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + } + + return byteValues; + } ); } From 2a5df2dfb05469a15cf1386e70139a93eaad1d7d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 4 May 2024 11:19:07 +0200 Subject: [PATCH 0595/1381] Create permanent backup before migrating collections. --- Penumbra/Configuration.cs | 2 +- Penumbra/Services/BackupService.cs | 14 ++++++++++++-- Penumbra/Services/ConfigMigrationService.cs | 16 +++++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 98668e8a..a065bc26 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -136,7 +136,7 @@ public class Configuration : IPluginConfiguration, ISavable /// Contains some default values or boundaries for config values. public static class Constants { - public const int CurrentVersion = 8; + public const int CurrentVersion = 9; public const float MaxAbsoluteSize = 600; public const int DefaultAbsoluteSize = 250; public const float MinAbsoluteSize = 50; diff --git a/Penumbra/Services/BackupService.cs b/Penumbra/Services/BackupService.cs index bd5b3bcc..88b99de1 100644 --- a/Penumbra/Services/BackupService.cs +++ b/Penumbra/Services/BackupService.cs @@ -7,6 +7,10 @@ namespace Penumbra.Services; public class BackupService : IAsyncService { + private readonly Logger _logger; + private readonly DirectoryInfo _configDirectory; + private readonly IReadOnlyList _fileNames; + /// public Task Awaiter { get; } @@ -17,10 +21,16 @@ public class BackupService : IAsyncService /// Start a backup process on the collected files. public BackupService(Logger logger, FilenameService fileNames) { - var files = PenumbraFiles(fileNames); - Awaiter = Task.Run(() => Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), files)); + _logger = logger; + _fileNames = PenumbraFiles(fileNames); + _configDirectory = new DirectoryInfo(fileNames.ConfigDirectory); + Awaiter = Task.Run(() => Backup.CreateAutomaticBackup(logger, new DirectoryInfo(fileNames.ConfigDirectory), _fileNames)); } + /// Create a permanent backup with a given name for migrations. + public void CreateMigrationBackup(string name) + => Backup.CreatePermanentBackup(_logger, _configDirectory, _fileNames, name); + /// Collect all relevant files for penumbra configuration. private static IReadOnlyList PenumbraFiles(FilenameService fileNames) { diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index fafaa0e5..1f6ac170 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -22,7 +22,7 @@ namespace Penumbra.Services; /// Contains everything to migrate from older versions of the config to the current, /// including deprecated fields. /// -public class ConfigMigrationService(SaveService saveService) : IService +public class ConfigMigrationService(SaveService saveService, BackupService backupService) : IService { private Configuration _config = null!; private JObject _data = null!; @@ -73,9 +73,23 @@ public class ConfigMigrationService(SaveService saveService) : IService Version5To6(); Version6To7(); Version7To8(); + Version8To9(); AddColors(config, true); } + // Migrate to ephemeral config. + private void Version8To9() + { + if (_config.Version != 8) + return; + + backupService.CreateMigrationBackup("pre_collection_identifiers"); + _config.Version = 9; + _config.Ephemeral.Version = 9; + _config.Save(); + _config.Ephemeral.Save(); + } + // Migrate to ephemeral config. private void Version7To8() { From d8dad91e899a4055e5fe19dbc1255333a07f9033 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 4 May 2024 11:24:01 +0200 Subject: [PATCH 0596/1381] Oop, not yet. --- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index fc5311d9..107a2d04 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -2,7 +2,6 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; using OtterGui.Services; -using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.UI.Classes; @@ -70,7 +69,7 @@ public class ModPanelSettingsTab( using var color = ImRaii.PushColor(ImGuiCol.Button, Colors.PressEnterWarningBg); var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); - if (ImUtf8.Button($"These settings are inherited from {_collection.Name}.", width)) + if (ImGui.Button($"These settings are inherited from {_collection.Name}.", width)) collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selector.Selected!, false); ImGuiUtil.HoverTooltip("You can click this button to copy the current settings to the current selection.\n" From 1f2f66b1141f83613c3799faf80439b1142bd571 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 4 May 2024 11:34:02 +0200 Subject: [PATCH 0597/1381] Meh. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 20c4a6c5..bc2afed8 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 20c4a6c53103d9fa8dec63babc628c9d01f094c0 +Subproject commit bc2afed8a873d1f9517eefe7a7296bc5b83e693b From bbbf65eb4c0c9d8dd77ac8f8101ad2ac86433c1c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 9 May 2024 15:49:49 +0200 Subject: [PATCH 0598/1381] Fix bug preventing deduplication. --- Penumbra/Mods/Editor/DuplicateManager.cs | 3 +++ Penumbra/Mods/Groups/ModSaveGroup.cs | 2 +- Penumbra/UI/Classes/CollectionSelectHeader.cs | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 84a832a2..2e6dc1d6 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -84,7 +84,10 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co if (useModManager) modManager.OptionEditor.SetFiles(subMod, dict, SaveType.ImmediateSync); else + { + subMod.Files = dict; saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, subMod, config.ReplaceNonAsciiOnImport)); + } } } diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index ed3c8857..7efc76a6 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -40,7 +40,7 @@ public readonly struct ModSaveGroup : ISavable _basePath = basePath; _defaultMod = container as DefaultSubMod; _onlyAscii = onlyAscii; - if (_defaultMod == null) + if (_defaultMod != null) { _groupIdx = -1; _group = null; diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index de2b6a34..bff0092a 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -89,7 +89,7 @@ public class CollectionSelectHeader var collection = _resolver.PlayerCollection(); return CheckCollection(collection) switch { - CollectionState.Empty => (collection, "None", "The base collection is configured to use no mods.", true), + CollectionState.Empty => (collection, "None", "The loaded player character is configured to use no mods.", true), CollectionState.Selected => (collection, collection.Name, "The collection configured to apply to the loaded player character is already selected as the current collection.", true), CollectionState.Available => (collection, collection.Name, From 32dbf419e254ca432055f6e4b08b684b5a03447b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 9 May 2024 19:58:35 +0200 Subject: [PATCH 0599/1381] Fix single group default options not applying. --- Penumbra/Mods/Editor/DuplicateManager.cs | 2 ++ Penumbra/Mods/Groups/SingleModGroup.cs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 2e6dc1d6..47aa18dc 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -82,7 +82,9 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co return; if (useModManager) + { modManager.OptionEditor.SetFiles(subMod, dict, SaveType.ImmediateSync); + } else { subMod.Files = dict; diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 459cec4a..bc463c1e 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -93,7 +93,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { - if (!IsOption) + if (OptionData.Count == 0) return; OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); From d47d31b665ffa4cd14774f04888a6c50c7a37a72 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 14 May 2024 18:10:59 +0200 Subject: [PATCH 0600/1381] achieve feature parity... I think. --- OtterGui | 2 +- Penumbra/Mods/Groups/IModGroup.cs | 2 +- Penumbra/UI/ModsTab/DescriptionEditPopup.cs | 114 ++++++ Penumbra/UI/ModsTab/ModGroupEditDrawer.cs | 424 ++++++++++++++++---- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 420 +------------------ 5 files changed, 473 insertions(+), 489 deletions(-) create mode 100644 Penumbra/UI/ModsTab/DescriptionEditPopup.cs diff --git a/OtterGui b/OtterGui index bc2afed8..866389b3 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit bc2afed8a873d1f9517eefe7a7296bc5b83e693b +Subproject commit 866389b3988d9c4926a786f6c78ac9d5265591ac diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index d7138434..2ec60f7e 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -20,7 +20,7 @@ public enum GroupDrawBehaviour public interface IModGroup { - public const int MaxMultiOptions = 63; + public const int MaxMultiOptions = 32; public Mod Mod { get; } public string Name { get; set; } diff --git a/Penumbra/UI/ModsTab/DescriptionEditPopup.cs b/Penumbra/UI/ModsTab/DescriptionEditPopup.cs new file mode 100644 index 00000000..c284afc3 --- /dev/null +++ b/Penumbra/UI/ModsTab/DescriptionEditPopup.cs @@ -0,0 +1,114 @@ +using Dalamud.Interface.Utility; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Mods; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Manager; +using Penumbra.Mods.SubMods; + +namespace Penumbra.UI.ModsTab; + +public class DescriptionEditPopup(ModManager modManager) : IUiService +{ + private static ReadOnlySpan PopupId + => "PenumbraEditDescription"u8; + + private bool _hasBeenEdited; + private string _description = string.Empty; + + private object? _current; + private bool _opened; + + public void Open(Mod mod) + { + _current = mod; + _opened = true; + _hasBeenEdited = false; + _description = mod.Description; + } + + public void Open(IModGroup group) + { + _current = group; + _opened = true; + _hasBeenEdited = false; + _description = group.Description; + } + + public void Open(IModOption option) + { + _current = option; + _opened = true; + _hasBeenEdited = false; + _description = option.Description; + } + + public void Draw() + { + if (_current == null) + return; + + if (_opened) + { + _opened = false; + ImUtf8.OpenPopup(PopupId); + } + + var inputSize = ImGuiHelpers.ScaledVector2(800); + using var popup = ImUtf8.Popup(PopupId); + if (!popup) + return; + + if (ImGui.IsWindowAppearing()) + ImGui.SetKeyboardFocusHere(); + + ImUtf8.InputMultiLineOnDeactivated("##editDescription"u8, ref _description, inputSize); + _hasBeenEdited |= ImGui.IsItemEdited(); + UiHelpers.DefaultLineSpace(); + + var buttonSize = new Vector2(ImUtf8.GlobalScale * 100, 0); + + var width = 2 * buttonSize.X + + 4 * ImUtf8.FramePadding.X + + ImUtf8.ItemSpacing.X; + + ImGui.SetCursorPosX((inputSize.X - width) / 2); + DrawSaveButton(buttonSize); + ImGui.SameLine(); + DrawCancelButton(buttonSize); + } + + private void DrawSaveButton(Vector2 buttonSize) + { + if (!ImUtf8.ButtonEx("Save"u8, _hasBeenEdited ? [] : "No changes made yet."u8, buttonSize, !_hasBeenEdited)) + return; + + switch (_current) + { + case Mod mod: + modManager.DataEditor.ChangeModDescription(mod, _description); + break; + case IModGroup group: + modManager.OptionEditor.ChangeGroupDescription(group, _description); + break; + case IModOption option: + modManager.OptionEditor.ChangeOptionDescription(option, _description); + break; + } + + _description = string.Empty; + _hasBeenEdited = false; + ImGui.CloseCurrentPopup(); + } + + private void DrawCancelButton(Vector2 buttonSize) + { + if (!ImUtf8.Button("Cancel"u8, buttonSize) && !ImGui.IsKeyPressed(ImGuiKey.Escape)) + return; + + _description = string.Empty; + _hasBeenEdited = false; + ImGui.CloseCurrentPopup(); + } +} diff --git a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs index 6b62d5b8..5652fa98 100644 --- a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs @@ -1,11 +1,12 @@ using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; -using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; +using OtterGui.Text.EndObjects; using Penumbra.Mods; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; @@ -17,87 +18,79 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; -public sealed class ModGroupEditDrawer(ModManager modManager, Configuration config, FilenameService filenames) : IUiService +public sealed class ModGroupEditDrawer( + ModManager modManager, + Configuration config, + FilenameService filenames, + DescriptionEditPopup descriptionPopup) : IUiService { + private static ReadOnlySpan DragDropLabel + => "##DragOption"u8; + private Vector2 _buttonSize; + private Vector2 _availableWidth; private float _priorityWidth; private float _groupNameWidth; + private float _optionNameWidth; private float _spacing; + private Vector2 _optionIdxSelectable; + private bool _deleteEnabled; private string? _currentGroupName; private ModPriority? _currentGroupPriority; private IModGroup? _currentGroupEdited; - private bool _isGroupNameValid; - private IModGroup? _deleteGroup; - private IModGroup? _moveGroup; - private int _moveTo; + private bool _isGroupNameValid = true; - private string? _currentOptionName; - private ModPriority? _currentOptionPriority; - private IModOption? _currentOptionEdited; - private IModOption? _deleteOption; + private string? _newOptionName; + private IModGroup? _newOptionGroup; + private readonly Queue _actionQueue = new(); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void SameLine() - => ImGui.SameLine(0, _spacing); + private IModGroup? _dragDropGroup; + private IModOption? _dragDropOption; public void Draw(Mod mod) { - _buttonSize = new Vector2(ImGui.GetFrameHeight()); - _priorityWidth = 50 * ImGuiHelpers.GlobalScale; - _groupNameWidth = 350f * ImGuiHelpers.GlobalScale; - _spacing = ImGui.GetStyle().ItemInnerSpacing.X; + PrepareStyle(); + using var id = ImUtf8.PushId("##GroupEdit"u8); + foreach (var (group, groupIdx) in mod.Groups.WithIndex()) + DrawGroup(group, groupIdx); - FinishGroupCleanup(); - } - - private void FinishGroupCleanup() - { - if (_deleteGroup != null) - { - modManager.OptionEditor.DeleteModGroup(_deleteGroup); - _deleteGroup = null; - } - - if (_deleteOption != null) - { - modManager.OptionEditor.DeleteOption(_deleteOption); - _deleteOption = null; - } - - if (_moveGroup != null) - { - modManager.OptionEditor.MoveModGroup(_moveGroup, _moveTo); - _moveGroup = null; - } + while (_actionQueue.TryDequeue(out var action)) + action.Invoke(); } private void DrawGroup(IModGroup group, int idx) { - using var id = ImRaii.PushId(idx); + using var id = ImUtf8.PushId(idx); using var frame = ImRaii.FramedGroup($"Group #{idx + 1}"); - DrawGroupNameRow(group); + DrawGroupNameRow(group, idx); switch (group) { case SingleModGroup s: - DrawSingleGroup(s, idx); + DrawSingleGroup(s); break; case MultiModGroup m: - DrawMultiGroup(m, idx); + DrawMultiGroup(m); break; case ImcModGroup i: - DrawImcGroup(i, idx); + DrawImcGroup(i); break; } } - private void DrawGroupNameRow(IModGroup group) + private void DrawGroupNameRow(IModGroup group, int idx) { DrawGroupName(group); - SameLine(); + ImUtf8.SameLineInner(); + DrawGroupMoveButtons(group, idx); + ImUtf8.SameLineInner(); + DrawGroupOpenFile(group, idx); + ImUtf8.SameLineInner(); + DrawGroupDescription(group); + ImUtf8.SameLineInner(); DrawGroupDelete(group); - SameLine(); + ImUtf8.SameLineInner(); DrawGroupPriority(group); } @@ -106,11 +99,11 @@ public sealed class ModGroupEditDrawer(ModManager modManager, Configuration conf var text = _currentGroupEdited == group ? _currentGroupName ?? group.Name : group.Name; ImGui.SetNextItemWidth(_groupNameWidth); using var border = ImRaii.PushFrameBorder(UiHelpers.ScaleX2, Colors.RegexWarningBorder, !_isGroupNameValid); - if (ImGui.InputText("##GroupName", ref text, 256)) + if (ImUtf8.InputText("##GroupName"u8, ref text)) { _currentGroupEdited = group; _currentGroupName = text; - _isGroupNameValid = ModGroupEditor.VerifyFileName(group.Mod, group, text, false); + _isGroupNameValid = text == group.Name || ModGroupEditor.VerifyFileName(group.Mod, group, text, false); } if (ImGui.IsItemDeactivated()) @@ -123,20 +116,21 @@ public sealed class ModGroupEditDrawer(ModManager modManager, Configuration conf } var tt = _isGroupNameValid - ? "Group Name" - : "Current name can not be used for this group."; - ImGuiUtil.HoverTooltip(tt); + ? "Change the Group name."u8 + : "Current name can not be used for this group."u8; + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tt); } private void DrawGroupDelete(IModGroup group) { - var enabled = config.DeleteModModifier.IsActive(); - var tt = enabled - ? "Delete this option group." - : $"Delete this option group.\nHold {config.DeleteModModifier} while clicking to delete."; + if (ImUtf8.IconButton(FontAwesomeIcon.Trash, !_deleteEnabled)) + _actionQueue.Enqueue(() => modManager.OptionEditor.DeleteModGroup(group)); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), _buttonSize, tt, !enabled, true)) - _deleteGroup = group; + if (_deleteEnabled) + ImUtf8.HoverTooltip("Delete this option group."u8); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + $"Delete this option group.\nHold {config.DeleteModModifier} while clicking to delete."); } private void DrawGroupPriority(IModGroup group) @@ -162,36 +156,41 @@ public sealed class ModGroupEditDrawer(ModManager modManager, Configuration conf ImGuiUtil.HoverTooltip("Group Priority"); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawGroupDescription(IModGroup group) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Edit, "Edit group description."u8)) + descriptionPopup.Open(group); + } + private void DrawGroupMoveButtons(IModGroup group, int idx) { var isFirst = idx == 0; - var tt = isFirst ? "Can not move this group further upwards." : $"Move this group up to group {idx}."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowUp.ToIconString(), UiHelpers.IconButtonSize, tt, isFirst, true)) - { - _moveGroup = group; - _moveTo = idx - 1; - } + if (ImUtf8.IconButton(FontAwesomeIcon.ArrowUp, isFirst)) + _actionQueue.Enqueue(() => modManager.OptionEditor.MoveModGroup(group, idx - 1)); - SameLine(); + if (isFirst) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Can not move this group further upwards."u8); + else + ImUtf8.HoverTooltip($"Move this group up to group {idx}."); + + + ImUtf8.SameLineInner(); var isLast = idx == group.Mod.Groups.Count - 1; - tt = isLast - ? "Can not move this group further downwards." - : $"Move this group down to group {idx + 2}."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowDown.ToIconString(), UiHelpers.IconButtonSize, tt, isLast, true)) - { - _moveGroup = group; - _moveTo = idx + 1; - } + if (ImUtf8.IconButton(FontAwesomeIcon.ArrowDown, isLast)) + _actionQueue.Enqueue(() => modManager.OptionEditor.MoveModGroup(group, idx + 1)); + + if (isLast) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Can not move this group further downwards."u8); + else + ImUtf8.HoverTooltip($"Move this group down to group {idx + 2}."); } private void DrawGroupOpenFile(IModGroup group, int idx) { var fileName = filenames.OptionGroupFile(group.Mod, idx, config.ReplaceNonAsciiOnImport); var fileExists = File.Exists(fileName); - var tt = fileExists - ? $"Open the {group.Name} json file in the text editor of your choice." - : $"The {group.Name} json file does not exist."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileExport.ToIconString(), UiHelpers.IconButtonSize, tt, !fileExists, true)) + if (ImUtf8.IconButton(FontAwesomeIcon.FileExport, !fileExists)) try { Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); @@ -200,15 +199,274 @@ public sealed class ModGroupEditDrawer(ModManager modManager, Configuration conf { Penumbra.Messager.NotificationMessage(e, "Could not open editor.", NotificationType.Error); } + + if (fileExists) + ImUtf8.HoverTooltip($"Open the {group.Name} json file in the text editor of your choice."); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"The {group.Name} json file does not exist."); } + private void DrawSingleGroup(SingleModGroup group) + { + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImRaii.PushId(optionIdx); + DrawOptionPosition(group, option, optionIdx); - private void DrawSingleGroup(SingleModGroup group, int idx) - { } + ImUtf8.SameLineInner(); + DrawOptionDefaultSingleBehaviour(group, option, optionIdx); - private void DrawMultiGroup(MultiModGroup group, int idx) - { } + ImUtf8.SameLineInner(); + DrawOptionName(option); - private void DrawImcGroup(ImcModGroup group, int idx) - { } + ImUtf8.SameLineInner(); + DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + DrawOptionDelete(option); + + ImUtf8.SameLineInner(); + ImGui.Dummy(new Vector2(_priorityWidth, 0)); + } + + DrawNewOption(group); + var convertible = group.Options.Count <= IModGroup.MaxMultiOptions; + if (ImUtf8.ButtonEx("Convert to Multi Group", _availableWidth, !convertible)) + _actionQueue.Enqueue(() => modManager.OptionEditor.SingleEditor.ChangeToMulti(group)); + if (!convertible) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + "Can not convert to multi group since maximum number of options is exceeded."u8); + } + + private void DrawMultiGroup(MultiModGroup group) + { + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImRaii.PushId(optionIdx); + DrawOptionPosition(group, option, optionIdx); + + ImUtf8.SameLineInner(); + DrawOptionDefaultMultiBehaviour(group, option, optionIdx); + + ImUtf8.SameLineInner(); + DrawOptionName(option); + + ImUtf8.SameLineInner(); + DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + DrawOptionDelete(option); + + ImUtf8.SameLineInner(); + DrawOptionPriority(option); + } + + DrawNewOption(group); + if (ImUtf8.Button("Convert to Single Group"u8, _availableWidth)) + _actionQueue.Enqueue(() => modManager.OptionEditor.MultiEditor.ChangeToSingle(group)); + } + + private void DrawImcGroup(ImcModGroup group) + { + // TODO + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionPosition(IModGroup group, IModOption option, int optionIdx) + { + ImGui.AlignTextToFramePadding(); + ImUtf8.Selectable($"Option #{optionIdx + 1}", false, size: _optionIdxSelectable); + Target(group, optionIdx); + Source(option); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionDefaultSingleBehaviour(IModGroup group, IModOption option, int optionIdx) + { + var isDefaultOption = group.DefaultSettings.AsIndex == optionIdx; + if (ImUtf8.RadioButton("##default"u8, isDefaultOption)) + modManager.OptionEditor.ChangeModGroupDefaultOption(group, Setting.Single(optionIdx)); + ImUtf8.HoverTooltip($"Set {option.Name} as the default choice for this group."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionDefaultMultiBehaviour(IModGroup group, IModOption option, int optionIdx) + { + var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); + if (ImUtf8.Checkbox("##default"u8, ref isDefaultOption)) + modManager.OptionEditor.ChangeModGroupDefaultOption(group, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); + ImUtf8.HoverTooltip($"{(isDefaultOption ? "Disable"u8 : "Enable"u8)} {option.Name} per default in this group."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionDescription(IModOption option) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Edit, "Edit option description."u8)) + descriptionPopup.Open(option); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionPriority(MultiSubMod option) + { + var priority = option.Priority.Value; + ImGui.SetNextItemWidth(_priorityWidth); + if (ImUtf8.InputScalarOnDeactivated("##Priority"u8, ref priority)) + modManager.OptionEditor.MultiEditor.ChangeOptionPriority(option, new ModPriority(priority)); + ImUtf8.HoverTooltip("Option priority inside the mod."u8); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionName(IModOption option) + { + var name = option.Name; + ImGui.SetNextItemWidth(_optionNameWidth); + if (ImUtf8.InputTextOnDeactivated("##Name"u8, ref name)) + modManager.OptionEditor.RenameOption(option, name); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawOptionDelete(IModOption option) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Trash, !_deleteEnabled)) + _actionQueue.Enqueue(() => modManager.OptionEditor.DeleteOption(option)); + + if (_deleteEnabled) + ImUtf8.HoverTooltip("Delete this option."u8); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + $"Delete this option.\nHold {config.DeleteModModifier} while clicking to delete."); + } + + private void DrawNewOption(SingleModGroup group) + { + var count = group.Options.Count; + if (count >= int.MaxValue) + return; + + DrawNewOptionBase(group, count); + + var validName = _newOptionName?.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, !validName)) + { + modManager.OptionEditor.SingleEditor.AddOption(group, _newOptionName!); + _newOptionName = null; + } + } + + private void DrawNewOption(MultiModGroup group) + { + var count = group.Options.Count; + if (count >= IModGroup.MaxMultiOptions) + return; + + DrawNewOptionBase(group, count); + + var validName = _newOptionName?.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, !validName)) + { + modManager.OptionEditor.MultiEditor.AddOption(group, _newOptionName!); + _newOptionName = null; + } + } + + private void DrawNewOption(ImcModGroup group) + { + // TODO + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawNewOptionBase(IModGroup group, int count) + { + ImUtf8.Selectable($"Option #{count + 1}", false, size: _optionIdxSelectable); + Target(group, count); + + ImUtf8.SameLineInner(); + ImUtf8.IconDummy(); + + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(_optionNameWidth); + var newName = _newOptionGroup == group + ? _newOptionName ?? string.Empty + : string.Empty; + if (ImUtf8.InputText("##newOption"u8, ref newName, "Add new option..."u8)) + { + _newOptionName = newName; + _newOptionGroup = group; + } + + ImUtf8.SameLineInner(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Source(IModOption option) + { + if (option.Group is not ITexToolsGroup) + return; + + using var source = ImUtf8.DragDropSource(); + if (!source) + return; + + if (!DragDropSource.SetPayload(DragDropLabel)) + { + _dragDropGroup = option.Group; + _dragDropOption = option; + } + + ImGui.TextUnformatted($"Dragging option {option.Name} from group {option.Group.Name}..."); + } + + private void Target(IModGroup group, int optionIdx) + { + if (group is not ITexToolsGroup) + return; + + if (_dragDropGroup != group && _dragDropGroup != null && group is MultiModGroup { Options.Count: >= IModGroup.MaxMultiOptions }) + return; + + using var target = ImRaii.DragDropTarget(); + if (!target.Success || !DragDropTarget.CheckPayload(DragDropLabel)) + return; + + if (_dragDropGroup != null && _dragDropOption != null) + { + if (_dragDropGroup == group) + { + var sourceOption = _dragDropOption; + _actionQueue.Enqueue(() => modManager.OptionEditor.MoveOption(sourceOption, optionIdx)); + } + else + { + // Move from one group to another by deleting, then adding, then moving the option. + var sourceOption = _dragDropOption; + _actionQueue.Enqueue(() => + { + modManager.OptionEditor.DeleteOption(sourceOption); + if (modManager.OptionEditor.AddOption(group, sourceOption) is { } newOption) + modManager.OptionEditor.MoveOption(newOption, optionIdx); + }); + } + } + + _dragDropGroup = null; + _dragDropOption = null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void PrepareStyle() + { + var totalWidth = 400f * ImUtf8.GlobalScale; + _buttonSize = new Vector2(ImUtf8.FrameHeight); + _priorityWidth = 50 * ImUtf8.GlobalScale; + _availableWidth = new Vector2(totalWidth + 3 * _spacing + 2 * _buttonSize.X + _priorityWidth, 0); + _groupNameWidth = totalWidth - 3 * (_buttonSize.X + _spacing); + _spacing = ImGui.GetStyle().ItemInnerSpacing.X; + _optionIdxSelectable = ImUtf8.CalcTextSize("Option #88."u8); + _optionNameWidth = totalWidth - _optionIdxSelectable.X - _buttonSize.X - 2 * _spacing; + _deleteEnabled = config.DeleteModModifier.IsActive(); + } } diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 862852fa..a5db15b6 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -1,21 +1,17 @@ using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.Internal.Notifications; -using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; using OtterGui.Classes; -using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.AdvancedWindow; -using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; -using Penumbra.Mods.SubMods; using Penumbra.Mods.Manager.OptionEditor; namespace Penumbra.UI.ModsTab; @@ -30,15 +26,13 @@ public class ModPanelEditTab( FilenameService filenames, ModExportManager modExportManager, Configuration config, - PredefinedTagManager predefinedTagManager) + PredefinedTagManager predefinedTagManager, + ModGroupEditDrawer groupEditDrawer, + DescriptionEditPopup descriptionPopup) : ITab { - private readonly ModManager _modManager = modManager; - private readonly TagButtons _modTags = new(); - private Vector2 _cellPadding = Vector2.Zero; - private Vector2 _itemSpacing = Vector2.Zero; private ModFileSystem.Leaf _leaf = null!; private Mod _mod = null!; @@ -54,9 +48,6 @@ public class ModPanelEditTab( _leaf = selector.SelectedLeaf!; _mod = selector.Selected!; - _cellPadding = ImGui.GetStyle().CellPadding with { X = 2 * UiHelpers.Scale }; - _itemSpacing = ImGui.GetStyle().CellPadding with { X = 4 * UiHelpers.Scale }; - EditButtons(); EditRegularMeta(); UiHelpers.DefaultLineSpace(); @@ -77,21 +68,18 @@ public class ModPanelEditTab( var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); if (tagIdx >= 0) - _modManager.DataEditor.ChangeModTag(_mod, tagIdx, editedTag); + modManager.DataEditor.ChangeModTag(_mod, tagIdx, editedTag); if (sharedTagsEnabled) predefinedTagManager.DrawAddFromSharedTagsAndUpdateTags(selector.Selected!.LocalTags, selector.Selected!.ModTags, false, selector.Selected!); UiHelpers.DefaultLineSpace(); - AddOptionGroup.Draw(filenames, _modManager, _mod, config.ReplaceNonAsciiOnImport); + AddOptionGroup.Draw(filenames, modManager, _mod, config.ReplaceNonAsciiOnImport); UiHelpers.DefaultLineSpace(); - for (var groupIdx = 0; groupIdx < _mod.Groups.Count; ++groupIdx) - EditGroup(groupIdx); - - EndActions(); - DescriptionEdit.DrawPopup(_modManager); + groupEditDrawer.Draw(_mod); + descriptionPopup.Draw(); } public void Reset() @@ -99,7 +87,6 @@ public class ModPanelEditTab( AddOptionGroup.Reset(); MoveDirectory.Reset(); Input.Reset(); - OptionTable.Reset(); } /// The general edit row for non-detailed mod edits. @@ -117,10 +104,10 @@ public class ModPanelEditTab( if (ImGuiUtil.DrawDisabledButton("Reload Mod", buttonSize, "Reload the current mod from its files.\n" + "If the mod directory or meta file do not exist anymore or if the new mod name is empty, the mod is deleted instead.", false)) - _modManager.ReloadMod(_mod); + modManager.ReloadMod(_mod); BackupButtons(buttonSize); - MoveDirectory.Draw(_modManager, _mod, buttonSize); + MoveDirectory.Draw(modManager, _mod, buttonSize); UiHelpers.DefaultLineSpace(); DrawUpdateBibo(buttonSize); @@ -169,7 +156,7 @@ public class ModPanelEditTab( : $"Exported mod \"{backup.Name}\" does not exist."; ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Restore From Export", buttonSize, tt, !backup.Exists || !config.DeleteModModifier.IsActive())) - backup.Restore(_modManager); + backup.Restore(modManager); if (backup.Exists) { ImGui.SameLine(); @@ -186,24 +173,24 @@ public class ModPanelEditTab( private void EditRegularMeta() { if (Input.Text("Name", Input.Name, Input.None, _mod.Name, out var newName, 256, UiHelpers.InputTextWidth.X)) - _modManager.DataEditor.ChangeModName(_mod, newName); + modManager.DataEditor.ChangeModName(_mod, newName); if (Input.Text("Author", Input.Author, Input.None, _mod.Author, out var newAuthor, 256, UiHelpers.InputTextWidth.X)) - _modManager.DataEditor.ChangeModAuthor(_mod, newAuthor); + modManager.DataEditor.ChangeModAuthor(_mod, newAuthor); if (Input.Text("Version", Input.Version, Input.None, _mod.Version, out var newVersion, 32, UiHelpers.InputTextWidth.X)) - _modManager.DataEditor.ChangeModVersion(_mod, newVersion); + modManager.DataEditor.ChangeModVersion(_mod, newVersion); if (Input.Text("Website", Input.Website, Input.None, _mod.Website, out var newWebsite, 256, UiHelpers.InputTextWidth.X)) - _modManager.DataEditor.ChangeModWebsite(_mod, newWebsite); + modManager.DataEditor.ChangeModWebsite(_mod, newWebsite); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3)); var reducedSize = new Vector2(UiHelpers.InputTextMinusButton3, 0); if (ImGui.Button("Edit Description", reducedSize)) - _delayedActions.Enqueue(() => DescriptionEdit.OpenPopup(_mod, Input.Description)); + descriptionPopup.Open(_mod); ImGui.SameLine(); var fileExists = File.Exists(filenames.ModMetaPath(_mod)); @@ -215,16 +202,6 @@ public class ModPanelEditTab( Process.Start(new ProcessStartInfo(filenames.ModMetaPath(_mod)) { UseShellExecute = true }); } - /// Do some edits outside of iterations. - private readonly Queue _delayedActions = new(); - - /// Delete a marked group or option outside of iteration. - private void EndActions() - { - while (_delayedActions.TryDequeue(out var action)) - action.Invoke(); - } - /// Text input to add a new option group at the end of the current groups. private static class AddOptionGroup { @@ -309,372 +286,6 @@ public class ModPanelEditTab( } } - /// Open a popup to edit a multi-line mod or option description. - private static class DescriptionEdit - { - private const string PopupName = "Edit Description"; - private static string _newDescription = string.Empty; - private static string _oldDescription = string.Empty; - private static int _newDescriptionIdx = -1; - private static int _newDescriptionOptionIdx = -1; - private static Mod? _mod; - - public static void OpenPopup(Mod mod, int groupIdx, int optionIdx = -1) - { - _newDescriptionIdx = groupIdx; - _newDescriptionOptionIdx = optionIdx; - _newDescription = groupIdx < 0 - ? mod.Description - : optionIdx < 0 - ? mod.Groups[groupIdx].Description - : mod.Groups[groupIdx].Options[optionIdx].Description; - _oldDescription = _newDescription; - - _mod = mod; - ImGui.OpenPopup(PopupName); - } - - public static void DrawPopup(ModManager modManager) - { - if (_mod == null) - return; - - using var popup = ImRaii.Popup(PopupName); - if (!popup) - return; - - if (ImGui.IsWindowAppearing()) - ImGui.SetKeyboardFocusHere(); - - ImGui.InputTextMultiline("##editDescription", ref _newDescription, 4096, ImGuiHelpers.ScaledVector2(800, 800)); - UiHelpers.DefaultLineSpace(); - - var buttonSize = ImGuiHelpers.ScaledVector2(100, 0); - var width = 2 * buttonSize.X - + 4 * ImGui.GetStyle().FramePadding.X - + ImGui.GetStyle().ItemSpacing.X; - ImGui.SetCursorPosX((800 * UiHelpers.Scale - width) / 2); - - var tooltip = _newDescription != _oldDescription ? string.Empty : "No changes made yet."; - - if (ImGuiUtil.DrawDisabledButton("Save", buttonSize, tooltip, tooltip.Length > 0)) - { - switch (_newDescriptionIdx) - { - case Input.Description: - modManager.DataEditor.ChangeModDescription(_mod, _newDescription); - break; - case >= 0: - if (_newDescriptionOptionIdx < 0) - modManager.OptionEditor.ChangeGroupDescription(_mod.Groups[_newDescriptionIdx], _newDescription); - else - modManager.OptionEditor.ChangeOptionDescription(_mod.Groups[_newDescriptionIdx].Options[_newDescriptionOptionIdx], - _newDescription); - - break; - } - - ImGui.CloseCurrentPopup(); - } - - ImGui.SameLine(); - if (!ImGui.Button("Cancel", buttonSize) - && !ImGui.IsKeyPressed(ImGuiKey.Escape)) - return; - - _newDescriptionIdx = Input.None; - _newDescription = string.Empty; - ImGui.CloseCurrentPopup(); - } - } - - private void EditGroup(int groupIdx) - { - var group = _mod.Groups[groupIdx]; - using var id = ImRaii.PushId(groupIdx); - using var frame = ImRaii.FramedGroup($"Group #{groupIdx + 1}"); - - using var style = ImRaii.PushStyle(ImGuiStyleVar.CellPadding, _cellPadding) - .Push(ImGuiStyleVar.ItemSpacing, _itemSpacing); - - if (Input.Text("##Name", groupIdx, Input.None, group.Name, out var newGroupName, 256, UiHelpers.InputTextWidth.X)) - _modManager.OptionEditor.RenameModGroup(group, newGroupName); - - ImGuiUtil.HoverTooltip("Group Name"); - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, - "Delete this option group.\nHold Control while clicking to delete.", !ImGui.GetIO().KeyCtrl, true)) - _delayedActions.Enqueue(() => _modManager.OptionEditor.DeleteModGroup(group)); - - ImGui.SameLine(); - - if (Input.Priority("##Priority", groupIdx, Input.None, group.Priority, out var priority, 50 * UiHelpers.Scale)) - _modManager.OptionEditor.ChangeGroupPriority(group, priority); - - ImGuiUtil.HoverTooltip("Group Priority"); - - DrawGroupCombo(group, groupIdx); - ImGui.SameLine(); - - var tt = groupIdx == 0 ? "Can not move this group further upwards." : $"Move this group up to group {groupIdx}."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowUp.ToIconString(), UiHelpers.IconButtonSize, - tt, groupIdx == 0, true)) - _delayedActions.Enqueue(() => _modManager.OptionEditor.MoveModGroup(group, groupIdx - 1)); - - ImGui.SameLine(); - tt = groupIdx == _mod.Groups.Count - 1 - ? "Can not move this group further downwards." - : $"Move this group down to group {groupIdx + 2}."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.ArrowDown.ToIconString(), UiHelpers.IconButtonSize, - tt, groupIdx == _mod.Groups.Count - 1, true)) - _delayedActions.Enqueue(() => _modManager.OptionEditor.MoveModGroup(group, groupIdx + 1)); - - ImGui.SameLine(); - - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Edit.ToIconString(), UiHelpers.IconButtonSize, - "Edit group description.", false, true)) - _delayedActions.Enqueue(() => DescriptionEdit.OpenPopup(_mod, groupIdx)); - - ImGui.SameLine(); - var fileName = filenames.OptionGroupFile(_mod, groupIdx, config.ReplaceNonAsciiOnImport); - var fileExists = File.Exists(fileName); - tt = fileExists - ? $"Open the {group.Name} json file in the text editor of your choice." - : $"The {group.Name} json file does not exist."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileExport.ToIconString(), UiHelpers.IconButtonSize, tt, !fileExists, true)) - Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); - - UiHelpers.DefaultLineSpace(); - - OptionTable.Draw(this, groupIdx); - } - - /// Draw the table displaying all options and the add new option line. - private static class OptionTable - { - private const string DragDropLabel = "##DragOption"; - - private static int _newOptionNameIdx = -1; - private static string _newOptionName = string.Empty; - private static IModGroup? _dragDropGroup; - private static IModOption? _dragDropOption; - - public static void Reset() - { - _newOptionNameIdx = -1; - _newOptionName = string.Empty; - _dragDropGroup = null; - _dragDropOption = null; - } - - public static void Draw(ModPanelEditTab panel, int groupIdx) - { - using var table = ImRaii.Table(string.Empty, 6, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - var maxWidth = ImGui.CalcTextSize("Option #88.").X; - ImGui.TableSetupColumn("idx", ImGuiTableColumnFlags.WidthFixed, maxWidth); - ImGui.TableSetupColumn("default", ImGuiTableColumnFlags.WidthFixed, ImGui.GetFrameHeight()); - ImGui.TableSetupColumn("name", ImGuiTableColumnFlags.WidthFixed, - UiHelpers.InputTextWidth.X - maxWidth - 12 * UiHelpers.Scale - ImGui.GetFrameHeight() - UiHelpers.IconButtonSize.X); - ImGui.TableSetupColumn("description", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); - ImGui.TableSetupColumn("delete", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); - ImGui.TableSetupColumn("priority", ImGuiTableColumnFlags.WidthFixed, 50 * UiHelpers.Scale); - - switch (panel._mod.Groups[groupIdx]) - { - case SingleModGroup single: - for (var optionIdx = 0; optionIdx < single.OptionData.Count; ++optionIdx) - EditOption(panel, single, groupIdx, optionIdx); - break; - case MultiModGroup multi: - for (var optionIdx = 0; optionIdx < multi.OptionData.Count; ++optionIdx) - EditOption(panel, multi, groupIdx, optionIdx); - break; - } - - DrawNewOption(panel, groupIdx, UiHelpers.IconButtonSize); - } - - /// Draw a line for a single option. - private static void EditOption(ModPanelEditTab panel, IModGroup group, int groupIdx, int optionIdx) - { - var option = group.Options[optionIdx]; - using var id = ImRaii.PushId(optionIdx); - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.Selectable($"Option #{optionIdx + 1}"); - Source(option); - Target(panel, group, optionIdx); - - ImGui.TableNextColumn(); - - - if (group.Type == GroupType.Single) - { - if (ImGui.RadioButton("##default", group.DefaultSettings.AsIndex == optionIdx)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(group, Setting.Single(optionIdx)); - - ImGuiUtil.HoverTooltip($"Set {option.Name} as the default choice for this group."); - } - else - { - var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); - if (ImGui.Checkbox("##default", ref isDefaultOption)) - panel._modManager.OptionEditor.ChangeModGroupDefaultOption(group, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); - - ImGuiUtil.HoverTooltip($"{(isDefaultOption ? "Disable" : "Enable")} {option.Name} per default in this group."); - } - - ImGui.TableNextColumn(); - if (Input.Text("##Name", groupIdx, optionIdx, option.Name, out var newOptionName, 256, -1)) - panel._modManager.OptionEditor.RenameOption(option, newOptionName); - - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Edit.ToIconString(), UiHelpers.IconButtonSize, "Edit option description.", - false, true)) - panel._delayedActions.Enqueue(() => DescriptionEdit.OpenPopup(panel._mod, groupIdx, optionIdx)); - - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), UiHelpers.IconButtonSize, - "Delete this option.\nHold Control while clicking to delete.", !ImGui.GetIO().KeyCtrl, true)) - panel._delayedActions.Enqueue(() => panel._modManager.OptionEditor.DeleteOption(option)); - - ImGui.TableNextColumn(); - if (option is not MultiSubMod multi) - return; - - if (Input.Priority("##Priority", groupIdx, optionIdx, multi.Priority, out var priority, - 50 * UiHelpers.Scale)) - panel._modManager.OptionEditor.MultiEditor.ChangeOptionPriority(multi, priority); - - ImGuiUtil.HoverTooltip("Option priority."); - } - - /// Draw the line to add a new option. - private static void DrawNewOption(ModPanelEditTab panel, int groupIdx, Vector2 iconButtonSize) - { - var mod = panel._mod; - var group = mod.Groups[groupIdx]; - var count = group switch - { - SingleModGroup single => single.OptionData.Count, - MultiModGroup multi => multi.OptionData.Count, - _ => throw new Exception($"Dragging options to an option group of type {group.GetType()} is not supported."), - }; - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.Selectable($"Option #{count + 1}"); - Target(panel, group, count); - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(-1); - var tmp = _newOptionNameIdx == groupIdx ? _newOptionName : string.Empty; - if (ImGui.InputTextWithHint("##newOption", "Add new option...", ref tmp, 256)) - { - _newOptionName = tmp; - _newOptionNameIdx = groupIdx; - } - - ImGui.TableNextColumn(); - var canAddGroup = mod.Groups[groupIdx].Type != GroupType.Multi || count < IModGroup.MaxMultiOptions; - var validName = _newOptionName.Length > 0 && _newOptionNameIdx == groupIdx; - var tt = canAddGroup - ? validName ? "Add a new option to this group." : "Please enter a name for the new option." - : $"Can not add more than {IModGroup.MaxMultiOptions} options to a multi group."; - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconButtonSize, - tt, !(canAddGroup && validName), true)) - return; - - panel._modManager.OptionEditor.AddOption(group, _newOptionName); - _newOptionName = string.Empty; - } - - // Handle drag and drop to move options inside a group or into another group. - private static void Source(IModOption option) - { - if (option.Group is not ITexToolsGroup) - return; - - using var source = ImRaii.DragDropSource(); - if (!source) - return; - - if (ImGui.SetDragDropPayload(DragDropLabel, IntPtr.Zero, 0)) - { - _dragDropGroup = option.Group; - _dragDropOption = option; - } - - ImGui.TextUnformatted($"Dragging option {option.Name} from group {option.Group.Name}..."); - } - - private static void Target(ModPanelEditTab panel, IModGroup group, int optionIdx) - { - if (group is not ITexToolsGroup) - return; - - using var target = ImRaii.DragDropTarget(); - if (!target.Success || !ImGuiUtil.IsDropping(DragDropLabel)) - return; - - if (_dragDropGroup != null && _dragDropOption != null) - { - if (_dragDropGroup == group) - { - var sourceOption = _dragDropOption; - panel._delayedActions.Enqueue( - () => panel._modManager.OptionEditor.MoveOption(sourceOption, optionIdx)); - } - else - { - // Move from one group to another by deleting, then adding, then moving the option. - var sourceOption = _dragDropOption; - panel._delayedActions.Enqueue(() => - { - panel._modManager.OptionEditor.DeleteOption(sourceOption); - if (panel._modManager.OptionEditor.AddOption(group, sourceOption) is { } newOption) - panel._modManager.OptionEditor.MoveOption(newOption, optionIdx); - }); - } - } - - _dragDropGroup = null; - _dragDropOption = null; - } - } - - /// Draw a combo to select single or multi group and switch between them. - private void DrawGroupCombo(IModGroup group, int groupIdx) - { - ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X - 2 * UiHelpers.IconButtonSize.X - 2 * ImGui.GetStyle().ItemSpacing.X); - using var combo = ImRaii.Combo("##GroupType", GroupTypeName(group.Type)); - if (!combo) - return; - - if (ImGui.Selectable(GroupTypeName(GroupType.Single), group.Type == GroupType.Single) && group is MultiModGroup m) - _modManager.OptionEditor.MultiEditor.ChangeToSingle(m); - - var canSwitchToMulti = group.Options.Count <= IModGroup.MaxMultiOptions; - using var style = ImRaii.PushStyle(ImGuiStyleVar.Alpha, 0.5f, !canSwitchToMulti); - if (ImGui.Selectable(GroupTypeName(GroupType.Multi), group.Type == GroupType.Multi) && canSwitchToMulti && group is SingleModGroup s) - _modManager.OptionEditor.SingleEditor.ChangeToMulti(s); - - style.Pop(); - if (!canSwitchToMulti) - ImGuiUtil.HoverTooltip($"Can not convert group to multi group since it has more than {IModGroup.MaxMultiOptions} options."); - return; - - static string GroupTypeName(GroupType type) - => type switch - { - GroupType.Single => "Single Group", - GroupType.Multi => "Multi Group", - _ => "Unknown", - }; - } - /// Handles input text and integers in separate fields without buffers for every single one. private static class Input { @@ -705,6 +316,7 @@ public class ModPanelEditTab( { var tmp = field == _currentField && option == _optionIndex ? _currentEdit ?? oldValue : oldValue; ImGui.SetNextItemWidth(width); + if (ImGui.InputText(label, ref tmp, maxLength)) { _currentEdit = tmp; From df6eb3fdd2f4afac8b8b5e911b137ce0b9d54280 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 16 May 2024 18:30:40 +0200 Subject: [PATCH 0601/1381] Add some early support for IMC groups. --- OtterGui | 2 +- Penumbra/Collections/Cache/ImcCache.cs | 4 +- .../Import/TexToolsMeta.Deserialization.cs | 2 +- .../Meta/Manipulations/ImcManipulation.cs | 4 +- .../Meta/Manipulations/MetaManipulation.cs | 4 +- Penumbra/Mods/Groups/ImcModGroup.cs | 43 ++++ .../Manager/OptionEditor/ImcModGroupEditor.cs | 33 ++- .../Manager/OptionEditor/ModGroupEditor.cs | 2 +- Penumbra/Mods/ModCreator.cs | 1 + Penumbra/Mods/SubMods/ImcSubMod.cs | 7 + Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 4 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 80 +----- Penumbra/UI/Classes/Combos.cs | 40 ++- Penumbra/UI/ModsTab/ModGroupEditDrawer.cs | 238 +++++++++++++++++- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 42 +--- 15 files changed, 360 insertions(+), 146 deletions(-) diff --git a/OtterGui b/OtterGui index 866389b3..5028fba7 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 866389b3988d9c4926a786f6c78ac9d5265591ac +Subproject commit 5028fba767ca8febd75a1a5ebc312bd354efc81b diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index bc928360..843fe195 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -36,7 +36,7 @@ public readonly struct ImcCache : IDisposable public bool ApplyMod(MetaFileManager manager, ModCollection collection, ImcManipulation manip) { - if (!manip.Validate()) + if (!manip.Validate(true)) return false; var idx = _imcManipulations.FindIndex(p => p.Item1.Equals(manip)); @@ -77,7 +77,7 @@ public readonly struct ImcCache : IDisposable public bool RevertMod(MetaFileManager manager, ModCollection collection, ImcManipulation m) { - if (!m.Validate()) + if (!m.Validate(false)) return false; var idx = _imcManipulations.FindIndex(p => p.Item1.Equals(m)); diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index 64eff8ba..325c9143 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -120,7 +120,7 @@ public partial class TexToolsMeta { var imc = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, i, manip.EquipSlot, value); - if (imc.Validate()) + if (imc.Validate(true)) MetaManipulations.Add(imc); } diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs index a1c4b5bf..45295990 100644 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ b/Penumbra/Meta/Manipulations/ImcManipulation.cs @@ -146,7 +146,7 @@ public readonly struct ImcManipulation : IMetaManipulation public bool Apply(ImcFile file) => file.SetEntry(ImcFile.PartIndex(EquipSlot), Variant.Id, Entry); - public bool Validate() + public bool Validate(bool withMaterial) { switch (ObjectType) { @@ -178,7 +178,7 @@ public readonly struct ImcManipulation : IMetaManipulation break; } - if (Entry.MaterialId == 0) + if (withMaterial && Entry.MaterialId == 0) return false; return true; diff --git a/Penumbra/Meta/Manipulations/MetaManipulation.cs b/Penumbra/Meta/Manipulations/MetaManipulation.cs index e057d1a4..ed184d52 100644 --- a/Penumbra/Meta/Manipulations/MetaManipulation.cs +++ b/Penumbra/Meta/Manipulations/MetaManipulation.cs @@ -98,7 +98,7 @@ public readonly struct MetaManipulation : IEquatable, ICompara return; case ImcManipulation m: Imc = m; - ManipulationType = m.Validate() ? Type.Imc : Type.Unknown; + ManipulationType = m.Validate(true) ? Type.Imc : Type.Unknown; return; } } @@ -108,7 +108,7 @@ public readonly struct MetaManipulation : IEquatable, ICompara { return ManipulationType switch { - Type.Imc => Imc.Validate(), + Type.Imc => Imc.Validate(true), Type.Eqdp => Eqdp.Validate(), Type.Eqp => Eqp.Validate(), Type.Est => Est.Validate(), diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index e58d855a..21d8abe0 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -1,4 +1,7 @@ +using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -157,4 +160,44 @@ public class ImcModGroup(Mod mod) : IModGroup public (int Redirections, int Swaps, int Manips) GetCounts() => (0, 0, 1); + + public static ImcModGroup? Load(Mod mod, JObject json) + { + var options = json["Options"]; + var ret = new ImcModGroup(mod) + { + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, + DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, + ObjectType = json[nameof(ObjectType)]?.ToObject() ?? ObjectType.Unknown, + BodySlot = json[nameof(BodySlot)]?.ToObject() ?? BodySlot.Unknown, + EquipSlot = json[nameof(EquipSlot)]?.ToObject() ?? EquipSlot.Unknown, + PrimaryId = new PrimaryId(json[nameof(PrimaryId)]?.ToObject() ?? 0), + SecondaryId = new SecondaryId(json[nameof(SecondaryId)]?.ToObject() ?? 0), + Variant = new Variant(json[nameof(Variant)]?.ToObject() ?? 0), + CanBeDisabled = json[nameof(CanBeDisabled)]?.ToObject() ?? false, + DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), + }; + if (ret.Name.Length == 0) + return null; + + if (options != null) + foreach (var child in options.Children()) + { + var subMod = new ImcSubMod(ret, child); + ret.OptionData.Add(subMod); + } + + if (!new ImcManipulation(ret.ObjectType, ret.BodySlot, ret.PrimaryId, ret.SecondaryId.Id, ret.Variant.Id, ret.EquipSlot, + ret.DefaultEntry).Validate(true)) + { + Penumbra.Messager.NotificationMessage($"Could not add IMC group because the associated IMC Entry is invalid.", + NotificationType.Warning); + return null; + } + + ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); + return ret; + } } diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index 1194f961..f71547ba 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; +using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; @@ -11,13 +12,43 @@ namespace Penumbra.Mods.Manager.OptionEditor; public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) : ModOptionEditor(communicator, saveService, config), IService { + /// Add a new, empty imc group with the given manipulation data. + public ImcModGroup? AddModGroup(Mod mod, string newName, ImcManipulation manip, SaveType saveType = SaveType.ImmediateSync) + { + if (!ModGroupEditor.VerifyFileName(mod, null, newName, true)) + return null; + + var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; + var group = CreateGroup(mod, newName, manip, maxPriority); + mod.Groups.Add(group); + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, group, null, null, -1); + return group; + } + protected override ImcModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) => new(mod) { - Name = newName, + Name = newName, Priority = priority, }; + + private static ImcModGroup CreateGroup(Mod mod, string newName, ImcManipulation manip, ModPriority priority, + SaveType saveType = SaveType.ImmediateSync) + => new(mod) + { + Name = newName, + Priority = priority, + ObjectType = manip.ObjectType, + EquipSlot = manip.EquipSlot, + BodySlot = manip.BodySlot, + PrimaryId = manip.PrimaryId, + SecondaryId = manip.SecondaryId.Id, + Variant = manip.Variant, + DefaultEntry = manip.Entry, + }; + protected override ImcSubMod? CloneOption(ImcModGroup group, IModOption option) => null; diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index b2b48ac0..3c00dcc1 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -246,7 +246,7 @@ public class ModGroupEditor( { GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), - GroupType.Imc => ImcEditor.AddModGroup(mod, newName, saveType), + GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, saveType), _ => null, }; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 47261c6d..ed4245c4 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -434,6 +434,7 @@ public partial class ModCreator( { case GroupType.Multi: return MultiModGroup.Load(mod, json); case GroupType.Single: return SingleModGroup.Load(mod, json); + case GroupType.Imc: return ImcModGroup.Load(mod, json); } } catch (Exception e) diff --git a/Penumbra/Mods/SubMods/ImcSubMod.cs b/Penumbra/Mods/SubMods/ImcSubMod.cs index 167c8a6c..fca817aa 100644 --- a/Penumbra/Mods/SubMods/ImcSubMod.cs +++ b/Penumbra/Mods/SubMods/ImcSubMod.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json.Linq; using Penumbra.Mods.Groups; namespace Penumbra.Mods.SubMods; @@ -6,6 +7,12 @@ public class ImcSubMod(ImcModGroup group) : IModOption { public readonly ImcModGroup Group = group; + public ImcSubMod(ImcModGroup group, JToken json) + : this(group) + { + SubMod.LoadOptionData(json, this); + } + public Mod Mod => Group.Mod; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 4db0df47..6010cdaf 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -639,11 +639,11 @@ public class ItemSwapTab : IDisposable, ITab ImGui.TextUnformatted(text); ImGui.TableNextColumn(); - _dirty |= Combos.Gender("##Gender", InputWidth, _currentGender, out _currentGender); + _dirty |= Combos.Gender("##Gender", _currentGender, out _currentGender, InputWidth); if (drawRace == 1) { ImGui.SameLine(); - _dirty |= Combos.Race("##Race", InputWidth, _currentRace, out _currentRace); + _dirty |= Combos.Race("##Race", _currentRace, out _currentRace, InputWidth); } else if (drawRace == 2) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 743310ea..55125375 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -10,6 +10,7 @@ using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.UI.Classes; +using Penumbra.UI.ModsTab; namespace Penumbra.UI.AdvancedWindow; @@ -145,7 +146,7 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip(ModelSetIdTooltip); ImGui.TableNextColumn(); - if (Combos.EqpEquipSlot("##eqpSlot", 100, _new.Slot, out var slot)) + if (Combos.EqpEquipSlot("##eqpSlot", _new.Slot, out var slot)) _new = new EqpManipulation(ExpandedEqpFile.GetDefault(metaFileManager, setId), slot, _new.SetId); ImGuiUtil.HoverTooltip(EquipSlotTooltip); @@ -351,90 +352,31 @@ public partial class ModEditWindow // Identifier ImGui.TableNextColumn(); - if (Combos.ImcType("##imcType", _new.ObjectType, out var type)) - { - var equipSlot = type switch - { - ObjectType.Equipment => _new.EquipSlot.IsEquipment() ? _new.EquipSlot : EquipSlot.Head, - ObjectType.DemiHuman => _new.EquipSlot.IsEquipment() ? _new.EquipSlot : EquipSlot.Head, - ObjectType.Accessory => _new.EquipSlot.IsAccessory() ? _new.EquipSlot : EquipSlot.Ears, - _ => EquipSlot.Unknown, - }; - _new = new ImcManipulation(type, _new.BodySlot, _new.PrimaryId, _new.SecondaryId == 0 ? (ushort)1 : _new.SecondaryId, - _new.Variant.Id, equipSlot, _new.Entry); - } - - ImGuiUtil.HoverTooltip(ObjectTypeTooltip); + var change = MetaManipulationDrawer.DrawObjectType(ref _new); ImGui.TableNextColumn(); - if (IdInput("##imcId", IdWidth, _new.PrimaryId.Id, out var setId, 0, ushort.MaxValue, _new.PrimaryId <= 1)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, setId, _new.SecondaryId, _new.Variant.Id, _new.EquipSlot, _new.Entry) - .Copy(GetDefault(metaFileManager, _new) - ?? new ImcEntry()); - - ImGuiUtil.HoverTooltip(PrimaryIdTooltip); - + change |= MetaManipulationDrawer.DrawPrimaryId(ref _new); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); ImGui.TableNextColumn(); // Equipment and accessories are slightly different imcs than other types. - if (_new.ObjectType is ObjectType.Equipment) - { - if (Combos.EqpEquipSlot("##imcSlot", 100, _new.EquipSlot, out var slot)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, - _new.Entry) - .Copy(GetDefault(metaFileManager, _new) - ?? new ImcEntry()); - - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } - else if (_new.ObjectType is ObjectType.Accessory) - { - if (Combos.AccessorySlot("##imcSlot", _new.EquipSlot, out var slot)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, - _new.Entry) - .Copy(GetDefault(metaFileManager, _new) - ?? new ImcEntry()); - - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } + if (_new.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + change |= MetaManipulationDrawer.DrawSlot(ref _new); else - { - if (IdInput("##imcId2", 100 * UiHelpers.Scale, _new.SecondaryId.Id, out var setId2, 0, ushort.MaxValue, false)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, setId2, _new.Variant.Id, _new.EquipSlot, - _new.Entry) - .Copy(GetDefault(metaFileManager, _new) - ?? new ImcEntry()); - - ImGuiUtil.HoverTooltip(SecondaryIdTooltip); - } + change |= MetaManipulationDrawer.DrawSecondaryId(ref _new); ImGui.TableNextColumn(); - if (IdInput("##imcVariant", SmallIdWidth, _new.Variant.Id, out var variant, 0, byte.MaxValue, false)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, variant, _new.EquipSlot, - _new.Entry).Copy(GetDefault(metaFileManager, _new) - ?? new ImcEntry()); - - ImGuiUtil.HoverTooltip(VariantIdTooltip); + change |= MetaManipulationDrawer.DrawVariant(ref _new); ImGui.TableNextColumn(); if (_new.ObjectType is ObjectType.DemiHuman) - { - if (Combos.EqpEquipSlot("##imcSlot", 70, _new.EquipSlot, out var slot)) - _new = new ImcManipulation(_new.ObjectType, _new.BodySlot, _new.PrimaryId, _new.SecondaryId, _new.Variant.Id, slot, - _new.Entry) - .Copy(GetDefault(metaFileManager, _new) - ?? new ImcEntry()); - - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } + change |= MetaManipulationDrawer.DrawSlot(ref _new, 70); else - { ImGui.Dummy(new Vector2(70 * UiHelpers.Scale, 0)); - } - + if (change) + _new = _new.Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); // Values using var disabled = ImRaii.Disabled(); ImGui.TableNextColumn(); diff --git a/Penumbra/UI/Classes/Combos.cs b/Penumbra/UI/Classes/Combos.cs index 2cba7cf5..253bf0e0 100644 --- a/Penumbra/UI/Classes/Combos.cs +++ b/Penumbra/UI/Classes/Combos.cs @@ -8,41 +8,35 @@ namespace Penumbra.UI.Classes; public static class Combos { // Different combos to use with enums. - public static bool Race(string label, ModelRace current, out ModelRace race) - => Race(label, 100, current, out race); - - public static bool Race(string label, float unscaledWidth, ModelRace current, out ModelRace race) + public static bool Race(string label, ModelRace current, out ModelRace race, float unscaledWidth = 100) => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out race, RaceEnumExtensions.ToName, 1); - public static bool Gender(string label, Gender current, out Gender gender) - => Gender(label, 120, current, out gender); + public static bool Gender(string label, Gender current, out Gender gender, float unscaledWidth = 120) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth, current, out gender, RaceEnumExtensions.ToName, 1); - public static bool Gender(string label, float unscaledWidth, Gender current, out Gender gender) - => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out gender, RaceEnumExtensions.ToName, 1); - - public static bool EqdpEquipSlot(string label, EquipSlot current, out EquipSlot slot) - => ImGuiUtil.GenericEnumCombo(label, 100 * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EqdpSlots, + public static bool EqdpEquipSlot(string label, EquipSlot current, out EquipSlot slot, float unscaledWidth = 100) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EqdpSlots, EquipSlotExtensions.ToName); - public static bool EqpEquipSlot(string label, float width, EquipSlot current, out EquipSlot slot) - => ImGuiUtil.GenericEnumCombo(label, width * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EquipmentSlots, + public static bool EqpEquipSlot(string label, EquipSlot current, out EquipSlot slot, float unscaledWidth = 100) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out slot, EquipSlotExtensions.EquipmentSlots, EquipSlotExtensions.ToName); - public static bool AccessorySlot(string label, EquipSlot current, out EquipSlot slot) - => ImGuiUtil.GenericEnumCombo(label, 100 * UiHelpers.Scale, current, out slot, EquipSlotExtensions.AccessorySlots, + public static bool AccessorySlot(string label, EquipSlot current, out EquipSlot slot, float unscaledWidth = 100) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out slot, EquipSlotExtensions.AccessorySlots, EquipSlotExtensions.ToName); - public static bool SubRace(string label, SubRace current, out SubRace subRace) - => ImGuiUtil.GenericEnumCombo(label, 150 * UiHelpers.Scale, current, out subRace, RaceEnumExtensions.ToName, 1); + public static bool SubRace(string label, SubRace current, out SubRace subRace, float unscaledWidth = 150) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out subRace, RaceEnumExtensions.ToName, 1); - public static bool RspAttribute(string label, RspAttribute current, out RspAttribute attribute) - => ImGuiUtil.GenericEnumCombo(label, 200 * UiHelpers.Scale, current, out attribute, + public static bool RspAttribute(string label, RspAttribute current, out RspAttribute attribute, float unscaledWidth = 200) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out attribute, RspAttributeExtensions.ToFullString, 0, 1); - public static bool EstSlot(string label, EstManipulation.EstType current, out EstManipulation.EstType attribute) - => ImGuiUtil.GenericEnumCombo(label, 200 * UiHelpers.Scale, current, out attribute); + public static bool EstSlot(string label, EstManipulation.EstType current, out EstManipulation.EstType attribute, float unscaledWidth = 200) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out attribute); - public static bool ImcType(string label, ObjectType current, out ObjectType type) - => ImGuiUtil.GenericEnumCombo(label, 110 * UiHelpers.Scale, current, out type, ObjectTypeExtensions.ValidImcTypes, + public static bool ImcType(string label, ObjectType current, out ObjectType type, float unscaledWidth = 110) + => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out type, ObjectTypeExtensions.ValidImcTypes, ObjectTypeExtensions.ToName); } diff --git a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs index 5652fa98..b7262f95 100644 --- a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs @@ -1,12 +1,19 @@ using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.Utility; using ImGuiNET; +using Lumina.Data.Files; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; using OtterGui.Text.EndObjects; +using Penumbra.Api.Enums; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; @@ -15,9 +22,236 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.UI.Classes; +using ImcFile = Penumbra.Meta.Files.ImcFile; namespace Penumbra.UI.ModsTab; +public static class MetaManipulationDrawer +{ + public static bool DrawObjectType(ref ImcManipulation manip, float width = 110) + { + var ret = Combos.ImcType("##imcType", manip.ObjectType, out var type, width); + ImUtf8.HoverTooltip("Object Type"u8); + + if (ret) + { + var equipSlot = type switch + { + ObjectType.Equipment => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, + ObjectType.DemiHuman => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, + ObjectType.Accessory => manip.EquipSlot.IsAccessory() ? manip.EquipSlot : EquipSlot.Ears, + _ => EquipSlot.Unknown, + }; + manip = new ImcManipulation(type, manip.BodySlot, manip.PrimaryId, manip.SecondaryId == 0 ? 1 : manip.SecondaryId, + manip.Variant.Id, equipSlot, manip.Entry); + } + + return ret; + } + + public static bool DrawPrimaryId(ref ImcManipulation manip, float unscaledWidth = 80) + { + var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, manip.PrimaryId.Id, out var newId, 0, ushort.MaxValue, + manip.PrimaryId.Id <= 1); + ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 + + "This should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, newId, manip.SecondaryId, manip.Variant.Id, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawSecondaryId(ref ImcManipulation manip, float unscaledWidth = 100) + { + var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, manip.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); + ImUtf8.HoverTooltip("Secondary ID"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, newId, manip.Variant.Id, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawVariant(ref ImcManipulation manip, float unscaledWidth = 45) + { + var ret = IdInput("##imcVariant"u8, unscaledWidth, manip.Variant.Id, out var newId, 0, byte.MaxValue, false); + ImUtf8.HoverTooltip("Variant ID"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, (byte)newId, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawSlot(ref ImcManipulation manip, float unscaledWidth = 100) + { + bool ret; + EquipSlot slot; + switch (manip.ObjectType) + { + case ObjectType.Equipment: + case ObjectType.DemiHuman: + ret = Combos.EqpEquipSlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + break; + case ObjectType.Accessory: + ret = Combos.AccessorySlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + break; + default: return false; + } + + ImUtf8.HoverTooltip("Equip Slot"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, manip.Variant.Id, slot, + manip.Entry); + return ret; + } + + // A number input for ids with a optional max id of given width. + // Returns true if newId changed against currentId. + private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, + bool border) + { + int tmp = currentId; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); + if (ImUtf8.InputScalar(label, ref tmp)) + tmp = Math.Clamp(tmp, minId, maxId); + + newId = (ushort)tmp; + return newId != currentId; + } +} + +public class AddGroupDrawer : IUiService +{ + private string _groupName = string.Empty; + private bool _groupNameValid = false; + + private ImcManipulation _imcManip = new(EquipSlot.Head, 1, 1, new ImcEntry()); + private ImcEntry _defaultEntry; + private bool _imcFileExists; + private bool _entryExists; + private bool _entryInvalid; + private readonly MetaFileManager _metaManager; + private readonly ModManager _modManager; + + public AddGroupDrawer(MetaFileManager metaManager, ModManager modManager) + { + _metaManager = metaManager; + _modManager = modManager; + UpdateEntry(); + } + + public void Draw(Mod mod, float width) + { + DrawBasicGroups(mod, width); + DrawImcData(mod, width); + } + + private void UpdateEntry() + { + try + { + _defaultEntry = ImcFile.GetDefault(_metaManager, _imcManip.GamePath(), _imcManip.EquipSlot, _imcManip.Variant, + out _entryExists); + _imcFileExists = true; + } + catch (Exception) + { + _defaultEntry = new ImcEntry(); + _imcFileExists = false; + _entryExists = false; + } + + _imcManip = _imcManip.Copy(_entryExists ? _defaultEntry : new ImcEntry()); + _entryInvalid = !_imcManip.Validate(true); + } + + + private void DrawBasicGroups(Mod mod, float width) + { + ImGui.SetNextItemWidth(width); + if (ImUtf8.InputText("##name"u8, ref _groupName, "Enter New Name..."u8)) + _groupNameValid = ModGroupEditor.VerifyFileName(mod, null, _groupName, false); + + var buttonWidth = new Vector2((width - ImUtf8.ItemInnerSpacing.X) / 2, 0); + if (ImUtf8.ButtonEx("Add Single Group"u8, _groupNameValid + ? "Add a new single selection option group to this mod."u8 + : "Can not add a new group of this name."u8, + buttonWidth, !_groupNameValid)) + { + _modManager.OptionEditor.AddModGroup(mod, GroupType.Single, _groupName); + _groupName = string.Empty; + _groupNameValid = false; + } + + ImUtf8.SameLineInner(); + if (ImUtf8.ButtonEx("Add Multi Group"u8, _groupNameValid + ? "Add a new multi selection option group to this mod."u8 + : "Can not add a new group of this name."u8, + buttonWidth, !_groupNameValid)) + { + _modManager.OptionEditor.AddModGroup(mod, GroupType.Multi, _groupName); + _groupName = string.Empty; + _groupNameValid = false; + } + } + + private void DrawImcData(Mod mod, float width) + { + var halfWidth = (width - ImUtf8.ItemInnerSpacing.X) / 2 / ImUtf8.GlobalScale; + var change = MetaManipulationDrawer.DrawObjectType(ref _imcManip, halfWidth); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawPrimaryId(ref _imcManip, halfWidth); + if (_imcManip.ObjectType is ObjectType.Weapon or ObjectType.Monster) + { + change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, halfWidth); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, halfWidth); + } + else if (_imcManip.ObjectType is ObjectType.DemiHuman) + { + var quarterWidth = (halfWidth - ImUtf8.ItemInnerSpacing.X / ImUtf8.GlobalScale) / 2; + change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, halfWidth); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, quarterWidth); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, quarterWidth); + } + else + { + change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, halfWidth); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, halfWidth); + } + + if (change) + UpdateEntry(); + + var buttonWidth = new Vector2(halfWidth * ImUtf8.GlobalScale, 0); + + if (ImUtf8.ButtonEx("Add IMC Group"u8, !_groupNameValid + ? "Can not add a new group of this name."u8 + : _entryInvalid ? + "The associated IMC entry is invalid."u8 + : "Add a new multi selection option group to this mod."u8, + buttonWidth, !_groupNameValid || _entryInvalid)) + { + _modManager.OptionEditor.ImcEditor.AddModGroup(mod, _groupName, _imcManip); + _groupName = string.Empty; + _groupNameValid = false; + } + + if (_entryInvalid) + { + ImUtf8.SameLineInner(); + var text = _imcFileExists + ? "IMC Entry Does Not Exist" + : "IMC File Does Not Exist"; + ImGuiUtil.DrawTextButton(text, buttonWidth, Colors.PressEnterWarningBg); + } + } +} + public sealed class ModGroupEditDrawer( ModManager modManager, Configuration config, @@ -267,9 +501,7 @@ public sealed class ModGroupEditDrawer( } private void DrawImcGroup(ImcModGroup group) - { - // TODO - } + { } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void DrawOptionPosition(IModGroup group, IModOption option, int optionIdx) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index a5db15b6..b7951c49 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -28,7 +28,8 @@ public class ModPanelEditTab( Configuration config, PredefinedTagManager predefinedTagManager, ModGroupEditDrawer groupEditDrawer, - DescriptionEditPopup descriptionPopup) + DescriptionEditPopup descriptionPopup, + AddGroupDrawer addGroupDrawer) : ITab { private readonly TagButtons _modTags = new(); @@ -75,7 +76,7 @@ public class ModPanelEditTab( selector.Selected!); UiHelpers.DefaultLineSpace(); - AddOptionGroup.Draw(filenames, modManager, _mod, config.ReplaceNonAsciiOnImport); + addGroupDrawer.Draw(_mod, UiHelpers.InputTextWidth.X); UiHelpers.DefaultLineSpace(); groupEditDrawer.Draw(_mod); @@ -84,7 +85,6 @@ public class ModPanelEditTab( public void Reset() { - AddOptionGroup.Reset(); MoveDirectory.Reset(); Input.Reset(); } @@ -202,42 +202,6 @@ public class ModPanelEditTab( Process.Start(new ProcessStartInfo(filenames.ModMetaPath(_mod)) { UseShellExecute = true }); } - /// Text input to add a new option group at the end of the current groups. - private static class AddOptionGroup - { - private static string _newGroupName = string.Empty; - - public static void Reset() - => _newGroupName = string.Empty; - - public static void Draw(FilenameService filenames, ModManager modManager, Mod mod, bool onlyAscii) - { - using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(UiHelpers.ScaleX3)); - ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); - ImGui.InputTextWithHint("##newGroup", "Add new option group...", ref _newGroupName, 256); - ImGui.SameLine(); - var defaultFile = filenames.OptionGroupFile(mod, -1, onlyAscii); - var fileExists = File.Exists(defaultFile); - var tt = fileExists - ? "Open the default option json file in the text editor of your choice." - : "The default option json file does not exist."; - if (ImGuiUtil.DrawDisabledButton($"{FontAwesomeIcon.FileExport.ToIconString()}##defaultFile", UiHelpers.IconButtonSize, tt, - !fileExists, true)) - Process.Start(new ProcessStartInfo(defaultFile) { UseShellExecute = true }); - - ImGui.SameLine(); - - var nameValid = ModGroupEditor.VerifyFileName(mod, null, _newGroupName, false); - tt = nameValid ? "Add new option group to the mod." : "Can not add a group of this name."; - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, - tt, !nameValid, true)) - return; - - modManager.OptionEditor.SingleEditor.AddModGroup(mod, _newGroupName); - Reset(); - } - } - /// A text input for the new directory name and a button to apply the move. private static class MoveDirectory { From bb56faa288be5bf200e0e44af93a649b382ef632 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 20 May 2024 18:28:40 +0200 Subject: [PATCH 0602/1381] Improvements. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Mods/Groups/ImcModGroup.cs | 27 +- Penumbra/Mods/Manager/ModCacheManager.cs | 3 + .../Manager/OptionEditor/ImcAttributeCache.cs | 123 ++++++++ .../Manager/OptionEditor/ImcModGroupEditor.cs | 63 ++++ Penumbra/Mods/SubMods/ImcSubMod.cs | 7 +- Penumbra/UI/ModsTab/AddGroupDrawer.cs | 161 ++++++++++ Penumbra/UI/ModsTab/ModGroupEditDrawer.cs | 280 +++++++++--------- 9 files changed, 498 insertions(+), 170 deletions(-) create mode 100644 Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs create mode 100644 Penumbra/UI/ModsTab/AddGroupDrawer.cs diff --git a/OtterGui b/OtterGui index 5028fba7..462acb87 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5028fba767ca8febd75a1a5ebc312bd354efc81b +Subproject commit 462acb87099650019996e4306d18cc70f76ca576 diff --git a/Penumbra.GameData b/Penumbra.GameData index 595ac572..5fa4d0e7 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 595ac5722c9c400bea36110503ed2ae7b02d1489 +Subproject commit 5fa4d0e7972423b73f8cf569bb2bfbeddd825c8a diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 21d8abe0..671d684f 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -14,8 +14,7 @@ namespace Penumbra.Mods.Groups; public class ImcModGroup(Mod mod) : IModGroup { - public const int DisabledIndex = 30; - public const int NumAttributes = 10; + public const int DisabledIndex = 60; public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; @@ -55,23 +54,20 @@ public class ImcModGroup(Mod mod) : IModGroup } } + public bool DefaultDisabled + => _canBeDisabled && DefaultSettings.HasFlag(DisabledIndex); + public IModOption? AddOption(string name, string description = "") { - uint fullMask = GetFullMask(); - var firstUnset = (byte)BitOperations.TrailingZeroCount(~fullMask); - // All attributes handled. - if (firstUnset >= NumAttributes) - return null; - var groupIdx = Mod.Groups.IndexOf(this); if (groupIdx < 0) return null; var subMod = new ImcSubMod(this) { - Name = name, - Description = description, - AttributeIndex = firstUnset, + Name = name, + Description = description, + AttributeMask = 0, }; OptionData.Add(subMod); return subMod; @@ -100,7 +96,7 @@ public class ImcModGroup(Mod mod) : IModGroup continue; var option = OptionData[i]; - mask |= option.Attribute; + mask |= option.AttributeMask; } return mask; @@ -109,11 +105,10 @@ public class ImcModGroup(Mod mod) : IModGroup private ushort GetFullMask() => GetCurrentMask(Setting.AllBits(63)); - private ImcManipulation GetManip(ushort mask) + public ImcManipulation GetManip(ushort mask) => new(ObjectType, BodySlot, PrimaryId, SecondaryId.Id, Variant.Id, EquipSlot, DefaultEntry with { AttributeMask = mask }); - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { if (CanBeDisabled && setting.HasFlag(DisabledIndex)) @@ -150,8 +145,8 @@ public class ImcModGroup(Mod mod) : IModGroup { jWriter.WriteStartObject(); SubMod.WriteModOption(jWriter, option); - jWriter.WritePropertyName(nameof(option.AttributeIndex)); - jWriter.WriteValue(option.AttributeIndex); + jWriter.WritePropertyName(nameof(option.AttributeMask)); + jWriter.WriteValue(option.AttributeMask); jWriter.WriteEndObject(); } diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 59c88cf0..c6a723a0 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -202,6 +202,9 @@ public class ModCacheManager : IDisposable foreach (var manip in mod.AllDataContainers.SelectMany(m => m.Manipulations)) ComputeChangedItems(_identifier, changedItems, manip); + foreach(var imcGroup in mod.Groups.OfType()) + ComputeChangedItems(_identifier, changedItems, imcGroup.GetManip(0)); + mod.LowerChangedItemsString = string.Join("\0", mod.ChangedItems.Keys.Select(k => k.ToLowerInvariant())); } diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs b/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs new file mode 100644 index 00000000..e1235c5b --- /dev/null +++ b/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs @@ -0,0 +1,123 @@ +using OtterGui; +using Penumbra.GameData.Structs; +using Penumbra.Mods.Groups; +using Penumbra.Mods.SubMods; + +namespace Penumbra.Mods.Manager.OptionEditor; + +public unsafe ref struct ImcAttributeCache +{ + private fixed bool _canChange[ImcEntry.NumAttributes]; + private fixed byte _option[ImcEntry.NumAttributes]; + + /// Obtain the earliest unset flag, or 0 if none are unset. + public readonly ushort LowestUnsetMask; + + public ImcAttributeCache(ImcModGroup group) + { + for (var i = 0; i < ImcEntry.NumAttributes; ++i) + { + _canChange[i] = true; + _option[i] = byte.MaxValue; + + var flag = (ushort)(1 << i); + var set = (group.DefaultEntry.AttributeMask & flag) != 0; + if (set) + { + _canChange[i] = true; + _option[i] = byte.MaxValue - 1; + continue; + } + + foreach (var (option, idx) in group.OptionData.WithIndex()) + { + set = (option.AttributeMask & flag) != 0; + if (set) + { + _canChange[i] = option.AttributeMask != flag; + _option[i] = (byte)idx; + break; + } + } + + if (_option[i] == byte.MaxValue && LowestUnsetMask is 0) + LowestUnsetMask = flag; + } + } + + + /// Checks whether an attribute flag can be set by anything, i.e. if it might be the only flag for an option and thus could not be removed from that option. + public readonly bool CanChange(int idx) + => _canChange[idx]; + + /// Set a default attribute flag to a value if possible, remove it from its prior option if necessary, and return if anything changed. + public readonly bool Set(ImcModGroup group, int idx, bool value) + { + var flag = 1 << idx; + var oldMask = group.DefaultEntry.AttributeMask; + if (!value) + { + var newMask = (ushort)(oldMask & ~flag); + if (oldMask == newMask) + return false; + + group.DefaultEntry = group.DefaultEntry with { AttributeMask = newMask }; + return true; + } + + if (!_canChange[idx]) + return false; + + var mask = (ushort)(oldMask | flag); + if (oldMask == mask) + return false; + + group.DefaultEntry = group.DefaultEntry with { AttributeMask = mask }; + if (_option[idx] <= ImcEntry.NumAttributes) + { + var option = group.OptionData[_option[idx]]; + option.AttributeMask = (ushort)(option.AttributeMask & ~flag); + } + + return true; + } + + /// Set an attribute flag to a value if possible, remove it from its prior option or the default entry if necessary, and return if anything changed. + public readonly bool Set(ImcSubMod option, int idx, bool value) + { + if (!_canChange[idx]) + return false; + + var flag = 1 << idx; + var oldMask = option.AttributeMask; + if (!value) + { + var newMask = (ushort)(oldMask & ~flag); + if (oldMask == newMask) + return false; + + option.AttributeMask = newMask; + return true; + } + + var mask = (ushort)(oldMask | flag); + if (oldMask == mask) + return false; + + option.AttributeMask = mask; + if (_option[idx] <= ImcEntry.NumAttributes) + { + var oldOption = option.Group.OptionData[_option[idx]]; + oldOption.AttributeMask = (ushort)(oldOption.AttributeMask & ~flag); + } + else if (_option[idx] is byte.MaxValue - 1) + { + option.Group.DefaultEntry = option.Group.DefaultEntry with + { + AttributeMask = (ushort)(option.Group.DefaultEntry.AttributeMask & ~flag), + }; + } + + return true; + } +} diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index f71547ba..20021d29 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -1,11 +1,13 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; +using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; +using static FFXIVClientStructs.FFXIV.Client.UI.Misc.ConfigModule; namespace Penumbra.Mods.Manager.OptionEditor; @@ -26,6 +28,67 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ return group; } + public ImcSubMod? AddOption(ImcModGroup group, in ImcAttributeCache cache, string name, string description = "", + SaveType saveType = SaveType.Queue) + { + if (cache.LowestUnsetMask == 0) + return null; + + var subMod = new ImcSubMod(group) + { + Name = name, + Description = description, + AttributeMask = cache.LowestUnsetMask, + }; + group.OptionData.Add(subMod); + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionAdded, group.Mod, group, subMod, null, -1); + return subMod; + } + + // Hide this method. + private new ImcSubMod? AddOption(ImcModGroup group, string name, SaveType saveType) + => null; + + public void ChangeDefaultAttribute(ImcModGroup group, in ImcAttributeCache cache, int idx, bool value, SaveType saveType = SaveType.Queue) + { + if (!cache.Set(group, idx, value)) + return; + + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, group.Mod, group, null, null, -1); + } + + public void ChangeDefaultEntry(ImcModGroup group, in ImcEntry newEntry, SaveType saveType = SaveType.Queue) + { + var entry = newEntry with { AttributeMask = group.DefaultEntry.AttributeMask }; + if (entry.MaterialId == 0 || group.DefaultEntry.Equals(entry)) + return; + + group.DefaultEntry = entry; + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, group.Mod, group, null, null, -1); + } + + public void ChangeOptionAttribute(ImcSubMod option, in ImcAttributeCache cache, int idx, bool value, SaveType saveType = SaveType.Queue) + { + if (!cache.Set(option, idx, value)) + return; + + SaveService.Save(saveType, new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, option.Mod, option.Group, option, null, -1); + } + + public void ChangeCanBeDisabled(ImcModGroup group, bool canBeDisabled, SaveType saveType = SaveType.Queue) + { + if (group.CanBeDisabled == canBeDisabled) + return; + + group.CanBeDisabled = canBeDisabled; + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, group.Mod, group, null, null, -1); + } + protected override ImcModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) => new(mod) { diff --git a/Penumbra/Mods/SubMods/ImcSubMod.cs b/Penumbra/Mods/SubMods/ImcSubMod.cs index fca817aa..7f46bc95 100644 --- a/Penumbra/Mods/SubMods/ImcSubMod.cs +++ b/Penumbra/Mods/SubMods/ImcSubMod.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json.Linq; +using Penumbra.GameData.Structs; using Penumbra.Mods.Groups; namespace Penumbra.Mods.SubMods; @@ -11,15 +12,13 @@ public class ImcSubMod(ImcModGroup group) : IModOption : this(group) { SubMod.LoadOptionData(json, this); + AttributeMask = (ushort)((json[nameof(AttributeMask)]?.ToObject() ?? 0) & ImcEntry.AttributesMask); } public Mod Mod => Group.Mod; - public byte AttributeIndex; - - public ushort Attribute - => (ushort)(1 << AttributeIndex); + public ushort AttributeMask; Mod IModOption.Mod => Mod; diff --git a/Penumbra/UI/ModsTab/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/AddGroupDrawer.cs new file mode 100644 index 00000000..79c1bf9d --- /dev/null +++ b/Penumbra/UI/ModsTab/AddGroupDrawer.cs @@ -0,0 +1,161 @@ +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Api.Enums; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods; +using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.ModsTab; + +public class AddGroupDrawer : IUiService +{ + private string _groupName = string.Empty; + private bool _groupNameValid = false; + + private ImcManipulation _imcManip = new(EquipSlot.Head, 1, 1, new ImcEntry()); + private ImcEntry _defaultEntry; + private bool _imcFileExists; + private bool _entryExists; + private bool _entryInvalid; + private readonly MetaFileManager _metaManager; + private readonly ModManager _modManager; + + public AddGroupDrawer(MetaFileManager metaManager, ModManager modManager) + { + _metaManager = metaManager; + _modManager = modManager; + UpdateEntry(); + } + + public void Draw(Mod mod, float width) + { + var buttonWidth = new Vector2((width - ImUtf8.ItemInnerSpacing.X) / 2, 0); + DrawBasicGroups(mod, width, buttonWidth); + DrawImcData(mod, buttonWidth); + } + + private void DrawBasicGroups(Mod mod, float width, Vector2 buttonWidth) + { + ImGui.SetNextItemWidth(width); + if (ImUtf8.InputText("##name"u8, ref _groupName, "Enter New Name..."u8)) + _groupNameValid = ModGroupEditor.VerifyFileName(mod, null, _groupName, false); + + DrawSingleGroupButton(mod, buttonWidth); + ImUtf8.SameLineInner(); + DrawMultiGroupButton(mod, buttonWidth); + } + + private void DrawSingleGroupButton(Mod mod, Vector2 width) + { + if (!ImUtf8.ButtonEx("Add Single Group"u8, _groupNameValid + ? "Add a new single selection option group to this mod."u8 + : "Can not add a new group of this name."u8, + width, !_groupNameValid)) + return; + + _modManager.OptionEditor.AddModGroup(mod, GroupType.Single, _groupName); + _groupName = string.Empty; + _groupNameValid = false; + } + + private void DrawMultiGroupButton(Mod mod, Vector2 width) + { + if (!ImUtf8.ButtonEx("Add Multi Group"u8, _groupNameValid + ? "Add a new multi selection option group to this mod."u8 + : "Can not add a new group of this name."u8, + width, !_groupNameValid)) + return; + + _modManager.OptionEditor.AddModGroup(mod, GroupType.Multi, _groupName); + _groupName = string.Empty; + _groupNameValid = false; + } + + private void DrawImcInput(float width) + { + var change = MetaManipulationDrawer.DrawObjectType(ref _imcManip, width); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawPrimaryId(ref _imcManip, width); + if (_imcManip.ObjectType is ObjectType.Weapon or ObjectType.Monster) + { + change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, width); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, width); + } + else if (_imcManip.ObjectType is ObjectType.DemiHuman) + { + var quarterWidth = (width - ImUtf8.ItemInnerSpacing.X / ImUtf8.GlobalScale) / 2; + change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, width); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, quarterWidth); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, quarterWidth); + } + else + { + change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, width); + ImUtf8.SameLineInner(); + change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, width); + } + + if (change) + UpdateEntry(); + } + + private void DrawImcData(Mod mod, Vector2 width) + { + var halfWidth = width.X / ImUtf8.GlobalScale; + DrawImcInput(halfWidth); + DrawImcButton(mod, width); + } + + private void DrawImcButton(Mod mod, Vector2 width) + { + if (ImUtf8.ButtonEx("Add IMC Group"u8, !_groupNameValid + ? "Can not add a new group of this name."u8 + : _entryInvalid + ? "The associated IMC entry is invalid."u8 + : "Add a new multi selection option group to this mod."u8, + width, !_groupNameValid || _entryInvalid)) + { + _modManager.OptionEditor.ImcEditor.AddModGroup(mod, _groupName, _imcManip); + _groupName = string.Empty; + _groupNameValid = false; + } + + if (_entryInvalid) + { + ImUtf8.SameLineInner(); + var text = _imcFileExists + ? "IMC Entry Does Not Exist"u8 + : "IMC File Does Not Exist"u8; + ImUtf8.TextFramed(text, Colors.PressEnterWarningBg, width); + } + } + + private void UpdateEntry() + { + try + { + _defaultEntry = ImcFile.GetDefault(_metaManager, _imcManip.GamePath(), _imcManip.EquipSlot, _imcManip.Variant, + out _entryExists); + _imcFileExists = true; + } + catch (Exception) + { + _defaultEntry = new ImcEntry(); + _imcFileExists = false; + _entryExists = false; + } + + _imcManip = _imcManip.Copy(_entryExists ? _defaultEntry : new ImcEntry()); + _entryInvalid = !_imcManip.Validate(true); + } +} diff --git a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs index b7262f95..a94c25ea 100644 --- a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs @@ -1,15 +1,12 @@ using Dalamud.Interface; using Dalamud.Interface.Internal.Notifications; -using Dalamud.Interface.Utility; using ImGuiNET; -using Lumina.Data.Files; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; using OtterGui.Text.EndObjects; -using Penumbra.Api.Enums; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; @@ -22,7 +19,6 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.UI.Classes; -using ImcFile = Penumbra.Meta.Files.ImcFile; namespace Penumbra.UI.ModsTab; @@ -104,8 +100,10 @@ public static class MetaManipulationDrawer return ret; } - // A number input for ids with a optional max id of given width. - // Returns true if newId changed against currentId. + /// + /// A number input for ids with an optional max id of given width. + /// Returns true if newId changed against currentId. + /// private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, bool border) { @@ -121,142 +119,12 @@ public static class MetaManipulationDrawer } } -public class AddGroupDrawer : IUiService -{ - private string _groupName = string.Empty; - private bool _groupNameValid = false; - - private ImcManipulation _imcManip = new(EquipSlot.Head, 1, 1, new ImcEntry()); - private ImcEntry _defaultEntry; - private bool _imcFileExists; - private bool _entryExists; - private bool _entryInvalid; - private readonly MetaFileManager _metaManager; - private readonly ModManager _modManager; - - public AddGroupDrawer(MetaFileManager metaManager, ModManager modManager) - { - _metaManager = metaManager; - _modManager = modManager; - UpdateEntry(); - } - - public void Draw(Mod mod, float width) - { - DrawBasicGroups(mod, width); - DrawImcData(mod, width); - } - - private void UpdateEntry() - { - try - { - _defaultEntry = ImcFile.GetDefault(_metaManager, _imcManip.GamePath(), _imcManip.EquipSlot, _imcManip.Variant, - out _entryExists); - _imcFileExists = true; - } - catch (Exception) - { - _defaultEntry = new ImcEntry(); - _imcFileExists = false; - _entryExists = false; - } - - _imcManip = _imcManip.Copy(_entryExists ? _defaultEntry : new ImcEntry()); - _entryInvalid = !_imcManip.Validate(true); - } - - - private void DrawBasicGroups(Mod mod, float width) - { - ImGui.SetNextItemWidth(width); - if (ImUtf8.InputText("##name"u8, ref _groupName, "Enter New Name..."u8)) - _groupNameValid = ModGroupEditor.VerifyFileName(mod, null, _groupName, false); - - var buttonWidth = new Vector2((width - ImUtf8.ItemInnerSpacing.X) / 2, 0); - if (ImUtf8.ButtonEx("Add Single Group"u8, _groupNameValid - ? "Add a new single selection option group to this mod."u8 - : "Can not add a new group of this name."u8, - buttonWidth, !_groupNameValid)) - { - _modManager.OptionEditor.AddModGroup(mod, GroupType.Single, _groupName); - _groupName = string.Empty; - _groupNameValid = false; - } - - ImUtf8.SameLineInner(); - if (ImUtf8.ButtonEx("Add Multi Group"u8, _groupNameValid - ? "Add a new multi selection option group to this mod."u8 - : "Can not add a new group of this name."u8, - buttonWidth, !_groupNameValid)) - { - _modManager.OptionEditor.AddModGroup(mod, GroupType.Multi, _groupName); - _groupName = string.Empty; - _groupNameValid = false; - } - } - - private void DrawImcData(Mod mod, float width) - { - var halfWidth = (width - ImUtf8.ItemInnerSpacing.X) / 2 / ImUtf8.GlobalScale; - var change = MetaManipulationDrawer.DrawObjectType(ref _imcManip, halfWidth); - ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawPrimaryId(ref _imcManip, halfWidth); - if (_imcManip.ObjectType is ObjectType.Weapon or ObjectType.Monster) - { - change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, halfWidth); - ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, halfWidth); - } - else if (_imcManip.ObjectType is ObjectType.DemiHuman) - { - var quarterWidth = (halfWidth - ImUtf8.ItemInnerSpacing.X / ImUtf8.GlobalScale) / 2; - change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, halfWidth); - ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, quarterWidth); - ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, quarterWidth); - } - else - { - change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, halfWidth); - ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, halfWidth); - } - - if (change) - UpdateEntry(); - - var buttonWidth = new Vector2(halfWidth * ImUtf8.GlobalScale, 0); - - if (ImUtf8.ButtonEx("Add IMC Group"u8, !_groupNameValid - ? "Can not add a new group of this name."u8 - : _entryInvalid ? - "The associated IMC entry is invalid."u8 - : "Add a new multi selection option group to this mod."u8, - buttonWidth, !_groupNameValid || _entryInvalid)) - { - _modManager.OptionEditor.ImcEditor.AddModGroup(mod, _groupName, _imcManip); - _groupName = string.Empty; - _groupNameValid = false; - } - - if (_entryInvalid) - { - ImUtf8.SameLineInner(); - var text = _imcFileExists - ? "IMC Entry Does Not Exist" - : "IMC File Does Not Exist"; - ImGuiUtil.DrawTextButton(text, buttonWidth, Colors.PressEnterWarningBg); - } - } -} - public sealed class ModGroupEditDrawer( ModManager modManager, Configuration config, FilenameService filenames, - DescriptionEditPopup descriptionPopup) : IUiService + DescriptionEditPopup descriptionPopup, + MetaFileManager metaManager) : IUiService { private static ReadOnlySpan DragDropLabel => "##DragOption"u8; @@ -501,7 +369,111 @@ public sealed class ModGroupEditDrawer( } private void DrawImcGroup(ImcModGroup group) - { } + { + using (ImUtf8.Group()) + { + ImUtf8.Text("Object Type"u8); + if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) + ImUtf8.Text("Slot"u8); + ImUtf8.Text("Primary ID"); + if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) + ImUtf8.Text("Secondary ID"); + ImUtf8.Text("Variant"u8); + + ImUtf8.TextFrameAligned("Material ID"u8); + ImUtf8.TextFrameAligned("Material Animation ID"u8); + ImUtf8.TextFrameAligned("Decal ID"u8); + ImUtf8.TextFrameAligned("VFX ID"u8); + ImUtf8.TextFrameAligned("Sound ID"u8); + ImUtf8.TextFrameAligned("Can Be Disabled"u8); + ImUtf8.TextFrameAligned("Default Attributes"u8); + } + + ImGui.SameLine(); + + var attributeCache = new ImcAttributeCache(group); + + using (ImUtf8.Group()) + { + ImUtf8.Text(group.ObjectType.ToName()); + if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) + ImUtf8.Text(group.EquipSlot.ToName()); + ImUtf8.Text($"{group.PrimaryId.Id}"); + if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) + ImUtf8.Text($"{group.SecondaryId.Id}"); + ImUtf8.Text($"{group.Variant.Id}"); + + ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialAnimationId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.DecalId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.VfxId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.SoundId}"); + + var canBeDisabled = group.CanBeDisabled; + if (ImUtf8.Checkbox("##disabled"u8, ref canBeDisabled)) + modManager.OptionEditor.ImcEditor.ChangeCanBeDisabled(group, canBeDisabled, SaveType.Queue); + + var defaultDisabled = group.DefaultDisabled; + ImUtf8.SameLineInner(); + if (ImUtf8.Checkbox("##defaultDisabled"u8, ref defaultDisabled)) + modManager.OptionEditor.ChangeModGroupDefaultOption(group, + group.DefaultSettings.SetBit(ImcModGroup.DisabledIndex, defaultDisabled)); + + DrawAttributes(modManager.OptionEditor.ImcEditor, attributeCache, group.DefaultEntry.AttributeMask, group); + } + + + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImRaii.PushId(optionIdx); + DrawOptionPosition(group, option, optionIdx); + + ImUtf8.SameLineInner(); + DrawOptionDefaultMultiBehaviour(group, option, optionIdx); + + ImUtf8.SameLineInner(); + DrawOptionName(option); + + ImUtf8.SameLineInner(); + DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + DrawOptionDelete(option); + + ImUtf8.SameLineInner(); + ImGui.Dummy(new Vector2(_priorityWidth, 0)); + + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + _optionIdxSelectable.X + ImUtf8.ItemInnerSpacing.X * 2 + ImUtf8.FrameHeight); + DrawAttributes(modManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); + } + + DrawNewOption(group, attributeCache); + return; + + static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data) + { + for (var i = 0; i < ImcEntry.NumAttributes; ++i) + { + using var id = ImRaii.PushId(i); + var value = (mask & (1 << i)) != 0; + using (ImRaii.Disabled(!cache.CanChange(i))) + { + if (ImUtf8.Checkbox(TerminatedByteString.Empty, ref value)) + { + if (data is ImcModGroup g) + editor.ChangeDefaultAttribute(g, cache, i, value); + else + editor.ChangeOptionAttribute((ImcSubMod)data, cache, i, value); + } + } + + ImUtf8.HoverTooltip($"{(char)('A' + i)}"); + if (i != 9) + ImUtf8.SameLineInner(); + } + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void DrawOptionPosition(IModGroup group, IModOption option, int optionIdx) @@ -575,14 +547,14 @@ public sealed class ModGroupEditDrawer( if (count >= int.MaxValue) return; - DrawNewOptionBase(group, count); + var name = DrawNewOptionBase(group, count); - var validName = _newOptionName?.Length > 0; + var validName = name.Length > 0; if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName ? "Add a new option to this group."u8 : "Please enter a name for the new option."u8, !validName)) { - modManager.OptionEditor.SingleEditor.AddOption(group, _newOptionName!); + modManager.OptionEditor.SingleEditor.AddOption(group, name); _newOptionName = null; } } @@ -593,25 +565,36 @@ public sealed class ModGroupEditDrawer( if (count >= IModGroup.MaxMultiOptions) return; - DrawNewOptionBase(group, count); + var name = DrawNewOptionBase(group, count); - var validName = _newOptionName?.Length > 0; + var validName = name.Length > 0; if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName ? "Add a new option to this group."u8 : "Please enter a name for the new option."u8, !validName)) { - modManager.OptionEditor.MultiEditor.AddOption(group, _newOptionName!); + modManager.OptionEditor.MultiEditor.AddOption(group, name); _newOptionName = null; } } - private void DrawNewOption(ImcModGroup group) + private void DrawNewOption(ImcModGroup group, in ImcAttributeCache cache) { - // TODO + if (cache.LowestUnsetMask == 0) + return; + + var name = DrawNewOptionBase(group, group.Options.Count); + var validName = name.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, !validName)) + { + modManager.OptionEditor.ImcEditor.AddOption(group, cache, name); + _newOptionName = null; + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawNewOptionBase(IModGroup group, int count) + private string DrawNewOptionBase(IModGroup group, int count) { ImUtf8.Selectable($"Option #{count + 1}", false, size: _optionIdxSelectable); Target(group, count); @@ -631,6 +614,7 @@ public sealed class ModGroupEditDrawer( } ImUtf8.SameLineInner(); + return newName; } [MethodImpl(MethodImplOptions.AggressiveInlining)] From e85b84dafe543b3a2e8bcfe13ed665fbe92b4c93 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 21 May 2024 18:24:21 +0200 Subject: [PATCH 0603/1381] Add the option to omit mch offhands from changed items. --- Penumbra/Collections/Cache/CollectionCache.cs | 10 +- .../Cache/CollectionCacheManager.cs | 8 +- Penumbra/Configuration.cs | 25 ++-- Penumbra/Mods/Groups/IModGroup.cs | 2 + Penumbra/Mods/Groups/ImcModGroup.cs | 5 + Penumbra/Mods/Groups/MultiModGroup.cs | 8 ++ Penumbra/Mods/Groups/SingleModGroup.cs | 8 ++ Penumbra/Mods/Manager/ModCacheManager.cs | 92 ++------------ Penumbra/Mods/Manager/ModImportManager.cs | 19 +-- Penumbra/Mods/Mod.cs | 6 +- Penumbra/UI/ModsTab/ModGroupEditDrawer.cs | 3 +- Penumbra/UI/Tabs/SettingsTab.cs | 8 ++ Penumbra/Util/IdentifierExtensions.cs | 115 ++++++++++++++++++ 13 files changed, 192 insertions(+), 117 deletions(-) create mode 100644 Penumbra/Util/IdentifierExtensions.cs diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index ded1dc73..e2f20b46 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -6,6 +6,7 @@ using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Mods.Manager; +using Penumbra.Util; namespace Penumbra.Collections.Cache; @@ -252,8 +253,8 @@ public sealed class CollectionCache : IDisposable return mod.GetData(); var settings = _collection[mod.Index].Settings; - return settings is not { Enabled: true } - ? AppliedModData.Empty + return settings is not { Enabled: true } + ? AppliedModData.Empty : mod.GetData(settings); } @@ -439,9 +440,12 @@ public sealed class CollectionCache : IDisposable foreach (var (manip, mod) in Meta) { - ModCacheManager.ComputeChangedItems(identifier, items, manip); + identifier.MetaChangedItems(items, manip); AddItems(mod); } + + if (_manager.Config.HideMachinistOffhandFromChangedItems) + _changedItems.RemoveMachinistOffhands(); } catch (Exception e) { diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index fb9ee9a3..ca57c8b9 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -25,6 +25,7 @@ public class CollectionCacheManager : IDisposable private readonly ModStorage _modStorage; private readonly CollectionStorage _storage; private readonly ActiveCollections _active; + internal readonly Configuration Config; internal readonly ResolvedFileChanged ResolvedFileChanged; internal readonly MetaFileManager MetaFileManager; internal readonly ResourceLoader ResourceLoader; @@ -40,7 +41,8 @@ public class CollectionCacheManager : IDisposable => _storage.Where(c => c.HasCache); public CollectionCacheManager(FrameworkManager framework, CommunicatorService communicator, TempModManager tempMods, ModStorage modStorage, - MetaFileManager metaFileManager, ActiveCollections active, CollectionStorage storage, ResourceLoader resourceLoader) + MetaFileManager metaFileManager, ActiveCollections active, CollectionStorage storage, ResourceLoader resourceLoader, + Configuration config) { _framework = framework; _communicator = communicator; @@ -50,6 +52,7 @@ public class CollectionCacheManager : IDisposable _active = active; _storage = storage; ResourceLoader = resourceLoader; + Config = config; ResolvedFileChanged = _communicator.ResolvedFileChanged; if (!_active.Individuals.IsLoaded) @@ -260,7 +263,8 @@ public class CollectionCacheManager : IDisposable } /// Prepare Changes by removing mods from caches with collections or add or reload mods. - private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int movedToIdx) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, + int movedToIdx) { if (type is ModOptionChangeType.PrepareChange) { diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index a065bc26..b81e84d8 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -41,18 +41,19 @@ public class Configuration : IPluginConfiguration, ISavable public bool HideUiWhenUiHidden { get; set; } = false; public bool UseDalamudUiTextureRedirection { get; set; } = true; - public bool UseCharacterCollectionInMainWindow { get; set; } = true; - public bool UseCharacterCollectionsInCards { get; set; } = true; - public bool UseCharacterCollectionInInspect { get; set; } = true; - public bool UseCharacterCollectionInTryOn { get; set; } = true; - public bool UseOwnerNameForCharacterCollection { get; set; } = true; - public bool UseNoModsInInspect { get; set; } = false; - public bool HideChangedItemFilters { get; set; } = false; - public bool ReplaceNonAsciiOnImport { get; set; } = false; - public bool HidePrioritiesInSelector { get; set; } = false; - public bool HideRedrawBar { get; set; } = false; - public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; - public int OptionGroupCollapsibleMin { get; set; } = 5; + public bool UseCharacterCollectionInMainWindow { get; set; } = true; + public bool UseCharacterCollectionsInCards { get; set; } = true; + public bool UseCharacterCollectionInInspect { get; set; } = true; + public bool UseCharacterCollectionInTryOn { get; set; } = true; + public bool UseOwnerNameForCharacterCollection { get; set; } = true; + public bool UseNoModsInInspect { get; set; } = false; + public bool HideChangedItemFilters { get; set; } = false; + public bool ReplaceNonAsciiOnImport { get; set; } = false; + public bool HidePrioritiesInSelector { get; set; } = false; + public bool HideRedrawBar { get; set; } = false; + public bool HideMachinistOffhandFromChangedItems { get; set; } = true; + public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; + public int OptionGroupCollapsibleMin { get; set; } = 5; public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index 2ec60f7e..ab367532 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using Penumbra.Api.Enums; +using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; @@ -40,6 +41,7 @@ public interface IModGroup public int GetIndex(); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); /// Ensure that a value is valid for a group. public Setting FixSetting(Setting setting); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 671d684f..173bf57e 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -3,12 +3,14 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui.Classes; using Penumbra.Api.Enums; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.Util; namespace Penumbra.Mods.Groups; @@ -119,6 +121,9 @@ public class ImcModGroup(Mod mod) : IModGroup manipulations.Add(imc); } + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => identifier.MetaChangedItems(changedItems, GetManip(0)); + public Setting FixSetting(Setting setting) => new(setting.Value & (((1ul << OptionData.Count) - 1) | (CanBeDisabled ? 1ul << DisabledIndex : 0))); diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 7495c4b4..f587fc8f 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -4,10 +4,12 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; +using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.Util; namespace Penumbra.Mods.Groups; @@ -114,6 +116,12 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup } } + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + foreach (var container in DataContainers) + identifier.AddChangedItems(container, changedItems); + } + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) { ModSaveGroup.WriteJsonBase(jWriter, this); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index bc463c1e..7a551322 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -2,10 +2,12 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using Penumbra.Api.Enums; +using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.Util; namespace Penumbra.Mods.Groups; @@ -99,6 +101,12 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); } + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + foreach (var container in DataContainers) + identifier.AddChangedItems(container, changedItems); + } + public Setting FixSetting(Setting setting) => OptionData.Count == 0 ? Setting.Zero : new Setting(Math.Min(setting.Value, (ulong)(OptionData.Count - 1))); diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index c6a723a0..8ab8cf33 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -1,26 +1,27 @@ using Penumbra.Communication; using Penumbra.GameData.Data; -using Penumbra.GameData.Enums; -using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; using Penumbra.Services; +using Penumbra.Util; namespace Penumbra.Mods.Manager; public class ModCacheManager : IDisposable { + private readonly Configuration _config; private readonly CommunicatorService _communicator; private readonly ObjectIdentification _identifier; private readonly ModStorage _modManager; private bool _updatingItems = false; - public ModCacheManager(CommunicatorService communicator, ObjectIdentification identifier, ModStorage modStorage) + public ModCacheManager(CommunicatorService communicator, ObjectIdentification identifier, ModStorage modStorage, Configuration config) { _communicator = communicator; _identifier = identifier; _modManager = modStorage; + _config = config; _communicator.ModOptionChanged.Subscribe(OnModOptionChange, ModOptionChanged.Priority.ModCacheManager); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModCacheManager); @@ -38,75 +39,8 @@ public class ModCacheManager : IDisposable _communicator.ModDiscoveryFinished.Unsubscribe(OnModDiscoveryFinished); } - /// Compute the items changed by a given meta manipulation and put them into the changedItems dictionary. - public static void ComputeChangedItems(ObjectIdentification identifier, IDictionary changedItems, MetaManipulation manip) - { - switch (manip.ManipulationType) - { - case MetaManipulation.Type.Imc: - switch (manip.Imc.ObjectType) - { - case ObjectType.Equipment: - case ObjectType.Accessory: - identifier.Identify(changedItems, - GamePaths.Equipment.Mtrl.Path(manip.Imc.PrimaryId, GenderRace.MidlanderMale, manip.Imc.EquipSlot, manip.Imc.Variant, - "a")); - break; - case ObjectType.Weapon: - identifier.Identify(changedItems, - GamePaths.Weapon.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.Variant, "a")); - break; - case ObjectType.DemiHuman: - identifier.Identify(changedItems, - GamePaths.DemiHuman.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.EquipSlot, manip.Imc.Variant, - "a")); - break; - case ObjectType.Monster: - identifier.Identify(changedItems, - GamePaths.Monster.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.Variant, "a")); - break; - } - - break; - case MetaManipulation.Type.Eqdp: - identifier.Identify(changedItems, - GamePaths.Equipment.Mdl.Path(manip.Eqdp.SetId, Names.CombinedRace(manip.Eqdp.Gender, manip.Eqdp.Race), manip.Eqdp.Slot)); - break; - case MetaManipulation.Type.Eqp: - identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Eqp.SetId, GenderRace.MidlanderMale, manip.Eqp.Slot)); - break; - case MetaManipulation.Type.Est: - switch (manip.Est.Slot) - { - case EstManipulation.EstType.Hair: - changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Hair (Hair) {manip.Est.SetId}", null); - break; - case EstManipulation.EstType.Face: - changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Face (Face) {manip.Est.SetId}", null); - break; - case EstManipulation.EstType.Body: - identifier.Identify(changedItems, - GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), - EquipSlot.Body)); - break; - case EstManipulation.EstType.Head: - identifier.Identify(changedItems, - GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), - EquipSlot.Head)); - break; - } - - break; - case MetaManipulation.Type.Gmp: - identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Gmp.SetId, GenderRace.MidlanderMale, EquipSlot.Head)); - break; - case MetaManipulation.Type.Rsp: - changedItems.TryAdd($"{manip.Rsp.SubRace.ToName()} {manip.Rsp.Attribute.ToFullString()}", null); - break; - } - } - - private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int fromIdx) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, + int fromIdx) { switch (type) { @@ -194,16 +128,14 @@ public class ModCacheManager : IDisposable private void UpdateChangedItems(Mod mod) { - var changedItems = (SortedList)mod.ChangedItems; - changedItems.Clear(); - foreach (var gamePath in mod.AllDataContainers.SelectMany(m => m.Files.Keys.Concat(m.FileSwaps.Keys))) - _identifier.Identify(changedItems, gamePath.ToString()); + mod.ChangedItems.Clear(); - foreach (var manip in mod.AllDataContainers.SelectMany(m => m.Manipulations)) - ComputeChangedItems(_identifier, changedItems, manip); + _identifier.AddChangedItems(mod.Default, mod.ChangedItems); + foreach (var group in mod.Groups) + group.AddChangedItems(_identifier, mod.ChangedItems); - foreach(var imcGroup in mod.Groups.OfType()) - ComputeChangedItems(_identifier, changedItems, imcGroup.GetManip(0)); + if (_config.HideMachinistOffhandFromChangedItems) + mod.ChangedItems.RemoveMachinistOffhands(); mod.LowerChangedItemsString = string.Join("\0", mod.ChangedItems.Keys.Select(k => k.ToLowerInvariant())); } diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index 73571ea4..c99b7d0e 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -5,12 +5,8 @@ using Penumbra.Mods.Editor; namespace Penumbra.Mods.Manager; -public class ModImportManager : IDisposable +public class ModImportManager(ModManager modManager, Configuration config, ModEditor modEditor) : IDisposable { - private readonly ModManager _modManager; - private readonly Configuration _config; - private readonly ModEditor _modEditor; - private readonly ConcurrentQueue _modsToUnpack = new(); /// Mods need to be added thread-safely outside of iteration. @@ -26,13 +22,6 @@ public class ModImportManager : IDisposable => _modsToAdd; - public ModImportManager(ModManager modManager, Configuration config, ModEditor modEditor) - { - _modManager = modManager; - _config = config; - _modEditor = modEditor; - } - public void TryUnpacking() { if (Importing || !_modsToUnpack.TryDequeue(out var newMods)) @@ -51,7 +40,7 @@ public class ModImportManager : IDisposable if (files.Length == 0) return; - _import = new TexToolsImporter(files.Length, files, AddNewMod, _config, _modEditor, _modManager, _modEditor.Compactor); + _import = new TexToolsImporter(files.Length, files, AddNewMod, config, modEditor, modManager, modEditor.Compactor); } public bool Importing @@ -87,8 +76,8 @@ public class ModImportManager : IDisposable return false; } - _modManager.AddMod(directory); - mod = _modManager.LastOrDefault(); + modManager.AddMod(directory); + mod = modManager.LastOrDefault(); return mod != null && mod.ModPath == directory; } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 6f6eb8ce..783ef3e6 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -62,8 +62,8 @@ public sealed class Mod : IMod // Options - public readonly DefaultSubMod Default; - public readonly List Groups = []; + public readonly DefaultSubMod Default; + public readonly List Groups = []; public AppliedModData GetData(ModSettings? settings = null) { @@ -99,7 +99,7 @@ public sealed class Mod : IMod } // Cache - public readonly IReadOnlyDictionary ChangedItems = new SortedList(); + public readonly SortedList ChangedItems = new(); public string LowerChangedItemsString { get; internal set; } = string.Empty; public string AllTagsLower { get; internal set; } = string.Empty; diff --git a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs index a94c25ea..4ef1577f 100644 --- a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs @@ -123,8 +123,7 @@ public sealed class ModGroupEditDrawer( ModManager modManager, Configuration config, FilenameService filenames, - DescriptionEditPopup descriptionPopup, - MetaFileManager metaManager) : IUiService + DescriptionEditPopup descriptionPopup) : IUiService { private static ReadOnlySpan DragDropLabel => "##DragOption"u8; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 439f7be4..30384538 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -428,6 +428,14 @@ public class SettingsTab : ITab _config.Ephemeral.Save(); } }); + Checkbox("Omit Machinist Offhands in Changed Items", + "Omits all Aetherotransformers (machinist offhands) in the changed items tabs because any change on them changes all of them at the moment.\n\n" + + "Changing this triggers a rediscovery of your mods so all changed items can be updated.", + _config.HideMachinistOffhandFromChangedItems, v => + { + _config.HideMachinistOffhandFromChangedItems = v; + _modManager.DiscoverMods(); + }); Checkbox("Hide Priority Numbers in Mod Selector", "Hides the bracketed non-zero priority numbers displayed in the mod selector when there is enough space for them.", _config.HidePrioritiesInSelector, v => _config.HidePrioritiesInSelector = v); diff --git a/Penumbra/Util/IdentifierExtensions.cs b/Penumbra/Util/IdentifierExtensions.cs new file mode 100644 index 00000000..392a5aba --- /dev/null +++ b/Penumbra/Util/IdentifierExtensions.cs @@ -0,0 +1,115 @@ +using OtterGui.Classes; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.SubMods; + +namespace Penumbra.Util; + +public static class IdentifierExtensions +{ + /// Compute the items changed by a given meta manipulation and put them into the changedItems dictionary. + public static void MetaChangedItems(this ObjectIdentification identifier, IDictionary changedItems, + MetaManipulation manip) + { + switch (manip.ManipulationType) + { + case MetaManipulation.Type.Imc: + switch (manip.Imc.ObjectType) + { + case ObjectType.Equipment: + case ObjectType.Accessory: + identifier.Identify(changedItems, + GamePaths.Equipment.Mtrl.Path(manip.Imc.PrimaryId, GenderRace.MidlanderMale, manip.Imc.EquipSlot, manip.Imc.Variant, + "a")); + break; + case ObjectType.Weapon: + identifier.Identify(changedItems, + GamePaths.Weapon.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.Variant, "a")); + break; + case ObjectType.DemiHuman: + identifier.Identify(changedItems, + GamePaths.DemiHuman.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.EquipSlot, manip.Imc.Variant, + "a")); + break; + case ObjectType.Monster: + identifier.Identify(changedItems, + GamePaths.Monster.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.Variant, "a")); + break; + } + + break; + case MetaManipulation.Type.Eqdp: + identifier.Identify(changedItems, + GamePaths.Equipment.Mdl.Path(manip.Eqdp.SetId, Names.CombinedRace(manip.Eqdp.Gender, manip.Eqdp.Race), manip.Eqdp.Slot)); + break; + case MetaManipulation.Type.Eqp: + identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Eqp.SetId, GenderRace.MidlanderMale, manip.Eqp.Slot)); + break; + case MetaManipulation.Type.Est: + switch (manip.Est.Slot) + { + case EstManipulation.EstType.Hair: + changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Hair (Hair) {manip.Est.SetId}", null); + break; + case EstManipulation.EstType.Face: + changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Face (Face) {manip.Est.SetId}", null); + break; + case EstManipulation.EstType.Body: + identifier.Identify(changedItems, + GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), + EquipSlot.Body)); + break; + case EstManipulation.EstType.Head: + identifier.Identify(changedItems, + GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), + EquipSlot.Head)); + break; + } + + break; + case MetaManipulation.Type.Gmp: + identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Gmp.SetId, GenderRace.MidlanderMale, EquipSlot.Head)); + break; + case MetaManipulation.Type.Rsp: + changedItems.TryAdd($"{manip.Rsp.SubRace.ToName()} {manip.Rsp.Attribute.ToFullString()}", null); + break; + } + } + + public static void AddChangedItems(this ObjectIdentification identifier, IModDataContainer container, + IDictionary changedItems) + { + foreach (var gamePath in container.Files.Keys.Concat(container.FileSwaps.Keys)) + identifier.Identify(changedItems, gamePath.ToString()); + + foreach (var manip in container.Manipulations) + MetaChangedItems(identifier, changedItems, manip); + } + + public static void RemoveMachinistOffhands(this SortedList changedItems) + { + for (var i = 0; i < changedItems.Count; i++) + { + { + var value = changedItems.Values[i]; + if (value is EquipItem { Type: FullEquipType.GunOff }) + changedItems.RemoveAt(i--); + } + } + } + + public static void RemoveMachinistOffhands(this SortedList, object?)> changedItems) + { + for (var i = 0; i < changedItems.Count; i++) + { + { + var value = changedItems.Values[i].Item2; + if (value is EquipItem { Type: FullEquipType.GunOff }) + changedItems.RemoveAt(i--); + } + } + } +} From 2585de8b21e25fd62cf2295d58ac2520e526752b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 21 May 2024 22:01:20 +0200 Subject: [PATCH 0604/1381] Cleanup group drawing somewhat. --- Penumbra/Mods/Editor/ModNormalizer.cs | 16 +- Penumbra/Mods/Groups/IModGroup.cs | 3 + Penumbra/Mods/Groups/ImcModGroup.cs | 5 + Penumbra/Mods/Groups/MultiModGroup.cs | 4 + Penumbra/Mods/Groups/SingleModGroup.cs | 4 + .../Manager/OptionEditor/ModGroupEditor.cs | 94 +-- .../UI/ModsTab/{ => Groups}/AddGroupDrawer.cs | 32 +- .../UI/ModsTab/Groups/IModGroupEditDrawer.cs | 6 + .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 138 ++++ .../UI/ModsTab/{ => Groups}/ModGroupDrawer.cs | 36 +- .../UI/ModsTab/Groups/ModGroupEditDrawer.cs | 360 +++++++++ .../ModsTab/Groups/MultiModGroupEditDrawer.cs | 63 ++ .../Groups/SingleModGroupEditDrawer.cs | 68 ++ Penumbra/UI/ModsTab/MetaManipulationDrawer.cs | 105 +++ Penumbra/UI/ModsTab/ModGroupEditDrawer.cs | 687 ------------------ Penumbra/UI/ModsTab/ModPanelEditTab.cs | 1 + Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 1 + 17 files changed, 841 insertions(+), 782 deletions(-) rename Penumbra/UI/ModsTab/{ => Groups}/AddGroupDrawer.cs (83%) create mode 100644 Penumbra/UI/ModsTab/Groups/IModGroupEditDrawer.cs create mode 100644 Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs rename Penumbra/UI/ModsTab/{ => Groups}/ModGroupDrawer.cs (85%) create mode 100644 Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs create mode 100644 Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs create mode 100644 Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs create mode 100644 Penumbra/UI/ModsTab/MetaManipulationDrawer.cs delete mode 100644 Penumbra/UI/ModsTab/ModGroupEditDrawer.cs diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 437600c9..58e4fc08 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,4 +1,3 @@ -using System; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; @@ -279,19 +278,8 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) private void ApplyRedirections() { foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) - { - switch (group) - { - case SingleModGroup single: - foreach (var (option, optionIdx) in single.OptionData.WithIndex()) - _modManager.OptionEditor.SetFiles(option, _redirections[groupIdx + 1][optionIdx]); - break; - case MultiModGroup multi: - foreach (var (option, optionIdx) in multi.OptionData.WithIndex()) - _modManager.OptionEditor.SetFiles(option, _redirections[groupIdx + 1][optionIdx]); - break; - } - } + foreach (var (container, containerIdx) in group.DataContainers.WithIndex()) + _modManager.OptionEditor.SetFiles(container, _redirections[groupIdx + 1][containerIdx]); ++Step; } diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index ab367532..fcc8c093 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -5,6 +5,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.UI.ModsTab.Groups; namespace Penumbra.Mods.Groups; @@ -40,6 +41,8 @@ public interface IModGroup public int GetIndex(); + public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer); + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 173bf57e..d2c41f34 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -10,6 +10,8 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.UI.ModsTab; +using Penumbra.UI.ModsTab.Groups; using Penumbra.Util; namespace Penumbra.Mods.Groups; @@ -89,6 +91,9 @@ public class ImcModGroup(Mod mod) : IModGroup public int GetIndex() => ModGroup.GetIndex(this); + public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) + => new ImcModGroupEditDrawer(editDrawer, this); + private ushort GetCurrentMask(Setting setting) { var mask = DefaultEntry.AttributeMask; diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index f587fc8f..7fc9acb3 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -9,6 +9,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.UI.ModsTab.Groups; using Penumbra.Util; namespace Penumbra.Mods.Groups; @@ -107,6 +108,9 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public int GetIndex() => ModGroup.GetIndex(this); + public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) + => new MultiModGroupEditDrawer(editDrawer, this); + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { foreach (var (option, index) in OptionData.WithIndex().OrderByDescending(o => o.Value.Priority)) diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 7a551322..4eec0746 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -7,6 +7,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; +using Penumbra.UI.ModsTab.Groups; using Penumbra.Util; namespace Penumbra.Mods.Groups; @@ -93,6 +94,9 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public int GetIndex() => ModGroup.GetIndex(this); + public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) + => new SingleModGroupEditDrawer(editDrawer, this); + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) { if (OptionData.Count == 0) diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 3c00dcc1..969ad3fa 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -37,8 +37,8 @@ public class ModGroupEditor( SingleModGroupEditor singleEditor, MultiModGroupEditor multiEditor, ImcModGroupEditor imcEditor, - CommunicatorService Communicator, - SaveService SaveService, + CommunicatorService communicator, + SaveService saveService, Configuration Config) : IService { public SingleModGroupEditor SingleEditor @@ -57,8 +57,8 @@ public class ModGroupEditor( return; group.DefaultSettings = defaultOption; - SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, group.Mod, group, null, null, -1); + saveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, group.Mod, group, null, null, -1); } /// Rename an option group if possible. @@ -68,10 +68,10 @@ public class ModGroupEditor( if (oldName == newName || !VerifyFileName(group.Mod, group, newName, true)) return; - SaveService.ImmediateDelete(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + saveService.ImmediateDelete(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); group.Name = newName; - SaveService.ImmediateSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, group.Mod, group, null, null, -1); + saveService.ImmediateSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, group.Mod, group, null, null, -1); } /// Delete a given option group. Fires an event to prepare before actually deleting. @@ -79,22 +79,22 @@ public class ModGroupEditor( { var mod = group.Mod; var idx = group.GetIndex(); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, null, null, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, null, null, -1); mod.Groups.RemoveAt(idx); - SaveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, null, null, null, idx); + saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, null, null, null, idx); } /// Move the index of a given option group. public void MoveModGroup(IModGroup group, int groupIdxTo) { - var mod = group.Mod; + var mod = group.Mod; var idxFrom = group.GetIndex(); if (!mod.Groups.Move(idxFrom, groupIdxTo)) return; - SaveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, group, null, null, idxFrom); + saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, group, null, null, idxFrom); } /// Change the internal priority of the given option group. @@ -104,8 +104,8 @@ public class ModGroupEditor( return; group.Priority = newPriority; - SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, group.Mod, group, null, null, -1); + saveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, group.Mod, group, null, null, -1); } /// Change the description of the given option group. @@ -115,8 +115,8 @@ public class ModGroupEditor( return; group.Description = newDescription; - SaveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, group.Mod, group, null, null, -1); + saveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, group.Mod, group, null, null, -1); } /// Rename the given option. @@ -126,8 +126,8 @@ public class ModGroupEditor( return; option.Name = newName; - SaveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); + saveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); } /// Change the description of the given option. @@ -137,8 +137,8 @@ public class ModGroupEditor( return; option.Description = newDescription; - SaveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); + saveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); } /// Set the meta manipulations for a given option. Replaces existing manipulations. @@ -148,10 +148,10 @@ public class ModGroupEditor( && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) return; - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); subMod.Manipulations.SetTo(manipulations); - SaveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } /// Set the file redirections for a given option. Replaces existing redirections. @@ -160,10 +160,10 @@ public class ModGroupEditor( if (subMod.Files.SetEquals(replacements)) return; - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); subMod.Files.SetTo(replacements); - SaveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. @@ -173,8 +173,8 @@ public class ModGroupEditor( subMod.Files.AddFrom(additions); if (oldCount != subMod.Files.Count) { - SaveService.QueueSave(new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + saveService.QueueSave(new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } } @@ -184,10 +184,10 @@ public class ModGroupEditor( if (subMod.FileSwaps.SetEquals(swaps)) return; - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); subMod.FileSwaps.SetTo(swaps); - SaveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); - Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); + saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } /// Verify that a new option group name is unique in this mod. @@ -227,45 +227,45 @@ public class ModGroupEditor( => group switch { SingleModGroup s => SingleEditor.AddOption(s, option), - MultiModGroup m => MultiEditor.AddOption(m, option), - ImcModGroup i => ImcEditor.AddOption(i, option), - _ => null, + MultiModGroup m => MultiEditor.AddOption(m, option), + ImcModGroup i => ImcEditor.AddOption(i, option), + _ => null, }; public IModOption? AddOption(IModGroup group, string newName) => group switch { SingleModGroup s => SingleEditor.AddOption(s, newName), - MultiModGroup m => MultiEditor.AddOption(m, newName), - ImcModGroup i => ImcEditor.AddOption(i, newName), - _ => null, + MultiModGroup m => MultiEditor.AddOption(m, newName), + ImcModGroup i => ImcEditor.AddOption(i, newName), + _ => null, }; public IModGroup? AddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) => type switch { GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), - GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), - GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, saveType), - _ => null, + GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), + GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, saveType), + _ => null, }; public (IModGroup?, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string name, SaveType saveType = SaveType.ImmediateSync) => type switch { GroupType.Single => SingleEditor.FindOrAddModGroup(mod, name, saveType), - GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), - GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), - _ => (null, -1, false), + GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), + _ => (null, -1, false), }; public (IModOption?, int, bool) FindOrAddOption(IModGroup group, string name, SaveType saveType = SaveType.ImmediateSync) => group switch { SingleModGroup s => SingleEditor.FindOrAddOption(s, name, saveType), - MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), - ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), - _ => (null, -1, false), + MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), + ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), + _ => (null, -1, false), }; public void MoveOption(IModOption option, int toIdx) diff --git a/Penumbra/UI/ModsTab/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs similarity index 83% rename from Penumbra/UI/ModsTab/AddGroupDrawer.cs rename to Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index 79c1bf9d..06cb4154 100644 --- a/Penumbra/UI/ModsTab/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -12,25 +12,25 @@ using Penumbra.Mods.Manager; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.UI.Classes; -namespace Penumbra.UI.ModsTab; +namespace Penumbra.UI.ModsTab.Groups; public class AddGroupDrawer : IUiService { - private string _groupName = string.Empty; - private bool _groupNameValid = false; + private string _groupName = string.Empty; + private bool _groupNameValid = false; - private ImcManipulation _imcManip = new(EquipSlot.Head, 1, 1, new ImcEntry()); - private ImcEntry _defaultEntry; - private bool _imcFileExists; - private bool _entryExists; - private bool _entryInvalid; + private ImcManipulation _imcManip = new(EquipSlot.Head, 1, 1, new ImcEntry()); + private ImcEntry _defaultEntry; + private bool _imcFileExists; + private bool _entryExists; + private bool _entryInvalid; private readonly MetaFileManager _metaManager; - private readonly ModManager _modManager; + private readonly ModManager _modManager; public AddGroupDrawer(MetaFileManager metaManager, ModManager modManager) { _metaManager = metaManager; - _modManager = modManager; + _modManager = modManager; UpdateEntry(); } @@ -61,7 +61,7 @@ public class AddGroupDrawer : IUiService return; _modManager.OptionEditor.AddModGroup(mod, GroupType.Single, _groupName); - _groupName = string.Empty; + _groupName = string.Empty; _groupNameValid = false; } @@ -74,7 +74,7 @@ public class AddGroupDrawer : IUiService return; _modManager.OptionEditor.AddModGroup(mod, GroupType.Multi, _groupName); - _groupName = string.Empty; + _groupName = string.Empty; _groupNameValid = false; } @@ -126,7 +126,7 @@ public class AddGroupDrawer : IUiService width, !_groupNameValid || _entryInvalid)) { _modManager.OptionEditor.ImcEditor.AddModGroup(mod, _groupName, _imcManip); - _groupName = string.Empty; + _groupName = string.Empty; _groupNameValid = false; } @@ -150,12 +150,12 @@ public class AddGroupDrawer : IUiService } catch (Exception) { - _defaultEntry = new ImcEntry(); + _defaultEntry = new ImcEntry(); _imcFileExists = false; - _entryExists = false; + _entryExists = false; } - _imcManip = _imcManip.Copy(_entryExists ? _defaultEntry : new ImcEntry()); + _imcManip = _imcManip.Copy(_entryExists ? _defaultEntry : new ImcEntry()); _entryInvalid = !_imcManip.Validate(true); } } diff --git a/Penumbra/UI/ModsTab/Groups/IModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/IModGroupEditDrawer.cs new file mode 100644 index 00000000..d7114147 --- /dev/null +++ b/Penumbra/UI/ModsTab/Groups/IModGroupEditDrawer.cs @@ -0,0 +1,6 @@ +namespace Penumbra.UI.ModsTab.Groups; + +public interface IModGroupEditDrawer +{ + public void Draw(); +} diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs new file mode 100644 index 00000000..2418c5cb --- /dev/null +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -0,0 +1,138 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Classes; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Manager.OptionEditor; +using Penumbra.Mods.SubMods; + +namespace Penumbra.UI.ModsTab.Groups; + +public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGroup group) : IModGroupEditDrawer +{ + public void Draw() + { + using (ImUtf8.Group()) + { + ImUtf8.Text("Object Type"u8); + if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) + ImUtf8.Text("Slot"u8); + ImUtf8.Text("Primary ID"); + if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) + ImUtf8.Text("Secondary ID"); + ImUtf8.Text("Variant"u8); + + ImUtf8.TextFrameAligned("Material ID"u8); + ImUtf8.TextFrameAligned("Material Animation ID"u8); + ImUtf8.TextFrameAligned("Decal ID"u8); + ImUtf8.TextFrameAligned("VFX ID"u8); + ImUtf8.TextFrameAligned("Sound ID"u8); + ImUtf8.TextFrameAligned("Can Be Disabled"u8); + ImUtf8.TextFrameAligned("Default Attributes"u8); + } + + ImGui.SameLine(); + + var attributeCache = new ImcAttributeCache(group); + + using (ImUtf8.Group()) + { + ImUtf8.Text(group.ObjectType.ToName()); + if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) + ImUtf8.Text(group.EquipSlot.ToName()); + ImUtf8.Text($"{group.PrimaryId.Id}"); + if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) + ImUtf8.Text($"{group.SecondaryId.Id}"); + ImUtf8.Text($"{group.Variant.Id}"); + + ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialAnimationId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.DecalId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.VfxId}"); + ImUtf8.TextFrameAligned($"{group.DefaultEntry.SoundId}"); + + var canBeDisabled = group.CanBeDisabled; + if (ImUtf8.Checkbox("##disabled"u8, ref canBeDisabled)) + editor.ModManager.OptionEditor.ImcEditor.ChangeCanBeDisabled(group, canBeDisabled, SaveType.Queue); + + var defaultDisabled = group.DefaultDisabled; + ImUtf8.SameLineInner(); + if (ImUtf8.Checkbox("##defaultDisabled"u8, ref defaultDisabled)) + editor.ModManager.OptionEditor.ChangeModGroupDefaultOption(group, + group.DefaultSettings.SetBit(ImcModGroup.DisabledIndex, defaultDisabled)); + + DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, group.DefaultEntry.AttributeMask, group); + } + + + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImRaii.PushId(optionIdx); + editor.DrawOptionPosition(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionDefaultMultiBehaviour(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionName(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDelete(option); + + ImUtf8.SameLineInner(); + ImGui.Dummy(new Vector2(editor.PriorityWidth, 0)); + + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + editor.OptionIdxSelectable.X + ImUtf8.ItemInnerSpacing.X * 2 + ImUtf8.FrameHeight); + DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); + } + + DrawNewOption(attributeCache); + return; + + static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data) + { + for (var i = 0; i < ImcEntry.NumAttributes; ++i) + { + using var id = ImRaii.PushId(i); + var value = (mask & 1 << i) != 0; + using (ImRaii.Disabled(!cache.CanChange(i))) + { + if (ImUtf8.Checkbox(TerminatedByteString.Empty, ref value)) + { + if (data is ImcModGroup g) + editor.ChangeDefaultAttribute(g, cache, i, value); + else + editor.ChangeOptionAttribute((ImcSubMod)data, cache, i, value); + } + } + + ImUtf8.HoverTooltip($"{(char)('A' + i)}"); + if (i != 9) + ImUtf8.SameLineInner(); + } + } + } + + private void DrawNewOption(in ImcAttributeCache cache) + { + if (cache.LowestUnsetMask == 0) + return; + + var name = editor.DrawNewOptionBase(group, group.Options.Count); + var validName = name.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, !validName)) + { + editor.ModManager.OptionEditor.ImcEditor.AddOption(group, cache, name); + editor.NewOptionName = null; + } + } +} diff --git a/Penumbra/UI/ModsTab/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs similarity index 85% rename from Penumbra/UI/ModsTab/ModGroupDrawer.cs rename to Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index e9b0b396..dec77430 100644 --- a/Penumbra/UI/ModsTab/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -11,7 +11,7 @@ using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; -namespace Penumbra.UI.ModsTab; +namespace Penumbra.UI.ModsTab.Groups; public sealed class ModGroupDrawer(Configuration config, CollectionManager collectionManager) : IUiService { @@ -63,8 +63,8 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle /// private void DrawSingleGroupCombo(IModGroup group, int groupIdx, Setting setting) { - using var id = ImRaii.PushId(groupIdx); - var selectedOption = setting.AsIndex; + using var id = ImRaii.PushId(groupIdx); + var selectedOption = setting.AsIndex; ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); var options = group.Options; using (var combo = ImRaii.Combo(string.Empty, options[selectedOption].Name)) @@ -97,10 +97,10 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle /// private void DrawSingleGroupRadio(IModGroup group, int groupIdx, Setting setting) { - using var id = ImRaii.PushId(groupIdx); - var selectedOption = setting.AsIndex; - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - var options = group.Options; + using var id = ImRaii.PushId(groupIdx); + var selectedOption = setting.AsIndex; + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var options = group.Options; DrawCollapseHandling(options, minWidth, DrawOptions); Widget.EndFramedGroup(); @@ -110,8 +110,8 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle { for (var idx = 0; idx < group.Options.Count; ++idx) { - using var i = ImRaii.PushId(idx); - var option = options[idx]; + using var i = ImRaii.PushId(idx); + var option = options[idx]; if (ImGui.RadioButton(option.Name, selectedOption == idx)) SetModSetting(group, groupIdx, Setting.Single(idx)); @@ -130,9 +130,9 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle /// private void DrawMultiGroup(IModGroup group, int groupIdx, Setting setting) { - using var id = ImRaii.PushId(groupIdx); - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - var options = group.Options; + using var id = ImRaii.PushId(groupIdx); + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var options = group.Options; DrawCollapseHandling(options, minWidth, DrawOptions); Widget.EndFramedGroup(); @@ -147,9 +147,9 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle { for (var idx = 0; idx < options.Count; ++idx) { - using var i = ImRaii.PushId(idx); - var option = options[idx]; - var enabled = setting.HasFlag(idx); + using var i = ImRaii.PushId(idx); + var option = options[idx]; + var enabled = setting.HasFlag(idx); if (ImGui.Checkbox(option.Name, ref enabled)) SetModSetting(group, groupIdx, setting.SetBit(idx, enabled)); @@ -187,8 +187,8 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle } else { - var collapseId = ImGui.GetID("Collapse"); - var shown = ImGui.GetStateStorage().GetBool(collapseId, true); + var collapseId = ImGui.GetID("Collapse"); + var shown = ImGui.GetStateStorage().GetBool(collapseId, true); var buttonTextShow = $"Show {options.Count} Options"; var buttonTextHide = $"Hide {options.Count} Options"; var buttonWidth = Math.Max(ImGui.CalcTextSize(buttonTextShow).X, ImGui.CalcTextSize(buttonTextHide).X) @@ -204,7 +204,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle } - var width = Math.Max(ImGui.GetItemRectSize().X, minWidth); + var width = Math.Max(ImGui.GetItemRectSize().X, minWidth); var endPos = ImGui.GetCursorPos(); ImGui.SetCursorPos(pos); if (ImGui.Button(buttonTextHide, new Vector2(width, 0))) diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs new file mode 100644 index 00000000..e7d70922 --- /dev/null +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -0,0 +1,360 @@ +using Dalamud.Interface; +using Dalamud.Interface.Internal.Notifications; +using ImGuiNET; +using OtterGui; +using OtterGui.Classes; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using OtterGui.Text.EndObjects; +using Penumbra.Mods; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.ModsTab.Groups; + +public sealed class ModGroupEditDrawer( + ModManager modManager, + Configuration config, + FilenameService filenames, + DescriptionEditPopup descriptionPopup) : IUiService +{ + private static ReadOnlySpan DragDropLabel + => "##DragOption"u8; + + internal readonly ModManager ModManager = modManager; + internal readonly Queue ActionQueue = new(); + + internal Vector2 OptionIdxSelectable; + internal Vector2 AvailableWidth; + internal float PriorityWidth; + + internal string? NewOptionName; + private IModGroup? _newOptionGroup; + + private Vector2 _buttonSize; + private float _groupNameWidth; + private float _optionNameWidth; + private float _spacing; + private bool _deleteEnabled; + + private string? _currentGroupName; + private ModPriority? _currentGroupPriority; + private IModGroup? _currentGroupEdited; + private bool _isGroupNameValid = true; + + private IModGroup? _dragDropGroup; + private IModOption? _dragDropOption; + + public void Draw(Mod mod) + { + PrepareStyle(); + + using var id = ImUtf8.PushId("##GroupEdit"u8); + foreach (var (group, groupIdx) in mod.Groups.WithIndex()) + DrawGroup(group, groupIdx); + + while (ActionQueue.TryDequeue(out var action)) + action.Invoke(); + } + + private void DrawGroup(IModGroup group, int idx) + { + using var id = ImUtf8.PushId(idx); + using var frame = ImRaii.FramedGroup($"Group #{idx + 1}"); + DrawGroupNameRow(group, idx); + group.EditDrawer(this).Draw(); + } + + private void DrawGroupNameRow(IModGroup group, int idx) + { + DrawGroupName(group); + ImUtf8.SameLineInner(); + DrawGroupMoveButtons(group, idx); + ImUtf8.SameLineInner(); + DrawGroupOpenFile(group, idx); + ImUtf8.SameLineInner(); + DrawGroupDescription(group); + ImUtf8.SameLineInner(); + DrawGroupDelete(group); + ImUtf8.SameLineInner(); + DrawGroupPriority(group); + } + + private void DrawGroupName(IModGroup group) + { + var text = _currentGroupEdited == group ? _currentGroupName ?? group.Name : group.Name; + ImGui.SetNextItemWidth(_groupNameWidth); + using var border = ImRaii.PushFrameBorder(UiHelpers.ScaleX2, Colors.RegexWarningBorder, !_isGroupNameValid); + if (ImUtf8.InputText("##GroupName"u8, ref text)) + { + _currentGroupEdited = group; + _currentGroupName = text; + _isGroupNameValid = text == group.Name || ModGroupEditor.VerifyFileName(group.Mod, group, text, false); + } + + if (ImGui.IsItemDeactivated()) + { + if (_currentGroupName != null && _isGroupNameValid) + ModManager.OptionEditor.RenameModGroup(group, _currentGroupName); + _currentGroupName = null; + _currentGroupEdited = null; + _isGroupNameValid = true; + } + + var tt = _isGroupNameValid + ? "Change the Group name."u8 + : "Current name can not be used for this group."u8; + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tt); + } + + private void DrawGroupDelete(IModGroup group) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Trash, !_deleteEnabled)) + ActionQueue.Enqueue(() => ModManager.OptionEditor.DeleteModGroup(group)); + + if (_deleteEnabled) + ImUtf8.HoverTooltip("Delete this option group."u8); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + $"Delete this option group.\nHold {config.DeleteModModifier} while clicking to delete."); + } + + private void DrawGroupPriority(IModGroup group) + { + var priority = _currentGroupEdited == group + ? (_currentGroupPriority ?? group.Priority).Value + : group.Priority.Value; + ImGui.SetNextItemWidth(PriorityWidth); + if (ImGui.InputInt("##GroupPriority", ref priority, 0, 0)) + { + _currentGroupEdited = group; + _currentGroupPriority = new ModPriority(priority); + } + + if (ImGui.IsItemDeactivated()) + { + if (_currentGroupPriority.HasValue) + ModManager.OptionEditor.ChangeGroupPriority(group, _currentGroupPriority.Value); + _currentGroupEdited = null; + _currentGroupPriority = null; + } + + ImGuiUtil.HoverTooltip("Group Priority"); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawGroupDescription(IModGroup group) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Edit, "Edit group description."u8)) + descriptionPopup.Open(group); + } + + private void DrawGroupMoveButtons(IModGroup group, int idx) + { + var isFirst = idx == 0; + if (ImUtf8.IconButton(FontAwesomeIcon.ArrowUp, isFirst)) + ActionQueue.Enqueue(() => ModManager.OptionEditor.MoveModGroup(group, idx - 1)); + + if (isFirst) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Can not move this group further upwards."u8); + else + ImUtf8.HoverTooltip($"Move this group up to group {idx}."); + + + ImUtf8.SameLineInner(); + var isLast = idx == group.Mod.Groups.Count - 1; + if (ImUtf8.IconButton(FontAwesomeIcon.ArrowDown, isLast)) + ActionQueue.Enqueue(() => ModManager.OptionEditor.MoveModGroup(group, idx + 1)); + + if (isLast) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Can not move this group further downwards."u8); + else + ImUtf8.HoverTooltip($"Move this group down to group {idx + 2}."); + } + + private void DrawGroupOpenFile(IModGroup group, int idx) + { + var fileName = filenames.OptionGroupFile(group.Mod, idx, config.ReplaceNonAsciiOnImport); + var fileExists = File.Exists(fileName); + if (ImUtf8.IconButton(FontAwesomeIcon.FileExport, !fileExists)) + try + { + Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); + } + catch (Exception e) + { + Penumbra.Messager.NotificationMessage(e, "Could not open editor.", NotificationType.Error); + } + + if (fileExists) + ImUtf8.HoverTooltip($"Open the {group.Name} json file in the text editor of your choice."); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"The {group.Name} json file does not exist."); + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionPosition(IModGroup group, IModOption option, int optionIdx) + { + ImGui.AlignTextToFramePadding(); + ImUtf8.Selectable($"Option #{optionIdx + 1}", false, size: OptionIdxSelectable); + Target(group, optionIdx); + Source(option); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionDefaultSingleBehaviour(IModGroup group, IModOption option, int optionIdx) + { + var isDefaultOption = group.DefaultSettings.AsIndex == optionIdx; + if (ImUtf8.RadioButton("##default"u8, isDefaultOption)) + ModManager.OptionEditor.ChangeModGroupDefaultOption(group, Setting.Single(optionIdx)); + ImUtf8.HoverTooltip($"Set {option.Name} as the default choice for this group."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionDefaultMultiBehaviour(IModGroup group, IModOption option, int optionIdx) + { + var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); + if (ImUtf8.Checkbox("##default"u8, ref isDefaultOption)) + ModManager.OptionEditor.ChangeModGroupDefaultOption(group, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); + ImUtf8.HoverTooltip($"{(isDefaultOption ? "Disable"u8 : "Enable"u8)} {option.Name} per default in this group."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionDescription(IModOption option) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Edit, "Edit option description."u8)) + descriptionPopup.Open(option); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionPriority(MultiSubMod option) + { + var priority = option.Priority.Value; + ImGui.SetNextItemWidth(PriorityWidth); + if (ImUtf8.InputScalarOnDeactivated("##Priority"u8, ref priority)) + ModManager.OptionEditor.MultiEditor.ChangeOptionPriority(option, new ModPriority(priority)); + ImUtf8.HoverTooltip("Option priority inside the mod."u8); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionName(IModOption option) + { + var name = option.Name; + ImGui.SetNextItemWidth(_optionNameWidth); + if (ImUtf8.InputTextOnDeactivated("##Name"u8, ref name)) + ModManager.OptionEditor.RenameOption(option, name); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void DrawOptionDelete(IModOption option) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Trash, !_deleteEnabled)) + ActionQueue.Enqueue(() => ModManager.OptionEditor.DeleteOption(option)); + + if (_deleteEnabled) + ImUtf8.HoverTooltip("Delete this option."u8); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + $"Delete this option.\nHold {config.DeleteModModifier} while clicking to delete."); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal string DrawNewOptionBase(IModGroup group, int count) + { + ImUtf8.Selectable($"Option #{count + 1}", false, size: OptionIdxSelectable); + Target(group, count); + + ImUtf8.SameLineInner(); + ImUtf8.IconDummy(); + + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(_optionNameWidth); + var newName = _newOptionGroup == group + ? NewOptionName ?? string.Empty + : string.Empty; + if (ImUtf8.InputText("##newOption"u8, ref newName, "Add new option..."u8)) + { + NewOptionName = newName; + _newOptionGroup = group; + } + + ImUtf8.SameLineInner(); + return newName; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void Source(IModOption option) + { + if (option.Group is not ITexToolsGroup) + return; + + using var source = ImUtf8.DragDropSource(); + if (!source) + return; + + if (!DragDropSource.SetPayload(DragDropLabel)) + { + _dragDropGroup = option.Group; + _dragDropOption = option; + } + + ImGui.TextUnformatted($"Dragging option {option.Name} from group {option.Group.Name}..."); + } + + private void Target(IModGroup group, int optionIdx) + { + if (group is not ITexToolsGroup) + return; + + if (_dragDropGroup != group && _dragDropGroup != null && group is MultiModGroup { Options.Count: >= IModGroup.MaxMultiOptions }) + return; + + using var target = ImRaii.DragDropTarget(); + if (!target.Success || !DragDropTarget.CheckPayload(DragDropLabel)) + return; + + if (_dragDropGroup != null && _dragDropOption != null) + { + if (_dragDropGroup == group) + { + var sourceOption = _dragDropOption; + ActionQueue.Enqueue(() => ModManager.OptionEditor.MoveOption(sourceOption, optionIdx)); + } + else + { + // Move from one group to another by deleting, then adding, then moving the option. + var sourceOption = _dragDropOption; + ActionQueue.Enqueue(() => + { + ModManager.OptionEditor.DeleteOption(sourceOption); + if (ModManager.OptionEditor.AddOption(group, sourceOption) is { } newOption) + ModManager.OptionEditor.MoveOption(newOption, optionIdx); + }); + } + } + + _dragDropGroup = null; + _dragDropOption = null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void PrepareStyle() + { + var totalWidth = 400f * ImUtf8.GlobalScale; + _buttonSize = new Vector2(ImUtf8.FrameHeight); + PriorityWidth = 50 * ImUtf8.GlobalScale; + AvailableWidth = new Vector2(totalWidth + 3 * _spacing + 2 * _buttonSize.X + PriorityWidth, 0); + _groupNameWidth = totalWidth - 3 * (_buttonSize.X + _spacing); + _spacing = ImGui.GetStyle().ItemInnerSpacing.X; + OptionIdxSelectable = ImUtf8.CalcTextSize("Option #88."u8); + _optionNameWidth = totalWidth - OptionIdxSelectable.X - _buttonSize.X - 2 * _spacing; + _deleteEnabled = config.DeleteModModifier.IsActive(); + } +} diff --git a/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs new file mode 100644 index 00000000..e6701a03 --- /dev/null +++ b/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs @@ -0,0 +1,63 @@ +using Dalamud.Interface; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.Mods.Groups; + +namespace Penumbra.UI.ModsTab.Groups; + +public readonly struct MultiModGroupEditDrawer(ModGroupEditDrawer editor, MultiModGroup group) : IModGroupEditDrawer +{ + public void Draw() + { + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImRaii.PushId(optionIdx); + editor.DrawOptionPosition(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionDefaultMultiBehaviour(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionName(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDelete(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionPriority(option); + } + + DrawNewOption(); + DrawConvertButton(); + } + + private void DrawConvertButton() + { + var g = group; + var e = editor.ModManager.OptionEditor.MultiEditor; + if (ImUtf8.Button("Convert to Single Group"u8, editor.AvailableWidth)) + editor.ActionQueue.Enqueue(() => e.ChangeToSingle(g)); + } + + private void DrawNewOption() + { + var count = group.Options.Count; + if (count >= IModGroup.MaxMultiOptions) + return; + + var name = editor.DrawNewOptionBase(group, count); + + var validName = name.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, !validName)) + { + editor.ModManager.OptionEditor.MultiEditor.AddOption(group, name); + editor.NewOptionName = null; + } + } +} diff --git a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs new file mode 100644 index 00000000..75fbc63a --- /dev/null +++ b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs @@ -0,0 +1,68 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.Mods.Groups; + +namespace Penumbra.UI.ModsTab.Groups; + +public readonly struct SingleModGroupEditDrawer(ModGroupEditDrawer editor, SingleModGroup group) : IModGroupEditDrawer +{ + public void Draw() + { + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImRaii.PushId(optionIdx); + editor.DrawOptionPosition(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionDefaultSingleBehaviour(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionName(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDelete(option); + + ImUtf8.SameLineInner(); + ImGui.Dummy(new Vector2(editor.PriorityWidth, 0)); + } + + DrawNewOption(); + DrawConvertButton(); + } + + private void DrawConvertButton() + { + var convertible = group.Options.Count <= IModGroup.MaxMultiOptions; + var g = group; + var e = editor.ModManager.OptionEditor.SingleEditor; + if (ImUtf8.ButtonEx("Convert to Multi Group", editor.AvailableWidth, !convertible)) + editor.ActionQueue.Enqueue(() => e.ChangeToMulti(g)); + if (!convertible) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + "Can not convert to multi group since maximum number of options is exceeded."u8); + } + + private void DrawNewOption() + { + var count = group.Options.Count; + if (count >= int.MaxValue) + return; + + var name = editor.DrawNewOptionBase(group, count); + + var validName = name.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, !validName)) + { + editor.ModManager.OptionEditor.SingleEditor.AddOption(group, name); + editor.NewOptionName = null; + } + } +} diff --git a/Penumbra/UI/ModsTab/MetaManipulationDrawer.cs b/Penumbra/UI/ModsTab/MetaManipulationDrawer.cs new file mode 100644 index 00000000..1f2273b5 --- /dev/null +++ b/Penumbra/UI/ModsTab/MetaManipulationDrawer.cs @@ -0,0 +1,105 @@ +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.Meta.Manipulations; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.ModsTab; + +public static class MetaManipulationDrawer +{ + public static bool DrawObjectType(ref ImcManipulation manip, float width = 110) + { + var ret = Combos.ImcType("##imcType", manip.ObjectType, out var type, width); + ImUtf8.HoverTooltip("Object Type"u8); + + if (ret) + { + var equipSlot = type switch + { + ObjectType.Equipment => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, + ObjectType.DemiHuman => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, + ObjectType.Accessory => manip.EquipSlot.IsAccessory() ? manip.EquipSlot : EquipSlot.Ears, + _ => EquipSlot.Unknown, + }; + manip = new ImcManipulation(type, manip.BodySlot, manip.PrimaryId, manip.SecondaryId == 0 ? 1 : manip.SecondaryId, + manip.Variant.Id, equipSlot, manip.Entry); + } + + return ret; + } + + public static bool DrawPrimaryId(ref ImcManipulation manip, float unscaledWidth = 80) + { + var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, manip.PrimaryId.Id, out var newId, 0, ushort.MaxValue, + manip.PrimaryId.Id <= 1); + ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 + + "This should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, newId, manip.SecondaryId, manip.Variant.Id, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawSecondaryId(ref ImcManipulation manip, float unscaledWidth = 100) + { + var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, manip.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); + ImUtf8.HoverTooltip("Secondary ID"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, newId, manip.Variant.Id, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawVariant(ref ImcManipulation manip, float unscaledWidth = 45) + { + var ret = IdInput("##imcVariant"u8, unscaledWidth, manip.Variant.Id, out var newId, 0, byte.MaxValue, false); + ImUtf8.HoverTooltip("Variant ID"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, (byte)newId, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawSlot(ref ImcManipulation manip, float unscaledWidth = 100) + { + bool ret; + EquipSlot slot; + switch (manip.ObjectType) + { + case ObjectType.Equipment: + case ObjectType.DemiHuman: + ret = Combos.EqpEquipSlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + break; + case ObjectType.Accessory: + ret = Combos.AccessorySlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + break; + default: return false; + } + + ImUtf8.HoverTooltip("Equip Slot"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, manip.Variant.Id, slot, + manip.Entry); + return ret; + } + + /// + /// A number input for ids with an optional max id of given width. + /// Returns true if newId changed against currentId. + /// + private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, + bool border) + { + int tmp = currentId; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); + if (ImUtf8.InputScalar(label, ref tmp)) + tmp = Math.Clamp(tmp, minId, maxId); + + newId = (ushort)tmp; + return newId != currentId; + } +} diff --git a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs deleted file mode 100644 index 4ef1577f..00000000 --- a/Penumbra/UI/ModsTab/ModGroupEditDrawer.cs +++ /dev/null @@ -1,687 +0,0 @@ -using Dalamud.Interface; -using Dalamud.Interface.Internal.Notifications; -using ImGuiNET; -using OtterGui; -using OtterGui.Classes; -using OtterGui.Raii; -using OtterGui.Services; -using OtterGui.Text; -using OtterGui.Text.EndObjects; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; -using Penumbra.Meta; -using Penumbra.Meta.Manipulations; -using Penumbra.Mods; -using Penumbra.Mods.Groups; -using Penumbra.Mods.Manager; -using Penumbra.Mods.Manager.OptionEditor; -using Penumbra.Mods.Settings; -using Penumbra.Mods.SubMods; -using Penumbra.Services; -using Penumbra.UI.Classes; - -namespace Penumbra.UI.ModsTab; - -public static class MetaManipulationDrawer -{ - public static bool DrawObjectType(ref ImcManipulation manip, float width = 110) - { - var ret = Combos.ImcType("##imcType", manip.ObjectType, out var type, width); - ImUtf8.HoverTooltip("Object Type"u8); - - if (ret) - { - var equipSlot = type switch - { - ObjectType.Equipment => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, - ObjectType.DemiHuman => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, - ObjectType.Accessory => manip.EquipSlot.IsAccessory() ? manip.EquipSlot : EquipSlot.Ears, - _ => EquipSlot.Unknown, - }; - manip = new ImcManipulation(type, manip.BodySlot, manip.PrimaryId, manip.SecondaryId == 0 ? 1 : manip.SecondaryId, - manip.Variant.Id, equipSlot, manip.Entry); - } - - return ret; - } - - public static bool DrawPrimaryId(ref ImcManipulation manip, float unscaledWidth = 80) - { - var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, manip.PrimaryId.Id, out var newId, 0, ushort.MaxValue, - manip.PrimaryId.Id <= 1); - ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 - + "This should generally not be left <= 1 unless you explicitly want that."u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, newId, manip.SecondaryId, manip.Variant.Id, manip.EquipSlot, - manip.Entry); - return ret; - } - - public static bool DrawSecondaryId(ref ImcManipulation manip, float unscaledWidth = 100) - { - var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, manip.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); - ImUtf8.HoverTooltip("Secondary ID"u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, newId, manip.Variant.Id, manip.EquipSlot, - manip.Entry); - return ret; - } - - public static bool DrawVariant(ref ImcManipulation manip, float unscaledWidth = 45) - { - var ret = IdInput("##imcVariant"u8, unscaledWidth, manip.Variant.Id, out var newId, 0, byte.MaxValue, false); - ImUtf8.HoverTooltip("Variant ID"u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, (byte)newId, manip.EquipSlot, - manip.Entry); - return ret; - } - - public static bool DrawSlot(ref ImcManipulation manip, float unscaledWidth = 100) - { - bool ret; - EquipSlot slot; - switch (manip.ObjectType) - { - case ObjectType.Equipment: - case ObjectType.DemiHuman: - ret = Combos.EqpEquipSlot("##slot", manip.EquipSlot, out slot, unscaledWidth); - break; - case ObjectType.Accessory: - ret = Combos.AccessorySlot("##slot", manip.EquipSlot, out slot, unscaledWidth); - break; - default: return false; - } - - ImUtf8.HoverTooltip("Equip Slot"u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, manip.Variant.Id, slot, - manip.Entry); - return ret; - } - - /// - /// A number input for ids with an optional max id of given width. - /// Returns true if newId changed against currentId. - /// - private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, - bool border) - { - int tmp = currentId; - ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); - if (ImUtf8.InputScalar(label, ref tmp)) - tmp = Math.Clamp(tmp, minId, maxId); - - newId = (ushort)tmp; - return newId != currentId; - } -} - -public sealed class ModGroupEditDrawer( - ModManager modManager, - Configuration config, - FilenameService filenames, - DescriptionEditPopup descriptionPopup) : IUiService -{ - private static ReadOnlySpan DragDropLabel - => "##DragOption"u8; - - private Vector2 _buttonSize; - private Vector2 _availableWidth; - private float _priorityWidth; - private float _groupNameWidth; - private float _optionNameWidth; - private float _spacing; - private Vector2 _optionIdxSelectable; - private bool _deleteEnabled; - - private string? _currentGroupName; - private ModPriority? _currentGroupPriority; - private IModGroup? _currentGroupEdited; - private bool _isGroupNameValid = true; - - private string? _newOptionName; - private IModGroup? _newOptionGroup; - private readonly Queue _actionQueue = new(); - - private IModGroup? _dragDropGroup; - private IModOption? _dragDropOption; - - public void Draw(Mod mod) - { - PrepareStyle(); - - using var id = ImUtf8.PushId("##GroupEdit"u8); - foreach (var (group, groupIdx) in mod.Groups.WithIndex()) - DrawGroup(group, groupIdx); - - while (_actionQueue.TryDequeue(out var action)) - action.Invoke(); - } - - private void DrawGroup(IModGroup group, int idx) - { - using var id = ImUtf8.PushId(idx); - using var frame = ImRaii.FramedGroup($"Group #{idx + 1}"); - DrawGroupNameRow(group, idx); - switch (group) - { - case SingleModGroup s: - DrawSingleGroup(s); - break; - case MultiModGroup m: - DrawMultiGroup(m); - break; - case ImcModGroup i: - DrawImcGroup(i); - break; - } - } - - private void DrawGroupNameRow(IModGroup group, int idx) - { - DrawGroupName(group); - ImUtf8.SameLineInner(); - DrawGroupMoveButtons(group, idx); - ImUtf8.SameLineInner(); - DrawGroupOpenFile(group, idx); - ImUtf8.SameLineInner(); - DrawGroupDescription(group); - ImUtf8.SameLineInner(); - DrawGroupDelete(group); - ImUtf8.SameLineInner(); - DrawGroupPriority(group); - } - - private void DrawGroupName(IModGroup group) - { - var text = _currentGroupEdited == group ? _currentGroupName ?? group.Name : group.Name; - ImGui.SetNextItemWidth(_groupNameWidth); - using var border = ImRaii.PushFrameBorder(UiHelpers.ScaleX2, Colors.RegexWarningBorder, !_isGroupNameValid); - if (ImUtf8.InputText("##GroupName"u8, ref text)) - { - _currentGroupEdited = group; - _currentGroupName = text; - _isGroupNameValid = text == group.Name || ModGroupEditor.VerifyFileName(group.Mod, group, text, false); - } - - if (ImGui.IsItemDeactivated()) - { - if (_currentGroupName != null && _isGroupNameValid) - modManager.OptionEditor.RenameModGroup(group, _currentGroupName); - _currentGroupName = null; - _currentGroupEdited = null; - _isGroupNameValid = true; - } - - var tt = _isGroupNameValid - ? "Change the Group name."u8 - : "Current name can not be used for this group."u8; - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tt); - } - - private void DrawGroupDelete(IModGroup group) - { - if (ImUtf8.IconButton(FontAwesomeIcon.Trash, !_deleteEnabled)) - _actionQueue.Enqueue(() => modManager.OptionEditor.DeleteModGroup(group)); - - if (_deleteEnabled) - ImUtf8.HoverTooltip("Delete this option group."u8); - else - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, - $"Delete this option group.\nHold {config.DeleteModModifier} while clicking to delete."); - } - - private void DrawGroupPriority(IModGroup group) - { - var priority = _currentGroupEdited == group - ? (_currentGroupPriority ?? group.Priority).Value - : group.Priority.Value; - ImGui.SetNextItemWidth(_priorityWidth); - if (ImGui.InputInt("##GroupPriority", ref priority, 0, 0)) - { - _currentGroupEdited = group; - _currentGroupPriority = new ModPriority(priority); - } - - if (ImGui.IsItemDeactivated()) - { - if (_currentGroupPriority.HasValue) - modManager.OptionEditor.ChangeGroupPriority(group, _currentGroupPriority.Value); - _currentGroupEdited = null; - _currentGroupPriority = null; - } - - ImGuiUtil.HoverTooltip("Group Priority"); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawGroupDescription(IModGroup group) - { - if (ImUtf8.IconButton(FontAwesomeIcon.Edit, "Edit group description."u8)) - descriptionPopup.Open(group); - } - - private void DrawGroupMoveButtons(IModGroup group, int idx) - { - var isFirst = idx == 0; - if (ImUtf8.IconButton(FontAwesomeIcon.ArrowUp, isFirst)) - _actionQueue.Enqueue(() => modManager.OptionEditor.MoveModGroup(group, idx - 1)); - - if (isFirst) - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Can not move this group further upwards."u8); - else - ImUtf8.HoverTooltip($"Move this group up to group {idx}."); - - - ImUtf8.SameLineInner(); - var isLast = idx == group.Mod.Groups.Count - 1; - if (ImUtf8.IconButton(FontAwesomeIcon.ArrowDown, isLast)) - _actionQueue.Enqueue(() => modManager.OptionEditor.MoveModGroup(group, idx + 1)); - - if (isLast) - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Can not move this group further downwards."u8); - else - ImUtf8.HoverTooltip($"Move this group down to group {idx + 2}."); - } - - private void DrawGroupOpenFile(IModGroup group, int idx) - { - var fileName = filenames.OptionGroupFile(group.Mod, idx, config.ReplaceNonAsciiOnImport); - var fileExists = File.Exists(fileName); - if (ImUtf8.IconButton(FontAwesomeIcon.FileExport, !fileExists)) - try - { - Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); - } - catch (Exception e) - { - Penumbra.Messager.NotificationMessage(e, "Could not open editor.", NotificationType.Error); - } - - if (fileExists) - ImUtf8.HoverTooltip($"Open the {group.Name} json file in the text editor of your choice."); - else - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"The {group.Name} json file does not exist."); - } - - private void DrawSingleGroup(SingleModGroup group) - { - foreach (var (option, optionIdx) in group.OptionData.WithIndex()) - { - using var id = ImRaii.PushId(optionIdx); - DrawOptionPosition(group, option, optionIdx); - - ImUtf8.SameLineInner(); - DrawOptionDefaultSingleBehaviour(group, option, optionIdx); - - ImUtf8.SameLineInner(); - DrawOptionName(option); - - ImUtf8.SameLineInner(); - DrawOptionDescription(option); - - ImUtf8.SameLineInner(); - DrawOptionDelete(option); - - ImUtf8.SameLineInner(); - ImGui.Dummy(new Vector2(_priorityWidth, 0)); - } - - DrawNewOption(group); - var convertible = group.Options.Count <= IModGroup.MaxMultiOptions; - if (ImUtf8.ButtonEx("Convert to Multi Group", _availableWidth, !convertible)) - _actionQueue.Enqueue(() => modManager.OptionEditor.SingleEditor.ChangeToMulti(group)); - if (!convertible) - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, - "Can not convert to multi group since maximum number of options is exceeded."u8); - } - - private void DrawMultiGroup(MultiModGroup group) - { - foreach (var (option, optionIdx) in group.OptionData.WithIndex()) - { - using var id = ImRaii.PushId(optionIdx); - DrawOptionPosition(group, option, optionIdx); - - ImUtf8.SameLineInner(); - DrawOptionDefaultMultiBehaviour(group, option, optionIdx); - - ImUtf8.SameLineInner(); - DrawOptionName(option); - - ImUtf8.SameLineInner(); - DrawOptionDescription(option); - - ImUtf8.SameLineInner(); - DrawOptionDelete(option); - - ImUtf8.SameLineInner(); - DrawOptionPriority(option); - } - - DrawNewOption(group); - if (ImUtf8.Button("Convert to Single Group"u8, _availableWidth)) - _actionQueue.Enqueue(() => modManager.OptionEditor.MultiEditor.ChangeToSingle(group)); - } - - private void DrawImcGroup(ImcModGroup group) - { - using (ImUtf8.Group()) - { - ImUtf8.Text("Object Type"u8); - if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) - ImUtf8.Text("Slot"u8); - ImUtf8.Text("Primary ID"); - if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) - ImUtf8.Text("Secondary ID"); - ImUtf8.Text("Variant"u8); - - ImUtf8.TextFrameAligned("Material ID"u8); - ImUtf8.TextFrameAligned("Material Animation ID"u8); - ImUtf8.TextFrameAligned("Decal ID"u8); - ImUtf8.TextFrameAligned("VFX ID"u8); - ImUtf8.TextFrameAligned("Sound ID"u8); - ImUtf8.TextFrameAligned("Can Be Disabled"u8); - ImUtf8.TextFrameAligned("Default Attributes"u8); - } - - ImGui.SameLine(); - - var attributeCache = new ImcAttributeCache(group); - - using (ImUtf8.Group()) - { - ImUtf8.Text(group.ObjectType.ToName()); - if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) - ImUtf8.Text(group.EquipSlot.ToName()); - ImUtf8.Text($"{group.PrimaryId.Id}"); - if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) - ImUtf8.Text($"{group.SecondaryId.Id}"); - ImUtf8.Text($"{group.Variant.Id}"); - - ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialAnimationId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.DecalId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.VfxId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.SoundId}"); - - var canBeDisabled = group.CanBeDisabled; - if (ImUtf8.Checkbox("##disabled"u8, ref canBeDisabled)) - modManager.OptionEditor.ImcEditor.ChangeCanBeDisabled(group, canBeDisabled, SaveType.Queue); - - var defaultDisabled = group.DefaultDisabled; - ImUtf8.SameLineInner(); - if (ImUtf8.Checkbox("##defaultDisabled"u8, ref defaultDisabled)) - modManager.OptionEditor.ChangeModGroupDefaultOption(group, - group.DefaultSettings.SetBit(ImcModGroup.DisabledIndex, defaultDisabled)); - - DrawAttributes(modManager.OptionEditor.ImcEditor, attributeCache, group.DefaultEntry.AttributeMask, group); - } - - - foreach (var (option, optionIdx) in group.OptionData.WithIndex()) - { - using var id = ImRaii.PushId(optionIdx); - DrawOptionPosition(group, option, optionIdx); - - ImUtf8.SameLineInner(); - DrawOptionDefaultMultiBehaviour(group, option, optionIdx); - - ImUtf8.SameLineInner(); - DrawOptionName(option); - - ImUtf8.SameLineInner(); - DrawOptionDescription(option); - - ImUtf8.SameLineInner(); - DrawOptionDelete(option); - - ImUtf8.SameLineInner(); - ImGui.Dummy(new Vector2(_priorityWidth, 0)); - - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + _optionIdxSelectable.X + ImUtf8.ItemInnerSpacing.X * 2 + ImUtf8.FrameHeight); - DrawAttributes(modManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); - } - - DrawNewOption(group, attributeCache); - return; - - static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data) - { - for (var i = 0; i < ImcEntry.NumAttributes; ++i) - { - using var id = ImRaii.PushId(i); - var value = (mask & (1 << i)) != 0; - using (ImRaii.Disabled(!cache.CanChange(i))) - { - if (ImUtf8.Checkbox(TerminatedByteString.Empty, ref value)) - { - if (data is ImcModGroup g) - editor.ChangeDefaultAttribute(g, cache, i, value); - else - editor.ChangeOptionAttribute((ImcSubMod)data, cache, i, value); - } - } - - ImUtf8.HoverTooltip($"{(char)('A' + i)}"); - if (i != 9) - ImUtf8.SameLineInner(); - } - } - } - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionPosition(IModGroup group, IModOption option, int optionIdx) - { - ImGui.AlignTextToFramePadding(); - ImUtf8.Selectable($"Option #{optionIdx + 1}", false, size: _optionIdxSelectable); - Target(group, optionIdx); - Source(option); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionDefaultSingleBehaviour(IModGroup group, IModOption option, int optionIdx) - { - var isDefaultOption = group.DefaultSettings.AsIndex == optionIdx; - if (ImUtf8.RadioButton("##default"u8, isDefaultOption)) - modManager.OptionEditor.ChangeModGroupDefaultOption(group, Setting.Single(optionIdx)); - ImUtf8.HoverTooltip($"Set {option.Name} as the default choice for this group."); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionDefaultMultiBehaviour(IModGroup group, IModOption option, int optionIdx) - { - var isDefaultOption = group.DefaultSettings.HasFlag(optionIdx); - if (ImUtf8.Checkbox("##default"u8, ref isDefaultOption)) - modManager.OptionEditor.ChangeModGroupDefaultOption(group, group.DefaultSettings.SetBit(optionIdx, isDefaultOption)); - ImUtf8.HoverTooltip($"{(isDefaultOption ? "Disable"u8 : "Enable"u8)} {option.Name} per default in this group."); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionDescription(IModOption option) - { - if (ImUtf8.IconButton(FontAwesomeIcon.Edit, "Edit option description."u8)) - descriptionPopup.Open(option); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionPriority(MultiSubMod option) - { - var priority = option.Priority.Value; - ImGui.SetNextItemWidth(_priorityWidth); - if (ImUtf8.InputScalarOnDeactivated("##Priority"u8, ref priority)) - modManager.OptionEditor.MultiEditor.ChangeOptionPriority(option, new ModPriority(priority)); - ImUtf8.HoverTooltip("Option priority inside the mod."u8); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionName(IModOption option) - { - var name = option.Name; - ImGui.SetNextItemWidth(_optionNameWidth); - if (ImUtf8.InputTextOnDeactivated("##Name"u8, ref name)) - modManager.OptionEditor.RenameOption(option, name); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void DrawOptionDelete(IModOption option) - { - if (ImUtf8.IconButton(FontAwesomeIcon.Trash, !_deleteEnabled)) - _actionQueue.Enqueue(() => modManager.OptionEditor.DeleteOption(option)); - - if (_deleteEnabled) - ImUtf8.HoverTooltip("Delete this option."u8); - else - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, - $"Delete this option.\nHold {config.DeleteModModifier} while clicking to delete."); - } - - private void DrawNewOption(SingleModGroup group) - { - var count = group.Options.Count; - if (count >= int.MaxValue) - return; - - var name = DrawNewOptionBase(group, count); - - var validName = name.Length > 0; - if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName - ? "Add a new option to this group."u8 - : "Please enter a name for the new option."u8, !validName)) - { - modManager.OptionEditor.SingleEditor.AddOption(group, name); - _newOptionName = null; - } - } - - private void DrawNewOption(MultiModGroup group) - { - var count = group.Options.Count; - if (count >= IModGroup.MaxMultiOptions) - return; - - var name = DrawNewOptionBase(group, count); - - var validName = name.Length > 0; - if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName - ? "Add a new option to this group."u8 - : "Please enter a name for the new option."u8, !validName)) - { - modManager.OptionEditor.MultiEditor.AddOption(group, name); - _newOptionName = null; - } - } - - private void DrawNewOption(ImcModGroup group, in ImcAttributeCache cache) - { - if (cache.LowestUnsetMask == 0) - return; - - var name = DrawNewOptionBase(group, group.Options.Count); - var validName = name.Length > 0; - if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName - ? "Add a new option to this group."u8 - : "Please enter a name for the new option."u8, !validName)) - { - modManager.OptionEditor.ImcEditor.AddOption(group, cache, name); - _newOptionName = null; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private string DrawNewOptionBase(IModGroup group, int count) - { - ImUtf8.Selectable($"Option #{count + 1}", false, size: _optionIdxSelectable); - Target(group, count); - - ImUtf8.SameLineInner(); - ImUtf8.IconDummy(); - - ImUtf8.SameLineInner(); - ImGui.SetNextItemWidth(_optionNameWidth); - var newName = _newOptionGroup == group - ? _newOptionName ?? string.Empty - : string.Empty; - if (ImUtf8.InputText("##newOption"u8, ref newName, "Add new option..."u8)) - { - _newOptionName = newName; - _newOptionGroup = group; - } - - ImUtf8.SameLineInner(); - return newName; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void Source(IModOption option) - { - if (option.Group is not ITexToolsGroup) - return; - - using var source = ImUtf8.DragDropSource(); - if (!source) - return; - - if (!DragDropSource.SetPayload(DragDropLabel)) - { - _dragDropGroup = option.Group; - _dragDropOption = option; - } - - ImGui.TextUnformatted($"Dragging option {option.Name} from group {option.Group.Name}..."); - } - - private void Target(IModGroup group, int optionIdx) - { - if (group is not ITexToolsGroup) - return; - - if (_dragDropGroup != group && _dragDropGroup != null && group is MultiModGroup { Options.Count: >= IModGroup.MaxMultiOptions }) - return; - - using var target = ImRaii.DragDropTarget(); - if (!target.Success || !DragDropTarget.CheckPayload(DragDropLabel)) - return; - - if (_dragDropGroup != null && _dragDropOption != null) - { - if (_dragDropGroup == group) - { - var sourceOption = _dragDropOption; - _actionQueue.Enqueue(() => modManager.OptionEditor.MoveOption(sourceOption, optionIdx)); - } - else - { - // Move from one group to another by deleting, then adding, then moving the option. - var sourceOption = _dragDropOption; - _actionQueue.Enqueue(() => - { - modManager.OptionEditor.DeleteOption(sourceOption); - if (modManager.OptionEditor.AddOption(group, sourceOption) is { } newOption) - modManager.OptionEditor.MoveOption(newOption, optionIdx); - }); - } - } - - _dragDropGroup = null; - _dragDropOption = null; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void PrepareStyle() - { - var totalWidth = 400f * ImUtf8.GlobalScale; - _buttonSize = new Vector2(ImUtf8.FrameHeight); - _priorityWidth = 50 * ImUtf8.GlobalScale; - _availableWidth = new Vector2(totalWidth + 3 * _spacing + 2 * _buttonSize.X + _priorityWidth, 0); - _groupNameWidth = totalWidth - 3 * (_buttonSize.X + _spacing); - _spacing = ImGui.GetStyle().ItemInnerSpacing.X; - _optionIdxSelectable = ImUtf8.CalcTextSize("Option #88."u8); - _optionNameWidth = totalWidth - _optionIdxSelectable.X - _buttonSize.X - 2 * _spacing; - _deleteEnabled = config.DeleteModModifier.IsActive(); - } -} diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index b7951c49..125f539e 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -13,6 +13,7 @@ using Penumbra.Services; using Penumbra.UI.AdvancedWindow; using Penumbra.Mods.Settings; using Penumbra.Mods.Manager.OptionEditor; +using Penumbra.UI.ModsTab.Groups; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 107a2d04..7e3b8a95 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -9,6 +9,7 @@ using Penumbra.Collections.Manager; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.Mods.Settings; +using Penumbra.UI.ModsTab.Groups; namespace Penumbra.UI.ModsTab; From c06d5b08715924aba67910f7e0fe718b4f83b274 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 May 2024 16:57:16 +0200 Subject: [PATCH 0605/1381] Update for new gamedata. --- Penumbra.GameData | 2 +- Penumbra/Import/TexToolsMeta.Deserialization.cs | 4 +--- Penumbra/Meta/Files/CmpFile.cs | 6 +++--- Penumbra/Meta/Files/EqpGmpFile.cs | 6 +++--- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 5fa4d0e7..e8220a0a 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 5fa4d0e7972423b73f8cf569bb2bfbeddd825c8a +Subproject commit e8220a0a74e9480330e98ed7ca462353434b9649 diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index 325c9143..f062ae25 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -57,9 +57,7 @@ public partial class TexToolsMeta if (data == null) return; - using var reader = new BinaryReader(new MemoryStream(data)); - var value = (GmpEntry)reader.ReadUInt32(); - value.UnknownTotal = reader.ReadByte(); + var value = GmpEntry.FromTexToolsMeta(data.AsSpan(0, 5)); var def = ExpandedGmpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId); if (_keepDefault || value != def) MetaManipulations.Add(new GmpManipulation(value, metaFileInfo.PrimaryId)); diff --git a/Penumbra/Meta/Files/CmpFile.cs b/Penumbra/Meta/Files/CmpFile.cs index 8a6040ec..b265a5e8 100644 --- a/Penumbra/Meta/Files/CmpFile.cs +++ b/Penumbra/Meta/Files/CmpFile.cs @@ -19,8 +19,8 @@ public sealed unsafe class CmpFile : MetaBaseFile public float this[SubRace subRace, RspAttribute attribute] { - get => *(float*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspEntry.ByteSize + (int)attribute * 4); - set => *(float*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspEntry.ByteSize + (int)attribute * 4) = value; + get => *(float*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); + set => *(float*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4) = value; } public override void Reset() @@ -42,7 +42,7 @@ public sealed unsafe class CmpFile : MetaBaseFile public static float GetDefault(MetaFileManager manager, SubRace subRace, RspAttribute attribute) { var data = (byte*)manager.CharacterUtility.DefaultResource(InternalIndex).Address; - return *(float*)(data + RacialScalingStart + ToRspIndex(subRace) * RspEntry.ByteSize + (int)attribute * 4); + return *(float*)(data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); } private static int ToRspIndex(SubRace subRace) diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index 97f57703..70067c2b 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -157,12 +157,12 @@ public sealed class ExpandedGmpFile : ExpandedEqpGmpBase, IEnumerable public GmpEntry this[PrimaryId idx] { - get => (GmpEntry)GetInternal(idx); - set => SetInternal(idx, (ulong)value); + get => new() { Value = GetInternal(idx) }; + set => SetInternal(idx, value.Value); } public static GmpEntry GetDefault(MetaFileManager manager, PrimaryId primaryIdx) - => (GmpEntry)GetDefaultInternal(manager, InternalIndex, primaryIdx, (ulong)GmpEntry.Default); + => new() { Value = GetDefaultInternal(manager, InternalIndex, primaryIdx, GmpEntry.Default.Value) }; public void Reset(IEnumerable entries) { From dfdd5167a84c5a9c1aeb5280eb3fb91d895a613b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 May 2024 17:24:42 +0200 Subject: [PATCH 0606/1381] Remove auto descriptions from newly generated option groups. --- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 2 +- Penumbra/Mods/Groups/SingleModGroup.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index d2c41f34..cf228889 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -22,7 +22,7 @@ public class ImcModGroup(Mod mod) : IModGroup public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; - public string Description { get; set; } = "A single IMC manipulation."; + public string Description { get; set; } = string.Empty; public GroupType Type => GroupType.Imc; diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 7fc9acb3..38c0ef15 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -25,7 +25,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public Mod Mod { get; } = mod; public string Name { get; set; } = "Group"; - public string Description { get; set; } = "A non-exclusive group of settings."; + public string Description { get; set; } = string.Empty; public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } public readonly List OptionData = []; diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 4eec0746..49190e34 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -23,7 +23,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; - public string Description { get; set; } = "A mutually exclusive group of settings."; + public string Description { get; set; } = string.Empty; public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } From 7df9ddcb995b1f4b86abcfb827a63fb5488e6c1f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 May 2024 17:25:27 +0200 Subject: [PATCH 0607/1381] Re-Add button to open default mod json. --- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 125f539e..468e97b9 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -35,8 +35,8 @@ public class ModPanelEditTab( { private readonly TagButtons _modTags = new(); - private ModFileSystem.Leaf _leaf = null!; - private Mod _mod = null!; + private ModFileSystem.Leaf _leaf = null!; + private Mod _mod = null!; public ReadOnlySpan Label => "Edit Mod"u8; @@ -193,6 +193,7 @@ public class ModPanelEditTab( if (ImGui.Button("Edit Description", reducedSize)) descriptionPopup.Open(_mod); + ImGui.SameLine(); var fileExists = File.Exists(filenames.ModMetaPath(_mod)); var tt = fileExists @@ -201,8 +202,22 @@ public class ModPanelEditTab( if (ImGuiUtil.DrawDisabledButton($"{FontAwesomeIcon.FileExport.ToIconString()}##metaFile", UiHelpers.IconButtonSize, tt, !fileExists, true)) Process.Start(new ProcessStartInfo(filenames.ModMetaPath(_mod)) { UseShellExecute = true }); + + DrawOpenDefaultMod(); } + private void DrawOpenDefaultMod() + { + var file = filenames.OptionGroupFile(_mod, -1, false); + var fileExists = File.Exists(file); + var tt = fileExists + ? "Open the default mod data file in the text editor of your choice." + : "The default mod data file does not exist."; + if (ImGuiUtil.DrawDisabledButton("Open Default Data", UiHelpers.InputTextWidth, tt, !fileExists)) + Process.Start(new ProcessStartInfo(file) { UseShellExecute = true }); + } + + /// A text input for the new directory name and a button to apply the move. private static class MoveDirectory { From fca1bf9d946dc505c1834ccef6feb206ee3039f4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 May 2024 22:30:42 +0200 Subject: [PATCH 0608/1381] Add ImcIdentifier. --- .../Meta/Manipulations/IMetaIdentifier.cs | 16 ++ Penumbra/Meta/Manipulations/Imc.cs | 187 ++++++++++++++++++ 2 files changed, 203 insertions(+) create mode 100644 Penumbra/Meta/Manipulations/IMetaIdentifier.cs create mode 100644 Penumbra/Meta/Manipulations/Imc.cs diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs new file mode 100644 index 00000000..4ad6bd3d --- /dev/null +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public interface IMetaIdentifier +{ + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); + + public MetaIndex FileIndex(); + + public bool Validate(); + + public JObject AddToJson(JObject jObj); +} diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs new file mode 100644 index 00000000..f0101be2 --- /dev/null +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -0,0 +1,187 @@ +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; +using Penumbra.String.Classes; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct ImcIdentifier( + PrimaryId PrimaryId, + Variant Variant, + ObjectType ObjectType, + SecondaryId SecondaryId, + EquipSlot EquipSlot, + BodySlot BodySlot) : IMetaIdentifier, IComparable +{ + public ImcIdentifier(EquipSlot slot, PrimaryId primaryId, ushort variant) + : this(primaryId, (Variant)Math.Clamp(variant, (ushort)0, byte.MaxValue), + slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, + variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown) + { } + + public ImcIdentifier(EquipSlot slot, PrimaryId primaryId, Variant variant) + : this(primaryId, variant, slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, BodySlot.Unknown) + { } + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + var path = ObjectType switch + { + ObjectType.Equipment or ObjectType.Accessory => GamePaths.Equipment.Mtrl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot, + Variant, + "a"), + ObjectType.Weapon => GamePaths.Weapon.Mtrl.Path(PrimaryId, SecondaryId.Id, Variant, "a"), + ObjectType.DemiHuman => GamePaths.DemiHuman.Mtrl.Path(PrimaryId, SecondaryId.Id, EquipSlot, Variant, + "a"), + ObjectType.Monster => GamePaths.Monster.Mtrl.Path(PrimaryId, SecondaryId.Id, Variant, "a"), + _ => string.Empty, + }; + if (path.Length == 0) + return; + + identifier.Identify(changedItems, path); + } + + public Utf8GamePath GamePath() + { + return ObjectType switch + { + ObjectType.Accessory => Utf8GamePath.FromString(GamePaths.Accessory.Imc.Path(PrimaryId), out var p) ? p : Utf8GamePath.Empty, + ObjectType.Equipment => Utf8GamePath.FromString(GamePaths.Equipment.Imc.Path(PrimaryId), out var p) ? p : Utf8GamePath.Empty, + ObjectType.DemiHuman => Utf8GamePath.FromString(GamePaths.DemiHuman.Imc.Path(PrimaryId, SecondaryId.Id), out var p) + ? p + : Utf8GamePath.Empty, + ObjectType.Monster => Utf8GamePath.FromString(GamePaths.Monster.Imc.Path(PrimaryId, SecondaryId.Id), out var p) + ? p + : Utf8GamePath.Empty, + ObjectType.Weapon => Utf8GamePath.FromString(GamePaths.Weapon.Imc.Path(PrimaryId, SecondaryId.Id), out var p) + ? p + : Utf8GamePath.Empty, + _ => throw new NotImplementedException(), + }; + } + + public MetaIndex FileIndex() + => (MetaIndex)(-1); + + public override string ToString() + => ObjectType is ObjectType.Equipment or ObjectType.Accessory + ? $"Imc - {PrimaryId} - {EquipSlot.ToName()} - {Variant}" + : $"Imc - {PrimaryId} - {ObjectType.ToName()} - {SecondaryId} - {BodySlot} - {Variant}"; + + public bool Validate() + { + switch (ObjectType) + { + case ObjectType.Accessory: + case ObjectType.Equipment: + if (BodySlot is not BodySlot.Unknown) + return false; + if (!EquipSlot.IsEquipment() && !EquipSlot.IsAccessory()) + return false; + if (SecondaryId != 0) + return false; + + break; + case ObjectType.DemiHuman: + if (BodySlot is not BodySlot.Unknown) + return false; + if (!EquipSlot.IsEquipment() && !EquipSlot.IsAccessory()) + return false; + + break; + default: + if (!Enum.IsDefined(BodySlot)) + return false; + if (EquipSlot is not EquipSlot.Unknown) + return false; + if (!Enum.IsDefined(ObjectType)) + return false; + + break; + } + + return true; + } + + public int CompareTo(ImcIdentifier other) + { + var o = ObjectType.CompareTo(other.ObjectType); + if (o != 0) + return o; + + var i = PrimaryId.Id.CompareTo(other.PrimaryId.Id); + if (i != 0) + return i; + + if (ObjectType is ObjectType.Equipment or ObjectType.Accessory) + { + var e = EquipSlot.CompareTo(other.EquipSlot); + return e != 0 ? e : Variant.Id.CompareTo(other.Variant.Id); + } + + if (ObjectType is ObjectType.DemiHuman) + { + var e = EquipSlot.CompareTo(other.EquipSlot); + if (e != 0) + return e; + } + + var s = SecondaryId.Id.CompareTo(other.SecondaryId.Id); + if (s != 0) + return s; + + var b = BodySlot.CompareTo(other.BodySlot); + return b != 0 ? b : Variant.Id.CompareTo(other.Variant.Id); + } + + public static ImcIdentifier? FromJson(JObject jObj) + { + var objectType = jObj["PrimaryId"]?.ToObject() ?? ObjectType.Unknown; + var primaryId = new PrimaryId(jObj["PrimaryId"]?.ToObject() ?? 0); + var variant = jObj["Variant"]?.ToObject() ?? 0; + if (variant > byte.MaxValue) + return null; + + ImcIdentifier ret; + switch (objectType) + { + case ObjectType.Equipment: + case ObjectType.Accessory: + { + var slot = jObj["EquipSlot"]?.ToObject() ?? EquipSlot.Unknown; + ret = new ImcIdentifier(slot, primaryId, variant); + break; + } + case ObjectType.DemiHuman: + { + var secondaryId = new SecondaryId(jObj["SecondaryId"]?.ToObject() ?? 0); + var slot = jObj["Slot"]?.ToObject() ?? EquipSlot.Unknown; + ret = new ImcIdentifier(primaryId, (Variant)variant, objectType, secondaryId, slot, BodySlot.Unknown); + break; + } + + case ObjectType.Monster: + case ObjectType.Weapon: + { + var secondaryId = new SecondaryId(jObj["SecondaryId"]?.ToObject() ?? 0); + ret = new ImcIdentifier(primaryId, (Variant)variant, objectType, secondaryId, EquipSlot.Unknown, BodySlot.Body); + break; + } + default: return null; + } + + return ret.Validate() ? ret : null; + } + + public JObject AddToJson(JObject jObj) + { + var (gender, race) = GenderRace.Split(); + jObj["Gender"] = gender.ToString(); + jObj["Race"] = race.ToString(); + jObj["SetId"] = SetId.Id.ToString(); + jObj["Slot"] = Slot.ToString(); + return jObj; + } +} From 992cdff58d3a82c64dc166147de7de4a10be87f6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 May 2024 22:31:39 +0200 Subject: [PATCH 0609/1381] Improve some IMC things. --- OtterGui | 2 +- Penumbra/Meta/Manipulations/Imc.cs | 14 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 92 +++----- Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs | 18 +- Penumbra/UI/ModsTab/ImcManipulationDrawer.cs | 221 ++++++++++++++++++ Penumbra/UI/ModsTab/MetaManipulationDrawer.cs | 105 --------- 6 files changed, 267 insertions(+), 185 deletions(-) create mode 100644 Penumbra/UI/ModsTab/ImcManipulationDrawer.cs delete mode 100644 Penumbra/UI/ModsTab/MetaManipulationDrawer.cs diff --git a/OtterGui b/OtterGui index 462acb87..1d936516 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 462acb87099650019996e4306d18cc70f76ca576 +Subproject commit 1d9365164655a7cb38172e1311e15e19b1def6db diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index f0101be2..9b123df1 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json.Linq; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -134,7 +135,7 @@ public readonly record struct ImcIdentifier( var b = BodySlot.CompareTo(other.BodySlot); return b != 0 ? b : Variant.Id.CompareTo(other.Variant.Id); - } + } public static ImcIdentifier? FromJson(JObject jObj) { @@ -177,11 +178,12 @@ public readonly record struct ImcIdentifier( public JObject AddToJson(JObject jObj) { - var (gender, race) = GenderRace.Split(); - jObj["Gender"] = gender.ToString(); - jObj["Race"] = race.ToString(); - jObj["SetId"] = SetId.Id.ToString(); - jObj["Slot"] = Slot.ToString(); + jObj["ObjectType"] = ObjectType.ToString(); + jObj["PrimaryId"] = PrimaryId.Id; + jObj["PrimaryId"] = SecondaryId.Id; + jObj["Variant"] = Variant.Id; + jObj["EquipSlot"] = EquipSlot.ToString(); + jObj["BodySlot"] = BodySlot.ToString(); return jObj; } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 55125375..99889360 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -352,26 +352,26 @@ public partial class ModEditWindow // Identifier ImGui.TableNextColumn(); - var change = MetaManipulationDrawer.DrawObjectType(ref _new); + var change = ImcManipulationDrawer.DrawObjectType(ref _new); ImGui.TableNextColumn(); - change |= MetaManipulationDrawer.DrawPrimaryId(ref _new); + change |= ImcManipulationDrawer.DrawPrimaryId(ref _new); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); ImGui.TableNextColumn(); // Equipment and accessories are slightly different imcs than other types. if (_new.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - change |= MetaManipulationDrawer.DrawSlot(ref _new); + change |= ImcManipulationDrawer.DrawSlot(ref _new); else - change |= MetaManipulationDrawer.DrawSecondaryId(ref _new); + change |= ImcManipulationDrawer.DrawSecondaryId(ref _new); ImGui.TableNextColumn(); - change |= MetaManipulationDrawer.DrawVariant(ref _new); + change |= ImcManipulationDrawer.DrawVariant(ref _new); ImGui.TableNextColumn(); if (_new.ObjectType is ObjectType.DemiHuman) - change |= MetaManipulationDrawer.DrawSlot(ref _new, 70); + change |= ImcManipulationDrawer.DrawSlot(ref _new, 70); else ImGui.Dummy(new Vector2(70 * UiHelpers.Scale, 0)); @@ -379,32 +379,20 @@ public partial class ModEditWindow _new = _new.Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); // Values using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - IntDragInput("##imcMaterialId", "Material ID", SmallIdWidth, defaultEntry.Value.MaterialId, defaultEntry.Value.MaterialId, out _, - 1, byte.MaxValue, 0f); - ImGui.SameLine(); - IntDragInput("##imcMaterialAnimId", "Material Animation ID", SmallIdWidth, defaultEntry.Value.MaterialAnimationId, - defaultEntry.Value.MaterialAnimationId, out _, 0, byte.MaxValue, 0.01f); - ImGui.TableNextColumn(); - IntDragInput("##imcDecalId", "Decal ID", SmallIdWidth, defaultEntry.Value.DecalId, defaultEntry.Value.DecalId, out _, 0, - byte.MaxValue, 0f); - ImGui.SameLine(); - IntDragInput("##imcVfxId", "VFX ID", SmallIdWidth, defaultEntry.Value.VfxId, defaultEntry.Value.VfxId, out _, 0, byte.MaxValue, - 0f); - ImGui.SameLine(); - IntDragInput("##imcSoundId", "Sound ID", SmallIdWidth, defaultEntry.Value.SoundId, defaultEntry.Value.SoundId, out _, 0, 0b111111, - 0f); - ImGui.TableNextColumn(); - for (var i = 0; i < 10; ++i) - { - using var id = ImRaii.PushId(i); - var flag = 1 << i; - Checkmark("##attribute", $"{(char)('A' + i)}", (defaultEntry.Value.AttributeMask & flag) != 0, - (defaultEntry.Value.AttributeMask & flag) != 0, out _); - ImGui.SameLine(); - } - ImGui.NewLine(); + var entry = defaultEntry.Value; + ImGui.TableNextColumn(); + ImcManipulationDrawer.DrawMaterialId(entry, ref entry, false); + ImGui.SameLine(); + ImcManipulationDrawer.DrawMaterialAnimationId(entry, ref entry, false); + ImGui.TableNextColumn(); + ImcManipulationDrawer.DrawDecalId(entry, ref entry, false); + ImGui.SameLine(); + ImcManipulationDrawer.DrawVfxId(entry, ref entry, false); + ImGui.SameLine(); + ImcManipulationDrawer.DrawSoundId(entry, ref entry, false); + ImGui.TableNextColumn(); + ImcManipulationDrawer.DrawAttributes(entry, ref entry); } public static void Draw(MetaFileManager metaFileManager, ImcManipulation meta, ModEditor editor, Vector2 iconSize) @@ -452,46 +440,22 @@ public partial class ModEditWindow new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); ImGui.TableNextColumn(); var defaultEntry = GetDefault(metaFileManager, meta) ?? new ImcEntry(); - if (IntDragInput("##imcMaterialId", $"Material ID\nDefault Value: {defaultEntry.MaterialId}", SmallIdWidth, meta.Entry.MaterialId, - defaultEntry.MaterialId, out var materialId, 1, byte.MaxValue, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { MaterialId = (byte)materialId })); + var newEntry = meta.Entry; + var changes = ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref newEntry, true); ImGui.SameLine(); - if (IntDragInput("##imcMaterialAnimId", $"Material Animation ID\nDefault Value: {defaultEntry.MaterialAnimationId}", SmallIdWidth, - meta.Entry.MaterialAnimationId, defaultEntry.MaterialAnimationId, out var materialAnimId, 0, byte.MaxValue, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { MaterialAnimationId = (byte)materialAnimId })); - + changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref newEntry, true); ImGui.TableNextColumn(); - if (IntDragInput("##imcDecalId", $"Decal ID\nDefault Value: {defaultEntry.DecalId}", SmallIdWidth, meta.Entry.DecalId, - defaultEntry.DecalId, out var decalId, 0, byte.MaxValue, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { DecalId = (byte)decalId })); - + changes |= ImcManipulationDrawer.DrawDecalId(defaultEntry, ref newEntry, true); ImGui.SameLine(); - if (IntDragInput("##imcVfxId", $"VFX ID\nDefault Value: {defaultEntry.VfxId}", SmallIdWidth, meta.Entry.VfxId, defaultEntry.VfxId, - out var vfxId, 0, byte.MaxValue, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { VfxId = (byte)vfxId })); - + changes |= ImcManipulationDrawer.DrawVfxId(defaultEntry, ref newEntry, true); ImGui.SameLine(); - if (IntDragInput("##imcSoundId", $"Sound ID\nDefault Value: {defaultEntry.SoundId}", SmallIdWidth, meta.Entry.SoundId, - defaultEntry.SoundId, out var soundId, 0, 0b111111, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { SoundId = (byte)soundId })); - + changes |= ImcManipulationDrawer.DrawSoundId(defaultEntry, ref newEntry, true); ImGui.TableNextColumn(); - for (var i = 0; i < 10; ++i) - { - using var id = ImRaii.PushId(i); - var flag = 1 << i; - if (Checkmark("##attribute", $"{(char)('A' + i)}", (meta.Entry.AttributeMask & flag) != 0, - (defaultEntry.AttributeMask & flag) != 0, out var val)) - { - var attributes = val ? meta.Entry.AttributeMask | flag : meta.Entry.AttributeMask & ~flag; - editor.MetaEditor.Change(meta.Copy(meta.Entry with { AttributeMask = (ushort)attributes })); - } + changes |= ImcManipulationDrawer.DrawAttributes(defaultEntry, ref newEntry); - ImGui.SameLine(); - } - - ImGui.NewLine(); + if (changes) + editor.MetaEditor.Change(meta.Copy(newEntry)); } } diff --git a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index 06cb4154..2d80d3df 100644 --- a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -80,29 +80,29 @@ public class AddGroupDrawer : IUiService private void DrawImcInput(float width) { - var change = MetaManipulationDrawer.DrawObjectType(ref _imcManip, width); + var change = ImcManipulationDrawer.DrawObjectType(ref _imcManip, width); ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawPrimaryId(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawPrimaryId(ref _imcManip, width); if (_imcManip.ObjectType is ObjectType.Weapon or ObjectType.Monster) { - change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcManip, width); ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawVariant(ref _imcManip, width); } else if (_imcManip.ObjectType is ObjectType.DemiHuman) { var quarterWidth = (width - ImUtf8.ItemInnerSpacing.X / ImUtf8.GlobalScale) / 2; - change |= MetaManipulationDrawer.DrawSecondaryId(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcManip, width); ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, quarterWidth); + change |= ImcManipulationDrawer.DrawSlot(ref _imcManip, quarterWidth); ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, quarterWidth); + change |= ImcManipulationDrawer.DrawVariant(ref _imcManip, quarterWidth); } else { - change |= MetaManipulationDrawer.DrawSlot(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawSlot(ref _imcManip, width); ImUtf8.SameLineInner(); - change |= MetaManipulationDrawer.DrawVariant(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawVariant(ref _imcManip, width); } if (change) diff --git a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs new file mode 100644 index 00000000..5873119e --- /dev/null +++ b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs @@ -0,0 +1,221 @@ +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using OtterGui.Text.HelperObjects; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta.Manipulations; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.ModsTab; + +public static class ImcManipulationDrawer +{ + public static bool DrawObjectType(ref ImcManipulation manip, float width = 110) + { + var ret = Combos.ImcType("##imcType", manip.ObjectType, out var type, width); + ImUtf8.HoverTooltip("Object Type"u8); + + if (ret) + { + var equipSlot = type switch + { + ObjectType.Equipment => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, + ObjectType.DemiHuman => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, + ObjectType.Accessory => manip.EquipSlot.IsAccessory() ? manip.EquipSlot : EquipSlot.Ears, + _ => EquipSlot.Unknown, + }; + manip = new ImcManipulation(type, manip.BodySlot, manip.PrimaryId, manip.SecondaryId == 0 ? 1 : manip.SecondaryId, + manip.Variant.Id, equipSlot, manip.Entry); + } + + return ret; + } + + public static bool DrawPrimaryId(ref ImcManipulation manip, float unscaledWidth = 80) + { + var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, manip.PrimaryId.Id, out var newId, 0, ushort.MaxValue, + manip.PrimaryId.Id <= 1); + ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 + + "This should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, newId, manip.SecondaryId, manip.Variant.Id, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawSecondaryId(ref ImcManipulation manip, float unscaledWidth = 100) + { + var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, manip.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); + ImUtf8.HoverTooltip("Secondary ID"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, newId, manip.Variant.Id, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawVariant(ref ImcManipulation manip, float unscaledWidth = 45) + { + var ret = IdInput("##imcVariant"u8, unscaledWidth, manip.Variant.Id, out var newId, 0, byte.MaxValue, false); + ImUtf8.HoverTooltip("Variant ID"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, (byte)newId, manip.EquipSlot, + manip.Entry); + return ret; + } + + public static bool DrawSlot(ref ImcManipulation manip, float unscaledWidth = 100) + { + bool ret; + EquipSlot slot; + switch (manip.ObjectType) + { + case ObjectType.Equipment: + case ObjectType.DemiHuman: + ret = Combos.EqpEquipSlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + break; + case ObjectType.Accessory: + ret = Combos.AccessorySlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + break; + default: return false; + } + + ImUtf8.HoverTooltip("Equip Slot"u8); + if (ret) + manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, manip.Variant.Id, slot, + manip.Entry); + return ret; + } + + public static bool DrawMaterialId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##materialId"u8, "Material ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.MaterialId, defaultEntry.MaterialId, + out var newValue, (byte)1, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { MaterialId = newValue }; + return true; + } + + public static bool DrawMaterialAnimationId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##mAnimId"u8, "Material Animation ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.MaterialAnimationId, + defaultEntry.MaterialAnimationId, out var newValue, (byte)0, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { MaterialAnimationId = newValue }; + return true; + } + + public static bool DrawDecalId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##decalId"u8, "Decal ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.DecalId, defaultEntry.DecalId, out var newValue, + (byte)0, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { DecalId = newValue }; + return true; + } + + public static bool DrawVfxId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##vfxId"u8, "VFX ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.VfxId, defaultEntry.VfxId, out var newValue, (byte)0, + byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { VfxId = newValue }; + return true; + } + + public static bool DrawSoundId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##soundId"u8, "Sound ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.SoundId, defaultEntry.SoundId, out var newValue, + (byte)0, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { SoundId = newValue }; + return true; + } + + public static bool DrawAttributes(ImcEntry defaultEntry, ref ImcEntry entry) + { + var changes = false; + for (var i = 0; i < ImcEntry.NumAttributes; ++i) + { + using var id = ImRaii.PushId(i); + var flag = 1 << i; + var value = (entry.AttributeMask & flag) != 0; + var def = (defaultEntry.AttributeMask & flag) != 0; + if (Checkmark("##attribute"u8, "ABCDEFGHIJ"u8.Slice(i, 1), value, def, out var newValue)) + { + var newMask = (ushort)(newValue ? entry.AttributeMask | flag : entry.AttributeMask & ~flag); + entry = entry with { AttributeMask = newMask }; + changes = true; + } + + if (i < ImcEntry.NumAttributes - 1) + ImGui.SameLine(); + } + + return changes; + } + + + /// + /// A number input for ids with an optional max id of given width. + /// Returns true if newId changed against currentId. + /// + private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, + bool border) + { + int tmp = currentId; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); + if (ImUtf8.InputScalar(label, ref tmp)) + tmp = Math.Clamp(tmp, minId, maxId); + + newId = (ushort)tmp; + return newId != currentId; + } + + /// + /// A dragging int input of given width that compares against a default value, shows a tooltip and clamps against min and max. + /// Returns true if newValue changed against currentValue. + /// + private static bool DragInput(ReadOnlySpan label, ReadOnlySpan tooltip, float width, T currentValue, T defaultValue, + out T newValue, T minValue, T maxValue, float speed, bool addDefault) where T : unmanaged, INumber + { + newValue = currentValue; + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue > currentValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + ImGui.SetNextItemWidth(width); + if (ImUtf8.DragScalar(label, ref newValue, minValue, maxValue, speed)) + newValue = newValue <= minValue ? minValue : newValue >= maxValue ? maxValue : newValue; + + if (addDefault) + ImUtf8.HoverTooltip($"{tooltip}\nDefault Value: {defaultValue}"); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + + return newValue != currentValue; + } + + /// + /// A checkmark that compares against a default value and shows a tooltip. + /// Returns true if newValue is changed against currentValue. + /// + private static bool Checkmark(ReadOnlySpan label, ReadOnlySpan tooltip, bool currentValue, bool defaultValue, + out bool newValue) + { + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + newValue = currentValue; + ImUtf8.Checkbox(label, ref newValue); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + return newValue != currentValue; + } +} diff --git a/Penumbra/UI/ModsTab/MetaManipulationDrawer.cs b/Penumbra/UI/ModsTab/MetaManipulationDrawer.cs deleted file mode 100644 index 1f2273b5..00000000 --- a/Penumbra/UI/ModsTab/MetaManipulationDrawer.cs +++ /dev/null @@ -1,105 +0,0 @@ -using ImGuiNET; -using OtterGui.Raii; -using OtterGui.Text; -using Penumbra.GameData.Enums; -using Penumbra.Meta.Manipulations; -using Penumbra.UI.Classes; - -namespace Penumbra.UI.ModsTab; - -public static class MetaManipulationDrawer -{ - public static bool DrawObjectType(ref ImcManipulation manip, float width = 110) - { - var ret = Combos.ImcType("##imcType", manip.ObjectType, out var type, width); - ImUtf8.HoverTooltip("Object Type"u8); - - if (ret) - { - var equipSlot = type switch - { - ObjectType.Equipment => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, - ObjectType.DemiHuman => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, - ObjectType.Accessory => manip.EquipSlot.IsAccessory() ? manip.EquipSlot : EquipSlot.Ears, - _ => EquipSlot.Unknown, - }; - manip = new ImcManipulation(type, manip.BodySlot, manip.PrimaryId, manip.SecondaryId == 0 ? 1 : manip.SecondaryId, - manip.Variant.Id, equipSlot, manip.Entry); - } - - return ret; - } - - public static bool DrawPrimaryId(ref ImcManipulation manip, float unscaledWidth = 80) - { - var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, manip.PrimaryId.Id, out var newId, 0, ushort.MaxValue, - manip.PrimaryId.Id <= 1); - ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 - + "This should generally not be left <= 1 unless you explicitly want that."u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, newId, manip.SecondaryId, manip.Variant.Id, manip.EquipSlot, - manip.Entry); - return ret; - } - - public static bool DrawSecondaryId(ref ImcManipulation manip, float unscaledWidth = 100) - { - var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, manip.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); - ImUtf8.HoverTooltip("Secondary ID"u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, newId, manip.Variant.Id, manip.EquipSlot, - manip.Entry); - return ret; - } - - public static bool DrawVariant(ref ImcManipulation manip, float unscaledWidth = 45) - { - var ret = IdInput("##imcVariant"u8, unscaledWidth, manip.Variant.Id, out var newId, 0, byte.MaxValue, false); - ImUtf8.HoverTooltip("Variant ID"u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, (byte)newId, manip.EquipSlot, - manip.Entry); - return ret; - } - - public static bool DrawSlot(ref ImcManipulation manip, float unscaledWidth = 100) - { - bool ret; - EquipSlot slot; - switch (manip.ObjectType) - { - case ObjectType.Equipment: - case ObjectType.DemiHuman: - ret = Combos.EqpEquipSlot("##slot", manip.EquipSlot, out slot, unscaledWidth); - break; - case ObjectType.Accessory: - ret = Combos.AccessorySlot("##slot", manip.EquipSlot, out slot, unscaledWidth); - break; - default: return false; - } - - ImUtf8.HoverTooltip("Equip Slot"u8); - if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, manip.Variant.Id, slot, - manip.Entry); - return ret; - } - - /// - /// A number input for ids with an optional max id of given width. - /// Returns true if newId changed against currentId. - /// - private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, - bool border) - { - int tmp = currentId; - ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); - if (ImUtf8.InputScalar(label, ref tmp)) - tmp = Math.Clamp(tmp, minId, maxId); - - newId = (ushort)tmp; - return newId != currentId; - } -} From 125e5628ecbf2e42d75e8c499db39bdeef3ba668 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 May 2024 23:24:37 +0200 Subject: [PATCH 0610/1381] Fix fuckup. --- Penumbra/Mods/Groups/ModSaveGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index 7efc76a6..05437e3d 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -72,7 +72,7 @@ public readonly struct ModSaveGroup : ISavable var serializer = new JsonSerializer { Formatting = Formatting.Indented }; j.WriteStartObject(); if (_groupIdx >= 0) - _group!.WriteJson(j, serializer); + _group!.WriteJson(j, serializer, _basePath); else SubMod.WriteModContainer(j, serializer, _defaultMod!, _basePath); j.WriteEndObject(); From 65627b5002c2b1ff9ed6b73cd5d1e7efb7ef2963 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 24 May 2024 16:14:48 +0200 Subject: [PATCH 0611/1381] Fix a weird age-old bug apparently? --- Penumbra/Collections/Cache/CollectionCacheManager.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index ca57c8b9..ae424b94 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -274,17 +274,17 @@ public class CollectionCacheManager : IDisposable return; } - type.HandlingInfo(out _, out var recomputeList, out var reload); + type.HandlingInfo(out _, out var recomputeList, out var justAdd); if (!recomputeList) return; foreach (var collection in _storage.Where(collection => collection.HasCache && collection[mod.Index].Settings is { Enabled: true })) { - if (reload) - collection._cache!.ReloadMod(mod, true); - else + if (justAdd) collection._cache!.AddMod(mod, true); + else + collection._cache!.ReloadMod(mod, true); } } From 4743acf76786518307782677d6d38c48faeb0b95 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 24 May 2024 16:15:04 +0200 Subject: [PATCH 0612/1381] Make IMC handling even better. --- Penumbra.GameData | 2 +- Penumbra/Meta/ImcChecker.cs | 36 +++ Penumbra/Meta/Manipulations/Imc.cs | 24 +- .../Meta/Manipulations/ImcManipulation.cs | 169 ++++-------- Penumbra/Meta/MetaFileManager.cs | 2 + Penumbra/Mods/Groups/ImcModGroup.cs | 251 ++++++++++-------- .../Manager/OptionEditor/ImcModGroupEditor.cs | 16 +- .../Manager/OptionEditor/ModGroupEditor.cs | 2 +- Penumbra/Mods/SubMods/ImcSubMod.cs | 12 +- Penumbra/Services/StaticServiceManager.cs | 3 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 65 ++--- Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs | 68 ++--- .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 161 +++++------ .../UI/ModsTab/Groups/ModGroupEditDrawer.cs | 32 ++- Penumbra/UI/ModsTab/ImcManipulationDrawer.cs | 53 ++-- 15 files changed, 437 insertions(+), 459 deletions(-) create mode 100644 Penumbra/Meta/ImcChecker.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index e8220a0a..ec35e664 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e8220a0a74e9480330e98ed7ca462353434b9649 +Subproject commit ec35e66499eb388b4e7917e4fae4615218d33335 diff --git a/Penumbra/Meta/ImcChecker.cs b/Penumbra/Meta/ImcChecker.cs new file mode 100644 index 00000000..14486e21 --- /dev/null +++ b/Penumbra/Meta/ImcChecker.cs @@ -0,0 +1,36 @@ +using Penumbra.GameData.Structs; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Meta; + +public class ImcChecker(MetaFileManager metaFileManager) +{ + public readonly record struct CachedEntry(ImcEntry Entry, bool FileExists, bool VariantExists); + + private readonly Dictionary _cachedDefaultEntries = new(); + + public CachedEntry GetDefaultEntry(ImcIdentifier identifier, bool storeCache) + { + if (_cachedDefaultEntries.TryGetValue(identifier, out var entry)) + return entry; + + try + { + var e = ImcFile.GetDefault(metaFileManager, identifier.GamePath(), identifier.EquipSlot, identifier.Variant, out var entryExists); + entry = new CachedEntry(e, true, entryExists); + } + catch (Exception) + { + entry = new CachedEntry(default, false, false); + } + + if (storeCache) + _cachedDefaultEntries.Add(identifier, entry); + return entry; + } + + public CachedEntry GetDefaultEntry(ImcManipulation imcManip, bool storeCache) + => GetDefaultEntry(new ImcIdentifier(imcManip.PrimaryId, imcManip.Variant, imcManip.ObjectType, imcManip.SecondaryId.Id, + imcManip.EquipSlot, imcManip.BodySlot), storeCache); +} diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index 9b123df1..fef86520 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -15,6 +15,8 @@ public readonly record struct ImcIdentifier( EquipSlot EquipSlot, BodySlot BodySlot) : IMetaIdentifier, IComparable { + public static readonly ImcIdentifier Default = new(EquipSlot.Body, 1, (Variant)1); + public ImcIdentifier(EquipSlot slot, PrimaryId primaryId, ushort variant) : this(primaryId, (Variant)Math.Clamp(variant, (ushort)0, byte.MaxValue), slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, @@ -25,6 +27,9 @@ public readonly record struct ImcIdentifier( : this(primaryId, variant, slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, BodySlot.Unknown) { } + public ImcManipulation ToManipulation(ImcEntry entry) + => new(ObjectType, BodySlot, PrimaryId, SecondaryId.Id, Variant.Id, EquipSlot, entry); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { var path = ObjectType switch @@ -137,9 +142,12 @@ public readonly record struct ImcIdentifier( return b != 0 ? b : Variant.Id.CompareTo(other.Variant.Id); } - public static ImcIdentifier? FromJson(JObject jObj) + public static ImcIdentifier? FromJson(JObject? jObj) { - var objectType = jObj["PrimaryId"]?.ToObject() ?? ObjectType.Unknown; + if (jObj == null) + return null; + + var objectType = jObj["ObjectType"]?.ToObject() ?? ObjectType.Unknown; var primaryId = new PrimaryId(jObj["PrimaryId"]?.ToObject() ?? 0); var variant = jObj["Variant"]?.ToObject() ?? 0; if (variant > byte.MaxValue) @@ -178,12 +186,12 @@ public readonly record struct ImcIdentifier( public JObject AddToJson(JObject jObj) { - jObj["ObjectType"] = ObjectType.ToString(); - jObj["PrimaryId"] = PrimaryId.Id; - jObj["PrimaryId"] = SecondaryId.Id; - jObj["Variant"] = Variant.Id; - jObj["EquipSlot"] = EquipSlot.ToString(); - jObj["BodySlot"] = BodySlot.ToString(); + jObj["ObjectType"] = ObjectType.ToString(); + jObj["PrimaryId"] = PrimaryId.Id; + jObj["SecondaryId"] = SecondaryId.Id; + jObj["Variant"] = Variant.Id; + jObj["EquipSlot"] = EquipSlot.ToString(); + jObj["BodySlot"] = BodySlot.ToString(); return jObj; } } diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs index 45295990..945aab04 100644 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ b/Penumbra/Meta/Manipulations/ImcManipulation.cs @@ -12,171 +12,96 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct ImcManipulation : IMetaManipulation { - public ImcEntry Entry { get; private init; } - public PrimaryId PrimaryId { get; private init; } - public PrimaryId SecondaryId { get; private init; } - public Variant Variant { get; private init; } + [JsonIgnore] + public ImcIdentifier Identifier { get; private init; } + + public ImcEntry Entry { get; private init; } + + + public PrimaryId PrimaryId + => Identifier.PrimaryId; + + public SecondaryId SecondaryId + => Identifier.SecondaryId; + + public Variant Variant + => Identifier.Variant; [JsonConverter(typeof(StringEnumConverter))] - public ObjectType ObjectType { get; private init; } + public ObjectType ObjectType + => Identifier.ObjectType; [JsonConverter(typeof(StringEnumConverter))] - public EquipSlot EquipSlot { get; private init; } + public EquipSlot EquipSlot + => Identifier.EquipSlot; [JsonConverter(typeof(StringEnumConverter))] - public BodySlot BodySlot { get; private init; } + public BodySlot BodySlot + => Identifier.BodySlot; public ImcManipulation(EquipSlot equipSlot, ushort variant, PrimaryId primaryId, ImcEntry entry) + : this(new ImcIdentifier(equipSlot, primaryId, variant), entry) + { } + + public ImcManipulation(ImcIdentifier identifier, ImcEntry entry) { - Entry = entry; - PrimaryId = primaryId; - Variant = (Variant)Math.Clamp(variant, (ushort)0, byte.MaxValue); - SecondaryId = 0; - ObjectType = equipSlot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment; - EquipSlot = equipSlot; - BodySlot = variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown; + Identifier = identifier; + Entry = entry; } + // Variants were initially ushorts but got shortened to bytes. // There are still some manipulations around that have values > 255 for variant, // so we change the unused value to something nonsensical in that case, just so they do not compare equal, // and clamp the variant to 255. [JsonConstructor] - internal ImcManipulation(ObjectType objectType, BodySlot bodySlot, PrimaryId primaryId, PrimaryId secondaryId, ushort variant, + internal ImcManipulation(ObjectType objectType, BodySlot bodySlot, PrimaryId primaryId, SecondaryId secondaryId, ushort variant, EquipSlot equipSlot, ImcEntry entry) { - Entry = entry; - ObjectType = objectType; - PrimaryId = primaryId; - Variant = (Variant)Math.Clamp(variant, (ushort)0, byte.MaxValue); - - if (objectType is ObjectType.Accessory or ObjectType.Equipment) + Entry = entry; + var v = (Variant)Math.Clamp(variant, (ushort)0, byte.MaxValue); + Identifier = objectType switch { - BodySlot = variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown; - SecondaryId = 0; - EquipSlot = equipSlot; - } - else if (objectType is ObjectType.DemiHuman) - { - BodySlot = variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown; - SecondaryId = secondaryId; - EquipSlot = equipSlot == EquipSlot.Unknown ? EquipSlot.Head : equipSlot; - } - else - { - BodySlot = bodySlot; - SecondaryId = secondaryId; - EquipSlot = variant > byte.MaxValue ? EquipSlot.All : EquipSlot.Unknown; - } + ObjectType.Accessory or ObjectType.Equipment => new ImcIdentifier(primaryId, v, objectType, 0, equipSlot, + variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), + ObjectType.DemiHuman => new ImcIdentifier(primaryId, v, objectType, secondaryId, + equipSlot == EquipSlot.Unknown ? EquipSlot.Head : equipSlot, variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), + _ => new ImcIdentifier(primaryId, v, objectType, secondaryId, equipSlot == EquipSlot.Unknown ? EquipSlot.Head : equipSlot, + bodySlot), + }; } public ImcManipulation Copy(ImcEntry entry) - => new(ObjectType, BodySlot, PrimaryId, SecondaryId, Variant.Id, EquipSlot, entry); + => new(Identifier, entry); public override string ToString() - => ObjectType is ObjectType.Equipment or ObjectType.Accessory - ? $"Imc - {PrimaryId} - {EquipSlot} - {Variant}" - : $"Imc - {PrimaryId} - {ObjectType} - {SecondaryId} - {BodySlot} - {Variant}"; + => Identifier.ToString(); public bool Equals(ImcManipulation other) - => PrimaryId == other.PrimaryId - && Variant == other.Variant - && SecondaryId == other.SecondaryId - && ObjectType == other.ObjectType - && EquipSlot == other.EquipSlot - && BodySlot == other.BodySlot; + => Identifier == other.Identifier; public override bool Equals(object? obj) => obj is ImcManipulation other && Equals(other); public override int GetHashCode() - => HashCode.Combine(PrimaryId, Variant, SecondaryId, (int)ObjectType, (int)EquipSlot, (int)BodySlot); + => Identifier.GetHashCode(); public int CompareTo(ImcManipulation other) - { - var o = ObjectType.CompareTo(other.ObjectType); - if (o != 0) - return o; - - var i = PrimaryId.Id.CompareTo(other.PrimaryId.Id); - if (i != 0) - return i; - - if (ObjectType is ObjectType.Equipment or ObjectType.Accessory) - { - var e = EquipSlot.CompareTo(other.EquipSlot); - return e != 0 ? e : Variant.Id.CompareTo(other.Variant.Id); - } - - if (ObjectType is ObjectType.DemiHuman) - { - var e = EquipSlot.CompareTo(other.EquipSlot); - if (e != 0) - return e; - } - - var s = SecondaryId.Id.CompareTo(other.SecondaryId.Id); - if (s != 0) - return s; - - var b = BodySlot.CompareTo(other.BodySlot); - return b != 0 ? b : Variant.Id.CompareTo(other.Variant.Id); - } + => Identifier.CompareTo(other.Identifier); public MetaIndex FileIndex() - => (MetaIndex)(-1); + => Identifier.FileIndex(); public Utf8GamePath GamePath() - { - return ObjectType switch - { - ObjectType.Accessory => Utf8GamePath.FromString(GamePaths.Accessory.Imc.Path(PrimaryId), out var p) ? p : Utf8GamePath.Empty, - ObjectType.Equipment => Utf8GamePath.FromString(GamePaths.Equipment.Imc.Path(PrimaryId), out var p) ? p : Utf8GamePath.Empty, - ObjectType.DemiHuman => Utf8GamePath.FromString(GamePaths.DemiHuman.Imc.Path(PrimaryId, SecondaryId), out var p) - ? p - : Utf8GamePath.Empty, - ObjectType.Monster => Utf8GamePath.FromString(GamePaths.Monster.Imc.Path(PrimaryId, SecondaryId), out var p) - ? p - : Utf8GamePath.Empty, - ObjectType.Weapon => Utf8GamePath.FromString(GamePaths.Weapon.Imc.Path(PrimaryId, SecondaryId), out var p) ? p : Utf8GamePath.Empty, - _ => throw new NotImplementedException(), - }; - } + => Identifier.GamePath(); public bool Apply(ImcFile file) => file.SetEntry(ImcFile.PartIndex(EquipSlot), Variant.Id, Entry); public bool Validate(bool withMaterial) { - switch (ObjectType) - { - case ObjectType.Accessory: - case ObjectType.Equipment: - if (BodySlot is not BodySlot.Unknown) - return false; - if (!EquipSlot.IsEquipment() && !EquipSlot.IsAccessory()) - return false; - if (SecondaryId != 0) - return false; - - break; - case ObjectType.DemiHuman: - if (BodySlot is not BodySlot.Unknown) - return false; - if (!EquipSlot.IsEquipment() && !EquipSlot.IsAccessory()) - return false; - - break; - default: - if (!Enum.IsDefined(BodySlot)) - return false; - if (EquipSlot is not EquipSlot.Unknown) - return false; - if (!Enum.IsDefined(ObjectType)) - return false; - - break; - } + if (!Identifier.Validate()) + return false; if (withMaterial && Entry.MaterialId == 0) return false; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index cd99396b..40fceb07 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -27,6 +27,7 @@ public unsafe class MetaFileManager internal readonly ValidityChecker ValidityChecker; internal readonly ObjectIdentification Identifier; internal readonly FileCompactor Compactor; + internal readonly ImcChecker ImcChecker; public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, ObjectIdentification identifier, @@ -40,6 +41,7 @@ public unsafe class MetaFileManager ValidityChecker = validityChecker; Identifier = identifier; Compactor = compactor; + ImcChecker = new ImcChecker(this); interop.InitializeFromAttributes(this); } diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index cf228889..e0d70aa6 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -1,25 +1,21 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.GameData.Data; -using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; -using Penumbra.UI.ModsTab; using Penumbra.UI.ModsTab.Groups; -using Penumbra.Util; namespace Penumbra.Mods.Groups; public class ImcModGroup(Mod mod) : IModGroup { - public const int DisabledIndex = 60; - public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; public string Description { get; set; } = string.Empty; @@ -33,33 +29,35 @@ public class ImcModGroup(Mod mod) : IModGroup public ModPriority Priority { get; set; } = ModPriority.Default; public Setting DefaultSettings { get; set; } = Setting.Zero; - public PrimaryId PrimaryId; - public SecondaryId SecondaryId; - public ObjectType ObjectType; - public BodySlot BodySlot; - public EquipSlot EquipSlot; - public Variant Variant; - - public ImcEntry DefaultEntry; + public ImcIdentifier Identifier; + public ImcEntry DefaultEntry; public FullPath? FindBestMatch(Utf8GamePath gamePath) => null; - private bool _canBeDisabled = false; + private bool _canBeDisabled; public bool CanBeDisabled { - get => _canBeDisabled; + get => OptionData.Any(m => m.IsDisableSubMod); set { _canBeDisabled = value; if (!value) + { + OptionData.RemoveAll(m => m.IsDisableSubMod); DefaultSettings = FixSetting(DefaultSettings); + } + else + { + if (!OptionData.Any(m => m.IsDisableSubMod)) + OptionData.Add(ImcSubMod.DisableSubMod(this)); + } } } public bool DefaultDisabled - => _canBeDisabled && DefaultSettings.HasFlag(DisabledIndex); + => IsDisabled(DefaultSettings); public IModOption? AddOption(string name, string description = "") { @@ -86,7 +84,7 @@ public class ImcModGroup(Mod mod) : IModGroup => []; public bool IsOption - => CanBeDisabled || OptionData.Count > 0; + => OptionData.Count > 0; public int GetIndex() => ModGroup.GetIndex(this); @@ -94,6 +92,128 @@ public class ImcModGroup(Mod mod) : IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) => new ImcModGroupEditDrawer(editDrawer, this); + public ImcManipulation GetManip(ushort mask) + => new(Identifier.ObjectType, Identifier.BodySlot, Identifier.PrimaryId, Identifier.SecondaryId.Id, Identifier.Variant.Id, + Identifier.EquipSlot, DefaultEntry with { AttributeMask = mask }); + + public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + { + if (IsDisabled(setting)) + return; + + var mask = GetCurrentMask(setting); + var imc = GetManip(mask); + manipulations.Add(imc); + } + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => Identifier.AddChangedItems(identifier, changedItems); + + public Setting FixSetting(Setting setting) + => new(setting.Value & ((1ul << OptionData.Count) - 1)); + + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) + { + ModSaveGroup.WriteJsonBase(jWriter, this); + var jObj = Identifier.AddToJson(new JObject()); + jWriter.WritePropertyName(nameof(Identifier)); + jObj.WriteTo(jWriter); + jWriter.WritePropertyName(nameof(DefaultEntry)); + serializer.Serialize(jWriter, DefaultEntry); + jWriter.WritePropertyName("Options"); + jWriter.WriteStartArray(); + foreach (var option in OptionData) + { + jWriter.WriteStartObject(); + SubMod.WriteModOption(jWriter, option); + if (option.IsDisableSubMod) + { + jWriter.WritePropertyName(nameof(option.IsDisableSubMod)); + jWriter.WriteValue(true); + } + else + { + jWriter.WritePropertyName(nameof(option.AttributeMask)); + jWriter.WriteValue(option.AttributeMask); + } + + jWriter.WriteEndObject(); + } + + jWriter.WriteEndArray(); + } + + public (int Redirections, int Swaps, int Manips) GetCounts() + => (0, 0, 1); + + public static ImcModGroup? Load(Mod mod, JObject json) + { + var options = json["Options"]; + var identifier = ImcIdentifier.FromJson(json[nameof(Identifier)] as JObject); + var ret = new ImcModGroup(mod) + { + Name = json[nameof(Name)]?.ToObject() ?? string.Empty, + Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, + DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), + }; + if (ret.Name.Length == 0) + return null; + + if (!identifier.HasValue || ret.DefaultEntry.MaterialId == 0) + { + Penumbra.Messager.NotificationMessage($"Could not add IMC group {ret.Name} because the associated IMC Entry is invalid.", + NotificationType.Warning); + return null; + } + + var rollingMask = ret.DefaultEntry.AttributeMask; + if (options != null) + foreach (var child in options.Children()) + { + var subMod = new ImcSubMod(ret, child); + + if (subMod.IsDisableSubMod) + ret._canBeDisabled = true; + + if (subMod.IsDisableSubMod && ret.OptionData.FirstOrDefault(m => m.IsDisableSubMod) is { } disable) + { + Penumbra.Messager.NotificationMessage( + $"Could not add IMC option {subMod.Name} to {ret.Name} because it already contains {disable.Name} as disable option.", + NotificationType.Warning); + } + else if ((subMod.AttributeMask & rollingMask) != 0) + { + Penumbra.Messager.NotificationMessage( + $"Could not add IMC option {subMod.Name} to {ret.Name} because it contains attributes already in use.", + NotificationType.Warning); + } + else + { + rollingMask |= subMod.AttributeMask; + ret.OptionData.Add(subMod); + } + } + + ret.Identifier = identifier.Value; + ret.DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero; + ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); + return ret; + } + + private bool IsDisabled(Setting setting) + { + if (!CanBeDisabled) + return false; + + var idx = OptionData.IndexOf(m => m.IsDisableSubMod); + if (idx >= 0) + return setting.HasFlag(idx); + + Penumbra.Log.Warning($"A IMC Group should be able to be disabled, but does not contain a disable option."); + return false; + } + private ushort GetCurrentMask(Setting setting) { var mask = DefaultEntry.AttributeMask; @@ -108,101 +228,4 @@ public class ImcModGroup(Mod mod) : IModGroup return mask; } - - private ushort GetFullMask() - => GetCurrentMask(Setting.AllBits(63)); - - public ImcManipulation GetManip(ushort mask) - => new(ObjectType, BodySlot, PrimaryId, SecondaryId.Id, Variant.Id, EquipSlot, - DefaultEntry with { AttributeMask = mask }); - - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) - { - if (CanBeDisabled && setting.HasFlag(DisabledIndex)) - return; - - var mask = GetCurrentMask(setting); - var imc = GetManip(mask); - manipulations.Add(imc); - } - - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - => identifier.MetaChangedItems(changedItems, GetManip(0)); - - public Setting FixSetting(Setting setting) - => new(setting.Value & (((1ul << OptionData.Count) - 1) | (CanBeDisabled ? 1ul << DisabledIndex : 0))); - - public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) - { - ModSaveGroup.WriteJsonBase(jWriter, this); - jWriter.WritePropertyName(nameof(ObjectType)); - jWriter.WriteValue(ObjectType.ToString()); - jWriter.WritePropertyName(nameof(BodySlot)); - jWriter.WriteValue(BodySlot.ToString()); - jWriter.WritePropertyName(nameof(EquipSlot)); - jWriter.WriteValue(EquipSlot.ToString()); - jWriter.WritePropertyName(nameof(PrimaryId)); - jWriter.WriteValue(PrimaryId.Id); - jWriter.WritePropertyName(nameof(SecondaryId)); - jWriter.WriteValue(SecondaryId.Id); - jWriter.WritePropertyName(nameof(Variant)); - jWriter.WriteValue(Variant.Id); - jWriter.WritePropertyName(nameof(DefaultEntry)); - serializer.Serialize(jWriter, DefaultEntry); - jWriter.WritePropertyName("Options"); - jWriter.WriteStartArray(); - foreach (var option in OptionData) - { - jWriter.WriteStartObject(); - SubMod.WriteModOption(jWriter, option); - jWriter.WritePropertyName(nameof(option.AttributeMask)); - jWriter.WriteValue(option.AttributeMask); - jWriter.WriteEndObject(); - } - - jWriter.WriteEndArray(); - } - - public (int Redirections, int Swaps, int Manips) GetCounts() - => (0, 0, 1); - - public static ImcModGroup? Load(Mod mod, JObject json) - { - var options = json["Options"]; - var ret = new ImcModGroup(mod) - { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, - DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, - ObjectType = json[nameof(ObjectType)]?.ToObject() ?? ObjectType.Unknown, - BodySlot = json[nameof(BodySlot)]?.ToObject() ?? BodySlot.Unknown, - EquipSlot = json[nameof(EquipSlot)]?.ToObject() ?? EquipSlot.Unknown, - PrimaryId = new PrimaryId(json[nameof(PrimaryId)]?.ToObject() ?? 0), - SecondaryId = new SecondaryId(json[nameof(SecondaryId)]?.ToObject() ?? 0), - Variant = new Variant(json[nameof(Variant)]?.ToObject() ?? 0), - CanBeDisabled = json[nameof(CanBeDisabled)]?.ToObject() ?? false, - DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), - }; - if (ret.Name.Length == 0) - return null; - - if (options != null) - foreach (var child in options.Children()) - { - var subMod = new ImcSubMod(ret, child); - ret.OptionData.Add(subMod); - } - - if (!new ImcManipulation(ret.ObjectType, ret.BodySlot, ret.PrimaryId, ret.SecondaryId.Id, ret.Variant.Id, ret.EquipSlot, - ret.DefaultEntry).Validate(true)) - { - Penumbra.Messager.NotificationMessage($"Could not add IMC group because the associated IMC Entry is invalid.", - NotificationType.Warning); - return null; - } - - ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); - return ret; - } } diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index 20021d29..f9fd532f 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -7,7 +7,6 @@ using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -using static FFXIVClientStructs.FFXIV.Client.UI.Misc.ConfigModule; namespace Penumbra.Mods.Manager.OptionEditor; @@ -15,13 +14,13 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ : ModOptionEditor(communicator, saveService, config), IService { /// Add a new, empty imc group with the given manipulation data. - public ImcModGroup? AddModGroup(Mod mod, string newName, ImcManipulation manip, SaveType saveType = SaveType.ImmediateSync) + public ImcModGroup? AddModGroup(Mod mod, string newName, ImcIdentifier identifier, ImcEntry defaultEntry, SaveType saveType = SaveType.ImmediateSync) { if (!ModGroupEditor.VerifyFileName(mod, null, newName, true)) return null; var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; - var group = CreateGroup(mod, newName, manip, maxPriority); + var group = CreateGroup(mod, newName, identifier, defaultEntry, maxPriority); mod.Groups.Add(group); SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, group, null, null, -1); @@ -97,19 +96,14 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ }; - private static ImcModGroup CreateGroup(Mod mod, string newName, ImcManipulation manip, ModPriority priority, + private static ImcModGroup CreateGroup(Mod mod, string newName, ImcIdentifier identifier, ImcEntry defaultEntry, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) => new(mod) { Name = newName, Priority = priority, - ObjectType = manip.ObjectType, - EquipSlot = manip.EquipSlot, - BodySlot = manip.BodySlot, - PrimaryId = manip.PrimaryId, - SecondaryId = manip.SecondaryId.Id, - Variant = manip.Variant, - DefaultEntry = manip.Entry, + Identifier = identifier, + DefaultEntry = defaultEntry, }; protected override ImcSubMod? CloneOption(ImcModGroup group, IModOption option) diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 969ad3fa..e1db0ccf 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -246,7 +246,7 @@ public class ModGroupEditor( { GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), - GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, saveType), + GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, default, saveType), _ => null, }; diff --git a/Penumbra/Mods/SubMods/ImcSubMod.cs b/Penumbra/Mods/SubMods/ImcSubMod.cs index 7f46bc95..c5c8f002 100644 --- a/Penumbra/Mods/SubMods/ImcSubMod.cs +++ b/Penumbra/Mods/SubMods/ImcSubMod.cs @@ -12,13 +12,23 @@ public class ImcSubMod(ImcModGroup group) : IModOption : this(group) { SubMod.LoadOptionData(json, this); - AttributeMask = (ushort)((json[nameof(AttributeMask)]?.ToObject() ?? 0) & ImcEntry.AttributesMask); + AttributeMask = (ushort)((json[nameof(AttributeMask)]?.ToObject() ?? 0) & ImcEntry.AttributesMask); + IsDisableSubMod = json[nameof(IsDisableSubMod)]?.ToObject() ?? false; } + public static ImcSubMod DisableSubMod(ImcModGroup group) + => new(group) + { + Name = "Disable", + AttributeMask = 0, + IsDisableSubMod = true, + }; + public Mod Mod => Group.Mod; public ushort AttributeMask; + public bool IsDisableSubMod { get; private init; } Mod IModOption.Mod => Mod; diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 19ae31a2..0c6648ba 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -101,7 +101,8 @@ public static class StaticServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton(); + .AddSingleton() + .AddSingleton(p => p.GetRequiredService().ImcChecker); private static ServiceManager AddConfiguration(this ServiceManager services) => services.AddSingleton() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 99889360..68933c9e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -19,9 +19,6 @@ public partial class ModEditWindow private const string ModelSetIdTooltip = "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."; - private const string PrimaryIdTooltip = - "Primary ID - You can usually find this as the 'x####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."; - private const string ModelSetIdTooltipShort = "Model Set ID"; private const string EquipSlotTooltip = "Equip Slot"; private const string ModelRaceTooltip = "Model Race"; @@ -316,7 +313,7 @@ public partial class ModEditWindow private static class ImcRow { - private static ImcManipulation _new = new(EquipSlot.Head, 1, 1, new ImcEntry()); + private static ImcIdentifier _newIdentifier = ImcIdentifier.Default; private static float IdWidth => 80 * UiHelpers.Scale; @@ -324,75 +321,60 @@ public partial class ModEditWindow private static float SmallIdWidth => 45 * UiHelpers.Scale; - /// Convert throwing to null-return if the file does not exist. - private static ImcEntry? GetDefault(MetaFileManager metaFileManager, ImcManipulation imc) - { - try - { - return ImcFile.GetDefault(metaFileManager, imc.GamePath(), imc.EquipSlot, imc.Variant, out _); - } - catch - { - return null; - } - } - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) { ImGui.TableNextColumn(); CopyToClipboardButton("Copy all current IMC manipulations to clipboard.", iconSize, editor.MetaEditor.Imc.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); - var defaultEntry = GetDefault(metaFileManager, _new); - var canAdd = defaultEntry != null && editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : defaultEntry == null ? "This IMC file does not exist." : "This entry is already edited."; - defaultEntry ??= new ImcEntry(); + var (defaultEntry, fileExists, _) = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true); + var manip = (MetaManipulation)new ImcManipulation(_newIdentifier, defaultEntry); + var canAdd = fileExists && editor.MetaEditor.CanAdd(manip); + var tt = canAdd ? "Stage this edit." : !fileExists ? "This IMC file does not exist." : "This entry is already edited."; if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new.Copy(defaultEntry.Value)); + editor.MetaEditor.Add(manip); // Identifier ImGui.TableNextColumn(); - var change = ImcManipulationDrawer.DrawObjectType(ref _new); + var change = ImcManipulationDrawer.DrawObjectType(ref _newIdentifier); ImGui.TableNextColumn(); - change |= ImcManipulationDrawer.DrawPrimaryId(ref _new); + change |= ImcManipulationDrawer.DrawPrimaryId(ref _newIdentifier); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); ImGui.TableNextColumn(); // Equipment and accessories are slightly different imcs than other types. - if (_new.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - change |= ImcManipulationDrawer.DrawSlot(ref _new); + if (_newIdentifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier); else - change |= ImcManipulationDrawer.DrawSecondaryId(ref _new); + change |= ImcManipulationDrawer.DrawSecondaryId(ref _newIdentifier); ImGui.TableNextColumn(); - change |= ImcManipulationDrawer.DrawVariant(ref _new); + change |= ImcManipulationDrawer.DrawVariant(ref _newIdentifier); ImGui.TableNextColumn(); - if (_new.ObjectType is ObjectType.DemiHuman) - change |= ImcManipulationDrawer.DrawSlot(ref _new, 70); + if (_newIdentifier.ObjectType is ObjectType.DemiHuman) + change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier, 70); else ImGui.Dummy(new Vector2(70 * UiHelpers.Scale, 0)); if (change) - _new = _new.Copy(GetDefault(metaFileManager, _new) ?? new ImcEntry()); + defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true).Entry; // Values using var disabled = ImRaii.Disabled(); - - var entry = defaultEntry.Value; ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawMaterialId(entry, ref entry, false); + ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref defaultEntry, false); ImGui.SameLine(); - ImcManipulationDrawer.DrawMaterialAnimationId(entry, ref entry, false); + ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref defaultEntry, false); ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawDecalId(entry, ref entry, false); + ImcManipulationDrawer.DrawDecalId(defaultEntry, ref defaultEntry, false); ImGui.SameLine(); - ImcManipulationDrawer.DrawVfxId(entry, ref entry, false); + ImcManipulationDrawer.DrawVfxId(defaultEntry, ref defaultEntry, false); ImGui.SameLine(); - ImcManipulationDrawer.DrawSoundId(entry, ref entry, false); + ImcManipulationDrawer.DrawSoundId(defaultEntry, ref defaultEntry, false); ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawAttributes(entry, ref entry); + ImcManipulationDrawer.DrawAttributes(defaultEntry, ref defaultEntry); } public static void Draw(MetaFileManager metaFileManager, ImcManipulation meta, ModEditor editor, Vector2 iconSize) @@ -439,10 +421,9 @@ public partial class ModEditWindow using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); ImGui.TableNextColumn(); - var defaultEntry = GetDefault(metaFileManager, meta) ?? new ImcEntry(); + var defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(meta.Identifier, true).Entry; var newEntry = meta.Entry; - - var changes = ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref newEntry, true); + var changes = ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref newEntry, true); ImGui.SameLine(); changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref newEntry, true); ImGui.TableNextColumn(); diff --git a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index 2d80d3df..3ac10cd0 100644 --- a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -5,7 +5,6 @@ using Penumbra.Api.Enums; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -17,20 +16,20 @@ namespace Penumbra.UI.ModsTab.Groups; public class AddGroupDrawer : IUiService { private string _groupName = string.Empty; - private bool _groupNameValid = false; + private bool _groupNameValid; - private ImcManipulation _imcManip = new(EquipSlot.Head, 1, 1, new ImcEntry()); - private ImcEntry _defaultEntry; - private bool _imcFileExists; - private bool _entryExists; - private bool _entryInvalid; - private readonly MetaFileManager _metaManager; - private readonly ModManager _modManager; + private ImcIdentifier _imcIdentifier = ImcIdentifier.Default; + private ImcEntry _defaultEntry; + private bool _imcFileExists; + private bool _entryExists; + private bool _entryInvalid; + private readonly ImcChecker _imcChecker; + private readonly ModManager _modManager; - public AddGroupDrawer(MetaFileManager metaManager, ModManager modManager) + public AddGroupDrawer(ModManager modManager, ImcChecker imcChecker) { - _metaManager = metaManager; _modManager = modManager; + _imcChecker = imcChecker; UpdateEntry(); } @@ -61,7 +60,7 @@ public class AddGroupDrawer : IUiService return; _modManager.OptionEditor.AddModGroup(mod, GroupType.Single, _groupName); - _groupName = string.Empty; + _groupName = string.Empty; _groupNameValid = false; } @@ -74,35 +73,35 @@ public class AddGroupDrawer : IUiService return; _modManager.OptionEditor.AddModGroup(mod, GroupType.Multi, _groupName); - _groupName = string.Empty; + _groupName = string.Empty; _groupNameValid = false; } private void DrawImcInput(float width) { - var change = ImcManipulationDrawer.DrawObjectType(ref _imcManip, width); + var change = ImcManipulationDrawer.DrawObjectType(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawPrimaryId(ref _imcManip, width); - if (_imcManip.ObjectType is ObjectType.Weapon or ObjectType.Monster) + change |= ImcManipulationDrawer.DrawPrimaryId(ref _imcIdentifier, width); + if (_imcIdentifier.ObjectType is ObjectType.Weapon or ObjectType.Monster) { - change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawVariant(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawVariant(ref _imcIdentifier, width); } - else if (_imcManip.ObjectType is ObjectType.DemiHuman) + else if (_imcIdentifier.ObjectType is ObjectType.DemiHuman) { var quarterWidth = (width - ImUtf8.ItemInnerSpacing.X / ImUtf8.GlobalScale) / 2; - change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawSlot(ref _imcManip, quarterWidth); + change |= ImcManipulationDrawer.DrawSlot(ref _imcIdentifier, quarterWidth); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawVariant(ref _imcManip, quarterWidth); + change |= ImcManipulationDrawer.DrawVariant(ref _imcIdentifier, quarterWidth); } else { - change |= ImcManipulationDrawer.DrawSlot(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawSlot(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawVariant(ref _imcManip, width); + change |= ImcManipulationDrawer.DrawVariant(ref _imcIdentifier, width); } if (change) @@ -125,8 +124,8 @@ public class AddGroupDrawer : IUiService : "Add a new multi selection option group to this mod."u8, width, !_groupNameValid || _entryInvalid)) { - _modManager.OptionEditor.ImcEditor.AddModGroup(mod, _groupName, _imcManip); - _groupName = string.Empty; + _modManager.OptionEditor.ImcEditor.AddModGroup(mod, _groupName, _imcIdentifier, _defaultEntry); + _groupName = string.Empty; _groupNameValid = false; } @@ -142,20 +141,7 @@ public class AddGroupDrawer : IUiService private void UpdateEntry() { - try - { - _defaultEntry = ImcFile.GetDefault(_metaManager, _imcManip.GamePath(), _imcManip.EquipSlot, _imcManip.Variant, - out _entryExists); - _imcFileExists = true; - } - catch (Exception) - { - _defaultEntry = new ImcEntry(); - _imcFileExists = false; - _entryExists = false; - } - - _imcManip = _imcManip.Copy(_entryExists ? _defaultEntry : new ImcEntry()); - _entryInvalid = !_imcManip.Validate(true); + (_defaultEntry, _imcFileExists, _entryExists) = _imcChecker.GetDefaultEntry(_imcIdentifier, false); + _entryInvalid = !_imcIdentifier.Validate() || _defaultEntry.MaterialId == 0 || !_entryExists; } } diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 2418c5cb..045149c9 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -1,10 +1,8 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; -using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Text; -using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager.OptionEditor; @@ -16,59 +14,75 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr { public void Draw() { + var identifier = group.Identifier; + var defaultEntry = editor.ImcChecker.GetDefaultEntry(identifier, true).Entry; + var entry = group.DefaultEntry; + var changes = false; + + ImUtf8.TextFramed(identifier.ToString(), 0, editor.AvailableWidth, borderColor: ImGui.GetColorU32(ImGuiCol.Border)); + using (ImUtf8.Group()) { - ImUtf8.Text("Object Type"u8); - if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) - ImUtf8.Text("Slot"u8); - ImUtf8.Text("Primary ID"); - if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) - ImUtf8.Text("Secondary ID"); - ImUtf8.Text("Variant"u8); - ImUtf8.TextFrameAligned("Material ID"u8); - ImUtf8.TextFrameAligned("Material Animation ID"u8); - ImUtf8.TextFrameAligned("Decal ID"u8); ImUtf8.TextFrameAligned("VFX ID"u8); + ImUtf8.TextFrameAligned("Decal ID"u8); + } + + ImGui.SameLine(); + using (ImUtf8.Group()) + { + changes |= ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref entry, true); + changes |= ImcManipulationDrawer.DrawVfxId(defaultEntry, ref entry, true); + changes |= ImcManipulationDrawer.DrawDecalId(defaultEntry, ref entry, true); + } + + ImGui.SameLine(0, editor.PriorityWidth); + using (ImUtf8.Group()) + { + ImUtf8.TextFrameAligned("Material Animation ID"u8); ImUtf8.TextFrameAligned("Sound ID"u8); ImUtf8.TextFrameAligned("Can Be Disabled"u8); - ImUtf8.TextFrameAligned("Default Attributes"u8); } ImGui.SameLine(); + using (ImUtf8.Group()) + { + changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref entry, true); + changes |= ImcManipulationDrawer.DrawSoundId(defaultEntry, ref entry, true); + var canBeDisabled = group.CanBeDisabled; + if (ImUtf8.Checkbox("##disabled"u8, ref canBeDisabled)) + editor.ModManager.OptionEditor.ImcEditor.ChangeCanBeDisabled(group, canBeDisabled); + } + + if (changes) + editor.ModManager.OptionEditor.ImcEditor.ChangeDefaultEntry(group, entry); + + ImGui.Dummy(Vector2.Zero); + DrawOptions(); var attributeCache = new ImcAttributeCache(group); + DrawNewOption(attributeCache); + ImGui.Dummy(Vector2.Zero); + using (ImUtf8.Group()) { - ImUtf8.Text(group.ObjectType.ToName()); - if (group.ObjectType is ObjectType.Equipment or ObjectType.Accessory or ObjectType.DemiHuman) - ImUtf8.Text(group.EquipSlot.ToName()); - ImUtf8.Text($"{group.PrimaryId.Id}"); - if (group.ObjectType is not ObjectType.Equipment and not ObjectType.Accessory) - ImUtf8.Text($"{group.SecondaryId.Id}"); - ImUtf8.Text($"{group.Variant.Id}"); - - ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.MaterialAnimationId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.DecalId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.VfxId}"); - ImUtf8.TextFrameAligned($"{group.DefaultEntry.SoundId}"); - - var canBeDisabled = group.CanBeDisabled; - if (ImUtf8.Checkbox("##disabled"u8, ref canBeDisabled)) - editor.ModManager.OptionEditor.ImcEditor.ChangeCanBeDisabled(group, canBeDisabled, SaveType.Queue); - - var defaultDisabled = group.DefaultDisabled; - ImUtf8.SameLineInner(); - if (ImUtf8.Checkbox("##defaultDisabled"u8, ref defaultDisabled)) - editor.ModManager.OptionEditor.ChangeModGroupDefaultOption(group, - group.DefaultSettings.SetBit(ImcModGroup.DisabledIndex, defaultDisabled)); - - DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, group.DefaultEntry.AttributeMask, group); + ImUtf8.TextFrameAligned("Default Attributes"u8); + foreach (var option in group.OptionData.Where(o => !o.IsDisableSubMod)) + ImUtf8.TextFrameAligned(option.Name); } + ImUtf8.SameLineInner(); + using (ImUtf8.Group()) + { + DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, group.DefaultEntry.AttributeMask, group); + foreach (var option in group.OptionData.Where(o => !o.IsDisableSubMod)) + DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); + } + } + private void DrawOptions() + { foreach (var (option, optionIdx) in group.OptionData.WithIndex()) { using var id = ImRaii.PushId(optionIdx); @@ -83,56 +97,51 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr ImUtf8.SameLineInner(); editor.DrawOptionDescription(option); - ImUtf8.SameLineInner(); - editor.DrawOptionDelete(option); - - ImUtf8.SameLineInner(); - ImGui.Dummy(new Vector2(editor.PriorityWidth, 0)); - - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + editor.OptionIdxSelectable.X + ImUtf8.ItemInnerSpacing.X * 2 + ImUtf8.FrameHeight); - DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); - } - - DrawNewOption(attributeCache); - return; - - static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data) - { - for (var i = 0; i < ImcEntry.NumAttributes; ++i) + if (!option.IsDisableSubMod) { - using var id = ImRaii.PushId(i); - var value = (mask & 1 << i) != 0; - using (ImRaii.Disabled(!cache.CanChange(i))) - { - if (ImUtf8.Checkbox(TerminatedByteString.Empty, ref value)) - { - if (data is ImcModGroup g) - editor.ChangeDefaultAttribute(g, cache, i, value); - else - editor.ChangeOptionAttribute((ImcSubMod)data, cache, i, value); - } - } - - ImUtf8.HoverTooltip($"{(char)('A' + i)}"); - if (i != 9) - ImUtf8.SameLineInner(); + ImUtf8.SameLineInner(); + editor.DrawOptionDelete(option); } } } private void DrawNewOption(in ImcAttributeCache cache) { - if (cache.LowestUnsetMask == 0) - return; - - var name = editor.DrawNewOptionBase(group, group.Options.Count); + var dis = cache.LowestUnsetMask == 0; + var name = editor.DrawNewOptionBase(group, group.Options.Count); var validName = name.Length > 0; - if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + var tt = dis + ? "No Free Attribute Slots for New Options..."u8 + : validName ? "Add a new option to this group."u8 - : "Please enter a name for the new option."u8, !validName)) + : "Please enter a name for the new option."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, !validName || dis)) { editor.ModManager.OptionEditor.ImcEditor.AddOption(group, cache, name); editor.NewOptionName = null; } } + + private static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data) + { + for (var i = 0; i < ImcEntry.NumAttributes; ++i) + { + using var id = ImRaii.PushId(i); + var value = (mask & (1 << i)) != 0; + using (ImRaii.Disabled(!cache.CanChange(i))) + { + if (ImUtf8.Checkbox(TerminatedByteString.Empty, ref value)) + { + if (data is ImcModGroup g) + editor.ChangeDefaultAttribute(g, cache, i, value); + else + editor.ChangeOptionAttribute((ImcSubMod)data, cache, i, value); + } + } + + ImUtf8.HoverTooltip("ABCDEFGHIJ"u8.Slice(i, 1)); + if (i != 9) + ImUtf8.SameLineInner(); + } + } } diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs index e7d70922..e8a27a74 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -7,6 +7,7 @@ using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; using OtterGui.Text.EndObjects; +using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; @@ -22,11 +23,16 @@ public sealed class ModGroupEditDrawer( ModManager modManager, Configuration config, FilenameService filenames, - DescriptionEditPopup descriptionPopup) : IUiService + DescriptionEditPopup descriptionPopup, + ImcChecker imcChecker) : IUiService { - private static ReadOnlySpan DragDropLabel - => "##DragOption"u8; + private static ReadOnlySpan AcrossGroupsLabel + => "##DragOptionAcross"u8; + private static ReadOnlySpan InsideGroupLabel + => "##DragOptionInside"u8; + + internal readonly ImcChecker ImcChecker = imcChecker; internal readonly ModManager ModManager = modManager; internal readonly Queue ActionQueue = new(); @@ -50,6 +56,7 @@ public sealed class ModGroupEditDrawer( private IModGroup? _dragDropGroup; private IModOption? _dragDropOption; + private bool _draggingAcross; public void Draw(Mod mod) { @@ -292,32 +299,30 @@ public sealed class ModGroupEditDrawer( [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Source(IModOption option) { - if (option.Group is not ITexToolsGroup) - return; - using var source = ImUtf8.DragDropSource(); if (!source) return; - if (!DragDropSource.SetPayload(DragDropLabel)) + var across = option.Group is ITexToolsGroup; + + if (!DragDropSource.SetPayload(across ? AcrossGroupsLabel : InsideGroupLabel)) { _dragDropGroup = option.Group; _dragDropOption = option; + _draggingAcross = across; } - ImGui.TextUnformatted($"Dragging option {option.Name} from group {option.Group.Name}..."); + ImUtf8.Text($"Dragging option {option.Name} from group {option.Group.Name}..."); } private void Target(IModGroup group, int optionIdx) { - if (group is not ITexToolsGroup) - return; - - if (_dragDropGroup != group && _dragDropGroup != null && group is MultiModGroup { Options.Count: >= IModGroup.MaxMultiOptions }) + if (_dragDropGroup != group + && (!_draggingAcross || (_dragDropGroup != null && group is MultiModGroup { Options.Count: >= IModGroup.MaxMultiOptions }))) return; using var target = ImRaii.DragDropTarget(); - if (!target.Success || !DragDropTarget.CheckPayload(DragDropLabel)) + if (!target.Success || !DragDropTarget.CheckPayload(_draggingAcross ? AcrossGroupsLabel : InsideGroupLabel)) return; if (_dragDropGroup != null && _dragDropOption != null) @@ -342,6 +347,7 @@ public sealed class ModGroupEditDrawer( _dragDropGroup = null; _dragDropOption = null; + _draggingAcross = false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs index 5873119e..c14652ac 100644 --- a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs +++ b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs @@ -1,8 +1,6 @@ using ImGuiNET; -using OtterGui; using OtterGui.Raii; using OtterGui.Text; -using OtterGui.Text.HelperObjects; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; @@ -12,79 +10,78 @@ namespace Penumbra.UI.ModsTab; public static class ImcManipulationDrawer { - public static bool DrawObjectType(ref ImcManipulation manip, float width = 110) + public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) { - var ret = Combos.ImcType("##imcType", manip.ObjectType, out var type, width); + var ret = Combos.ImcType("##imcType", identifier.ObjectType, out var type, width); ImUtf8.HoverTooltip("Object Type"u8); if (ret) { var equipSlot = type switch { - ObjectType.Equipment => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, - ObjectType.DemiHuman => manip.EquipSlot.IsEquipment() ? manip.EquipSlot : EquipSlot.Head, - ObjectType.Accessory => manip.EquipSlot.IsAccessory() ? manip.EquipSlot : EquipSlot.Ears, + ObjectType.Equipment => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, + ObjectType.DemiHuman => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, + ObjectType.Accessory => identifier.EquipSlot.IsAccessory() ? identifier.EquipSlot : EquipSlot.Ears, _ => EquipSlot.Unknown, }; - manip = new ImcManipulation(type, manip.BodySlot, manip.PrimaryId, manip.SecondaryId == 0 ? 1 : manip.SecondaryId, - manip.Variant.Id, equipSlot, manip.Entry); + identifier = identifier with + { + EquipSlot = equipSlot, + SecondaryId = identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId, + }; } return ret; } - public static bool DrawPrimaryId(ref ImcManipulation manip, float unscaledWidth = 80) + public static bool DrawPrimaryId(ref ImcIdentifier identifier, float unscaledWidth = 80) { - var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, manip.PrimaryId.Id, out var newId, 0, ushort.MaxValue, - manip.PrimaryId.Id <= 1); + var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, identifier.PrimaryId.Id, out var newId, 0, ushort.MaxValue, + identifier.PrimaryId.Id <= 1); ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 + "This should generally not be left <= 1 unless you explicitly want that."u8); if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, newId, manip.SecondaryId, manip.Variant.Id, manip.EquipSlot, - manip.Entry); + identifier = identifier with { PrimaryId = newId }; return ret; } - public static bool DrawSecondaryId(ref ImcManipulation manip, float unscaledWidth = 100) + public static bool DrawSecondaryId(ref ImcIdentifier identifier, float unscaledWidth = 100) { - var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, manip.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); + var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, identifier.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); ImUtf8.HoverTooltip("Secondary ID"u8); if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, newId, manip.Variant.Id, manip.EquipSlot, - manip.Entry); + identifier = identifier with { SecondaryId = newId }; return ret; } - public static bool DrawVariant(ref ImcManipulation manip, float unscaledWidth = 45) + public static bool DrawVariant(ref ImcIdentifier identifier, float unscaledWidth = 45) { - var ret = IdInput("##imcVariant"u8, unscaledWidth, manip.Variant.Id, out var newId, 0, byte.MaxValue, false); + var ret = IdInput("##imcVariant"u8, unscaledWidth, identifier.Variant.Id, out var newId, 0, byte.MaxValue, false); ImUtf8.HoverTooltip("Variant ID"u8); if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, (byte)newId, manip.EquipSlot, - manip.Entry); + identifier = identifier with { Variant = (byte)newId }; return ret; } - public static bool DrawSlot(ref ImcManipulation manip, float unscaledWidth = 100) + public static bool DrawSlot(ref ImcIdentifier identifier, float unscaledWidth = 100) { bool ret; EquipSlot slot; - switch (manip.ObjectType) + switch (identifier.ObjectType) { case ObjectType.Equipment: case ObjectType.DemiHuman: - ret = Combos.EqpEquipSlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + ret = Combos.EqpEquipSlot("##slot", identifier.EquipSlot, out slot, unscaledWidth); break; case ObjectType.Accessory: - ret = Combos.AccessorySlot("##slot", manip.EquipSlot, out slot, unscaledWidth); + ret = Combos.AccessorySlot("##slot", identifier.EquipSlot, out slot, unscaledWidth); break; default: return false; } ImUtf8.HoverTooltip("Equip Slot"u8); if (ret) - manip = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, manip.Variant.Id, slot, - manip.Entry); + identifier = identifier with { EquipSlot = slot }; return ret; } From bad1f45ab91f54576da1041577eaeca83cb653ef Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 24 May 2024 17:34:56 +0200 Subject: [PATCH 0613/1381] Use different hooking method for EQP entries. --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 34 ++++++++++++++++++ Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs | 5 +-- .../Interop/Hooks/Meta/GetEqpIndirect2.cs | 36 +++++++++++++++++++ .../Interop/Hooks/Meta/ModelLoadComplete.cs | 4 ++- Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 6 ++-- Penumbra/Interop/PathResolving/MetaState.cs | 1 + 7 files changed, 82 insertions(+), 6 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Meta/EqpHook.cs create mode 100644 Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index ec35e664..539d1387 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ec35e66499eb388b4e7917e4fae4615218d33335 +Subproject commit 539d138700543e7c2c6c918f9f68e33228111e4d diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs new file mode 100644 index 00000000..457b9428 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -0,0 +1,34 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class EqpHook : FastHook +{ + public delegate void Delegate(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor); + + private readonly MetaState _metaState; + + public EqpHook(HookManager hooks, MetaState metaState) + { + _metaState = metaState; + Task = hooks.CreateHook("GetEqpFlags", "E8 ?? ?? ?? ?? 0F B6 44 24 ?? C0 E8", Detour, true); + } + + private void Detour(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor) + { + if (_metaState.EqpCollection.Valid) + { + using var eqp = _metaState.ResolveEqpData(_metaState.EqpCollection.ModCollection); + Task.Result.Original(utility, flags, armor); + } + else + { + Task.Result.Original(utility, flags, armor); + } + + Penumbra.Log.Excessive($"[GetEqpFlags] Invoked on 0x{(nint)utility:X} with 0x{(ulong)armor:X}, returned 0x{(ulong)*flags:X16}."); + } +} diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs index 8ffc050f..beae6acc 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.Collections; using Penumbra.GameData; using Penumbra.Interop.PathResolving; @@ -28,8 +29,8 @@ public sealed unsafe class GetEqpIndirect : FastHook return; Penumbra.Log.Excessive($"[Get EQP Indirect] Invoked on {(nint)drawObject:X}."); - var collection = _collectionResolver.IdentifyCollection(drawObject, true); - using var eqp = _metaState.ResolveEqpData(collection.ModCollection); + _metaState.EqpCollection = _collectionResolver.IdentifyCollection(drawObject, true); Task.Result.Original(drawObject); + _metaState.EqpCollection = ResolveData.Invalid; } } diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs new file mode 100644 index 00000000..89aaa9b0 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs @@ -0,0 +1,36 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class GetEqpIndirect2 : FastHook +{ + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public GetEqpIndirect2(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + { + _collectionResolver = collectionResolver; + _metaState = metaState; + Task = hooks.CreateHook("Get EQP Indirect 2", Sigs.GetEqpIndirect2, Detour, true); + } + + public delegate void Delegate(DrawObject* drawObject); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void Detour(DrawObject* drawObject) + { + // Shortcut because this is also called all the time. + // Same thing is checked at the beginning of the original function. + if (((*(uint*)((nint)drawObject + Offsets.GetEqpIndirect2Skip) >> 0x12) & 1) == 0) + return; + + Penumbra.Log.Excessive($"[Get EQP Indirect 2] Invoked on {(nint)drawObject:X}."); + _metaState.EqpCollection = _collectionResolver.IdentifyCollection(drawObject, true); + Task.Result.Original(drawObject); + _metaState.EqpCollection = ResolveData.Invalid; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs index 9f191fdd..10c12594 100644 --- a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.Collections; using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Meta; @@ -23,8 +24,9 @@ public sealed unsafe class ModelLoadComplete : FastHook Penumbra.Log.Excessive($"[Update Model] Invoked on {(nint)drawObject:X}."); var collection = _collectionResolver.IdentifyCollection(drawObject, true); - using var eqp = _metaState.ResolveEqpData(collection.ModCollection); using var eqdp = _metaState.ResolveEqdpData(collection.ModCollection, MetaState.GetDrawObjectGenderRace((nint)drawObject), true, true); - Task.Result.Original.Invoke(drawObject); + _metaState.EqpCollection = collection; + Task.Result.Original(drawObject); + _metaState.EqpCollection = ResolveData.Invalid; } } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 5f07ffc5..6fa5c263 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -46,6 +46,7 @@ public sealed unsafe class MetaState : IDisposable private readonly CreateCharacterBase _createCharacterBase; public ResolveData CustomizeChangeCollection = ResolveData.Invalid; + public ResolveData EqpCollection = ResolveData.Invalid; private ResolveData _lastCreatedCollection = ResolveData.Invalid; private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; From e32e314863e46fb4b806bc9b2c3adf86a5ec2d0e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 24 May 2024 17:51:47 +0200 Subject: [PATCH 0614/1381] Add initial changelog for next release. --- Penumbra/UI/Changelog.cs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 8b00ab8d..add16f94 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -48,10 +48,34 @@ public class PenumbraChangelog Add8_3_0(Changelog); Add1_0_0_0(Changelog); Add1_0_2_0(Changelog); + Add1_0_3_0(Changelog); } #region Changelogs + private static void Add1_0_3_0(Changelog log) + => log.NextVersion("Version 1.0.3.0") + .RegisterHighlight("Collections now have associated GUIDs as identifiers instead of their names, so they can now be renamed.") + .RegisterEntry("Migrating those collections may introduce issues, please let me know as soon as possible if you encounter any.", 1) + .RegisterEntry("A permanent (non-rolling) backup should be created before the migration in case of any issues.", 1) + .RegisterHighlight("A total rework of how options and groups are handled internally, and introduction of the first new group type, the IMC Group.") + .RegisterEntry("Mod Creators can add a IMC Group to their mod that controls a single IMC Manipulation, so they can provide options for the separate attributes for it.", 1) + .RegisterEntry("This makes it a lot easier to have combined options: No need for 'A', 'B' and 'AB', you can just define 'A' and 'B' and skip their combinations", 1) + .RegisterHighlight("Added a field to rename mods directly from the mod selector context menu, instead of moving them in the filesystem.") + .RegisterEntry("You can choose which rename field (none, either one or both) to display in the settings.", 1) + .RegisterEntry("You can now paste your current clipboard text into the mod selector filter with a simple right-click as long as it is not focused.") + .RegisterHighlight("Added the option to display VFX for accessories if added via IMC edits, which the game does not do inherently (by Ocealot).") + .RegisterEntry("Added support for reading and writing the new material and model file formats from the benchmark.") + .RegisterEntry("Added the option to hide Machinist Offhands from the Changed Items tabs (because any change to it changes ALL of them), which is on by default.") + .RegisterEntry("Removed the auto-generated descriptions for newly created groups in Penumbra.") + .RegisterEntry("Made some improvements to the Advanced Editing window, for example a much better and more performant Hex Viewer for unstructured data was added.") + .RegisterEntry("Made a lot of further improvements on Model import/export (by ackwell).") + .RegisterEntry("Reworked the API and IPC structure heavily.") + .RegisterEntry("Worked around the UI IPC possibly displacing all settings when the drawn additions became too big.") + .RegisterEntry("Fixed an issue with merging and deduplicating mods.") + .RegisterEntry("Fixed a crash when scanning for mods without access rights to the folder.") + .RegisterEntry("Made plugin conform to Dalamud requirements by adding a punchline and another button to open the menu from the installer."); + private static void Add1_0_2_0(Changelog log) => log.NextVersion("Version 1.0.2.0") .RegisterEntry("Updated to .net8 and XIV 6.58, using some new framework facilities to improve performance and stability.") From f9527970cb610f8d8529478e9674d1bd32548bf9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 25 May 2024 00:43:02 +0200 Subject: [PATCH 0615/1381] Fix missing ID push for imc attributes. --- Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 045149c9..b10f123c 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -76,8 +76,11 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr using (ImUtf8.Group()) { DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, group.DefaultEntry.AttributeMask, group); - foreach (var option in group.OptionData.Where(o => !o.IsDisableSubMod)) + foreach (var (option, idx) in group.OptionData.WithIndex().Where(o => !o.Value.IsDisableSubMod)) + { + using var id = ImUtf8.PushId(idx); DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); + } } } From ed083f2a4ca375bf50eede01d72796408c320d7c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 26 May 2024 13:30:35 +0200 Subject: [PATCH 0616/1381] Add support for Global EQP Changes. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/CollectionCache.cs | 1 - Penumbra/Collections/Cache/MetaCache.cs | 48 ++++-- .../Collections/ModCollection.Cache.Access.cs | 4 + Penumbra/Import/TexToolsMeta.Export.cs | 3 + Penumbra/Import/TexToolsMeta.cs | 2 +- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 1 + Penumbra/Meta/Manipulations/GlobalEqpCache.cs | 80 +++++++++ .../Manipulations/GlobalEqpManipulation.cs | 50 ++++++ Penumbra/Meta/Manipulations/GlobalEqpType.cs | 61 +++++++ .../Meta/Manipulations/MetaManipulation.cs | 156 ++++++++++-------- Penumbra/Mods/Editor/ModMetaEditor.cs | 97 ++++++----- Penumbra/Mods/SubMods/IModDataContainer.cs | 13 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 66 ++++++++ Penumbra/Util/IdentifierExtensions.cs | 20 +++ 15 files changed, 471 insertions(+), 133 deletions(-) create mode 100644 Penumbra/Meta/Manipulations/GlobalEqpCache.cs create mode 100644 Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs create mode 100644 Penumbra/Meta/Manipulations/GlobalEqpType.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 539d1387..07cc26f1 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 539d138700543e7c2c6c918f9f68e33228111e4d +Subproject commit 07cc26f196984a44711b3bc4c412947d863288bd diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index e2f20b46..4d8d0b4a 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -5,7 +5,6 @@ using Penumbra.Mods; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.String.Classes; -using Penumbra.Mods.Manager; using Penumbra.Util; namespace Penumbra.Collections.Cache; diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 4c147c3c..f42b72fc 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -4,7 +4,6 @@ using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Manipulations; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.String.Classes; @@ -14,13 +13,14 @@ public class MetaCache : IDisposable, IEnumerable _manipulations = new(); - private EqpCache _eqpCache = new(); - private readonly EqdpCache _eqdpCache = new(); - private EstCache _estCache = new(); - private GmpCache _gmpCache = new(); - private CmpCache _cmpCache = new(); - private readonly ImcCache _imcCache = new(); + private readonly Dictionary _manipulations = new(); + private EqpCache _eqpCache = new(); + private readonly EqdpCache _eqdpCache = new(); + private EstCache _estCache = new(); + private GmpCache _gmpCache = new(); + private CmpCache _cmpCache = new(); + private readonly ImcCache _imcCache = new(); + private GlobalEqpCache _globalEqpCache = new(); public bool TryGetValue(MetaManipulation manip, [NotNullWhen(true)] out IMod? mod) { @@ -69,6 +69,7 @@ public class MetaCache : IDisposable, IEnumerable _estCache.TemporarilySetFiles(_manager, type); + public unsafe EqpEntry ApplyGlobalEqp(EqpEntry baseEntry, CharacterArmor* armor) + => _globalEqpCache.Apply(baseEntry, armor); + /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) @@ -193,8 +204,8 @@ public class MetaCache : IDisposable, IEnumerable _eqpCache.ApplyMod(_manager, manip.Eqp), - MetaManipulation.Type.Eqdp => _eqdpCache.ApplyMod(_manager, manip.Eqdp), - MetaManipulation.Type.Est => _estCache.ApplyMod(_manager, manip.Est), - MetaManipulation.Type.Gmp => _gmpCache.ApplyMod(_manager, manip.Gmp), - MetaManipulation.Type.Rsp => _cmpCache.ApplyMod(_manager, manip.Rsp), - MetaManipulation.Type.Imc => _imcCache.ApplyMod(_manager, _collection, manip.Imc), - MetaManipulation.Type.Unknown => false, - _ => false, + MetaManipulation.Type.Eqp => _eqpCache.ApplyMod(_manager, manip.Eqp), + MetaManipulation.Type.Eqdp => _eqdpCache.ApplyMod(_manager, manip.Eqdp), + MetaManipulation.Type.Est => _estCache.ApplyMod(_manager, manip.Est), + MetaManipulation.Type.Gmp => _gmpCache.ApplyMod(_manager, manip.Gmp), + MetaManipulation.Type.Rsp => _cmpCache.ApplyMod(_manager, manip.Rsp), + MetaManipulation.Type.Imc => _imcCache.ApplyMod(_manager, _collection, manip.Imc), + MetaManipulation.Type.GlobalEqp => false, + MetaManipulation.Type.Unknown => false, + _ => false, } ? 1 : 0; diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index b073e731..3f3733e0 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -8,6 +8,7 @@ using Penumbra.String.Classes; using Penumbra.Collections.Cache; using Penumbra.Interop.Services; using Penumbra.Mods.Editor; +using Penumbra.GameData.Structs; namespace Penumbra.Collections; @@ -114,4 +115,7 @@ public partial class ModCollection public MetaList.MetaReverter TemporarilySetEstFile(CharacterUtility utility, EstManipulation.EstType type) => _cache?.Meta.TemporarilySetEstFile(type) ?? utility.TemporarilyResetResource((MetaIndex)type); + + public unsafe EqpEntry ApplyGlobalEqp(EqpEntry baseEntry, CharacterArmor* armor) + => _cache?.Meta.ApplyGlobalEqp(baseEntry, armor) ?? baseEntry; } diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 90ffaf60..03bdbd90 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -187,6 +187,9 @@ public partial class TexToolsMeta b.Write(manip.Gmp.Entry.UnknownTotal); } + break; + case MetaManipulation.Type.GlobalEqp: + // Not Supported break; } diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index 83b430fb..25e00bd7 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -44,7 +44,7 @@ public partial class TexToolsMeta var headerStart = reader.ReadUInt32(); reader.BaseStream.Seek(headerStart, SeekOrigin.Begin); - List<(MetaManipulation.Type type, uint offset, int size)> entries = new(); + List<(MetaManipulation.Type type, uint offset, int size)> entries = []; for (var i = 0; i < numHeaders; ++i) { var currentOffset = reader.BaseStream.Position; diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index 457b9428..6663c211 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -23,6 +23,7 @@ public unsafe class EqpHook : FastHook { using var eqp = _metaState.ResolveEqpData(_metaState.EqpCollection.ModCollection); Task.Result.Original(utility, flags, armor); + *flags = _metaState.EqpCollection.ModCollection.ApplyGlobalEqp(*flags, armor); } else { diff --git a/Penumbra/Meta/Manipulations/GlobalEqpCache.cs b/Penumbra/Meta/Manipulations/GlobalEqpCache.cs new file mode 100644 index 00000000..48ffb308 --- /dev/null +++ b/Penumbra/Meta/Manipulations/GlobalEqpCache.cs @@ -0,0 +1,80 @@ +using OtterGui.Services; +using Penumbra.GameData.Structs; + +namespace Penumbra.Meta.Manipulations; + +public struct GlobalEqpCache : IService +{ + private readonly HashSet _doNotHideEarrings = []; + private readonly HashSet _doNotHideNecklace = []; + private readonly HashSet _doNotHideBracelets = []; + private readonly HashSet _doNotHideRingL = []; + private readonly HashSet _doNotHideRingR = []; + private bool _doNotHideVieraHats; + private bool _doNotHideHrothgarHats; + + public GlobalEqpCache() + { } + + public void Clear() + { + _doNotHideEarrings.Clear(); + _doNotHideNecklace.Clear(); + _doNotHideBracelets.Clear(); + _doNotHideRingL.Clear(); + _doNotHideRingR.Clear(); + _doNotHideHrothgarHats = false; + _doNotHideVieraHats = false; + } + + public unsafe EqpEntry Apply(EqpEntry original, CharacterArmor* armor) + { + if (_doNotHideVieraHats) + original |= EqpEntry.HeadShowVieraHat; + + if (_doNotHideHrothgarHats) + original |= EqpEntry.HeadShowHrothgarHat; + + if (_doNotHideEarrings.Contains(armor[5].Set)) + original |= EqpEntry.HeadShowEarrings | EqpEntry.HeadShowEarringsAura | EqpEntry.HeadShowEarringsHuman; + + if (_doNotHideNecklace.Contains(armor[6].Set)) + original |= EqpEntry.BodyShowNecklace | EqpEntry.HeadShowNecklace; + + if (_doNotHideBracelets.Contains(armor[7].Set)) + original |= EqpEntry.BodyShowBracelet | EqpEntry.HandShowBracelet; + + if (_doNotHideBracelets.Contains(armor[8].Set)) + original |= EqpEntry.HandShowRingR; + + if (_doNotHideBracelets.Contains(armor[9].Set)) + original |= EqpEntry.HandShowRingL; + return original; + } + + public bool Add(GlobalEqpManipulation manipulation) + => manipulation.Type switch + { + GlobalEqpType.DoNotHideEarrings => _doNotHideEarrings.Add(manipulation.Condition), + GlobalEqpType.DoNotHideNecklace => _doNotHideNecklace.Add(manipulation.Condition), + GlobalEqpType.DoNotHideBracelets => _doNotHideBracelets.Add(manipulation.Condition), + GlobalEqpType.DoNotHideRingR => _doNotHideRingR.Add(manipulation.Condition), + GlobalEqpType.DoNotHideRingL => _doNotHideRingL.Add(manipulation.Condition), + GlobalEqpType.DoNotHideHrothgarHats => !_doNotHideHrothgarHats && (_doNotHideHrothgarHats = true), + GlobalEqpType.DoNotHideVieraHats => !_doNotHideVieraHats && (_doNotHideVieraHats = true), + _ => false, + }; + + public bool Remove(GlobalEqpManipulation manipulation) + => manipulation.Type switch + { + GlobalEqpType.DoNotHideEarrings => _doNotHideEarrings.Remove(manipulation.Condition), + GlobalEqpType.DoNotHideNecklace => _doNotHideNecklace.Remove(manipulation.Condition), + GlobalEqpType.DoNotHideBracelets => _doNotHideBracelets.Remove(manipulation.Condition), + GlobalEqpType.DoNotHideRingR => _doNotHideRingR.Remove(manipulation.Condition), + GlobalEqpType.DoNotHideRingL => _doNotHideRingL.Remove(manipulation.Condition), + GlobalEqpType.DoNotHideHrothgarHats => _doNotHideHrothgarHats && !(_doNotHideHrothgarHats = false), + GlobalEqpType.DoNotHideVieraHats => _doNotHideVieraHats && !(_doNotHideVieraHats = false), + _ => false, + }; +} diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs new file mode 100644 index 00000000..ada543dc --- /dev/null +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -0,0 +1,50 @@ +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly struct GlobalEqpManipulation : IMetaManipulation +{ + public GlobalEqpType Type { get; init; } + public PrimaryId Condition { get; init; } + + public bool Validate() + { + if (!Enum.IsDefined(Type)) + return false; + + if (Type is GlobalEqpType.DoNotHideVieraHats or GlobalEqpType.DoNotHideHrothgarHats) + return Condition == 0; + + return Condition != 0; + } + + + public bool Equals(GlobalEqpManipulation other) + => Type == other.Type + && Condition.Equals(other.Condition); + + public int CompareTo(GlobalEqpManipulation other) + { + var typeComp = Type.CompareTo(other); + return typeComp != 0 ? typeComp : Condition.Id.CompareTo(other.Condition.Id); + } + + public override bool Equals(object? obj) + => obj is GlobalEqpManipulation other && Equals(other); + + public override int GetHashCode() + => HashCode.Combine((int)Type, Condition); + + public static bool operator ==(GlobalEqpManipulation left, GlobalEqpManipulation right) + => left.Equals(right); + + public static bool operator !=(GlobalEqpManipulation left, GlobalEqpManipulation right) + => !left.Equals(right); + + public override string ToString() + => $"Global EQP - {Type}{(Condition != 0 ? $" - {Condition.Id}" : string.Empty)}"; + + public MetaIndex FileIndex() + => (MetaIndex)(-1); +} diff --git a/Penumbra/Meta/Manipulations/GlobalEqpType.cs b/Penumbra/Meta/Manipulations/GlobalEqpType.cs new file mode 100644 index 00000000..57d99d56 --- /dev/null +++ b/Penumbra/Meta/Manipulations/GlobalEqpType.cs @@ -0,0 +1,61 @@ +namespace Penumbra.Meta.Manipulations; + +public enum GlobalEqpType +{ + DoNotHideEarrings, + DoNotHideNecklace, + DoNotHideBracelets, + DoNotHideRingR, + DoNotHideRingL, + DoNotHideHrothgarHats, + DoNotHideVieraHats, +} + +public static class GlobalEqpExtensions +{ + public static bool HasCondition(this GlobalEqpType type) + => type switch + { + GlobalEqpType.DoNotHideEarrings => true, + GlobalEqpType.DoNotHideNecklace => true, + GlobalEqpType.DoNotHideBracelets => true, + GlobalEqpType.DoNotHideRingR => true, + GlobalEqpType.DoNotHideRingL => true, + GlobalEqpType.DoNotHideHrothgarHats => false, + GlobalEqpType.DoNotHideVieraHats => false, + _ => false, + }; + + + public static ReadOnlySpan ToName(this GlobalEqpType type) + => type switch + { + GlobalEqpType.DoNotHideEarrings => "Do Not Hide Earrings"u8, + GlobalEqpType.DoNotHideNecklace => "Do Not Hide Necklaces"u8, + GlobalEqpType.DoNotHideBracelets => "Do Not Hide Bracelets"u8, + GlobalEqpType.DoNotHideRingR => "Do Not Hide Rings (Right Finger)"u8, + GlobalEqpType.DoNotHideRingL => "Do Not Hide Rings (Left Finger)"u8, + GlobalEqpType.DoNotHideHrothgarHats => "Do Not Hide Hats for Hrothgar"u8, + GlobalEqpType.DoNotHideVieraHats => "Do Not Hide Hats for Viera"u8, + _ => "\0"u8, + }; + + public static ReadOnlySpan ToDescription(this GlobalEqpType type) + => type switch + { + GlobalEqpType.DoNotHideEarrings => "Prevents the game from hiding earrings through other models when a specific earring is worn."u8, + GlobalEqpType.DoNotHideNecklace => + "Prevents the game from hiding necklaces through other models when a specific necklace is worn."u8, + GlobalEqpType.DoNotHideBracelets => + "Prevents the game from hiding bracelets through other models when a specific bracelet is worn."u8, + GlobalEqpType.DoNotHideRingR => + "Prevents the game from hiding rings worn on the right finger through other models when a specific ring is worn on the right finger."u8, + GlobalEqpType.DoNotHideRingL => + "Prevents the game from hiding rings worn on the left finger through other models when a specific ring is worn on the left finger."u8, + GlobalEqpType.DoNotHideHrothgarHats => + "Prevents the game from hiding any hats for Hrothgar that are normally flagged to not display on them."u8, + GlobalEqpType.DoNotHideVieraHats => + "Prevents the game from hiding any hats for Viera that are normally flagged to not display on them."u8, + _ => "\0"u8, + }; +} diff --git a/Penumbra/Meta/Manipulations/MetaManipulation.cs b/Penumbra/Meta/Manipulations/MetaManipulation.cs index ed184d52..f22de809 100644 --- a/Penumbra/Meta/Manipulations/MetaManipulation.cs +++ b/Penumbra/Meta/Manipulations/MetaManipulation.cs @@ -21,13 +21,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara public enum Type : byte { - Unknown = 0, - Imc = 1, - Eqdp = 2, - Eqp = 3, - Est = 4, - Gmp = 5, - Rsp = 6, + Unknown = 0, + Imc = 1, + Eqdp = 2, + Eqp = 3, + Est = 4, + Gmp = 5, + Rsp = 6, + GlobalEqp = 7, } [FieldOffset(0)] @@ -54,6 +55,10 @@ public readonly struct MetaManipulation : IEquatable, ICompara [JsonIgnore] public readonly ImcManipulation Imc = default; + [FieldOffset(0)] + [JsonIgnore] + public readonly GlobalEqpManipulation GlobalEqp = default; + [FieldOffset(15)] [JsonConverter(typeof(StringEnumConverter))] [JsonProperty("Type")] @@ -63,14 +68,15 @@ public readonly struct MetaManipulation : IEquatable, ICompara { get => ManipulationType switch { - Type.Unknown => null, - Type.Imc => Imc, - Type.Eqdp => Eqdp, - Type.Eqp => Eqp, - Type.Est => Est, - Type.Gmp => Gmp, - Type.Rsp => Rsp, - _ => null, + Type.Unknown => null, + Type.Imc => Imc, + Type.Eqdp => Eqdp, + Type.Eqp => Eqp, + Type.Est => Est, + Type.Gmp => Gmp, + Type.Rsp => Rsp, + Type.GlobalEqp => GlobalEqp, + _ => null, }; init { @@ -100,6 +106,10 @@ public readonly struct MetaManipulation : IEquatable, ICompara Imc = m; ManipulationType = m.Validate(true) ? Type.Imc : Type.Unknown; return; + case GlobalEqpManipulation m: + GlobalEqp = m; + ManipulationType = m.Validate() ? Type.GlobalEqp : Type.Unknown; + return; } } } @@ -108,13 +118,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara { return ManipulationType switch { - Type.Imc => Imc.Validate(true), - Type.Eqdp => Eqdp.Validate(), - Type.Eqp => Eqp.Validate(), - Type.Est => Est.Validate(), - Type.Gmp => Gmp.Validate(), - Type.Rsp => Rsp.Validate(), - _ => false, + Type.Imc => Imc.Validate(true), + Type.Eqdp => Eqdp.Validate(), + Type.Eqp => Eqp.Validate(), + Type.Est => Est.Validate(), + Type.Gmp => Gmp.Validate(), + Type.Rsp => Rsp.Validate(), + Type.GlobalEqp => GlobalEqp.Validate(), + _ => false, }; } @@ -154,6 +165,12 @@ public readonly struct MetaManipulation : IEquatable, ICompara ManipulationType = Type.Imc; } + public MetaManipulation(GlobalEqpManipulation eqp) + { + GlobalEqp = eqp; + ManipulationType = Type.GlobalEqp; + } + public static implicit operator MetaManipulation(EqpManipulation eqp) => new(eqp); @@ -172,6 +189,9 @@ public readonly struct MetaManipulation : IEquatable, ICompara public static implicit operator MetaManipulation(ImcManipulation imc) => new(imc); + public static implicit operator MetaManipulation(GlobalEqpManipulation eqp) + => new(eqp); + public bool EntryEquals(MetaManipulation other) { if (ManipulationType != other.ManipulationType) @@ -179,13 +199,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara return ManipulationType switch { - Type.Eqp => Eqp.Entry.Equals(other.Eqp.Entry), - Type.Gmp => Gmp.Entry.Equals(other.Gmp.Entry), - Type.Eqdp => Eqdp.Entry.Equals(other.Eqdp.Entry), - Type.Est => Est.Entry.Equals(other.Est.Entry), - Type.Rsp => Rsp.Entry.Equals(other.Rsp.Entry), - Type.Imc => Imc.Entry.Equals(other.Imc.Entry), - _ => throw new ArgumentOutOfRangeException(), + Type.Eqp => Eqp.Entry.Equals(other.Eqp.Entry), + Type.Gmp => Gmp.Entry.Equals(other.Gmp.Entry), + Type.Eqdp => Eqdp.Entry.Equals(other.Eqdp.Entry), + Type.Est => Est.Entry.Equals(other.Est.Entry), + Type.Rsp => Rsp.Entry.Equals(other.Rsp.Entry), + Type.Imc => Imc.Entry.Equals(other.Imc.Entry), + Type.GlobalEqp => true, + _ => throw new ArgumentOutOfRangeException(), }; } @@ -196,13 +217,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara return ManipulationType switch { - Type.Eqp => Eqp.Equals(other.Eqp), - Type.Gmp => Gmp.Equals(other.Gmp), - Type.Eqdp => Eqdp.Equals(other.Eqdp), - Type.Est => Est.Equals(other.Est), - Type.Rsp => Rsp.Equals(other.Rsp), - Type.Imc => Imc.Equals(other.Imc), - _ => false, + Type.Eqp => Eqp.Equals(other.Eqp), + Type.Gmp => Gmp.Equals(other.Gmp), + Type.Eqdp => Eqdp.Equals(other.Eqdp), + Type.Est => Est.Equals(other.Est), + Type.Rsp => Rsp.Equals(other.Rsp), + Type.Imc => Imc.Equals(other.Imc), + Type.GlobalEqp => GlobalEqp.Equals(other.GlobalEqp), + _ => false, }; } @@ -213,13 +235,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara return ManipulationType switch { - Type.Eqp => Eqp.Copy(other.Eqp.Entry), - Type.Gmp => Gmp.Copy(other.Gmp.Entry), - Type.Eqdp => Eqdp.Copy(other.Eqdp), - Type.Est => Est.Copy(other.Est.Entry), - Type.Rsp => Rsp.Copy(other.Rsp.Entry), - Type.Imc => Imc.Copy(other.Imc.Entry), - _ => throw new ArgumentOutOfRangeException(), + Type.Eqp => Eqp.Copy(other.Eqp.Entry), + Type.Gmp => Gmp.Copy(other.Gmp.Entry), + Type.Eqdp => Eqdp.Copy(other.Eqdp), + Type.Est => Est.Copy(other.Est.Entry), + Type.Rsp => Rsp.Copy(other.Rsp.Entry), + Type.Imc => Imc.Copy(other.Imc.Entry), + Type.GlobalEqp => GlobalEqp, + _ => throw new ArgumentOutOfRangeException(), }; } @@ -229,13 +252,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara public override int GetHashCode() => ManipulationType switch { - Type.Eqp => Eqp.GetHashCode(), - Type.Gmp => Gmp.GetHashCode(), - Type.Eqdp => Eqdp.GetHashCode(), - Type.Est => Est.GetHashCode(), - Type.Rsp => Rsp.GetHashCode(), - Type.Imc => Imc.GetHashCode(), - _ => 0, + Type.Eqp => Eqp.GetHashCode(), + Type.Gmp => Gmp.GetHashCode(), + Type.Eqdp => Eqdp.GetHashCode(), + Type.Est => Est.GetHashCode(), + Type.Rsp => Rsp.GetHashCode(), + Type.Imc => Imc.GetHashCode(), + Type.GlobalEqp => GlobalEqp.GetHashCode(), + _ => 0, }; public unsafe int CompareTo(MetaManipulation other) @@ -249,13 +273,14 @@ public readonly struct MetaManipulation : IEquatable, ICompara public override string ToString() => ManipulationType switch { - Type.Eqp => Eqp.ToString(), - Type.Gmp => Gmp.ToString(), - Type.Eqdp => Eqdp.ToString(), - Type.Est => Est.ToString(), - Type.Rsp => Rsp.ToString(), - Type.Imc => Imc.ToString(), - _ => "Invalid", + Type.Eqp => Eqp.ToString(), + Type.Gmp => Gmp.ToString(), + Type.Eqdp => Eqdp.ToString(), + Type.Est => Est.ToString(), + Type.Rsp => Rsp.ToString(), + Type.Imc => Imc.ToString(), + Type.GlobalEqp => GlobalEqp.ToString(), + _ => "Invalid", }; public string EntryToString() @@ -263,14 +288,15 @@ public readonly struct MetaManipulation : IEquatable, ICompara { Type.Imc => $"{Imc.Entry.DecalId}-{Imc.Entry.MaterialId}-{Imc.Entry.VfxId}-{Imc.Entry.SoundId}-{Imc.Entry.MaterialAnimationId}-{Imc.Entry.AttributeMask}", - Type.Eqdp => $"{(ushort)Eqdp.Entry:X}", - Type.Eqp => $"{(ulong)Eqp.Entry:X}", - Type.Est => $"{Est.Entry}", - Type.Gmp => $"{Gmp.Entry.Value}", - Type.Rsp => $"{Rsp.Entry}", - _ => string.Empty, - }; - + Type.Eqdp => $"{(ushort)Eqdp.Entry:X}", + Type.Eqp => $"{(ulong)Eqp.Entry:X}", + Type.Est => $"{Est.Entry}", + Type.Gmp => $"{Gmp.Entry.Value}", + Type.Rsp => $"{Rsp.Entry}", + Type.GlobalEqp => string.Empty, + _ => string.Empty, + }; + public static bool operator ==(MetaManipulation left, MetaManipulation right) => left.Equals(right); diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 2f7fd04c..829161f5 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -6,19 +6,21 @@ namespace Penumbra.Mods.Editor; public class ModMetaEditor(ModManager modManager) { - private readonly HashSet _imc = []; - private readonly HashSet _eqp = []; - private readonly HashSet _eqdp = []; - private readonly HashSet _gmp = []; - private readonly HashSet _est = []; - private readonly HashSet _rsp = []; + private readonly HashSet _imc = []; + private readonly HashSet _eqp = []; + private readonly HashSet _eqdp = []; + private readonly HashSet _gmp = []; + private readonly HashSet _est = []; + private readonly HashSet _rsp = []; + private readonly HashSet _globalEqp = []; - public int OtherImcCount { get; private set; } - public int OtherEqpCount { get; private set; } - public int OtherEqdpCount { get; private set; } - public int OtherGmpCount { get; private set; } - public int OtherEstCount { get; private set; } - public int OtherRspCount { get; private set; } + public int OtherImcCount { get; private set; } + public int OtherEqpCount { get; private set; } + public int OtherEqdpCount { get; private set; } + public int OtherGmpCount { get; private set; } + public int OtherEstCount { get; private set; } + public int OtherRspCount { get; private set; } + public int OtherGlobalEqpCount { get; private set; } public bool Changes { get; private set; } @@ -40,17 +42,21 @@ public class ModMetaEditor(ModManager modManager) public IReadOnlySet Rsp => _rsp; + public IReadOnlySet GlobalEqp + => _globalEqp; + public bool CanAdd(MetaManipulation m) { return m.ManipulationType switch { - MetaManipulation.Type.Imc => !_imc.Contains(m.Imc), - MetaManipulation.Type.Eqdp => !_eqdp.Contains(m.Eqdp), - MetaManipulation.Type.Eqp => !_eqp.Contains(m.Eqp), - MetaManipulation.Type.Est => !_est.Contains(m.Est), - MetaManipulation.Type.Gmp => !_gmp.Contains(m.Gmp), - MetaManipulation.Type.Rsp => !_rsp.Contains(m.Rsp), - _ => false, + MetaManipulation.Type.Imc => !_imc.Contains(m.Imc), + MetaManipulation.Type.Eqdp => !_eqdp.Contains(m.Eqdp), + MetaManipulation.Type.Eqp => !_eqp.Contains(m.Eqp), + MetaManipulation.Type.Est => !_est.Contains(m.Est), + MetaManipulation.Type.Gmp => !_gmp.Contains(m.Gmp), + MetaManipulation.Type.Rsp => !_rsp.Contains(m.Rsp), + MetaManipulation.Type.GlobalEqp => !_globalEqp.Contains(m.GlobalEqp), + _ => false, }; } @@ -58,13 +64,14 @@ public class ModMetaEditor(ModManager modManager) { var added = m.ManipulationType switch { - MetaManipulation.Type.Imc => _imc.Add(m.Imc), - MetaManipulation.Type.Eqdp => _eqdp.Add(m.Eqdp), - MetaManipulation.Type.Eqp => _eqp.Add(m.Eqp), - MetaManipulation.Type.Est => _est.Add(m.Est), - MetaManipulation.Type.Gmp => _gmp.Add(m.Gmp), - MetaManipulation.Type.Rsp => _rsp.Add(m.Rsp), - _ => false, + MetaManipulation.Type.Imc => _imc.Add(m.Imc), + MetaManipulation.Type.Eqdp => _eqdp.Add(m.Eqdp), + MetaManipulation.Type.Eqp => _eqp.Add(m.Eqp), + MetaManipulation.Type.Est => _est.Add(m.Est), + MetaManipulation.Type.Gmp => _gmp.Add(m.Gmp), + MetaManipulation.Type.Rsp => _rsp.Add(m.Rsp), + MetaManipulation.Type.GlobalEqp => _globalEqp.Add(m.GlobalEqp), + _ => false, }; Changes |= added; return added; @@ -74,13 +81,14 @@ public class ModMetaEditor(ModManager modManager) { var deleted = m.ManipulationType switch { - MetaManipulation.Type.Imc => _imc.Remove(m.Imc), - MetaManipulation.Type.Eqdp => _eqdp.Remove(m.Eqdp), - MetaManipulation.Type.Eqp => _eqp.Remove(m.Eqp), - MetaManipulation.Type.Est => _est.Remove(m.Est), - MetaManipulation.Type.Gmp => _gmp.Remove(m.Gmp), - MetaManipulation.Type.Rsp => _rsp.Remove(m.Rsp), - _ => false, + MetaManipulation.Type.Imc => _imc.Remove(m.Imc), + MetaManipulation.Type.Eqdp => _eqdp.Remove(m.Eqdp), + MetaManipulation.Type.Eqp => _eqp.Remove(m.Eqp), + MetaManipulation.Type.Est => _est.Remove(m.Est), + MetaManipulation.Type.Gmp => _gmp.Remove(m.Gmp), + MetaManipulation.Type.Rsp => _rsp.Remove(m.Rsp), + MetaManipulation.Type.GlobalEqp => _globalEqp.Remove(m.GlobalEqp), + _ => false, }; Changes |= deleted; return deleted; @@ -100,17 +108,19 @@ public class ModMetaEditor(ModManager modManager) _gmp.Clear(); _est.Clear(); _rsp.Clear(); + _globalEqp.Clear(); Changes = true; } public void Load(Mod mod, IModDataContainer currentOption) { - OtherImcCount = 0; - OtherEqpCount = 0; - OtherEqdpCount = 0; - OtherGmpCount = 0; - OtherEstCount = 0; - OtherRspCount = 0; + OtherImcCount = 0; + OtherEqpCount = 0; + OtherEqdpCount = 0; + OtherGmpCount = 0; + OtherEstCount = 0; + OtherRspCount = 0; + OtherGlobalEqpCount = 0; foreach (var option in mod.AllDataContainers) { if (option == currentOption) @@ -138,6 +148,9 @@ public class ModMetaEditor(ModManager modManager) case MetaManipulation.Type.Rsp: ++OtherRspCount; break; + case MetaManipulation.Type.GlobalEqp: + ++OtherGlobalEqpCount; + break; } } } @@ -179,6 +192,9 @@ public class ModMetaEditor(ModManager modManager) case MetaManipulation.Type.Rsp: _rsp.Add(manip.Rsp); break; + case MetaManipulation.Type.GlobalEqp: + _globalEqp.Add(manip.GlobalEqp); + break; } } @@ -191,5 +207,6 @@ public class ModMetaEditor(ModManager modManager) .Concat(_eqp.Select(m => (MetaManipulation)m)) .Concat(_est.Select(m => (MetaManipulation)m)) .Concat(_gmp.Select(m => (MetaManipulation)m)) - .Concat(_rsp.Select(m => (MetaManipulation)m)); + .Concat(_rsp.Select(m => (MetaManipulation)m)) + .Concat(_globalEqp.Select(m => (MetaManipulation)m)); } diff --git a/Penumbra/Mods/SubMods/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs index a6ab491f..7f7ef4a6 100644 --- a/Penumbra/Mods/SubMods/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -5,17 +5,16 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.SubMods; - public interface IModDataContainer { - public IMod Mod { get; } + public IMod Mod { get; } public IModGroup? Group { get; } - public Dictionary Files { get; set; } - public Dictionary FileSwaps { get; set; } - public HashSet Manipulations { get; set; } + public Dictionary Files { get; set; } + public Dictionary FileSwaps { get; set; } + public HashSet Manipulations { get; set; } - public string GetName(); - public string GetFullName(); + public string GetName(); + public string GetFullName(); public (int GroupIndex, int DataIndex) GetDataIndices(); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 68933c9e..7cf75c03 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Text; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; @@ -75,6 +76,8 @@ public partial class ModEditWindow _editor.MetaEditor.OtherGmpCount); DrawEditHeader(_editor.MetaEditor.Rsp, "Racial Scaling Edits (RSP)###RSP", 5, RspRow.Draw, RspRow.DrawNew, _editor.MetaEditor.OtherRspCount); + DrawEditHeader(_editor.MetaEditor.GlobalEqp, "Global Equipment Parameter Edits Edits (Global EQP)###GEQP", 4, GlobalEqpRow.Draw, + GlobalEqpRow.DrawNew, _editor.MetaEditor.OtherGlobalEqpCount); } @@ -702,6 +705,69 @@ public partial class ModEditWindow } } + private static class GlobalEqpRow + { + private static GlobalEqpManipulation _new = new() + { + Type = GlobalEqpType.DoNotHideEarrings, + Condition = 1, + }; + + public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current global EQP manipulations to clipboard.", iconSize, + editor.MetaEditor.GlobalEqp.Select(m => (MetaManipulation)m)); + ImGui.TableNextColumn(); + var canAdd = editor.MetaEditor.CanAdd(_new); + var tt = canAdd ? "Stage this edit." : "This entry is already manipulated."; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) + editor.MetaEditor.Add(_new); + + // Identifier + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(250 * ImUtf8.GlobalScale); + using (var combo = ImUtf8.Combo("##geqpType"u8, _new.Type.ToName())) + { + if (combo) + foreach (var type in Enum.GetValues()) + { + if (ImUtf8.Selectable(type.ToName(), type == _new.Type)) + _new = new GlobalEqpManipulation + { + Type = type, + Condition = type.HasCondition() ? _new.Type.HasCondition() ? _new.Condition : 1 : 0, + }; + ImUtf8.HoverTooltip(type.ToDescription()); + } + } + + ImUtf8.HoverTooltip(_new.Type.ToDescription()); + + ImGui.TableNextColumn(); + if (!_new.Type.HasCondition()) + return; + + if (IdInput("##geqpCond", 100 * ImUtf8.GlobalScale, _new.Condition.Id, out var newId, 1, ushort.MaxValue, _new.Condition.Id <= 1)) + _new = _new with { Condition = newId }; + } + + public static void Draw(MetaFileManager metaFileManager, GlobalEqpManipulation meta, ModEditor editor, Vector2 iconSize) + { + DrawMetaButtons(meta, editor, iconSize); + ImGui.TableNextColumn(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + ImUtf8.Text(meta.Type.ToName()); + ImUtf8.HoverTooltip(meta.Type.ToDescription()); + ImGui.TableNextColumn(); + if (meta.Type.HasCondition()) + { + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + ImUtf8.Text($"{meta.Condition.Id}"); + } + } + } + // A number input for ids with a optional max id of given width. // Returns true if newId changed against currentId. private static bool IdInput(string label, float width, ushort currentId, out ushort newId, int minId, int maxId, bool border) diff --git a/Penumbra/Util/IdentifierExtensions.cs b/Penumbra/Util/IdentifierExtensions.cs index 392a5aba..7368c7c8 100644 --- a/Penumbra/Util/IdentifierExtensions.cs +++ b/Penumbra/Util/IdentifierExtensions.cs @@ -76,6 +76,26 @@ public static class IdentifierExtensions case MetaManipulation.Type.Rsp: changedItems.TryAdd($"{manip.Rsp.SubRace.ToName()} {manip.Rsp.Attribute.ToFullString()}", null); break; + case MetaManipulation.Type.GlobalEqp: + var path = manip.GlobalEqp.Type switch + { + GlobalEqpType.DoNotHideEarrings => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, + EquipSlot.Ears), + GlobalEqpType.DoNotHideNecklace => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, + EquipSlot.Neck), + GlobalEqpType.DoNotHideBracelets => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, + EquipSlot.Wrists), + GlobalEqpType.DoNotHideRingR => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, + EquipSlot.RFinger), + GlobalEqpType.DoNotHideRingL => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, + EquipSlot.LFinger), + GlobalEqpType.DoNotHideHrothgarHats => string.Empty, + GlobalEqpType.DoNotHideVieraHats => string.Empty, + _ => string.Empty, + }; + if (path.Length > 0) + identifier.Identify(changedItems, path); + break; } } From cd133bddbba7241138829ce7f7f7a45a8e50b98f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 26 May 2024 14:50:22 +0200 Subject: [PATCH 0617/1381] Update Changelog. --- Penumbra/UI/Changelog.cs | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index add16f94..2b2cfa99 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -55,26 +55,46 @@ public class PenumbraChangelog private static void Add1_0_3_0(Changelog log) => log.NextVersion("Version 1.0.3.0") + .RegisterImportant( + "This update comes, again, with a lot of very heavy backend changes (collections and groups) and thus may introduce new issues.") .RegisterHighlight("Collections now have associated GUIDs as identifiers instead of their names, so they can now be renamed.") .RegisterEntry("Migrating those collections may introduce issues, please let me know as soon as possible if you encounter any.", 1) - .RegisterEntry("A permanent (non-rolling) backup should be created before the migration in case of any issues.", 1) - .RegisterHighlight("A total rework of how options and groups are handled internally, and introduction of the first new group type, the IMC Group.") - .RegisterEntry("Mod Creators can add a IMC Group to their mod that controls a single IMC Manipulation, so they can provide options for the separate attributes for it.", 1) - .RegisterEntry("This makes it a lot easier to have combined options: No need for 'A', 'B' and 'AB', you can just define 'A' and 'B' and skip their combinations", 1) - .RegisterHighlight("Added a field to rename mods directly from the mod selector context menu, instead of moving them in the filesystem.") + .RegisterEntry("A permanent (non-rolling) backup should be created before the migration in case of any issues.", 1) + .RegisterHighlight( + "A total rework of how options and groups are handled internally, and introduction of the first new group type, the IMC Group.") + .RegisterEntry( + "Mod Creators can add a IMC Group to their mod that controls a single IMC Manipulation, so they can provide options for the separate attributes for it.", + 1) + .RegisterEntry( + "This makes it a lot easier to have combined options: No need for 'A', 'B' and 'AB', you can just define 'A' and 'B' and skip their combinations", + 1) + .RegisterHighlight("A new type of Meta Manipulation was added, 'Global EQP Manipulation'.") + .RegisterEntry( + "Global EQP Manipulations allow accessories to make other equipment pieces not hide them, e.g. whenever a character is wearing a specific Bracelet, neither body nor hand items will ever hide bracelets.", + 1) + .RegisterEntry( + "This can be used if something like a jacket or a stole is put onto an accessory to prevent it from being hidden in general.", + 1) + .RegisterHighlight( + "Added a field to rename mods directly from the mod selector context menu, instead of moving them in the filesystem.") .RegisterEntry("You can choose which rename field (none, either one or both) to display in the settings.", 1) - .RegisterEntry("You can now paste your current clipboard text into the mod selector filter with a simple right-click as long as it is not focused.") - .RegisterHighlight("Added the option to display VFX for accessories if added via IMC edits, which the game does not do inherently (by Ocealot).") + .RegisterEntry( + "You can now paste your current clipboard text into the mod selector filter with a simple right-click as long as it is not focused.") + .RegisterHighlight( + "Added the option to display VFX for accessories if added via IMC edits, which the game does not do inherently (by Ocealot).") .RegisterEntry("Added support for reading and writing the new material and model file formats from the benchmark.") - .RegisterEntry("Added the option to hide Machinist Offhands from the Changed Items tabs (because any change to it changes ALL of them), which is on by default.") + .RegisterEntry( + "Added the option to hide Machinist Offhands from the Changed Items tabs (because any change to it changes ALL of them), which is on by default.") .RegisterEntry("Removed the auto-generated descriptions for newly created groups in Penumbra.") - .RegisterEntry("Made some improvements to the Advanced Editing window, for example a much better and more performant Hex Viewer for unstructured data was added.") + .RegisterEntry( + "Made some improvements to the Advanced Editing window, for example a much better and more performant Hex Viewer for unstructured data was added.") .RegisterEntry("Made a lot of further improvements on Model import/export (by ackwell).") .RegisterEntry("Reworked the API and IPC structure heavily.") .RegisterEntry("Worked around the UI IPC possibly displacing all settings when the drawn additions became too big.") .RegisterEntry("Fixed an issue with merging and deduplicating mods.") .RegisterEntry("Fixed a crash when scanning for mods without access rights to the folder.") - .RegisterEntry("Made plugin conform to Dalamud requirements by adding a punchline and another button to open the menu from the installer."); + .RegisterEntry( + "Made plugin conform to Dalamud requirements by adding a punchline and another button to open the menu from the installer."); private static void Add1_0_2_0(Changelog log) => log.NextVersion("Version 1.0.2.0") From 1d230050c214df15aeb83e7f14b110a3e836a4eb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 26 May 2024 15:41:27 +0200 Subject: [PATCH 0618/1381] Fix typo and rename geqp options. --- Penumbra/Meta/Manipulations/GlobalEqpType.cs | 14 +++++++------- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Penumbra/Meta/Manipulations/GlobalEqpType.cs b/Penumbra/Meta/Manipulations/GlobalEqpType.cs index 57d99d56..d57af1d9 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpType.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpType.cs @@ -30,13 +30,13 @@ public static class GlobalEqpExtensions public static ReadOnlySpan ToName(this GlobalEqpType type) => type switch { - GlobalEqpType.DoNotHideEarrings => "Do Not Hide Earrings"u8, - GlobalEqpType.DoNotHideNecklace => "Do Not Hide Necklaces"u8, - GlobalEqpType.DoNotHideBracelets => "Do Not Hide Bracelets"u8, - GlobalEqpType.DoNotHideRingR => "Do Not Hide Rings (Right Finger)"u8, - GlobalEqpType.DoNotHideRingL => "Do Not Hide Rings (Left Finger)"u8, - GlobalEqpType.DoNotHideHrothgarHats => "Do Not Hide Hats for Hrothgar"u8, - GlobalEqpType.DoNotHideVieraHats => "Do Not Hide Hats for Viera"u8, + GlobalEqpType.DoNotHideEarrings => "Always Show Earrings"u8, + GlobalEqpType.DoNotHideNecklace => "Always Show Necklaces"u8, + GlobalEqpType.DoNotHideBracelets => "Always Show Bracelets"u8, + GlobalEqpType.DoNotHideRingR => "Always Show Rings (Right Finger)"u8, + GlobalEqpType.DoNotHideRingL => "Always Show Rings (Left Finger)"u8, + GlobalEqpType.DoNotHideHrothgarHats => "Always Show Hats for Hrothgar"u8, + GlobalEqpType.DoNotHideVieraHats => "Always Show Hats for Viera"u8, _ => "\0"u8, }; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 7cf75c03..6f542377 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -76,7 +76,7 @@ public partial class ModEditWindow _editor.MetaEditor.OtherGmpCount); DrawEditHeader(_editor.MetaEditor.Rsp, "Racial Scaling Edits (RSP)###RSP", 5, RspRow.Draw, RspRow.DrawNew, _editor.MetaEditor.OtherRspCount); - DrawEditHeader(_editor.MetaEditor.GlobalEqp, "Global Equipment Parameter Edits Edits (Global EQP)###GEQP", 4, GlobalEqpRow.Draw, + DrawEditHeader(_editor.MetaEditor.GlobalEqp, "Global Equipment Parameter Edits (Global EQP)###GEQP", 4, GlobalEqpRow.Draw, GlobalEqpRow.DrawNew, _editor.MetaEditor.OtherGlobalEqpCount); } From ca777ba1bf6369f7fd6202f40620d882d56b4e86 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 27 May 2024 17:43:13 +0200 Subject: [PATCH 0619/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 07cc26f1..b8282970 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 07cc26f196984a44711b3bc4c412947d863288bd +Subproject commit b8282970ee78a2c085e740f60450fecf7ea58b9c From fe266dca314f873422ec3f87a4769cbdc7dd520a Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 27 May 2024 15:45:29 +0000 Subject: [PATCH 0620/1381] [CI] Updating repo.json for testing_1.0.3.0 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 232afaa0..2327420d 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.2.6", + "TestingAssemblyVersion": "1.0.3.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.2.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.3.0/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From f11cefcec1e21d416d25f7cbb1a6f31d8a19705f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 28 May 2024 00:11:31 +0200 Subject: [PATCH 0621/1381] Fix best match fullpath returning broken FullPath instead of nullopt. --- Penumbra/Mods/Groups/MultiModGroup.cs | 11 ++++++++--- Penumbra/Mods/Groups/SingleModGroup.cs | 10 +++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 38c0ef15..7816d628 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; +using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; @@ -40,9 +41,13 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup => OptionData.Count > 0; public FullPath? FindBestMatch(Utf8GamePath gamePath) - => OptionData.OrderByDescending(o => o.Priority) - .SelectWhere(o => (o.Files.TryGetValue(gamePath, out var file) || o.FileSwaps.TryGetValue(gamePath, out file), file)) - .FirstOrDefault(); + { + foreach (var path in OptionData.OrderByDescending(o => o.Priority) + .SelectWhere(o => (o.Files.TryGetValue(gamePath, out var file) || o.FileSwaps.TryGetValue(gamePath, out file), file))) + return path; + + return null; + } public IModOption? AddOption(string name, string description = "") { diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 49190e34..a6ebd846 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -30,9 +30,13 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public readonly List OptionData = []; public FullPath? FindBestMatch(Utf8GamePath gamePath) - => OptionData - .SelectWhere(m => (m.Files.TryGetValue(gamePath, out var file) || m.FileSwaps.TryGetValue(gamePath, out file), file)) - .FirstOrDefault(); + { + foreach (var path in OptionData + .SelectWhere(m => (m.Files.TryGetValue(gamePath, out var file) || m.FileSwaps.TryGetValue(gamePath, out file), file))) + return path; + + return null; + } public IModOption AddOption(string name, string description = "") { From b30de460e729c4d0eb6ccdfcab298738f10ef54a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 28 May 2024 00:11:54 +0200 Subject: [PATCH 0622/1381] Fix ColorTable preview with legacy color tables. --- Penumbra.GameData | 2 +- .../Import/Models/Export/MaterialExporter.cs | 4 ++-- .../LiveColorTablePreviewer.cs | 2 +- .../ModEditWindow.Materials.ColorTable.cs | 13 ++++++------ .../ModEditWindow.Materials.MtrlTab.cs | 21 +++++++++++-------- 5 files changed, 23 insertions(+), 19 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index b8282970..b83ce830 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b8282970ee78a2c085e740f60450fecf7ea58b9c +Subproject commit b83ce830919ca56e8b066d48d588c889df3af39b diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 73a5e725..5df9e1c1 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -49,7 +49,7 @@ public class MaterialExporter private static MaterialBuilder BuildCharacter(Material material, string name) { // Build the textures from the color table. - var table = material.Mtrl.Table; + var table = new LegacyColorTable(material.Mtrl.Table); var normal = material.Textures[TextureUsage.SamplerNormal]; @@ -103,7 +103,7 @@ public class MaterialExporter // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. - private readonly struct ProcessCharacterNormalOperation(Image normal, ColorTable table) : IRowOperation + private readonly struct ProcessCharacterNormalOperation(Image normal, LegacyColorTable table) : IRowOperation { public Image Normal { get; } = normal.Clone(); public Image BaseColor { get; } = new(normal.Width, normal.Height); diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index f211e0bc..8e75a895 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -8,7 +8,7 @@ namespace Penumbra.Interop.MaterialPreview; public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase { public const int TextureWidth = 4; - public const int TextureHeight = GameData.Files.MaterialStructs.ColorTable.NumUsedRows; + public const int TextureHeight = GameData.Files.MaterialStructs.LegacyColorTable.NumUsedRows; public const int TextureLength = TextureWidth * TextureHeight * 4; private readonly IFramework _framework; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index 54c0eff6..15bd7cc9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -116,7 +116,7 @@ public partial class ModEditWindow { var ret = false; if (tab.Mtrl.HasDyeTable) - for (var i = 0; i < ColorTable.NumUsedRows; ++i) + for (var i = 0; i < LegacyColorTable.NumUsedRows; ++i) ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId, 0); tab.UpdateColorTablePreview(); @@ -170,6 +170,7 @@ public partial class ModEditWindow } } + [SkipLocalsInit] private static unsafe void ColorTableCopyClipboardButton(ColorTable.Row row, ColorDyeTable.Row dye) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, @@ -178,11 +179,11 @@ public partial class ModEditWindow try { - var data = new byte[ColorTable.Row.Size + 2]; + Span data = stackalloc byte[ColorTable.Row.Size + ColorDyeTable.Row.Size]; fixed (byte* ptr = data) { - MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTable.Row.Size); - MemoryUtility.MemCpyUnchecked(ptr + ColorTable.Row.Size, &dye, 2); + MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTable.Row.Size); + MemoryUtility.MemCpyUnchecked(ptr + ColorTable.Row.Size, &dye, ColorDyeTable.Row.Size); } var text = Convert.ToBase64String(data); @@ -218,7 +219,7 @@ public partial class ModEditWindow { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - if (data.Length != ColorTable.Row.Size + 2 + if (data.Length != ColorTable.Row.Size + ColorDyeTable.Row.Size || !tab.Mtrl.HasTable) return false; @@ -349,7 +350,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); tmpFloat = row.GlossStrength; ImGui.SetNextItemWidth(floatSize); - float glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; + var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), glossStrengthMin, HalfMaxValue, "%.1f") && FixFloat(ref tmpFloat, row.GlossStrength)) { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 9421493e..56e9482b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -455,7 +455,8 @@ public partial class ModEditWindow { UnbindFromMaterialInstances(); - var instances = MaterialInfo.FindMaterials(_edit._resourceTreeFactory.GetLocalPlayerRelatedCharacters().Select(ch => ch.Address), FilePath); + var instances = MaterialInfo.FindMaterials(_edit._resourceTreeFactory.GetLocalPlayerRelatedCharacters().Select(ch => ch.Address), + FilePath); var foundMaterials = new HashSet(); foreach (var materialInfo in instances) @@ -596,13 +597,13 @@ public partial class ModEditWindow if (!Mtrl.HasTable) return; - var row = Mtrl.Table[rowIdx]; + var row = new LegacyColorTable.Row(Mtrl.Table[rowIdx]); if (Mtrl.HasDyeTable) { var stm = _edit._stainService.StmFile; - var dye = Mtrl.DyeTable[rowIdx]; + var dye = new LegacyColorDyeTable.Row(Mtrl.DyeTable[rowIdx]); if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) - row.ApplyDyeTemplate(dye, dyes, default); + row.ApplyDyeTemplate(dye, dyes); } if (HighlightedColorTableRow == rowIdx) @@ -624,17 +625,18 @@ public partial class ModEditWindow if (!Mtrl.HasTable) return; - var rows = Mtrl.Table; + var rows = new LegacyColorTable(Mtrl.Table); + var dyeRows = new LegacyColorDyeTable(Mtrl.DyeTable); if (Mtrl.HasDyeTable) { var stm = _edit._stainService.StmFile; var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; - for (var i = 0; i < ColorTable.NumUsedRows; ++i) + for (var i = 0; i < LegacyColorTable.NumUsedRows; ++i) { ref var row = ref rows[i]; - var dye = Mtrl.DyeTable[i]; + var dye = dyeRows[i]; if (stm.TryGetValue(dye.Template, stainId, out var dyes)) - row.ApplyDyeTemplate(dye, dyes, default); + row.ApplyDyeTemplate(dye, dyes); } } @@ -643,12 +645,13 @@ public partial class ModEditWindow foreach (var previewer in ColorTablePreviewers) { + // TODO: Dawntrail rows.AsHalves().CopyTo(previewer.ColorTable); previewer.ScheduleUpdate(); } } - private static void ApplyHighlight(ref ColorTable.Row row, float time) + private static void ApplyHighlight(ref LegacyColorTable.Row row, float time) { var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; var baseColor = ColorId.InGameHighlight.Value(); From eb2a9b810922f409f8630e73a75c63353f1e709f Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 27 May 2024 22:13:55 +0000 Subject: [PATCH 0623/1381] [CI] Updating repo.json for testing_1.0.3.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 2327420d..1cf9c104 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.3.0", + "TestingAssemblyVersion": "1.0.3.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.3.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.3.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 255d11974fcad8893e009766b9c8254be12ec9eb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 28 May 2024 11:20:17 +0200 Subject: [PATCH 0624/1381] Fix IMC Stupid. --- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- Penumbra/UI/ModsTab/ImcManipulationDrawer.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 01bf112b..c95884c6 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -204,7 +204,7 @@ public class FileEditor( private void SaveButton() { - var canSave = _changed && _currentFile != null && _currentFile.Valid; + var canSave = _changed && _currentFile is { Valid: true }; if (ImGuiUtil.DrawDisabledButton("Save to File", Vector2.Zero, $"Save the selected {fileType} file with all changes applied. This is not revertible.", !canSave)) { diff --git a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs index c14652ac..694ae11c 100644 --- a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs +++ b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs @@ -26,6 +26,7 @@ public static class ImcManipulationDrawer }; identifier = identifier with { + ObjectType = type, EquipSlot = equipSlot, SecondaryId = identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId, }; From 5d1b17f96d159276e3470e462b56fbd2b101dd6e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 28 May 2024 12:51:12 +0200 Subject: [PATCH 0625/1381] Fix mdl imports not being savable. --- Penumbra.GameData | 2 +- Penumbra/Import/Models/Import/ModelImporter.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index b83ce830..f2cea65b 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b83ce830919ca56e8b066d48d588c889df3af39b +Subproject commit f2cea65b83b2d6cb0d03339e8f76aed8102a41d5 diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index eedd12ab..a141d754 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -104,6 +104,7 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) Radius = 1, BoneBoundingBoxes = Enumerable.Repeat(MdlFile.EmptyBoundingBox, _bones.Count).ToArray(), RemainingData = [.._vertexBuffer, ..indexBuffer], + Valid = true, }; } From f5d6ac8bdbd43edf11f5d7ed41d7f587c49590d6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 28 May 2024 12:51:28 +0200 Subject: [PATCH 0626/1381] Fix Remove Assignment being visible for base and interface. --- Penumbra/Collections/Manager/CollectionType.cs | 3 +++ Penumbra/UI/CollectionTab/CollectionPanel.cs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Penumbra/Collections/Manager/CollectionType.cs b/Penumbra/Collections/Manager/CollectionType.cs index 8c51fd90..c25413b8 100644 --- a/Penumbra/Collections/Manager/CollectionType.cs +++ b/Penumbra/Collections/Manager/CollectionType.cs @@ -107,6 +107,9 @@ public static class CollectionTypeExtensions public static bool IsSpecial(this CollectionType collectionType) => collectionType < CollectionType.Default; + public static bool CanBeRemoved(this CollectionType collectionType) + => collectionType.IsSpecial() || collectionType is CollectionType.Individual; + public static readonly (CollectionType, string, string)[] Special = Enum.GetValues() .Where(IsSpecial) .Select(s => (s, s.ToName(), s.ToDescription())) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 8625335e..bb22e6a7 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -287,7 +287,7 @@ public sealed class CollectionPanel : IDisposable _active.SetCollection(ModCollection.Empty, type, _active.Individuals.GetGroup(identifier)); } - if (collection != null) + if (collection != null && type.CanBeRemoved()) { using var color = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); if (ImGui.MenuItem("Remove this assignment.")) From 8891ea057086094e56220b60989741d7fc36dfc7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 28 May 2024 12:53:02 +0200 Subject: [PATCH 0627/1381] Fix imc identifiers setting equip slot to something where they should not. --- Penumbra/Meta/Manipulations/ImcManipulation.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs index 945aab04..eb3720c9 100644 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ b/Penumbra/Meta/Manipulations/ImcManipulation.cs @@ -64,10 +64,8 @@ public readonly struct ImcManipulation : IMetaManipulation { ObjectType.Accessory or ObjectType.Equipment => new ImcIdentifier(primaryId, v, objectType, 0, equipSlot, variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), - ObjectType.DemiHuman => new ImcIdentifier(primaryId, v, objectType, secondaryId, - equipSlot == EquipSlot.Unknown ? EquipSlot.Head : equipSlot, variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), - _ => new ImcIdentifier(primaryId, v, objectType, secondaryId, equipSlot == EquipSlot.Unknown ? EquipSlot.Head : equipSlot, - bodySlot), + ObjectType.DemiHuman => new ImcIdentifier(primaryId, v, objectType, secondaryId, equipSlot, variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), + _ => new ImcIdentifier(primaryId, v, objectType, secondaryId, equipSlot, bodySlot == BodySlot.Unknown ? BodySlot.Body : BodySlot.Unknown), }; } From 09742e2e50d24acfe62e4876451f9be556b457fe Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 28 May 2024 10:56:23 +0000 Subject: [PATCH 0628/1381] [CI] Updating repo.json for testing_1.0.3.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 1cf9c104..a996e2d0 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.3.1", + "TestingAssemblyVersion": "1.0.3.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.3.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.3.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From b2e1bff782f5aff12766ecbe82bfa743242e0705 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 30 May 2024 17:18:39 +0200 Subject: [PATCH 0629/1381] Consolidate path-data encoding into a single file and make it neater. --- Penumbra/Collections/Cache/ImcCache.cs | 16 +- .../Collections/Manager/CollectionStorage.cs | 64 ++++++- .../Manager/TempCollectionManager.cs | 3 +- Penumbra/Collections/ModCollection.cs | 27 +-- .../Interop/PathResolving/PathDataHandler.cs | 162 ++++++++++++++++++ .../Interop/PathResolving/PathResolver.cs | 52 +++--- .../Interop/PathResolving/SubfileHelper.cs | 19 +- .../ResourceLoading/CreateFileWHook.cs | 3 +- .../Interop/ResourceLoading/ResourceLoader.cs | 24 ++- .../Interop/ResourceTree/ResolveContext.cs | 11 +- Penumbra/Mods/TemporaryMod.cs | 7 +- Penumbra/Services/ConfigMigrationService.cs | 3 +- Penumbra/Services/CrashHandlerService.cs | 4 +- .../UI/ResourceWatcher/ResourceWatcher.cs | 2 +- 14 files changed, 302 insertions(+), 95 deletions(-) create mode 100644 Penumbra/Interop/PathResolving/PathDataHandler.cs diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 843fe195..33b366d3 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -1,3 +1,4 @@ +using Penumbra.Interop.PathResolving; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -7,8 +8,8 @@ namespace Penumbra.Collections.Cache; public readonly struct ImcCache : IDisposable { - private readonly Dictionary _imcFiles = new(); - private readonly List<(ImcManipulation, ImcFile)> _imcManipulations = new(); + private readonly Dictionary _imcFiles = []; + private readonly List<(ImcManipulation, ImcFile)> _imcManipulations = []; public ImcCache() { } @@ -17,10 +18,10 @@ public readonly struct ImcCache : IDisposable { if (fromFullCompute) foreach (var path in _imcFiles.Keys) - collection._cache!.ForceFileSync(path, CreateImcPath(collection, path)); + collection._cache!.ForceFileSync(path, PathDataHandler.CreateImc(path.Path, collection)); else foreach (var path in _imcFiles.Keys) - collection._cache!.ForceFile(path, CreateImcPath(collection, path)); + collection._cache!.ForceFile(path, PathDataHandler.CreateImc(path.Path, collection)); } public void Reset(ModCollection collection) @@ -57,7 +58,7 @@ public readonly struct ImcCache : IDisposable return false; _imcFiles[path] = file; - var fullPath = CreateImcPath(collection, path); + var fullPath = PathDataHandler.CreateImc(file.Path.Path, collection); collection._cache!.ForceFile(path, fullPath); return true; @@ -100,7 +101,7 @@ public readonly struct ImcCache : IDisposable if (!manip.Apply(file)) return false; - var fullPath = CreateImcPath(collection, file.Path); + var fullPath = PathDataHandler.CreateImc(file.Path.Path, collection); collection._cache!.ForceFile(file.Path, fullPath); return true; @@ -115,9 +116,6 @@ public readonly struct ImcCache : IDisposable _imcManipulations.Clear(); } - private static FullPath CreateImcPath(ModCollection collection, Utf8GamePath path) - => new($"|{collection.Id.OptimizedString()}_{collection.ChangeCounter}|{path}"); - public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out ImcFile? file) => _imcFiles.TryGetValue(path, out file); } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index de5d0a14..39068e87 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,3 +1,4 @@ +using System; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; @@ -10,23 +11,71 @@ using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; +using Penumbra.UI.CollectionTab; namespace Penumbra.Collections.Manager; +/// A contiguously incrementing ID managed by the CollectionCreator. +public readonly record struct LocalCollectionId(int Id) : IAdditionOperators +{ + public static readonly LocalCollectionId Zero = new(0); + + public static LocalCollectionId operator +(LocalCollectionId left, int right) + => new(left.Id + right); +} + public class CollectionStorage : IReadOnlyList, IDisposable { private readonly CommunicatorService _communicator; private readonly SaveService _saveService; private readonly ModStorage _modStorage; + public ModCollection Create(string name, int index, ModCollection? duplicate) + { + var newCollection = duplicate?.Duplicate(name, CurrentCollectionId, index) + ?? ModCollection.CreateEmpty(name, CurrentCollectionId, index, _modStorage.Count); + _collectionsByLocal[CurrentCollectionId] = newCollection; + CurrentCollectionId += 1; + return newCollection; + } + + public ModCollection CreateFromData(Guid id, string name, int version, Dictionary allSettings, + IReadOnlyList inheritances) + { + var newCollection = ModCollection.CreateFromData(_saveService, _modStorage, id, name, CurrentCollectionId, version, Count, allSettings, + inheritances); + _collectionsByLocal[CurrentCollectionId] = newCollection; + CurrentCollectionId += 1; + return newCollection; + } + + public ModCollection CreateTemporary(string name, int index, int globalChangeCounter) + { + var newCollection = ModCollection.CreateTemporary(name, CurrentCollectionId, index, globalChangeCounter); + _collectionsByLocal[CurrentCollectionId] = newCollection; + CurrentCollectionId += 1; + return newCollection; + } + + public void Delete(ModCollection collection) + => _collectionsByLocal.Remove(collection.LocalId); + /// The empty collection is always available at Index 0. private readonly List _collections = [ ModCollection.Empty, ]; + /// A list of all collections ever created still existing by their local id. + private readonly Dictionary + _collectionsByLocal = new() { [LocalCollectionId.Zero] = ModCollection.Empty }; + + public readonly ModCollection DefaultNamed; + /// Incremented by 1 because the empty collection gets Zero. + public LocalCollectionId CurrentCollectionId { get; private set; } = LocalCollectionId.Zero + 1; + /// Default enumeration skips the empty collection. public IEnumerator GetEnumerator() => _collections.Skip(1).GetEnumerator(); @@ -69,6 +118,10 @@ public class CollectionStorage : IReadOnlyList, IDisposable return ByName(identifier, out collection); } + /// Find a collection by its local ID if it still exists, otherwise returns the empty collection. + public ModCollection ByLocalId(LocalCollectionId localId) + => _collectionsByLocal.TryGetValue(localId, out var coll) ? coll : ModCollection.Empty; + public CollectionStorage(CommunicatorService communicator, SaveService saveService, ModStorage modStorage) { _communicator = communicator; @@ -100,10 +153,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable /// public bool AddCollection(string name, ModCollection? duplicate) { - var newCollection = duplicate?.Duplicate(name, _collections.Count) - ?? ModCollection.CreateEmpty(name, _collections.Count, _modStorage.Count); - _collections.Add(newCollection); - + var newCollection = Create(name, _collections.Count, duplicate); _saveService.ImmediateSave(new ModCollectionSave(_modStorage, newCollection)); Penumbra.Messager.NotificationMessage($"Created new collection {newCollection.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, null, newCollection, string.Empty); @@ -132,6 +182,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable // Update indices. for (var i = collection.Index; i < Count; ++i) _collections[i].Index = i; + _collectionsByLocal.Remove(collection.LocalId); Penumbra.Messager.NotificationMessage($"Deleted collection {collection.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, collection, null, string.Empty); @@ -180,7 +231,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable continue; } - var collection = ModCollection.CreateFromData(_saveService, _modStorage, id, name, version, Count, settings, inheritance); + var collection = CreateFromData(id, name, version, settings, inheritance); var correctName = _saveService.FileNames.CollectionFile(collection); if (file.FullName != correctName) try @@ -293,7 +344,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable } /// Save all collections where the mod has settings and the change requires saving. - private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int movedToIdx) + private void OnModOptionChange(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, + int movedToIdx) { type.HandlingInfo(out var requiresSaving, out _, out _); if (!requiresSaving) diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index de08c6a2..ce438a6b 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -52,7 +52,7 @@ public class TempCollectionManager : IDisposable { if (GlobalChangeCounter == int.MaxValue) GlobalChangeCounter = 0; - var collection = ModCollection.CreateTemporary(name, ~Count, GlobalChangeCounter++); + var collection = _storage.CreateTemporary(name, ~Count, GlobalChangeCounter++); Penumbra.Log.Debug($"Creating temporary collection {collection.Name} with {collection.Id}."); if (_customCollections.TryAdd(collection.Id, collection)) { @@ -72,6 +72,7 @@ public class TempCollectionManager : IDisposable return false; } + _storage.Delete(collection); Penumbra.Log.Debug($"Deleted temporary collection {collection.Id}."); GlobalChangeCounter += Math.Max(collection.ChangeCounter + 1 - GlobalChangeCounter, 0); for (var i = 0; i < Collections.Count; ++i) diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index 4580e37a..9286d459 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -25,13 +25,15 @@ public partial class ModCollection /// Create the always available Empty Collection that will always sit at index 0, /// can not be deleted and does never create a cache. /// - public static readonly ModCollection Empty = new(Guid.Empty, EmptyCollectionName, 0, 0, CurrentVersion, [], [], []); + public static readonly ModCollection Empty = new(Guid.Empty, EmptyCollectionName, LocalCollectionId.Zero, 0, 0, CurrentVersion, [], [], []); /// The name of a collection. public string Name { get; set; } public Guid Id { get; } + public LocalCollectionId LocalId { get; } + public string Identifier => Id.ToString(); @@ -117,19 +119,20 @@ public partial class ModCollection /// /// Constructor for duplication. Deep copies all settings and parent collections and adds the new collection to their children lists. /// - public ModCollection Duplicate(string name, int index) + public ModCollection Duplicate(string name, LocalCollectionId localId, int index) { Debug.Assert(index > 0, "Collection duplicated with non-positive index."); - return new ModCollection(Guid.NewGuid(), name, index, 0, CurrentVersion, Settings.Select(s => s?.DeepCopy()).ToList(), + return new ModCollection(Guid.NewGuid(), name, localId, index, 0, CurrentVersion, Settings.Select(s => s?.DeepCopy()).ToList(), [.. DirectlyInheritsFrom], UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); } /// Constructor for reading from files. - public static ModCollection CreateFromData(SaveService saver, ModStorage mods, Guid id, string name, int version, int index, + public static ModCollection CreateFromData(SaveService saver, ModStorage mods, Guid id, string name, LocalCollectionId localId, int version, + int index, Dictionary allSettings, IReadOnlyList inheritances) { Debug.Assert(index > 0, "Collection read with non-positive index."); - var ret = new ModCollection(id, name, index, 0, version, [], [], allSettings) + var ret = new ModCollection(id, name, localId, index, 0, version, [], [], allSettings) { InheritanceByName = inheritances, }; @@ -139,18 +142,19 @@ public partial class ModCollection } /// Constructor for temporary collections. - public static ModCollection CreateTemporary(string name, int index, int changeCounter) + public static ModCollection CreateTemporary(string name, LocalCollectionId localId, int index, int changeCounter) { Debug.Assert(index < 0, "Temporary collection created with non-negative index."); - var ret = new ModCollection(Guid.NewGuid(), name, index, changeCounter, CurrentVersion, [], [], []); + var ret = new ModCollection(Guid.NewGuid(), name, localId, index, changeCounter, CurrentVersion, [], [], []); return ret; } /// Constructor for empty collections. - public static ModCollection CreateEmpty(string name, int index, int modCount) + public static ModCollection CreateEmpty(string name, LocalCollectionId localId, int index, int modCount) { Debug.Assert(index >= 0, "Empty collection created with negative index."); - return new ModCollection(Guid.NewGuid(), name, index, 0, CurrentVersion, Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], + return new ModCollection(Guid.NewGuid(), name, localId, index, 0, CurrentVersion, + Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], []); } @@ -199,11 +203,12 @@ public partial class ModCollection saver.ImmediateSave(new ModCollectionSave(mods, this)); } - private ModCollection(Guid id, string name, int index, int changeCounter, int version, List appliedSettings, - List inheritsFrom, Dictionary settings) + private ModCollection(Guid id, string name, LocalCollectionId localId, int index, int changeCounter, int version, + List appliedSettings, List inheritsFrom, Dictionary settings) { Name = name; Id = id; + LocalId = localId; Index = index; ChangeCounter = changeCounter; Settings = appliedSettings; diff --git a/Penumbra/Interop/PathResolving/PathDataHandler.cs b/Penumbra/Interop/PathResolving/PathDataHandler.cs new file mode 100644 index 00000000..5627e015 --- /dev/null +++ b/Penumbra/Interop/PathResolving/PathDataHandler.cs @@ -0,0 +1,162 @@ +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.PathResolving; + +public static class PathDataHandler +{ + public static readonly ushort Discriminator = (ushort)(Environment.TickCount >> 12); + private static readonly string DiscriminatorString = $"{Discriminator:X4}"; + private const int MinimumLength = 8; + + /// Additional Data encoded in a path. + /// The local ID of the collection. + /// The change counter of that collection when this file was loaded. + /// The CRC32 of the originally requested path, only used for materials. + /// A discriminator to differ between multiple loads of Penumbra. + public readonly record struct AdditionalPathData( + LocalCollectionId Collection, + int ChangeCounter, + int OriginalPathCrc32, + ushort Discriminator) + { + public static readonly AdditionalPathData Invalid = new(LocalCollectionId.Zero, 0, 0, PathDataHandler.Discriminator); + + /// Any collection but the empty collection can appear. In particular, they can be negative for temporary collections. + public bool Valid + => Collection.Id != 0; + } + + /// Create the encoding path for an IMC file. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FullPath CreateImc(ByteString path, ModCollection collection) + => CreateBase(path, collection); + + /// Create the encoding path for a TMB file. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FullPath CreateTmb(ByteString path, ModCollection collection) + => CreateBase(path, collection); + + /// Create the encoding path for an AVFX file. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FullPath CreateAvfx(ByteString path, ModCollection collection) + => CreateBase(path, collection); + + /// Create the encoding path for a MTRL file. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FullPath CreateMtrl(ByteString path, ModCollection collection, Utf8GamePath originalPath) + => new($"|{collection.LocalId.Id}_{collection.ChangeCounter}_{originalPath.Path.Crc32:X8}_{DiscriminatorString}|{path}"); + + /// The base function shared by most file types. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static FullPath CreateBase(ByteString path, ModCollection collection) + => new($"|{collection.LocalId.Id}_{collection.ChangeCounter}_{DiscriminatorString}|{path}"); + + /// Read an additional data blurb and parse it into usable data for all file types but Materials. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Read(ReadOnlySpan additionalData, out AdditionalPathData data) + => ReadBase(additionalData, out data, out _); + + /// Read an additional data blurb and parse it into usable data for Materials. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ReadMtrl(ReadOnlySpan additionalData, out AdditionalPathData data) + { + if (!ReadBase(additionalData, out data, out var remaining)) + return false; + + if (!int.TryParse(remaining, out var crc32)) + return false; + + data = data with { OriginalPathCrc32 = crc32 }; + return true; + } + + /// Parse the common attributes of an additional data blurb and return remaining data if there is any. + private static bool ReadBase(ReadOnlySpan additionalData, out AdditionalPathData data, out ReadOnlySpan remainingData) + { + data = AdditionalPathData.Invalid; + remainingData = []; + + // At least (\d_\d_\x\x\x\x) + if (additionalData.Length < MinimumLength) + return false; + + // Fetch discriminator, constant length. + var discriminatorSpan = additionalData[^4..]; + if (!ushort.TryParse(discriminatorSpan, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var discriminator)) + return false; + + additionalData = additionalData[..^5]; + var collectionSplit = additionalData.IndexOf((byte)'_'); + if (collectionSplit == -1) + return false; + + var collectionSpan = additionalData[..collectionSplit]; + additionalData = additionalData[(collectionSplit + 1)..]; + + if (!int.TryParse(collectionSpan, out var id)) + return false; + + var changeCounterSpan = additionalData; + var changeCounterSplit = additionalData.IndexOf((byte)'_'); + if (changeCounterSplit != -1) + { + changeCounterSpan = additionalData[..changeCounterSplit]; + remainingData = additionalData[(changeCounterSplit + 1)..]; + } + + if (!int.TryParse(changeCounterSpan, out var changeCounter)) + return false; + + data = new AdditionalPathData(new LocalCollectionId(id), changeCounter, 0, discriminator); + return true; + } + + /// Split a given span into the actual path and the additional data blurb. Returns true if a blurb exists. + public static bool Split(ReadOnlySpan text, out ReadOnlySpan path, out ReadOnlySpan data) + { + if (text.IsEmpty || text[0] is not (byte)'|') + { + path = text; + data = []; + return false; + } + + var endIdx = text[1..].IndexOf((byte)'|'); + if (endIdx++ < 0) + { + path = text; + data = []; + return false; + } + + data = text.Slice(1, endIdx - 1); + path = ++endIdx == text.Length ? [] : text[endIdx..]; + return true; + } + + /// + public static bool Split(ReadOnlySpan text, out ReadOnlySpan path, out ReadOnlySpan data) + { + if (text.Length == 0 || text[0] is not '|') + { + path = text; + data = []; + return false; + } + + var endIdx = text[1..].IndexOf('|'); + if (endIdx++ < 0) + { + path = text; + data = []; + return false; + } + + data = text.Slice(1, endIdx - 1); + path = ++endIdx >= text.Length ? [] : text[endIdx..]; + return true; + } +} diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 5c3d8d19..e5c75327 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -13,11 +13,10 @@ namespace Penumbra.Interop.PathResolving; public class PathResolver : IDisposable { - private readonly PerformanceTracker _performance; - private readonly Configuration _config; - private readonly CollectionManager _collectionManager; - private readonly TempCollectionManager _tempCollections; - private readonly ResourceLoader _loader; + private readonly PerformanceTracker _performance; + private readonly Configuration _config; + private readonly CollectionManager _collectionManager; + private readonly ResourceLoader _loader; private readonly SubfileHelper _subfileHelper; private readonly PathState _pathState; @@ -25,14 +24,12 @@ public class PathResolver : IDisposable private readonly GameState _gameState; private readonly CollectionResolver _collectionResolver; - public unsafe PathResolver(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, - TempCollectionManager tempCollections, ResourceLoader loader, SubfileHelper subfileHelper, - PathState pathState, MetaState metaState, CollectionResolver collectionResolver, GameState gameState) + public unsafe PathResolver(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ResourceLoader loader, + SubfileHelper subfileHelper, PathState pathState, MetaState metaState, CollectionResolver collectionResolver, GameState gameState) { _performance = performance; _config = config; _collectionManager = collectionManager; - _tempCollections = tempCollections; _subfileHelper = subfileHelper; _pathState = pathState; _metaState = metaState; @@ -43,9 +40,12 @@ public class PathResolver : IDisposable _loader.FileLoaded += ImcLoadResource; } - /// Obtain a temporary or permanent collection by name. - public bool CollectionById(Guid id, [NotNullWhen(true)] out ModCollection? collection) - => _tempCollections.CollectionById(id, out collection) || _collectionManager.Storage.ById(id, out collection); + /// Obtain a temporary or permanent collection by local ID. + public bool CollectionByLocalId(LocalCollectionId id, out ModCollection collection) + { + collection = _collectionManager.Storage.ByLocalId(id); + return collection != ModCollection.Empty; + } /// Try to resolve the given game path to the replaced path. public (FullPath?, ResolveData) ResolvePath(Utf8GamePath path, ResourceCategory category, ResourceType resourceType) @@ -113,7 +113,7 @@ public class PathResolver : IDisposable // so that the functions loading tex and shpk can find that path and use its collection. // We also need to handle defaulted materials against a non-default collection. var path = resolved == null ? gamePath.Path : resolved.Value.InternalName; - SubfileHelper.HandleCollection(resolveData, path, nonDefault, type, resolved, out var pair); + SubfileHelper.HandleCollection(resolveData, path, nonDefault, type, resolved, gamePath, out var pair); return pair; } @@ -131,23 +131,21 @@ public class PathResolver : IDisposable } /// After loading an IMC file, replace its contents with the modded IMC file. - private unsafe void ImcLoadResource(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, ByteString additionalData) + private unsafe void ImcLoadResource(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, + ReadOnlySpan additionalData) { - if (resource->FileType != ResourceType.Imc) + if (resource->FileType != ResourceType.Imc + || !PathDataHandler.Read(additionalData, out var data) + || data.Discriminator != PathDataHandler.Discriminator + || !Utf8GamePath.FromByteString(path, out var gamePath) + || !CollectionByLocalId(data.Collection, out var collection) + || !collection.HasCache + || !collection.GetImcFile(gamePath, out var file)) return; - var lastUnderscore = additionalData.LastIndexOf((byte)'_'); - var idString = lastUnderscore == -1 ? additionalData : additionalData.Substring(0, lastUnderscore); - if (Utf8GamePath.FromByteString(path, out var gamePath) - && GuidExtensions.FromOptimizedString(idString.Span, out var id) - && CollectionById(id, out var collection) - && collection.HasCache - && collection.GetImcFile(gamePath, out var file)) - { - file.Replace(resource); - Penumbra.Log.Verbose( - $"[ResourceLoader] Loaded {gamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); - } + file.Replace(resource); + Penumbra.Log.Verbose( + $"[ResourceLoader] Loaded {gamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); } /// Resolve a path from the interface collection. diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 844baaa9..793ea20b 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -66,21 +66,18 @@ public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection Materials, TMB, and AVFX need to be set per collection so they can load their sub files independently from each other. + /// Materials, TMB, and AVFX need to be set per collection, so they can load their sub files independently of each other. public static void HandleCollection(ResolveData resolveData, ByteString path, bool nonDefault, ResourceType type, FullPath? resolved, - out (FullPath?, ResolveData) data) + Utf8GamePath originalPath, out (FullPath?, ResolveData) data) { if (nonDefault) - switch (type) + resolved = type switch { - case ResourceType.Mtrl: - case ResourceType.Avfx: - case ResourceType.Tmb: - var fullPath = new FullPath($"|{resolveData.ModCollection.Id.OptimizedString()}_{resolveData.ModCollection.ChangeCounter}|{path}"); - data = (fullPath, resolveData); - return; - } - + ResourceType.Mtrl => PathDataHandler.CreateMtrl(path, resolveData.ModCollection, originalPath), + ResourceType.Avfx => PathDataHandler.CreateAvfx(path, resolveData.ModCollection), + ResourceType.Tmb => PathDataHandler.CreateTmb(path, resolveData.ModCollection), + _ => resolved, + }; data = (resolved, resolveData); } diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs index 8a5e779b..bde640d2 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs @@ -1,5 +1,6 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; +using OtterGui.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.String.Functions; @@ -11,7 +12,7 @@ namespace Penumbra.Interop.ResourceLoading; /// we use the fixed size buffers of their formats to only store pointers to the actual path instead. /// Then we translate the stored pointer to the path in CreateFileW, if the prefix matches. /// -public unsafe class CreateFileWHook : IDisposable +public unsafe class CreateFileWHook : IDisposable, IRequiredService { public const int Size = 28; diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 6c2c83b3..7b49beab 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,6 +1,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; +using Penumbra.Interop.PathResolving; using Penumbra.Interop.SafeHandles; using Penumbra.Interop.Structs; using Penumbra.String; @@ -17,8 +18,7 @@ public unsafe class ResourceLoader : IDisposable private ResolveData _resolvedData = ResolveData.Invalid; - public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService, - CreateFileWHook _) + public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService) { _resources = resources; _fileReadService = fileReadService; @@ -54,7 +54,7 @@ public unsafe class ResourceLoader : IDisposable /// Reset the ResolvePath function to always return null. public void ResetResolvePath() - => ResolvePath = (_1, _2, _3) => (null, ResolveData.Invalid); + => ResolvePath = (_, _, _) => (null, ResolveData.Invalid); public delegate void ResourceLoadedDelegate(ResourceHandle* handle, Utf8GamePath originalPath, FullPath? manipulatedPath, ResolveData resolveData); @@ -67,7 +67,7 @@ public unsafe class ResourceLoader : IDisposable public event ResourceLoadedDelegate? ResourceLoaded; public delegate void FileLoadedDelegate(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, - ByteString additionalData); + ReadOnlySpan additionalData); /// /// Event fired whenever a resource is newly loaded. @@ -132,19 +132,17 @@ public unsafe class ResourceLoader : IDisposable // Paths starting with a '|' are handled separately to allow for special treatment. // They are expected to also have a closing '|'. - if (gamePath.Path[0] != (byte)'|') + if (!PathDataHandler.Split(gamePath.Path.Span, out var actualPath, out var data)) { - returnValue = DefaultLoadResource(gamePath.Path, fileDescriptor, priority, isSync, ByteString.Empty); + returnValue = DefaultLoadResource(gamePath.Path, fileDescriptor, priority, isSync, []); return; } - // Split the path into the special-treatment part (between the first and second '|') - // and the actual path. - var split = gamePath.Path.Split((byte)'|', 3, false); - fileDescriptor->ResourceHandle->FileNameData = split[2].Path; - fileDescriptor->ResourceHandle->FileNameLength = split[2].Length; + var path = ByteString.FromSpanUnsafe(actualPath, gamePath.Path.IsNullTerminated, gamePath.Path.IsAsciiLowerCase, gamePath.Path.IsAscii); + fileDescriptor->ResourceHandle->FileNameData = path.Path; + fileDescriptor->ResourceHandle->FileNameLength = path.Length; MtrlForceSync(fileDescriptor, ref isSync); - returnValue = DefaultLoadResource(split[2], fileDescriptor, priority, isSync, split[1]); + returnValue = DefaultLoadResource(path, fileDescriptor, priority, isSync, data); // Return original resource handle path so that they can be loaded separately. fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; fileDescriptor->ResourceHandle->FileNameLength = gamePath.Path.Length; @@ -153,7 +151,7 @@ public unsafe class ResourceLoader : IDisposable /// Load a resource by its path. If it is rooted, it will be loaded from the drive, otherwise from the SqPack. private byte DefaultLoadResource(ByteString gamePath, SeFileDescriptor* fileDescriptor, int priority, - bool isSync, ByteString additionalData) + bool isSync, ReadOnlySpan additionalData) { if (Utf8GamePath.IsRooted(gamePath)) { diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 615ef2b0..7c8da41f 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -9,6 +9,7 @@ using Penumbra.Collections; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; using Penumbra.Interop.Services; using Penumbra.String; using Penumbra.String.Classes; @@ -373,14 +374,8 @@ internal unsafe partial record ResolveContext( if (name.IsEmpty) return ByteString.Empty; - if (stripPrefix && name[0] == (byte)'|') - { - var pos = name.IndexOf((byte)'|', 1); - if (pos < 0) - return ByteString.Empty; - - name = name.Substring(pos + 1); - } + if (stripPrefix && PathDataHandler.Split(name.Span, out var path, out _)) + name = ByteString.FromSpanUnsafe(path, name.IsNullTerminated, name.IsAsciiLowerCase, name.IsAscii); return name; } diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index d08c8b06..6e6e72ab 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Collections; +using Penumbra.Interop.PathResolving; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; @@ -83,10 +84,8 @@ public class TemporaryMod : IMod } var targetPath = fullPath.Path.FullName; - if (fullPath.Path.Name.StartsWith('|')) - { - targetPath = targetPath.Split('|', 3, StringSplitOptions.RemoveEmptyEntries).Last(); - } + if (PathDataHandler.Split(fullPath.Path.FullName, out var actualPath, out _)) + targetPath = actualPath.ToString(); if (Path.IsPathRooted(targetPath)) { diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index 1f6ac170..70b05a73 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -379,7 +379,8 @@ public class ConfigMigrationService(SaveService saveService, BackupService backu dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value with { Priority = maxPriority - kvp.Value.Priority }); var emptyStorage = new ModStorage(); - var collection = ModCollection.CreateFromData(saveService, emptyStorage, Guid.NewGuid(), ModCollection.DefaultCollectionName, 0, 1, dict, []); + // Only used for saving and immediately discarded, so the local collection id here is irrelevant. + var collection = ModCollection.CreateFromData(saveService, emptyStorage, Guid.NewGuid(), ModCollection.DefaultCollectionName, LocalCollectionId.Zero, 0, 1, dict, []); saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 6805e7db..1239578b 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -7,6 +7,7 @@ using Penumbra.Communication; using Penumbra.CrashHandler; using Penumbra.CrashHandler.Buffers; using Penumbra.GameData.Actors; +using Penumbra.Interop.PathResolving; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.String; @@ -286,8 +287,7 @@ public sealed class CrashHandlerService : IDisposable, IService try { - var dashIdx = manipulatedPath.Value.InternalName[0] == (byte)'|' ? manipulatedPath.Value.InternalName.IndexOf((byte)'|', 1) : -1; - if (dashIdx >= 0 && !Utf8GamePath.IsRooted(manipulatedPath.Value.InternalName.Substring(dashIdx + 1))) + if (PathDataHandler.Split(manipulatedPath.Value.FullName, out var actualPath, out _) && Path.IsPathRooted(actualPath)) return; var name = GetActorName(resolveData.AssociatedGameObject); diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index d5ff1abd..65a8fe76 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -236,7 +236,7 @@ public sealed class ResourceWatcher : IDisposable, ITab _newRecords.Enqueue(record); } - private unsafe void OnFileLoaded(ResourceHandle* resource, ByteString path, bool success, bool custom, ByteString _) + private unsafe void OnFileLoaded(ResourceHandle* resource, ByteString path, bool success, bool custom, ReadOnlySpan _) { if (_ephemeral.EnableResourceLogging && FilterMatch(path, out var match)) Penumbra.Log.Information( From a6661f15e87ad8b8b15d386943d08e20001c9848 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 30 May 2024 20:46:04 +0200 Subject: [PATCH 0630/1381] Display the additional path data in ResourceTree --- .../Interop/MaterialPreview/MaterialInfo.cs | 11 +++++--- .../ResolveContext.PathResolution.cs | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 27 +++++++------------ Penumbra/Interop/ResourceTree/ResourceNode.cs | 4 +++ .../UI/AdvancedWindow/ResourceTreeViewer.cs | 8 ++++-- 5 files changed, 28 insertions(+), 24 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index 61e7c764..f7e6caf0 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -3,8 +3,9 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; -using Penumbra.Interop.ResourceTree; +using Penumbra.Interop.PathResolving; using Penumbra.String; +using static Penumbra.Interop.Structs.StructExtensions; using Model = Penumbra.GameData.Interop.Model; namespace Penumbra.Interop.MaterialPreview; @@ -78,8 +79,12 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy continue; var mtrlHandle = material->MaterialResourceHandle; - var path = ResolveContext.GetResourceHandlePath(&mtrlHandle->ResourceHandle); - if (path == needle) + if (mtrlHandle == null) + continue; + + PathDataHandler.Split(mtrlHandle->ResourceHandle.FileName.AsSpan(), out var path, out _); + var fileName = ByteString.FromSpanUnsafe(path, true); + if (fileName == needle) result.Add(new MaterialInfo(index, type, i, j)); } } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index d5b4fa39..236c7051 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -155,7 +155,7 @@ internal partial record ResolveContext var imcFileData = imc->GetDataSpan(); if (imcFileData.IsEmpty) { - Penumbra.Log.Warning($"IMC resource handle with path {GetResourceHandlePath(imc, false)} doesn't have a valid data span"); + Penumbra.Log.Warning($"IMC resource handle with path {imc->FileName.AsByteString()} doesn't have a valid data span"); return variant.Id; } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 7c8da41f..e38bf4f6 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -111,12 +111,18 @@ internal unsafe partial record ResolveContext( if (resourceHandle == null) throw new ArgumentNullException(nameof(resourceHandle)); - var fullPath = Utf8GamePath.FromByteString(GetResourceHandlePath(resourceHandle), out var p) ? new FullPath(p) : FullPath.Empty; + var fileName = resourceHandle->FileName.AsSpan(); + var additionalData = ByteString.Empty; + if (PathDataHandler.Split(fileName, out fileName, out var data)) + additionalData = ByteString.FromSpanUnsafe(data, false).Clone(); + + var fullPath = Utf8GamePath.FromSpan(fileName, out var p) ? new FullPath(p.Clone()) : FullPath.Empty; var node = new ResourceNode(type, objectAddress, (nint)resourceHandle, GetResourceHandleLength(resourceHandle), this) { - GamePath = gamePath, - FullPath = fullPath, + GamePath = gamePath, + FullPath = fullPath, + AdditionalData = additionalData, }; if (autoAdd) Global.Nodes.Add((gamePath, (nint)resourceHandle), node); @@ -365,21 +371,6 @@ internal unsafe partial record ResolveContext( return i >= 0 && i < array.Length ? array[i] : null; } - internal static ByteString GetResourceHandlePath(ResourceHandle* handle, bool stripPrefix = true) - { - if (handle == null) - return ByteString.Empty; - - var name = handle->FileName.AsByteString(); - if (name.IsEmpty) - return ByteString.Empty; - - if (stripPrefix && PathDataHandler.Split(name.Span, out var path, out _)) - name = ByteString.FromSpanUnsafe(path, name.IsNullTerminated, name.IsAsciiLowerCase, name.IsAscii); - - return name; - } - private static ulong GetResourceHandleLength(ResourceHandle* handle) { if (handle == null) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 7ec75893..e74edb91 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -1,4 +1,5 @@ using Penumbra.Api.Enums; +using Penumbra.String; using Penumbra.String.Classes; using ChangedItemIcon = Penumbra.UI.ChangedItemDrawer.ChangedItemIcon; @@ -15,6 +16,7 @@ public class ResourceNode : ICloneable public readonly nint ResourceHandle; public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; + public ByteString AdditionalData; public readonly ulong Length; public readonly List Children; internal ResolveContext? ResolveContext; @@ -40,6 +42,7 @@ public class ResourceNode : ICloneable ObjectAddress = objectAddress; ResourceHandle = resourceHandle; PossibleGamePaths = Array.Empty(); + AdditionalData = ByteString.Empty; Length = length; Children = new List(); ResolveContext = resolveContext; @@ -56,6 +59,7 @@ public class ResourceNode : ICloneable ResourceHandle = other.ResourceHandle; PossibleGamePaths = other.PossibleGamePaths; FullPath = other.FullPath; + AdditionalData = other.AdditionalData; Length = other.Length; Children = other.Children; ResolveContext = other.ResolveContext; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index d31f3e52..3ada77df 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -5,6 +5,7 @@ using OtterGui.Raii; using OtterGui; using Penumbra.Interop.ResourceTree; using Penumbra.UI.Classes; +using Penumbra.String; namespace Penumbra.UI.AdvancedWindow; @@ -177,6 +178,9 @@ public class ResourceTreeViewer return NodeVisibility.Hidden; } + string GetAdditionalDataSuffix(ByteString data) + => !debugMode || data.IsEmpty ? string.Empty : $"\n\nAdditional Data: {data}"; + foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { var visibility = GetNodeVisibility(resourceNode); @@ -260,13 +264,13 @@ public class ResourceTreeViewer ImGui.Selectable(resourceNode.FullPath.ToPath(), false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); if (ImGui.IsItemClicked()) ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); - ImGuiUtil.HoverTooltip($"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard."); + ImGuiUtil.HoverTooltip($"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } else { ImGui.Selectable("(unavailable)", false, ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); - ImGuiUtil.HoverTooltip("The actual path to this file is unavailable.\nIt may be managed by another plug-in."); + ImGuiUtil.HoverTooltip($"The actual path to this file is unavailable.\nIt may be managed by another plug-in.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } mutedColor.Dispose(); From f4bdbcac5338f6bb7deb5e021ca2e4d6236de739 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 30 May 2024 23:09:26 +0200 Subject: [PATCH 0631/1381] Make Resource Trees honor Incognito Mode --- Penumbra/Interop/ResourceTree/ResourceTree.cs | 26 ++++++----- .../ResourceTree/ResourceTreeFactory.cs | 43 ++++++++++--------- Penumbra/Services/StaticServiceManager.cs | 2 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 6 +-- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 17 +++++--- .../ResourceTreeViewerFactory.cs | 13 ++++++ Penumbra/UI/ChangedItemDrawer.cs | 7 ++- Penumbra/UI/CollectionTab/CollectionPanel.cs | 11 +++-- .../UI/CollectionTab/CollectionSelector.cs | 8 ++-- Penumbra/UI/CollectionTab/InheritanceUi.cs | 4 +- Penumbra/UI/IncognitoService.cs | 29 +++++++++++++ Penumbra/UI/Tabs/CollectionsTab.cs | 25 ++++------- Penumbra/UI/Tabs/OnScreenTab.cs | 7 +-- 13 files changed, 123 insertions(+), 75 deletions(-) create mode 100644 Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs create mode 100644 Penumbra/UI/IncognitoService.cs diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index dac86e44..fc8c805a 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -15,6 +15,7 @@ namespace Penumbra.Interop.ResourceTree; public class ResourceTree { public readonly string Name; + public readonly string AnonymizedName; public readonly int GameObjectIndex; public readonly nint GameObjectAddress; public readonly nint DrawObjectAddress; @@ -22,6 +23,7 @@ public class ResourceTree public readonly bool PlayerRelated; public readonly bool Networked; public readonly string CollectionName; + public readonly string AnonymizedCollectionName; public readonly List Nodes; public readonly HashSet FlatNodes; @@ -29,18 +31,20 @@ public class ResourceTree public CustomizeData CustomizeData; public GenderRace RaceCode; - public ResourceTree(string name, int gameObjectIndex, nint gameObjectAddress, nint drawObjectAddress, bool localPlayerRelated, bool playerRelated, bool networked, string collectionName) + public ResourceTree(string name, string anonymizedName, int gameObjectIndex, nint gameObjectAddress, nint drawObjectAddress, bool localPlayerRelated, bool playerRelated, bool networked, string collectionName, string anonymizedCollectionName) { - Name = name; - GameObjectIndex = gameObjectIndex; - GameObjectAddress = gameObjectAddress; - DrawObjectAddress = drawObjectAddress; - LocalPlayerRelated = localPlayerRelated; - Networked = networked; - PlayerRelated = playerRelated; - CollectionName = collectionName; - Nodes = new List(); - FlatNodes = new HashSet(); + Name = name; + AnonymizedName = anonymizedName; + GameObjectIndex = gameObjectIndex; + GameObjectAddress = gameObjectAddress; + DrawObjectAddress = drawObjectAddress; + LocalPlayerRelated = localPlayerRelated; + Networked = networked; + PlayerRelated = playerRelated; + CollectionName = collectionName; + AnonymizedCollectionName = anonymizedCollectionName; + Nodes = new List(); + FlatNodes = new HashSet(); } public void ProcessPostfix(Action action) diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index ae7187f0..a722e344 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -72,10 +72,10 @@ public class ResourceTreeFactory( return null; var localPlayerRelated = cache.IsLocalPlayerRelated(character); - var (name, related) = GetCharacterName(character, cache); + var (name, anonymizedName, related) = GetCharacterName(character); var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; - var tree = new ResourceTree(name, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, - networked, collectionResolveData.ModCollection.Name); + var tree = new ResourceTree(name, anonymizedName, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, + networked, collectionResolveData.ModCollection.Name, collectionResolveData.ModCollection.AnonymizedName); var globalContext = new GlobalResolveContext(identifier, collectionResolveData.ModCollection, cache, (flags & Flags.WithUiData) != 0); using (var _ = pathState.EnterInternalResolve()) @@ -157,27 +157,30 @@ public class ResourceTreeFactory( } } - private unsafe (string Name, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character, - TreeBuildCache cache) + private unsafe (string Name, string AnonymizedName, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character) { var identifier = actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); - switch (identifier.Type) - { - case IdentifierType.Player: return (identifier.PlayerName.ToString(), true); - case IdentifierType.Owned: - var ownerChara = objects.Objects.CreateObjectReference(owner) as Dalamud.Game.ClientState.Objects.Types.Character; - if (ownerChara != null) - { - var ownerName = GetCharacterName(ownerChara, cache); - return ($"[{ownerName.Name}] {character.Name} ({identifier.Kind.ToName()})", ownerName.PlayerRelated); - } - - break; - } - - return ($"{character.Name} ({identifier.Kind.ToName()})", false); + var identifierStr = identifier.ToString(); + return (identifierStr, identifier.Incognito(identifierStr), IsPlayerRelated(identifier, owner)); } + private unsafe bool IsPlayerRelated(Dalamud.Game.ClientState.Objects.Types.Character? character) + { + if (character == null) + return false; + + var identifier = actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); + return IsPlayerRelated(identifier, owner); + } + + private bool IsPlayerRelated(ActorIdentifier identifier, Actor owner) + => identifier.Type switch + { + IdentifierType.Player => true, + IdentifierType.Owned => IsPlayerRelated(objects.Objects.CreateObjectReference(owner) as Dalamud.Game.ClientState.Objects.Types.Character), + _ => false, + }; + [Flags] public enum Flags { diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 0c6648ba..146d7ee0 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -149,6 +149,7 @@ public static class StaticServiceManager private static ServiceManager AddInterface(this ServiceManager services) => services.AddSingleton() .AddSingleton() + .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() @@ -181,6 +182,7 @@ public static class StaticServiceManager .AddSingleton() .AddSingleton() .AddSingleton() + .AddSingleton() .AddSingleton(p => new Diagnostics(p)); private static ServiceManager AddModEditor(this ServiceManager services) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 6b48a048..af01047b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -585,7 +585,8 @@ public partial class ModEditWindow : Window, IDisposable Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, - ChangedItemDrawer changedItemDrawer, ObjectManager objects, IFramework framework, CharacterBaseDestructor characterBaseDestructor) + ResourceTreeViewerFactory resourceTreeViewerFactory, ObjectManager objects, IFramework framework, + CharacterBaseDestructor characterBaseDestructor) : base(WindowBaseLabel) { _performance = performance; @@ -618,8 +619,7 @@ public partial class ModEditWindow : Window, IDisposable _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); _resourceTreeFactory = resourceTreeFactory; - _quickImportViewer = - new ResourceTreeViewer(_config, resourceTreeFactory, changedItemDrawer, 2, OnQuickImportRefresh, DrawQuickImportActions); + _quickImportViewer = resourceTreeViewerFactory.Create(2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModEditWindow); IsOpen = _config is { OpenWindowAtStart: true, Ephemeral.AdvancedEditingOpen: true }; } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 3ada77df..c0c49e47 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -6,6 +6,7 @@ using OtterGui; using Penumbra.Interop.ResourceTree; using Penumbra.UI.Classes; using Penumbra.String; +using Penumbra.UI.Tabs; namespace Penumbra.UI.AdvancedWindow; @@ -17,6 +18,7 @@ public class ResourceTreeViewer private readonly Configuration _config; private readonly ResourceTreeFactory _treeFactory; private readonly ChangedItemDrawer _changedItemDrawer; + private readonly IncognitoService _incognito; private readonly int _actionCapacity; private readonly Action _onRefresh; private readonly Action _drawActions; @@ -29,11 +31,12 @@ public class ResourceTreeViewer private Task? _task; public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, - int actionCapacity, Action onRefresh, Action drawActions) + IncognitoService incognito, int actionCapacity, Action onRefresh, Action drawActions) { _config = config; _treeFactory = treeFactory; _changedItemDrawer = changedItemDrawer; + _incognito = incognito; _actionCapacity = actionCapacity; _onRefresh = onRefresh; _drawActions = drawActions; @@ -75,7 +78,7 @@ public class ResourceTreeViewer using (var c = ImRaii.PushColor(ImGuiCol.Text, CategoryColor(category).Value())) { - var isOpen = ImGui.CollapsingHeader($"{tree.Name}##{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); + var isOpen = ImGui.CollapsingHeader($"{(_incognito.IncognitoMode ? tree.AnonymizedName : tree.Name)}###{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); if (debugMode) { using var _ = ImRaii.PushFont(UiBuilder.MonoFont); @@ -89,7 +92,7 @@ public class ResourceTreeViewer using var id = ImRaii.PushId(index); - ImGui.TextUnformatted($"Collection: {tree.CollectionName}"); + ImGui.TextUnformatted($"Collection: {(_incognito.IncognitoMode ? tree.AnonymizedCollectionName : tree.CollectionName)}"); using var table = ImRaii.Table("##ResourceTree", _actionCapacity > 0 ? 4 : 3, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); @@ -137,10 +140,14 @@ public class ResourceTreeViewer ImGui.SameLine(0, checkPadding); - _changedItemDrawer.DrawTypeFilter(ref _typeFilter, -yOffset); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() - yOffset); + using (ImRaii.Child("##typeFilter", new Vector2(ImGui.GetContentRegionAvail().X, ChangedItemDrawer.TypeFilterIconSize.Y))) + _changedItemDrawer.DrawTypeFilter(ref _typeFilter); - ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - checkSpacing - ImGui.GetFrameHeightWithSpacing()); ImGui.InputTextWithHint("##TreeNameFilter", "Filter by Character/Entity Name...", ref _nameFilter, 128); + ImGui.SameLine(0, checkSpacing); + _incognito.DrawToggle(); } private Task RefreshCharacterList() diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs new file mode 100644 index 00000000..91dab6cb --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs @@ -0,0 +1,13 @@ +using Penumbra.Interop.ResourceTree; + +namespace Penumbra.UI.AdvancedWindow; + +public class ResourceTreeViewerFactory( + Configuration config, + ResourceTreeFactory treeFactory, + ChangedItemDrawer changedItemDrawer, + IncognitoService incognito) +{ + public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) + => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions); +} diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 638afef0..29a1f291 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -212,7 +212,7 @@ public class ChangedItemDrawer : IDisposable return; var typeFilter = _config.Ephemeral.ChangedItemFilter; - if (DrawTypeFilter(ref typeFilter, 0.0f)) + if (DrawTypeFilter(ref typeFilter)) { _config.Ephemeral.ChangedItemFilter = typeFilter; _config.Ephemeral.Save(); @@ -220,7 +220,7 @@ public class ChangedItemDrawer : IDisposable } /// Draw a header line with the different icon types to filter them. - public bool DrawTypeFilter(ref ChangedItemIcon typeFilter, float yOffset) + public bool DrawTypeFilter(ref ChangedItemIcon typeFilter) { var ret = false; using var _ = ImRaii.PushId("ChangedItemIconFilter"); @@ -233,7 +233,6 @@ public class ChangedItemDrawer : IDisposable var ret = false; var icon = _icons[type]; var flag = typeFilter.HasFlag(type); - ImGui.SetCursorPosY(ImGui.GetCursorPosY() + yOffset); ImGui.Image(icon.ImGuiHandle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); if (ImGui.IsItemClicked(ImGuiMouseButton.Left)) { @@ -267,7 +266,7 @@ public class ChangedItemDrawer : IDisposable ImGui.SameLine(); } - ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionMax().X - size.X, ImGui.GetCursorPosY() + yOffset)); + ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); ImGui.Image(_icons[AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, typeFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : typeFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index bb22e6a7..cb4dbe20 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -31,6 +31,7 @@ public sealed class CollectionPanel : IDisposable private readonly InheritanceUi _inheritanceUi; private readonly ModStorage _mods; private readonly FilenameService _fileNames; + private readonly IncognitoService _incognito; private readonly IFontHandle _nameFont; private static readonly IReadOnlyDictionary Buttons = CreateButtons(); @@ -41,7 +42,8 @@ public sealed class CollectionPanel : IDisposable private int _draggedIndividualAssignment = -1; public CollectionPanel(DalamudPluginInterface pi, CommunicatorService communicator, CollectionManager manager, - CollectionSelector selector, ActorManager actors, ITargetManager targets, ModStorage mods, FilenameService fileNames) + CollectionSelector selector, ActorManager actors, ITargetManager targets, ModStorage mods, FilenameService fileNames, + IncognitoService incognito) { _collections = manager.Storage; _active = manager.Active; @@ -50,8 +52,9 @@ public sealed class CollectionPanel : IDisposable _targets = targets; _mods = mods; _fileNames = fileNames; + _incognito = incognito; _individualAssignmentUi = new IndividualAssignmentUi(communicator, actors, manager); - _inheritanceUi = new InheritanceUi(manager, _selector); + _inheritanceUi = new InheritanceUi(manager, incognito); _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); } @@ -415,7 +418,7 @@ public sealed class CollectionPanel : IDisposable /// Respect incognito mode for names of identifiers. private string Name(ActorIdentifier id, string? name) - => _selector.IncognitoMode && id.Type is IdentifierType.Player or IdentifierType.Owned + => _incognito.IncognitoMode && id.Type is IdentifierType.Player or IdentifierType.Owned ? id.Incognito(name) : name ?? id.ToString(); @@ -423,7 +426,7 @@ public sealed class CollectionPanel : IDisposable private string Name(ModCollection? collection) => collection == null ? "Unassigned" : collection == ModCollection.Empty ? "Use No Mods" : - _selector.IncognitoMode ? collection.AnonymizedName : collection.Name; + _incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; private void DrawIndividualButton(string intro, Vector2 width, string tooltip, char suffix, params ActorIdentifier[] identifiers) { diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index fac85d4d..24d3f591 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -17,13 +17,12 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl private readonly CollectionStorage _storage; private readonly ActiveCollections _active; private readonly TutorialService _tutorial; + private readonly IncognitoService _incognito; private ModCollection? _dragging; - public bool IncognitoMode; - public CollectionSelector(Configuration config, CommunicatorService communicator, CollectionStorage storage, ActiveCollections active, - TutorialService tutorial) + TutorialService tutorial, IncognitoService incognito) : base([], Flags.Delete | Flags.Add | Flags.Duplicate | Flags.Filter) { _config = config; @@ -31,6 +30,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl _storage = storage; _active = active; _tutorial = tutorial; + _incognito = incognito; _communicator.CollectionChange.Subscribe(OnCollectionChange, CollectionChange.Priority.CollectionSelector); // Set items. @@ -109,7 +109,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl } private string Name(ModCollection collection) - => IncognitoMode ? collection.AnonymizedName : collection.Name; + => _incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; private void OnCollectionChange(CollectionType type, ModCollection? old, ModCollection? @new, string _3) { diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index 2290592d..418fe52c 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -9,7 +9,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.CollectionTab; -public class InheritanceUi(CollectionManager collectionManager, CollectionSelector selector) : IUiService +public class InheritanceUi(CollectionManager collectionManager, IncognitoService incognito) : IUiService { private const int InheritedCollectionHeight = 9; private const string InheritanceDragDropLabel = "##InheritanceMove"; @@ -312,5 +312,5 @@ public class InheritanceUi(CollectionManager collectionManager, CollectionSelect } private string Name(ModCollection collection) - => selector.IncognitoMode ? collection.AnonymizedName : collection.Name; + => incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; } diff --git a/Penumbra/UI/IncognitoService.cs b/Penumbra/UI/IncognitoService.cs new file mode 100644 index 00000000..d4b1828f --- /dev/null +++ b/Penumbra/UI/IncognitoService.cs @@ -0,0 +1,29 @@ +using Dalamud.Interface.Utility; +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using Penumbra.UI.Classes; +using OtterGui.Raii; + +namespace Penumbra.UI; + +public class IncognitoService(TutorialService tutorial) +{ + public bool IncognitoMode; + + public void DrawToggle(float? buttonWidth = null) + { + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); + using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()) + .Push(ImGuiCol.Border, ColorId.FolderExpanded.Value()); + if (ImGuiUtil.DrawDisabledButton( + $"{(IncognitoMode ? FontAwesomeIcon.Eye : FontAwesomeIcon.EyeSlash).ToIconString()}###IncognitoMode", + new Vector2(buttonWidth ?? ImGui.GetFrameHeightWithSpacing(), ImGui.GetFrameHeight()), string.Empty, false, true)) + IncognitoMode = !IncognitoMode; + var hovered = ImGui.IsItemHovered(); + tutorial.OpenTutorial(BasicTutorialSteps.Incognito); + color.Pop(2); + if (hovered) + ImGui.SetTooltip(IncognitoMode ? "Toggle incognito mode off." : "Toggle incognito mode on."); + } +} diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index fe1471b3..1eaece50 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -21,6 +21,7 @@ public sealed class CollectionsTab : IDisposable, ITab private readonly CollectionSelector _selector; private readonly CollectionPanel _panel; private readonly TutorialService _tutorial; + private readonly IncognitoService _incognito; public enum PanelMode { @@ -40,13 +41,14 @@ public sealed class CollectionsTab : IDisposable, ITab } } - public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, + public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, IncognitoService incognito, CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial, FilenameService fileNames) { - _config = configuration.Ephemeral; - _tutorial = tutorial; - _selector = new CollectionSelector(configuration, communicator, collectionManager.Storage, collectionManager.Active, _tutorial); - _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage, fileNames); + _config = configuration.Ephemeral; + _tutorial = tutorial; + _incognito = incognito; + _selector = new CollectionSelector(configuration, communicator, collectionManager.Storage, collectionManager.Active, _tutorial, incognito); + _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage, fileNames, incognito); } public void Dispose() @@ -116,18 +118,7 @@ public sealed class CollectionsTab : IDisposable, ITab _tutorial.OpenTutorial(BasicTutorialSteps.CollectionDetails); ImGui.SameLine(); - style.Push(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); - color.Push(ImGuiCol.Text, ColorId.FolderExpanded.Value()) - .Push(ImGuiCol.Border, ColorId.FolderExpanded.Value()); - if (ImGuiUtil.DrawDisabledButton( - $"{(_selector.IncognitoMode ? FontAwesomeIcon.Eye : FontAwesomeIcon.EyeSlash).ToIconString()}###IncognitoMode", - buttonSize with { X = withSpacing }, string.Empty, false, true)) - _selector.IncognitoMode = !_selector.IncognitoMode; - var hovered = ImGui.IsItemHovered(); - _tutorial.OpenTutorial(BasicTutorialSteps.Incognito); - color.Pop(2); - if (hovered) - ImGui.SetTooltip(_selector.IncognitoMode ? "Toggle incognito mode off." : "Toggle incognito mode on."); + _incognito.DrawToggle(withSpacing); } private void DrawPanel() diff --git a/Penumbra/UI/Tabs/OnScreenTab.cs b/Penumbra/UI/Tabs/OnScreenTab.cs index 09772d8e..787e07a1 100644 --- a/Penumbra/UI/Tabs/OnScreenTab.cs +++ b/Penumbra/UI/Tabs/OnScreenTab.cs @@ -1,18 +1,15 @@ using OtterGui.Widgets; -using Penumbra.Interop.ResourceTree; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.Tabs; public class OnScreenTab : ITab { - private readonly Configuration _config; private readonly ResourceTreeViewer _viewer; - public OnScreenTab(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer) + public OnScreenTab(ResourceTreeViewerFactory resourceTreeViewerFactory) { - _config = config; - _viewer = new ResourceTreeViewer(_config, treeFactory, changedItemDrawer, 0, delegate { }, delegate { }); + _viewer = resourceTreeViewerFactory.Create(0, delegate { }, delegate { }); } public ReadOnlySpan Label From c7046ec0069bef1ee9d98602589740ed0d3a74bb Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 31 May 2024 01:05:05 +0200 Subject: [PATCH 0632/1381] ResourceTree: Add name/path filter --- Penumbra/Interop/ResourceTree/ResourceNode.cs | 2 - .../ResourceTree/ResourceTreeFactory.cs | 3 - .../UI/AdvancedWindow/ResourceTreeViewer.cs | 74 +++++++++++++++---- 3 files changed, 60 insertions(+), 19 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index e74edb91..9c911791 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -10,7 +10,6 @@ public class ResourceNode : ICloneable public string? Name; public string? FallbackName; public ChangedItemIcon Icon; - public ChangedItemIcon DescendentIcons; public readonly ResourceType Type; public readonly nint ObjectAddress; public readonly nint ResourceHandle; @@ -53,7 +52,6 @@ public class ResourceNode : ICloneable Name = other.Name; FallbackName = other.FallbackName; Icon = other.Icon; - DescendentIcons = other.DescendentIcons; Type = other.Type; ObjectAddress = other.ObjectAddress; ResourceHandle = other.ResourceHandle; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index a722e344..5a190e52 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -116,9 +116,6 @@ public class ResourceTreeFactory( { if (node.Name == parent?.Name) node.Name = null; - - if (parent != null) - parent.DescendentIcons |= node.Icon | node.DescendentIcons; }); } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index c0c49e47..5f376b26 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -24,9 +24,12 @@ public class ResourceTreeViewer private readonly Action _drawActions; private readonly HashSet _unfolded; + private readonly Dictionary _filterCache; + private TreeCategory _categoryFilter; private ChangedItemDrawer.ChangedItemIcon _typeFilter; private string _nameFilter; + private string _nodeFilter; private Task? _task; @@ -40,11 +43,14 @@ public class ResourceTreeViewer _actionCapacity = actionCapacity; _onRefresh = onRefresh; _drawActions = drawActions; - _unfolded = new HashSet(); + _unfolded = []; + + _filterCache = []; _categoryFilter = AllCategories; _typeFilter = ChangedItemDrawer.AllFlags; _nameFilter = string.Empty; + _nodeFilter = string.Empty; } public void Draw() @@ -107,7 +113,7 @@ public class ResourceTreeViewer (_actionCapacity - 1) * 3 * ImGuiHelpers.GlobalScale + _actionCapacity * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); - DrawNodes(tree.Nodes, 0, unchecked(tree.DrawObjectAddress * 31)); + DrawNodes(tree.Nodes, 0, unchecked(tree.DrawObjectAddress * 31), 0); } } } @@ -140,14 +146,22 @@ public class ResourceTreeViewer ImGui.SameLine(0, checkPadding); + var filterChanged = false; ImGui.SetCursorPosY(ImGui.GetCursorPosY() - yOffset); using (ImRaii.Child("##typeFilter", new Vector2(ImGui.GetContentRegionAvail().X, ChangedItemDrawer.TypeFilterIconSize.Y))) - _changedItemDrawer.DrawTypeFilter(ref _typeFilter); + filterChanged |= _changedItemDrawer.DrawTypeFilter(ref _typeFilter); - ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - checkSpacing - ImGui.GetFrameHeightWithSpacing()); - ImGui.InputTextWithHint("##TreeNameFilter", "Filter by Character/Entity Name...", ref _nameFilter, 128); + var fieldWidth = (ImGui.GetContentRegionAvail().X - checkSpacing * 2.0f - ImGui.GetFrameHeightWithSpacing()) / 2.0f; + ImGui.SetNextItemWidth(fieldWidth); + filterChanged |= ImGui.InputTextWithHint("##TreeNameFilter", "Filter by Character/Entity Name...", ref _nameFilter, 128); + ImGui.SameLine(0, checkSpacing); + ImGui.SetNextItemWidth(fieldWidth); + filterChanged |= ImGui.InputTextWithHint("##NodeFilter", "Filter by Item/Part Name or Path...", ref _nodeFilter, 128); ImGui.SameLine(0, checkSpacing); _incognito.DrawToggle(); + + if (filterChanged) + _filterCache.Clear(); } private Task RefreshCharacterList() @@ -161,36 +175,68 @@ public class ResourceTreeViewer } finally { + _filterCache.Clear(); _unfolded.Clear(); _onRefresh(); } }); - private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash) + private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) { var debugMode = _config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); var cellHeight = _actionCapacity > 0 ? frameHeight : 0.0f; - NodeVisibility GetNodeVisibility(ResourceNode node) + bool MatchesFilter(ResourceNode node, ChangedItemDrawer.ChangedItemIcon filterIcon) + { + if (!_typeFilter.HasFlag(filterIcon)) + return false; + + if (_nodeFilter.Length == 0) + return true; + + return node.Name != null && node.Name.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || node.FullPath.FullName.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || node.FullPath.InternalName.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); + } + + NodeVisibility CalculateNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) { if (node.Internal && !debugMode) return NodeVisibility.Hidden; - if (_typeFilter.HasFlag(node.Icon)) + var filterIcon = node.Icon != 0 ? node.Icon : parentFilterIcon; + if (MatchesFilter(node, filterIcon)) return NodeVisibility.Visible; - if ((_typeFilter & node.DescendentIcons) != 0) - return NodeVisibility.DescendentsOnly; + + foreach (var child in node.Children) + { + if (GetNodeVisibility(unchecked(nodePathHash * 31 + child.ResourceHandle), child, filterIcon) != NodeVisibility.Hidden) + return NodeVisibility.DescendentsOnly; + } return NodeVisibility.Hidden; } + NodeVisibility GetNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) + { + if (!_filterCache.TryGetValue(nodePathHash, out var visibility)) + { + visibility = CalculateNodeVisibility(nodePathHash, node, parentFilterIcon); + _filterCache.Add(nodePathHash, visibility); + } + return visibility; + } + string GetAdditionalDataSuffix(ByteString data) => !debugMode || data.IsEmpty ? string.Empty : $"\n\nAdditional Data: {data}"; foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { - var visibility = GetNodeVisibility(resourceNode); + var nodePathHash = unchecked(pathHash + resourceNode.ResourceHandle); + + var visibility = GetNodeVisibility(nodePathHash, resourceNode, parentFilterIcon); if (visibility == NodeVisibility.Hidden) continue; @@ -199,14 +245,14 @@ public class ResourceTreeViewer using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, textColorInternal, resourceNode.Internal); - var nodePathHash = unchecked(pathHash + resourceNode.ResourceHandle); + var filterIcon = resourceNode.Icon != 0 ? resourceNode.Icon : parentFilterIcon; using var id = ImRaii.PushId(index); ImGui.TableNextColumn(); var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) { - var hasVisibleChildren = resourceNode.Children.Any(child => GetNodeVisibility(child) != NodeVisibility.Hidden); + var hasVisibleChildren = resourceNode.Children.Any(child => GetNodeVisibility(unchecked(nodePathHash * 31 + child.ResourceHandle), child, filterIcon) != NodeVisibility.Hidden); var unfoldable = hasVisibleChildren && visibility != NodeVisibility.DescendentsOnly; if (unfoldable) { @@ -291,7 +337,7 @@ public class ResourceTreeViewer } if (unfolded) - DrawNodes(resourceNode.Children, level + 1, unchecked(nodePathHash * 31)); + DrawNodes(resourceNode.Children, level + 1, unchecked(nodePathHash * 31), filterIcon); } } From 81fdbf6ccff729daedc003eba80b3969a4f799f2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 31 May 2024 16:59:51 +0200 Subject: [PATCH 0633/1381] Small cleanup. --- Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs index e8a27a74..b8faadf7 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -321,8 +321,8 @@ public sealed class ModGroupEditDrawer( && (!_draggingAcross || (_dragDropGroup != null && group is MultiModGroup { Options.Count: >= IModGroup.MaxMultiOptions }))) return; - using var target = ImRaii.DragDropTarget(); - if (!target.Success || !DragDropTarget.CheckPayload(_draggingAcross ? AcrossGroupsLabel : InsideGroupLabel)) + using var target = ImUtf8.DragDropTarget(); + if (!target.IsDropping(_draggingAcross ? AcrossGroupsLabel : InsideGroupLabel)) return; if (_dragDropGroup != null && _dragDropOption != null) From 67bb95f6e64232480ced89d33318edc976206e63 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 31 May 2024 17:00:40 +0200 Subject: [PATCH 0634/1381] Update submodules. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 1d936516..0b5afffd 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 1d9365164655a7cb38172e1311e15e19b1def6db +Subproject commit 0b5afffda19d3e16aec9e8682d18c8f11f67f1c6 diff --git a/Penumbra.GameData b/Penumbra.GameData index f2cea65b..29b71cf7 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f2cea65b83b2d6cb0d03339e8f76aed8102a41d5 +Subproject commit 29b71cf7b3cc68995d38f0954fa38c4b9500a81d From f61bd8bb8a5cd2bb45156803d1eddd8b8d74b8f9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 31 May 2024 19:37:24 +0200 Subject: [PATCH 0635/1381] Update Changelog and improve metamanipulation display in advanced editing. --- Penumbra/Mods/Editor/ModMetaEditor.cs | 58 +++++++------------ .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 30 ++++++---- Penumbra/UI/Changelog.cs | 47 ++++++++------- 3 files changed, 64 insertions(+), 71 deletions(-) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 829161f5..86d5e02e 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,3 +1,4 @@ +using System.Collections.Frozen; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; @@ -14,13 +15,19 @@ public class ModMetaEditor(ModManager modManager) private readonly HashSet _rsp = []; private readonly HashSet _globalEqp = []; - public int OtherImcCount { get; private set; } - public int OtherEqpCount { get; private set; } - public int OtherEqdpCount { get; private set; } - public int OtherGmpCount { get; private set; } - public int OtherEstCount { get; private set; } - public int OtherRspCount { get; private set; } - public int OtherGlobalEqpCount { get; private set; } + public sealed class OtherOptionData : List + { + public int TotalCount; + + public new void Clear() + { + TotalCount = 0; + base.Clear(); + } + } + + public readonly FrozenDictionary OtherData = + Enum.GetValues().ToFrozenDictionary(t => t, _ => new OtherOptionData()); public bool Changes { get; private set; } @@ -114,13 +121,9 @@ public class ModMetaEditor(ModManager modManager) public void Load(Mod mod, IModDataContainer currentOption) { - OtherImcCount = 0; - OtherEqpCount = 0; - OtherEqdpCount = 0; - OtherGmpCount = 0; - OtherEstCount = 0; - OtherRspCount = 0; - OtherGlobalEqpCount = 0; + foreach (var type in Enum.GetValues()) + OtherData[type].Clear(); + foreach (var option in mod.AllDataContainers) { if (option == currentOption) @@ -128,30 +131,9 @@ public class ModMetaEditor(ModManager modManager) foreach (var manip in option.Manipulations) { - switch (manip.ManipulationType) - { - case MetaManipulation.Type.Imc: - ++OtherImcCount; - break; - case MetaManipulation.Type.Eqdp: - ++OtherEqdpCount; - break; - case MetaManipulation.Type.Eqp: - ++OtherEqpCount; - break; - case MetaManipulation.Type.Est: - ++OtherEstCount; - break; - case MetaManipulation.Type.Gmp: - ++OtherGmpCount; - break; - case MetaManipulation.Type.Rsp: - ++OtherRspCount; - break; - case MetaManipulation.Type.GlobalEqp: - ++OtherGlobalEqpCount; - break; - } + var data = OtherData[manip.ManipulationType]; + ++data.TotalCount; + data.Add(option.GetFullName()); } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 6f542377..a2a6925a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -66,37 +66,45 @@ public partial class ModEditWindow return; DrawEditHeader(_editor.MetaEditor.Eqp, "Equipment Parameter Edits (EQP)###EQP", 5, EqpRow.Draw, EqpRow.DrawNew, - _editor.MetaEditor.OtherEqpCount); + _editor.MetaEditor.OtherData[MetaManipulation.Type.Eqp]); DrawEditHeader(_editor.MetaEditor.Eqdp, "Racial Model Edits (EQDP)###EQDP", 7, EqdpRow.Draw, EqdpRow.DrawNew, - _editor.MetaEditor.OtherEqdpCount); - DrawEditHeader(_editor.MetaEditor.Imc, "Variant Edits (IMC)###IMC", 10, ImcRow.Draw, ImcRow.DrawNew, _editor.MetaEditor.OtherImcCount); + _editor.MetaEditor.OtherData[MetaManipulation.Type.Eqdp]); + DrawEditHeader(_editor.MetaEditor.Imc, "Variant Edits (IMC)###IMC", 10, ImcRow.Draw, ImcRow.DrawNew, + _editor.MetaEditor.OtherData[MetaManipulation.Type.Imc]); DrawEditHeader(_editor.MetaEditor.Est, "Extra Skeleton Parameters (EST)###EST", 7, EstRow.Draw, EstRow.DrawNew, - _editor.MetaEditor.OtherEstCount); + _editor.MetaEditor.OtherData[MetaManipulation.Type.Est]); DrawEditHeader(_editor.MetaEditor.Gmp, "Visor/Gimmick Edits (GMP)###GMP", 7, GmpRow.Draw, GmpRow.DrawNew, - _editor.MetaEditor.OtherGmpCount); + _editor.MetaEditor.OtherData[MetaManipulation.Type.Gmp]); DrawEditHeader(_editor.MetaEditor.Rsp, "Racial Scaling Edits (RSP)###RSP", 5, RspRow.Draw, RspRow.DrawNew, - _editor.MetaEditor.OtherRspCount); + _editor.MetaEditor.OtherData[MetaManipulation.Type.Rsp]); DrawEditHeader(_editor.MetaEditor.GlobalEqp, "Global Equipment Parameter Edits (Global EQP)###GEQP", 4, GlobalEqpRow.Draw, - GlobalEqpRow.DrawNew, _editor.MetaEditor.OtherGlobalEqpCount); + GlobalEqpRow.DrawNew, _editor.MetaEditor.OtherData[MetaManipulation.Type.GlobalEqp]); } /// The headers for the different meta changes all have basically the same structure for different types. private void DrawEditHeader(IReadOnlyCollection items, string label, int numColumns, - Action draw, - Action drawNew, int otherCount) + Action draw, Action drawNew, + ModMetaEditor.OtherOptionData otherOptionData) { const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.BordersInnerV; var oldPos = ImGui.GetCursorPosY(); var header = ImGui.CollapsingHeader($"{items.Count} {label}"); var newPos = ImGui.GetCursorPos(); - if (otherCount > 0) + if (otherOptionData.TotalCount > 0) { - var text = $"{otherCount} Edits in other Options"; + var text = $"{otherOptionData.TotalCount} Edits in other Options"; var size = ImGui.CalcTextSize(text).X; ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionAvail().X - size, oldPos + ImGui.GetStyle().FramePadding.Y)); ImGuiUtil.TextColored(ColorId.RedundantAssignment.Value() | 0xFF000000, text); + if (ImGui.IsItemHovered()) + { + using var tt = ImUtf8.Tooltip(); + foreach (var name in otherOptionData) + ImUtf8.Text(name); + } + ImGui.SetCursorPos(newPos); } diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 2b2cfa99..3f5a446a 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -47,19 +47,26 @@ public class PenumbraChangelog Add8_2_0(Changelog); Add8_3_0(Changelog); Add1_0_0_0(Changelog); - Add1_0_2_0(Changelog); - Add1_0_3_0(Changelog); + AddDummy(Changelog); + AddDummy(Changelog); + Add1_1_0_0(Changelog); } #region Changelogs - private static void Add1_0_3_0(Changelog log) - => log.NextVersion("Version 1.0.3.0") + private static void Add1_1_0_0(Changelog log) + => log.NextVersion("Version 1.1.0.0") .RegisterImportant( "This update comes, again, with a lot of very heavy backend changes (collections and groups) and thus may introduce new issues.") + .RegisterEntry("Updated to .net8 and XIV 6.58, using some new framework facilities to improve performance and stability.") + .RegisterHighlight( + "Added an experimental crash handler that is supposed to write a Penumbra.log file when the game crashes, containing Penumbra-specific information.") + .RegisterEntry("This is disabled by default. It can be enabled in Advanced Settings.", 1) .RegisterHighlight("Collections now have associated GUIDs as identifiers instead of their names, so they can now be renamed.") .RegisterEntry("Migrating those collections may introduce issues, please let me know as soon as possible if you encounter any.", 1) .RegisterEntry("A permanent (non-rolling) backup should be created before the migration in case of any issues.", 1) + .RegisterHighlight( + "Added predefined tags that can be setup in the Settings tab and can be more easily applied or removed from mods. (by DZD)") .RegisterHighlight( "A total rework of how options and groups are handled internally, and introduction of the first new group type, the IMC Group.") .RegisterEntry( @@ -75,9 +82,14 @@ public class PenumbraChangelog .RegisterEntry( "This can be used if something like a jacket or a stole is put onto an accessory to prevent it from being hidden in general.", 1) + .RegisterEntry( + "The first empty option in a single-select option group imported from a TTMP will now keep its location instead of being moved to the first option.") + .RegisterEntry("Further empty options are still removed.", 1) .RegisterHighlight( "Added a field to rename mods directly from the mod selector context menu, instead of moving them in the filesystem.") .RegisterEntry("You can choose which rename field (none, either one or both) to display in the settings.", 1) + .RegisterEntry("Added the characterglass.shpk shader file to special shader treatment to fix issues when replacing it. (By Ny)") + .RegisterEntry("Made it more obvious if a user has not set their root directory yet.") .RegisterEntry( "You can now paste your current clipboard text into the mod selector filter with a simple right-click as long as it is not focused.") .RegisterHighlight( @@ -88,29 +100,17 @@ public class PenumbraChangelog .RegisterEntry("Removed the auto-generated descriptions for newly created groups in Penumbra.") .RegisterEntry( "Made some improvements to the Advanced Editing window, for example a much better and more performant Hex Viewer for unstructured data was added.") - .RegisterEntry("Made a lot of further improvements on Model import/export (by ackwell).") + .RegisterEntry("Various improvements to model import/export by ackwell (throughout all patches).") + .RegisterEntry("Hovering over meta manipulations in other options in the advanced editing window now shows a list of those options.") .RegisterEntry("Reworked the API and IPC structure heavily.") + .RegisterImportant("This means some plugins interacting with Penumbra may not work correctly until they update.", 1) .RegisterEntry("Worked around the UI IPC possibly displacing all settings when the drawn additions became too big.") + .RegisterEntry("Fixed an issue where reloading a mod did not ensure settings for that mod being correct afterwards.") + .RegisterEntry("Fixed some issues with the file sizes of compressed files.") .RegisterEntry("Fixed an issue with merging and deduplicating mods.") .RegisterEntry("Fixed a crash when scanning for mods without access rights to the folder.") .RegisterEntry( - "Made plugin conform to Dalamud requirements by adding a punchline and another button to open the menu from the installer."); - - private static void Add1_0_2_0(Changelog log) - => log.NextVersion("Version 1.0.2.0") - .RegisterEntry("Updated to .net8 and XIV 6.58, using some new framework facilities to improve performance and stability.") - .RegisterHighlight( - "Added an experimental crash handler that is supposed to write a Penumbra.log file when the game crashes, containing Penumbra-specific information.") - .RegisterEntry("Various improvements to model import/export by ackwell (throughout all patches).") - .RegisterHighlight( - "Added predefined tags that can be setup in the Settings tab and can be more easily applied or removed from mods. (by DZD)") - .RegisterEntry( - "The first empty option in a single-select option group imported from a TTMP will now keep its location instead of being moved to the first option.") - .RegisterEntry("Further empty options are still removed.", 1) - .RegisterEntry("Made it more obvious if a user has not set their root directory yet.") - .RegisterEntry("Added the characterglass.shpk shader file to special shader treatment to fix issues when replacing it. (By Ny)") - .RegisterEntry("Fixed some issues with the file sizes of compressed files.") - .RegisterEntry("Fixed an issue where reloading a mod did not ensure settings for that mod being correct afterwards.") + "Made plugin conform to Dalamud requirements by adding a punchline and another button to open the menu from the installer.") .RegisterEntry("Added an option to automatically redraw the player character when saving files. (1.0.0.8)") .RegisterEntry("Fixed issue with manipulating mods not triggering some events. (1.0.0.7)") .RegisterEntry("Fixed issue with temporary mods not triggering some events. (1.0.0.6)") @@ -762,6 +762,9 @@ public class PenumbraChangelog #endregion + private static void AddDummy(Changelog log) + => log.NextVersion(string.Empty); + private (int, ChangeLogDisplayType) ConfigData() => (_config.Ephemeral.LastSeenVersion, _config.ChangeLogDisplayType); From ce11bec985770af2f9bfdaf68f8e265823dfa38a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 31 May 2024 22:55:22 +0200 Subject: [PATCH 0636/1381] Use strings for global eqp. --- Penumbra/Meta/Manipulations/GlobalEqpType.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Penumbra/Meta/Manipulations/GlobalEqpType.cs b/Penumbra/Meta/Manipulations/GlobalEqpType.cs index d57af1d9..1a7396f9 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpType.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpType.cs @@ -1,5 +1,9 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + namespace Penumbra.Meta.Manipulations; +[JsonConverter(typeof(StringEnumConverter))] public enum GlobalEqpType { DoNotHideEarrings, From b79600ea1489dab7cb3dc7dc5e2c28708de6ea3f Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 1 Jun 2024 09:54:26 +0000 Subject: [PATCH 0637/1381] [CI] Updating repo.json for 1.1.0.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index a996e2d0..54e6b8b4 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.0.1.0", - "TestingAssemblyVersion": "1.0.3.2", + "AssemblyVersion": "1.1.0.0", + "TestingAssemblyVersion": "1.1.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,9 +17,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.0.3.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.0.1.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 24d4e9fac6b15dd700a01cc6ec05b224d508b7f9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Jun 2024 18:13:46 +0200 Subject: [PATCH 0638/1381] Fix collections not being added on creation. --- Penumbra/Collections/Manager/CollectionStorage.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 39068e87..68bd08cb 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -154,6 +154,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable public bool AddCollection(string name, ModCollection? duplicate) { var newCollection = Create(name, _collections.Count, duplicate); + _collections.Add(newCollection); _saveService.ImmediateSave(new ModCollectionSave(_modStorage, newCollection)); Penumbra.Messager.NotificationMessage($"Created new collection {newCollection.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, null, newCollection, string.Empty); From 331b7fbc1de13181aba85099518a14665ec0130e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Jun 2024 18:14:08 +0200 Subject: [PATCH 0639/1381] Fix other options displaying the same option multiple times. --- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 86d5e02e..86853755 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -15,7 +15,7 @@ public class ModMetaEditor(ModManager modManager) private readonly HashSet _rsp = []; private readonly HashSet _globalEqp = []; - public sealed class OtherOptionData : List + public sealed class OtherOptionData : HashSet { public int TotalCount; From aba68cfb925a0dc97dd9fa6cc5be3f0fe8310f7a Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 1 Jun 2024 16:18:13 +0000 Subject: [PATCH 0640/1381] [CI] Updating repo.json for 1.1.0.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 54e6b8b4..3f5d7262 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.1.0.0", - "TestingAssemblyVersion": "1.1.0.0", + "AssemblyVersion": "1.1.0.1", + "TestingAssemblyVersion": "1.1.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,9 +17,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 5101b73fdcb9db2e4cd992d70b0d74bf66316616 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Jun 2024 20:28:43 +0200 Subject: [PATCH 0641/1381] Fix issue with creating unnamed collections. --- Penumbra/Collections/Manager/CollectionStorage.cs | 3 +++ Penumbra/UI/CollectionTab/CollectionSelector.cs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 68bd08cb..f6287320 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -153,6 +153,9 @@ public class CollectionStorage : IReadOnlyList, IDisposable /// public bool AddCollection(string name, ModCollection? duplicate) { + if (name.Length == 0) + return false; + var newCollection = Create(name, _collections.Count, duplicate); _collections.Add(newCollection); _saveService.ImmediateSave(new ModCollectionSave(_modStorage, newCollection)); diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index fac85d4d..cecb41d7 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -109,7 +109,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl } private string Name(ModCollection collection) - => IncognitoMode ? collection.AnonymizedName : collection.Name; + => IncognitoMode || collection.Name.Length == 0 ? collection.AnonymizedName : collection.Name; private void OnCollectionChange(CollectionType type, ModCollection? old, ModCollection? @new, string _3) { From e7cf9d35c9ca7208423c95bc59fbfcddaa415df9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Jun 2024 23:33:21 +0200 Subject: [PATCH 0642/1381] Add GetChangedItems for Mods. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ModsApi.cs | 9 +++-- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/IpcProviders.cs | 1 + Penumbra/Api/IpcTester/ModsIpcTester.cs | 44 +++++++++++++++++++------ 5 files changed, 44 insertions(+), 14 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 69d106b4..f1e4e520 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 69d106b457eb0f73d4b4caf1234da5631fd6fbf0 +Subproject commit f1e4e520daaa8f23e5c8b71d55e5992b8f6768e2 diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index c1e0c684..16dd8be9 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -106,8 +106,8 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable var fullPath = leaf.FullName(); var isDefault = ModFileSystem.ModHasDefaultPath(mod, fullPath); - var isNameDefault = isDefault || ModFileSystem.ModHasDefaultPath(mod, leaf.Name); - return (PenumbraApiEc.Success, fullPath, !isDefault, !isNameDefault ); + var isNameDefault = isDefault || ModFileSystem.ModHasDefaultPath(mod, leaf.Name); + return (PenumbraApiEc.Success, fullPath, !isDefault, !isNameDefault); } public PenumbraApiEc SetModPath(string modDirectory, string modName, string newPath) @@ -129,4 +129,9 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable return PenumbraApiEc.PathRenameFailed; } } + + public Dictionary GetChangedItems(string modDirectory, string modName) + => _modManager.TryGetMod(modDirectory, modName, out var mod) + ? mod.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + : []; } diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 1d5b1537..0400c694 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -22,7 +22,7 @@ public class PenumbraApi( } public (int Breaking, int Feature) ApiVersion - => (5, 0); + => (5, 1); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index ebf71176..6b146c39 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -49,6 +49,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ModMoved.Provider(pi, api.Mods), IpcSubscribers.GetModPath.Provider(pi, api.Mods), IpcSubscribers.SetModPath.Provider(pi, api.Mods), + IpcSubscribers.GetChangedItems.Provider(pi, api.Mods), IpcSubscribers.GetAvailableModSettings.Provider(pi, api.ModSettings), IpcSubscribers.GetCurrentModSettings.Provider(pi, api.ModSettings), diff --git a/Penumbra/Api/IpcTester/ModsIpcTester.cs b/Penumbra/Api/IpcTester/ModsIpcTester.cs index 43f397e5..2be51a80 100644 --- a/Penumbra/Api/IpcTester/ModsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModsIpcTester.cs @@ -3,6 +3,7 @@ using Dalamud.Plugin; using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; using Penumbra.Api.IpcSubscribers; @@ -13,16 +14,17 @@ public class ModsIpcTester : IUiService, IDisposable { private readonly DalamudPluginInterface _pi; - private string _modDirectory = string.Empty; - private string _modName = string.Empty; - private string _pathInput = string.Empty; - private string _newInstallPath = string.Empty; - private PenumbraApiEc _lastReloadEc; - private PenumbraApiEc _lastAddEc; - private PenumbraApiEc _lastDeleteEc; - private PenumbraApiEc _lastSetPathEc; - private PenumbraApiEc _lastInstallEc; - private Dictionary _mods = []; + private string _modDirectory = string.Empty; + private string _modName = string.Empty; + private string _pathInput = string.Empty; + private string _newInstallPath = string.Empty; + private PenumbraApiEc _lastReloadEc; + private PenumbraApiEc _lastAddEc; + private PenumbraApiEc _lastDeleteEc; + private PenumbraApiEc _lastSetPathEc; + private PenumbraApiEc _lastInstallEc; + private Dictionary _mods = []; + private Dictionary _changedItems = []; public readonly EventSubscriber DeleteSubscriber; public readonly EventSubscriber AddSubscriber; @@ -120,6 +122,14 @@ public class ModsIpcTester : IUiService, IDisposable ImGui.SameLine(); ImGui.TextUnformatted(_lastDeleteEc.ToString()); + IpcTester.DrawIntro(GetChangedItems.Label, "Get Changed Items"); + DrawChangedItemsPopup(); + if (ImUtf8.Button("Get##ChangedItems"u8)) + { + _changedItems = new GetChangedItems(_pi).Invoke(_modDirectory, _modName); + ImUtf8.OpenPopup("ChangedItems"u8); + } + IpcTester.DrawIntro(GetModPath.Label, "Current Path"); var (ec, path, def, nameDef) = new GetModPath(_pi).Invoke(_modDirectory, _modName); ImGui.TextUnformatted($"{path} ({(def ? "Custom" : "Default")} Path, {(nameDef ? "Custom" : "Default")} Name) [{ec}]"); @@ -157,4 +167,18 @@ public class ModsIpcTester : IUiService, IDisposable if (ImGui.Button("Close", -Vector2.UnitX) || !ImGui.IsWindowFocused()) ImGui.CloseCurrentPopup(); } + + private void DrawChangedItemsPopup() + { + ImGui.SetNextWindowSize(ImGuiHelpers.ScaledVector2(500, 500)); + using var p = ImUtf8.Popup("ChangedItems"u8); + if (!p) + return; + + foreach (var (name, data) in _changedItems) + ImUtf8.Text($"{name}: {data}"); + + if (ImUtf8.Button("Close"u8, -Vector2.UnitX) || !ImGui.IsWindowFocused()) + ImGui.CloseCurrentPopup(); + } } From cfa58ee19672a335592e5d06bad26a71aa58aee6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Jun 2024 23:42:04 +0200 Subject: [PATCH 0643/1381] Fix global EQP rings checking bracelets instead. --- Penumbra/Meta/Manipulations/GlobalEqpCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Meta/Manipulations/GlobalEqpCache.cs b/Penumbra/Meta/Manipulations/GlobalEqpCache.cs index 48ffb308..26eb1d05 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpCache.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpCache.cs @@ -44,10 +44,10 @@ public struct GlobalEqpCache : IService if (_doNotHideBracelets.Contains(armor[7].Set)) original |= EqpEntry.BodyShowBracelet | EqpEntry.HandShowBracelet; - if (_doNotHideBracelets.Contains(armor[8].Set)) + if (_doNotHideRingR.Contains(armor[8].Set)) original |= EqpEntry.HandShowRingR; - if (_doNotHideBracelets.Contains(armor[9].Set)) + if (_doNotHideRingL.Contains(armor[9].Set)) original |= EqpEntry.HandShowRingL; return original; } From ef9d81c061c659c0b43643991b15e8be44b068af Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Jun 2024 23:42:17 +0200 Subject: [PATCH 0644/1381] Fix mod merger. --- Penumbra/Mods/Editor/ModMerger.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index d6e21076..32a207ff 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -37,7 +37,7 @@ public class ModMerger : IDisposable public readonly HashSet SelectedOptions = []; - public readonly IReadOnlyList Warnings = []; + public readonly IReadOnlyList Warnings = new List(); public Exception? Error { get; private set; } public ModMerger(ModManager mods, ModGroupEditor editor, ModFileSystemSelector selector, DuplicateManager duplicates, From 2e6473dc096363901c5665f79eb8afb750c2eb7c Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 1 Jun 2024 21:44:53 +0000 Subject: [PATCH 0645/1381] [CI] Updating repo.json for 1.1.0.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 3f5d7262..5e9e5b37 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.1.0.1", - "TestingAssemblyVersion": "1.1.0.1", + "AssemblyVersion": "1.1.0.2", + "TestingAssemblyVersion": "1.1.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,9 +17,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 3deda68eeca875ebd6403359f52877ec7d53b55a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 2 Jun 2024 01:03:51 +0200 Subject: [PATCH 0646/1381] Small updates. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Services/StaticServiceManager.cs | 2 -- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 2 +- .../ResourceTreeViewerFactory.cs | 3 +- Penumbra/UI/IncognitoService.cs | 29 +++++++++---------- .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 2 +- .../ModsTab/Groups/MultiModGroupEditDrawer.cs | 2 +- .../Groups/SingleModGroupEditDrawer.cs | 2 +- 9 files changed, 21 insertions(+), 25 deletions(-) diff --git a/OtterGui b/OtterGui index 0b5afffd..becacbca 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 0b5afffda19d3e16aec9e8682d18c8f11f67f1c6 +Subproject commit becacbca4f35595d16ff40dc9639cfa24be3461f diff --git a/Penumbra.GameData b/Penumbra.GameData index 29b71cf7..fed687b5 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 29b71cf7b3cc68995d38f0954fa38c4b9500a81d +Subproject commit fed687b536b7c709484db251b690b8821c5ef403 diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 146d7ee0..0c6648ba 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -149,7 +149,6 @@ public static class StaticServiceManager private static ServiceManager AddInterface(this ServiceManager services) => services.AddSingleton() .AddSingleton() - .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() @@ -182,7 +181,6 @@ public static class StaticServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() .AddSingleton(p => new Diagnostics(p)); private static ServiceManager AddModEditor(this ServiceManager services) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 5f376b26..7315f136 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -158,7 +158,7 @@ public class ResourceTreeViewer ImGui.SetNextItemWidth(fieldWidth); filterChanged |= ImGui.InputTextWithHint("##NodeFilter", "Filter by Item/Part Name or Path...", ref _nodeFilter, 128); ImGui.SameLine(0, checkSpacing); - _incognito.DrawToggle(); + _incognito.DrawToggle(ImGui.GetFrameHeightWithSpacing()); if (filterChanged) _filterCache.Clear(); diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs index 91dab6cb..ea64c0bf 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Interop.ResourceTree; namespace Penumbra.UI.AdvancedWindow; @@ -6,7 +7,7 @@ public class ResourceTreeViewerFactory( Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, - IncognitoService incognito) + IncognitoService incognito) : IService { public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions); diff --git a/Penumbra/UI/IncognitoService.cs b/Penumbra/UI/IncognitoService.cs index d4b1828f..d58ea1ec 100644 --- a/Penumbra/UI/IncognitoService.cs +++ b/Penumbra/UI/IncognitoService.cs @@ -1,29 +1,26 @@ -using Dalamud.Interface.Utility; using Dalamud.Interface; -using ImGuiNET; -using OtterGui; using Penumbra.UI.Classes; using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; namespace Penumbra.UI; -public class IncognitoService(TutorialService tutorial) +public class IncognitoService(TutorialService tutorial) : IService { public bool IncognitoMode; - public void DrawToggle(float? buttonWidth = null) + public void DrawToggle(float width) { - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); - using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()) - .Push(ImGuiCol.Border, ColorId.FolderExpanded.Value()); - if (ImGuiUtil.DrawDisabledButton( - $"{(IncognitoMode ? FontAwesomeIcon.Eye : FontAwesomeIcon.EyeSlash).ToIconString()}###IncognitoMode", - new Vector2(buttonWidth ?? ImGui.GetFrameHeightWithSpacing(), ImGui.GetFrameHeight()), string.Empty, false, true)) - IncognitoMode = !IncognitoMode; - var hovered = ImGui.IsItemHovered(); + var color = ColorId.FolderExpanded.Value(); + using (ImRaii.PushFrameBorder(ImUtf8.GlobalScale, color)) + { + var tt = IncognitoMode ? "Toggle incognito mode off."u8 : "Toggle incognito mode on."u8; + var icon = IncognitoMode ? FontAwesomeIcon.EyeSlash : FontAwesomeIcon.Eye; + if (ImUtf8.IconButton(icon, tt, new Vector2(width, ImUtf8.FrameHeight), false, color)) + IncognitoMode = !IncognitoMode; + } + tutorial.OpenTutorial(BasicTutorialSteps.Incognito); - color.Pop(2); - if (hovered) - ImGui.SetTooltip(IncognitoMode ? "Toggle incognito mode off." : "Toggle incognito mode on."); } } diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index b10f123c..b129d275 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -118,7 +118,7 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr : validName ? "Add a new option to this group."u8 : "Please enter a name for the new option."u8; - if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, !validName || dis)) + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, default, !validName || dis)) { editor.ModManager.OptionEditor.ImcEditor.AddOption(group, cache, name); editor.NewOptionName = null; diff --git a/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs index e6701a03..f0275853 100644 --- a/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs @@ -54,7 +54,7 @@ public readonly struct MultiModGroupEditDrawer(ModGroupEditDrawer editor, MultiM var validName = name.Length > 0; if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName ? "Add a new option to this group."u8 - : "Please enter a name for the new option."u8, !validName)) + : "Please enter a name for the new option."u8, default, !validName)) { editor.ModManager.OptionEditor.MultiEditor.AddOption(group, name); editor.NewOptionName = null; diff --git a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs index 75fbc63a..be2dbd73 100644 --- a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs @@ -59,7 +59,7 @@ public readonly struct SingleModGroupEditDrawer(ModGroupEditDrawer editor, Singl var validName = name.Length > 0; if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName ? "Add a new option to this group."u8 - : "Please enter a name for the new option."u8, !validName)) + : "Please enter a name for the new option."u8, default, !validName)) { editor.ModManager.OptionEditor.SingleEditor.AddOption(group, name); editor.NewOptionName = null; From 137b752196154960e2687be65728ae9d60bd913b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 2 Jun 2024 01:53:29 +0200 Subject: [PATCH 0647/1381] Fix Dye Preview not applying. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fed687b5..ad12ddce 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fed687b536b7c709484db251b690b8821c5ef403 +Subproject commit ad12ddcef38a9ed4e4dd7424d748f41c4b97db10 From 05d010a281de9e494c389bcb34fdad35ba9fe13d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 2 Jun 2024 12:08:49 +0200 Subject: [PATCH 0648/1381] Add some functionality to allow an IMC group to add apply to all variants. --- Penumbra/Collections/Cache/ImcCache.cs | 2 +- .../Import/TexToolsMeta.Deserialization.cs | 2 +- Penumbra/Import/TexToolsMeta.Export.cs | 2 +- Penumbra/Meta/Files/ImcFile.cs | 21 +++++----- Penumbra/Meta/ImcChecker.cs | 40 ++++++++++++++++++- Penumbra/Meta/Manipulations/Imc.cs | 37 +++++++++-------- Penumbra/Mods/Groups/ImcModGroup.cs | 31 ++++++++++---- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 6 +-- .../Manager/OptionEditor/ImcModGroupEditor.cs | 14 ++++++- .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 8 +++- 10 files changed, 117 insertions(+), 46 deletions(-) diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 33b366d3..7990122a 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -51,7 +51,7 @@ public readonly struct ImcCache : IDisposable try { if (!_imcFiles.TryGetValue(path, out var file)) - file = new ImcFile(manager, manip); + file = new ImcFile(manager, manip.Identifier); _imcManipulations[idx] = (manip, file); if (!manip.Apply(file)) diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index f062ae25..554cf848 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -110,7 +110,7 @@ public partial class TexToolsMeta var manip = new ImcManipulation(metaFileInfo.PrimaryType, metaFileInfo.SecondaryType, metaFileInfo.PrimaryId, metaFileInfo.SecondaryId, i, metaFileInfo.EquipSlot, new ImcEntry()); - var def = new ImcFile(_metaFileManager, manip); + var def = new ImcFile(_metaFileManager, manip.Identifier); var partIdx = ImcFile.PartIndex(manip.EquipSlot); // Gets turned to unknown for things without equip, and unknown turns to 0. foreach (var value in values) { diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 03bdbd90..09bd2c12 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -133,7 +133,7 @@ public partial class TexToolsMeta { case MetaManipulation.Type.Imc: var allManips = manips.ToList(); - var baseFile = new ImcFile(manager, allManips[0].Imc); + var baseFile = new ImcFile(manager, allManips[0].Imc.Identifier); foreach (var manip in allManips) manip.Imc.Apply(baseFile); diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 68d3f5b3..5d704cf8 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -9,20 +9,20 @@ namespace Penumbra.Meta.Files; public class ImcException : Exception { - public readonly ImcManipulation Manipulation; - public readonly string GamePath; + public readonly ImcIdentifier Identifier; + public readonly string GamePath; - public ImcException(ImcManipulation manip, Utf8GamePath path) + public ImcException(ImcIdentifier identifier, Utf8GamePath path) { - Manipulation = manip; - GamePath = path.ToString(); + Identifier = identifier; + GamePath = path.ToString(); } public override string Message => "Could not obtain default Imc File.\n" + " Either the default file does not exist (possibly for offhand files from TexTools) or the installation is corrupted.\n" + $" Game Path: {GamePath}\n" - + $" Manipulation: {Manipulation}"; + + $" Manipulation: {Identifier}"; } public unsafe class ImcFile : MetaBaseFile @@ -142,13 +142,14 @@ public unsafe class ImcFile : MetaBaseFile } } - public ImcFile(MetaFileManager manager, ImcManipulation manip) + public ImcFile(MetaFileManager manager, ImcIdentifier identifier) : base(manager, 0) { - Path = manip.GamePath(); - var file = manager.GameData.GetFile(Path.ToString()); + var path = identifier.GamePathString(); + Path = Utf8GamePath.FromString(path, out var p) ? p : Utf8GamePath.Empty; + var file = manager.GameData.GetFile(path); if (file == null) - throw new ImcException(manip, Path); + throw new ImcException(identifier, Path); fixed (byte* ptr = file.Data) { diff --git a/Penumbra/Meta/ImcChecker.cs b/Penumbra/Meta/ImcChecker.cs index 14486e21..650919a3 100644 --- a/Penumbra/Meta/ImcChecker.cs +++ b/Penumbra/Meta/ImcChecker.cs @@ -4,11 +4,32 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Meta; -public class ImcChecker(MetaFileManager metaFileManager) +public class ImcChecker { + private static readonly Dictionary VariantCounts = []; + private static MetaFileManager? _dataManager; + + + public static int GetVariantCount(ImcIdentifier identifier) + { + if (VariantCounts.TryGetValue(identifier, out var count)) + return count; + + count = GetFile(identifier)?.Count ?? 0; + VariantCounts[identifier] = count; + return count; + } + public readonly record struct CachedEntry(ImcEntry Entry, bool FileExists, bool VariantExists); private readonly Dictionary _cachedDefaultEntries = new(); + private readonly MetaFileManager _metaFileManager; + + public ImcChecker(MetaFileManager metaFileManager) + { + _metaFileManager = metaFileManager; + _dataManager = metaFileManager; + } public CachedEntry GetDefaultEntry(ImcIdentifier identifier, bool storeCache) { @@ -17,7 +38,7 @@ public class ImcChecker(MetaFileManager metaFileManager) try { - var e = ImcFile.GetDefault(metaFileManager, identifier.GamePath(), identifier.EquipSlot, identifier.Variant, out var entryExists); + var e = ImcFile.GetDefault(_metaFileManager, identifier.GamePath(), identifier.EquipSlot, identifier.Variant, out var entryExists); entry = new CachedEntry(e, true, entryExists); } catch (Exception) @@ -33,4 +54,19 @@ public class ImcChecker(MetaFileManager metaFileManager) public CachedEntry GetDefaultEntry(ImcManipulation imcManip, bool storeCache) => GetDefaultEntry(new ImcIdentifier(imcManip.PrimaryId, imcManip.Variant, imcManip.ObjectType, imcManip.SecondaryId.Id, imcManip.EquipSlot, imcManip.BodySlot), storeCache); + + private static ImcFile? GetFile(ImcIdentifier identifier) + { + if (_dataManager == null) + return null; + + try + { + return new ImcFile(_dataManager, identifier); + } + catch + { + return null; + } + } } diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index fef86520..2a2f4c03 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -31,12 +31,16 @@ public readonly record struct ImcIdentifier( => new(ObjectType, BodySlot, PrimaryId, SecondaryId.Id, Variant.Id, EquipSlot, entry); public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => AddChangedItems(identifier, changedItems, false); + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems, bool allVariants) { var path = ObjectType switch { - ObjectType.Equipment or ObjectType.Accessory => GamePaths.Equipment.Mtrl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot, - Variant, - "a"), + ObjectType.Equipment when allVariants => GamePaths.Equipment.Mdl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot), + ObjectType.Equipment => GamePaths.Equipment.Mtrl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot, Variant, "a"), + ObjectType.Accessory when allVariants => GamePaths.Accessory.Mdl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot), + ObjectType.Accessory => GamePaths.Accessory.Mtrl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot, Variant, "a"), ObjectType.Weapon => GamePaths.Weapon.Mtrl.Path(PrimaryId, SecondaryId.Id, Variant, "a"), ObjectType.DemiHuman => GamePaths.DemiHuman.Mtrl.Path(PrimaryId, SecondaryId.Id, EquipSlot, Variant, "a"), @@ -49,24 +53,19 @@ public readonly record struct ImcIdentifier( identifier.Identify(changedItems, path); } - public Utf8GamePath GamePath() - { - return ObjectType switch + public string GamePathString() + => ObjectType switch { - ObjectType.Accessory => Utf8GamePath.FromString(GamePaths.Accessory.Imc.Path(PrimaryId), out var p) ? p : Utf8GamePath.Empty, - ObjectType.Equipment => Utf8GamePath.FromString(GamePaths.Equipment.Imc.Path(PrimaryId), out var p) ? p : Utf8GamePath.Empty, - ObjectType.DemiHuman => Utf8GamePath.FromString(GamePaths.DemiHuman.Imc.Path(PrimaryId, SecondaryId.Id), out var p) - ? p - : Utf8GamePath.Empty, - ObjectType.Monster => Utf8GamePath.FromString(GamePaths.Monster.Imc.Path(PrimaryId, SecondaryId.Id), out var p) - ? p - : Utf8GamePath.Empty, - ObjectType.Weapon => Utf8GamePath.FromString(GamePaths.Weapon.Imc.Path(PrimaryId, SecondaryId.Id), out var p) - ? p - : Utf8GamePath.Empty, - _ => throw new NotImplementedException(), + ObjectType.Accessory => GamePaths.Accessory.Imc.Path(PrimaryId), + ObjectType.Equipment => GamePaths.Equipment.Imc.Path(PrimaryId), + ObjectType.DemiHuman => GamePaths.DemiHuman.Imc.Path(PrimaryId, SecondaryId.Id), + ObjectType.Monster => GamePaths.Monster.Imc.Path(PrimaryId, SecondaryId.Id), + ObjectType.Weapon => GamePaths.Weapon.Imc.Path(PrimaryId, SecondaryId.Id), + _ => string.Empty, }; - } + + public Utf8GamePath GamePath() + => Utf8GamePath.FromString(GamePathString(), out var p) ? p : Utf8GamePath.Empty; public MetaIndex FileIndex() => (MetaIndex)(-1); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index e0d70aa6..b336203d 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -6,6 +6,7 @@ using OtterGui.Classes; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.GameData.Structs; +using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; @@ -31,6 +32,8 @@ public class ImcModGroup(Mod mod) : IModGroup public ImcIdentifier Identifier; public ImcEntry DefaultEntry; + public bool AllVariants; + public FullPath? FindBestMatch(Utf8GamePath gamePath) => null; @@ -39,7 +42,7 @@ public class ImcModGroup(Mod mod) : IModGroup public bool CanBeDisabled { - get => OptionData.Any(m => m.IsDisableSubMod); + get => _canBeDisabled; set { _canBeDisabled = value; @@ -92,8 +95,8 @@ public class ImcModGroup(Mod mod) : IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) => new ImcModGroupEditDrawer(editDrawer, this); - public ImcManipulation GetManip(ushort mask) - => new(Identifier.ObjectType, Identifier.BodySlot, Identifier.PrimaryId, Identifier.SecondaryId.Id, Identifier.Variant.Id, + public ImcManipulation GetManip(ushort mask, Variant variant) + => new(Identifier.ObjectType, Identifier.BodySlot, Identifier.PrimaryId, Identifier.SecondaryId.Id, variant.Id, Identifier.EquipSlot, DefaultEntry with { AttributeMask = mask }); public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) @@ -102,12 +105,23 @@ public class ImcModGroup(Mod mod) : IModGroup return; var mask = GetCurrentMask(setting); - var imc = GetManip(mask); - manipulations.Add(imc); + if (AllVariants) + { + var count = ImcChecker.GetVariantCount(Identifier); + if (count == 0) + manipulations.Add(GetManip(mask, Identifier.Variant)); + else + for (var i = 0; i <= count; ++i) + manipulations.Add(GetManip(mask, (Variant)i)); + } + else + { + manipulations.Add(GetManip(mask, Identifier.Variant)); + } } public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - => Identifier.AddChangedItems(identifier, changedItems); + => Identifier.AddChangedItems(identifier, changedItems, AllVariants); public Setting FixSetting(Setting setting) => new(setting.Value & ((1ul << OptionData.Count) - 1)); @@ -120,6 +134,8 @@ public class ImcModGroup(Mod mod) : IModGroup jObj.WriteTo(jWriter); jWriter.WritePropertyName(nameof(DefaultEntry)); serializer.Serialize(jWriter, DefaultEntry); + jWriter.WritePropertyName(nameof(AllVariants)); + jWriter.WriteValue(AllVariants); jWriter.WritePropertyName("Options"); jWriter.WriteStartArray(); foreach (var option in OptionData) @@ -156,6 +172,7 @@ public class ImcModGroup(Mod mod) : IModGroup Description = json[nameof(Description)]?.ToObject() ?? string.Empty, Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), + AllVariants = json[nameof(AllVariants)]?.ToObject() ?? false, }; if (ret.Name.Length == 0) return null; @@ -210,7 +227,7 @@ public class ImcModGroup(Mod mod) : IModGroup if (idx >= 0) return setting.HasFlag(idx); - Penumbra.Log.Warning($"A IMC Group should be able to be disabled, but does not contain a disable option."); + Penumbra.Log.Warning("A IMC Group should be able to be disabled, but does not contain a disable option."); return false; } diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 5a5181a5..ea4ef7b1 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -51,7 +51,7 @@ public static class EquipmentSwap var (imcFileFrom, variants, affectedItems) = GetVariants(manager, identifier, slotFrom, idFrom, idTo, variantFrom); var imcManip = new ImcManipulation(slotTo, variantTo.Id, idTo.Id, default); - var imcFileTo = new ImcFile(manager, imcManip); + var imcFileTo = new ImcFile(manager, imcManip.Identifier); var skipFemale = false; var skipMale = false; var mtrlVariantTo = manips(imcManip.Copy(imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo.Id))).Imc.Entry.MaterialId; @@ -121,7 +121,7 @@ public static class EquipmentSwap { (var imcFileFrom, var variants, affectedItems) = GetVariants(manager, identifier, slot, idFrom, idTo, variantFrom); var imcManip = new ImcManipulation(slot, variantTo.Id, idTo, default); - var imcFileTo = new ImcFile(manager, imcManip); + var imcFileTo = new ImcFile(manager, imcManip.Identifier); var isAccessory = slot.IsAccessory(); var estType = slot switch @@ -250,7 +250,7 @@ public static class EquipmentSwap PrimaryId idFrom, PrimaryId idTo, Variant variantFrom) { var entry = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, default); - var imc = new ImcFile(manager, entry); + var imc = new ImcFile(manager, entry.Identifier); EquipItem[] items; Variant[] variants; if (idFrom == idTo) diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index f9fd532f..4aae45a2 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -2,6 +2,7 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.GameData.Structs; +using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; @@ -14,7 +15,8 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ : ModOptionEditor(communicator, saveService, config), IService { /// Add a new, empty imc group with the given manipulation data. - public ImcModGroup? AddModGroup(Mod mod, string newName, ImcIdentifier identifier, ImcEntry defaultEntry, SaveType saveType = SaveType.ImmediateSync) + public ImcModGroup? AddModGroup(Mod mod, string newName, ImcIdentifier identifier, ImcEntry defaultEntry, + SaveType saveType = SaveType.ImmediateSync) { if (!ModGroupEditor.VerifyFileName(mod, null, newName, true)) return null; @@ -78,6 +80,16 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, option.Mod, option.Group, option, null, -1); } + public void ChangeAllVariants(ImcModGroup group, bool allVariants, SaveType saveType = SaveType.Queue) + { + if (group.AllVariants == allVariants) + return; + + group.AllVariants = allVariants; + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, group.Mod, group, null, null, -1); + } + public void ChangeCanBeDisabled(ImcModGroup group, bool canBeDisabled, SaveType saveType = SaveType.Queue) { if (group.CanBeDisabled == canBeDisabled) diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index b129d275..d346e05c 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -19,7 +19,13 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr var entry = group.DefaultEntry; var changes = false; - ImUtf8.TextFramed(identifier.ToString(), 0, editor.AvailableWidth, borderColor: ImGui.GetColorU32(ImGuiCol.Border)); + var width = editor.AvailableWidth.X - ImUtf8.ItemInnerSpacing.X - ImUtf8.CalcTextSize("All Variants"u8).X; + ImUtf8.TextFramed(identifier.ToString(), 0, new Vector2(width, 0), borderColor: ImGui.GetColorU32(ImGuiCol.Border)); + ImUtf8.SameLineInner(); + var allVariants = group.AllVariants; + if (ImUtf8.Checkbox("All Variants"u8, ref allVariants)) + editor.ModManager.OptionEditor.ImcEditor.ChangeAllVariants(group, allVariants); + ImUtf8.HoverTooltip("Make this group overwrite all corresponding variants for this identifier, not just the one specified."u8); using (ImUtf8.Group()) { From b63935e81ed45d562a1a898ba5361f6233516798 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 2 Jun 2024 12:09:05 +0200 Subject: [PATCH 0649/1381] Fix issue with accessory vfx hook. --- Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 4e24ba39..8118343d 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -182,7 +182,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) { - if (slotIndex <= 4) + if (slotIndex is <= 4 or >= 10) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); var changedEquipData = ((Human*)drawObject)->ChangedEquipData; From 63b3a02e95b00dcbed78f55da4db6ba2ce874d23 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 3 Jun 2024 17:45:22 +0200 Subject: [PATCH 0650/1381] Fix issue with crash handler and collections not saving on rename. --- OtterGui | 2 +- Penumbra.CrashHandler/CrashData.cs | 4 +- .../Collections/Manager/CollectionStorage.cs | 1 + Penumbra/Communication/ModSettingChanged.cs | 2 +- Penumbra/Services/CrashHandlerService.cs | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 68 ++++++++----------- .../UI/CollectionTab/CollectionSelector.cs | 22 +++--- Penumbra/UI/Tabs/CollectionsTab.cs | 8 +-- Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs | 2 +- 9 files changed, 52 insertions(+), 59 deletions(-) diff --git a/OtterGui b/OtterGui index becacbca..5de708b2 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit becacbca4f35595d16ff40dc9639cfa24be3461f +Subproject commit 5de708b27ed45c9cdead71742c7061ad9ce64323 diff --git a/Penumbra.CrashHandler/CrashData.cs b/Penumbra.CrashHandler/CrashData.cs index cdac103f..dd75f46e 100644 --- a/Penumbra.CrashHandler/CrashData.cs +++ b/Penumbra.CrashHandler/CrashData.cs @@ -55,7 +55,7 @@ public class CrashData /// The last vfx function invoked before this crash data was generated. public VfxFuncInvokedEntry? LastVfxFuncInvoked - => LastVfxFuncsInvoked.Count == 0 ? default : LastVfxFuncsInvoked[0]; + => LastVFXFuncsInvoked.Count == 0 ? default : LastVFXFuncsInvoked[0]; /// A collection of the last few characters loaded before this crash data was generated. public List LastCharactersLoaded { get; set; } = []; @@ -64,5 +64,5 @@ public class CrashData public List LastModdedFilesLoaded { get; set; } = []; /// A collection of the last few vfx functions invoked before this crash data was generated. - public List LastVfxFuncsInvoked { get; set; } = []; + public List LastVFXFuncsInvoked { get; set; } = []; } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index f6287320..67de3a03 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -181,6 +181,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable return false; } + Delete(collection); _saveService.ImmediateDelete(new ModCollectionSave(_modStorage, collection)); _collections.RemoveAt(collection.Index); // Update indices. diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index a7da345b..7fda2f35 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -24,7 +24,7 @@ public sealed class ModSettingChanged() { public enum Priority { - /// + /// Api = int.MinValue, /// diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 1239578b..25c6cf57 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -287,7 +287,7 @@ public sealed class CrashHandlerService : IDisposable, IService try { - if (PathDataHandler.Split(manipulatedPath.Value.FullName, out var actualPath, out _) && Path.IsPathRooted(actualPath)) + if (PathDataHandler.Split(manipulatedPath.Value.FullName, out var actualPath, out _) && !Path.IsPathRooted(actualPath)) return; var name = GetActorName(resolveData.AssociatedGameObject); diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index cb4dbe20..082b78b8 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -20,19 +20,23 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.CollectionTab; -public sealed class CollectionPanel : IDisposable +public sealed class CollectionPanel( + DalamudPluginInterface pi, + CommunicatorService communicator, + CollectionManager manager, + CollectionSelector selector, + ActorManager actors, + ITargetManager targets, + ModStorage mods, + SaveService saveService, + IncognitoService incognito) + : IDisposable { - private readonly CollectionStorage _collections; - private readonly ActiveCollections _active; - private readonly CollectionSelector _selector; - private readonly ActorManager _actors; - private readonly ITargetManager _targets; - private readonly IndividualAssignmentUi _individualAssignmentUi; - private readonly InheritanceUi _inheritanceUi; - private readonly ModStorage _mods; - private readonly FilenameService _fileNames; - private readonly IncognitoService _incognito; - private readonly IFontHandle _nameFont; + private readonly CollectionStorage _collections = manager.Storage; + private readonly ActiveCollections _active = manager.Active; + private readonly IndividualAssignmentUi _individualAssignmentUi = new(communicator, actors, manager); + private readonly InheritanceUi _inheritanceUi = new(manager, incognito); + private readonly IFontHandle _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); private static readonly IReadOnlyDictionary Buttons = CreateButtons(); private static readonly IReadOnlyList<(CollectionType, bool, bool, string, uint)> AdvancedTree = CreateTree(); @@ -41,23 +45,6 @@ public sealed class CollectionPanel : IDisposable private int _draggedIndividualAssignment = -1; - public CollectionPanel(DalamudPluginInterface pi, CommunicatorService communicator, CollectionManager manager, - CollectionSelector selector, ActorManager actors, ITargetManager targets, ModStorage mods, FilenameService fileNames, - IncognitoService incognito) - { - _collections = manager.Storage; - _active = manager.Active; - _selector = selector; - _actors = actors; - _targets = targets; - _mods = mods; - _fileNames = fileNames; - _incognito = incognito; - _individualAssignmentUi = new IndividualAssignmentUi(communicator, actors, manager); - _inheritanceUi = new InheritanceUi(manager, incognito); - _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); - } - public void Dispose() { _individualAssignmentUi.Dispose(); @@ -237,17 +224,22 @@ public sealed class CollectionPanel : IDisposable var name = _newName ?? collection.Name; var identifier = collection.Identifier; var width = ImGui.GetContentRegionAvail().X; - var fileName = _fileNames.CollectionFile(collection); + var fileName = saveService.FileNames.CollectionFile(collection); ImGui.SetNextItemWidth(width); if (ImGui.InputText("##name", ref name, 128)) _newName = name; - if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null) + if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null && _newName != collection.Name) { collection.Name = _newName; - _newName = null; + saveService.QueueSave(new ModCollectionSave(mods, collection)); + selector.RestoreCollections(); + _newName = null; } else if (ImGui.IsItemDeactivated()) + { _newName = null; + } + using (ImRaii.PushFont(UiBuilder.MonoFont)) { if (ImGui.Button(collection.Identifier, new Vector2(width, 0))) @@ -329,7 +321,7 @@ public sealed class CollectionPanel : IDisposable DrawIndividualDragTarget(text, id); if (!invalid) { - _selector.DragTargetAssignment(type, id); + selector.DragTargetAssignment(type, id); var name = Name(collection); var size = ImGui.CalcTextSize(name); var textPos = ImGui.GetItemRectMax() - size - ImGui.GetStyle().FramePadding; @@ -418,7 +410,7 @@ public sealed class CollectionPanel : IDisposable /// Respect incognito mode for names of identifiers. private string Name(ActorIdentifier id, string? name) - => _incognito.IncognitoMode && id.Type is IdentifierType.Player or IdentifierType.Owned + => incognito.IncognitoMode && id.Type is IdentifierType.Player or IdentifierType.Owned ? id.Incognito(name) : name ?? id.ToString(); @@ -426,7 +418,7 @@ public sealed class CollectionPanel : IDisposable private string Name(ModCollection? collection) => collection == null ? "Unassigned" : collection == ModCollection.Empty ? "Use No Mods" : - _incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; + incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; private void DrawIndividualButton(string intro, Vector2 width, string tooltip, char suffix, params ActorIdentifier[] identifiers) { @@ -445,11 +437,11 @@ public sealed class CollectionPanel : IDisposable } private void DrawCurrentCharacter(Vector2 width) - => DrawIndividualButton("Current Character", width, string.Empty, 'c', _actors.GetCurrentPlayer()); + => DrawIndividualButton("Current Character", width, string.Empty, 'c', actors.GetCurrentPlayer()); private void DrawCurrentTarget(Vector2 width) => DrawIndividualButton("Current Target", width, string.Empty, 't', - _actors.FromObject(_targets.Target, false, true, true)); + actors.FromObject(targets.Target, false, true, true)); private void DrawNewPlayer(Vector2 width) => DrawIndividualButton("New Player", width, _individualAssignmentUi.PlayerTooltip, 'p', @@ -610,7 +602,7 @@ public sealed class CollectionPanel : IDisposable ImGui.TableSetupColumn("State", ImGuiTableColumnFlags.WidthFixed, 1.75f * ImGui.GetFrameHeight()); ImGui.TableSetupColumn("Priority", ImGuiTableColumnFlags.WidthFixed, 2.5f * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); - foreach (var (mod, (settings, parent)) in _mods.Select(m => (m, collection[m.Index])) + foreach (var (mod, (settings, parent)) in mods.Select(m => (m, collection[m.Index])) .Where(t => t.Item2.Settings != null) .OrderBy(t => t.m.Name)) { diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index c14baf5b..024873bf 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -44,7 +44,9 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl if (idx < 0 || idx >= Items.Count) return false; - return _storage.RemoveCollection(Items[idx]); + // Always return false since we handle the selection update ourselves. + _storage.RemoveCollection(Items[idx]); + return false; } protected override bool DeleteButtonEnabled() @@ -111,6 +113,15 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl private string Name(ModCollection collection) => _incognito.IncognitoMode || collection.Name.Length == 0 ? collection.AnonymizedName : collection.Name; + public void RestoreCollections() + { + Items.Clear(); + foreach (var c in _storage.OrderBy(c => c.Name)) + Items.Add(c); + SetFilterDirty(); + SetCurrent(_active.Current); + } + private void OnCollectionChange(CollectionType type, ModCollection? old, ModCollection? @new, string _3) { switch (type) @@ -122,14 +133,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl SetFilterDirty(); return; case CollectionType.Inactive: - Items.Clear(); - foreach (var c in _storage.OrderBy(c => c.Name)) - Items.Add(c); - - if (old == Current) - ClearCurrentSelection(); - else - TryRestoreCurrent(); + RestoreCollections(); SetFilterDirty(); return; default: diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 1eaece50..fabf7561 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -1,16 +1,12 @@ using Dalamud.Game.ClientState.Objects; -using Dalamud.Interface; -using Dalamud.Interface.Utility; using Dalamud.Plugin; using ImGuiNET; -using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.UI.Classes; using Penumbra.UI.CollectionTab; namespace Penumbra.UI.Tabs; @@ -42,13 +38,13 @@ public sealed class CollectionsTab : IDisposable, ITab } public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, IncognitoService incognito, - CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial, FilenameService fileNames) + CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial, SaveService saveService) { _config = configuration.Ephemeral; _tutorial = tutorial; _incognito = incognito; _selector = new CollectionSelector(configuration, communicator, collectionManager.Storage, collectionManager.Active, _tutorial, incognito); - _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage, fileNames, incognito); + _panel = new CollectionPanel(pi, communicator, collectionManager, _selector, actors, targets, modStorage, saveService, incognito); } public void Dispose() diff --git a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs index 4649e548..94c6cbd6 100644 --- a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs +++ b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs @@ -96,7 +96,7 @@ public static class CrashDataExtensions if (!table) return; - ImGuiClip.ClippedDraw(data.LastVfxFuncsInvoked, vfx => + ImGuiClip.ClippedDraw(data.LastVFXFuncsInvoked, vfx => { ImGuiUtil.DrawTableColumn(vfx.Age.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn(vfx.ThreadId.ToString()); From aeb2db9f5d7f390407e4ab760a55b5eb6a4a53ae Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 3 Jun 2024 17:46:45 +0200 Subject: [PATCH 0651/1381] Add tooltip to global eqp condition. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index a2a6925a..d4049bd9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -758,6 +758,7 @@ public partial class ModEditWindow if (IdInput("##geqpCond", 100 * ImUtf8.GlobalScale, _new.Condition.Id, out var newId, 1, ushort.MaxValue, _new.Condition.Id <= 1)) _new = _new with { Condition = newId }; + ImUtf8.HoverTooltip("The Model ID for the item that should not be hidden."u8); } public static void Draw(MetaFileManager metaFileManager, GlobalEqpManipulation meta, ModEditor editor, Vector2 iconSize) From 699ae8e1fb5939c8b7c8afe1614d73ba70d6317d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 3 Jun 2024 17:47:11 +0200 Subject: [PATCH 0652/1381] Fix issue with collection settings being set to negative value for some reason. --- Penumbra/Mods/Settings/Setting.cs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Penumbra/Mods/Settings/Setting.cs b/Penumbra/Mods/Settings/Setting.cs index 059cbf51..e8ad103c 100644 --- a/Penumbra/Mods/Settings/Setting.cs +++ b/Penumbra/Mods/Settings/Setting.cs @@ -85,6 +85,24 @@ public readonly record struct Setting(ulong Value) public override Setting ReadJson(JsonReader reader, Type objectType, Setting existingValue, bool hasExistingValue, JsonSerializer serializer) - => new(serializer.Deserialize(reader)); + { + try + { + return new Setting(serializer.Deserialize(reader)); + } + catch (Exception e) + { + Penumbra.Log.Warning($"Could not deserialize setting {reader.Value} to unsigned long:\n{e}"); + try + { + return new Setting((ulong)serializer.Deserialize(reader)); + } + catch + { + Penumbra.Log.Warning($"Could not deserialize setting {reader.Value} to long:\n{e}"); + return Zero; + } + } + } } } From 87fec7783eb3d416f2ffb5aa3cdc1b2c78acfc75 Mon Sep 17 00:00:00 2001 From: ackwell Date: Tue, 4 Jun 2024 12:10:45 +1000 Subject: [PATCH 0653/1381] Fix blend weight adjustment getting stuck on near-bounds values --- Penumbra/Import/Models/Import/VertexAttribute.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index a4651776..af401ec1 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -150,6 +150,12 @@ public class VertexAttribute { var convertedValues = byteValues.Select(value => value * (1f / 255f)).ToArray(); var closestIndex = Enumerable.Range(0, 4) + .Where(index => { + var byteValue = byteValues[index]; + if (adjustment < 0) return byteValue > 0; + if (adjustment > 0) return byteValue < 255; + return true; + }) .Select(index => (index, delta: Math.Abs(originalValues[index] - convertedValues[index]))) .MinBy(x => x.delta) .index; From 48dd4bcadb2a43e0cef94e89022da1fd802cec3a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 4 Jun 2024 15:53:35 +0200 Subject: [PATCH 0654/1381] Bleh. --- Penumbra/UI/FileDialogService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/FileDialogService.cs b/Penumbra/UI/FileDialogService.cs index e5b0fa19..88c0b00f 100644 --- a/Penumbra/UI/FileDialogService.cs +++ b/Penumbra/UI/FileDialogService.cs @@ -101,7 +101,7 @@ public class FileDialogService : IDisposable private static string HandleRoot(string path) { - if (path.Length == 2 && path[1] == ':') + if (path is [_, ':']) return path + '\\'; return path; From 03bfbcc3095042bdf7eccadc2494074bfe4e5189 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 5 Jun 2024 10:36:38 +0200 Subject: [PATCH 0655/1381] Fidx wrong group --- Penumbra/Mods/Editor/ModMerger.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 32a207ff..8d47051c 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -105,7 +105,7 @@ public class ModMerger : IDisposable throw new Exception( $"The merged group {originalGroup.Name} already existed, but had a different type than the original group of type {originalGroup.Type}."); - foreach (var originalOption in group.DataContainers) + foreach (var originalOption in originalGroup.DataContainers) { var (option, _, optionCreated) = _editor.FindOrAddOption(group, originalOption.GetName()); if (optionCreated) From ceed8531af0da494a9bd3909835e2f8a245491f7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 6 Jun 2024 16:49:39 +0200 Subject: [PATCH 0656/1381] Fix GMP Entry edit. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index d4049bd9..0783dd98 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -640,7 +640,7 @@ public partial class ModEditWindow ImGui.SameLine(); if (IntDragInput("##gmpUnkB", $"Animation Type B?\nDefault Value: {defaultEntry.UnknownB}", UnkWidth, meta.Entry.UnknownB, defaultEntry.UnknownB, out var unkB, 0, 15, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { UnknownA = (byte)unkB })); + editor.MetaEditor.Change(meta.Copy(meta.Entry with { UnknownB = (byte)unkB })); } } From 2e9f1844546476713634c2343e4db2020544faad Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 6 Jun 2024 17:26:25 +0200 Subject: [PATCH 0657/1381] Introduce Identifiers and strong entry types for each meta manipulation and use them in the manipulations. --- Penumbra/Collections/Cache/EstCache.cs | 38 +++--- Penumbra/Collections/Cache/MetaCache.cs | 4 +- .../Collections/ModCollection.Cache.Access.cs | 2 +- Penumbra/Import/Models/ModelManager.cs | 16 +-- .../Import/TexToolsMeta.Deserialization.cs | 12 +- Penumbra/Import/TexToolsMeta.Export.cs | 12 +- Penumbra/Import/TexToolsMeta.Rgsp.cs | 4 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 8 +- .../ResolveContext.PathResolution.cs | 14 +-- Penumbra/Meta/Files/CmpFile.cs | 11 +- Penumbra/Meta/Files/EstFile.cs | 44 +++---- Penumbra/Meta/Manipulations/Eqdp.cs | 87 ++++++++++++++ .../Meta/Manipulations/EqdpManipulation.cs | 23 ++-- Penumbra/Meta/Manipulations/Eqp.cs | 72 +++++++++++ .../Meta/Manipulations/EqpManipulation.cs | 14 ++- Penumbra/Meta/Manipulations/Est.cs | 113 ++++++++++++++++++ .../Meta/Manipulations/EstManipulation.cs | 36 +++--- Penumbra/Meta/Manipulations/Gmp.cs | 39 ++++++ .../Meta/Manipulations/GmpManipulation.cs | 12 +- Penumbra/Meta/Manipulations/Rsp.cs | 52 ++++++++ .../Meta/Manipulations/RspManipulation.cs | 22 ++-- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 6 +- Penumbra/Mods/ItemSwap/ItemSwap.cs | 16 +-- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 6 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 23 ++-- Penumbra/UI/Classes/Combos.cs | 2 +- Penumbra/Util/IdentifierExtensions.cs | 8 +- 27 files changed, 533 insertions(+), 163 deletions(-) create mode 100644 Penumbra/Meta/Manipulations/Eqdp.cs create mode 100644 Penumbra/Meta/Manipulations/Eqp.cs create mode 100644 Penumbra/Meta/Manipulations/Est.cs create mode 100644 Penumbra/Meta/Manipulations/Gmp.cs create mode 100644 Penumbra/Meta/Manipulations/Rsp.cs diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 2552cd4a..3a0b4695 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -48,33 +48,33 @@ public struct EstCache : IDisposable } } - public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager, EstManipulation.EstType type) + public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager, EstType type) { var (file, idx) = type switch { - EstManipulation.EstType.Face => (_estFaceFile, MetaIndex.FaceEst), - EstManipulation.EstType.Hair => (_estHairFile, MetaIndex.HairEst), - EstManipulation.EstType.Body => (_estBodyFile, MetaIndex.BodyEst), - EstManipulation.EstType.Head => (_estHeadFile, MetaIndex.HeadEst), + EstType.Face => (_estFaceFile, MetaIndex.FaceEst), + EstType.Hair => (_estHairFile, MetaIndex.HairEst), + EstType.Body => (_estBodyFile, MetaIndex.BodyEst), + EstType.Head => (_estHeadFile, MetaIndex.HeadEst), _ => (null, 0), }; return manager.TemporarilySetFile(file, idx); } - private readonly EstFile? GetEstFile(EstManipulation.EstType type) + private readonly EstFile? GetEstFile(EstType type) { return type switch { - EstManipulation.EstType.Face => _estFaceFile, - EstManipulation.EstType.Hair => _estHairFile, - EstManipulation.EstType.Body => _estBodyFile, - EstManipulation.EstType.Head => _estHeadFile, + EstType.Face => _estFaceFile, + EstType.Hair => _estHairFile, + EstType.Body => _estBodyFile, + EstType.Head => _estHeadFile, _ => null, }; } - internal ushort GetEstEntry(MetaFileManager manager, EstManipulation.EstType type, GenderRace genderRace, PrimaryId primaryId) + internal EstEntry GetEstEntry(MetaFileManager manager, EstType type, GenderRace genderRace, PrimaryId primaryId) { var file = GetEstFile(type); return file != null @@ -96,10 +96,10 @@ public struct EstCache : IDisposable _estManipulations.AddOrReplace(m); var file = m.Slot switch { - EstManipulation.EstType.Hair => _estHairFile ??= new EstFile(manager, EstManipulation.EstType.Hair), - EstManipulation.EstType.Face => _estFaceFile ??= new EstFile(manager, EstManipulation.EstType.Face), - EstManipulation.EstType.Body => _estBodyFile ??= new EstFile(manager, EstManipulation.EstType.Body), - EstManipulation.EstType.Head => _estHeadFile ??= new EstFile(manager, EstManipulation.EstType.Head), + EstType.Hair => _estHairFile ??= new EstFile(manager, EstType.Hair), + EstType.Face => _estFaceFile ??= new EstFile(manager, EstType.Face), + EstType.Body => _estBodyFile ??= new EstFile(manager, EstType.Body), + EstType.Head => _estHeadFile ??= new EstFile(manager, EstType.Head), _ => throw new ArgumentOutOfRangeException(), }; return m.Apply(file); @@ -114,10 +114,10 @@ public struct EstCache : IDisposable var manip = new EstManipulation(m.Gender, m.Race, m.Slot, m.SetId, def); var file = m.Slot switch { - EstManipulation.EstType.Hair => _estHairFile!, - EstManipulation.EstType.Face => _estFaceFile!, - EstManipulation.EstType.Body => _estBodyFile!, - EstManipulation.EstType.Head => _estHeadFile!, + EstType.Hair => _estHairFile!, + EstType.Face => _estFaceFile!, + EstType.Body => _estBodyFile!, + EstType.Head => _estHeadFile!, _ => throw new ArgumentOutOfRangeException(), }; return manip.Apply(file); diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index f42b72fc..fbca9c0e 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -188,7 +188,7 @@ public class MetaCache : IDisposable, IEnumerable _cmpCache.TemporarilySetFiles(_manager); - public MetaList.MetaReverter TemporarilySetEstFile(EstManipulation.EstType type) + public MetaList.MetaReverter TemporarilySetEstFile(EstType type) => _estCache.TemporarilySetFiles(_manager, type); public unsafe EqpEntry ApplyGlobalEqp(EqpEntry baseEntry, CharacterArmor* armor) @@ -208,7 +208,7 @@ public class MetaCache : IDisposable, IEnumerable _estCache.GetEstEntry(_manager, type, genderRace, primaryId); /// Use this when CharacterUtility becomes ready. diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 3f3733e0..484d4dd2 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -112,7 +112,7 @@ public partial class ModCollection => _cache?.Meta.TemporarilySetCmpFile() ?? utility.TemporarilyResetResource(MetaIndex.HumanCmp); - public MetaList.MetaReverter TemporarilySetEstFile(CharacterUtility utility, EstManipulation.EstType type) + public MetaList.MetaReverter TemporarilySetEstFile(CharacterUtility utility, EstType type) => _cache?.Meta.TemporarilySetEstFile(type) ?? utility.TemporarilyResetResource((MetaIndex)type); diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 485a76a7..fdd28ef1 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -63,16 +63,16 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect return info.ObjectType switch { ObjectType.Equipment when info.EquipSlot.ToSlot() is EquipSlot.Body - => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Body, info, estManipulations)], + => [baseSkeleton, ..ResolveEstSkeleton(EstType.Body, info, estManipulations)], ObjectType.Equipment when info.EquipSlot.ToSlot() is EquipSlot.Head - => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Head, info, estManipulations)], + => [baseSkeleton, ..ResolveEstSkeleton(EstType.Head, info, estManipulations)], ObjectType.Equipment => [baseSkeleton], ObjectType.Accessory => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Body or BodySlot.Tail => [baseSkeleton], ObjectType.Character when info.BodySlot is BodySlot.Hair - => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Hair, info, estManipulations)], + => [baseSkeleton, ..ResolveEstSkeleton(EstType.Hair, info, estManipulations)], ObjectType.Character when info.BodySlot is BodySlot.Face or BodySlot.Ear - => [baseSkeleton, ..ResolveEstSkeleton(EstManipulation.EstType.Face, info, estManipulations)], + => [baseSkeleton, ..ResolveEstSkeleton(EstType.Face, info, estManipulations)], ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], ObjectType.Monster => [GamePaths.Monster.Sklb.Path(info.PrimaryId)], @@ -81,7 +81,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect }; } - private string[] ResolveEstSkeleton(EstManipulation.EstType type, GameObjectInfo info, EstManipulation[] estManipulations) + private string[] ResolveEstSkeleton(EstType type, GameObjectInfo info, EstManipulation[] estManipulations) { // Try to find an EST entry from the manipulations provided. var (gender, race) = info.GenderRace.Split(); @@ -96,13 +96,13 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect // Try to use an entry from provided manipulations, falling back to the current collection. var targetId = modEst?.Entry ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) - ?? 0; + ?? EstEntry.Zero; // If there's no entries, we can assume that there's no additional skeleton. - if (targetId == 0) + if (targetId == EstEntry.Zero) return []; - return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId)]; + return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId.AsId)]; } /// Try to resolve the absolute path to a .mtrl from the potentially-partial path provided by a model. diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index 554cf848..f6157747 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -75,14 +75,14 @@ public partial class TexToolsMeta { var gr = (GenderRace)reader.ReadUInt16(); var id = reader.ReadUInt16(); - var value = reader.ReadUInt16(); + var value = new EstEntry(reader.ReadUInt16()); var type = (metaFileInfo.SecondaryType, metaFileInfo.EquipSlot) switch { - (BodySlot.Face, _) => EstManipulation.EstType.Face, - (BodySlot.Hair, _) => EstManipulation.EstType.Hair, - (_, EquipSlot.Head) => EstManipulation.EstType.Head, - (_, EquipSlot.Body) => EstManipulation.EstType.Body, - _ => (EstManipulation.EstType)0, + (BodySlot.Face, _) => EstType.Face, + (BodySlot.Hair, _) => EstType.Hair, + (_, EquipSlot.Head) => EstType.Head, + (_, EquipSlot.Body) => EstType.Body, + _ => (EstType)0, }; if (!gr.IsValid() || type == 0) continue; diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 09bd2c12..4fb56df6 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -66,7 +66,7 @@ public partial class TexToolsMeta foreach (var attribute in attributes) { var value = list.TryGetValue(attribute, out var tmp) ? tmp.Entry : CmpFile.GetDefault(manager, race, attribute); - b.Write(value); + b.Write(value.Value); } } @@ -176,7 +176,7 @@ public partial class TexToolsMeta { b.Write((ushort)Names.CombinedRace(manip.Est.Gender, manip.Est.Race)); b.Write(manip.Est.SetId.Id); - b.Write(manip.Est.Entry); + b.Write(manip.Est.Entry.Value); } break; @@ -239,10 +239,10 @@ public partial class TexToolsMeta var raceCode = Names.CombinedRace(manip.Gender, manip.Race).ToRaceCode(); return manip.Slot switch { - EstManipulation.EstType.Hair => $"chara/human/c{raceCode}/obj/hair/h{manip.SetId:D4}/c{raceCode}h{manip.SetId:D4}_hir.meta", - EstManipulation.EstType.Face => $"chara/human/c{raceCode}/obj/face/h{manip.SetId:D4}/c{raceCode}f{manip.SetId:D4}_fac.meta", - EstManipulation.EstType.Body => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Body.ToSuffix()}.meta", - EstManipulation.EstType.Head => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Head.ToSuffix()}.meta", + EstType.Hair => $"chara/human/c{raceCode}/obj/hair/h{manip.SetId:D4}/c{raceCode}h{manip.SetId:D4}_hir.meta", + EstType.Face => $"chara/human/c{raceCode}/obj/face/h{manip.SetId:D4}/c{raceCode}f{manip.SetId:D4}_fac.meta", + EstType.Body => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Body.ToSuffix()}.meta", + EstType.Head => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Head.ToSuffix()}.meta", _ => throw new ArgumentOutOfRangeException(), }; } diff --git a/Penumbra/Import/TexToolsMeta.Rgsp.cs b/Penumbra/Import/TexToolsMeta.Rgsp.cs index 51faa175..71b9165f 100644 --- a/Penumbra/Import/TexToolsMeta.Rgsp.cs +++ b/Penumbra/Import/TexToolsMeta.Rgsp.cs @@ -46,8 +46,8 @@ public partial class TexToolsMeta void Add(RspAttribute attribute, float value) { var def = CmpFile.GetDefault(manager, subRace, attribute); - if (keepDefault || value != def) - ret.MetaManipulations.Add(new RspManipulation(subRace, attribute, value)); + if (keepDefault || value != def.Value) + ret.MetaManipulations.Add(new RspManipulation(subRace, attribute, new RspEntry(value))); } if (gender == 1) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 8118343d..9a68160b 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -212,10 +212,10 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable if (_parent.InInternalResolve) return DisposableContainer.Empty; - return new DisposableContainer(data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Face), - data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Body), - data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Hair), - data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstManipulation.EstType.Head)); + return new DisposableContainer(data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Face), + data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Body), + data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Hair), + data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Head)); } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 236c7051..2b87e688 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -250,30 +250,30 @@ internal partial record ResolveContext _ => 0, }; } - return ResolveHumanExtraSkeletonData(characterRaceCode, EstManipulation.EstType.Face, faceId); + return ResolveHumanExtraSkeletonData(characterRaceCode, EstType.Face, faceId); case 2: - return ResolveHumanExtraSkeletonData(characterRaceCode, EstManipulation.EstType.Hair, human->HairId); + return ResolveHumanExtraSkeletonData(characterRaceCode, EstType.Hair, human->HairId); case 3: - return ResolveHumanEquipmentSkeletonData(EquipSlot.Head, EstManipulation.EstType.Head); + return ResolveHumanEquipmentSkeletonData(EquipSlot.Head, EstType.Head); case 4: - return ResolveHumanEquipmentSkeletonData(EquipSlot.Body, EstManipulation.EstType.Body); + return ResolveHumanEquipmentSkeletonData(EquipSlot.Body, EstType.Body); default: return (0, string.Empty, 0); } } - private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanEquipmentSkeletonData(EquipSlot slot, EstManipulation.EstType type) + private unsafe (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanEquipmentSkeletonData(EquipSlot slot, EstType type) { var human = (Human*)CharacterBase; var equipment = ((CharacterArmor*)&human->Head)[slot.ToIndex()]; return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot, equipment.Set), type, equipment.Set); } - private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstManipulation.EstType type, PrimaryId primary) + private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstType type, PrimaryId primary) { var metaCache = Global.Collection.MetaCache; var skeletonSet = metaCache?.GetEstEntry(type, raceCode, primary) ?? default; - return (raceCode, EstManipulation.ToName(type), skeletonSet); + return (raceCode, EstManipulation.ToName(type), skeletonSet.AsId); } private unsafe Utf8GamePath ResolveSkeletonPathNative(uint partialSkeletonIndex) diff --git a/Penumbra/Meta/Files/CmpFile.cs b/Penumbra/Meta/Files/CmpFile.cs index b265a5e8..96cda496 100644 --- a/Penumbra/Meta/Files/CmpFile.cs +++ b/Penumbra/Meta/Files/CmpFile.cs @@ -2,6 +2,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; using Penumbra.Interop.Services; +using Penumbra.Meta.Manipulations; using Penumbra.String.Functions; namespace Penumbra.Meta.Files; @@ -17,10 +18,10 @@ public sealed unsafe class CmpFile : MetaBaseFile private const int RacialScalingStart = 0x2A800; - public float this[SubRace subRace, RspAttribute attribute] + public RspEntry this[SubRace subRace, RspAttribute attribute] { - get => *(float*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); - set => *(float*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4) = value; + get => *(RspEntry*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); + set => *(RspEntry*)(Data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4) = value; } public override void Reset() @@ -39,10 +40,10 @@ public sealed unsafe class CmpFile : MetaBaseFile Reset(); } - public static float GetDefault(MetaFileManager manager, SubRace subRace, RspAttribute attribute) + public static RspEntry GetDefault(MetaFileManager manager, SubRace subRace, RspAttribute attribute) { var data = (byte*)manager.CharacterUtility.DefaultResource(InternalIndex).Address; - return *(float*)(data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); + return *(RspEntry*)(data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); } private static int ToRspIndex(SubRace subRace) diff --git a/Penumbra/Meta/Files/EstFile.cs b/Penumbra/Meta/Files/EstFile.cs index af441b22..ee38ea1e 100644 --- a/Penumbra/Meta/Files/EstFile.cs +++ b/Penumbra/Meta/Files/EstFile.cs @@ -34,26 +34,26 @@ public sealed unsafe class EstFile : MetaBaseFile Removed, } - public ushort this[GenderRace genderRace, ushort setId] + public EstEntry this[GenderRace genderRace, PrimaryId setId] { get { var (idx, exists) = FindEntry(genderRace, setId); if (!exists) - return 0; + return EstEntry.Zero; - return *(ushort*)(Data + EntryDescSize * (Count + 1) + EntrySize * idx); + return *(EstEntry*)(Data + EntryDescSize * (Count + 1) + EntrySize * idx); } set => SetEntry(genderRace, setId, value); } - private void InsertEntry(int idx, GenderRace genderRace, ushort setId, ushort skeletonId) + private void InsertEntry(int idx, GenderRace genderRace, PrimaryId setId, EstEntry skeletonId) { if (Length < Size + EntryDescSize + EntrySize) ResizeResources(Length + IncreaseSize); var control = (Info*)(Data + 4); - var entries = (ushort*)(control + Count); + var entries = (EstEntry*)(control + Count); for (var i = Count - 1; i >= idx; --i) entries[i + 3] = entries[i]; @@ -94,10 +94,10 @@ public sealed unsafe class EstFile : MetaBaseFile [StructLayout(LayoutKind.Sequential, Size = 4)] private struct Info : IComparable { - public readonly ushort SetId; + public readonly PrimaryId SetId; public readonly GenderRace GenderRace; - public Info(GenderRace gr, ushort setId) + public Info(GenderRace gr, PrimaryId setId) { GenderRace = gr; SetId = setId; @@ -106,42 +106,42 @@ public sealed unsafe class EstFile : MetaBaseFile public int CompareTo(Info other) { var genderRaceComparison = GenderRace.CompareTo(other.GenderRace); - return genderRaceComparison != 0 ? genderRaceComparison : SetId.CompareTo(other.SetId); + return genderRaceComparison != 0 ? genderRaceComparison : SetId.Id.CompareTo(other.SetId.Id); } } - private static (int, bool) FindEntry(ReadOnlySpan data, GenderRace genderRace, ushort setId) + private static (int, bool) FindEntry(ReadOnlySpan data, GenderRace genderRace, PrimaryId setId) { var idx = data.BinarySearch(new Info(genderRace, setId)); return idx < 0 ? (~idx, false) : (idx, true); } - private (int, bool) FindEntry(GenderRace genderRace, ushort setId) + private (int, bool) FindEntry(GenderRace genderRace, PrimaryId setId) { var span = new ReadOnlySpan(Data + 4, Count); return FindEntry(span, genderRace, setId); } - public EstEntryChange SetEntry(GenderRace genderRace, ushort setId, ushort skeletonId) + public EstEntryChange SetEntry(GenderRace genderRace, PrimaryId setId, EstEntry skeletonId) { var (idx, exists) = FindEntry(genderRace, setId); if (exists) { - var value = *(ushort*)(Data + 4 * (Count + 1) + 2 * idx); + var value = *(EstEntry*)(Data + 4 * (Count + 1) + 2 * idx); if (value == skeletonId) return EstEntryChange.Unchanged; - if (skeletonId == 0) + if (skeletonId == EstEntry.Zero) { RemoveEntry(idx); return EstEntryChange.Removed; } - *(ushort*)(Data + 4 * (Count + 1) + 2 * idx) = skeletonId; + *(EstEntry*)(Data + 4 * (Count + 1) + 2 * idx) = skeletonId; return EstEntryChange.Changed; } - if (skeletonId == 0) + if (skeletonId == EstEntry.Zero) return EstEntryChange.Unchanged; InsertEntry(idx, genderRace, setId, skeletonId); @@ -156,7 +156,7 @@ public sealed unsafe class EstFile : MetaBaseFile MemoryUtility.MemSet(Data + length, 0, Length - length); } - public EstFile(MetaFileManager manager, EstManipulation.EstType estType) + public EstFile(MetaFileManager manager, EstType estType) : base(manager, (MetaIndex)estType) { var length = DefaultData.Length; @@ -164,24 +164,24 @@ public sealed unsafe class EstFile : MetaBaseFile Reset(); } - public ushort GetDefault(GenderRace genderRace, ushort setId) + public EstEntry GetDefault(GenderRace genderRace, PrimaryId setId) => GetDefault(Manager, Index, genderRace, setId); - public static ushort GetDefault(MetaFileManager manager, CharacterUtility.InternalIndex index, GenderRace genderRace, PrimaryId primaryId) + public static EstEntry GetDefault(MetaFileManager manager, CharacterUtility.InternalIndex index, GenderRace genderRace, PrimaryId primaryId) { var data = (byte*)manager.CharacterUtility.DefaultResource(index).Address; var count = *(int*)data; var span = new ReadOnlySpan(data + 4, count); var (idx, found) = FindEntry(span, genderRace, primaryId.Id); if (!found) - return 0; + return EstEntry.Zero; - return *(ushort*)(data + 4 + count * EntryDescSize + idx * EntrySize); + return *(EstEntry*)(data + 4 + count * EntryDescSize + idx * EntrySize); } - public static ushort GetDefault(MetaFileManager manager, MetaIndex metaIndex, GenderRace genderRace, PrimaryId primaryId) + public static EstEntry GetDefault(MetaFileManager manager, MetaIndex metaIndex, GenderRace genderRace, PrimaryId primaryId) => GetDefault(manager, CharacterUtility.ReverseIndices[(int)metaIndex], genderRace, primaryId); - public static ushort GetDefault(MetaFileManager manager, EstManipulation.EstType estType, GenderRace genderRace, PrimaryId primaryId) + public static EstEntry GetDefault(MetaFileManager manager, EstType estType, GenderRace genderRace, PrimaryId primaryId) => GetDefault(manager, (MetaIndex)estType, genderRace, primaryId); } diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs new file mode 100644 index 00000000..6d6942e6 --- /dev/null +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -0,0 +1,87 @@ +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, GenderRace GenderRace) + : IMetaIdentifier, IComparable +{ + public ModelRace Race + => GenderRace.Split().Item2; + + public Gender Gender + => GenderRace.Split().Item1; + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, Slot)); + + public MetaIndex FileIndex() + => CharacterUtilityData.EqdpIdx(GenderRace, Slot.IsAccessory()); + + public override string ToString() + => $"Eqdp - {SetId} - {Slot.ToName()} - {GenderRace.ToName()}"; + + public bool Validate() + { + var mask = Eqdp.Mask(Slot); + if (mask == 0) + return false; + + if (FileIndex() == (MetaIndex)(-1)) + return false; + + // No check for set id. + return true; + } + + public int CompareTo(EqdpIdentifier other) + { + var gr = GenderRace.CompareTo(other.GenderRace); + if (gr != 0) + return gr; + + var set = SetId.Id.CompareTo(other.SetId.Id); + if (set != 0) + return set; + + return Slot.CompareTo(other.Slot); + } + + public static EqdpIdentifier? FromJson(JObject jObj) + { + var gender = jObj["Gender"]?.ToObject() ?? Gender.Unknown; + var race = jObj["Race"]?.ToObject() ?? ModelRace.Unknown; + var setId = new PrimaryId(jObj["SetId"]?.ToObject() ?? 0); + var slot = jObj["Slot"]?.ToObject() ?? EquipSlot.Unknown; + var ret = new EqdpIdentifier(setId, slot, Names.CombinedRace(gender, race)); + return ret.Validate() ? ret : null; + } + + public JObject AddToJson(JObject jObj) + { + var (gender, race) = GenderRace.Split(); + jObj["Gender"] = gender.ToString(); + jObj["Race"] = race.ToString(); + jObj["SetId"] = SetId.Id.ToString(); + jObj["Slot"] = Slot.ToString(); + return jObj; + } +} + +public readonly record struct InternalEqdpEntry(bool Model, bool Material) +{ + private InternalEqdpEntry((bool, bool) val) + : this(val.Item1, val.Item2) + { } + + public InternalEqdpEntry(EqdpEntry entry, EquipSlot slot) + : this(entry.ToBits(slot)) + { } + + + public EqdpEntry ToEntry(EquipSlot slot) + => Eqdp.FromSlotAndBits(slot, Model, Material); +} diff --git a/Penumbra/Meta/Manipulations/EqdpManipulation.cs b/Penumbra/Meta/Manipulations/EqdpManipulation.cs index 0426dfce..2c01ce3f 100644 --- a/Penumbra/Meta/Manipulations/EqdpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqdpManipulation.cs @@ -10,27 +10,30 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct EqdpManipulation : IMetaManipulation { - public EqdpEntry Entry { get; private init; } + [JsonIgnore] + public EqdpIdentifier Identifier { get; private init; } + public EqdpEntry Entry { get; private init; } [JsonConverter(typeof(StringEnumConverter))] - public Gender Gender { get; private init; } + public Gender Gender + => Identifier.Gender; [JsonConverter(typeof(StringEnumConverter))] - public ModelRace Race { get; private init; } + public ModelRace Race + => Identifier.Race; - public PrimaryId SetId { get; private init; } + public PrimaryId SetId + => Identifier.SetId; [JsonConverter(typeof(StringEnumConverter))] - public EquipSlot Slot { get; private init; } + public EquipSlot Slot + => Identifier.Slot; [JsonConstructor] public EqdpManipulation(EqdpEntry entry, EquipSlot slot, Gender gender, ModelRace race, PrimaryId setId) { - Gender = gender; - Race = race; - SetId = setId; - Slot = slot; - Entry = Eqdp.Mask(Slot) & entry; + Identifier = new EqdpIdentifier(setId, slot, Names.CombinedRace(gender, race)); + Entry = Eqdp.Mask(Slot) & entry; } public EqdpManipulation Copy(EqdpManipulation entry) diff --git a/Penumbra/Meta/Manipulations/Eqp.cs b/Penumbra/Meta/Manipulations/Eqp.cs new file mode 100644 index 00000000..572dc203 --- /dev/null +++ b/Penumbra/Meta/Manipulations/Eqp.cs @@ -0,0 +1,72 @@ +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct EqpIdentifier(PrimaryId SetId, EquipSlot Slot) : IMetaIdentifier, IComparable +{ + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace.MidlanderMale, Slot)); + + public MetaIndex FileIndex() + => MetaIndex.Eqp; + + public override string ToString() + => $"Eqp - {SetId} - {Slot}"; + + public bool Validate() + { + var mask = Eqp.Mask(Slot); + if (mask == 0) + return false; + + // No check for set id. + return true; + } + + public int CompareTo(EqpIdentifier other) + { + var set = SetId.Id.CompareTo(other.SetId.Id); + if (set != 0) + return set; + + return Slot.CompareTo(other.Slot); + } + + public static EqpIdentifier? FromJson(JObject jObj) + { + var setId = new PrimaryId(jObj["SetId"]?.ToObject() ?? 0); + var slot = jObj["Slot"]?.ToObject() ?? EquipSlot.Unknown; + var ret = new EqpIdentifier(setId, slot); + return ret.Validate() ? ret : null; + } + + public JObject AddToJson(JObject jObj) + { + jObj["SetId"] = SetId.Id.ToString(); + jObj["Slot"] = Slot.ToString(); + return jObj; + } +} + +public readonly record struct EqpEntryInternal(uint Value) +{ + public EqpEntryInternal(EqpEntry entry, EquipSlot slot) + : this(GetValue(entry, slot)) + { } + + public EqpEntry ToEntry(EquipSlot slot) + { + var (offset, mask) = Eqp.OffsetAndMask(slot); + return (EqpEntry)((ulong)Value << offset) & mask; + } + + private static uint GetValue(EqpEntry entry, EquipSlot slot) + { + var (offset, mask) = Eqp.OffsetAndMask(slot); + return (uint)((ulong)(entry & mask) >> offset); + } +} diff --git a/Penumbra/Meta/Manipulations/EqpManipulation.cs b/Penumbra/Meta/Manipulations/EqpManipulation.cs index d59938b6..3bced096 100644 --- a/Penumbra/Meta/Manipulations/EqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqpManipulation.cs @@ -5,7 +5,6 @@ using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; using Penumbra.Meta.Files; using Penumbra.Util; -using SharpCompress.Common; namespace Penumbra.Meta.Manipulations; @@ -15,17 +14,20 @@ public readonly struct EqpManipulation : IMetaManipulation [JsonConverter(typeof(ForceNumericFlagEnumConverter))] public EqpEntry Entry { get; private init; } - public PrimaryId SetId { get; private init; } + public EqpIdentifier Identifier { get; private init; } + + public PrimaryId SetId + => Identifier.SetId; [JsonConverter(typeof(StringEnumConverter))] - public EquipSlot Slot { get; private init; } + public EquipSlot Slot + => Identifier.Slot; [JsonConstructor] public EqpManipulation(EqpEntry entry, EquipSlot slot, PrimaryId setId) { - Slot = slot; - SetId = setId; - Entry = Eqp.Mask(slot) & entry; + Identifier = new EqpIdentifier(setId, slot); + Entry = Eqp.Mask(slot) & entry; } public EqpManipulation Copy(EqpEntry entry) diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs new file mode 100644 index 00000000..9f878f97 --- /dev/null +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -0,0 +1,113 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public enum EstType : byte +{ + Hair = MetaIndex.HairEst, + Face = MetaIndex.FaceEst, + Body = MetaIndex.BodyEst, + Head = MetaIndex.HeadEst, +} + +public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, GenderRace GenderRace) + : IMetaIdentifier, IComparable +{ + public ModelRace Race + => GenderRace.Split().Item2; + + public Gender Gender + => GenderRace.Split().Item1; + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + switch (Slot) + { + case EstType.Hair: + changedItems.TryAdd( + $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Hair (Hair) {SetId}", null); + break; + case EstType.Face: + changedItems.TryAdd( + $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Face (Face) {SetId}", null); + break; + case EstType.Body: + identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, EquipSlot.Body)); + break; + case EstType.Head: + identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, EquipSlot.Head)); + break; + } + } + + public MetaIndex FileIndex() + => (MetaIndex)Slot; + + public override string ToString() + => $"Est - {SetId} - {Slot} - {GenderRace.ToName()}"; + + public bool Validate() + { + if (!Enum.IsDefined(Slot)) + return false; + if (GenderRace is GenderRace.Unknown || !Enum.IsDefined(GenderRace)) + return false; + + // No known check for set id. + return true; + } + + public int CompareTo(EstIdentifier other) + { + var gr = GenderRace.CompareTo(other.GenderRace); + if (gr != 0) + return gr; + + var id = SetId.Id.CompareTo(other.SetId.Id); + return id != 0 ? id : Slot.CompareTo(other.Slot); + } + + public static EstIdentifier? FromJson(JObject jObj) + { + var gender = jObj["Gender"]?.ToObject() ?? Gender.Unknown; + var race = jObj["Race"]?.ToObject() ?? ModelRace.Unknown; + var setId = new PrimaryId(jObj["SetId"]?.ToObject() ?? 0); + var slot = jObj["Slot"]?.ToObject() ?? 0; + var ret = new EstIdentifier(setId, slot, Names.CombinedRace(gender, race)); + return ret.Validate() ? ret : null; + } + + public JObject AddToJson(JObject jObj) + { + var (gender, race) = GenderRace.Split(); + jObj["Gender"] = gender.ToString(); + jObj["Race"] = race.ToString(); + jObj["SetId"] = SetId.Id.ToString(); + jObj["Slot"] = Slot.ToString(); + return jObj; + } +} + +[JsonConverter(typeof(Converter))] +public readonly record struct EstEntry(ushort Value) +{ + public static readonly EstEntry Zero = new(0); + + public PrimaryId AsId + => new(Value); + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, EstEntry value, JsonSerializer serializer) + => serializer.Serialize(writer, value.Value); + + public override EstEntry ReadJson(JsonReader reader, Type objectType, EstEntry existingValue, bool hasExistingValue, + JsonSerializer serializer) + => new(serializer.Deserialize(reader)); + } +} diff --git a/Penumbra/Meta/Manipulations/EstManipulation.cs b/Penumbra/Meta/Manipulations/EstManipulation.cs index d3c92ad3..c3f9792f 100644 --- a/Penumbra/Meta/Manipulations/EstManipulation.cs +++ b/Penumbra/Meta/Manipulations/EstManipulation.cs @@ -10,14 +10,6 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct EstManipulation : IMetaManipulation { - public enum EstType : byte - { - Hair = MetaIndex.HairEst, - Face = MetaIndex.FaceEst, - Body = MetaIndex.BodyEst, - Head = MetaIndex.HeadEst, - } - public static string ToName(EstType type) => type switch { @@ -28,31 +20,33 @@ public readonly struct EstManipulation : IMetaManipulation _ => "unk", }; - public ushort Entry { get; private init; } // SkeletonIdx. + public EstIdentifier Identifier { get; private init; } + public EstEntry Entry { get; private init; } [JsonConverter(typeof(StringEnumConverter))] - public Gender Gender { get; private init; } + public Gender Gender + => Identifier.Gender; [JsonConverter(typeof(StringEnumConverter))] - public ModelRace Race { get; private init; } + public ModelRace Race + => Identifier.Race; - public PrimaryId SetId { get; private init; } + public PrimaryId SetId + => Identifier.SetId; [JsonConverter(typeof(StringEnumConverter))] - public EstType Slot { get; private init; } + public EstType Slot + => Identifier.Slot; [JsonConstructor] - public EstManipulation(Gender gender, ModelRace race, EstType slot, PrimaryId setId, ushort entry) + public EstManipulation(Gender gender, ModelRace race, EstType slot, PrimaryId setId, EstEntry entry) { - Entry = entry; - Gender = gender; - Race = race; - SetId = setId; - Slot = slot; + Entry = entry; + Identifier = new EstIdentifier(setId, slot, Names.CombinedRace(gender, race)); } - public EstManipulation Copy(ushort entry) + public EstManipulation Copy(EstEntry entry) => new(Gender, Race, Slot, SetId, entry); @@ -111,3 +105,5 @@ public readonly struct EstManipulation : IMetaManipulation return true; } } + + diff --git a/Penumbra/Meta/Manipulations/Gmp.cs b/Penumbra/Meta/Manipulations/Gmp.cs new file mode 100644 index 00000000..1b7c70ba --- /dev/null +++ b/Penumbra/Meta/Manipulations/Gmp.cs @@ -0,0 +1,39 @@ +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct GmpIdentifier(PrimaryId SetId) : IMetaIdentifier, IComparable +{ + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace.MidlanderMale, EquipSlot.Head)); + + public MetaIndex FileIndex() + => MetaIndex.Gmp; + + public override string ToString() + => $"Gmp - {SetId}"; + + public bool Validate() + // No known conditions. + => true; + + public int CompareTo(GmpIdentifier other) + => SetId.Id.CompareTo(other.SetId.Id); + + public static GmpIdentifier? FromJson(JObject jObj) + { + var setId = new PrimaryId(jObj["SetId"]?.ToObject() ?? 0); + var ret = new GmpIdentifier(setId); + return ret.Validate() ? ret : null; + } + + public JObject AddToJson(JObject jObj) + { + jObj["SetId"] = SetId.Id.ToString(); + return jObj; + } +} diff --git a/Penumbra/Meta/Manipulations/GmpManipulation.cs b/Penumbra/Meta/Manipulations/GmpManipulation.cs index ee58295d..0b2a9f4b 100644 --- a/Penumbra/Meta/Manipulations/GmpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GmpManipulation.cs @@ -8,14 +8,18 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct GmpManipulation : IMetaManipulation { - public GmpEntry Entry { get; private init; } - public PrimaryId SetId { get; private init; } + public GmpIdentifier Identifier { get; private init; } + + public GmpEntry Entry { get; private init; } + + public PrimaryId SetId + => Identifier.SetId; [JsonConstructor] public GmpManipulation(GmpEntry entry, PrimaryId setId) { - Entry = entry; - SetId = setId; + Entry = entry; + Identifier = new GmpIdentifier(setId); } public GmpManipulation Copy(GmpEntry entry) diff --git a/Penumbra/Meta/Manipulations/Rsp.cs b/Penumbra/Meta/Manipulations/Rsp.cs new file mode 100644 index 00000000..29cdfd71 --- /dev/null +++ b/Penumbra/Meta/Manipulations/Rsp.cs @@ -0,0 +1,52 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct RspIdentifier(SubRace SubRace, RspAttribute Attribute) : IMetaIdentifier +{ + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => changedItems.TryAdd($"{SubRace.ToName()} {Attribute.ToFullString()}", null); + + public MetaIndex FileIndex() + => throw new NotImplementedException(); + + public bool Validate() + => throw new NotImplementedException(); + + public JObject AddToJson(JObject jObj) + => throw new NotImplementedException(); +} + +[JsonConverter(typeof(Converter))] +public readonly record struct RspEntry(float Value) : IComparisonOperators +{ + public const float MinValue = 0.01f; + public const float MaxValue = 512f; + public static readonly RspEntry One = new(1f); + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, RspEntry value, JsonSerializer serializer) + => serializer.Serialize(writer, value.Value); + + public override RspEntry ReadJson(JsonReader reader, Type objectType, RspEntry existingValue, bool hasExistingValue, + JsonSerializer serializer) + => new(serializer.Deserialize(reader)); + } + + public static bool operator >(RspEntry left, RspEntry right) + => left.Value > right.Value; + + public static bool operator >=(RspEntry left, RspEntry right) + => left.Value >= right.Value; + + public static bool operator <(RspEntry left, RspEntry right) + => left.Value < right.Value; + + public static bool operator <=(RspEntry left, RspEntry right) + => left.Value <= right.Value; +} diff --git a/Penumbra/Meta/Manipulations/RspManipulation.cs b/Penumbra/Meta/Manipulations/RspManipulation.cs index 7e5e3fcb..04691c9f 100644 --- a/Penumbra/Meta/Manipulations/RspManipulation.cs +++ b/Penumbra/Meta/Manipulations/RspManipulation.cs @@ -9,25 +9,25 @@ namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct RspManipulation : IMetaManipulation { - public const float MinValue = 0.01f; - public const float MaxValue = 512f; - public float Entry { get; private init; } + public RspIdentifier Identifier { get; private init; } + public RspEntry Entry { get; private init; } [JsonConverter(typeof(StringEnumConverter))] - public SubRace SubRace { get; private init; } + public SubRace SubRace + => Identifier.SubRace; [JsonConverter(typeof(StringEnumConverter))] - public RspAttribute Attribute { get; private init; } + public RspAttribute Attribute + => Identifier.Attribute; [JsonConstructor] - public RspManipulation(SubRace subRace, RspAttribute attribute, float entry) + public RspManipulation(SubRace subRace, RspAttribute attribute, RspEntry entry) { - Entry = entry; - SubRace = subRace; - Attribute = attribute; + Entry = entry; + Identifier = new RspIdentifier(subRace, attribute); } - public RspManipulation Copy(float entry) + public RspManipulation Copy(RspEntry entry) => new(SubRace, Attribute, entry); public override string ToString() @@ -68,7 +68,7 @@ public readonly struct RspManipulation : IMetaManipulation return false; if (!Enum.IsDefined(Attribute)) return false; - if (Entry is < MinValue or > MaxValue) + if (Entry.Value is < RspEntry.MinValue or > RspEntry.MaxValue) return false; return true; diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index ea4ef7b1..3efee857 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -126,9 +126,9 @@ public static class EquipmentSwap var isAccessory = slot.IsAccessory(); var estType = slot switch { - EquipSlot.Head => EstManipulation.EstType.Head, - EquipSlot.Body => EstManipulation.EstType.Body, - _ => (EstManipulation.EstType)0, + EquipSlot.Head => EstType.Head, + EquipSlot.Body => EstType.Body, + _ => (EstType)0, }; var skipFemale = false; diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index b269d89c..7fac52c1 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -133,23 +133,23 @@ public static class ItemSwap } - public static FileSwap CreatePhyb(MetaFileManager manager, Func redirections, EstManipulation.EstType type, - GenderRace race, ushort estEntry) + public static FileSwap CreatePhyb(MetaFileManager manager, Func redirections, EstType type, + GenderRace race, EstEntry estEntry) { - var phybPath = GamePaths.Skeleton.Phyb.Path(race, EstManipulation.ToName(type), estEntry); + var phybPath = GamePaths.Skeleton.Phyb.Path(race, EstManipulation.ToName(type), estEntry.AsId); return FileSwap.CreateSwap(manager, ResourceType.Phyb, redirections, phybPath, phybPath); } - public static FileSwap CreateSklb(MetaFileManager manager, Func redirections, EstManipulation.EstType type, - GenderRace race, ushort estEntry) + public static FileSwap CreateSklb(MetaFileManager manager, Func redirections, EstType type, + GenderRace race, EstEntry estEntry) { - var sklbPath = GamePaths.Skeleton.Sklb.Path(race, EstManipulation.ToName(type), estEntry); + var sklbPath = GamePaths.Skeleton.Sklb.Path(race, EstManipulation.ToName(type), estEntry.AsId); return FileSwap.CreateSwap(manager, ResourceType.Sklb, redirections, sklbPath, sklbPath); } /// metaChanges is not manipulated, but IReadOnlySet does not support TryGetValue. public static MetaSwap? CreateEst(MetaFileManager manager, Func redirections, - Func manips, EstManipulation.EstType type, + Func manips, EstType type, GenderRace genderRace, PrimaryId idFrom, PrimaryId idTo, bool ownMdl) { if (type == 0) @@ -160,7 +160,7 @@ public static class ItemSwap var toDefault = new EstManipulation(gender, race, type, idTo, EstFile.GetDefault(manager, type, genderRace, idTo)); var est = new MetaSwap(manips, fromDefault, toDefault); - if (ownMdl && est.SwapApplied.Est.Entry >= 2) + if (ownMdl && est.SwapApplied.Est.Entry.Value >= 2) { var phyb = CreatePhyb(manager, redirections, type, genderRace, est.SwapApplied.Est.Entry); est.ChildSwaps.Add(phyb); diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 449405a0..48d687d0 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -152,9 +152,9 @@ public class ItemSwapContainer var mdl = CustomizationSwap.CreateMdl(manager, pathResolver, slot, race, from, to); var type = slot switch { - BodySlot.Hair => EstManipulation.EstType.Hair, - BodySlot.Face => EstManipulation.EstType.Face, - _ => (EstManipulation.EstType)0, + BodySlot.Hair => EstType.Hair, + BodySlot.Face => EstType.Face, + _ => (EstType)0, }; var metaResolver = MetaResolver(collection); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 0783dd98..b0a74637 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -453,7 +453,7 @@ public partial class ModEditWindow private static class EstRow { - private static EstManipulation _new = new(Gender.Male, ModelRace.Midlander, EstManipulation.EstType.Body, 1, 0); + private static EstManipulation _new = new(Gender.Male, ModelRace.Midlander, EstType.Body, 1, EstEntry.Zero); private static float IdWidth => 100 * UiHelpers.Scale; @@ -510,7 +510,7 @@ public partial class ModEditWindow // Values using var disabled = ImRaii.Disabled(); ImGui.TableNextColumn(); - IntDragInput("##estSkeleton", "Skeleton Index", IdWidth, _new.Entry, defaultEntry, out _, 0, ushort.MaxValue, 0.05f); + IntDragInput("##estSkeleton", "Skeleton Index", IdWidth, _new.Entry.Value, defaultEntry.Value, out _, 0, ushort.MaxValue, 0.05f); } public static void Draw(MetaFileManager metaFileManager, EstManipulation meta, ModEditor editor, Vector2 iconSize) @@ -538,9 +538,9 @@ public partial class ModEditWindow // Values var defaultEntry = EstFile.GetDefault(metaFileManager, meta.Slot, Names.CombinedRace(meta.Gender, meta.Race), meta.SetId); ImGui.TableNextColumn(); - if (IntDragInput("##estSkeleton", $"Skeleton Index\nDefault Value: {defaultEntry}", IdWidth, meta.Entry, defaultEntry, + if (IntDragInput("##estSkeleton", $"Skeleton Index\nDefault Value: {defaultEntry}", IdWidth, meta.Entry.Value, defaultEntry.Value, out var entry, 0, ushort.MaxValue, 0.05f)) - editor.MetaEditor.Change(meta.Copy((ushort)entry)); + editor.MetaEditor.Change(meta.Copy(new EstEntry((ushort)entry))); } } @@ -646,7 +646,7 @@ public partial class ModEditWindow private static class RspRow { - private static RspManipulation _new = new(SubRace.Midlander, RspAttribute.MaleMinSize, 1f); + private static RspManipulation _new = new(SubRace.Midlander, RspAttribute.MaleMinSize, RspEntry.One); private static float FloatWidth => 150 * UiHelpers.Scale; @@ -680,7 +680,8 @@ public partial class ModEditWindow using var disabled = ImRaii.Disabled(); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(FloatWidth); - ImGui.DragFloat("##rspValue", ref defaultEntry, 0f); + var value = defaultEntry.Value; + ImGui.DragFloat("##rspValue", ref value, 0f); } public static void Draw(MetaFileManager metaFileManager, RspManipulation meta, ModEditor editor, Vector2 iconSize) @@ -699,15 +700,15 @@ public partial class ModEditWindow ImGui.TableNextColumn(); // Values - var def = CmpFile.GetDefault(metaFileManager, meta.SubRace, meta.Attribute); - var value = meta.Entry; + var def = CmpFile.GetDefault(metaFileManager, meta.SubRace, meta.Attribute).Value; + var value = meta.Entry.Value; ImGui.SetNextItemWidth(FloatWidth); using var color = ImRaii.PushColor(ImGuiCol.FrameBg, def < value ? ColorId.IncreasedMetaValue.Value() : ColorId.DecreasedMetaValue.Value(), def != value); - if (ImGui.DragFloat("##rspValue", ref value, 0.001f, RspManipulation.MinValue, RspManipulation.MaxValue) - && value is >= RspManipulation.MinValue and <= RspManipulation.MaxValue) - editor.MetaEditor.Change(meta.Copy(value)); + if (ImGui.DragFloat("##rspValue", ref value, 0.001f, RspEntry.MinValue, RspEntry.MaxValue) + && value is >= RspEntry.MinValue and <= RspEntry.MaxValue) + editor.MetaEditor.Change(meta.Copy(new RspEntry(value))); ImGuiUtil.HoverTooltip($"Default Value: {def:0.###}"); } diff --git a/Penumbra/UI/Classes/Combos.cs b/Penumbra/UI/Classes/Combos.cs index 253bf0e0..234f7a3e 100644 --- a/Penumbra/UI/Classes/Combos.cs +++ b/Penumbra/UI/Classes/Combos.cs @@ -33,7 +33,7 @@ public static class Combos => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out attribute, RspAttributeExtensions.ToFullString, 0, 1); - public static bool EstSlot(string label, EstManipulation.EstType current, out EstManipulation.EstType attribute, float unscaledWidth = 200) + public static bool EstSlot(string label, EstType current, out EstType attribute, float unscaledWidth = 200) => ImGuiUtil.GenericEnumCombo(label, unscaledWidth * UiHelpers.Scale, current, out attribute); public static bool ImcType(string label, ObjectType current, out ObjectType type, float unscaledWidth = 110) diff --git a/Penumbra/Util/IdentifierExtensions.cs b/Penumbra/Util/IdentifierExtensions.cs index 7368c7c8..0647ea8e 100644 --- a/Penumbra/Util/IdentifierExtensions.cs +++ b/Penumbra/Util/IdentifierExtensions.cs @@ -51,18 +51,18 @@ public static class IdentifierExtensions case MetaManipulation.Type.Est: switch (manip.Est.Slot) { - case EstManipulation.EstType.Hair: + case EstType.Hair: changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Hair (Hair) {manip.Est.SetId}", null); break; - case EstManipulation.EstType.Face: + case EstType.Face: changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Face (Face) {manip.Est.SetId}", null); break; - case EstManipulation.EstType.Body: + case EstType.Body: identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), EquipSlot.Body)); break; - case EstManipulation.EstType.Head: + case EstType.Head: identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), EquipSlot.Head)); From 50a7e7efb7f0ea41583ab04b1dd6dd16ca2f992e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 7 Jun 2024 16:34:09 +0200 Subject: [PATCH 0658/1381] Add more filter options. --- OtterGui | 2 +- .../Meta/Manipulations/ImcManipulation.cs | 1 - Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 106 ++++---------- .../UI/ModsTab/ModSearchStringSplitter.cs | 138 ++++++++++++++++++ 4 files changed, 171 insertions(+), 76 deletions(-) create mode 100644 Penumbra/UI/ModsTab/ModSearchStringSplitter.cs diff --git a/OtterGui b/OtterGui index 5de708b2..ac176daf 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5de708b27ed45c9cdead71742c7061ad9ce64323 +Subproject commit ac176daf068f42d0b04a77dbc149f68a425fd460 diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs index eb3720c9..5065a06e 100644 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ b/Penumbra/Meta/Manipulations/ImcManipulation.cs @@ -1,6 +1,5 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; -using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 5b6cfa99..58f0b615 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -23,17 +23,20 @@ namespace Penumbra.UI.ModsTab; public sealed class ModFileSystemSelector : FileSystemSelector { - private readonly CommunicatorService _communicator; - private readonly MessageService _messager; - private readonly Configuration _config; - private readonly FileDialogService _fileDialog; - private readonly ModManager _modManager; - private readonly CollectionManager _collectionManager; - private readonly TutorialService _tutorial; - private readonly ModImportManager _modImportManager; - private readonly IDragDropManager _dragDrop; - public ModSettings SelectedSettings { get; private set; } = ModSettings.Empty; - public ModCollection SelectedSettingCollection { get; private set; } = ModCollection.Empty; + private readonly CommunicatorService _communicator; + private readonly MessageService _messager; + private readonly Configuration _config; + private readonly FileDialogService _fileDialog; + private readonly ModManager _modManager; + private readonly CollectionManager _collectionManager; + private readonly TutorialService _tutorial; + private readonly ModImportManager _modImportManager; + private readonly IDragDropManager _dragDrop; + private readonly ModSearchStringSplitter Filter = new(); + + public ModSettings SelectedSettings { get; private set; } = ModSettings.Empty; + public ModCollection SelectedSettingCollection { get; private set; } = ModCollection.Empty; + public ModFileSystemSelector(IKeyState keyState, CommunicatorService communicator, ModFileSystem fileSystem, ModManager modManager, CollectionManager collectionManager, Configuration config, TutorialService tutorial, FileDialogService fileDialog, @@ -568,78 +571,49 @@ public sealed class ModFileSystemSelector : FileSystemSelector Appropriately identify and set the string filter and its type. protected override bool ChangeFilter(string filterValue) { - (_modFilter, _filterType) = filterValue.Length switch - { - 0 => (LowerString.Empty, -1), - > 1 when filterValue[1] == ':' => - filterValue[0] switch - { - 'n' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 1), - 'N' => filterValue.Length == 2 ? (LowerString.Empty, -1) : (new LowerString(filterValue[2..]), 1), - 'a' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 2), - 'A' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 2), - 'c' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 3), - 'C' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 3), - 't' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 4), - 'T' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 4), - 's' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 5), - 'S' => filterValue.Length == 2 ? (LowerString.Empty, -1) : ParseFilter(filterValue, 5), - _ => (new LowerString(filterValue), 0), - }, - _ => (new LowerString(filterValue), 0), - }; - + Filter.Parse(filterValue); return true; } - private const int EmptyOffset = 128; - - private (LowerString, int) ParseFilter(string value, int id) - { - value = value[2..]; - var lower = new LowerString(value); - if (id == 5 && !ChangedItemDrawer.TryParsePartial(lower.Lower, out _slotFilter)) - _slotFilter = 0; - - return (lower, lower.Lower is "none" ? id + EmptyOffset : id); - } - - /// /// Check the state filter for a specific pair of has/has-not flags. /// Uses count == 0 to check for has-not and count != 0 for has. /// Returns true if it should be filtered and false if not. /// private bool CheckFlags(int count, ModFilter hasNoFlag, ModFilter hasFlag) - { - return count switch + => count switch { 0 when _stateFilter.HasFlag(hasNoFlag) => false, 0 => true, _ when _stateFilter.HasFlag(hasFlag) => false, _ => true, }; - } /// /// The overwritten filter method also computes the state. @@ -653,7 +627,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector 0 && !f.FullName().Contains(FilterValue, IgnoreCase); + || !Filter.IsVisible(f); } return ApplyFiltersAndState((ModFileSystem.Leaf)path, out state); @@ -661,23 +635,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Apply the string filters. private bool ApplyStringFilters(ModFileSystem.Leaf leaf, Mod mod) - { - return _filterType switch - { - -1 => false, - 0 => !(leaf.FullName().Contains(_modFilter.Lower, IgnoreCase) || mod.Name.Contains(_modFilter)), - 1 => !mod.Name.Contains(_modFilter), - 2 => !mod.Author.Contains(_modFilter), - 3 => !mod.LowerChangedItemsString.Contains(_modFilter.Lower), - 4 => !mod.AllTagsLower.Contains(_modFilter.Lower), - 5 => mod.ChangedItems.All(p => (ChangedItemDrawer.GetCategoryIcon(p.Key, p.Value) & _slotFilter) == 0), - 2 + EmptyOffset => !mod.Author.IsEmpty, - 3 + EmptyOffset => mod.LowerChangedItemsString.Length > 0, - 4 + EmptyOffset => mod.AllTagsLower.Length > 0, - 5 + EmptyOffset => mod.ChangedItems.Count == 0, - _ => false, // Should never happen - }; - } + => !Filter.IsVisible(leaf); /// Only get the text color for a mod if no filters are set. private ColorId GetTextColor(Mod mod, ModSettings? settings, ModCollection collection) diff --git a/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs b/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs new file mode 100644 index 00000000..1ea70731 --- /dev/null +++ b/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs @@ -0,0 +1,138 @@ +using OtterGui.Filesystem; +using OtterGui.Filesystem.Selector; +using Penumbra.Mods; +using Penumbra.Mods.Manager; + +namespace Penumbra.UI.ModsTab; + +public enum ModSearchType : byte +{ + Default = 0, + ChangedItem, + Tag, + Name, + Author, + Category, +} + +public sealed class ModSearchStringSplitter : SearchStringSplitter.Leaf, ModSearchStringSplitter.Entry> +{ + public readonly struct Entry : ISplitterEntry + { + public string Needle { get; init; } + public ModSearchType Type { get; init; } + public ChangedItemDrawer.ChangedItemIcon IconFilter { get; init; } + + public bool Contains(Entry other) + { + if (Type != other.Type) + return false; + if (Type is ModSearchType.Category) + return IconFilter == other.IconFilter; + + return Needle.Contains(other.Needle); + } + } + + protected override bool ConvertToken(char token, out ModSearchType val) + { + val = token switch + { + 'c' or 'C' => ModSearchType.ChangedItem, + 't' or 'T' => ModSearchType.Tag, + 'n' or 'N' => ModSearchType.Name, + 'a' or 'A' => ModSearchType.Author, + 's' or 'S' => ModSearchType.Category, + _ => ModSearchType.Default, + }; + return val is not ModSearchType.Default; + } + + protected override bool AllowsNone(ModSearchType val) + => val switch + { + ModSearchType.Author => true, + ModSearchType.ChangedItem => true, + ModSearchType.Tag => true, + ModSearchType.Category => true, + _ => false, + }; + + protected override void PostProcessing() + { + base.PostProcessing(); + HandleList(General); + HandleList(Forced); + HandleList(Negated); + return; + + static void HandleList(List list) + { + for (var i = 0; i < list.Count; ++i) + { + var entry = list[i]; + if (entry.Type is not ModSearchType.Category) + continue; + + if (ChangedItemDrawer.TryParsePartial(entry.Needle, out var icon)) + list[i] = entry with + { + IconFilter = icon, + Needle = string.Empty, + }; + else + list.RemoveAt(i--); + } + } + } + + public bool IsVisible(ModFileSystem.Folder folder) + { + switch (State) + { + case FilterState.NoFilters: return true; + case FilterState.NoMatches: return false; + } + + var fullName = folder.FullName(); + return Forced.All(i => MatchesName(i, folder.Name, fullName)) + && !Negated.Any(i => MatchesName(i, folder.Name, fullName)) + && (General.Count == 0 || General.Any(i => MatchesName(i, folder.Name, fullName))); + } + + protected override bool Matches(Entry entry, ModFileSystem.Leaf leaf) + => entry.Type switch + { + ModSearchType.Default => leaf.FullName().AsSpan().Contains(entry.Needle, StringComparison.OrdinalIgnoreCase) + || leaf.Value.Name.Lower.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), + ModSearchType.ChangedItem => leaf.Value.LowerChangedItemsString.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), + ModSearchType.Tag => leaf.Value.AllTagsLower.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), + ModSearchType.Name => leaf.Value.Name.Lower.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), + ModSearchType.Author => leaf.Value.Author.Lower.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), + ModSearchType.Category => leaf.Value.ChangedItems.Any(p + => (ChangedItemDrawer.GetCategoryIcon(p.Key, p.Value) & entry.IconFilter) != 0), + _ => true, + }; + + protected override bool MatchesNone(ModSearchType type, bool negated, ModFileSystem.Leaf haystack) + => type switch + { + ModSearchType.Author when negated => !haystack.Value.Author.IsEmpty, + ModSearchType.Author => haystack.Value.Author.IsEmpty, + ModSearchType.ChangedItem when negated => haystack.Value.LowerChangedItemsString.Length > 0, + ModSearchType.ChangedItem => haystack.Value.LowerChangedItemsString.Length == 0, + ModSearchType.Tag when negated => haystack.Value.AllTagsLower.Length > 0, + ModSearchType.Tag => haystack.Value.AllTagsLower.Length == 0, + ModSearchType.Category when negated => haystack.Value.ChangedItems.Count > 0, + ModSearchType.Category => haystack.Value.ChangedItems.Count == 0, + _ => true, + }; + + private static bool MatchesName(Entry entry, ReadOnlySpan name, ReadOnlySpan fullName) + => entry.Type switch + { + ModSearchType.Default => fullName.Contains(entry.Needle, StringComparison.OrdinalIgnoreCase), + ModSearchType.Name => name.Contains(entry.Needle, StringComparison.OrdinalIgnoreCase), + _ => false, + }; +} From 102e7335a7303526a6ae71c5f89194538c8c9f56 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 7 Jun 2024 14:40:25 +0000 Subject: [PATCH 0659/1381] [CI] Updating repo.json for testing_1.1.0.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 5e9e5b37..5d6a9ed8 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.0.2", - "TestingAssemblyVersion": "1.1.0.2", + "TestingAssemblyVersion": "1.1.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.0.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From de0309bfa7abcc925209086cbf88360bfaee1ee0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 12:45:12 +0200 Subject: [PATCH 0660/1381] Fix issue with ImcGroup settings and IPC. --- Penumbra/Api/Api/ModSettingsApi.cs | 27 +++++++++++++------------- Penumbra/Mods/Manager/ModDataEditor.cs | 6 ++---- Penumbra/Mods/Settings/ModSettings.cs | 4 ++-- 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 56b80e63..e046ce30 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -77,10 +77,10 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable if (!_collectionManager.Storage.ById(collectionId, out var collection)) return (PenumbraApiEc.CollectionMissing, null); - var settings = collection.Id == Guid.Empty - ? null - : ignoreInheritance - ? collection.Settings[mod.Index] + var settings = collection.Id == Guid.Empty + ? null + : ignoreInheritance + ? collection.Settings[mod.Index] : collection[mod.Index].Settings; if (settings == null) return (PenumbraApiEc.Success, null); @@ -160,11 +160,11 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); - var setting = mod.Groups[groupIdx] switch + var setting = mod.Groups[groupIdx].Behaviour switch { - MultiModGroup => Setting.Multi(optionIdx), - SingleModGroup => Setting.Single(optionIdx), - _ => Setting.Zero, + GroupDrawBehaviour.MultiSelection => Setting.Multi(optionIdx), + GroupDrawBehaviour.SingleSelection => Setting.Single(optionIdx), + _ => Setting.Zero, }; var ret = _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success @@ -191,20 +191,20 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable var setting = Setting.Zero; switch (mod.Groups[groupIdx]) { - case SingleModGroup single: + case { Behaviour: GroupDrawBehaviour.SingleSelection } single: { - var optionIdx = optionNames.Count == 0 ? -1 : single.OptionData.IndexOf(o => o.Name == optionNames[^1]); + var optionIdx = optionNames.Count == 0 ? -1 : single.Options.IndexOf(o => o.Name == optionNames[^1]); if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); setting = Setting.Single(optionIdx); break; } - case MultiModGroup multi: + case { Behaviour: GroupDrawBehaviour.MultiSelection } multi: { foreach (var name in optionNames) { - var optionIdx = multi.OptionData.IndexOf(o => o.Mod.Name == name); + var optionIdx = multi.Options.IndexOf(o => o.Name == name); if (optionIdx < 0) return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); @@ -256,7 +256,8 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting _1, int _2, bool inherited) => ModSettingChanged?.Invoke(type, collection.Id, mod?.ModPath.Name ?? string.Empty, inherited); - private void OnModOptionEdited(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int moveIndex) + private void OnModOptionEdited(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, + int moveIndex) { switch (type) { diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index e0af6f36..c7c7c2cc 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -50,7 +50,6 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic var save = true; if (File.Exists(dataFile)) { - save = false; try { var text = File.ReadAllText(dataFile); @@ -60,6 +59,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic favorite = json[nameof(Mod.Favorite)]?.Value() ?? favorite; note = json[nameof(Mod.Note)]?.Value() ?? note; localTags = json[nameof(Mod.LocalTags)]?.Values().OfType() ?? localTags; + save = false; } catch (Exception e) { @@ -239,7 +239,6 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic mod.Favorite = state; saveService.QueueSave(new ModLocalData(mod)); - ; communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); } @@ -250,7 +249,6 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic mod.Note = newNote; saveService.QueueSave(new ModLocalData(mod)); - ; communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); } @@ -260,7 +258,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic if (tagIdx < 0 || tagIdx > which.Count) return; - ModDataChangeType flags = 0; + ModDataChangeType flags; if (tagIdx == which.Count) { flags = ModLocalData.UpdateTags(mod, local ? null : which.Append(newTag), local ? which.Append(newTag) : null); diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index 7fe48365..25e4805d 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -185,10 +185,10 @@ public class ModSettings switch (mod.Groups[idx]) { - case SingleModGroup single when setting.Value < (ulong)single.Options.Count: + case { Behaviour: GroupDrawBehaviour.SingleSelection } single when setting.Value < (ulong)single.Options.Count: dict.Add(single.Name, [single.Options[setting.AsIndex].Name]); break; - case MultiModGroup multi: + case { Behaviour: GroupDrawBehaviour.MultiSelection } multi: var list = multi.Options.WithIndex().Where(p => setting.HasFlag(p.Index)).Select(p => p.Value.Name).ToList(); dict.Add(multi.Name, list); break; From e884b269a9ca3f2ea4c6ef63cf7da9e53d1353cb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 14:55:42 +0200 Subject: [PATCH 0661/1381] Add a version field to mod group files. --- Penumbra/Mods/Groups/ModSaveGroup.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index 05437e3d..c82c67c7 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -6,6 +6,8 @@ namespace Penumbra.Mods.Groups; public readonly struct ModSaveGroup : ISavable { + public const int CurrentVersion = 0; + private readonly DirectoryInfo _basePath; private readonly IModGroup? _group; private readonly int _groupIdx; @@ -71,6 +73,8 @@ public readonly struct ModSaveGroup : ISavable j.Formatting = Formatting.Indented; var serializer = new JsonSerializer { Formatting = Formatting.Indented }; j.WriteStartObject(); + j.WritePropertyName("Version"); + j.WriteValue(CurrentVersion); if (_groupIdx >= 0) _group!.WriteJson(j, serializer, _basePath); else From 159942f29c229f3dafef7275c553cc9f7e2183b6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 20:33:07 +0200 Subject: [PATCH 0662/1381] Add by-name identification in the lobby. --- .../PathResolving/CollectionResolver.cs | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index aea58304..ed111794 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.UI.Agent; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -7,6 +8,8 @@ using Penumbra.GameData.Actors; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; +using Penumbra.GameData.Structs; +using Penumbra.String; using Penumbra.Util; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; using GameObject = FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject; @@ -94,14 +97,8 @@ public sealed unsafe class CollectionResolver( public bool IsModelHuman(uint modelCharaId) => humanModels.IsHuman(modelCharaId); - /// Return whether the given character has a human model. - public bool IsModelHuman(Character* character) - => character != null && IsModelHuman((uint)character->CharacterData.ModelCharaId); - /// - /// Used if on the Login screen. Names are populated after actors are drawn, - /// so it is not possible to fetch names from the ui list. - /// Actors are also not named. So use Yourself > Players > Racial > Default. + /// Used if on the Login screen. /// private bool LoginScreen(GameObject* gameObject, out ResolveData ret) { @@ -114,6 +111,27 @@ public sealed unsafe class CollectionResolver( } var notYetReady = false; + var lobby = AgentLobby.Instance(); + if (lobby != null) + { + var span = lobby->LobbyData.CharaSelectEntries.Span; + // The lobby uses the first 8 cutscene actors. + var idx = gameObject->ObjectIndex - ObjectIndex.CutsceneStart.Index; + if (idx >= 0 && idx < span.Length && span[idx].Value != null) + { + var item = span[idx].Value; + var identifier = actors.CreatePlayer(new ByteString(item->Name), item->HomeWorldId); + Penumbra.Log.Verbose( + $"Identified {identifier.Incognito(null)} in cutscene for actor {idx + 200} at 0x{(ulong)gameObject:X} of race {(gameObject->IsCharacter() ? ((Character*)gameObject)->DrawData.CustomizeData.Race.ToString() : "Unknown")}."); + if (identifier.IsValid && CollectionByIdentifier(identifier) is { } coll) + { + // Do not add this to caches because game objects are reused for different draw objects. + ret = coll.ToResolveData(gameObject); + return true; + } + } + } + var collection = collectionManager.Active.ByType(CollectionType.Yourself) ?? CollectionByAttributes(gameObject, ref notYetReady) ?? collectionManager.Active.Default; @@ -189,7 +207,7 @@ public sealed unsafe class CollectionResolver( return null; // Only handle human models. - + if (!IsModelHuman((uint)actor.AsCharacter->CharacterData.ModelCharaId)) return null; From f51fc2cafd985cf3b3cca605f74b85639cf8036f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Jun 2024 22:05:19 +0200 Subject: [PATCH 0663/1381] Allow root directory overwriting with case sensitivity. --- Penumbra/Mods/Manager/ModManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index adaca85e..010cad19 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -266,7 +266,7 @@ public sealed class ModManager : ModStorage, IDisposable /// private void SetBaseDirectory(string newPath, bool firstTime) { - if (!firstTime && string.Equals(newPath, _config.ModDirectory, StringComparison.OrdinalIgnoreCase)) + if (!firstTime && string.Equals(newPath, _config.ModDirectory, StringComparison.Ordinal)) return; if (newPath.Length == 0) From f6b35497c5610acc00663ea31e9c69190ff3e357 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Jun 2024 22:05:37 +0200 Subject: [PATCH 0664/1381] Change path comparison for AddMod. --- Penumbra/Api/Api/ModsApi.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 16dd8be9..548831d5 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -75,7 +75,7 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable if (!dir.Exists) return ApiHelpers.Return(PenumbraApiEc.FileMissing, args); - if (_modManager.BasePath.FullName != dir.Parent?.FullName) + if (dir.Parent == null || Path.GetFullPath(_modManager.BasePath.FullName) != Path.GetFullPath(dir.Parent.FullName)) return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); _modManager.AddMod(dir); From f7adc83d631936bf76446af1205a333baa260c44 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Jun 2024 22:06:18 +0200 Subject: [PATCH 0665/1381] Fix issue with preview of file in advanced model editing. --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 110 ++++++++++-------- 1 file changed, 61 insertions(+), 49 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index a7d39c6e..bbed64b7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,5 +1,4 @@ using Dalamud.Interface; -using Dalamud.Interface.Components; using ImGuiNET; using Lumina.Data.Parsing; using OtterGui; @@ -27,44 +26,56 @@ public partial class ModEditWindow private readonly FileEditor _modelTab; private readonly ModelManager _models; + private class LoadedData + { + public MdlFile LastFile = null!; + public readonly List SubMeshAttributeTags = []; + public long[] LodTriCount = []; + } + private string _modelNewMaterial = string.Empty; - private readonly List _subMeshAttributeTagWidgets = []; + + private readonly LoadedData _main = new(); + private readonly LoadedData _preview = new(); + private string _customPath = string.Empty; private Utf8GamePath _customGamePath = Utf8GamePath.Empty; - private MdlFile _lastFile = null!; - private long[] _lodTriCount = []; - private void UpdateFile(MdlFile file, bool force) + + + private LoadedData UpdateFile(MdlFile file, bool force, bool disabled) { - if (file == _lastFile && !force) - return; + var data = disabled ? _preview : _main; + if (file == data.LastFile && !force) + return data; - _lastFile = file; + data.LastFile = file; var subMeshTotal = file.Meshes.Aggregate(0, (count, mesh) => count + mesh.SubMeshCount); - if (_subMeshAttributeTagWidgets.Count != subMeshTotal) + if (data.SubMeshAttributeTags.Count != subMeshTotal) { - _subMeshAttributeTagWidgets.Clear(); - _subMeshAttributeTagWidgets.AddRange( + data.SubMeshAttributeTags.Clear(); + data.SubMeshAttributeTags.AddRange( Enumerable.Range(0, subMeshTotal).Select(_ => new TagButtons()) ); } - _lodTriCount = Enumerable.Range(0, file.Lods.Length).Select(l => GetTriangleCountForLod(file, l)).ToArray(); + data.LodTriCount = Enumerable.Range(0, file.Lods.Length).Select(l => GetTriangleCountForLod(file, l)).ToArray(); + return data; } private bool DrawModelPanel(MdlTab tab, bool disabled) { var ret = tab.Dirty; - UpdateFile(tab.Mdl, ret); + var data = UpdateFile(tab.Mdl, ret, disabled); DrawImportExport(tab, disabled); ret |= DrawModelMaterialDetails(tab, disabled); - if (ImGui.CollapsingHeader($"Meshes ({_lastFile.Meshes.Length})###meshes")) - for (var i = 0; i < _lastFile.LodCount; ++i) + if (ImGui.CollapsingHeader($"Meshes ({data.LastFile.Meshes.Length})###meshes")) + for (var i = 0; i < data.LastFile.LodCount; ++i) ret |= DrawModelLodDetails(tab, i, disabled); - ret |= DrawOtherModelDetails(disabled); + ret |= DrawOtherModelDetails(data); return !disabled && ret; } @@ -98,7 +109,7 @@ public partial class ModEditWindow return true; }); - using (var frame = ImRaii.FramedGroup("Import", size, headerPreIcon: FontAwesomeIcon.FileImport)) + using (ImRaii.FramedGroup("Import", size, headerPreIcon: FontAwesomeIcon.FileImport)) { ImGui.Checkbox("Keep current materials", ref tab.ImportKeepMaterials); ImGui.Checkbox("Keep current attributes", ref tab.ImportKeepAttributes); @@ -232,7 +243,7 @@ public partial class ModEditWindow if (!ImGui.InputTextWithHint("##customInput", "Enter custom game path...", ref _customPath, 256)) return; - if (!Utf8GamePath.FromString(_customPath, out _customGamePath, false)) + if (!Utf8GamePath.FromString(_customPath, out _customGamePath)) _customGamePath = Utf8GamePath.Empty; } @@ -399,9 +410,9 @@ public partial class ModEditWindow return ret; } - private void DrawInvalidMaterialMarker() + private static void DrawInvalidMaterialMarker() { - using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + using (ImRaii.PushFont(UiBuilder.IconFont)) ImGuiUtil.TextColored(0xFF0000FF, FontAwesomeIcon.TimesCircle.ToIconString()); ImGuiUtil.HoverTooltip( @@ -534,7 +545,8 @@ public partial class ModEditWindow ImGui.TextUnformatted($"Attributes #{subMeshOffset + 1}"); ImGui.TableNextColumn(); - var widget = _subMeshAttributeTagWidgets[subMeshIndex]; + var data = disabled ? _preview : _main; + var widget = data.SubMeshAttributeTags[subMeshIndex]; var attributes = tab.GetSubMeshAttributes(subMeshIndex); if (attributes == null) @@ -555,7 +567,7 @@ public partial class ModEditWindow return true; } - private bool DrawOtherModelDetails(bool _) + private bool DrawOtherModelDetails(LoadedData data) { using var header = ImRaii.CollapsingHeader("Further Content"); if (!header) @@ -566,44 +578,44 @@ public partial class ModEditWindow if (table) { ImGuiUtil.DrawTableColumn("Version"); - ImGuiUtil.DrawTableColumn($"0x{_lastFile.Version:X}"); + ImGuiUtil.DrawTableColumn($"0x{data.LastFile.Version:X}"); ImGuiUtil.DrawTableColumn("Radius"); - ImGuiUtil.DrawTableColumn(_lastFile.Radius.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(data.LastFile.Radius.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("Model Clip Out Distance"); - ImGuiUtil.DrawTableColumn(_lastFile.ModelClipOutDistance.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(data.LastFile.ModelClipOutDistance.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("Shadow Clip Out Distance"); - ImGuiUtil.DrawTableColumn(_lastFile.ShadowClipOutDistance.ToString(CultureInfo.InvariantCulture)); + ImGuiUtil.DrawTableColumn(data.LastFile.ShadowClipOutDistance.ToString(CultureInfo.InvariantCulture)); ImGuiUtil.DrawTableColumn("LOD Count"); - ImGuiUtil.DrawTableColumn(_lastFile.LodCount.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.LodCount.ToString()); ImGuiUtil.DrawTableColumn("Enable Index Buffer Streaming"); - ImGuiUtil.DrawTableColumn(_lastFile.EnableIndexBufferStreaming.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.EnableIndexBufferStreaming.ToString()); ImGuiUtil.DrawTableColumn("Enable Edge Geometry"); - ImGuiUtil.DrawTableColumn(_lastFile.EnableEdgeGeometry.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.EnableEdgeGeometry.ToString()); ImGuiUtil.DrawTableColumn("Flags 1"); - ImGuiUtil.DrawTableColumn(_lastFile.Flags1.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.Flags1.ToString()); ImGuiUtil.DrawTableColumn("Flags 2"); - ImGuiUtil.DrawTableColumn(_lastFile.Flags2.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.Flags2.ToString()); ImGuiUtil.DrawTableColumn("Vertex Declarations"); - ImGuiUtil.DrawTableColumn(_lastFile.VertexDeclarations.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.VertexDeclarations.Length.ToString()); ImGuiUtil.DrawTableColumn("Bone Bounding Boxes"); - ImGuiUtil.DrawTableColumn(_lastFile.BoneBoundingBoxes.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.BoneBoundingBoxes.Length.ToString()); ImGuiUtil.DrawTableColumn("Bone Tables"); - ImGuiUtil.DrawTableColumn(_lastFile.BoneTables.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.BoneTables.Length.ToString()); ImGuiUtil.DrawTableColumn("Element IDs"); - ImGuiUtil.DrawTableColumn(_lastFile.ElementIds.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.ElementIds.Length.ToString()); ImGuiUtil.DrawTableColumn("Extra LoDs"); - ImGuiUtil.DrawTableColumn(_lastFile.ExtraLods.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.ExtraLods.Length.ToString()); ImGuiUtil.DrawTableColumn("Meshes"); - ImGuiUtil.DrawTableColumn(_lastFile.Meshes.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.Meshes.Length.ToString()); ImGuiUtil.DrawTableColumn("Shape Meshes"); - ImGuiUtil.DrawTableColumn(_lastFile.ShapeMeshes.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.ShapeMeshes.Length.ToString()); ImGuiUtil.DrawTableColumn("LoDs"); - ImGuiUtil.DrawTableColumn(_lastFile.Lods.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.Lods.Length.ToString()); ImGuiUtil.DrawTableColumn("Vertex Declarations"); - ImGuiUtil.DrawTableColumn(_lastFile.VertexDeclarations.Length.ToString()); + ImGuiUtil.DrawTableColumn(data.LastFile.VertexDeclarations.Length.ToString()); ImGuiUtil.DrawTableColumn("Stack Size"); - ImGuiUtil.DrawTableColumn(_lastFile.StackSize.ToString()); - foreach (var (triCount, lod) in _lodTriCount.WithIndex()) + ImGuiUtil.DrawTableColumn(data.LastFile.StackSize.ToString()); + foreach (var (triCount, lod) in data.LodTriCount.WithIndex()) { ImGuiUtil.DrawTableColumn($"LOD #{lod + 1} Triangle Count"); ImGuiUtil.DrawTableColumn(triCount.ToString()); @@ -614,36 +626,36 @@ public partial class ModEditWindow using (var materials = ImRaii.TreeNode("Materials", ImGuiTreeNodeFlags.DefaultOpen)) { if (materials) - foreach (var material in _lastFile.Materials) + foreach (var material in data.LastFile.Materials) ImRaii.TreeNode(material, ImGuiTreeNodeFlags.Leaf).Dispose(); } using (var attributes = ImRaii.TreeNode("Attributes", ImGuiTreeNodeFlags.DefaultOpen)) { if (attributes) - foreach (var attribute in _lastFile.Attributes) + foreach (var attribute in data.LastFile.Attributes) ImRaii.TreeNode(attribute, ImGuiTreeNodeFlags.Leaf).Dispose(); } using (var bones = ImRaii.TreeNode("Bones", ImGuiTreeNodeFlags.DefaultOpen)) { if (bones) - foreach (var bone in _lastFile.Bones) + foreach (var bone in data.LastFile.Bones) ImRaii.TreeNode(bone, ImGuiTreeNodeFlags.Leaf).Dispose(); } using (var shapes = ImRaii.TreeNode("Shapes", ImGuiTreeNodeFlags.DefaultOpen)) { if (shapes) - foreach (var shape in _lastFile.Shapes) + foreach (var shape in data.LastFile.Shapes) ImRaii.TreeNode(shape.ShapeName, ImGuiTreeNodeFlags.Leaf).Dispose(); } - if (_lastFile.RemainingData.Length > 0) + if (data.LastFile.RemainingData.Length > 0) { - using var t = ImRaii.TreeNode($"Additional Data (Size: {_lastFile.RemainingData.Length})###AdditionalData"); + using var t = ImRaii.TreeNode($"Additional Data (Size: {data.LastFile.RemainingData.Length})###AdditionalData"); if (t) - Widget.DrawHexViewer(_lastFile.RemainingData); + Widget.DrawHexViewer(data.LastFile.RemainingData); } return false; From ecd5752d16d14f64ed15775a43459b2006c78593 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Jun 2024 22:12:55 +0200 Subject: [PATCH 0666/1381] Make imc attribute letter tooltip appear on disabled. --- Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index d346e05c..5c8edce6 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -148,7 +148,7 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr } } - ImUtf8.HoverTooltip("ABCDEFGHIJ"u8.Slice(i, 1)); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "ABCDEFGHIJ"u8.Slice(i, 1)); if (i != 9) ImUtf8.SameLineInner(); } From 30a87e3f402495517d067235f8235fbf46c3ba81 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 11 Jun 2024 12:28:33 +0200 Subject: [PATCH 0667/1381] Update valid world check. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index ac176daf..e95c0f04 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit ac176daf068f42d0b04a77dbc149f68a425fd460 +Subproject commit e95c0f04edc7e85aea67498fd8bf495a7fe6d3c8 diff --git a/Penumbra.GameData b/Penumbra.GameData index ad12ddce..6aeae346 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ad12ddcef38a9ed4e4dd7424d748f41c4b97db10 +Subproject commit 6aeae346332a255b7575ccfca554afb0f3cf1494 From 863a7edf0ee57c2e5abadb59cad8cd4d85e5272d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 11 Jun 2024 12:50:13 +0200 Subject: [PATCH 0668/1381] Add changelog. --- Penumbra/Penumbra.cs | 1 - Penumbra/UI/Changelog.cs | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 42be0aa3..3bbfdf65 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -20,7 +20,6 @@ using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; using Penumbra.GameData.Enums; using Penumbra.UI; -using IPenumbraApi = Penumbra.Api.Api.IPenumbraApi; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra; diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 3f5a446a..184633f2 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -50,10 +50,39 @@ public class PenumbraChangelog AddDummy(Changelog); AddDummy(Changelog); Add1_1_0_0(Changelog); - } - + Add1_1_1_0(Changelog); + } + #region Changelogs + private static void Add1_1_1_0(Changelog log) + => log.NextVersion("Version 1.1.1.0") + .RegisterHighlight("Filtering for mods is now tokenized and can filter for multiple things at once, or exclude specific things.") + .RegisterEntry("Hover over the filter to see the new available options in the tooltip.", 1) + .RegisterEntry("Be aware that the tokenization changed the prior behavior slightly.", 1) + .RegisterEntry("This is open to improvements, if you have any ideas, let me know!", 1) + .RegisterHighlight("Added initial identification of characters in the login-screen by name.") + .RegisterEntry("Those characters can not be redrawn and re-use some things, so this may not always behave as expected, but should work in general. Let me know if you encounter edge cases!", 1) + .RegisterEntry("Added functionality for IMC groups to apply to all variants for a model instead of a specific one.") + .RegisterEntry("Improved the resource tree view with filters and incognito mode. (by Ny)") + .RegisterEntry("Added a tooltip to the global EQP condition.") + .RegisterEntry("Fixed the new worlds not being identified correctly because Square Enix could not be bothered to turn them public.") + .RegisterEntry("Fixed model import getting stuck when doing weight adjustments. (by ackwell)") + .RegisterEntry("Fixed an issue with dye previews in the material editor not applying.") + .RegisterEntry("Fixed an issue with collections not saving on renames.") + .RegisterEntry("Fixed an issue parsing collections with settings set to negative values, which should now be set to 0.") + .RegisterEntry("Fixed an issue with the accessory VFX addition.") + .RegisterEntry("Fixed an issue with GMP animation type entries.") + .RegisterEntry("Fixed another issue with the mod merger.") + .RegisterEntry("Fixed an issue with IMC groups and IPC.") + .RegisterEntry("Fixed some issues with the capitalization of the root directory.") + .RegisterEntry("Fixed IMC attribute tooltips not appearing for disabled checkboxes.") + .RegisterEntry("Added GetChangedItems IPC for single mods. (1.1.0.2)") + .RegisterEntry("Fixed an issue with creating unnamed collections. (1.1.0.2)") + .RegisterEntry("Fixed an issue with the mod merger. (1.1.0.2)") + .RegisterEntry("Fixed the global EQP entry for rings checking for bracelets instead of rings. (1.1.0.2)") + .RegisterEntry("Fixed an issue with newly created collections not being added to the collection list. (1.1.0.1)"); + private static void Add1_1_0_0(Changelog log) => log.NextVersion("Version 1.1.0.0") .RegisterImportant( From c8ea33f8dddff7a8ee7bc92791a54c3d20c45f12 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 11 Jun 2024 10:52:49 +0000 Subject: [PATCH 0669/1381] [CI] Updating repo.json for 1.1.1.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 5d6a9ed8..05de7ec7 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.1.0.2", - "TestingAssemblyVersion": "1.1.0.3", + "AssemblyVersion": "1.1.1.0", + "TestingAssemblyVersion": "1.1.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,9 +17,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.0.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.0.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 447735f6091db767d5d06a39cb8959b3aaebc279 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 11 Jun 2024 16:32:29 +0200 Subject: [PATCH 0670/1381] Add a configuration to disable showing mods in the lobby and at the aesthetician. --- Penumbra/Configuration.cs | 1 + .../Interop/PathResolving/CollectionResolver.cs | 13 +++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 3 +++ 3 files changed, 17 insertions(+) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index b81e84d8..02286cc7 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -41,6 +41,7 @@ public class Configuration : IPluginConfiguration, ISavable public bool HideUiWhenUiHidden { get; set; } = false; public bool UseDalamudUiTextureRedirection { get; set; } = true; + public bool ShowModsInLobby { get; set; } = true; public bool UseCharacterCollectionInMainWindow { get; set; } = true; public bool UseCharacterCollectionsInCards { get; set; } = true; public bool UseCharacterCollectionInInspect { get; set; } = true; diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index ed111794..b42571ac 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.UI.Agent; +using Microsoft.VisualBasic; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -110,6 +111,12 @@ public sealed unsafe class CollectionResolver( return false; } + if (!config.ShowModsInLobby) + { + ret = ModCollection.Empty.ToResolveData(gameObject); + return true; + } + var notYetReady = false; var lobby = AgentLobby.Instance(); if (lobby != null) @@ -148,6 +155,12 @@ public sealed unsafe class CollectionResolver( return false; } + if (!config.ShowModsInLobby) + { + ret = ModCollection.Empty.ToResolveData(gameObject); + return true; + } + var player = actors.GetCurrentPlayer(); var notYetReady = false; var collection = (player.IsValid ? CollectionByIdentifier(player) : null) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 30384538..9989f90a 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -449,6 +449,9 @@ public class SettingsTab : ITab Checkbox("Use Interface Collection for other Plugin UIs", "Use the collection assigned to your interface for other plugins requesting UI-textures and icons through Dalamud.", _dalamudSubstitutionProvider.Enabled, _dalamudSubstitutionProvider.Set); + Checkbox($"Use {TutorialService.AssignedCollections} in Lobby", + "If this is disabled, no mods are applied to characters in the lobby or at the aesthetician.", + _config.ShowModsInLobby, v => _config.ShowModsInLobby = v); Checkbox($"Use {TutorialService.AssignedCollections} in Character Window", "Use the individual collection for your characters name or the Your Character collection in your main character window, if it is set.", _config.UseCharacterCollectionInMainWindow, v => _config.UseCharacterCollectionInMainWindow = v); From 2346b7588a49049012f240eec2c1cad912c4b86c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Jun 2024 13:39:25 +0200 Subject: [PATCH 0671/1381] Fix GMP bug. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 6aeae346..0a2e2650 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 6aeae346332a255b7575ccfca554afb0f3cf1494 +Subproject commit 0a2e2650d693d1bba267498f96112682cc09dbab From 532e8a0936acd38cdfe1701bc62c3f57d06c58ff Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 14 Jun 2024 12:11:16 +0000 Subject: [PATCH 0672/1381] [CI] Updating repo.json for 1.1.1.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 05de7ec7..318aafc2 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.1.1.0", - "TestingAssemblyVersion": "1.1.1.0", + "AssemblyVersion": "1.1.1.1", + "TestingAssemblyVersion": "1.1.1.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -17,9 +17,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From b1a059038221960133882e7b45dc697efd694981 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Jun 2024 23:08:04 +0200 Subject: [PATCH 0673/1381] Make modmerger file lookup case insensitive. --- Penumbra/Mods/Editor/ModMerger.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 8d47051c..74f182d3 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -196,7 +196,7 @@ public class ModMerger : IDisposable { if (fromFileToFile) { - if (!_fileToFile.TryGetValue(input.FullName, out var s)) + if (!_fileToFile.TryGetValue(input.FullName.ToLowerInvariant(), out var s)) { ret = input; return false; @@ -238,7 +238,7 @@ public class ModMerger : IDisposable Directory.CreateDirectory(finalDir); file.CopyTo(path); Penumbra.Log.Verbose($"[Merger] Copied file {file.FullName} to {path}."); - _fileToFile.Add(file.FullName, path); + _fileToFile.Add(file.FullName.ToLowerInvariant(), path); } } From ec207bdba2c01448250f6cbc3dc8e980a720fac1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 20:48:37 +0200 Subject: [PATCH 0674/1381] Force saves independent of manipulations for swaps and merges. --- Penumbra/Mods/Editor/ModMerger.cs | 18 +++++++++++------- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 3 ++- .../Manager/OptionEditor/ModGroupEditor.cs | 4 ++++ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 74f182d3..f5fc9cd7 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -189,7 +189,8 @@ public class ModMerger : IDisposable _editor.SetFiles(option, redirections, SaveType.None); _editor.SetFileSwaps(option, swaps, SaveType.None); - _editor.SetManipulations(option, manips, SaveType.ImmediateSync); + _editor.SetManipulations(option, manips, SaveType.None); + _editor.ForceSave(option, SaveType.ImmediateSync); return; bool GetFullPath(FullPath input, out FullPath ret) @@ -263,9 +264,10 @@ public class ModMerger : IDisposable if (mods.Count == 1) { var files = CopySubModFiles(mods[0], dir); - _editor.SetFiles(result.Default, files); - _editor.SetFileSwaps(result.Default, mods[0].FileSwaps); - _editor.SetManipulations(result.Default, mods[0].Manipulations); + _editor.SetFiles(result.Default, files, SaveType.None); + _editor.SetFileSwaps(result.Default, mods[0].FileSwaps, SaveType.None); + _editor.SetManipulations(result.Default, mods[0].Manipulations, SaveType.None); + _editor.ForceSave(result.Default); } else { @@ -277,6 +279,7 @@ public class ModMerger : IDisposable _editor.SetFiles(result.Default, files); _editor.SetFileSwaps(result.Default, mods[0].FileSwaps); _editor.SetManipulations(result.Default, mods[0].Manipulations); + _editor.ForceSave(result.Default); } else { @@ -285,9 +288,10 @@ public class ModMerger : IDisposable var (option, _, _) = _editor.FindOrAddOption(group!, originalOption.GetName()); var folder = Path.Combine(dir.FullName, group!.Name, option!.Name); var files = CopySubModFiles(originalOption, new DirectoryInfo(folder)); - _editor.SetFiles((IModDataContainer)option, files); - _editor.SetFileSwaps((IModDataContainer)option, originalOption.FileSwaps); - _editor.SetManipulations((IModDataContainer)option, originalOption.Manipulations); + _editor.SetFiles((IModDataContainer)option, files, SaveType.None); + _editor.SetFileSwaps((IModDataContainer)option, originalOption.FileSwaps, SaveType.None); + _editor.SetManipulations((IModDataContainer)option, originalOption.Manipulations, SaveType.None); + _editor.ForceSave((IModDataContainer)option); } } } diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 48d687d0..af5b2d3a 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -83,7 +83,8 @@ public class ItemSwapContainer manager.OptionEditor.SetFiles(container, convertedFiles, SaveType.None); manager.OptionEditor.SetFileSwaps(container, convertedSwaps, SaveType.None); - manager.OptionEditor.SetManipulations(container, convertedManips, SaveType.ImmediateSync); + manager.OptionEditor.SetManipulations(container, convertedManips, SaveType.None); + manager.OptionEditor.ForceSave(container, SaveType.ImmediateSync); return true; } catch (Exception e) diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index e1db0ccf..55e01015 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -166,6 +166,10 @@ public class ModGroupEditor( communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } + /// Forces a file save of the given container's group. + public void ForceSave(IModDataContainer subMod, SaveType saveType = SaveType.Queue) + => saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. public void AddFiles(IModDataContainer subMod, IReadOnlyDictionary additions) { From b3f87624949c9c48de7bc847782601577bd86336 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 17 Jun 2024 14:50:07 +0200 Subject: [PATCH 0675/1381] Fix some crash handler issues --- Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs | 2 ++ Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs | 2 ++ Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs | 4 ++++ 3 files changed, 8 insertions(+) diff --git a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs index 3446530a..11dc52db 100644 --- a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs @@ -55,8 +55,10 @@ internal sealed class AnimationInvocationBuffer : MemoryMappedBuffer, IAnimation accessor.Write(16, characterAddress); var span = GetSpan(accessor, 24, 16); collectionId.TryWriteBytes(span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); span = GetSpan(accessor, 40); WriteSpan(characterName, span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); } } diff --git a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs index 4036455d..a48fe846 100644 --- a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs @@ -38,8 +38,10 @@ internal sealed class CharacterBaseBuffer : MemoryMappedBuffer, ICharacterBaseBu accessor.Write(12, characterAddress); var span = GetSpan(accessor, 20, 16); collectionId.TryWriteBytes(span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); span = GetSpan(accessor, 36); WriteSpan(characterName, span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); } } diff --git a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs index 03f63ba4..ac507e7f 100644 --- a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs @@ -44,12 +44,16 @@ internal sealed class ModdedFileBuffer : MemoryMappedBuffer, IModdedFileBufferWr accessor.Write(12, characterAddress); var span = GetSpan(accessor, 20, 16); collectionId.TryWriteBytes(span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); span = GetSpan(accessor, 36, 80); WriteSpan(characterName, span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); span = GetSpan(accessor, 116, 260); WriteSpan(requestedFileName, span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); span = GetSpan(accessor, 376); WriteSpan(actualFileName, span); + accessor.SafeMemoryMappedViewHandle.ReleasePointer(); } } From 250c4034e04323b025cd39cd4641be8e04d431ce Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 17 Jun 2024 14:50:33 +0200 Subject: [PATCH 0676/1381] Improve root directory behavior and AddMods. --- Penumbra/Api/Api/ModsApi.cs | 4 +++- Penumbra/Mods/Manager/ModManager.cs | 16 +++++++++------- Penumbra/UI/Tabs/SettingsTab.cs | 2 +- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 548831d5..60b00d37 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -75,7 +75,9 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable if (!dir.Exists) return ApiHelpers.Return(PenumbraApiEc.FileMissing, args); - if (dir.Parent == null || Path.GetFullPath(_modManager.BasePath.FullName) != Path.GetFullPath(dir.Parent.FullName)) + if (dir.Parent == null + || Path.TrimEndingDirectorySeparator(Path.GetFullPath(_modManager.BasePath.FullName)) + != Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir.Parent.FullName))) return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); _modManager.AddMod(dir); diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 010cad19..62b54865 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -47,15 +47,15 @@ public sealed class ModManager : ModStorage, IDisposable DataEditor = dataEditor; OptionEditor = optionEditor; Creator = creator; - SetBaseDirectory(config.ModDirectory, true); + SetBaseDirectory(config.ModDirectory, true, out _); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModManager); DiscoverMods(); } /// Change the mod base directory and discover available mods. - public void DiscoverMods(string newDir) + public void DiscoverMods(string newDir, out string resultNewDir) { - SetBaseDirectory(newDir, false); + SetBaseDirectory(newDir, false, out resultNewDir); DiscoverMods(); } @@ -264,8 +264,9 @@ public sealed class ModManager : ModStorage, IDisposable /// If its not the first time, check if it is the same directory as before. /// Also checks if the directory is available and tries to create it if it is not. /// - private void SetBaseDirectory(string newPath, bool firstTime) + private void SetBaseDirectory(string newPath, bool firstTime, out string resultNewDir) { + resultNewDir = newPath; if (!firstTime && string.Equals(newPath, _config.ModDirectory, StringComparison.Ordinal)) return; @@ -278,7 +279,7 @@ public sealed class ModManager : ModStorage, IDisposable } else { - var newDir = new DirectoryInfo(newPath); + var newDir = new DirectoryInfo(Path.TrimEndingDirectorySeparator(newPath)); if (!newDir.Exists) try { @@ -290,8 +291,9 @@ public sealed class ModManager : ModStorage, IDisposable Penumbra.Log.Error($"Could not create specified mod directory {newDir.FullName}:\n{e}"); } - BasePath = newDir; - Valid = Directory.Exists(newDir.FullName); + BasePath = newDir; + Valid = Directory.Exists(newDir.FullName); + resultNewDir = BasePath.FullName; if (!firstTime && _config.ModDirectory != BasePath.FullName) TriggerModDirectoryChange(BasePath.FullName, Valid); } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 9989f90a..0de4f790 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -269,7 +269,7 @@ public class SettingsTab : ITab if (_config.ModDirectory != _newModDirectory && _newModDirectory.Length != 0 && DrawPressEnterWarning(_newModDirectory, _config.ModDirectory, pos, save, selected)) - _modManager.DiscoverMods(_newModDirectory); + _modManager.DiscoverMods(_newModDirectory, out _newModDirectory); } /// Draw the Open Directory and Rediscovery buttons. From d7b60206d77610d2d0ba62ca280e93470698c94e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 14:55:10 +0200 Subject: [PATCH 0677/1381] Improve meta manipulation handling a bit. --- Penumbra/Api/Api/TemporaryApi.cs | 4 +- Penumbra/Api/TempModManager.cs | 2 +- .../Meta/Manipulations/EqdpManipulation.cs | 17 +-- .../Meta/Manipulations/EqpManipulation.cs | 17 +-- .../Meta/Manipulations/EstManipulation.cs | 15 +- .../Manipulations/GlobalEqpManipulation.cs | 31 +++- .../Meta/Manipulations/GmpManipulation.cs | 15 +- Penumbra/Meta/Manipulations/MetaDictionary.cs | 140 ++++++++++++++++++ Penumbra/Meta/Manipulations/Rsp.cs | 28 +++- .../Meta/Manipulations/RspManipulation.cs | 27 ++-- Penumbra/Mods/SubMods/DefaultSubMod.cs | 2 +- Penumbra/Mods/SubMods/IModDataContainer.cs | 6 +- Penumbra/Mods/SubMods/OptionSubMod.cs | 2 +- Penumbra/Mods/TemporaryMod.cs | 2 +- 14 files changed, 242 insertions(+), 66 deletions(-) create mode 100644 Penumbra/Meta/Manipulations/MetaDictionary.cs diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 38d080cc..09a9b7c4 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -160,7 +160,7 @@ public class TemporaryApi( /// Only returns true if all conversions are successful and distinct. /// private static bool ConvertManips(string manipString, - [NotNullWhen(true)] out HashSet? manips) + [NotNullWhen(true)] out MetaDictionary? manips) { if (manipString.Length == 0) { @@ -174,7 +174,7 @@ public class TemporaryApi( return false; } - manips = new HashSet(manipArray!.Length); + manips = new MetaDictionary(manipArray!.Length); foreach (var manip in manipArray.Where(m => m.Validate())) { if (manips.Add(manip)) diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index aee2b447..cbb07436 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -43,7 +43,7 @@ public class TempModManager : IDisposable => _modsForAllCollections; public RedirectResult Register(string tag, ModCollection? collection, Dictionary dict, - HashSet manips, ModPriority priority) + MetaDictionary manips, ModPriority priority) { var mod = GetOrCreateMod(tag, collection, priority, out var created); Penumbra.Log.Verbose($"{(created ? "Created" : "Changed")} temporary Mod {mod.Name}."); diff --git a/Penumbra/Meta/Manipulations/EqdpManipulation.cs b/Penumbra/Meta/Manipulations/EqdpManipulation.cs index 2c01ce3f..8c5f27e5 100644 --- a/Penumbra/Meta/Manipulations/EqdpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqdpManipulation.cs @@ -8,11 +8,12 @@ using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct EqdpManipulation : IMetaManipulation +public readonly struct EqdpManipulation(EqdpIdentifier identifier, EqdpEntry entry) : IMetaManipulation { [JsonIgnore] - public EqdpIdentifier Identifier { get; private init; } - public EqdpEntry Entry { get; private init; } + public EqdpIdentifier Identifier { get; } = identifier; + + public EqdpEntry Entry { get; } = entry; [JsonConverter(typeof(StringEnumConverter))] public Gender Gender @@ -31,20 +32,18 @@ public readonly struct EqdpManipulation : IMetaManipulation [JsonConstructor] public EqdpManipulation(EqdpEntry entry, EquipSlot slot, Gender gender, ModelRace race, PrimaryId setId) - { - Identifier = new EqdpIdentifier(setId, slot, Names.CombinedRace(gender, race)); - Entry = Eqdp.Mask(Slot) & entry; - } + : this(new EqdpIdentifier(setId, slot, Names.CombinedRace(gender, race)), Eqdp.Mask(slot) & entry) + { } public EqdpManipulation Copy(EqdpManipulation entry) { if (entry.Slot != Slot) { var (bit1, bit2) = entry.Entry.ToBits(entry.Slot); - return new EqdpManipulation(Eqdp.FromSlotAndBits(Slot, bit1, bit2), Slot, Gender, Race, SetId); + return new EqdpManipulation(Identifier, Eqdp.FromSlotAndBits(Slot, bit1, bit2)); } - return new EqdpManipulation(entry.Entry, Slot, Gender, Race, SetId); + return new EqdpManipulation(Identifier, entry.Entry); } public EqdpManipulation Copy(EqdpEntry entry) diff --git a/Penumbra/Meta/Manipulations/EqpManipulation.cs b/Penumbra/Meta/Manipulations/EqpManipulation.cs index 3bced096..eef21d12 100644 --- a/Penumbra/Meta/Manipulations/EqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/EqpManipulation.cs @@ -9,12 +9,13 @@ using Penumbra.Util; namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct EqpManipulation : IMetaManipulation +public readonly struct EqpManipulation(EqpIdentifier identifier, EqpEntry entry) : IMetaManipulation { - [JsonConverter(typeof(ForceNumericFlagEnumConverter))] - public EqpEntry Entry { get; private init; } + [JsonIgnore] + public EqpIdentifier Identifier { get; } = identifier; - public EqpIdentifier Identifier { get; private init; } + [JsonConverter(typeof(ForceNumericFlagEnumConverter))] + public EqpEntry Entry { get; } = entry; public PrimaryId SetId => Identifier.SetId; @@ -25,13 +26,11 @@ public readonly struct EqpManipulation : IMetaManipulation [JsonConstructor] public EqpManipulation(EqpEntry entry, EquipSlot slot, PrimaryId setId) - { - Identifier = new EqpIdentifier(setId, slot); - Entry = Eqp.Mask(slot) & entry; - } + : this(new EqpIdentifier(setId, slot), Eqp.Mask(slot) & entry) + { } public EqpManipulation Copy(EqpEntry entry) - => new(entry, Slot, SetId); + => new(Identifier, entry); public override string ToString() => $"Eqp - {SetId} - {Slot}"; diff --git a/Penumbra/Meta/Manipulations/EstManipulation.cs b/Penumbra/Meta/Manipulations/EstManipulation.cs index c3f9792f..09abbaa5 100644 --- a/Penumbra/Meta/Manipulations/EstManipulation.cs +++ b/Penumbra/Meta/Manipulations/EstManipulation.cs @@ -8,7 +8,7 @@ using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct EstManipulation : IMetaManipulation +public readonly struct EstManipulation(EstIdentifier identifier, EstEntry entry) : IMetaManipulation { public static string ToName(EstType type) => type switch @@ -20,8 +20,9 @@ public readonly struct EstManipulation : IMetaManipulation _ => "unk", }; - public EstIdentifier Identifier { get; private init; } - public EstEntry Entry { get; private init; } + [JsonIgnore] + public EstIdentifier Identifier { get; } = identifier; + public EstEntry Entry { get; } = entry; [JsonConverter(typeof(StringEnumConverter))] public Gender Gender @@ -41,13 +42,11 @@ public readonly struct EstManipulation : IMetaManipulation [JsonConstructor] public EstManipulation(Gender gender, ModelRace race, EstType slot, PrimaryId setId, EstEntry entry) - { - Entry = entry; - Identifier = new EstIdentifier(setId, slot, Names.CombinedRace(gender, race)); - } + : this(new EstIdentifier(setId, slot, Names.CombinedRace(gender, race)), entry) + { } public EstManipulation Copy(EstEntry entry) - => new(Gender, Race, Slot, SetId, entry); + => new(Identifier, entry); public override string ToString() diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs index ada543dc..94c892e2 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -1,9 +1,11 @@ +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; namespace Penumbra.Meta.Manipulations; -public readonly struct GlobalEqpManipulation : IMetaManipulation +public readonly struct GlobalEqpManipulation : IMetaManipulation, IMetaIdentifier { public GlobalEqpType Type { get; init; } public PrimaryId Condition { get; init; } @@ -19,6 +21,28 @@ public readonly struct GlobalEqpManipulation : IMetaManipulation() ?? (GlobalEqpType)100; + var condition = jObj[nameof(Condition)]?.ToObject() ?? 0; + var ret = new GlobalEqpManipulation + { + Type = type, + Condition = condition, + }; + return ret.Validate() ? ret : null; + } + public bool Equals(GlobalEqpManipulation other) => Type == other.Type @@ -45,6 +69,9 @@ public readonly struct GlobalEqpManipulation : IMetaManipulation $"Global EQP - {Type}{(Condition != 0 ? $" - {Condition.Id}" : string.Empty)}"; + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { } + public MetaIndex FileIndex() - => (MetaIndex)(-1); + => MetaIndex.Eqp; } diff --git a/Penumbra/Meta/Manipulations/GmpManipulation.cs b/Penumbra/Meta/Manipulations/GmpManipulation.cs index 0b2a9f4b..431f6325 100644 --- a/Penumbra/Meta/Manipulations/GmpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GmpManipulation.cs @@ -6,24 +6,23 @@ using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct GmpManipulation : IMetaManipulation +public readonly struct GmpManipulation(GmpIdentifier identifier, GmpEntry entry) : IMetaManipulation { - public GmpIdentifier Identifier { get; private init; } + [JsonIgnore] + public GmpIdentifier Identifier { get; } = identifier; - public GmpEntry Entry { get; private init; } + public GmpEntry Entry { get; } = entry; public PrimaryId SetId => Identifier.SetId; [JsonConstructor] public GmpManipulation(GmpEntry entry, PrimaryId setId) - { - Entry = entry; - Identifier = new GmpIdentifier(setId); - } + : this(new GmpIdentifier(setId), entry) + { } public GmpManipulation Copy(GmpEntry entry) - => new(entry, SetId); + => new(Identifier, entry); public override string ToString() => $"Gmp - {SetId}"; diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs new file mode 100644 index 00000000..65252c5d --- /dev/null +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -0,0 +1,140 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Structs; +using ImcEntry = Penumbra.GameData.Structs.ImcEntry; + +namespace Penumbra.Meta.Manipulations; + +[JsonConverter(typeof(Converter))] +public sealed class MetaDictionary : HashSet +{ + public MetaDictionary() + { } + + public MetaDictionary(int capacity) + : base(capacity) + { } + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, MetaDictionary? value, JsonSerializer serializer) + { + if (value is null) + { + writer.WriteNull(); + return; + } + + writer.WriteStartArray(); + foreach (var item in value) + { + writer.WriteStartObject(); + writer.WritePropertyName("Type"); + writer.WriteValue(item.ManipulationType.ToString()); + writer.WritePropertyName("Manipulation"); + serializer.Serialize(writer, item.Manipulation); + writer.WriteEndObject(); + } + + writer.WriteEndArray(); + } + + public override MetaDictionary ReadJson(JsonReader reader, Type objectType, MetaDictionary? existingValue, bool hasExistingValue, + JsonSerializer serializer) + { + var dict = existingValue ?? []; + dict.Clear(); + var jObj = JArray.Load(reader); + foreach (var item in jObj) + { + var type = item["Type"]?.ToObject() ?? MetaManipulation.Type.Unknown; + if (type is MetaManipulation.Type.Unknown) + { + Penumbra.Log.Warning($"Invalid Meta Manipulation Type {type} encountered."); + continue; + } + + if (item["Manipulation"] is not JObject manip) + { + Penumbra.Log.Warning($"Manipulation of type {type} does not contain manipulation data."); + continue; + } + + switch (type) + { + case MetaManipulation.Type.Imc: + { + var identifier = ImcIdentifier.FromJson(manip); + var entry = manip["Entry"]?.ToObject(); + if (identifier.HasValue && entry.HasValue) + dict.Add(new MetaManipulation(new ImcManipulation(identifier.Value, entry.Value))); + else + Penumbra.Log.Warning("Invalid IMC Manipulation encountered."); + break; + } + case MetaManipulation.Type.Eqdp: + { + var identifier = EqdpIdentifier.FromJson(manip); + var entry = (EqdpEntry?)manip["Entry"]?.ToObject(); + if (identifier.HasValue && entry.HasValue) + dict.Add(new MetaManipulation(new EqdpManipulation(identifier.Value, entry.Value))); + else + Penumbra.Log.Warning("Invalid EQDP Manipulation encountered."); + break; + } + case MetaManipulation.Type.Eqp: + { + var identifier = EqpIdentifier.FromJson(manip); + var entry = (EqpEntry?)manip["Entry"]?.ToObject(); + if (identifier.HasValue && entry.HasValue) + dict.Add(new MetaManipulation(new EqpManipulation(identifier.Value, entry.Value))); + else + Penumbra.Log.Warning("Invalid EQP Manipulation encountered."); + break; + } + case MetaManipulation.Type.Est: + { + var identifier = EstIdentifier.FromJson(manip); + var entry = manip["Entry"]?.ToObject(); + if (identifier.HasValue && entry.HasValue) + dict.Add(new MetaManipulation(new EstManipulation(identifier.Value, entry.Value))); + else + Penumbra.Log.Warning("Invalid EST Manipulation encountered."); + break; + } + case MetaManipulation.Type.Gmp: + { + var identifier = GmpIdentifier.FromJson(manip); + var entry = manip["Entry"]?.ToObject(); + if (identifier.HasValue && entry.HasValue) + dict.Add(new MetaManipulation(new GmpManipulation(identifier.Value, entry.Value))); + else + Penumbra.Log.Warning("Invalid GMP Manipulation encountered."); + break; + } + case MetaManipulation.Type.Rsp: + { + var identifier = RspIdentifier.FromJson(manip); + var entry = manip["Entry"]?.ToObject(); + if (identifier.HasValue && entry.HasValue) + dict.Add(new MetaManipulation(new RspManipulation(identifier.Value, entry.Value))); + else + Penumbra.Log.Warning("Invalid RSP Manipulation encountered."); + break; + } + case MetaManipulation.Type.GlobalEqp: + { + var identifier = GlobalEqpManipulation.FromJson(manip); + if (identifier.HasValue) + dict.Add(new MetaManipulation(identifier.Value)); + else + Penumbra.Log.Warning("Invalid Global EQP Manipulation encountered."); + break; + } + } + } + + return dict; + } + } +} diff --git a/Penumbra/Meta/Manipulations/Rsp.cs b/Penumbra/Meta/Manipulations/Rsp.cs index 29cdfd71..ca7cb1c5 100644 --- a/Penumbra/Meta/Manipulations/Rsp.cs +++ b/Penumbra/Meta/Manipulations/Rsp.cs @@ -1,3 +1,4 @@ +using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.GameData.Data; @@ -12,13 +13,31 @@ public readonly record struct RspIdentifier(SubRace SubRace, RspAttribute Attrib => changedItems.TryAdd($"{SubRace.ToName()} {Attribute.ToFullString()}", null); public MetaIndex FileIndex() - => throw new NotImplementedException(); + => MetaIndex.HumanCmp; public bool Validate() - => throw new NotImplementedException(); + => SubRace is not SubRace.Unknown + && Enum.IsDefined(SubRace) + && Attribute is not RspAttribute.NumAttributes + && Enum.IsDefined(Attribute); public JObject AddToJson(JObject jObj) - => throw new NotImplementedException(); + { + jObj["SubRace"] = SubRace.ToString(); + jObj["Attribute"] = Attribute.ToString(); + return jObj; + } + + public static RspIdentifier? FromJson(JObject? jObj) + { + if (jObj == null) + return null; + + var subRace = jObj["SubRace"]?.ToObject() ?? SubRace.Unknown; + var attribute = jObj["Attribute"]?.ToObject() ?? RspAttribute.NumAttributes; + var ret = new RspIdentifier(subRace, attribute); + return ret.Validate() ? ret : null; + } } [JsonConverter(typeof(Converter))] @@ -28,6 +47,9 @@ public readonly record struct RspEntry(float Value) : IComparisonOperators Value is >= MinValue and <= MaxValue; + private class Converter : JsonConverter { public override void WriteJson(JsonWriter writer, RspEntry value, JsonSerializer serializer) diff --git a/Penumbra/Meta/Manipulations/RspManipulation.cs b/Penumbra/Meta/Manipulations/RspManipulation.cs index 04691c9f..e2282c41 100644 --- a/Penumbra/Meta/Manipulations/RspManipulation.cs +++ b/Penumbra/Meta/Manipulations/RspManipulation.cs @@ -7,10 +7,12 @@ using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; [StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct RspManipulation : IMetaManipulation +public readonly struct RspManipulation(RspIdentifier identifier, RspEntry entry) : IMetaManipulation { - public RspIdentifier Identifier { get; private init; } - public RspEntry Entry { get; private init; } + [JsonIgnore] + public RspIdentifier Identifier { get; } = identifier; + + public RspEntry Entry { get; } = entry; [JsonConverter(typeof(StringEnumConverter))] public SubRace SubRace @@ -22,13 +24,11 @@ public readonly struct RspManipulation : IMetaManipulation [JsonConstructor] public RspManipulation(SubRace subRace, RspAttribute attribute, RspEntry entry) - { - Entry = entry; - Identifier = new RspIdentifier(subRace, attribute); - } + : this(new RspIdentifier(subRace, attribute), entry) + { } public RspManipulation Copy(RspEntry entry) - => new(SubRace, Attribute, entry); + => new(Identifier, entry); public override string ToString() => $"Rsp - {SubRace.ToName()} - {Attribute.ToFullString()}"; @@ -63,14 +63,5 @@ public readonly struct RspManipulation : IMetaManipulation } public bool Validate() - { - if (SubRace is SubRace.Unknown || !Enum.IsDefined(SubRace)) - return false; - if (!Enum.IsDefined(Attribute)) - return false; - if (Entry.Value is < RspEntry.MinValue or > RspEntry.MaxValue) - return false; - - return true; - } + => Identifier.Validate() && Entry.Validate(); } diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 1a234879..5a300a48 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -13,7 +13,7 @@ public class DefaultSubMod(IMod mod) : IModDataContainer public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; + public MetaDictionary Manipulations { get; set; } = []; IMod IModDataContainer.Mod => Mod; diff --git a/Penumbra/Mods/SubMods/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs index 7f7ef4a6..1a89ec17 100644 --- a/Penumbra/Mods/SubMods/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -10,9 +10,9 @@ public interface IModDataContainer public IMod Mod { get; } public IModGroup? Group { get; } - public Dictionary Files { get; set; } - public Dictionary FileSwaps { get; set; } - public HashSet Manipulations { get; set; } + public Dictionary Files { get; set; } + public Dictionary FileSwaps { get; set; } + public MetaDictionary Manipulations { get; set; } public string GetName(); public string GetFullName(); diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs index 02d86af2..378f6dc8 100644 --- a/Penumbra/Mods/SubMods/OptionSubMod.cs +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -33,7 +33,7 @@ public abstract class OptionSubMod(IModGroup group) : IModOption, IModDataContai public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; - public HashSet Manipulations { get; set; } = []; + public MetaDictionary Manipulations { get; set; } = []; public void AddDataTo(Dictionary redirections, HashSet manipulations) => SubMod.AddContainerTo(this, redirections, manipulations); diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 6e6e72ab..e0a03c92 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -57,7 +57,7 @@ public class TemporaryMod : IMod public bool SetManipulation(MetaManipulation manip) => Default.Manipulations.Remove(manip) | Default.Manipulations.Add(manip); - public void SetAll(Dictionary dict, HashSet manips) + public void SetAll(Dictionary dict, MetaDictionary manips) { Default.Files = dict; Default.Manipulations = manips; From 94fdd848b718ef2c7e932faff6b108f7ed7287d8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 16:06:37 +0200 Subject: [PATCH 0678/1381] Expand on MetaDictionary to use separate dictionaries. --- Penumbra/Api/Api/TemporaryApi.cs | 4 +- Penumbra/Meta/Manipulations/MetaDictionary.cs | 244 +++++++++++++++++- Penumbra/Mods/Editor/IMod.cs | 2 +- Penumbra/Mods/Editor/ModMerger.cs | 2 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 +- Penumbra/Mods/Groups/IModGroup.cs | 2 +- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 2 +- Penumbra/Mods/Groups/SingleModGroup.cs | 2 +- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 21 +- .../Manager/OptionEditor/ModGroupEditor.cs | 2 +- Penumbra/Mods/Mod.cs | 2 +- Penumbra/Mods/SubMods/DefaultSubMod.cs | 2 +- Penumbra/Mods/SubMods/OptionSubMod.cs | 2 +- Penumbra/Mods/SubMods/SubMod.cs | 2 +- 15 files changed, 257 insertions(+), 36 deletions(-) diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 09a9b7c4..995ec388 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -174,8 +174,8 @@ public class TemporaryApi( return false; } - manips = new MetaDictionary(manipArray!.Length); - foreach (var manip in manipArray.Where(m => m.Validate())) + manips = []; + foreach (var manip in manipArray!.Where(m => m.Validate())) { if (manips.Add(manip)) continue; diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 65252c5d..b0b7f011 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -1,19 +1,237 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.GameData.Structs; +using Penumbra.Util; using ImcEntry = Penumbra.GameData.Structs.ImcEntry; namespace Penumbra.Meta.Manipulations; [JsonConverter(typeof(Converter))] -public sealed class MetaDictionary : HashSet +public sealed class MetaDictionary : IEnumerable { - public MetaDictionary() - { } + private readonly Dictionary _imc = []; + private readonly Dictionary _eqp = []; + private readonly Dictionary _eqdp = []; + private readonly Dictionary _est = []; + private readonly Dictionary _rsp = []; + private readonly Dictionary _gmp = []; + private readonly HashSet _globalEqp = []; - public MetaDictionary(int capacity) - : base(capacity) - { } + public int Count { get; private set; } + + public void Clear() + { + _imc.Clear(); + _eqp.Clear(); + _eqdp.Clear(); + _est.Clear(); + _rsp.Clear(); + _gmp.Clear(); + _globalEqp.Clear(); + } + + public IEnumerator GetEnumerator() + => _imc.Select(kvp => new MetaManipulation(new ImcManipulation(kvp.Key, kvp.Value))) + .Concat(_eqp.Select(kvp => new MetaManipulation(new EqpManipulation(kvp.Key, kvp.Value)))) + .Concat(_eqdp.Select(kvp => new MetaManipulation(new EqdpManipulation(kvp.Key, kvp.Value)))) + .Concat(_est.Select(kvp => new MetaManipulation(new EstManipulation(kvp.Key, kvp.Value)))) + .Concat(_rsp.Select(kvp => new MetaManipulation(new RspManipulation(kvp.Key, kvp.Value)))) + .Concat(_gmp.Select(kvp => new MetaManipulation(new GmpManipulation(kvp.Key, kvp.Value)))) + .Concat(_globalEqp.Select(manip => new MetaManipulation(manip))).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); + + public bool Add(MetaManipulation manip) + { + var ret = manip.ManipulationType switch + { + MetaManipulation.Type.Imc => _imc.TryAdd(manip.Imc.Identifier, manip.Imc.Entry), + MetaManipulation.Type.Eqdp => _eqdp.TryAdd(manip.Eqdp.Identifier, manip.Eqdp.Entry), + MetaManipulation.Type.Eqp => _eqp.TryAdd(manip.Eqp.Identifier, manip.Eqp.Entry), + MetaManipulation.Type.Est => _est.TryAdd(manip.Est.Identifier, manip.Est.Entry), + MetaManipulation.Type.Gmp => _gmp.TryAdd(manip.Gmp.Identifier, manip.Gmp.Entry), + MetaManipulation.Type.Rsp => _rsp.TryAdd(manip.Rsp.Identifier, manip.Rsp.Entry), + MetaManipulation.Type.GlobalEqp => _globalEqp.Add(manip.GlobalEqp), + _ => false, + }; + + if (ret) + ++Count; + return ret; + } + + public bool TryAdd(ImcIdentifier identifier, ImcEntry entry) + { + if (!_imc.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + public bool TryAdd(EqpIdentifier identifier, EqpEntry entry) + { + if (!_eqp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + public bool TryAdd(EqdpIdentifier identifier, EqdpEntry entry) + { + if (!_eqdp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + public bool TryAdd(EstIdentifier identifier, EstEntry entry) + { + if (!_est.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + public bool TryAdd(GmpIdentifier identifier, GmpEntry entry) + { + if (!_gmp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + public bool TryAdd(RspIdentifier identifier, RspEntry entry) + { + if (!_rsp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + public bool TryAdd(GlobalEqpManipulation identifier) + { + if (!_globalEqp.Add(identifier)) + return false; + + ++Count; + return true; + } + + public bool Remove(MetaManipulation manip) + { + var ret = manip.ManipulationType switch + { + MetaManipulation.Type.Imc => _imc.Remove(manip.Imc.Identifier), + MetaManipulation.Type.Eqdp => _eqdp.Remove(manip.Eqdp.Identifier), + MetaManipulation.Type.Eqp => _eqp.Remove(manip.Eqp.Identifier), + MetaManipulation.Type.Est => _est.Remove(manip.Est.Identifier), + MetaManipulation.Type.Gmp => _gmp.Remove(manip.Gmp.Identifier), + MetaManipulation.Type.Rsp => _rsp.Remove(manip.Rsp.Identifier), + MetaManipulation.Type.GlobalEqp => _globalEqp.Remove(manip.GlobalEqp), + _ => false, + }; + if (ret) + --Count; + return ret; + } + + public void UnionWith(IEnumerable manips) + { + foreach (var manip in manips) + Add(manip); + } + + public bool TryGetValue(MetaManipulation identifier, out MetaManipulation oldValue) + { + switch (identifier.ManipulationType) + { + case MetaManipulation.Type.Imc: + if (_imc.TryGetValue(identifier.Imc.Identifier, out var oldImc)) + { + oldValue = new MetaManipulation(new ImcManipulation(identifier.Imc.Identifier, oldImc)); + return true; + } + + break; + case MetaManipulation.Type.Eqdp: + if (_eqp.TryGetValue(identifier.Eqp.Identifier, out var oldEqdp)) + { + oldValue = new MetaManipulation(new EqpManipulation(identifier.Eqp.Identifier, oldEqdp)); + return true; + } + + break; + case MetaManipulation.Type.Eqp: + if (_eqdp.TryGetValue(identifier.Eqdp.Identifier, out var oldEqp)) + { + oldValue = new MetaManipulation(new EqdpManipulation(identifier.Eqdp.Identifier, oldEqp)); + return true; + } + + break; + case MetaManipulation.Type.Est: + if (_est.TryGetValue(identifier.Est.Identifier, out var oldEst)) + { + oldValue = new MetaManipulation(new EstManipulation(identifier.Est.Identifier, oldEst)); + return true; + } + + break; + case MetaManipulation.Type.Gmp: + if (_gmp.TryGetValue(identifier.Gmp.Identifier, out var oldGmp)) + { + oldValue = new MetaManipulation(new GmpManipulation(identifier.Gmp.Identifier, oldGmp)); + return true; + } + + break; + case MetaManipulation.Type.Rsp: + if (_rsp.TryGetValue(identifier.Rsp.Identifier, out var oldRsp)) + { + oldValue = new MetaManipulation(new RspManipulation(identifier.Rsp.Identifier, oldRsp)); + return true; + } + + break; + case MetaManipulation.Type.GlobalEqp: + if (_globalEqp.TryGetValue(identifier.GlobalEqp, out var oldGlobalEqp)) + { + oldValue = new MetaManipulation(oldGlobalEqp); + return true; + } + + break; + } + + oldValue = default; + return false; + } + + public void SetTo(MetaDictionary other) + { + _imc.SetTo(other._imc); + _eqp.SetTo(other._eqp); + _eqdp.SetTo(other._eqdp); + _est.SetTo(other._est); + _rsp.SetTo(other._rsp); + _gmp.SetTo(other._gmp); + _globalEqp.SetTo(other._globalEqp); + Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _globalEqp.Count; + } + + public MetaDictionary Clone() + { + var ret = new MetaDictionary(); + ret.SetTo(this); + return ret; + } private class Converter : JsonConverter { @@ -67,7 +285,7 @@ public sealed class MetaDictionary : HashSet var identifier = ImcIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); if (identifier.HasValue && entry.HasValue) - dict.Add(new MetaManipulation(new ImcManipulation(identifier.Value, entry.Value))); + dict.TryAdd(identifier.Value, entry.Value); else Penumbra.Log.Warning("Invalid IMC Manipulation encountered."); break; @@ -77,7 +295,7 @@ public sealed class MetaDictionary : HashSet var identifier = EqdpIdentifier.FromJson(manip); var entry = (EqdpEntry?)manip["Entry"]?.ToObject(); if (identifier.HasValue && entry.HasValue) - dict.Add(new MetaManipulation(new EqdpManipulation(identifier.Value, entry.Value))); + dict.TryAdd(identifier.Value, entry.Value); else Penumbra.Log.Warning("Invalid EQDP Manipulation encountered."); break; @@ -87,7 +305,7 @@ public sealed class MetaDictionary : HashSet var identifier = EqpIdentifier.FromJson(manip); var entry = (EqpEntry?)manip["Entry"]?.ToObject(); if (identifier.HasValue && entry.HasValue) - dict.Add(new MetaManipulation(new EqpManipulation(identifier.Value, entry.Value))); + dict.TryAdd(identifier.Value, entry.Value); else Penumbra.Log.Warning("Invalid EQP Manipulation encountered."); break; @@ -97,7 +315,7 @@ public sealed class MetaDictionary : HashSet var identifier = EstIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); if (identifier.HasValue && entry.HasValue) - dict.Add(new MetaManipulation(new EstManipulation(identifier.Value, entry.Value))); + dict.TryAdd(identifier.Value, entry.Value); else Penumbra.Log.Warning("Invalid EST Manipulation encountered."); break; @@ -107,7 +325,7 @@ public sealed class MetaDictionary : HashSet var identifier = GmpIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); if (identifier.HasValue && entry.HasValue) - dict.Add(new MetaManipulation(new GmpManipulation(identifier.Value, entry.Value))); + dict.TryAdd(identifier.Value, entry.Value); else Penumbra.Log.Warning("Invalid GMP Manipulation encountered."); break; @@ -117,7 +335,7 @@ public sealed class MetaDictionary : HashSet var identifier = RspIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); if (identifier.HasValue && entry.HasValue) - dict.Add(new MetaManipulation(new RspManipulation(identifier.Value, entry.Value))); + dict.TryAdd(identifier.Value, entry.Value); else Penumbra.Log.Warning("Invalid RSP Manipulation encountered."); break; @@ -126,7 +344,7 @@ public sealed class MetaDictionary : HashSet { var identifier = GlobalEqpManipulation.FromJson(manip); if (identifier.HasValue) - dict.Add(new MetaManipulation(identifier.Value)); + dict.TryAdd(identifier.Value); else Penumbra.Log.Warning("Invalid Global EQP Manipulation encountered."); break; diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index d4c881e9..06c31846 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -8,7 +8,7 @@ namespace Penumbra.Mods.Editor; public record struct AppliedModData( Dictionary FileRedirections, - HashSet Manipulations) + MetaDictionary Manipulations) { public static readonly AppliedModData Empty = new([], []); } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index f5fc9cd7..4faced80 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -158,7 +158,7 @@ public class ModMerger : IDisposable { var redirections = option.Files.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); var swaps = option.FileSwaps.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - var manips = option.Manipulations.ToHashSet(); + var manips = option.Manipulations.Clone(); foreach (var originalOption in mergeOptions) { diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 86853755..45d9f8a1 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -145,7 +145,7 @@ public class ModMetaEditor(ModManager modManager) if (!Changes) return; - modManager.OptionEditor.SetManipulations(container, Recombine().ToHashSet()); + modManager.OptionEditor.SetManipulations(container, [..Recombine()]); Changes = false; } diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index fcc8c093..00f47e25 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -43,7 +43,7 @@ public interface IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer); - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations); + public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations); public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); /// Ensure that a value is valid for a group. diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index b336203d..383bc9fd 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -99,7 +99,7 @@ public class ImcModGroup(Mod mod) : IModGroup => new(Identifier.ObjectType, Identifier.BodySlot, Identifier.PrimaryId, Identifier.SecondaryId.Id, variant.Id, Identifier.EquipSlot, DefaultEntry with { AttributeMask = mask }); - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) { if (IsDisabled(setting)) return; diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 7816d628..220d0a7c 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -116,7 +116,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) => new MultiModGroupEditDrawer(editDrawer, this); - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) { foreach (var (option, index) in OptionData.WithIndex().OrderByDescending(o => o.Value.Priority)) { diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index a6ebd846..a559d609 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -101,7 +101,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) => new SingleModGroupEditDrawer(editDrawer, this); - public void AddData(Setting setting, Dictionary redirections, HashSet manipulations) + public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) { if (OptionData.Count == 0) return; diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index af5b2d3a..67a5d007 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -23,7 +23,7 @@ public class ItemSwapContainer public IReadOnlyDictionary ModRedirections => _appliedModData.FileRedirections; - public IReadOnlySet ModManipulations + public MetaDictionary ModManipulations => _appliedModData.Manipulations; public readonly List Swaps = []; @@ -42,9 +42,10 @@ public class ItemSwapContainer NoSwaps, } - public bool WriteMod(ModManager manager, Mod mod, IModDataContainer container, WriteType writeType = WriteType.NoSwaps, DirectoryInfo? directory = null) + public bool WriteMod(ModManager manager, Mod mod, IModDataContainer container, WriteType writeType = WriteType.NoSwaps, + DirectoryInfo? directory = null) { - var convertedManips = new HashSet(Swaps.Count); + var convertedManips = new MetaDictionary(); var convertedFiles = new Dictionary(Swaps.Count); var convertedSwaps = new Dictionary(Swaps.Count); directory ??= mod.ModPath; @@ -98,13 +99,9 @@ public class ItemSwapContainer { Clear(); if (mod == null || mod.Index < 0) - { - _appliedModData = AppliedModData.Empty; - } + _appliedModData = AppliedModData.Empty; else - { _appliedModData = ModSettings.GetResolveData(mod, settings); - } } public ItemSwapContainer(MetaFileManager manager, ObjectIdentification identifier) @@ -121,7 +118,13 @@ public class ItemSwapContainer private Func MetaResolver(ModCollection? collection) { - var set = collection?.MetaCache?.Manipulations.ToHashSet() ?? _appliedModData.Manipulations; + if (collection?.MetaCache?.Manipulations is { } cache) + { + MetaDictionary dict = [.. cache]; + return m => dict.TryGetValue(m, out var a) ? a : m; + } + + var set = _appliedModData.Manipulations; return m => set.TryGetValue(m, out var a) ? a : m; } diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 55e01015..01092862 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -142,7 +142,7 @@ public class ModGroupEditor( } /// Set the meta manipulations for a given option. Replaces existing manipulations. - public void SetManipulations(IModDataContainer subMod, HashSet manipulations, SaveType saveType = SaveType.Queue) + public void SetManipulations(IModDataContainer subMod, MetaDictionary manipulations, SaveType saveType = SaveType.Queue) { if (subMod.Manipulations.Count == manipulations.Count && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 783ef3e6..a7f87dcd 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -71,7 +71,7 @@ public sealed class Mod : IMod return AppliedModData.Empty; var dictRedirections = new Dictionary(TotalFileCount); - var setManips = new HashSet(TotalManipulations); + var setManips = new MetaDictionary(); foreach (var (group, groupIndex) in Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) { var config = settings.Settings[groupIndex]; diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 5a300a48..dcd33610 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -21,7 +21,7 @@ public class DefaultSubMod(IMod mod) : IModDataContainer IModGroup? IModDataContainer.Group => null; - public void AddTo(Dictionary redirections, HashSet manipulations) + public void AddTo(Dictionary redirections, MetaDictionary manipulations) => SubMod.AddContainerTo(this, redirections, manipulations); public string GetName() diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs index 378f6dc8..ed7b6ff8 100644 --- a/Penumbra/Mods/SubMods/OptionSubMod.cs +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -35,7 +35,7 @@ public abstract class OptionSubMod(IModGroup group) : IModOption, IModDataContai public Dictionary FileSwaps { get; set; } = []; public MetaDictionary Manipulations { get; set; } = []; - public void AddDataTo(Dictionary redirections, HashSet manipulations) + public void AddDataTo(Dictionary redirections, MetaDictionary manipulations) => SubMod.AddContainerTo(this, redirections, manipulations); public string GetName() diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index b984b570..06a924c8 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -21,7 +21,7 @@ public static class SubMod /// Add all unique meta manipulations, file redirections and then file swaps from a ModDataContainer to the given sets. Skip any keys that are already contained. [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void AddContainerTo(IModDataContainer container, Dictionary redirections, - HashSet manipulations) + MetaDictionary manipulations) { foreach (var (path, file) in container.Files) redirections.TryAdd(path, file); From 13156a58e92ab64965879f994eb9f1aec77d8f12 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 16:09:34 +0200 Subject: [PATCH 0679/1381] Remove unused functions. --- Penumbra/Mods/TemporaryMod.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index e0a03c92..a715f786 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -51,12 +51,6 @@ public class TemporaryMod : IMod public TemporaryMod() => Default = new DefaultSubMod(this); - public void SetFile(Utf8GamePath gamePath, FullPath fullPath) - => Default.Files[gamePath] = fullPath; - - public bool SetManipulation(MetaManipulation manip) - => Default.Manipulations.Remove(manip) | Default.Manipulations.Add(manip); - public void SetAll(Dictionary dict, MetaDictionary manips) { Default.Files = dict; From e0339160e908276a97963fd498f9e785a88ee690 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 16:25:08 +0200 Subject: [PATCH 0680/1381] Start removing MetaManipulation functions. --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 40 +++++++++---------- .../Manager/OptionEditor/ModGroupEditor.cs | 3 +- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index b0b7f011..b9d7990d 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -124,28 +124,28 @@ public sealed class MetaDictionary : IEnumerable return true; } - public bool Remove(MetaManipulation manip) + public void UnionWith(MetaDictionary manips) { - var ret = manip.ManipulationType switch - { - MetaManipulation.Type.Imc => _imc.Remove(manip.Imc.Identifier), - MetaManipulation.Type.Eqdp => _eqdp.Remove(manip.Eqdp.Identifier), - MetaManipulation.Type.Eqp => _eqp.Remove(manip.Eqp.Identifier), - MetaManipulation.Type.Est => _est.Remove(manip.Est.Identifier), - MetaManipulation.Type.Gmp => _gmp.Remove(manip.Gmp.Identifier), - MetaManipulation.Type.Rsp => _rsp.Remove(manip.Rsp.Identifier), - MetaManipulation.Type.GlobalEqp => _globalEqp.Remove(manip.GlobalEqp), - _ => false, - }; - if (ret) - --Count; - return ret; - } + foreach (var (identifier, entry) in manips._imc) + TryAdd(identifier, entry); - public void UnionWith(IEnumerable manips) - { - foreach (var manip in manips) - Add(manip); + foreach (var (identifier, entry) in manips._eqp) + TryAdd(identifier, entry); + + foreach (var (identifier, entry) in manips._eqdp) + TryAdd(identifier, entry); + + foreach (var (identifier, entry) in manips._gmp) + TryAdd(identifier, entry); + + foreach (var (identifier, entry) in manips._rsp) + TryAdd(identifier, entry); + + foreach (var (identifier, entry) in manips._est) + TryAdd(identifier, entry); + + foreach (var identifier in manips._globalEqp) + TryAdd(identifier); } public bool TryGetValue(MetaManipulation identifier, out MetaManipulation oldValue) diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 01092862..594ec9d2 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -144,8 +144,7 @@ public class ModGroupEditor( /// Set the meta manipulations for a given option. Replaces existing manipulations. public void SetManipulations(IModDataContainer subMod, MetaDictionary manipulations, SaveType saveType = SaveType.Queue) { - if (subMod.Manipulations.Count == manipulations.Count - && subMod.Manipulations.All(m => manipulations.TryGetValue(m, out var old) && old.EntryEquals(m))) + if (subMod.Manipulations.Equals(manipulations)) return; communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); From 5ca9e63a2a5f1f44dd9c5859578c3684bc6df4e6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 16:34:51 +0200 Subject: [PATCH 0681/1381] Use internal entries. --- Penumbra/Meta/Manipulations/Eqdp.cs | 6 +- Penumbra/Meta/Manipulations/MetaDictionary.cs | 70 ++++++++++++------- Penumbra/Mods/ModCreator.cs | 4 +- 3 files changed, 48 insertions(+), 32 deletions(-) diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs index 6d6942e6..a986d475 100644 --- a/Penumbra/Meta/Manipulations/Eqdp.cs +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -71,13 +71,13 @@ public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, Ge } } -public readonly record struct InternalEqdpEntry(bool Model, bool Material) +public readonly record struct EqdpEntryInternal(bool Model, bool Material) { - private InternalEqdpEntry((bool, bool) val) + private EqdpEntryInternal((bool, bool) val) : this(val.Item1, val.Item2) { } - public InternalEqdpEntry(EqdpEntry entry, EquipSlot slot) + public EqdpEntryInternal(EqdpEntry entry, EquipSlot slot) : this(entry.ToBits(slot)) { } diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index b9d7990d..941cdf34 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -9,13 +9,13 @@ namespace Penumbra.Meta.Manipulations; [JsonConverter(typeof(Converter))] public sealed class MetaDictionary : IEnumerable { - private readonly Dictionary _imc = []; - private readonly Dictionary _eqp = []; - private readonly Dictionary _eqdp = []; - private readonly Dictionary _est = []; - private readonly Dictionary _rsp = []; - private readonly Dictionary _gmp = []; - private readonly HashSet _globalEqp = []; + private readonly Dictionary _imc = []; + private readonly Dictionary _eqp = []; + private readonly Dictionary _eqdp = []; + private readonly Dictionary _est = []; + private readonly Dictionary _rsp = []; + private readonly Dictionary _gmp = []; + private readonly HashSet _globalEqp = []; public int Count { get; private set; } @@ -30,10 +30,20 @@ public sealed class MetaDictionary : IEnumerable _globalEqp.Clear(); } + public bool Equals(MetaDictionary other) + => Count == other.Count + && _imc.SetEquals(other._imc) + && _eqp.SetEquals(other._eqp) + && _eqdp.SetEquals(other._eqdp) + && _est.SetEquals(other._est) + && _rsp.SetEquals(other._rsp) + && _gmp.SetEquals(other._gmp) + && _globalEqp.SetEquals(other._globalEqp); + public IEnumerator GetEnumerator() => _imc.Select(kvp => new MetaManipulation(new ImcManipulation(kvp.Key, kvp.Value))) - .Concat(_eqp.Select(kvp => new MetaManipulation(new EqpManipulation(kvp.Key, kvp.Value)))) - .Concat(_eqdp.Select(kvp => new MetaManipulation(new EqdpManipulation(kvp.Key, kvp.Value)))) + .Concat(_eqp.Select(kvp => new MetaManipulation(new EqpManipulation(kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))))) + .Concat(_eqdp.Select(kvp => new MetaManipulation(new EqdpManipulation(kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))))) .Concat(_est.Select(kvp => new MetaManipulation(new EstManipulation(kvp.Key, kvp.Value)))) .Concat(_rsp.Select(kvp => new MetaManipulation(new RspManipulation(kvp.Key, kvp.Value)))) .Concat(_gmp.Select(kvp => new MetaManipulation(new GmpManipulation(kvp.Key, kvp.Value)))) @@ -47,8 +57,8 @@ public sealed class MetaDictionary : IEnumerable var ret = manip.ManipulationType switch { MetaManipulation.Type.Imc => _imc.TryAdd(manip.Imc.Identifier, manip.Imc.Entry), - MetaManipulation.Type.Eqdp => _eqdp.TryAdd(manip.Eqdp.Identifier, manip.Eqdp.Entry), - MetaManipulation.Type.Eqp => _eqp.TryAdd(manip.Eqp.Identifier, manip.Eqp.Entry), + MetaManipulation.Type.Eqdp => _eqdp.TryAdd(manip.Eqdp.Identifier, new EqdpEntryInternal(manip.Eqdp.Entry, manip.Eqdp.Slot)), + MetaManipulation.Type.Eqp => _eqp.TryAdd(manip.Eqp.Identifier, new EqpEntryInternal(manip.Eqp.Entry, manip.Eqp.Slot)), MetaManipulation.Type.Est => _est.TryAdd(manip.Est.Identifier, manip.Est.Entry), MetaManipulation.Type.Gmp => _gmp.TryAdd(manip.Gmp.Identifier, manip.Gmp.Entry), MetaManipulation.Type.Rsp => _rsp.TryAdd(manip.Rsp.Identifier, manip.Rsp.Entry), @@ -71,22 +81,10 @@ public sealed class MetaDictionary : IEnumerable } public bool TryAdd(EqpIdentifier identifier, EqpEntry entry) - { - if (!_eqp.TryAdd(identifier, entry)) - return false; - - ++Count; - return true; - } + => TryAdd(identifier, new EqpEntryInternal(entry, identifier.Slot)); public bool TryAdd(EqdpIdentifier identifier, EqdpEntry entry) - { - if (!_eqdp.TryAdd(identifier, entry)) - return false; - - ++Count; - return true; - } + => TryAdd(identifier, new EqdpEntryInternal(entry, identifier.Slot)); public bool TryAdd(EstIdentifier identifier, EstEntry entry) { @@ -163,7 +161,7 @@ public sealed class MetaDictionary : IEnumerable case MetaManipulation.Type.Eqdp: if (_eqp.TryGetValue(identifier.Eqp.Identifier, out var oldEqdp)) { - oldValue = new MetaManipulation(new EqpManipulation(identifier.Eqp.Identifier, oldEqdp)); + oldValue = new MetaManipulation(new EqpManipulation(identifier.Eqp.Identifier, oldEqdp.ToEntry(identifier.Eqp.Slot))); return true; } @@ -171,7 +169,7 @@ public sealed class MetaDictionary : IEnumerable case MetaManipulation.Type.Eqp: if (_eqdp.TryGetValue(identifier.Eqdp.Identifier, out var oldEqp)) { - oldValue = new MetaManipulation(new EqdpManipulation(identifier.Eqdp.Identifier, oldEqp)); + oldValue = new MetaManipulation(new EqdpManipulation(identifier.Eqdp.Identifier, oldEqp.ToEntry(identifier.Eqdp.Slot))); return true; } @@ -355,4 +353,22 @@ public sealed class MetaDictionary : IEnumerable return dict; } } + + private bool TryAdd(EqpIdentifier identifier, EqpEntryInternal entry) + { + if (!_eqp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + + private bool TryAdd(EqdpIdentifier identifier, EqdpEntryInternal entry) + { + if (!_eqdp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index ed4245c4..0035fd41 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -198,7 +198,7 @@ public partial class ModCreator( Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - option.Manipulations.UnionWith(meta.MetaManipulations); + option.Manipulations.UnionWith([.. meta.MetaManipulations]); } else if (ext1 == ".rgsp" || ext2 == ".rgsp") { @@ -212,7 +212,7 @@ public partial class ModCreator( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - option.Manipulations.UnionWith(rgsp.MetaManipulations); + option.Manipulations.UnionWith([.. rgsp.MetaManipulations]); } } catch (Exception e) From 0445ed0ef9ed456a45ac100007f1e847ecd2e68e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 19:09:46 +0200 Subject: [PATCH 0682/1381] Remove TryGetValue(MetaManipulation) from MetaDictionary. --- Penumbra/Meta/Files/EqdpFile.cs | 4 + Penumbra/Meta/Files/EqpGmpFile.cs | 4 + Penumbra/Meta/Files/EstFile.cs | 3 + Penumbra/Meta/Files/ImcFile.cs | 3 + Penumbra/Meta/Manipulations/Eqdp.cs | 5 +- Penumbra/Meta/Manipulations/MetaDictionary.cs | 85 ++++-------- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 131 +++++++++--------- Penumbra/Mods/ItemSwap/ItemSwap.cs | 21 ++- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 23 ++- Penumbra/Mods/ItemSwap/Swaps.cs | 82 +++++++---- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 4 +- 11 files changed, 182 insertions(+), 183 deletions(-) diff --git a/Penumbra/Meta/Files/EqdpFile.cs b/Penumbra/Meta/Files/EqdpFile.cs index c76c4efd..e46e82e9 100644 --- a/Penumbra/Meta/Files/EqdpFile.cs +++ b/Penumbra/Meta/Files/EqdpFile.cs @@ -2,6 +2,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; +using Penumbra.Meta.Manipulations; using Penumbra.String.Functions; namespace Penumbra.Meta.Files; @@ -126,4 +127,7 @@ public sealed unsafe class ExpandedEqdpFile : MetaBaseFile public static EqdpEntry GetDefault(MetaFileManager manager, GenderRace raceCode, bool accessory, PrimaryId primaryId) => GetDefault(manager, CharacterUtility.ReverseIndices[(int)CharacterUtilityData.EqdpIdx(raceCode, accessory)], primaryId); + + public static EqdpEntry GetDefault(MetaFileManager manager, EqdpIdentifier identifier) + => GetDefault(manager, CharacterUtility.ReverseIndices[(int)identifier.FileIndex()], identifier.SetId); } diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index 70067c2b..17541c4f 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -1,6 +1,7 @@ using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; +using Penumbra.Meta.Manipulations; using Penumbra.String.Functions; namespace Penumbra.Meta.Files; @@ -164,6 +165,9 @@ public sealed class ExpandedGmpFile : ExpandedEqpGmpBase, IEnumerable public static GmpEntry GetDefault(MetaFileManager manager, PrimaryId primaryIdx) => new() { Value = GetDefaultInternal(manager, InternalIndex, primaryIdx, GmpEntry.Default.Value) }; + public static GmpEntry GetDefault(MetaFileManager manager, GmpIdentifier identifier) + => new() { Value = GetDefaultInternal(manager, InternalIndex, identifier.SetId, GmpEntry.Default.Value) }; + public void Reset(IEnumerable entries) { foreach (var entry in entries) diff --git a/Penumbra/Meta/Files/EstFile.cs b/Penumbra/Meta/Files/EstFile.cs index ee38ea1e..f3860416 100644 --- a/Penumbra/Meta/Files/EstFile.cs +++ b/Penumbra/Meta/Files/EstFile.cs @@ -184,4 +184,7 @@ public sealed unsafe class EstFile : MetaBaseFile public static EstEntry GetDefault(MetaFileManager manager, EstType estType, GenderRace genderRace, PrimaryId primaryId) => GetDefault(manager, (MetaIndex)estType, genderRace, primaryId); + + public static EstEntry GetDefault(MetaFileManager manager, EstIdentifier identifier) + => GetDefault(manager, identifier.FileIndex(), identifier.GenderRace, identifier.SetId); } diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 5d704cf8..892f5b44 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -65,6 +65,9 @@ public unsafe class ImcFile : MetaBaseFile return ptr == null ? new ImcEntry() : *ptr; } + public ImcEntry GetEntry(EquipSlot slot, Variant variantIdx) + => GetEntry(PartIndex(slot), variantIdx); + public ImcEntry GetEntry(int partIdx, Variant variantIdx, out bool exists) { var ptr = VariantPtr(Data, partIdx, variantIdx); diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs index a986d475..6306f419 100644 --- a/Penumbra/Meta/Manipulations/Eqdp.cs +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -71,7 +71,7 @@ public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, Ge } } -public readonly record struct EqdpEntryInternal(bool Model, bool Material) +public readonly record struct EqdpEntryInternal(bool Material, bool Model) { private EqdpEntryInternal((bool, bool) val) : this(val.Item1, val.Item2) @@ -81,7 +81,6 @@ public readonly record struct EqdpEntryInternal(bool Model, bool Material) : this(entry.ToBits(slot)) { } - public EqdpEntry ToEntry(EquipSlot slot) - => Eqdp.FromSlotAndBits(slot, Model, Material); + => Eqdp.FromSlotAndBits(slot, Material, Model); } diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 941cdf34..51149e3b 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -52,6 +52,19 @@ public sealed class MetaDictionary : IEnumerable IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public bool Add(IMetaIdentifier identifier, object entry) + => identifier switch + { + EqdpIdentifier eqdpIdentifier => entry is EqdpEntryInternal e && Add(eqdpIdentifier, e), + EqpIdentifier eqpIdentifier => entry is EqpEntryInternal e && Add(eqpIdentifier, e), + EstIdentifier estIdentifier => entry is EstEntry e && Add(estIdentifier, e), + GlobalEqpManipulation globalEqpManipulation => Add(globalEqpManipulation), + GmpIdentifier gmpIdentifier => entry is GmpEntry e && Add(gmpIdentifier, e), + ImcIdentifier imcIdentifier => entry is ImcEntry e && Add(imcIdentifier, e), + RspIdentifier rspIdentifier => entry is RspEntry e && Add(rspIdentifier, e), + _ => false, + }; + public bool Add(MetaManipulation manip) { var ret = manip.ManipulationType switch @@ -146,71 +159,23 @@ public sealed class MetaDictionary : IEnumerable TryAdd(identifier); } - public bool TryGetValue(MetaManipulation identifier, out MetaManipulation oldValue) - { - switch (identifier.ManipulationType) - { - case MetaManipulation.Type.Imc: - if (_imc.TryGetValue(identifier.Imc.Identifier, out var oldImc)) - { - oldValue = new MetaManipulation(new ImcManipulation(identifier.Imc.Identifier, oldImc)); - return true; - } + public bool TryGetValue(EstIdentifier identifier, out EstEntry value) + => _est.TryGetValue(identifier, out value); - break; - case MetaManipulation.Type.Eqdp: - if (_eqp.TryGetValue(identifier.Eqp.Identifier, out var oldEqdp)) - { - oldValue = new MetaManipulation(new EqpManipulation(identifier.Eqp.Identifier, oldEqdp.ToEntry(identifier.Eqp.Slot))); - return true; - } + public bool TryGetValue(EqpIdentifier identifier, out EqpEntryInternal value) + => _eqp.TryGetValue(identifier, out value); - break; - case MetaManipulation.Type.Eqp: - if (_eqdp.TryGetValue(identifier.Eqdp.Identifier, out var oldEqp)) - { - oldValue = new MetaManipulation(new EqdpManipulation(identifier.Eqdp.Identifier, oldEqp.ToEntry(identifier.Eqdp.Slot))); - return true; - } + public bool TryGetValue(EqdpIdentifier identifier, out EqdpEntryInternal value) + => _eqdp.TryGetValue(identifier, out value); - break; - case MetaManipulation.Type.Est: - if (_est.TryGetValue(identifier.Est.Identifier, out var oldEst)) - { - oldValue = new MetaManipulation(new EstManipulation(identifier.Est.Identifier, oldEst)); - return true; - } + public bool TryGetValue(GmpIdentifier identifier, out GmpEntry value) + => _gmp.TryGetValue(identifier, out value); - break; - case MetaManipulation.Type.Gmp: - if (_gmp.TryGetValue(identifier.Gmp.Identifier, out var oldGmp)) - { - oldValue = new MetaManipulation(new GmpManipulation(identifier.Gmp.Identifier, oldGmp)); - return true; - } + public bool TryGetValue(RspIdentifier identifier, out RspEntry value) + => _rsp.TryGetValue(identifier, out value); - break; - case MetaManipulation.Type.Rsp: - if (_rsp.TryGetValue(identifier.Rsp.Identifier, out var oldRsp)) - { - oldValue = new MetaManipulation(new RspManipulation(identifier.Rsp.Identifier, oldRsp)); - return true; - } - - break; - case MetaManipulation.Type.GlobalEqp: - if (_globalEqp.TryGetValue(identifier.GlobalEqp, out var oldGlobalEqp)) - { - oldValue = new MetaManipulation(oldGlobalEqp); - return true; - } - - break; - } - - oldValue = default; - return false; - } + public bool TryGetValue(ImcIdentifier identifier, out ImcEntry value) + => _imc.TryGetValue(identifier, out value); public void SetTo(MetaDictionary other) { diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 3efee857..e42a1d31 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -1,4 +1,4 @@ -using Penumbra.Api.Enums; +using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; @@ -16,32 +16,19 @@ public static class EquipmentSwap private static EquipSlot[] ConvertSlots(EquipSlot slot, bool rFinger, bool lFinger) { if (slot != EquipSlot.RFinger) - return new[] - { - slot, - }; + return [slot]; return rFinger ? lFinger - ? new[] - { - EquipSlot.RFinger, - EquipSlot.LFinger, - } - : new[] - { - EquipSlot.RFinger, - } + ? [EquipSlot.RFinger, EquipSlot.LFinger] + : [EquipSlot.RFinger] : lFinger - ? new[] - { - EquipSlot.LFinger, - } - : Array.Empty(); + ? [EquipSlot.LFinger] + : []; } public static EquipItem[] CreateTypeSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, - Func redirections, Func manips, + Func redirections, MetaDictionary manips, EquipSlot slotFrom, EquipItem itemFrom, EquipSlot slotTo, EquipItem itemTo) { LookupItem(itemFrom, out var actualSlotFrom, out var idFrom, out var variantFrom); @@ -50,11 +37,14 @@ public static class EquipmentSwap throw new ItemSwap.InvalidItemTypeException(); var (imcFileFrom, variants, affectedItems) = GetVariants(manager, identifier, slotFrom, idFrom, idTo, variantFrom); - var imcManip = new ImcManipulation(slotTo, variantTo.Id, idTo.Id, default); - var imcFileTo = new ImcFile(manager, imcManip.Identifier); + var imcIdentifierTo = new ImcIdentifier(slotTo, idTo, variantTo); + var imcFileTo = new ImcFile(manager, imcIdentifierTo); + var imcEntry = manips.TryGetValue(imcIdentifierTo, out var entry) + ? entry + : imcFileTo.GetEntry(imcIdentifierTo.EquipSlot, imcIdentifierTo.Variant); + var mtrlVariantTo = imcEntry.MaterialId; var skipFemale = false; var skipMale = false; - var mtrlVariantTo = manips(imcManip.Copy(imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo.Id))).Imc.Entry.MaterialId; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) @@ -99,7 +89,7 @@ public static class EquipmentSwap } public static EquipItem[] CreateItemSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, - Func redirections, Func manips, EquipItem itemFrom, + Func redirections, MetaDictionary manips, EquipItem itemFrom, EquipItem itemTo, bool rFinger = true, bool lFinger = true) { // Check actual ids, variants and slots. We only support using the same slot. @@ -120,8 +110,12 @@ public static class EquipmentSwap foreach (var slot in ConvertSlots(slotFrom, rFinger, lFinger)) { (var imcFileFrom, var variants, affectedItems) = GetVariants(manager, identifier, slot, idFrom, idTo, variantFrom); - var imcManip = new ImcManipulation(slot, variantTo.Id, idTo, default); - var imcFileTo = new ImcFile(manager, imcManip.Identifier); + var imcIdentifierTo = new ImcIdentifier(slotTo, idTo, variantTo); + var imcFileTo = new ImcFile(manager, imcIdentifierTo); + var imcEntry = manips.TryGetValue(imcIdentifierTo, out var entry) + ? entry + : imcFileTo.GetEntry(imcIdentifierTo.EquipSlot, imcIdentifierTo.Variant); + var mtrlVariantTo = imcEntry.MaterialId; var isAccessory = slot.IsAccessory(); var estType = slot switch @@ -133,7 +127,6 @@ public static class EquipmentSwap var skipFemale = false; var skipMale = false; - var mtrlVariantTo = manips(imcManip.Copy(imcFileTo.GetEntry(ImcFile.PartIndex(slot), variantTo))).Imc.Entry.MaterialId; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) @@ -154,7 +147,7 @@ public static class EquipmentSwap if (eqdp != null) swaps.Add(eqdp); - var ownMdl = eqdp?.SwapApplied.Eqdp.Entry.ToBits(slot).Item2 ?? false; + var ownMdl = eqdp?.SwapToModdedEntry.Model ?? false; var est = ItemSwap.CreateEst(manager, redirections, manips, estType, gr, idFrom, idTo, ownMdl); if (est != null) swaps.Add(est); @@ -184,22 +177,22 @@ public static class EquipmentSwap return affectedItems; } - public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, - Func manips, EquipSlot slot, GenderRace gr, PrimaryId idFrom, - PrimaryId idTo, byte mtrlTo) + public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, + MetaDictionary manips, EquipSlot slot, GenderRace gr, PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) => CreateEqdp(manager, redirections, manips, slot, slot, gr, idFrom, idTo, mtrlTo); - public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, - Func manips, EquipSlot slotFrom, EquipSlot slotTo, GenderRace gr, PrimaryId idFrom, + public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, + MetaDictionary manips, EquipSlot slotFrom, EquipSlot slotTo, GenderRace gr, PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) { - var (gender, race) = gr.Split(); - var eqdpFrom = new EqdpManipulation(ExpandedEqdpFile.GetDefault(manager, gr, slotFrom.IsAccessory(), idFrom), slotFrom, gender, - race, idFrom); - var eqdpTo = new EqdpManipulation(ExpandedEqdpFile.GetDefault(manager, gr, slotTo.IsAccessory(), idTo), slotTo, gender, race, - idTo); - var meta = new MetaSwap(manips, eqdpFrom, eqdpTo); - var (ownMtrl, ownMdl) = meta.SwapApplied.Eqdp.Entry.ToBits(slotFrom); + var eqdpFromIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); + var eqdpToIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); + var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); + var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); + var meta = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, eqdpFromIdentifier, + eqdpFromDefault, eqdpToIdentifier, + eqdpToDefault); + var (ownMtrl, ownMdl) = meta.SwapToModdedEntry; if (ownMdl) { var mdl = CreateMdl(manager, redirections, slotFrom, slotTo, gr, idFrom, idTo, mtrlTo); @@ -270,38 +263,39 @@ public static class EquipmentSwap return (imc, variants, items); } - public static MetaSwap? CreateGmp(MetaFileManager manager, Func manips, EquipSlot slot, PrimaryId idFrom, - PrimaryId idTo) + public static MetaSwap? CreateGmp(MetaFileManager manager, MetaDictionary manips, + EquipSlot slot, PrimaryId idFrom, PrimaryId idTo) { if (slot is not EquipSlot.Head) return null; - var manipFrom = new GmpManipulation(ExpandedGmpFile.GetDefault(manager, idFrom), idFrom); - var manipTo = new GmpManipulation(ExpandedGmpFile.GetDefault(manager, idTo), idTo); - return new MetaSwap(manips, manipFrom, manipTo); + var manipFromIdentifier = new GmpIdentifier(idFrom); + var manipToIdentifier = new GmpIdentifier(idTo); + var manipFromDefault = ExpandedGmpFile.GetDefault(manager, manipFromIdentifier); + var manipToDefault = ExpandedGmpFile.GetDefault(manager, manipToIdentifier); + return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); } - public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, - Func manips, EquipSlot slot, - PrimaryId idFrom, PrimaryId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) + public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, + MetaDictionary manips, EquipSlot slot, PrimaryId idFrom, PrimaryId idTo, Variant variantFrom, Variant variantTo, + ImcFile imcFileFrom, ImcFile imcFileTo) => CreateImc(manager, redirections, manips, slot, slot, idFrom, idTo, variantFrom, variantTo, imcFileFrom, imcFileTo); - public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, - Func manips, - EquipSlot slotFrom, EquipSlot slotTo, PrimaryId idFrom, PrimaryId idTo, + public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, + MetaDictionary manips, EquipSlot slotFrom, EquipSlot slotTo, PrimaryId idFrom, PrimaryId idTo, Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) { - var entryFrom = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); - var entryTo = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); - var manipulationFrom = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, entryFrom); - var manipulationTo = new ImcManipulation(slotTo, variantTo.Id, idTo, entryTo); - var imc = new MetaSwap(manips, manipulationFrom, manipulationTo); + var manipFromIdentifier = new ImcIdentifier(slotFrom, idFrom, variantFrom); + var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); + var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); + var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); + var imc = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); - var decal = CreateDecal(manager, redirections, imc.SwapToModded.Imc.Entry.DecalId); + var decal = CreateDecal(manager, redirections, imc.SwapToModdedEntry.DecalId); if (decal != null) imc.ChildSwaps.Add(decal); - var avfx = CreateAvfx(manager, redirections, idFrom, idTo, imc.SwapToModded.Imc.Entry.VfxId); + var avfx = CreateAvfx(manager, redirections, idFrom, idTo, imc.SwapToModdedEntry.VfxId); if (avfx != null) imc.ChildSwaps.Add(avfx); @@ -322,7 +316,8 @@ public static class EquipmentSwap // Example: Abyssos Helm / Body - public static FileSwap? CreateAvfx(MetaFileManager manager, Func redirections, PrimaryId idFrom, PrimaryId idTo, byte vfxId) + public static FileSwap? CreateAvfx(MetaFileManager manager, Func redirections, PrimaryId idFrom, PrimaryId idTo, + byte vfxId) { if (vfxId == 0) return null; @@ -340,17 +335,18 @@ public static class EquipmentSwap return avfx; } - public static MetaSwap? CreateEqp(MetaFileManager manager, Func manips, EquipSlot slot, PrimaryId idFrom, - PrimaryId idTo) + public static MetaSwap? CreateEqp(MetaFileManager manager, MetaDictionary manips, + EquipSlot slot, PrimaryId idFrom, PrimaryId idTo) { if (slot.IsAccessory()) return null; - var eqpValueFrom = ExpandedEqpFile.GetDefault(manager, idFrom); - var eqpValueTo = ExpandedEqpFile.GetDefault(manager, idTo); - var eqpFrom = new EqpManipulation(eqpValueFrom, slot, idFrom); - var eqpTo = new EqpManipulation(eqpValueTo, slot, idFrom); - return new MetaSwap(manips, eqpFrom, eqpTo); + var manipFromIdentifier = new EqpIdentifier(idFrom, slot); + var manipToIdentifier = new EqpIdentifier(idTo, slot); + var manipFromDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idFrom), slot); + var manipToDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idTo), slot); + return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, + manipFromDefault, manipToIdentifier, manipToDefault); } public static FileSwap? CreateMtrl(MetaFileManager manager, Func redirections, EquipSlot slot, PrimaryId idFrom, @@ -397,7 +393,8 @@ public static class EquipmentSwap return mtrl; } - public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, PrimaryId idFrom, PrimaryId idTo, + public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, PrimaryId idFrom, + PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) => CreateTex(manager, redirections, prefix, EquipSlot.Unknown, EquipSlot.Unknown, idFrom, idTo, ref texture, ref dataWasChanged); diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 7fac52c1..efd8080c 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -147,24 +147,23 @@ public static class ItemSwap return FileSwap.CreateSwap(manager, ResourceType.Sklb, redirections, sklbPath, sklbPath); } - /// metaChanges is not manipulated, but IReadOnlySet does not support TryGetValue. - public static MetaSwap? CreateEst(MetaFileManager manager, Func redirections, - Func manips, EstType type, - GenderRace genderRace, PrimaryId idFrom, PrimaryId idTo, bool ownMdl) + public static MetaSwap? CreateEst(MetaFileManager manager, Func redirections, + MetaDictionary manips, EstType type, GenderRace genderRace, PrimaryId idFrom, PrimaryId idTo, bool ownMdl) { if (type == 0) return null; - var (gender, race) = genderRace.Split(); - var fromDefault = new EstManipulation(gender, race, type, idFrom, EstFile.GetDefault(manager, type, genderRace, idFrom)); - var toDefault = new EstManipulation(gender, race, type, idTo, EstFile.GetDefault(manager, type, genderRace, idTo)); - var est = new MetaSwap(manips, fromDefault, toDefault); + var manipFromIdentifier = new EstIdentifier(idFrom, type, genderRace); + var manipToIdentifier = new EstIdentifier(idTo, type, genderRace); + var manipFromDefault = EstFile.GetDefault(manager, manipFromIdentifier); + var manipToDefault = EstFile.GetDefault(manager, manipToIdentifier); + var est = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); - if (ownMdl && est.SwapApplied.Est.Entry.Value >= 2) + if (ownMdl && est.SwapToModdedEntry.Value >= 2) { - var phyb = CreatePhyb(manager, redirections, type, genderRace, est.SwapApplied.Est.Entry); + var phyb = CreatePhyb(manager, redirections, type, genderRace, est.SwapToModdedEntry); est.ChildSwaps.Add(phyb); - var sklb = CreateSklb(manager, redirections, type, genderRace, est.SwapApplied.Est.Entry); + var sklb = CreateSklb(manager, redirections, type, genderRace, est.SwapToModdedEntry); est.ChildSwaps.Add(sklb); } else if (est.SwapAppliedIsDefault) diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 67a5d007..021ee665 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -74,9 +74,9 @@ public class ItemSwapContainer } break; - case MetaSwap meta: + case IMetaSwap meta: if (!meta.SwapAppliedIsDefault) - convertedManips.Add(meta.SwapApplied); + convertedManips.Add(meta.SwapFromIdentifier, meta.SwapToModdedEntry); break; } @@ -116,17 +116,10 @@ public class ItemSwapContainer ? p => collection.ResolvePath(p) ?? new FullPath(p) : p => ModRedirections.TryGetValue(p, out var path) ? path : new FullPath(p); - private Func MetaResolver(ModCollection? collection) - { - if (collection?.MetaCache?.Manipulations is { } cache) - { - MetaDictionary dict = [.. cache]; - return m => dict.TryGetValue(m, out var a) ? a : m; - } - - var set = _appliedModData.Manipulations; - return m => set.TryGetValue(m, out var a) ? a : m; - } + private MetaDictionary MetaResolver(ModCollection? collection) + => collection?.MetaCache?.Manipulations is { } cache + ? [.. cache] + : _appliedModData.Manipulations; public EquipItem[] LoadEquipment(EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, bool useLeftRing = true) @@ -161,8 +154,8 @@ public class ItemSwapContainer _ => (EstType)0, }; - var metaResolver = MetaResolver(collection); - var est = ItemSwap.CreateEst(manager, pathResolver, metaResolver, type, race, from, to, true); + var estResolver = MetaResolver(collection); + var est = ItemSwap.CreateEst(manager, pathResolver, estResolver, type, race, from, to, true); Swaps.Add(mdl); if (est != null) diff --git a/Penumbra/Mods/ItemSwap/Swaps.cs b/Penumbra/Mods/ItemSwap/Swaps.cs index 27935ffb..36c54203 100644 --- a/Penumbra/Mods/ItemSwap/Swaps.cs +++ b/Penumbra/Mods/ItemSwap/Swaps.cs @@ -1,58 +1,91 @@ -using Penumbra.Api.Enums; +using Penumbra.Api.Enums; using Penumbra.GameData.Files; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; using Penumbra.Meta; using static Penumbra.Mods.ItemSwap.ItemSwap; -using Penumbra.Services; namespace Penumbra.Mods.ItemSwap; public class Swap { /// Any further swaps belonging specifically to this tree of changes. - public readonly List ChildSwaps = new(); + public readonly List ChildSwaps = []; public IEnumerable WithChildren() => ChildSwaps.SelectMany(c => c.WithChildren()).Prepend(this); } -public sealed class MetaSwap : Swap +public interface IMetaSwap { + public IMetaIdentifier SwapFromIdentifier { get; } + public IMetaIdentifier SwapToIdentifier { get; } + + public object SwapFromDefaultEntry { get; } + public object SwapToDefaultEntry { get; } + public object SwapToModdedEntry { get; } + + public bool SwapToIsDefault { get; } + public bool SwapAppliedIsDefault { get; } +} + +public sealed class MetaSwap : Swap, IMetaSwap + where TIdentifier : unmanaged, IMetaIdentifier + where TEntry : unmanaged, IEquatable +{ + public TIdentifier SwapFromIdentifier; + public TIdentifier SwapToIdentifier; + /// The default value of a specific meta manipulation that needs to be redirected. - public MetaManipulation SwapFrom; + public TEntry SwapFromDefaultEntry; /// The default value of the same Meta entry of the redirected item. - public MetaManipulation SwapToDefault; + public TEntry SwapToDefaultEntry; /// The modded value of the same Meta entry of the redirected item, or the same as SwapToDefault if unmodded. - public MetaManipulation SwapToModded; + public TEntry SwapToModdedEntry; - /// The modded value applied to the specific meta manipulation target before redirection. - public MetaManipulation SwapApplied; - - /// Whether SwapToModded equals SwapToDefault. - public bool SwapToIsDefault; + /// Whether SwapToModdedEntry equals SwapToDefaultEntry. + public bool SwapToIsDefault { get; } /// Whether the applied meta manipulation does not change anything against the default. - public bool SwapAppliedIsDefault; + public bool SwapAppliedIsDefault { get; } /// /// Create a new MetaSwap from the original meta identifier and the target meta identifier. /// - /// A function that converts the given manipulation to the modded one. - /// The original meta identifier with its default value. - /// The target meta identifier with its default value. - public MetaSwap(Func manipulations, MetaManipulation manipFrom, MetaManipulation manipTo) + /// A function that obtains a modded meta entry if it exists. + /// The original meta identifier. + /// The default value for the original meta identifier. + /// The target meta identifier. + /// The default value for the target meta identifier. + public MetaSwap(Func manipulations, TIdentifier manipFromIdentifier, TEntry manipFromEntry, + TIdentifier manipToIdentifier, TEntry manipToEntry) { - SwapFrom = manipFrom; - SwapToDefault = manipTo; + SwapFromIdentifier = manipFromIdentifier; + SwapToIdentifier = manipToIdentifier; + SwapFromDefaultEntry = manipFromEntry; + SwapToDefaultEntry = manipToEntry; - SwapToModded = manipulations(manipTo); - SwapToIsDefault = manipTo.EntryEquals(SwapToModded); - SwapApplied = SwapFrom.WithEntryOf(SwapToModded); - SwapAppliedIsDefault = SwapApplied.EntryEquals(SwapFrom); + SwapToModdedEntry = manipulations(SwapToIdentifier) ?? SwapToDefaultEntry; + SwapToIsDefault = SwapToModdedEntry.Equals(SwapToDefaultEntry); + SwapAppliedIsDefault = SwapToModdedEntry.Equals(SwapFromDefaultEntry); } + + IMetaIdentifier IMetaSwap.SwapFromIdentifier + => SwapFromIdentifier; + + IMetaIdentifier IMetaSwap.SwapToIdentifier + => SwapToIdentifier; + + object IMetaSwap.SwapFromDefaultEntry + => SwapFromDefaultEntry; + + object IMetaSwap.SwapToDefaultEntry + => SwapToDefaultEntry; + + object IMetaSwap.SwapToModdedEntry + => SwapToModdedEntry; } public sealed class FileSwap : Swap @@ -113,8 +146,7 @@ public sealed class FileSwap : Swap /// A full swap container with the actual file in memory. /// True if everything could be read correctly, false otherwise. public static FileSwap CreateSwap(MetaFileManager manager, ResourceType type, Func redirections, - string swapFromRequest, string swapToRequest, - string? swapFromPreChange = null) + string swapFromRequest, string swapToRequest, string? swapFromPreChange = null) { var swap = new FileSwap { diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 6010cdaf..62115dd6 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -240,7 +240,7 @@ public class ItemSwapTab : IDisposable, ITab { return swap switch { - MetaSwap meta => $"{meta.SwapFrom}: {meta.SwapFrom.EntryToString()} -> {meta.SwapApplied.EntryToString()}", + IMetaSwap meta => $"{meta.SwapFromIdentifier}: {meta.SwapFromDefaultEntry} -> {meta.SwapToModdedEntry}", FileSwap file => $"{file.Type}: {file.SwapFromRequestPath} -> {file.SwapToModded.FullName}{(file.DataWasChanged ? " (EDITED)" : string.Empty)}", _ => string.Empty, @@ -410,7 +410,7 @@ public class ItemSwapTab : IDisposable, ITab private ImRaii.IEndObject DrawTab(SwapType newTab) { - using var tab = ImRaii.TabItem(newTab is SwapType.BetweenSlots ? "Between Slots" : newTab.ToString()); + var tab = ImRaii.TabItem(newTab is SwapType.BetweenSlots ? "Between Slots" : newTab.ToString()); if (tab) { _dirty |= _lastTab != newTab; From d9b63320f07b5600bdd71b3420fd740e0f44e6d4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 20:46:29 +0200 Subject: [PATCH 0683/1381] Some small fixes, parse directly into MetaDictionary. --- Penumbra/Api/Api/TemporaryApi.cs | 24 ++++--------------- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 3 ++- Penumbra/Meta/Manipulations/MetaDictionary.cs | 16 ++++++------- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 +- 5 files changed, 17 insertions(+), 30 deletions(-) diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 995ec388..49958a0d 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -159,8 +159,7 @@ public class TemporaryApi( /// The empty string is treated as an empty set. /// Only returns true if all conversions are successful and distinct. /// - private static bool ConvertManips(string manipString, - [NotNullWhen(true)] out MetaDictionary? manips) + private static bool ConvertManips(string manipString, [NotNullWhen(true)] out MetaDictionary? manips) { if (manipString.Length == 0) { @@ -168,23 +167,10 @@ public class TemporaryApi( return true; } - if (Functions.FromCompressedBase64(manipString, out var manipArray) != MetaManipulation.CurrentVersion) - { - manips = null; - return false; - } + if (Functions.FromCompressedBase64(manipString, out manips!) == MetaManipulation.CurrentVersion) + return true; - manips = []; - foreach (var manip in manipArray!.Where(m => m.Validate())) - { - if (manips.Add(manip)) - continue; - - Penumbra.Log.Warning($"Manipulation {manip} {manip.EntryToString()} is invalid and was skipped."); - manips = null; - return false; - } - - return true; + manips = null; + return false; } } diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index a8405eb2..15601867 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -4,6 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.Api.IpcSubscribers; using Penumbra.Collections.Manager; @@ -49,7 +50,7 @@ public class TemporaryIpcTester( ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); - ImGui.InputTextWithHint("##tempManip", "Manipulation Base64 String...", ref _tempManipulation, 256); + ImUtf8.InputText("##tempManip"u8, ref _tempManipulation, "Manipulation Base64 String..."u8); ImGui.Checkbox("Force Character Collection Overwrite", ref _forceOverwrite); using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 51149e3b..3ce54afb 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -52,16 +52,16 @@ public sealed class MetaDictionary : IEnumerable IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public bool Add(IMetaIdentifier identifier, object entry) + public bool TryAdd(IMetaIdentifier identifier, object entry) => identifier switch { - EqdpIdentifier eqdpIdentifier => entry is EqdpEntryInternal e && Add(eqdpIdentifier, e), - EqpIdentifier eqpIdentifier => entry is EqpEntryInternal e && Add(eqpIdentifier, e), - EstIdentifier estIdentifier => entry is EstEntry e && Add(estIdentifier, e), - GlobalEqpManipulation globalEqpManipulation => Add(globalEqpManipulation), - GmpIdentifier gmpIdentifier => entry is GmpEntry e && Add(gmpIdentifier, e), - ImcIdentifier imcIdentifier => entry is ImcEntry e && Add(imcIdentifier, e), - RspIdentifier rspIdentifier => entry is RspEntry e && Add(rspIdentifier, e), + EqdpIdentifier eqdpIdentifier => entry is EqdpEntryInternal e && TryAdd(eqdpIdentifier, e), + EqpIdentifier eqpIdentifier => entry is EqpEntryInternal e && TryAdd(eqpIdentifier, e), + EstIdentifier estIdentifier => entry is EstEntry e && TryAdd(estIdentifier, e), + GlobalEqpManipulation globalEqpManipulation => TryAdd(globalEqpManipulation), + GmpIdentifier gmpIdentifier => entry is GmpEntry e && TryAdd(gmpIdentifier, e), + ImcIdentifier imcIdentifier => entry is ImcEntry e && TryAdd(imcIdentifier, e), + RspIdentifier rspIdentifier => entry is RspEntry e && TryAdd(rspIdentifier, e), _ => false, }; diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 021ee665..b0b588b4 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -76,7 +76,7 @@ public class ItemSwapContainer break; case IMetaSwap meta: if (!meta.SwapAppliedIsDefault) - convertedManips.Add(meta.SwapFromIdentifier, meta.SwapToModdedEntry); + convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry); break; } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 1813a7e3..396029d5 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -432,7 +432,7 @@ public class DebugTab : Window, ITab foreach (var obj in _objects) { - ImGuiUtil.DrawTableColumn($"{((GameObject*)obj.Address)->ObjectIndex}"); + ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero ? $"{((GameObject*)obj.Address)->ObjectIndex}" : "NULL"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero ? string.Empty From 196ca2ce393ba160c1bc7c29f9375feeb64f1b1f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 8 Jun 2024 21:15:40 +0200 Subject: [PATCH 0684/1381] Remove all usages of Add(MetaManipulation) --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 137 +++++++++++------- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 54 ++++--- Penumbra/Mods/SubMods/SubMod.cs | 6 +- Penumbra/Mods/TemporaryMod.cs | 4 +- 4 files changed, 121 insertions(+), 80 deletions(-) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 3ce54afb..1dc6496e 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -52,38 +52,6 @@ public sealed class MetaDictionary : IEnumerable IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public bool TryAdd(IMetaIdentifier identifier, object entry) - => identifier switch - { - EqdpIdentifier eqdpIdentifier => entry is EqdpEntryInternal e && TryAdd(eqdpIdentifier, e), - EqpIdentifier eqpIdentifier => entry is EqpEntryInternal e && TryAdd(eqpIdentifier, e), - EstIdentifier estIdentifier => entry is EstEntry e && TryAdd(estIdentifier, e), - GlobalEqpManipulation globalEqpManipulation => TryAdd(globalEqpManipulation), - GmpIdentifier gmpIdentifier => entry is GmpEntry e && TryAdd(gmpIdentifier, e), - ImcIdentifier imcIdentifier => entry is ImcEntry e && TryAdd(imcIdentifier, e), - RspIdentifier rspIdentifier => entry is RspEntry e && TryAdd(rspIdentifier, e), - _ => false, - }; - - public bool Add(MetaManipulation manip) - { - var ret = manip.ManipulationType switch - { - MetaManipulation.Type.Imc => _imc.TryAdd(manip.Imc.Identifier, manip.Imc.Entry), - MetaManipulation.Type.Eqdp => _eqdp.TryAdd(manip.Eqdp.Identifier, new EqdpEntryInternal(manip.Eqdp.Entry, manip.Eqdp.Slot)), - MetaManipulation.Type.Eqp => _eqp.TryAdd(manip.Eqp.Identifier, new EqpEntryInternal(manip.Eqp.Entry, manip.Eqp.Slot)), - MetaManipulation.Type.Est => _est.TryAdd(manip.Est.Identifier, manip.Est.Entry), - MetaManipulation.Type.Gmp => _gmp.TryAdd(manip.Gmp.Identifier, manip.Gmp.Entry), - MetaManipulation.Type.Rsp => _rsp.TryAdd(manip.Rsp.Identifier, manip.Rsp.Entry), - MetaManipulation.Type.GlobalEqp => _globalEqp.Add(manip.GlobalEqp), - _ => false, - }; - - if (ret) - ++Count; - return ret; - } - public bool TryAdd(ImcIdentifier identifier, ImcEntry entry) { if (!_imc.TryAdd(identifier, entry)) @@ -93,9 +61,29 @@ public sealed class MetaDictionary : IEnumerable return true; } + + public bool TryAdd(EqpIdentifier identifier, EqpEntryInternal entry) + { + if (!_eqp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + public bool TryAdd(EqpIdentifier identifier, EqpEntry entry) => TryAdd(identifier, new EqpEntryInternal(entry, identifier.Slot)); + + public bool TryAdd(EqdpIdentifier identifier, EqdpEntryInternal entry) + { + if (!_eqdp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + public bool TryAdd(EqdpIdentifier identifier, EqdpEntry entry) => TryAdd(identifier, new EqdpEntryInternal(entry, identifier.Slot)); @@ -159,6 +147,73 @@ public sealed class MetaDictionary : IEnumerable TryAdd(identifier); } + /// Try to merge all manipulations from manips into this, and return the first failure, if any. + public bool MergeForced(MetaDictionary manips, out IMetaIdentifier failedIdentifier) + { + foreach (var (identifier, entry) in manips._imc) + { + if (!TryAdd(identifier, entry)) + { + failedIdentifier = identifier; + return false; + } + } + + foreach (var (identifier, entry) in manips._eqp) + { + if (!TryAdd(identifier, entry)) + { + failedIdentifier = identifier; + return false; + } + } + + foreach (var (identifier, entry) in manips._eqdp) + { + if (!TryAdd(identifier, entry)) + { + failedIdentifier = identifier; + return false; + } + } + + foreach (var (identifier, entry) in manips._gmp) + { + if (!TryAdd(identifier, entry)) + { + failedIdentifier = identifier; + return false; + } + } + + foreach (var (identifier, entry) in manips._rsp) + { + if (!TryAdd(identifier, entry)) + { + failedIdentifier = identifier; + return false; + } + } + + foreach (var (identifier, entry) in manips._est) + { + if (!TryAdd(identifier, entry)) + { + failedIdentifier = identifier; + return false; + } + } + + foreach (var identifier in manips._globalEqp) + { + if (!TryAdd(identifier)) + { + failedIdentifier = identifier; + return false; + } + } + } + public bool TryGetValue(EstIdentifier identifier, out EstEntry value) => _est.TryGetValue(identifier, out value); @@ -318,22 +373,4 @@ public sealed class MetaDictionary : IEnumerable return dict; } } - - private bool TryAdd(EqpIdentifier identifier, EqpEntryInternal entry) - { - if (!_eqp.TryAdd(identifier, entry)) - return false; - - ++Count; - return true; - } - - private bool TryAdd(EqdpIdentifier identifier, EqdpEntryInternal entry) - { - if (!_eqdp.TryAdd(identifier, entry)) - return false; - - ++Count; - return true; - } } diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index b0b588b4..72a6005d 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -53,32 +53,38 @@ public class ItemSwapContainer { foreach (var swap in Swaps.SelectMany(s => s.WithChildren())) { - switch (swap) + if (swap is FileSwap file) { - case FileSwap file: - // Skip, nothing to do - if (file.SwapToModdedEqualsOriginal) - continue; + // Skip, nothing to do + if (file.SwapToModdedEqualsOriginal) + continue; - if (writeType == WriteType.UseSwaps && file.SwapToModdedExistsInGame && !file.DataWasChanged) - { - convertedSwaps.TryAdd(file.SwapFromRequestPath, file.SwapToModded); - } - else - { - var path = file.GetNewPath(directory.FullName); - var bytes = file.FileData.Write(); - Directory.CreateDirectory(Path.GetDirectoryName(path)!); - _manager.Compactor.WriteAllBytes(path, bytes); - convertedFiles.TryAdd(file.SwapFromRequestPath, new FullPath(path)); - } - - break; - case IMetaSwap meta: - if (!meta.SwapAppliedIsDefault) - convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry); - - break; + if (writeType == WriteType.UseSwaps && file.SwapToModdedExistsInGame && !file.DataWasChanged) + { + convertedSwaps.TryAdd(file.SwapFromRequestPath, file.SwapToModded); + } + else + { + var path = file.GetNewPath(directory.FullName); + var bytes = file.FileData.Write(); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + _manager.Compactor.WriteAllBytes(path, bytes); + convertedFiles.TryAdd(file.SwapFromRequestPath, new FullPath(path)); + } + } + else if (swap is IMetaSwap { SwapAppliedIsDefault: false }) + { + // @formatter:off + _ = swap switch + { + MetaSwap meta => convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry), + MetaSwap meta => convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry), + MetaSwap meta => convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry), + MetaSwapmeta => convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry), + MetaSwapmeta => convertedManips.TryAdd(meta.SwapFromIdentifier, meta.SwapToModdedEntry), + _ => false, + }; + // @formatter:on } } diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index 06a924c8..40fd2e75 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -64,11 +64,9 @@ public static class SubMod data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); } - var manips = json[nameof(data.Manipulations)]; + var manips = json[nameof(data.Manipulations)]?.ToObject(); if (manips != null) - foreach (var s in manips.Children().Select(c => c.ToObject()) - .Where(m => m.Validate())) - data.Manipulations.Add(s); + data.Manipulations.UnionWith(manips); } /// Load the relevant data for a selectable option from a JToken of that option. diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index a715f786..61ed4528 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -93,8 +93,8 @@ public class TemporaryMod : IMod } } - foreach (var manip in collection.MetaCache?.Manipulations ?? Array.Empty()) - defaultMod.Manipulations.Add(manip); + MetaDictionary manips = [.. collection.MetaCache?.Manipulations ?? []]; + defaultMod.Manipulations.UnionWith(manips); saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir); From 361082813b59c125949c3a3c092945a2844626e3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 11 Jun 2024 12:23:08 +0200 Subject: [PATCH 0685/1381] tmp --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 198 +++++-- .../Meta/Manipulations/MetaManipulation.cs | 142 ++++- Penumbra/Mods/Editor/ModMerger.cs | 9 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 167 +----- Penumbra/Mods/Groups/ImcModGroup.cs | 14 +- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 2 +- Penumbra/Mods/ModCreator.cs | 6 +- Penumbra/Mods/SubMods/SubMod.cs | 2 +- Penumbra/Mods/TemporaryMod.cs | 3 +- Penumbra/Services/StaticServiceManager.cs | 1 - .../UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 353 ++++++++++++ .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 522 ++++++++++-------- Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs | 19 +- .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 11 +- Penumbra/UI/ModsTab/ImcManipulationDrawer.cs | 207 +------ Penumbra/Util/DictionaryExtensions.cs | 12 + 16 files changed, 1008 insertions(+), 660 deletions(-) create mode 100644 Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 1dc6496e..236157ae 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -7,7 +7,7 @@ using ImcEntry = Penumbra.GameData.Structs.ImcEntry; namespace Penumbra.Meta.Manipulations; [JsonConverter(typeof(Converter))] -public sealed class MetaDictionary : IEnumerable +public class MetaDictionary : IEnumerable { private readonly Dictionary _imc = []; private readonly Dictionary _eqp = []; @@ -17,8 +17,37 @@ public sealed class MetaDictionary : IEnumerable private readonly Dictionary _gmp = []; private readonly HashSet _globalEqp = []; + public IReadOnlyDictionary Imc + => _imc; + public int Count { get; private set; } + public int GetCount(MetaManipulation.Type type) + => type switch + { + MetaManipulation.Type.Imc => _imc.Count, + MetaManipulation.Type.Eqdp => _eqdp.Count, + MetaManipulation.Type.Eqp => _eqp.Count, + MetaManipulation.Type.Est => _est.Count, + MetaManipulation.Type.Gmp => _gmp.Count, + MetaManipulation.Type.Rsp => _rsp.Count, + MetaManipulation.Type.GlobalEqp => _globalEqp.Count, + _ => 0, + }; + + public bool CanAdd(IMetaIdentifier identifier) + => identifier switch + { + EqdpIdentifier eqdpIdentifier => !_eqdp.ContainsKey(eqdpIdentifier), + EqpIdentifier eqpIdentifier => !_eqp.ContainsKey(eqpIdentifier), + EstIdentifier estIdentifier => !_est.ContainsKey(estIdentifier), + GlobalEqpManipulation globalEqpManipulation => !_globalEqp.Contains(globalEqpManipulation), + GmpIdentifier gmpIdentifier => !_gmp.ContainsKey(gmpIdentifier), + ImcIdentifier imcIdentifier => !_imc.ContainsKey(imcIdentifier), + RspIdentifier rspIdentifier => !_rsp.ContainsKey(rspIdentifier), + _ => false, + }; + public void Clear() { _imc.Clear(); @@ -123,6 +152,68 @@ public sealed class MetaDictionary : IEnumerable return true; } + public bool Update(ImcIdentifier identifier, ImcEntry entry) + { + if (!_imc.ContainsKey(identifier)) + return false; + + _imc[identifier] = entry; + return true; + } + + + public bool Update(EqpIdentifier identifier, EqpEntryInternal entry) + { + if (!_eqp.ContainsKey(identifier)) + return false; + + _eqp[identifier] = entry; + return true; + } + + public bool Update(EqpIdentifier identifier, EqpEntry entry) + => Update(identifier, new EqpEntryInternal(entry, identifier.Slot)); + + + public bool Update(EqdpIdentifier identifier, EqdpEntryInternal entry) + { + if (!_eqdp.ContainsKey(identifier)) + return false; + + _eqdp[identifier] = entry; + return true; + } + + public bool Update(EqdpIdentifier identifier, EqdpEntry entry) + => Update(identifier, new EqdpEntryInternal(entry, identifier.Slot)); + + public bool Update(EstIdentifier identifier, EstEntry entry) + { + if (!_est.ContainsKey(identifier)) + return false; + + _est[identifier] = entry; + return true; + } + + public bool Update(GmpIdentifier identifier, GmpEntry entry) + { + if (!_gmp.ContainsKey(identifier)) + return false; + + _gmp[identifier] = entry; + return true; + } + + public bool Update(RspIdentifier identifier, RspEntry entry) + { + if (!_rsp.ContainsKey(identifier)) + return false; + + _rsp[identifier] = entry; + return true; + } + public void UnionWith(MetaDictionary manips) { foreach (var (identifier, entry) in manips._imc) @@ -148,70 +239,52 @@ public sealed class MetaDictionary : IEnumerable } /// Try to merge all manipulations from manips into this, and return the first failure, if any. - public bool MergeForced(MetaDictionary manips, out IMetaIdentifier failedIdentifier) + public bool MergeForced(MetaDictionary manips, out IMetaIdentifier? failedIdentifier) { - foreach (var (identifier, entry) in manips._imc) + foreach (var (identifier, _) in manips._imc.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { - if (!TryAdd(identifier, entry)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } - foreach (var (identifier, entry) in manips._eqp) + foreach (var (identifier, _) in manips._eqp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { - if (!TryAdd(identifier, entry)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } - foreach (var (identifier, entry) in manips._eqdp) + foreach (var (identifier, _) in manips._eqdp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { - if (!TryAdd(identifier, entry)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } - foreach (var (identifier, entry) in manips._gmp) + foreach (var (identifier, _) in manips._gmp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { - if (!TryAdd(identifier, entry)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } - foreach (var (identifier, entry) in manips._rsp) + foreach (var (identifier, _) in manips._rsp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { - if (!TryAdd(identifier, entry)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } - foreach (var (identifier, entry) in manips._est) + foreach (var (identifier, _) in manips._est.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { - if (!TryAdd(identifier, entry)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } - foreach (var identifier in manips._globalEqp) + foreach (var identifier in manips._globalEqp.Where(identifier => !TryAdd(identifier))) { - if (!TryAdd(identifier)) - { - failedIdentifier = identifier; - return false; - } + failedIdentifier = identifier; + return false; } + + failedIdentifier = default; + return false; } public bool TryGetValue(EstIdentifier identifier, out EstEntry value) @@ -244,6 +317,18 @@ public sealed class MetaDictionary : IEnumerable Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _globalEqp.Count; } + public void UpdateTo(MetaDictionary other) + { + _imc.UpdateTo(other._imc); + _eqp.UpdateTo(other._eqp); + _eqdp.UpdateTo(other._eqdp); + _est.UpdateTo(other._est); + _rsp.UpdateTo(other._rsp); + _gmp.UpdateTo(other._gmp); + _globalEqp.UnionWith(other._globalEqp); + Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _globalEqp.Count; + } + public MetaDictionary Clone() { var ret = new MetaDictionary(); @@ -251,6 +336,31 @@ public sealed class MetaDictionary : IEnumerable return ret; } + private static void WriteJson(JsonWriter writer, JsonSerializer serializer, IMetaIdentifier identifier, object entry) + { + var type = identifier switch + { + ImcIdentifier => "Imc", + EqdpIdentifier => "Eqdp", + EqpIdentifier => "Eqp", + EstIdentifier => "Est", + GmpIdentifier => "Gmp", + RspIdentifier => "Rsp", + GlobalEqpManipulation => "GlobalEqp", + _ => string.Empty, + }; + + if (type.Length == 0) + return; + + writer.WriteStartObject(); + writer.WritePropertyName("Type"); + writer.WriteValue(type); + writer.WritePropertyName("Manipulation"); + + writer.WriteEndObject(); + } + private class Converter : JsonConverter { public override void WriteJson(JsonWriter writer, MetaDictionary? value, JsonSerializer serializer) diff --git a/Penumbra/Meta/Manipulations/MetaManipulation.cs b/Penumbra/Meta/Manipulations/MetaManipulation.cs index f22de809..b80681d2 100644 --- a/Penumbra/Meta/Manipulations/MetaManipulation.cs +++ b/Penumbra/Meta/Manipulations/MetaManipulation.cs @@ -1,9 +1,148 @@ +using Dalamud.Interface; +using ImGuiNET; using Newtonsoft.Json; using Newtonsoft.Json.Converters; +using OtterGui; +using Penumbra.GameData.Enums; using Penumbra.Interop.Structs; +using Penumbra.Mods.Editor; using Penumbra.String.Functions; +using Penumbra.UI; +using Penumbra.UI.ModsTab; -namespace Penumbra.Meta.Manipulations; +namespace Penumbra.Meta.Manipulations; + +#if false +private static class ImcRow +{ + private static ImcIdentifier _newIdentifier = ImcIdentifier.Default; + + private static float IdWidth + => 80 * UiHelpers.Scale; + + private static float SmallIdWidth + => 45 * UiHelpers.Scale; + + public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current IMC manipulations to clipboard.", iconSize, + editor.MetaEditor.Imc.Select(m => (MetaManipulation)m)); + ImGui.TableNextColumn(); + var (defaultEntry, fileExists, _) = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true); + var manip = (MetaManipulation)new ImcManipulation(_newIdentifier, defaultEntry); + var canAdd = fileExists && editor.MetaEditor.CanAdd(manip); + var tt = canAdd ? "Stage this edit." : !fileExists ? "This IMC file does not exist." : "This entry is already edited."; + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) + editor.MetaEditor.Add(manip); + + // Identifier + ImGui.TableNextColumn(); + var change = ImcManipulationDrawer.DrawObjectType(ref _newIdentifier); + + ImGui.TableNextColumn(); + change |= ImcManipulationDrawer.DrawPrimaryId(ref _newIdentifier); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, + new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); + + ImGui.TableNextColumn(); + // Equipment and accessories are slightly different imcs than other types. + if (_newIdentifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier); + else + change |= ImcManipulationDrawer.DrawSecondaryId(ref _newIdentifier); + + ImGui.TableNextColumn(); + change |= ImcManipulationDrawer.DrawVariant(ref _newIdentifier); + + ImGui.TableNextColumn(); + if (_newIdentifier.ObjectType is ObjectType.DemiHuman) + change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier, 70); + else + ImUtf8.ScaledDummy(new Vector2(70 * UiHelpers.Scale, 0)); + + if (change) + defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true).Entry; + // Values + using var disabled = ImRaii.Disabled(); + ImGui.TableNextColumn(); + ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref defaultEntry, false); + ImGui.SameLine(); + ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref defaultEntry, false); + ImGui.TableNextColumn(); + ImcManipulationDrawer.DrawDecalId(defaultEntry, ref defaultEntry, false); + ImGui.SameLine(); + ImcManipulationDrawer.DrawVfxId(defaultEntry, ref defaultEntry, false); + ImGui.SameLine(); + ImcManipulationDrawer.DrawSoundId(defaultEntry, ref defaultEntry, false); + ImGui.TableNextColumn(); + ImcManipulationDrawer.DrawAttributes(defaultEntry, ref defaultEntry); + } + + public static void Draw(MetaFileManager metaFileManager, ImcManipulation meta, ModEditor editor, Vector2 iconSize) + { + DrawMetaButtons(meta, editor, iconSize); + + // Identifier + ImGui.TableNextColumn(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + ImGui.TextUnformatted(meta.ObjectType.ToName()); + ImGuiUtil.HoverTooltip(ObjectTypeTooltip); + ImGui.TableNextColumn(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + ImGui.TextUnformatted(meta.PrimaryId.ToString()); + ImGuiUtil.HoverTooltip(PrimaryIdTooltipShort); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + if (meta.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + { + ImGui.TextUnformatted(meta.EquipSlot.ToName()); + ImGuiUtil.HoverTooltip(EquipSlotTooltip); + } + else + { + ImGui.TextUnformatted(meta.SecondaryId.ToString()); + ImGuiUtil.HoverTooltip(SecondaryIdTooltip); + } + + ImGui.TableNextColumn(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + ImGui.TextUnformatted(meta.Variant.ToString()); + ImGuiUtil.HoverTooltip(VariantIdTooltip); + + ImGui.TableNextColumn(); + ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); + if (meta.ObjectType is ObjectType.DemiHuman) + { + ImGui.TextUnformatted(meta.EquipSlot.ToName()); + ImGuiUtil.HoverTooltip(EquipSlotTooltip); + } + + // Values + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, + new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); + ImGui.TableNextColumn(); + var defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(meta.Identifier, true).Entry; + var newEntry = meta.Entry; + var changes = ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref newEntry, true); + ImGui.SameLine(); + changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref newEntry, true); + ImGui.TableNextColumn(); + changes |= ImcManipulationDrawer.DrawDecalId(defaultEntry, ref newEntry, true); + ImGui.SameLine(); + changes |= ImcManipulationDrawer.DrawVfxId(defaultEntry, ref newEntry, true); + ImGui.SameLine(); + changes |= ImcManipulationDrawer.DrawSoundId(defaultEntry, ref newEntry, true); + ImGui.TableNextColumn(); + changes |= ImcManipulationDrawer.DrawAttributes(defaultEntry, ref newEntry); + + if (changes) + editor.MetaEditor.Change(meta.Copy(newEntry)); + } +} + +#endif public interface IMetaManipulation { @@ -315,3 +454,4 @@ public readonly struct MetaManipulation : IEquatable, ICompara public static bool operator >=(MetaManipulation left, MetaManipulation right) => left.CompareTo(right) >= 0; } + diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 4faced80..2df76838 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -162,12 +162,9 @@ public class ModMerger : IDisposable foreach (var originalOption in mergeOptions) { - foreach (var manip in originalOption.Manipulations) - { - if (!manips.Add(manip)) - throw new Exception( - $"Could not add meta manipulation {manip} from {originalOption.GetFullName()} to {option.GetFullName()} because another manipulation of the same data already exists in this option."); - } + if (!manips.MergeForced(originalOption.Manipulations, out var failed)) + throw new Exception( + $"Could not add meta manipulation {failed} from {originalOption.GetFullName()} to {option.GetFullName()} because another manipulation of the same data already exists in this option."); foreach (var (swapA, swapB) in originalOption.FileSwaps) { diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 45d9f8a1..42171378 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,24 +1,24 @@ using System.Collections.Frozen; +using OtterGui.Services; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Editor; -public class ModMetaEditor(ModManager modManager) +public class ModMetaEditor(ModManager modManager) : MetaDictionary, IService { - private readonly HashSet _imc = []; - private readonly HashSet _eqp = []; - private readonly HashSet _eqdp = []; - private readonly HashSet _gmp = []; - private readonly HashSet _est = []; - private readonly HashSet _rsp = []; - private readonly HashSet _globalEqp = []; - public sealed class OtherOptionData : HashSet { public int TotalCount; + public void Add(string name, int count) + { + if (count > 0) + Add(name); + TotalCount += count; + } + public new void Clear() { TotalCount = 0; @@ -31,91 +31,9 @@ public class ModMetaEditor(ModManager modManager) public bool Changes { get; private set; } - public IReadOnlySet Imc - => _imc; - - public IReadOnlySet Eqp - => _eqp; - - public IReadOnlySet Eqdp - => _eqdp; - - public IReadOnlySet Gmp - => _gmp; - - public IReadOnlySet Est - => _est; - - public IReadOnlySet Rsp - => _rsp; - - public IReadOnlySet GlobalEqp - => _globalEqp; - - public bool CanAdd(MetaManipulation m) + public new void Clear() { - return m.ManipulationType switch - { - MetaManipulation.Type.Imc => !_imc.Contains(m.Imc), - MetaManipulation.Type.Eqdp => !_eqdp.Contains(m.Eqdp), - MetaManipulation.Type.Eqp => !_eqp.Contains(m.Eqp), - MetaManipulation.Type.Est => !_est.Contains(m.Est), - MetaManipulation.Type.Gmp => !_gmp.Contains(m.Gmp), - MetaManipulation.Type.Rsp => !_rsp.Contains(m.Rsp), - MetaManipulation.Type.GlobalEqp => !_globalEqp.Contains(m.GlobalEqp), - _ => false, - }; - } - - public bool Add(MetaManipulation m) - { - var added = m.ManipulationType switch - { - MetaManipulation.Type.Imc => _imc.Add(m.Imc), - MetaManipulation.Type.Eqdp => _eqdp.Add(m.Eqdp), - MetaManipulation.Type.Eqp => _eqp.Add(m.Eqp), - MetaManipulation.Type.Est => _est.Add(m.Est), - MetaManipulation.Type.Gmp => _gmp.Add(m.Gmp), - MetaManipulation.Type.Rsp => _rsp.Add(m.Rsp), - MetaManipulation.Type.GlobalEqp => _globalEqp.Add(m.GlobalEqp), - _ => false, - }; - Changes |= added; - return added; - } - - public bool Delete(MetaManipulation m) - { - var deleted = m.ManipulationType switch - { - MetaManipulation.Type.Imc => _imc.Remove(m.Imc), - MetaManipulation.Type.Eqdp => _eqdp.Remove(m.Eqdp), - MetaManipulation.Type.Eqp => _eqp.Remove(m.Eqp), - MetaManipulation.Type.Est => _est.Remove(m.Est), - MetaManipulation.Type.Gmp => _gmp.Remove(m.Gmp), - MetaManipulation.Type.Rsp => _rsp.Remove(m.Rsp), - MetaManipulation.Type.GlobalEqp => _globalEqp.Remove(m.GlobalEqp), - _ => false, - }; - Changes |= deleted; - return deleted; - } - - public bool Change(MetaManipulation m) - => Delete(m) && Add(m); - - public bool Set(MetaManipulation m) - => Delete(m) | Add(m); - - public void Clear() - { - _imc.Clear(); - _eqp.Clear(); - _eqdp.Clear(); - _gmp.Clear(); - _est.Clear(); - _rsp.Clear(); - _globalEqp.Clear(); + base.Clear(); Changes = true; } @@ -129,15 +47,19 @@ public class ModMetaEditor(ModManager modManager) if (option == currentOption) continue; - foreach (var manip in option.Manipulations) - { - var data = OtherData[manip.ManipulationType]; - ++data.TotalCount; - data.Add(option.GetFullName()); - } + var name = option.GetFullName(); + OtherData[MetaManipulation.Type.Imc].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Imc)); + OtherData[MetaManipulation.Type.Eqp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Eqp)); + OtherData[MetaManipulation.Type.Eqdp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Eqdp)); + OtherData[MetaManipulation.Type.Gmp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Gmp)); + OtherData[MetaManipulation.Type.Est].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Est)); + OtherData[MetaManipulation.Type.Rsp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Rsp)); + OtherData[MetaManipulation.Type.GlobalEqp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.GlobalEqp)); } - Split(currentOption.Manipulations); + Clear(); + UnionWith(currentOption.Manipulations); + Changes = false; } public void Apply(IModDataContainer container) @@ -145,50 +67,7 @@ public class ModMetaEditor(ModManager modManager) if (!Changes) return; - modManager.OptionEditor.SetManipulations(container, [..Recombine()]); + modManager.OptionEditor.SetManipulations(container, this); Changes = false; } - - private void Split(IEnumerable manips) - { - Clear(); - foreach (var manip in manips) - { - switch (manip.ManipulationType) - { - case MetaManipulation.Type.Imc: - _imc.Add(manip.Imc); - break; - case MetaManipulation.Type.Eqdp: - _eqdp.Add(manip.Eqdp); - break; - case MetaManipulation.Type.Eqp: - _eqp.Add(manip.Eqp); - break; - case MetaManipulation.Type.Est: - _est.Add(manip.Est); - break; - case MetaManipulation.Type.Gmp: - _gmp.Add(manip.Gmp); - break; - case MetaManipulation.Type.Rsp: - _rsp.Add(manip.Rsp); - break; - case MetaManipulation.Type.GlobalEqp: - _globalEqp.Add(manip.GlobalEqp); - break; - } - } - - Changes = false; - } - - public IEnumerable Recombine() - => _imc.Select(m => (MetaManipulation)m) - .Concat(_eqdp.Select(m => (MetaManipulation)m)) - .Concat(_eqp.Select(m => (MetaManipulation)m)) - .Concat(_est.Select(m => (MetaManipulation)m)) - .Concat(_gmp.Select(m => (MetaManipulation)m)) - .Concat(_rsp.Select(m => (MetaManipulation)m)) - .Concat(_globalEqp.Select(m => (MetaManipulation)m)); } diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 383bc9fd..c52828c0 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -95,28 +95,28 @@ public class ImcModGroup(Mod mod) : IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) => new ImcModGroupEditDrawer(editDrawer, this); - public ImcManipulation GetManip(ushort mask, Variant variant) - => new(Identifier.ObjectType, Identifier.BodySlot, Identifier.PrimaryId, Identifier.SecondaryId.Id, variant.Id, - Identifier.EquipSlot, DefaultEntry with { AttributeMask = mask }); + public ImcEntry GetEntry(ushort mask) + => DefaultEntry with { AttributeMask = mask }; public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) { if (IsDisabled(setting)) return; - var mask = GetCurrentMask(setting); + var mask = GetCurrentMask(setting); + var entry = GetEntry(mask); if (AllVariants) { var count = ImcChecker.GetVariantCount(Identifier); if (count == 0) - manipulations.Add(GetManip(mask, Identifier.Variant)); + manipulations.TryAdd(Identifier, entry); else for (var i = 0; i <= count; ++i) - manipulations.Add(GetManip(mask, (Variant)i)); + manipulations.TryAdd(Identifier with { Variant = (Variant)i }, entry); } else { - manipulations.Add(GetManip(mask, Identifier.Variant)); + manipulations.TryAdd(Identifier, entry); } } diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 72a6005d..8328edea 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -124,7 +124,7 @@ public class ItemSwapContainer private MetaDictionary MetaResolver(ModCollection? collection) => collection?.MetaCache?.Manipulations is { } cache - ? [.. cache] + ? [] // [.. cache] TODO : _appliedModData.Manipulations; public EquipItem[] LoadEquipment(EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 0035fd41..e8ca3199 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -198,7 +198,8 @@ public partial class ModCreator( Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - option.Manipulations.UnionWith([.. meta.MetaManipulations]); + // TODO + option.Manipulations.UnionWith([]);//[.. meta.MetaManipulations]); } else if (ext1 == ".rgsp" || ext2 == ".rgsp") { @@ -212,7 +213,8 @@ public partial class ModCreator( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - option.Manipulations.UnionWith([.. rgsp.MetaManipulations]); + // TODO + option.Manipulations.UnionWith([]);//[.. rgsp.MetaManipulations]); } } catch (Exception e) diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index 40fd2e75..a8c37369 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -37,7 +37,7 @@ public static class SubMod { to.Files = new Dictionary(from.Files); to.FileSwaps = new Dictionary(from.FileSwaps); - to.Manipulations = [.. from.Manipulations]; + to.Manipulations = from.Manipulations.Clone(); } /// Load all file redirections, file swaps and meta manipulations from a JToken of that option into a data container. diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 61ed4528..91c4c5df 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -93,7 +93,8 @@ public class TemporaryMod : IMod } } - MetaDictionary manips = [.. collection.MetaCache?.Manipulations ?? []]; + // TODO + MetaDictionary manips = []; // [.. collection.MetaCache?.Manipulations ?? []]; defaultMod.Manipulations.UnionWith(manips); saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 0c6648ba..35e36349 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -188,7 +188,6 @@ public static class StaticServiceManager .AddSingleton() .AddSingleton() .AddSingleton() - .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs new file mode 100644 index 00000000..d9a8c27c --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -0,0 +1,353 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + private bool _fileExists; + + private const string ModelSetIdTooltipShort = "Model Set ID"; + private const string EquipSlotTooltip = "Equip Slot"; + private const string ModelRaceTooltip = "Model Race"; + private const string GenderTooltip = "Gender"; + private const string ObjectTypeTooltip = "Object Type"; + private const string SecondaryIdTooltip = "Secondary ID"; + private const string PrimaryIdTooltipShort = "Primary ID"; + private const string VariantIdTooltip = "Variant ID"; + private const string EstTypeTooltip = "EST Type"; + private const string RacialTribeTooltip = "Racial Tribe"; + private const string ScalingTypeTooltip = "Scaling Type"; + + protected override void Initialize() + { + Identifier = ImcIdentifier.Default; + UpdateEntry(); + } + + private void UpdateEntry() + => (Entry, _fileExists, _) = MetaFiles.ImcChecker.GetDefaultEntry(Identifier, true); + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + // Copy To Clipboard + ImGui.TableNextColumn(); + var canAdd = _fileExists && Editor.MetaEditor.CanAdd(Identifier); + var tt = canAdd ? "Stage this edit."u8 : !_fileExists ? "This IMC file does not exist."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.MetaEditor.TryAdd(Identifier, Entry); + + if (DrawIdentifier(ref Identifier)) + UpdateEntry(); + + using var disabled = ImRaii.Disabled(); + DrawEntry(Entry, ref Entry, false); + } + + protected override void DrawEntry(ImcIdentifier identifier, ImcEntry entry) + { + const uint frameColor = 0; + // Meta Buttons + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.ObjectType.ToName(), frameColor); + ImUtf8.HoverTooltip("Object Type"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.PrimaryId.Id}", frameColor); + ImUtf8.HoverTooltip("Primary ID"); + + ImGui.TableNextColumn(); + if (identifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + { + ImUtf8.TextFramed(identifier.EquipSlot.ToName(), frameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + else + { + ImUtf8.TextFramed($"{identifier.SecondaryId.Id}", frameColor); + ImUtf8.HoverTooltip("Secondary ID"u8); + } + + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.Variant.Id}", frameColor); + ImUtf8.HoverTooltip("Variant"u8); + + ImGui.TableNextColumn(); + if (identifier.ObjectType is ObjectType.DemiHuman) + { + ImUtf8.TextFramed(identifier.EquipSlot.ToName(), frameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + + var defaultEntry = MetaFiles.ImcChecker.GetDefaultEntry(identifier, true).Entry; + if (DrawEntry(defaultEntry, ref entry, true)) + Editor.MetaEditor.Update(identifier, entry); + } + + private static bool DrawIdentifier(ref ImcIdentifier identifier) + { + ImGui.TableNextColumn(); + var change = DrawObjectType(ref identifier); + + ImGui.TableNextColumn(); + change |= DrawPrimaryId(ref identifier); + + ImGui.TableNextColumn(); + if (identifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + change |= DrawSlot(ref identifier); + else + change |= DrawSecondaryId(ref identifier); + + ImGui.TableNextColumn(); + change |= DrawVariant(ref identifier); + + ImGui.TableNextColumn(); + if (identifier.ObjectType is ObjectType.DemiHuman) + change |= DrawSlot(ref identifier, 70f); + else + ImUtf8.ScaledDummy(70f); + return change; + } + + private static bool DrawEntry(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault) + { + ImGui.TableNextColumn(); + var change = DrawMaterialId(defaultEntry, ref entry, addDefault); + ImUtf8.SameLineInner(); + change |= DrawMaterialAnimationId(defaultEntry, ref entry, addDefault); + + ImGui.TableNextColumn(); + change |= DrawDecalId(defaultEntry, ref entry, addDefault); + ImUtf8.SameLineInner(); + change |= DrawVfxId(defaultEntry, ref entry, addDefault); + ImUtf8.SameLineInner(); + change |= DrawSoundId(defaultEntry, ref entry, addDefault); + + ImGui.TableNextColumn(); + change |= DrawAttributes(defaultEntry, ref entry); + return change; + } + + + protected override IEnumerable<(ImcIdentifier, ImcEntry)> Enumerate() + => Editor.MetaEditor.Imc.Select(kvp => (kvp.Key, kvp.Value)); + + public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) + { + var ret = Combos.ImcType("##imcType", identifier.ObjectType, out var type, width); + ImUtf8.HoverTooltip("Object Type"u8); + + if (ret) + { + var equipSlot = type switch + { + ObjectType.Equipment => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, + ObjectType.DemiHuman => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, + ObjectType.Accessory => identifier.EquipSlot.IsAccessory() ? identifier.EquipSlot : EquipSlot.Ears, + _ => EquipSlot.Unknown, + }; + identifier = identifier with + { + ObjectType = type, + EquipSlot = equipSlot, + SecondaryId = identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId, + }; + } + + return ret; + } + + public static bool DrawPrimaryId(ref ImcIdentifier identifier, float unscaledWidth = 80) + { + var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, identifier.PrimaryId.Id, out var newId, 0, ushort.MaxValue, + identifier.PrimaryId.Id <= 1); + ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 + + "This should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + identifier = identifier with { PrimaryId = newId }; + return ret; + } + + public static bool DrawSecondaryId(ref ImcIdentifier identifier, float unscaledWidth = 100) + { + var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, identifier.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); + ImUtf8.HoverTooltip("Secondary ID"u8); + if (ret) + identifier = identifier with { SecondaryId = newId }; + return ret; + } + + public static bool DrawVariant(ref ImcIdentifier identifier, float unscaledWidth = 45) + { + var ret = IdInput("##imcVariant"u8, unscaledWidth, identifier.Variant.Id, out var newId, 0, byte.MaxValue, false); + ImUtf8.HoverTooltip("Variant ID"u8); + if (ret) + identifier = identifier with { Variant = (byte)newId }; + return ret; + } + + public static bool DrawSlot(ref ImcIdentifier identifier, float unscaledWidth = 100) + { + bool ret; + EquipSlot slot; + switch (identifier.ObjectType) + { + case ObjectType.Equipment: + case ObjectType.DemiHuman: + ret = Combos.EqpEquipSlot("##slot", identifier.EquipSlot, out slot, unscaledWidth); + break; + case ObjectType.Accessory: + ret = Combos.AccessorySlot("##slot", identifier.EquipSlot, out slot, unscaledWidth); + break; + default: return false; + } + + ImUtf8.HoverTooltip("Equip Slot"u8); + if (ret) + identifier = identifier with { EquipSlot = slot }; + return ret; + } + + public static bool DrawMaterialId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##materialId"u8, "Material ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.MaterialId, defaultEntry.MaterialId, + out var newValue, (byte)1, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { MaterialId = newValue }; + return true; + } + + public static bool DrawMaterialAnimationId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##mAnimId"u8, "Material Animation ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.MaterialAnimationId, + defaultEntry.MaterialAnimationId, out var newValue, (byte)0, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { MaterialAnimationId = newValue }; + return true; + } + + public static bool DrawDecalId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##decalId"u8, "Decal ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.DecalId, defaultEntry.DecalId, out var newValue, + (byte)0, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { DecalId = newValue }; + return true; + } + + public static bool DrawVfxId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##vfxId"u8, "VFX ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.VfxId, defaultEntry.VfxId, out var newValue, (byte)0, + byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { VfxId = newValue }; + return true; + } + + public static bool DrawSoundId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) + { + if (!DragInput("##soundId"u8, "Sound ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.SoundId, defaultEntry.SoundId, out var newValue, + (byte)0, byte.MaxValue, 0.01f, addDefault)) + return false; + + entry = entry with { SoundId = newValue }; + return true; + } + + public static bool DrawAttributes(ImcEntry defaultEntry, ref ImcEntry entry) + { + var changes = false; + for (var i = 0; i < ImcEntry.NumAttributes; ++i) + { + using var id = ImRaii.PushId(i); + var flag = 1 << i; + var value = (entry.AttributeMask & flag) != 0; + var def = (defaultEntry.AttributeMask & flag) != 0; + if (Checkmark("##attribute"u8, "ABCDEFGHIJ"u8.Slice(i, 1), value, def, out var newValue)) + { + var newMask = (ushort)(newValue ? entry.AttributeMask | flag : entry.AttributeMask & ~flag); + entry = entry with { AttributeMask = newMask }; + changes = true; + } + + if (i < ImcEntry.NumAttributes - 1) + ImUtf8.SameLineInner(); + } + + return changes; + } + + + /// + /// A number input for ids with an optional max id of given width. + /// Returns true if newId changed against currentId. + /// + private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, + bool border) + { + int tmp = currentId; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); + if (ImUtf8.InputScalar(label, ref tmp)) + tmp = Math.Clamp(tmp, minId, maxId); + + newId = (ushort)tmp; + return newId != currentId; + } + + /// + /// A dragging int input of given width that compares against a default value, shows a tooltip and clamps against min and max. + /// Returns true if newValue changed against currentValue. + /// + private static bool DragInput(ReadOnlySpan label, ReadOnlySpan tooltip, float width, T currentValue, T defaultValue, + out T newValue, T minValue, T maxValue, float speed, bool addDefault) where T : unmanaged, INumber + { + newValue = currentValue; + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue > currentValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + ImGui.SetNextItemWidth(width); + if (ImUtf8.DragScalar(label, ref newValue, minValue, maxValue, speed)) + newValue = newValue <= minValue ? minValue : newValue >= maxValue ? maxValue : newValue; + + if (addDefault) + ImUtf8.HoverTooltip($"{tooltip}\nDefault Value: {defaultValue}"); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + + return newValue != currentValue; + } + + /// + /// A checkmark that compares against a default value and shows a tooltip. + /// Returns true if newValue is changed against currentValue. + /// + private static bool Checkmark(ReadOnlySpan label, ReadOnlySpan tooltip, bool currentValue, bool defaultValue, + out bool newValue) + { + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + newValue = currentValue; + ImUtf8.Checkbox(label, ref newValue); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + return newValue != currentValue; + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index b0a74637..50862eec 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -1,10 +1,11 @@ +using System.Reflection.Emit; using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Text; +using OtterGui.Text.EndObjects; using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; @@ -20,17 +21,7 @@ public partial class ModEditWindow private const string ModelSetIdTooltip = "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."; - private const string ModelSetIdTooltipShort = "Model Set ID"; - private const string EquipSlotTooltip = "Equip Slot"; - private const string ModelRaceTooltip = "Model Race"; - private const string GenderTooltip = "Gender"; - private const string ObjectTypeTooltip = "Object Type"; - private const string SecondaryIdTooltip = "Secondary ID"; - private const string PrimaryIdTooltipShort = "Primary ID"; - private const string VariantIdTooltip = "Variant ID"; - private const string EstTypeTooltip = "EST Type"; - private const string RacialTribeTooltip = "Racial Tribe"; - private const string ScalingTypeTooltip = "Scaling Type"; + private void DrawMetaTab() { @@ -56,7 +47,7 @@ public partial class ModEditWindow ImGui.SameLine(); SetFromClipboardButton(); ImGui.SameLine(); - CopyToClipboardButton("Copy all current manipulations to clipboard.", _iconSize, _editor.MetaEditor.Recombine()); + CopyToClipboardButton("Copy all current manipulations to clipboard.", _iconSize, _editor.MetaEditor); ImGui.SameLine(); if (ImGui.Button("Write as TexTools Files")) _metaFileManager.WriteAllTexToolsMeta(Mod!); @@ -65,71 +56,103 @@ public partial class ModEditWindow if (!child) return; - DrawEditHeader(_editor.MetaEditor.Eqp, "Equipment Parameter Edits (EQP)###EQP", 5, EqpRow.Draw, EqpRow.DrawNew, - _editor.MetaEditor.OtherData[MetaManipulation.Type.Eqp]); - DrawEditHeader(_editor.MetaEditor.Eqdp, "Racial Model Edits (EQDP)###EQDP", 7, EqdpRow.Draw, EqdpRow.DrawNew, - _editor.MetaEditor.OtherData[MetaManipulation.Type.Eqdp]); - DrawEditHeader(_editor.MetaEditor.Imc, "Variant Edits (IMC)###IMC", 10, ImcRow.Draw, ImcRow.DrawNew, - _editor.MetaEditor.OtherData[MetaManipulation.Type.Imc]); - DrawEditHeader(_editor.MetaEditor.Est, "Extra Skeleton Parameters (EST)###EST", 7, EstRow.Draw, EstRow.DrawNew, - _editor.MetaEditor.OtherData[MetaManipulation.Type.Est]); - DrawEditHeader(_editor.MetaEditor.Gmp, "Visor/Gimmick Edits (GMP)###GMP", 7, GmpRow.Draw, GmpRow.DrawNew, - _editor.MetaEditor.OtherData[MetaManipulation.Type.Gmp]); - DrawEditHeader(_editor.MetaEditor.Rsp, "Racial Scaling Edits (RSP)###RSP", 5, RspRow.Draw, RspRow.DrawNew, - _editor.MetaEditor.OtherData[MetaManipulation.Type.Rsp]); - DrawEditHeader(_editor.MetaEditor.GlobalEqp, "Global Equipment Parameter Edits (Global EQP)###GEQP", 4, GlobalEqpRow.Draw, - GlobalEqpRow.DrawNew, _editor.MetaEditor.OtherData[MetaManipulation.Type.GlobalEqp]); + DrawEditHeader(MetaManipulation.Type.Eqp); + DrawEditHeader(MetaManipulation.Type.Eqdp); + DrawEditHeader(MetaManipulation.Type.Imc); + DrawEditHeader(MetaManipulation.Type.Est); + DrawEditHeader(MetaManipulation.Type.Gmp); + DrawEditHeader(MetaManipulation.Type.Rsp); + DrawEditHeader(MetaManipulation.Type.GlobalEqp); } - - /// The headers for the different meta changes all have basically the same structure for different types. - private void DrawEditHeader(IReadOnlyCollection items, string label, int numColumns, - Action draw, Action drawNew, - ModMetaEditor.OtherOptionData otherOptionData) - { - const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.BordersInnerV; - - var oldPos = ImGui.GetCursorPosY(); - var header = ImGui.CollapsingHeader($"{items.Count} {label}"); - var newPos = ImGui.GetCursorPos(); - if (otherOptionData.TotalCount > 0) + private static ReadOnlySpan Label(MetaManipulation.Type type) + => type switch { - var text = $"{otherOptionData.TotalCount} Edits in other Options"; - var size = ImGui.CalcTextSize(text).X; - ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionAvail().X - size, oldPos + ImGui.GetStyle().FramePadding.Y)); - ImGuiUtil.TextColored(ColorId.RedundantAssignment.Value() | 0xFF000000, text); - if (ImGui.IsItemHovered()) - { - using var tt = ImUtf8.Tooltip(); - foreach (var name in otherOptionData) - ImUtf8.Text(name); - } + MetaManipulation.Type.Imc => "Variant Edits (IMC)###IMC"u8, + MetaManipulation.Type.Eqdp => "Racial Model Edits (EQDP)###EQDP"u8, + MetaManipulation.Type.Eqp => "Equipment Parameter Edits (EQP)###EQP"u8, + MetaManipulation.Type.Est => "Extra Skeleton Parameters (EST)###EST"u8, + MetaManipulation.Type.Gmp => "Visor/Gimmick Edits (GMP)###GMP"u8, + MetaManipulation.Type.Rsp => "Racial Scaling Edits (RSP)###RSP"u8, + MetaManipulation.Type.GlobalEqp => "Global Equipment Parameter Edits (Global EQP)###GEQP"u8, + _ => "\0"u8, + }; - ImGui.SetCursorPos(newPos); - } + private static int ColumnCount(MetaManipulation.Type type) + => type switch + { + MetaManipulation.Type.Imc => 10, + MetaManipulation.Type.Eqdp => 7, + MetaManipulation.Type.Eqp => 5, + MetaManipulation.Type.Est => 7, + MetaManipulation.Type.Gmp => 7, + MetaManipulation.Type.Rsp => 5, + MetaManipulation.Type.GlobalEqp => 4, + _ => 0, + }; + private void DrawEditHeader(MetaManipulation.Type type) + { + var oldPos = ImGui.GetCursorPosY(); + var header = ImUtf8.CollapsingHeader($"{_editor.MetaEditor.GetCount(type)} {Label(type)}"); + DrawOtherOptionData(type, oldPos, ImGui.GetCursorPos()); if (!header) return; - using (var table = ImRaii.Table(label, numColumns, flags)) - { - if (table) - { - drawNew(_metaFileManager, _editor, _iconSize); - foreach (var (item, index) in items.ToArray().WithIndex()) - { - using var id = ImRaii.PushId(index); - draw(_metaFileManager, item, _editor, _iconSize); - } - } - } + DrawTable(type); + } + private IMetaDrawer? Drawer(MetaManipulation.Type type) + => type switch + { + //MetaManipulation.Type.Imc => expr, + //MetaManipulation.Type.Eqdp => expr, + //MetaManipulation.Type.Eqp => expr, + //MetaManipulation.Type.Est => expr, + //MetaManipulation.Type.Gmp => expr, + //MetaManipulation.Type.Rsp => expr, + //MetaManipulation.Type.GlobalEqp => expr, + _ => null, + }; + + private void DrawTable(MetaManipulation.Type type) + { + const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.BordersInnerV; + using var table = ImUtf8.Table(Label(type), ColumnCount(type), flags); + if (!table) + return; + + if (Drawer(type) is not { } drawer) + return; + + drawer.Draw(); ImGui.NewLine(); } + private void DrawOtherOptionData(MetaManipulation.Type type, float oldPos, Vector2 newPos) + { + var otherOptionData = _editor.MetaEditor.OtherData[type]; + if (otherOptionData.TotalCount <= 0) + return; + + var text = $"{otherOptionData.TotalCount} Edits in other Options"; + var size = ImGui.CalcTextSize(text).X; + ImGui.SetCursorPos(new Vector2(ImGui.GetContentRegionAvail().X - size, oldPos + ImGui.GetStyle().FramePadding.Y)); + ImGuiUtil.TextColored(ColorId.RedundantAssignment.Value() | 0xFF000000, text); + if (ImGui.IsItemHovered()) + { + using var tt = ImUtf8.Tooltip(); + foreach (var name in otherOptionData) + ImUtf8.Text(name); + } + + ImGui.SetCursorPos(newPos); + } + +#if false private static class EqpRow { - private static EqpManipulation _new = new(Eqp.DefaultEntry, EquipSlot.Head, 1); + private static EqpIdentifier _newIdentifier = new(1, EquipSlot.Body); private static float IdWidth => 100 * UiHelpers.Scale; @@ -140,8 +163,8 @@ public partial class ModEditWindow CopyToClipboardButton("Copy all current EQP manipulations to clipboard.", iconSize, editor.MetaEditor.Eqp.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; + var canAdd = editor.MetaEditor.CanAdd(_new); + var tt = canAdd ? "Stage this edit." : "This entry is already edited."; var defaultEntry = ExpandedEqpFile.GetDefault(metaFileManager, _new.SetId); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) editor.MetaEditor.Add(_new.Copy(defaultEntry)); @@ -197,7 +220,7 @@ public partial class ModEditWindow var idx = 0; foreach (var flag in Eqp.EqpAttributes[meta.Slot]) { - using var id = ImRaii.PushId(idx++); + using var id = ImRaii.PushId(idx++); var defaultValue = defaultEntry.HasFlag(flag); var currentValue = meta.Entry.HasFlag(flag); if (Checkmark("##eqp", flag.ToLocalName(), currentValue, defaultValue, out var value)) @@ -209,8 +232,6 @@ public partial class ModEditWindow ImGui.NewLine(); } } - - private static class EqdpRow { private static EqdpManipulation _new = new(EqdpEntry.Invalid, EquipSlot.Head, Gender.Male, ModelRace.Midlander, 1); @@ -224,9 +245,9 @@ public partial class ModEditWindow CopyToClipboardButton("Copy all current EQDP manipulations to clipboard.", iconSize, editor.MetaEditor.Eqdp.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); - var raceCode = Names.CombinedRace(_new.Gender, _new.Race); + var raceCode = Names.CombinedRace(_new.Gender, _new.Race); var validRaceCode = CharacterUtilityData.EqdpIdx(raceCode, false) >= 0; - var canAdd = validRaceCode && editor.MetaEditor.CanAdd(_new); + var canAdd = validRaceCode && editor.MetaEditor.CanAdd(_new); var tt = canAdd ? "Stage this edit." : validRaceCode ? "This entry is already edited." : "This combination of race and gender can not be used."; var defaultEntry = validRaceCode @@ -311,7 +332,7 @@ public partial class ModEditWindow var defaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(meta.Gender, meta.Race), meta.Slot.IsAccessory(), meta.SetId); var (defaultBit1, defaultBit2) = defaultEntry.ToBits(meta.Slot); - var (bit1, bit2) = meta.Entry.ToBits(meta.Slot); + var (bit1, bit2) = meta.Entry.ToBits(meta.Slot); ImGui.TableNextColumn(); if (Checkmark("Material##eqdpCheck1", string.Empty, bit1, defaultBit1, out var newBit1)) editor.MetaEditor.Change(meta.Copy(Eqdp.FromSlotAndBits(meta.Slot, newBit1, bit2))); @@ -321,136 +342,7 @@ public partial class ModEditWindow editor.MetaEditor.Change(meta.Copy(Eqdp.FromSlotAndBits(meta.Slot, bit1, newBit2))); } } - - private static class ImcRow - { - private static ImcIdentifier _newIdentifier = ImcIdentifier.Default; - - private static float IdWidth - => 80 * UiHelpers.Scale; - - private static float SmallIdWidth - => 45 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current IMC manipulations to clipboard.", iconSize, - editor.MetaEditor.Imc.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var (defaultEntry, fileExists, _) = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true); - var manip = (MetaManipulation)new ImcManipulation(_newIdentifier, defaultEntry); - var canAdd = fileExists && editor.MetaEditor.CanAdd(manip); - var tt = canAdd ? "Stage this edit." : !fileExists ? "This IMC file does not exist." : "This entry is already edited."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(manip); - - // Identifier - ImGui.TableNextColumn(); - var change = ImcManipulationDrawer.DrawObjectType(ref _newIdentifier); - - ImGui.TableNextColumn(); - change |= ImcManipulationDrawer.DrawPrimaryId(ref _newIdentifier); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); - - ImGui.TableNextColumn(); - // Equipment and accessories are slightly different imcs than other types. - if (_newIdentifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier); - else - change |= ImcManipulationDrawer.DrawSecondaryId(ref _newIdentifier); - - ImGui.TableNextColumn(); - change |= ImcManipulationDrawer.DrawVariant(ref _newIdentifier); - - ImGui.TableNextColumn(); - if (_newIdentifier.ObjectType is ObjectType.DemiHuman) - change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier, 70); - else - ImGui.Dummy(new Vector2(70 * UiHelpers.Scale, 0)); - - if (change) - defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true).Entry; - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref defaultEntry, false); - ImGui.SameLine(); - ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref defaultEntry, false); - ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawDecalId(defaultEntry, ref defaultEntry, false); - ImGui.SameLine(); - ImcManipulationDrawer.DrawVfxId(defaultEntry, ref defaultEntry, false); - ImGui.SameLine(); - ImcManipulationDrawer.DrawSoundId(defaultEntry, ref defaultEntry, false); - ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawAttributes(defaultEntry, ref defaultEntry); - } - - public static void Draw(MetaFileManager metaFileManager, ImcManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.ObjectType.ToName()); - ImGuiUtil.HoverTooltip(ObjectTypeTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.PrimaryId.ToString()); - ImGuiUtil.HoverTooltip(PrimaryIdTooltipShort); - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - if (meta.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - { - ImGui.TextUnformatted(meta.EquipSlot.ToName()); - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } - else - { - ImGui.TextUnformatted(meta.SecondaryId.ToString()); - ImGuiUtil.HoverTooltip(SecondaryIdTooltip); - } - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Variant.ToString()); - ImGuiUtil.HoverTooltip(VariantIdTooltip); - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - if (meta.ObjectType is ObjectType.DemiHuman) - { - ImGui.TextUnformatted(meta.EquipSlot.ToName()); - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } - - // Values - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); - ImGui.TableNextColumn(); - var defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(meta.Identifier, true).Entry; - var newEntry = meta.Entry; - var changes = ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref newEntry, true); - ImGui.SameLine(); - changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref newEntry, true); - ImGui.TableNextColumn(); - changes |= ImcManipulationDrawer.DrawDecalId(defaultEntry, ref newEntry, true); - ImGui.SameLine(); - changes |= ImcManipulationDrawer.DrawVfxId(defaultEntry, ref newEntry, true); - ImGui.SameLine(); - changes |= ImcManipulationDrawer.DrawSoundId(defaultEntry, ref newEntry, true); - ImGui.TableNextColumn(); - changes |= ImcManipulationDrawer.DrawAttributes(defaultEntry, ref newEntry); - - if (changes) - editor.MetaEditor.Change(meta.Copy(newEntry)); - } - } - + private static class EstRow { private static EstManipulation _new = new(Gender.Male, ModelRace.Midlander, EstType.Body, 1, EstEntry.Zero); @@ -464,8 +356,8 @@ public partial class ModEditWindow CopyToClipboardButton("Copy all current EST manipulations to clipboard.", iconSize, editor.MetaEditor.Est.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; + var canAdd = editor.MetaEditor.CanAdd(_new); + var tt = canAdd ? "Stage this edit." : "This entry is already edited."; var defaultEntry = EstFile.GetDefault(metaFileManager, _new.Slot, Names.CombinedRace(_new.Gender, _new.Race), _new.SetId); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) editor.MetaEditor.Add(_new.Copy(defaultEntry)); @@ -538,12 +430,11 @@ public partial class ModEditWindow // Values var defaultEntry = EstFile.GetDefault(metaFileManager, meta.Slot, Names.CombinedRace(meta.Gender, meta.Race), meta.SetId); ImGui.TableNextColumn(); - if (IntDragInput("##estSkeleton", $"Skeleton Index\nDefault Value: {defaultEntry}", IdWidth, meta.Entry.Value, defaultEntry.Value, + if (IntDragInput("##estSkeleton", $"Skeleton Index\nDefault Value: {defaultEntry}", IdWidth, meta.Entry.Value, defaultEntry.Value, out var entry, 0, ushort.MaxValue, 0.05f)) editor.MetaEditor.Change(meta.Copy(new EstEntry((ushort)entry))); } } - private static class GmpRow { private static GmpManipulation _new = new(GmpEntry.Default, 1); @@ -563,8 +454,8 @@ public partial class ModEditWindow CopyToClipboardButton("Copy all current GMP manipulations to clipboard.", iconSize, editor.MetaEditor.Gmp.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; + var canAdd = editor.MetaEditor.CanAdd(_new); + var tt = canAdd ? "Stage this edit." : "This entry is already edited."; var defaultEntry = ExpandedGmpFile.GetDefault(metaFileManager, _new.SetId); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) editor.MetaEditor.Add(_new.Copy(defaultEntry)); @@ -643,7 +534,6 @@ public partial class ModEditWindow editor.MetaEditor.Change(meta.Copy(meta.Entry with { UnknownB = (byte)unkB })); } } - private static class RspRow { private static RspManipulation _new = new(SubRace.Midlander, RspAttribute.MaleMinSize, RspEntry.One); @@ -657,8 +547,8 @@ public partial class ModEditWindow CopyToClipboardButton("Copy all current RSP manipulations to clipboard.", iconSize, editor.MetaEditor.Rsp.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; + var canAdd = editor.MetaEditor.CanAdd(_new); + var tt = canAdd ? "Stage this edit." : "This entry is already edited."; var defaultEntry = CmpFile.GetDefault(metaFileManager, _new.SubRace, _new.Attribute); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) editor.MetaEditor.Add(_new.Copy(defaultEntry)); @@ -700,7 +590,7 @@ public partial class ModEditWindow ImGui.TableNextColumn(); // Values - var def = CmpFile.GetDefault(metaFileManager, meta.SubRace, meta.Attribute).Value; + var def = CmpFile.GetDefault(metaFileManager, meta.SubRace, meta.Attribute).Value; var value = meta.Entry.Value; ImGui.SetNextItemWidth(FloatWidth); using var color = ImRaii.PushColor(ImGuiCol.FrameBg, @@ -713,12 +603,11 @@ public partial class ModEditWindow ImGuiUtil.HoverTooltip($"Default Value: {def:0.###}"); } } - private static class GlobalEqpRow { private static GlobalEqpManipulation _new = new() { - Type = GlobalEqpType.DoNotHideEarrings, + Type = GlobalEqpType.DoNotHideEarrings, Condition = 1, }; @@ -729,7 +618,7 @@ public partial class ModEditWindow editor.MetaEditor.GlobalEqp.Select(m => (MetaManipulation)m)); ImGui.TableNextColumn(); var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already manipulated."; + var tt = canAdd ? "Stage this edit." : "This entry is already manipulated."; if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) editor.MetaEditor.Add(_new); @@ -744,7 +633,7 @@ public partial class ModEditWindow if (ImUtf8.Selectable(type.ToName(), type == _new.Type)) _new = new GlobalEqpManipulation { - Type = type, + Type = type, Condition = type.HasCondition() ? _new.Type.HasCondition() ? _new.Condition : 1 : 0, }; ImUtf8.HoverTooltip(type.ToDescription()); @@ -777,6 +666,7 @@ public partial class ModEditWindow } } } +#endif // A number input for ids with a optional max id of given width. // Returns true if newId changed against currentId. @@ -824,7 +714,7 @@ public partial class ModEditWindow return newValue != currentValue; } - private static void CopyToClipboardButton(string tooltip, Vector2 iconSize, IEnumerable manipulations) + private static void CopyToClipboardButton(string tooltip, Vector2 iconSize, MetaDictionary manipulations) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), iconSize, tooltip, false, true)) return; @@ -840,10 +730,9 @@ public partial class ModEditWindow { var clipboard = ImGuiUtil.GetClipboardText(); - var version = Functions.FromCompressedBase64(clipboard, out var manips); + var version = Functions.FromCompressedBase64(clipboard, out var manips); if (version == MetaManipulation.CurrentVersion && manips != null) - foreach (var manip in manips.Where(m => m.ManipulationType != MetaManipulation.Type.Unknown)) - _editor.MetaEditor.Set(manip); + _editor.MetaEditor.UpdateTo(manips); } ImGuiUtil.HoverTooltip( @@ -855,13 +744,9 @@ public partial class ModEditWindow if (ImGui.Button("Set from Clipboard")) { var clipboard = ImGuiUtil.GetClipboardText(); - var version = Functions.FromCompressedBase64(clipboard, out var manips); + var version = Functions.FromCompressedBase64(clipboard, out var manips); if (version == MetaManipulation.CurrentVersion && manips != null) - { - _editor.MetaEditor.Clear(); - foreach (var manip in manips.Where(m => m.ManipulationType != MetaManipulation.Type.Unknown)) - _editor.MetaEditor.Set(manip); - } + _editor.MetaEditor.SetTo(manips); } ImGuiUtil.HoverTooltip( @@ -870,11 +755,184 @@ public partial class ModEditWindow private static void DrawMetaButtons(MetaManipulation meta, ModEditor editor, Vector2 iconSize) { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy this manipulation to clipboard.", iconSize, Array.Empty().Append(meta)); - - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), iconSize, "Delete this meta manipulation.", false, true)) - editor.MetaEditor.Delete(meta); + //ImGui.TableNextColumn(); + //CopyToClipboardButton("Copy this manipulation to clipboard.", iconSize, Array.Empty().Append(meta)); + // + //ImGui.TableNextColumn(); + //if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), iconSize, "Delete this meta manipulation.", false, true)) + // editor.MetaEditor.Delete(meta); } +} + + +public interface IMetaDrawer +{ + public void Draw(); } + + + + +public abstract class MetaDrawer(ModEditor editor, MetaFileManager metaFiles) : IMetaDrawer + where TIdentifier : unmanaged, IMetaIdentifier + where TEntry : unmanaged +{ + protected readonly ModEditor Editor = editor; + protected readonly MetaFileManager MetaFiles = metaFiles; + protected TIdentifier Identifier; + protected TEntry Entry; + private bool _initialized; + + public void Draw() + { + if (!_initialized) + { + Initialize(); + _initialized = true; + } + + DrawNew(); + foreach (var ((identifier, entry), idx) in Enumerate().WithIndex()) + { + using var id = ImUtf8.PushId(idx); + DrawEntry(identifier, entry); + } + } + + protected abstract void DrawNew(); + protected abstract void Initialize(); + protected abstract void DrawEntry(TIdentifier identifier, TEntry entry); + + protected abstract IEnumerable<(TIdentifier, TEntry)> Enumerate(); +} + + +#if false +public sealed class GmpMetaDrawer(ModEditor editor) : MetaDrawer, IService +{ + protected override void Initialize() + { + Identifier = new GmpIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); + + protected override void DrawNew() + { } + + protected override void DrawEntry(GmpIdentifier identifier, GmpEntry entry) + { } + + protected override IEnumerable<(GmpIdentifier, GmpEntry)> Enumerate() + => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); +} + +public sealed class EstMetaDrawer(ModEditor editor) : MetaDrawer, IService +{ + protected override void Initialize() + { + Identifier = new EqpIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); + + protected override void DrawNew() + { } + + protected override void DrawEntry(EstIdentifier identifier, EstEntry entry) + { } + + protected override IEnumerable<(EstIdentifier, EstEntry)> Enumerate() + => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); +} + +public sealed class EqdpMetaDrawer(ModEditor editor) : MetaDrawer, IService +{ + protected override void Initialize() + { + Identifier = new EqdpIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); + + protected override void DrawNew() + { } + + protected override void DrawEntry(EqdpIdentifier identifier, EqdpEntry entry) + { } + + protected override IEnumerable<(EqdpIdentifier, EqdpEntry)> Enumerate() + => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); +} + +public sealed class EqpMetaDrawer(ModEditor editor, MetaFileManager metaManager) : MetaDrawer, IService +{ + protected override void Initialize() + { + Identifier = new EqpIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); + + protected override void DrawNew() + { } + + protected override void DrawEntry(EqpIdentifier identifier, EqpEntry entry) + { } + + protected override IEnumerable<(EqpIdentifier, EqpEntry)> Enumerate() + => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); +} + +public sealed class RspMetaDrawer(ModEditor editor) : MetaDrawer, IService +{ + protected override void Initialize() + { + Identifier = new RspIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); + + protected override void DrawNew() + { } + + protected override void DrawEntry(RspIdentifier identifier, RspEntry entry) + { } + + protected override IEnumerable<(RspIdentifier, RspEntry)> Enumerate() + => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); +} + + + +public sealed class GlobalEqpMetaDrawer(ModEditor editor) : MetaDrawer, IService +{ + protected override void Initialize() + { + Identifier = new EqpIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); + + protected override void DrawNew() + { } + + protected override void DrawEntry(GlobalEqpManipulation identifier, byte _) + { } + + protected override IEnumerable<(GlobalEqpManipulation, byte)> Enumerate() + => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); +} +#endif diff --git a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index 3ac10cd0..689571f3 100644 --- a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -9,6 +9,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Mods.Manager.OptionEditor; +using Penumbra.UI.AdvancedWindow.Meta; using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab.Groups; @@ -79,29 +80,29 @@ public class AddGroupDrawer : IUiService private void DrawImcInput(float width) { - var change = ImcManipulationDrawer.DrawObjectType(ref _imcIdentifier, width); + var change = ImcMetaDrawer.DrawObjectType(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawPrimaryId(ref _imcIdentifier, width); + change |= ImcMetaDrawer.DrawPrimaryId(ref _imcIdentifier, width); if (_imcIdentifier.ObjectType is ObjectType.Weapon or ObjectType.Monster) { - change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcIdentifier, width); + change |= ImcMetaDrawer.DrawSecondaryId(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawVariant(ref _imcIdentifier, width); + change |= ImcMetaDrawer.DrawVariant(ref _imcIdentifier, width); } else if (_imcIdentifier.ObjectType is ObjectType.DemiHuman) { var quarterWidth = (width - ImUtf8.ItemInnerSpacing.X / ImUtf8.GlobalScale) / 2; - change |= ImcManipulationDrawer.DrawSecondaryId(ref _imcIdentifier, width); + change |= ImcMetaDrawer.DrawSecondaryId(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawSlot(ref _imcIdentifier, quarterWidth); + change |= ImcMetaDrawer.DrawSlot(ref _imcIdentifier, quarterWidth); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawVariant(ref _imcIdentifier, quarterWidth); + change |= ImcMetaDrawer.DrawVariant(ref _imcIdentifier, quarterWidth); } else { - change |= ImcManipulationDrawer.DrawSlot(ref _imcIdentifier, width); + change |= ImcMetaDrawer.DrawSlot(ref _imcIdentifier, width); ImUtf8.SameLineInner(); - change |= ImcManipulationDrawer.DrawVariant(ref _imcIdentifier, width); + change |= ImcMetaDrawer.DrawVariant(ref _imcIdentifier, width); } if (change) diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 5c8edce6..5d10febd 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -7,6 +7,7 @@ using Penumbra.GameData.Structs; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; +using Penumbra.UI.AdvancedWindow.Meta; namespace Penumbra.UI.ModsTab.Groups; @@ -37,9 +38,9 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr ImGui.SameLine(); using (ImUtf8.Group()) { - changes |= ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref entry, true); - changes |= ImcManipulationDrawer.DrawVfxId(defaultEntry, ref entry, true); - changes |= ImcManipulationDrawer.DrawDecalId(defaultEntry, ref entry, true); + changes |= ImcMetaDrawer.DrawMaterialId(defaultEntry, ref entry, true); + changes |= ImcMetaDrawer.DrawVfxId(defaultEntry, ref entry, true); + changes |= ImcMetaDrawer.DrawDecalId(defaultEntry, ref entry, true); } ImGui.SameLine(0, editor.PriorityWidth); @@ -54,8 +55,8 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr using (ImUtf8.Group()) { - changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref entry, true); - changes |= ImcManipulationDrawer.DrawSoundId(defaultEntry, ref entry, true); + changes |= ImcMetaDrawer.DrawMaterialAnimationId(defaultEntry, ref entry, true); + changes |= ImcMetaDrawer.DrawSoundId(defaultEntry, ref entry, true); var canBeDisabled = group.CanBeDisabled; if (ImUtf8.Checkbox("##disabled"u8, ref canBeDisabled)) editor.ModManager.OptionEditor.ImcEditor.ChangeCanBeDisabled(group, canBeDisabled); diff --git a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs index 694ae11c..1291f568 100644 --- a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs +++ b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs @@ -10,210 +10,5 @@ namespace Penumbra.UI.ModsTab; public static class ImcManipulationDrawer { - public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) - { - var ret = Combos.ImcType("##imcType", identifier.ObjectType, out var type, width); - ImUtf8.HoverTooltip("Object Type"u8); - - if (ret) - { - var equipSlot = type switch - { - ObjectType.Equipment => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, - ObjectType.DemiHuman => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, - ObjectType.Accessory => identifier.EquipSlot.IsAccessory() ? identifier.EquipSlot : EquipSlot.Ears, - _ => EquipSlot.Unknown, - }; - identifier = identifier with - { - ObjectType = type, - EquipSlot = equipSlot, - SecondaryId = identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId, - }; - } - - return ret; - } - - public static bool DrawPrimaryId(ref ImcIdentifier identifier, float unscaledWidth = 80) - { - var ret = IdInput("##imcPrimaryId"u8, unscaledWidth, identifier.PrimaryId.Id, out var newId, 0, ushort.MaxValue, - identifier.PrimaryId.Id <= 1); - ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'x####' part of an item path.\n"u8 - + "This should generally not be left <= 1 unless you explicitly want that."u8); - if (ret) - identifier = identifier with { PrimaryId = newId }; - return ret; - } - - public static bool DrawSecondaryId(ref ImcIdentifier identifier, float unscaledWidth = 100) - { - var ret = IdInput("##imcSecondaryId"u8, unscaledWidth, identifier.SecondaryId.Id, out var newId, 0, ushort.MaxValue, false); - ImUtf8.HoverTooltip("Secondary ID"u8); - if (ret) - identifier = identifier with { SecondaryId = newId }; - return ret; - } - - public static bool DrawVariant(ref ImcIdentifier identifier, float unscaledWidth = 45) - { - var ret = IdInput("##imcVariant"u8, unscaledWidth, identifier.Variant.Id, out var newId, 0, byte.MaxValue, false); - ImUtf8.HoverTooltip("Variant ID"u8); - if (ret) - identifier = identifier with { Variant = (byte)newId }; - return ret; - } - - public static bool DrawSlot(ref ImcIdentifier identifier, float unscaledWidth = 100) - { - bool ret; - EquipSlot slot; - switch (identifier.ObjectType) - { - case ObjectType.Equipment: - case ObjectType.DemiHuman: - ret = Combos.EqpEquipSlot("##slot", identifier.EquipSlot, out slot, unscaledWidth); - break; - case ObjectType.Accessory: - ret = Combos.AccessorySlot("##slot", identifier.EquipSlot, out slot, unscaledWidth); - break; - default: return false; - } - - ImUtf8.HoverTooltip("Equip Slot"u8); - if (ret) - identifier = identifier with { EquipSlot = slot }; - return ret; - } - - public static bool DrawMaterialId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) - { - if (!DragInput("##materialId"u8, "Material ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.MaterialId, defaultEntry.MaterialId, - out var newValue, (byte)1, byte.MaxValue, 0.01f, addDefault)) - return false; - - entry = entry with { MaterialId = newValue }; - return true; - } - - public static bool DrawMaterialAnimationId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) - { - if (!DragInput("##mAnimId"u8, "Material Animation ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.MaterialAnimationId, - defaultEntry.MaterialAnimationId, out var newValue, (byte)0, byte.MaxValue, 0.01f, addDefault)) - return false; - - entry = entry with { MaterialAnimationId = newValue }; - return true; - } - - public static bool DrawDecalId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) - { - if (!DragInput("##decalId"u8, "Decal ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.DecalId, defaultEntry.DecalId, out var newValue, - (byte)0, byte.MaxValue, 0.01f, addDefault)) - return false; - - entry = entry with { DecalId = newValue }; - return true; - } - - public static bool DrawVfxId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) - { - if (!DragInput("##vfxId"u8, "VFX ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.VfxId, defaultEntry.VfxId, out var newValue, (byte)0, - byte.MaxValue, 0.01f, addDefault)) - return false; - - entry = entry with { VfxId = newValue }; - return true; - } - - public static bool DrawSoundId(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault, float unscaledWidth = 45) - { - if (!DragInput("##soundId"u8, "Sound ID"u8, unscaledWidth * ImUtf8.GlobalScale, entry.SoundId, defaultEntry.SoundId, out var newValue, - (byte)0, byte.MaxValue, 0.01f, addDefault)) - return false; - - entry = entry with { SoundId = newValue }; - return true; - } - - public static bool DrawAttributes(ImcEntry defaultEntry, ref ImcEntry entry) - { - var changes = false; - for (var i = 0; i < ImcEntry.NumAttributes; ++i) - { - using var id = ImRaii.PushId(i); - var flag = 1 << i; - var value = (entry.AttributeMask & flag) != 0; - var def = (defaultEntry.AttributeMask & flag) != 0; - if (Checkmark("##attribute"u8, "ABCDEFGHIJ"u8.Slice(i, 1), value, def, out var newValue)) - { - var newMask = (ushort)(newValue ? entry.AttributeMask | flag : entry.AttributeMask & ~flag); - entry = entry with { AttributeMask = newMask }; - changes = true; - } - - if (i < ImcEntry.NumAttributes - 1) - ImGui.SameLine(); - } - - return changes; - } - - - /// - /// A number input for ids with an optional max id of given width. - /// Returns true if newId changed against currentId. - /// - private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, - bool border) - { - int tmp = currentId; - ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); - if (ImUtf8.InputScalar(label, ref tmp)) - tmp = Math.Clamp(tmp, minId, maxId); - - newId = (ushort)tmp; - return newId != currentId; - } - - /// - /// A dragging int input of given width that compares against a default value, shows a tooltip and clamps against min and max. - /// Returns true if newValue changed against currentValue. - /// - private static bool DragInput(ReadOnlySpan label, ReadOnlySpan tooltip, float width, T currentValue, T defaultValue, - out T newValue, T minValue, T maxValue, float speed, bool addDefault) where T : unmanaged, INumber - { - newValue = currentValue; - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - defaultValue > currentValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), - defaultValue != currentValue); - ImGui.SetNextItemWidth(width); - if (ImUtf8.DragScalar(label, ref newValue, minValue, maxValue, speed)) - newValue = newValue <= minValue ? minValue : newValue >= maxValue ? maxValue : newValue; - - if (addDefault) - ImUtf8.HoverTooltip($"{tooltip}\nDefault Value: {defaultValue}"); - else - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); - - return newValue != currentValue; - } - - /// - /// A checkmark that compares against a default value and shows a tooltip. - /// Returns true if newValue is changed against currentValue. - /// - private static bool Checkmark(ReadOnlySpan label, ReadOnlySpan tooltip, bool currentValue, bool defaultValue, - out bool newValue) - { - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), - defaultValue != currentValue); - newValue = currentValue; - ImUtf8.Checkbox(label, ref newValue); - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); - return newValue != currentValue; - } + } diff --git a/Penumbra/Util/DictionaryExtensions.cs b/Penumbra/Util/DictionaryExtensions.cs index abf715e6..f7aa5598 100644 --- a/Penumbra/Util/DictionaryExtensions.cs +++ b/Penumbra/Util/DictionaryExtensions.cs @@ -45,6 +45,18 @@ public static class DictionaryExtensions lhs.Add(key, value); } + /// Set all entries in the right-hand dictionary to the same values in the left-hand dictionary, ensuring capacity beforehand. + public static void UpdateTo(this Dictionary lhs, IReadOnlyDictionary rhs) + where TKey : notnull + { + if (ReferenceEquals(lhs, rhs)) + return; + + lhs.EnsureCapacity(rhs.Count); + foreach (var (key, value) in rhs) + lhs[key] = value; + } + /// Set one set to the other, deleting previous entries and ensuring capacity beforehand. public static void SetTo(this HashSet lhs, IReadOnlySet rhs) { From 3170edfeb659f0362d46f56fde9c000ee54ba0ee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Jun 2024 13:38:36 +0200 Subject: [PATCH 0686/1381] Get rid off all MetaManipulation things. --- Penumbra/Api/Api/MetaApi.cs | 28 +- Penumbra/Api/Api/TemporaryApi.cs | 4 +- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 8 +- Penumbra/Collections/Cache/CmpCache.cs | 56 -- Penumbra/Collections/Cache/CollectionCache.cs | 40 +- .../Collections/Cache/CollectionModData.cs | 12 +- Penumbra/Collections/Cache/EqdpCache.cs | 85 +- Penumbra/Collections/Cache/EqpCache.cs | 77 +- Penumbra/Collections/Cache/EstCache.cs | 136 ++- .../Cache}/GlobalEqpCache.cs | 44 +- Penumbra/Collections/Cache/GmpCache.cs | 74 +- Penumbra/Collections/Cache/IMetaCache.cs | 89 ++ Penumbra/Collections/Cache/ImcCache.cs | 153 ++-- Penumbra/Collections/Cache/MetaCache.cs | 269 +++--- Penumbra/Collections/Cache/RspCache.cs | 81 ++ Penumbra/Import/Models/ModelManager.cs | 23 +- .../Import/TexToolsMeta.Deserialization.cs | 61 +- Penumbra/Import/TexToolsMeta.Export.cs | 328 ++++--- Penumbra/Import/TexToolsMeta.Rgsp.cs | 17 +- Penumbra/Import/TexToolsMeta.cs | 25 +- .../PathResolving/CollectionResolver.cs | 1 - .../ResolveContext.PathResolution.cs | 2 +- Penumbra/Meta/ImcChecker.cs | 4 - Penumbra/Meta/Manipulations/Eqdp.cs | 9 + .../Meta/Manipulations/EqdpManipulation.cs | 110 --- Penumbra/Meta/Manipulations/Eqp.cs | 3 + .../Meta/Manipulations/EqpManipulation.cs | 80 -- Penumbra/Meta/Manipulations/Est.cs | 16 + .../Meta/Manipulations/EstManipulation.cs | 108 --- .../Manipulations/GlobalEqpManipulation.cs | 26 +- Penumbra/Meta/Manipulations/Gmp.cs | 3 + .../Meta/Manipulations/GmpManipulation.cs | 58 -- .../Meta/Manipulations/IMetaIdentifier.cs | 16 + Penumbra/Meta/Manipulations/Imc.cs | 6 +- .../Meta/Manipulations/ImcManipulation.cs | 108 --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 338 +++++-- .../Meta/Manipulations/MetaManipulation.cs | 457 ---------- Penumbra/Meta/Manipulations/Rsp.cs | 3 + .../Meta/Manipulations/RspManipulation.cs | 67 -- Penumbra/Mods/Editor/IMod.cs | 2 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 24 +- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 41 +- Penumbra/Mods/ItemSwap/ItemSwap.cs | 29 +- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 4 +- Penumbra/Mods/ModCreator.cs | 6 +- Penumbra/Mods/SubMods/DefaultSubMod.cs | 2 +- Penumbra/Mods/SubMods/OptionSubMod.cs | 2 +- Penumbra/Mods/TemporaryMod.cs | 3 +- .../UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 159 ++++ .../UI/AdvancedWindow/Meta/EqpMetaDrawer.cs | 134 +++ .../UI/AdvancedWindow/Meta/EstMetaDrawer.cs | 147 +++ .../Meta/GlobalEqpMetaDrawer.cs | 111 +++ .../UI/AdvancedWindow/Meta/GmpMetaDrawer.cs | 148 +++ .../UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 164 ++-- Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 154 ++++ .../UI/AdvancedWindow/Meta/MetaDrawers.cs | 35 + .../UI/AdvancedWindow/Meta/RspMetaDrawer.cs | 112 +++ .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 847 +----------------- .../ModEditWindow.Models.MdlTab.cs | 6 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 4 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 6 +- Penumbra/UI/Tabs/EffectiveTab.cs | 10 +- Penumbra/Util/IdentifierExtensions.cs | 94 +- 63 files changed, 2422 insertions(+), 2847 deletions(-) delete mode 100644 Penumbra/Collections/Cache/CmpCache.cs rename Penumbra/{Meta/Manipulations => Collections/Cache}/GlobalEqpCache.cs (75%) create mode 100644 Penumbra/Collections/Cache/IMetaCache.cs create mode 100644 Penumbra/Collections/Cache/RspCache.cs delete mode 100644 Penumbra/Meta/Manipulations/EqdpManipulation.cs delete mode 100644 Penumbra/Meta/Manipulations/EqpManipulation.cs delete mode 100644 Penumbra/Meta/Manipulations/EstManipulation.cs delete mode 100644 Penumbra/Meta/Manipulations/GmpManipulation.cs delete mode 100644 Penumbra/Meta/Manipulations/ImcManipulation.cs delete mode 100644 Penumbra/Meta/Manipulations/MetaManipulation.cs delete mode 100644 Penumbra/Meta/Manipulations/RspManipulation.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index c467df58..ce1a9def 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -1,5 +1,8 @@ +using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; using Penumbra.Meta.Manipulations; @@ -7,17 +10,34 @@ namespace Penumbra.Api.Api; public class MetaApi(CollectionResolver collectionResolver, ApiHelpers helpers) : IPenumbraApiMeta, IApiService { + public const int CurrentVersion = 0; + public string GetPlayerMetaManipulations() { var collection = collectionResolver.PlayerCollection(); - var set = collection.MetaCache?.Manipulations.ToArray() ?? []; - return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); + return CompressMetaManipulations(collection); } public string GetMetaManipulations(int gameObjectIdx) { helpers.AssociatedCollection(gameObjectIdx, out var collection); - var set = collection.MetaCache?.Manipulations.ToArray() ?? []; - return Functions.ToCompressedBase64(set, MetaManipulation.CurrentVersion); + return CompressMetaManipulations(collection); + } + + internal static string CompressMetaManipulations(ModCollection collection) + { + var array = new JArray(); + if (collection.MetaCache is { } cache) + { + MetaDictionary.SerializeTo(array, cache.GlobalEqp.Select(kvp => kvp.Key)); + MetaDictionary.SerializeTo(array, cache.Imc.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Eqp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Eqdp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Est.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Rsp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Gmp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + } + + return Functions.ToCompressedBase64(array, CurrentVersion); } } diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 49958a0d..0894a8e5 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -163,11 +163,11 @@ public class TemporaryApi( { if (manipString.Length == 0) { - manips = []; + manips = new MetaDictionary(); return true; } - if (Functions.FromCompressedBase64(manipString, out manips!) == MetaManipulation.CurrentVersion) + if (Functions.FromCompressedBase64(manipString, out manips!) == MetaApi.CurrentVersion) return true; manips = null; diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 15601867..0aa6821c 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -5,6 +5,7 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; +using Penumbra.Api.Api; using Penumbra.Api.Enums; using Penumbra.Api.IpcSubscribers; using Penumbra.Collections.Manager; @@ -102,8 +103,7 @@ public class TemporaryIpcTester( && copyCollection is { HasCache: true }) { var files = copyCollection.ResolvedFiles.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.Path.ToString()); - var manips = Functions.ToCompressedBase64(copyCollection.MetaCache?.Manipulations.ToArray() ?? Array.Empty(), - MetaManipulation.CurrentVersion); + var manips = MetaApi.CompressMetaManipulations(copyCollection); _lastTempError = new AddTemporaryMod(pi).Invoke(_tempModName, guid, files, manips, 999); } @@ -188,8 +188,8 @@ public class TemporaryIpcTester( if (ImGui.IsItemHovered()) { using var tt = ImRaii.Tooltip(); - foreach (var manip in mod.Default.Manipulations) - ImGui.TextUnformatted(manip.ToString()); + foreach (var identifier in mod.Default.Manipulations.Identifiers) + ImGui.TextUnformatted(identifier.ToString()); } } } diff --git a/Penumbra/Collections/Cache/CmpCache.cs b/Penumbra/Collections/Cache/CmpCache.cs deleted file mode 100644 index 470cadd4..00000000 --- a/Penumbra/Collections/Cache/CmpCache.cs +++ /dev/null @@ -1,56 +0,0 @@ -using OtterGui.Filesystem; -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; -using Penumbra.Meta; -using Penumbra.Meta.Files; -using Penumbra.Meta.Manipulations; - -namespace Penumbra.Collections.Cache; - -public struct CmpCache : IDisposable -{ - private CmpFile? _cmpFile = null; - private readonly List _cmpManipulations = new(); - - public CmpCache() - { } - - public void SetFiles(MetaFileManager manager) - => manager.SetFile(_cmpFile, MetaIndex.HumanCmp); - - public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager) - => manager.TemporarilySetFile(_cmpFile, MetaIndex.HumanCmp); - - public void Reset() - { - if (_cmpFile == null) - return; - - _cmpFile.Reset(_cmpManipulations.Select(m => (m.SubRace, m.Attribute))); - _cmpManipulations.Clear(); - } - - public bool ApplyMod(MetaFileManager manager, RspManipulation manip) - { - _cmpManipulations.AddOrReplace(manip); - _cmpFile ??= new CmpFile(manager); - return manip.Apply(_cmpFile); - } - - public bool RevertMod(MetaFileManager manager, RspManipulation manip) - { - if (!_cmpManipulations.Remove(manip)) - return false; - - var def = CmpFile.GetDefault(manager, manip.SubRace, manip.Attribute); - manip = new RspManipulation(manip.SubRace, manip.Attribute, def); - return manip.Apply(_cmpFile!); - } - - public void Dispose() - { - _cmpFile?.Dispose(); - _cmpFile = null; - _cmpManipulations.Clear(); - } -} diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 4d8d0b4a..fd801d3b 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -36,7 +36,7 @@ public sealed class CollectionCache : IDisposable => ConflictDict.Values; public SingleArray Conflicts(IMod mod) - => ConflictDict.TryGetValue(mod, out var c) ? c : new SingleArray(); + => ConflictDict.TryGetValue(mod, out SingleArray c) ? c : new SingleArray(); private int _changedItemsSaveCounter = -1; @@ -233,8 +233,20 @@ public sealed class CollectionCache : IDisposable foreach (var (path, file) in files.FileRedirections) AddFile(path, file, mod); - foreach (var manip in files.Manipulations) - AddManipulation(manip, mod); + foreach (var (identifier, entry) in files.Manipulations.Eqp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Eqdp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Est) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Gmp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Rsp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Imc) + AddManipulation(mod, identifier, entry); + foreach (var identifier in files.Manipulations.GlobalEqp) + AddManipulation(mod, identifier, null!); if (addMetaChanges) { @@ -342,7 +354,7 @@ public sealed class CollectionCache : IDisposable foreach (var conflict in tmpConflicts) { if (data is Utf8GamePath path && conflict.Conflicts.RemoveAll(p => p is Utf8GamePath x && x.Equals(path)) > 0 - || data is MetaManipulation meta && conflict.Conflicts.RemoveAll(m => m is MetaManipulation x && x.Equals(meta)) > 0) + || data is IMetaIdentifier meta && conflict.Conflicts.RemoveAll(m => m.Equals(meta)) > 0) AddConflict(data, addedMod, conflict.Mod2); } @@ -374,12 +386,12 @@ public sealed class CollectionCache : IDisposable // For different mods, higher mod priority takes precedence before option group priority, // which takes precedence before option priority, which takes precedence before ordering. // Inside the same mod, conflicts are not recorded. - private void AddManipulation(MetaManipulation manip, IMod mod) + private void AddManipulation(IMod mod, IMetaIdentifier identifier, object entry) { - if (!Meta.TryGetValue(manip, out var existingMod)) + if (!Meta.TryGetMod(identifier, out var existingMod)) { - Meta.ApplyMod(manip, mod); - ModData.AddManip(mod, manip); + Meta.ApplyMod(mod, identifier, entry); + ModData.AddManip(mod, identifier); return; } @@ -387,11 +399,11 @@ public sealed class CollectionCache : IDisposable if (mod == existingMod) return; - if (AddConflict(manip, mod, existingMod)) + if (AddConflict(identifier, mod, existingMod)) { - ModData.RemoveManip(existingMod, manip); - Meta.ApplyMod(manip, mod); - ModData.AddManip(mod, manip); + ModData.RemoveManip(existingMod, identifier); + Meta.ApplyMod(mod, identifier, entry); + ModData.AddManip(mod, identifier); } } @@ -437,9 +449,9 @@ public sealed class CollectionCache : IDisposable AddItems(modPath.Mod); } - foreach (var (manip, mod) in Meta) + foreach (var (manip, mod) in Meta.IdentifierSources) { - identifier.MetaChangedItems(items, manip); + manip.AddChangedItems(identifier, items); AddItems(mod); } diff --git a/Penumbra/Collections/Cache/CollectionModData.cs b/Penumbra/Collections/Cache/CollectionModData.cs index d0a3bc76..295191d2 100644 --- a/Penumbra/Collections/Cache/CollectionModData.cs +++ b/Penumbra/Collections/Cache/CollectionModData.cs @@ -9,12 +9,12 @@ namespace Penumbra.Collections.Cache; /// public class CollectionModData { - private readonly Dictionary, HashSet)> _data = new(); + private readonly Dictionary, HashSet)> _data = new(); - public IEnumerable<(IMod, IReadOnlySet, IReadOnlySet)> Data - => _data.Select(kvp => (kvp.Key, (IReadOnlySet)kvp.Value.Item1, (IReadOnlySet)kvp.Value.Item2)); + public IEnumerable<(IMod, IReadOnlySet, IReadOnlySet)> Data + => _data.Select(kvp => (kvp.Key, (IReadOnlySet)kvp.Value.Item1, (IReadOnlySet)kvp.Value.Item2)); - public (IReadOnlyCollection Paths, IReadOnlyCollection Manipulations) RemoveMod(IMod mod) + public (IReadOnlyCollection Paths, IReadOnlyCollection Manipulations) RemoveMod(IMod mod) { if (_data.Remove(mod, out var data)) return data; @@ -35,7 +35,7 @@ public class CollectionModData } } - public void AddManip(IMod mod, MetaManipulation manipulation) + public void AddManip(IMod mod, IMetaIdentifier manipulation) { if (_data.TryGetValue(mod, out var data)) { @@ -54,7 +54,7 @@ public class CollectionModData _data.Remove(mod); } - public void RemoveManip(IMod mod, MetaManipulation manip) + public void RemoveManip(IMod mod, IMetaIdentifier manip) { if (_data.TryGetValue(mod, out var data) && data.Item2.Remove(manip) && data.Item1.Count == 0 && data.Item2.Count == 0) _data.Remove(mod); diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index a0f27c23..f3475c7e 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -1,5 +1,5 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using OtterGui; -using OtterGui.Filesystem; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; @@ -10,28 +10,38 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; -public readonly struct EqdpCache : IDisposable +public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private readonly ExpandedEqdpFile?[] _eqdpFiles = new ExpandedEqdpFile[CharacterUtilityData.EqdpIndices.Length]; // TODO: female Hrothgar - private readonly List _eqdpManipulations = new(); + private readonly ExpandedEqdpFile?[] _eqdpFiles = new ExpandedEqdpFile[CharacterUtilityData.EqdpIndices.Length]; // TODO: female Hrothgar - public EqdpCache() - { } - - public void SetFiles(MetaFileManager manager) + public override void SetFiles() { for (var i = 0; i < CharacterUtilityData.EqdpIndices.Length; ++i) - manager.SetFile(_eqdpFiles[i], CharacterUtilityData.EqdpIndices[i]); + Manager.SetFile(_eqdpFiles[i], CharacterUtilityData.EqdpIndices[i]); } - public void SetFile(MetaFileManager manager, MetaIndex index) + public void SetFile(MetaIndex index) { var i = CharacterUtilityData.EqdpIndices.IndexOf(index); if (i != -1) - manager.SetFile(_eqdpFiles[i], index); + Manager.SetFile(_eqdpFiles[i], index); } - public MetaList.MetaReverter? TemporarilySetFiles(MetaFileManager manager, GenderRace genderRace, bool accessory) + public override void ResetFiles() + => Manager.SetFile(null, MetaIndex.Eqp); + + protected override void IncorporateChangesInternal() + { + foreach (var (identifier, (_, entry)) in this) + Apply(GetFile(identifier)!, identifier, entry); + + Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EQDP manipulations."); + } + + public ExpandedEqdpFile? EqdpFile(GenderRace race, bool accessory) + => _eqdpFiles[Array.IndexOf(CharacterUtilityData.EqdpIndices, CharacterUtilityData.EqdpIdx(race, accessory))]; // TODO: female Hrothgar + + public MetaList.MetaReverter? TemporarilySetFile(GenderRace genderRace, bool accessory) { var idx = CharacterUtilityData.EqdpIdx(genderRace, accessory); if (idx < 0) @@ -47,44 +57,44 @@ public readonly struct EqdpCache : IDisposable return null; } - return manager.TemporarilySetFile(_eqdpFiles[i], idx); + return Manager.TemporarilySetFile(_eqdpFiles[i], idx); } - public void Reset() + public override void Reset() { foreach (var file in _eqdpFiles.OfType()) { var relevant = CharacterUtility.RelevantIndices[file.Index.Value]; - file.Reset(_eqdpManipulations.Where(m => m.FileIndex() == relevant).Select(m => (PrimaryId)m.SetId)); + file.Reset(Keys.Where(m => m.FileIndex() == relevant).Select(m => m.SetId)); } - _eqdpManipulations.Clear(); + Clear(); } - public bool ApplyMod(MetaFileManager manager, EqdpManipulation manip) + protected override void ApplyModInternal(EqdpIdentifier identifier, EqdpEntry entry) { - _eqdpManipulations.AddOrReplace(manip); - var file = _eqdpFiles[Array.IndexOf(CharacterUtilityData.EqdpIndices, manip.FileIndex())] ??= - new ExpandedEqdpFile(manager, Names.CombinedRace(manip.Gender, manip.Race), manip.Slot.IsAccessory()); // TODO: female Hrothgar - return manip.Apply(file); + if (GetFile(identifier) is { } file) + Apply(file, identifier, entry); } - public bool RevertMod(MetaFileManager manager, EqdpManipulation manip) + protected override void RevertModInternal(EqdpIdentifier identifier) { - if (!_eqdpManipulations.Remove(manip)) + if (GetFile(identifier) is { } file) + Apply(file, identifier, ExpandedEqdpFile.GetDefault(Manager, identifier)); + } + + public static bool Apply(ExpandedEqdpFile file, EqdpIdentifier identifier, EqdpEntry entry) + { + var origEntry = file[identifier.SetId]; + var mask = Eqdp.Mask(identifier.Slot); + if ((origEntry & mask) == entry) return false; - var def = ExpandedEqdpFile.GetDefault(manager, Names.CombinedRace(manip.Gender, manip.Race), manip.Slot.IsAccessory(), manip.SetId); - var file = _eqdpFiles[Array.IndexOf(CharacterUtilityData.EqdpIndices, manip.FileIndex())]!; - manip = new EqdpManipulation(def, manip.Slot, manip.Gender, manip.Race, manip.SetId); - return manip.Apply(file); + file[identifier.SetId] = (entry & ~mask) | origEntry; + return true; } - public ExpandedEqdpFile? EqdpFile(GenderRace race, bool accessory) - => _eqdpFiles - [Array.IndexOf(CharacterUtilityData.EqdpIndices, CharacterUtilityData.EqdpIdx(race, accessory))]; // TODO: female Hrothgar - - public void Dispose() + protected override void Dispose(bool _) { for (var i = 0; i < _eqdpFiles.Length; ++i) { @@ -92,6 +102,15 @@ public readonly struct EqdpCache : IDisposable _eqdpFiles[i] = null; } - _eqdpManipulations.Clear(); + Clear(); + } + + private ExpandedEqdpFile? GetFile(EqdpIdentifier identifier) + { + if (!Manager.CharacterUtility.Ready) + return null; + + var index = Array.IndexOf(CharacterUtilityData.EqdpIndices, identifier.FileIndex()); + return _eqdpFiles[index] ??= new ExpandedEqdpFile(Manager, identifier.GenderRace, identifier.Slot.IsAccessory()); } } diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 972ee5a5..599ae588 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -1,4 +1,4 @@ -using OtterGui.Filesystem; +using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta; @@ -7,54 +7,77 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; -public struct EqpCache : IDisposable +public sealed class EqpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private ExpandedEqpFile? _eqpFile = null; - private readonly List _eqpManipulations = new(); + private ExpandedEqpFile? _eqpFile; - public EqpCache() - { } + public override void SetFiles() + => Manager.SetFile(_eqpFile, MetaIndex.Eqp); - public void SetFiles(MetaFileManager manager) - => manager.SetFile(_eqpFile, MetaIndex.Eqp); + public override void ResetFiles() + => Manager.SetFile(null, MetaIndex.Eqp); - public static void ResetFiles(MetaFileManager manager) - => manager.SetFile(null, MetaIndex.Eqp); + protected override void IncorporateChangesInternal() + { + if (GetFile() is not { } file) + return; - public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager) - => manager.TemporarilySetFile(_eqpFile, MetaIndex.Eqp); + foreach (var (identifier, (_, entry)) in this) + Apply(file, identifier, entry); - public void Reset() + Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EQP manipulations."); + } + + public MetaList.MetaReverter TemporarilySetFile() + => Manager.TemporarilySetFile(_eqpFile, MetaIndex.Eqp); + + public override void Reset() { if (_eqpFile == null) return; - _eqpFile.Reset(_eqpManipulations.Select(m => m.SetId)); - _eqpManipulations.Clear(); + _eqpFile.Reset(Keys.Select(identifier => identifier.SetId)); + Clear(); } - public bool ApplyMod(MetaFileManager manager, EqpManipulation manip) + protected override void ApplyModInternal(EqpIdentifier identifier, EqpEntry entry) { - _eqpManipulations.AddOrReplace(manip); - _eqpFile ??= new ExpandedEqpFile(manager); - return manip.Apply(_eqpFile); + if (GetFile() is { } file) + Apply(file, identifier, entry); } - public bool RevertMod(MetaFileManager manager, EqpManipulation manip) + protected override void RevertModInternal(EqpIdentifier identifier) { - var idx = _eqpManipulations.FindIndex(manip.Equals); - if (idx < 0) + if (GetFile() is { } file) + Apply(file, identifier, ExpandedEqpFile.GetDefault(Manager, identifier.SetId)); + } + + public static bool Apply(ExpandedEqpFile file, EqpIdentifier identifier, EqpEntry entry) + { + var origEntry = file[identifier.SetId]; + var mask = Eqp.Mask(identifier.Slot); + if ((origEntry & mask) == entry) return false; - var def = ExpandedEqpFile.GetDefault(manager, manip.SetId); - manip = new EqpManipulation(def, manip.Slot, manip.SetId); - return manip.Apply(_eqpFile!); + file[identifier.SetId] = (origEntry & ~mask) | entry; + return true; } - public void Dispose() + protected override void Dispose(bool _) { _eqpFile?.Dispose(); _eqpFile = null; - _eqpManipulations.Clear(); + Clear(); + } + + private ExpandedEqpFile? GetFile() + { + if (_eqpFile != null) + return _eqpFile; + + if (!Manager.CharacterUtility.Ready) + return null; + + return _eqpFile = new ExpandedEqpFile(Manager); } } diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 3a0b4695..412dd322 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -1,6 +1,3 @@ -using OtterGui.Filesystem; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta; @@ -9,46 +6,41 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; -public struct EstCache : IDisposable +public sealed class EstCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private EstFile? _estFaceFile = null; - private EstFile? _estHairFile = null; - private EstFile? _estBodyFile = null; - private EstFile? _estHeadFile = null; + private EstFile? _estFaceFile; + private EstFile? _estHairFile; + private EstFile? _estBodyFile; + private EstFile? _estHeadFile; - private readonly List _estManipulations = new(); - - public EstCache() - { } - - public void SetFiles(MetaFileManager manager) + public override void SetFiles() { - manager.SetFile(_estFaceFile, MetaIndex.FaceEst); - manager.SetFile(_estHairFile, MetaIndex.HairEst); - manager.SetFile(_estBodyFile, MetaIndex.BodyEst); - manager.SetFile(_estHeadFile, MetaIndex.HeadEst); + Manager.SetFile(_estFaceFile, MetaIndex.FaceEst); + Manager.SetFile(_estHairFile, MetaIndex.HairEst); + Manager.SetFile(_estBodyFile, MetaIndex.BodyEst); + Manager.SetFile(_estHeadFile, MetaIndex.HeadEst); } - public void SetFile(MetaFileManager manager, MetaIndex index) + public void SetFile(MetaIndex index) { switch (index) { case MetaIndex.FaceEst: - manager.SetFile(_estFaceFile, MetaIndex.FaceEst); + Manager.SetFile(_estFaceFile, MetaIndex.FaceEst); break; case MetaIndex.HairEst: - manager.SetFile(_estHairFile, MetaIndex.HairEst); + Manager.SetFile(_estHairFile, MetaIndex.HairEst); break; case MetaIndex.BodyEst: - manager.SetFile(_estBodyFile, MetaIndex.BodyEst); + Manager.SetFile(_estBodyFile, MetaIndex.BodyEst); break; case MetaIndex.HeadEst: - manager.SetFile(_estHeadFile, MetaIndex.HeadEst); + Manager.SetFile(_estHeadFile, MetaIndex.HeadEst); break; } } - public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager, EstType type) + public MetaList.MetaReverter TemporarilySetFiles(EstType type) { var (file, idx) = type switch { @@ -56,74 +48,65 @@ public struct EstCache : IDisposable EstType.Hair => (_estHairFile, MetaIndex.HairEst), EstType.Body => (_estBodyFile, MetaIndex.BodyEst), EstType.Head => (_estHeadFile, MetaIndex.HeadEst), - _ => (null, 0), + _ => (null, 0), }; - return manager.TemporarilySetFile(file, idx); + return Manager.TemporarilySetFile(file, idx); } - private readonly EstFile? GetEstFile(EstType type) + public override void ResetFiles() + => Manager.SetFile(null, MetaIndex.Eqp); + + protected override void IncorporateChangesInternal() { - return type switch - { - EstType.Face => _estFaceFile, - EstType.Hair => _estHairFile, - EstType.Body => _estBodyFile, - EstType.Head => _estHeadFile, - _ => null, - }; + if (!Manager.CharacterUtility.Ready) + return; + + foreach (var (identifier, (_, entry)) in this) + Apply(GetFile(identifier)!, identifier, entry); + Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EST manipulations."); } - internal EstEntry GetEstEntry(MetaFileManager manager, EstType type, GenderRace genderRace, PrimaryId primaryId) + public EstEntry GetEstEntry(EstIdentifier identifier) { - var file = GetEstFile(type); + var file = GetFile(identifier); return file != null - ? file[genderRace, primaryId.Id] - : EstFile.GetDefault(manager, type, genderRace, primaryId); + ? file[identifier.GenderRace, identifier.SetId] + : EstFile.GetDefault(Manager, identifier); } - public void Reset() + public override void Reset() { _estFaceFile?.Reset(); _estHairFile?.Reset(); _estBodyFile?.Reset(); _estHeadFile?.Reset(); - _estManipulations.Clear(); + Clear(); } - public bool ApplyMod(MetaFileManager manager, EstManipulation m) + protected override void ApplyModInternal(EstIdentifier identifier, EstEntry entry) { - _estManipulations.AddOrReplace(m); - var file = m.Slot switch - { - EstType.Hair => _estHairFile ??= new EstFile(manager, EstType.Hair), - EstType.Face => _estFaceFile ??= new EstFile(manager, EstType.Face), - EstType.Body => _estBodyFile ??= new EstFile(manager, EstType.Body), - EstType.Head => _estHeadFile ??= new EstFile(manager, EstType.Head), - _ => throw new ArgumentOutOfRangeException(), - }; - return m.Apply(file); + if (GetFile(identifier) is { } file) + Apply(file, identifier, entry); } - public bool RevertMod(MetaFileManager manager, EstManipulation m) + protected override void RevertModInternal(EstIdentifier identifier) { - if (!_estManipulations.Remove(m)) - return false; - - var def = EstFile.GetDefault(manager, m.Slot, Names.CombinedRace(m.Gender, m.Race), m.SetId); - var manip = new EstManipulation(m.Gender, m.Race, m.Slot, m.SetId, def); - var file = m.Slot switch - { - EstType.Hair => _estHairFile!, - EstType.Face => _estFaceFile!, - EstType.Body => _estBodyFile!, - EstType.Head => _estHeadFile!, - _ => throw new ArgumentOutOfRangeException(), - }; - return manip.Apply(file); + if (GetFile(identifier) is { } file) + Apply(file, identifier, EstFile.GetDefault(Manager, identifier.Slot, identifier.GenderRace, identifier.SetId)); } - public void Dispose() + public static bool Apply(EstFile file, EstIdentifier identifier, EstEntry entry) + => file.SetEntry(identifier.GenderRace, identifier.SetId, entry) switch + { + EstFile.EstEntryChange.Unchanged => false, + EstFile.EstEntryChange.Changed => true, + EstFile.EstEntryChange.Added => true, + EstFile.EstEntryChange.Removed => true, + _ => false, + }; + + protected override void Dispose(bool _) { _estFaceFile?.Dispose(); _estHairFile?.Dispose(); @@ -133,6 +116,21 @@ public struct EstCache : IDisposable _estHairFile = null; _estBodyFile = null; _estHeadFile = null; - _estManipulations.Clear(); + Clear(); + } + + private EstFile? GetFile(EstIdentifier identifier) + { + if (Manager.CharacterUtility.Ready) + return null; + + return identifier.Slot switch + { + EstType.Hair => _estHairFile ??= new EstFile(Manager, EstType.Hair), + EstType.Face => _estFaceFile ??= new EstFile(Manager, EstType.Face), + EstType.Body => _estBodyFile ??= new EstFile(Manager, EstType.Body), + EstType.Head => _estHeadFile ??= new EstFile(Manager, EstType.Head), + _ => null, + }; } } diff --git a/Penumbra/Meta/Manipulations/GlobalEqpCache.cs b/Penumbra/Collections/Cache/GlobalEqpCache.cs similarity index 75% rename from Penumbra/Meta/Manipulations/GlobalEqpCache.cs rename to Penumbra/Collections/Cache/GlobalEqpCache.cs index 26eb1d05..1c80b47d 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpCache.cs +++ b/Penumbra/Collections/Cache/GlobalEqpCache.cs @@ -1,9 +1,11 @@ using OtterGui.Services; using Penumbra.GameData.Structs; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; -namespace Penumbra.Meta.Manipulations; +namespace Penumbra.Collections.Cache; -public struct GlobalEqpCache : IService +public class GlobalEqpCache : Dictionary, IService { private readonly HashSet _doNotHideEarrings = []; private readonly HashSet _doNotHideNecklace = []; @@ -13,11 +15,9 @@ public struct GlobalEqpCache : IService private bool _doNotHideVieraHats; private bool _doNotHideHrothgarHats; - public GlobalEqpCache() - { } - - public void Clear() + public new void Clear() { + base.Clear(); _doNotHideEarrings.Clear(); _doNotHideNecklace.Clear(); _doNotHideBracelets.Clear(); @@ -29,6 +29,9 @@ public struct GlobalEqpCache : IService public unsafe EqpEntry Apply(EqpEntry original, CharacterArmor* armor) { + if (Count == 0) + return original; + if (_doNotHideVieraHats) original |= EqpEntry.HeadShowVieraHat; @@ -52,8 +55,13 @@ public struct GlobalEqpCache : IService return original; } - public bool Add(GlobalEqpManipulation manipulation) - => manipulation.Type switch + public bool ApplyMod(IMod mod, GlobalEqpManipulation manipulation) + { + if (Remove(manipulation, out var oldMod) && oldMod == mod) + return false; + + this[manipulation] = mod; + _ = manipulation.Type switch { GlobalEqpType.DoNotHideEarrings => _doNotHideEarrings.Add(manipulation.Condition), GlobalEqpType.DoNotHideNecklace => _doNotHideNecklace.Add(manipulation.Condition), @@ -61,12 +69,18 @@ public struct GlobalEqpCache : IService GlobalEqpType.DoNotHideRingR => _doNotHideRingR.Add(manipulation.Condition), GlobalEqpType.DoNotHideRingL => _doNotHideRingL.Add(manipulation.Condition), GlobalEqpType.DoNotHideHrothgarHats => !_doNotHideHrothgarHats && (_doNotHideHrothgarHats = true), - GlobalEqpType.DoNotHideVieraHats => !_doNotHideVieraHats && (_doNotHideVieraHats = true), - _ => false, + GlobalEqpType.DoNotHideVieraHats => !_doNotHideVieraHats && (_doNotHideVieraHats = true), + _ => false, }; + return true; + } - public bool Remove(GlobalEqpManipulation manipulation) - => manipulation.Type switch + public bool RevertMod(GlobalEqpManipulation manipulation, [NotNullWhen(true)] out IMod? mod) + { + if (!Remove(manipulation, out mod)) + return false; + + _ = manipulation.Type switch { GlobalEqpType.DoNotHideEarrings => _doNotHideEarrings.Remove(manipulation.Condition), GlobalEqpType.DoNotHideNecklace => _doNotHideNecklace.Remove(manipulation.Condition), @@ -74,7 +88,9 @@ public struct GlobalEqpCache : IService GlobalEqpType.DoNotHideRingR => _doNotHideRingR.Remove(manipulation.Condition), GlobalEqpType.DoNotHideRingL => _doNotHideRingL.Remove(manipulation.Condition), GlobalEqpType.DoNotHideHrothgarHats => _doNotHideHrothgarHats && !(_doNotHideHrothgarHats = false), - GlobalEqpType.DoNotHideVieraHats => _doNotHideVieraHats && !(_doNotHideVieraHats = false), - _ => false, + GlobalEqpType.DoNotHideVieraHats => _doNotHideVieraHats && !(_doNotHideVieraHats = false), + _ => false, }; + return true; + } } diff --git a/Penumbra/Collections/Cache/GmpCache.cs b/Penumbra/Collections/Cache/GmpCache.cs index 0a713867..1475ffd5 100644 --- a/Penumbra/Collections/Cache/GmpCache.cs +++ b/Penumbra/Collections/Cache/GmpCache.cs @@ -1,4 +1,4 @@ -using OtterGui.Filesystem; +using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Meta; @@ -7,50 +7,76 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; -public struct GmpCache : IDisposable +public sealed class GmpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private ExpandedGmpFile? _gmpFile = null; - private readonly List _gmpManipulations = new(); + private ExpandedGmpFile? _gmpFile; - public GmpCache() - { } + public override void SetFiles() + => Manager.SetFile(_gmpFile, MetaIndex.Gmp); - public void SetFiles(MetaFileManager manager) - => manager.SetFile(_gmpFile, MetaIndex.Gmp); + public override void ResetFiles() + => Manager.SetFile(null, MetaIndex.Gmp); - public MetaList.MetaReverter TemporarilySetFiles(MetaFileManager manager) - => manager.TemporarilySetFile(_gmpFile, MetaIndex.Gmp); + protected override void IncorporateChangesInternal() + { + if (GetFile() is not { } file) + return; - public void Reset() + foreach (var (identifier, (_, entry)) in this) + Apply(file, identifier, entry); + + Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed GMP manipulations."); + } + + public MetaList.MetaReverter TemporarilySetFile() + => Manager.TemporarilySetFile(_gmpFile, MetaIndex.Gmp); + + public override void Reset() { if (_gmpFile == null) return; - _gmpFile.Reset(_gmpManipulations.Select(m => m.SetId)); - _gmpManipulations.Clear(); + _gmpFile.Reset(Keys.Select(identifier => identifier.SetId)); + Clear(); } - public bool ApplyMod(MetaFileManager manager, GmpManipulation manip) + protected override void ApplyModInternal(GmpIdentifier identifier, GmpEntry entry) { - _gmpManipulations.AddOrReplace(manip); - _gmpFile ??= new ExpandedGmpFile(manager); - return manip.Apply(_gmpFile); + if (GetFile() is { } file) + Apply(file, identifier, entry); } - public bool RevertMod(MetaFileManager manager, GmpManipulation manip) + protected override void RevertModInternal(GmpIdentifier identifier) { - if (!_gmpManipulations.Remove(manip)) + if (GetFile() is { } file) + Apply(file, identifier, ExpandedGmpFile.GetDefault(Manager, identifier.SetId)); + } + + public static bool Apply(ExpandedGmpFile file, GmpIdentifier identifier, GmpEntry entry) + { + var origEntry = file[identifier.SetId]; + if (entry == origEntry) return false; - var def = ExpandedGmpFile.GetDefault(manager, manip.SetId); - manip = new GmpManipulation(def, manip.SetId); - return manip.Apply(_gmpFile!); + file[identifier.SetId] = entry; + return true; } - public void Dispose() + protected override void Dispose(bool _) { _gmpFile?.Dispose(); _gmpFile = null; - _gmpManipulations.Clear(); + Clear(); + } + + private ExpandedGmpFile? GetFile() + { + if (_gmpFile != null) + return _gmpFile; + + if (!Manager.CharacterUtility.Ready) + return null; + + return _gmpFile = new ExpandedGmpFile(Manager); } } diff --git a/Penumbra/Collections/Cache/IMetaCache.cs b/Penumbra/Collections/Cache/IMetaCache.cs new file mode 100644 index 00000000..218c1840 --- /dev/null +++ b/Penumbra/Collections/Cache/IMetaCache.cs @@ -0,0 +1,89 @@ +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; + +namespace Penumbra.Collections.Cache; + +public interface IMetaCache : IDisposable +{ + public void SetFiles(); + public void Reset(); + public void ResetFiles(); + + public int Count { get; } +} + +public abstract class MetaCacheBase + : Dictionary, IMetaCache + where TIdentifier : unmanaged, IMetaIdentifier + where TEntry : unmanaged +{ + public MetaCacheBase(MetaFileManager manager, ModCollection collection) + { + Manager = manager; + Collection = collection; + if (!Manager.CharacterUtility.Ready) + Manager.CharacterUtility.LoadingFinished += IncorporateChanges; + } + + protected readonly MetaFileManager Manager; + protected readonly ModCollection Collection; + + public void Dispose() + { + Manager.CharacterUtility.LoadingFinished -= IncorporateChanges; + Dispose(true); + } + + public abstract void SetFiles(); + public abstract void Reset(); + public abstract void ResetFiles(); + + public bool ApplyMod(IMod source, TIdentifier identifier, TEntry entry) + { + lock (this) + { + if (TryGetValue(identifier, out var pair) && pair.Source == source && EqualityComparer.Default.Equals(pair.Entry, entry)) + return false; + + this[identifier] = (source, entry); + } + + ApplyModInternal(identifier, entry); + return true; + } + + public bool RevertMod(TIdentifier identifier, [NotNullWhen(true)] out IMod? mod) + { + lock (this) + { + if (!Remove(identifier, out var pair)) + { + mod = null; + return false; + } + + mod = pair.Source; + } + + RevertModInternal(identifier); + return true; + } + + private void IncorporateChanges() + { + lock (this) + { + IncorporateChangesInternal(); + } + if (Manager.ActiveCollections.Default == Collection && Manager.Config.EnableMods) + SetFiles(); + } + + protected abstract void ApplyModInternal(TIdentifier identifier, TEntry entry); + protected abstract void RevertModInternal(TIdentifier identifier); + protected abstract void IncorporateChangesInternal(); + + protected virtual void Dispose(bool _) + { } +} diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 7990122a..3d05e793 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -1,3 +1,6 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; using Penumbra.Meta; using Penumbra.Meta.Files; @@ -6,116 +9,132 @@ using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; -public readonly struct ImcCache : IDisposable +public sealed class ImcCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private readonly Dictionary _imcFiles = []; - private readonly List<(ImcManipulation, ImcFile)> _imcManipulations = []; + private readonly Dictionary)> _imcFiles = []; - public ImcCache() - { } + public override void SetFiles() + => SetFiles(false); - public void SetFiles(ModCollection collection, bool fromFullCompute) + public bool GetFile(Utf8GamePath path, [NotNullWhen(true)] out ImcFile? file) + { + if (!_imcFiles.TryGetValue(path, out var p)) + { + file = null; + return false; + } + + file = p.Item1; + return true; + } + + public void SetFiles(bool fromFullCompute) { if (fromFullCompute) - foreach (var path in _imcFiles.Keys) - collection._cache!.ForceFileSync(path, PathDataHandler.CreateImc(path.Path, collection)); + foreach (var (path, _) in _imcFiles) + Collection._cache!.ForceFileSync(path, PathDataHandler.CreateImc(path.Path, Collection)); else - foreach (var path in _imcFiles.Keys) - collection._cache!.ForceFile(path, PathDataHandler.CreateImc(path.Path, collection)); + foreach (var (path, _) in _imcFiles) + Collection._cache!.ForceFile(path, PathDataHandler.CreateImc(path.Path, Collection)); } - public void Reset(ModCollection collection) + public override void ResetFiles() { - foreach (var (path, file) in _imcFiles) + foreach (var (path, _) in _imcFiles) + Collection._cache!.ForceFile(path, FullPath.Empty); + } + + protected override void IncorporateChangesInternal() + { + if (!Manager.CharacterUtility.Ready) + return; + + foreach (var (identifier, (_, entry)) in this) + ApplyFile(identifier, entry); + + Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed IMC manipulations."); + } + + + public override void Reset() + { + foreach (var (path, (file, set)) in _imcFiles) { - collection._cache!.RemovePath(path); + Collection._cache!.RemovePath(path); file.Reset(); + set.Clear(); } - _imcManipulations.Clear(); + Clear(); } - public bool ApplyMod(MetaFileManager manager, ModCollection collection, ImcManipulation manip) + protected override void ApplyModInternal(ImcIdentifier identifier, ImcEntry entry) { - if (!manip.Validate(true)) - return false; + if (Manager.CharacterUtility.Ready) + ApplyFile(identifier, entry); + } - var idx = _imcManipulations.FindIndex(p => p.Item1.Equals(manip)); - if (idx < 0) - { - idx = _imcManipulations.Count; - _imcManipulations.Add((manip, null!)); - } - - var path = manip.GamePath(); + private void ApplyFile(ImcIdentifier identifier, ImcEntry entry) + { + var path = identifier.GamePath(); try { - if (!_imcFiles.TryGetValue(path, out var file)) - file = new ImcFile(manager, manip.Identifier); + if (!_imcFiles.TryGetValue(path, out var pair)) + pair = (new ImcFile(Manager, identifier), []); - _imcManipulations[idx] = (manip, file); - if (!manip.Apply(file)) - return false; - _imcFiles[path] = file; - var fullPath = PathDataHandler.CreateImc(file.Path.Path, collection); - collection._cache!.ForceFile(path, fullPath); + if (!Apply(pair.Item1, identifier, entry)) + return; - return true; + pair.Item2.Add(identifier); + _imcFiles[path] = pair; + var fullPath = PathDataHandler.CreateImc(pair.Item1.Path.Path, Collection); + Collection._cache!.ForceFile(path, fullPath); } catch (ImcException e) { - manager.ValidityChecker.ImcExceptions.Add(e); + Manager.ValidityChecker.ImcExceptions.Add(e); Penumbra.Log.Error(e.ToString()); } catch (Exception e) { - Penumbra.Log.Error($"Could not apply IMC Manipulation {manip}:\n{e}"); + Penumbra.Log.Error($"Could not apply IMC Manipulation {identifier}:\n{e}"); } - - return false; } - public bool RevertMod(MetaFileManager manager, ModCollection collection, ImcManipulation m) + protected override void RevertModInternal(ImcIdentifier identifier) { - if (!m.Validate(false)) - return false; + var path = identifier.GamePath(); + if (!_imcFiles.TryGetValue(path, out var pair)) + return; - var idx = _imcManipulations.FindIndex(p => p.Item1.Equals(m)); - if (idx < 0) - return false; + if (!pair.Item2.Remove(identifier)) + return; - var (_, file) = _imcManipulations[idx]; - _imcManipulations.RemoveAt(idx); - - if (_imcManipulations.All(p => !ReferenceEquals(p.Item2, file))) + if (pair.Item2.Count == 0) { - _imcFiles.Remove(file.Path); - collection._cache!.ForceFile(file.Path, FullPath.Empty); - file.Dispose(); - return true; + _imcFiles.Remove(path); + Collection._cache!.ForceFile(pair.Item1.Path, FullPath.Empty); + pair.Item1.Dispose(); + return; } - var def = ImcFile.GetDefault(manager, file.Path, m.EquipSlot, m.Variant.Id, out _); - var manip = m.Copy(def); - if (!manip.Apply(file)) - return false; + var def = ImcFile.GetDefault(Manager, pair.Item1.Path, identifier.EquipSlot, identifier.Variant, out _); + if (!Apply(pair.Item1, identifier, def)) + return; - var fullPath = PathDataHandler.CreateImc(file.Path.Path, collection); - collection._cache!.ForceFile(file.Path, fullPath); - - return true; + var fullPath = PathDataHandler.CreateImc(pair.Item1.Path.Path, Collection); + Collection._cache!.ForceFile(pair.Item1.Path, fullPath); } - public void Dispose() + public static bool Apply(ImcFile file, ImcIdentifier identifier, ImcEntry entry) + => file.SetEntry(ImcFile.PartIndex(identifier.EquipSlot), identifier.Variant.Id, entry); + + protected override void Dispose(bool _) { - foreach (var file in _imcFiles.Values) + foreach (var (_, (file, _)) in _imcFiles) file.Dispose(); - + Clear(); _imcFiles.Clear(); - _imcManipulations.Clear(); } - - public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out ImcFile? file) - => _imcFiles.TryGetValue(path, out file); } diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index fbca9c0e..bc6ef34d 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,3 +1,4 @@ +using System.IO.Pipes; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; @@ -9,238 +10,174 @@ using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; -public class MetaCache : IDisposable, IEnumerable> +public class MetaCache(MetaFileManager manager, ModCollection collection) { - private readonly MetaFileManager _manager; - private readonly ModCollection _collection; - private readonly Dictionary _manipulations = new(); - private EqpCache _eqpCache = new(); - private readonly EqdpCache _eqdpCache = new(); - private EstCache _estCache = new(); - private GmpCache _gmpCache = new(); - private CmpCache _cmpCache = new(); - private readonly ImcCache _imcCache = new(); - private GlobalEqpCache _globalEqpCache = new(); - - public bool TryGetValue(MetaManipulation manip, [NotNullWhen(true)] out IMod? mod) - { - lock (_manipulations) - { - return _manipulations.TryGetValue(manip, out mod); - } - } + public readonly EqpCache Eqp = new(manager, collection); + public readonly EqdpCache Eqdp = new(manager, collection); + public readonly EstCache Est = new(manager, collection); + public readonly GmpCache Gmp = new(manager, collection); + public readonly RspCache Rsp = new(manager, collection); + public readonly ImcCache Imc = new(manager, collection); + public readonly GlobalEqpCache GlobalEqp = new(); public int Count - => _manipulations.Count; + => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + GlobalEqp.Count; - public IReadOnlyCollection Manipulations - => _manipulations.Keys; - - public IEnumerator> GetEnumerator() - => _manipulations.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() - => GetEnumerator(); - - public MetaCache(MetaFileManager manager, ModCollection collection) - { - _manager = manager; - _collection = collection; - if (!_manager.CharacterUtility.Ready) - _manager.CharacterUtility.LoadingFinished += ApplyStoredManipulations; - } + public IEnumerable<(IMetaIdentifier, IMod)> IdentifierSources + => Eqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source)) + .Concat(Eqdp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Est.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Gmp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Rsp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Imc.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(GlobalEqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value))); public void SetFiles() { - _eqpCache.SetFiles(_manager); - _eqdpCache.SetFiles(_manager); - _estCache.SetFiles(_manager); - _gmpCache.SetFiles(_manager); - _cmpCache.SetFiles(_manager); - _imcCache.SetFiles(_collection, false); + Eqp.SetFiles(); + Eqdp.SetFiles(); + Est.SetFiles(); + Gmp.SetFiles(); + Rsp.SetFiles(); + Imc.SetFiles(false); } public void Reset() { - _eqpCache.Reset(); - _eqdpCache.Reset(); - _estCache.Reset(); - _gmpCache.Reset(); - _cmpCache.Reset(); - _imcCache.Reset(_collection); - _manipulations.Clear(); - _globalEqpCache.Clear(); + Eqp.Reset(); + Eqdp.Reset(); + Est.Reset(); + Gmp.Reset(); + Rsp.Reset(); + Imc.Reset(); + GlobalEqp.Clear(); } public void Dispose() { - _manager.CharacterUtility.LoadingFinished -= ApplyStoredManipulations; - _eqpCache.Dispose(); - _eqdpCache.Dispose(); - _estCache.Dispose(); - _gmpCache.Dispose(); - _cmpCache.Dispose(); - _imcCache.Dispose(); - _manipulations.Clear(); + Eqp.Dispose(); + Eqdp.Dispose(); + Est.Dispose(); + Gmp.Dispose(); + Rsp.Dispose(); + Imc.Dispose(); } + public bool TryGetMod(IMetaIdentifier identifier, [NotNullWhen(true)] out IMod? mod) + { + mod = null; + return identifier switch + { + EqdpIdentifier i => Eqdp.TryGetValue(i, out var p) && Convert(p, out mod), + EqpIdentifier i => Eqp.TryGetValue(i, out var p) && Convert(p, out mod), + EstIdentifier i => Est.TryGetValue(i, out var p) && Convert(p, out mod), + GmpIdentifier i => Gmp.TryGetValue(i, out var p) && Convert(p, out mod), + ImcIdentifier i => Imc.TryGetValue(i, out var p) && Convert(p, out mod), + RspIdentifier i => Rsp.TryGetValue(i, out var p) && Convert(p, out mod), + GlobalEqpManipulation i => GlobalEqp.TryGetValue(i, out mod), + _ => false, + }; + + static bool Convert((IMod, T) pair, out IMod mod) + { + mod = pair.Item1; + return true; + } + } + + public bool RevertMod(IMetaIdentifier identifier, [NotNullWhen(true)] out IMod? mod) + => identifier switch + { + EqdpIdentifier i => Eqdp.RevertMod(i, out mod), + EqpIdentifier i => Eqp.RevertMod(i, out mod), + EstIdentifier i => Est.RevertMod(i, out mod), + GmpIdentifier i => Gmp.RevertMod(i, out mod), + ImcIdentifier i => Imc.RevertMod(i, out mod), + RspIdentifier i => Rsp.RevertMod(i, out mod), + GlobalEqpManipulation i => GlobalEqp.RevertMod(i, out mod), + _ => (mod = null) != null, + }; + + public bool ApplyMod(IMod mod, IMetaIdentifier identifier, object entry) + => identifier switch + { + EqdpIdentifier i when entry is EqdpEntry e => Eqdp.ApplyMod(mod, i, e), + EqdpIdentifier i when entry is EqdpEntryInternal e => Eqdp.ApplyMod(mod, i, e.ToEntry(i.Slot)), + EqpIdentifier i when entry is EqpEntry e => Eqp.ApplyMod(mod, i, e), + EqpIdentifier i when entry is EqpEntryInternal e => Eqp.ApplyMod(mod, i, e.ToEntry(i.Slot)), + EstIdentifier i when entry is EstEntry e => Est.ApplyMod(mod, i, e), + GmpIdentifier i when entry is GmpEntry e => Gmp.ApplyMod(mod, i, e), + ImcIdentifier i when entry is ImcEntry e => Imc.ApplyMod(mod, i, e), + RspIdentifier i when entry is RspEntry e => Rsp.ApplyMod(mod, i, e), + GlobalEqpManipulation i => GlobalEqp.ApplyMod(mod, i), + _ => false, + }; + ~MetaCache() => Dispose(); - public bool ApplyMod(MetaManipulation manip, IMod mod) - { - lock (_manipulations) - { - if (_manipulations.ContainsKey(manip)) - _manipulations.Remove(manip); - - _manipulations[manip] = mod; - } - - if (manip.ManipulationType is MetaManipulation.Type.GlobalEqp) - return _globalEqpCache.Add(manip.GlobalEqp); - - if (!_manager.CharacterUtility.Ready) - return true; - - // Imc manipulations do not require character utility, - // but they do require the file space to be ready. - return manip.ManipulationType switch - { - MetaManipulation.Type.Eqp => _eqpCache.ApplyMod(_manager, manip.Eqp), - MetaManipulation.Type.Eqdp => _eqdpCache.ApplyMod(_manager, manip.Eqdp), - MetaManipulation.Type.Est => _estCache.ApplyMod(_manager, manip.Est), - MetaManipulation.Type.Gmp => _gmpCache.ApplyMod(_manager, manip.Gmp), - MetaManipulation.Type.Rsp => _cmpCache.ApplyMod(_manager, manip.Rsp), - MetaManipulation.Type.Imc => _imcCache.ApplyMod(_manager, _collection, manip.Imc), - MetaManipulation.Type.Unknown => false, - _ => false, - }; - } - - public bool RevertMod(MetaManipulation manip, [NotNullWhen(true)] out IMod? mod) - { - lock (_manipulations) - { - var ret = _manipulations.Remove(manip, out mod); - - if (manip.ManipulationType is MetaManipulation.Type.GlobalEqp) - return _globalEqpCache.Remove(manip.GlobalEqp); - - if (!_manager.CharacterUtility.Ready) - return ret; - } - - // Imc manipulations do not require character utility, - // but they do require the file space to be ready. - return manip.ManipulationType switch - { - MetaManipulation.Type.Eqp => _eqpCache.RevertMod(_manager, manip.Eqp), - MetaManipulation.Type.Eqdp => _eqdpCache.RevertMod(_manager, manip.Eqdp), - MetaManipulation.Type.Est => _estCache.RevertMod(_manager, manip.Est), - MetaManipulation.Type.Gmp => _gmpCache.RevertMod(_manager, manip.Gmp), - MetaManipulation.Type.Rsp => _cmpCache.RevertMod(_manager, manip.Rsp), - MetaManipulation.Type.Imc => _imcCache.RevertMod(_manager, _collection, manip.Imc), - MetaManipulation.Type.Unknown => false, - _ => false, - }; - } - /// Set a single file. public void SetFile(MetaIndex metaIndex) { switch (metaIndex) { case MetaIndex.Eqp: - _eqpCache.SetFiles(_manager); + Eqp.SetFiles(); break; case MetaIndex.Gmp: - _gmpCache.SetFiles(_manager); + Gmp.SetFiles(); break; case MetaIndex.HumanCmp: - _cmpCache.SetFiles(_manager); + Rsp.SetFiles(); break; case MetaIndex.FaceEst: case MetaIndex.HairEst: case MetaIndex.HeadEst: case MetaIndex.BodyEst: - _estCache.SetFile(_manager, metaIndex); + Est.SetFile(metaIndex); break; default: - _eqdpCache.SetFile(_manager, metaIndex); + Eqdp.SetFile(metaIndex); break; } } /// Set the currently relevant IMC files for the collection cache. public void SetImcFiles(bool fromFullCompute) - => _imcCache.SetFiles(_collection, fromFullCompute); + => Imc.SetFiles(fromFullCompute); public MetaList.MetaReverter TemporarilySetEqpFile() - => _eqpCache.TemporarilySetFiles(_manager); + => Eqp.TemporarilySetFile(); public MetaList.MetaReverter? TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) - => _eqdpCache.TemporarilySetFiles(_manager, genderRace, accessory); + => Eqdp.TemporarilySetFile(genderRace, accessory); public MetaList.MetaReverter TemporarilySetGmpFile() - => _gmpCache.TemporarilySetFiles(_manager); + => Gmp.TemporarilySetFile(); public MetaList.MetaReverter TemporarilySetCmpFile() - => _cmpCache.TemporarilySetFiles(_manager); + => Rsp.TemporarilySetFile(); public MetaList.MetaReverter TemporarilySetEstFile(EstType type) - => _estCache.TemporarilySetFiles(_manager, type); + => Est.TemporarilySetFiles(type); public unsafe EqpEntry ApplyGlobalEqp(EqpEntry baseEntry, CharacterArmor* armor) - => _globalEqpCache.Apply(baseEntry, armor); + => GlobalEqp.Apply(baseEntry, armor); /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) - => _imcCache.GetImcFile(path, out file); + => Imc.GetFile(path, out file); internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, PrimaryId primaryId) { - var eqdpFile = _eqdpCache.EqdpFile(race, accessory); + var eqdpFile = Eqdp.EqdpFile(race, accessory); if (eqdpFile != null) return primaryId.Id < eqdpFile.Count ? eqdpFile[primaryId] : default; - return Meta.Files.ExpandedEqdpFile.GetDefault(_manager, race, accessory, primaryId); + return Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId); } internal EstEntry GetEstEntry(EstType type, GenderRace genderRace, PrimaryId primaryId) - => _estCache.GetEstEntry(_manager, type, genderRace, primaryId); - - /// Use this when CharacterUtility becomes ready. - private void ApplyStoredManipulations() - { - if (!_manager.CharacterUtility.Ready) - return; - - var loaded = 0; - lock (_manipulations) - { - foreach (var manip in Manipulations) - { - loaded += manip.ManipulationType switch - { - MetaManipulation.Type.Eqp => _eqpCache.ApplyMod(_manager, manip.Eqp), - MetaManipulation.Type.Eqdp => _eqdpCache.ApplyMod(_manager, manip.Eqdp), - MetaManipulation.Type.Est => _estCache.ApplyMod(_manager, manip.Est), - MetaManipulation.Type.Gmp => _gmpCache.ApplyMod(_manager, manip.Gmp), - MetaManipulation.Type.Rsp => _cmpCache.ApplyMod(_manager, manip.Rsp), - MetaManipulation.Type.Imc => _imcCache.ApplyMod(_manager, _collection, manip.Imc), - MetaManipulation.Type.GlobalEqp => false, - MetaManipulation.Type.Unknown => false, - _ => false, - } - ? 1 - : 0; - } - } - - _manager.ApplyDefaultFiles(_collection); - _manager.CharacterUtility.LoadingFinished -= ApplyStoredManipulations; - Penumbra.Log.Debug($"{_collection.AnonymizedName}: Loaded {loaded} delayed meta manipulations."); - } + => Est.GetEstEntry(new EstIdentifier(primaryId, type, genderRace)); } diff --git a/Penumbra/Collections/Cache/RspCache.cs b/Penumbra/Collections/Cache/RspCache.cs new file mode 100644 index 00000000..3889d6f1 --- /dev/null +++ b/Penumbra/Collections/Cache/RspCache.cs @@ -0,0 +1,81 @@ +using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Collections.Cache; + +public sealed class RspCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) +{ + private CmpFile? _cmpFile; + + public override void SetFiles() + => Manager.SetFile(_cmpFile, MetaIndex.HumanCmp); + + public override void ResetFiles() + => Manager.SetFile(null, MetaIndex.HumanCmp); + + protected override void IncorporateChangesInternal() + { + if (GetFile() is not { } file) + return; + + foreach (var (identifier, (_, entry)) in this) + Apply(file, identifier, entry); + + Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed RSP manipulations."); + } + + public MetaList.MetaReverter TemporarilySetFile() + => Manager.TemporarilySetFile(_cmpFile, MetaIndex.HumanCmp); + + public override void Reset() + { + if (_cmpFile == null) + return; + + _cmpFile.Reset(Keys.Select(identifier => (identifier.SubRace, identifier.Attribute))); + Clear(); + } + + protected override void ApplyModInternal(RspIdentifier identifier, RspEntry entry) + { + if (GetFile() is { } file) + Apply(file, identifier, entry); + } + + protected override void RevertModInternal(RspIdentifier identifier) + { + if (GetFile() is { } file) + Apply(file, identifier, CmpFile.GetDefault(Manager, identifier.SubRace, identifier.Attribute)); + } + + public static bool Apply(CmpFile file, RspIdentifier identifier, RspEntry entry) + { + var value = file[identifier.SubRace, identifier.Attribute]; + if (value == entry) + return false; + + file[identifier.SubRace, identifier.Attribute] = entry; + return true; + } + + protected override void Dispose(bool _) + { + _cmpFile?.Dispose(); + _cmpFile = null; + Clear(); + } + + private CmpFile? GetFile() + { + if (_cmpFile != null) + return _cmpFile; + + if (!Manager.CharacterUtility.Ready) + return null; + + return _cmpFile = new CmpFile(Manager); + } +} diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index fdd28ef1..9fa77784 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -37,7 +37,8 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect _tasks.Clear(); } - public Task ExportToGltf(in ExportConfig config, MdlFile mdl, IEnumerable sklbPaths, Func read, string outputPath) + public Task ExportToGltf(in ExportConfig config, MdlFile mdl, IEnumerable sklbPaths, Func read, + string outputPath) => EnqueueWithResult( new ExportToGltfAction(this, config, mdl, sklbPaths, read, outputPath), action => action.Notifier @@ -52,7 +53,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect /// Try to find the .sklb paths for a .mdl file. /// .mdl file to look up the skeletons for. /// Modified extra skeleton template parameters. - public string[] ResolveSklbsForMdl(string mdlPath, EstManipulation[] estManipulations) + public string[] ResolveSklbsForMdl(string mdlPath, KeyValuePair[] estManipulations) { var info = parser.GetFileInfo(mdlPath); if (info.FileType is not FileType.Model) @@ -81,20 +82,18 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect }; } - private string[] ResolveEstSkeleton(EstType type, GameObjectInfo info, EstManipulation[] estManipulations) + private string[] ResolveEstSkeleton(EstType type, GameObjectInfo info, KeyValuePair[] estManipulations) { // Try to find an EST entry from the manipulations provided. - var (gender, race) = info.GenderRace.Split(); var modEst = estManipulations - .FirstOrNull(est => - est.Gender == gender - && est.Race == race - && est.Slot == type - && est.SetId == info.PrimaryId + .FirstOrNull( + est => est.Key.GenderRace == info.GenderRace + && est.Key.Slot == type + && est.Key.SetId == info.PrimaryId ); // Try to use an entry from provided manipulations, falling back to the current collection. - var targetId = modEst?.Entry + var targetId = modEst?.Value ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) ?? EstEntry.Zero; @@ -102,7 +101,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect if (targetId == EstEntry.Zero) return []; - return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, EstManipulation.ToName(type), targetId.AsId)]; + return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, type.ToName(), targetId.AsId)]; } /// Try to resolve the absolute path to a .mtrl from the potentially-partial path provided by a model. @@ -250,9 +249,11 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect var path = manager.ResolveMtrlPath(relativePath, notifier); if (path == null) return null; + var bytes = read(path); if (bytes == null) return null; + var mtrl = new MtrlFile(bytes); return new MaterialExporter.Material diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index f6157747..1f970dfe 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -13,15 +13,15 @@ public partial class TexToolsMeta private void DeserializeEqpEntry(MetaFileInfo metaFileInfo, byte[]? data) { // Eqp can only be valid for equipment. - if (data == null || !metaFileInfo.EquipSlot.IsEquipment()) + var mask = Eqp.Mask(metaFileInfo.EquipSlot); + if (data == null || mask == 0) return; - var value = Eqp.FromSlotAndBytes(metaFileInfo.EquipSlot, data); - var def = new EqpManipulation(ExpandedEqpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId), metaFileInfo.EquipSlot, - metaFileInfo.PrimaryId); - var manip = new EqpManipulation(value, metaFileInfo.EquipSlot, metaFileInfo.PrimaryId); - if (_keepDefault || def.Entry != manip.Entry) - MetaManipulations.Add(manip); + var identifier = new EqpIdentifier(metaFileInfo.PrimaryId, metaFileInfo.EquipSlot); + var value = Eqp.FromSlotAndBytes(metaFileInfo.EquipSlot, data) & mask; + var def = ExpandedEqpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId) & mask; + if (_keepDefault || def != value) + MetaManipulations.TryAdd(identifier, value); } // Deserialize and check Eqdp Entries and add them to the list if they are non-default. @@ -40,14 +40,12 @@ public partial class TexToolsMeta if (!gr.IsValid() || !metaFileInfo.EquipSlot.IsEquipment() && !metaFileInfo.EquipSlot.IsAccessory()) continue; - var value = Eqdp.FromSlotAndBits(metaFileInfo.EquipSlot, (byteValue & 1) == 1, (byteValue & 2) == 2); - var def = new EqdpManipulation( - ExpandedEqdpFile.GetDefault(_metaFileManager, gr, metaFileInfo.EquipSlot.IsAccessory(), metaFileInfo.PrimaryId), - metaFileInfo.EquipSlot, - gr.Split().Item1, gr.Split().Item2, metaFileInfo.PrimaryId); - var manip = new EqdpManipulation(value, metaFileInfo.EquipSlot, gr.Split().Item1, gr.Split().Item2, metaFileInfo.PrimaryId); - if (_keepDefault || def.Entry != manip.Entry) - MetaManipulations.Add(manip); + var identifier = new EqdpIdentifier(metaFileInfo.PrimaryId, metaFileInfo.EquipSlot, gr); + var mask = Eqdp.Mask(metaFileInfo.EquipSlot); + var value = Eqdp.FromSlotAndBits(metaFileInfo.EquipSlot, (byteValue & 1) == 1, (byteValue & 2) == 2) & mask; + var def = ExpandedEqdpFile.GetDefault(_metaFileManager, gr, metaFileInfo.EquipSlot.IsAccessory(), metaFileInfo.PrimaryId) & mask; + if (_keepDefault || def != value) + MetaManipulations.TryAdd(identifier, value); } } @@ -57,10 +55,10 @@ public partial class TexToolsMeta if (data == null) return; - var value = GmpEntry.FromTexToolsMeta(data.AsSpan(0, 5)); - var def = ExpandedGmpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId); + var value = GmpEntry.FromTexToolsMeta(data.AsSpan(0, 5)); + var def = ExpandedGmpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId); if (_keepDefault || value != def) - MetaManipulations.Add(new GmpManipulation(value, metaFileInfo.PrimaryId)); + MetaManipulations.TryAdd(new GmpIdentifier(metaFileInfo.PrimaryId), value); } // Deserialize and check Est Entries and add them to the list if they are non-default. @@ -74,7 +72,7 @@ public partial class TexToolsMeta for (var i = 0; i < num; ++i) { var gr = (GenderRace)reader.ReadUInt16(); - var id = reader.ReadUInt16(); + var id = (PrimaryId)reader.ReadUInt16(); var value = new EstEntry(reader.ReadUInt16()); var type = (metaFileInfo.SecondaryType, metaFileInfo.EquipSlot) switch { @@ -87,9 +85,10 @@ public partial class TexToolsMeta if (!gr.IsValid() || type == 0) continue; - var def = EstFile.GetDefault(_metaFileManager, type, gr, id); + var identifier = new EstIdentifier(id, type, gr); + var def = EstFile.GetDefault(_metaFileManager, type, gr, id); if (_keepDefault || def != value) - MetaManipulations.Add(new EstManipulation(gr.Split().Item1, gr.Split().Item2, type, id, value)); + MetaManipulations.TryAdd(identifier, value); } } @@ -107,20 +106,16 @@ public partial class TexToolsMeta ushort i = 0; try { - var manip = new ImcManipulation(metaFileInfo.PrimaryType, metaFileInfo.SecondaryType, metaFileInfo.PrimaryId, - metaFileInfo.SecondaryId, i, metaFileInfo.EquipSlot, - new ImcEntry()); - var def = new ImcFile(_metaFileManager, manip.Identifier); - var partIdx = ImcFile.PartIndex(manip.EquipSlot); // Gets turned to unknown for things without equip, and unknown turns to 0. + var identifier = new ImcIdentifier(metaFileInfo.PrimaryId, 0, metaFileInfo.PrimaryType, metaFileInfo.SecondaryId, + metaFileInfo.EquipSlot, metaFileInfo.SecondaryType); + var file = new ImcFile(_metaFileManager, identifier); + var partIdx = ImcFile.PartIndex(identifier.EquipSlot); // Gets turned to unknown for things without equip, and unknown turns to 0. foreach (var value in values) { - if (_keepDefault || !value.Equals(def.GetEntry(partIdx, (Variant)i))) - { - var imc = new ImcManipulation(manip.ObjectType, manip.BodySlot, manip.PrimaryId, manip.SecondaryId, i, manip.EquipSlot, - value); - if (imc.Validate(true)) - MetaManipulations.Add(imc); - } + identifier = identifier with { Variant = (Variant)i }; + var def = file.GetEntry(partIdx, (Variant)i); + if (_keepDefault || def != value && identifier.Validate()) + MetaManipulations.TryAdd(identifier, value); ++i; } diff --git a/Penumbra/Import/TexToolsMeta.Export.cs b/Penumbra/Import/TexToolsMeta.Export.cs index 4fb56df6..9cce60e3 100644 --- a/Penumbra/Import/TexToolsMeta.Export.cs +++ b/Penumbra/Import/TexToolsMeta.Export.cs @@ -1,3 +1,4 @@ +using Penumbra.Collections.Cache; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; @@ -8,7 +9,7 @@ namespace Penumbra.Import; public partial class TexToolsMeta { - public static void WriteTexToolsMeta(MetaFileManager manager, IEnumerable manipulations, DirectoryInfo basePath) + public static void WriteTexToolsMeta(MetaFileManager manager, MetaDictionary manipulations, DirectoryInfo basePath) { var files = ConvertToTexTools(manager, manipulations); @@ -27,49 +28,81 @@ public partial class TexToolsMeta } } - public static Dictionary ConvertToTexTools(MetaFileManager manager, IEnumerable manips) + public static Dictionary ConvertToTexTools(MetaFileManager manager, MetaDictionary manips) { var ret = new Dictionary(); - foreach (var group in manips.GroupBy(ManipToPath)) + foreach (var group in manips.Rsp.GroupBy(ManipToPath)) { if (group.Key.Length == 0) continue; - var bytes = group.Key.EndsWith(".rgsp") - ? WriteRgspFile(manager, group.Key, group) - : WriteMetaFile(manager, group.Key, group); + var bytes = WriteRgspFile(manager, group); if (bytes.Length == 0) continue; ret.Add(group.Key, bytes); } + foreach (var (file, dict) in SplitByFile(manips)) + { + var bytes = WriteMetaFile(manager, file, dict); + if (bytes.Length == 0) + continue; + + ret.Add(file, bytes); + } + return ret; } - private static byte[] WriteRgspFile(MetaFileManager manager, string path, IEnumerable manips) + private static Dictionary SplitByFile(MetaDictionary manips) { - var list = manips.GroupBy(m => m.Rsp.Attribute).ToDictionary(m => m.Key, m => m.Last().Rsp); + var ret = new Dictionary(); + foreach (var (identifier, key) in manips.Imc) + GetDict(ManipToPath(identifier)).TryAdd(identifier, key); + + foreach (var (identifier, key) in manips.Eqp) + GetDict(ManipToPath(identifier)).TryAdd(identifier, key); + + foreach (var (identifier, key) in manips.Eqdp) + GetDict(ManipToPath(identifier)).TryAdd(identifier, key); + + foreach (var (identifier, key) in manips.Est) + GetDict(ManipToPath(identifier)).TryAdd(identifier, key); + + foreach (var (identifier, key) in manips.Gmp) + GetDict(ManipToPath(identifier)).TryAdd(identifier, key); + + ret.Remove(string.Empty); + + return ret; + + MetaDictionary GetDict(string path) + { + if (!ret.TryGetValue(path, out var dict)) + { + dict = new MetaDictionary(); + ret.Add(path, dict); + } + + return dict; + } + } + + private static byte[] WriteRgspFile(MetaFileManager manager, IEnumerable> manips) + { + var list = manips.GroupBy(m => m.Key.Attribute).ToDictionary(g => g.Key, g => g.Last()); using var m = new MemoryStream(45); using var b = new BinaryWriter(m); // Version b.Write(byte.MaxValue); b.Write((ushort)2); - var race = list.First().Value.SubRace; - var gender = list.First().Value.Attribute.ToGender(); + var race = list.First().Value.Key.SubRace; + var gender = list.First().Value.Key.Attribute.ToGender(); b.Write((byte)(race - 1)); // offset by one due to Unknown b.Write((byte)(gender - 1)); // offset by one due to Unknown - void Add(params RspAttribute[] attributes) - { - foreach (var attribute in attributes) - { - var value = list.TryGetValue(attribute, out var tmp) ? tmp.Entry : CmpFile.GetDefault(manager, race, attribute); - b.Write(value.Value); - } - } - if (gender == Gender.Male) { Add(RspAttribute.MaleMinSize, RspAttribute.MaleMaxSize, RspAttribute.MaleMinTail, RspAttribute.MaleMaxTail); @@ -82,12 +115,24 @@ public partial class TexToolsMeta } return m.GetBuffer(); + + void Add(params RspAttribute[] attributes) + { + foreach (var attribute in attributes) + { + var value = list.TryGetValue(attribute, out var tmp) ? tmp.Value : CmpFile.GetDefault(manager, race, attribute); + b.Write(value.Value); + } + } } - private static byte[] WriteMetaFile(MetaFileManager manager, string path, IEnumerable manips) + private static byte[] WriteMetaFile(MetaFileManager manager, string path, MetaDictionary manips) { - var filteredManips = manips.GroupBy(m => m.ManipulationType).ToDictionary(p => p.Key, p => p.Select(x => x)); - + var headerCount = (manips.Imc.Count > 0 ? 1 : 0) + + (manips.Eqp.Count > 0 ? 1 : 0) + + (manips.Eqdp.Count > 0 ? 1 : 0) + + (manips.Est.Count > 0 ? 1 : 0) + + (manips.Gmp.Count > 0 ? 1 : 0); using var m = new MemoryStream(); using var b = new BinaryWriter(m); @@ -101,7 +146,7 @@ public partial class TexToolsMeta b.Write((byte)0); // Number of Headers - b.Write((uint)filteredManips.Count); + b.Write((uint)headerCount); // Current TT Size of Headers b.Write((uint)12); @@ -109,88 +154,44 @@ public partial class TexToolsMeta var headerStart = b.BaseStream.Position + 4; b.Write((uint)headerStart); - var offset = (uint)(b.BaseStream.Position + 12 * filteredManips.Count); - foreach (var (header, data) in filteredManips) - { - b.Write((uint)header); - b.Write(offset); - - var size = WriteData(manager, b, offset, header, data); - b.Write(size); - offset += size; - } + var offset = (uint)(b.BaseStream.Position + 12 * manips.Count); + offset += WriteData(manager, b, offset, manips.Imc); + offset += WriteData(b, offset, manips.Eqdp); + offset += WriteData(b, offset, manips.Eqp); + offset += WriteData(b, offset, manips.Est); + offset += WriteData(b, offset, manips.Gmp); return m.ToArray(); } - private static uint WriteData(MetaFileManager manager, BinaryWriter b, uint offset, MetaManipulation.Type type, - IEnumerable manips) + private static uint WriteData(MetaFileManager manager, BinaryWriter b, uint offset, IReadOnlyDictionary manips) { + if (manips.Count == 0) + return 0; + + b.Write((uint)MetaManipulationType.Imc); + b.Write(offset); + var oldPos = b.BaseStream.Position; b.Seek((int)offset, SeekOrigin.Begin); - switch (type) + var refIdentifier = manips.First().Key; + var baseFile = new ImcFile(manager, refIdentifier); + foreach (var (identifier, entry) in manips) + ImcCache.Apply(baseFile, identifier, entry); + + var partIdx = refIdentifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory + ? ImcFile.PartIndex(refIdentifier.EquipSlot) + : 0; + + for (var i = 0; i <= baseFile.Count; ++i) { - case MetaManipulation.Type.Imc: - var allManips = manips.ToList(); - var baseFile = new ImcFile(manager, allManips[0].Imc.Identifier); - foreach (var manip in allManips) - manip.Imc.Apply(baseFile); - - var partIdx = allManips[0].Imc.ObjectType is ObjectType.Equipment or ObjectType.Accessory - ? ImcFile.PartIndex(allManips[0].Imc.EquipSlot) - : 0; - - for (var i = 0; i <= baseFile.Count; ++i) - { - var entry = baseFile.GetEntry(partIdx, (Variant)i); - b.Write(entry.MaterialId); - b.Write(entry.DecalId); - b.Write(entry.AttributeAndSound); - b.Write(entry.VfxId); - b.Write(entry.MaterialAnimationId); - } - - break; - case MetaManipulation.Type.Eqdp: - foreach (var manip in manips) - { - b.Write((uint)Names.CombinedRace(manip.Eqdp.Gender, manip.Eqdp.Race)); - var entry = (byte)(((uint)manip.Eqdp.Entry >> Eqdp.Offset(manip.Eqdp.Slot)) & 0x03); - b.Write(entry); - } - - break; - case MetaManipulation.Type.Eqp: - foreach (var manip in manips) - { - var bytes = BitConverter.GetBytes((ulong)manip.Eqp.Entry); - var (numBytes, byteOffset) = Eqp.BytesAndOffset(manip.Eqp.Slot); - for (var i = byteOffset; i < numBytes + byteOffset; ++i) - b.Write(bytes[i]); - } - - break; - case MetaManipulation.Type.Est: - foreach (var manip in manips) - { - b.Write((ushort)Names.CombinedRace(manip.Est.Gender, manip.Est.Race)); - b.Write(manip.Est.SetId.Id); - b.Write(manip.Est.Entry.Value); - } - - break; - case MetaManipulation.Type.Gmp: - foreach (var manip in manips) - { - b.Write((uint)manip.Gmp.Entry.Value); - b.Write(manip.Gmp.Entry.UnknownTotal); - } - - break; - case MetaManipulation.Type.GlobalEqp: - // Not Supported - break; + var entry = baseFile.GetEntry(partIdx, (Variant)i); + b.Write(entry.MaterialId); + b.Write(entry.DecalId); + b.Write(entry.AttributeAndSound); + b.Write(entry.VfxId); + b.Write(entry.MaterialAnimationId); } var size = b.BaseStream.Position - offset; @@ -198,19 +199,98 @@ public partial class TexToolsMeta return (uint)size; } - private static string ManipToPath(MetaManipulation manip) - => manip.ManipulationType switch - { - MetaManipulation.Type.Imc => ManipToPath(manip.Imc), - MetaManipulation.Type.Eqdp => ManipToPath(manip.Eqdp), - MetaManipulation.Type.Eqp => ManipToPath(manip.Eqp), - MetaManipulation.Type.Est => ManipToPath(manip.Est), - MetaManipulation.Type.Gmp => ManipToPath(manip.Gmp), - MetaManipulation.Type.Rsp => ManipToPath(manip.Rsp), - _ => string.Empty, - }; + private static uint WriteData(BinaryWriter b, uint offset, IReadOnlyDictionary manips) + { + if (manips.Count == 0) + return 0; - private static string ManipToPath(ImcManipulation manip) + b.Write((uint)MetaManipulationType.Eqdp); + b.Write(offset); + + var oldPos = b.BaseStream.Position; + b.Seek((int)offset, SeekOrigin.Begin); + + foreach (var (identifier, entry) in manips) + { + b.Write((uint)identifier.GenderRace); + b.Write(entry.AsByte); + } + + var size = b.BaseStream.Position - offset; + b.Seek((int)oldPos, SeekOrigin.Begin); + return (uint)size; + } + + private static uint WriteData(BinaryWriter b, uint offset, + IReadOnlyDictionary manips) + { + if (manips.Count == 0) + return 0; + + b.Write((uint)MetaManipulationType.Imc); + b.Write(offset); + + var oldPos = b.BaseStream.Position; + b.Seek((int)offset, SeekOrigin.Begin); + + foreach (var (identifier, entry) in manips) + { + var numBytes = Eqp.BytesAndOffset(identifier.Slot).Item1; + for (var i = 0; i < numBytes; ++i) + b.Write((byte)(entry.Value >> (8 * i))); + } + + var size = b.BaseStream.Position - offset; + b.Seek((int)oldPos, SeekOrigin.Begin); + return (uint)size; + } + + private static uint WriteData(BinaryWriter b, uint offset, IReadOnlyDictionary manips) + { + if (manips.Count == 0) + return 0; + + b.Write((uint)MetaManipulationType.Imc); + b.Write(offset); + + var oldPos = b.BaseStream.Position; + b.Seek((int)offset, SeekOrigin.Begin); + + foreach (var (identifier, entry) in manips) + { + b.Write((ushort)identifier.GenderRace); + b.Write(identifier.SetId.Id); + b.Write(entry.Value); + } + + var size = b.BaseStream.Position - offset; + b.Seek((int)oldPos, SeekOrigin.Begin); + return (uint)size; + } + + private static uint WriteData(BinaryWriter b, uint offset, IReadOnlyDictionary manips) + { + if (manips.Count == 0) + return 0; + + b.Write((uint)MetaManipulationType.Imc); + b.Write(offset); + + var oldPos = b.BaseStream.Position; + b.Seek((int)offset, SeekOrigin.Begin); + + foreach (var entry in manips.Values) + { + b.Write((uint)entry.Value); + b.Write(entry.UnknownTotal); + } + + var size = b.BaseStream.Position - offset; + b.Seek((int)oldPos, SeekOrigin.Begin); + return (uint)size; + } + + private static string ManipToPath(ImcIdentifier manip) { var path = manip.GamePath().ToString(); var replacement = manip.ObjectType switch @@ -224,33 +304,33 @@ public partial class TexToolsMeta return path.Replace(".imc", replacement); } - private static string ManipToPath(EqdpManipulation manip) + private static string ManipToPath(EqdpIdentifier manip) => manip.Slot.IsAccessory() - ? $"chara/accessory/a{manip.SetId:D4}/a{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta" - : $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta"; + ? $"chara/accessory/a{manip.SetId.Id:D4}/a{manip.SetId.Id:D4}_{manip.Slot.ToSuffix()}.meta" + : $"chara/equipment/e{manip.SetId.Id:D4}/e{manip.SetId.Id:D4}_{manip.Slot.ToSuffix()}.meta"; - private static string ManipToPath(EqpManipulation manip) + private static string ManipToPath(EqpIdentifier manip) => manip.Slot.IsAccessory() - ? $"chara/accessory/a{manip.SetId:D4}/a{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta" - : $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{manip.Slot.ToSuffix()}.meta"; + ? $"chara/accessory/a{manip.SetId.Id:D4}/a{manip.SetId.Id:D4}_{manip.Slot.ToSuffix()}.meta" + : $"chara/equipment/e{manip.SetId.Id:D4}/e{manip.SetId.Id:D4}_{manip.Slot.ToSuffix()}.meta"; - private static string ManipToPath(EstManipulation manip) + private static string ManipToPath(EstIdentifier manip) { var raceCode = Names.CombinedRace(manip.Gender, manip.Race).ToRaceCode(); return manip.Slot switch { - EstType.Hair => $"chara/human/c{raceCode}/obj/hair/h{manip.SetId:D4}/c{raceCode}h{manip.SetId:D4}_hir.meta", - EstType.Face => $"chara/human/c{raceCode}/obj/face/h{manip.SetId:D4}/c{raceCode}f{manip.SetId:D4}_fac.meta", - EstType.Body => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Body.ToSuffix()}.meta", - EstType.Head => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Head.ToSuffix()}.meta", - _ => throw new ArgumentOutOfRangeException(), + EstType.Hair => $"chara/human/c{raceCode}/obj/hair/h{manip.SetId.Id:D4}/c{raceCode}h{manip.SetId.Id:D4}_hir.meta", + EstType.Face => $"chara/human/c{raceCode}/obj/face/h{manip.SetId.Id:D4}/c{raceCode}f{manip.SetId.Id:D4}_fac.meta", + EstType.Body => $"chara/equipment/e{manip.SetId.Id:D4}/e{manip.SetId.Id:D4}_{EquipSlot.Body.ToSuffix()}.meta", + EstType.Head => $"chara/equipment/e{manip.SetId.Id:D4}/e{manip.SetId.Id:D4}_{EquipSlot.Head.ToSuffix()}.meta", + _ => throw new ArgumentOutOfRangeException(), }; } - private static string ManipToPath(GmpManipulation manip) - => $"chara/equipment/e{manip.SetId:D4}/e{manip.SetId:D4}_{EquipSlot.Head.ToSuffix()}.meta"; + private static string ManipToPath(GmpIdentifier manip) + => $"chara/equipment/e{manip.SetId.Id:D4}/e{manip.SetId.Id:D4}_{EquipSlot.Head.ToSuffix()}.meta"; - private static string ManipToPath(RspManipulation manip) - => $"chara/xls/charamake/rgsp/{(int)manip.SubRace - 1}-{(int)manip.Attribute.ToGender() - 1}.rgsp"; + private static string ManipToPath(KeyValuePair manip) + => $"chara/xls/charamake/rgsp/{(int)manip.Key.SubRace - 1}-{(int)manip.Key.Attribute.ToGender() - 1}.rgsp"; } diff --git a/Penumbra/Import/TexToolsMeta.Rgsp.cs b/Penumbra/Import/TexToolsMeta.Rgsp.cs index 71b9165f..7b0bb5a8 100644 --- a/Penumbra/Import/TexToolsMeta.Rgsp.cs +++ b/Penumbra/Import/TexToolsMeta.Rgsp.cs @@ -42,14 +42,6 @@ public partial class TexToolsMeta return Invalid; } - // Add the given values to the manipulations if they are not default. - void Add(RspAttribute attribute, float value) - { - var def = CmpFile.GetDefault(manager, subRace, attribute); - if (keepDefault || value != def.Value) - ret.MetaManipulations.Add(new RspManipulation(subRace, attribute, new RspEntry(value))); - } - if (gender == 1) { Add(RspAttribute.FemaleMinSize, br.ReadSingle()); @@ -73,5 +65,14 @@ public partial class TexToolsMeta } return ret; + + // Add the given values to the manipulations if they are not default. + void Add(RspAttribute attribute, float value) + { + var identifier = new RspIdentifier(subRace, attribute); + var def = CmpFile.GetDefault(manager, subRace, attribute); + if (keepDefault || value != def.Value) + ret.MetaManipulations.TryAdd(identifier, new RspEntry(value)); + } } } diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index 25e00bd7..c4a8e81f 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -1,4 +1,3 @@ -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.Import.Structs; using Penumbra.Meta; @@ -22,10 +21,10 @@ public partial class TexToolsMeta public static readonly TexToolsMeta Invalid = new(null!, string.Empty, 0); // The info class determines the files or table locations the changes need to apply to from the filename. - public readonly uint Version; - public readonly string FilePath; - public readonly List MetaManipulations = new(); - private readonly bool _keepDefault = false; + public readonly uint Version; + public readonly string FilePath; + public readonly MetaDictionary MetaManipulations = new(); + private readonly bool _keepDefault; private readonly MetaFileManager _metaFileManager; @@ -44,18 +43,18 @@ public partial class TexToolsMeta var headerStart = reader.ReadUInt32(); reader.BaseStream.Seek(headerStart, SeekOrigin.Begin); - List<(MetaManipulation.Type type, uint offset, int size)> entries = []; + List<(MetaManipulationType type, uint offset, int size)> entries = []; for (var i = 0; i < numHeaders; ++i) { var currentOffset = reader.BaseStream.Position; - var type = (MetaManipulation.Type)reader.ReadUInt32(); + var type = (MetaManipulationType)reader.ReadUInt32(); var offset = reader.ReadUInt32(); var size = reader.ReadInt32(); entries.Add((type, offset, size)); reader.BaseStream.Seek(currentOffset + headerSize, SeekOrigin.Begin); } - byte[]? ReadEntry(MetaManipulation.Type type) + byte[]? ReadEntry(MetaManipulationType type) { var idx = entries.FindIndex(t => t.type == type); if (idx < 0) @@ -65,11 +64,11 @@ public partial class TexToolsMeta return reader.ReadBytes(entries[idx].size); } - DeserializeEqpEntry(metaInfo, ReadEntry(MetaManipulation.Type.Eqp)); - DeserializeGmpEntry(metaInfo, ReadEntry(MetaManipulation.Type.Gmp)); - DeserializeEqdpEntries(metaInfo, ReadEntry(MetaManipulation.Type.Eqdp)); - DeserializeEstEntries(metaInfo, ReadEntry(MetaManipulation.Type.Est)); - DeserializeImcEntries(metaInfo, ReadEntry(MetaManipulation.Type.Imc)); + DeserializeEqpEntry(metaInfo, ReadEntry(MetaManipulationType.Eqp)); + DeserializeGmpEntry(metaInfo, ReadEntry(MetaManipulationType.Gmp)); + DeserializeEqdpEntries(metaInfo, ReadEntry(MetaManipulationType.Eqdp)); + DeserializeEstEntries(metaInfo, ReadEntry(MetaManipulationType.Est)); + DeserializeImcEntries(metaInfo, ReadEntry(MetaManipulationType.Imc)); } catch (Exception e) { diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index b42571ac..bc474952 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,7 +1,6 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.UI.Agent; -using Microsoft.VisualBasic; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 2b87e688..4dfefd96 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -273,7 +273,7 @@ internal partial record ResolveContext { var metaCache = Global.Collection.MetaCache; var skeletonSet = metaCache?.GetEstEntry(type, raceCode, primary) ?? default; - return (raceCode, EstManipulation.ToName(type), skeletonSet.AsId); + return (raceCode, type.ToName(), skeletonSet.AsId); } private unsafe Utf8GamePath ResolveSkeletonPathNative(uint partialSkeletonIndex) diff --git a/Penumbra/Meta/ImcChecker.cs b/Penumbra/Meta/ImcChecker.cs index 650919a3..751113a0 100644 --- a/Penumbra/Meta/ImcChecker.cs +++ b/Penumbra/Meta/ImcChecker.cs @@ -51,10 +51,6 @@ public class ImcChecker return entry; } - public CachedEntry GetDefaultEntry(ImcManipulation imcManip, bool storeCache) - => GetDefaultEntry(new ImcIdentifier(imcManip.PrimaryId, imcManip.Variant, imcManip.ObjectType, imcManip.SecondaryId.Id, - imcManip.EquipSlot, imcManip.BodySlot), storeCache); - private static ImcFile? GetFile(ImcIdentifier identifier) { if (_dataManager == null) diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs index 6306f419..3f856bd2 100644 --- a/Penumbra/Meta/Manipulations/Eqdp.cs +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -69,10 +69,16 @@ public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, Ge jObj["Slot"] = Slot.ToString(); return jObj; } + + public MetaManipulationType Type + => MetaManipulationType.Eqdp; } public readonly record struct EqdpEntryInternal(bool Material, bool Model) { + public byte AsByte + => (byte)(Material ? Model ? 3 : 1 : Model ? 2 : 0); + private EqdpEntryInternal((bool, bool) val) : this(val.Item1, val.Item2) { } @@ -83,4 +89,7 @@ public readonly record struct EqdpEntryInternal(bool Material, bool Model) public EqdpEntry ToEntry(EquipSlot slot) => Eqdp.FromSlotAndBits(slot, Material, Model); + + public override string ToString() + => $"Material: {Material}, Model: {Model}"; } diff --git a/Penumbra/Meta/Manipulations/EqdpManipulation.cs b/Penumbra/Meta/Manipulations/EqdpManipulation.cs deleted file mode 100644 index 8c5f27e5..00000000 --- a/Penumbra/Meta/Manipulations/EqdpManipulation.cs +++ /dev/null @@ -1,110 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; - -namespace Penumbra.Meta.Manipulations; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct EqdpManipulation(EqdpIdentifier identifier, EqdpEntry entry) : IMetaManipulation -{ - [JsonIgnore] - public EqdpIdentifier Identifier { get; } = identifier; - - public EqdpEntry Entry { get; } = entry; - - [JsonConverter(typeof(StringEnumConverter))] - public Gender Gender - => Identifier.Gender; - - [JsonConverter(typeof(StringEnumConverter))] - public ModelRace Race - => Identifier.Race; - - public PrimaryId SetId - => Identifier.SetId; - - [JsonConverter(typeof(StringEnumConverter))] - public EquipSlot Slot - => Identifier.Slot; - - [JsonConstructor] - public EqdpManipulation(EqdpEntry entry, EquipSlot slot, Gender gender, ModelRace race, PrimaryId setId) - : this(new EqdpIdentifier(setId, slot, Names.CombinedRace(gender, race)), Eqdp.Mask(slot) & entry) - { } - - public EqdpManipulation Copy(EqdpManipulation entry) - { - if (entry.Slot != Slot) - { - var (bit1, bit2) = entry.Entry.ToBits(entry.Slot); - return new EqdpManipulation(Identifier, Eqdp.FromSlotAndBits(Slot, bit1, bit2)); - } - - return new EqdpManipulation(Identifier, entry.Entry); - } - - public EqdpManipulation Copy(EqdpEntry entry) - => new(entry, Slot, Gender, Race, SetId); - - public override string ToString() - => $"Eqdp - {SetId} - {Slot} - {Race.ToName()} - {Gender.ToName()}"; - - public bool Equals(EqdpManipulation other) - => Gender == other.Gender - && Race == other.Race - && SetId == other.SetId - && Slot == other.Slot; - - public override bool Equals(object? obj) - => obj is EqdpManipulation other && Equals(other); - - public override int GetHashCode() - => HashCode.Combine((int)Gender, (int)Race, SetId, (int)Slot); - - public int CompareTo(EqdpManipulation other) - { - var r = Race.CompareTo(other.Race); - if (r != 0) - return r; - - var g = Gender.CompareTo(other.Gender); - if (g != 0) - return g; - - var set = SetId.Id.CompareTo(other.SetId.Id); - return set != 0 ? set : Slot.CompareTo(other.Slot); - } - - public MetaIndex FileIndex() - => CharacterUtilityData.EqdpIdx(Names.CombinedRace(Gender, Race), Slot.IsAccessory()); - - public bool Apply(ExpandedEqdpFile file) - { - var entry = file[SetId]; - var mask = Eqdp.Mask(Slot); - if ((entry & mask) == Entry) - return false; - - file[SetId] = (entry & ~mask) | Entry; - return true; - } - - public bool Validate() - { - var mask = Eqdp.Mask(Slot); - if (mask == 0) - return false; - - if ((mask & Entry) != Entry) - return false; - - if (FileIndex() == (MetaIndex)(-1)) - return false; - - // No check for set id. - return true; - } -} diff --git a/Penumbra/Meta/Manipulations/Eqp.cs b/Penumbra/Meta/Manipulations/Eqp.cs index 572dc203..ec4dd6e7 100644 --- a/Penumbra/Meta/Manipulations/Eqp.cs +++ b/Penumbra/Meta/Manipulations/Eqp.cs @@ -50,6 +50,9 @@ public readonly record struct EqpIdentifier(PrimaryId SetId, EquipSlot Slot) : I jObj["Slot"] = Slot.ToString(); return jObj; } + + public MetaManipulationType Type + => MetaManipulationType.Eqp; } public readonly record struct EqpEntryInternal(uint Value) diff --git a/Penumbra/Meta/Manipulations/EqpManipulation.cs b/Penumbra/Meta/Manipulations/EqpManipulation.cs deleted file mode 100644 index eef21d12..00000000 --- a/Penumbra/Meta/Manipulations/EqpManipulation.cs +++ /dev/null @@ -1,80 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; -using Penumbra.Util; - -namespace Penumbra.Meta.Manipulations; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct EqpManipulation(EqpIdentifier identifier, EqpEntry entry) : IMetaManipulation -{ - [JsonIgnore] - public EqpIdentifier Identifier { get; } = identifier; - - [JsonConverter(typeof(ForceNumericFlagEnumConverter))] - public EqpEntry Entry { get; } = entry; - - public PrimaryId SetId - => Identifier.SetId; - - [JsonConverter(typeof(StringEnumConverter))] - public EquipSlot Slot - => Identifier.Slot; - - [JsonConstructor] - public EqpManipulation(EqpEntry entry, EquipSlot slot, PrimaryId setId) - : this(new EqpIdentifier(setId, slot), Eqp.Mask(slot) & entry) - { } - - public EqpManipulation Copy(EqpEntry entry) - => new(Identifier, entry); - - public override string ToString() - => $"Eqp - {SetId} - {Slot}"; - - public bool Equals(EqpManipulation other) - => Slot == other.Slot - && SetId == other.SetId; - - public override bool Equals(object? obj) - => obj is EqpManipulation other && Equals(other); - - public override int GetHashCode() - => HashCode.Combine((int)Slot, SetId); - - public int CompareTo(EqpManipulation other) - { - var set = SetId.Id.CompareTo(other.SetId.Id); - return set != 0 ? set : Slot.CompareTo(other.Slot); - } - - public MetaIndex FileIndex() - => MetaIndex.Eqp; - - public bool Apply(ExpandedEqpFile file) - { - var entry = file[SetId]; - var mask = Eqp.Mask(Slot); - if ((entry & mask) == Entry) - return false; - - file[SetId] = (entry & ~mask) | Entry; - return true; - } - - public bool Validate() - { - var mask = Eqp.Mask(Slot); - if (mask == 0) - return false; - if ((Entry & mask) != Entry) - return false; - - // No check for set id. - - return true; - } -} diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs index 9f878f97..2955dba4 100644 --- a/Penumbra/Meta/Manipulations/Est.cs +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -91,6 +91,9 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende jObj["Slot"] = Slot.ToString(); return jObj; } + + public MetaManipulationType Type + => MetaManipulationType.Est; } [JsonConverter(typeof(Converter))] @@ -111,3 +114,16 @@ public readonly record struct EstEntry(ushort Value) => new(serializer.Deserialize(reader)); } } + +public static class EstTypeExtension +{ + public static string ToName(this EstType type) + => type switch + { + EstType.Hair => "hair", + EstType.Face => "face", + EstType.Body => "top", + EstType.Head => "met", + _ => "unk", + }; +} diff --git a/Penumbra/Meta/Manipulations/EstManipulation.cs b/Penumbra/Meta/Manipulations/EstManipulation.cs deleted file mode 100644 index 09abbaa5..00000000 --- a/Penumbra/Meta/Manipulations/EstManipulation.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; - -namespace Penumbra.Meta.Manipulations; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct EstManipulation(EstIdentifier identifier, EstEntry entry) : IMetaManipulation -{ - public static string ToName(EstType type) - => type switch - { - EstType.Hair => "hair", - EstType.Face => "face", - EstType.Body => "top", - EstType.Head => "met", - _ => "unk", - }; - - [JsonIgnore] - public EstIdentifier Identifier { get; } = identifier; - public EstEntry Entry { get; } = entry; - - [JsonConverter(typeof(StringEnumConverter))] - public Gender Gender - => Identifier.Gender; - - [JsonConverter(typeof(StringEnumConverter))] - public ModelRace Race - => Identifier.Race; - - public PrimaryId SetId - => Identifier.SetId; - - [JsonConverter(typeof(StringEnumConverter))] - public EstType Slot - => Identifier.Slot; - - - [JsonConstructor] - public EstManipulation(Gender gender, ModelRace race, EstType slot, PrimaryId setId, EstEntry entry) - : this(new EstIdentifier(setId, slot, Names.CombinedRace(gender, race)), entry) - { } - - public EstManipulation Copy(EstEntry entry) - => new(Identifier, entry); - - - public override string ToString() - => $"Est - {SetId} - {Slot} - {Race.ToName()} {Gender.ToName()}"; - - public bool Equals(EstManipulation other) - => Gender == other.Gender - && Race == other.Race - && SetId == other.SetId - && Slot == other.Slot; - - public override bool Equals(object? obj) - => obj is EstManipulation other && Equals(other); - - public override int GetHashCode() - => HashCode.Combine((int)Gender, (int)Race, SetId, (int)Slot); - - public int CompareTo(EstManipulation other) - { - var r = Race.CompareTo(other.Race); - if (r != 0) - return r; - - var g = Gender.CompareTo(other.Gender); - if (g != 0) - return g; - - var s = Slot.CompareTo(other.Slot); - return s != 0 ? s : SetId.Id.CompareTo(other.SetId.Id); - } - - public MetaIndex FileIndex() - => (MetaIndex)Slot; - - public bool Apply(EstFile file) - { - return file.SetEntry(Names.CombinedRace(Gender, Race), SetId.Id, Entry) switch - { - EstFile.EstEntryChange.Unchanged => false, - EstFile.EstEntryChange.Changed => true, - EstFile.EstEntryChange.Added => true, - EstFile.EstEntryChange.Removed => true, - _ => throw new ArgumentOutOfRangeException(), - }; - } - - public bool Validate() - { - if (!Enum.IsDefined(Slot)) - return false; - if (Names.CombinedRace(Gender, Race) == GenderRace.Unknown) - return false; - - // No known check for set id or entry. - return true; - } -} - - diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs index 94c892e2..2b88d962 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -1,11 +1,12 @@ using Newtonsoft.Json.Linq; using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; namespace Penumbra.Meta.Manipulations; -public readonly struct GlobalEqpManipulation : IMetaManipulation, IMetaIdentifier +public readonly struct GlobalEqpManipulation : IMetaIdentifier { public GlobalEqpType Type { get; init; } public PrimaryId Condition { get; init; } @@ -70,8 +71,29 @@ public readonly struct GlobalEqpManipulation : IMetaManipulation $"Global EQP - {Type}{(Condition != 0 ? $" - {Condition.Id}" : string.Empty)}"; public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - { } + { + var path = Type switch + { + GlobalEqpType.DoNotHideEarrings => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.Ears), + GlobalEqpType.DoNotHideNecklace => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.Neck), + GlobalEqpType.DoNotHideBracelets => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.Wrists), + GlobalEqpType.DoNotHideRingR => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.RFinger), + GlobalEqpType.DoNotHideRingL => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.LFinger), + GlobalEqpType.DoNotHideHrothgarHats => string.Empty, + GlobalEqpType.DoNotHideVieraHats => string.Empty, + _ => string.Empty, + }; + if (path.Length > 0) + identifier.Identify(changedItems, path); + else if (Type is GlobalEqpType.DoNotHideVieraHats) + changedItems["All Hats for Viera"] = null; + else if (Type is GlobalEqpType.DoNotHideHrothgarHats) + changedItems["All Hats for Hrothgar"] = null; + } public MetaIndex FileIndex() => MetaIndex.Eqp; + + MetaManipulationType IMetaIdentifier.Type + => MetaManipulationType.GlobalEqp; } diff --git a/Penumbra/Meta/Manipulations/Gmp.cs b/Penumbra/Meta/Manipulations/Gmp.cs index 1b7c70ba..a6fcf58b 100644 --- a/Penumbra/Meta/Manipulations/Gmp.cs +++ b/Penumbra/Meta/Manipulations/Gmp.cs @@ -36,4 +36,7 @@ public readonly record struct GmpIdentifier(PrimaryId SetId) : IMetaIdentifier, jObj["SetId"] = SetId.Id.ToString(); return jObj; } + + public MetaManipulationType Type + => MetaManipulationType.Gmp; } diff --git a/Penumbra/Meta/Manipulations/GmpManipulation.cs b/Penumbra/Meta/Manipulations/GmpManipulation.cs deleted file mode 100644 index 431f6325..00000000 --- a/Penumbra/Meta/Manipulations/GmpManipulation.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Newtonsoft.Json; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; - -namespace Penumbra.Meta.Manipulations; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct GmpManipulation(GmpIdentifier identifier, GmpEntry entry) : IMetaManipulation -{ - [JsonIgnore] - public GmpIdentifier Identifier { get; } = identifier; - - public GmpEntry Entry { get; } = entry; - - public PrimaryId SetId - => Identifier.SetId; - - [JsonConstructor] - public GmpManipulation(GmpEntry entry, PrimaryId setId) - : this(new GmpIdentifier(setId), entry) - { } - - public GmpManipulation Copy(GmpEntry entry) - => new(Identifier, entry); - - public override string ToString() - => $"Gmp - {SetId}"; - - public bool Equals(GmpManipulation other) - => SetId == other.SetId; - - public override bool Equals(object? obj) - => obj is GmpManipulation other && Equals(other); - - public override int GetHashCode() - => SetId.GetHashCode(); - - public int CompareTo(GmpManipulation other) - => SetId.Id.CompareTo(other.SetId.Id); - - public MetaIndex FileIndex() - => MetaIndex.Gmp; - - public bool Apply(ExpandedGmpFile file) - { - var entry = file[SetId]; - if (entry == Entry) - return false; - - file[SetId] = Entry; - return true; - } - - public bool Validate() - // No known conditions. - => true; -} diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs index 4ad6bd3d..5707ffca 100644 --- a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -4,6 +4,18 @@ using Penumbra.Interop.Structs; namespace Penumbra.Meta.Manipulations; +public enum MetaManipulationType : byte +{ + Unknown = 0, + Imc = 1, + Eqdp = 2, + Eqp = 3, + Est = 4, + Gmp = 5, + Rsp = 6, + GlobalEqp = 7, +} + public interface IMetaIdentifier { public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); @@ -13,4 +25,8 @@ public interface IMetaIdentifier public bool Validate(); public JObject AddToJson(JObject jObj); + + public MetaManipulationType Type { get; } + + public string ToString(); } diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index 2a2f4c03..44c60942 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -27,9 +27,6 @@ public readonly record struct ImcIdentifier( : this(primaryId, variant, slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, BodySlot.Unknown) { } - public ImcManipulation ToManipulation(ImcEntry entry) - => new(ObjectType, BodySlot, PrimaryId, SecondaryId.Id, Variant.Id, EquipSlot, entry); - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => AddChangedItems(identifier, changedItems, false); @@ -193,4 +190,7 @@ public readonly record struct ImcIdentifier( jObj["BodySlot"] = BodySlot.ToString(); return jObj; } + + public MetaManipulationType Type + => MetaManipulationType.Imc; } diff --git a/Penumbra/Meta/Manipulations/ImcManipulation.cs b/Penumbra/Meta/Manipulations/ImcManipulation.cs deleted file mode 100644 index 5065a06e..00000000 --- a/Penumbra/Meta/Manipulations/ImcManipulation.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; -using Penumbra.String.Classes; - -namespace Penumbra.Meta.Manipulations; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct ImcManipulation : IMetaManipulation -{ - [JsonIgnore] - public ImcIdentifier Identifier { get; private init; } - - public ImcEntry Entry { get; private init; } - - - public PrimaryId PrimaryId - => Identifier.PrimaryId; - - public SecondaryId SecondaryId - => Identifier.SecondaryId; - - public Variant Variant - => Identifier.Variant; - - [JsonConverter(typeof(StringEnumConverter))] - public ObjectType ObjectType - => Identifier.ObjectType; - - [JsonConverter(typeof(StringEnumConverter))] - public EquipSlot EquipSlot - => Identifier.EquipSlot; - - [JsonConverter(typeof(StringEnumConverter))] - public BodySlot BodySlot - => Identifier.BodySlot; - - public ImcManipulation(EquipSlot equipSlot, ushort variant, PrimaryId primaryId, ImcEntry entry) - : this(new ImcIdentifier(equipSlot, primaryId, variant), entry) - { } - - public ImcManipulation(ImcIdentifier identifier, ImcEntry entry) - { - Identifier = identifier; - Entry = entry; - } - - - // Variants were initially ushorts but got shortened to bytes. - // There are still some manipulations around that have values > 255 for variant, - // so we change the unused value to something nonsensical in that case, just so they do not compare equal, - // and clamp the variant to 255. - [JsonConstructor] - internal ImcManipulation(ObjectType objectType, BodySlot bodySlot, PrimaryId primaryId, SecondaryId secondaryId, ushort variant, - EquipSlot equipSlot, ImcEntry entry) - { - Entry = entry; - var v = (Variant)Math.Clamp(variant, (ushort)0, byte.MaxValue); - Identifier = objectType switch - { - ObjectType.Accessory or ObjectType.Equipment => new ImcIdentifier(primaryId, v, objectType, 0, equipSlot, - variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), - ObjectType.DemiHuman => new ImcIdentifier(primaryId, v, objectType, secondaryId, equipSlot, variant > byte.MaxValue ? BodySlot.Body : BodySlot.Unknown), - _ => new ImcIdentifier(primaryId, v, objectType, secondaryId, equipSlot, bodySlot == BodySlot.Unknown ? BodySlot.Body : BodySlot.Unknown), - }; - } - - public ImcManipulation Copy(ImcEntry entry) - => new(Identifier, entry); - - public override string ToString() - => Identifier.ToString(); - - public bool Equals(ImcManipulation other) - => Identifier == other.Identifier; - - public override bool Equals(object? obj) - => obj is ImcManipulation other && Equals(other); - - public override int GetHashCode() - => Identifier.GetHashCode(); - - public int CompareTo(ImcManipulation other) - => Identifier.CompareTo(other.Identifier); - - public MetaIndex FileIndex() - => Identifier.FileIndex(); - - public Utf8GamePath GamePath() - => Identifier.GamePath(); - - public bool Apply(ImcFile file) - => file.SetEntry(ImcFile.PartIndex(EquipSlot), Variant.Id, Entry); - - public bool Validate(bool withMaterial) - { - if (!Identifier.Validate()) - return false; - - if (withMaterial && Entry.MaterialId == 0) - return false; - - return true; - } -} diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 236157ae..5a51df83 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using Penumbra.Collections.Cache; using Penumbra.GameData.Structs; using Penumbra.Util; using ImcEntry = Penumbra.GameData.Structs.ImcEntry; @@ -7,7 +8,7 @@ using ImcEntry = Penumbra.GameData.Structs.ImcEntry; namespace Penumbra.Meta.Manipulations; [JsonConverter(typeof(Converter))] -public class MetaDictionary : IEnumerable +public class MetaDictionary { private readonly Dictionary _imc = []; private readonly Dictionary _eqp = []; @@ -20,32 +21,50 @@ public class MetaDictionary : IEnumerable public IReadOnlyDictionary Imc => _imc; + public IReadOnlyDictionary Eqp + => _eqp; + + public IReadOnlyDictionary Eqdp + => _eqdp; + + public IReadOnlyDictionary Est + => _est; + + public IReadOnlyDictionary Gmp + => _gmp; + + public IReadOnlyDictionary Rsp + => _rsp; + + public IReadOnlySet GlobalEqp + => _globalEqp; + public int Count { get; private set; } - public int GetCount(MetaManipulation.Type type) + public int GetCount(MetaManipulationType type) => type switch { - MetaManipulation.Type.Imc => _imc.Count, - MetaManipulation.Type.Eqdp => _eqdp.Count, - MetaManipulation.Type.Eqp => _eqp.Count, - MetaManipulation.Type.Est => _est.Count, - MetaManipulation.Type.Gmp => _gmp.Count, - MetaManipulation.Type.Rsp => _rsp.Count, - MetaManipulation.Type.GlobalEqp => _globalEqp.Count, - _ => 0, + MetaManipulationType.Imc => _imc.Count, + MetaManipulationType.Eqdp => _eqdp.Count, + MetaManipulationType.Eqp => _eqp.Count, + MetaManipulationType.Est => _est.Count, + MetaManipulationType.Gmp => _gmp.Count, + MetaManipulationType.Rsp => _rsp.Count, + MetaManipulationType.GlobalEqp => _globalEqp.Count, + _ => 0, }; - public bool CanAdd(IMetaIdentifier identifier) + public bool Contains(IMetaIdentifier identifier) => identifier switch { - EqdpIdentifier eqdpIdentifier => !_eqdp.ContainsKey(eqdpIdentifier), - EqpIdentifier eqpIdentifier => !_eqp.ContainsKey(eqpIdentifier), - EstIdentifier estIdentifier => !_est.ContainsKey(estIdentifier), - GlobalEqpManipulation globalEqpManipulation => !_globalEqp.Contains(globalEqpManipulation), - GmpIdentifier gmpIdentifier => !_gmp.ContainsKey(gmpIdentifier), - ImcIdentifier imcIdentifier => !_imc.ContainsKey(imcIdentifier), - RspIdentifier rspIdentifier => !_rsp.ContainsKey(rspIdentifier), - _ => false, + EqdpIdentifier i => _eqdp.ContainsKey(i), + EqpIdentifier i => _eqp.ContainsKey(i), + EstIdentifier i => _est.ContainsKey(i), + GlobalEqpManipulation i => _globalEqp.Contains(i), + GmpIdentifier i => _gmp.ContainsKey(i), + ImcIdentifier i => _imc.ContainsKey(i), + RspIdentifier i => _rsp.ContainsKey(i), + _ => false, }; public void Clear() @@ -69,17 +88,16 @@ public class MetaDictionary : IEnumerable && _gmp.SetEquals(other._gmp) && _globalEqp.SetEquals(other._globalEqp); - public IEnumerator GetEnumerator() - => _imc.Select(kvp => new MetaManipulation(new ImcManipulation(kvp.Key, kvp.Value))) - .Concat(_eqp.Select(kvp => new MetaManipulation(new EqpManipulation(kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))))) - .Concat(_eqdp.Select(kvp => new MetaManipulation(new EqdpManipulation(kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))))) - .Concat(_est.Select(kvp => new MetaManipulation(new EstManipulation(kvp.Key, kvp.Value)))) - .Concat(_rsp.Select(kvp => new MetaManipulation(new RspManipulation(kvp.Key, kvp.Value)))) - .Concat(_gmp.Select(kvp => new MetaManipulation(new GmpManipulation(kvp.Key, kvp.Value)))) - .Concat(_globalEqp.Select(manip => new MetaManipulation(manip))).GetEnumerator(); + public IEnumerable Identifiers + => _imc.Keys.Cast() + .Concat(_eqdp.Keys.Cast()) + .Concat(_eqp.Keys.Cast()) + .Concat(_est.Keys.Cast()) + .Concat(_gmp.Keys.Cast()) + .Concat(_rsp.Keys.Cast()) + .Concat(_globalEqp.Cast()); - IEnumerator IEnumerable.GetEnumerator() - => GetEnumerator(); + #region TryAdd public bool TryAdd(ImcIdentifier identifier, ImcEntry entry) { @@ -90,7 +108,6 @@ public class MetaDictionary : IEnumerable return true; } - public bool TryAdd(EqpIdentifier identifier, EqpEntryInternal entry) { if (!_eqp.TryAdd(identifier, entry)) @@ -103,7 +120,6 @@ public class MetaDictionary : IEnumerable public bool TryAdd(EqpIdentifier identifier, EqpEntry entry) => TryAdd(identifier, new EqpEntryInternal(entry, identifier.Slot)); - public bool TryAdd(EqdpIdentifier identifier, EqdpEntryInternal entry) { if (!_eqdp.TryAdd(identifier, entry)) @@ -152,6 +168,10 @@ public class MetaDictionary : IEnumerable return true; } + #endregion + + #region Update + public bool Update(ImcIdentifier identifier, ImcEntry entry) { if (!_imc.ContainsKey(identifier)) @@ -161,7 +181,6 @@ public class MetaDictionary : IEnumerable return true; } - public bool Update(EqpIdentifier identifier, EqpEntryInternal entry) { if (!_eqp.ContainsKey(identifier)) @@ -174,7 +193,6 @@ public class MetaDictionary : IEnumerable public bool Update(EqpIdentifier identifier, EqpEntry entry) => Update(identifier, new EqpEntryInternal(entry, identifier.Slot)); - public bool Update(EqdpIdentifier identifier, EqdpEntryInternal entry) { if (!_eqdp.ContainsKey(identifier)) @@ -214,6 +232,50 @@ public class MetaDictionary : IEnumerable return true; } + #endregion + + #region TryGetValue + + public bool TryGetValue(EstIdentifier identifier, out EstEntry value) + => _est.TryGetValue(identifier, out value); + + public bool TryGetValue(EqpIdentifier identifier, out EqpEntryInternal value) + => _eqp.TryGetValue(identifier, out value); + + public bool TryGetValue(EqdpIdentifier identifier, out EqdpEntryInternal value) + => _eqdp.TryGetValue(identifier, out value); + + public bool TryGetValue(GmpIdentifier identifier, out GmpEntry value) + => _gmp.TryGetValue(identifier, out value); + + public bool TryGetValue(RspIdentifier identifier, out RspEntry value) + => _rsp.TryGetValue(identifier, out value); + + public bool TryGetValue(ImcIdentifier identifier, out ImcEntry value) + => _imc.TryGetValue(identifier, out value); + + #endregion + + public bool Remove(IMetaIdentifier identifier) + { + var ret = identifier switch + { + EqdpIdentifier i => _eqdp.Remove(i), + EqpIdentifier i => _eqp.Remove(i), + EstIdentifier i => _est.Remove(i), + GlobalEqpManipulation i => _globalEqp.Remove(i), + GmpIdentifier i => _gmp.Remove(i), + ImcIdentifier i => _imc.Remove(i), + RspIdentifier i => _rsp.Remove(i), + _ => false, + }; + if (ret) + --Count; + return ret; + } + + #region Merging + public void UnionWith(MetaDictionary manips) { foreach (var (identifier, entry) in manips._imc) @@ -287,24 +349,6 @@ public class MetaDictionary : IEnumerable return false; } - public bool TryGetValue(EstIdentifier identifier, out EstEntry value) - => _est.TryGetValue(identifier, out value); - - public bool TryGetValue(EqpIdentifier identifier, out EqpEntryInternal value) - => _eqp.TryGetValue(identifier, out value); - - public bool TryGetValue(EqdpIdentifier identifier, out EqdpEntryInternal value) - => _eqdp.TryGetValue(identifier, out value); - - public bool TryGetValue(GmpIdentifier identifier, out GmpEntry value) - => _gmp.TryGetValue(identifier, out value); - - public bool TryGetValue(RspIdentifier identifier, out RspEntry value) - => _rsp.TryGetValue(identifier, out value); - - public bool TryGetValue(ImcIdentifier identifier, out ImcEntry value) - => _imc.TryGetValue(identifier, out value); - public void SetTo(MetaDictionary other) { _imc.SetTo(other._imc); @@ -329,6 +373,8 @@ public class MetaDictionary : IEnumerable Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _globalEqp.Count; } + #endregion + public MetaDictionary Clone() { var ret = new MetaDictionary(); @@ -336,29 +382,124 @@ public class MetaDictionary : IEnumerable return ret; } - private static void WriteJson(JsonWriter writer, JsonSerializer serializer, IMetaIdentifier identifier, object entry) - { - var type = identifier switch + public static JObject Serialize(EqpIdentifier identifier, EqpEntryInternal entry) + => Serialize(identifier, entry.ToEntry(identifier.Slot)); + + public static JObject Serialize(EqpIdentifier identifier, EqpEntry entry) + => new() { - ImcIdentifier => "Imc", - EqdpIdentifier => "Eqdp", - EqpIdentifier => "Eqp", - EstIdentifier => "Est", - GmpIdentifier => "Gmp", - RspIdentifier => "Rsp", - GlobalEqpManipulation => "GlobalEqp", - _ => string.Empty, + ["Type"] = MetaManipulationType.Eqp.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = (ulong)entry, + }), }; - if (type.Length == 0) - return; + public static JObject Serialize(EqdpIdentifier identifier, EqdpEntryInternal entry) + => Serialize(identifier, entry.ToEntry(identifier.Slot)); - writer.WriteStartObject(); - writer.WritePropertyName("Type"); - writer.WriteValue(type); - writer.WritePropertyName("Manipulation"); + public static JObject Serialize(EqdpIdentifier identifier, EqdpEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Eqdp.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = (ushort)entry, + }), + }; - writer.WriteEndObject(); + public static JObject Serialize(EstIdentifier identifier, EstEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Est.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = entry.Value, + }), + }; + + public static JObject Serialize(GmpIdentifier identifier, GmpEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Gmp.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = JObject.FromObject(entry), + }), + }; + + public static JObject Serialize(ImcIdentifier identifier, ImcEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Imc.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = JObject.FromObject(entry), + }), + }; + + public static JObject Serialize(RspIdentifier identifier, RspEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Rsp.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = entry.Value, + }), + }; + + public static JObject Serialize(GlobalEqpManipulation identifier) + => new() + { + ["Type"] = MetaManipulationType.GlobalEqp.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject()), + }; + + public static JObject? Serialize(TIdentifier identifier, TEntry entry) + where TIdentifier : unmanaged, IMetaIdentifier + where TEntry : unmanaged + { + if (typeof(TIdentifier) == typeof(EqpIdentifier) && typeof(TEntry) == typeof(EqpEntryInternal)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(EqpIdentifier) && typeof(TEntry) == typeof(EqpEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(EqdpIdentifier) && typeof(TEntry) == typeof(EqdpEntryInternal)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(EqdpIdentifier) && typeof(TEntry) == typeof(EqdpEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(EstIdentifier) && typeof(TEntry) == typeof(EstEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(GmpIdentifier) && typeof(TEntry) == typeof(GmpEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(RspIdentifier) && typeof(TEntry) == typeof(RspEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(ImcIdentifier) && typeof(TEntry) == typeof(ImcEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(GlobalEqpManipulation)) + return Serialize(Unsafe.As(ref identifier)); + + return null; + } + + public static JArray SerializeTo(JArray array, IEnumerable> manipulations) + where TIdentifier : unmanaged, IMetaIdentifier + where TEntry : unmanaged + { + foreach (var (identifier, entry) in manipulations) + { + if (Serialize(identifier, entry) is { } jObj) + array.Add(jObj); + } + + return array; + } + + public static JArray SerializeTo(JArray array, IEnumerable manipulations) + { + foreach (var manip in manipulations) + array.Add(Serialize(manip)); + + return array; } private class Converter : JsonConverter @@ -371,30 +512,27 @@ public class MetaDictionary : IEnumerable return; } - writer.WriteStartArray(); - foreach (var item in value) - { - writer.WriteStartObject(); - writer.WritePropertyName("Type"); - writer.WriteValue(item.ManipulationType.ToString()); - writer.WritePropertyName("Manipulation"); - serializer.Serialize(writer, item.Manipulation); - writer.WriteEndObject(); - } - - writer.WriteEndArray(); + var array = new JArray(); + SerializeTo(array, value._imc); + SerializeTo(array, value._eqp); + SerializeTo(array, value._eqdp); + SerializeTo(array, value._est); + SerializeTo(array, value._rsp); + SerializeTo(array, value._gmp); + SerializeTo(array, value._globalEqp); + array.WriteTo(writer); } public override MetaDictionary ReadJson(JsonReader reader, Type objectType, MetaDictionary? existingValue, bool hasExistingValue, JsonSerializer serializer) { - var dict = existingValue ?? []; + var dict = existingValue ?? new MetaDictionary(); dict.Clear(); var jObj = JArray.Load(reader); foreach (var item in jObj) { - var type = item["Type"]?.ToObject() ?? MetaManipulation.Type.Unknown; - if (type is MetaManipulation.Type.Unknown) + var type = item["Type"]?.ToObject() ?? MetaManipulationType.Unknown; + if (type is MetaManipulationType.Unknown) { Penumbra.Log.Warning($"Invalid Meta Manipulation Type {type} encountered."); continue; @@ -408,7 +546,7 @@ public class MetaDictionary : IEnumerable switch (type) { - case MetaManipulation.Type.Imc: + case MetaManipulationType.Imc: { var identifier = ImcIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); @@ -418,7 +556,7 @@ public class MetaDictionary : IEnumerable Penumbra.Log.Warning("Invalid IMC Manipulation encountered."); break; } - case MetaManipulation.Type.Eqdp: + case MetaManipulationType.Eqdp: { var identifier = EqdpIdentifier.FromJson(manip); var entry = (EqdpEntry?)manip["Entry"]?.ToObject(); @@ -428,7 +566,7 @@ public class MetaDictionary : IEnumerable Penumbra.Log.Warning("Invalid EQDP Manipulation encountered."); break; } - case MetaManipulation.Type.Eqp: + case MetaManipulationType.Eqp: { var identifier = EqpIdentifier.FromJson(manip); var entry = (EqpEntry?)manip["Entry"]?.ToObject(); @@ -438,7 +576,7 @@ public class MetaDictionary : IEnumerable Penumbra.Log.Warning("Invalid EQP Manipulation encountered."); break; } - case MetaManipulation.Type.Est: + case MetaManipulationType.Est: { var identifier = EstIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); @@ -448,7 +586,7 @@ public class MetaDictionary : IEnumerable Penumbra.Log.Warning("Invalid EST Manipulation encountered."); break; } - case MetaManipulation.Type.Gmp: + case MetaManipulationType.Gmp: { var identifier = GmpIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); @@ -458,7 +596,7 @@ public class MetaDictionary : IEnumerable Penumbra.Log.Warning("Invalid GMP Manipulation encountered."); break; } - case MetaManipulation.Type.Rsp: + case MetaManipulationType.Rsp: { var identifier = RspIdentifier.FromJson(manip); var entry = manip["Entry"]?.ToObject(); @@ -468,7 +606,7 @@ public class MetaDictionary : IEnumerable Penumbra.Log.Warning("Invalid RSP Manipulation encountered."); break; } - case MetaManipulation.Type.GlobalEqp: + case MetaManipulationType.GlobalEqp: { var identifier = GlobalEqpManipulation.FromJson(manip); if (identifier.HasValue) @@ -483,4 +621,22 @@ public class MetaDictionary : IEnumerable return dict; } } + + public MetaDictionary() + { } + + public MetaDictionary(MetaCache? cache) + { + if (cache == null) + return; + + _imc = cache.Imc.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + _eqp = cache.Eqp.ToDictionary(kvp => kvp.Key, kvp => new EqpEntryInternal(kvp.Value.Entry, kvp.Key.Slot)); + _eqdp = cache.Eqdp.ToDictionary(kvp => kvp.Key, kvp => new EqdpEntryInternal(kvp.Value.Entry, kvp.Key.Slot)); + _est = cache.Est.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + _gmp = cache.Gmp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + _rsp = cache.Rsp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + _globalEqp = cache.GlobalEqp.Select(kvp => kvp.Key).ToHashSet(); + Count = cache.Count; + } } diff --git a/Penumbra/Meta/Manipulations/MetaManipulation.cs b/Penumbra/Meta/Manipulations/MetaManipulation.cs deleted file mode 100644 index b80681d2..00000000 --- a/Penumbra/Meta/Manipulations/MetaManipulation.cs +++ /dev/null @@ -1,457 +0,0 @@ -using Dalamud.Interface; -using ImGuiNET; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using OtterGui; -using Penumbra.GameData.Enums; -using Penumbra.Interop.Structs; -using Penumbra.Mods.Editor; -using Penumbra.String.Functions; -using Penumbra.UI; -using Penumbra.UI.ModsTab; - -namespace Penumbra.Meta.Manipulations; - -#if false -private static class ImcRow -{ - private static ImcIdentifier _newIdentifier = ImcIdentifier.Default; - - private static float IdWidth - => 80 * UiHelpers.Scale; - - private static float SmallIdWidth - => 45 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current IMC manipulations to clipboard.", iconSize, - editor.MetaEditor.Imc.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var (defaultEntry, fileExists, _) = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true); - var manip = (MetaManipulation)new ImcManipulation(_newIdentifier, defaultEntry); - var canAdd = fileExists && editor.MetaEditor.CanAdd(manip); - var tt = canAdd ? "Stage this edit." : !fileExists ? "This IMC file does not exist." : "This entry is already edited."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(manip); - - // Identifier - ImGui.TableNextColumn(); - var change = ImcManipulationDrawer.DrawObjectType(ref _newIdentifier); - - ImGui.TableNextColumn(); - change |= ImcManipulationDrawer.DrawPrimaryId(ref _newIdentifier); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); - - ImGui.TableNextColumn(); - // Equipment and accessories are slightly different imcs than other types. - if (_newIdentifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier); - else - change |= ImcManipulationDrawer.DrawSecondaryId(ref _newIdentifier); - - ImGui.TableNextColumn(); - change |= ImcManipulationDrawer.DrawVariant(ref _newIdentifier); - - ImGui.TableNextColumn(); - if (_newIdentifier.ObjectType is ObjectType.DemiHuman) - change |= ImcManipulationDrawer.DrawSlot(ref _newIdentifier, 70); - else - ImUtf8.ScaledDummy(new Vector2(70 * UiHelpers.Scale, 0)); - - if (change) - defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(_newIdentifier, true).Entry; - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref defaultEntry, false); - ImGui.SameLine(); - ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref defaultEntry, false); - ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawDecalId(defaultEntry, ref defaultEntry, false); - ImGui.SameLine(); - ImcManipulationDrawer.DrawVfxId(defaultEntry, ref defaultEntry, false); - ImGui.SameLine(); - ImcManipulationDrawer.DrawSoundId(defaultEntry, ref defaultEntry, false); - ImGui.TableNextColumn(); - ImcManipulationDrawer.DrawAttributes(defaultEntry, ref defaultEntry); - } - - public static void Draw(MetaFileManager metaFileManager, ImcManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.ObjectType.ToName()); - ImGuiUtil.HoverTooltip(ObjectTypeTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.PrimaryId.ToString()); - ImGuiUtil.HoverTooltip(PrimaryIdTooltipShort); - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - if (meta.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - { - ImGui.TextUnformatted(meta.EquipSlot.ToName()); - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } - else - { - ImGui.TextUnformatted(meta.SecondaryId.ToString()); - ImGuiUtil.HoverTooltip(SecondaryIdTooltip); - } - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Variant.ToString()); - ImGuiUtil.HoverTooltip(VariantIdTooltip); - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - if (meta.ObjectType is ObjectType.DemiHuman) - { - ImGui.TextUnformatted(meta.EquipSlot.ToName()); - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - } - - // Values - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); - ImGui.TableNextColumn(); - var defaultEntry = metaFileManager.ImcChecker.GetDefaultEntry(meta.Identifier, true).Entry; - var newEntry = meta.Entry; - var changes = ImcManipulationDrawer.DrawMaterialId(defaultEntry, ref newEntry, true); - ImGui.SameLine(); - changes |= ImcManipulationDrawer.DrawMaterialAnimationId(defaultEntry, ref newEntry, true); - ImGui.TableNextColumn(); - changes |= ImcManipulationDrawer.DrawDecalId(defaultEntry, ref newEntry, true); - ImGui.SameLine(); - changes |= ImcManipulationDrawer.DrawVfxId(defaultEntry, ref newEntry, true); - ImGui.SameLine(); - changes |= ImcManipulationDrawer.DrawSoundId(defaultEntry, ref newEntry, true); - ImGui.TableNextColumn(); - changes |= ImcManipulationDrawer.DrawAttributes(defaultEntry, ref newEntry); - - if (changes) - editor.MetaEditor.Change(meta.Copy(newEntry)); - } -} - -#endif - -public interface IMetaManipulation -{ - public MetaIndex FileIndex(); -} - -public interface IMetaManipulation - : IMetaManipulation, IComparable, IEquatable where T : struct -{ } - -[StructLayout(LayoutKind.Explicit, Pack = 1, Size = 16)] -public readonly struct MetaManipulation : IEquatable, IComparable -{ - public const int CurrentVersion = 0; - - public enum Type : byte - { - Unknown = 0, - Imc = 1, - Eqdp = 2, - Eqp = 3, - Est = 4, - Gmp = 5, - Rsp = 6, - GlobalEqp = 7, - } - - [FieldOffset(0)] - [JsonIgnore] - public readonly EqpManipulation Eqp = default; - - [FieldOffset(0)] - [JsonIgnore] - public readonly GmpManipulation Gmp = default; - - [FieldOffset(0)] - [JsonIgnore] - public readonly EqdpManipulation Eqdp = default; - - [FieldOffset(0)] - [JsonIgnore] - public readonly EstManipulation Est = default; - - [FieldOffset(0)] - [JsonIgnore] - public readonly RspManipulation Rsp = default; - - [FieldOffset(0)] - [JsonIgnore] - public readonly ImcManipulation Imc = default; - - [FieldOffset(0)] - [JsonIgnore] - public readonly GlobalEqpManipulation GlobalEqp = default; - - [FieldOffset(15)] - [JsonConverter(typeof(StringEnumConverter))] - [JsonProperty("Type")] - public readonly Type ManipulationType; - - public object? Manipulation - { - get => ManipulationType switch - { - Type.Unknown => null, - Type.Imc => Imc, - Type.Eqdp => Eqdp, - Type.Eqp => Eqp, - Type.Est => Est, - Type.Gmp => Gmp, - Type.Rsp => Rsp, - Type.GlobalEqp => GlobalEqp, - _ => null, - }; - init - { - switch (value) - { - case EqpManipulation m: - Eqp = m; - ManipulationType = m.Validate() ? Type.Eqp : Type.Unknown; - return; - case EqdpManipulation m: - Eqdp = m; - ManipulationType = m.Validate() ? Type.Eqdp : Type.Unknown; - return; - case GmpManipulation m: - Gmp = m; - ManipulationType = m.Validate() ? Type.Gmp : Type.Unknown; - return; - case EstManipulation m: - Est = m; - ManipulationType = m.Validate() ? Type.Est : Type.Unknown; - return; - case RspManipulation m: - Rsp = m; - ManipulationType = m.Validate() ? Type.Rsp : Type.Unknown; - return; - case ImcManipulation m: - Imc = m; - ManipulationType = m.Validate(true) ? Type.Imc : Type.Unknown; - return; - case GlobalEqpManipulation m: - GlobalEqp = m; - ManipulationType = m.Validate() ? Type.GlobalEqp : Type.Unknown; - return; - } - } - } - - public bool Validate() - { - return ManipulationType switch - { - Type.Imc => Imc.Validate(true), - Type.Eqdp => Eqdp.Validate(), - Type.Eqp => Eqp.Validate(), - Type.Est => Est.Validate(), - Type.Gmp => Gmp.Validate(), - Type.Rsp => Rsp.Validate(), - Type.GlobalEqp => GlobalEqp.Validate(), - _ => false, - }; - } - - public MetaManipulation(EqpManipulation eqp) - { - Eqp = eqp; - ManipulationType = Type.Eqp; - } - - public MetaManipulation(GmpManipulation gmp) - { - Gmp = gmp; - ManipulationType = Type.Gmp; - } - - public MetaManipulation(EqdpManipulation eqdp) - { - Eqdp = eqdp; - ManipulationType = Type.Eqdp; - } - - public MetaManipulation(EstManipulation est) - { - Est = est; - ManipulationType = Type.Est; - } - - public MetaManipulation(RspManipulation rsp) - { - Rsp = rsp; - ManipulationType = Type.Rsp; - } - - public MetaManipulation(ImcManipulation imc) - { - Imc = imc; - ManipulationType = Type.Imc; - } - - public MetaManipulation(GlobalEqpManipulation eqp) - { - GlobalEqp = eqp; - ManipulationType = Type.GlobalEqp; - } - - public static implicit operator MetaManipulation(EqpManipulation eqp) - => new(eqp); - - public static implicit operator MetaManipulation(GmpManipulation gmp) - => new(gmp); - - public static implicit operator MetaManipulation(EqdpManipulation eqdp) - => new(eqdp); - - public static implicit operator MetaManipulation(EstManipulation est) - => new(est); - - public static implicit operator MetaManipulation(RspManipulation rsp) - => new(rsp); - - public static implicit operator MetaManipulation(ImcManipulation imc) - => new(imc); - - public static implicit operator MetaManipulation(GlobalEqpManipulation eqp) - => new(eqp); - - public bool EntryEquals(MetaManipulation other) - { - if (ManipulationType != other.ManipulationType) - return false; - - return ManipulationType switch - { - Type.Eqp => Eqp.Entry.Equals(other.Eqp.Entry), - Type.Gmp => Gmp.Entry.Equals(other.Gmp.Entry), - Type.Eqdp => Eqdp.Entry.Equals(other.Eqdp.Entry), - Type.Est => Est.Entry.Equals(other.Est.Entry), - Type.Rsp => Rsp.Entry.Equals(other.Rsp.Entry), - Type.Imc => Imc.Entry.Equals(other.Imc.Entry), - Type.GlobalEqp => true, - _ => throw new ArgumentOutOfRangeException(), - }; - } - - public bool Equals(MetaManipulation other) - { - if (ManipulationType != other.ManipulationType) - return false; - - return ManipulationType switch - { - Type.Eqp => Eqp.Equals(other.Eqp), - Type.Gmp => Gmp.Equals(other.Gmp), - Type.Eqdp => Eqdp.Equals(other.Eqdp), - Type.Est => Est.Equals(other.Est), - Type.Rsp => Rsp.Equals(other.Rsp), - Type.Imc => Imc.Equals(other.Imc), - Type.GlobalEqp => GlobalEqp.Equals(other.GlobalEqp), - _ => false, - }; - } - - public MetaManipulation WithEntryOf(MetaManipulation other) - { - if (ManipulationType != other.ManipulationType) - return this; - - return ManipulationType switch - { - Type.Eqp => Eqp.Copy(other.Eqp.Entry), - Type.Gmp => Gmp.Copy(other.Gmp.Entry), - Type.Eqdp => Eqdp.Copy(other.Eqdp), - Type.Est => Est.Copy(other.Est.Entry), - Type.Rsp => Rsp.Copy(other.Rsp.Entry), - Type.Imc => Imc.Copy(other.Imc.Entry), - Type.GlobalEqp => GlobalEqp, - _ => throw new ArgumentOutOfRangeException(), - }; - } - - public override bool Equals(object? obj) - => obj is MetaManipulation other && Equals(other); - - public override int GetHashCode() - => ManipulationType switch - { - Type.Eqp => Eqp.GetHashCode(), - Type.Gmp => Gmp.GetHashCode(), - Type.Eqdp => Eqdp.GetHashCode(), - Type.Est => Est.GetHashCode(), - Type.Rsp => Rsp.GetHashCode(), - Type.Imc => Imc.GetHashCode(), - Type.GlobalEqp => GlobalEqp.GetHashCode(), - _ => 0, - }; - - public unsafe int CompareTo(MetaManipulation other) - { - fixed (MetaManipulation* lhs = &this) - { - return MemoryUtility.MemCmpUnchecked(lhs, &other, sizeof(MetaManipulation)); - } - } - - public override string ToString() - => ManipulationType switch - { - Type.Eqp => Eqp.ToString(), - Type.Gmp => Gmp.ToString(), - Type.Eqdp => Eqdp.ToString(), - Type.Est => Est.ToString(), - Type.Rsp => Rsp.ToString(), - Type.Imc => Imc.ToString(), - Type.GlobalEqp => GlobalEqp.ToString(), - _ => "Invalid", - }; - - public string EntryToString() - => ManipulationType switch - { - Type.Imc => - $"{Imc.Entry.DecalId}-{Imc.Entry.MaterialId}-{Imc.Entry.VfxId}-{Imc.Entry.SoundId}-{Imc.Entry.MaterialAnimationId}-{Imc.Entry.AttributeMask}", - Type.Eqdp => $"{(ushort)Eqdp.Entry:X}", - Type.Eqp => $"{(ulong)Eqp.Entry:X}", - Type.Est => $"{Est.Entry}", - Type.Gmp => $"{Gmp.Entry.Value}", - Type.Rsp => $"{Rsp.Entry}", - Type.GlobalEqp => string.Empty, - _ => string.Empty, - }; - - public static bool operator ==(MetaManipulation left, MetaManipulation right) - => left.Equals(right); - - public static bool operator !=(MetaManipulation left, MetaManipulation right) - => !(left == right); - - public static bool operator <(MetaManipulation left, MetaManipulation right) - => left.CompareTo(right) < 0; - - public static bool operator <=(MetaManipulation left, MetaManipulation right) - => left.CompareTo(right) <= 0; - - public static bool operator >(MetaManipulation left, MetaManipulation right) - => left.CompareTo(right) > 0; - - public static bool operator >=(MetaManipulation left, MetaManipulation right) - => left.CompareTo(right) >= 0; -} - diff --git a/Penumbra/Meta/Manipulations/Rsp.cs b/Penumbra/Meta/Manipulations/Rsp.cs index ca7cb1c5..73d1d7e5 100644 --- a/Penumbra/Meta/Manipulations/Rsp.cs +++ b/Penumbra/Meta/Manipulations/Rsp.cs @@ -38,6 +38,9 @@ public readonly record struct RspIdentifier(SubRace SubRace, RspAttribute Attrib var ret = new RspIdentifier(subRace, attribute); return ret.Validate() ? ret : null; } + + public MetaManipulationType Type + => MetaManipulationType.Rsp; } [JsonConverter(typeof(Converter))] diff --git a/Penumbra/Meta/Manipulations/RspManipulation.cs b/Penumbra/Meta/Manipulations/RspManipulation.cs deleted file mode 100644 index e2282c41..00000000 --- a/Penumbra/Meta/Manipulations/RspManipulation.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Penumbra.GameData.Enums; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; - -namespace Penumbra.Meta.Manipulations; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -public readonly struct RspManipulation(RspIdentifier identifier, RspEntry entry) : IMetaManipulation -{ - [JsonIgnore] - public RspIdentifier Identifier { get; } = identifier; - - public RspEntry Entry { get; } = entry; - - [JsonConverter(typeof(StringEnumConverter))] - public SubRace SubRace - => Identifier.SubRace; - - [JsonConverter(typeof(StringEnumConverter))] - public RspAttribute Attribute - => Identifier.Attribute; - - [JsonConstructor] - public RspManipulation(SubRace subRace, RspAttribute attribute, RspEntry entry) - : this(new RspIdentifier(subRace, attribute), entry) - { } - - public RspManipulation Copy(RspEntry entry) - => new(Identifier, entry); - - public override string ToString() - => $"Rsp - {SubRace.ToName()} - {Attribute.ToFullString()}"; - - public bool Equals(RspManipulation other) - => SubRace == other.SubRace - && Attribute == other.Attribute; - - public override bool Equals(object? obj) - => obj is RspManipulation other && Equals(other); - - public override int GetHashCode() - => HashCode.Combine((int)SubRace, (int)Attribute); - - public int CompareTo(RspManipulation other) - { - var s = SubRace.CompareTo(other.SubRace); - return s != 0 ? s : Attribute.CompareTo(other.Attribute); - } - - public MetaIndex FileIndex() - => MetaIndex.HumanCmp; - - public bool Apply(CmpFile file) - { - var value = file[SubRace, Attribute]; - if (value == Entry) - return false; - - file[SubRace, Attribute] = Entry; - return true; - } - - public bool Validate() - => Identifier.Validate() && Entry.Validate(); -} diff --git a/Penumbra/Mods/Editor/IMod.cs b/Penumbra/Mods/Editor/IMod.cs index 06c31846..3da38829 100644 --- a/Penumbra/Mods/Editor/IMod.cs +++ b/Penumbra/Mods/Editor/IMod.cs @@ -10,7 +10,7 @@ public record struct AppliedModData( Dictionary FileRedirections, MetaDictionary Manipulations) { - public static readonly AppliedModData Empty = new([], []); + public static readonly AppliedModData Empty = new([], new MetaDictionary()); } public interface IMod diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 42171378..bacf4122 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -26,20 +26,20 @@ public class ModMetaEditor(ModManager modManager) : MetaDictionary, IService } } - public readonly FrozenDictionary OtherData = - Enum.GetValues().ToFrozenDictionary(t => t, _ => new OtherOptionData()); + public readonly FrozenDictionary OtherData = + Enum.GetValues().ToFrozenDictionary(t => t, _ => new OtherOptionData()); - public bool Changes { get; private set; } + public bool Changes { get; set; } public new void Clear() { + Changes = Count > 0; base.Clear(); - Changes = true; } public void Load(Mod mod, IModDataContainer currentOption) { - foreach (var type in Enum.GetValues()) + foreach (var type in Enum.GetValues()) OtherData[type].Clear(); foreach (var option in mod.AllDataContainers) @@ -48,13 +48,13 @@ public class ModMetaEditor(ModManager modManager) : MetaDictionary, IService continue; var name = option.GetFullName(); - OtherData[MetaManipulation.Type.Imc].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Imc)); - OtherData[MetaManipulation.Type.Eqp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Eqp)); - OtherData[MetaManipulation.Type.Eqdp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Eqdp)); - OtherData[MetaManipulation.Type.Gmp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Gmp)); - OtherData[MetaManipulation.Type.Est].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Est)); - OtherData[MetaManipulation.Type.Rsp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.Rsp)); - OtherData[MetaManipulation.Type.GlobalEqp].Add(name, option.Manipulations.GetCount(MetaManipulation.Type.GlobalEqp)); + OtherData[MetaManipulationType.Imc].Add(name, option.Manipulations.GetCount(MetaManipulationType.Imc)); + OtherData[MetaManipulationType.Eqp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Eqp)); + OtherData[MetaManipulationType.Eqdp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Eqdp)); + OtherData[MetaManipulationType.Gmp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Gmp)); + OtherData[MetaManipulationType.Est].Add(name, option.Manipulations.GetCount(MetaManipulationType.Est)); + OtherData[MetaManipulationType.Rsp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Rsp)); + OtherData[MetaManipulationType.GlobalEqp].Add(name, option.Manipulations.GetCount(MetaManipulationType.GlobalEqp)); } Clear(); diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index e42a1d31..b7827c47 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -125,8 +125,8 @@ public static class EquipmentSwap _ => (EstType)0, }; - var skipFemale = false; - var skipMale = false; + var skipFemale = false; + var skipMale = false; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) @@ -242,8 +242,8 @@ public static class EquipmentSwap private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, ObjectIdentification identifier, EquipSlot slotFrom, PrimaryId idFrom, PrimaryId idTo, Variant variantFrom) { - var entry = new ImcManipulation(slotFrom, variantFrom.Id, idFrom, default); - var imc = new ImcFile(manager, entry.Identifier); + var ident = new ImcIdentifier(slotFrom, idFrom, variantFrom); + var imc = new ImcFile(manager, ident); EquipItem[] items; Variant[] variants; if (idFrom == idTo) @@ -273,7 +273,8 @@ public static class EquipmentSwap var manipToIdentifier = new GmpIdentifier(idTo); var manipFromDefault = ExpandedGmpFile.GetDefault(manager, manipFromIdentifier); var manipToDefault = ExpandedGmpFile.GetDefault(manager, manipToIdentifier); - return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); + return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, + manipToIdentifier, manipToDefault); } public static MetaSwap CreateImc(MetaFileManager manager, Func redirections, @@ -286,16 +287,17 @@ public static class EquipmentSwap Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) { var manipFromIdentifier = new ImcIdentifier(slotFrom, idFrom, variantFrom); - var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); - var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); - var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); - var imc = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); + var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); + var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); + var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); + var imc = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, + manipToIdentifier, manipToDefault); var decal = CreateDecal(manager, redirections, imc.SwapToModdedEntry.DecalId); if (decal != null) imc.ChildSwaps.Add(decal); - var avfx = CreateAvfx(manager, redirections, idFrom, idTo, imc.SwapToModdedEntry.VfxId); + var avfx = CreateAvfx(manager, redirections, slotFrom, slotTo, idFrom, idTo, imc.SwapToModdedEntry.VfxId); if (avfx != null) imc.ChildSwaps.Add(avfx); @@ -316,19 +318,21 @@ public static class EquipmentSwap // Example: Abyssos Helm / Body - public static FileSwap? CreateAvfx(MetaFileManager manager, Func redirections, PrimaryId idFrom, PrimaryId idTo, + public static FileSwap? CreateAvfx(MetaFileManager manager, Func redirections, EquipSlot slotFrom, EquipSlot slotTo, + PrimaryId idFrom, PrimaryId idTo, byte vfxId) { if (vfxId == 0) return null; var vfxPathFrom = GamePaths.Equipment.Avfx.Path(idFrom, vfxId); - var vfxPathTo = GamePaths.Equipment.Avfx.Path(idTo, vfxId); - var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); + vfxPathFrom = ItemSwap.ReplaceType(vfxPathFrom, slotFrom, slotTo, idFrom); + var vfxPathTo = GamePaths.Equipment.Avfx.Path(idTo, vfxId); + var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); foreach (ref var filePath in avfx.AsAvfx()!.Textures.AsSpan()) { - var atex = CreateAtex(manager, redirections, ref filePath, ref avfx.DataWasChanged); + var atex = CreateAtex(manager, redirections, slotFrom, slotTo, idFrom, ref filePath, ref avfx.DataWasChanged); avfx.ChildSwaps.Add(atex); } @@ -394,8 +398,7 @@ public static class EquipmentSwap } public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, PrimaryId idFrom, - PrimaryId idTo, - ref MtrlFile.Texture texture, ref bool dataWasChanged) + PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) => CreateTex(manager, redirections, prefix, EquipSlot.Unknown, EquipSlot.Unknown, idFrom, idTo, ref texture, ref dataWasChanged); public static FileSwap CreateTex(MetaFileManager manager, Func redirections, char prefix, EquipSlot slotFrom, @@ -404,6 +407,7 @@ public static class EquipmentSwap var addedDashes = GamePaths.Tex.HandleDx11Path(texture, out var path); var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); newPath = ItemSwap.ReplaceSlot(newPath, slotTo, slotFrom, slotTo != slotFrom); + newPath = ItemSwap.ReplaceType(newPath, slotFrom, slotTo, idFrom); newPath = ItemSwap.AddSuffix(newPath, ".tex", $"_{Path.GetFileName(texture.Path).GetStableHashCode():x8}"); if (newPath != path) { @@ -421,11 +425,12 @@ public static class EquipmentSwap return FileSwap.CreateSwap(manager, ResourceType.Shpk, redirections, path, path); } - public static FileSwap CreateAtex(MetaFileManager manager, Func redirections, ref string filePath, - ref bool dataWasChanged) + public static FileSwap CreateAtex(MetaFileManager manager, Func redirections, EquipSlot slotFrom, EquipSlot slotTo, + PrimaryId idFrom, ref string filePath, ref bool dataWasChanged) { var oldPath = filePath; filePath = ItemSwap.AddSuffix(filePath, ".atex", $"_{Path.GetFileName(filePath).GetStableHashCode():x8}"); + filePath = ItemSwap.ReplaceType(filePath, slotFrom, slotTo, idFrom); dataWasChanged = true; return FileSwap.CreateSwap(manager, ResourceType.Atex, redirections, filePath, oldPath, oldPath); diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index efd8080c..1f4c5e7a 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -136,14 +136,14 @@ public static class ItemSwap public static FileSwap CreatePhyb(MetaFileManager manager, Func redirections, EstType type, GenderRace race, EstEntry estEntry) { - var phybPath = GamePaths.Skeleton.Phyb.Path(race, EstManipulation.ToName(type), estEntry.AsId); + var phybPath = GamePaths.Skeleton.Phyb.Path(race, type.ToName(), estEntry.AsId); return FileSwap.CreateSwap(manager, ResourceType.Phyb, redirections, phybPath, phybPath); } public static FileSwap CreateSklb(MetaFileManager manager, Func redirections, EstType type, GenderRace race, EstEntry estEntry) { - var sklbPath = GamePaths.Skeleton.Sklb.Path(race, EstManipulation.ToName(type), estEntry.AsId); + var sklbPath = GamePaths.Skeleton.Sklb.Path(race, type.ToName(), estEntry.AsId); return FileSwap.CreateSwap(manager, ResourceType.Sklb, redirections, sklbPath, sklbPath); } @@ -154,10 +154,11 @@ public static class ItemSwap return null; var manipFromIdentifier = new EstIdentifier(idFrom, type, genderRace); - var manipToIdentifier = new EstIdentifier(idTo, type, genderRace); - var manipFromDefault = EstFile.GetDefault(manager, manipFromIdentifier); - var manipToDefault = EstFile.GetDefault(manager, manipToIdentifier); - var est = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); + var manipToIdentifier = new EstIdentifier(idTo, type, genderRace); + var manipFromDefault = EstFile.GetDefault(manager, manipFromIdentifier); + var manipToDefault = EstFile.GetDefault(manager, manipToIdentifier); + var est = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, + manipToIdentifier, manipToDefault); if (ownMdl && est.SwapToModdedEntry.Value >= 2) { @@ -215,6 +216,22 @@ public static class ItemSwap ? path.Replace($"_{from.ToSuffix()}_", $"_{to.ToSuffix()}_") : path; + public static string ReplaceType(string path, EquipSlot from, EquipSlot to, PrimaryId idFrom) + { + var isAccessoryFrom = from.IsAccessory(); + if (isAccessoryFrom == to.IsAccessory()) + return path; + + if (isAccessoryFrom) + { + path = path.Replace("accessory/a", "equipment/e"); + return path.Replace($"a{idFrom.Id:D4}", $"e{idFrom.Id:D4}"); + } + + path = path.Replace("equipment/e", "accessory/a"); + return path.Replace($"e{idFrom.Id:D4}", $"a{idFrom.Id:D4}"); + } + public static string ReplaceRace(string path, GenderRace from, GenderRace to, bool condition = true) => ReplaceId(path, 'c', (ushort)from, (ushort)to, condition); diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index 8328edea..d2deb9ef 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -123,8 +123,8 @@ public class ItemSwapContainer : p => ModRedirections.TryGetValue(p, out var path) ? path : new FullPath(p); private MetaDictionary MetaResolver(ModCollection? collection) - => collection?.MetaCache?.Manipulations is { } cache - ? [] // [.. cache] TODO + => collection?.MetaCache is { } cache + ? new MetaDictionary(cache) : _appliedModData.Manipulations; public EquipItem[] LoadEquipment(EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index e8ca3199..ed4245c4 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -198,8 +198,7 @@ public partial class ModCreator( Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - // TODO - option.Manipulations.UnionWith([]);//[.. meta.MetaManipulations]); + option.Manipulations.UnionWith(meta.MetaManipulations); } else if (ext1 == ".rgsp" || ext2 == ".rgsp") { @@ -213,8 +212,7 @@ public partial class ModCreator( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); - // TODO - option.Manipulations.UnionWith([]);//[.. rgsp.MetaManipulations]); + option.Manipulations.UnionWith(rgsp.MetaManipulations); } } catch (Exception e) diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index dcd33610..3840468f 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -13,7 +13,7 @@ public class DefaultSubMod(IMod mod) : IModDataContainer public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; - public MetaDictionary Manipulations { get; set; } = []; + public MetaDictionary Manipulations { get; set; } = new(); IMod IModDataContainer.Mod => Mod; diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs index ed7b6ff8..8fac52d8 100644 --- a/Penumbra/Mods/SubMods/OptionSubMod.cs +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -33,7 +33,7 @@ public abstract class OptionSubMod(IModGroup group) : IModOption, IModDataContai public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; - public MetaDictionary Manipulations { get; set; } = []; + public MetaDictionary Manipulations { get; set; } = new(); public void AddDataTo(Dictionary redirections, MetaDictionary manipulations) => SubMod.AddContainerTo(this, redirections, manipulations); diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index 91c4c5df..e1cf9f2b 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -93,8 +93,7 @@ public class TemporaryMod : IMod } } - // TODO - MetaDictionary manips = []; // [.. collection.MetaCache?.Manipulations ?? []]; + var manips = new MetaDictionary(collection.MetaCache); defaultMod.Manipulations.UnionWith(manips); saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs new file mode 100644 index 00000000..b1ac93f1 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -0,0 +1,159 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.Interop.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Racial Model Edits (EQDP)###EQDP"u8; + + public override int NumColumns + => 7; + + protected override void Initialize() + { + Identifier = new EqdpIdentifier(1, EquipSlot.Head, GenderRace.MidlanderMale); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(MetaFiles, Identifier), Identifier.Slot); + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current EQDP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Eqdp)); + + ImGui.TableNextColumn(); + var validRaceCode = CharacterUtilityData.EqdpIdx(Identifier.GenderRace, false) >= 0; + var canAdd = validRaceCode && !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : + validRaceCode ? "This entry is already edited."u8 : "This combination of race and gender can not be used."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, Entry); + + if (DrawIdentifierInput(ref Identifier)) + UpdateEntry(); + + DrawEntry(Entry, ref Entry, true); + } + + protected override void DrawEntry(EqdpIdentifier identifier, EqdpEntryInternal entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + var defaultEntry = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(MetaFiles, identifier), identifier.Slot); + if (DrawEntry(defaultEntry, ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(EqdpIdentifier, EqdpEntryInternal)> Enumerate() + => Editor.Eqdp.Select(kvp => (kvp.Key, kvp.Value)); + + private static bool DrawIdentifierInput(ref EqdpIdentifier identifier) + { + ImGui.TableNextColumn(); + var changes = DrawPrimaryId(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawRace(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawGender(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawEquipSlot(ref identifier); + return changes; + } + + private static void DrawIdentifier(EqdpIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.SetId.Id}", FrameColor); + ImUtf8.HoverTooltip("Model Set ID"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Gender.ToName(), FrameColor); + ImUtf8.HoverTooltip("Model Race"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Race.ToName(), FrameColor); + ImUtf8.HoverTooltip("Gender"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Slot.ToName(), FrameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + + private static bool DrawEntry(EqdpEntryInternal defaultEntry, ref EqdpEntryInternal entry, bool disabled) + { + var changes = false; + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + if (Checkmark("Material##eqdp"u8, "\0"u8, entry.Material, defaultEntry.Material, out var newMaterial)) + { + entry = entry with { Material = newMaterial }; + changes = true; + } + + ImGui.SameLine(); + if (Checkmark("Model##eqdp"u8, "\0"u8, entry.Model, defaultEntry.Model, out var newModel)) + { + entry = entry with { Material = newModel }; + changes = true; + } + + return changes; + } + + public static bool DrawPrimaryId(ref EqdpIdentifier identifier, float unscaledWidth = 100) + { + var ret = IdInput("##eqdpPrimaryId"u8, unscaledWidth, identifier.SetId.Id, out var setId, 0, ExpandedEqpGmpBase.Count - 1, + identifier.SetId.Id <= 1); + ImUtf8.HoverTooltip( + "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + identifier = identifier with { SetId = setId }; + return ret; + } + + public static bool DrawRace(ref EqdpIdentifier identifier, float unscaledWidth = 100) + { + var ret = Combos.Race("##eqdpRace", identifier.Race, out var race, unscaledWidth); + ImUtf8.HoverTooltip("Model Race"u8); + if (ret) + identifier = identifier with { GenderRace = Names.CombinedRace(identifier.Gender, race) }; + return ret; + } + + public static bool DrawGender(ref EqdpIdentifier identifier, float unscaledWidth = 120) + { + var ret = Combos.Gender("##eqdpGender", identifier.Gender, out var gender, unscaledWidth); + ImUtf8.HoverTooltip("Gender"u8); + if (ret) + identifier = identifier with { GenderRace = Names.CombinedRace(gender, identifier.Race) }; + return ret; + } + + public static bool DrawEquipSlot(ref EqdpIdentifier identifier, float unscaledWidth = 100) + { + var ret = Combos.EqdpEquipSlot("##eqdpSlot", identifier.Slot, out var slot, unscaledWidth); + ImUtf8.HoverTooltip("Equip Slot"u8); + if (ret) + identifier = identifier with { Slot = slot }; + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs new file mode 100644 index 00000000..56c06bc9 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs @@ -0,0 +1,134 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class EqpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Equipment Parameter Edits (EQP)###EQP"u8; + + public override int NumColumns + => 5; + + protected override void Initialize() + { + Identifier = new EqpIdentifier(1, EquipSlot.Body); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = new EqpEntryInternal(ExpandedEqpFile.GetDefault(MetaFiles, Identifier.SetId), Identifier.Slot); + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current EQP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Eqp)); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, Entry); + + if (DrawIdentifierInput(ref Identifier)) + UpdateEntry(); + + DrawEntry(Identifier.Slot, Entry, ref Entry, true); + } + + protected override void DrawEntry(EqpIdentifier identifier, EqpEntryInternal entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + var defaultEntry = new EqpEntryInternal(ExpandedEqpFile.GetDefault(MetaFiles, identifier.SetId), identifier.Slot); + if (DrawEntry(identifier.Slot, defaultEntry, ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(EqpIdentifier, EqpEntryInternal)> Enumerate() + => Editor.Eqp.Select(kvp => (kvp.Key, kvp.Value)); + + private static bool DrawIdentifierInput(ref EqpIdentifier identifier) + { + ImGui.TableNextColumn(); + var changes = DrawPrimaryId(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawEquipSlot(ref identifier); + return changes; + } + + private static void DrawIdentifier(EqpIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.SetId.Id}", FrameColor); + ImUtf8.HoverTooltip("Model Set ID"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Slot.ToName(), FrameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + + private static bool DrawEntry(EquipSlot slot, EqpEntryInternal defaultEntry, ref EqpEntryInternal entry, bool disabled) + { + var changes = false; + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + var offset = Eqp.OffsetAndMask(slot).Item1; + DrawBox(ref entry, 0); + for (var i = 1; i < Eqp.EqpAttributes[slot].Count; ++i) + { + ImUtf8.SameLineInner(); + DrawBox(ref entry, i); + } + + return changes; + + void DrawBox(ref EqpEntryInternal entry, int i) + { + using var id = ImUtf8.PushId(i); + var flag = 1u << i; + var eqpFlag = (EqpEntry)((ulong)flag << offset); + var defaultValue = (flag & defaultEntry.Value) != 0; + var value = (flag & entry.Value) != 0; + if (Checkmark("##eqp"u8, eqpFlag.ToLocalName(), value, defaultValue, out var newValue)) + { + entry = new EqpEntryInternal(newValue ? entry.Value | flag : entry.Value & ~flag); + changes = true; + } + } + } + + public static bool DrawPrimaryId(ref EqpIdentifier identifier, float unscaledWidth = 100) + { + var ret = IdInput("##eqpPrimaryId"u8, unscaledWidth, identifier.SetId.Id, out var setId, 0, ExpandedEqpGmpBase.Count - 1, + identifier.SetId.Id <= 1); + ImUtf8.HoverTooltip( + "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + identifier = identifier with { SetId = setId }; + return ret; + } + + public static bool DrawEquipSlot(ref EqpIdentifier identifier, float unscaledWidth = 100) + { + var ret = Combos.EqpEquipSlot("##eqpSlot", identifier.Slot, out var slot, unscaledWidth); + ImUtf8.HoverTooltip("Equip Slot"u8); + if (ret) + identifier = identifier with { Slot = slot }; + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs new file mode 100644 index 00000000..5c3c5df5 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs @@ -0,0 +1,147 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class EstMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Extra Skeleton Parameters (EST)###EST"u8; + + public override int NumColumns + => 7; + + protected override void Initialize() + { + Identifier = new EstIdentifier(1, EstType.Hair, GenderRace.MidlanderMale); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = EstFile.GetDefault(MetaFiles, Identifier.Slot, Identifier.GenderRace, Identifier.SetId); + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current EST manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Est)); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, Entry); + + if (DrawIdentifierInput(ref Identifier)) + UpdateEntry(); + + DrawEntry(Entry, ref Entry, true); + } + + protected override void DrawEntry(EstIdentifier identifier, EstEntry entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + var defaultEntry = EstFile.GetDefault(MetaFiles, identifier.Slot, identifier.GenderRace, identifier.SetId); + if (DrawEntry(defaultEntry, ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(EstIdentifier, EstEntry)> Enumerate() + => Editor.Est.Select(kvp => (kvp.Key, kvp.Value)); + + private static bool DrawIdentifierInput(ref EstIdentifier identifier) + { + ImGui.TableNextColumn(); + var changes = DrawPrimaryId(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawRace(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawGender(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawSlot(ref identifier); + + return changes; + } + + private static void DrawIdentifier(EstIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.SetId.Id}", FrameColor); + ImUtf8.HoverTooltip("Model Set ID"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Race.ToName(), FrameColor); + ImUtf8.HoverTooltip("Model Race"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Gender.ToName(), FrameColor); + ImUtf8.HoverTooltip("Gender"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Slot.ToString(), FrameColor); + ImUtf8.HoverTooltip("Extra Skeleton Type"u8); + } + + private static bool DrawEntry(EstEntry defaultEntry, ref EstEntry entry, bool disabled) + { + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + var ret = DragInput("##estValue"u8, [], 100f * ImUtf8.GlobalScale, entry.Value, defaultEntry.Value, out var newValue, (ushort)0, + ushort.MaxValue, 0.05f, !disabled); + if (ret) + entry = new EstEntry(newValue); + return ret; + } + + public static bool DrawPrimaryId(ref EstIdentifier identifier, float unscaledWidth = 100) + { + var ret = IdInput("##estPrimaryId"u8, unscaledWidth, identifier.SetId.Id, out var setId, 0, ExpandedEqpGmpBase.Count - 1, + identifier.SetId.Id <= 1); + ImUtf8.HoverTooltip( + "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + identifier = identifier with { SetId = setId }; + return ret; + } + + public static bool DrawRace(ref EstIdentifier identifier, float unscaledWidth = 100) + { + var ret = Combos.Race("##estRace", identifier.Race, out var race, unscaledWidth); + ImUtf8.HoverTooltip("Model Race"u8); + if (ret) + identifier = identifier with { GenderRace = Names.CombinedRace(identifier.Gender, race) }; + return ret; + } + + public static bool DrawGender(ref EstIdentifier identifier, float unscaledWidth = 120) + { + var ret = Combos.Gender("##estGender", identifier.Gender, out var gender, unscaledWidth); + ImUtf8.HoverTooltip("Gender"u8); + if (ret) + identifier = identifier with { GenderRace = Names.CombinedRace(gender, identifier.Race) }; + return ret; + } + + public static bool DrawSlot(ref EstIdentifier identifier, float unscaledWidth = 200) + { + var ret = Combos.EstSlot("##estSlot", identifier.Slot, out var slot, unscaledWidth); + ImUtf8.HoverTooltip("Extra Skeleton Type"u8); + if (ret) + identifier = identifier with { Slot = slot }; + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs new file mode 100644 index 00000000..130831a0 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs @@ -0,0 +1,111 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class GlobalEqpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Global Equipment Parameter Edits (Global EQP)###GEQP"u8; + + public override int NumColumns + => 4; + + protected override void Initialize() + { + Identifier = new GlobalEqpManipulation() + { + Condition = 1, + Type = GlobalEqpType.DoNotHideEarrings, + }; + } + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current global EQP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.GlobalEqp)); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier); + + DrawIdentifierInput(ref Identifier); + } + + protected override void DrawEntry(GlobalEqpManipulation identifier, byte _) + { + DrawMetaButtons(identifier, 0); + DrawIdentifier(identifier); + } + + protected override IEnumerable<(GlobalEqpManipulation, byte)> Enumerate() + => Editor.GlobalEqp.Select(identifier => (identifier, (byte)0)); + + private static void DrawIdentifierInput(ref GlobalEqpManipulation identifier) + { + ImGui.TableNextColumn(); + DrawType(ref identifier); + + ImGui.TableNextColumn(); + if (identifier.Type.HasCondition()) + DrawCondition(ref identifier); + else + ImUtf8.ScaledDummy(100); + } + + private static void DrawIdentifier(GlobalEqpManipulation identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Type.ToName(), FrameColor); + ImUtf8.HoverTooltip("Global EQP Type"u8); + + ImGui.TableNextColumn(); + if (identifier.Type.HasCondition()) + { + ImUtf8.TextFramed($"{identifier.Condition.Id}", FrameColor); + ImUtf8.HoverTooltip("Conditional Model ID"u8); + } + } + + public static bool DrawType(ref GlobalEqpManipulation identifier, float unscaledWidth = 250) + { + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using var combo = ImUtf8.Combo("##geqpType"u8, identifier.Type.ToName()); + if (!combo) + return false; + + var ret = false; + foreach (var type in Enum.GetValues()) + { + if (ImUtf8.Selectable(type.ToName(), type == identifier.Type)) + { + identifier = new GlobalEqpManipulation + { + Type = type, + Condition = type.HasCondition() ? identifier.Type.HasCondition() ? identifier.Condition : 1 : 0, + }; + ret = true; + } + + ImUtf8.HoverTooltip(type.ToDescription()); + } + + return ret; + } + + public static void DrawCondition(ref GlobalEqpManipulation identifier, float unscaledWidth = 100) + { + if (IdInput("##geqpCond"u8, unscaledWidth, identifier.Condition.Id, out var newId, 1, ushort.MaxValue, + identifier.Condition.Id <= 1)) + identifier = identifier with { Condition = newId }; + ImUtf8.HoverTooltip("The Model ID for the item that should not be hidden."u8); + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs new file mode 100644 index 00000000..87ed21dc --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs @@ -0,0 +1,148 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Structs; +using Penumbra.Meta.Files; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class GmpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Visor/Gimmick Edits (GMP)###GMP"u8; + + public override int NumColumns + => 7; + + protected override void Initialize() + { + Identifier = new GmpIdentifier(1); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = ExpandedGmpFile.GetDefault(MetaFiles, Identifier.SetId); + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current Gmp manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Gmp)); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, Entry); + + if (DrawIdentifierInput(ref Identifier)) + UpdateEntry(); + + DrawEntry(Entry, ref Entry, true); + } + + protected override void DrawEntry(GmpIdentifier identifier, GmpEntry entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + var defaultEntry = ExpandedGmpFile.GetDefault(MetaFiles, identifier.SetId); + if (DrawEntry(defaultEntry, ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(GmpIdentifier, GmpEntry)> Enumerate() + => Editor.Gmp.Select(kvp => (kvp.Key, kvp.Value)); + + private static bool DrawIdentifierInput(ref GmpIdentifier identifier) + { + ImGui.TableNextColumn(); + return DrawPrimaryId(ref identifier); + } + + private static void DrawIdentifier(GmpIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.SetId.Id}", FrameColor); + ImUtf8.HoverTooltip("Model Set ID"u8); + } + + private static bool DrawEntry(GmpEntry defaultEntry, ref GmpEntry entry, bool disabled) + { + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + var changes = false; + if (Checkmark("##gmpEnabled"u8, "Gimmick Enabled", entry.Enabled, defaultEntry.Enabled, out var enabled)) + { + entry = entry with { Enabled = enabled }; + changes = true; + } + + ImGui.TableNextColumn(); + if (Checkmark("##gmpAnimated"u8, "Gimmick Animated", entry.Animated, defaultEntry.Animated, out var animated)) + { + entry = entry with { Animated = animated }; + changes = true; + } + + var rotationWidth = 75 * ImUtf8.GlobalScale; + ImGui.TableNextColumn(); + if (DragInput("##gmpRotationA"u8, "Rotation A in Degrees"u8, rotationWidth, entry.RotationA, defaultEntry.RotationA, out var rotationA, + (ushort)0, (ushort)360, 0.05f, !disabled)) + { + entry = entry with { RotationA = rotationA }; + changes = true; + } + + ImUtf8.SameLineInner(); + if (DragInput("##gmpRotationB"u8, "Rotation B in Degrees"u8, rotationWidth, entry.RotationB, defaultEntry.RotationB, out var rotationB, + (ushort)0, (ushort)360, 0.05f, !disabled)) + { + entry = entry with { RotationB = rotationB }; + changes = true; + } + + ImUtf8.SameLineInner(); + if (DragInput("##gmpRotationC"u8, "Rotation C in Degrees"u8, rotationWidth, entry.RotationC, defaultEntry.RotationC, out var rotationC, + (ushort)0, (ushort)360, 0.05f, !disabled)) + { + entry = entry with { RotationC = rotationC }; + changes = true; + } + + var unkWidth = 50 * ImUtf8.GlobalScale; + ImGui.TableNextColumn(); + if (DragInput("##gmpUnkA"u8, "Animation Type A?"u8, unkWidth, entry.UnknownA, defaultEntry.UnknownA, out var unknownA, + (byte)0, (byte)15, 0.01f, !disabled)) + { + entry = entry with { UnknownA = unknownA }; + changes = true; + } + + ImUtf8.SameLineInner(); + if (DragInput("##gmpUnkB"u8, "Animation Type B?"u8, unkWidth, entry.UnknownB, defaultEntry.UnknownB, out var unknownB, + (byte)0, (byte)15, 0.01f, !disabled)) + { + entry = entry with { UnknownB = unknownB }; + changes = true; + } + + return changes; + } + + public static bool DrawPrimaryId(ref GmpIdentifier identifier, float unscaledWidth = 100) + { + var ret = IdInput("##gmpPrimaryId"u8, unscaledWidth, identifier.SetId.Id, out var setId, 1, ExpandedEqpGmpBase.Count - 1, + identifier.SetId.Id <= 1); + ImUtf8.HoverTooltip( + "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."u8); + if (ret) + identifier = new GmpIdentifier(setId); + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index d9a8c27c..58f626fc 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -12,22 +12,16 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow.Meta; -public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) +public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) : MetaDrawer(editor, metaFiles), IService { - private bool _fileExists; + public override ReadOnlySpan Label + => "Variant Edits (IMC)###IMC"u8; - private const string ModelSetIdTooltipShort = "Model Set ID"; - private const string EquipSlotTooltip = "Equip Slot"; - private const string ModelRaceTooltip = "Model Race"; - private const string GenderTooltip = "Gender"; - private const string ObjectTypeTooltip = "Object Type"; - private const string SecondaryIdTooltip = "Secondary ID"; - private const string PrimaryIdTooltipShort = "Primary ID"; - private const string VariantIdTooltip = "Variant ID"; - private const string EstTypeTooltip = "EST Type"; - private const string RacialTribeTooltip = "Racial Tribe"; - private const string ScalingTypeTooltip = "Scaling Type"; + public override int NumColumns + => 10; + + private bool _fileExists; protected override void Initialize() { @@ -41,14 +35,14 @@ public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) protected override void DrawNew() { ImGui.TableNextColumn(); - // Copy To Clipboard + CopyToClipboardButton("Copy all current IMC manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Imc)); ImGui.TableNextColumn(); - var canAdd = _fileExists && Editor.MetaEditor.CanAdd(Identifier); + var canAdd = _fileExists && !Editor.Contains(Identifier); var tt = canAdd ? "Stage this edit."u8 : !_fileExists ? "This IMC file does not exist."u8 : "This entry is already edited."u8; if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) - Editor.MetaEditor.TryAdd(Identifier, Entry); + Editor.Changes |= Editor.TryAdd(Identifier, Entry); - if (DrawIdentifier(ref Identifier)) + if (DrawIdentifierInput(ref Identifier)) UpdateEntry(); using var disabled = ImRaii.Disabled(); @@ -57,46 +51,15 @@ public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) protected override void DrawEntry(ImcIdentifier identifier, ImcEntry entry) { - const uint frameColor = 0; - // Meta Buttons - - ImGui.TableNextColumn(); - ImUtf8.TextFramed(identifier.ObjectType.ToName(), frameColor); - ImUtf8.HoverTooltip("Object Type"u8); - - ImGui.TableNextColumn(); - ImUtf8.TextFramed($"{identifier.PrimaryId.Id}", frameColor); - ImUtf8.HoverTooltip("Primary ID"); - - ImGui.TableNextColumn(); - if (identifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) - { - ImUtf8.TextFramed(identifier.EquipSlot.ToName(), frameColor); - ImUtf8.HoverTooltip("Equip Slot"u8); - } - else - { - ImUtf8.TextFramed($"{identifier.SecondaryId.Id}", frameColor); - ImUtf8.HoverTooltip("Secondary ID"u8); - } - - ImGui.TableNextColumn(); - ImUtf8.TextFramed($"{identifier.Variant.Id}", frameColor); - ImUtf8.HoverTooltip("Variant"u8); - - ImGui.TableNextColumn(); - if (identifier.ObjectType is ObjectType.DemiHuman) - { - ImUtf8.TextFramed(identifier.EquipSlot.ToName(), frameColor); - ImUtf8.HoverTooltip("Equip Slot"u8); - } + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); var defaultEntry = MetaFiles.ImcChecker.GetDefaultEntry(identifier, true).Entry; if (DrawEntry(defaultEntry, ref entry, true)) - Editor.MetaEditor.Update(identifier, entry); + Editor.Changes |= Editor.Update(identifier, entry); } - private static bool DrawIdentifier(ref ImcIdentifier identifier) + private static bool DrawIdentifierInput(ref ImcIdentifier identifier) { ImGui.TableNextColumn(); var change = DrawObjectType(ref identifier); @@ -121,6 +84,41 @@ public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) return change; } + private static void DrawIdentifier(ImcIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.ObjectType.ToName(), FrameColor); + ImUtf8.HoverTooltip("Object Type"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.PrimaryId.Id}", FrameColor); + ImUtf8.HoverTooltip("Primary ID"); + + ImGui.TableNextColumn(); + if (identifier.ObjectType is ObjectType.Equipment or ObjectType.Accessory) + { + ImUtf8.TextFramed(identifier.EquipSlot.ToName(), FrameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + else + { + ImUtf8.TextFramed($"{identifier.SecondaryId.Id}", FrameColor); + ImUtf8.HoverTooltip("Secondary ID"u8); + } + + ImGui.TableNextColumn(); + ImUtf8.TextFramed($"{identifier.Variant.Id}", FrameColor); + ImUtf8.HoverTooltip("Variant"u8); + + ImGui.TableNextColumn(); + if (identifier.ObjectType is ObjectType.DemiHuman) + { + ImUtf8.TextFramed(identifier.EquipSlot.ToName(), FrameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + + } + private static bool DrawEntry(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault) { ImGui.TableNextColumn(); @@ -142,7 +140,7 @@ public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) protected override IEnumerable<(ImcIdentifier, ImcEntry)> Enumerate() - => Editor.MetaEditor.Imc.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Imc.Select(kvp => (kvp.Key, kvp.Value)); public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) { @@ -270,7 +268,7 @@ public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) return true; } - public static bool DrawAttributes(ImcEntry defaultEntry, ref ImcEntry entry) + private static bool DrawAttributes(ImcEntry defaultEntry, ref ImcEntry entry) { var changes = false; for (var i = 0; i < ImcEntry.NumAttributes; ++i) @@ -292,62 +290,4 @@ public sealed class ImcMetaDrawer(ModEditor editor, MetaFileManager metaFiles) return changes; } - - - /// - /// A number input for ids with an optional max id of given width. - /// Returns true if newId changed against currentId. - /// - private static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, - bool border) - { - int tmp = currentId; - ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); - if (ImUtf8.InputScalar(label, ref tmp)) - tmp = Math.Clamp(tmp, minId, maxId); - - newId = (ushort)tmp; - return newId != currentId; - } - - /// - /// A dragging int input of given width that compares against a default value, shows a tooltip and clamps against min and max. - /// Returns true if newValue changed against currentValue. - /// - private static bool DragInput(ReadOnlySpan label, ReadOnlySpan tooltip, float width, T currentValue, T defaultValue, - out T newValue, T minValue, T maxValue, float speed, bool addDefault) where T : unmanaged, INumber - { - newValue = currentValue; - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - defaultValue > currentValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), - defaultValue != currentValue); - ImGui.SetNextItemWidth(width); - if (ImUtf8.DragScalar(label, ref newValue, minValue, maxValue, speed)) - newValue = newValue <= minValue ? minValue : newValue >= maxValue ? maxValue : newValue; - - if (addDefault) - ImUtf8.HoverTooltip($"{tooltip}\nDefault Value: {defaultValue}"); - else - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); - - return newValue != currentValue; - } - - /// - /// A checkmark that compares against a default value and shows a tooltip. - /// Returns true if newValue is changed against currentValue. - /// - private static bool Checkmark(ReadOnlySpan label, ReadOnlySpan tooltip, bool currentValue, bool defaultValue, - out bool newValue) - { - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), - defaultValue != currentValue); - newValue = currentValue; - ImUtf8.Checkbox(label, ref newValue); - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); - return newValue != currentValue; - } } diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs new file mode 100644 index 00000000..229526c4 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -0,0 +1,154 @@ +using Dalamud.Interface; +using ImGuiNET; +using Newtonsoft.Json.Linq; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.Api.Api; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public interface IMetaDrawer +{ + public ReadOnlySpan Label { get; } + public int NumColumns { get; } + public void Draw(); +} + +public abstract class MetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) : IMetaDrawer + where TIdentifier : unmanaged, IMetaIdentifier + where TEntry : unmanaged +{ + protected const uint FrameColor = 0; + + protected readonly ModMetaEditor Editor = editor; + protected readonly MetaFileManager MetaFiles = metaFiles; + protected TIdentifier Identifier; + protected TEntry Entry; + private bool _initialized; + + public void Draw() + { + if (!_initialized) + { + Initialize(); + _initialized = true; + } + + using var id = ImUtf8.PushId((int)Identifier.Type); + DrawNew(); + foreach (var ((identifier, entry), idx) in Enumerate().WithIndex()) + { + id.Push(idx); + DrawEntry(identifier, entry); + id.Pop(); + } + } + + public abstract ReadOnlySpan Label { get; } + public abstract int NumColumns { get; } + + protected abstract void DrawNew(); + protected abstract void Initialize(); + protected abstract void DrawEntry(TIdentifier identifier, TEntry entry); + + protected abstract IEnumerable<(TIdentifier, TEntry)> Enumerate(); + + + /// + /// A number input for ids with an optional max id of given width. + /// Returns true if newId changed against currentId. + /// + protected static bool IdInput(ReadOnlySpan label, float unscaledWidth, ushort currentId, out ushort newId, int minId, int maxId, + bool border) + { + int tmp = currentId; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); + using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); + if (ImUtf8.InputScalar(label, ref tmp)) + tmp = Math.Clamp(tmp, minId, maxId); + + newId = (ushort)tmp; + return newId != currentId; + } + + /// + /// A dragging int input of given width that compares against a default value, shows a tooltip and clamps against min and max. + /// Returns true if newValue changed against currentValue. + /// + protected static bool DragInput(ReadOnlySpan label, ReadOnlySpan tooltip, float width, T currentValue, T defaultValue, + out T newValue, T minValue, T maxValue, float speed, bool addDefault) where T : unmanaged, INumber + { + newValue = currentValue; + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue > currentValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + ImGui.SetNextItemWidth(width); + if (ImUtf8.DragScalar(label, ref newValue, minValue, maxValue, speed)) + newValue = newValue <= minValue ? minValue : newValue >= maxValue ? maxValue : newValue; + + if (addDefault) + ImUtf8.HoverTooltip($"{tooltip}\nDefault Value: {defaultValue}"); + else + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + + return newValue != currentValue; + } + + /// + /// A checkmark that compares against a default value and shows a tooltip. + /// Returns true if newValue is changed against currentValue. + /// + protected static bool Checkmark(ReadOnlySpan label, ReadOnlySpan tooltip, bool currentValue, bool defaultValue, + out bool newValue) + { + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + newValue = currentValue; + ImUtf8.Checkbox(label, ref newValue); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + return newValue != currentValue; + } + + /// + /// A checkmark that compares against a default value and shows a tooltip. + /// Returns true if newValue is changed against currentValue. + /// + protected static bool Checkmark(ReadOnlySpan label, ReadOnlySpan tooltip, bool currentValue, bool defaultValue, + out bool newValue) + { + using var color = ImRaii.PushColor(ImGuiCol.FrameBg, + defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), + defaultValue != currentValue); + newValue = currentValue; + ImUtf8.Checkbox(label, ref newValue); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, tooltip); + return newValue != currentValue; + } + + protected void DrawMetaButtons(TIdentifier identifier, TEntry entry) + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy this manipulation to clipboard."u8, new JArray { MetaDictionary.Serialize(identifier, entry)! }); + + ImGui.TableNextColumn(); + if (ImUtf8.IconButton(FontAwesomeIcon.Trash, "Delete this meta manipulation."u8)) + Editor.Changes |= Editor.Remove(identifier); + } + + protected void CopyToClipboardButton(ReadOnlySpan tooltip, JToken? manipulations) + { + if (!ImUtf8.IconButton(FontAwesomeIcon.Clipboard, tooltip)) + return; + + var text = Functions.ToCompressedBase64(manipulations, MetaApi.CurrentVersion); + if (text.Length > 0) + ImGui.SetClipboardText(text); + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs new file mode 100644 index 00000000..b3dd9299 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs @@ -0,0 +1,35 @@ +using OtterGui.Services; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public class MetaDrawers( + EqdpMetaDrawer eqdp, + EqpMetaDrawer eqp, + EstMetaDrawer est, + GlobalEqpMetaDrawer globalEqp, + GmpMetaDrawer gmp, + ImcMetaDrawer imc, + RspMetaDrawer rsp) : IService +{ + public readonly EqdpMetaDrawer Eqdp = eqdp; + public readonly EqpMetaDrawer Eqp = eqp; + public readonly EstMetaDrawer Est = est; + public readonly GmpMetaDrawer Gmp = gmp; + public readonly RspMetaDrawer Rsp = rsp; + public readonly ImcMetaDrawer Imc = imc; + public readonly GlobalEqpMetaDrawer GlobalEqp = globalEqp; + + public IMetaDrawer? Get(MetaManipulationType type) + => type switch + { + MetaManipulationType.Imc => Imc, + MetaManipulationType.Eqdp => Eqdp, + MetaManipulationType.Eqp => Eqp, + MetaManipulationType.Est => Est, + MetaManipulationType.Gmp => Gmp, + MetaManipulationType.Rsp => Rsp, + MetaManipulationType.GlobalEqp => GlobalEqp, + _ => null, + }; +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs new file mode 100644 index 00000000..2b7904ce --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs @@ -0,0 +1,112 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class RspMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Racial Scaling Edits (RSP)###RSP"u8; + + public override int NumColumns + => 5; + + protected override void Initialize() + { + Identifier = new RspIdentifier(SubRace.Midlander, RspAttribute.MaleMinSize); + UpdateEntry(); + } + + private void UpdateEntry() + => Entry = CmpFile.GetDefault(MetaFiles, Identifier.SubRace, Identifier.Attribute); + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current RSP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Rsp)); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, Entry); + + if (DrawIdentifierInput(ref Identifier)) + UpdateEntry(); + + DrawEntry(Entry, ref Entry, true); + } + + protected override void DrawEntry(RspIdentifier identifier, RspEntry entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + var defaultEntry = CmpFile.GetDefault(MetaFiles, identifier.SubRace, identifier.Attribute); + if (DrawEntry(defaultEntry, ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(RspIdentifier, RspEntry)> Enumerate() + => Editor.Rsp.Select(kvp => (kvp.Key, kvp.Value)); + + private static bool DrawIdentifierInput(ref RspIdentifier identifier) + { + ImGui.TableNextColumn(); + var changes = DrawSubRace(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawAttribute(ref identifier); + return changes; + } + + private static void DrawIdentifier(RspIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.SubRace.ToName(), FrameColor); + ImUtf8.HoverTooltip("Model Set ID"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Attribute.ToFullString(), FrameColor); + ImUtf8.HoverTooltip("Equip Slot"u8); + } + + private static bool DrawEntry(RspEntry defaultEntry, ref RspEntry entry, bool disabled) + { + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + var ret = DragInput("##rspValue"u8, [], ImUtf8.GlobalScale * 150, defaultEntry.Value, entry.Value, out var newValue, + RspEntry.MinValue, RspEntry.MaxValue, 0.001f, !disabled); + if (ret) + entry = new RspEntry(newValue); + return ret; + } + + public static bool DrawSubRace(ref RspIdentifier identifier, float unscaledWidth = 150) + { + var ret = Combos.SubRace("##rspSubRace", identifier.SubRace, out var subRace, unscaledWidth); + ImUtf8.HoverTooltip("Racial Clan"u8); + if (ret) + identifier = identifier with { SubRace = subRace }; + return ret; + } + + public static bool DrawAttribute(ref RspIdentifier identifier, float unscaledWidth = 200) + { + var ret = Combos.RspAttribute("##rspAttribute", identifier.Attribute, out var attribute, unscaledWidth); + ImUtf8.HoverTooltip("Scaling Attribute"u8); + if (ret) + identifier = identifier with { Attribute = attribute }; + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 50862eec..3ec6a4d5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -1,27 +1,18 @@ -using System.Reflection.Emit; using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Text; -using OtterGui.Text.EndObjects; -using Penumbra.GameData.Enums; -using Penumbra.Interop.Structs; -using Penumbra.Meta; -using Penumbra.Meta.Files; +using Penumbra.Api.Api; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Editor; +using Penumbra.UI.AdvancedWindow.Meta; using Penumbra.UI.Classes; -using Penumbra.UI.ModsTab; namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private const string ModelSetIdTooltip = - "Model Set ID - You can usually find this as the 'e####' part of an item path.\nThis should generally not be left <= 1 unless you explicitly want that."; - - + private readonly MetaDrawers _metaDrawers; private void DrawMetaTab() { @@ -56,80 +47,42 @@ public partial class ModEditWindow if (!child) return; - DrawEditHeader(MetaManipulation.Type.Eqp); - DrawEditHeader(MetaManipulation.Type.Eqdp); - DrawEditHeader(MetaManipulation.Type.Imc); - DrawEditHeader(MetaManipulation.Type.Est); - DrawEditHeader(MetaManipulation.Type.Gmp); - DrawEditHeader(MetaManipulation.Type.Rsp); - DrawEditHeader(MetaManipulation.Type.GlobalEqp); + DrawEditHeader(MetaManipulationType.Eqp); + DrawEditHeader(MetaManipulationType.Eqdp); + DrawEditHeader(MetaManipulationType.Imc); + DrawEditHeader(MetaManipulationType.Est); + DrawEditHeader(MetaManipulationType.Gmp); + DrawEditHeader(MetaManipulationType.Rsp); + DrawEditHeader(MetaManipulationType.GlobalEqp); } - private static ReadOnlySpan Label(MetaManipulation.Type type) - => type switch - { - MetaManipulation.Type.Imc => "Variant Edits (IMC)###IMC"u8, - MetaManipulation.Type.Eqdp => "Racial Model Edits (EQDP)###EQDP"u8, - MetaManipulation.Type.Eqp => "Equipment Parameter Edits (EQP)###EQP"u8, - MetaManipulation.Type.Est => "Extra Skeleton Parameters (EST)###EST"u8, - MetaManipulation.Type.Gmp => "Visor/Gimmick Edits (GMP)###GMP"u8, - MetaManipulation.Type.Rsp => "Racial Scaling Edits (RSP)###RSP"u8, - MetaManipulation.Type.GlobalEqp => "Global Equipment Parameter Edits (Global EQP)###GEQP"u8, - _ => "\0"u8, - }; - - private static int ColumnCount(MetaManipulation.Type type) - => type switch - { - MetaManipulation.Type.Imc => 10, - MetaManipulation.Type.Eqdp => 7, - MetaManipulation.Type.Eqp => 5, - MetaManipulation.Type.Est => 7, - MetaManipulation.Type.Gmp => 7, - MetaManipulation.Type.Rsp => 5, - MetaManipulation.Type.GlobalEqp => 4, - _ => 0, - }; - - private void DrawEditHeader(MetaManipulation.Type type) + private void DrawEditHeader(MetaManipulationType type) { + var drawer = _metaDrawers.Get(type); + if (drawer == null) + return; + var oldPos = ImGui.GetCursorPosY(); - var header = ImUtf8.CollapsingHeader($"{_editor.MetaEditor.GetCount(type)} {Label(type)}"); + var header = ImUtf8.CollapsingHeader($"{_editor.MetaEditor.GetCount(type)} {drawer.Label}"); DrawOtherOptionData(type, oldPos, ImGui.GetCursorPos()); if (!header) return; - DrawTable(type); + DrawTable(drawer); } - private IMetaDrawer? Drawer(MetaManipulation.Type type) - => type switch - { - //MetaManipulation.Type.Imc => expr, - //MetaManipulation.Type.Eqdp => expr, - //MetaManipulation.Type.Eqp => expr, - //MetaManipulation.Type.Est => expr, - //MetaManipulation.Type.Gmp => expr, - //MetaManipulation.Type.Rsp => expr, - //MetaManipulation.Type.GlobalEqp => expr, - _ => null, - }; - - private void DrawTable(MetaManipulation.Type type) + private static void DrawTable(IMetaDrawer drawer) { const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.BordersInnerV; - using var table = ImUtf8.Table(Label(type), ColumnCount(type), flags); + using var table = ImUtf8.Table(drawer.Label, drawer.NumColumns, flags); if (!table) return; - if (Drawer(type) is not { } drawer) - return; - drawer.Draw(); ImGui.NewLine(); } - private void DrawOtherOptionData(MetaManipulation.Type type, float oldPos, Vector2 newPos) + private void DrawOtherOptionData(MetaManipulationType type, float oldPos, Vector2 newPos) { var otherOptionData = _editor.MetaEditor.OtherData[type]; if (otherOptionData.TotalCount <= 0) @@ -149,577 +102,12 @@ public partial class ModEditWindow ImGui.SetCursorPos(newPos); } -#if false - private static class EqpRow - { - private static EqpIdentifier _newIdentifier = new(1, EquipSlot.Body); - - private static float IdWidth - => 100 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current EQP manipulations to clipboard.", iconSize, - editor.MetaEditor.Eqp.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; - var defaultEntry = ExpandedEqpFile.GetDefault(metaFileManager, _new.SetId); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new.Copy(defaultEntry)); - - // Identifier - ImGui.TableNextColumn(); - if (IdInput("##eqpId", IdWidth, _new.SetId.Id, out var setId, 1, ExpandedEqpGmpBase.Count - 1, _new.SetId <= 1)) - _new = new EqpManipulation(ExpandedEqpFile.GetDefault(metaFileManager, setId), _new.Slot, setId); - - ImGuiUtil.HoverTooltip(ModelSetIdTooltip); - - ImGui.TableNextColumn(); - if (Combos.EqpEquipSlot("##eqpSlot", _new.Slot, out var slot)) - _new = new EqpManipulation(ExpandedEqpFile.GetDefault(metaFileManager, setId), slot, _new.SetId); - - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); - foreach (var flag in Eqp.EqpAttributes[_new.Slot]) - { - var value = defaultEntry.HasFlag(flag); - Checkmark("##eqp", flag.ToLocalName(), value, value, out _); - ImGui.SameLine(); - } - - ImGui.NewLine(); - } - - public static void Draw(MetaFileManager metaFileManager, EqpManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.SetId.ToString()); - ImGuiUtil.HoverTooltip(ModelSetIdTooltipShort); - var defaultEntry = ExpandedEqpFile.GetDefault(metaFileManager, meta.SetId); - - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Slot.ToName()); - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - - // Values - ImGui.TableNextColumn(); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - new Vector2(3 * UiHelpers.Scale, ImGui.GetStyle().ItemSpacing.Y)); - var idx = 0; - foreach (var flag in Eqp.EqpAttributes[meta.Slot]) - { - using var id = ImRaii.PushId(idx++); - var defaultValue = defaultEntry.HasFlag(flag); - var currentValue = meta.Entry.HasFlag(flag); - if (Checkmark("##eqp", flag.ToLocalName(), currentValue, defaultValue, out var value)) - editor.MetaEditor.Change(meta.Copy(value ? meta.Entry | flag : meta.Entry & ~flag)); - - ImGui.SameLine(); - } - - ImGui.NewLine(); - } - } - private static class EqdpRow - { - private static EqdpManipulation _new = new(EqdpEntry.Invalid, EquipSlot.Head, Gender.Male, ModelRace.Midlander, 1); - - private static float IdWidth - => 100 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current EQDP manipulations to clipboard.", iconSize, - editor.MetaEditor.Eqdp.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var raceCode = Names.CombinedRace(_new.Gender, _new.Race); - var validRaceCode = CharacterUtilityData.EqdpIdx(raceCode, false) >= 0; - var canAdd = validRaceCode && editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : - validRaceCode ? "This entry is already edited." : "This combination of race and gender can not be used."; - var defaultEntry = validRaceCode - ? ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), _new.Slot.IsAccessory(), _new.SetId) - : 0; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new.Copy(defaultEntry)); - - // Identifier - ImGui.TableNextColumn(); - if (IdInput("##eqdpId", IdWidth, _new.SetId.Id, out var setId, 0, ExpandedEqpGmpBase.Count - 1, _new.SetId <= 1)) - { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), - _new.Slot.IsAccessory(), setId); - _new = new EqdpManipulation(newDefaultEntry, _new.Slot, _new.Gender, _new.Race, setId); - } - - ImGuiUtil.HoverTooltip(ModelSetIdTooltip); - - ImGui.TableNextColumn(); - if (Combos.Race("##eqdpRace", _new.Race, out var race)) - { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, race), - _new.Slot.IsAccessory(), _new.SetId); - _new = new EqdpManipulation(newDefaultEntry, _new.Slot, _new.Gender, race, _new.SetId); - } - - ImGuiUtil.HoverTooltip(ModelRaceTooltip); - - ImGui.TableNextColumn(); - if (Combos.Gender("##eqdpGender", _new.Gender, out var gender)) - { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(gender, _new.Race), - _new.Slot.IsAccessory(), _new.SetId); - _new = new EqdpManipulation(newDefaultEntry, _new.Slot, gender, _new.Race, _new.SetId); - } - - ImGuiUtil.HoverTooltip(GenderTooltip); - - ImGui.TableNextColumn(); - if (Combos.EqdpEquipSlot("##eqdpSlot", _new.Slot, out var slot)) - { - var newDefaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(_new.Gender, _new.Race), - slot.IsAccessory(), _new.SetId); - _new = new EqdpManipulation(newDefaultEntry, slot, _new.Gender, _new.Race, _new.SetId); - } - - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - var (bit1, bit2) = defaultEntry.ToBits(_new.Slot); - Checkmark("Material##eqdpCheck1", string.Empty, bit1, bit1, out _); - ImGui.SameLine(); - Checkmark("Model##eqdpCheck2", string.Empty, bit2, bit2, out _); - } - - public static void Draw(MetaFileManager metaFileManager, EqdpManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.SetId.ToString()); - ImGuiUtil.HoverTooltip(ModelSetIdTooltipShort); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Race.ToName()); - ImGuiUtil.HoverTooltip(ModelRaceTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Gender.ToName()); - ImGuiUtil.HoverTooltip(GenderTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Slot.ToName()); - ImGuiUtil.HoverTooltip(EquipSlotTooltip); - - // Values - var defaultEntry = ExpandedEqdpFile.GetDefault(metaFileManager, Names.CombinedRace(meta.Gender, meta.Race), meta.Slot.IsAccessory(), - meta.SetId); - var (defaultBit1, defaultBit2) = defaultEntry.ToBits(meta.Slot); - var (bit1, bit2) = meta.Entry.ToBits(meta.Slot); - ImGui.TableNextColumn(); - if (Checkmark("Material##eqdpCheck1", string.Empty, bit1, defaultBit1, out var newBit1)) - editor.MetaEditor.Change(meta.Copy(Eqdp.FromSlotAndBits(meta.Slot, newBit1, bit2))); - - ImGui.SameLine(); - if (Checkmark("Model##eqdpCheck2", string.Empty, bit2, defaultBit2, out var newBit2)) - editor.MetaEditor.Change(meta.Copy(Eqdp.FromSlotAndBits(meta.Slot, bit1, newBit2))); - } - } - - private static class EstRow - { - private static EstManipulation _new = new(Gender.Male, ModelRace.Midlander, EstType.Body, 1, EstEntry.Zero); - - private static float IdWidth - => 100 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current EST manipulations to clipboard.", iconSize, - editor.MetaEditor.Est.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; - var defaultEntry = EstFile.GetDefault(metaFileManager, _new.Slot, Names.CombinedRace(_new.Gender, _new.Race), _new.SetId); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new.Copy(defaultEntry)); - - // Identifier - ImGui.TableNextColumn(); - if (IdInput("##estId", IdWidth, _new.SetId.Id, out var setId, 0, ExpandedEqpGmpBase.Count - 1, _new.SetId <= 1)) - { - var newDefaultEntry = EstFile.GetDefault(metaFileManager, _new.Slot, Names.CombinedRace(_new.Gender, _new.Race), setId); - _new = new EstManipulation(_new.Gender, _new.Race, _new.Slot, setId, newDefaultEntry); - } - - ImGuiUtil.HoverTooltip(ModelSetIdTooltip); - - ImGui.TableNextColumn(); - if (Combos.Race("##estRace", _new.Race, out var race)) - { - var newDefaultEntry = EstFile.GetDefault(metaFileManager, _new.Slot, Names.CombinedRace(_new.Gender, race), _new.SetId); - _new = new EstManipulation(_new.Gender, race, _new.Slot, _new.SetId, newDefaultEntry); - } - - ImGuiUtil.HoverTooltip(ModelRaceTooltip); - - ImGui.TableNextColumn(); - if (Combos.Gender("##estGender", _new.Gender, out var gender)) - { - var newDefaultEntry = EstFile.GetDefault(metaFileManager, _new.Slot, Names.CombinedRace(gender, _new.Race), _new.SetId); - _new = new EstManipulation(gender, _new.Race, _new.Slot, _new.SetId, newDefaultEntry); - } - - ImGuiUtil.HoverTooltip(GenderTooltip); - - ImGui.TableNextColumn(); - if (Combos.EstSlot("##estSlot", _new.Slot, out var slot)) - { - var newDefaultEntry = EstFile.GetDefault(metaFileManager, slot, Names.CombinedRace(_new.Gender, _new.Race), _new.SetId); - _new = new EstManipulation(_new.Gender, _new.Race, slot, _new.SetId, newDefaultEntry); - } - - ImGuiUtil.HoverTooltip(EstTypeTooltip); - - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - IntDragInput("##estSkeleton", "Skeleton Index", IdWidth, _new.Entry.Value, defaultEntry.Value, out _, 0, ushort.MaxValue, 0.05f); - } - - public static void Draw(MetaFileManager metaFileManager, EstManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.SetId.ToString()); - ImGuiUtil.HoverTooltip(ModelSetIdTooltipShort); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Race.ToName()); - ImGuiUtil.HoverTooltip(ModelRaceTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Gender.ToName()); - ImGuiUtil.HoverTooltip(GenderTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Slot.ToString()); - ImGuiUtil.HoverTooltip(EstTypeTooltip); - - // Values - var defaultEntry = EstFile.GetDefault(metaFileManager, meta.Slot, Names.CombinedRace(meta.Gender, meta.Race), meta.SetId); - ImGui.TableNextColumn(); - if (IntDragInput("##estSkeleton", $"Skeleton Index\nDefault Value: {defaultEntry}", IdWidth, meta.Entry.Value, defaultEntry.Value, - out var entry, 0, ushort.MaxValue, 0.05f)) - editor.MetaEditor.Change(meta.Copy(new EstEntry((ushort)entry))); - } - } - private static class GmpRow - { - private static GmpManipulation _new = new(GmpEntry.Default, 1); - - private static float RotationWidth - => 75 * UiHelpers.Scale; - - private static float UnkWidth - => 50 * UiHelpers.Scale; - - private static float IdWidth - => 100 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current GMP manipulations to clipboard.", iconSize, - editor.MetaEditor.Gmp.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; - var defaultEntry = ExpandedGmpFile.GetDefault(metaFileManager, _new.SetId); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new.Copy(defaultEntry)); - - // Identifier - ImGui.TableNextColumn(); - if (IdInput("##gmpId", IdWidth, _new.SetId.Id, out var setId, 1, ExpandedEqpGmpBase.Count - 1, _new.SetId <= 1)) - _new = new GmpManipulation(ExpandedGmpFile.GetDefault(metaFileManager, setId), setId); - - ImGuiUtil.HoverTooltip(ModelSetIdTooltip); - - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - Checkmark("##gmpEnabled", "Gimmick Enabled", defaultEntry.Enabled, defaultEntry.Enabled, out _); - ImGui.TableNextColumn(); - Checkmark("##gmpAnimated", "Gimmick Animated", defaultEntry.Animated, defaultEntry.Animated, out _); - ImGui.TableNextColumn(); - IntDragInput("##gmpRotationA", "Rotation A in Degrees", RotationWidth, defaultEntry.RotationA, defaultEntry.RotationA, out _, 0, - 360, 0f); - ImGui.SameLine(); - IntDragInput("##gmpRotationB", "Rotation B in Degrees", RotationWidth, defaultEntry.RotationB, defaultEntry.RotationB, out _, 0, - 360, 0f); - ImGui.SameLine(); - IntDragInput("##gmpRotationC", "Rotation C in Degrees", RotationWidth, defaultEntry.RotationC, defaultEntry.RotationC, out _, 0, - 360, 0f); - ImGui.TableNextColumn(); - IntDragInput("##gmpUnkA", "Animation Type A?", UnkWidth, defaultEntry.UnknownA, defaultEntry.UnknownA, out _, 0, 15, 0f); - ImGui.SameLine(); - IntDragInput("##gmpUnkB", "Animation Type B?", UnkWidth, defaultEntry.UnknownB, defaultEntry.UnknownB, out _, 0, 15, 0f); - } - - public static void Draw(MetaFileManager metaFileManager, GmpManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.SetId.ToString()); - ImGuiUtil.HoverTooltip(ModelSetIdTooltipShort); - - // Values - var defaultEntry = ExpandedGmpFile.GetDefault(metaFileManager, meta.SetId); - ImGui.TableNextColumn(); - if (Checkmark("##gmpEnabled", "Gimmick Enabled", meta.Entry.Enabled, defaultEntry.Enabled, out var enabled)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { Enabled = enabled })); - - ImGui.TableNextColumn(); - if (Checkmark("##gmpAnimated", "Gimmick Animated", meta.Entry.Animated, defaultEntry.Animated, out var animated)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { Animated = animated })); - - ImGui.TableNextColumn(); - if (IntDragInput("##gmpRotationA", $"Rotation A in Degrees\nDefault Value: {defaultEntry.RotationA}", RotationWidth, - meta.Entry.RotationA, defaultEntry.RotationA, out var rotationA, 0, 360, 0.05f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { RotationA = (ushort)rotationA })); - - ImGui.SameLine(); - if (IntDragInput("##gmpRotationB", $"Rotation B in Degrees\nDefault Value: {defaultEntry.RotationB}", RotationWidth, - meta.Entry.RotationB, defaultEntry.RotationB, out var rotationB, 0, 360, 0.05f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { RotationB = (ushort)rotationB })); - - ImGui.SameLine(); - if (IntDragInput("##gmpRotationC", $"Rotation C in Degrees\nDefault Value: {defaultEntry.RotationC}", RotationWidth, - meta.Entry.RotationC, defaultEntry.RotationC, out var rotationC, 0, 360, 0.05f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { RotationC = (ushort)rotationC })); - - ImGui.TableNextColumn(); - if (IntDragInput("##gmpUnkA", $"Animation Type A?\nDefault Value: {defaultEntry.UnknownA}", UnkWidth, meta.Entry.UnknownA, - defaultEntry.UnknownA, out var unkA, 0, 15, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { UnknownA = (byte)unkA })); - - ImGui.SameLine(); - if (IntDragInput("##gmpUnkB", $"Animation Type B?\nDefault Value: {defaultEntry.UnknownB}", UnkWidth, meta.Entry.UnknownB, - defaultEntry.UnknownB, out var unkB, 0, 15, 0.01f)) - editor.MetaEditor.Change(meta.Copy(meta.Entry with { UnknownB = (byte)unkB })); - } - } - private static class RspRow - { - private static RspManipulation _new = new(SubRace.Midlander, RspAttribute.MaleMinSize, RspEntry.One); - - private static float FloatWidth - => 150 * UiHelpers.Scale; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current RSP manipulations to clipboard.", iconSize, - editor.MetaEditor.Rsp.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already edited."; - var defaultEntry = CmpFile.GetDefault(metaFileManager, _new.SubRace, _new.Attribute); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new.Copy(defaultEntry)); - - // Identifier - ImGui.TableNextColumn(); - if (Combos.SubRace("##rspSubRace", _new.SubRace, out var subRace)) - _new = new RspManipulation(subRace, _new.Attribute, CmpFile.GetDefault(metaFileManager, subRace, _new.Attribute)); - - ImGuiUtil.HoverTooltip(RacialTribeTooltip); - - ImGui.TableNextColumn(); - if (Combos.RspAttribute("##rspAttribute", _new.Attribute, out var attribute)) - _new = new RspManipulation(_new.SubRace, attribute, CmpFile.GetDefault(metaFileManager, subRace, attribute)); - - ImGuiUtil.HoverTooltip(ScalingTypeTooltip); - - // Values - using var disabled = ImRaii.Disabled(); - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(FloatWidth); - var value = defaultEntry.Value; - ImGui.DragFloat("##rspValue", ref value, 0f); - } - - public static void Draw(MetaFileManager metaFileManager, RspManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.SubRace.ToName()); - ImGuiUtil.HoverTooltip(RacialTribeTooltip); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImGui.TextUnformatted(meta.Attribute.ToFullString()); - ImGuiUtil.HoverTooltip(ScalingTypeTooltip); - ImGui.TableNextColumn(); - - // Values - var def = CmpFile.GetDefault(metaFileManager, meta.SubRace, meta.Attribute).Value; - var value = meta.Entry.Value; - ImGui.SetNextItemWidth(FloatWidth); - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - def < value ? ColorId.IncreasedMetaValue.Value() : ColorId.DecreasedMetaValue.Value(), - def != value); - if (ImGui.DragFloat("##rspValue", ref value, 0.001f, RspEntry.MinValue, RspEntry.MaxValue) - && value is >= RspEntry.MinValue and <= RspEntry.MaxValue) - editor.MetaEditor.Change(meta.Copy(new RspEntry(value))); - - ImGuiUtil.HoverTooltip($"Default Value: {def:0.###}"); - } - } - private static class GlobalEqpRow - { - private static GlobalEqpManipulation _new = new() - { - Type = GlobalEqpType.DoNotHideEarrings, - Condition = 1, - }; - - public static void DrawNew(MetaFileManager metaFileManager, ModEditor editor, Vector2 iconSize) - { - ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current global EQP manipulations to clipboard.", iconSize, - editor.MetaEditor.GlobalEqp.Select(m => (MetaManipulation)m)); - ImGui.TableNextColumn(); - var canAdd = editor.MetaEditor.CanAdd(_new); - var tt = canAdd ? "Stage this edit." : "This entry is already manipulated."; - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), iconSize, tt, !canAdd, true)) - editor.MetaEditor.Add(_new); - - // Identifier - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(250 * ImUtf8.GlobalScale); - using (var combo = ImUtf8.Combo("##geqpType"u8, _new.Type.ToName())) - { - if (combo) - foreach (var type in Enum.GetValues()) - { - if (ImUtf8.Selectable(type.ToName(), type == _new.Type)) - _new = new GlobalEqpManipulation - { - Type = type, - Condition = type.HasCondition() ? _new.Type.HasCondition() ? _new.Condition : 1 : 0, - }; - ImUtf8.HoverTooltip(type.ToDescription()); - } - } - - ImUtf8.HoverTooltip(_new.Type.ToDescription()); - - ImGui.TableNextColumn(); - if (!_new.Type.HasCondition()) - return; - - if (IdInput("##geqpCond", 100 * ImUtf8.GlobalScale, _new.Condition.Id, out var newId, 1, ushort.MaxValue, _new.Condition.Id <= 1)) - _new = _new with { Condition = newId }; - ImUtf8.HoverTooltip("The Model ID for the item that should not be hidden."u8); - } - - public static void Draw(MetaFileManager metaFileManager, GlobalEqpManipulation meta, ModEditor editor, Vector2 iconSize) - { - DrawMetaButtons(meta, editor, iconSize); - ImGui.TableNextColumn(); - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImUtf8.Text(meta.Type.ToName()); - ImUtf8.HoverTooltip(meta.Type.ToDescription()); - ImGui.TableNextColumn(); - if (meta.Type.HasCondition()) - { - ImGui.SetCursorPosX(ImGui.GetCursorPosX() + ImGui.GetStyle().FramePadding.X); - ImUtf8.Text($"{meta.Condition.Id}"); - } - } - } -#endif - - // A number input for ids with a optional max id of given width. - // Returns true if newId changed against currentId. - private static bool IdInput(string label, float width, ushort currentId, out ushort newId, int minId, int maxId, bool border) - { - int tmp = currentId; - ImGui.SetNextItemWidth(width); - using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, UiHelpers.Scale, border); - using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.RegexWarningBorder, border); - if (ImGui.InputInt(label, ref tmp, 0)) - tmp = Math.Clamp(tmp, minId, maxId); - - newId = (ushort)tmp; - return newId != currentId; - } - - // A checkmark that compares against a default value and shows a tooltip. - // Returns true if newValue is changed against currentValue. - private static bool Checkmark(string label, string tooltip, bool currentValue, bool defaultValue, out bool newValue) - { - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - defaultValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), - defaultValue != currentValue); - newValue = currentValue; - ImGui.Checkbox(label, ref newValue); - ImGuiUtil.HoverTooltip(tooltip, ImGuiHoveredFlags.AllowWhenDisabled); - return newValue != currentValue; - } - - // A dragging int input of given width that compares against a default value, shows a tooltip and clamps against min and max. - // Returns true if newValue changed against currentValue. - private static bool IntDragInput(string label, string tooltip, float width, int currentValue, int defaultValue, out int newValue, - int minValue, int maxValue, float speed) - { - newValue = currentValue; - using var color = ImRaii.PushColor(ImGuiCol.FrameBg, - defaultValue > currentValue ? ColorId.DecreasedMetaValue.Value() : ColorId.IncreasedMetaValue.Value(), - defaultValue != currentValue); - ImGui.SetNextItemWidth(width); - if (ImGui.DragInt(label, ref newValue, speed, minValue, maxValue)) - newValue = Math.Clamp(newValue, minValue, maxValue); - - ImGuiUtil.HoverTooltip(tooltip, ImGuiHoveredFlags.AllowWhenDisabled); - - return newValue != currentValue; - } - private static void CopyToClipboardButton(string tooltip, Vector2 iconSize, MetaDictionary manipulations) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), iconSize, tooltip, false, true)) return; - var text = Functions.ToCompressedBase64(manipulations, MetaManipulation.CurrentVersion); + var text = Functions.ToCompressedBase64(manipulations, MetaApi.CurrentVersion); if (text.Length > 0) ImGui.SetClipboardText(text); } @@ -731,8 +119,11 @@ public partial class ModEditWindow var clipboard = ImGuiUtil.GetClipboardText(); var version = Functions.FromCompressedBase64(clipboard, out var manips); - if (version == MetaManipulation.CurrentVersion && manips != null) + if (version == MetaApi.CurrentVersion && manips != null) + { _editor.MetaEditor.UpdateTo(manips); + _editor.MetaEditor.Changes = true; + } } ImGuiUtil.HoverTooltip( @@ -745,194 +136,14 @@ public partial class ModEditWindow { var clipboard = ImGuiUtil.GetClipboardText(); var version = Functions.FromCompressedBase64(clipboard, out var manips); - if (version == MetaManipulation.CurrentVersion && manips != null) + if (version == MetaApi.CurrentVersion && manips != null) + { _editor.MetaEditor.SetTo(manips); + _editor.MetaEditor.Changes = true; + } } ImGuiUtil.HoverTooltip( "Try to set the current meta manipulations to the set currently stored in the clipboard.\nRemoves all other manipulations."); } - - private static void DrawMetaButtons(MetaManipulation meta, ModEditor editor, Vector2 iconSize) - { - //ImGui.TableNextColumn(); - //CopyToClipboardButton("Copy this manipulation to clipboard.", iconSize, Array.Empty().Append(meta)); - // - //ImGui.TableNextColumn(); - //if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Trash.ToIconString(), iconSize, "Delete this meta manipulation.", false, true)) - // editor.MetaEditor.Delete(meta); - } -} - - -public interface IMetaDrawer -{ - public void Draw(); } - - - - -public abstract class MetaDrawer(ModEditor editor, MetaFileManager metaFiles) : IMetaDrawer - where TIdentifier : unmanaged, IMetaIdentifier - where TEntry : unmanaged -{ - protected readonly ModEditor Editor = editor; - protected readonly MetaFileManager MetaFiles = metaFiles; - protected TIdentifier Identifier; - protected TEntry Entry; - private bool _initialized; - - public void Draw() - { - if (!_initialized) - { - Initialize(); - _initialized = true; - } - - DrawNew(); - foreach (var ((identifier, entry), idx) in Enumerate().WithIndex()) - { - using var id = ImUtf8.PushId(idx); - DrawEntry(identifier, entry); - } - } - - protected abstract void DrawNew(); - protected abstract void Initialize(); - protected abstract void DrawEntry(TIdentifier identifier, TEntry entry); - - protected abstract IEnumerable<(TIdentifier, TEntry)> Enumerate(); -} - - -#if false -public sealed class GmpMetaDrawer(ModEditor editor) : MetaDrawer, IService -{ - protected override void Initialize() - { - Identifier = new GmpIdentifier(1, EquipSlot.Body); - UpdateEntry(); - } - - private void UpdateEntry() - => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); - - protected override void DrawNew() - { } - - protected override void DrawEntry(GmpIdentifier identifier, GmpEntry entry) - { } - - protected override IEnumerable<(GmpIdentifier, GmpEntry)> Enumerate() - => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); -} - -public sealed class EstMetaDrawer(ModEditor editor) : MetaDrawer, IService -{ - protected override void Initialize() - { - Identifier = new EqpIdentifier(1, EquipSlot.Body); - UpdateEntry(); - } - - private void UpdateEntry() - => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); - - protected override void DrawNew() - { } - - protected override void DrawEntry(EstIdentifier identifier, EstEntry entry) - { } - - protected override IEnumerable<(EstIdentifier, EstEntry)> Enumerate() - => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); -} - -public sealed class EqdpMetaDrawer(ModEditor editor) : MetaDrawer, IService -{ - protected override void Initialize() - { - Identifier = new EqdpIdentifier(1, EquipSlot.Body); - UpdateEntry(); - } - - private void UpdateEntry() - => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); - - protected override void DrawNew() - { } - - protected override void DrawEntry(EqdpIdentifier identifier, EqdpEntry entry) - { } - - protected override IEnumerable<(EqdpIdentifier, EqdpEntry)> Enumerate() - => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); -} - -public sealed class EqpMetaDrawer(ModEditor editor, MetaFileManager metaManager) : MetaDrawer, IService -{ - protected override void Initialize() - { - Identifier = new EqpIdentifier(1, EquipSlot.Body); - UpdateEntry(); - } - - private void UpdateEntry() - => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); - - protected override void DrawNew() - { } - - protected override void DrawEntry(EqpIdentifier identifier, EqpEntry entry) - { } - - protected override IEnumerable<(EqpIdentifier, EqpEntry)> Enumerate() - => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); -} - -public sealed class RspMetaDrawer(ModEditor editor) : MetaDrawer, IService -{ - protected override void Initialize() - { - Identifier = new RspIdentifier(1, EquipSlot.Body); - UpdateEntry(); - } - - private void UpdateEntry() - => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); - - protected override void DrawNew() - { } - - protected override void DrawEntry(RspIdentifier identifier, RspEntry entry) - { } - - protected override IEnumerable<(RspIdentifier, RspEntry)> Enumerate() - => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); -} - - - -public sealed class GlobalEqpMetaDrawer(ModEditor editor) : MetaDrawer, IService -{ - protected override void Initialize() - { - Identifier = new EqpIdentifier(1, EquipSlot.Body); - UpdateEntry(); - } - - private void UpdateEntry() - => Entry = ExpandedEqpFile.GetDefault(metaManager, Identifier.SetId); - - protected override void DrawNew() - { } - - protected override void DrawEntry(GlobalEqpManipulation identifier, byte _) - { } - - protected override IEnumerable<(GlobalEqpManipulation, byte)> Enumerate() - => editor.MetaEditor.Eqp.Select(kvp => (kvp.Key, kvp.Value.ToEntry(kvp.Key.Slot))); -} -#endif diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 1f935eb6..72ab37b2 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -95,7 +95,7 @@ public partial class ModEditWindow task.ContinueWith(t => { GamePaths = FinalizeIo(t); }, TaskScheduler.Default); } - private EstManipulation[] GetCurrentEstManipulations() + private KeyValuePair[] GetCurrentEstManipulations() { var mod = _edit._editor.Mod; var option = _edit._editor.Option; @@ -106,9 +106,7 @@ public partial class ModEditWindow return mod.AllDataContainers .Where(subMod => subMod != option) .Prepend(option) - .SelectMany(subMod => subMod.Manipulations) - .Where(manipulation => manipulation.ManipulationType is MetaManipulation.Type.Est) - .Select(manipulation => manipulation.Est) + .SelectMany(subMod => subMod.Manipulations.Est) .ToArray(); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index af01047b..9410b793 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -25,6 +25,7 @@ using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; +using Penumbra.UI.AdvancedWindow.Meta; using Penumbra.UI.Classes; using Penumbra.Util; using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; @@ -586,7 +587,7 @@ public partial class ModEditWindow : Window, IDisposable StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, ResourceTreeViewerFactory resourceTreeViewerFactory, ObjectManager objects, IFramework framework, - CharacterBaseDestructor characterBaseDestructor) + CharacterBaseDestructor characterBaseDestructor, MetaDrawers metaDrawers) : base(WindowBaseLabel) { _performance = performance; @@ -606,6 +607,7 @@ public partial class ModEditWindow : Window, IDisposable _objects = objects; _framework = framework; _characterBaseDestructor = characterBaseDestructor; + _metaDrawers = metaDrawers; _materialTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => Mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 5e3aac48..962d156d 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -120,9 +120,9 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy { var _ = data switch { - Utf8GamePath p => ImGuiNative.igSelectable_Bool(p.Path.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) > 0, - MetaManipulation m => ImGui.Selectable(m.Manipulation?.ToString() ?? string.Empty), - _ => false, + Utf8GamePath p => ImGuiNative.igSelectable_Bool(p.Path.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) > 0, + IMetaIdentifier m => ImGui.Selectable(m.ToString()), + _ => false, }; } } diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index 37561000..7076b80f 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -98,7 +98,7 @@ public class EffectiveTab(CollectionManager collectionManager, CollectionSelectH // Filters mean we can not use the known counts. if (hasFilters) { - var it2 = m.Select(p => (p.Key.ToString(), p.Value.Name)); + var it2 = m.IdentifierSources.Select(p => (p.Item1.ToString(), p.Item2.Name)); if (stop >= 0) { ImGuiClip.DrawEndDummy(stop + it2.Count(CheckFilters), height); @@ -117,7 +117,7 @@ public class EffectiveTab(CollectionManager collectionManager, CollectionSelectH } else { - stop = ImGuiClip.ClippedDraw(m, skips, DrawLine, m.Count, ~stop); + stop = ImGuiClip.ClippedDraw(m.IdentifierSources, skips, DrawLine, m.Count, ~stop); ImGuiClip.DrawEndDummy(stop, height); } } @@ -152,11 +152,11 @@ public class EffectiveTab(CollectionManager collectionManager, CollectionSelectH ImGui.TableNextColumn(); ImGuiUtil.PrintIcon(FontAwesomeIcon.LongArrowAltLeft); ImGui.TableNextColumn(); - ImGuiUtil.CopyOnClickSelectable(name); + ImGuiUtil.CopyOnClickSelectable(name.Text); } /// Draw a line for a unfiltered/unconverted manipulation and mod-index pair. - private static void DrawLine(KeyValuePair pair) + private static void DrawLine((IMetaIdentifier, IMod) pair) { var (manipulation, mod) = pair; ImGui.TableNextColumn(); @@ -165,7 +165,7 @@ public class EffectiveTab(CollectionManager collectionManager, CollectionSelectH ImGui.TableNextColumn(); ImGuiUtil.PrintIcon(FontAwesomeIcon.LongArrowAltLeft); ImGui.TableNextColumn(); - ImGuiUtil.CopyOnClickSelectable(mod.Name); + ImGuiUtil.CopyOnClickSelectable(mod.Name.Text); } /// Check filters for file replacements. diff --git a/Penumbra/Util/IdentifierExtensions.cs b/Penumbra/Util/IdentifierExtensions.cs index 0647ea8e..cb43ac06 100644 --- a/Penumbra/Util/IdentifierExtensions.cs +++ b/Penumbra/Util/IdentifierExtensions.cs @@ -2,7 +2,6 @@ using OtterGui.Classes; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.SubMods; @@ -10,103 +9,14 @@ namespace Penumbra.Util; public static class IdentifierExtensions { - /// Compute the items changed by a given meta manipulation and put them into the changedItems dictionary. - public static void MetaChangedItems(this ObjectIdentification identifier, IDictionary changedItems, - MetaManipulation manip) - { - switch (manip.ManipulationType) - { - case MetaManipulation.Type.Imc: - switch (manip.Imc.ObjectType) - { - case ObjectType.Equipment: - case ObjectType.Accessory: - identifier.Identify(changedItems, - GamePaths.Equipment.Mtrl.Path(manip.Imc.PrimaryId, GenderRace.MidlanderMale, manip.Imc.EquipSlot, manip.Imc.Variant, - "a")); - break; - case ObjectType.Weapon: - identifier.Identify(changedItems, - GamePaths.Weapon.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.Variant, "a")); - break; - case ObjectType.DemiHuman: - identifier.Identify(changedItems, - GamePaths.DemiHuman.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.EquipSlot, manip.Imc.Variant, - "a")); - break; - case ObjectType.Monster: - identifier.Identify(changedItems, - GamePaths.Monster.Mtrl.Path(manip.Imc.PrimaryId, manip.Imc.SecondaryId, manip.Imc.Variant, "a")); - break; - } - - break; - case MetaManipulation.Type.Eqdp: - identifier.Identify(changedItems, - GamePaths.Equipment.Mdl.Path(manip.Eqdp.SetId, Names.CombinedRace(manip.Eqdp.Gender, manip.Eqdp.Race), manip.Eqdp.Slot)); - break; - case MetaManipulation.Type.Eqp: - identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Eqp.SetId, GenderRace.MidlanderMale, manip.Eqp.Slot)); - break; - case MetaManipulation.Type.Est: - switch (manip.Est.Slot) - { - case EstType.Hair: - changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Hair (Hair) {manip.Est.SetId}", null); - break; - case EstType.Face: - changedItems.TryAdd($"Customization: {manip.Est.Race} {manip.Est.Gender} Face (Face) {manip.Est.SetId}", null); - break; - case EstType.Body: - identifier.Identify(changedItems, - GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), - EquipSlot.Body)); - break; - case EstType.Head: - identifier.Identify(changedItems, - GamePaths.Equipment.Mdl.Path(manip.Est.SetId, Names.CombinedRace(manip.Est.Gender, manip.Est.Race), - EquipSlot.Head)); - break; - } - - break; - case MetaManipulation.Type.Gmp: - identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(manip.Gmp.SetId, GenderRace.MidlanderMale, EquipSlot.Head)); - break; - case MetaManipulation.Type.Rsp: - changedItems.TryAdd($"{manip.Rsp.SubRace.ToName()} {manip.Rsp.Attribute.ToFullString()}", null); - break; - case MetaManipulation.Type.GlobalEqp: - var path = manip.GlobalEqp.Type switch - { - GlobalEqpType.DoNotHideEarrings => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, - EquipSlot.Ears), - GlobalEqpType.DoNotHideNecklace => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, - EquipSlot.Neck), - GlobalEqpType.DoNotHideBracelets => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, - EquipSlot.Wrists), - GlobalEqpType.DoNotHideRingR => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, - EquipSlot.RFinger), - GlobalEqpType.DoNotHideRingL => GamePaths.Accessory.Mdl.Path(manip.GlobalEqp.Condition, GenderRace.MidlanderMale, - EquipSlot.LFinger), - GlobalEqpType.DoNotHideHrothgarHats => string.Empty, - GlobalEqpType.DoNotHideVieraHats => string.Empty, - _ => string.Empty, - }; - if (path.Length > 0) - identifier.Identify(changedItems, path); - break; - } - } - public static void AddChangedItems(this ObjectIdentification identifier, IModDataContainer container, IDictionary changedItems) { foreach (var gamePath in container.Files.Keys.Concat(container.FileSwaps.Keys)) identifier.Identify(changedItems, gamePath.ToString()); - foreach (var manip in container.Manipulations) - MetaChangedItems(identifier, changedItems, manip); + foreach (var manip in container.Manipulations.Identifiers) + manip.AddChangedItems(identifier, changedItems); } public static void RemoveMachinistOffhands(this SortedList changedItems) From 4ca49598f8ffff55728e98e108183c88d679c2e8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Jun 2024 17:40:47 +0200 Subject: [PATCH 0687/1381] Small improvement. --- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index 962d156d..c1a3c1eb 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections.Cache; using Penumbra.Collections.Manager; @@ -116,15 +117,12 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy using var indent = ImRaii.PushIndent(30f); foreach (var data in conflict.Conflicts) { - unsafe + _ = data switch { - var _ = data switch - { - Utf8GamePath p => ImGuiNative.igSelectable_Bool(p.Path.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) > 0, - IMetaIdentifier m => ImGui.Selectable(m.ToString()), - _ => false, - }; - } + Utf8GamePath p => ImUtf8.Selectable(p.Path.Span, false), + IMetaIdentifier m => ImUtf8.Selectable(m.ToString(), false), + _ => false, + }; } return true; From e33512cf7ff3dcc887b0516188e79d6d9fe09aa1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Jun 2024 23:09:38 +0200 Subject: [PATCH 0688/1381] Fix issue, remove IMetaCache. --- Penumbra/Collections/Cache/IMetaCache.cs | 14 +++----------- Penumbra/Meta/Manipulations/MetaDictionary.cs | 2 +- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/Penumbra/Collections/Cache/IMetaCache.cs b/Penumbra/Collections/Cache/IMetaCache.cs index 218c1840..eacbdcc2 100644 --- a/Penumbra/Collections/Cache/IMetaCache.cs +++ b/Penumbra/Collections/Cache/IMetaCache.cs @@ -4,21 +4,12 @@ using Penumbra.Mods.Editor; namespace Penumbra.Collections.Cache; -public interface IMetaCache : IDisposable -{ - public void SetFiles(); - public void Reset(); - public void ResetFiles(); - - public int Count { get; } -} - public abstract class MetaCacheBase - : Dictionary, IMetaCache + : Dictionary where TIdentifier : unmanaged, IMetaIdentifier where TEntry : unmanaged { - public MetaCacheBase(MetaFileManager manager, ModCollection collection) + protected MetaCacheBase(MetaFileManager manager, ModCollection collection) { Manager = manager; Collection = collection; @@ -76,6 +67,7 @@ public abstract class MetaCacheBase { IncorporateChangesInternal(); } + if (Manager.ActiveCollections.Default == Collection && Manager.Config.EnableMods) SetFiles(); } diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 5a51df83..1093c6c5 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -346,7 +346,7 @@ public class MetaDictionary } failedIdentifier = default; - return false; + return true; } public void SetTo(MetaDictionary other) From ad0c64d4ac9e3b2d8ba89b7920b2f96a72480709 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 11:37:39 +0200 Subject: [PATCH 0689/1381] Change Eqp hook to not need eqp files anymore. --- Penumbra/Collections/Cache/EqpCache.cs | 12 ++++++++++++ Penumbra/Collections/Cache/MetaCache.cs | 8 -------- Penumbra/Collections/ModCollection.Cache.Access.cs | 7 ------- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 7 +++---- Penumbra/Interop/PathResolving/MetaState.cs | 5 ++--- Penumbra/UI/ConfigWindow.cs | 3 ++- 6 files changed, 19 insertions(+), 23 deletions(-) diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 599ae588..8dde9aba 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -1,3 +1,4 @@ +using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; @@ -28,6 +29,17 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EQP manipulations."); } + public unsafe EqpEntry GetValues(CharacterArmor* armor) + => GetSingleValue(armor[0].Set, EquipSlot.Head) + | GetSingleValue(armor[1].Set, EquipSlot.Body) + | GetSingleValue(armor[2].Set, EquipSlot.Hands) + | GetSingleValue(armor[3].Set, EquipSlot.Legs) + | GetSingleValue(armor[4].Set, EquipSlot.Feet); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private EqpEntry GetSingleValue(PrimaryId id, EquipSlot slot) + => TryGetValue(new EqpIdentifier(id, slot), out var pair) ? pair.Entry : ExpandedEqpFile.GetDefault(manager, id) & Eqp.Mask(slot); + public MetaList.MetaReverter TemporarilySetFile() => Manager.TemporarilySetFile(_eqpFile, MetaIndex.Eqp); diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index bc6ef34d..45a85d0f 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,4 +1,3 @@ -using System.IO.Pipes; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Services; @@ -146,9 +145,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public void SetImcFiles(bool fromFullCompute) => Imc.SetFiles(fromFullCompute); - public MetaList.MetaReverter TemporarilySetEqpFile() - => Eqp.TemporarilySetFile(); - public MetaList.MetaReverter? TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) => Eqdp.TemporarilySetFile(genderRace, accessory); @@ -161,10 +157,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public MetaList.MetaReverter TemporarilySetEstFile(EstType type) => Est.TemporarilySetFiles(type); - public unsafe EqpEntry ApplyGlobalEqp(EqpEntry baseEntry, CharacterArmor* armor) - => GlobalEqp.Apply(baseEntry, armor); - - /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) => Imc.GetFile(path, out file); diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 484d4dd2..3e3386ea 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -100,10 +100,6 @@ public partial class ModCollection return idx >= 0 ? utility.TemporarilyResetResource(idx) : null; } - public MetaList.MetaReverter TemporarilySetEqpFile(CharacterUtility utility) - => _cache?.Meta.TemporarilySetEqpFile() - ?? utility.TemporarilyResetResource(MetaIndex.Eqp); - public MetaList.MetaReverter TemporarilySetGmpFile(CharacterUtility utility) => _cache?.Meta.TemporarilySetGmpFile() ?? utility.TemporarilyResetResource(MetaIndex.Gmp); @@ -115,7 +111,4 @@ public partial class ModCollection public MetaList.MetaReverter TemporarilySetEstFile(CharacterUtility utility, EstType type) => _cache?.Meta.TemporarilySetEstFile(type) ?? utility.TemporarilyResetResource((MetaIndex)type); - - public unsafe EqpEntry ApplyGlobalEqp(EqpEntry baseEntry, CharacterArmor* armor) - => _cache?.Meta.ApplyGlobalEqp(baseEntry, armor) ?? baseEntry; } diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index 6663c211..448605c1 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -19,11 +19,10 @@ public unsafe class EqpHook : FastHook private void Detour(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor) { - if (_metaState.EqpCollection.Valid) + if (_metaState.EqpCollection is { Valid: true, ModCollection.MetaCache: { } cache }) { - using var eqp = _metaState.ResolveEqpData(_metaState.EqpCollection.ModCollection); - Task.Result.Original(utility, flags, armor); - *flags = _metaState.EqpCollection.ModCollection.ApplyGlobalEqp(*flags, armor); + *flags = cache.Eqp.GetValues(armor); + *flags = cache.GlobalEqp.Apply(*flags, armor); } else { diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 6fa5c263..de7912e0 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -47,6 +47,8 @@ public sealed unsafe class MetaState : IDisposable public ResolveData CustomizeChangeCollection = ResolveData.Invalid; public ResolveData EqpCollection = ResolveData.Invalid; + public ResolveData GmpCollection = ResolveData.Invalid; + public PrimaryId UndividedGmpId = 0; private ResolveData _lastCreatedCollection = ResolveData.Invalid; private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; @@ -93,9 +95,6 @@ public sealed unsafe class MetaState : IDisposable _ => DisposableContainer.Empty, }; - public MetaList.MetaReverter ResolveEqpData(ModCollection collection) - => collection.TemporarilySetEqpFile(_characterUtility); - public MetaList.MetaReverter ResolveGmpData(ModCollection collection) => collection.TemporarilySetGmpFile(_characterUtility); diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 9ae11fc3..0ae16f6d 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -4,6 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Custom; using OtterGui.Raii; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.Services; using Penumbra.UI.Classes; @@ -144,7 +145,7 @@ public sealed class ConfigWindow : Window using var color = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); ImGui.NewLine(); ImGui.NewLine(); - ImGuiUtil.TextWrapped(text); + ImUtf8.TextWrapped(text); color.Pop(); ImGui.NewLine(); From 30b32fdcd21e82d9f9e1176793f6b01082a79528 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 12:09:41 +0200 Subject: [PATCH 0690/1381] Fix EQDP bug. --- Penumbra/Collections/Cache/EqpCache.cs | 2 +- Penumbra/Meta/Files/EqpGmpFile.cs | 12 ++---------- Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 2 +- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 8dde9aba..32c4c0ae 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -38,7 +38,7 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private EqpEntry GetSingleValue(PrimaryId id, EquipSlot slot) - => TryGetValue(new EqpIdentifier(id, slot), out var pair) ? pair.Entry : ExpandedEqpFile.GetDefault(manager, id) & Eqp.Mask(slot); + => TryGetValue(new EqpIdentifier(id, slot), out var pair) ? pair.Entry : ExpandedEqpFile.GetDefault(Manager, id) & Eqp.Mask(slot); public MetaList.MetaReverter TemporarilySetFile() => Manager.TemporarilySetFile(_eqpFile, MetaIndex.Eqp); diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index 17541c4f..a7470b75 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -104,15 +104,11 @@ public unsafe class ExpandedEqpGmpBase : MetaBaseFile } } -public sealed class ExpandedEqpFile : ExpandedEqpGmpBase, IEnumerable +public sealed class ExpandedEqpFile(MetaFileManager manager) : ExpandedEqpGmpBase(manager, false), IEnumerable { public static readonly CharacterUtility.InternalIndex InternalIndex = CharacterUtility.ReverseIndices[(int)MetaIndex.Eqp]; - public ExpandedEqpFile(MetaFileManager manager) - : base(manager, false) - { } - public EqpEntry this[PrimaryId idx] { get => (EqpEntry)GetInternal(idx); @@ -147,15 +143,11 @@ public sealed class ExpandedEqpFile : ExpandedEqpGmpBase, IEnumerable => GetEnumerator(); } -public sealed class ExpandedGmpFile : ExpandedEqpGmpBase, IEnumerable +public sealed class ExpandedGmpFile(MetaFileManager manager) : ExpandedEqpGmpBase(manager, true), IEnumerable { public static readonly CharacterUtility.InternalIndex InternalIndex = CharacterUtility.ReverseIndices[(int)MetaIndex.Gmp]; - public ExpandedGmpFile(MetaFileManager manager) - : base(manager, true) - { } - public GmpEntry this[PrimaryId idx] { get => new() { Value = GetInternal(idx) }; diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index b1ac93f1..970b70cb 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -112,7 +112,7 @@ public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFil ImGui.SameLine(); if (Checkmark("Model##eqdp"u8, "\0"u8, entry.Model, defaultEntry.Model, out var newModel)) { - entry = entry with { Material = newModel }; + entry = entry with { Model = newModel }; changes = true; } From a61a96f1ef5bcc9e0c96210595c07a52c0ac8115 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 14:04:16 +0200 Subject: [PATCH 0691/1381] Make GmpEntry readonly. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 0a2e2650..cf1ff07e 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 0a2e2650d693d1bba267498f96112682cc09dbab +Subproject commit cf1ff07e900e2f93ab628a1fa535fc2b103794a5 From a7b90639c6deb2859adeac608521bd664ac2cbca Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 14:46:42 +0200 Subject: [PATCH 0692/1381] Some fixes. --- Penumbra/Collections/Cache/EqdpCache.cs | 10 ++++++---- Penumbra/Collections/Cache/EstCache.cs | 7 ++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index f3475c7e..7139bb72 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -1,4 +1,3 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using OtterGui; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -28,7 +27,10 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) } public override void ResetFiles() - => Manager.SetFile(null, MetaIndex.Eqp); + { + foreach (var t in CharacterUtilityData.EqdpIndices) + Manager.SetFile(null, t); + } protected override void IncorporateChangesInternal() { @@ -89,8 +91,8 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) var mask = Eqdp.Mask(identifier.Slot); if ((origEntry & mask) == entry) return false; - - file[identifier.SetId] = (entry & ~mask) | origEntry; + + file[identifier.SetId] = (origEntry & ~mask) | entry; return true; } diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 412dd322..8ee530cc 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -55,7 +55,12 @@ public sealed class EstCache(MetaFileManager manager, ModCollection collection) } public override void ResetFiles() - => Manager.SetFile(null, MetaIndex.Eqp); + { + Manager.SetFile(null, MetaIndex.FaceEst); + Manager.SetFile(null, MetaIndex.HairEst); + Manager.SetFile(null, MetaIndex.BodyEst); + Manager.SetFile(null, MetaIndex.HeadEst); + } protected override void IncorporateChangesInternal() { From c53f29c257003bb8131441cc5bcf7086d808ad73 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 15:19:48 +0200 Subject: [PATCH 0693/1381] Fix unnecessary EST file creations. --- Penumbra/Collections/Cache/EstCache.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 8ee530cc..845ff128 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -74,7 +74,7 @@ public sealed class EstCache(MetaFileManager manager, ModCollection collection) public EstEntry GetEstEntry(EstIdentifier identifier) { - var file = GetFile(identifier); + var file = GetCurrentFile(identifier); return file != null ? file[identifier.GenderRace, identifier.SetId] : EstFile.GetDefault(Manager, identifier); @@ -124,9 +124,19 @@ public sealed class EstCache(MetaFileManager manager, ModCollection collection) Clear(); } + private EstFile? GetCurrentFile(EstIdentifier identifier) + => identifier.Slot switch + { + EstType.Hair => _estHairFile, + EstType.Face => _estFaceFile, + EstType.Body => _estBodyFile, + EstType.Head => _estHeadFile, + _ => null, + }; + private EstFile? GetFile(EstIdentifier identifier) { - if (Manager.CharacterUtility.Ready) + if (!Manager.CharacterUtility.Ready) return null; return identifier.Slot switch From 943207cae8923720fc8dbe56d763ddc3d1034bd4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 15:55:51 +0200 Subject: [PATCH 0694/1381] Make GMP independent of file, cleanup unused functions. --- Penumbra/Collections/Cache/EqdpCache.cs | 4 +- Penumbra/Collections/Cache/EqpCache.cs | 59 ++--------------- Penumbra/Collections/Cache/EstCache.cs | 4 +- Penumbra/Collections/Cache/GmpCache.cs | 59 ++--------------- Penumbra/Collections/Cache/IMetaCache.cs | 2 - Penumbra/Collections/Cache/ImcCache.cs | 4 +- Penumbra/Collections/Cache/MetaCache.cs | 3 - Penumbra/Collections/Cache/RspCache.cs | 5 +- .../Collections/ModCollection.Cache.Access.cs | 4 -- Penumbra/Interop/Hooks/Meta/GmpHook.cs | 64 +++++++++++++++++++ Penumbra/Interop/Hooks/Meta/SetupVisor.cs | 24 +++---- Penumbra/Interop/PathResolving/MetaState.cs | 3 - Penumbra/Interop/Services/MetaList.cs | 23 ++----- Penumbra/Meta/Files/EqpGmpFile.cs | 8 +-- 14 files changed, 108 insertions(+), 158 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Meta/GmpHook.cs diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index 7139bb72..c63403ae 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -26,7 +26,7 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) Manager.SetFile(_eqdpFiles[i], index); } - public override void ResetFiles() + public void ResetFiles() { foreach (var t in CharacterUtilityData.EqdpIndices) Manager.SetFile(null, t); @@ -62,7 +62,7 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) return Manager.TemporarilySetFile(_eqdpFiles[i], idx); } - public override void Reset() + public void Reset() { foreach (var file in _eqdpFiles.OfType()) { diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 32c4c0ae..b1e03943 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -1,7 +1,5 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -10,24 +8,11 @@ namespace Penumbra.Collections.Cache; public sealed class EqpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private ExpandedEqpFile? _eqpFile; - public override void SetFiles() - => Manager.SetFile(_eqpFile, MetaIndex.Eqp); - - public override void ResetFiles() - => Manager.SetFile(null, MetaIndex.Eqp); + { } protected override void IncorporateChangesInternal() - { - if (GetFile() is not { } file) - return; - - foreach (var (identifier, (_, entry)) in this) - Apply(file, identifier, entry); - - Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EQP manipulations."); - } + { } public unsafe EqpEntry GetValues(CharacterArmor* armor) => GetSingleValue(armor[0].Set, EquipSlot.Head) @@ -40,29 +25,14 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) private EqpEntry GetSingleValue(PrimaryId id, EquipSlot slot) => TryGetValue(new EqpIdentifier(id, slot), out var pair) ? pair.Entry : ExpandedEqpFile.GetDefault(Manager, id) & Eqp.Mask(slot); - public MetaList.MetaReverter TemporarilySetFile() - => Manager.TemporarilySetFile(_eqpFile, MetaIndex.Eqp); - - public override void Reset() - { - if (_eqpFile == null) - return; - - _eqpFile.Reset(Keys.Select(identifier => identifier.SetId)); - Clear(); - } + public void Reset() + => Clear(); protected override void ApplyModInternal(EqpIdentifier identifier, EqpEntry entry) - { - if (GetFile() is { } file) - Apply(file, identifier, entry); - } + { } protected override void RevertModInternal(EqpIdentifier identifier) - { - if (GetFile() is { } file) - Apply(file, identifier, ExpandedEqpFile.GetDefault(Manager, identifier.SetId)); - } + { } public static bool Apply(ExpandedEqpFile file, EqpIdentifier identifier, EqpEntry entry) { @@ -76,20 +46,5 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) } protected override void Dispose(bool _) - { - _eqpFile?.Dispose(); - _eqpFile = null; - Clear(); - } - - private ExpandedEqpFile? GetFile() - { - if (_eqpFile != null) - return _eqpFile; - - if (!Manager.CharacterUtility.Ready) - return null; - - return _eqpFile = new ExpandedEqpFile(Manager); - } + => Clear(); } diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 845ff128..6a9fa909 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -54,7 +54,7 @@ public sealed class EstCache(MetaFileManager manager, ModCollection collection) return Manager.TemporarilySetFile(file, idx); } - public override void ResetFiles() + public void ResetFiles() { Manager.SetFile(null, MetaIndex.FaceEst); Manager.SetFile(null, MetaIndex.HairEst); @@ -80,7 +80,7 @@ public sealed class EstCache(MetaFileManager manager, ModCollection collection) : EstFile.GetDefault(Manager, identifier); } - public override void Reset() + public void Reset() { _estFaceFile?.Reset(); _estHairFile?.Reset(); diff --git a/Penumbra/Collections/Cache/GmpCache.cs b/Penumbra/Collections/Cache/GmpCache.cs index 1475ffd5..0beb51d8 100644 --- a/Penumbra/Collections/Cache/GmpCache.cs +++ b/Penumbra/Collections/Cache/GmpCache.cs @@ -1,6 +1,4 @@ using Penumbra.GameData.Structs; -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -9,48 +7,20 @@ namespace Penumbra.Collections.Cache; public sealed class GmpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private ExpandedGmpFile? _gmpFile; - public override void SetFiles() - => Manager.SetFile(_gmpFile, MetaIndex.Gmp); - - public override void ResetFiles() - => Manager.SetFile(null, MetaIndex.Gmp); + { } protected override void IncorporateChangesInternal() - { - if (GetFile() is not { } file) - return; + { } - foreach (var (identifier, (_, entry)) in this) - Apply(file, identifier, entry); - - Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed GMP manipulations."); - } - - public MetaList.MetaReverter TemporarilySetFile() - => Manager.TemporarilySetFile(_gmpFile, MetaIndex.Gmp); - - public override void Reset() - { - if (_gmpFile == null) - return; - - _gmpFile.Reset(Keys.Select(identifier => identifier.SetId)); - Clear(); - } + public void Reset() + => Clear(); protected override void ApplyModInternal(GmpIdentifier identifier, GmpEntry entry) - { - if (GetFile() is { } file) - Apply(file, identifier, entry); - } + { } protected override void RevertModInternal(GmpIdentifier identifier) - { - if (GetFile() is { } file) - Apply(file, identifier, ExpandedGmpFile.GetDefault(Manager, identifier.SetId)); - } + { } public static bool Apply(ExpandedGmpFile file, GmpIdentifier identifier, GmpEntry entry) { @@ -63,20 +33,5 @@ public sealed class GmpCache(MetaFileManager manager, ModCollection collection) } protected override void Dispose(bool _) - { - _gmpFile?.Dispose(); - _gmpFile = null; - Clear(); - } - - private ExpandedGmpFile? GetFile() - { - if (_gmpFile != null) - return _gmpFile; - - if (!Manager.CharacterUtility.Ready) - return null; - - return _gmpFile = new ExpandedGmpFile(Manager); - } + => Clear(); } diff --git a/Penumbra/Collections/Cache/IMetaCache.cs b/Penumbra/Collections/Cache/IMetaCache.cs index eacbdcc2..dd218b48 100644 --- a/Penumbra/Collections/Cache/IMetaCache.cs +++ b/Penumbra/Collections/Cache/IMetaCache.cs @@ -27,8 +27,6 @@ public abstract class MetaCacheBase } public abstract void SetFiles(); - public abstract void Reset(); - public abstract void ResetFiles(); public bool ApplyMod(IMod source, TIdentifier identifier, TEntry entry) { diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 3d05e793..a9daf795 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -38,7 +38,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) Collection._cache!.ForceFile(path, PathDataHandler.CreateImc(path.Path, Collection)); } - public override void ResetFiles() + public void ResetFiles() { foreach (var (path, _) in _imcFiles) Collection._cache!.ForceFile(path, FullPath.Empty); @@ -56,7 +56,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) } - public override void Reset() + public void Reset() { foreach (var (path, (file, set)) in _imcFiles) { diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 45a85d0f..c8a116eb 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -148,9 +148,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public MetaList.MetaReverter? TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) => Eqdp.TemporarilySetFile(genderRace, accessory); - public MetaList.MetaReverter TemporarilySetGmpFile() - => Gmp.TemporarilySetFile(); - public MetaList.MetaReverter TemporarilySetCmpFile() => Rsp.TemporarilySetFile(); diff --git a/Penumbra/Collections/Cache/RspCache.cs b/Penumbra/Collections/Cache/RspCache.cs index 3889d6f1..8a5fe97d 100644 --- a/Penumbra/Collections/Cache/RspCache.cs +++ b/Penumbra/Collections/Cache/RspCache.cs @@ -13,9 +13,6 @@ public sealed class RspCache(MetaFileManager manager, ModCollection collection) public override void SetFiles() => Manager.SetFile(_cmpFile, MetaIndex.HumanCmp); - public override void ResetFiles() - => Manager.SetFile(null, MetaIndex.HumanCmp); - protected override void IncorporateChangesInternal() { if (GetFile() is not { } file) @@ -30,7 +27,7 @@ public sealed class RspCache(MetaFileManager manager, ModCollection collection) public MetaList.MetaReverter TemporarilySetFile() => Manager.TemporarilySetFile(_cmpFile, MetaIndex.HumanCmp); - public override void Reset() + public void Reset() { if (_cmpFile == null) return; diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 3e3386ea..8701e3bb 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -100,10 +100,6 @@ public partial class ModCollection return idx >= 0 ? utility.TemporarilyResetResource(idx) : null; } - public MetaList.MetaReverter TemporarilySetGmpFile(CharacterUtility utility) - => _cache?.Meta.TemporarilySetGmpFile() - ?? utility.TemporarilyResetResource(MetaIndex.Gmp); - public MetaList.MetaReverter TemporarilySetCmpFile(CharacterUtility utility) => _cache?.Meta.TemporarilySetCmpFile() ?? utility.TemporarilyResetResource(MetaIndex.HumanCmp); diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs new file mode 100644 index 00000000..60966fb7 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -0,0 +1,64 @@ +using OtterGui.Services; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class GmpHook : FastHook +{ + public delegate nint Delegate(nint gmpResource, uint dividedHeadId); + + private readonly MetaState _metaState; + + private static readonly Finalizer StablePointer = new(); + + public GmpHook(HookManager hooks, MetaState metaState) + { + _metaState = metaState; + Task = hooks.CreateHook("GetGmpEntry", "E8 ?? ?? ?? ?? 48 85 C0 74 ?? 43 8D 0C", Detour, true); + } + + /// + /// This function returns a pointer to the correct block in the GMP file, if it exists - cf. . + /// To work around this, we just have a single stable ulong accessible and offset the pointer to this by the required distance, + /// which is defined by the modulo of the original ID and the block size, if we return our own custom gmp entry. + /// + private nint Detour(nint gmpResource, uint dividedHeadId) + { + nint ret; + if (_metaState.GmpCollection is { Valid: true, ModCollection.MetaCache: { } cache } + && cache.Gmp.TryGetValue(new GmpIdentifier(_metaState.UndividedGmpId), out var entry)) + { + if (entry.Entry.Enabled) + { + *StablePointer.Pointer = entry.Entry.Value; + // This function already gets the original ID divided by the block size, so we can compute the modulo with a single multiplication and addition. + // We then go backwards from our pointer because this gets added by the calling functions. + ret = (nint)(StablePointer.Pointer - (_metaState.UndividedGmpId.Id - dividedHeadId * ExpandedEqpGmpBase.BlockSize)); + } + else + { + ret = nint.Zero; + } + } + else + { + ret = Task.Result.Original(gmpResource, dividedHeadId); + } + + Penumbra.Log.Excessive($"[GetGmpFlags] Invoked on 0x{gmpResource:X} with {dividedHeadId}, returned {ret:X10}."); + return ret; + } + + /// Allocate and clean up our single stable ulong pointer. + private class Finalizer + { + public readonly ulong* Pointer = (ulong*)Marshal.AllocHGlobal(8); + + ~Finalizer() + { + Marshal.FreeHGlobal((nint)Pointer); + } + } +} diff --git a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs index e451f118..a3e56d7f 100644 --- a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs +++ b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs @@ -1,10 +1,11 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Services; -using Penumbra.GameData; -using Penumbra.Interop.PathResolving; - -namespace Penumbra.Interop.Hooks.Meta; - +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + /// /// GMP. This gets called every time when changing visor state, and it accesses the gmp file itself, /// but it only applies a changed gmp file after a redraw for some reason. @@ -26,10 +27,11 @@ public sealed unsafe class SetupVisor : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private byte Detour(DrawObject* drawObject, ushort modelId, byte visorState) { - var collection = _collectionResolver.IdentifyCollection(drawObject, true); - using var gmp = _metaState.ResolveGmpData(collection.ModCollection); - var ret = Task.Result.Original.Invoke(drawObject, modelId, visorState); - Penumbra.Log.Excessive($"[Setup Visor] Invoked on {(nint)drawObject:X} with {modelId}, {visorState} -> {ret}."); + _metaState.GmpCollection = _collectionResolver.IdentifyCollection(drawObject, true); + _metaState.UndividedGmpId = modelId; + var ret = Task.Result.Original.Invoke(drawObject, modelId, visorState); + Penumbra.Log.Information($"[Setup Visor] Invoked on {(nint)drawObject:X} with {modelId}, {visorState} -> {ret}."); + _metaState.GmpCollection = ResolveData.Invalid; return ret; } } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index de7912e0..c8ebe18f 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -95,9 +95,6 @@ public sealed unsafe class MetaState : IDisposable _ => DisposableContainer.Empty, }; - public MetaList.MetaReverter ResolveGmpData(ModCollection collection) - => collection.TemporarilySetGmpFile(_characterUtility); - public MetaList.MetaReverter ResolveRspData(ModCollection collection) => collection.TemporarilySetCmpFile(_characterUtility); diff --git a/Penumbra/Interop/Services/MetaList.cs b/Penumbra/Interop/Services/MetaList.cs index e956040b..dc472b8e 100644 --- a/Penumbra/Interop/Services/MetaList.cs +++ b/Penumbra/Interop/Services/MetaList.cs @@ -102,30 +102,19 @@ public unsafe class MetaList : IDisposable ResetResourceInternal(); } - public sealed class MetaReverter : IDisposable + public sealed class MetaReverter(MetaList metaList, nint data, int length) : IDisposable { public static readonly MetaReverter Disabled = new(null!) { Disposed = true }; - public readonly MetaList MetaList; - public readonly nint Data; - public readonly int Length; + public readonly MetaList MetaList = metaList; + public readonly nint Data = data; + public readonly int Length = length; public readonly bool Resetter; public bool Disposed; - public MetaReverter(MetaList metaList, nint data, int length) - { - MetaList = metaList; - Data = data; - Length = length; - } - public MetaReverter(MetaList metaList) - { - MetaList = metaList; - Data = nint.Zero; - Length = 0; - Resetter = true; - } + : this(metaList, nint.Zero, 0) + => Resetter = true; public void Dispose() { diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index a7470b75..c47c84ef 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -15,10 +15,10 @@ namespace Penumbra.Meta.Files; /// public unsafe class ExpandedEqpGmpBase : MetaBaseFile { - protected const int BlockSize = 160; - protected const int NumBlocks = 64; - protected const int EntrySize = 8; - protected const int MaxSize = BlockSize * NumBlocks * EntrySize; + public const int BlockSize = 160; + public const int NumBlocks = 64; + public const int EntrySize = 8; + public const int MaxSize = BlockSize * NumBlocks * EntrySize; public const int Count = BlockSize * NumBlocks; From ebef4ff650c19aee26306135ab125a451210bab9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 16:17:44 +0200 Subject: [PATCH 0695/1381] No EST files anymore. --- Penumbra/Collections/Cache/EqpCache.cs | 11 -- Penumbra/Collections/Cache/EstCache.cs | 136 ++---------------- Penumbra/Collections/Cache/GmpCache.cs | 11 -- Penumbra/Collections/Cache/MetaCache.cs | 6 - .../Collections/ModCollection.Cache.Access.cs | 4 - Penumbra/Interop/Hooks/Meta/EstHook.cs | 49 +++++++ .../Hooks/Resources/ResolvePathHooksBase.cs | 29 ++-- Penumbra/Interop/PathResolving/MetaState.cs | 5 +- 8 files changed, 68 insertions(+), 183 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Meta/EstHook.cs diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index b1e03943..7ba0c489 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -34,17 +34,6 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) protected override void RevertModInternal(EqpIdentifier identifier) { } - public static bool Apply(ExpandedEqpFile file, EqpIdentifier identifier, EqpEntry entry) - { - var origEntry = file[identifier.SetId]; - var mask = Eqp.Mask(identifier.Slot); - if ((origEntry & mask) == entry) - return false; - - file[identifier.SetId] = (origEntry & ~mask) | entry; - return true; - } - protected override void Dispose(bool _) => Clear(); } diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index 6a9fa909..ff94324e 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -1,5 +1,3 @@ -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -8,144 +6,26 @@ namespace Penumbra.Collections.Cache; public sealed class EstCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private EstFile? _estFaceFile; - private EstFile? _estHairFile; - private EstFile? _estBodyFile; - private EstFile? _estHeadFile; - public override void SetFiles() - { - Manager.SetFile(_estFaceFile, MetaIndex.FaceEst); - Manager.SetFile(_estHairFile, MetaIndex.HairEst); - Manager.SetFile(_estBodyFile, MetaIndex.BodyEst); - Manager.SetFile(_estHeadFile, MetaIndex.HeadEst); - } - - public void SetFile(MetaIndex index) - { - switch (index) - { - case MetaIndex.FaceEst: - Manager.SetFile(_estFaceFile, MetaIndex.FaceEst); - break; - case MetaIndex.HairEst: - Manager.SetFile(_estHairFile, MetaIndex.HairEst); - break; - case MetaIndex.BodyEst: - Manager.SetFile(_estBodyFile, MetaIndex.BodyEst); - break; - case MetaIndex.HeadEst: - Manager.SetFile(_estHeadFile, MetaIndex.HeadEst); - break; - } - } - - public MetaList.MetaReverter TemporarilySetFiles(EstType type) - { - var (file, idx) = type switch - { - EstType.Face => (_estFaceFile, MetaIndex.FaceEst), - EstType.Hair => (_estHairFile, MetaIndex.HairEst), - EstType.Body => (_estBodyFile, MetaIndex.BodyEst), - EstType.Head => (_estHeadFile, MetaIndex.HeadEst), - _ => (null, 0), - }; - - return Manager.TemporarilySetFile(file, idx); - } - - public void ResetFiles() - { - Manager.SetFile(null, MetaIndex.FaceEst); - Manager.SetFile(null, MetaIndex.HairEst); - Manager.SetFile(null, MetaIndex.BodyEst); - Manager.SetFile(null, MetaIndex.HeadEst); - } + { } protected override void IncorporateChangesInternal() - { - if (!Manager.CharacterUtility.Ready) - return; - - foreach (var (identifier, (_, entry)) in this) - Apply(GetFile(identifier)!, identifier, entry); - Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EST manipulations."); - } + { } public EstEntry GetEstEntry(EstIdentifier identifier) - { - var file = GetCurrentFile(identifier); - return file != null - ? file[identifier.GenderRace, identifier.SetId] + => TryGetValue(identifier, out var entry) + ? entry.Entry : EstFile.GetDefault(Manager, identifier); - } public void Reset() - { - _estFaceFile?.Reset(); - _estHairFile?.Reset(); - _estBodyFile?.Reset(); - _estHeadFile?.Reset(); - Clear(); - } + => Clear(); protected override void ApplyModInternal(EstIdentifier identifier, EstEntry entry) - { - if (GetFile(identifier) is { } file) - Apply(file, identifier, entry); - } + { } protected override void RevertModInternal(EstIdentifier identifier) - { - if (GetFile(identifier) is { } file) - Apply(file, identifier, EstFile.GetDefault(Manager, identifier.Slot, identifier.GenderRace, identifier.SetId)); - } - - public static bool Apply(EstFile file, EstIdentifier identifier, EstEntry entry) - => file.SetEntry(identifier.GenderRace, identifier.SetId, entry) switch - { - EstFile.EstEntryChange.Unchanged => false, - EstFile.EstEntryChange.Changed => true, - EstFile.EstEntryChange.Added => true, - EstFile.EstEntryChange.Removed => true, - _ => false, - }; + { } protected override void Dispose(bool _) - { - _estFaceFile?.Dispose(); - _estHairFile?.Dispose(); - _estBodyFile?.Dispose(); - _estHeadFile?.Dispose(); - _estFaceFile = null; - _estHairFile = null; - _estBodyFile = null; - _estHeadFile = null; - Clear(); - } - - private EstFile? GetCurrentFile(EstIdentifier identifier) - => identifier.Slot switch - { - EstType.Hair => _estHairFile, - EstType.Face => _estFaceFile, - EstType.Body => _estBodyFile, - EstType.Head => _estHeadFile, - _ => null, - }; - - private EstFile? GetFile(EstIdentifier identifier) - { - if (!Manager.CharacterUtility.Ready) - return null; - - return identifier.Slot switch - { - EstType.Hair => _estHairFile ??= new EstFile(Manager, EstType.Hair), - EstType.Face => _estFaceFile ??= new EstFile(Manager, EstType.Face), - EstType.Body => _estBodyFile ??= new EstFile(Manager, EstType.Body), - EstType.Head => _estHeadFile ??= new EstFile(Manager, EstType.Head), - _ => null, - }; - } + => Clear(); } diff --git a/Penumbra/Collections/Cache/GmpCache.cs b/Penumbra/Collections/Cache/GmpCache.cs index 0beb51d8..541b424d 100644 --- a/Penumbra/Collections/Cache/GmpCache.cs +++ b/Penumbra/Collections/Cache/GmpCache.cs @@ -1,6 +1,5 @@ using Penumbra.GameData.Structs; using Penumbra.Meta; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; @@ -22,16 +21,6 @@ public sealed class GmpCache(MetaFileManager manager, ModCollection collection) protected override void RevertModInternal(GmpIdentifier identifier) { } - public static bool Apply(ExpandedGmpFile file, GmpIdentifier identifier, GmpEntry entry) - { - var origEntry = file[identifier.SetId]; - if (entry == origEntry) - return false; - - file[identifier.SetId] = entry; - return true; - } - protected override void Dispose(bool _) => Clear(); } diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index c8a116eb..014c7552 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -121,10 +121,8 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) switch (metaIndex) { case MetaIndex.Eqp: - Eqp.SetFiles(); break; case MetaIndex.Gmp: - Gmp.SetFiles(); break; case MetaIndex.HumanCmp: Rsp.SetFiles(); @@ -133,7 +131,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) case MetaIndex.HairEst: case MetaIndex.HeadEst: case MetaIndex.BodyEst: - Est.SetFile(metaIndex); break; default: Eqdp.SetFile(metaIndex); @@ -151,9 +148,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public MetaList.MetaReverter TemporarilySetCmpFile() => Rsp.TemporarilySetFile(); - public MetaList.MetaReverter TemporarilySetEstFile(EstType type) - => Est.TemporarilySetFiles(type); - /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) => Imc.GetFile(path, out file); diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 8701e3bb..dba971c6 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -103,8 +103,4 @@ public partial class ModCollection public MetaList.MetaReverter TemporarilySetCmpFile(CharacterUtility utility) => _cache?.Meta.TemporarilySetCmpFile() ?? utility.TemporarilyResetResource(MetaIndex.HumanCmp); - - public MetaList.MetaReverter TemporarilySetEstFile(CharacterUtility utility, EstType type) - => _cache?.Meta.TemporarilySetEstFile(type) - ?? utility.TemporarilyResetResource((MetaIndex)type); } diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs new file mode 100644 index 00000000..3fab1434 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -0,0 +1,49 @@ +using OtterGui.Services; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Interop.Hooks.Meta; + +public class EstHook : FastHook +{ + public delegate EstEntry Delegate(uint id, int estType, uint genderRace); + + private readonly MetaState _metaState; + + public EstHook(HookManager hooks, MetaState metaState) + { + _metaState = metaState; + Task = hooks.CreateHook("GetEstEntry", "44 8B C9 83 EA ?? 74", Detour, true); + } + + private EstEntry Detour(uint genderRace, int estType, uint id) + { + EstEntry ret; + if (_metaState.EstCollection is { Valid: true, ModCollection.MetaCache: { } cache } + && cache.Est.TryGetValue(Convert(genderRace, estType, id), out var entry)) + ret = entry.Entry; + else + ret = Task.Result.Original(genderRace, estType, id); + + Penumbra.Log.Information($"[GetEstEntry] Invoked with {genderRace}, {estType}, {id}, returned {ret.Value}."); + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static EstIdentifier Convert(uint genderRace, int estType, uint id) + { + var i = new PrimaryId((ushort)id); + var gr = (GenderRace)genderRace; + var type = estType switch + { + 1 => EstType.Face, + 2 => EstType.Hair, + 3 => EstType.Head, + 4 => EstType.Body, + _ => (EstType)0, + }; + return new EstIdentifier(i, type, gr); + } +} diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 9a68160b..6c9c1b7d 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -158,26 +158,26 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolvePapHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) { - using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); + _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + return ResolvePath(_parent.MetaState.EstCollection, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); } private nint ResolvePhybHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { - using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + return ResolvePath(_parent.MetaState.EstCollection, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } private nint ResolveSklbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { - using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + return ResolvePath(_parent.MetaState.EstCollection, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } private nint ResolveSkpHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { - using var est = GetEstChanges(drawObject, out var data); - return ResolvePath(data, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + return ResolvePath(_parent.MetaState.EstCollection, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); } private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) @@ -206,19 +206,6 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ResolvePath(drawObject, pathBuffer); } - private DisposableContainer GetEstChanges(nint drawObject, out ResolveData data) - { - data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - if (_parent.InInternalResolve) - return DisposableContainer.Empty; - - return new DisposableContainer(data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Face), - data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Body), - data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Hair), - data.ModCollection.TemporarilySetEstFile(_parent.CharacterUtility, EstType.Head)); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private static Hook Create(string name, HookManager hooks, nint address, Type type, T other, T human) where T : Delegate { diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index c8ebe18f..8fa09232 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -18,7 +18,7 @@ namespace Penumbra.Interop.PathResolving; // GetSlotEqpData seems to be the only function using the EQP table. // It is only called by CheckSlotsForUnload (called by UpdateModels), // SetupModelAttributes (called by UpdateModels and OnModelLoadComplete) -// and a unnamed function called by UpdateRender. +// and an unnamed function called by UpdateRender. // It seems to be enough to change the EQP entries for UpdateModels. // GetEqdpDataFor[Adults|Children|Other] seem to be the only functions using the EQDP tables. @@ -35,7 +35,7 @@ namespace Penumbra.Interop.PathResolving; // they all are called by many functions, but the most relevant seem to be Human.SetupFromCharacterData, which is only called by CharacterBase.Create, // ChangeCustomize and RspSetupCharacter, which is hooked here, as well as Character.CalculateHeight. -// GMP Entries seem to be only used by "48 8B ?? 53 55 57 48 83 ?? ?? 48 8B", which has a DrawObject as its first parameter. +// GMP Entries seem to be only used by "48 8B ?? 53 55 57 48 83 ?? ?? 48 8B", which is SetupVisor. public sealed unsafe class MetaState : IDisposable { private readonly Configuration _config; @@ -48,6 +48,7 @@ public sealed unsafe class MetaState : IDisposable public ResolveData CustomizeChangeCollection = ResolveData.Invalid; public ResolveData EqpCollection = ResolveData.Invalid; public ResolveData GmpCollection = ResolveData.Invalid; + public ResolveData EstCollection = ResolveData.Invalid; public PrimaryId UndividedGmpId = 0; private ResolveData _lastCreatedCollection = ResolveData.Invalid; From 9ecc4ab46d1b04e1bea0a6816d3e8ab06b862812 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Jun 2024 20:47:08 +0200 Subject: [PATCH 0696/1381] Remove CMP file. --- Penumbra/Collections/Cache/MetaCache.cs | 3 - Penumbra/Collections/Cache/RspCache.cs | 64 ++--------------- .../Collections/ModCollection.Cache.Access.cs | 4 -- .../Interop/Hooks/Meta/CalculateHeight.cs | 7 +- .../Interop/Hooks/Meta/ChangeCustomize.cs | 3 +- Penumbra/Interop/Hooks/Meta/EstHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 66 ++++++++++++++++++ Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 68 +++++++++++++++++++ .../Interop/Hooks/Meta/RspSetupCharacter.cs | 5 +- Penumbra/Interop/Hooks/Meta/RspTailHook.cs | 68 +++++++++++++++++++ Penumbra/Interop/Hooks/Meta/SetupVisor.cs | 2 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 16 +++-- Penumbra/Interop/PathResolving/MetaState.cs | 9 ++- Penumbra/Meta/Files/CmpFile.cs | 8 +++ .../UI/AdvancedWindow/Meta/RspMetaDrawer.cs | 2 +- 15 files changed, 244 insertions(+), 83 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Meta/RspBustHook.cs create mode 100644 Penumbra/Interop/Hooks/Meta/RspHeightHook.cs create mode 100644 Penumbra/Interop/Hooks/Meta/RspTailHook.cs diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 014c7552..e6083351 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -145,9 +145,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public MetaList.MetaReverter? TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) => Eqdp.TemporarilySetFile(genderRace, accessory); - public MetaList.MetaReverter TemporarilySetCmpFile() - => Rsp.TemporarilySetFile(); - /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) => Imc.GetFile(path, out file); diff --git a/Penumbra/Collections/Cache/RspCache.cs b/Penumbra/Collections/Cache/RspCache.cs index 8a5fe97d..8a983c6c 100644 --- a/Penumbra/Collections/Cache/RspCache.cs +++ b/Penumbra/Collections/Cache/RspCache.cs @@ -1,78 +1,26 @@ -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; public sealed class RspCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private CmpFile? _cmpFile; - public override void SetFiles() - => Manager.SetFile(_cmpFile, MetaIndex.HumanCmp); + { } protected override void IncorporateChangesInternal() - { - if (GetFile() is not { } file) - return; - - foreach (var (identifier, (_, entry)) in this) - Apply(file, identifier, entry); - - Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed RSP manipulations."); - } - - public MetaList.MetaReverter TemporarilySetFile() - => Manager.TemporarilySetFile(_cmpFile, MetaIndex.HumanCmp); + { } public void Reset() - { - if (_cmpFile == null) - return; - - _cmpFile.Reset(Keys.Select(identifier => (identifier.SubRace, identifier.Attribute))); - Clear(); - } + => Clear(); protected override void ApplyModInternal(RspIdentifier identifier, RspEntry entry) - { - if (GetFile() is { } file) - Apply(file, identifier, entry); - } + { } protected override void RevertModInternal(RspIdentifier identifier) - { - if (GetFile() is { } file) - Apply(file, identifier, CmpFile.GetDefault(Manager, identifier.SubRace, identifier.Attribute)); - } + { } - public static bool Apply(CmpFile file, RspIdentifier identifier, RspEntry entry) - { - var value = file[identifier.SubRace, identifier.Attribute]; - if (value == entry) - return false; - - file[identifier.SubRace, identifier.Attribute] = entry; - return true; - } protected override void Dispose(bool _) - { - _cmpFile?.Dispose(); - _cmpFile = null; - Clear(); - } - - private CmpFile? GetFile() - { - if (_cmpFile != null) - return _cmpFile; - - if (!Manager.CharacterUtility.Ready) - return null; - - return _cmpFile = new CmpFile(Manager); - } + => Clear(); } diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index dba971c6..d93a0f53 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -99,8 +99,4 @@ public partial class ModCollection var idx = CharacterUtilityData.EqdpIdx(genderRace, accessory); return idx >= 0 ? utility.TemporarilyResetResource(idx) : null; } - - public MetaList.MetaReverter TemporarilySetCmpFile(CharacterUtility utility) - => _cache?.Meta.TemporarilySetCmpFile() - ?? utility.TemporarilyResetResource(MetaIndex.HumanCmp); } diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index 2fd87f6e..5a207491 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; +using Penumbra.Collections; using Penumbra.Interop.PathResolving; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; @@ -22,10 +23,10 @@ public sealed unsafe class CalculateHeight : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private ulong Detour(Character* character) { - var collection = _collectionResolver.IdentifyCollection((GameObject*)character, true); - using var cmp = _metaState.ResolveRspData(collection.ModCollection); - var ret = Task.Result.Original.Invoke(character); + _metaState.RspCollection = _collectionResolver.IdentifyCollection((GameObject*)character, true); + var ret = Task.Result.Original.Invoke(character); Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)character:X} -> {ret}."); + _metaState.RspCollection = ResolveData.Invalid; return ret; } } diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs index 2f717491..4e0a5744 100644 --- a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -25,12 +25,13 @@ public sealed unsafe class ChangeCustomize : FastHook private bool Detour(Human* human, CustomizeArray* data, byte skipEquipment) { _metaState.CustomizeChangeCollection = _collectionResolver.IdentifyCollection((DrawObject*)human, true); - using var cmp = _metaState.ResolveRspData(_metaState.CustomizeChangeCollection.ModCollection); + _metaState.RspCollection = _metaState.CustomizeChangeCollection; using var decal1 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, true); using var decal2 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, false); var ret = Task.Result.Original.Invoke(human, data, skipEquipment); Penumbra.Log.Excessive($"[Change Customize] Invoked on {(nint)human:X} with {(nint)data:X}, {skipEquipment} -> {ret}."); _metaState.CustomizeChangeCollection = ResolveData.Invalid; + _metaState.RspCollection = ResolveData.Invalid; return ret; } } diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index 3fab1434..34935edb 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -27,7 +27,7 @@ public class EstHook : FastHook else ret = Task.Result.Original(genderRace, estType, id); - Penumbra.Log.Information($"[GetEstEntry] Invoked with {genderRace}, {estType}, {id}, returned {ret.Value}."); + Penumbra.Log.Excessive($"[GetEstEntry] Invoked with {genderRace}, {estType}, {id}, returned {ret.Value}."); return ret; } diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs new file mode 100644 index 00000000..fc1d743a --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -0,0 +1,66 @@ +using OtterGui.Services; +using Penumbra.GameData.Enums; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class RspBustHook : FastHook +{ + public delegate float* Delegate(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, + byte bustSize); + + private readonly MetaState _metaState; + private readonly MetaFileManager _metaFileManager; + + public RspBustHook(HookManager hooks, MetaState metaState, MetaFileManager metaFileManager) + { + _metaState = metaState; + _metaFileManager = metaFileManager; + Task = hooks.CreateHook("GetRspBust", "E8 ?? ?? ?? ?? F2 0F 10 44 24 ?? 8B 44 24", Detour, true); + } + + private float* Detour(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte bustSize) + { + if (gender == 0) + { + storage[0] = 1f; + storage[1] = 1f; + storage[2] = 1f; + return storage; + } + + var ret = storage; + if (bodyType < 2 && _metaState.RspCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + { + var bustScale = bustSize / 100f; + var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); + var ptr = CmpFile.GetDefaults(_metaFileManager, clan, RspAttribute.BustMinX); + storage[0] = GetValue(0, RspAttribute.BustMinX, RspAttribute.BustMaxX); + storage[1] = GetValue(1, RspAttribute.BustMinY, RspAttribute.BustMaxY); + storage[2] = GetValue(2, RspAttribute.BustMinZ, RspAttribute.BustMaxZ); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + float GetValue(int dimension, RspAttribute min, RspAttribute max) + { + var minValue = cache.Rsp.TryGetValue(new RspIdentifier(clan, min), out var minEntry) + ? minEntry.Entry.Value + : (ptr + dimension)->Value; + var maxValue = cache.Rsp.TryGetValue(new RspIdentifier(clan, max), out var maxEntry) + ? maxEntry.Entry.Value + : (ptr + 3 + dimension)->Value; + return (maxValue - minValue) * bustScale + minValue; + } + } + else + { + ret = Task.Result.Original(cmpResource, storage, race, gender, isSecondSubRace, bodyType, bustSize); + } + + Penumbra.Log.Information( + $"[GetRspBust] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); + return ret; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs new file mode 100644 index 00000000..883f5fc6 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -0,0 +1,68 @@ +using OtterGui.Services; +using Penumbra.GameData.Enums; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Interop.Hooks.Meta; + +public class RspHeightHook : FastHook +{ + public delegate float Delegate(nint cmpResource, Race clan, byte gender, byte isSecondSubRace, byte bodyType, byte height); + + private readonly MetaState _metaState; + private readonly MetaFileManager _metaFileManager; + + public RspHeightHook(HookManager hooks, MetaState metaState, MetaFileManager metaFileManager) + { + _metaState = metaState; + _metaFileManager = metaFileManager; + Task = hooks.CreateHook("GetRspHeight", "E8 ?? ?? ?? ?? 48 8B 8E ?? ?? ?? ?? 44 8B CF", Detour, true); + } + + private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte height) + { + float scale; + if (bodyType < 2 && _metaState.RspCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + { + var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); + var (minIdent, maxIdent) = gender == 0 + ? (new RspIdentifier(clan, RspAttribute.MaleMinSize), new RspIdentifier(clan, RspAttribute.MaleMaxSize)) + : (new RspIdentifier(clan, RspAttribute.FemaleMinSize), new RspIdentifier(clan, RspAttribute.FemaleMaxSize)); + + float minEntry, maxEntry; + if (cache.Rsp.TryGetValue(minIdent, out var min)) + { + minEntry = min.Entry.Value; + maxEntry = cache.Rsp.TryGetValue(maxIdent, out var max) + ? max.Entry.Value + : CmpFile.GetDefault(_metaFileManager, minIdent.SubRace, maxIdent.Attribute).Value; + } + else + { + var ptr = CmpFile.GetDefaults(_metaFileManager, minIdent.SubRace, minIdent.Attribute); + if (cache.Rsp.TryGetValue(maxIdent, out var max)) + { + minEntry = ptr->Value; + maxEntry = max.Entry.Value; + } + else + { + minEntry = ptr[0].Value; + maxEntry = ptr[1].Value; + } + } + + scale = (maxEntry - minEntry) * height / 100f + minEntry; + } + else + { + scale = Task.Result.Original(cmpResource, race, gender, isSecondSubRace, bodyType, height); + } + + Penumbra.Log.Excessive( + $"[GetRspHeight] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {height}, returned {scale}."); + return scale; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs index 8f8f1d78..831c99bb 100644 --- a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs +++ b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.Collections; using Penumbra.GameData; using Penumbra.Interop.PathResolving; @@ -30,8 +31,8 @@ public sealed unsafe class RspSetupCharacter : FastHook +{ + public delegate float Delegate(nint cmpResource, Race clan, byte gender, byte isSecondSubRace, byte bodyType, byte height); + + private readonly MetaState _metaState; + private readonly MetaFileManager _metaFileManager; + + public RspTailHook(HookManager hooks, MetaState metaState, MetaFileManager metaFileManager) + { + _metaState = metaState; + _metaFileManager = metaFileManager; + Task = hooks.CreateHook("GetRspTail", "E8 ?? ?? ?? ?? 0F 28 F0 48 8B 05", Detour, true); + } + + private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte tailLength) + { + float scale; + if (bodyType < 2 && _metaState.RspCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + { + var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); + var (minIdent, maxIdent) = gender == 0 + ? (new RspIdentifier(clan, RspAttribute.MaleMinTail), new RspIdentifier(clan, RspAttribute.MaleMaxTail)) + : (new RspIdentifier(clan, RspAttribute.FemaleMinTail), new RspIdentifier(clan, RspAttribute.FemaleMaxTail)); + + float minEntry, maxEntry; + if (cache.Rsp.TryGetValue(minIdent, out var min)) + { + minEntry = min.Entry.Value; + maxEntry = cache.Rsp.TryGetValue(maxIdent, out var max) + ? max.Entry.Value + : CmpFile.GetDefault(_metaFileManager, minIdent.SubRace, maxIdent.Attribute).Value; + } + else + { + var ptr = CmpFile.GetDefaults(_metaFileManager, minIdent.SubRace, minIdent.Attribute); + if (cache.Rsp.TryGetValue(maxIdent, out var max)) + { + minEntry = ptr->Value; + maxEntry = max.Entry.Value; + } + else + { + minEntry = ptr[0].Value; + maxEntry = ptr[1].Value; + } + } + + scale = (maxEntry - minEntry) * tailLength / 100f + minEntry; + } + else + { + scale = Task.Result.Original(cmpResource, race, gender, isSecondSubRace, bodyType, tailLength); + } + + Penumbra.Log.Excessive( + $"[GetRspTail] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {tailLength}, returned {scale}."); + return scale; + } +} diff --git a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs index a3e56d7f..8479968f 100644 --- a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs +++ b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs @@ -30,7 +30,7 @@ public sealed unsafe class SetupVisor : FastHook _metaState.GmpCollection = _collectionResolver.IdentifyCollection(drawObject, true); _metaState.UndividedGmpId = modelId; var ret = Task.Result.Original.Invoke(drawObject, modelId, visorState); - Penumbra.Log.Information($"[Setup Visor] Invoked on {(nint)drawObject:X} with {modelId}, {visorState} -> {ret}."); + Penumbra.Log.Excessive($"[Setup Visor] Invoked on {(nint)drawObject:X} with {modelId}, {visorState} -> {ret}."); _metaState.GmpCollection = ResolveData.Invalid; return ret; } diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 6c9c1b7d..17cfa3f6 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -159,25 +159,33 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolvePapHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) { _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - return ResolvePath(_parent.MetaState.EstCollection, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); + var ret = ResolvePath(_parent.MetaState.EstCollection, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); + _parent.MetaState.EstCollection = ResolveData.Invalid; + return ret; } private nint ResolvePhybHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - return ResolvePath(_parent.MetaState.EstCollection, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + var ret = ResolvePath(_parent.MetaState.EstCollection, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection = ResolveData.Invalid; + return ret; } private nint ResolveSklbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - return ResolvePath(_parent.MetaState.EstCollection, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + var ret = ResolvePath(_parent.MetaState.EstCollection, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection = ResolveData.Invalid; + return ret; } private nint ResolveSkpHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - return ResolvePath(_parent.MetaState.EstCollection, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + var ret = ResolvePath(_parent.MetaState.EstCollection, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection = ResolveData.Invalid; + return ret; } private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 8fa09232..3da94ce3 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -49,6 +49,7 @@ public sealed unsafe class MetaState : IDisposable public ResolveData EqpCollection = ResolveData.Invalid; public ResolveData GmpCollection = ResolveData.Invalid; public ResolveData EstCollection = ResolveData.Invalid; + public ResolveData RspCollection = ResolveData.Invalid; public PrimaryId UndividedGmpId = 0; private ResolveData _lastCreatedCollection = ResolveData.Invalid; @@ -96,9 +97,6 @@ public sealed unsafe class MetaState : IDisposable _ => DisposableContainer.Empty, }; - public MetaList.MetaReverter ResolveRspData(ModCollection collection) - => collection.TemporarilySetCmpFile(_characterUtility); - public DecalReverter ResolveDecal(ResolveData resolve, bool which) => new(_config, _characterUtility, _resources, resolve, which); @@ -132,9 +130,9 @@ public sealed unsafe class MetaState : IDisposable var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, UsesDecal(*(uint*)modelCharaId, (nint)customize)); - var cmp = _lastCreatedCollection.ModCollection.TemporarilySetCmpFile(_characterUtility); + RspCollection = _lastCreatedCollection; _characterBaseCreateMetaChanges.Dispose(); // Should always be empty. - _characterBaseCreateMetaChanges = new DisposableContainer(decal, cmp); + _characterBaseCreateMetaChanges = new DisposableContainer(decal); } private void OnCharacterBaseCreated(ModelCharaId _1, CustomizeArray* _2, CharacterArmor* _3, CharacterBase* drawObject) @@ -144,6 +142,7 @@ public sealed unsafe class MetaState : IDisposable if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero && drawObject != null) _communicator.CreatedCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, _lastCreatedCollection.ModCollection, (nint)drawObject); + RspCollection = ResolveData.Invalid; _lastCreatedCollection = ResolveData.Invalid; } diff --git a/Penumbra/Meta/Files/CmpFile.cs b/Penumbra/Meta/Files/CmpFile.cs index 96cda496..8ca7cb80 100644 --- a/Penumbra/Meta/Files/CmpFile.cs +++ b/Penumbra/Meta/Files/CmpFile.cs @@ -46,6 +46,14 @@ public sealed unsafe class CmpFile : MetaBaseFile return *(RspEntry*)(data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); } + public static RspEntry* GetDefaults(MetaFileManager manager, SubRace subRace, RspAttribute attribute) + { + { + var data = (byte*)manager.CharacterUtility.DefaultResource(InternalIndex).Address; + return (RspEntry*)(data + RacialScalingStart + ToRspIndex(subRace) * RspData.ByteSize + (int)attribute * 4); + } + } + private static int ToRspIndex(SubRace subRace) => subRace switch { diff --git a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs index 2b7904ce..be02e321 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs @@ -85,7 +85,7 @@ public sealed class RspMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile { using var dis = ImRaii.Disabled(disabled); ImGui.TableNextColumn(); - var ret = DragInput("##rspValue"u8, [], ImUtf8.GlobalScale * 150, defaultEntry.Value, entry.Value, out var newValue, + var ret = DragInput("##rspValue"u8, [], ImUtf8.GlobalScale * 150, entry.Value, defaultEntry.Value, out var newValue, RspEntry.MinValue, RspEntry.MaxValue, 0.001f, !disabled); if (ret) entry = new RspEntry(newValue); From 600fd2ecd36faa72292a7a8e2e8ce8982f6c708e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Jun 2024 01:02:42 +0200 Subject: [PATCH 0697/1381] Get rid off EQDP files --- Penumbra/Collections/Cache/EqdpCache.cs | 115 +++++------------- Penumbra/Collections/Cache/MetaCache.cs | 38 +----- .../Collections/ModCollection.Cache.Access.cs | 36 ------ .../Interop/Hooks/Meta/CalculateHeight.cs | 5 +- .../Interop/Hooks/Meta/ChangeCustomize.cs | 23 ++-- .../Interop/Hooks/Meta/EqdpAccessoryHook.cs | 33 +++++ Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 32 +++++ Penumbra/Interop/Hooks/Meta/EqpHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/EstHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs | 5 +- .../Interop/Hooks/Meta/GetEqpIndirect2.cs | 23 ++-- Penumbra/Interop/Hooks/Meta/GmpHook.cs | 6 +- .../Interop/Hooks/Meta/ModelLoadComplete.cs | 9 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 3 +- .../Interop/Hooks/Meta/RspSetupCharacter.cs | 5 +- Penumbra/Interop/Hooks/Meta/RspTailHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/SetupVisor.cs | 6 +- Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 9 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 45 ++++--- Penumbra/Interop/PathResolving/MetaState.cs | 33 ++--- Penumbra/Interop/Services/MetaList.cs | 2 +- Penumbra/Penumbra.cs | 2 - 23 files changed, 192 insertions(+), 246 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs create mode 100644 Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index c63403ae..5bfe2dbf 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -1,8 +1,5 @@ -using OtterGui; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -11,108 +8,60 @@ namespace Penumbra.Collections.Cache; public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private readonly ExpandedEqdpFile?[] _eqdpFiles = new ExpandedEqdpFile[CharacterUtilityData.EqdpIndices.Length]; // TODO: female Hrothgar + private readonly Dictionary<(PrimaryId Id, GenderRace GenderRace, bool Accessory), EqdpEntry> _fullEntries = []; public override void SetFiles() - { - for (var i = 0; i < CharacterUtilityData.EqdpIndices.Length; ++i) - Manager.SetFile(_eqdpFiles[i], CharacterUtilityData.EqdpIndices[i]); - } + { } - public void SetFile(MetaIndex index) - { - var i = CharacterUtilityData.EqdpIndices.IndexOf(index); - if (i != -1) - Manager.SetFile(_eqdpFiles[i], index); - } - - public void ResetFiles() - { - foreach (var t in CharacterUtilityData.EqdpIndices) - Manager.SetFile(null, t); - } + public bool TryGetFullEntry(PrimaryId id, GenderRace genderRace, bool accessory, out EqdpEntry entry) + => _fullEntries.TryGetValue((id, genderRace, accessory), out entry); protected override void IncorporateChangesInternal() - { - foreach (var (identifier, (_, entry)) in this) - Apply(GetFile(identifier)!, identifier, entry); - - Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed EQDP manipulations."); - } - - public ExpandedEqdpFile? EqdpFile(GenderRace race, bool accessory) - => _eqdpFiles[Array.IndexOf(CharacterUtilityData.EqdpIndices, CharacterUtilityData.EqdpIdx(race, accessory))]; // TODO: female Hrothgar - - public MetaList.MetaReverter? TemporarilySetFile(GenderRace genderRace, bool accessory) - { - var idx = CharacterUtilityData.EqdpIdx(genderRace, accessory); - if (idx < 0) - { - Penumbra.Log.Warning($"Invalid Gender, Race or Accessory for EQDP file {genderRace}, {accessory}."); - return null; - } - - var i = CharacterUtilityData.EqdpIndices.IndexOf(idx); - if (i < 0) - { - Penumbra.Log.Warning($"Invalid Gender, Race or Accessory for EQDP file {genderRace}, {accessory}."); - return null; - } - - return Manager.TemporarilySetFile(_eqdpFiles[i], idx); - } + { } public void Reset() { - foreach (var file in _eqdpFiles.OfType()) - { - var relevant = CharacterUtility.RelevantIndices[file.Index.Value]; - file.Reset(Keys.Where(m => m.FileIndex() == relevant).Select(m => m.SetId)); - } - Clear(); + _fullEntries.Clear(); } protected override void ApplyModInternal(EqdpIdentifier identifier, EqdpEntry entry) { - if (GetFile(identifier) is { } file) - Apply(file, identifier, entry); + var tuple = (identifier.SetId, identifier.GenderRace, identifier.Slot.IsAccessory()); + var mask = Eqdp.Mask(identifier.Slot); + if (!_fullEntries.TryGetValue(tuple, out var currentEntry)) + currentEntry = ExpandedEqdpFile.GetDefault(Manager, identifier); + + _fullEntries[tuple] = (currentEntry & ~mask) | (entry & mask); } protected override void RevertModInternal(EqdpIdentifier identifier) { - if (GetFile(identifier) is { } file) - Apply(file, identifier, ExpandedEqdpFile.GetDefault(Manager, identifier)); - } + var tuple = (identifier.SetId, identifier.GenderRace, identifier.Slot.IsAccessory()); + var mask = Eqdp.Mask(identifier.Slot); - public static bool Apply(ExpandedEqdpFile file, EqdpIdentifier identifier, EqdpEntry entry) - { - var origEntry = file[identifier.SetId]; - var mask = Eqdp.Mask(identifier.Slot); - if ((origEntry & mask) == entry) - return false; - - file[identifier.SetId] = (origEntry & ~mask) | entry; - return true; + if (_fullEntries.TryGetValue(tuple, out var currentEntry)) + { + var def = ExpandedEqdpFile.GetDefault(Manager, identifier); + var newEntry = (currentEntry & ~mask) | (def & mask); + if (currentEntry != newEntry) + { + _fullEntries[tuple] = newEntry; + } + else + { + var slots = tuple.Item3 ? EquipSlotExtensions.AccessorySlots : EquipSlotExtensions.EquipmentSlots; + if (slots.All(s => !ContainsKey(identifier with { Slot = s }))) + _fullEntries.Remove(tuple); + else + _fullEntries[tuple] = newEntry; + } + } } protected override void Dispose(bool _) { - for (var i = 0; i < _eqdpFiles.Length; ++i) - { - _eqdpFiles[i]?.Dispose(); - _eqdpFiles[i] = null; - } - Clear(); - } - - private ExpandedEqdpFile? GetFile(EqdpIdentifier identifier) - { - if (!Manager.CharacterUtility.Ready) - return null; - - var index = Array.IndexOf(CharacterUtilityData.EqdpIndices, identifier.FileIndex()); - return _eqdpFiles[index] ??= new ExpandedEqdpFile(Manager, identifier.GenderRace, identifier.Slot.IsAccessory()); + _fullEntries.Clear(); } } diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index e6083351..614a5a2c 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,7 +1,5 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; @@ -115,48 +113,18 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) ~MetaCache() => Dispose(); - /// Set a single file. - public void SetFile(MetaIndex metaIndex) - { - switch (metaIndex) - { - case MetaIndex.Eqp: - break; - case MetaIndex.Gmp: - break; - case MetaIndex.HumanCmp: - Rsp.SetFiles(); - break; - case MetaIndex.FaceEst: - case MetaIndex.HairEst: - case MetaIndex.HeadEst: - case MetaIndex.BodyEst: - break; - default: - Eqdp.SetFile(metaIndex); - break; - } - } - /// Set the currently relevant IMC files for the collection cache. public void SetImcFiles(bool fromFullCompute) => Imc.SetFiles(fromFullCompute); - public MetaList.MetaReverter? TemporarilySetEqdpFile(GenderRace genderRace, bool accessory) - => Eqdp.TemporarilySetFile(genderRace, accessory); - /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) => Imc.GetFile(path, out file); internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, PrimaryId primaryId) - { - var eqdpFile = Eqdp.EqdpFile(race, accessory); - if (eqdpFile != null) - return primaryId.Id < eqdpFile.Count ? eqdpFile[primaryId] : default; - - return Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId); - } + => Eqdp.TryGetFullEntry(primaryId, race, accessory, out var entry) + ? entry + : Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId); internal EstEntry GetEstEntry(EstType type, GenderRace genderRace, PrimaryId primaryId) => Est.GetEstEntry(new EstIdentifier(primaryId, type, genderRace)); diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index d93a0f53..81751128 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -1,14 +1,9 @@ using OtterGui.Classes; -using Penumbra.GameData.Enums; using Penumbra.Mods; -using Penumbra.Interop.Structs; using Penumbra.Meta.Files; -using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; using Penumbra.Collections.Cache; -using Penumbra.Interop.Services; using Penumbra.Mods.Editor; -using Penumbra.GameData.Structs; namespace Penumbra.Collections; @@ -68,35 +63,4 @@ public partial class ModCollection internal SingleArray Conflicts(Mod mod) => _cache?.Conflicts(mod) ?? new SingleArray(); - - public void SetFiles(CharacterUtility utility) - { - if (_cache == null) - { - utility.ResetAll(); - } - else - { - _cache.Meta.SetFiles(); - Penumbra.Log.Debug($"Set CharacterUtility resources for collection {Identifier}."); - } - } - - public void SetMetaFile(CharacterUtility utility, MetaIndex idx) - { - if (_cache == null) - utility.ResetResource(idx); - else - _cache.Meta.SetFile(idx); - } - - // Used for short periods of changed files. - public MetaList.MetaReverter? TemporarilySetEqdpFile(CharacterUtility utility, GenderRace genderRace, bool accessory) - { - if (_cache != null) - return _cache?.Meta.TemporarilySetEqdpFile(genderRace, accessory); - - var idx = CharacterUtilityData.EqdpIdx(genderRace, accessory); - return idx >= 0 ? utility.TemporarilyResetResource(idx) : null; - } } diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index 5a207491..7936b831 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -23,10 +23,11 @@ public sealed unsafe class CalculateHeight : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private ulong Detour(Character* character) { - _metaState.RspCollection = _collectionResolver.IdentifyCollection((GameObject*)character, true); + var collection = _collectionResolver.IdentifyCollection((GameObject*)character, true); + _metaState.RspCollection.Push(collection); var ret = Task.Result.Original.Invoke(character); Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)character:X} -> {ret}."); - _metaState.RspCollection = ResolveData.Invalid; + _metaState.RspCollection.Pop(); return ret; } } diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs index 4e0a5744..f589cf4e 100644 --- a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -1,12 +1,12 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; using Penumbra.Collections; -using Penumbra.GameData; -using Penumbra.GameData.Structs; -using Penumbra.Interop.PathResolving; - -namespace Penumbra.Interop.Hooks.Meta; - +using Penumbra.GameData; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + public sealed unsafe class ChangeCustomize : FastHook { private readonly CollectionResolver _collectionResolver; @@ -24,14 +24,15 @@ public sealed unsafe class ChangeCustomize : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private bool Detour(Human* human, CustomizeArray* data, byte skipEquipment) { - _metaState.CustomizeChangeCollection = _collectionResolver.IdentifyCollection((DrawObject*)human, true); - _metaState.RspCollection = _metaState.CustomizeChangeCollection; + var collection = _collectionResolver.IdentifyCollection((DrawObject*)human, true); + _metaState.CustomizeChangeCollection = collection; + _metaState.RspCollection.Push(collection); using var decal1 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, true); using var decal2 = _metaState.ResolveDecal(_metaState.CustomizeChangeCollection, false); var ret = Task.Result.Original.Invoke(human, data, skipEquipment); Penumbra.Log.Excessive($"[Change Customize] Invoked on {(nint)human:X} with {(nint)data:X}, {skipEquipment} -> {ret}."); _metaState.CustomizeChangeCollection = ResolveData.Invalid; - _metaState.RspCollection = ResolveData.Invalid; + _metaState.RspCollection.Pop(); return ret; } -} +} diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs new file mode 100644 index 00000000..475e1eb7 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -0,0 +1,33 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class EqdpAccessoryHook : FastHook +{ + public delegate void Delegate(CharacterUtility* utility, EqdpEntry* entry, uint id, uint raceCode); + + private readonly MetaState _metaState; + + public EqdpAccessoryHook(HookManager hooks, MetaState metaState) + { + _metaState = metaState; + Task = hooks.CreateHook("GetEqdpAccessoryEntry", "E8 ?? ?? ?? ?? 41 BF ?? ?? ?? ?? 83 FB", Detour, true); + } + + private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) + { + if (_metaState.EqdpCollection.TryPeek(out var collection) + && collection is { Valid: true, ModCollection.MetaCache: { } cache } + && cache.Eqdp.TryGetFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, true, out var newEntry)) + *entry = newEntry; + else + Task.Result.Original(utility, entry, setId, raceCode); + Penumbra.Log.Information( + $"[GetEqdpAccessoryEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); + } +} diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs new file mode 100644 index 00000000..9b911710 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -0,0 +1,32 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class EqdpEquipHook : FastHook +{ + public delegate void Delegate(CharacterUtility* utility, EqdpEntry* entry, uint id, uint raceCode); + + private readonly MetaState _metaState; + + public EqdpEquipHook(HookManager hooks, MetaState metaState) + { + _metaState = metaState; + Task = hooks.CreateHook("GetEqdpEquipEntry", "E8 ?? ?? ?? ?? 85 DB 75 ?? F6 45", Detour, true); + } + + private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) + { + if (_metaState.EqdpCollection.TryPeek(out var collection) + && collection is { Valid: true, ModCollection.MetaCache: { } cache } + && cache.Eqdp.TryGetFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, false, out var newEntry)) + *entry = newEntry; + else + Task.Result.Original(utility, entry, setId, raceCode); + Penumbra.Log.Information( + $"[GetEqdpEquipEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); + } +} diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index 448605c1..7107e26b 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -19,7 +19,7 @@ public unsafe class EqpHook : FastHook private void Detour(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor) { - if (_metaState.EqpCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (_metaState.EqpCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { *flags = cache.Eqp.GetValues(armor); *flags = cache.GlobalEqp.Apply(*flags, armor); diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index 34935edb..23931182 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -21,7 +21,7 @@ public class EstHook : FastHook private EstEntry Detour(uint genderRace, int estType, uint id) { EstEntry ret; - if (_metaState.EstCollection is { Valid: true, ModCollection.MetaCache: { } cache } + if (_metaState.EstCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache } && cache.Est.TryGetValue(Convert(genderRace, estType, id), out var entry)) ret = entry.Entry; else diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs index beae6acc..a10b511a 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs @@ -29,8 +29,9 @@ public sealed unsafe class GetEqpIndirect : FastHook return; Penumbra.Log.Excessive($"[Get EQP Indirect] Invoked on {(nint)drawObject:X}."); - _metaState.EqpCollection = _collectionResolver.IdentifyCollection(drawObject, true); + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + _metaState.EqpCollection.Push(collection); Task.Result.Original(drawObject); - _metaState.EqpCollection = ResolveData.Invalid; + _metaState.EqpCollection.Pop(); } } diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs index 89aaa9b0..30ec2597 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs @@ -1,11 +1,11 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Services; -using Penumbra.Collections; -using Penumbra.GameData; -using Penumbra.Interop.PathResolving; - -namespace Penumbra.Interop.Hooks.Meta; - +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + public sealed unsafe class GetEqpIndirect2 : FastHook { private readonly CollectionResolver _collectionResolver; @@ -29,8 +29,9 @@ public sealed unsafe class GetEqpIndirect2 : FastHook return; Penumbra.Log.Excessive($"[Get EQP Indirect 2] Invoked on {(nint)drawObject:X}."); - _metaState.EqpCollection = _collectionResolver.IdentifyCollection(drawObject, true); + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + _metaState.EqpCollection.Push(collection); Task.Result.Original(drawObject); - _metaState.EqpCollection = ResolveData.Invalid; + _metaState.EqpCollection.Pop(); } -} +} diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 60966fb7..256d8702 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -27,15 +27,15 @@ public unsafe class GmpHook : FastHook private nint Detour(nint gmpResource, uint dividedHeadId) { nint ret; - if (_metaState.GmpCollection is { Valid: true, ModCollection.MetaCache: { } cache } - && cache.Gmp.TryGetValue(new GmpIdentifier(_metaState.UndividedGmpId), out var entry)) + if (_metaState.GmpCollection.TryPeek(out var collection) && collection.Collection is { Valid: true, ModCollection.MetaCache: { } cache } + && cache.Gmp.TryGetValue(new GmpIdentifier(collection.Id), out var entry)) { if (entry.Entry.Enabled) { *StablePointer.Pointer = entry.Entry.Value; // This function already gets the original ID divided by the block size, so we can compute the modulo with a single multiplication and addition. // We then go backwards from our pointer because this gets added by the calling functions. - ret = (nint)(StablePointer.Pointer - (_metaState.UndividedGmpId.Id - dividedHeadId * ExpandedEqpGmpBase.BlockSize)); + ret = (nint)(StablePointer.Pointer - (collection.Id.Id - dividedHeadId * ExpandedEqpGmpBase.BlockSize)); } else { diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs index 10c12594..2c17362d 100644 --- a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -23,10 +23,11 @@ public sealed unsafe class ModelLoadComplete : FastHook } var ret = storage; - if (bodyType < 2 && _metaState.RspCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var bustScale = bustSize / 100f; var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index 883f5fc6..cf88c34a 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -1,3 +1,4 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.Interop.PathResolving; @@ -24,7 +25,7 @@ public class RspHeightHook : FastHook private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte height) { float scale; - if (bodyType < 2 && _metaState.RspCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 diff --git a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs index 831c99bb..58856f52 100644 --- a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs +++ b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs @@ -31,8 +31,9 @@ public sealed unsafe class RspSetupCharacter : FastHook private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte tailLength) { float scale; - if (bodyType < 2 && _metaState.RspCollection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 diff --git a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs index 8479968f..82b24dc4 100644 --- a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs +++ b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs @@ -27,11 +27,11 @@ public sealed unsafe class SetupVisor : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private byte Detour(DrawObject* drawObject, ushort modelId, byte visorState) { - _metaState.GmpCollection = _collectionResolver.IdentifyCollection(drawObject, true); - _metaState.UndividedGmpId = modelId; + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + _metaState.GmpCollection.Push((collection, modelId)); var ret = Task.Result.Original.Invoke(drawObject, modelId, visorState); Penumbra.Log.Excessive($"[Setup Visor] Invoked on {(nint)drawObject:X} with {modelId}, {visorState} -> {ret}."); - _metaState.GmpCollection = ResolveData.Invalid; + _metaState.GmpCollection.Pop(); return ret; } } diff --git a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs index b0298ac7..76854bca 100644 --- a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs @@ -29,10 +29,11 @@ public sealed unsafe class UpdateModel : FastHook return; Penumbra.Log.Excessive($"[Update Model] Invoked on {(nint)drawObject:X}."); - var collection = _collectionResolver.IdentifyCollection(drawObject, true); - using var eqdp = _metaState.ResolveEqdpData(collection.ModCollection, MetaState.GetDrawObjectGenderRace((nint)drawObject), true, true); - _metaState.EqpCollection = collection; + var collection = _collectionResolver.IdentifyCollection(drawObject, true); + _metaState.EqpCollection.Push(collection); + _metaState.EqdpCollection.Push(collection); Task.Result.Original(drawObject); - _metaState.EqpCollection = ResolveData.Invalid; + _metaState.EqpCollection.Pop(); + _metaState.EqdpCollection.Pop(); } } diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 17cfa3f6..5941773f 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -1,11 +1,9 @@ using System.Text.Unicode; using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Classes; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Interop.PathResolving; -using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Resources; @@ -149,42 +147,51 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolveMdlHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) { - var data = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - using var eqdp = slotIndex > 9 || _parent.InInternalResolve - ? DisposableContainer.Empty - : _parent.MetaState.ResolveEqdpData(data.ModCollection, MetaState.GetHumanGenderRace(drawObject), slotIndex < 5, slotIndex > 4); - return ResolvePath(data, _resolveMdlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + if (slotIndex < 10) + _parent.MetaState.EqdpCollection.Push(collection); + + var ret = ResolvePath(collection, _resolveMdlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); + if (slotIndex < 10) + _parent.MetaState.EqdpCollection.Pop(); + + return ret; } private nint ResolvePapHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) { - _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - var ret = ResolvePath(_parent.MetaState.EstCollection, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); - _parent.MetaState.EstCollection = ResolveData.Invalid; + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = ResolvePath(collection, + _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); + _parent.MetaState.EstCollection.Pop(); return ret; } private nint ResolvePhybHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { - _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - var ret = ResolvePath(_parent.MetaState.EstCollection, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); - _parent.MetaState.EstCollection = ResolveData.Invalid; + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = ResolvePath(collection, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection.Pop(); return ret; } private nint ResolveSklbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { - _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - var ret = ResolvePath(_parent.MetaState.EstCollection, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); - _parent.MetaState.EstCollection = ResolveData.Invalid; + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = ResolvePath(collection, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection.Pop(); return ret; } private nint ResolveSkpHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { - _parent.MetaState.EstCollection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - var ret = ResolvePath(_parent.MetaState.EstCollection, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); - _parent.MetaState.EstCollection = ResolveData.Invalid; + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = ResolvePath(collection, _resolveSkpPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection.Pop(); return ret; } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 3da94ce3..4bd23cf8 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -45,12 +45,14 @@ public sealed unsafe class MetaState : IDisposable private readonly CharacterUtility _characterUtility; private readonly CreateCharacterBase _createCharacterBase; - public ResolveData CustomizeChangeCollection = ResolveData.Invalid; - public ResolveData EqpCollection = ResolveData.Invalid; - public ResolveData GmpCollection = ResolveData.Invalid; - public ResolveData EstCollection = ResolveData.Invalid; - public ResolveData RspCollection = ResolveData.Invalid; - public PrimaryId UndividedGmpId = 0; + public ResolveData CustomizeChangeCollection = ResolveData.Invalid; + public readonly Stack EqpCollection = []; + public readonly Stack EqdpCollection = []; + public readonly Stack EstCollection = []; + public readonly Stack RspCollection = []; + + public readonly Stack<(ResolveData Collection, PrimaryId Id)> GmpCollection = []; + private ResolveData _lastCreatedCollection = ResolveData.Invalid; private DisposableContainer _characterBaseCreateMetaChanges = DisposableContainer.Empty; @@ -82,21 +84,6 @@ public sealed unsafe class MetaState : IDisposable return false; } - public DisposableContainer ResolveEqdpData(ModCollection collection, GenderRace race, bool equipment, bool accessory) - => (equipment, accessory) switch - { - (true, true) => new DisposableContainer(race.Dependencies().SelectMany(r => new[] - { - collection.TemporarilySetEqdpFile(_characterUtility, r, false), - collection.TemporarilySetEqdpFile(_characterUtility, r, true), - })), - (true, false) => new DisposableContainer(race.Dependencies() - .Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, false))), - (false, true) => new DisposableContainer(race.Dependencies() - .Select(r => collection.TemporarilySetEqdpFile(_characterUtility, r, true))), - _ => DisposableContainer.Empty, - }; - public DecalReverter ResolveDecal(ResolveData resolve, bool which) => new(_config, _characterUtility, _resources, resolve, which); @@ -130,7 +117,7 @@ public sealed unsafe class MetaState : IDisposable var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, UsesDecal(*(uint*)modelCharaId, (nint)customize)); - RspCollection = _lastCreatedCollection; + RspCollection.Push(_lastCreatedCollection); _characterBaseCreateMetaChanges.Dispose(); // Should always be empty. _characterBaseCreateMetaChanges = new DisposableContainer(decal); } @@ -142,7 +129,7 @@ public sealed unsafe class MetaState : IDisposable if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero && drawObject != null) _communicator.CreatedCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, _lastCreatedCollection.ModCollection, (nint)drawObject); - RspCollection = ResolveData.Invalid; + RspCollection.Pop(); _lastCreatedCollection = ResolveData.Invalid; } diff --git a/Penumbra/Interop/Services/MetaList.cs b/Penumbra/Interop/Services/MetaList.cs index dc472b8e..24d3f088 100644 --- a/Penumbra/Interop/Services/MetaList.cs +++ b/Penumbra/Interop/Services/MetaList.cs @@ -87,7 +87,7 @@ public unsafe class MetaList : IDisposable => SetResourceInternal(_defaultResourceData, _defaultResourceSize); private void SetResourceToDefaultCollection() - => _utility.Active.Default.SetMetaFile(_utility, GlobalMetaIndex); + {} public void Dispose() { diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 3bbfdf65..905b998d 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -144,7 +144,6 @@ public class Penumbra : IDalamudPlugin { if (_characterUtility.Ready) { - _collectionManager.Active.Default.SetFiles(_characterUtility); _residentResources.Reload(); _redrawService.RedrawAll(RedrawType.Redraw); } @@ -153,7 +152,6 @@ public class Penumbra : IDalamudPlugin { if (_characterUtility.Ready) { - _characterUtility.ResetAll(); _residentResources.Reload(); _redrawService.RedrawAll(RedrawType.Redraw); } From 91d9e465ede9850fd7d5d0a457870e068cfd0cc8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Jun 2024 12:30:47 +0200 Subject: [PATCH 0698/1381] Improve eqdp. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/EqdpCache.cs | 49 ++++++++----------- Penumbra/Collections/Cache/MetaCache.cs | 4 +- .../Interop/Hooks/Meta/EqdpAccessoryHook.cs | 9 ++-- Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 8 ++- Penumbra/Interop/PathResolving/MetaState.cs | 17 ------- .../Services/ShaderReplacementFixer.cs | 4 +- 7 files changed, 31 insertions(+), 62 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index cf1ff07e..3fbc7045 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit cf1ff07e900e2f93ab628a1fa535fc2b103794a5 +Subproject commit 3fbc704515b7b5fa9be02fb2a44719fc333747c1 diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index 5bfe2dbf..6047736b 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -1,20 +1,22 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private readonly Dictionary<(PrimaryId Id, GenderRace GenderRace, bool Accessory), EqdpEntry> _fullEntries = []; + private readonly Dictionary<(PrimaryId Id, GenderRace GenderRace, bool Accessory), (EqdpEntry Entry, EqdpEntry InverseMask)> _fullEntries = + []; public override void SetFiles() { } - public bool TryGetFullEntry(PrimaryId id, GenderRace genderRace, bool accessory, out EqdpEntry entry) - => _fullEntries.TryGetValue((id, genderRace, accessory), out entry); + public EqdpEntry ApplyFullEntry(PrimaryId id, GenderRace genderRace, bool accessory, EqdpEntry originalEntry) + => _fullEntries.TryGetValue((id, genderRace, accessory), out var pair) + ? (originalEntry & pair.InverseMask) | pair.Entry + : originalEntry; protected override void IncorporateChangesInternal() { } @@ -27,36 +29,27 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) protected override void ApplyModInternal(EqdpIdentifier identifier, EqdpEntry entry) { - var tuple = (identifier.SetId, identifier.GenderRace, identifier.Slot.IsAccessory()); - var mask = Eqdp.Mask(identifier.Slot); - if (!_fullEntries.TryGetValue(tuple, out var currentEntry)) - currentEntry = ExpandedEqdpFile.GetDefault(Manager, identifier); - - _fullEntries[tuple] = (currentEntry & ~mask) | (entry & mask); + var tuple = (identifier.SetId, identifier.GenderRace, identifier.Slot.IsAccessory()); + var mask = Eqdp.Mask(identifier.Slot); + var inverseMask = ~mask; + if (_fullEntries.TryGetValue(tuple, out var pair)) + pair = ((pair.Entry & inverseMask) | (entry & mask), pair.InverseMask & inverseMask); + else + pair = (entry & mask, inverseMask); + _fullEntries[tuple] = pair; } protected override void RevertModInternal(EqdpIdentifier identifier) { var tuple = (identifier.SetId, identifier.GenderRace, identifier.Slot.IsAccessory()); - var mask = Eqdp.Mask(identifier.Slot); - if (_fullEntries.TryGetValue(tuple, out var currentEntry)) - { - var def = ExpandedEqdpFile.GetDefault(Manager, identifier); - var newEntry = (currentEntry & ~mask) | (def & mask); - if (currentEntry != newEntry) - { - _fullEntries[tuple] = newEntry; - } - else - { - var slots = tuple.Item3 ? EquipSlotExtensions.AccessorySlots : EquipSlotExtensions.EquipmentSlots; - if (slots.All(s => !ContainsKey(identifier with { Slot = s }))) - _fullEntries.Remove(tuple); - else - _fullEntries[tuple] = newEntry; - } - } + if (!_fullEntries.Remove(tuple, out var pair)) + return; + + var mask = Eqdp.Mask(identifier.Slot); + var newMask = pair.InverseMask | mask; + if (newMask is not EqdpEntry.FullMask) + _fullEntries[tuple] = (pair.Entry & ~mask, newMask); } protected override void Dispose(bool _) diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 614a5a2c..92a445dd 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -122,9 +122,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) => Imc.GetFile(path, out file); internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, PrimaryId primaryId) - => Eqdp.TryGetFullEntry(primaryId, race, accessory, out var entry) - ? entry - : Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId); + => Eqdp.ApplyFullEntry(primaryId, race, accessory, Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId)); internal EstEntry GetEstEntry(EstType type, GenderRace genderRace, PrimaryId primaryId) => Est.GetEstEntry(new EstIdentifier(primaryId, type, genderRace)); diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs index 475e1eb7..f7390ea3 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -3,7 +3,6 @@ using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; -using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Meta; @@ -21,12 +20,10 @@ public unsafe class EqdpAccessoryHook : FastHook private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) { + Task.Result.Original(utility, entry, setId, raceCode); if (_metaState.EqdpCollection.TryPeek(out var collection) - && collection is { Valid: true, ModCollection.MetaCache: { } cache } - && cache.Eqdp.TryGetFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, true, out var newEntry)) - *entry = newEntry; - else - Task.Result.Original(utility, entry, setId, raceCode); + && collection is { Valid: true, ModCollection.MetaCache: { } cache }) + *entry = cache.Eqdp.ApplyFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, true, *entry); Penumbra.Log.Information( $"[GetEqdpAccessoryEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); } diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs index 9b911710..9b635b1f 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -20,12 +20,10 @@ public unsafe class EqdpEquipHook : FastHook private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) { + Task.Result.Original(utility, entry, setId, raceCode); if (_metaState.EqdpCollection.TryPeek(out var collection) - && collection is { Valid: true, ModCollection.MetaCache: { } cache } - && cache.Eqdp.TryGetFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, false, out var newEntry)) - *entry = newEntry; - else - Task.Result.Original(utility, entry, setId, raceCode); + && collection is { Valid: true, ModCollection.MetaCache: { } cache }) + *entry = cache.Eqdp.ApplyFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, false, *entry); Penumbra.Log.Information( $"[GetEqdpEquipEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 4bd23cf8..7f820b4e 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -2,13 +2,11 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Api.Enums; -using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Services; using Penumbra.String.Classes; -using ObjectType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using Penumbra.Interop.Hooks.Objects; @@ -87,21 +85,6 @@ public sealed unsafe class MetaState : IDisposable public DecalReverter ResolveDecal(ResolveData resolve, bool which) => new(_config, _characterUtility, _resources, resolve, which); - public static GenderRace GetHumanGenderRace(nint human) - => (GenderRace)((Human*)human)->RaceSexId; - - public static GenderRace GetDrawObjectGenderRace(nint drawObject) - { - var draw = (DrawObject*)drawObject; - if (draw->Object.GetObjectType() != ObjectType.CharacterBase) - return GenderRace.Unknown; - - var c = (CharacterBase*)drawObject; - return c->GetModelType() == CharacterBase.ModelType.Human - ? GetHumanGenderRace(drawObject) - : GenderRace.Unknown; - } - public void Dispose() { _createCharacterBase.Unsubscribe(OnCreatingCharacterBase); diff --git a/Penumbra/Interop/Services/ShaderReplacementFixer.cs b/Penumbra/Interop/Services/ShaderReplacementFixer.cs index 3809ecbd..95e70b45 100644 --- a/Penumbra/Interop/Services/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Services/ShaderReplacementFixer.cs @@ -139,9 +139,9 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic // Performance considerations: // - This function is called from several threads simultaneously, hence the need for synchronization in the swapping path ; - // - Function is called each frame for each material on screen, after culling, i. e. up to thousands of times a frame in crowded areas ; + // - Function is called each frame for each material on screen, after culling, i.e. up to thousands of times a frame in crowded areas ; // - Swapping path is taken up to hundreds of times a frame. - // At the time of writing, the lock doesn't seem to have a noticeable impact in either framerate or CPU usage, but the swapping path shall still be avoided as much as possible. + // At the time of writing, the lock doesn't seem to have a noticeable impact in either frame rate or CPU usage, but the swapping path shall still be avoided as much as possible. lock (_skinLock) { try From be729afd4b382e618c91558373e013f34959ba02 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 17 Jun 2024 16:39:10 +0200 Subject: [PATCH 0699/1381] Some cleanup --- Penumbra/Collections/Cache/ImcCache.cs | 2 -- Penumbra/Communication/CreatingCharacterBase.cs | 3 +-- Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 2 +- Penumbra/Mods/Manager/ModManager.cs | 2 +- 6 files changed, 5 insertions(+), 8 deletions(-) diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index a9daf795..c6bb0330 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -1,5 +1,3 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Render; -using Penumbra.Collections.Manager; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; using Penumbra.Meta; diff --git a/Penumbra/Communication/CreatingCharacterBase.cs b/Penumbra/Communication/CreatingCharacterBase.cs index 8a906ca0..51d55868 100644 --- a/Penumbra/Communication/CreatingCharacterBase.cs +++ b/Penumbra/Communication/CreatingCharacterBase.cs @@ -1,5 +1,4 @@ using OtterGui.Classes; -using Penumbra.Api; using Penumbra.Api.Api; using Penumbra.Services; @@ -19,7 +18,7 @@ public sealed class CreatingCharacterBase() { public enum Priority { - /// + /// Api = 0, /// diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs index f7390ea3..aaaaccd4 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -24,7 +24,7 @@ public unsafe class EqdpAccessoryHook : FastHook if (_metaState.EqdpCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) *entry = cache.Eqdp.ApplyFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, true, *entry); - Penumbra.Log.Information( + Penumbra.Log.Excessive( $"[GetEqdpAccessoryEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); } } diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs index 9b635b1f..2711f195 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -24,7 +24,7 @@ public unsafe class EqdpEquipHook : FastHook if (_metaState.EqdpCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) *entry = cache.Eqdp.ApplyFullEntry(new PrimaryId((ushort)setId), (GenderRace)raceCode, false, *entry); - Penumbra.Log.Information( + Penumbra.Log.Excessive( $"[GetEqdpEquipEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); } } diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index 13a5410d..86759460 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -59,7 +59,7 @@ public unsafe class RspBustHook : FastHook ret = Task.Result.Original(cmpResource, storage, race, gender, isSecondSubRace, bodyType, bustSize); } - Penumbra.Log.Information( + Penumbra.Log.Excessive( $"[GetRspBust] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); return ret; } diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 62b54865..42082383 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -261,7 +261,7 @@ public sealed class ModManager : ModStorage, IDisposable /// /// Set the mod base directory. - /// If its not the first time, check if it is the same directory as before. + /// If it's not the first time, check if it is the same directory as before. /// Also checks if the directory is available and tries to create it if it is not. /// private void SetBaseDirectory(string newPath, bool firstTime, out string resultNewDir) From d7a8c9415bb57f8fe13e3cfeed067e6d4a579470 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 17 Jun 2024 23:11:42 +0200 Subject: [PATCH 0700/1381] Use specific counter for Imc. --- Penumbra/Collections/Cache/ImcCache.cs | 2 ++ Penumbra/Collections/ModCollection.cs | 2 ++ Penumbra/Interop/PathResolving/PathDataHandler.cs | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index c6bb0330..786463bc 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -68,6 +68,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) protected override void ApplyModInternal(ImcIdentifier identifier, ImcEntry entry) { + ++Collection.ImcChangeCounter; if (Manager.CharacterUtility.Ready) ApplyFile(identifier, entry); } @@ -102,6 +103,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) protected override void RevertModInternal(ImcIdentifier identifier) { + ++Collection.ImcChangeCounter; var path = identifier.GamePath(); if (!_imcFiles.TryGetValue(path, out var pair)) return; diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index 9286d459..eb5ab46a 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -56,6 +56,8 @@ public partial class ModCollection /// public int ChangeCounter { get; private set; } + public uint ImcChangeCounter { get; set; } + /// Increment the number of changes in the effective file list. public int IncrementCounter() => ++ChangeCounter; diff --git a/Penumbra/Interop/PathResolving/PathDataHandler.cs b/Penumbra/Interop/PathResolving/PathDataHandler.cs index 5627e015..a8be97c8 100644 --- a/Penumbra/Interop/PathResolving/PathDataHandler.cs +++ b/Penumbra/Interop/PathResolving/PathDataHandler.cs @@ -32,7 +32,7 @@ public static class PathDataHandler /// Create the encoding path for an IMC file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateImc(ByteString path, ModCollection collection) - => CreateBase(path, collection); + => new($"|{collection.LocalId.Id}_{collection.ImcChangeCounter}_{DiscriminatorString}|{path}"); /// Create the encoding path for a TMB file. [MethodImpl(MethodImplOptions.AggressiveInlining)] From 03d3c38ad577756d3a4fb20c1bd0417344538727 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 18 Jun 2024 17:52:34 +0200 Subject: [PATCH 0701/1381] Improve Imc Handling. --- Penumbra/Collections/Cache/CollectionCache.cs | 16 +--- .../Cache/CollectionCacheManager.cs | 2 - Penumbra/Collections/Cache/ImcCache.cs | 58 ++++---------- Penumbra/Collections/Cache/MetaCache.cs | 8 +- .../Interop/PathResolving/PathResolver.cs | 50 +++--------- .../Interop/PathResolving/SubfileHelper.cs | 17 ++-- .../Interop/ResourceLoading/ResourceLoader.cs | 69 +++++++++++++++++ Penumbra/Interop/Services/CharacterUtility.cs | 35 +-------- Penumbra/Meta/Files/CmpFile.cs | 2 +- Penumbra/Meta/Files/EqdpFile.cs | 2 +- Penumbra/Meta/Files/EqpGmpFile.cs | 2 +- Penumbra/Meta/Files/EstFile.cs | 2 +- Penumbra/Meta/Files/EvpFile.cs | 6 +- Penumbra/Meta/Files/ImcFile.cs | 30 ++++---- Penumbra/Meta/Files/MetaBaseFile.cs | 77 +++++++++++++++---- Penumbra/Meta/MetaFileManager.cs | 54 +------------ 16 files changed, 197 insertions(+), 233 deletions(-) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index fd801d3b..4755840e 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -36,7 +36,7 @@ public sealed class CollectionCache : IDisposable => ConflictDict.Values; public SingleArray Conflicts(IMod mod) - => ConflictDict.TryGetValue(mod, out SingleArray c) ? c : new SingleArray(); + => ConflictDict.TryGetValue(mod, out var c) ? c : new SingleArray(); private int _changedItemsSaveCounter = -1; @@ -125,12 +125,6 @@ public sealed class CollectionCache : IDisposable return ret; } - public void ForceFile(Utf8GamePath path, FullPath fullPath) - => _manager.AddChange(ChangeData.ForcedFile(this, path, fullPath)); - - public void RemovePath(Utf8GamePath path) - => _manager.AddChange(ChangeData.ForcedFile(this, path, FullPath.Empty)); - public void ReloadMod(IMod mod, bool addMetaChanges) => _manager.AddChange(ChangeData.ModReload(this, mod, addMetaChanges)); @@ -251,9 +245,6 @@ public sealed class CollectionCache : IDisposable if (addMetaChanges) { _collection.IncrementCounter(); - if (mod.TotalManipulations > 0) - AddMetaFiles(false); - _manager.MetaFileManager.ApplyDefaultFiles(_collection); } } @@ -408,11 +399,6 @@ public sealed class CollectionCache : IDisposable } - // Add all necessary meta file redirects. - public void AddMetaFiles(bool fromFullCompute) - => Meta.SetImcFiles(fromFullCompute); - - // Identify and record all manipulated objects for this entire collection. private void SetChangedItems() { diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index ae424b94..02c9c8a9 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -180,8 +180,6 @@ public class CollectionCacheManager : IDisposable foreach (var mod in _modStorage) cache.AddModSync(mod, false); - cache.AddMetaFiles(true); - collection.IncrementCounter(); MetaFileManager.ApplyDefaultFiles(collection); diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 786463bc..e7eedc04 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -1,20 +1,22 @@ using Penumbra.GameData.Structs; -using Penumbra.Interop.PathResolving; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; -using Penumbra.String.Classes; +using Penumbra.String; namespace Penumbra.Collections.Cache; public sealed class ImcCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private readonly Dictionary)> _imcFiles = []; + private readonly Dictionary)> _imcFiles = []; public override void SetFiles() - => SetFiles(false); + { } - public bool GetFile(Utf8GamePath path, [NotNullWhen(true)] out ImcFile? file) + public bool HasFile(ByteString path) + => _imcFiles.ContainsKey(path); + + public bool GetFile(ByteString path, [NotNullWhen(true)] out ImcFile? file) { if (!_imcFiles.TryGetValue(path, out var p)) { @@ -26,56 +28,31 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) return true; } - public void SetFiles(bool fromFullCompute) - { - if (fromFullCompute) - foreach (var (path, _) in _imcFiles) - Collection._cache!.ForceFileSync(path, PathDataHandler.CreateImc(path.Path, Collection)); - else - foreach (var (path, _) in _imcFiles) - Collection._cache!.ForceFile(path, PathDataHandler.CreateImc(path.Path, Collection)); - } - - public void ResetFiles() - { - foreach (var (path, _) in _imcFiles) - Collection._cache!.ForceFile(path, FullPath.Empty); - } - protected override void IncorporateChangesInternal() - { - if (!Manager.CharacterUtility.Ready) - return; - - foreach (var (identifier, (_, entry)) in this) - ApplyFile(identifier, entry); - - Penumbra.Log.Verbose($"{Collection.AnonymizedName}: Loaded {Count} delayed IMC manipulations."); - } + { } public void Reset() { - foreach (var (path, (file, set)) in _imcFiles) + foreach (var (_, (file, set)) in _imcFiles) { - Collection._cache!.RemovePath(path); file.Reset(); set.Clear(); } + _imcFiles.Clear(); Clear(); } protected override void ApplyModInternal(ImcIdentifier identifier, ImcEntry entry) { ++Collection.ImcChangeCounter; - if (Manager.CharacterUtility.Ready) - ApplyFile(identifier, entry); + ApplyFile(identifier, entry); } private void ApplyFile(ImcIdentifier identifier, ImcEntry entry) { - var path = identifier.GamePath(); + var path = identifier.GamePath().Path; try { if (!_imcFiles.TryGetValue(path, out var pair)) @@ -87,8 +64,6 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) pair.Item2.Add(identifier); _imcFiles[path] = pair; - var fullPath = PathDataHandler.CreateImc(pair.Item1.Path.Path, Collection); - Collection._cache!.ForceFile(path, fullPath); } catch (ImcException e) { @@ -104,7 +79,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) protected override void RevertModInternal(ImcIdentifier identifier) { ++Collection.ImcChangeCounter; - var path = identifier.GamePath(); + var path = identifier.GamePath().Path; if (!_imcFiles.TryGetValue(path, out var pair)) return; @@ -114,17 +89,12 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) if (pair.Item2.Count == 0) { _imcFiles.Remove(path); - Collection._cache!.ForceFile(pair.Item1.Path, FullPath.Empty); pair.Item1.Dispose(); return; } var def = ImcFile.GetDefault(Manager, pair.Item1.Path, identifier.EquipSlot, identifier.Variant, out _); - if (!Apply(pair.Item1, identifier, def)) - return; - - var fullPath = PathDataHandler.CreateImc(pair.Item1.Path.Path, Collection); - Collection._cache!.ForceFile(pair.Item1.Path, fullPath); + Apply(pair.Item1, identifier, def); } public static bool Apply(ImcFile file, ImcIdentifier identifier, ImcEntry entry) diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 92a445dd..253f3c7f 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -36,7 +36,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Est.SetFiles(); Gmp.SetFiles(); Rsp.SetFiles(); - Imc.SetFiles(false); + Imc.SetFiles(); } public void Reset() @@ -113,13 +113,9 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) ~MetaCache() => Dispose(); - /// Set the currently relevant IMC files for the collection cache. - public void SetImcFiles(bool fromFullCompute) - => Imc.SetFiles(fromFullCompute); - /// Try to obtain a manipulated IMC file. public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) - => Imc.GetFile(path, out file); + => Imc.GetFile(path.Path, out file); internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, PrimaryId primaryId) => Eqdp.ApplyFullEntry(primaryId, race, accessory, Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId)); diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index e5c75327..e069e3ea 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,11 +1,8 @@ -using System.Runtime; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Interop.ResourceLoading; -using Penumbra.Interop.Structs; -using Penumbra.String; using Penumbra.String.Classes; using Penumbra.Util; @@ -27,24 +24,16 @@ public class PathResolver : IDisposable public unsafe PathResolver(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ResourceLoader loader, SubfileHelper subfileHelper, PathState pathState, MetaState metaState, CollectionResolver collectionResolver, GameState gameState) { - _performance = performance; - _config = config; - _collectionManager = collectionManager; - _subfileHelper = subfileHelper; - _pathState = pathState; - _metaState = metaState; - _gameState = gameState; - _collectionResolver = collectionResolver; - _loader = loader; - _loader.ResolvePath = ResolvePath; - _loader.FileLoaded += ImcLoadResource; - } - - /// Obtain a temporary or permanent collection by local ID. - public bool CollectionByLocalId(LocalCollectionId id, out ModCollection collection) - { - collection = _collectionManager.Storage.ByLocalId(id); - return collection != ModCollection.Empty; + _performance = performance; + _config = config; + _collectionManager = collectionManager; + _subfileHelper = subfileHelper; + _pathState = pathState; + _metaState = metaState; + _gameState = gameState; + _collectionResolver = collectionResolver; + _loader = loader; + _loader.ResolvePath = ResolvePath; } /// Try to resolve the given game path to the replaced path. @@ -120,7 +109,6 @@ public class PathResolver : IDisposable public unsafe void Dispose() { _loader.ResetResolvePath(); - _loader.FileLoaded -= ImcLoadResource; } /// Use the default method of path replacement. @@ -130,24 +118,6 @@ public class PathResolver : IDisposable return (resolved, _collectionManager.Active.Default.ToResolveData()); } - /// After loading an IMC file, replace its contents with the modded IMC file. - private unsafe void ImcLoadResource(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, - ReadOnlySpan additionalData) - { - if (resource->FileType != ResourceType.Imc - || !PathDataHandler.Read(additionalData, out var data) - || data.Discriminator != PathDataHandler.Discriminator - || !Utf8GamePath.FromByteString(path, out var gamePath) - || !CollectionByLocalId(data.Collection, out var collection) - || !collection.HasCache - || !collection.GetImcFile(gamePath, out var file)) - return; - - file.Replace(resource); - Penumbra.Log.Verbose( - $"[ResourceLoader] Loaded {gamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); - } - /// Resolve a path from the interface collection. private (FullPath?, ResolveData) ResolveUi(Utf8GamePath path) => (_collectionManager.Active.Interface.ResolvePath(path), diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 793ea20b..b9631cf2 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -70,14 +70,15 @@ public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection PathDataHandler.CreateMtrl(path, resolveData.ModCollection, originalPath), - ResourceType.Avfx => PathDataHandler.CreateAvfx(path, resolveData.ModCollection), - ResourceType.Tmb => PathDataHandler.CreateTmb(path, resolveData.ModCollection), - _ => resolved, - }; + resolved = type switch + { + ResourceType.Mtrl when nonDefault => PathDataHandler.CreateMtrl(path, resolveData.ModCollection, originalPath), + ResourceType.Avfx when nonDefault => PathDataHandler.CreateAvfx(path, resolveData.ModCollection), + ResourceType.Tmb when nonDefault => PathDataHandler.CreateTmb(path, resolveData.ModCollection), + ResourceType.Imc when resolveData.ModCollection.MetaCache?.Imc.HasFile(path) ?? false => PathDataHandler.CreateImc(path, + resolveData.ModCollection), + _ => resolved, + }; data = (resolved, resolveData); } diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 7b49beab..fae38907 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,6 +1,9 @@ +using System.Collections.Frozen; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; +using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; using Penumbra.Interop.SafeHandles; using Penumbra.Interop.Structs; @@ -10,6 +13,72 @@ using FileMode = Penumbra.Interop.Structs.FileMode; namespace Penumbra.Interop.ResourceLoading; +public interface IFilePostProcessor : IService +{ + public ResourceType Type { get; } + public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData); +} + +public sealed class MaterialFilePostProcessor : IFilePostProcessor +{ + public ResourceType Type + => ResourceType.Mtrl; + + public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) + { + if (!PathDataHandler.ReadMtrl(additionalData, out var data)) + return; + } +} + +public sealed class ImcFilePostProcessor(CollectionStorage collections) : IFilePostProcessor +{ + public ResourceType Type + => ResourceType.Imc; + + public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) + { + if (!PathDataHandler.Read(additionalData, out var data) || data.Discriminator != PathDataHandler.Discriminator) + return; + + var collection = collections.ByLocalId(data.Collection); + if (collection.MetaCache is not { } cache) + return; + + if (!cache.Imc.GetFile(originalGamePath, out var file)) + return; + + file.Replace(resource); + Penumbra.Log.Information( + $"[ResourceLoader] Loaded {originalGamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); + } +} + +public unsafe class FilePostProcessService : IRequiredService, IDisposable +{ + private readonly ResourceLoader _resourceLoader; + private readonly FrozenDictionary _processors; + + public FilePostProcessService(ResourceLoader resourceLoader, ServiceManager services) + { + _resourceLoader = resourceLoader; + _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); + _resourceLoader.FileLoaded += OnFileLoaded; + } + + public void Dispose() + { + _resourceLoader.FileLoaded -= OnFileLoaded; + } + + private void OnFileLoaded(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, + ReadOnlySpan additionalData) + { + if (_processors.TryGetValue(resource->FileType, out var processor)) + processor.PostProcess(resource, path, additionalData); + } +} + public unsafe class ResourceLoader : IDisposable { private readonly ResourceService _resources; diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index da04bf90..9459df06 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -1,6 +1,5 @@ using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; -using Penumbra.Collections.Manager; using Penumbra.GameData; using Penumbra.Interop.Structs; @@ -53,17 +52,15 @@ public unsafe class CharacterUtility : IDisposable public (nint Address, int Size) DefaultResource(InternalIndex idx) => _lists[idx.Value].DefaultResource; - private readonly IFramework _framework; - public readonly ActiveCollectionData Active; + private readonly IFramework _framework; - public CharacterUtility(IFramework framework, IGameInteropProvider interop, ActiveCollectionData active) + public CharacterUtility(IFramework framework, IGameInteropProvider interop) { interop.InitializeFromAttributes(this); _lists = Enumerable.Range(0, RelevantIndices.Length) .Select(idx => new MetaList(this, new InternalIndex(idx))) .ToArray(); _framework = framework; - Active = active; LoadingFinished += () => Penumbra.Log.Debug("Loading of CharacterUtility finished."); LoadDefaultResources(null!); if (!Ready) @@ -121,34 +118,6 @@ public unsafe class CharacterUtility : IDisposable LoadingFinished.Invoke(); } - public void SetResource(MetaIndex resourceIdx, nint data, int length) - { - var idx = ReverseIndices[(int)resourceIdx]; - var list = _lists[idx.Value]; - list.SetResource(data, length); - } - - public void ResetResource(MetaIndex resourceIdx) - { - var idx = ReverseIndices[(int)resourceIdx]; - var list = _lists[idx.Value]; - list.ResetResource(); - } - - public MetaList.MetaReverter TemporarilySetResource(MetaIndex resourceIdx, nint data, int length) - { - var idx = ReverseIndices[(int)resourceIdx]; - var list = _lists[idx.Value]; - return list.TemporarilySetResource(data, length); - } - - public MetaList.MetaReverter TemporarilyResetResource(MetaIndex resourceIdx) - { - var idx = ReverseIndices[(int)resourceIdx]; - var list = _lists[idx.Value]; - return list.TemporarilyResetResource(); - } - /// Return all relevant resources to the default resource. public void ResetAll() { diff --git a/Penumbra/Meta/Files/CmpFile.cs b/Penumbra/Meta/Files/CmpFile.cs index 8ca7cb80..5028a3de 100644 --- a/Penumbra/Meta/Files/CmpFile.cs +++ b/Penumbra/Meta/Files/CmpFile.cs @@ -34,7 +34,7 @@ public sealed unsafe class CmpFile : MetaBaseFile } public CmpFile(MetaFileManager manager) - : base(manager, MetaIndex.HumanCmp) + : base(manager, manager.MarshalAllocator, MetaIndex.HumanCmp) { AllocateData(DefaultData.Length); Reset(); diff --git a/Penumbra/Meta/Files/EqdpFile.cs b/Penumbra/Meta/Files/EqdpFile.cs index e46e82e9..34b4f25b 100644 --- a/Penumbra/Meta/Files/EqdpFile.cs +++ b/Penumbra/Meta/Files/EqdpFile.cs @@ -87,7 +87,7 @@ public sealed unsafe class ExpandedEqdpFile : MetaBaseFile } public ExpandedEqdpFile(MetaFileManager manager, GenderRace raceCode, bool accessory) - : base(manager, CharacterUtilityData.EqdpIdx(raceCode, accessory)) + : base(manager, manager.MarshalAllocator, CharacterUtilityData.EqdpIdx(raceCode, accessory)) { var def = (byte*)DefaultData.Data; var blockSize = *(ushort*)(def + IdentifierSize); diff --git a/Penumbra/Meta/Files/EqpGmpFile.cs b/Penumbra/Meta/Files/EqpGmpFile.cs index c47c84ef..a7540f4b 100644 --- a/Penumbra/Meta/Files/EqpGmpFile.cs +++ b/Penumbra/Meta/Files/EqpGmpFile.cs @@ -76,7 +76,7 @@ public unsafe class ExpandedEqpGmpBase : MetaBaseFile } public ExpandedEqpGmpBase(MetaFileManager manager, bool gmp) - : base(manager, gmp ? MetaIndex.Gmp : MetaIndex.Eqp) + : base(manager, manager.MarshalAllocator, gmp ? MetaIndex.Gmp : MetaIndex.Eqp) { AllocateData(MaxSize); Reset(); diff --git a/Penumbra/Meta/Files/EstFile.cs b/Penumbra/Meta/Files/EstFile.cs index f3860416..ba38d6d9 100644 --- a/Penumbra/Meta/Files/EstFile.cs +++ b/Penumbra/Meta/Files/EstFile.cs @@ -157,7 +157,7 @@ public sealed unsafe class EstFile : MetaBaseFile } public EstFile(MetaFileManager manager, EstType estType) - : base(manager, (MetaIndex)estType) + : base(manager, manager.MarshalAllocator, (MetaIndex)estType) { var length = DefaultData.Length; AllocateData(length + IncreaseSize); diff --git a/Penumbra/Meta/Files/EvpFile.cs b/Penumbra/Meta/Files/EvpFile.cs index 3d0b4dbe..6ab1591c 100644 --- a/Penumbra/Meta/Files/EvpFile.cs +++ b/Penumbra/Meta/Files/EvpFile.cs @@ -12,7 +12,7 @@ namespace Penumbra.Meta.Files; /// Containing Flags in each byte, 0x01 set for Body, 0x02 set for Helmet. /// Each flag corresponds to a mount row from the Mounts table and determines whether the mount disables the effect. /// -public unsafe class EvpFile : MetaBaseFile +public unsafe class EvpFile(MetaFileManager manager) : MetaBaseFile(manager, manager.MarshalAllocator, (MetaIndex)1) { public const int FlagArraySize = 512; @@ -57,8 +57,4 @@ public unsafe class EvpFile : MetaBaseFile return EvpFlag.None; } - - public EvpFile(MetaFileManager manager) - : base(manager, (MetaIndex)1) // TODO: Name - { } } diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 892f5b44..01ef3f16 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -7,16 +7,10 @@ using Penumbra.String.Functions; namespace Penumbra.Meta.Files; -public class ImcException : Exception +public class ImcException(ImcIdentifier identifier, Utf8GamePath path) : Exception { - public readonly ImcIdentifier Identifier; - public readonly string GamePath; - - public ImcException(ImcIdentifier identifier, Utf8GamePath path) - { - Identifier = identifier; - GamePath = path.ToString(); - } + public readonly ImcIdentifier Identifier = identifier; + public readonly string GamePath = path.ToString(); public override string Message => "Could not obtain default Imc File.\n" @@ -146,7 +140,11 @@ public unsafe class ImcFile : MetaBaseFile } public ImcFile(MetaFileManager manager, ImcIdentifier identifier) - : base(manager, 0) + : this(manager, manager.MarshalAllocator, identifier) + { } + + public ImcFile(MetaFileManager manager, IFileAllocator alloc, ImcIdentifier identifier) + : base(manager, alloc, 0) { var path = identifier.GamePathString(); Path = Utf8GamePath.FromString(path, out var p) ? p : Utf8GamePath.Empty; @@ -194,7 +192,13 @@ public unsafe class ImcFile : MetaBaseFile public void Replace(ResourceHandle* resource) { var (data, length) = resource->GetData(); - var newData = Manager.AllocateDefaultMemory(ActualLength, 8); + if (length == ActualLength) + { + MemoryUtility.MemCpyUnchecked((byte*)data, Data, ActualLength); + return; + } + + var newData = Manager.XivAllocator.Allocate(ActualLength, 8); if (newData == null) { Penumbra.Log.Error($"Could not replace loaded IMC data at 0x{(ulong)resource:X}, allocation failed."); @@ -203,7 +207,7 @@ public unsafe class ImcFile : MetaBaseFile MemoryUtility.MemCpyUnchecked(newData, Data, ActualLength); - Manager.Free(data, length); - resource->SetData((IntPtr)newData, ActualLength); + Manager.XivAllocator.Release((void*)data, length); + resource->SetData((nint)newData, ActualLength); } } diff --git a/Penumbra/Meta/Files/MetaBaseFile.cs b/Penumbra/Meta/Files/MetaBaseFile.cs index ab08efc2..86a55101 100644 --- a/Penumbra/Meta/Files/MetaBaseFile.cs +++ b/Penumbra/Meta/Files/MetaBaseFile.cs @@ -1,23 +1,75 @@ using Dalamud.Memory; +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.System.Memory; +using OtterGui.Services; +using Penumbra.GameData; using Penumbra.Interop.Structs; using Penumbra.String.Functions; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; namespace Penumbra.Meta.Files; -public unsafe class MetaBaseFile : IDisposable +public unsafe interface IFileAllocator { - protected readonly MetaFileManager Manager; + public T* Allocate(int length, int alignment = 1) where T : unmanaged; + public void Release(ref T* pointer, int length) where T : unmanaged; + + public void Release(void* pointer, int length) + { + var tmp = (byte*)pointer; + Release(ref tmp, length); + } + + public byte* Allocate(int length, int alignment = 1) + => Allocate(length, alignment); +} + +public sealed class MarshalAllocator : IFileAllocator +{ + public unsafe T* Allocate(int length, int alignment = 1) where T : unmanaged + => (T*)Marshal.AllocHGlobal(length * sizeof(T)); + + public unsafe void Release(ref T* pointer, int length) where T : unmanaged + { + Marshal.FreeHGlobal((nint)pointer); + pointer = null; + } +} + +public sealed unsafe class XivFileAllocator : IFileAllocator, IService +{ + /// + /// Allocate in the games space for file storage. + /// We only need this if using any meta file. + /// + [Signature(Sigs.GetFileSpace)] + private readonly nint _getFileSpaceAddress = nint.Zero; + + public XivFileAllocator(IGameInteropProvider provider) + => provider.InitializeFromAttributes(this); + + public IMemorySpace* GetFileSpace() + => ((delegate* unmanaged)_getFileSpaceAddress)(); + + public T* Allocate(int length, int alignment = 1) where T : unmanaged + => (T*)GetFileSpace()->Malloc((ulong)(length * sizeof(T)), (ulong)alignment); + + public void Release(ref T* pointer, int length) where T : unmanaged + { + IMemorySpace.Free(pointer, (ulong)(length * sizeof(T))); + pointer = null; + } +} + +public unsafe class MetaBaseFile(MetaFileManager manager, IFileAllocator alloc, MetaIndex idx) : IDisposable +{ + protected readonly MetaFileManager Manager = manager; + protected readonly IFileAllocator Allocator = alloc; public byte* Data { get; private set; } public int Length { get; private set; } - public CharacterUtility.InternalIndex Index { get; } - - public MetaBaseFile(MetaFileManager manager, MetaIndex idx) - { - Manager = manager; - Index = CharacterUtility.ReverseIndices[(int)idx]; - } + public CharacterUtility.InternalIndex Index { get; } = CharacterUtility.ReverseIndices[(int)idx]; protected (IntPtr Data, int Length) DefaultData => Manager.CharacterUtility.DefaultResource(Index); @@ -30,7 +82,7 @@ public unsafe class MetaBaseFile : IDisposable protected void AllocateData(int length) { Length = length; - Data = (byte*)Manager.AllocateFileMemory(length); + Data = Allocator.Allocate(length); if (length > 0) GC.AddMemoryPressure(length); } @@ -38,8 +90,7 @@ public unsafe class MetaBaseFile : IDisposable /// Free memory. protected void ReleaseUnmanagedResources() { - var ptr = (IntPtr)Data; - MemoryHelper.GameFree(ref ptr, (ulong)Length); + Allocator.Release(Data, Length); if (Length > 0) GC.RemoveMemoryPressure(Length); @@ -53,7 +104,7 @@ public unsafe class MetaBaseFile : IDisposable if (newLength == Length) return; - var data = (byte*)Manager.AllocateFileMemory((ulong)newLength); + var data = Allocator.Allocate(newLength); if (newLength > Length) { MemoryUtility.MemCpyUnchecked(data, Data, Length); diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 40fceb07..81c0fa3e 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -1,14 +1,10 @@ using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.System.Memory; using OtterGui.Compression; using Penumbra.Collections; using Penumbra.Collections.Manager; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.Import; using Penumbra.Interop.Services; -using Penumbra.Interop.Structs; using Penumbra.Meta.Files; using Penumbra.Mods; using Penumbra.Mods.Groups; @@ -28,6 +24,9 @@ public unsafe class MetaFileManager internal readonly ObjectIdentification Identifier; internal readonly FileCompactor Compactor; internal readonly ImcChecker ImcChecker; + internal readonly IFileAllocator MarshalAllocator = new MarshalAllocator(); + internal readonly IFileAllocator XivAllocator; + public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, ObjectIdentification identifier, @@ -42,6 +41,7 @@ public unsafe class MetaFileManager Identifier = identifier; Compactor = compactor; ImcChecker = new ImcChecker(this); + XivAllocator = new XivFileAllocator(interop); interop.InitializeFromAttributes(this); } @@ -76,57 +76,11 @@ public unsafe class MetaFileManager } } - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public void SetFile(MetaBaseFile? file, MetaIndex metaIndex) - { - if (file == null || !Config.EnableMods) - CharacterUtility.ResetResource(metaIndex); - else - CharacterUtility.SetResource(metaIndex, (nint)file.Data, file.Length); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - public MetaList.MetaReverter TemporarilySetFile(MetaBaseFile? file, MetaIndex metaIndex) - => Config.EnableMods - ? file == null - ? CharacterUtility.TemporarilyResetResource(metaIndex) - : CharacterUtility.TemporarilySetResource(metaIndex, (nint)file.Data, file.Length) - : MetaList.MetaReverter.Disabled; - public void ApplyDefaultFiles(ModCollection? collection) { if (ActiveCollections.Default != collection || !CharacterUtility.Ready || !Config.EnableMods) return; ResidentResources.Reload(); - if (collection._cache == null) - CharacterUtility.ResetAll(); - else - collection._cache.Meta.SetFiles(); } - - /// - /// Allocate in the games space for file storage. - /// We only need this if using any meta file. - /// - [Signature(Sigs.GetFileSpace)] - private readonly nint _getFileSpaceAddress = nint.Zero; - - public IMemorySpace* GetFileSpace() - => ((delegate* unmanaged)_getFileSpaceAddress)(); - - public void* AllocateFileMemory(ulong length, ulong alignment = 0) - => GetFileSpace()->Malloc(length, alignment); - - public void* AllocateFileMemory(int length, int alignment = 0) - => AllocateFileMemory((ulong)length, (ulong)alignment); - - public void* AllocateDefaultMemory(ulong length, ulong alignment = 0) - => GetFileSpace()->Malloc(length, alignment); - - public void* AllocateDefaultMemory(int length, int alignment = 0) - => IMemorySpace.GetDefaultSpace()->Malloc((ulong)length, (ulong)alignment); - - public void Free(nint ptr, int length) - => IMemorySpace.Free((void*)ptr, (ulong)length); } From f9c45a2f3f9bae991a67076622c6ef7d701c94ea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 18 Jun 2024 17:57:12 +0200 Subject: [PATCH 0702/1381] Clean unused functions. --- Penumbra/Collections/Cache/EqdpCache.cs | 10 ++----- Penumbra/Collections/Cache/EqpCache.cs | 12 --------- Penumbra/Collections/Cache/EstCache.cs | 12 --------- Penumbra/Collections/Cache/GmpCache.cs | 12 --------- Penumbra/Collections/Cache/IMetaCache.cs | 33 +++++------------------- Penumbra/Collections/Cache/ImcCache.cs | 7 ----- Penumbra/Collections/Cache/MetaCache.cs | 10 ------- Penumbra/Collections/Cache/RspCache.cs | 13 ---------- 8 files changed, 9 insertions(+), 100 deletions(-) diff --git a/Penumbra/Collections/Cache/EqdpCache.cs b/Penumbra/Collections/Cache/EqdpCache.cs index 6047736b..5e0626cf 100644 --- a/Penumbra/Collections/Cache/EqdpCache.cs +++ b/Penumbra/Collections/Cache/EqdpCache.cs @@ -10,17 +10,11 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) private readonly Dictionary<(PrimaryId Id, GenderRace GenderRace, bool Accessory), (EqdpEntry Entry, EqdpEntry InverseMask)> _fullEntries = []; - public override void SetFiles() - { } - public EqdpEntry ApplyFullEntry(PrimaryId id, GenderRace genderRace, bool accessory, EqdpEntry originalEntry) => _fullEntries.TryGetValue((id, genderRace, accessory), out var pair) ? (originalEntry & pair.InverseMask) | pair.Entry : originalEntry; - protected override void IncorporateChangesInternal() - { } - public void Reset() { Clear(); @@ -46,8 +40,8 @@ public sealed class EqdpCache(MetaFileManager manager, ModCollection collection) if (!_fullEntries.Remove(tuple, out var pair)) return; - var mask = Eqdp.Mask(identifier.Slot); - var newMask = pair.InverseMask | mask; + var mask = Eqdp.Mask(identifier.Slot); + var newMask = pair.InverseMask | mask; if (newMask is not EqdpEntry.FullMask) _fullEntries[tuple] = (pair.Entry & ~mask, newMask); } diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 7ba0c489..60e38aef 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -8,12 +8,6 @@ namespace Penumbra.Collections.Cache; public sealed class EqpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - public override void SetFiles() - { } - - protected override void IncorporateChangesInternal() - { } - public unsafe EqpEntry GetValues(CharacterArmor* armor) => GetSingleValue(armor[0].Set, EquipSlot.Head) | GetSingleValue(armor[1].Set, EquipSlot.Body) @@ -28,12 +22,6 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) public void Reset() => Clear(); - protected override void ApplyModInternal(EqpIdentifier identifier, EqpEntry entry) - { } - - protected override void RevertModInternal(EqpIdentifier identifier) - { } - protected override void Dispose(bool _) => Clear(); } diff --git a/Penumbra/Collections/Cache/EstCache.cs b/Penumbra/Collections/Cache/EstCache.cs index ff94324e..aff8beef 100644 --- a/Penumbra/Collections/Cache/EstCache.cs +++ b/Penumbra/Collections/Cache/EstCache.cs @@ -6,12 +6,6 @@ namespace Penumbra.Collections.Cache; public sealed class EstCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - public override void SetFiles() - { } - - protected override void IncorporateChangesInternal() - { } - public EstEntry GetEstEntry(EstIdentifier identifier) => TryGetValue(identifier, out var entry) ? entry.Entry @@ -20,12 +14,6 @@ public sealed class EstCache(MetaFileManager manager, ModCollection collection) public void Reset() => Clear(); - protected override void ApplyModInternal(EstIdentifier identifier, EstEntry entry) - { } - - protected override void RevertModInternal(EstIdentifier identifier) - { } - protected override void Dispose(bool _) => Clear(); } diff --git a/Penumbra/Collections/Cache/GmpCache.cs b/Penumbra/Collections/Cache/GmpCache.cs index 541b424d..9170b871 100644 --- a/Penumbra/Collections/Cache/GmpCache.cs +++ b/Penumbra/Collections/Cache/GmpCache.cs @@ -6,21 +6,9 @@ namespace Penumbra.Collections.Cache; public sealed class GmpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - public override void SetFiles() - { } - - protected override void IncorporateChangesInternal() - { } - public void Reset() => Clear(); - protected override void ApplyModInternal(GmpIdentifier identifier, GmpEntry entry) - { } - - protected override void RevertModInternal(GmpIdentifier identifier) - { } - protected override void Dispose(bool _) => Clear(); } diff --git a/Penumbra/Collections/Cache/IMetaCache.cs b/Penumbra/Collections/Cache/IMetaCache.cs index dd218b48..fecc6f50 100644 --- a/Penumbra/Collections/Cache/IMetaCache.cs +++ b/Penumbra/Collections/Cache/IMetaCache.cs @@ -4,30 +4,19 @@ using Penumbra.Mods.Editor; namespace Penumbra.Collections.Cache; -public abstract class MetaCacheBase +public abstract class MetaCacheBase(MetaFileManager manager, ModCollection collection) : Dictionary where TIdentifier : unmanaged, IMetaIdentifier where TEntry : unmanaged { - protected MetaCacheBase(MetaFileManager manager, ModCollection collection) - { - Manager = manager; - Collection = collection; - if (!Manager.CharacterUtility.Ready) - Manager.CharacterUtility.LoadingFinished += IncorporateChanges; - } - - protected readonly MetaFileManager Manager; - protected readonly ModCollection Collection; + protected readonly MetaFileManager Manager = manager; + protected readonly ModCollection Collection = collection; public void Dispose() { - Manager.CharacterUtility.LoadingFinished -= IncorporateChanges; Dispose(true); } - public abstract void SetFiles(); - public bool ApplyMod(IMod source, TIdentifier identifier, TEntry entry) { lock (this) @@ -59,20 +48,12 @@ public abstract class MetaCacheBase return true; } - private void IncorporateChanges() - { - lock (this) - { - IncorporateChangesInternal(); - } - if (Manager.ActiveCollections.Default == Collection && Manager.Config.EnableMods) - SetFiles(); - } + protected virtual void ApplyModInternal(TIdentifier identifier, TEntry entry) + { } - protected abstract void ApplyModInternal(TIdentifier identifier, TEntry entry); - protected abstract void RevertModInternal(TIdentifier identifier); - protected abstract void IncorporateChangesInternal(); + protected virtual void RevertModInternal(TIdentifier identifier) + { } protected virtual void Dispose(bool _) { } diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index e7eedc04..40c3d2c7 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -10,9 +10,6 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) { private readonly Dictionary)> _imcFiles = []; - public override void SetFiles() - { } - public bool HasFile(ByteString path) => _imcFiles.ContainsKey(path); @@ -28,10 +25,6 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) return true; } - protected override void IncorporateChangesInternal() - { } - - public void Reset() { foreach (var (_, (file, set)) in _imcFiles) diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 253f3c7f..02056fad 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -29,16 +29,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) .Concat(Imc.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(GlobalEqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value))); - public void SetFiles() - { - Eqp.SetFiles(); - Eqdp.SetFiles(); - Est.SetFiles(); - Gmp.SetFiles(); - Rsp.SetFiles(); - Imc.SetFiles(); - } - public void Reset() { Eqp.Reset(); diff --git a/Penumbra/Collections/Cache/RspCache.cs b/Penumbra/Collections/Cache/RspCache.cs index 8a983c6c..064b1f44 100644 --- a/Penumbra/Collections/Cache/RspCache.cs +++ b/Penumbra/Collections/Cache/RspCache.cs @@ -5,22 +5,9 @@ namespace Penumbra.Collections.Cache; public sealed class RspCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - public override void SetFiles() - { } - - protected override void IncorporateChangesInternal() - { } - public void Reset() => Clear(); - protected override void ApplyModInternal(RspIdentifier identifier, RspEntry entry) - { } - - protected override void RevertModInternal(RspIdentifier identifier) - { } - - protected override void Dispose(bool _) => Clear(); } From cf1dcfcb7cb27e6928810b75c63f1f352da4ecd2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 18 Jun 2024 18:33:37 +0200 Subject: [PATCH 0703/1381] Improve Path preprocessing. --- .../Interop/PathResolving/PathResolver.cs | 23 ++-- .../Interop/PathResolving/SubfileHelper.cs | 16 --- .../Processing/AvfxPathPreProcessor.cs | 16 +++ .../Processing/FilePostProcessService.cs | 39 ++++++ .../Processing/GamePathPreProcessService.cs | 37 +++++ .../Processing/ImcFilePostProcessor.cs | 30 ++++ .../Interop/Processing/ImcPathPreProcessor.cs | 18 +++ .../Processing/MaterialFilePostProcessor.cs | 18 +++ .../Processing/MtrlPathPreProcessor.cs | 16 +++ .../Interop/Processing/TmbPathPreProcessor.cs | 16 +++ .../Interop/ResourceLoading/ResourceLoader.cs | 69 ---------- Penumbra/Interop/Services/CharacterUtility.cs | 8 +- Penumbra/Interop/Services/MetaList.cs | 130 +----------------- Penumbra/UI/Tabs/Debug/DebugTab.cs | 19 --- 14 files changed, 209 insertions(+), 246 deletions(-) create mode 100644 Penumbra/Interop/Processing/AvfxPathPreProcessor.cs create mode 100644 Penumbra/Interop/Processing/FilePostProcessService.cs create mode 100644 Penumbra/Interop/Processing/GamePathPreProcessService.cs create mode 100644 Penumbra/Interop/Processing/ImcFilePostProcessor.cs create mode 100644 Penumbra/Interop/Processing/ImcPathPreProcessor.cs create mode 100644 Penumbra/Interop/Processing/MaterialFilePostProcessor.cs create mode 100644 Penumbra/Interop/Processing/MtrlPathPreProcessor.cs create mode 100644 Penumbra/Interop/Processing/TmbPathPreProcessor.cs diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index e069e3ea..f31b3323 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -2,6 +2,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; +using Penumbra.Interop.Processing; using Penumbra.Interop.ResourceLoading; using Penumbra.String.Classes; using Penumbra.Util; @@ -15,14 +16,16 @@ public class PathResolver : IDisposable private readonly CollectionManager _collectionManager; private readonly ResourceLoader _loader; - private readonly SubfileHelper _subfileHelper; - private readonly PathState _pathState; - private readonly MetaState _metaState; - private readonly GameState _gameState; - private readonly CollectionResolver _collectionResolver; + private readonly SubfileHelper _subfileHelper; + private readonly PathState _pathState; + private readonly MetaState _metaState; + private readonly GameState _gameState; + private readonly CollectionResolver _collectionResolver; + private readonly GamePathPreProcessService _preprocessor; - public unsafe PathResolver(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ResourceLoader loader, - SubfileHelper subfileHelper, PathState pathState, MetaState metaState, CollectionResolver collectionResolver, GameState gameState) + public PathResolver(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ResourceLoader loader, + SubfileHelper subfileHelper, PathState pathState, MetaState metaState, CollectionResolver collectionResolver, GameState gameState, + GamePathPreProcessService preprocessor) { _performance = performance; _config = config; @@ -31,6 +34,7 @@ public class PathResolver : IDisposable _pathState = pathState; _metaState = metaState; _gameState = gameState; + _preprocessor = preprocessor; _collectionResolver = collectionResolver; _loader = loader; _loader.ResolvePath = ResolvePath; @@ -102,11 +106,10 @@ public class PathResolver : IDisposable // so that the functions loading tex and shpk can find that path and use its collection. // We also need to handle defaulted materials against a non-default collection. var path = resolved == null ? gamePath.Path : resolved.Value.InternalName; - SubfileHelper.HandleCollection(resolveData, path, nonDefault, type, resolved, gamePath, out var pair); - return pair; + return _preprocessor.PreProcess(resolveData, path, nonDefault, type, resolved, gamePath); } - public unsafe void Dispose() + public void Dispose() { _loader.ResetResolvePath(); } diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index b9631cf2..3cefd98d 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -66,22 +66,6 @@ public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection Materials, TMB, and AVFX need to be set per collection, so they can load their sub files independently of each other. - public static void HandleCollection(ResolveData resolveData, ByteString path, bool nonDefault, ResourceType type, FullPath? resolved, - Utf8GamePath originalPath, out (FullPath?, ResolveData) data) - { - resolved = type switch - { - ResourceType.Mtrl when nonDefault => PathDataHandler.CreateMtrl(path, resolveData.ModCollection, originalPath), - ResourceType.Avfx when nonDefault => PathDataHandler.CreateAvfx(path, resolveData.ModCollection), - ResourceType.Tmb when nonDefault => PathDataHandler.CreateTmb(path, resolveData.ModCollection), - ResourceType.Imc when resolveData.ModCollection.MetaCache?.Imc.HasFile(path) ?? false => PathDataHandler.CreateImc(path, - resolveData.ModCollection), - _ => resolved, - }; - data = (resolved, resolveData); - } - public void Dispose() { _loader.ResourceLoaded -= SubfileContainerRequested; diff --git a/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs b/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs new file mode 100644 index 00000000..56f693e6 --- /dev/null +++ b/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs @@ -0,0 +1,16 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Interop.PathResolving; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Processing; + +public sealed class AvfxPathPreProcessor : IPathPreProcessor +{ + public ResourceType Type + => ResourceType.Avfx; + + public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) + => nonDefault ? PathDataHandler.CreateAvfx(path, resolveData.ModCollection) : resolved; +} diff --git a/Penumbra/Interop/Processing/FilePostProcessService.cs b/Penumbra/Interop/Processing/FilePostProcessService.cs new file mode 100644 index 00000000..0dc62b3d --- /dev/null +++ b/Penumbra/Interop/Processing/FilePostProcessService.cs @@ -0,0 +1,39 @@ +using System.Collections.Frozen; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Structs; +using Penumbra.String; + +namespace Penumbra.Interop.Processing; + +public interface IFilePostProcessor : IService +{ + public ResourceType Type { get; } + public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData); +} + +public unsafe class FilePostProcessService : IRequiredService, IDisposable +{ + private readonly ResourceLoader _resourceLoader; + private readonly FrozenDictionary _processors; + + public FilePostProcessService(ResourceLoader resourceLoader, ServiceManager services) + { + _resourceLoader = resourceLoader; + _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); + _resourceLoader.FileLoaded += OnFileLoaded; + } + + public void Dispose() + { + _resourceLoader.FileLoaded -= OnFileLoaded; + } + + private void OnFileLoaded(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, + ReadOnlySpan additionalData) + { + if (_processors.TryGetValue(resource->FileType, out var processor)) + processor.PostProcess(resource, path, additionalData); + } +} diff --git a/Penumbra/Interop/Processing/GamePathPreProcessService.cs b/Penumbra/Interop/Processing/GamePathPreProcessService.cs new file mode 100644 index 00000000..004b7168 --- /dev/null +++ b/Penumbra/Interop/Processing/GamePathPreProcessService.cs @@ -0,0 +1,37 @@ +using System.Collections.Frozen; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Processing; + +public interface IPathPreProcessor : IService +{ + public ResourceType Type { get; } + + public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved); +} + +public class GamePathPreProcessService : IService +{ + private readonly FrozenDictionary _processors; + + public GamePathPreProcessService(ServiceManager services) + { + _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); + } + + + public (FullPath? Path, ResolveData Data) PreProcess(ResolveData resolveData, ByteString path, bool nonDefault, ResourceType type, + FullPath? resolved, + Utf8GamePath originalPath) + { + if (!_processors.TryGetValue(type, out var processor)) + return (resolved, resolveData); + + resolved = processor.PreProcess(resolveData, path, originalPath, nonDefault, resolved); + return (resolved, resolveData); + } +} diff --git a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs new file mode 100644 index 00000000..4a0ebe22 --- /dev/null +++ b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs @@ -0,0 +1,30 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections.Manager; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Structs; +using Penumbra.String; + +namespace Penumbra.Interop.Processing; + +public sealed class ImcFilePostProcessor(CollectionStorage collections) : IFilePostProcessor +{ + public ResourceType Type + => ResourceType.Imc; + + public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) + { + if (!PathDataHandler.Read(additionalData, out var data) || data.Discriminator != PathDataHandler.Discriminator) + return; + + var collection = collections.ByLocalId(data.Collection); + if (collection.MetaCache is not { } cache) + return; + + if (!cache.Imc.GetFile(originalGamePath, out var file)) + return; + + file.Replace(resource); + Penumbra.Log.Information( + $"[ResourceLoader] Loaded {originalGamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); + } +} diff --git a/Penumbra/Interop/Processing/ImcPathPreProcessor.cs b/Penumbra/Interop/Processing/ImcPathPreProcessor.cs new file mode 100644 index 00000000..907d7587 --- /dev/null +++ b/Penumbra/Interop/Processing/ImcPathPreProcessor.cs @@ -0,0 +1,18 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Interop.PathResolving; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Processing; + +public sealed class ImcPathPreProcessor : IPathPreProcessor +{ + public ResourceType Type + => ResourceType.Imc; + + public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath originalGamePath, bool _, FullPath? resolved) + => resolveData.ModCollection.MetaCache?.Imc.HasFile(originalGamePath.Path) ?? false + ? PathDataHandler.CreateImc(path, resolveData.ModCollection) + : resolved; +} diff --git a/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs b/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs new file mode 100644 index 00000000..02b5d46c --- /dev/null +++ b/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs @@ -0,0 +1,18 @@ +using Penumbra.Api.Enums; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Structs; +using Penumbra.String; + +namespace Penumbra.Interop.Processing; + +public sealed class MaterialFilePostProcessor //: IFilePostProcessor +{ + public ResourceType Type + => ResourceType.Mtrl; + + public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) + { + if (!PathDataHandler.ReadMtrl(additionalData, out var data)) + return; + } +} diff --git a/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs b/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs new file mode 100644 index 00000000..8fb2400b --- /dev/null +++ b/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs @@ -0,0 +1,16 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Interop.PathResolving; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Processing; + +public sealed class MtrlPathPreProcessor : IPathPreProcessor +{ + public ResourceType Type + => ResourceType.Mtrl; + + public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved) + => nonDefault ? PathDataHandler.CreateMtrl(path, resolveData.ModCollection, originalGamePath) : resolved; +} diff --git a/Penumbra/Interop/Processing/TmbPathPreProcessor.cs b/Penumbra/Interop/Processing/TmbPathPreProcessor.cs new file mode 100644 index 00000000..dd887819 --- /dev/null +++ b/Penumbra/Interop/Processing/TmbPathPreProcessor.cs @@ -0,0 +1,16 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Interop.PathResolving; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Processing; + +public sealed class TmbPathPreProcessor : IPathPreProcessor +{ + public ResourceType Type + => ResourceType.Tmb; + + public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) + => nonDefault ? PathDataHandler.CreateTmb(path, resolveData.ModCollection) : resolved; +} diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index fae38907..7b49beab 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,9 +1,6 @@ -using System.Collections.Frozen; using FFXIVClientStructs.FFXIV.Client.System.Resource; -using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; using Penumbra.Interop.SafeHandles; using Penumbra.Interop.Structs; @@ -13,72 +10,6 @@ using FileMode = Penumbra.Interop.Structs.FileMode; namespace Penumbra.Interop.ResourceLoading; -public interface IFilePostProcessor : IService -{ - public ResourceType Type { get; } - public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData); -} - -public sealed class MaterialFilePostProcessor : IFilePostProcessor -{ - public ResourceType Type - => ResourceType.Mtrl; - - public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) - { - if (!PathDataHandler.ReadMtrl(additionalData, out var data)) - return; - } -} - -public sealed class ImcFilePostProcessor(CollectionStorage collections) : IFilePostProcessor -{ - public ResourceType Type - => ResourceType.Imc; - - public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) - { - if (!PathDataHandler.Read(additionalData, out var data) || data.Discriminator != PathDataHandler.Discriminator) - return; - - var collection = collections.ByLocalId(data.Collection); - if (collection.MetaCache is not { } cache) - return; - - if (!cache.Imc.GetFile(originalGamePath, out var file)) - return; - - file.Replace(resource); - Penumbra.Log.Information( - $"[ResourceLoader] Loaded {originalGamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); - } -} - -public unsafe class FilePostProcessService : IRequiredService, IDisposable -{ - private readonly ResourceLoader _resourceLoader; - private readonly FrozenDictionary _processors; - - public FilePostProcessService(ResourceLoader resourceLoader, ServiceManager services) - { - _resourceLoader = resourceLoader; - _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); - _resourceLoader.FileLoaded += OnFileLoaded; - } - - public void Dispose() - { - _resourceLoader.FileLoaded -= OnFileLoaded; - } - - private void OnFileLoaded(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, - ReadOnlySpan additionalData) - { - if (_processors.TryGetValue(resource->FileType, out var processor)) - processor.PostProcess(resource, path, additionalData); - } -} - public unsafe class ResourceLoader : IDisposable { private readonly ResourceService _resources; diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 9459df06..0877d221 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -46,9 +46,6 @@ public unsafe class CharacterUtility : IDisposable private readonly MetaList[] _lists; - public IReadOnlyList Lists - => _lists; - public (nint Address, int Size) DefaultResource(InternalIndex idx) => _lists[idx.Value].DefaultResource; @@ -58,7 +55,7 @@ public unsafe class CharacterUtility : IDisposable { interop.InitializeFromAttributes(this); _lists = Enumerable.Range(0, RelevantIndices.Length) - .Select(idx => new MetaList(this, new InternalIndex(idx))) + .Select(idx => new MetaList(new InternalIndex(idx))) .ToArray(); _framework = framework; LoadingFinished += () => Penumbra.Log.Debug("Loading of CharacterUtility finished."); @@ -124,9 +121,6 @@ public unsafe class CharacterUtility : IDisposable if (!Ready) return; - foreach (var list in _lists) - list.Dispose(); - Address->HumanPbdResource = (ResourceHandle*)DefaultHumanPbdResource; Address->TransparentTexResource = (TextureResourceHandle*)DefaultTransparentResource; Address->DecalTexResource = (TextureResourceHandle*)DefaultDecalResource; diff --git a/Penumbra/Interop/Services/MetaList.cs b/Penumbra/Interop/Services/MetaList.cs index 24d3f088..839c289e 100644 --- a/Penumbra/Interop/Services/MetaList.cs +++ b/Penumbra/Interop/Services/MetaList.cs @@ -2,26 +2,14 @@ using Penumbra.Interop.Structs; namespace Penumbra.Interop.Services; -public unsafe class MetaList : IDisposable +public class MetaList(CharacterUtility.InternalIndex index) { - private readonly CharacterUtility _utility; - private readonly LinkedList _entries = new(); - public readonly CharacterUtility.InternalIndex Index; - public readonly MetaIndex GlobalMetaIndex; - - public IReadOnlyCollection Entries - => _entries; + public readonly CharacterUtility.InternalIndex Index = index; + public readonly MetaIndex GlobalMetaIndex = CharacterUtility.RelevantIndices[index.Value]; private nint _defaultResourceData = nint.Zero; - private int _defaultResourceSize = 0; - public bool Ready { get; private set; } = false; - - public MetaList(CharacterUtility utility, CharacterUtility.InternalIndex index) - { - _utility = utility; - Index = index; - GlobalMetaIndex = CharacterUtility.RelevantIndices[index.Value]; - } + private int _defaultResourceSize; + public bool Ready { get; private set; } public void SetDefaultResource(nint data, int size) { @@ -31,116 +19,8 @@ public unsafe class MetaList : IDisposable _defaultResourceData = data; _defaultResourceSize = size; Ready = _defaultResourceData != nint.Zero && size != 0; - if (_entries.Count <= 0) - return; - - var first = _entries.First!.Value; - SetResource(first.Data, first.Length); } public (nint Address, int Size) DefaultResource => (_defaultResourceData, _defaultResourceSize); - - public MetaReverter TemporarilySetResource(nint data, int length) - { - Penumbra.Log.Excessive($"Temporarily set resource {GlobalMetaIndex} to 0x{(ulong)data:X} ({length} bytes)."); - var reverter = new MetaReverter(this, data, length); - _entries.AddFirst(reverter); - SetResourceInternal(data, length); - return reverter; - } - - public MetaReverter TemporarilyResetResource() - { - Penumbra.Log.Excessive( - $"Temporarily reset resource {GlobalMetaIndex} to default at 0x{_defaultResourceData:X} ({_defaultResourceSize} bytes)."); - var reverter = new MetaReverter(this); - _entries.AddFirst(reverter); - ResetResourceInternal(); - return reverter; - } - - public void SetResource(nint data, int length) - { - Penumbra.Log.Excessive($"Set resource {GlobalMetaIndex} to 0x{(ulong)data:X} ({length} bytes)."); - SetResourceInternal(data, length); - } - - public void ResetResource() - { - Penumbra.Log.Excessive($"Reset resource {GlobalMetaIndex} to default at 0x{_defaultResourceData:X} ({_defaultResourceSize} bytes)."); - ResetResourceInternal(); - } - - /// Set the currently stored data of this resource to new values. - private void SetResourceInternal(nint data, int length) - { - if (!Ready) - return; - - var resource = _utility.Address->Resource(GlobalMetaIndex); - resource->SetData(data, length); - } - - /// Reset the currently stored data of this resource to its default values. - private void ResetResourceInternal() - => SetResourceInternal(_defaultResourceData, _defaultResourceSize); - - private void SetResourceToDefaultCollection() - {} - - public void Dispose() - { - if (_entries.Count > 0) - { - foreach (var entry in _entries) - entry.Disposed = true; - - _entries.Clear(); - } - - ResetResourceInternal(); - } - - public sealed class MetaReverter(MetaList metaList, nint data, int length) : IDisposable - { - public static readonly MetaReverter Disabled = new(null!) { Disposed = true }; - - public readonly MetaList MetaList = metaList; - public readonly nint Data = data; - public readonly int Length = length; - public readonly bool Resetter; - public bool Disposed; - - public MetaReverter(MetaList metaList) - : this(metaList, nint.Zero, 0) - => Resetter = true; - - public void Dispose() - { - if (Disposed) - return; - - var list = MetaList._entries; - var wasCurrent = ReferenceEquals(this, list.First?.Value); - list.Remove(this); - if (!wasCurrent) - return; - - if (list.Count == 0) - { - MetaList.SetResourceToDefaultCollection(); - } - else - { - var next = list.First!.Value; - if (next.Resetter) - MetaList.ResetResourceInternal(); - else - MetaList.SetResourceInternal(next.Data, next.Length); - } - - Disposed = true; - } - } } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 396029d5..1519ebf0 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -179,8 +179,6 @@ public class DebugTab : Window, ITab ImGui.NewLine(); DrawData(); ImGui.NewLine(); - DrawDebugTabMetaLists(); - ImGui.NewLine(); DrawResourceProblems(); ImGui.NewLine(); DrawPlayerModelInfo(); @@ -788,23 +786,6 @@ public class DebugTab : Window, ITab } } - private void DrawDebugTabMetaLists() - { - if (!ImGui.CollapsingHeader("Metadata Changes")) - return; - - using var table = Table("##DebugMetaTable", 3, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - foreach (var list in _characterUtility.Lists) - { - ImGuiUtil.DrawTableColumn(list.GlobalMetaIndex.ToString()); - ImGuiUtil.DrawTableColumn(list.Entries.Count.ToString()); - ImGuiUtil.DrawTableColumn(string.Join(", ", list.Entries.Select(e => $"0x{e.Data:X}"))); - } - } - /// Draw information about the resident resource files. private unsafe void DrawDebugResidentResources() { From e05dbe988570d949f6af81f65b3073c875fb9fb9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 18 Jun 2024 21:59:04 +0200 Subject: [PATCH 0704/1381] Make everything services. --- OtterGui | 2 +- Penumbra/Api/TempModManager.cs | 3 +- .../Cache/CollectionCacheManager.cs | 3 +- .../Collections/Manager/ActiveCollections.cs | 5 +- .../Collections/Manager/CollectionEditor.cs | 3 +- .../Collections/Manager/CollectionManager.cs | 3 +- .../Collections/Manager/CollectionStorage.cs | 5 +- .../Collections/Manager/InheritanceManager.cs | 14 +- .../Manager/TempCollectionManager.cs | 3 +- Penumbra/CommandHandler.cs | 4 +- Penumbra/Configuration.cs | 3 +- Penumbra/EphemeralConfig.cs | 3 +- Penumbra/Import/Models/ModelManager.cs | 4 +- Penumbra/Import/Textures/TextureManager.cs | 26 ++- .../Interop/PathResolving/CutsceneService.cs | 3 +- .../IdentifiedCollectionCache.cs | 4 +- Penumbra/Interop/PathResolving/MetaState.cs | 3 +- .../Interop/PathResolving/PathResolver.cs | 3 +- Penumbra/Interop/PathResolving/PathState.cs | 3 +- .../Interop/PathResolving/SubfileHelper.cs | 4 +- .../ResourceLoading/FileReadService.cs | 3 +- .../Interop/ResourceLoading/ResourceLoader.cs | 5 +- .../ResourceLoading/ResourceManagerService.cs | 3 +- .../ResourceLoading/ResourceService.cs | 3 +- .../Interop/ResourceLoading/TexMdlService.cs | 3 +- .../ResourceTree/ResourceTreeFactory.cs | 3 +- Penumbra/Interop/Services/CharacterUtility.cs | 3 +- Penumbra/Interop/Services/FontReloader.cs | 3 +- Penumbra/Interop/Services/ModelRenderer.cs | 9 +- Penumbra/Interop/Services/RedrawService.cs | 11 +- .../Services/ResidentResourceManager.cs | 5 +- Penumbra/Meta/MetaFileManager.cs | 3 +- Penumbra/Mods/Editor/DuplicateManager.cs | 3 +- Penumbra/Mods/Editor/MdlMaterialEditor.cs | 3 +- Penumbra/Mods/Editor/ModEditor.cs | 4 +- Penumbra/Mods/Editor/ModFileCollection.cs | 3 +- Penumbra/Mods/Editor/ModFileEditor.cs | 3 +- Penumbra/Mods/Editor/ModMerger.cs | 3 +- Penumbra/Mods/Editor/ModNormalizer.cs | 4 +- Penumbra/Mods/Editor/ModSwapEditor.cs | 4 +- Penumbra/Mods/Manager/ModCacheManager.cs | 3 +- Penumbra/Mods/Manager/ModDataEditor.cs | 5 +- Penumbra/Mods/Manager/ModExportManager.cs | 3 +- Penumbra/Mods/Manager/ModFileSystem.cs | 5 +- Penumbra/Mods/Manager/ModImportManager.cs | 6 +- Penumbra/Mods/Manager/ModManager.cs | 3 +- Penumbra/Mods/ModCreator.cs | 3 +- Penumbra/Services/StaticServiceManager.cs | 154 +----------------- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 3 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 3 +- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 5 +- Penumbra/UI/ChangedItemDrawer.cs | 5 +- Penumbra/UI/Changelog.cs | 3 +- Penumbra/UI/Classes/CollectionSelectHeader.cs | 3 +- Penumbra/UI/ConfigWindow.cs | 3 +- Penumbra/UI/FileDialogService.cs | 3 +- Penumbra/UI/ImportPopup.cs | 3 +- Penumbra/UI/LaunchButton.cs | 3 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 9 +- Penumbra/UI/ModsTab/ModPanel.cs | 3 +- .../UI/ModsTab/ModPanelChangedItemsTab.cs | 28 +--- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 18 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 3 +- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 3 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 4 +- Penumbra/UI/ModsTab/ModPanelTabBar.cs | 11 +- Penumbra/UI/ModsTab/MultiModPanel.cs | 7 +- Penumbra/UI/PredefinedTagManager.cs | 4 +- .../UI/ResourceWatcher/ResourceWatcher.cs | 3 +- Penumbra/UI/Tabs/ChangedItemsTab.cs | 3 +- Penumbra/UI/Tabs/CollectionsTab.cs | 3 +- Penumbra/UI/Tabs/ConfigTabBar.cs | 3 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 6 +- Penumbra/UI/Tabs/EffectiveTab.cs | 3 +- Penumbra/UI/Tabs/MessagesTab.cs | 3 +- Penumbra/UI/Tabs/ModsTab.cs | 3 +- Penumbra/UI/Tabs/OnScreenTab.cs | 10 +- Penumbra/UI/Tabs/ResourceTab.cs | 3 +- Penumbra/UI/Tabs/SettingsTab.cs | 3 +- Penumbra/UI/TutorialService.cs | 3 +- Penumbra/UI/WindowSystem.cs | 3 +- 81 files changed, 220 insertions(+), 317 deletions(-) diff --git a/OtterGui b/OtterGui index e95c0f04..caa9e9b9 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit e95c0f04edc7e85aea67498fd8bf495a7fe6d3c8 +Subproject commit caa9e9b9a5dc3928eba10b315cf6a0f6f1d84b65 diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index cbb07436..0b52e64a 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Meta.Manipulations; @@ -18,7 +19,7 @@ public enum RedirectResult FilteredGamePath = 3, } -public class TempModManager : IDisposable +public class TempModManager : IDisposable, IService { private readonly CommunicatorService _communicator; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 02c9c8a9..44c12856 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; @@ -17,7 +18,7 @@ using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; -public class CollectionCacheManager : IDisposable +public class CollectionCacheManager : IDisposable, IService { private readonly FrameworkManager _framework; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 4e8ebe36..6d48f74b 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -3,6 +3,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; @@ -11,7 +12,7 @@ using Penumbra.UI; namespace Penumbra.Collections.Manager; -public class ActiveCollectionData +public class ActiveCollectionData : IService { public ModCollection Current { get; internal set; } = ModCollection.Empty; public ModCollection Default { get; internal set; } = ModCollection.Empty; @@ -20,7 +21,7 @@ public class ActiveCollectionData public readonly ModCollection?[] SpecialCollections = new ModCollection?[Enum.GetValues().Length - 3]; } -public class ActiveCollections : ISavable, IDisposable +public class ActiveCollections : ISavable, IDisposable, IService { public const int Version = 2; diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 0243de1e..caff2c86 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -1,4 +1,5 @@ using OtterGui; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -7,7 +8,7 @@ using Penumbra.Services; namespace Penumbra.Collections.Manager; -public class CollectionEditor(SaveService saveService, CommunicatorService communicator, ModStorage modStorage) +public class CollectionEditor(SaveService saveService, CommunicatorService communicator, ModStorage modStorage) : IService { /// Enable or disable the mod inheritance of mod idx. public bool SetModInheritance(ModCollection collection, Mod mod, bool inherit) diff --git a/Penumbra/Collections/Manager/CollectionManager.cs b/Penumbra/Collections/Manager/CollectionManager.cs index e95617b1..85f5b957 100644 --- a/Penumbra/Collections/Manager/CollectionManager.cs +++ b/Penumbra/Collections/Manager/CollectionManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Collections.Cache; namespace Penumbra.Collections.Manager; @@ -8,7 +9,7 @@ public class CollectionManager( InheritanceManager inheritances, CollectionCacheManager caches, TempCollectionManager temp, - CollectionEditor editor) + CollectionEditor editor) : IService { public readonly CollectionStorage Storage = storage; public readonly ActiveCollections Active = active; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 67de3a03..cd680d36 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,7 +1,7 @@ -using System; using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods; using Penumbra.Mods.Editor; @@ -11,7 +11,6 @@ using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; -using Penumbra.UI.CollectionTab; namespace Penumbra.Collections.Manager; @@ -24,7 +23,7 @@ public readonly record struct LocalCollectionId(int Id) : IAdditionOperators new(left.Id + right); } -public class CollectionStorage : IReadOnlyList, IDisposable +public class CollectionStorage : IReadOnlyList, IDisposable, IService { private readonly CommunicatorService _communicator; private readonly SaveService _saveService; diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index 6003b5f9..f3482cdf 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -2,11 +2,10 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; +using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.UI.CollectionTab; -using Penumbra.Util; namespace Penumbra.Collections.Manager; @@ -15,7 +14,7 @@ namespace Penumbra.Collections.Manager; /// This is transitive, so a collection A inheriting from B also inherits from everything B inherits. /// Circular dependencies are resolved by distinctness. /// -public class InheritanceManager : IDisposable +public class InheritanceManager : IDisposable, IService { public enum ValidInheritance { @@ -144,7 +143,8 @@ public class InheritanceManager : IDisposable continue; changes = true; - Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", + NotificationType.Warning); } else if (_storage.ByName(subCollectionName, out subCollection)) { @@ -153,12 +153,14 @@ public class InheritanceManager : IDisposable if (AddInheritance(collection, subCollection, false)) continue; - Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", NotificationType.Warning); + Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", + NotificationType.Warning); } else { Penumbra.Messager.NotificationMessage( - $"Inherited collection {subCollectionName} for {collection.AnonymizedName} does not exist, it was removed.", NotificationType.Warning); + $"Inherited collection {subCollectionName} for {collection.AnonymizedName} does not exist, it was removed.", + NotificationType.Warning); changes = true; } } diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index ce438a6b..5c893232 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -1,4 +1,5 @@ using OtterGui; +using OtterGui.Services; using Penumbra.Api; using Penumbra.Communication; using Penumbra.GameData.Actors; @@ -8,7 +9,7 @@ using Penumbra.String; namespace Penumbra.Collections.Manager; -public class TempCollectionManager : IDisposable +public class TempCollectionManager : IDisposable, IService { public int GlobalChangeCounter { get; private set; } public readonly IndividualCollections Collections; diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 4e1d6453..484dd954 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -3,6 +3,7 @@ using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -10,12 +11,11 @@ using Penumbra.GameData.Actors; using Penumbra.Interop.Services; using Penumbra.Mods; using Penumbra.Mods.Manager; -using Penumbra.Services; using Penumbra.UI; namespace Penumbra; -public class CommandHandler : IDisposable +public class CommandHandler : IDisposable, IApiService { private const string CommandName = "/penumbra"; diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 02286cc7..f6100b62 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json; using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Import.Structs; using Penumbra.Interop.Services; @@ -18,7 +19,7 @@ using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra; [Serializable] -public class Configuration : IPluginConfiguration, ISavable +public class Configuration : IPluginConfiguration, ISavable, IService { [JsonIgnore] private readonly SaveService _saveService; diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 0a542d04..52e276c7 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -1,6 +1,7 @@ using Dalamud.Interface.Internal.Notifications; using Newtonsoft.Json; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Enums; @@ -14,7 +15,7 @@ using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra; -public class EphemeralConfig : ISavable, IDisposable +public class EphemeralConfig : ISavable, IDisposable, IService { [JsonIgnore] private readonly SaveService _saveService; diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 9fa77784..01396cfb 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using Lumina.Data.Parsing; using OtterGui; +using OtterGui.Services; using OtterGui.Tasks; using Penumbra.Collections.Manager; using Penumbra.GameData; @@ -21,7 +22,8 @@ namespace Penumbra.Import.Models; using Schema2 = SharpGLTF.Schema2; using LuminaMaterial = Lumina.Models.Materials.Material; -public sealed class ModelManager(IFramework framework, ActiveCollections collections, GamePathParser parser) : SingleTaskQueue, IDisposable +public sealed class ModelManager(IFramework framework, ActiveCollections collections, GamePathParser parser) + : SingleTaskQueue, IDisposable, IService { private readonly IFramework _framework = framework; diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 976bc179..4aa64209 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Internal; using Dalamud.Plugin.Services; using Lumina.Data.Files; using OtterGui.Log; +using OtterGui.Services; using OtterGui.Tasks; using OtterTex; using SixLabors.ImageSharp; @@ -12,22 +13,14 @@ using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; -public sealed class TextureManager : SingleTaskQueue, IDisposable +public sealed class TextureManager(UiBuilder uiBuilder, IDataManager gameData, Logger logger) + : SingleTaskQueue, IDisposable, IService { - private readonly Logger _logger; - private readonly UiBuilder _uiBuilder; - private readonly IDataManager _gameData; + private readonly Logger _logger = logger; - private readonly ConcurrentDictionary _tasks = new(); + private readonly ConcurrentDictionary _tasks = new(); private bool _disposed; - public TextureManager(UiBuilder uiBuilder, IDataManager gameData, Logger logger) - { - _uiBuilder = uiBuilder; - _gameData = gameData; - _logger = logger; - } - public IReadOnlyDictionary Tasks => _tasks; @@ -64,7 +57,8 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable { var token = new CancellationTokenSource(); var task = Enqueue(a, token.Token); - task.ContinueWith(_ => _tasks.TryRemove(a, out var unused), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); + task.ContinueWith(_ => _tasks.TryRemove(a, out var unused), CancellationToken.None, TaskContinuationOptions.None, + TaskScheduler.Default); return (task, token); }).Item1; } @@ -217,7 +211,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable /// Load a texture wrap for a given image. public IDalamudTextureWrap LoadTextureWrap(byte[] rgba, int width, int height) - => _uiBuilder.LoadImageRaw(rgba, width, height, 4); + => uiBuilder.LoadImageRaw(rgba, width, height, 4); /// Load any supported file from game data or drive depending on extension and if the path is rooted. public (BaseImage, TextureType) Load(string path) @@ -326,7 +320,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable } public bool GameFileExists(string path) - => _gameData.FileExists(path); + => gameData.FileExists(path); /// Add up to 13 mip maps to the input if mip maps is true, otherwise return input. public static ScratchImage AddMipMaps(ScratchImage input, bool mipMaps) @@ -382,7 +376,7 @@ public sealed class TextureManager : SingleTaskQueue, IDisposable if (Path.IsPathRooted(path)) return File.OpenRead(path); - var file = _gameData.GetFile(path); + var file = gameData.GetFile(path); return file != null ? new MemoryStream(file.Data) : throw new Exception($"Unable to obtain \"{path}\" from game files."); } diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 93fee11e..feb27341 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -1,6 +1,5 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; -using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; @@ -9,7 +8,7 @@ using Penumbra.String; namespace Penumbra.Interop.PathResolving; -public sealed class CutsceneService : IService, IDisposable +public sealed class CutsceneService : IRequiredService, IDisposable { public const int CutsceneStartIdx = (int)ScreenActor.CutsceneStart; public const int CutsceneEndIdx = (int)ScreenActor.CutsceneEnd; diff --git a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs index 32090f7c..eeff7eee 100644 --- a/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs +++ b/Penumbra/Interop/PathResolving/IdentifiedCollectionCache.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -10,7 +11,8 @@ using Penumbra.Services; namespace Penumbra.Interop.PathResolving; -public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint Address, ActorIdentifier Identifier, ModCollection Collection)> +public unsafe class IdentifiedCollectionCache : IDisposable, IEnumerable<(nint Address, ActorIdentifier Identifier, ModCollection Collection)>, + IService { private readonly CommunicatorService _communicator; private readonly CharacterDestructor _characterDestructor; diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 7f820b4e..f7dcfc07 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Api.Enums; using Penumbra.GameData.Structs; @@ -34,7 +35,7 @@ namespace Penumbra.Interop.PathResolving; // ChangeCustomize and RspSetupCharacter, which is hooked here, as well as Character.CalculateHeight. // GMP Entries seem to be only used by "48 8B ?? 53 55 57 48 83 ?? ?? 48 8B", which is SetupVisor. -public sealed unsafe class MetaState : IDisposable +public sealed unsafe class MetaState : IDisposable, IService { private readonly Configuration _config; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index f31b3323..cc3e0e9b 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,4 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -9,7 +10,7 @@ using Penumbra.Util; namespace Penumbra.Interop.PathResolving; -public class PathResolver : IDisposable +public class PathResolver : IDisposable, IService { private readonly PerformanceTracker _performance; private readonly Configuration _config; diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index f4218e9c..bf9d1e25 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Interop.Services; using Penumbra.String; @@ -5,7 +6,7 @@ using Penumbra.String; namespace Penumbra.Interop.PathResolving; public sealed class PathState(CollectionResolver collectionResolver, MetaState metaState, CharacterUtility characterUtility) - : IDisposable + : IDisposable, IService { public readonly CollectionResolver CollectionResolver = collectionResolver; public readonly MetaState MetaState = metaState; diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 3cefd98d..44a152f0 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,9 +1,9 @@ +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; -using Penumbra.String; using Penumbra.String.Classes; namespace Penumbra.Interop.PathResolving; @@ -13,7 +13,7 @@ namespace Penumbra.Interop.PathResolving; /// Those are loaded synchronously. /// Thus, we need to ensure the correct files are loaded when a material is loaded. /// -public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection> +public sealed unsafe class SubfileHelper : IDisposable, IReadOnlyCollection>, IService { private readonly GameState _gameState; private readonly ResourceLoader _loader; diff --git a/Penumbra/Interop/ResourceLoading/FileReadService.cs b/Penumbra/Interop/ResourceLoading/FileReadService.cs index 64442771..f1d7fe24 100644 --- a/Penumbra/Interop/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/ResourceLoading/FileReadService.cs @@ -1,13 +1,14 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; +using OtterGui.Services; using Penumbra.GameData; using Penumbra.Interop.Structs; using Penumbra.Util; namespace Penumbra.Interop.ResourceLoading; -public unsafe class FileReadService : IDisposable +public unsafe class FileReadService : IDisposable, IRequiredService { public FileReadService(PerformanceTracker performance, ResourceManagerService resourceManager, IGameInteropProvider interop) { diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs index 7b49beab..4a423993 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceLoader.cs @@ -1,4 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Interop.PathResolving; @@ -10,7 +11,7 @@ using FileMode = Penumbra.Interop.Structs.FileMode; namespace Penumbra.Interop.ResourceLoading; -public unsafe class ResourceLoader : IDisposable +public unsafe class ResourceLoader : IDisposable, IService { private readonly ResourceService _resources; private readonly FileReadService _fileReadService; @@ -212,7 +213,7 @@ public unsafe class ResourceLoader : IDisposable /// /// Catch weird errors with invalid decrements of the reference count. /// - private void DecRefProtection(ResourceHandle* handle, ref byte? returnValue) + private static void DecRefProtection(ResourceHandle* handle, ref byte? returnValue) { if (handle->RefCount != 0) return; diff --git a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs index a087a659..c885c317 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs @@ -4,12 +4,13 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; using FFXIVClientStructs.STD; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData; namespace Penumbra.Interop.ResourceLoading; -public unsafe class ResourceManagerService +public unsafe class ResourceManagerService : IRequiredService { public ResourceManagerService(IGameInteropProvider interop) => interop.InitializeFromAttributes(this); diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index e3338e6c..54c86777 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -2,6 +2,7 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.Interop.SafeHandles; @@ -13,7 +14,7 @@ using CSResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle. namespace Penumbra.Interop.ResourceLoading; -public unsafe class ResourceService : IDisposable +public unsafe class ResourceService : IDisposable, IRequiredService { private readonly PerformanceTracker _performance; private readonly ResourceManagerService _resourceManager; diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/ResourceLoading/TexMdlService.cs index b9279f54..e617673e 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/ResourceLoading/TexMdlService.cs @@ -2,13 +2,14 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceLoading; -public unsafe class TexMdlService : IDisposable +public unsafe class TexMdlService : IDisposable, IRequiredService { /// Custom ulong flag to signal our files as opposed to SE files. public static readonly IntPtr CustomFileFlag = new(0xDEADBEEF); diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 5a190e52..e26c1436 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData.Actors; using Penumbra.GameData.Data; @@ -17,7 +18,7 @@ public class ResourceTreeFactory( ObjectIdentification identifier, Configuration config, ActorManager actors, - PathState pathState) + PathState pathState) : IService { private TreeBuildCache CreateTreeBuildCache() => new(objects, gameData, actors); diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 0877d221..532dc823 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -1,11 +1,12 @@ using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; +using OtterGui.Services; using Penumbra.GameData; using Penumbra.Interop.Structs; namespace Penumbra.Interop.Services; -public unsafe class CharacterUtility : IDisposable +public unsafe class CharacterUtility : IDisposable, IRequiredService { public record struct InternalIndex(int Value); diff --git a/Penumbra/Interop/Services/FontReloader.cs b/Penumbra/Interop/Services/FontReloader.cs index 2f4a3cfd..259fdd10 100644 --- a/Penumbra/Interop/Services/FontReloader.cs +++ b/Penumbra/Interop/Services/FontReloader.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.System.Framework; using FFXIVClientStructs.FFXIV.Component.GUI; +using OtterGui.Services; using Penumbra.GameData; namespace Penumbra.Interop.Services; @@ -9,7 +10,7 @@ namespace Penumbra.Interop.Services; /// Handle font reloading via game functions. /// May cause a interface flicker while reloading. /// -public unsafe class FontReloader +public unsafe class FontReloader : IService { public bool Valid => _reloadFontsFunc != null; diff --git a/Penumbra/Interop/Services/ModelRenderer.cs b/Penumbra/Interop/Services/ModelRenderer.cs index 7df83cf7..b268b395 100644 --- a/Penumbra/Interop/Services/ModelRenderer.cs +++ b/Penumbra/Interop/Services/ModelRenderer.cs @@ -1,10 +1,11 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Services; namespace Penumbra.Interop.Services; -public unsafe class ModelRenderer : IDisposable +public unsafe class ModelRenderer : IDisposable, IRequiredService { public bool Ready { get; private set; } @@ -37,14 +38,14 @@ public unsafe class ModelRenderer : IDisposable if (DefaultCharacterGlassShaderPackage == null) { - DefaultCharacterGlassShaderPackage = *CharacterGlassShaderPackage; - anyMissing |= DefaultCharacterGlassShaderPackage == null; + DefaultCharacterGlassShaderPackage = *CharacterGlassShaderPackage; + anyMissing |= DefaultCharacterGlassShaderPackage == null; } if (anyMissing) return; - Ready = true; + Ready = true; _framework.Update -= LoadDefaultResources; } diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 21ecfd4f..61d7b90c 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -6,6 +6,7 @@ using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Housing; using FFXIVClientStructs.Interop; +using OtterGui.Services; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Communication; @@ -20,7 +21,7 @@ using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; namespace Penumbra.Interop.Services; -public unsafe partial class RedrawService +public unsafe partial class RedrawService : IService { public const int GPosePlayerIdx = 201; public const int GPoseSlots = 42; @@ -171,7 +172,8 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) DisableDraw(actor!); - if (actor is PlayerCharacter && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) + if (actor is PlayerCharacter + && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { *ActorDrawState(mountOrOrnament) |= DrawState.Invisibility; if (gPose) @@ -190,7 +192,8 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) EnableDraw(actor!); - if (actor is PlayerCharacter && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) + if (actor is PlayerCharacter + && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { *ActorDrawState(mountOrOrnament) &= ~DrawState.Invisibility; if (gPose) @@ -380,7 +383,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (!ret && lowerName.Length > 1 && lowerName[0] == '#' && ushort.TryParse(lowerName[1..], out var objectIndex)) { ret = true; - actor = _objects.GetDalamudObject((int) objectIndex); + actor = _objects.GetDalamudObject((int)objectIndex); } return ret; diff --git a/Penumbra/Interop/Services/ResidentResourceManager.cs b/Penumbra/Interop/Services/ResidentResourceManager.cs index 72697185..4f430aa1 100644 --- a/Penumbra/Interop/Services/ResidentResourceManager.cs +++ b/Penumbra/Interop/Services/ResidentResourceManager.cs @@ -1,10 +1,11 @@ -using Dalamud.Plugin.Services; +using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; +using OtterGui.Services; using Penumbra.GameData; namespace Penumbra.Interop.Services; -public unsafe class ResidentResourceManager +public unsafe class ResidentResourceManager : IService { // A static pointer to the resident resource manager address. [Signature(Sigs.ResidentResourceManager, ScanType = ScanType.StaticAddress)] diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 81c0fa3e..3755afa2 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using OtterGui.Compression; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Data; @@ -13,7 +14,7 @@ using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManage namespace Penumbra.Meta; -public unsafe class MetaFileManager +public class MetaFileManager : IService { internal readonly Configuration Config; internal readonly CharacterUtility CharacterUtility; diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index 47aa18dc..bcecf264 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -1,4 +1,5 @@ using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; @@ -7,7 +8,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class DuplicateManager(ModManager modManager, SaveService saveService, Configuration config) +public class DuplicateManager(ModManager modManager, SaveService saveService, Configuration config) : IService { private readonly SHA256 _hasher = SHA256.Create(); private readonly List<(FullPath[] Paths, long Size, byte[] Hash)> _duplicates = []; diff --git a/Penumbra/Mods/Editor/MdlMaterialEditor.cs b/Penumbra/Mods/Editor/MdlMaterialEditor.cs index 738e606e..2a23ffad 100644 --- a/Penumbra/Mods/Editor/MdlMaterialEditor.cs +++ b/Penumbra/Mods/Editor/MdlMaterialEditor.cs @@ -1,11 +1,12 @@ using OtterGui; using OtterGui.Compression; +using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; namespace Penumbra.Mods.Editor; -public partial class MdlMaterialEditor(ModFileCollection files) +public partial class MdlMaterialEditor(ModFileCollection files) : IService { [GeneratedRegex(@"/mt_c(?'RaceCode'\d{4})b0001_(?'Suffix'.*?)\.mtrl", RegexOptions.ExplicitCapture | RegexOptions.NonBacktracking)] private static partial Regex MaterialRegex(); diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index 37524da1..cacb7f88 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -1,5 +1,5 @@ -using OtterGui; using OtterGui.Compression; +using OtterGui.Services; using Penumbra.Mods.Groups; using Penumbra.Mods.SubMods; @@ -14,7 +14,7 @@ public class ModEditor( ModSwapEditor swapEditor, MdlMaterialEditor mdlMaterialEditor, FileCompactor compactor) - : IDisposable + : IDisposable, IService { public readonly ModNormalizer ModNormalizer = modNormalizer; public readonly ModMetaEditor MetaEditor = metaEditor; diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 551d04cf..241f5b3b 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -1,10 +1,11 @@ using OtterGui; +using OtterGui.Services; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class ModFileCollection : IDisposable +public class ModFileCollection : IDisposable, IService { private readonly List _available = []; private readonly List _mtrl = []; diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index e2c0b726..55e0e94e 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; using Penumbra.Services; @@ -5,7 +6,7 @@ using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class ModFileEditor(ModFileCollection files, ModManager modManager, CommunicatorService communicator) +public class ModFileEditor(ModFileCollection files, ModManager modManager, CommunicatorService communicator) : IService { public bool Changes { get; private set; } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 2df76838..9d31664b 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Internal.Notifications; using Dalamud.Utility; using OtterGui; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Communication; using Penumbra.Mods.Manager; @@ -13,7 +14,7 @@ using Penumbra.UI.ModsTab; namespace Penumbra.Mods.Editor; -public class ModMerger : IDisposable +public class ModMerger : IDisposable, IService { private readonly Configuration _config; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 58e4fc08..c6bc4939 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,15 +1,15 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui; using OtterGui.Classes; +using OtterGui.Services; using OtterGui.Tasks; -using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class ModNormalizer(ModManager _modManager, Configuration _config) +public class ModNormalizer(ModManager _modManager, Configuration _config) : IService { private readonly List>> _redirections = []; diff --git a/Penumbra/Mods/Editor/ModSwapEditor.cs b/Penumbra/Mods/Editor/ModSwapEditor.cs index 0250efae..1a8ff2eb 100644 --- a/Penumbra/Mods/Editor/ModSwapEditor.cs +++ b/Penumbra/Mods/Editor/ModSwapEditor.cs @@ -1,10 +1,10 @@ -using Penumbra.Mods; +using OtterGui.Services; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; using Penumbra.Util; -public class ModSwapEditor(ModManager modManager) +public class ModSwapEditor(ModManager modManager) : IService { private readonly Dictionary _swaps = []; diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 8ab8cf33..38d98d7c 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData.Data; using Penumbra.Mods.Groups; @@ -8,7 +9,7 @@ using Penumbra.Util; namespace Penumbra.Mods.Manager; -public class ModCacheManager : IDisposable +public class ModCacheManager : IDisposable, IService { private readonly Configuration _config; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index c7c7c2cc..4ab9deb1 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -1,6 +1,7 @@ using Dalamud.Utility; using Newtonsoft.Json.Linq; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Services; namespace Penumbra.Mods.Manager; @@ -23,7 +24,7 @@ public enum ModDataChangeType : ushort Note = 0x0800, } -public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService) +public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService) : IService { /// Create the file containing the meta information about a mod from scratch. public void CreateMeta(DirectoryInfo directory, string? name, string? author, string? description, string? version, @@ -49,7 +50,6 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic var save = true; if (File.Exists(dataFile)) - { try { var text = File.ReadAllText(dataFile); @@ -65,7 +65,6 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic { Penumbra.Log.Error($"Could not load local mod data:\n{e}"); } - } if (importDate == 0) importDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); diff --git a/Penumbra/Mods/Manager/ModExportManager.cs b/Penumbra/Mods/Manager/ModExportManager.cs index 676018be..38b9c0fd 100644 --- a/Penumbra/Mods/Manager/ModExportManager.cs +++ b/Penumbra/Mods/Manager/ModExportManager.cs @@ -1,10 +1,11 @@ +using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Services; namespace Penumbra.Mods.Manager; -public class ModExportManager : IDisposable +public class ModExportManager : IDisposable, IService { private readonly Configuration _config; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index c8a0a5db..e32fec0c 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -1,12 +1,11 @@ -using Newtonsoft.Json.Linq; -using OtterGui.Classes; using OtterGui.Filesystem; +using OtterGui.Services; using Penumbra.Communication; using Penumbra.Services; namespace Penumbra.Mods.Manager; -public sealed class ModFileSystem : FileSystem, IDisposable, ISavable +public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, IService { private readonly ModManager _modManager; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index c99b7d0e..ff39b021 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -1,11 +1,12 @@ using Dalamud.Interface.Internal.Notifications; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Import; using Penumbra.Mods.Editor; namespace Penumbra.Mods.Manager; -public class ModImportManager(ModManager modManager, Configuration config, ModEditor modEditor) : IDisposable +public class ModImportManager(ModManager modManager, Configuration config, ModEditor modEditor) : IDisposable, IService { private readonly ConcurrentQueue _modsToUnpack = new(); @@ -32,7 +33,8 @@ public class ModImportManager(ModManager modManager, Configuration config, ModEd if (File.Exists(s)) return true; - Penumbra.Messager.NotificationMessage($"Failed to import queued mod at {s}, the file does not exist.", NotificationType.Warning, false); + Penumbra.Messager.NotificationMessage($"Failed to import queued mod at {s}, the file does not exist.", NotificationType.Warning, + false); return false; }).Select(s => new FileInfo(s)).ToArray(); diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 42082383..4b19ea4c 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager.OptionEditor; @@ -27,7 +28,7 @@ public enum ModPathChangeType StartingReload, } -public sealed class ModManager : ModStorage, IDisposable +public sealed class ModManager : ModStorage, IDisposable, IService { private readonly Configuration _config; private readonly CommunicatorService _communicator; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index ed4245c4..0e66367a 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.Import; @@ -23,7 +24,7 @@ public partial class ModCreator( Configuration config, ModDataEditor _dataEditor, MetaFileManager _metaFileManager, - GamePathParser _gamePathParser) + GamePathParser _gamePathParser) : IService { public readonly Configuration Config = config; diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 35e36349..3279da96 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -5,36 +5,15 @@ using Dalamud.Plugin; using Dalamud.Plugin.Services; using Microsoft.Extensions.DependencyInjection; using OtterGui; -using OtterGui.Classes; using OtterGui.Log; using OtterGui.Services; -using Penumbra.Api; using Penumbra.Api.Api; -using Penumbra.Collections.Cache; -using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; -using Penumbra.Import.Models; using Penumbra.GameData.Structs; -using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; -using Penumbra.Interop.ResourceLoading; -using Penumbra.Interop.ResourceTree; -using Penumbra.Interop.Services; using Penumbra.Meta; -using Penumbra.Mods; -using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; -using Penumbra.UI; -using Penumbra.UI.AdvancedWindow; -using Penumbra.UI.Classes; -using Penumbra.UI.ModsTab; -using Penumbra.UI.ResourceWatcher; -using Penumbra.UI.Tabs; -using Penumbra.UI.Tabs.Debug; using IPenumbraApi = Penumbra.Api.Api.IPenumbraApi; -using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; -using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; -using Penumbra.Api.IpcTester; namespace Penumbra.Services; @@ -45,19 +24,18 @@ public static class StaticServiceManager var services = new ServiceManager(log) .AddDalamudServices(pi) .AddExistingService(log) - .AddExistingService(penumbra) - .AddInterop() - .AddConfiguration() - .AddCollections() - .AddMods() - .AddResources() - .AddResolvers() - .AddInterface() - .AddModEditor() - .AddApi(); + .AddExistingService(penumbra); services.AddIServices(typeof(EquipItem).Assembly); services.AddIServices(typeof(Penumbra).Assembly); services.AddIServices(typeof(ImGuiUtil).Assembly); + services.AddSingleton(p => + { + var cutsceneService = p.GetRequiredService(); + return new CutsceneResolver(cutsceneService.GetParentIndex); + }) + .AddSingleton(p => p.GetRequiredService().ImcChecker) + .AddSingleton(s => (ModStorage)s.GetRequiredService()) + .AddSingleton(x => x.GetRequiredService()); services.CreateProvider(); return services; } @@ -83,118 +61,4 @@ public static class StaticServiceManager .AddDalamudService(pi) .AddDalamudService(pi) .AddDalamudService(pi); - - private static ServiceManager AddInterop(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton(p => - { - var cutsceneService = p.GetRequiredService(); - return new CutsceneResolver(cutsceneService.GetParentIndex); - }) - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(p => p.GetRequiredService().ImcChecker); - - private static ServiceManager AddConfiguration(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton(); - - private static ServiceManager AddCollections(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); - - private static ServiceManager AddMods(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(s => (ModStorage)s.GetRequiredService()); - - private static ServiceManager AddResources(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); - - private static ServiceManager AddResolvers(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); - - private static ServiceManager AddInterface(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(p => new Diagnostics(p)); - - private static ServiceManager AddModEditor(this ServiceManager services) - => services.AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton(); - - private static ServiceManager AddApi(this ServiceManager services) - => services.AddSingleton(x => x.GetRequiredService()); } diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 62115dd6..652f928d 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -24,7 +25,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; -public class ItemSwapTab : IDisposable, ITab +public class ItemSwapTab : IDisposable, ITab, IUiService { private readonly Configuration _config; private readonly CommunicatorService _communicator; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 9410b793..90fdc48e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -7,6 +7,7 @@ using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -32,7 +33,7 @@ using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; namespace Penumbra.UI.AdvancedWindow; -public partial class ModEditWindow : Window, IDisposable +public partial class ModEditWindow : Window, IDisposable, IUiService { private const string WindowBaseLabel = "###SubModEdit"; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index 5dad66b4..b5f0255c 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; @@ -9,7 +10,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; -public class ModMergeTab(ModMerger modMerger) +public class ModMergeTab(ModMerger modMerger) : IUiService { private readonly ModCombo _modCombo = new(() => modMerger.ModsWithoutCurrent.ToList()); private string _newModName = string.Empty; @@ -183,7 +184,7 @@ public class ModMergeTab(ModMerger modMerger) else { ImGuiUtil.DrawTableColumn(option.GetName()); - + ImGui.TableNextColumn(); ImGui.Selectable(group.Name, false); if (ImGui.BeginPopupContextItem("##groupContext")) diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 29a1f291..0afeeeeb 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -10,6 +10,7 @@ using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -19,7 +20,7 @@ using ApiChangedItemIcon = Penumbra.Api.Enums.ChangedItemIcon; namespace Penumbra.UI; -public class ChangedItemDrawer : IDisposable +public class ChangedItemDrawer : IDisposable, IUiService { [Flags] public enum ChangedItemIcon : uint @@ -99,8 +100,10 @@ public class ChangedItemDrawer : IDisposable slot = 0; foreach (var (item, flag) in LowerNames.Zip(Order)) + { if (item.Contains(lowerInput, StringComparison.Ordinal)) slot |= flag; + } return slot != 0; } diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 184633f2..f4cedf7d 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -1,8 +1,9 @@ +using OtterGui.Services; using OtterGui.Widgets; namespace Penumbra.UI; -public class PenumbraChangelog +public class PenumbraChangelog : IUiService { public const int LastChangelogVersion = 0; diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index bff0092a..6c8bbf64 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -1,6 +1,7 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; +using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; @@ -9,7 +10,7 @@ using Penumbra.UI.ModsTab; namespace Penumbra.UI.Classes; -public class CollectionSelectHeader +public class CollectionSelectHeader : IUiService { private readonly CollectionCombo _collectionCombo; private readonly ActiveCollections _activeCollections; diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 0ae16f6d..67b0a50c 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -4,6 +4,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Custom; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.Services; @@ -13,7 +14,7 @@ using Penumbra.Util; namespace Penumbra.UI; -public sealed class ConfigWindow : Window +public sealed class ConfigWindow : Window, IUiService { private readonly DalamudPluginInterface _pluginInterface; private readonly Configuration _config; diff --git a/Penumbra/UI/FileDialogService.cs b/Penumbra/UI/FileDialogService.cs index 88c0b00f..cc2a7f6a 100644 --- a/Penumbra/UI/FileDialogService.cs +++ b/Penumbra/UI/FileDialogService.cs @@ -3,12 +3,13 @@ using Dalamud.Interface.ImGuiFileDialog; using Dalamud.Utility; using ImGuiNET; using OtterGui; +using OtterGui.Services; using Penumbra.Communication; using Penumbra.Services; namespace Penumbra.UI; -public class FileDialogService : IDisposable +public class FileDialogService : IDisposable, IUiService { private readonly CommunicatorService _communicator; private readonly FileDialogManager _manager; diff --git a/Penumbra/UI/ImportPopup.cs b/Penumbra/UI/ImportPopup.cs index 71164d1d..fb2028b5 100644 --- a/Penumbra/UI/ImportPopup.cs +++ b/Penumbra/UI/ImportPopup.cs @@ -1,13 +1,14 @@ using Dalamud.Interface.Windowing; using ImGuiNET; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Import.Structs; using Penumbra.Mods.Manager; namespace Penumbra.UI; /// Draw the progress information for import. -public sealed class ImportPopup : Window +public sealed class ImportPopup : Window, IUiService { public const string WindowLabel = "Penumbra Import Status"; diff --git a/Penumbra/UI/LaunchButton.cs b/Penumbra/UI/LaunchButton.cs index 9650ccf8..14e16432 100644 --- a/Penumbra/UI/LaunchButton.cs +++ b/Penumbra/UI/LaunchButton.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using Dalamud.Interface.Internal; using Dalamud.Plugin; using Dalamud.Plugin.Services; +using OtterGui.Services; namespace Penumbra.UI; @@ -9,7 +10,7 @@ namespace Penumbra.UI; /// A Launch Button used in the title screen of the game, /// using the Dalamud-provided collapsible submenu. /// -public class LaunchButton : IDisposable +public class LaunchButton : IDisposable, IUiService { private readonly ConfigWindow _configWindow; private readonly UiBuilder _uiBuilder; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 58f0b615..0ca4d40c 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -8,6 +8,7 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.FileSystem.Selector; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -21,7 +22,7 @@ using MessageService = Penumbra.Services.MessageService; namespace Penumbra.UI.ModsTab; -public sealed class ModFileSystemSelector : FileSystemSelector +public sealed class ModFileSystemSelector : FileSystemSelector, IUiService { private readonly CommunicatorService _communicator; private readonly MessageService _messager; @@ -33,9 +34,9 @@ public sealed class ModFileSystemSelector : FileSystemSelector().Aggregate((a, b) => a | b); - public ReadOnlySpan Label => "Changed Items"u8; - public ModPanelChangedItemsTab(ModFileSystemSelector selector, ChangedItemDrawer drawer) - { - _selector = selector; - _drawer = drawer; - } - public bool IsVisible - => _selector.Selected!.ChangedItems.Count > 0; + => selector.Selected!.ChangedItems.Count > 0; public void DrawContent() { - _drawer.DrawTypeFilter(); + drawer.DrawTypeFilter(); ImGui.Separator(); using var table = ImRaii.Table("##changedItems", 1, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(ImGui.GetContentRegionAvail().X, -1)); if (!table) return; - var zipList = ZipList.FromSortedList((SortedList)_selector.Selected!.ChangedItems); + var zipList = ZipList.FromSortedList((SortedList)selector.Selected!.ChangedItems); var height = ImGui.GetFrameHeightWithSpacing(); ImGui.TableNextColumn(); var skips = ImGuiClip.GetNecessarySkips(height); @@ -43,14 +33,14 @@ public class ModPanelChangedItemsTab : ITab } private bool CheckFilter((string Name, object? Data) kvp) - => _drawer.FilterChangedItem(kvp.Name, kvp.Data, LowerString.Empty); + => drawer.FilterChangedItem(kvp.Name, kvp.Data, LowerString.Empty); private void DrawChangedItem((string Name, object? Data) kvp) { ImGui.TableNextColumn(); - _drawer.DrawCategoryIcon(kvp.Name, kvp.Data); + drawer.DrawCategoryIcon(kvp.Name, kvp.Data); ImGui.SameLine(); - _drawer.DrawChangedItem(kvp.Name, kvp.Data); - _drawer.DrawModelData(kvp.Data); + drawer.DrawChangedItem(kvp.Name, kvp.Data); + drawer.DrawModelData(kvp.Data); } } diff --git a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs index aa598557..9f37f847 100644 --- a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -10,25 +11,16 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; -public class ModPanelCollectionsTab : ITab +public class ModPanelCollectionsTab(CollectionStorage storage, ModFileSystemSelector selector) : ITab, IUiService { - private readonly ModFileSystemSelector _selector; - private readonly CollectionStorage _collections; - - private readonly List<(ModCollection, ModCollection, uint, string)> _cache = new(); - - public ModPanelCollectionsTab(CollectionStorage storage, ModFileSystemSelector selector) - { - _collections = storage; - _selector = selector; - } + private readonly List<(ModCollection, ModCollection, uint, string)> _cache = []; public ReadOnlySpan Label => "Collections"u8; public void DrawContent() { - var (direct, inherited) = CountUsage(_selector.Selected!); + var (direct, inherited) = CountUsage(selector.Selected!); ImGui.NewLine(); if (direct == 1) ImGui.TextUnformatted("This Mod is directly configured in 1 collection."); @@ -80,7 +72,7 @@ public class ModPanelCollectionsTab : ITab var disInherited = ColorId.InheritedDisabledMod.Value(); var directCount = 0; var inheritedCount = 0; - foreach (var collection in _collections) + foreach (var collection in storage) { var (settings, parent) = collection[mod.Index]; var (color, text) = settings == null diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index c1a3c1eb..bee48068 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections.Cache; @@ -16,7 +17,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; -public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSystemSelector selector) : ITab +public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSystemSelector selector) : ITab, IUiService { private int? _currentPriority; diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index ed6340ab..6fe3e4c6 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui.Raii; using OtterGui; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Mods.Manager; @@ -12,7 +13,7 @@ public class ModPanelDescriptionTab( TutorialService tutorial, ModManager modManager, PredefinedTagManager predefinedTagsConfig) - : ITab + : ITab, IUiService { private readonly TagButtons _localTags = new(); private readonly TagButtons _modTags = new(); diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 468e97b9..1e371065 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -6,13 +6,13 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; using OtterGui.Classes; +using OtterGui.Services; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.AdvancedWindow; using Penumbra.Mods.Settings; -using Penumbra.Mods.Manager.OptionEditor; using Penumbra.UI.ModsTab.Groups; namespace Penumbra.UI.ModsTab; @@ -31,7 +31,7 @@ public class ModPanelEditTab( ModGroupEditDrawer groupEditDrawer, DescriptionEditPopup descriptionPopup, AddGroupDrawer addGroupDrawer) - : ITab + : ITab, IUiService { private readonly TagButtons _modTags = new(); diff --git a/Penumbra/UI/ModsTab/ModPanelTabBar.cs b/Penumbra/UI/ModsTab/ModPanelTabBar.cs index 8b09d8b9..639118f5 100644 --- a/Penumbra/UI/ModsTab/ModPanelTabBar.cs +++ b/Penumbra/UI/ModsTab/ModPanelTabBar.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Mods; using Penumbra.Mods.Manager; @@ -9,7 +10,7 @@ using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.ModsTab; -public class ModPanelTabBar +public class ModPanelTabBar : IUiService { private enum ModPanelTabType { @@ -33,7 +34,7 @@ public class ModPanelTabBar public readonly ITab[] Tabs; private ModPanelTabType _preferredTab = ModPanelTabType.Settings; - private Mod? _lastMod = null; + private Mod? _lastMod; public ModPanelTabBar(ModEditWindow modEditWindow, ModPanelSettingsTab settings, ModPanelDescriptionTab description, ModPanelConflictsTab conflicts, ModPanelChangedItemsTab changedItems, ModPanelEditTab edit, ModManager modManager, @@ -49,15 +50,15 @@ public class ModPanelTabBar _tutorial = tutorial; Collections = collections; - Tabs = new ITab[] - { + Tabs = + [ Settings, Description, Conflicts, ChangedItems, Collections, Edit, - }; + ]; } public void Draw(Mod mod) diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs index 595240f4..4079748e 100644 --- a/Penumbra/UI/ModsTab/MultiModPanel.cs +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -3,12 +3,13 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Mods; using Penumbra.Mods.Manager; namespace Penumbra.UI.ModsTab; -public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _editor) +public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _editor) : IUiService { public void Draw() { @@ -65,8 +66,8 @@ public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _edito } private string _tag = string.Empty; - private readonly List _addMods = []; - private readonly List<(Mod, int)> _removeMods = []; + private readonly List _addMods = []; + private readonly List<(Mod, int)> _removeMods = []; private void DrawMultiTagger() { diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index 0e5377d6..d531b1a2 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -6,14 +6,14 @@ using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using OtterGui.Services; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.Classes; -using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra.UI; -public sealed class PredefinedTagManager : ISavable, IReadOnlyList +public sealed class PredefinedTagManager : ISavable, IReadOnlyList, IService { public const int Version = 1; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 65a8fe76..a7d1a8c6 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -2,6 +2,7 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; using ImGuiNET; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -15,7 +16,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.ResourceWatcher; -public sealed class ResourceWatcher : IDisposable, ITab +public sealed class ResourceWatcher : IDisposable, ITab, IUiService { public const int DefaultMaxEntries = 1024; public const RecordType AllRecords = RecordType.Request | RecordType.ResourceLoad | RecordType.FileLoad | RecordType.Destruction; diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index ab0badf4..2aeaaea0 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -2,6 +2,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; @@ -17,7 +18,7 @@ public class ChangedItemsTab( CollectionSelectHeader collectionHeader, ChangedItemDrawer drawer, CommunicatorService communicator) - : ITab + : ITab, IUiService { public ReadOnlySpan Label => "Changed Items"u8; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index fabf7561..34e2cbcf 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -2,6 +2,7 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Plugin; using ImGuiNET; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; @@ -11,7 +12,7 @@ using Penumbra.UI.CollectionTab; namespace Penumbra.UI.Tabs; -public sealed class CollectionsTab : IDisposable, ITab +public sealed class CollectionsTab : IDisposable, ITab, IUiService { private readonly EphemeralConfig _config; private readonly CollectionSelector _selector; diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index 9fd07f27..28827ad9 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -1,4 +1,5 @@ using ImGuiNET; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Mods; @@ -8,7 +9,7 @@ using Watcher = Penumbra.UI.ResourceWatcher.ResourceWatcher; namespace Penumbra.UI.Tabs; -public class ConfigTabBar : IDisposable +public class ConfigTabBar : IDisposable, IUiService { private readonly CommunicatorService _communicator; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 1519ebf0..0122a6f5 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -44,7 +44,7 @@ using Penumbra.Api.IpcTester; namespace Penumbra.UI.Tabs.Debug; -public class Diagnostics(IServiceProvider provider) +public class Diagnostics(ServiceManager provider) : IUiService { public void DrawDiagnostics() { @@ -55,7 +55,7 @@ public class Diagnostics(IServiceProvider provider) foreach (var type in typeof(ActorManager).Assembly.GetTypes() .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncDataContainer)))) { - var container = (IAsyncDataContainer)provider.GetRequiredService(type); + var container = (IAsyncDataContainer)provider.Provider!.GetRequiredService(type); ImGuiUtil.DrawTableColumn(container.Name); ImGuiUtil.DrawTableColumn(container.Time.ToString()); ImGuiUtil.DrawTableColumn(Functions.HumanReadableSize(container.Memory)); @@ -64,7 +64,7 @@ public class Diagnostics(IServiceProvider provider) } } -public class DebugTab : Window, ITab +public class DebugTab : Window, ITab, IUiService { private readonly PerformanceTracker _performance; private readonly Configuration _config; diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index 7076b80f..1b9af75c 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Cache; @@ -15,7 +16,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.Tabs; public class EffectiveTab(CollectionManager collectionManager, CollectionSelectHeader collectionHeader) - : ITab + : ITab, IUiService { public ReadOnlySpan Label => "Effective Changes"u8; diff --git a/Penumbra/UI/Tabs/MessagesTab.cs b/Penumbra/UI/Tabs/MessagesTab.cs index abaf2ba6..190f9407 100644 --- a/Penumbra/UI/Tabs/MessagesTab.cs +++ b/Penumbra/UI/Tabs/MessagesTab.cs @@ -1,9 +1,10 @@ +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Services; namespace Penumbra.UI.Tabs; -public class MessagesTab(MessageService messages) : ITab +public class MessagesTab(MessageService messages) : ITab, IUiService { public ReadOnlySpan Label => "Messages"u8; diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index e4d94bb5..7faa3da8 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -6,6 +6,7 @@ using Penumbra.UI.Classes; using Dalamud.Interface; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Housing; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Interop.Services; @@ -30,7 +31,7 @@ public class ModsTab( CollectionSelectHeader collectionHeader, ITargetManager targets, ObjectManager objects) - : ITab + : ITab, IUiService { private readonly ActiveCollections _activeCollections = collectionManager.Active; diff --git a/Penumbra/UI/Tabs/OnScreenTab.cs b/Penumbra/UI/Tabs/OnScreenTab.cs index 787e07a1..fa33f702 100644 --- a/Penumbra/UI/Tabs/OnScreenTab.cs +++ b/Penumbra/UI/Tabs/OnScreenTab.cs @@ -1,16 +1,12 @@ +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.UI.AdvancedWindow; namespace Penumbra.UI.Tabs; -public class OnScreenTab : ITab +public class OnScreenTab(ResourceTreeViewerFactory resourceTreeViewerFactory) : ITab, IUiService { - private readonly ResourceTreeViewer _viewer; - - public OnScreenTab(ResourceTreeViewerFactory resourceTreeViewerFactory) - { - _viewer = resourceTreeViewerFactory.Create(0, delegate { }, delegate { }); - } + private readonly ResourceTreeViewer _viewer = resourceTreeViewerFactory.Create(0, delegate { }, delegate { }); public ReadOnlySpan Label => "On-Screen"u8; diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index bbb0561b..0b54c5e2 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -6,6 +6,7 @@ using FFXIVClientStructs.STD; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Interop.ResourceLoading; using Penumbra.String.Classes; @@ -13,7 +14,7 @@ using Penumbra.String.Classes; namespace Penumbra.UI.Tabs; public class ResourceTab(Configuration config, ResourceManagerService resourceManager, ISigScanner sigScanner) - : ITab + : ITab, IUiService { public ReadOnlySpan Label => "Resource Manager"u8; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 0de4f790..17db21c9 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -9,6 +9,7 @@ using OtterGui; using OtterGui.Compression; using OtterGui.Custom; using OtterGui.Raii; +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Interop.Services; @@ -19,7 +20,7 @@ using Penumbra.UI.ModsTab; namespace Penumbra.UI.Tabs; -public class SettingsTab : ITab +public class SettingsTab : ITab, IUiService { public const int RootDirectoryMaxLength = 64; diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index d87df19e..7d2a0d2a 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -1,3 +1,4 @@ +using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -40,7 +41,7 @@ public enum BasicTutorialSteps } /// Service for the in-game tutorial. -public class TutorialService +public class TutorialService : IUiService { public const string SelectedCollection = "Selected Collection"; public const string DefaultCollection = "Base Collection"; diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index c5418eb3..99819fce 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -1,12 +1,13 @@ using Dalamud.Interface; using Dalamud.Interface.Windowing; using Dalamud.Plugin; +using OtterGui.Services; using Penumbra.UI.AdvancedWindow; using Penumbra.UI.Tabs.Debug; namespace Penumbra.UI; -public class PenumbraWindowSystem : IDisposable +public class PenumbraWindowSystem : IDisposable, IUiService { private readonly UiBuilder _uiBuilder; private readonly WindowSystem _windowSystem; From 90124e83df4dfc6c21c5a8107e0d749229df2309 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 19 Jun 2024 11:51:55 +0000 Subject: [PATCH 0705/1381] [CI] Updating repo.json for testing_1.1.1.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 318aafc2..fc7234bd 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.1", - "TestingAssemblyVersion": "1.1.1.1", + "TestingAssemblyVersion": "1.1.1.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a90e253c73b6bd6e68f37f911e7be3f2c5e0a69b Mon Sep 17 00:00:00 2001 From: Ottermandias <70807659+Ottermandias@users.noreply.github.com> Date: Wed, 19 Jun 2024 13:54:17 +0200 Subject: [PATCH 0706/1381] Update repo.json --- repo.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/repo.json b/repo.json index fc7234bd..c00e3c8f 100644 --- a/repo.json +++ b/repo.json @@ -5,7 +5,7 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.1.1.1", + "AssemblyVersion": "1.1.1.2", "TestingAssemblyVersion": "1.1.1.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", @@ -17,9 +17,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 29f8c91306daafc4bc5eab156015c895c8aa9a21 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 19 Jun 2024 22:34:59 +0200 Subject: [PATCH 0707/1381] Make meta hooks respect Enable Mod setting and fix EQP composition. --- OtterGui | 2 +- Penumbra/Collections/Cache/EqpCache.cs | 49 +++++++++++++++++-- Penumbra/Configuration.cs | 16 +++++- .../Interop/Hooks/Meta/EqdpAccessoryHook.cs | 8 ++- Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 8 ++- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 8 ++- Penumbra/Interop/Hooks/Meta/EstHook.cs | 13 +++-- Penumbra/Interop/Hooks/Meta/GmpHook.cs | 11 +++-- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 8 ++- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 15 ++++-- Penumbra/Interop/Hooks/Meta/RspTailHook.cs | 8 ++- Penumbra/Interop/PathResolving/MetaState.cs | 8 +-- 12 files changed, 121 insertions(+), 33 deletions(-) diff --git a/OtterGui b/OtterGui index caa9e9b9..6fafc03b 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit caa9e9b9a5dc3928eba10b315cf6a0f6f1d84b65 +Subproject commit 6fafc03b34971be7c0e74fd9a638d1ed642ea19a diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index 60e38aef..c681b230 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -9,11 +9,24 @@ namespace Penumbra.Collections.Cache; public sealed class EqpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { public unsafe EqpEntry GetValues(CharacterArmor* armor) - => GetSingleValue(armor[0].Set, EquipSlot.Head) - | GetSingleValue(armor[1].Set, EquipSlot.Body) - | GetSingleValue(armor[2].Set, EquipSlot.Hands) - | GetSingleValue(armor[3].Set, EquipSlot.Legs) - | GetSingleValue(armor[4].Set, EquipSlot.Feet); + { + var bodyEntry = GetSingleValue(armor[1].Set, EquipSlot.Body); + var headEntry = bodyEntry.HasFlag(EqpEntry.BodyShowHead) + ? GetSingleValue(armor[0].Set, EquipSlot.Head) + : GetSingleValue(armor[1].Set, EquipSlot.Head); + var handEntry = bodyEntry.HasFlag(EqpEntry.BodyShowHand) + ? GetSingleValue(armor[2].Set, EquipSlot.Hands) + : GetSingleValue(armor[1].Set, EquipSlot.Hands); + var (legsEntry, legsId) = bodyEntry.HasFlag(EqpEntry.BodyShowLeg) + ? (GetSingleValue(armor[3].Set, EquipSlot.Legs), 3) + : (GetSingleValue(armor[1].Set, EquipSlot.Legs), 1); + var footEntry = legsEntry.HasFlag(EqpEntry.LegsShowFoot) + ? GetSingleValue(armor[4].Set, EquipSlot.Feet) + : GetSingleValue(armor[legsId].Set, EquipSlot.Feet); + + var combined = bodyEntry | headEntry | handEntry | legsEntry | footEntry; + return PostProcessFeet(PostProcessHands(combined)); + } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private EqpEntry GetSingleValue(PrimaryId id, EquipSlot slot) @@ -24,4 +37,30 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) protected override void Dispose(bool _) => Clear(); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static EqpEntry PostProcessHands(EqpEntry entry) + { + if (!entry.HasFlag(EqpEntry.HandsHideForearm)) + return entry; + + var testFlag = entry.HasFlag(EqpEntry.HandsHideElbow) + ? entry.HasFlag(EqpEntry.BodyHideGlovesL) + : entry.HasFlag(EqpEntry.BodyHideGlovesM); + return testFlag + ? (entry | EqpEntry._4) & ~EqpEntry.BodyHideGlovesS + : entry & ~(EqpEntry._4 | EqpEntry.BodyHideGlovesS); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static EqpEntry PostProcessFeet(EqpEntry entry) + { + if (!entry.HasFlag(EqpEntry.FeetHideCalf)) + return entry; + + if (entry.HasFlag(EqpEntry.FeetHideKnee) || !entry.HasFlag(EqpEntry._20)) + return entry & ~(EqpEntry.LegsHideBootsS | EqpEntry.LegsHideBootsM); + + return (entry | EqpEntry.LegsHideBootsM) & ~EqpEntry.LegsHideBootsS; + } } diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index f6100b62..7faed6a2 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -31,7 +31,21 @@ public class Configuration : IPluginConfiguration, ISavable, IService public ChangeLogDisplayType ChangeLogDisplayType { get; set; } = ChangeLogDisplayType.New; - public bool EnableMods { get; set; } = true; + public event Action? ModsEnabled; + + [JsonIgnore] + private bool _enableMods = true; + + public bool EnableMods + { + get => _enableMods; + set + { + _enableMods = value; + ModsEnabled?.Invoke(value); + } + } + public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs index aaaaccd4..583a2ac5 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -6,7 +6,7 @@ using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Meta; -public unsafe class EqdpAccessoryHook : FastHook +public unsafe class EqdpAccessoryHook : FastHook, IDisposable { public delegate void Delegate(CharacterUtility* utility, EqdpEntry* entry, uint id, uint raceCode); @@ -15,7 +15,8 @@ public unsafe class EqdpAccessoryHook : FastHook public EqdpAccessoryHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpAccessoryEntry", "E8 ?? ?? ?? ?? 41 BF ?? ?? ?? ?? 83 FB", Detour, true); + Task = hooks.CreateHook("GetEqdpAccessoryEntry", "E8 ?? ?? ?? ?? 41 BF ?? ?? ?? ?? 83 FB", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) @@ -27,4 +28,7 @@ public unsafe class EqdpAccessoryHook : FastHook Penumbra.Log.Excessive( $"[GetEqdpAccessoryEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs index 2711f195..f5488f80 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -6,7 +6,7 @@ using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Meta; -public unsafe class EqdpEquipHook : FastHook +public unsafe class EqdpEquipHook : FastHook, IDisposable { public delegate void Delegate(CharacterUtility* utility, EqdpEntry* entry, uint id, uint raceCode); @@ -15,7 +15,8 @@ public unsafe class EqdpEquipHook : FastHook public EqdpEquipHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpEquipEntry", "E8 ?? ?? ?? ?? 85 DB 75 ?? F6 45", Detour, true); + Task = hooks.CreateHook("GetEqdpEquipEntry", "E8 ?? ?? ?? ?? 85 DB 75 ?? F6 45", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) @@ -27,4 +28,7 @@ public unsafe class EqdpEquipHook : FastHook Penumbra.Log.Excessive( $"[GetEqdpEquipEntry] Invoked on 0x{(ulong)utility:X} with {setId}, {(GenderRace)raceCode}, returned {(ushort)*entry:B10}."); } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index 7107e26b..e96d8115 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -5,7 +5,7 @@ using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Meta; -public unsafe class EqpHook : FastHook +public unsafe class EqpHook : FastHook, IDisposable { public delegate void Delegate(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor); @@ -14,7 +14,8 @@ public unsafe class EqpHook : FastHook public EqpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqpFlags", "E8 ?? ?? ?? ?? 0F B6 44 24 ?? C0 E8", Detour, true); + Task = hooks.CreateHook("GetEqpFlags", "E8 ?? ?? ?? ?? 0F B6 44 24 ?? C0 E8", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private void Detour(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor) @@ -31,4 +32,7 @@ public unsafe class EqpHook : FastHook Penumbra.Log.Excessive($"[GetEqpFlags] Invoked on 0x{(nint)utility:X} with 0x{(ulong)armor:X}, returned 0x{(ulong)*flags:X16}."); } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index 23931182..fa0bb3c5 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -6,7 +6,7 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Meta; -public class EstHook : FastHook +public class EstHook : FastHook, IDisposable { public delegate EstEntry Delegate(uint id, int estType, uint genderRace); @@ -14,14 +14,16 @@ public class EstHook : FastHook public EstHook(HookManager hooks, MetaState metaState) { - _metaState = metaState; - Task = hooks.CreateHook("GetEstEntry", "44 8B C9 83 EA ?? 74", Detour, true); + _metaState = metaState; + Task = hooks.CreateHook("GetEstEntry", "44 8B C9 83 EA ?? 74", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private EstEntry Detour(uint genderRace, int estType, uint id) { EstEntry ret; - if (_metaState.EstCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache } + if (_metaState.EstCollection.TryPeek(out var collection) + && collection is { Valid: true, ModCollection.MetaCache: { } cache } && cache.Est.TryGetValue(Convert(genderRace, estType, id), out var entry)) ret = entry.Entry; else @@ -46,4 +48,7 @@ public class EstHook : FastHook }; return new EstIdentifier(i, type, gr); } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 256d8702..44d35f12 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -5,7 +5,7 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Meta; -public unsafe class GmpHook : FastHook +public unsafe class GmpHook : FastHook, IDisposable { public delegate nint Delegate(nint gmpResource, uint dividedHeadId); @@ -16,7 +16,8 @@ public unsafe class GmpHook : FastHook public GmpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetGmpEntry", "E8 ?? ?? ?? ?? 48 85 C0 74 ?? 43 8D 0C", Detour, true); + Task = hooks.CreateHook("GetGmpEntry", "E8 ?? ?? ?? ?? 48 85 C0 74 ?? 43 8D 0C", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } /// @@ -27,7 +28,8 @@ public unsafe class GmpHook : FastHook private nint Detour(nint gmpResource, uint dividedHeadId) { nint ret; - if (_metaState.GmpCollection.TryPeek(out var collection) && collection.Collection is { Valid: true, ModCollection.MetaCache: { } cache } + if (_metaState.GmpCollection.TryPeek(out var collection) + && collection.Collection is { Valid: true, ModCollection.MetaCache: { } cache } && cache.Gmp.TryGetValue(new GmpIdentifier(collection.Id), out var entry)) { if (entry.Entry.Enabled) @@ -61,4 +63,7 @@ public unsafe class GmpHook : FastHook Marshal.FreeHGlobal((nint)Pointer); } } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index 86759460..db22d90c 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -7,7 +7,7 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Meta; -public unsafe class RspBustHook : FastHook +public unsafe class RspBustHook : FastHook, IDisposable { public delegate float* Delegate(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte bustSize); @@ -19,7 +19,8 @@ public unsafe class RspBustHook : FastHook { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspBust", "E8 ?? ?? ?? ?? F2 0F 10 44 24 ?? 8B 44 24", Detour, true); + Task = hooks.CreateHook("GetRspBust", "E8 ?? ?? ?? ?? F2 0F 10 44 24 ?? 8B 44 24", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private float* Detour(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte bustSize) @@ -63,4 +64,7 @@ public unsafe class RspBustHook : FastHook $"[GetRspBust] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); return ret; } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index cf88c34a..dcb3f19c 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -1,4 +1,3 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.Interop.PathResolving; @@ -8,7 +7,7 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Meta; -public class RspHeightHook : FastHook +public class RspHeightHook : FastHook, IDisposable { public delegate float Delegate(nint cmpResource, Race clan, byte gender, byte isSecondSubRace, byte bodyType, byte height); @@ -17,15 +16,18 @@ public class RspHeightHook : FastHook public RspHeightHook(HookManager hooks, MetaState metaState, MetaFileManager metaFileManager) { - _metaState = metaState; + _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspHeight", "E8 ?? ?? ?? ?? 48 8B 8E ?? ?? ?? ?? 44 8B CF", Detour, true); + Task = hooks.CreateHook("GetRspHeight", "E8 ?? ?? ?? ?? 48 8B 8E ?? ?? ?? ?? 44 8B CF", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte height) { float scale; - if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (bodyType < 2 + && _metaState.RspCollection.TryPeek(out var collection) + && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 @@ -66,4 +68,7 @@ public class RspHeightHook : FastHook $"[GetRspHeight] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {height}, returned {scale}."); return scale; } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs index e40f0161..8d333575 100644 --- a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs @@ -7,7 +7,7 @@ using Penumbra.Meta.Manipulations; namespace Penumbra.Interop.Hooks.Meta; -public class RspTailHook : FastHook +public class RspTailHook : FastHook, IDisposable { public delegate float Delegate(nint cmpResource, Race clan, byte gender, byte isSecondSubRace, byte bodyType, byte height); @@ -18,7 +18,8 @@ public class RspTailHook : FastHook { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspTail", "E8 ?? ?? ?? ?? 0F 28 F0 48 8B 05", Detour, true); + Task = hooks.CreateHook("GetRspTail", "E8 ?? ?? ?? ?? 0F 28 F0 48 8B 05", Detour, metaState.Config.EnableMods); + _metaState.Config.ModsEnabled += Toggle; } private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte tailLength) @@ -65,4 +66,7 @@ public class RspTailHook : FastHook $"[GetRspTail] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {tailLength}, returned {scale}."); return scale; } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index f7dcfc07..5eacbfb0 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -37,7 +37,7 @@ namespace Penumbra.Interop.PathResolving; // GMP Entries seem to be only used by "48 8B ?? 53 55 57 48 83 ?? ?? 48 8B", which is SetupVisor. public sealed unsafe class MetaState : IDisposable, IService { - private readonly Configuration _config; + public readonly Configuration Config; private readonly CommunicatorService _communicator; private readonly CollectionResolver _collectionResolver; private readonly ResourceLoader _resources; @@ -64,7 +64,7 @@ public sealed unsafe class MetaState : IDisposable, IService _resources = resources; _createCharacterBase = createCharacterBase; _characterUtility = characterUtility; - _config = config; + Config = config; _createCharacterBase.Subscribe(OnCreatingCharacterBase, CreateCharacterBase.Priority.MetaState); _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.MetaState); } @@ -84,7 +84,7 @@ public sealed unsafe class MetaState : IDisposable, IService } public DecalReverter ResolveDecal(ResolveData resolve, bool which) - => new(_config, _characterUtility, _resources, resolve, which); + => new(Config, _characterUtility, _resources, resolve, which); public void Dispose() { @@ -99,7 +99,7 @@ public sealed unsafe class MetaState : IDisposable, IService _communicator.CreatingCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, _lastCreatedCollection.ModCollection.Id, (nint)modelCharaId, (nint)customize, (nint)equipData); - var decal = new DecalReverter(_config, _characterUtility, _resources, _lastCreatedCollection, + var decal = new DecalReverter(Config, _characterUtility, _resources, _lastCreatedCollection, UsesDecal(*(uint*)modelCharaId, (nint)customize)); RspCollection.Push(_lastCreatedCollection); _characterBaseCreateMetaChanges.Dispose(); // Should always be empty. From f686a0ff09873a08eba20a332b27c0090834dbae Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 19 Jun 2024 20:37:08 +0000 Subject: [PATCH 0708/1381] [CI] Updating repo.json for testing_1.1.1.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index c00e3c8f..03f13499 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.1.1.3", + "TestingAssemblyVersion": "1.1.1.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 8cd8efa72347bda899a32baab1f878e55c3c7c9f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Jun 2024 14:24:35 +0200 Subject: [PATCH 0709/1381] Fix RSP scaling for NPC values. --- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index dcb3f19c..98e39061 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -29,6 +29,12 @@ public class RspHeightHook : FastHook, IDisposable && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { + // Special cases. + if (height == 0xFF) + return 1.0f; + if (height > 100) + height = 0; + var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 ? (new RspIdentifier(clan, RspAttribute.MaleMinSize), new RspIdentifier(clan, RspAttribute.MaleMaxSize)) From ab1e11aba1b42a67552d5557cc16402b41f0e4ad Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Jun 2024 14:51:17 +0200 Subject: [PATCH 0710/1381] Improve support info a bit. --- Penumbra/Penumbra.cs | 44 ++++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 905b998d..38d9c7b2 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -21,6 +21,7 @@ using OtterGui.Tasks; using Penumbra.GameData.Enums; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; +using System.Xml.Linq; namespace Penumbra; @@ -175,6 +176,26 @@ public class Penumbra : IDalamudPlugin _disposed = true; } + private void GatherRelevantPlugins(StringBuilder sb) + { + ReadOnlySpan relevantPlugins = + [ + "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", + ]; + var plugins = _services.GetService().InstalledPlugins + .GroupBy(p => p.InternalName) + .ToDictionary(g => g.Key, g => + { + var item = g.OrderByDescending(p => p.IsLoaded).ThenByDescending(p => p.Version).First(); + return (item.IsLoaded, item.Version, item.Name); + }); + foreach (var plugin in relevantPlugins) + { + if (plugins.TryGetValue(plugin, out var data)) + sb.Append($"> **`{data.Name + ':',-29}`** {data.Version}{(data.IsLoaded ? string.Empty : " (Disabled)")}\n"); + } + } + public string GatherSupportInformation() { var sb = new StringBuilder(10240); @@ -198,6 +219,7 @@ public class Penumbra : IDalamudPlugin sb.Append( $"> **`Logging: `** Log: {_config.Ephemeral.EnableResourceLogging}, Watcher: {_config.Ephemeral.EnableResourceWatcher} ({_config.MaxResourceWatcherRecords})\n"); sb.Append($"> **`Use Ownership: `** {_config.UseOwnerNameForCharacterCollection}\n"); + GatherRelevantPlugins(sb); sb.AppendLine("**Mods**"); sb.Append($"> **`Installed Mods: `** {_modManager.Count}\n"); sb.Append($"> **`Mods with Config: `** {_modManager.Count(m => m.HasOptions)}\n"); @@ -212,27 +234,25 @@ public class Penumbra : IDalamudPlugin $"> **`#Temp Mods: `** {_tempMods.Mods.Sum(kvp => kvp.Value.Count) + _tempMods.ModsForAllCollections.Count}\n"); void PrintCollection(ModCollection c, CollectionCache _) - => sb.Append($"**Collection {c.AnonymizedName}**\n" - + $"> **`Inheritances: `** {c.DirectlyInheritsFrom.Count}\n" - + $"> **`Enabled Mods: `** {c.ActualSettings.Count(s => s is { Enabled: true })}\n" - + $"> **`Conflicts (Solved/Total): `** {c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority && x.Solved ? x.Conflicts.Count : 0)}/{c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority ? x.Conflicts.Count : 0)}\n"); + => sb.Append( + $"> **`Collection {c.AnonymizedName + ':',-18}`** Inheritances: `{c.DirectlyInheritsFrom.Count,3}`, Enabled Mods: `{c.ActualSettings.Count(s => s is { Enabled: true }),4}`, Conflicts: `{c.AllConflicts.SelectMany(x => x).Sum(x => x is { HasPriority: true, Solved: true } ? x.Conflicts.Count : 0),5}/{c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority ? x.Conflicts.Count : 0),5}`\n"); sb.AppendLine("**Collections**"); - sb.Append($"> **`#Collections: `** {_collectionManager.Storage.Count - 1}\n"); - sb.Append($"> **`#Temp Collections: `** {_tempCollections.Count}\n"); - sb.Append($"> **`Active Collections: `** {_collectionManager.Caches.Count}\n"); - sb.Append($"> **`Base Collection: `** {_collectionManager.Active.Default.AnonymizedName}\n"); - sb.Append($"> **`Interface Collection: `** {_collectionManager.Active.Interface.AnonymizedName}\n"); - sb.Append($"> **`Selected Collection: `** {_collectionManager.Active.Current.AnonymizedName}\n"); + sb.Append($"> **`#Collections: `** {_collectionManager.Storage.Count - 1}\n"); + sb.Append($"> **`#Temp Collections: `** {_tempCollections.Count}\n"); + sb.Append($"> **`Active Collections: `** {_collectionManager.Caches.Count}\n"); + sb.Append($"> **`Base Collection: `** {_collectionManager.Active.Default.AnonymizedName}\n"); + sb.Append($"> **`Interface Collection: `** {_collectionManager.Active.Interface.AnonymizedName}\n"); + sb.Append($"> **`Selected Collection: `** {_collectionManager.Active.Current.AnonymizedName}\n"); foreach (var (type, name, _) in CollectionTypeExtensions.Special) { var collection = _collectionManager.Active.ByType(type); if (collection != null) - sb.Append($"> **`{name,-30}`** {collection.AnonymizedName}\n"); + sb.Append($"> **`{name,-29}`** {collection.AnonymizedName}\n"); } foreach (var (name, id, collection) in _collectionManager.Active.Individuals.Assignments) - sb.Append($"> **`{id[0].Incognito(name) + ':',-30}`** {collection.AnonymizedName}\n"); + sb.Append($"> **`{id[0].Incognito(name) + ':',-29}`** {collection.AnonymizedName}\n"); foreach (var collection in _collectionManager.Caches.Active) PrintCollection(collection, collection._cache!); From 045abc787d46bb472366a08bf22c020906ec5690 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 20 Jun 2024 12:53:23 +0000 Subject: [PATCH 0711/1381] [CI] Updating repo.json for testing_1.1.1.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 03f13499..3142f8d4 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.1.1.4", + "TestingAssemblyVersion": "1.1.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From b07af32deead6ee2c601ff26d1d8a5194ea3ae30 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 22 Jun 2024 23:04:09 +0200 Subject: [PATCH 0712/1381] Fix doubled hook. --- .../Resources/ResourceHandleDestructor.cs | 4 +++ .../ResourceLoading/ResourceService.cs | 28 +--------------- .../UI/ResourceWatcher/ResourceWatcher.cs | 32 +++++++++++-------- 3 files changed, 23 insertions(+), 41 deletions(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index 5ddb7eaa..ac3f504a 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -3,6 +3,7 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.GameData; using Penumbra.Interop.Structs; +using Penumbra.UI.ResourceWatcher; namespace Penumbra.Interop.Hooks.Resources; @@ -15,6 +16,9 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr ShaderReplacementFixer, + + /// + ResourceWatcher, } public ResourceHandleDestructor(HookManager hooks) diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 54c86777..0947d2ec 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -26,7 +26,6 @@ public unsafe class ResourceService : IDisposable, IRequiredService interop.InitializeFromAttributes(this); _getResourceSyncHook.Enable(); _getResourceAsyncHook.Enable(); - _resourceHandleDestructorHook.Enable(); _incRefHook = interop.HookFromAddress( (nint)CSResourceHandle.MemberFunctionPointers.IncRef, ResourceHandleIncRefDetour); @@ -51,7 +50,6 @@ public unsafe class ResourceService : IDisposable, IRequiredService { _getResourceSyncHook.Dispose(); _getResourceAsyncHook.Dispose(); - _resourceHandleDestructorHook.Dispose(); _incRefHook.Dispose(); _decRefHook.Dispose(); } @@ -67,8 +65,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService /// Whether to request the resource synchronously or asynchronously. /// The returned resource handle. If this is not null, calling original will be skipped. public delegate void GetResourcePreDelegate(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, - Utf8GamePath original, - GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue); + Utf8GamePath original, GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue); /// /// Subscribers should be exception-safe. @@ -192,27 +189,4 @@ public unsafe class ResourceService : IDisposable, IRequiredService } #endregion - - #region Destructor - - /// Invoked before a resource handle is destructed. - /// The resource handle. - public delegate void ResourceHandleDtorDelegate(ResourceHandle* handle); - - /// - /// - /// Subscribers should be exception-safe. - /// - public event ResourceHandleDtorDelegate? ResourceHandleDestructor; - - [Signature(Sigs.ResourceHandleDestructor, DetourName = nameof(ResourceHandleDestructorDetour))] - private readonly Hook _resourceHandleDestructorHook = null!; - - private nint ResourceHandleDestructorDetour(ResourceHandle* handle) - { - ResourceHandleDestructor?.Invoke(handle); - return _resourceHandleDestructorHook.OriginalDisposeSafe(handle); - } - - #endregion } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index a7d1a8c6..3bf4cd88 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -8,8 +8,10 @@ using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; +using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; +using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -21,28 +23,30 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService public const int DefaultMaxEntries = 1024; public const RecordType AllRecords = RecordType.Request | RecordType.ResourceLoad | RecordType.FileLoad | RecordType.Destruction; - private readonly Configuration _config; - private readonly EphemeralConfig _ephemeral; - private readonly ResourceService _resources; - private readonly ResourceLoader _loader; - private readonly ActorManager _actors; - private readonly List _records = []; - private readonly ConcurrentQueue _newRecords = []; - private readonly ResourceWatcherTable _table; - private string _logFilter = string.Empty; - private Regex? _logRegex; - private int _newMaxEntries; + private readonly Configuration _config; + private readonly EphemeralConfig _ephemeral; + private readonly ResourceService _resources; + private readonly ResourceLoader _loader; + private readonly ResourceHandleDestructor _destructor; + private readonly ActorManager _actors; + private readonly List _records = []; + private readonly ConcurrentQueue _newRecords = []; + private readonly ResourceWatcherTable _table; + private string _logFilter = string.Empty; + private Regex? _logRegex; + private int _newMaxEntries; - public unsafe ResourceWatcher(ActorManager actors, Configuration config, ResourceService resources, ResourceLoader loader) + public unsafe ResourceWatcher(ActorManager actors, Configuration config, ResourceService resources, ResourceLoader loader, ResourceHandleDestructor destructor) { _actors = actors; _config = config; _ephemeral = config.Ephemeral; _resources = resources; + _destructor = destructor; _loader = loader; _table = new ResourceWatcherTable(config.Ephemeral, _records); _resources.ResourceRequested += OnResourceRequested; - _resources.ResourceHandleDestructor += OnResourceDestroyed; + _destructor.Subscribe(OnResourceDestroyed, ResourceHandleDestructor.Priority.ResourceWatcher); _loader.ResourceLoaded += OnResourceLoaded; _loader.FileLoaded += OnFileLoaded; UpdateFilter(_ephemeral.ResourceLoggingFilter, false); @@ -54,7 +58,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService Clear(); _records.TrimExcess(); _resources.ResourceRequested -= OnResourceRequested; - _resources.ResourceHandleDestructor -= OnResourceDestroyed; + _destructor.Unsubscribe(OnResourceDestroyed); _loader.ResourceLoaded -= OnResourceLoaded; _loader.FileLoaded -= OnFileLoaded; } From c2e74ed382c494272fd7ee1a7474ba33fb504c9b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 25 Jun 2024 22:50:52 +0200 Subject: [PATCH 0713/1381] Improve signatures. --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/EstHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/GmpHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 3 ++- Penumbra/Interop/Hooks/Meta/RspTailHook.cs | 3 ++- 9 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 3fbc7045..4b55c05c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3fbc704515b7b5fa9be02fb2a44719fc333747c1 +Subproject commit 4b55c05c72eb194bec0d28c52cf076962010424b diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs index 583a2ac5..bfbe6866 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; @@ -15,7 +16,7 @@ public unsafe class EqdpAccessoryHook : FastHook, ID public EqdpAccessoryHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpAccessoryEntry", "E8 ?? ?? ?? ?? 41 BF ?? ?? ?? ?? 83 FB", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEqdpAccessoryEntry", Sigs.GetEqdpAccessoryEntry, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs index f5488f80..6ea38ee2 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; @@ -15,7 +16,7 @@ public unsafe class EqdpEquipHook : FastHook, IDisposabl public EqdpEquipHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpEquipEntry", "E8 ?? ?? ?? ?? 85 DB 75 ?? F6 45", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEqdpEquipEntry", Sigs.GetEqdpEquipEntry, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index e96d8115..19b870b0 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; @@ -14,7 +15,7 @@ public unsafe class EqpHook : FastHook, IDisposable public EqpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqpFlags", "E8 ?? ?? ?? ?? 0F B6 44 24 ?? C0 E8", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEqpFlags", Sigs.GetEqpEntry, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index fa0bb3c5..3fc7080f 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -1,4 +1,5 @@ using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; @@ -15,7 +16,7 @@ public class EstHook : FastHook, IDisposable public EstHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEstEntry", "44 8B C9 83 EA ?? 74", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEstEntry", Sigs.GetEstEntry, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 44d35f12..72c8d075 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -1,4 +1,5 @@ using OtterGui.Services; +using Penumbra.GameData; using Penumbra.Interop.PathResolving; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -16,7 +17,7 @@ public unsafe class GmpHook : FastHook, IDisposable public GmpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetGmpEntry", "E8 ?? ?? ?? ?? 48 85 C0 74 ?? 43 8D 0C", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetGmpEntry", Sigs.GetGmpEntry, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index db22d90c..d1019d3e 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -1,4 +1,5 @@ using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.Interop.PathResolving; using Penumbra.Meta; @@ -19,7 +20,7 @@ public unsafe class RspBustHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspBust", "E8 ?? ?? ?? ?? F2 0F 10 44 24 ?? 8B 44 24", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetRspBust", Sigs.GetRspBust, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index 98e39061..d54fe31e 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -1,4 +1,5 @@ using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.Interop.PathResolving; using Penumbra.Meta; @@ -18,7 +19,7 @@ public class RspHeightHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspHeight", "E8 ?? ?? ?? ?? 48 8B 8E ?? ?? ?? ?? 44 8B CF", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetRspHeight", Sigs.GetRspHeight, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs index 8d333575..8aa7ea9f 100644 --- a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs @@ -1,4 +1,5 @@ using OtterGui.Services; +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.Interop.PathResolving; using Penumbra.Meta; @@ -18,7 +19,7 @@ public class RspTailHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspTail", "E8 ?? ?? ?? ?? 0F 28 F0 48 8B 05", Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetRspTail", Sigs.GetRspTail, Detour, metaState.Config.EnableMods); _metaState.Config.ModsEnabled += Toggle; } From 221b18751d092a8138d5e8087cf6d9143e47f25f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 2 Jul 2024 17:08:27 +0200 Subject: [PATCH 0714/1381] Some updates. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Api/Api/RedrawApi.cs | 2 +- Penumbra/Api/Api/ResourceTreeApi.cs | 6 +- Penumbra/Api/IpcProviders.cs | 2 +- .../Api/IpcTester/CollectionsIpcTester.cs | 2 +- Penumbra/Api/IpcTester/EditingIpcTester.cs | 2 +- Penumbra/Api/IpcTester/GameStateIpcTester.cs | 7 +- Penumbra/Api/IpcTester/MetaIpcTester.cs | 2 +- .../Api/IpcTester/ModSettingsIpcTester.cs | 4 +- Penumbra/Api/IpcTester/ModsIpcTester.cs | 4 +- .../Api/IpcTester/PluginStateIpcTester.cs | 4 +- Penumbra/Api/IpcTester/RedrawingIpcTester.cs | 4 +- Penumbra/Api/IpcTester/ResolveIpcTester.cs | 2 +- .../Api/IpcTester/ResourceTreeIpcTester.cs | 2 +- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 2 +- Penumbra/Api/IpcTester/UiIpcTester.cs | 4 +- .../Manager/ActiveCollectionMigration.cs | 2 +- .../Collections/Manager/ActiveCollections.cs | 2 +- .../Collections/Manager/CollectionStorage.cs | 2 +- .../Manager/IndividualCollections.Access.cs | 2 +- .../Manager/IndividualCollections.Files.cs | 2 +- .../Collections/Manager/InheritanceManager.cs | 2 +- Penumbra/Configuration.cs | 2 +- Penumbra/EphemeralConfig.cs | 2 +- Penumbra/Import/Models/HavokConverter.cs | 5 +- Penumbra/Import/Textures/BaseImage.cs | 2 +- Penumbra/Import/Textures/TexFileParser.cs | 16 ++-- Penumbra/Import/Textures/Texture.cs | 2 +- Penumbra/Import/Textures/TextureDrawer.cs | 2 +- Penumbra/Import/Textures/TextureManager.cs | 8 +- .../Animation/ApricotListenerSoundPlay.cs | 2 +- .../Animation/CharacterBaseLoadAnimation.cs | 2 +- Penumbra/Interop/Hooks/Animation/Dismount.cs | 2 +- .../Interop/Hooks/Animation/LoadAreaVfx.cs | 2 +- .../Hooks/Animation/LoadCharacterSound.cs | 9 +- .../Hooks/Animation/LoadCharacterVfx.cs | 2 +- .../Hooks/Animation/LoadTimelineResources.cs | 2 +- .../Interop/Hooks/Animation/PlayFootstep.cs | 2 +- .../Hooks/Animation/ScheduleClipUpdate.cs | 2 +- .../Interop/Hooks/Animation/SomeActionLoad.cs | 10 +- .../Hooks/Animation/SomeMountAnimation.cs | 2 +- .../Interop/Hooks/Animation/SomePapLoad.cs | 2 +- .../Hooks/Animation/SomeParasolAnimation.cs | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 8 ++ .../Interop/Hooks/Meta/CalculateHeight.cs | 3 +- .../Interop/Hooks/Meta/ChangeCustomize.cs | 2 +- .../Interop/Hooks/Meta/EqdpAccessoryHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/EstHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs | 2 +- .../Interop/Hooks/Meta/GetEqpIndirect2.cs | 2 +- Penumbra/Interop/Hooks/Meta/GmpHook.cs | 2 +- .../Interop/Hooks/Meta/ModelLoadComplete.cs | 3 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 2 +- .../Interop/Hooks/Meta/RspSetupCharacter.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspTailHook.cs | 2 +- Penumbra/Interop/Hooks/Meta/SetupVisor.cs | 2 +- Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 2 +- .../Interop/Hooks/Objects/CopyCharacter.cs | 6 +- .../Interop/Hooks/Objects/WeaponReload.cs | 2 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 26 ++--- .../PathResolving/CollectionResolver.cs | 4 +- .../Interop/PathResolving/CutsceneService.cs | 5 +- .../ResourceLoading/FileReadService.cs | 4 +- .../ResourceLoading/ResourceManagerService.cs | 33 ++----- .../ResourceLoading/ResourceService.cs | 2 +- .../Interop/ResourceLoading/TexMdlService.cs | 96 +++++++++++-------- .../Interop/ResourceTree/ResolveContext.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- .../ResourceTree/ResourceTreeApiHelper.cs | 6 +- .../ResourceTree/ResourceTreeFactory.cs | 21 ++-- .../Interop/ResourceTree/TreeBuildCache.cs | 20 ++-- Penumbra/Interop/Services/FontReloader.cs | 4 +- Penumbra/Interop/Services/RedrawService.cs | 59 ++++++------ Penumbra/Interop/Structs/ClipScheduler.cs | 4 +- Penumbra/Interop/Structs/ResourceHandle.cs | 8 +- Penumbra/Meta/Files/MetaBaseFile.cs | 2 +- Penumbra/Mods/Editor/ModMerger.cs | 2 +- Penumbra/Mods/Editor/ModNormalizer.cs | 2 +- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 3 +- Penumbra/Mods/Manager/ModImportManager.cs | 2 +- .../Manager/OptionEditor/ModGroupEditor.cs | 2 +- Penumbra/Mods/ModCreator.cs | 2 +- Penumbra/Penumbra.cs | 4 +- Penumbra/Penumbra.csproj | 1 + Penumbra/Penumbra.json | 2 +- Penumbra/Services/DalamudConfigService.cs | 6 +- Penumbra/Services/FilenameService.cs | 2 +- Penumbra/Services/MessageService.cs | 4 +- Penumbra/Services/StaticServiceManager.cs | 4 +- Penumbra/Services/ValidityChecker.cs | 12 +-- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- .../ModEditWindow.Materials.MtrlTab.cs | 2 +- .../ModEditWindow.Materials.Shpk.cs | 2 +- .../ModEditWindow.ShaderPackages.cs | 2 +- Penumbra/UI/ChangedItemDrawer.cs | 29 +++--- Penumbra/UI/CollectionTab/CollectionPanel.cs | 8 +- Penumbra/UI/ConfigWindow.cs | 4 +- Penumbra/UI/LaunchButton.cs | 25 ++--- .../UI/ModsTab/Groups/ModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 2 +- Penumbra/UI/ModsTab/ModPanel.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelHeader.cs | 2 +- Penumbra/UI/PredefinedTagManager.cs | 2 +- .../UI/ResourceWatcher/ResourceWatcher.cs | 2 +- Penumbra/UI/Tabs/CollectionsTab.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 11 +-- Penumbra/UI/Tabs/ModsTab.cs | 2 +- Penumbra/UI/Tabs/ResourceTab.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 4 +- Penumbra/UI/UiHelpers.cs | 2 +- Penumbra/UI/WindowSystem.cs | 4 +- repo.json | 2 +- 121 files changed, 338 insertions(+), 328 deletions(-) create mode 100644 Penumbra/Interop/Hooks/HookSettings.cs diff --git a/OtterGui b/OtterGui index 6fafc03b..437ef65c 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 6fafc03b34971be7c0e74fd9a638d1ed642ea19a +Subproject commit 437ef65c6464c54c8f40196dd2428da901d73aab diff --git a/Penumbra.Api b/Penumbra.Api index f1e4e520..43b0b47f 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit f1e4e520daaa8f23e5c8b71d55e5992b8f6768e2 +Subproject commit 43b0b47f2d019af0fe4681dfc578f9232e3ba90c diff --git a/Penumbra.GameData b/Penumbra.GameData index 4b55c05c..3a97e5ae 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 4b55c05c72eb194bec0d28c52cf076962010424b +Subproject commit 3a97e5aeee3b7375b333c1add5305d0ce80cbf83 diff --git a/Penumbra.String b/Penumbra.String index caa58c5c..f04abbab 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit caa58c5c92710e69ce07b9d736ebe2d228cb4488 +Subproject commit f04abbabedf5e757c5cbb970f3e513fef23e53cf diff --git a/Penumbra/Api/Api/RedrawApi.cs b/Penumbra/Api/Api/RedrawApi.cs index 03b42493..82d14f7b 100644 --- a/Penumbra/Api/Api/RedrawApi.cs +++ b/Penumbra/Api/Api/RedrawApi.cs @@ -13,7 +13,7 @@ public class RedrawApi(RedrawService redrawService) : IPenumbraApiRedraw, IApiSe public void RedrawObject(string name, RedrawType setting) => redrawService.RedrawObject(name, setting); - public void RedrawObject(GameObject? gameObject, RedrawType setting) + public void RedrawObject(IGameObject? gameObject, RedrawType setting) => redrawService.RedrawObject(gameObject, setting); public void RedrawAll(RedrawType setting) diff --git a/Penumbra/Api/Api/ResourceTreeApi.cs b/Penumbra/Api/Api/ResourceTreeApi.cs index 6e9aaa48..dcec99bf 100644 --- a/Penumbra/Api/Api/ResourceTreeApi.cs +++ b/Penumbra/Api/Api/ResourceTreeApi.cs @@ -12,7 +12,7 @@ public class ResourceTreeApi(ResourceTreeFactory resourceTreeFactory, ObjectMana { public Dictionary>?[] GetGameObjectResourcePaths(params ushort[] gameObjects) { - var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); + var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); var resourceTrees = resourceTreeFactory.FromCharacters(characters, 0); var pathDictionaries = ResourceTreeApiHelper.GetResourcePathDictionaries(resourceTrees); @@ -28,7 +28,7 @@ public class ResourceTreeApi(ResourceTreeFactory resourceTreeFactory, ObjectMana public GameResourceDict?[] GetGameObjectResourcesOfType(ResourceType type, bool withUiData, params ushort[] gameObjects) { - var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); + var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); var resourceTrees = resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionaries = ResourceTreeApiHelper.GetResourcesOfType(resourceTrees, type); @@ -45,7 +45,7 @@ public class ResourceTreeApi(ResourceTreeFactory resourceTreeFactory, ObjectMana public JObject?[] GetGameObjectResourceTrees(bool withUiData, params ushort[] gameObjects) { - var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); + var characters = gameObjects.Select(index => objects.GetDalamudObject((int)index)).OfType(); var resourceTrees = resourceTreeFactory.FromCharacters(characters, withUiData ? ResourceTreeFactory.Flags.WithUiData : 0); var resDictionary = ResourceTreeApiHelper.EncapsulateResourceTrees(resourceTrees); diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 6b146c39..861225fa 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -12,7 +12,7 @@ public sealed class IpcProviders : IDisposable, IApiService private readonly EventProvider _disposedProvider; private readonly EventProvider _initializedProvider; - public IpcProviders(DalamudPluginInterface pi, IPenumbraApi api) + public IpcProviders(IDalamudPluginInterface pi, IPenumbraApi api) { _disposedProvider = IpcSubscribers.Disposed.Provider(pi); _initializedProvider = IpcSubscribers.Initialized.Provider(pi); diff --git a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs index 2679bc69..026fabbc 100644 --- a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs +++ b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs @@ -13,7 +13,7 @@ using ImGuiClip = OtterGui.ImGuiClip; namespace Penumbra.Api.IpcTester; -public class CollectionsIpcTester(DalamudPluginInterface pi) : IUiService +public class CollectionsIpcTester(IDalamudPluginInterface pi) : IUiService { private int _objectIdx; private string _collectionIdString = string.Empty; diff --git a/Penumbra/Api/IpcTester/EditingIpcTester.cs b/Penumbra/Api/IpcTester/EditingIpcTester.cs index 94b1e4e8..a1001630 100644 --- a/Penumbra/Api/IpcTester/EditingIpcTester.cs +++ b/Penumbra/Api/IpcTester/EditingIpcTester.cs @@ -8,7 +8,7 @@ using Penumbra.Api.IpcSubscribers; namespace Penumbra.Api.IpcTester; -public class EditingIpcTester(DalamudPluginInterface pi) : IUiService +public class EditingIpcTester(IDalamudPluginInterface pi) : IUiService { private string _inputPath = string.Empty; private string _inputPath2 = string.Empty; diff --git a/Penumbra/Api/IpcTester/GameStateIpcTester.cs b/Penumbra/Api/IpcTester/GameStateIpcTester.cs index 93806162..04541a57 100644 --- a/Penumbra/Api/IpcTester/GameStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/GameStateIpcTester.cs @@ -12,7 +12,7 @@ namespace Penumbra.Api.IpcTester; public class GameStateIpcTester : IUiService, IDisposable { - private readonly DalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; public readonly EventSubscriber CharacterBaseCreating; public readonly EventSubscriber CharacterBaseCreated; public readonly EventSubscriber GameObjectResourcePathResolved; @@ -30,7 +30,7 @@ public class GameStateIpcTester : IUiService, IDisposable private int _currentCutsceneParent; private PenumbraApiEc _cutsceneError = PenumbraApiEc.Success; - public GameStateIpcTester(DalamudPluginInterface pi) + public GameStateIpcTester(IDalamudPluginInterface pi) { _pi = pi; CharacterBaseCreating = IpcSubscribers.CreatingCharacterBase.Subscriber(pi, UpdateLastCreated); @@ -134,7 +134,6 @@ public class GameStateIpcTester : IUiService, IDisposable private static unsafe string GetObjectName(nint gameObject) { var obj = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)gameObject; - var name = obj != null ? obj->Name : null; - return name != null && *name != 0 ? new ByteString(name).ToString() : "Unknown"; + return obj != null && obj->Name[0] != 0 ? new ByteString(obj->Name).ToString() : "Unknown"; } } diff --git a/Penumbra/Api/IpcTester/MetaIpcTester.cs b/Penumbra/Api/IpcTester/MetaIpcTester.cs index 3fa7de7f..8b393ade 100644 --- a/Penumbra/Api/IpcTester/MetaIpcTester.cs +++ b/Penumbra/Api/IpcTester/MetaIpcTester.cs @@ -6,7 +6,7 @@ using Penumbra.Api.IpcSubscribers; namespace Penumbra.Api.IpcTester; -public class MetaIpcTester(DalamudPluginInterface pi) : IUiService +public class MetaIpcTester(IDalamudPluginInterface pi) : IUiService { private int _gameObjectIndex; diff --git a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs index b117d603..23078576 100644 --- a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs @@ -12,7 +12,7 @@ namespace Penumbra.Api.IpcTester; public class ModSettingsIpcTester : IUiService, IDisposable { - private readonly DalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; public readonly EventSubscriber SettingChanged; private PenumbraApiEc _lastSettingsError = PenumbraApiEc.Success; @@ -33,7 +33,7 @@ public class ModSettingsIpcTester : IUiService, IDisposable private IReadOnlyDictionary? _availableSettings; private Dictionary>? _currentSettings; - public ModSettingsIpcTester(DalamudPluginInterface pi) + public ModSettingsIpcTester(IDalamudPluginInterface pi) { _pi = pi; SettingChanged = ModSettingChanged.Subscriber(pi, UpdateLastModSetting); diff --git a/Penumbra/Api/IpcTester/ModsIpcTester.cs b/Penumbra/Api/IpcTester/ModsIpcTester.cs index 2be51a80..a24861a3 100644 --- a/Penumbra/Api/IpcTester/ModsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModsIpcTester.cs @@ -12,7 +12,7 @@ namespace Penumbra.Api.IpcTester; public class ModsIpcTester : IUiService, IDisposable { - private readonly DalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; private string _modDirectory = string.Empty; private string _modName = string.Empty; @@ -38,7 +38,7 @@ public class ModsIpcTester : IUiService, IDisposable private string _lastMovedModFrom = string.Empty; private string _lastMovedModTo = string.Empty; - public ModsIpcTester(DalamudPluginInterface pi) + public ModsIpcTester(IDalamudPluginInterface pi) { _pi = pi; DeleteSubscriber = ModDeleted.Subscriber(pi, s => diff --git a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs index 984f17b1..df82033d 100644 --- a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs @@ -12,7 +12,7 @@ namespace Penumbra.Api.IpcTester; public class PluginStateIpcTester : IUiService, IDisposable { - private readonly DalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; public readonly EventSubscriber ModDirectoryChanged; public readonly EventSubscriber Initialized; public readonly EventSubscriber Disposed; @@ -29,7 +29,7 @@ public class PluginStateIpcTester : IUiService, IDisposable private DateTimeOffset _lastEnabledChange = DateTimeOffset.UnixEpoch; private bool? _lastEnabledValue; - public PluginStateIpcTester(DalamudPluginInterface pi) + public PluginStateIpcTester(IDalamudPluginInterface pi) { _pi = pi; ModDirectoryChanged = IpcSubscribers.ModDirectoryChanged.Subscriber(pi, UpdateModDirectoryChanged); diff --git a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs index 801f0b97..b862dde5 100644 --- a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs +++ b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs @@ -13,14 +13,14 @@ namespace Penumbra.Api.IpcTester; public class RedrawingIpcTester : IUiService, IDisposable { - private readonly DalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; private readonly ObjectManager _objects; public readonly EventSubscriber Redrawn; private int _redrawIndex; private string _lastRedrawnString = "None"; - public RedrawingIpcTester(DalamudPluginInterface pi, ObjectManager objects) + public RedrawingIpcTester(IDalamudPluginInterface pi, ObjectManager objects) { _pi = pi; _objects = objects; diff --git a/Penumbra/Api/IpcTester/ResolveIpcTester.cs b/Penumbra/Api/IpcTester/ResolveIpcTester.cs index 978ed8d6..a79b099d 100644 --- a/Penumbra/Api/IpcTester/ResolveIpcTester.cs +++ b/Penumbra/Api/IpcTester/ResolveIpcTester.cs @@ -7,7 +7,7 @@ using Penumbra.String.Classes; namespace Penumbra.Api.IpcTester; -public class ResolveIpcTester(DalamudPluginInterface pi) : IUiService +public class ResolveIpcTester(IDalamudPluginInterface pi) : IUiService { private string _currentResolvePath = string.Empty; private string _currentReversePath = string.Empty; diff --git a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs index 1f57fc9d..088a77bd 100644 --- a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs +++ b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs @@ -15,7 +15,7 @@ using Penumbra.GameData.Structs; namespace Penumbra.Api.IpcTester; -public class ResourceTreeIpcTester(DalamudPluginInterface pi, ObjectManager objects) : IUiService +public class ResourceTreeIpcTester(IDalamudPluginInterface pi, ObjectManager objects) : IUiService { private readonly Stopwatch _stopwatch = new(); diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 0aa6821c..6d4f17b2 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -17,7 +17,7 @@ using Penumbra.Services; namespace Penumbra.Api.IpcTester; public class TemporaryIpcTester( - DalamudPluginInterface pi, + IDalamudPluginInterface pi, ModManager modManager, CollectionManager collections, TempModManager tempMods, diff --git a/Penumbra/Api/IpcTester/UiIpcTester.cs b/Penumbra/Api/IpcTester/UiIpcTester.cs index a2c36938..647a4dda 100644 --- a/Penumbra/Api/IpcTester/UiIpcTester.cs +++ b/Penumbra/Api/IpcTester/UiIpcTester.cs @@ -10,7 +10,7 @@ namespace Penumbra.Api.IpcTester; public class UiIpcTester : IUiService, IDisposable { - private readonly DalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; public readonly EventSubscriber PreSettingsTabBar; public readonly EventSubscriber PreSettingsPanel; public readonly EventSubscriber PostEnabled; @@ -28,7 +28,7 @@ public class UiIpcTester : IUiService, IDisposable private string _modName = string.Empty; private PenumbraApiEc _ec = PenumbraApiEc.Success; - public UiIpcTester(DalamudPluginInterface pi) + public UiIpcTester(IDalamudPluginInterface pi) { _pi = pi; PreSettingsTabBar = IpcSubscribers.PreSettingsTabBarDraw.Subscriber(pi, UpdateLastDrawnMod); diff --git a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs index 2f9e9b15..19f781fc 100644 --- a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui.Classes; diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 6d48f74b..60f9a427 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index cd680d36..a326fb92 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using OtterGui; using OtterGui.Classes; using OtterGui.Services; diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index 785f0013..6b90a333 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -127,7 +127,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa } } - public bool TryGetCollection(GameObject? gameObject, out ModCollection? collection) + public bool TryGetCollection(IGameObject? gameObject, out ModCollection? collection) => TryGetCollection(_actors.FromObject(gameObject, true, false, false), out collection); public unsafe bool TryGetCollection(FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject* gameObject, out ModCollection? collection) diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index 8a717b35..f7a26384 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -1,5 +1,5 @@ using Dalamud.Game.ClientState.Objects.Enums; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json.Linq; using OtterGui.Classes; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index f3482cdf..bc1a362c 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 7faed6a2..49aecfdc 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -1,5 +1,5 @@ using Dalamud.Configuration; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 52e276c7..7457c910 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using OtterGui.Classes; using OtterGui.Services; diff --git a/Penumbra/Import/Models/HavokConverter.cs b/Penumbra/Import/Models/HavokConverter.cs index dc9d3e6a..e3797083 100644 --- a/Penumbra/Import/Models/HavokConverter.cs +++ b/Penumbra/Import/Models/HavokConverter.cs @@ -1,4 +1,7 @@ -using FFXIVClientStructs.Havok; +using FFXIVClientStructs.Havok.Common.Base.System.IO.OStream; +using FFXIVClientStructs.Havok.Common.Base.Types; +using FFXIVClientStructs.Havok.Common.Serialize.Resource; +using FFXIVClientStructs.Havok.Common.Serialize.Util; namespace Penumbra.Import.Models; diff --git a/Penumbra/Import/Textures/BaseImage.cs b/Penumbra/Import/Textures/BaseImage.cs index a4a0e203..eba2d8ba 100644 --- a/Penumbra/Import/Textures/BaseImage.cs +++ b/Penumbra/Import/Textures/BaseImage.cs @@ -103,7 +103,7 @@ public readonly struct BaseImage : IDisposable { null => 0, ScratchImage s => s.Meta.MipLevels, - TexFile t => t.Header.MipLevelsCount, + TexFile t => t.Header.MipCount, _ => 1, }; } diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 6f854022..09025b61 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -79,8 +79,8 @@ public static class TexFileParser w.Write(header.Width); w.Write(header.Height); w.Write(header.Depth); - w.Write(header.MipLevelsCount); - w.Write((byte)0); // TODO Lumina Update + w.Write(header.MipCount); + w.Write(header.MipUnknownFlag); // TODO Lumina Update unsafe { w.Write(header.LodOffset[0]); @@ -96,11 +96,11 @@ public static class TexFileParser var meta = scratch.Meta; var ret = new TexFile.TexHeader() { - Height = (ushort)meta.Height, - Width = (ushort)meta.Width, - Depth = (ushort)Math.Max(meta.Depth, 1), - MipLevelsCount = (byte)Math.Min(meta.MipLevels, 13), - Format = meta.Format.ToTexFormat(), + Height = (ushort)meta.Height, + Width = (ushort)meta.Width, + Depth = (ushort)Math.Max(meta.Depth, 1), + MipCount = (byte)Math.Min(meta.MipLevels, 13), + Format = meta.Format.ToTexFormat(), Type = meta.Dimension switch { _ when meta.IsCubeMap => TexFile.Attribute.TextureTypeCube, @@ -143,7 +143,7 @@ public static class TexFileParser Height = header.Height, Width = header.Width, Depth = Math.Max(header.Depth, (ushort)1), - MipLevels = header.MipLevelsCount, + MipLevels = header.MipCount, ArraySize = 1, Format = header.Format.ToDXGI(), Dimension = header.Type.ToDimension(), diff --git a/Penumbra/Import/Textures/Texture.cs b/Penumbra/Import/Textures/Texture.cs index c4d6dc56..c5207e94 100644 --- a/Penumbra/Import/Textures/Texture.cs +++ b/Penumbra/Import/Textures/Texture.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal; +using Dalamud.Interface.Textures.TextureWraps; using OtterTex; namespace Penumbra.Import.Textures; diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index 427db92d..bd95d1ab 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -105,7 +105,7 @@ public static class TextureDrawer ImGuiUtil.DrawTableColumn("Format"); ImGuiUtil.DrawTableColumn(t.Header.Format.ToString()); ImGuiUtil.DrawTableColumn("Mip Levels"); - ImGuiUtil.DrawTableColumn(t.Header.MipLevelsCount.ToString()); + ImGuiUtil.DrawTableColumn(t.Header.MipCount.ToString()); ImGuiUtil.DrawTableColumn("Data Size"); ImGuiUtil.DrawTableColumn($"{Functions.HumanReadableSize(t.ImageData.Length)} ({t.ImageData.Length} Bytes)"); break; diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 4aa64209..cc785d02 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -1,5 +1,5 @@ -using Dalamud.Interface; -using Dalamud.Interface.Internal; +using Dalamud.Interface.Textures; +using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Services; using Lumina.Data.Files; using OtterGui.Log; @@ -13,7 +13,7 @@ using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; -public sealed class TextureManager(UiBuilder uiBuilder, IDataManager gameData, Logger logger) +public sealed class TextureManager(IDataManager gameData, Logger logger, ITextureProvider textureProvider) : SingleTaskQueue, IDisposable, IService { private readonly Logger _logger = logger; @@ -211,7 +211,7 @@ public sealed class TextureManager(UiBuilder uiBuilder, IDataManager gameData, L /// Load a texture wrap for a given image. public IDalamudTextureWrap LoadTextureWrap(byte[] rgba, int width, int height) - => uiBuilder.LoadImageRaw(rgba, width, height, 4); + => textureProvider.CreateFromRaw(RawImageSpecification.Rgba32(width, height), rgba, "Penumbra.Texture"); /// Load any supported file from game data or drive depending on extension and if the path is rooted. public (BaseImage, TextureType) Load(string path) diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index 77927593..e58c7268 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -21,7 +21,7 @@ public sealed unsafe class ApricotListenerSoundPlay : FastHook("Apricot Listener Sound Play", Sigs.ApricotListenerSoundPlay, Detour, true); + Task = hooks.CreateHook("Apricot Listener Sound Play", Sigs.ApricotListenerSoundPlay, Detour, HookSettings.VfxIdentificationHooks); } public delegate nint Delegate(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6); diff --git a/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs b/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs index df25358e..f99d8ca4 100644 --- a/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs +++ b/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs @@ -26,7 +26,7 @@ public sealed unsafe class CharacterBaseLoadAnimation : FastHook("CharacterBase Load Animation", Sigs.CharacterBaseLoadAnimation, Detour, true); + Task = hooks.CreateHook("CharacterBase Load Animation", Sigs.CharacterBaseLoadAnimation, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(DrawObject* drawBase); diff --git a/Penumbra/Interop/Hooks/Animation/Dismount.cs b/Penumbra/Interop/Hooks/Animation/Dismount.cs index 8085bcdb..523e750c 100644 --- a/Penumbra/Interop/Hooks/Animation/Dismount.cs +++ b/Penumbra/Interop/Hooks/Animation/Dismount.cs @@ -15,7 +15,7 @@ public sealed unsafe class Dismount : FastHook { _state = state; _collectionResolver = collectionResolver; - Task = hooks.CreateHook("Dismount", Sigs.Dismount, Detour, true); + Task = hooks.CreateHook("Dismount", Sigs.Dismount, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(nint a1, nint a2); diff --git a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs index 1a78d3b4..0f51157c 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs @@ -20,7 +20,7 @@ public sealed unsafe class LoadAreaVfx : FastHook _state = state; _collectionResolver = collectionResolver; _crashHandler = crashHandler; - Task = hooks.CreateHook("Load Area VFX", Sigs.LoadAreaVfx, Detour, true); + Task = hooks.CreateHook("Load Area VFX", Sigs.LoadAreaVfx, Detour, HookSettings.VfxIdentificationHooks); } public delegate nint Delegate(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3); diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs index 98454a77..ed04880e 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs @@ -1,3 +1,4 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.CrashHandler.Buffers; @@ -15,12 +16,10 @@ public sealed unsafe class LoadCharacterSound : FastHook("Load Character Sound", - (nint)FFXIVClientStructs.FFXIV.Client.Game.Character.Character.VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, - true); + _crashHandler = crashHandler; + Task = hooks.CreateHook("Load Character Sound", (nint)VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, HookSettings.VfxIdentificationHooks); } public delegate nint Delegate(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs index 77aaa742..af801345 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs @@ -26,7 +26,7 @@ public sealed unsafe class LoadCharacterVfx : FastHook("Load Character VFX", Sigs.LoadCharacterVfx, Detour, true); + Task = hooks.CreateHook("Load Character VFX", Sigs.LoadCharacterVfx, Detour, HookSettings.VfxIdentificationHooks); } public delegate nint Delegate(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4); diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index 018892a0..4e9037bd 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -30,7 +30,7 @@ public sealed unsafe class LoadTimelineResources : FastHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, true); + Task = hooks.CreateHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, HookSettings.VfxIdentificationHooks); } public delegate ulong Delegate(nint timeline); diff --git a/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs b/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs index 491d7662..e4a8c83c 100644 --- a/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs +++ b/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs @@ -14,7 +14,7 @@ public sealed unsafe class PlayFootstep : FastHook { _state = state; _collectionResolver = collectionResolver; - Task = hooks.CreateHook("Play Footstep", Sigs.FootStepSound, Detour, true); + Task = hooks.CreateHook("Play Footstep", Sigs.FootStepSound, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(GameObject* gameObject, int id, int unk); diff --git a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs index 342ffc25..645b3565 100644 --- a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs +++ b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs @@ -23,7 +23,7 @@ public sealed unsafe class ScheduleClipUpdate : FastHook("Schedule Clip Update", Sigs.ScheduleClipUpdate, Detour, true); + Task = hooks.CreateHook("Schedule Clip Update", Sigs.ScheduleClipUpdate, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(ClipScheduler* x); diff --git a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs index 6de3aeb0..1f3c0e3b 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs @@ -1,4 +1,4 @@ -using FFXIVClientStructs.FFXIV.Client.Game; +using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.CrashHandler.Buffers; @@ -20,15 +20,15 @@ public sealed unsafe class SomeActionLoad : FastHook _state = state; _collectionResolver = collectionResolver; _crashHandler = crashHandler; - Task = hooks.CreateHook("Some Action Load", Sigs.LoadSomeAction, Detour, true); + Task = hooks.CreateHook("Some Action Load", Sigs.LoadSomeAction, Detour, HookSettings.VfxIdentificationHooks); } - public delegate void Delegate(ActionTimelineManager* timelineManager); + public delegate void Delegate(TimelineContainer* timelineManager); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void Detour(ActionTimelineManager* timelineManager) + private void Detour(TimelineContainer* timelineManager) { - var newData = _collectionResolver.IdentifyCollection((GameObject*)timelineManager->Parent, true); + var newData = _collectionResolver.IdentifyCollection((GameObject*)timelineManager->OwnerObject, true); var last = _state.SetAnimationData(newData); Penumbra.Log.Excessive($"[Some Action Load] Invoked on 0x{(nint)timelineManager:X}."); _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.ActionLoad); diff --git a/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs b/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs index 5dd8227d..f2b48afe 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs @@ -15,7 +15,7 @@ public sealed unsafe class SomeMountAnimation : FastHook("Some Mount Animation", Sigs.UnkMountAnimation, Detour, true); + Task = hooks.CreateHook("Some Mount Animation", Sigs.UnkMountAnimation, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(DrawObject* drawObject, uint unk1, byte unk2, uint unk3); diff --git a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs index fad1f819..8f952df5 100644 --- a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs @@ -22,7 +22,7 @@ public sealed unsafe class SomePapLoad : FastHook _collectionResolver = collectionResolver; _objects = objects; _crashHandler = crashHandler; - Task = hooks.CreateHook("Some PAP Load", Sigs.LoadSomePap, Detour, true); + Task = hooks.CreateHook("Some PAP Load", Sigs.LoadSomePap, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(nint a1, int a2, nint a3, int a4); diff --git a/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs b/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs index ab4a7201..165bd5eb 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs @@ -15,7 +15,7 @@ public sealed unsafe class SomeParasolAnimation : FastHook("Some Parasol Animation", Sigs.UnkParasolAnimation, Detour, true); + Task = hooks.CreateHook("Some Parasol Animation", Sigs.UnkParasolAnimation, Detour, HookSettings.VfxIdentificationHooks); } public delegate void Delegate(DrawObject* drawObject, int unk1); diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs new file mode 100644 index 00000000..6d511a28 --- /dev/null +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -0,0 +1,8 @@ +namespace Penumbra.Interop.Hooks; + +public static class HookSettings +{ + public const bool MetaEntryHooks = false; + public const bool MetaParentHooks = false; + public const bool VfxIdentificationHooks = false; +} diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index 7936b831..aab64871 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -1,6 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; -using Penumbra.Collections; using Penumbra.Interop.PathResolving; using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; @@ -15,7 +14,7 @@ public sealed unsafe class CalculateHeight : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, true); + Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, HookSettings.MetaParentHooks); } public delegate ulong Delegate(Character* character); diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs index f589cf4e..f69e98e7 100644 --- a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -16,7 +16,7 @@ public sealed unsafe class ChangeCustomize : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Change Customize", Sigs.ChangeCustomize, Detour, true); + Task = hooks.CreateHook("Change Customize", Sigs.ChangeCustomize, Detour, HookSettings.MetaParentHooks); } public delegate bool Delegate(Human* human, CustomizeArray* data, byte skipEquipment); diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs index bfbe6866..63cca53f 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -16,7 +16,7 @@ public unsafe class EqdpAccessoryHook : FastHook, ID public EqdpAccessoryHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpAccessoryEntry", Sigs.GetEqdpAccessoryEntry, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEqdpAccessoryEntry", Sigs.GetEqdpAccessoryEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs index 6ea38ee2..5d5d2f84 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -16,7 +16,7 @@ public unsafe class EqdpEquipHook : FastHook, IDisposabl public EqdpEquipHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpEquipEntry", Sigs.GetEqdpEquipEntry, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEqdpEquipEntry", Sigs.GetEqdpEquipEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index 19b870b0..f47db795 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -15,7 +15,7 @@ public unsafe class EqpHook : FastHook, IDisposable public EqpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqpFlags", Sigs.GetEqpEntry, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEqpFlags", Sigs.GetEqpEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index 3fc7080f..5b272019 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -16,7 +16,7 @@ public class EstHook : FastHook, IDisposable public EstHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEstEntry", Sigs.GetEstEntry, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetEstEntry", Sigs.GetEstEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs index a10b511a..8bd49500 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs @@ -15,7 +15,7 @@ public sealed unsafe class GetEqpIndirect : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Get EQP Indirect", Sigs.GetEqpIndirect, Detour, true); + Task = hooks.CreateHook("Get EQP Indirect", Sigs.GetEqpIndirect, Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs index 30ec2597..3767c4a2 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs @@ -15,7 +15,7 @@ public sealed unsafe class GetEqpIndirect2 : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Get EQP Indirect 2", Sigs.GetEqpIndirect2, Detour, true); + Task = hooks.CreateHook("Get EQP Indirect 2", Sigs.GetEqpIndirect2, Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 72c8d075..329a8beb 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -17,7 +17,7 @@ public unsafe class GmpHook : FastHook, IDisposable public GmpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetGmpEntry", Sigs.GetGmpEntry, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetGmpEntry", Sigs.GetGmpEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs index 2c17362d..79e7f6a6 100644 --- a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -1,6 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; -using Penumbra.Collections; using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Meta; @@ -14,7 +13,7 @@ public sealed unsafe class ModelLoadComplete : FastHook("Model Load Complete", vtables.HumanVTable[58], Detour, true); + Task = hooks.CreateHook("Model Load Complete", vtables.HumanVTable[58], Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index d1019d3e..eb8a8a37 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -20,7 +20,7 @@ public unsafe class RspBustHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspBust", Sigs.GetRspBust, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetRspBust", Sigs.GetRspBust, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index d54fe31e..f8f9e51e 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -19,7 +19,7 @@ public class RspHeightHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspHeight", Sigs.GetRspHeight, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetRspHeight", Sigs.GetRspHeight, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs index 58856f52..8bcc7593 100644 --- a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs +++ b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs @@ -15,7 +15,7 @@ public sealed unsafe class RspSetupCharacter : FastHook("RSP Setup Character", Sigs.RspSetupCharacter, Detour, true); + Task = hooks.CreateHook("RSP Setup Character", Sigs.RspSetupCharacter, Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject, nint unk2, float unk3, nint unk4, byte unk5); diff --git a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs index 8aa7ea9f..86d21c6f 100644 --- a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs @@ -19,7 +19,7 @@ public class RspTailHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspTail", Sigs.GetRspTail, Detour, metaState.Config.EnableMods); + Task = hooks.CreateHook("GetRspTail", Sigs.GetRspTail, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs index 82b24dc4..83c0e0c4 100644 --- a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs +++ b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs @@ -19,7 +19,7 @@ public sealed unsafe class SetupVisor : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Setup Visor", Sigs.SetupVisor, Detour, true); + Task = hooks.CreateHook("Setup Visor", Sigs.SetupVisor, Detour, HookSettings.MetaParentHooks); } public delegate byte Delegate(DrawObject* drawObject, ushort modelId, byte visorState); diff --git a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs index 76854bca..a088a0f2 100644 --- a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs @@ -15,7 +15,7 @@ public sealed unsafe class UpdateModel : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Update Model", Sigs.UpdateModel, Detour, true); + Task = hooks.CreateHook("Update Model", Sigs.UpdateModel, Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs index 7b730f84..20c96f56 100644 --- a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs +++ b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs @@ -20,7 +20,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtr> _task; public nint Address - => (nint)CharacterSetup.MemberFunctionPointers.CopyFromCharacter; + => (nint)CharacterSetupContainer.MemberFunctionPointers.CopyFromCharacter; public void Enable() => _task.Result.Enable(); @@ -34,9 +34,9 @@ public sealed unsafe class CopyCharacter : EventWrapperPtr _task.IsCompletedSuccessfully; - private delegate ulong Delegate(CharacterSetup* target, Character* source, uint unk); + private delegate ulong Delegate(CharacterSetupContainer* target, Character* source, uint unk); - private ulong Detour(CharacterSetup* target, Character* source, uint unk) + private ulong Detour(CharacterSetupContainer* target, Character* source, uint unk) { // TODO: update when CS updated. var character = ((Character**)target)[1]; diff --git a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs index 31c6b883..fec0a13f 100644 --- a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs +++ b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs @@ -39,7 +39,7 @@ public sealed unsafe class WeaponReload : EventWrapperPtrParent; + var gameObject = drawData->OwnerObject; Penumbra.Log.Verbose($"[{Name}] Triggered with drawData: 0x{(nint)drawData:X}, {slot}, {weapon}, {d}, {e}, {f}, {g}."); Invoke(drawData, gameObject, (CharacterWeapon*)(&weapon)); _task.Result.Original(drawData, slot, weapon, d, e, f, g); diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 5941773f..a7e82b72 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -44,18 +44,20 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable { _parent = parent; // @formatter:off - _resolveDecalPathHook = Create($"{name}.{nameof(ResolveDecal)}", hooks, vTable[83], ResolveDecal); - _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[85], ResolveEid); - _resolveImcPathHook = Create($"{name}.{nameof(ResolveImc)}", hooks, vTable[81], ResolveImc); - _resolveMPapPathHook = Create( $"{name}.{nameof(ResolveMPap)}", hooks, vTable[79], ResolveMPap); - _resolveMdlPathHook = Create($"{name}.{nameof(ResolveMdl)}", hooks, vTable[73], type, ResolveMdl, ResolveMdlHuman); - _resolveMtrlPathHook = Create( $"{name}.{nameof(ResolveMtrl)}", hooks, vTable[82], ResolveMtrl); - _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[76], type, ResolvePap, ResolvePapHuman); - _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[75], type, ResolvePhyb, ResolvePhybHuman); - _resolveSklbPathHook = Create($"{name}.{nameof(ResolveSklb)}", hooks, vTable[72], type, ResolveSklb, ResolveSklbHuman); - _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[74], type, ResolveSkp, ResolveSkpHuman); - _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[77], ResolveTmb); - _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[84], type, ResolveVfx, ResolveVfxHuman); + _resolveSklbPathHook = Create($"{name}.{nameof(ResolveSklb)}", hooks, vTable[76], type, ResolveSklb, ResolveSklbHuman); + _resolveMdlPathHook = Create($"{name}.{nameof(ResolveMdl)}", hooks, vTable[77], type, ResolveMdl, ResolveMdlHuman); + _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[78], type, ResolveSkp, ResolveSkpHuman); + _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[79], type, ResolvePhyb, ResolvePhybHuman); + + + _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[84], type, ResolvePap, ResolvePapHuman); + _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[85], ResolveTmb); + _resolveMPapPathHook = Create( $"{name}.{nameof(ResolveMPap)}", hooks, vTable[87], ResolveMPap); + _resolveImcPathHook = Create($"{name}.{nameof(ResolveImc)}", hooks, vTable[89], ResolveImc); + _resolveMtrlPathHook = Create( $"{name}.{nameof(ResolveMtrl)}", hooks, vTable[90], ResolveMtrl); + _resolveDecalPathHook = Create($"{name}.{nameof(ResolveDecal)}", hooks, vTable[92], ResolveDecal); + _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[93], type, ResolveVfx, ResolveVfxHuman); + _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[94], ResolveEid); // @formatter:on Enable(); } diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index bc474952..136da0f5 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -120,7 +120,7 @@ public sealed unsafe class CollectionResolver( var lobby = AgentLobby.Instance(); if (lobby != null) { - var span = lobby->LobbyData.CharaSelectEntries.Span; + var span = lobby->LobbyData.CharaSelectEntries.AsSpan(); // The lobby uses the first 8 cutscene actors. var idx = gameObject->ObjectIndex - ObjectIndex.CutsceneStart.Index; if (idx >= 0 && idx < span.Length && span[idx].Value != null) @@ -148,7 +148,7 @@ public sealed unsafe class CollectionResolver( /// Used if at the aesthetician. The relevant actor is yourself, so use player collection when possible. private bool Aesthetician(GameObject* gameObject, out ResolveData ret) { - if (gameGui.GetAddonByName("ScreenLog") != IntPtr.Zero) + if (gameGui.GetAddonByName("ScreenLog") != nint.Zero) { ret = ResolveData.Invalid; return false; diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index feb27341..8e32dd76 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -1,3 +1,4 @@ +using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using OtterGui.Services; @@ -19,7 +20,7 @@ public sealed class CutsceneService : IRequiredService, IDisposable private readonly CharacterDestructor _characterDestructor; private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); - public IEnumerable> Actors + public IEnumerable> Actors => Enumerable.Range(CutsceneStartIdx, CutsceneSlots) .Where(i => _objects[i].Valid) .Select(i => KeyValuePair.Create(i, this[i] ?? _objects.GetDalamudObject(i)!)); @@ -42,7 +43,7 @@ public sealed class CutsceneService : IRequiredService, IDisposable /// Does not check for valid input index. /// Returns null if no connected actor is set or the actor does not exist anymore. /// - private Dalamud.Game.ClientState.Objects.Types.GameObject? this[int idx] + private IGameObject? this[int idx] { get { diff --git a/Penumbra/Interop/ResourceLoading/FileReadService.cs b/Penumbra/Interop/ResourceLoading/FileReadService.cs index f1d7fe24..5edba790 100644 --- a/Penumbra/Interop/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/ResourceLoading/FileReadService.cs @@ -63,7 +63,7 @@ public unsafe class FileReadService : IDisposable, IRequiredService byte? ret = null; _lastFileThreadResourceManager.Value = resourceManager; ReadSqPack?.Invoke(fileDescriptor, ref priority, ref isSync, ref ret); - _lastFileThreadResourceManager.Value = IntPtr.Zero; + _lastFileThreadResourceManager.Value = nint.Zero; return ret ?? _readSqPackHook.Original(resourceManager, fileDescriptor, priority, isSync); } @@ -82,7 +82,7 @@ public unsafe class FileReadService : IDisposable, IRequiredService /// So we keep track of them per thread and use them. /// private nint GetResourceManager() - => !_lastFileThreadResourceManager.IsValueCreated || _lastFileThreadResourceManager.Value == IntPtr.Zero + => !_lastFileThreadResourceManager.IsValueCreated || _lastFileThreadResourceManager.Value == nint.Zero ? (nint)_resourceManager.ResourceManager : _lastFileThreadResourceManager.Value; } diff --git a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs index c885c317..0479d2a6 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs @@ -25,8 +25,8 @@ public unsafe class ResourceManagerService : IRequiredService ref var manager = ref *ResourceManager; var catIdx = (uint)cat >> 0x18; cat = (ResourceCategory)(ushort)cat; - ref var category = ref manager.ResourceGraph->ContainerArraySpan[(int)cat]; - var extMap = FindInMap(category.CategoryMapsSpan[(int)catIdx].Value, (uint)ext); + ref var category = ref manager.ResourceGraph->Containers[(int)cat]; + var extMap = FindInMap(category.CategoryMaps[(int)catIdx].Value, (uint)ext); if (extMap == null) return null; @@ -44,10 +44,10 @@ public unsafe class ResourceManagerService : IRequiredService ref var manager = ref *ResourceManager; foreach (var resourceType in Enum.GetValues().SkipLast(1)) { - ref var graph = ref manager.ResourceGraph->ContainerArraySpan[(int)resourceType]; + ref var graph = ref manager.ResourceGraph->Containers[(int)resourceType]; for (var i = 0; i < 20; ++i) { - var map = graph.CategoryMapsSpan[i]; + var map = graph.CategoryMaps[i]; if (map.Value != null) action(resourceType, map, i); } @@ -79,25 +79,10 @@ public unsafe class ResourceManagerService : IRequiredService where TKey : unmanaged, IComparable where TValue : unmanaged { - if (map == null || map->Count == 0) + if (map == null) return null; - var node = map->Head->Parent; - while (!node->IsNil) - { - switch (key.CompareTo(node->KeyValuePair.Item1)) - { - case 0: return &node->KeyValuePair.Item2; - case < 0: - node = node->Left; - break; - default: - node = node->Right; - break; - } - } - - return null; + return map->TryGetValuePointer(key, out var val) ? val : null; } // Iterate in tree-order through a map, applying action to each KeyValuePair. @@ -105,10 +90,10 @@ public unsafe class ResourceManagerService : IRequiredService where TKey : unmanaged where TValue : unmanaged { - if (map == null || map->Count == 0) + if (map == null) return; - for (var node = map->SmallestValue; !node->IsNil; node = node->Next()) - action(node->KeyValuePair.Item1, node->KeyValuePair.Item2); + foreach (var (key, value) in *map) + action(key, value); } } diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/ResourceLoading/ResourceService.cs index 0947d2ec..d623d72d 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/ResourceLoading/ResourceService.cs @@ -127,7 +127,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService #endregion - private delegate IntPtr ResourceHandlePrototype(ResourceHandle* handle); + private delegate nint ResourceHandlePrototype(ResourceHandle* handle); #region IncRef diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/ResourceLoading/TexMdlService.cs index e617673e..a2b43c64 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/ResourceLoading/TexMdlService.cs @@ -1,6 +1,7 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.LayoutEngine; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Services; using Penumbra.Api.Enums; @@ -12,88 +13,99 @@ namespace Penumbra.Interop.ResourceLoading; public unsafe class TexMdlService : IDisposable, IRequiredService { /// Custom ulong flag to signal our files as opposed to SE files. - public static readonly IntPtr CustomFileFlag = new(0xDEADBEEF); - + public static readonly nint CustomFileFlag = new(0xDEADBEEF); + /// /// We need to keep a list of all CRC64 hash values of our replaced Mdl and Tex files, /// i.e. CRC32 of filename in the lower bytes, CRC32 of parent path in the upper bytes. /// public IReadOnlySet CustomFileCrc => _customFileCrc; - + public TexMdlService(IGameInteropProvider interop) { interop.InitializeFromAttributes(this); - _checkFileStateHook.Enable(); - _loadTexFileExternHook.Enable(); - _loadMdlFileExternHook.Enable(); + //_checkFileStateHook.Enable(); + //_loadTexFileExternHook.Enable(); + //_loadMdlFileExternHook.Enable(); } - + /// Add CRC64 if the given file is a model or texture file and has an associated path. public void AddCrc(ResourceType type, FullPath? path) { if (path.HasValue && type is ResourceType.Mdl or ResourceType.Tex) _customFileCrc.Add(path.Value.Crc64); } - + /// Add a fixed CRC64 value. public void AddCrc(ulong crc64) => _customFileCrc.Add(crc64); - + public void Dispose() { - _checkFileStateHook.Dispose(); - _loadTexFileExternHook.Dispose(); - _loadMdlFileExternHook.Dispose(); + //_checkFileStateHook.Dispose(); + //_loadTexFileExternHook.Dispose(); + //_loadMdlFileExternHook.Dispose(); } - + private readonly HashSet _customFileCrc = new(); - - private delegate IntPtr CheckFileStatePrototype(IntPtr unk1, ulong crc64); - + + private delegate nint CheckFileStatePrototype(nint unk1, ulong crc64); + [Signature(Sigs.CheckFileState, DetourName = nameof(CheckFileStateDetour))] private readonly Hook _checkFileStateHook = null!; - + /// /// The function that checks a files CRC64 to determine whether it is 'protected'. /// We use it to check against our stored CRC64s and if it corresponds, we return the custom flag. /// - private IntPtr CheckFileStateDetour(IntPtr ptr, ulong crc64) + private nint CheckFileStateDetour(nint ptr, ulong crc64) => _customFileCrc.Contains(crc64) ? CustomFileFlag : _checkFileStateHook.Original(ptr, crc64); - - - private delegate byte LoadTexFileLocalDelegate(ResourceHandle* handle, int unk1, IntPtr unk2, bool unk3); - + + + private delegate byte LoadTexFileLocalDelegate(ResourceHandle* handle, int unk1, nint unk2, bool unk3); + /// We use the local functions for our own files in the extern hook. [Signature(Sigs.LoadTexFileLocal)] private readonly LoadTexFileLocalDelegate _loadTexFileLocal = null!; - - private delegate byte LoadMdlFileLocalPrototype(ResourceHandle* handle, IntPtr unk1, bool unk2); - + + private delegate byte LoadMdlFileLocalPrototype(ResourceHandle* handle, nint unk1, bool unk2); + /// We use the local functions for our own files in the extern hook. [Signature(Sigs.LoadMdlFileLocal)] private readonly LoadMdlFileLocalPrototype _loadMdlFileLocal = null!; - - - private delegate byte LoadTexFileExternPrototype(ResourceHandle* handle, int unk1, IntPtr unk2, bool unk3, IntPtr unk4); - - [Signature(Sigs.LoadTexFileExtern, DetourName = nameof(LoadTexFileExternDetour))] - private readonly Hook _loadTexFileExternHook = null!; - + + + private delegate byte LoadTexFileExternPrototype(ResourceHandle* handle, int unk1, nint unk2, bool unk3, nint unk4); + + private delegate byte TexResourceHandleVf32Prototype(ResourceHandle* handle, nint unk1, byte unk2); + + //[Signature("40 53 55 41 54 41 55 41 56 41 57 48 81 EC ?? ?? ?? ?? 48 8B D9", DetourName = nameof(Vf32Detour))] + //private readonly Hook _vf32Hook = null!; + // + //private byte Vf32Detour(ResourceHandle* handle, nint unk1, byte unk2) + //{ + // var ret = _vf32Hook.Original(handle, unk1, unk2); + // return _loadTexFileLocal() + //} + + //[Signature(Sigs.LoadTexFileExtern, DetourName = nameof(LoadTexFileExternDetour))] + //private readonly Hook _loadTexFileExternHook = null!; + /// We hook the extern functions to just return the local one if given the custom flag as last argument. - private byte LoadTexFileExternDetour(ResourceHandle* resourceHandle, int unk1, IntPtr unk2, bool unk3, IntPtr ptr) - => ptr.Equals(CustomFileFlag) - ? _loadTexFileLocal.Invoke(resourceHandle, unk1, unk2, unk3) - : _loadTexFileExternHook.Original(resourceHandle, unk1, unk2, unk3, ptr); - - public delegate byte LoadMdlFileExternPrototype(ResourceHandle* handle, IntPtr unk1, bool unk2, IntPtr unk3); - - + //private byte LoadTexFileExternDetour(ResourceHandle* resourceHandle, int unk1, nint unk2, bool unk3, nint ptr) + // => ptr.Equals(CustomFileFlag) + // ? _loadTexFileLocal.Invoke(resourceHandle, unk1, unk2, unk3) + // : _loadTexFileExternHook.Original(resourceHandle, unk1, unk2, unk3, ptr); + + public delegate byte LoadMdlFileExternPrototype(ResourceHandle* handle, nint unk1, bool unk2, nint unk3); + + [Signature(Sigs.LoadMdlFileExtern, DetourName = nameof(LoadMdlFileExternDetour))] private readonly Hook _loadMdlFileExternHook = null!; - + /// We hook the extern functions to just return the local one if given the custom flag as last argument. - private byte LoadMdlFileExternDetour(ResourceHandle* resourceHandle, IntPtr unk1, bool unk2, IntPtr ptr) + private byte LoadMdlFileExternDetour(ResourceHandle* resourceHandle, nint unk1, bool unk2, nint ptr) => ptr.Equals(CustomFileFlag) ? _loadMdlFileLocal.Invoke(resourceHandle, unk1, unk2) : _loadMdlFileExternHook.Original(resourceHandle, unk1, unk2, ptr); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index e38bf4f6..ca8836b0 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -111,7 +111,7 @@ internal unsafe partial record ResolveContext( if (resourceHandle == null) throw new ArgumentNullException(nameof(resourceHandle)); - var fileName = resourceHandle->FileName.AsSpan(); + var fileName = (ReadOnlySpan) resourceHandle->FileName.AsSpan(); var additionalData = ByteString.Empty; if (PathDataHandler.Split(fileName, out fileName, out var data)) additionalData = ByteString.FromSpanUnsafe(data, false).Clone(); diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index fc8c805a..b8bad84a 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -62,7 +62,7 @@ public class ResourceTree var equipment = modelType switch { CharacterBase.ModelType.Human => new ReadOnlySpan(&human->Head, 10), - CharacterBase.ModelType.DemiHuman => new ReadOnlySpan(&character->DrawData.Head, 10), + CharacterBase.ModelType.DemiHuman => new ReadOnlySpan(Unsafe.AsPointer(ref character->DrawData.EquipmentModelIds[0]), 10), _ => ReadOnlySpan.Empty, }; ModelId = character->CharacterData.ModelCharaId; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index 0d1e3abc..22025dd6 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -10,7 +10,7 @@ namespace Penumbra.Interop.ResourceTree; internal static class ResourceTreeApiHelper { public static Dictionary>> GetResourcePathDictionaries( - IEnumerable<(Character, ResourceTree)> resourceTrees) + IEnumerable<(ICharacter, ResourceTree)> resourceTrees) { var pathDictionaries = new Dictionary>>(4); @@ -47,7 +47,7 @@ internal static class ResourceTreeApiHelper } } - public static Dictionary GetResourcesOfType(IEnumerable<(Character, ResourceTree)> resourceTrees, + public static Dictionary GetResourcesOfType(IEnumerable<(ICharacter, ResourceTree)> resourceTrees, ResourceType type) { var resDictionaries = new Dictionary(4); @@ -74,7 +74,7 @@ internal static class ResourceTreeApiHelper return resDictionaries; } - public static Dictionary EncapsulateResourceTrees(IEnumerable<(Character, ResourceTree)> resourceTrees) + public static Dictionary EncapsulateResourceTrees(IEnumerable<(ICharacter, ResourceTree)> resourceTrees) { var resDictionary = new Dictionary(4); foreach (var (gameObject, resourceTree) in resourceTrees) diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index e26c1436..1f6d1f6f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -1,3 +1,4 @@ +using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; @@ -23,13 +24,13 @@ public class ResourceTreeFactory( private TreeBuildCache CreateTreeBuildCache() => new(objects, gameData, actors); - public IEnumerable GetLocalPlayerRelatedCharacters() + public IEnumerable GetLocalPlayerRelatedCharacters() { var cache = CreateTreeBuildCache(); return cache.GetLocalPlayerRelatedCharacters(); } - public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromObjectTable( + public IEnumerable<(ICharacter Character, ResourceTree ResourceTree)> FromObjectTable( Flags flags) { var cache = CreateTreeBuildCache(); @@ -43,8 +44,8 @@ public class ResourceTreeFactory( } } - public IEnumerable<(Dalamud.Game.ClientState.Objects.Types.Character Character, ResourceTree ResourceTree)> FromCharacters( - IEnumerable characters, Flags flags) + public IEnumerable<(ICharacter Character, ResourceTree ResourceTree)> FromCharacters( + IEnumerable characters, Flags flags) { var cache = CreateTreeBuildCache(); foreach (var character in characters) @@ -55,10 +56,10 @@ public class ResourceTreeFactory( } } - public ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, Flags flags) + public ResourceTree? FromCharacter(ICharacter character, Flags flags) => FromCharacter(character, CreateTreeBuildCache(), flags); - private unsafe ResourceTree? FromCharacter(Dalamud.Game.ClientState.Objects.Types.Character character, TreeBuildCache cache, Flags flags) + private unsafe ResourceTree? FromCharacter(ICharacter character, TreeBuildCache cache, Flags flags) { if (!character.IsValid()) return null; @@ -74,7 +75,7 @@ public class ResourceTreeFactory( var localPlayerRelated = cache.IsLocalPlayerRelated(character); var (name, anonymizedName, related) = GetCharacterName(character); - var networked = character.ObjectId != Dalamud.Game.ClientState.Objects.Types.GameObject.InvalidGameObjectId; + var networked = character.EntityId != 0xE0000000; var tree = new ResourceTree(name, anonymizedName, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name, collectionResolveData.ModCollection.AnonymizedName); var globalContext = new GlobalResolveContext(identifier, collectionResolveData.ModCollection, @@ -155,14 +156,14 @@ public class ResourceTreeFactory( } } - private unsafe (string Name, string AnonymizedName, bool PlayerRelated) GetCharacterName(Dalamud.Game.ClientState.Objects.Types.Character character) + private unsafe (string Name, string AnonymizedName, bool PlayerRelated) GetCharacterName(ICharacter character) { var identifier = actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); var identifierStr = identifier.ToString(); return (identifierStr, identifier.Incognito(identifierStr), IsPlayerRelated(identifier, owner)); } - private unsafe bool IsPlayerRelated(Dalamud.Game.ClientState.Objects.Types.Character? character) + private unsafe bool IsPlayerRelated(ICharacter? character) { if (character == null) return false; @@ -175,7 +176,7 @@ public class ResourceTreeFactory( => identifier.Type switch { IdentifierType.Player => true, - IdentifierType.Owned => IsPlayerRelated(objects.Objects.CreateObjectReference(owner) as Dalamud.Game.ClientState.Objects.Types.Character), + IdentifierType.Owned => IsPlayerRelated(objects.Objects.CreateObjectReference(owner) as ICharacter), _ => false, }; diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 2798002a..ca5ff736 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -13,7 +13,7 @@ internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager data { private readonly Dictionary _shaderPackages = []; - public unsafe bool IsLocalPlayerRelated(Character character) + public unsafe bool IsLocalPlayerRelated(ICharacter character) { var player = objects.GetDalamudObject(0); if (player == null) @@ -25,36 +25,36 @@ internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager data return actualIndex switch { < 2 => true, - < (int)ScreenActor.CutsceneStart => gameObject->OwnerID == player.ObjectId, + < (int)ScreenActor.CutsceneStart => gameObject->OwnerId == player.EntityId, _ => false, }; } - public IEnumerable GetCharacters() - => objects.Objects.OfType(); + public IEnumerable GetCharacters() + => objects.Objects.OfType(); - public IEnumerable GetLocalPlayerRelatedCharacters() + public IEnumerable GetLocalPlayerRelatedCharacters() { var player = objects.GetDalamudObject(0); if (player == null) yield break; - yield return (Character)player; + yield return (ICharacter)player; var minion = objects.GetDalamudObject(1); if (minion != null) - yield return (Character)minion; + yield return (ICharacter)minion; - var playerId = player.ObjectId; + var playerId = player.EntityId; for (var i = 2; i < ObjectIndex.CutsceneStart.Index; i += 2) { - if (objects.GetDalamudObject(i) is Character owned && owned.OwnerId == playerId) + if (objects.GetDalamudObject(i) is ICharacter owned && owned.OwnerId == playerId) yield return owned; } for (var i = ObjectIndex.CutsceneStart.Index; i < ObjectIndex.CharacterScreen.Index; ++i) { - var character = objects.GetDalamudObject((int) i) as Character; + var character = objects.GetDalamudObject((int) i) as ICharacter; if (character == null) continue; diff --git a/Penumbra/Interop/Services/FontReloader.cs b/Penumbra/Interop/Services/FontReloader.cs index 259fdd10..4f48f08f 100644 --- a/Penumbra/Interop/Services/FontReloader.cs +++ b/Penumbra/Interop/Services/FontReloader.cs @@ -34,7 +34,7 @@ public unsafe class FontReloader : IService if (framework == null) return; - var uiModule = framework->GetUiModule(); + var uiModule = framework->GetUIModule(); if (uiModule == null) return; @@ -43,7 +43,7 @@ public unsafe class FontReloader : IService return; _atkModule = &atkModule->AtkModule; - _reloadFontsFunc = ((delegate* unmanaged*)_atkModule->vtbl)[Offsets.ReloadFontsVfunc]; + _reloadFontsFunc = ((delegate* unmanaged*)_atkModule->VirtualTable)[Offsets.ReloadFontsVfunc]; }); } } diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 61d7b90c..163b2c0e 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -4,8 +4,8 @@ using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; -using FFXIVClientStructs.FFXIV.Client.Game.Housing; -using FFXIVClientStructs.Interop; +using FFXIVClientStructs.FFXIV.Client.Game; +using FFXIVClientStructs.FFXIV.Client.Game.Character; using OtterGui.Services; using Penumbra.Api; using Penumbra.Api.Enums; @@ -37,11 +37,11 @@ public unsafe partial class RedrawService : IService => _clientState.IsGPosing; // VFuncs that disable and enable draw, used only for GPose actors. - private static void DisableDraw(GameObject actor) - => ((delegate* unmanaged< IntPtr, void >**)actor.Address)[0][Offsets.DisableDrawVfunc](actor.Address); + private static void DisableDraw(IGameObject actor) + => ((delegate* unmanaged**)actor.Address)[0][Offsets.DisableDrawVfunc](actor.Address); - private static void EnableDraw(GameObject actor) - => ((delegate* unmanaged< IntPtr, void >**)actor.Address)[0][Offsets.EnableDrawVfunc](actor.Address); + private static void EnableDraw(IGameObject actor) + => ((delegate* unmanaged**)actor.Address)[0][Offsets.EnableDrawVfunc](actor.Address); // Check whether we currently are in GPose. // Also clear the name list. @@ -57,7 +57,7 @@ public unsafe partial class RedrawService : IService // obj will be the object itself (or null) and false will be returned. // If we are in GPose and a game object with the same name as the original actor is found, // this will be in obj and true will be returned. - private bool FindCorrectActor(int idx, out GameObject? obj) + private bool FindCorrectActor(int idx, out IGameObject? obj) { obj = _objects.GetDalamudObject(idx); if (!InGPose || obj == null || IsGPoseActor(idx)) @@ -91,11 +91,11 @@ public unsafe partial class RedrawService : IService } } - return obj; + return false; } // Do not ever redraw any of the five UI Window actors. - private static bool BadRedrawIndices(GameObject? actor, out int tableIndex) + private static bool BadRedrawIndices(IGameObject? actor, out int tableIndex) { if (actor == null) { @@ -155,13 +155,13 @@ public sealed unsafe partial class RedrawService : IDisposable _communicator.ModFileChanged.Unsubscribe(OnModFileChanged); } - public static DrawState* ActorDrawState(GameObject actor) + public static DrawState* ActorDrawState(IGameObject actor) => (DrawState*)(&((FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)actor.Address)->RenderFlags); - private static int ObjectTableIndex(GameObject actor) + private static int ObjectTableIndex(IGameObject actor) => ((FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)actor.Address)->ObjectIndex; - private void WriteInvisible(GameObject? actor) + private void WriteInvisible(IGameObject? actor) { if (BadRedrawIndices(actor, out var tableIndex)) return; @@ -172,7 +172,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) DisableDraw(actor!); - if (actor is PlayerCharacter + if (actor is IPlayerCharacter && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { *ActorDrawState(mountOrOrnament) |= DrawState.Invisibility; @@ -181,7 +181,7 @@ public sealed unsafe partial class RedrawService : IDisposable } } - private void WriteVisible(GameObject? actor) + private void WriteVisible(IGameObject? actor) { if (BadRedrawIndices(actor, out var tableIndex)) return; @@ -192,7 +192,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (gPose) EnableDraw(actor!); - if (actor is PlayerCharacter + if (actor is IPlayerCharacter && _objects.GetDalamudObject(tableIndex + 1) is { ObjectKind: ObjectKind.MountType or ObjectKind.Ornament } mountOrOrnament) { *ActorDrawState(mountOrOrnament) &= ~DrawState.Invisibility; @@ -203,7 +203,7 @@ public sealed unsafe partial class RedrawService : IDisposable GameObjectRedrawn?.Invoke(actor!.Address, tableIndex); } - private void ReloadActor(GameObject? actor) + private void ReloadActor(IGameObject? actor) { if (BadRedrawIndices(actor, out var tableIndex)) return; @@ -214,7 +214,7 @@ public sealed unsafe partial class RedrawService : IDisposable _queue.Add(~tableIndex); } - private void ReloadActorAfterGPose(GameObject? actor) + private void ReloadActorAfterGPose(IGameObject? actor) { if (_objects[GPosePlayerIdx].Valid) { @@ -284,21 +284,21 @@ public sealed unsafe partial class RedrawService : IDisposable _queue.RemoveRange(numKept, _queue.Count - numKept); } - private static uint GetCurrentAnimationId(GameObject obj) + private static uint GetCurrentAnimationId(IGameObject obj) { var gameObj = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)obj.Address; if (gameObj == null || !gameObj->IsCharacter()) return 0; var chara = (Character*)gameObj; - var ptr = (byte*)&chara->ActionTimelineManager + 0xF0; + var ptr = (byte*)&chara->Timeline + 0xF0; return *(uint*)ptr; } - private static bool DelayRedraw(GameObject obj) + private static bool DelayRedraw(IGameObject obj) => ((Character*)obj.Address)->Mode switch { - (Character.CharacterModes)6 => // fishing + (CharacterModes)6 => // fishing GetCurrentAnimationId(obj) switch { 278 => true, // line out. @@ -345,7 +345,7 @@ public sealed unsafe partial class RedrawService : IDisposable HandleTarget(); } - public void RedrawObject(GameObject? actor, RedrawType settings) + public void RedrawObject(IGameObject? actor, RedrawType settings) { switch (settings) { @@ -359,13 +359,13 @@ public sealed unsafe partial class RedrawService : IDisposable } } - private GameObject? GetLocalPlayer() + private IGameObject? GetLocalPlayer() { var gPosePlayer = _objects.GetDalamudObject(GPosePlayerIdx); return gPosePlayer ?? _objects.GetDalamudObject(0); } - public bool GetName(string lowerName, out GameObject? actor) + public bool GetName(string lowerName, out IGameObject? actor) { (actor, var ret) = lowerName switch { @@ -419,15 +419,14 @@ public sealed unsafe partial class RedrawService : IDisposable if (housingManager == null) return; - var currentTerritory = housingManager->CurrentTerritory; - if (currentTerritory == null) - return; - if (!housingManager->IsInside()) + var currentTerritory = (OutdoorTerritory*) housingManager->CurrentTerritory; + if (currentTerritory == null || currentTerritory->GetTerritoryType() is not HousingTerritoryType.Outdoor) return; - foreach (var f in currentTerritory->FurnitureSpan.PointerEnumerator()) + + foreach (ref var f in currentTerritory->Furniture) { - var gameObject = f->Index >= 0 ? currentTerritory->HousingObjectManager.ObjectsSpan[f->Index].Value : null; + var gameObject = f.Index >= 0 ? currentTerritory->HousingObjectManager.Objects[f.Index].Value : null; if (gameObject == null) continue; diff --git a/Penumbra/Interop/Structs/ClipScheduler.cs b/Penumbra/Interop/Structs/ClipScheduler.cs index 3211c4f9..44a905b8 100644 --- a/Penumbra/Interop/Structs/ClipScheduler.cs +++ b/Penumbra/Interop/Structs/ClipScheduler.cs @@ -4,8 +4,8 @@ namespace Penumbra.Interop.Structs; public unsafe struct ClipScheduler { [FieldOffset(0)] - public IntPtr* VTable; + public nint* VTable; [FieldOffset(0x38)] - public IntPtr SchedulerTimeline; + public nint SchedulerTimeline; } diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 382368b4..058b9004 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -83,12 +83,12 @@ public unsafe struct ResourceHandle [FieldOffset(0xB8)] public uint DataLength; - public (IntPtr Data, int Length) GetData() + public (nint Data, int Length) GetData() => Data != null - ? ((IntPtr)Data->DataPtr, (int)Data->DataLength) - : (IntPtr.Zero, 0); + ? ((nint)Data->DataPtr, (int)Data->DataLength) + : (nint.Zero, 0); - public bool SetData(IntPtr data, int length) + public bool SetData(nint data, int length) { if (Data == null) return false; diff --git a/Penumbra/Meta/Files/MetaBaseFile.cs b/Penumbra/Meta/Files/MetaBaseFile.cs index 86a55101..5bc36068 100644 --- a/Penumbra/Meta/Files/MetaBaseFile.cs +++ b/Penumbra/Meta/Files/MetaBaseFile.cs @@ -71,7 +71,7 @@ public unsafe class MetaBaseFile(MetaFileManager manager, IFileAllocator alloc, public int Length { get; private set; } public CharacterUtility.InternalIndex Index { get; } = CharacterUtility.ReverseIndices[(int)idx]; - protected (IntPtr Data, int Length) DefaultData + protected (nint Data, int Length) DefaultData => Manager.CharacterUtility.DefaultResource(Index); /// Reset to default values. diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 9d31664b..b059813b 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Utility; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index c6bc4939..c0876f5d 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using OtterGui; using OtterGui.Classes; using OtterGui.Services; diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index c52828c0..46204d6c 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 220d0a7c..95f49230 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -1,10 +1,9 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; using Penumbra.Api.Enums; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index ff39b021..39a53bb9 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using OtterGui.Classes; using OtterGui.Services; using Penumbra.Import; diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 594ec9d2..712630c6 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 0e66367a..546f5f5c 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 38d9c7b2..b1ad0b78 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -48,7 +48,7 @@ public class Penumbra : IDalamudPlugin private readonly ServiceManager _services; - public Penumbra(DalamudPluginInterface pluginInterface) + public Penumbra(IDalamudPluginInterface pluginInterface) { try { @@ -182,7 +182,7 @@ public class Penumbra : IDalamudPlugin [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", ]; - var plugins = _services.GetService().InstalledPlugins + var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) .ToDictionary(g => g.Key, g => { diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 2e53bd22..ed5c5e30 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -37,6 +37,7 @@ $(AppData)\XIVLauncher\addon\Hooks\dev\ + H:\Projects\FFPlugins\Dalamud\bin\Release\ diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 85e01c84..805f4d85 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -8,7 +8,7 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], - "DalamudApiLevel": 9, + "DalamudApiLevel": 10, "LoadPriority": 69420, "LoadState": 2, "LoadSync": true, diff --git a/Penumbra/Services/DalamudConfigService.cs b/Penumbra/Services/DalamudConfigService.cs index 8379a3e7..012a45f5 100644 --- a/Penumbra/Services/DalamudConfigService.cs +++ b/Penumbra/Services/DalamudConfigService.cs @@ -10,9 +10,9 @@ public class DalamudConfigService : IService try { var serviceType = - typeof(DalamudPluginInterface).Assembly.DefinedTypes.FirstOrDefault(t => t.Name == "Service`1" && t.IsGenericType); - var configType = typeof(DalamudPluginInterface).Assembly.DefinedTypes.FirstOrDefault(t => t.Name == "DalamudConfiguration"); - var interfaceType = typeof(DalamudPluginInterface).Assembly.DefinedTypes.FirstOrDefault(t => t.Name == "DalamudInterface"); + typeof(IDalamudPluginInterface).Assembly.DefinedTypes.FirstOrDefault(t => t.Name == "Service`1" && t.IsGenericType); + var configType = typeof(IDalamudPluginInterface).Assembly.DefinedTypes.FirstOrDefault(t => t.Name == "DalamudConfiguration"); + var interfaceType = typeof(IDalamudPluginInterface).Assembly.DefinedTypes.FirstOrDefault(t => t.Name == "DalamudInterface"); if (serviceType == null || configType == null || interfaceType == null) return; diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index e1c482f7..817af0d2 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -5,7 +5,7 @@ using Penumbra.Mods; namespace Penumbra.Services; -public class FilenameService(DalamudPluginInterface pi) : IService +public class FilenameService(IDalamudPluginInterface pi) : IService { public readonly string ConfigDirectory = pi.ConfigDirectory.FullName; public readonly string CollectionDirectory = Path.Combine(pi.ConfigDirectory.FullName, "collections"); diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index 0a85a569..08118483 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -9,8 +9,8 @@ using OtterGui.Services; namespace Penumbra.Services; -public class MessageService(Logger log, UiBuilder uiBuilder, IChatGui chat, INotificationManager notificationManager) - : OtterGui.Classes.MessageService(log, uiBuilder, chat, notificationManager), IService +public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INotificationManager notificationManager) + : OtterGui.Classes.MessageService(log, builder, chat, notificationManager), IService { public void LinkItem(Item item) { diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 3279da96..c0dc9314 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -19,7 +19,7 @@ namespace Penumbra.Services; public static class StaticServiceManager { - public static ServiceManager CreateProvider(Penumbra penumbra, DalamudPluginInterface pi, Logger log) + public static ServiceManager CreateProvider(Penumbra penumbra, IDalamudPluginInterface pi, Logger log) { var services = new ServiceManager(log) .AddDalamudServices(pi) @@ -40,7 +40,7 @@ public static class StaticServiceManager return services; } - private static ServiceManager AddDalamudServices(this ServiceManager services, DalamudPluginInterface pi) + private static ServiceManager AddDalamudServices(this ServiceManager services, IDalamudPluginInterface pi) => services.AddExistingService(pi) .AddExistingService(pi.UiBuilder) .AddDalamudService(pi) diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index cc70306b..cefee139 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin; using FFXIVClientStructs.FFXIV.Client.System.Framework; using OtterGui.Classes; @@ -27,11 +27,11 @@ public class ValidityChecker : IService get { var framework = Framework.Instance(); - return framework == null ? string.Empty : framework->GameVersion[0]; + return framework == null ? string.Empty : framework->GameVersionString; } } - public ValidityChecker(DalamudPluginInterface pi) + public ValidityChecker(IDalamudPluginInterface pi) { DevPenumbraExists = CheckDevPluginPenumbra(pi); IsNotInstalledPenumbra = CheckIsNotInstalled(pi); @@ -50,7 +50,7 @@ public class ValidityChecker : IService } // Because remnants of penumbra in devPlugins cause issues, we check for them to warn users to remove them. - private static bool CheckDevPluginPenumbra(DalamudPluginInterface pi) + private static bool CheckDevPluginPenumbra(IDalamudPluginInterface pi) { #if !DEBUG var path = Path.Combine(pi.DalamudAssetDirectory.Parent?.FullName ?? "INVALIDPATH", "devPlugins", "Penumbra"); @@ -71,7 +71,7 @@ public class ValidityChecker : IService } // Check if the loaded version of Penumbra itself is in devPlugins. - private static bool CheckIsNotInstalled(DalamudPluginInterface pi) + private static bool CheckIsNotInstalled(IDalamudPluginInterface pi) { #if !DEBUG var checkedDirectory = pi.AssemblyLocation.Directory?.Parent?.Parent?.Name; @@ -86,7 +86,7 @@ public class ValidityChecker : IService } // Check if the loaded version of Penumbra is installed from a valid source repo. - private static bool CheckSourceRepo(DalamudPluginInterface pi) + private static bool CheckSourceRepo(IDalamudPluginInterface pi) { #if !DEBUG return pi.SourceRepository?.Trim().ToLowerInvariant() switch diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index c95884c6..eeb94c71 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 652f928d..6db4db5c 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 56e9482b..91129129 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; using Newtonsoft.Json.Linq; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs index 3ce10224..b9525b29 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs @@ -287,7 +287,7 @@ public partial class ModEditWindow { fixed (ushort* v2 = &v) { - return ImGui.InputScalar(label, ImGuiDataType.U16, (nint)v2, IntPtr.Zero, IntPtr.Zero, "%04X", flags); + return ImGui.InputScalar(label, ImGuiDataType.U16, (nint)v2, nint.Zero, nint.Zero, "%04X", flags); } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 070895b5..a22c10ad 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -1,5 +1,5 @@ -using Dalamud.Interface.Internal.Notifications; using Dalamud.Interface; +using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using Lumina.Misc; using OtterGui.Raii; diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 0afeeeeb..72bfa266 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -1,5 +1,6 @@ using Dalamud.Interface; -using Dalamud.Interface.Internal; +using Dalamud.Interface.Textures; +using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Services; using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; @@ -121,7 +122,7 @@ public class ChangedItemDrawer : IDisposable, IUiService public static Vector2 TypeFilterIconSize => new(2 * ImGui.GetTextLineHeight()); - public ChangedItemDrawer(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, + public ChangedItemDrawer(IUiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, Configuration config) { _items = gameData.GetExcelSheet()!; @@ -417,7 +418,7 @@ public class ChangedItemDrawer : IDisposable, IUiService }; /// Initialize the icons. - private bool CreateEquipSlotIcons(UiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider) + private bool CreateEquipSlotIcons(IUiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider) { using var equipTypeIcons = uiBuilder.LoadUld("ui/uld/ArmouryBoard.uld"); @@ -441,20 +442,20 @@ public class ChangedItemDrawer : IDisposable, IUiService Add(ChangedItemIcon.Neck, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 9)); Add(ChangedItemIcon.Wrists, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 10)); Add(ChangedItemIcon.Finger, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 11)); - Add(ChangedItemIcon.Monster, textureProvider.GetTextureFromGame("ui/icon/062000/062042_hr1.tex", true)); - Add(ChangedItemIcon.Demihuman, textureProvider.GetTextureFromGame("ui/icon/062000/062041_hr1.tex", true)); - Add(ChangedItemIcon.Customization, textureProvider.GetTextureFromGame("ui/icon/062000/062043_hr1.tex", true)); - Add(ChangedItemIcon.Action, textureProvider.GetTextureFromGame("ui/icon/062000/062001_hr1.tex", true)); - Add(ChangedItemIcon.Emote, LoadEmoteTexture(gameData, uiBuilder)); - Add(ChangedItemIcon.Unknown, LoadUnknownTexture(gameData, uiBuilder)); - Add(AllFlags, textureProvider.GetTextureFromGame("ui/icon/114000/114052_hr1.tex", true)); + Add(ChangedItemIcon.Monster, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062042_hr1.tex")!)); + Add(ChangedItemIcon.Demihuman, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062041_hr1.tex")!)); + Add(ChangedItemIcon.Customization, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062043_hr1.tex")!)); + Add(ChangedItemIcon.Action, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062001_hr1.tex")!)); + Add(ChangedItemIcon.Emote, LoadEmoteTexture(gameData, textureProvider)); + Add(ChangedItemIcon.Unknown, LoadUnknownTexture(gameData, textureProvider)); + Add(AllFlags, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/114000/114052_hr1.tex")!)); _smallestIconWidth = _icons.Values.Min(i => i.Width); return true; } - private static unsafe IDalamudTextureWrap? LoadUnknownTexture(IDataManager gameData, UiBuilder uiBuilder) + private static unsafe IDalamudTextureWrap? LoadUnknownTexture(IDataManager gameData, ITextureProvider textureProvider) { var unk = gameData.GetFile("ui/uld/levelup2_hr1.tex"); if (unk == null) @@ -466,10 +467,10 @@ public class ChangedItemDrawer : IDisposable, IUiService for (var y = 0; y < unk.Header.Height; ++y) image.AsSpan(4 * y * unk.Header.Width, 4 * unk.Header.Width).CopyTo(bytes.AsSpan(4 * y * unk.Header.Height + diff)); - return uiBuilder.LoadImageRaw(bytes, unk.Header.Height, unk.Header.Height, 4); + return textureProvider.CreateFromRaw(RawImageSpecification.Rgba32(unk.Header.Height, unk.Header.Height), bytes, "Penumbra.UnkItemIcon"); } - private static unsafe IDalamudTextureWrap? LoadEmoteTexture(IDataManager gameData, UiBuilder uiBuilder) + private static unsafe IDalamudTextureWrap? LoadEmoteTexture(IDataManager gameData, ITextureProvider textureProvider) { var emote = gameData.GetFile("ui/icon/000000/000019_hr1.tex"); if (emote == null) @@ -486,6 +487,6 @@ public class ChangedItemDrawer : IDisposable, IUiService } } - return uiBuilder.LoadImageRaw(image2, emote.Header.Width, emote.Header.Height, 4); + return textureProvider.CreateFromRaw(RawImageSpecification.Rgba32(emote.Header.Width, emote.Header.Height), image2, "Penumbra.EmoteItemIcon"); } } diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 082b78b8..914f10d9 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -2,7 +2,7 @@ using Dalamud.Game.ClientState.Objects; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.GameFonts; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Utility; using Dalamud.Plugin; @@ -21,7 +21,7 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.CollectionTab; public sealed class CollectionPanel( - DalamudPluginInterface pi, + IDalamudPluginInterface pi, CommunicatorService communicator, CollectionManager manager, CollectionSelector selector, @@ -318,7 +318,7 @@ public sealed class CollectionPanel( var button = ImGui.Button(text, width) || ImGui.IsItemClicked(ImGuiMouseButton.Right); var hovered = redundancy.Length > 0 && ImGui.IsItemHovered(); DrawIndividualDragSource(text, id); - DrawIndividualDragTarget(text, id); + DrawIndividualDragTarget(id); if (!invalid) { selector.DragTargetAssignment(type, id); @@ -349,7 +349,7 @@ public sealed class CollectionPanel( _draggedIndividualAssignment = _active.Individuals.Index(id); } - private void DrawIndividualDragTarget(string text, ActorIdentifier id) + private void DrawIndividualDragTarget(ActorIdentifier id) { if (!id.IsValid) return; diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 67b0a50c..53fa0b33 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -16,7 +16,7 @@ namespace Penumbra.UI; public sealed class ConfigWindow : Window, IUiService { - private readonly DalamudPluginInterface _pluginInterface; + private readonly IDalamudPluginInterface _pluginInterface; private readonly Configuration _config; private readonly PerformanceTracker _tracker; private readonly ValidityChecker _validityChecker; @@ -24,7 +24,7 @@ public sealed class ConfigWindow : Window, IUiService private ConfigTabBar _configTabs = null!; private string? _lastException; - public ConfigWindow(PerformanceTracker tracker, DalamudPluginInterface pi, Configuration config, ValidityChecker checker, + public ConfigWindow(PerformanceTracker tracker, IDalamudPluginInterface pi, Configuration config, ValidityChecker checker, TutorialService tutorial) : base(GetLabel(checker)) { diff --git a/Penumbra/UI/LaunchButton.cs b/Penumbra/UI/LaunchButton.cs index 14e16432..cb533a00 100644 --- a/Penumbra/UI/LaunchButton.cs +++ b/Penumbra/UI/LaunchButton.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using Dalamud.Interface.Internal; +using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin; using Dalamud.Plugin.Services; using OtterGui.Services; @@ -13,23 +13,25 @@ namespace Penumbra.UI; public class LaunchButton : IDisposable, IUiService { private readonly ConfigWindow _configWindow; - private readonly UiBuilder _uiBuilder; + private readonly IUiBuilder _uiBuilder; private readonly ITitleScreenMenu _title; private readonly string _fileName; + private readonly ITextureProvider _textureProvider; - private IDalamudTextureWrap? _icon; - private TitleScreenMenuEntry? _entry; + private IDalamudTextureWrap? _icon; + private IReadOnlyTitleScreenMenuEntry? _entry; /// /// Register the launch button to be created on the next draw event. /// - public LaunchButton(DalamudPluginInterface pi, ITitleScreenMenu title, ConfigWindow ui) + public LaunchButton(IDalamudPluginInterface pi, ITitleScreenMenu title, ConfigWindow ui, ITextureProvider textureProvider) { - _uiBuilder = pi.UiBuilder; - _configWindow = ui; - _title = title; - _icon = null; - _entry = null; + _uiBuilder = pi.UiBuilder; + _configWindow = ui; + _textureProvider = textureProvider; + _title = title; + _icon = null; + _entry = null; _fileName = Path.Combine(pi.AssemblyLocation.DirectoryName!, "tsmLogo.png"); _uiBuilder.Draw += CreateEntry; @@ -49,7 +51,8 @@ public class LaunchButton : IDisposable, IUiService { try { - _icon = _uiBuilder.LoadImage(_fileName); + // TODO: update when API updated. + _icon = _textureProvider.GetFromFile(_fileName).RentAsync().Result; if (_icon != null) _entry = _title.AddEntry("Manage Penumbra", _icon, OnTriggered); diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs index b8faadf7..ec5bb920 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 0ca4d40c..88d6afa2 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.DragDrop; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index 28f00a97..ee6fab1f 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -17,7 +17,7 @@ public class ModPanel : IDisposable, IUiService private readonly ModPanelTabBar _tabs; private bool _resetCursor; - public ModPanel(DalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs, + public ModPanel(IDalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs, MultiModPanel multiModPanel, CommunicatorService communicator) { _selector = selector; diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 1e371065..f81b2831 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Components; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index a8b393b1..6c974f9c 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -20,7 +20,7 @@ public class ModPanelHeader : IDisposable private readonly CommunicatorService _communicator; private float _lastPreSettingsHeight = 0; - public ModPanelHeader(DalamudPluginInterface pi, CommunicatorService communicator) + public ModPanelHeader(IDalamudPluginInterface pi, CommunicatorService communicator) { _communicator = communicator; _nameFont = pi.UiBuilder.FontAtlas.NewGameFontHandle(new GameFontStyle(GameFontFamilyAndSize.Jupiter23)); diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index d531b1a2..8de613d4 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 3bf4cd88..c53f1b8e 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -271,7 +271,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService public unsafe string Name(ResolveData resolve, string none = "") { - if (resolve.AssociatedGameObject == IntPtr.Zero || !_actors.Awaiter.IsCompletedSuccessfully) + if (resolve.AssociatedGameObject == nint.Zero || !_actors.Awaiter.IsCompletedSuccessfully) return none; try diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 34e2cbcf..05a1f33b 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -38,7 +38,7 @@ public sealed class CollectionsTab : IDisposable, ITab, IUiService } } - public CollectionsTab(DalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, IncognitoService incognito, + public CollectionsTab(IDalamudPluginInterface pi, Configuration configuration, CommunicatorService communicator, IncognitoService incognito, CollectionManager collectionManager, ModStorage modStorage, ActorManager actors, ITargetManager targets, TutorialService tutorial, SaveService saveService) { _config = configuration.Ephemeral; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 0122a6f5..41f28ab9 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -37,7 +37,6 @@ using Penumbra.Util; using static OtterGui.Raii.ImRaii; using CharacterBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; -using ObjectKind = Dalamud.Game.ClientState.Objects.Enums.ObjectKind; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using ImGuiClip = OtterGui.ImGuiClip; using Penumbra.Api.IpcTester; @@ -437,8 +436,8 @@ public class DebugTab : Window, ITab, IUiService : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); var identifier = _actors.FromObject(obj, out _, false, true, false); ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); - var id = obj.AsObject->ObjectKind == (byte)ObjectKind.BattleNpc - ? $"{identifier.DataId} | {obj.AsObject->DataID}" + var id = obj.AsObject->ObjectKind is ObjectKind.BattleNpc + ? $"{identifier.DataId} | {obj.AsObject->BaseId}" : identifier.DataId.ToString(); ImGuiUtil.DrawTableColumn(id); } @@ -587,11 +586,11 @@ public class DebugTab : Window, ITab, IUiService if (table) { ImGuiUtil.DrawTableColumn("Group Members"); - ImGuiUtil.DrawTableColumn(GroupManager.Instance()->MemberCount.ToString()); + ImGuiUtil.DrawTableColumn(GroupManager.Instance()->MainGroup.MemberCount.ToString()); for (var i = 0; i < 8; ++i) { ImGuiUtil.DrawTableColumn($"Member #{i}"); - var member = GroupManager.Instance()->GetPartyMemberByIndex(i); + var member = GroupManager.Instance()->MainGroup.GetPartyMemberByIndex(i); ImGuiUtil.DrawTableColumn(member == null ? "NULL" : new ByteString(member->Name).ToString()); } } @@ -612,7 +611,7 @@ public class DebugTab : Window, ITab, IUiService if (table) for (var i = 0; i < 8; ++i) { - ref var c = ref agent->Data->CharacterArraySpan[i]; + ref var c = ref agent->Data->Characters[i]; ImGuiUtil.DrawTableColumn($"Character {i}"); var name = c.Name1.ToString(); ImGuiUtil.DrawTableColumn(name.Length == 0 ? "NULL" : $"{name} ({c.WorldId})"); diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 7faa3da8..50fdc1d3 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -5,7 +5,7 @@ using OtterGui.Raii; using Penumbra.UI.Classes; using Dalamud.Interface; using Dalamud.Plugin.Services; -using FFXIVClientStructs.FFXIV.Client.Game.Housing; +using FFXIVClientStructs.FFXIV.Client.Game; using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index 0b54c5e2..14d4ed41 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -121,7 +121,7 @@ public class ResourceTab(Configuration config, ResourceManagerService resourceMa } /// Obtain a label for an extension node. - private static string GetNodeLabel(uint label, uint type, ulong count) + private static string GetNodeLabel(uint label, uint type, int count) { var (lowest, mid1, mid2, highest) = Functions.SplitBytes(type); return highest == 0 diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 17db21c9..49e77a4d 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -41,7 +41,7 @@ public class SettingsTab : ITab, IUiService private readonly DalamudSubstitutionProvider _dalamudSubstitutionProvider; private readonly FileCompactor _compactor; private readonly DalamudConfigService _dalamudConfig; - private readonly DalamudPluginInterface _pluginInterface; + private readonly IDalamudPluginInterface _pluginInterface; private readonly IDataManager _gameData; private readonly PredefinedTagManager _predefinedTagManager; private readonly CrashHandlerService _crashService; @@ -51,7 +51,7 @@ public class SettingsTab : ITab, IUiService private readonly TagButtons _sharedTags = new(); - public SettingsTab(DalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, + public SettingsTab(IDalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, diff --git a/Penumbra/UI/UiHelpers.cs b/Penumbra/UI/UiHelpers.cs index 8fbce6d0..deba7023 100644 --- a/Penumbra/UI/UiHelpers.cs +++ b/Penumbra/UI/UiHelpers.cs @@ -1,4 +1,4 @@ -using Dalamud.Interface.Internal.Notifications; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index 99819fce..72ac0d01 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -9,13 +9,13 @@ namespace Penumbra.UI; public class PenumbraWindowSystem : IDisposable, IUiService { - private readonly UiBuilder _uiBuilder; + private readonly IUiBuilder _uiBuilder; private readonly WindowSystem _windowSystem; private readonly FileDialogService _fileDialog; public readonly ConfigWindow Window; public readonly PenumbraChangelog Changelog; - public PenumbraWindowSystem(DalamudPluginInterface pi, Configuration config, PenumbraChangelog changelog, ConfigWindow window, + public PenumbraWindowSystem(IDalamudPluginInterface pi, Configuration config, PenumbraChangelog changelog, ConfigWindow window, LaunchButton _, ModEditWindow editWindow, FileDialogService fileDialog, ImportPopup importPopup, DebugTab debugTab) { _uiBuilder = pi.UiBuilder; diff --git a/repo.json b/repo.json index 3142f8d4..6379595e 100644 --- a/repo.json +++ b/repo.json @@ -9,7 +9,7 @@ "TestingAssemblyVersion": "1.1.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 9, + "DalamudApiLevel": 10, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 431933e9c16ac5e4e0e25504cda14eb1a670ea3c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 2 Jul 2024 18:27:53 +0200 Subject: [PATCH 0715/1381] Revert repo API version. --- repo.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/repo.json b/repo.json index 6379595e..3142f8d4 100644 --- a/repo.json +++ b/repo.json @@ -9,7 +9,7 @@ "TestingAssemblyVersion": "1.1.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 10, + "DalamudApiLevel": 9, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 9fb80907811f1fac339410ba60ce6384c40195a2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 3 Jul 2024 17:29:49 +0200 Subject: [PATCH 0716/1381] Current state. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/Api/GameStateApi.cs | 2 +- .../Cache/CollectionCacheManager.cs | 2 +- .../Collections/Cache/CustomResourceCache.cs | 2 +- Penumbra/Communication/MtrlShpkLoaded.cs | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 18 ++- .../Hooks/Objects/CharacterBaseDestructor.cs | 2 +- .../Hooks/Objects/CharacterDestructor.cs | 2 +- .../Interop/Hooks/Objects/CopyCharacter.cs | 2 +- .../Hooks/Objects/CreateCharacterBase.cs | 2 +- Penumbra/Interop/Hooks/Objects/EnableDraw.cs | 2 +- .../Interop/Hooks/Objects/WeaponReload.cs | 2 +- .../PreBoneDeformerReplacer.cs | 24 ++-- .../PostProcessing}/ShaderReplacementFixer.cs | 20 ++-- .../ResourceLoading/CreateFileWHook.cs | 5 +- .../ResourceLoading/FileReadService.cs | 11 +- .../ResourceLoading/ResourceLoader.cs | 26 ++-- .../ResourceLoading/ResourceManagerService.cs | 6 +- .../ResourceLoading/ResourceService.cs | 13 +- .../ResourceLoading/TexMdlService.cs | 113 +++++++++++------- .../Hooks/Resources/ApricotResourceLoad.cs | 2 +- .../Interop/Hooks/Resources/LoadMtrlShpk.cs | 2 +- .../Interop/Hooks/Resources/LoadMtrlTex.cs | 2 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 3 +- .../Resources/ResourceHandleDestructor.cs | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 2 +- .../Interop/PathResolving/PathResolver.cs | 2 +- .../Interop/PathResolving/SubfileHelper.cs | 2 +- .../Processing/FilePostProcessService.cs | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 30 +++-- Penumbra/Interop/Services/DecalReverter.cs | 2 +- Penumbra/Penumbra.cs | 2 +- Penumbra/Penumbra.csproj | 1 - Penumbra/Services/CrashHandlerService.cs | 2 +- .../UI/ResourceWatcher/ResourceWatcher.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 3 +- Penumbra/UI/Tabs/ResourceTab.cs | 2 +- 39 files changed, 186 insertions(+), 139 deletions(-) rename Penumbra/Interop/{Services => Hooks/PostProcessing}/PreBoneDeformerReplacer.cs (81%) rename Penumbra/Interop/{Services => Hooks/PostProcessing}/ShaderReplacementFixer.cs (91%) rename Penumbra/Interop/{ => Hooks}/ResourceLoading/CreateFileWHook.cs (97%) rename Penumbra/Interop/{ => Hooks}/ResourceLoading/FileReadService.cs (92%) rename Penumbra/Interop/{ => Hooks}/ResourceLoading/ResourceLoader.cs (93%) rename Penumbra/Interop/{ => Hooks}/ResourceLoading/ResourceManagerService.cs (93%) rename Penumbra/Interop/{ => Hooks}/ResourceLoading/ResourceService.cs (95%) rename Penumbra/Interop/{ => Hooks}/ResourceLoading/TexMdlService.cs (60%) diff --git a/OtterGui b/OtterGui index 437ef65c..c2738e1d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 437ef65c6464c54c8f40196dd2428da901d73aab +Subproject commit c2738e1d42974cddbe5a31238c6ed236a831d17d diff --git a/Penumbra.GameData b/Penumbra.GameData index 3a97e5ae..066637ab 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3a97e5aeee3b7375b333c1add5305d0ce80cbf83 +Subproject commit 066637abe05c659b79d84f52e6db33487498f433 diff --git a/Penumbra/Api/Api/GameStateApi.cs b/Penumbra/Api/Api/GameStateApi.cs index becb55ee..b035c886 100644 --- a/Penumbra/Api/Api/GameStateApi.cs +++ b/Penumbra/Api/Api/GameStateApi.cs @@ -2,8 +2,8 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.PathResolving; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.Services; using Penumbra.String.Classes; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 44c12856..80d4cf1d 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -5,7 +5,7 @@ using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Communication; -using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Groups; diff --git a/Penumbra/Collections/Cache/CustomResourceCache.cs b/Penumbra/Collections/Cache/CustomResourceCache.cs index 46c28393..e63f8637 100644 --- a/Penumbra/Collections/Cache/CustomResourceCache.cs +++ b/Penumbra/Collections/Cache/CustomResourceCache.cs @@ -1,6 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; -using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.SafeHandles; using Penumbra.String.Classes; diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlShpkLoaded.cs index 8aab0e0e..9d3597a8 100644 --- a/Penumbra/Communication/MtrlShpkLoaded.cs +++ b/Penumbra/Communication/MtrlShpkLoaded.cs @@ -10,7 +10,7 @@ public sealed class MtrlShpkLoaded() : EventWrapper + /// ShaderReplacementFixer = 0, } } diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 6d511a28..ed4eb669 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -1,8 +1,14 @@ -namespace Penumbra.Interop.Hooks; - +namespace Penumbra.Interop.Hooks; + public static class HookSettings { - public const bool MetaEntryHooks = false; - public const bool MetaParentHooks = false; - public const bool VfxIdentificationHooks = false; -} + public const bool AllHooks = true; + + public const bool ObjectHooks = false && AllHooks; + public const bool ReplacementHooks = true && AllHooks; + public const bool ResourceHooks = false && AllHooks; + public const bool MetaEntryHooks = false && AllHooks; + public const bool MetaParentHooks = false && AllHooks; + public const bool VfxIdentificationHooks = false && AllHooks; + public const bool PostProcessingHooks = false && AllHooks; +} diff --git a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs index e01a6550..c67bb9f3 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs @@ -19,7 +19,7 @@ public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, true); + => _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs index 6e10c5e3..618d0bd7 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs @@ -19,7 +19,7 @@ public sealed unsafe class CharacterDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Sigs.CharacterDestructor, Detour, true); + => _task = hooks.CreateHook(Name, Sigs.CharacterDestructor, Detour, HookSettings.ObjectHooks); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs index 20c96f56..663209ae 100644 --- a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs +++ b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs @@ -15,7 +15,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, true); + => _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs index 299f312a..56b3d853 100644 --- a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs +++ b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs @@ -16,7 +16,7 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, true); + => _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/EnableDraw.cs b/Penumbra/Interop/Hooks/Objects/EnableDraw.cs index 267b4711..8b701fe5 100644 --- a/Penumbra/Interop/Hooks/Objects/EnableDraw.cs +++ b/Penumbra/Interop/Hooks/Objects/EnableDraw.cs @@ -17,7 +17,7 @@ public sealed unsafe class EnableDraw : IHookService public EnableDraw(HookManager hooks, GameState state) { _state = state; - _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, true); + _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, HookSettings.ObjectHooks); } private delegate void Delegate(GameObject* gameObject); diff --git a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs index fec0a13f..da31840f 100644 --- a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs +++ b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs @@ -16,7 +16,7 @@ public sealed unsafe class WeaponReload : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, true); + => _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); private readonly Task> _task; diff --git a/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs similarity index 81% rename from Penumbra/Interop/Services/PreBoneDeformerReplacer.cs rename to Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs index 9f553257..903484ea 100644 --- a/Penumbra/Interop/Services/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs @@ -4,12 +4,13 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui.Services; using Penumbra.Api.Enums; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.PathResolving; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.SafeHandles; using Penumbra.String.Classes; +using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; -namespace Penumbra.Interop.Services; +namespace Penumbra.Interop.Hooks.PostProcessing; public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredService { @@ -29,17 +30,16 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi private readonly IFramework _framework; public PreBoneDeformerReplacer(CharacterUtility utility, CollectionResolver collectionResolver, ResourceLoader resourceLoader, - IGameInteropProvider interop, IFramework framework, CharacterBaseVTables vTables) + HookManager hooks, IFramework framework, CharacterBaseVTables vTables) { - interop.InitializeFromAttributes(this); - _utility = utility; - _collectionResolver = collectionResolver; - _resourceLoader = resourceLoader; - _framework = framework; - _humanSetupScalingHook = interop.HookFromAddress(vTables.HumanVTable[57], SetupScaling); - _humanCreateDeformerHook = interop.HookFromAddress(vTables.HumanVTable[91], CreateDeformer); - _humanSetupScalingHook.Enable(); - _humanCreateDeformerHook.Enable(); + _utility = utility; + _collectionResolver = collectionResolver; + _resourceLoader = resourceLoader; + _framework = framework; + _humanSetupScalingHook = hooks.CreateHook("HumanSetupScaling", vTables.HumanVTable[58], SetupScaling, + HookSettings.PostProcessingHooks).Result; + _humanCreateDeformerHook = hooks.CreateHook("HumanCreateDeformer", vTables.HumanVTable[101], + CreateDeformer, HookSettings.PostProcessingHooks).Result; } public void Dispose() diff --git a/Penumbra/Interop/Services/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs similarity index 91% rename from Penumbra/Interop/Services/ShaderReplacementFixer.cs rename to Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 95e70b45..b27ca4c5 100644 --- a/Penumbra/Interop/Services/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -1,6 +1,4 @@ using Dalamud.Hooking; -using Dalamud.Plugin.Services; -using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; @@ -10,9 +8,11 @@ using Penumbra.Communication; using Penumbra.GameData; using Penumbra.Interop.Hooks.Resources; using Penumbra.Services; +using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using CSModelRenderer = FFXIVClientStructs.FFXIV.Client.Graphics.Render.ModelRenderer; +using ModelRenderer = Penumbra.Interop.Services.ModelRenderer; -namespace Penumbra.Interop.Services; +namespace Penumbra.Interop.Hooks.PostProcessing; public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredService { @@ -29,8 +29,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private readonly Hook _humanOnRenderMaterialHook; - [Signature(Sigs.ModelRendererOnRenderMaterial, DetourName = nameof(ModelRendererOnRenderMaterialDetour))] - private readonly Hook _modelRendererOnRenderMaterialHook = null!; + private readonly Hook _modelRendererOnRenderMaterialHook; private readonly ResourceHandleDestructor _resourceHandleDestructor; private readonly CommunicatorService _communicator; @@ -59,19 +58,18 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic => _moddedCharacterGlassShpkCount; public ShaderReplacementFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, ModelRenderer modelRenderer, - CommunicatorService communicator, IGameInteropProvider interop, CharacterBaseVTables vTables) + CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables) { - interop.InitializeFromAttributes(this); _resourceHandleDestructor = resourceHandleDestructor; _utility = utility; _modelRenderer = modelRenderer; _communicator = communicator; - _humanOnRenderMaterialHook = - interop.HookFromAddress(vTables.HumanVTable[62], OnRenderHumanMaterial); + _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[62], + OnRenderHumanMaterial, HookSettings.PostProcessingHooks).Result; + _modelRendererOnRenderMaterialHook = hooks.CreateHook("ModelRenderer.OnRenderMaterial", + Sigs.ModelRendererOnRenderMaterial, ModelRendererOnRenderMaterialDetour, HookSettings.PostProcessingHooks).Result; _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.ShaderReplacementFixer); _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.ShaderReplacementFixer); - _humanOnRenderMaterialHook.Enable(); - _modelRendererOnRenderMaterialHook.Enable(); } public void Dispose() diff --git a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs similarity index 97% rename from Penumbra/Interop/ResourceLoading/CreateFileWHook.cs rename to Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs index bde640d2..a8ac0608 100644 --- a/Penumbra/Interop/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs @@ -5,7 +5,7 @@ using Penumbra.String; using Penumbra.String.Classes; using Penumbra.String.Functions; -namespace Penumbra.Interop.ResourceLoading; +namespace Penumbra.Interop.Hooks.ResourceLoading; /// /// To allow XIV to load files of arbitrary path length, @@ -19,7 +19,8 @@ public unsafe class CreateFileWHook : IDisposable, IRequiredService public CreateFileWHook(IGameInteropProvider interop) { _createFileWHook = interop.HookFromImport(null, "KERNEL32.dll", "CreateFileW", 0, CreateFileWDetour); - _createFileWHook.Enable(); + if (HookSettings.ReplacementHooks) + _createFileWHook.Enable(); } /// diff --git a/Penumbra/Interop/ResourceLoading/FileReadService.cs b/Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs similarity index 92% rename from Penumbra/Interop/ResourceLoading/FileReadService.cs rename to Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs index 5edba790..199525fb 100644 --- a/Penumbra/Interop/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs @@ -6,16 +6,17 @@ using Penumbra.GameData; using Penumbra.Interop.Structs; using Penumbra.Util; -namespace Penumbra.Interop.ResourceLoading; +namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class FileReadService : IDisposable, IRequiredService { public FileReadService(PerformanceTracker performance, ResourceManagerService resourceManager, IGameInteropProvider interop) { _resourceManager = resourceManager; - _performance = performance; + _performance = performance; interop.InitializeFromAttributes(this); - _readSqPackHook.Enable(); + if (HookSettings.ReplacementHooks) + _readSqPackHook.Enable(); } /// Invoked when a file is supposed to be read from SqPack. @@ -49,7 +50,7 @@ public unsafe class FileReadService : IDisposable, IRequiredService _readSqPackHook.Dispose(); } - private readonly PerformanceTracker _performance; + private readonly PerformanceTracker _performance; private readonly ResourceManagerService _resourceManager; private delegate byte ReadSqPackPrototype(nint resourceManager, SeFileDescriptor* pFileDesc, int priority, bool isSync); @@ -60,7 +61,7 @@ public unsafe class FileReadService : IDisposable, IRequiredService private byte ReadSqPackDetour(nint resourceManager, SeFileDescriptor* fileDescriptor, int priority, bool isSync) { using var performance = _performance.Measure(PerformanceType.ReadSqPack); - byte? ret = null; + byte? ret = null; _lastFileThreadResourceManager.Value = resourceManager; ReadSqPack?.Invoke(fileDescriptor, ref priority, ref isSync, ref ret); _lastFileThreadResourceManager.Value = nint.Zero; diff --git a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs similarity index 93% rename from Penumbra/Interop/ResourceLoading/ResourceLoader.cs rename to Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 4a423993..5cac2f32 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -9,27 +9,27 @@ using Penumbra.String; using Penumbra.String.Classes; using FileMode = Penumbra.Interop.Structs.FileMode; -namespace Penumbra.Interop.ResourceLoading; +namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class ResourceLoader : IDisposable, IService { private readonly ResourceService _resources; private readonly FileReadService _fileReadService; - private readonly TexMdlService _texMdlService; + private readonly TexMdlService _texMdlService; private ResolveData _resolvedData = ResolveData.Invalid; public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService) { - _resources = resources; + _resources = resources; _fileReadService = fileReadService; - _texMdlService = texMdlService; + _texMdlService = texMdlService; ResetResolvePath(); - _resources.ResourceRequested += ResourceHandler; + _resources.ResourceRequested += ResourceHandler; _resources.ResourceHandleIncRef += IncRefProtection; _resources.ResourceHandleDecRef += DecRefProtection; - _fileReadService.ReadSqPack += ReadSqPackDetour; + _fileReadService.ReadSqPack += ReadSqPackDetour; } /// Load a resource for a given path and a specific collection. @@ -80,10 +80,10 @@ public unsafe class ResourceLoader : IDisposable, IService public void Dispose() { - _resources.ResourceRequested -= ResourceHandler; + _resources.ResourceRequested -= ResourceHandler; _resources.ResourceHandleIncRef -= IncRefProtection; _resources.ResourceHandleDecRef -= DecRefProtection; - _fileReadService.ReadSqPack -= ReadSqPackDetour; + _fileReadService.ReadSqPack -= ReadSqPackDetour; } private void ResourceHandler(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, @@ -112,7 +112,7 @@ public unsafe class ResourceLoader : IDisposable, IService // Replace the hash and path with the correct one for the replacement. hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; - path = p; + path = p; returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); ResourceLoaded?.Invoke(returnValue, oldPath, resolvedPath.Value, data); } @@ -140,12 +140,12 @@ public unsafe class ResourceLoader : IDisposable, IService } var path = ByteString.FromSpanUnsafe(actualPath, gamePath.Path.IsNullTerminated, gamePath.Path.IsAsciiLowerCase, gamePath.Path.IsAscii); - fileDescriptor->ResourceHandle->FileNameData = path.Path; + fileDescriptor->ResourceHandle->FileNameData = path.Path; fileDescriptor->ResourceHandle->FileNameLength = path.Length; MtrlForceSync(fileDescriptor, ref isSync); returnValue = DefaultLoadResource(path, fileDescriptor, priority, isSync, data); // Return original resource handle path so that they can be loaded separately. - fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; + fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; fileDescriptor->ResourceHandle->FileNameLength = gamePath.Path.Length; } @@ -165,7 +165,7 @@ public unsafe class ResourceLoader : IDisposable, IService // Ensure that the file descriptor has its wchar_t array on aligned boundary even if it has to be odd. var fd = stackalloc char[0x11 + 0x0B + 14]; fileDescriptor->FileDescriptor = (byte*)fd + 1; - CreateFileWHook.WritePtr(fd + 0x11, gamePath.Path, gamePath.Length); + CreateFileWHook.WritePtr(fd + 0x11, gamePath.Path, gamePath.Length); CreateFileWHook.WritePtr(&fileDescriptor->Utf16FileName, gamePath.Path, gamePath.Length); // Use the SE ReadFile function. @@ -206,7 +206,7 @@ public unsafe class ResourceLoader : IDisposable, IService return; _incMode.Value = true; - returnValue = _resources.IncRef(handle); + returnValue = _resources.IncRef(handle); _incMode.Value = false; } diff --git a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceManagerService.cs similarity index 93% rename from Penumbra/Interop/ResourceLoading/ResourceManagerService.cs rename to Penumbra/Interop/Hooks/ResourceLoading/ResourceManagerService.cs index 0479d2a6..1bff80ba 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceManagerService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceManagerService.cs @@ -8,7 +8,7 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData; -namespace Penumbra.Interop.ResourceLoading; +namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class ResourceManagerService : IRequiredService { @@ -23,10 +23,10 @@ public unsafe class ResourceManagerService : IRequiredService public ResourceHandle* FindResource(ResourceCategory cat, ResourceType ext, uint crc32) { ref var manager = ref *ResourceManager; - var catIdx = (uint)cat >> 0x18; + var catIdx = (uint)cat >> 0x18; cat = (ResourceCategory)(ushort)cat; ref var category = ref manager.ResourceGraph->Containers[(int)cat]; - var extMap = FindInMap(category.CategoryMaps[(int)catIdx].Value, (uint)ext); + var extMap = FindInMap(category.CategoryMaps[(int)catIdx].Value, (uint)ext); if (extMap == null) return null; diff --git a/Penumbra/Interop/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs similarity index 95% rename from Penumbra/Interop/ResourceLoading/ResourceService.cs rename to Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index d623d72d..0b00452b 100644 --- a/Penumbra/Interop/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -12,7 +12,7 @@ using Penumbra.String.Classes; using Penumbra.Util; using CSResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle; -namespace Penumbra.Interop.ResourceLoading; +namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class ResourceService : IDisposable, IRequiredService { @@ -24,16 +24,19 @@ public unsafe class ResourceService : IDisposable, IRequiredService _performance = performance; _resourceManager = resourceManager; interop.InitializeFromAttributes(this); - _getResourceSyncHook.Enable(); - _getResourceAsyncHook.Enable(); _incRefHook = interop.HookFromAddress( (nint)CSResourceHandle.MemberFunctionPointers.IncRef, ResourceHandleIncRefDetour); - _incRefHook.Enable(); _decRefHook = interop.HookFromAddress( (nint)CSResourceHandle.MemberFunctionPointers.DecRef, ResourceHandleDecRefDetour); - _decRefHook.Enable(); + if (HookSettings.ReplacementHooks) + { + _getResourceSyncHook.Enable(); + _getResourceAsyncHook.Enable(); + _incRefHook.Enable(); + _decRefHook.Enable(); + } } public ResourceHandle* GetResource(ResourceCategory category, ResourceType type, ByteString path) diff --git a/Penumbra/Interop/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs similarity index 60% rename from Penumbra/Interop/ResourceLoading/TexMdlService.cs rename to Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index a2b43c64..28ad7aa4 100644 --- a/Penumbra/Interop/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -1,109 +1,138 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; -using FFXIVClientStructs.FFXIV.Client.LayoutEngine; -using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using Lumina.Excel.GeneratedSheets2; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData; +using Penumbra.Interop.Structs; using Penumbra.String.Classes; +using FileMode = Penumbra.Interop.Structs.FileMode; +using ResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle; -namespace Penumbra.Interop.ResourceLoading; +namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class TexMdlService : IDisposable, IRequiredService { /// Custom ulong flag to signal our files as opposed to SE files. public static readonly nint CustomFileFlag = new(0xDEADBEEF); - + /// /// We need to keep a list of all CRC64 hash values of our replaced Mdl and Tex files, /// i.e. CRC32 of filename in the lower bytes, CRC32 of parent path in the upper bytes. /// public IReadOnlySet CustomFileCrc => _customFileCrc; - + public TexMdlService(IGameInteropProvider interop) { interop.InitializeFromAttributes(this); - //_checkFileStateHook.Enable(); - //_loadTexFileExternHook.Enable(); - //_loadMdlFileExternHook.Enable(); + if (HookSettings.ReplacementHooks) + { + _checkFileStateHook.Enable(); + _loadMdlFileExternHook.Enable(); + _textureSomethingHook.Enable(); + _vf32Hook.Enable(); + //_loadTexFileExternHook.Enable(); + } } - + /// Add CRC64 if the given file is a model or texture file and has an associated path. public void AddCrc(ResourceType type, FullPath? path) { - if (path.HasValue && type is ResourceType.Mdl or ResourceType.Tex) + if (path.HasValue && type is ResourceType.Mdl) _customFileCrc.Add(path.Value.Crc64); } - + /// Add a fixed CRC64 value. public void AddCrc(ulong crc64) => _customFileCrc.Add(crc64); - + public void Dispose() { - //_checkFileStateHook.Dispose(); + _checkFileStateHook.Dispose(); //_loadTexFileExternHook.Dispose(); - //_loadMdlFileExternHook.Dispose(); + _textureSomethingHook.Dispose(); + _loadMdlFileExternHook.Dispose(); + _vf32Hook.Dispose(); } - - private readonly HashSet _customFileCrc = new(); - + + private readonly HashSet _customFileCrc = []; + private delegate nint CheckFileStatePrototype(nint unk1, ulong crc64); - + + private delegate nint TextureSomethingDelegate(TextureResourceHandle* handle, int lod, SeFileDescriptor* descriptor); + [Signature(Sigs.CheckFileState, DetourName = nameof(CheckFileStateDetour))] private readonly Hook _checkFileStateHook = null!; - + + [Signature("E8 ?? ?? ?? ?? 0F B6 C8 EB ?? 4C 8B 83", DetourName = nameof(TextureSomethingDetour))] + private readonly Hook _textureSomethingHook = null!; + + private nint TextureSomethingDetour(TextureResourceHandle* handle, int lod, SeFileDescriptor* descriptor) + { + //Penumbra.Log.Information($"SomethingDetour {handle->Handle.FileName()}"); + //if (!handle->Handle.GamePath(out var path) || !path.IsRooted()) + return _textureSomethingHook.Original(handle, lod, descriptor); + + descriptor->FileMode = FileMode.LoadUnpackedResource; + return _loadTexFileLocal.Invoke((ResourceHandle*)handle, lod, (nint)descriptor, true); + } + /// /// The function that checks a files CRC64 to determine whether it is 'protected'. /// We use it to check against our stored CRC64s and if it corresponds, we return the custom flag. /// private nint CheckFileStateDetour(nint ptr, ulong crc64) => _customFileCrc.Contains(crc64) ? CustomFileFlag : _checkFileStateHook.Original(ptr, crc64); - - + + private delegate byte LoadTexFileLocalDelegate(ResourceHandle* handle, int unk1, nint unk2, bool unk3); - + /// We use the local functions for our own files in the extern hook. [Signature(Sigs.LoadTexFileLocal)] private readonly LoadTexFileLocalDelegate _loadTexFileLocal = null!; - + private delegate byte LoadMdlFileLocalPrototype(ResourceHandle* handle, nint unk1, bool unk2); - + /// We use the local functions for our own files in the extern hook. [Signature(Sigs.LoadMdlFileLocal)] private readonly LoadMdlFileLocalPrototype _loadMdlFileLocal = null!; - - + + private delegate byte LoadTexFileExternPrototype(ResourceHandle* handle, int unk1, nint unk2, bool unk3, nint unk4); + + private delegate byte TexResourceHandleVf32Prototype(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2); + + [Signature("40 53 55 41 54 41 55 41 56 41 57 48 81 EC ?? ?? ?? ?? 48 8B D9", DetourName = nameof(Vf32Detour))] + private readonly Hook _vf32Hook = null!; - private delegate byte TexResourceHandleVf32Prototype(ResourceHandle* handle, nint unk1, byte unk2); - - //[Signature("40 53 55 41 54 41 55 41 56 41 57 48 81 EC ?? ?? ?? ?? 48 8B D9", DetourName = nameof(Vf32Detour))] - //private readonly Hook _vf32Hook = null!; - // - //private byte Vf32Detour(ResourceHandle* handle, nint unk1, byte unk2) - //{ - // var ret = _vf32Hook.Original(handle, unk1, unk2); - // return _loadTexFileLocal() - //} - + private byte Vf32Detour(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2) + { + //if (handle->Handle.GamePath(out var path) && path.IsRooted()) + //{ + // Penumbra.Log.Information($"Replacing {descriptor->FileMode} with {FileMode.LoadSqPackResource} in VF32 for {path}."); + // descriptor->FileMode = FileMode.LoadSqPackResource; + //} + + var ret = _vf32Hook.Original(handle, descriptor, unk2); + return ret; + } + //[Signature(Sigs.LoadTexFileExtern, DetourName = nameof(LoadTexFileExternDetour))] //private readonly Hook _loadTexFileExternHook = null!; - + /// We hook the extern functions to just return the local one if given the custom flag as last argument. //private byte LoadTexFileExternDetour(ResourceHandle* resourceHandle, int unk1, nint unk2, bool unk3, nint ptr) // => ptr.Equals(CustomFileFlag) // ? _loadTexFileLocal.Invoke(resourceHandle, unk1, unk2, unk3) // : _loadTexFileExternHook.Original(resourceHandle, unk1, unk2, unk3, ptr); - public delegate byte LoadMdlFileExternPrototype(ResourceHandle* handle, nint unk1, bool unk2, nint unk3); - - + + [Signature(Sigs.LoadMdlFileExtern, DetourName = nameof(LoadMdlFileExternDetour))] private readonly Hook _loadMdlFileExternHook = null!; - + /// We hook the extern functions to just return the local one if given the custom flag as last argument. private byte LoadMdlFileExternDetour(ResourceHandle* resourceHandle, nint unk1, bool unk2, nint ptr) => ptr.Equals(CustomFileFlag) diff --git a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs index 2e5698a3..511e842f 100644 --- a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs +++ b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs @@ -11,7 +11,7 @@ public sealed unsafe class ApricotResourceLoad : FastHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, true); + Task = hooks.CreateHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, HookSettings.ResourceHooks); } public delegate byte Delegate(ResourceHandle* handle, nint unk1, byte unk2); diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs index 5ef3bf37..8447762b 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs @@ -14,7 +14,7 @@ public sealed unsafe class LoadMtrlShpk : FastHook { _gameState = gameState; _communicator = communicator; - Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, true); + Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, HookSettings.ResourceHooks); } public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs index 14a011ea..7bc3c7b0 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs @@ -11,7 +11,7 @@ public sealed unsafe class LoadMtrlTex : FastHook public LoadMtrlTex(HookManager hooks, GameState gameState) { _gameState = gameState; - Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, true); + Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, HookSettings.ResourceHooks); } public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index a7e82b72..8fa6d861 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -59,7 +59,8 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[93], type, ResolveVfx, ResolveVfxHuman); _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[94], ResolveEid); // @formatter:on - Enable(); + if (HookSettings.ResourceHooks) + Enable(); } public void Enable() diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index ac3f504a..cd4a53c4 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -23,7 +23,7 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Sigs.ResourceHandleDestructor, Detour, true); + => _task = hooks.CreateHook(Name, Sigs.ResourceHandleDestructor, Detour, HookSettings.ResourceHooks); private readonly Task> _task; diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index 5eacbfb0..e709c210 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -4,12 +4,12 @@ using OtterGui.Services; using Penumbra.Collections; using Penumbra.Api.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Services; using Penumbra.String.Classes; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using Penumbra.Interop.Hooks.Objects; +using Penumbra.Interop.Hooks.ResourceLoading; namespace Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index cc3e0e9b..49035dc8 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -3,8 +3,8 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.Processing; -using Penumbra.Interop.ResourceLoading; using Penumbra.String.Classes; using Penumbra.Util; diff --git a/Penumbra/Interop/PathResolving/SubfileHelper.cs b/Penumbra/Interop/PathResolving/SubfileHelper.cs index 44a152f0..836cf731 100644 --- a/Penumbra/Interop/PathResolving/SubfileHelper.cs +++ b/Penumbra/Interop/PathResolving/SubfileHelper.cs @@ -1,8 +1,8 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.Hooks.Resources; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.String.Classes; diff --git a/Penumbra/Interop/Processing/FilePostProcessService.cs b/Penumbra/Interop/Processing/FilePostProcessService.cs index 0dc62b3d..bba53c94 100644 --- a/Penumbra/Interop/Processing/FilePostProcessService.cs +++ b/Penumbra/Interop/Processing/FilePostProcessService.cs @@ -1,7 +1,7 @@ using System.Collections.Frozen; using OtterGui.Services; using Penumbra.Api.Enums; -using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.String; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index ca8836b0..a852a4cc 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -9,8 +9,8 @@ using Penumbra.Collections; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.PathResolving; -using Penumbra.Interop.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index b8bad84a..810c946d 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -5,7 +5,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Interop.Services; +using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; using CustomizeIndex = Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex; @@ -31,7 +31,8 @@ public class ResourceTree public CustomizeData CustomizeData; public GenderRace RaceCode; - public ResourceTree(string name, string anonymizedName, int gameObjectIndex, nint gameObjectAddress, nint drawObjectAddress, bool localPlayerRelated, bool playerRelated, bool networked, string collectionName, string anonymizedCollectionName) + public ResourceTree(string name, string anonymizedName, int gameObjectIndex, nint gameObjectAddress, nint drawObjectAddress, + bool localPlayerRelated, bool playerRelated, bool networked, string collectionName, string anonymizedCollectionName) { Name = name; AnonymizedName = anonymizedName; @@ -61,9 +62,10 @@ public class ResourceTree var human = modelType == CharacterBase.ModelType.Human ? (Human*)model : null; var equipment = modelType switch { - CharacterBase.ModelType.Human => new ReadOnlySpan(&human->Head, 10), - CharacterBase.ModelType.DemiHuman => new ReadOnlySpan(Unsafe.AsPointer(ref character->DrawData.EquipmentModelIds[0]), 10), - _ => ReadOnlySpan.Empty, + CharacterBase.ModelType.Human => new ReadOnlySpan(&human->Head, 10), + CharacterBase.ModelType.DemiHuman => new ReadOnlySpan( + Unsafe.AsPointer(ref character->DrawData.EquipmentModelIds[0]), 10), + _ => ReadOnlySpan.Empty, }; ModelId = character->CharacterData.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; @@ -112,15 +114,17 @@ public class ResourceTree { if (baseSubObject->GetObjectType() != FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType.CharacterBase) continue; + var subObject = (CharacterBase*)baseSubObject; if (subObject->GetModelType() != CharacterBase.ModelType.Weapon) continue; - var weapon = (Weapon*)subObject; + + var weapon = (Weapon*)subObject; // This way to tell apart MainHand and OffHand is not always accurate, but seems good enough for what we're doing with it. var slot = weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand; - var equipment = new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, (byte)weapon->ModelUnknown); + var equipment = new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, new StainIds(weapon->Stain1, weapon->Stain2)); var weaponType = weapon->SecondaryId; var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment, weaponType); @@ -152,6 +156,7 @@ public class ResourceTree ++weaponIndex; } + Nodes.InsertRange(0, weaponNodes); } @@ -167,10 +172,11 @@ public class ResourceTree { if (globalContext.WithUiData) { - pbdNode = pbdNode.Clone(); + pbdNode = pbdNode.Clone(); pbdNode.FallbackName = "Racial Deformer"; - pbdNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + pbdNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; } + Nodes.Add(pbdNode); } } @@ -184,10 +190,11 @@ public class ResourceTree { if (globalContext.WithUiData) { - decalNode = decalNode.Clone(); + decalNode = decalNode.Clone(); decalNode.FallbackName = "Face Decal"; decalNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; } + Nodes.Add(decalNode); } @@ -200,10 +207,11 @@ public class ResourceTree { if (globalContext.WithUiData) { - legacyDecalNode = legacyDecalNode.Clone(); + legacyDecalNode = legacyDecalNode.Clone(); legacyDecalNode.FallbackName = "Legacy Body Decal"; legacyDecalNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; } + Nodes.Add(legacyDecalNode); } } diff --git a/Penumbra/Interop/Services/DecalReverter.cs b/Penumbra/Interop/Services/DecalReverter.cs index 17d8d2e0..21b51fd2 100644 --- a/Penumbra/Interop/Services/DecalReverter.cs +++ b/Penumbra/Interop/Services/DecalReverter.cs @@ -1,7 +1,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; -using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.String.Classes; namespace Penumbra.Interop.Services; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b1ad0b78..9f2db2e6 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -8,7 +8,6 @@ using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Cache; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.PathResolving; using Penumbra.Services; using Penumbra.Interop.Services; @@ -22,6 +21,7 @@ using Penumbra.GameData.Enums; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using System.Xml.Linq; +using Penumbra.Interop.Hooks.ResourceLoading; namespace Penumbra; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index ed5c5e30..2e53bd22 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -37,7 +37,6 @@ $(AppData)\XIVLauncher\addon\Hooks\dev\ - H:\Projects\FFPlugins\Dalamud\bin\Release\ diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 25c6cf57..9103b29c 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -7,8 +7,8 @@ using Penumbra.Communication; using Penumbra.CrashHandler; using Penumbra.CrashHandler.Buffers; using Penumbra.GameData.Actors; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.PathResolving; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index c53f1b8e..935f11e3 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -8,8 +8,8 @@ using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.Hooks.Resources; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.Services; using Penumbra.String; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 41f28ab9..9a03f384 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -25,7 +25,6 @@ using Penumbra.GameData.Interop; using Penumbra.Import.Structs; using Penumbra.Import.Textures; using Penumbra.Interop.PathResolving; -using Penumbra.Interop.ResourceLoading; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Mods; @@ -40,6 +39,8 @@ using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using ImGuiClip = OtterGui.ImGuiClip; using Penumbra.Api.IpcTester; +using Penumbra.Interop.Hooks.PostProcessing; +using Penumbra.Interop.Hooks.ResourceLoading; namespace Penumbra.UI.Tabs.Debug; diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index 14d4ed41..a4dbba2f 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -8,7 +8,7 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Widgets; -using Penumbra.Interop.ResourceLoading; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.String.Classes; namespace Penumbra.UI.Tabs; From 4026dd58672fb38a6c83dfe1309ded1b10a9aa67 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Jul 2024 12:14:31 +0200 Subject: [PATCH 0717/1381] Change texture handling. --- Penumbra.GameData | 2 +- .../Hooks/ResourceLoading/TexMdlService.cs | 128 +++++++++--------- Penumbra/Interop/Structs/ResourceHandle.cs | 6 + 3 files changed, 73 insertions(+), 63 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 066637ab..19923f8d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 066637abe05c659b79d84f52e6db33487498f433 +Subproject commit 19923f8d5649f11edcfae710c26d6273cf2e9d62 diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index 28ad7aa4..793d15af 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -1,93 +1,110 @@ using Dalamud.Hooking; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; -using Lumina.Excel.GeneratedSheets2; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.GameData; using Penumbra.Interop.Structs; using Penumbra.String.Classes; -using FileMode = Penumbra.Interop.Structs.FileMode; using ResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle; namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class TexMdlService : IDisposable, IRequiredService { + /// + /// We need to be able to obtain the requested LoD level. + /// This replicates the LoD behavior of a textures OnLoad function. + /// + private readonly struct LodService + { + public LodService(IGameInteropProvider interop) + => interop.InitializeFromAttributes(this); + + [Signature(Sigs.LodConfig)] + private readonly nint _lodConfig = nint.Zero; + + public byte GetLod(TextureResourceHandle* handle) + { + if (handle->ChangeLod) + { + var config = *(byte*)_lodConfig + 0xE; + if (config == byte.MaxValue) + return 2; + } + + return 0; + } + } + /// Custom ulong flag to signal our files as opposed to SE files. public static readonly nint CustomFileFlag = new(0xDEADBEEF); - /// - /// We need to keep a list of all CRC64 hash values of our replaced Mdl and Tex files, - /// i.e. CRC32 of filename in the lower bytes, CRC32 of parent path in the upper bytes. - /// - public IReadOnlySet CustomFileCrc - => _customFileCrc; + private readonly LodService _lodService; public TexMdlService(IGameInteropProvider interop) { interop.InitializeFromAttributes(this); + _lodService = new LodService(interop); if (HookSettings.ReplacementHooks) { _checkFileStateHook.Enable(); _loadMdlFileExternHook.Enable(); - _textureSomethingHook.Enable(); - _vf32Hook.Enable(); - //_loadTexFileExternHook.Enable(); + _textureOnLoadHook.Enable(); } } /// Add CRC64 if the given file is a model or texture file and has an associated path. public void AddCrc(ResourceType type, FullPath? path) { - if (path.HasValue && type is ResourceType.Mdl) - _customFileCrc.Add(path.Value.Crc64); + _ = type switch + { + ResourceType.Mdl when path.HasValue => _customMdlCrc.Add(path.Value.Crc64), + ResourceType.Tex when path.HasValue => _customTexCrc.Add(path.Value.Crc64), + _ => false, + }; } - /// Add a fixed CRC64 value. - public void AddCrc(ulong crc64) - => _customFileCrc.Add(crc64); - public void Dispose() { _checkFileStateHook.Dispose(); - //_loadTexFileExternHook.Dispose(); - _textureSomethingHook.Dispose(); _loadMdlFileExternHook.Dispose(); - _vf32Hook.Dispose(); + _textureOnLoadHook.Dispose(); } - private readonly HashSet _customFileCrc = []; + /// + /// We need to keep a list of all CRC64 hash values of our replaced Mdl and Tex files, + /// i.e. CRC32 of filename in the lower bytes, CRC32 of parent path in the upper bytes. + /// + private readonly HashSet _customMdlCrc = []; + + private readonly HashSet _customTexCrc = []; private delegate nint CheckFileStatePrototype(nint unk1, ulong crc64); - private delegate nint TextureSomethingDelegate(TextureResourceHandle* handle, int lod, SeFileDescriptor* descriptor); - [Signature(Sigs.CheckFileState, DetourName = nameof(CheckFileStateDetour))] private readonly Hook _checkFileStateHook = null!; - [Signature("E8 ?? ?? ?? ?? 0F B6 C8 EB ?? 4C 8B 83", DetourName = nameof(TextureSomethingDetour))] - private readonly Hook _textureSomethingHook = null!; - - private nint TextureSomethingDetour(TextureResourceHandle* handle, int lod, SeFileDescriptor* descriptor) - { - //Penumbra.Log.Information($"SomethingDetour {handle->Handle.FileName()}"); - //if (!handle->Handle.GamePath(out var path) || !path.IsRooted()) - return _textureSomethingHook.Original(handle, lod, descriptor); - - descriptor->FileMode = FileMode.LoadUnpackedResource; - return _loadTexFileLocal.Invoke((ResourceHandle*)handle, lod, (nint)descriptor, true); - } + private readonly ThreadLocal _texReturnData = new(() => default); /// /// The function that checks a files CRC64 to determine whether it is 'protected'. - /// We use it to check against our stored CRC64s and if it corresponds, we return the custom flag. + /// We use it to check against our stored CRC64s and if it corresponds, we return the custom flag for models. + /// Since Dawntrail inlined the RSF function for textures, we can not use the flag method here. + /// Instead, we signal the caller that this will fail and let it call the local function after intentionally failing. /// private nint CheckFileStateDetour(nint ptr, ulong crc64) - => _customFileCrc.Contains(crc64) ? CustomFileFlag : _checkFileStateHook.Original(ptr, crc64); + { + if (_customMdlCrc.Contains(crc64)) + return CustomFileFlag; + if (_customTexCrc.Contains(crc64)) + _texReturnData.Value = true; - private delegate byte LoadTexFileLocalDelegate(ResourceHandle* handle, int unk1, nint unk2, bool unk3); + return _checkFileStateHook.Original(ptr, crc64); + } + + private delegate byte LoadTexFileLocalDelegate(TextureResourceHandle* handle, int unk1, SeFileDescriptor* unk2, bool unk3); /// We use the local functions for our own files in the extern hook. [Signature(Sigs.LoadTexFileLocal)] @@ -99,36 +116,23 @@ public unsafe class TexMdlService : IDisposable, IRequiredService [Signature(Sigs.LoadMdlFileLocal)] private readonly LoadMdlFileLocalPrototype _loadMdlFileLocal = null!; + private delegate byte TexResourceHandleOnLoadPrototype(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2); - private delegate byte LoadTexFileExternPrototype(ResourceHandle* handle, int unk1, nint unk2, bool unk3, nint unk4); + [Signature(Sigs.TexResourceHandleOnLoad, DetourName = nameof(OnLoadDetour))] + private readonly Hook _textureOnLoadHook = null!; - private delegate byte TexResourceHandleVf32Prototype(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2); - - [Signature("40 53 55 41 54 41 55 41 56 41 57 48 81 EC ?? ?? ?? ?? 48 8B D9", DetourName = nameof(Vf32Detour))] - private readonly Hook _vf32Hook = null!; - - private byte Vf32Detour(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2) + private byte OnLoadDetour(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2) { - //if (handle->Handle.GamePath(out var path) && path.IsRooted()) - //{ - // Penumbra.Log.Information($"Replacing {descriptor->FileMode} with {FileMode.LoadSqPackResource} in VF32 for {path}."); - // descriptor->FileMode = FileMode.LoadSqPackResource; - //} + var ret = _textureOnLoadHook.Original(handle, descriptor, unk2); + if (!_texReturnData.Value) + return ret; - var ret = _vf32Hook.Original(handle, descriptor, unk2); - return ret; + // Function failed on a replaced texture, call local. + _texReturnData.Value = false; + return _loadTexFileLocal(handle, _lodService.GetLod(handle), descriptor, unk2 != 0); } - //[Signature(Sigs.LoadTexFileExtern, DetourName = nameof(LoadTexFileExternDetour))] - //private readonly Hook _loadTexFileExternHook = null!; - - /// We hook the extern functions to just return the local one if given the custom flag as last argument. - //private byte LoadTexFileExternDetour(ResourceHandle* resourceHandle, int unk1, nint unk2, bool unk3, nint ptr) - // => ptr.Equals(CustomFileFlag) - // ? _loadTexFileLocal.Invoke(resourceHandle, unk1, unk2, unk3) - // : _loadTexFileExternHook.Original(resourceHandle, unk1, unk2, unk3, ptr); - public delegate byte LoadMdlFileExternPrototype(ResourceHandle* handle, nint unk1, bool unk2, nint unk3); - + private delegate byte LoadMdlFileExternPrototype(ResourceHandle* handle, nint unk1, bool unk2, nint unk3); [Signature(Sigs.LoadMdlFileExtern, DetourName = nameof(LoadMdlFileExternDetour))] private readonly Hook _loadMdlFileExternHook = null!; diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 058b9004..6e428f25 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -14,6 +14,12 @@ public unsafe struct TextureResourceHandle [FieldOffset(0x0)] public CsHandle.TextureResourceHandle CsHandle; + + [FieldOffset(0x104)] + public byte SomeLodFlag; + + public bool ChangeLod + => (SomeLodFlag & 1) != 0; } public enum LoadState : byte From 1284037554fdeebd4e21d7a3ed846629b1c43e6b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Jul 2024 14:39:03 +0200 Subject: [PATCH 0718/1381] Fix some hooks. --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 10 ++-- .../Interop/Hooks/Meta/GetEqpIndirect2.cs | 1 - Penumbra/Interop/Hooks/Meta/GmpHook.cs | 47 ++++--------------- .../Interop/Hooks/Meta/ModelLoadComplete.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 10 ++-- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 9 ++-- .../Interop/Hooks/Objects/CopyCharacter.cs | 5 +- .../Hooks/Objects/CreateCharacterBase.cs | 6 +-- .../Interop/Structs/CharacterUtilityData.cs | 10 ++-- Penumbra/Interop/Structs/MetaIndex.cs | 13 +++-- 11 files changed, 40 insertions(+), 75 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 19923f8d..27d15145 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 19923f8d5649f11edcfae710c26d6273cf2e9d62 +Subproject commit 27d15145567c11e2bb1902857f8db25f02189390 diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index ed4eb669..9dd8d74f 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -4,11 +4,11 @@ public static class HookSettings { public const bool AllHooks = true; - public const bool ObjectHooks = false && AllHooks; + public const bool ObjectHooks = true && AllHooks; public const bool ReplacementHooks = true && AllHooks; - public const bool ResourceHooks = false && AllHooks; - public const bool MetaEntryHooks = false && AllHooks; - public const bool MetaParentHooks = false && AllHooks; + public const bool ResourceHooks = true && AllHooks; + public const bool MetaEntryHooks = true && AllHooks; + public const bool MetaParentHooks = true && AllHooks; public const bool VfxIdentificationHooks = false && AllHooks; - public const bool PostProcessingHooks = false && AllHooks; + public const bool PostProcessingHooks = true && AllHooks; } diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs index 3767c4a2..e90674a8 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs @@ -1,6 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; -using Penumbra.Collections; using Penumbra.GameData; using Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 329a8beb..12b221d9 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -1,3 +1,5 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Lumina.Data.Parsing.Uld; using OtterGui.Services; using Penumbra.GameData; using Penumbra.Interop.PathResolving; @@ -8,12 +10,10 @@ namespace Penumbra.Interop.Hooks.Meta; public unsafe class GmpHook : FastHook, IDisposable { - public delegate nint Delegate(nint gmpResource, uint dividedHeadId); + public delegate ulong Delegate(CharacterUtility* characterUtility, ulong* outputEntry, ushort setId); private readonly MetaState _metaState; - private static readonly Finalizer StablePointer = new(); - public GmpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; @@ -21,50 +21,21 @@ public unsafe class GmpHook : FastHook, IDisposable _metaState.Config.ModsEnabled += Toggle; } - /// - /// This function returns a pointer to the correct block in the GMP file, if it exists - cf. . - /// To work around this, we just have a single stable ulong accessible and offset the pointer to this by the required distance, - /// which is defined by the modulo of the original ID and the block size, if we return our own custom gmp entry. - /// - private nint Detour(nint gmpResource, uint dividedHeadId) + private ulong Detour(CharacterUtility* characterUtility, ulong* outputEntry, ushort setId) { - nint ret; + ulong ret; if (_metaState.GmpCollection.TryPeek(out var collection) && collection.Collection is { Valid: true, ModCollection.MetaCache: { } cache } && cache.Gmp.TryGetValue(new GmpIdentifier(collection.Id), out var entry)) - { - if (entry.Entry.Enabled) - { - *StablePointer.Pointer = entry.Entry.Value; - // This function already gets the original ID divided by the block size, so we can compute the modulo with a single multiplication and addition. - // We then go backwards from our pointer because this gets added by the calling functions. - ret = (nint)(StablePointer.Pointer - (collection.Id.Id - dividedHeadId * ExpandedEqpGmpBase.BlockSize)); - } - else - { - ret = nint.Zero; - } - } + ret = (*outputEntry) = entry.Entry.Enabled ? entry.Entry.Value : 0ul; else - { - ret = Task.Result.Original(gmpResource, dividedHeadId); - } + ret = Task.Result.Original(characterUtility, outputEntry, setId); - Penumbra.Log.Excessive($"[GetGmpFlags] Invoked on 0x{gmpResource:X} with {dividedHeadId}, returned {ret:X10}."); + Penumbra.Log.Excessive( + $"[GetGmpFlags] Invoked on 0x{(ulong)characterUtility:X} for {setId} with 0x{(ulong)outputEntry:X} (={*outputEntry:X}), returned {ret:X10}."); return ret; } - /// Allocate and clean up our single stable ulong pointer. - private class Finalizer - { - public readonly ulong* Pointer = (ulong*)Marshal.AllocHGlobal(8); - - ~Finalizer() - { - Marshal.FreeHGlobal((nint)Pointer); - } - } - public void Dispose() => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs index 79e7f6a6..c1803745 100644 --- a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -13,7 +13,7 @@ public sealed unsafe class ModelLoadComplete : FastHook("Model Load Complete", vtables.HumanVTable[58], Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Model Load Complete", vtables.HumanVTable[59], Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index eb8a8a37..e08dc393 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -10,8 +10,7 @@ namespace Penumbra.Interop.Hooks.Meta; public unsafe class RspBustHook : FastHook, IDisposable { - public delegate float* Delegate(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, - byte bustSize); + public delegate float* Delegate(nint cmpResource, float* storage, SubRace race, byte gender, byte bodyType, byte bustSize); private readonly MetaState _metaState; private readonly MetaFileManager _metaFileManager; @@ -24,7 +23,7 @@ public unsafe class RspBustHook : FastHook, IDisposable _metaState.Config.ModsEnabled += Toggle; } - private float* Detour(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte bustSize) + private float* Detour(nint cmpResource, float* storage, SubRace clan, byte gender, byte bodyType, byte bustSize) { if (gender == 0) { @@ -38,7 +37,6 @@ public unsafe class RspBustHook : FastHook, IDisposable if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var bustScale = bustSize / 100f; - var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var ptr = CmpFile.GetDefaults(_metaFileManager, clan, RspAttribute.BustMinX); storage[0] = GetValue(0, RspAttribute.BustMinX, RspAttribute.BustMaxX); storage[1] = GetValue(1, RspAttribute.BustMinY, RspAttribute.BustMaxY); @@ -58,11 +56,11 @@ public unsafe class RspBustHook : FastHook, IDisposable } else { - ret = Task.Result.Original(cmpResource, storage, race, gender, isSecondSubRace, bodyType, bustSize); + ret = Task.Result.Original(cmpResource, storage, clan, gender, bodyType, bustSize); } Penumbra.Log.Excessive( - $"[GetRspBust] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); + $"[GetRspBust] Invoked on 0x{cmpResource:X} with {clan}, {(Gender)(gender + 1)}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); return ret; } diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index f8f9e51e..20e3c939 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -10,7 +10,7 @@ namespace Penumbra.Interop.Hooks.Meta; public class RspHeightHook : FastHook, IDisposable { - public delegate float Delegate(nint cmpResource, Race clan, byte gender, byte isSecondSubRace, byte bodyType, byte height); + public delegate float Delegate(nint cmpResource, SubRace clan, byte gender, byte bodyType, byte height); private readonly MetaState _metaState; private readonly MetaFileManager _metaFileManager; @@ -23,7 +23,7 @@ public class RspHeightHook : FastHook, IDisposable _metaState.Config.ModsEnabled += Toggle; } - private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte height) + private unsafe float Detour(nint cmpResource, SubRace clan, byte gender, byte bodyType, byte height) { float scale; if (bodyType < 2 @@ -36,7 +36,6 @@ public class RspHeightHook : FastHook, IDisposable if (height > 100) height = 0; - var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 ? (new RspIdentifier(clan, RspAttribute.MaleMinSize), new RspIdentifier(clan, RspAttribute.MaleMaxSize)) : (new RspIdentifier(clan, RspAttribute.FemaleMinSize), new RspIdentifier(clan, RspAttribute.FemaleMaxSize)); @@ -68,11 +67,11 @@ public class RspHeightHook : FastHook, IDisposable } else { - scale = Task.Result.Original(cmpResource, race, gender, isSecondSubRace, bodyType, height); + scale = Task.Result.Original(cmpResource, clan, gender, bodyType, height); } Penumbra.Log.Excessive( - $"[GetRspHeight] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {height}, returned {scale}."); + $"[GetRspHeight] Invoked on 0x{cmpResource:X} with {clan}, {(Gender)(gender + 1)}, {bodyType}, {height}, returned {scale}."); return scale; } diff --git a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs index 663209ae..d81043c8 100644 --- a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs +++ b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs @@ -9,7 +9,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtr + /// CutsceneService = 0, } @@ -38,8 +38,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtrOwnerObject; Penumbra.Log.Verbose($"[{Name}] Triggered with target: 0x{(nint)target:X}, source : 0x{(nint)source:X} unk: {unk}."); Invoke(character, source); return _task.Result.Original(target, source, unk); diff --git a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs index 56b3d853..f00a9984 100644 --- a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs +++ b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs @@ -10,7 +10,7 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr + /// MetaState = 0, } @@ -64,10 +64,10 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr + /// DrawObjectState = 0, - /// + /// MetaState = 0, } } diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 22150cc1..d33da477 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -6,16 +6,16 @@ namespace Penumbra.Interop.Structs; public unsafe struct CharacterUtilityData { public const int IndexHumanPbd = 63; - public const int IndexTransparentTex = 72; - public const int IndexDecalTex = 73; - public const int IndexSkinShpk = 76; + public const int IndexTransparentTex = 79; + public const int IndexDecalTex = 80; + public const int IndexSkinShpk = 83; public static readonly MetaIndex[] EqdpIndices = Enum.GetNames() .Zip(Enum.GetValues()) .Where(n => n.First.StartsWith("Eqdp")) .Select(n => n.Second).ToArray(); - public const int TotalNumResources = 87; + public const int TotalNumResources = 89; /// Obtain the index for the eqdp file corresponding to the given race code and accessory. public static MetaIndex EqdpIdx(GenderRace raceCode, bool accessory) @@ -36,7 +36,7 @@ public unsafe struct CharacterUtilityData 1301 => accessory ? MetaIndex.Eqdp1301Acc : MetaIndex.Eqdp1301, 1401 => accessory ? MetaIndex.Eqdp1401Acc : MetaIndex.Eqdp1401, 1501 => accessory ? MetaIndex.Eqdp1501Acc : MetaIndex.Eqdp1501, - //1601 => accessory ? MetaIndex.Eqdp1601Acc : MetaIndex.Eqdp1601, Female Hrothgar + 1601 => accessory ? MetaIndex.Eqdp1601Acc : MetaIndex.Eqdp1601, 1701 => accessory ? MetaIndex.Eqdp1701Acc : MetaIndex.Eqdp1701, 1801 => accessory ? MetaIndex.Eqdp1801Acc : MetaIndex.Eqdp1801, 0104 => accessory ? MetaIndex.Eqdp0104Acc : MetaIndex.Eqdp0104, diff --git a/Penumbra/Interop/Structs/MetaIndex.cs b/Penumbra/Interop/Structs/MetaIndex.cs index 65302264..2ec5fce4 100644 --- a/Penumbra/Interop/Structs/MetaIndex.cs +++ b/Penumbra/Interop/Structs/MetaIndex.cs @@ -4,6 +4,7 @@ namespace Penumbra.Interop.Structs; public enum MetaIndex : int { Eqp = 0, + Evp = 1, Gmp = 2, Eqdp0101 = 3, @@ -21,9 +22,8 @@ public enum MetaIndex : int Eqdp1301, Eqdp1401, Eqdp1501, - - //Eqdp1601, // TODO: female Hrothgar - Eqdp1701 = Eqdp1501 + 2, + Eqdp1601, + Eqdp1701, Eqdp1801, Eqdp0104, Eqdp0204, @@ -51,9 +51,8 @@ public enum MetaIndex : int Eqdp1301Acc, Eqdp1401Acc, Eqdp1501Acc, - - //Eqdp1601Acc, // TODO: female Hrothgar - Eqdp1701Acc = Eqdp1501Acc + 2, + Eqdp1601Acc, + Eqdp1701Acc, Eqdp1801Acc, Eqdp0104Acc, Eqdp0204Acc, @@ -66,7 +65,7 @@ public enum MetaIndex : int Eqdp9104Acc, Eqdp9204Acc, - HumanCmp = 64, + HumanCmp = 71, FaceEst, HairEst, HeadEst, From 41d271213efb97c34d173f3759d110780bd81d5b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 5 Jul 2024 23:59:22 +0200 Subject: [PATCH 0719/1381] Update ShaderReplacementFixer for 7.0 --- .../PostProcessing/ShaderReplacementFixer.cs | 250 ++++++++++++++---- Penumbra/Interop/Services/ModelRenderer.cs | 82 +++++- Penumbra/UI/Tabs/Debug/DebugTab.cs | 97 +++++-- 3 files changed, 359 insertions(+), 70 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index b27ca4c5..b87d33ef 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -19,9 +19,24 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic public static ReadOnlySpan SkinShpkName => "skin.shpk"u8; + public static ReadOnlySpan IrisShpkName + => "iris.shpk"u8; + public static ReadOnlySpan CharacterGlassShpkName => "characterglass.shpk"u8; + public static ReadOnlySpan CharacterTransparencyShpkName + => "charactertransparency.shpk"u8; + + public static ReadOnlySpan CharacterTattooShpkName + => "charactertattoo.shpk"u8; + + public static ReadOnlySpan CharacterOcclusionShpkName + => "characterocclusion.shpk"u8; + + public static ReadOnlySpan HairMaskShpkName + => "hairmask.shpk"u8; + private delegate nint CharacterBaseOnRenderMaterialDelegate(CharacterBase* drawObject, CSModelRenderer.OnRenderMaterialParams* param); private delegate nint ModelRendererOnRenderMaterialDelegate(CSModelRenderer* modelRenderer, ushort* outFlags, @@ -36,26 +51,36 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private readonly CharacterUtility _utility; private readonly ModelRenderer _modelRenderer; - // MaterialResourceHandle set - private readonly ConcurrentSet _moddedSkinShpkMaterials = new(); - private readonly ConcurrentSet _moddedCharacterGlassShpkMaterials = new(); - - private readonly object _skinLock = new(); - private readonly object _characterGlassLock = new(); - - // ConcurrentDictionary.Count uses a lock in its current implementation. - private int _moddedSkinShpkCount; - private int _moddedCharacterGlassShpkCount; - private ulong _skinSlowPathCallDelta; - private ulong _characterGlassSlowPathCallDelta; + private readonly ModdedShaderPackageState _skinState; + private readonly ModdedShaderPackageState _irisState; + private readonly ModdedShaderPackageState _characterGlassState; + private readonly ModdedShaderPackageState _characterTransparencyState; + private readonly ModdedShaderPackageState _characterTattooState; + private readonly ModdedShaderPackageState _characterOcclusionState; + private readonly ModdedShaderPackageState _hairMaskState; public bool Enabled { get; internal set; } = true; - public int ModdedSkinShpkCount - => _moddedSkinShpkCount; + public uint ModdedSkinShpkCount + => _skinState.MaterialCount; - public int ModdedCharacterGlassShpkCount - => _moddedCharacterGlassShpkCount; + public uint ModdedIrisShpkCount + => _irisState.MaterialCount; + + public uint ModdedCharacterGlassShpkCount + => _characterGlassState.MaterialCount; + + public uint ModdedCharacterTransparencyShpkCount + => _characterTransparencyState.MaterialCount; + + public uint ModdedCharacterTattooShpkCount + => _characterTattooState.MaterialCount; + + public uint ModdedCharacterOcclusionShpkCount + => _characterOcclusionState.MaterialCount; + + public uint ModdedHairMaskShpkCount + => _hairMaskState.MaterialCount; public ShaderReplacementFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, ModelRenderer modelRenderer, CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables) @@ -64,7 +89,18 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _utility = utility; _modelRenderer = modelRenderer; _communicator = communicator; - _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[62], + + _skinState = new( + () => (ShaderPackageResourceHandle**)&_utility.Address->SkinShpkResource, + () => (ShaderPackageResourceHandle*)_utility.DefaultSkinShpkResource); + _irisState = new(() => _modelRenderer.IrisShaderPackage, () => _modelRenderer.DefaultIrisShaderPackage); + _characterGlassState = new(() => _modelRenderer.CharacterGlassShaderPackage, () => _modelRenderer.DefaultCharacterGlassShaderPackage); + _characterTransparencyState = new(() => _modelRenderer.CharacterTransparencyShaderPackage, () => _modelRenderer.DefaultCharacterTransparencyShaderPackage); + _characterTattooState = new(() => _modelRenderer.CharacterTattooShaderPackage, () => _modelRenderer.DefaultCharacterTattooShaderPackage); + _characterOcclusionState = new(() => _modelRenderer.CharacterOcclusionShaderPackage, () => _modelRenderer.DefaultCharacterOcclusionShaderPackage); + _hairMaskState = new(() => _modelRenderer.HairMaskShaderPackage, () => _modelRenderer.DefaultHairMaskShaderPackage); + + _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[64], OnRenderHumanMaterial, HookSettings.PostProcessingHooks).Result; _modelRendererOnRenderMaterialHook = hooks.CreateHook("ModelRenderer.OnRenderMaterial", Sigs.ModelRendererOnRenderMaterial, ModelRendererOnRenderMaterialDetour, HookSettings.PostProcessingHooks).Result; @@ -78,14 +114,23 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _humanOnRenderMaterialHook.Dispose(); _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); - _moddedCharacterGlassShpkMaterials.Clear(); - _moddedSkinShpkMaterials.Clear(); - _moddedCharacterGlassShpkCount = 0; - _moddedSkinShpkCount = 0; + _hairMaskState.ClearMaterials(); + _characterOcclusionState.ClearMaterials(); + _characterTattooState.ClearMaterials(); + _characterTransparencyState.ClearMaterials(); + _characterGlassState.ClearMaterials(); + _irisState.ClearMaterials(); + _skinState.ClearMaterials(); } - public (ulong Skin, ulong CharacterGlass) GetAndResetSlowPathCallDeltas() - => (Interlocked.Exchange(ref _skinSlowPathCallDelta, 0), Interlocked.Exchange(ref _characterGlassSlowPathCallDelta, 0)); + public (ulong Skin, ulong Iris, ulong CharacterGlass, ulong CharacterTransparency, ulong CharacterTattoo, ulong CharacterOcclusion, ulong HairMask) GetAndResetSlowPathCallDeltas() + => (_skinState.GetAndResetSlowPathCallDelta(), + _irisState.GetAndResetSlowPathCallDelta(), + _characterGlassState.GetAndResetSlowPathCallDelta(), + _characterTransparencyState.GetAndResetSlowPathCallDelta(), + _characterTattooState.GetAndResetSlowPathCallDelta(), + _characterOcclusionState.GetAndResetSlowPathCallDelta(), + _hairMaskState.GetAndResetSlowPathCallDelta()); private static bool IsMaterialWithShpk(MaterialResourceHandle* mtrlResource, ReadOnlySpan shpkName) { @@ -102,54 +147,99 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (shpk == null) return; - var shpkName = mtrl->ShpkNameSpan; + var shpkName = mtrl->ShpkNameSpan; + var shpkState = GetStateForHuman(shpkName) ?? GetStateForModelRenderer(shpkName); - if (SkinShpkName.SequenceEqual(shpkName) && (nint)shpk != _utility.DefaultSkinShpkResource) - if (_moddedSkinShpkMaterials.TryAdd(mtrlResourceHandle)) - Interlocked.Increment(ref _moddedSkinShpkCount); - - if (CharacterGlassShpkName.SequenceEqual(shpkName) && shpk != _modelRenderer.DefaultCharacterGlassShaderPackage) - if (_moddedCharacterGlassShpkMaterials.TryAdd(mtrlResourceHandle)) - Interlocked.Increment(ref _moddedCharacterGlassShpkCount); + if (shpkState != null && shpk != shpkState.DefaultShaderPackage) + shpkState.TryAddMaterial(mtrlResourceHandle); } private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) { - if (_moddedSkinShpkMaterials.TryRemove((nint)handle)) - Interlocked.Decrement(ref _moddedSkinShpkCount); - - if (_moddedCharacterGlassShpkMaterials.TryRemove((nint)handle)) - Interlocked.Decrement(ref _moddedCharacterGlassShpkCount); + _skinState.TryRemoveMaterial(handle); + _irisState.TryRemoveMaterial(handle); + _characterGlassState.TryRemoveMaterial(handle); + _characterTransparencyState.TryRemoveMaterial(handle); + _characterTattooState.TryRemoveMaterial(handle); + _characterOcclusionState.TryRemoveMaterial(handle); + _hairMaskState.TryRemoveMaterial(handle); } + private ModdedShaderPackageState? GetStateForHuman(MaterialResourceHandle* mtrlResource) + => mtrlResource == null ? null : GetStateForHuman(mtrlResource->ShpkNameSpan); + + private ModdedShaderPackageState? GetStateForHuman(ReadOnlySpan shpkName) + { + if (SkinShpkName.SequenceEqual(shpkName)) + return _skinState; + + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private uint GetTotalMaterialCountForHuman() + => _skinState.MaterialCount; + + private ModdedShaderPackageState? GetStateForModelRenderer(MaterialResourceHandle* mtrlResource) + => mtrlResource == null ? null : GetStateForModelRenderer(mtrlResource->ShpkNameSpan); + + private ModdedShaderPackageState? GetStateForModelRenderer(ReadOnlySpan shpkName) + { + if (IrisShpkName.SequenceEqual(shpkName)) + return _irisState; + + if (CharacterGlassShpkName.SequenceEqual(shpkName)) + return _characterGlassState; + + if (CharacterTransparencyShpkName.SequenceEqual(shpkName)) + return _characterTransparencyState; + + if (CharacterTattooShpkName.SequenceEqual(shpkName)) + return _characterTattooState; + + if (CharacterOcclusionShpkName.SequenceEqual(shpkName)) + return _characterOcclusionState; + + if (HairMaskShpkName.SequenceEqual(shpkName)) + return _hairMaskState; + + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private uint GetTotalMaterialCountForModelRenderer() + => _irisState.MaterialCount + _characterGlassState.MaterialCount + _characterTransparencyState.MaterialCount + _characterTattooState.MaterialCount + _characterOcclusionState.MaterialCount + _hairMaskState.MaterialCount; + private nint OnRenderHumanMaterial(CharacterBase* human, CSModelRenderer.OnRenderMaterialParams* param) { // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. - if (!Enabled || _moddedSkinShpkCount == 0) + if (!Enabled || GetTotalMaterialCountForHuman() == 0) return _humanOnRenderMaterialHook.Original(human, param); var material = param->Model->Materials[param->MaterialIndex]; var mtrlResource = material->MaterialResourceHandle; - if (!IsMaterialWithShpk(mtrlResource, SkinShpkName)) + var shpkState = GetStateForHuman(mtrlResource); + if (shpkState == null) return _humanOnRenderMaterialHook.Original(human, param); - Interlocked.Increment(ref _skinSlowPathCallDelta); + shpkState.IncrementSlowPathCallDelta(); // Performance considerations: // - This function is called from several threads simultaneously, hence the need for synchronization in the swapping path ; // - Function is called each frame for each material on screen, after culling, i.e. up to thousands of times a frame in crowded areas ; // - Swapping path is taken up to hundreds of times a frame. // At the time of writing, the lock doesn't seem to have a noticeable impact in either frame rate or CPU usage, but the swapping path shall still be avoided as much as possible. - lock (_skinLock) + lock (shpkState) { + var shpkReference = shpkState.ShaderPackageReference; try { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)mtrlResource->ShaderPackageResourceHandle; + *shpkReference = mtrlResource->ShaderPackageResourceHandle; return _humanOnRenderMaterialHook.Original(human, param); } finally { - _utility.Address->SkinShpkResource = (Structs.ResourceHandle*)_utility.DefaultSkinShpkResource; + *shpkReference = shpkState.DefaultShaderPackage; } } } @@ -158,27 +248,91 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex) { // If we don't have any on-screen instances of modded characterglass.shpk, we don't need the slow path at all. - if (!Enabled || _moddedCharacterGlassShpkCount == 0) + if (!Enabled || GetTotalMaterialCountForModelRenderer() == 0) return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); var mtrlResource = material->MaterialResourceHandle; - if (!IsMaterialWithShpk(mtrlResource, CharacterGlassShpkName)) + var shpkState = GetStateForModelRenderer(mtrlResource); + if (shpkState == null) return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); - Interlocked.Increment(ref _characterGlassSlowPathCallDelta); + shpkState.IncrementSlowPathCallDelta(); // Same performance considerations as above. - lock (_characterGlassLock) + lock (shpkState) { + var shpkReference = shpkState.ShaderPackageReference; try { - *_modelRenderer.CharacterGlassShaderPackage = mtrlResource->ShaderPackageResourceHandle; + *shpkReference = mtrlResource->ShaderPackageResourceHandle; return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); } finally { - *_modelRenderer.CharacterGlassShaderPackage = _modelRenderer.DefaultCharacterGlassShaderPackage; + *shpkReference = shpkState.DefaultShaderPackage; } } } + + private sealed class ModdedShaderPackageState(ShaderPackageReferenceGetter referenceGetter, DefaultShaderPackageGetter defaultGetter) + { + // MaterialResourceHandle set + private readonly ConcurrentSet _materials = new(); + + // ConcurrentDictionary.Count uses a lock in its current implementation. + private uint _materialCount = 0; + + private ulong _slowPathCallDelta = 0; + + public uint MaterialCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + get => _materialCount; + } + + public ShaderPackageResourceHandle** ShaderPackageReference + { + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + get => referenceGetter(); + } + + public ShaderPackageResourceHandle* DefaultShaderPackage + { + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + get => defaultGetter(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void TryAddMaterial(nint mtrlResourceHandle) + { + if (_materials.TryAdd(mtrlResourceHandle)) + Interlocked.Increment(ref _materialCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void TryRemoveMaterial(Structs.ResourceHandle* handle) + { + if (_materials.TryRemove((nint)handle)) + Interlocked.Decrement(ref _materialCount); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void ClearMaterials() + { + _materials.Clear(); + _materialCount = 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public void IncrementSlowPathCallDelta() + => Interlocked.Increment(ref _slowPathCallDelta); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public ulong GetAndResetSlowPathCallDelta() + => Interlocked.Exchange(ref _slowPathCallDelta, 0); + } + + private delegate ShaderPackageResourceHandle* DefaultShaderPackageGetter(); + + private delegate ShaderPackageResourceHandle** ShaderPackageReferenceGetter(); } diff --git a/Penumbra/Interop/Services/ModelRenderer.cs b/Penumbra/Interop/Services/ModelRenderer.cs index b268b395..10f3977f 100644 --- a/Penumbra/Interop/Services/ModelRenderer.cs +++ b/Penumbra/Interop/Services/ModelRenderer.cs @@ -9,6 +9,13 @@ public unsafe class ModelRenderer : IDisposable, IRequiredService { public bool Ready { get; private set; } + public ShaderPackageResourceHandle** IrisShaderPackage + => Manager.Instance() switch + { + null => null, + var renderManager => &renderManager->ModelRenderer.IrisShaderPackage, + }; + public ShaderPackageResourceHandle** CharacterGlassShaderPackage => Manager.Instance() switch { @@ -16,8 +23,46 @@ public unsafe class ModelRenderer : IDisposable, IRequiredService var renderManager => &renderManager->ModelRenderer.CharacterGlassShaderPackage, }; + public ShaderPackageResourceHandle** CharacterTransparencyShaderPackage + => Manager.Instance() switch + { + null => null, + var renderManager => &renderManager->ModelRenderer.CharacterTransparencyShaderPackage, + }; + + public ShaderPackageResourceHandle** CharacterTattooShaderPackage + => Manager.Instance() switch + { + null => null, + var renderManager => &renderManager->ModelRenderer.CharacterTattooShaderPackage, + }; + + public ShaderPackageResourceHandle** CharacterOcclusionShaderPackage + => Manager.Instance() switch + { + null => null, + var renderManager => &renderManager->ModelRenderer.CharacterOcclusionShaderPackage, + }; + + public ShaderPackageResourceHandle** HairMaskShaderPackage + => Manager.Instance() switch + { + null => null, + var renderManager => &renderManager->ModelRenderer.HairMaskShaderPackage, + }; + + public ShaderPackageResourceHandle* DefaultIrisShaderPackage { get; private set; } + public ShaderPackageResourceHandle* DefaultCharacterGlassShaderPackage { get; private set; } + public ShaderPackageResourceHandle* DefaultCharacterTransparencyShaderPackage { get; private set; } + + public ShaderPackageResourceHandle* DefaultCharacterTattooShaderPackage { get; private set; } + + public ShaderPackageResourceHandle* DefaultCharacterOcclusionShaderPackage { get; private set; } + + public ShaderPackageResourceHandle* DefaultHairMaskShaderPackage { get; private set; } + private readonly IFramework _framework; public ModelRenderer(IFramework framework) @@ -36,12 +81,42 @@ public unsafe class ModelRenderer : IDisposable, IRequiredService var anyMissing = false; + if (DefaultIrisShaderPackage == null) + { + DefaultIrisShaderPackage = *IrisShaderPackage; + anyMissing |= DefaultIrisShaderPackage == null; + } + if (DefaultCharacterGlassShaderPackage == null) { DefaultCharacterGlassShaderPackage = *CharacterGlassShaderPackage; anyMissing |= DefaultCharacterGlassShaderPackage == null; } + if (DefaultCharacterTransparencyShaderPackage == null) + { + DefaultCharacterTransparencyShaderPackage = *CharacterTransparencyShaderPackage; + anyMissing |= DefaultCharacterTransparencyShaderPackage == null; + } + + if (DefaultCharacterTattooShaderPackage == null) + { + DefaultCharacterTattooShaderPackage = *CharacterTattooShaderPackage; + anyMissing |= DefaultCharacterTattooShaderPackage == null; + } + + if (DefaultCharacterOcclusionShaderPackage == null) + { + DefaultCharacterOcclusionShaderPackage = *CharacterOcclusionShaderPackage; + anyMissing |= DefaultCharacterOcclusionShaderPackage == null; + } + + if (DefaultHairMaskShaderPackage == null) + { + DefaultHairMaskShaderPackage = *HairMaskShaderPackage; + anyMissing |= DefaultHairMaskShaderPackage == null; + } + if (anyMissing) return; @@ -55,7 +130,12 @@ public unsafe class ModelRenderer : IDisposable, IRequiredService if (!Ready) return; - *CharacterGlassShaderPackage = DefaultCharacterGlassShaderPackage; + *HairMaskShaderPackage = DefaultHairMaskShaderPackage; + *CharacterOcclusionShaderPackage = DefaultCharacterOcclusionShaderPackage; + *CharacterTattooShaderPackage = DefaultCharacterTattooShaderPackage; + *CharacterTransparencyShaderPackage = DefaultCharacterTransparencyShaderPackage; + *CharacterGlassShaderPackage = DefaultCharacterGlassShaderPackage; + *IrisShaderPackage = DefaultIrisShaderPackage; } public void Dispose() diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 9a03f384..0c2581bf 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -177,6 +177,8 @@ public class DebugTab : Window, ITab, IUiService ImGui.NewLine(); DrawDebugCharacterUtility(); ImGui.NewLine(); + DrawShaderReplacementFixer(); + ImGui.NewLine(); DrawData(); ImGui.NewLine(); DrawResourceProblems(); @@ -711,27 +713,6 @@ public class DebugTab : Window, ITab, IUiService if (!ImGui.CollapsingHeader("Character Utility")) return; - var enableShaderReplacementFixer = _shaderReplacementFixer.Enabled; - if (ImGui.Checkbox("Enable Shader Replacement Fixer", ref enableShaderReplacementFixer)) - _shaderReplacementFixer.Enabled = enableShaderReplacementFixer; - - if (enableShaderReplacementFixer) - { - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); - var slowPathCallDeltas = _shaderReplacementFixer.GetAndResetSlowPathCallDeltas(); - ImGui.SameLine(); - ImGui.TextUnformatted($"\u0394 Slow-Path Calls for skin.shpk: {slowPathCallDeltas.Skin}"); - ImGui.SameLine(); - ImGui.TextUnformatted($"characterglass.shpk: {slowPathCallDeltas.CharacterGlass}"); - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); - ImGui.SameLine(); - ImGui.TextUnformatted($"Materials with Modded skin.shpk: {_shaderReplacementFixer.ModdedSkinShpkCount}"); - ImGui.SameLine(); - ImGui.TextUnformatted($"characterglass.shpk: {_shaderReplacementFixer.ModdedCharacterGlassShpkCount}"); - } - using var table = Table("##CharacterUtility", 7, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) @@ -786,6 +767,80 @@ public class DebugTab : Window, ITab, IUiService } } + private void DrawShaderReplacementFixer() + { + if (!ImGui.CollapsingHeader("Shader Replacement Fixer")) + return; + + var enableShaderReplacementFixer = _shaderReplacementFixer.Enabled; + if (ImGui.Checkbox("Enable Shader Replacement Fixer", ref enableShaderReplacementFixer)) + _shaderReplacementFixer.Enabled = enableShaderReplacementFixer; + + if (!enableShaderReplacementFixer) + return; + + using var table = Table("##ShaderReplacementFixer", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + -Vector2.UnitX); + if (!table) + return; + + var slowPathCallDeltas = _shaderReplacementFixer.GetAndResetSlowPathCallDeltas(); + + ImGui.TableSetupColumn("Shader Package Name", ImGuiTableColumnFlags.WidthStretch, 0.6f); + ImGui.TableSetupColumn("Materials with Modded ShPk", ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImGui.TableSetupColumn("\u0394 Slow-Path Calls", ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImGui.TableHeadersRow(); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("skin.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedSkinShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.Skin}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("iris.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedIrisShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.Iris}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("characterglass.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterGlassShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterGlass}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("charactertransparency.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterTransparencyShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterTransparency}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("charactertattoo.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterTattooShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterTattoo}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("characterocclusion.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterOcclusionShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterOcclusion}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("hairmask.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedHairMaskShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.HairMask}"); + } + /// Draw information about the resident resource files. private unsafe void DrawDebugResidentResources() { From 68135f3757eb4de0cd7ce83f37c7d7a6544656fd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 5 Jul 2024 14:39:03 +0200 Subject: [PATCH 0720/1381] Update Gamedata --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 10 ++-- .../Interop/Hooks/Meta/GetEqpIndirect2.cs | 1 - Penumbra/Interop/Hooks/Meta/GmpHook.cs | 47 ++++--------------- .../Interop/Hooks/Meta/ModelLoadComplete.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 10 ++-- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 9 ++-- .../Interop/Hooks/Objects/CopyCharacter.cs | 5 +- .../Hooks/Objects/CreateCharacterBase.cs | 6 +-- .../Interop/Structs/CharacterUtilityData.cs | 10 ++-- Penumbra/Interop/Structs/MetaIndex.cs | 13 +++-- 11 files changed, 40 insertions(+), 75 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 19923f8d..62f6acfb 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 19923f8d5649f11edcfae710c26d6273cf2e9d62 +Subproject commit 62f6acfb0f9e31b2907c02a270d723bfff18b390 diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index ed4eb669..9dd8d74f 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -4,11 +4,11 @@ public static class HookSettings { public const bool AllHooks = true; - public const bool ObjectHooks = false && AllHooks; + public const bool ObjectHooks = true && AllHooks; public const bool ReplacementHooks = true && AllHooks; - public const bool ResourceHooks = false && AllHooks; - public const bool MetaEntryHooks = false && AllHooks; - public const bool MetaParentHooks = false && AllHooks; + public const bool ResourceHooks = true && AllHooks; + public const bool MetaEntryHooks = true && AllHooks; + public const bool MetaParentHooks = true && AllHooks; public const bool VfxIdentificationHooks = false && AllHooks; - public const bool PostProcessingHooks = false && AllHooks; + public const bool PostProcessingHooks = true && AllHooks; } diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs index 3767c4a2..e90674a8 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs +++ b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs @@ -1,6 +1,5 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; -using Penumbra.Collections; using Penumbra.GameData; using Penumbra.Interop.PathResolving; diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 329a8beb..12b221d9 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -1,3 +1,5 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using Lumina.Data.Parsing.Uld; using OtterGui.Services; using Penumbra.GameData; using Penumbra.Interop.PathResolving; @@ -8,12 +10,10 @@ namespace Penumbra.Interop.Hooks.Meta; public unsafe class GmpHook : FastHook, IDisposable { - public delegate nint Delegate(nint gmpResource, uint dividedHeadId); + public delegate ulong Delegate(CharacterUtility* characterUtility, ulong* outputEntry, ushort setId); private readonly MetaState _metaState; - private static readonly Finalizer StablePointer = new(); - public GmpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; @@ -21,50 +21,21 @@ public unsafe class GmpHook : FastHook, IDisposable _metaState.Config.ModsEnabled += Toggle; } - /// - /// This function returns a pointer to the correct block in the GMP file, if it exists - cf. . - /// To work around this, we just have a single stable ulong accessible and offset the pointer to this by the required distance, - /// which is defined by the modulo of the original ID and the block size, if we return our own custom gmp entry. - /// - private nint Detour(nint gmpResource, uint dividedHeadId) + private ulong Detour(CharacterUtility* characterUtility, ulong* outputEntry, ushort setId) { - nint ret; + ulong ret; if (_metaState.GmpCollection.TryPeek(out var collection) && collection.Collection is { Valid: true, ModCollection.MetaCache: { } cache } && cache.Gmp.TryGetValue(new GmpIdentifier(collection.Id), out var entry)) - { - if (entry.Entry.Enabled) - { - *StablePointer.Pointer = entry.Entry.Value; - // This function already gets the original ID divided by the block size, so we can compute the modulo with a single multiplication and addition. - // We then go backwards from our pointer because this gets added by the calling functions. - ret = (nint)(StablePointer.Pointer - (collection.Id.Id - dividedHeadId * ExpandedEqpGmpBase.BlockSize)); - } - else - { - ret = nint.Zero; - } - } + ret = (*outputEntry) = entry.Entry.Enabled ? entry.Entry.Value : 0ul; else - { - ret = Task.Result.Original(gmpResource, dividedHeadId); - } + ret = Task.Result.Original(characterUtility, outputEntry, setId); - Penumbra.Log.Excessive($"[GetGmpFlags] Invoked on 0x{gmpResource:X} with {dividedHeadId}, returned {ret:X10}."); + Penumbra.Log.Excessive( + $"[GetGmpFlags] Invoked on 0x{(ulong)characterUtility:X} for {setId} with 0x{(ulong)outputEntry:X} (={*outputEntry:X}), returned {ret:X10}."); return ret; } - /// Allocate and clean up our single stable ulong pointer. - private class Finalizer - { - public readonly ulong* Pointer = (ulong*)Marshal.AllocHGlobal(8); - - ~Finalizer() - { - Marshal.FreeHGlobal((nint)Pointer); - } - } - public void Dispose() => _metaState.Config.ModsEnabled -= Toggle; } diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs index 79e7f6a6..c1803745 100644 --- a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -13,7 +13,7 @@ public sealed unsafe class ModelLoadComplete : FastHook("Model Load Complete", vtables.HumanVTable[58], Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Model Load Complete", vtables.HumanVTable[59], Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index eb8a8a37..e08dc393 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -10,8 +10,7 @@ namespace Penumbra.Interop.Hooks.Meta; public unsafe class RspBustHook : FastHook, IDisposable { - public delegate float* Delegate(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, - byte bustSize); + public delegate float* Delegate(nint cmpResource, float* storage, SubRace race, byte gender, byte bodyType, byte bustSize); private readonly MetaState _metaState; private readonly MetaFileManager _metaFileManager; @@ -24,7 +23,7 @@ public unsafe class RspBustHook : FastHook, IDisposable _metaState.Config.ModsEnabled += Toggle; } - private float* Detour(nint cmpResource, float* storage, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte bustSize) + private float* Detour(nint cmpResource, float* storage, SubRace clan, byte gender, byte bodyType, byte bustSize) { if (gender == 0) { @@ -38,7 +37,6 @@ public unsafe class RspBustHook : FastHook, IDisposable if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var bustScale = bustSize / 100f; - var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var ptr = CmpFile.GetDefaults(_metaFileManager, clan, RspAttribute.BustMinX); storage[0] = GetValue(0, RspAttribute.BustMinX, RspAttribute.BustMaxX); storage[1] = GetValue(1, RspAttribute.BustMinY, RspAttribute.BustMaxY); @@ -58,11 +56,11 @@ public unsafe class RspBustHook : FastHook, IDisposable } else { - ret = Task.Result.Original(cmpResource, storage, race, gender, isSecondSubRace, bodyType, bustSize); + ret = Task.Result.Original(cmpResource, storage, clan, gender, bodyType, bustSize); } Penumbra.Log.Excessive( - $"[GetRspBust] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); + $"[GetRspBust] Invoked on 0x{cmpResource:X} with {clan}, {(Gender)(gender + 1)}, {bodyType}, {bustSize}, returned {storage[0]}, {storage[1]}, {storage[2]}."); return ret; } diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index f8f9e51e..20e3c939 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -10,7 +10,7 @@ namespace Penumbra.Interop.Hooks.Meta; public class RspHeightHook : FastHook, IDisposable { - public delegate float Delegate(nint cmpResource, Race clan, byte gender, byte isSecondSubRace, byte bodyType, byte height); + public delegate float Delegate(nint cmpResource, SubRace clan, byte gender, byte bodyType, byte height); private readonly MetaState _metaState; private readonly MetaFileManager _metaFileManager; @@ -23,7 +23,7 @@ public class RspHeightHook : FastHook, IDisposable _metaState.Config.ModsEnabled += Toggle; } - private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte height) + private unsafe float Detour(nint cmpResource, SubRace clan, byte gender, byte bodyType, byte height) { float scale; if (bodyType < 2 @@ -36,7 +36,6 @@ public class RspHeightHook : FastHook, IDisposable if (height > 100) height = 0; - var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 ? (new RspIdentifier(clan, RspAttribute.MaleMinSize), new RspIdentifier(clan, RspAttribute.MaleMaxSize)) : (new RspIdentifier(clan, RspAttribute.FemaleMinSize), new RspIdentifier(clan, RspAttribute.FemaleMaxSize)); @@ -68,11 +67,11 @@ public class RspHeightHook : FastHook, IDisposable } else { - scale = Task.Result.Original(cmpResource, race, gender, isSecondSubRace, bodyType, height); + scale = Task.Result.Original(cmpResource, clan, gender, bodyType, height); } Penumbra.Log.Excessive( - $"[GetRspHeight] Invoked on 0x{cmpResource:X} with {race}, {(Gender)(gender + 1)}, {isSecondSubRace == 1}, {bodyType}, {height}, returned {scale}."); + $"[GetRspHeight] Invoked on 0x{cmpResource:X} with {clan}, {(Gender)(gender + 1)}, {bodyType}, {height}, returned {scale}."); return scale; } diff --git a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs index 663209ae..d81043c8 100644 --- a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs +++ b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs @@ -9,7 +9,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtr + /// CutsceneService = 0, } @@ -38,8 +38,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtrOwnerObject; Penumbra.Log.Verbose($"[{Name}] Triggered with target: 0x{(nint)target:X}, source : 0x{(nint)source:X} unk: {unk}."); Invoke(character, source); return _task.Result.Original(target, source, unk); diff --git a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs index 56b3d853..f00a9984 100644 --- a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs +++ b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs @@ -10,7 +10,7 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr + /// MetaState = 0, } @@ -64,10 +64,10 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr + /// DrawObjectState = 0, - /// + /// MetaState = 0, } } diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 22150cc1..d33da477 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -6,16 +6,16 @@ namespace Penumbra.Interop.Structs; public unsafe struct CharacterUtilityData { public const int IndexHumanPbd = 63; - public const int IndexTransparentTex = 72; - public const int IndexDecalTex = 73; - public const int IndexSkinShpk = 76; + public const int IndexTransparentTex = 79; + public const int IndexDecalTex = 80; + public const int IndexSkinShpk = 83; public static readonly MetaIndex[] EqdpIndices = Enum.GetNames() .Zip(Enum.GetValues()) .Where(n => n.First.StartsWith("Eqdp")) .Select(n => n.Second).ToArray(); - public const int TotalNumResources = 87; + public const int TotalNumResources = 89; /// Obtain the index for the eqdp file corresponding to the given race code and accessory. public static MetaIndex EqdpIdx(GenderRace raceCode, bool accessory) @@ -36,7 +36,7 @@ public unsafe struct CharacterUtilityData 1301 => accessory ? MetaIndex.Eqdp1301Acc : MetaIndex.Eqdp1301, 1401 => accessory ? MetaIndex.Eqdp1401Acc : MetaIndex.Eqdp1401, 1501 => accessory ? MetaIndex.Eqdp1501Acc : MetaIndex.Eqdp1501, - //1601 => accessory ? MetaIndex.Eqdp1601Acc : MetaIndex.Eqdp1601, Female Hrothgar + 1601 => accessory ? MetaIndex.Eqdp1601Acc : MetaIndex.Eqdp1601, 1701 => accessory ? MetaIndex.Eqdp1701Acc : MetaIndex.Eqdp1701, 1801 => accessory ? MetaIndex.Eqdp1801Acc : MetaIndex.Eqdp1801, 0104 => accessory ? MetaIndex.Eqdp0104Acc : MetaIndex.Eqdp0104, diff --git a/Penumbra/Interop/Structs/MetaIndex.cs b/Penumbra/Interop/Structs/MetaIndex.cs index 65302264..2ec5fce4 100644 --- a/Penumbra/Interop/Structs/MetaIndex.cs +++ b/Penumbra/Interop/Structs/MetaIndex.cs @@ -4,6 +4,7 @@ namespace Penumbra.Interop.Structs; public enum MetaIndex : int { Eqp = 0, + Evp = 1, Gmp = 2, Eqdp0101 = 3, @@ -21,9 +22,8 @@ public enum MetaIndex : int Eqdp1301, Eqdp1401, Eqdp1501, - - //Eqdp1601, // TODO: female Hrothgar - Eqdp1701 = Eqdp1501 + 2, + Eqdp1601, + Eqdp1701, Eqdp1801, Eqdp0104, Eqdp0204, @@ -51,9 +51,8 @@ public enum MetaIndex : int Eqdp1301Acc, Eqdp1401Acc, Eqdp1501Acc, - - //Eqdp1601Acc, // TODO: female Hrothgar - Eqdp1701Acc = Eqdp1501Acc + 2, + Eqdp1601Acc, + Eqdp1701Acc, Eqdp1801Acc, Eqdp0104Acc, Eqdp0204Acc, @@ -66,7 +65,7 @@ public enum MetaIndex : int Eqdp9104Acc, Eqdp9204Acc, - HumanCmp = 64, + HumanCmp = 71, FaceEst, HairEst, HeadEst, From 4f0f3721a6296e0fad1c816c06e42d0ac3cf0de0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jul 2024 16:16:58 +0200 Subject: [PATCH 0721/1381] Update animation hooks. --- Penumbra/Interop/Hooks/Animation/Dismount.cs | 13 ++++---- .../Interop/Hooks/Animation/LoadAreaVfx.cs | 8 ++--- .../Hooks/Animation/LoadCharacterSound.cs | 16 ++++++---- .../Hooks/Animation/LoadTimelineResources.cs | 32 +++++++++---------- Penumbra/Interop/Hooks/HookSettings.cs | 2 +- .../Hooks/ResourceLoading/ResourceLoader.cs | 30 +++++++++-------- .../Hooks/ResourceLoading/TexMdlService.cs | 18 +++++++++-- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- Penumbra/Interop/Structs/ClipScheduler.cs | 4 ++- Penumbra/Interop/Structs/StructExtensions.cs | 12 +++---- Penumbra/UI/Tabs/Debug/DebugTab.cs | 7 ++-- 11 files changed, 83 insertions(+), 61 deletions(-) diff --git a/Penumbra/Interop/Hooks/Animation/Dismount.cs b/Penumbra/Interop/Hooks/Animation/Dismount.cs index 523e750c..034011e7 100644 --- a/Penumbra/Interop/Hooks/Animation/Dismount.cs +++ b/Penumbra/Interop/Hooks/Animation/Dismount.cs @@ -1,3 +1,4 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.GameData; @@ -18,26 +19,26 @@ public sealed unsafe class Dismount : FastHook Task = hooks.CreateHook("Dismount", Sigs.Dismount, Detour, HookSettings.VfxIdentificationHooks); } - public delegate void Delegate(nint a1, nint a2); + public delegate void Delegate(MountContainer* a1, nint a2); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void Detour(nint a1, nint a2) + private void Detour(MountContainer* a1, nint a2) { - Penumbra.Log.Excessive($"[Dismount] Invoked on {a1:X} with {a2:X}."); - if (a1 == nint.Zero) + Penumbra.Log.Excessive($"[Dismount] Invoked on 0x{(nint)a1:X} with {a2:X}."); + if (a1 == null) { Task.Result.Original(a1, a2); return; } - var gameObject = *(GameObject**)(a1 + 8); + var gameObject = a1->OwnerObject; if (gameObject == null) { Task.Result.Original(a1, a2); return; } - var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection(gameObject, true)); + var last = _state.SetAnimationData(_collectionResolver.IdentifyCollection((GameObject*) gameObject, true)); Task.Result.Original(a1, a2); _state.RestoreAnimationData(last); } diff --git a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs index 0f51157c..cfab29d3 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs @@ -29,13 +29,13 @@ public sealed unsafe class LoadAreaVfx : FastHook private nint Detour(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3) { var newData = caster != null - ? _collectionResolver.IdentifyCollection(caster, true) - : ResolveData.Invalid; + ? _collectionResolver.IdentifyCollection(caster, true) + : ResolveData.Invalid; var last = _state.SetAnimationData(newData); _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.LoadAreaVfx); - var ret = Task.Result.Original(vfxId, pos, caster, unk1, unk2, unk3); - Penumbra.Log.Excessive( + var ret = Task.Result.Original(vfxId, pos, caster, unk1, unk2, unk3); + Penumbra.Log.Information( $"[Load Area VFX] Invoked with {vfxId}, [{pos[0]} {pos[1]} {pos[2]}], 0x{(nint)caster:X}, {unk1}, {unk2}, {unk3} -> 0x{ret:X}."); _state.RestoreAnimationData(last); return ret; diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs index ed04880e..8d1096d2 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs @@ -16,23 +16,25 @@ public sealed unsafe class LoadCharacterSound : FastHook("Load Character Sound", (nint)VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, HookSettings.VfxIdentificationHooks); + _crashHandler = crashHandler; + Task = hooks.CreateHook("Load Character Sound", (nint)VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, + HookSettings.VfxIdentificationHooks); } - public delegate nint Delegate(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); + public delegate nint Delegate(VfxContainer* container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private nint Detour(nint container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7) + private nint Detour(VfxContainer* container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7) { - var character = *(GameObject**)(container + 8); + var character = (GameObject*)container->OwnerObject; var newData = _collectionResolver.IdentifyCollection(character, true); var last = _state.SetSoundData(newData); _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.LoadCharacterSound); var ret = Task.Result.Original(container, unk1, unk2, unk3, unk4, unk5, unk6, unk7); - Penumbra.Log.Excessive($"[Load Character Sound] Invoked with {container:X} {unk1} {unk2} {unk3} {unk4} {unk5} {unk6} {unk7} -> {ret}."); + Penumbra.Log.Excessive( + $"[Load Character Sound] Invoked with {(nint)container:X} {unk1} {unk2} {unk3} {unk4} {unk5} {unk6} {unk7} -> {ret}."); _state.RestoreSoundData(last); return ret; } diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index 4e9037bd..8bb14db6 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -1,6 +1,7 @@ using Dalamud.Game.ClientState.Conditions; using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Object; +using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Base; using OtterGui.Services; using Penumbra.Collections; using Penumbra.GameData; @@ -25,45 +26,44 @@ public sealed unsafe class LoadTimelineResources : FastHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, HookSettings.VfxIdentificationHooks); + _conditions = conditions; + _objects = objects; + _crashHandler = crashHandler; + Task = hooks.CreateHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, HookSettings.VfxIdentificationHooks); } - public delegate ulong Delegate(nint timeline); + public delegate ulong Delegate(SchedulerTimeline* timeline); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private ulong Detour(nint timeline) + private ulong Detour(SchedulerTimeline* timeline) { - Penumbra.Log.Excessive($"[Load Timeline Resources] Invoked on {timeline:X}."); + Penumbra.Log.Excessive($"[Load Timeline Resources] Invoked on {(nint)timeline:X}."); // Do not check timeline loading in cutscenes. if (_conditions[ConditionFlag.OccupiedInCutSceneEvent] || _conditions[ConditionFlag.WatchingCutscene78]) return Task.Result.Original(timeline); var newData = GetDataFromTimeline(_objects, _collectionResolver, timeline); - var last = _state.SetAnimationData(newData); - + var last = _state.SetAnimationData(newData); + #if false // This is called far too often and spams the log too much. _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.LoadTimelineResources); #endif - var ret = Task.Result.Original(timeline); + var ret = Task.Result.Original(timeline); _state.RestoreAnimationData(last); return ret; } /// Use timelines vfuncs to obtain the associated game object. - public static ResolveData GetDataFromTimeline(ObjectManager objects, CollectionResolver resolver, nint timeline) + public static ResolveData GetDataFromTimeline(ObjectManager objects, CollectionResolver resolver, SchedulerTimeline* timeline) { try { - if (timeline != nint.Zero) + if (timeline != null) { - var getGameObjectIdx = ((delegate* unmanaged**)timeline)[0][Offsets.GetGameObjectIdxVfunc]; - var idx = getGameObjectIdx(timeline); + var idx = timeline->GetOwningGameObjectIndex(); if (idx >= 0 && idx < objects.TotalCount) { var obj = objects[idx]; @@ -73,7 +73,7 @@ public sealed unsafe class LoadTimelineResources : FastHook Load a resource for a given path and a specific collection. @@ -80,10 +80,10 @@ public unsafe class ResourceLoader : IDisposable, IService public void Dispose() { - _resources.ResourceRequested -= ResourceHandler; + _resources.ResourceRequested -= ResourceHandler; _resources.ResourceHandleIncRef -= IncRefProtection; _resources.ResourceHandleDecRef -= DecRefProtection; - _fileReadService.ReadSqPack -= ReadSqPackDetour; + _fileReadService.ReadSqPack -= ReadSqPackDetour; } private void ResourceHandler(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, @@ -94,6 +94,9 @@ public unsafe class ResourceLoader : IDisposable, IService CompareHash(ComputeHash(path.Path, parameters), hash, path); + if (path.ToString() == "vfx/common/eff/abi_cnj022g.avfx") + ; + // If no replacements are being made, we still want to be able to trigger the event. var (resolvedPath, data) = _incMode.Value ? (null, ResolveData.Invalid) @@ -112,7 +115,7 @@ public unsafe class ResourceLoader : IDisposable, IService // Replace the hash and path with the correct one for the replacement. hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; - path = p; + path = p; returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); ResourceLoaded?.Invoke(returnValue, oldPath, resolvedPath.Value, data); } @@ -121,7 +124,8 @@ public unsafe class ResourceLoader : IDisposable, IService { if (fileDescriptor->ResourceHandle == null) { - Penumbra.Log.Error("[ResourceLoader] Failure to load file from SqPack: invalid File Descriptor."); + Penumbra.Log.Verbose( + $"[ResourceLoader] Failure to load file from SqPack: invalid File Descriptor: {Marshal.PtrToStringUni((nint)(&fileDescriptor->Utf16FileName))}"); return; } @@ -140,12 +144,12 @@ public unsafe class ResourceLoader : IDisposable, IService } var path = ByteString.FromSpanUnsafe(actualPath, gamePath.Path.IsNullTerminated, gamePath.Path.IsAsciiLowerCase, gamePath.Path.IsAscii); - fileDescriptor->ResourceHandle->FileNameData = path.Path; + fileDescriptor->ResourceHandle->FileNameData = path.Path; fileDescriptor->ResourceHandle->FileNameLength = path.Length; MtrlForceSync(fileDescriptor, ref isSync); returnValue = DefaultLoadResource(path, fileDescriptor, priority, isSync, data); // Return original resource handle path so that they can be loaded separately. - fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; + fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; fileDescriptor->ResourceHandle->FileNameLength = gamePath.Path.Length; } @@ -165,7 +169,7 @@ public unsafe class ResourceLoader : IDisposable, IService // Ensure that the file descriptor has its wchar_t array on aligned boundary even if it has to be odd. var fd = stackalloc char[0x11 + 0x0B + 14]; fileDescriptor->FileDescriptor = (byte*)fd + 1; - CreateFileWHook.WritePtr(fd + 0x11, gamePath.Path, gamePath.Length); + CreateFileWHook.WritePtr(fd + 0x11, gamePath.Path, gamePath.Length); CreateFileWHook.WritePtr(&fileDescriptor->Utf16FileName, gamePath.Path, gamePath.Length); // Use the SE ReadFile function. @@ -206,7 +210,7 @@ public unsafe class ResourceLoader : IDisposable, IService return; _incMode.Value = true; - returnValue = _resources.IncRef(handle); + returnValue = _resources.IncRef(handle); _incMode.Value = false; } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index 793d15af..80ba5cb9 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -87,6 +87,11 @@ public unsafe class TexMdlService : IDisposable, IRequiredService private readonly ThreadLocal _texReturnData = new(() => default); + private delegate void UpdateCategoryDelegate(TextureResourceHandle* resourceHandle); + + [Signature(Sigs.TexHandleUpdateCategory)] + private readonly UpdateCategoryDelegate _updateCategory = null!; + /// /// The function that checks a files CRC64 to determine whether it is 'protected'. /// We use it to check against our stored CRC64s and if it corresponds, we return the custom flag for models. @@ -99,9 +104,14 @@ public unsafe class TexMdlService : IDisposable, IRequiredService return CustomFileFlag; if (_customTexCrc.Contains(crc64)) + { _texReturnData.Value = true; + return nint.Zero; + } - return _checkFileStateHook.Original(ptr, crc64); + var ret = _checkFileStateHook.Original(ptr, crc64); + Penumbra.Log.Excessive($"[CheckFileState] Called on 0x{ptr:X} with CRC {crc64:X16}, returned 0x{ret:X}."); + return ret; } private delegate byte LoadTexFileLocalDelegate(TextureResourceHandle* handle, int unk1, SeFileDescriptor* unk2, bool unk3); @@ -118,7 +128,7 @@ public unsafe class TexMdlService : IDisposable, IRequiredService private delegate byte TexResourceHandleOnLoadPrototype(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2); - [Signature(Sigs.TexResourceHandleOnLoad, DetourName = nameof(OnLoadDetour))] + [Signature(Sigs.TexHandleOnLoad, DetourName = nameof(OnLoadDetour))] private readonly Hook _textureOnLoadHook = null!; private byte OnLoadDetour(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2) @@ -129,7 +139,9 @@ public unsafe class TexMdlService : IDisposable, IRequiredService // Function failed on a replaced texture, call local. _texReturnData.Value = false; - return _loadTexFileLocal(handle, _lodService.GetLod(handle), descriptor, unk2 != 0); + ret = _loadTexFileLocal(handle, _lodService.GetLod(handle), descriptor, unk2 != 0); + _updateCategory(handle); + return ret; } private delegate byte LoadMdlFileExternPrototype(ResourceHandle* handle, nint unk1, bool unk2, nint unk3); diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 810c946d..96125df2 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -124,7 +124,7 @@ public class ResourceTree // This way to tell apart MainHand and OffHand is not always accurate, but seems good enough for what we're doing with it. var slot = weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand; - var equipment = new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, new StainIds(weapon->Stain1, weapon->Stain2)); + var equipment = new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, new StainIds(weapon->Stain0, weapon->Stain1)); var weaponType = weapon->SecondaryId; var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment, weaponType); diff --git a/Penumbra/Interop/Structs/ClipScheduler.cs b/Penumbra/Interop/Structs/ClipScheduler.cs index 44a905b8..8270e0f2 100644 --- a/Penumbra/Interop/Structs/ClipScheduler.cs +++ b/Penumbra/Interop/Structs/ClipScheduler.cs @@ -1,3 +1,5 @@ +using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Base; + namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] @@ -7,5 +9,5 @@ public unsafe struct ClipScheduler public nint* VTable; [FieldOffset(0x38)] - public nint SchedulerTimeline; + public SchedulerTimeline* SchedulerTimeline; } diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 3cd87424..fc8b1c3d 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -9,37 +9,37 @@ internal static class StructExtensions public static unsafe ByteString AsByteString(in this StdString str) => ByteString.FromSpanUnsafe(str.AsSpan(), true); - public static ByteString ResolveEidPathAsByteString(in this CharacterBase character) + public static ByteString ResolveEidPathAsByteString(ref this CharacterBase character) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveEidPath(pathBuffer)); } - public static ByteString ResolveImcPathAsByteString(in this CharacterBase character, uint slotIndex) + public static ByteString ResolveImcPathAsByteString(ref this CharacterBase character, uint slotIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveImcPath(pathBuffer, slotIndex)); } - public static ByteString ResolveMdlPathAsByteString(in this CharacterBase character, uint slotIndex) + public static ByteString ResolveMdlPathAsByteString(ref this CharacterBase character, uint slotIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveMdlPath(pathBuffer, slotIndex)); } - public static unsafe ByteString ResolveMtrlPathAsByteString(in this CharacterBase character, uint slotIndex, byte* mtrlFileName) + public static unsafe ByteString ResolveMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex, byte* mtrlFileName) { var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex, mtrlFileName)); } - public static ByteString ResolveSklbPathAsByteString(in this CharacterBase character, uint partialSkeletonIndex) + public static ByteString ResolveSklbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveSklbPath(pathBuffer, partialSkeletonIndex)); } - public static ByteString ResolveSkpPathAsByteString(in this CharacterBase character, uint partialSkeletonIndex) + public static ByteString ResolveSkpPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveSkpPath(pathBuffer, partialSkeletonIndex)); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 9a03f384..180049bc 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -430,7 +430,7 @@ public class DebugTab : Window, ITab, IUiService foreach (var obj in _objects) { - ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero ? $"{((GameObject*)obj.Address)->ObjectIndex}" : "NULL"); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"{((GameObject*)obj.Address)->ObjectIndex}" : "NULL"); ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero ? string.Empty @@ -482,14 +482,15 @@ public class DebugTab : Window, ITab, IUiService { var gameObject = (GameObject*)gameObjectPtr; ImGui.TableNextColumn(); - ImGui.TextUnformatted($"0x{drawObject:X}"); + + ImGuiUtil.CopyOnClickSelectable($"0x{drawObject:X}"); ImGui.TableNextColumn(); ImGui.TextUnformatted(gameObject->ObjectIndex.ToString()); ImGui.TableNextColumn(); ImGui.TextUnformatted(child ? "Child" : "Main"); ImGui.TableNextColumn(); var (address, name) = ($"0x{gameObjectPtr:X}", new ByteString(gameObject->Name).ToString()); - ImGui.TextUnformatted(address); + ImGuiUtil.CopyOnClickSelectable(address); ImGui.TableNextColumn(); ImGui.TextUnformatted(name); ImGui.TableNextColumn(); From 0d939b12f4381a8dc4e6c96d977fdbd03348424f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Jul 2024 16:17:12 +0200 Subject: [PATCH 0722/1381] Add model update button. --- Penumbra/UI/AdvancedWindow/FileEditor.cs | 15 +++++++++------ .../AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 1 - .../UI/AdvancedWindow/ModEditWindow.Models.cs | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index eeb94c71..2c6ac170 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -207,12 +207,15 @@ public class FileEditor( var canSave = _changed && _currentFile is { Valid: true }; if (ImGuiUtil.DrawDisabledButton("Save to File", Vector2.Zero, $"Save the selected {fileType} file with all changes applied. This is not revertible.", !canSave)) - { - compactor.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); - if (owner.Mod != null) - communicator.ModFileChanged.Invoke(owner.Mod, _currentPath); - _changed = false; - } + SaveFile(); + } + + public void SaveFile() + { + compactor.WriteAllBytes(_currentPath!.File.FullName, _currentFile!.Write()); + if (owner.Mod != null) + communicator.ModFileChanged.Invoke(owner.Mod, _currentPath); + _changed = false; } private void ResetButton() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index 72ab37b2..b05bcac2 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,4 +1,3 @@ -using Lumina.Data.Parsing; using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Files; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index bbed64b7..de088736 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -4,6 +4,7 @@ using Lumina.Data.Parsing; using OtterGui; using OtterGui.Custom; using OtterGui.Raii; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.GameData; using Penumbra.GameData.Files; @@ -67,6 +68,7 @@ public partial class ModEditWindow { var ret = tab.Dirty; var data = UpdateFile(tab.Mdl, ret, disabled); + DrawVersionUpdate(tab, disabled); DrawImportExport(tab, disabled); ret |= DrawModelMaterialDetails(tab, disabled); @@ -80,6 +82,19 @@ public partial class ModEditWindow return !disabled && ret; } + private void DrawVersionUpdate(MdlTab tab, bool disabled) + { + if (disabled || tab.Mdl.Version is not MdlFile.V5) + return; + + if (!ImUtf8.ButtonEx("Update MDL Version from V5 to V6"u8, "Try using this if the bone weights of a pre-Dawntrail model seem wrong.\n\nThis is not revertible."u8, + new Vector2(-0.1f, 0), false, 0, Colors.PressEnterWarningBg)) + return; + + tab.Mdl.ConvertV5ToV6(); + _modelTab.SaveFile(); + } + private void DrawImportExport(MdlTab tab, bool disabled) { if (!ImGui.CollapsingHeader("Import / Export")) From 56e284a99eedb73f2053d4e961d714edcbfc1937 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 8 Jul 2024 14:55:49 +0200 Subject: [PATCH 0723/1381] Add some migration things. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Configuration.cs | 2 + Penumbra/Import/TexToolsImport.cs | 33 +- Penumbra/Import/TexToolsImporter.Archives.cs | 26 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 23 +- .../Interop/Hooks/Animation/LoadAreaVfx.cs | 2 +- .../Hooks/ResourceLoading/ResourceLoader.cs | 3 - .../ResolveContext.PathResolution.cs | 50 +-- Penumbra/Interop/ResourceTree/ResourceTree.cs | 6 +- Penumbra/Mods/Manager/ModImportManager.cs | 5 +- Penumbra/Services/MigrationManager.cs | 287 ++++++++++++++++++ .../AdvancedWindow/ModEditWindow.Materials.cs | 16 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 5 +- Penumbra/UI/Classes/CollectionSelectHeader.cs | 4 +- Penumbra/UI/Classes/MigrationSectionDrawer.cs | 121 ++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 8 +- 17 files changed, 515 insertions(+), 80 deletions(-) create mode 100644 Penumbra/Services/MigrationManager.cs create mode 100644 Penumbra/UI/Classes/MigrationSectionDrawer.cs diff --git a/OtterGui b/OtterGui index c2738e1d..89b3b951 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c2738e1d42974cddbe5a31238c6ed236a831d17d +Subproject commit 89b3b9513f9b4989045517a452ef971e24377203 diff --git a/Penumbra.GameData b/Penumbra.GameData index 62f6acfb..b5eb074d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 62f6acfb0f9e31b2907c02a270d723bfff18b390 +Subproject commit b5eb074d80a4aaa2703a3124d2973a7fa08046ad diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 49aecfdc..8d0f7fd8 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -99,6 +99,8 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool UseFileSystemCompression { get; set; } = true; public bool EnableHttpApi { get; set; } = true; + public bool MigrateImportedModelsToV6 { get; set; } = false; + public string DefaultModImportPath { get; set; } = string.Empty; public bool AlwaysOpenDefaultImport { get; set; } = false; public bool KeepDefaultMetaChanges { get; set; } = false; diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index bb006d8d..ba089662 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -3,6 +3,7 @@ using OtterGui.Compression; using Penumbra.Import.Structs; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; +using Penumbra.Services; using FileMode = System.IO.FileMode; using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; using ZipArchiveEntry = SharpCompress.Archives.Zip.ZipArchiveEntry; @@ -27,24 +28,26 @@ public partial class TexToolsImporter : IDisposable public ImporterState State { get; private set; } public readonly List<(FileInfo File, DirectoryInfo? Mod, Exception? Error)> ExtractedMods; - private readonly Configuration _config; - private readonly ModEditor _editor; - private readonly ModManager _modManager; - private readonly FileCompactor _compactor; + private readonly Configuration _config; + private readonly ModEditor _editor; + private readonly ModManager _modManager; + private readonly FileCompactor _compactor; + private readonly MigrationManager _migrationManager; public TexToolsImporter(int count, IEnumerable modPackFiles, Action handler, - Configuration config, ModEditor editor, ModManager modManager, FileCompactor compactor) + Configuration config, ModEditor editor, ModManager modManager, FileCompactor compactor, MigrationManager migrationManager) { - _baseDirectory = modManager.BasePath; - _tmpFile = Path.Combine(_baseDirectory.FullName, TempFileName); - _modPackFiles = modPackFiles; - _config = config; - _editor = editor; - _modManager = modManager; - _compactor = compactor; - _modPackCount = count; - ExtractedMods = new List<(FileInfo, DirectoryInfo?, Exception?)>(count); - _token = _cancellation.Token; + _baseDirectory = modManager.BasePath; + _tmpFile = Path.Combine(_baseDirectory.FullName, TempFileName); + _modPackFiles = modPackFiles; + _config = config; + _editor = editor; + _modManager = modManager; + _compactor = compactor; + _migrationManager = migrationManager; + _modPackCount = count; + ExtractedMods = new List<(FileInfo, DirectoryInfo?, Exception?)>(count); + _token = _cancellation.Token; Task.Run(ImportFiles, _token) .ContinueWith(_ => CloseStreams(), TaskScheduler.Default) .ContinueWith(_ => diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index 57313ab1..a51dbc61 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -2,6 +2,7 @@ using Dalamud.Utility; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui.Filesystem; +using Penumbra.GameData.Files; using Penumbra.Import.Structs; using Penumbra.Mods; using SharpCompress.Archives; @@ -9,12 +10,19 @@ using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; using SharpCompress.Common; using SharpCompress.Readers; +using static FFXIVClientStructs.FFXIV.Client.UI.Misc.ConfigModule; using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; namespace Penumbra.Import; public partial class TexToolsImporter { + private static readonly ExtractionOptions _extractionOptions = new() + { + ExtractFullPath = true, + Overwrite = true, + }; + /// /// Extract regular compressed archives that are folders containing penumbra-formatted mods. /// The mod has to either contain a meta.json at top level, or one folder deep. @@ -45,11 +53,7 @@ public partial class TexToolsImporter Penumbra.Log.Information($" -> Importing {archive.Type} Archive."); _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, Path.GetRandomFileName(), _config.ReplaceNonAsciiOnImport, true); - var options = new ExtractionOptions() - { - ExtractFullPath = true, - Overwrite = true, - }; + State = ImporterState.ExtractingModFiles; _currentFileIdx = 0; @@ -86,7 +90,7 @@ public partial class TexToolsImporter } else { - reader.WriteEntryToDirectory(_currentModDirectory.FullName, options); + HandleFileMigrations(reader); } ++_currentFileIdx; @@ -114,6 +118,16 @@ public partial class TexToolsImporter } + private void HandleFileMigrations(IReader reader) + { + switch (Path.GetExtension(reader.Entry.Key)) + { + case ".mdl": + _migrationManager.MigrateMdlDuringExtraction(reader, _currentModDirectory!.FullName, _extractionOptions); + break; + } + } + // Search the archive for the meta.json file which needs to exist. private static string FindArchiveModMeta(IArchive archive, out bool leadDir) { diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 2b45ecbe..ba294353 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -253,25 +253,12 @@ public partial class TexToolsImporter extractedFile.Directory?.Create(); - if (extractedFile.FullName.EndsWith(".mdl")) - ProcessMdl(data.Data); + data.Data = Path.GetExtension(extractedFile.FullName) switch + { + ".mdl" => _migrationManager.MigrateTtmpModel(extractedFile.FullName, data.Data), + _ => data.Data, + }; _compactor.WriteAllBytesAsync(extractedFile.FullName, data.Data, _token).Wait(_token); } - - private static void ProcessMdl(byte[] mdl) - { - const int modelHeaderLodOffset = 22; - - // Model file header LOD num - mdl[64] = 1; - - // Model header LOD num - var stackSize = BitConverter.ToUInt32(mdl, 4); - var runtimeBegin = stackSize + 0x44; - var stringsLengthOffset = runtimeBegin + 4; - var stringsLength = BitConverter.ToUInt32(mdl, (int)stringsLengthOffset); - var modelHeaderStart = stringsLengthOffset + stringsLength + 4; - mdl[modelHeaderStart + modelHeaderLodOffset] = 1; - } } diff --git a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs index cfab29d3..48dc0078 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs @@ -35,7 +35,7 @@ public sealed unsafe class LoadAreaVfx : FastHook var last = _state.SetAnimationData(newData); _crashHandler.LogAnimation(newData.AssociatedGameObject, newData.ModCollection, AnimationInvocationType.LoadAreaVfx); var ret = Task.Result.Original(vfxId, pos, caster, unk1, unk2, unk3); - Penumbra.Log.Information( + Penumbra.Log.Excessive( $"[Load Area VFX] Invoked with {vfxId}, [{pos[0]} {pos[1]} {pos[2]}], 0x{(nint)caster:X}, {unk1}, {unk2}, {unk3} -> 0x{ret:X}."); _state.RestoreAnimationData(last); return ret; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index af637768..195a8b9e 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -94,9 +94,6 @@ public unsafe class ResourceLoader : IDisposable, IService CompareHash(ComputeHash(path.Path, parameters), hash, path); - if (path.ToString() == "vfx/common/eff/abi_cnj022g.avfx") - ; - // If no replacements are being made, we still want to be able to trigger the event. var (resolvedPath, data) = _incMode.Value ? (null, ResolveData.Invalid) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 4dfefd96..72cb1681 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -81,11 +81,12 @@ internal partial record ResolveContext // Resolving a material path through the game's code can dereference null pointers for materials that involve IMC metadata. return ModelType switch { - ModelType.Human when SlotIndex < 10 && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), - ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), - ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imc, mtrlFileName), - ModelType.Monster => ResolveMonsterMaterialPath(modelPath, imc, mtrlFileName), - _ => ResolveMaterialPathNative(mtrlFileName), + ModelType.Human when SlotIndex is < 10 or 16 && mtrlFileName[8] != (byte)'b' + => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), + ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), + ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imc, mtrlFileName), + ModelType.Monster => ResolveMonsterMaterialPath(modelPath, imc, mtrlFileName), + _ => ResolveMaterialPathNative(mtrlFileName), }; } @@ -96,7 +97,7 @@ internal partial record ResolveContext var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; - pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; } @@ -126,7 +127,7 @@ internal partial record ResolveContext WriteZeroPaddedNumber(mirroredFileName[4..8], mirroredSetId); Span pathBuffer = stackalloc byte[260]; - pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, mirroredFileName); + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, mirroredFileName); var weaponPosition = pathBuffer.IndexOf("/weapon/w"u8); if (weaponPosition >= 0) @@ -145,7 +146,7 @@ internal partial record ResolveContext var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[260]; - pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; } @@ -166,7 +167,8 @@ internal partial record ResolveContext return entry.MaterialId; } - private static Span AssembleMaterialPath(Span materialPathBuffer, ReadOnlySpan modelPath, byte variant, ReadOnlySpan mtrlFileName) + private static Span AssembleMaterialPath(Span materialPathBuffer, ReadOnlySpan modelPath, byte variant, + ReadOnlySpan mtrlFileName) { var modelPosition = modelPath.IndexOf("/model/"u8); if (modelPosition < 0) @@ -187,8 +189,8 @@ internal partial record ResolveContext { for (var i = destination.Length; i-- > 0;) { - destination[i] = (byte)('0' + number % 10); - number /= 10; + destination[i] = (byte)('0' + number % 10); + number /= 10; } } @@ -197,13 +199,17 @@ internal partial record ResolveContext ByteString? path; try { + Penumbra.Log.Information($"{(nint)CharacterBase:X} {ModelType} {SlotIndex} 0x{(ulong)mtrlFileName:X}"); + Penumbra.Log.Information($"{new ByteString(mtrlFileName)}"); path = CharacterBase->ResolveMtrlPathAsByteString(SlotIndex, mtrlFileName); } catch (AccessViolationException) { - Penumbra.Log.Error($"Access violation during attempt to resolve material path\nDraw object: {(nint)CharacterBase:X} (of type {ModelType})\nSlot index: {SlotIndex}\nMaterial file name: {(nint)mtrlFileName:X} ({new string((sbyte*)mtrlFileName)})"); + Penumbra.Log.Error( + $"Access violation during attempt to resolve material path\nDraw object: {(nint)CharacterBase:X} (of type {ModelType})\nSlot index: {SlotIndex}\nMaterial file name: {(nint)mtrlFileName:X} ({new string((sbyte*)mtrlFileName)})"); return Utf8GamePath.Empty; } + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -235,30 +241,23 @@ internal partial record ResolveContext var characterRaceCode = (GenderRace)human->RaceSexId; switch (partialSkeletonIndex) { - case 0: - return (characterRaceCode, "base", 1); + case 0: return (characterRaceCode, "base", 1); case 1: var faceId = human->FaceId; var tribe = human->Customize[(int)Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex.Tribe]; var modelType = human->Customize[(int)Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex.ModelType]; if (faceId < 201) - { faceId -= tribe switch { 0xB when modelType == 4 => 100, 0xE | 0xF => 100, _ => 0, }; - } return ResolveHumanExtraSkeletonData(characterRaceCode, EstType.Face, faceId); - case 2: - return ResolveHumanExtraSkeletonData(characterRaceCode, EstType.Hair, human->HairId); - case 3: - return ResolveHumanEquipmentSkeletonData(EquipSlot.Head, EstType.Head); - case 4: - return ResolveHumanEquipmentSkeletonData(EquipSlot.Body, EstType.Body); - default: - return (0, string.Empty, 0); + case 2: return ResolveHumanExtraSkeletonData(characterRaceCode, EstType.Hair, human->HairId); + case 3: return ResolveHumanEquipmentSkeletonData(EquipSlot.Head, EstType.Head); + case 4: return ResolveHumanEquipmentSkeletonData(EquipSlot.Body, EstType.Body); + default: return (0, string.Empty, 0); } } @@ -269,7 +268,8 @@ internal partial record ResolveContext return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot, equipment.Set), type, equipment.Set); } - private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstType type, PrimaryId primary) + private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstType type, + PrimaryId primary) { var metaCache = Global.Collection.MetaCache; var skeletonSet = metaCache?.GetEstEntry(type, raceCode, primary) ?? default; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 96125df2..6663fb40 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -73,11 +73,11 @@ public class ResourceTree var genericContext = globalContext.CreateContext(model); - for (var i = 0; i < model->SlotCount; ++i) + for (var i = 0u; i < model->SlotCount; ++i) { var slotContext = i < equipment.Length - ? globalContext.CreateContext(model, (uint)i, ((uint)i).ToEquipSlot(), equipment[i]) - : globalContext.CreateContext(model, (uint)i); + ? globalContext.CreateContext(model, i, i.ToEquipSlot(), equipment[(int)i]) + : globalContext.CreateContext(model, i); var imc = (ResourceHandle*)model->IMCArray[i]; var imcNode = slotContext.CreateNodeFromImc(imc); diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index 39a53bb9..d984d374 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -3,10 +3,11 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.Import; using Penumbra.Mods.Editor; +using Penumbra.Services; namespace Penumbra.Mods.Manager; -public class ModImportManager(ModManager modManager, Configuration config, ModEditor modEditor) : IDisposable, IService +public class ModImportManager(ModManager modManager, Configuration config, ModEditor modEditor, MigrationManager migrationManager) : IDisposable, IService { private readonly ConcurrentQueue _modsToUnpack = new(); @@ -42,7 +43,7 @@ public class ModImportManager(ModManager modManager, Configuration config, ModEd if (files.Length == 0) return; - _import = new TexToolsImporter(files.Length, files, AddNewMod, config, modEditor, modManager, modEditor.Compactor); + _import = new TexToolsImporter(files.Length, files, AddNewMod, config, modEditor, modManager, modEditor.Compactor, migrationManager); } public bool Importing diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs new file mode 100644 index 00000000..a4b80656 --- /dev/null +++ b/Penumbra/Services/MigrationManager.cs @@ -0,0 +1,287 @@ +using Dalamud.Interface.ImGuiNotification; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.GameData.Files; +using SharpCompress.Common; +using SharpCompress.Readers; + +namespace Penumbra.Services; + +public class MigrationManager(Configuration config) : IService +{ + private Task? _currentTask; + private CancellationTokenSource? _source; + + public bool HasCleanUpTask { get; private set; } + public bool HasMigrationTask { get; private set; } + public bool HasRestoreTask { get; private set; } + + public bool IsMigrationTask { get; private set; } + public bool IsRestorationTask { get; private set; } + public bool IsCleanupTask { get; private set; } + + + public int Restored { get; private set; } + public int RestoreFails { get; private set; } + + public int CleanedUp { get; private set; } + + public int CleanupFails { get; private set; } + + public int Migrated { get; private set; } + + public int Unchanged { get; private set; } + + public int Failed { get; private set; } + + public bool IsRunning + => _currentTask is { IsCompleted: false }; + + /// Writes or migrates a .mdl file during extraction from a regular archive. + public void MigrateMdlDuringExtraction(IReader reader, string directory, ExtractionOptions options) + { + if (!config.MigrateImportedModelsToV6) + { + reader.WriteEntryToDirectory(directory, options); + return; + } + + var path = Path.Combine(directory, reader.Entry.Key); + using var s = new MemoryStream(); + using var e = reader.OpenEntryStream(); + e.CopyTo(s); + using var b = new BinaryReader(s); + var version = b.ReadUInt32(); + if (version == MdlFile.V5) + { + var data = s.ToArray(); + var mdl = new MdlFile(data); + MigrateModel(path, mdl, false); + Penumbra.Log.Debug($"Migrated model {reader.Entry.Key} from V5 to V6 during import."); + } + else + { + using var f = File.Open(path, FileMode.Create, FileAccess.Write); + s.Seek(0, SeekOrigin.Begin); + s.WriteTo(f); + } + } + + public void CleanBackups(string path) + { + if (IsRunning) + return; + + _source = new CancellationTokenSource(); + var token = _source.Token; + _currentTask = Task.Run(() => + { + HasCleanUpTask = true; + IsCleanupTask = true; + IsMigrationTask = false; + IsRestorationTask = false; + CleanedUp = 0; + CleanupFails = 0; + foreach (var file in Directory.EnumerateFiles(path, "*.mdl.bak", SearchOption.AllDirectories)) + { + if (token.IsCancellationRequested) + return; + + try + { + File.Delete(file); + ++CleanedUp; + Penumbra.Log.Debug($"Deleted model backup file {file}."); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, $"Failed to delete model backup file {file}", NotificationType.Warning); + ++CleanupFails; + } + } + }, token); + } + + public void RestoreBackups(string path) + { + if (IsRunning) + return; + + _source = new CancellationTokenSource(); + var token = _source.Token; + _currentTask = Task.Run(() => + { + HasRestoreTask = true; + IsCleanupTask = false; + IsMigrationTask = false; + IsRestorationTask = true; + CleanedUp = 0; + CleanupFails = 0; + foreach (var file in Directory.EnumerateFiles(path, "*.mdl.bak", SearchOption.AllDirectories)) + { + if (token.IsCancellationRequested) + return; + + var target = file[..^4]; + try + { + File.Copy(file, target, true); + ++Restored; + Penumbra.Log.Debug($"Restored model backup file {file} to {target}."); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, $"Failed to restore model backup file {file} to {target}", + NotificationType.Warning); + ++RestoreFails; + } + } + }, token); + } + + /// Update the data of a .mdl file during TTMP extraction. Returns either the existing array or a new one. + public byte[] MigrateTtmpModel(string path, byte[] data) + { + FixLodNum(data); + if (!config.MigrateImportedModelsToV6) + return data; + + var version = BitConverter.ToUInt32(data); + if (version != 5) + return data; + + var mdl = new MdlFile(data); + if (!mdl.ConvertV5ToV6()) + return data; + + data = mdl.Write(); + Penumbra.Log.Debug($"Migrated model {path} from V5 to V6 during import."); + return data; + } + + public void MigrateDirectory(string path, bool createBackups) + { + if (IsRunning) + return; + + _source = new CancellationTokenSource(); + var token = _source.Token; + _currentTask = Task.Run(() => + { + HasMigrationTask = true; + IsCleanupTask = false; + IsMigrationTask = true; + IsRestorationTask = false; + Unchanged = 0; + Migrated = 0; + Failed = 0; + foreach (var file in Directory.EnumerateFiles(path, "*.mdl", SearchOption.AllDirectories)) + { + if (token.IsCancellationRequested) + return; + + var timer = Stopwatch.StartNew(); + try + { + var data = File.ReadAllBytes(file); + var mdl = new MdlFile(data); + if (MigrateModel(file, mdl, createBackups)) + { + ++Migrated; + Penumbra.Log.Debug($"Migrated model file {file} from V5 to V6 in {timer.ElapsedMilliseconds} ms."); + } + else + { + ++Unchanged; + Penumbra.Log.Verbose($"Verified that model file {file} is already V6 in {timer.ElapsedMilliseconds} ms."); + } + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, $"Failed to migrate model file {file} to V6 in {timer.ElapsedMilliseconds} ms", + NotificationType.Warning); + ++Failed; + } + } + }, token); + } + + public void Cancel() + { + _source?.Cancel(); + _source = null; + _currentTask = null; + } + + private static void FixLodNum(byte[] data) + { + const int modelHeaderLodOffset = 22; + + // Model file header LOD num + data[64] = 1; + + // Model header LOD num + var stackSize = BitConverter.ToUInt32(data, 4); + var runtimeBegin = stackSize + 0x44; + var stringsLengthOffset = runtimeBegin + 4; + var stringsLength = BitConverter.ToUInt32(data, (int)stringsLengthOffset); + var modelHeaderStart = stringsLengthOffset + stringsLength + 4; + data[modelHeaderStart + modelHeaderLodOffset] = 1; + } + + public static bool TryMigrateSingleModel(string path, bool createBackup) + { + try + { + var data = File.ReadAllBytes(path); + var mdl = new MdlFile(data); + return MigrateModel(path, mdl, createBackup); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, $"Failed to migrate the model {path} to V6", NotificationType.Warning); + return false; + } + } + + public static bool TryMigrateSingleMaterial(string path, bool createBackup) + { + try + { + var data = File.ReadAllBytes(path); + var mtrl = new MtrlFile(data); + return MigrateMaterial(path, mtrl, createBackup); + } + catch (Exception ex) + { + Penumbra.Messager.NotificationMessage(ex, $"Failed to migrate the material {path} to Dawntrail", NotificationType.Warning); + return false; + } + } + + private static bool MigrateModel(string path, MdlFile mdl, bool createBackup) + { + if (!mdl.ConvertV5ToV6()) + return false; + + var data = mdl.Write(); + if (createBackup) + File.Copy(path, Path.ChangeExtension(path, ".mdl.bak")); + File.WriteAllBytes(path, data); + return true; + } + + private static bool MigrateMaterial(string path, MtrlFile mtrl, bool createBackup) + { + if (!mtrl.MigrateToDawntrail()) + return false; + + var data = mtrl.Write(); + + mtrl.Write(); + if (createBackup) + File.Copy(path, Path.ChangeExtension(path, ".mtrl.bak")); + File.WriteAllBytes(path, data); + return true; + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 68b3717f..0223ca6b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.GameData.Files; using Penumbra.String.Classes; @@ -16,6 +17,7 @@ public partial class ModEditWindow private bool DrawMaterialPanel(MtrlTab tab, bool disabled) { + DrawVersionUpdate(tab, disabled); DrawMaterialLivePreviewRebind(tab, disabled); ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); @@ -34,6 +36,20 @@ public partial class ModEditWindow return !disabled && ret; } + private void DrawVersionUpdate(MtrlTab tab, bool disabled) + { + if (disabled || tab.Mtrl.IsDawnTrail) + return; + + if (!ImUtf8.ButtonEx("Update MTRL Version to Dawntrail"u8, + "Try using this if the material can not be loaded or should use legacy shaders.\n\nThis is not revertible."u8, + new Vector2(-0.1f, 0), false, 0, Colors.PressEnterWarningBg)) + return; + + tab.Mtrl.MigrateToDawntrail(); + _materialTab.SaveFile(); + } + private static void DrawMaterialLivePreviewRebind(MtrlTab tab, bool disabled) { if (disabled) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 90fdc48e..83a8958b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -37,6 +37,8 @@ public partial class ModEditWindow : Window, IDisposable, IUiService { private const string WindowBaseLabel = "###SubModEdit"; + public readonly MigrationManager MigrationManager; + private readonly PerformanceTracker _performance; private readonly ModEditor _editor; private readonly Configuration _config; @@ -588,7 +590,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, ResourceTreeViewerFactory resourceTreeViewerFactory, ObjectManager objects, IFramework framework, - CharacterBaseDestructor characterBaseDestructor, MetaDrawers metaDrawers) + CharacterBaseDestructor characterBaseDestructor, MetaDrawers metaDrawers, MigrationManager migrationManager) : base(WindowBaseLabel) { _performance = performance; @@ -608,6 +610,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _objects = objects; _framework = framework; _characterBaseDestructor = characterBaseDestructor; + MigrationManager = migrationManager; _metaDrawers = metaDrawers; _materialTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => Mod?.ModPath.FullName ?? string.Empty, diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index 6c8bbf64..0f9b2518 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -37,9 +37,9 @@ public class CollectionSelectHeader : IUiService var buttonSize = new Vector2(comboWidth * 3f / 4f, 0f); using (var _ = ImRaii.Group()) { - DrawCollectionButton(buttonSize, GetDefaultCollectionInfo(), 1); + DrawCollectionButton(buttonSize, GetDefaultCollectionInfo(), 1); DrawCollectionButton(buttonSize, GetInterfaceCollectionInfo(), 2); - DrawCollectionButton(buttonSize, GetPlayerCollectionInfo(), 3); + DrawCollectionButton(buttonSize, GetPlayerCollectionInfo(), 3); DrawCollectionButton(buttonSize, GetInheritedCollectionInfo(), 4); _collectionCombo.Draw("##collectionSelector", comboWidth, ColorId.SelectedCollection.Value()); diff --git a/Penumbra/UI/Classes/MigrationSectionDrawer.cs b/Penumbra/UI/Classes/MigrationSectionDrawer.cs new file mode 100644 index 00000000..75d37368 --- /dev/null +++ b/Penumbra/UI/Classes/MigrationSectionDrawer.cs @@ -0,0 +1,121 @@ +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Services; + +namespace Penumbra.UI.Classes; + +public class MigrationSectionDrawer(MigrationManager migrationManager, Configuration config) : IUiService +{ + private bool _createBackups = true; + private Vector2 _buttonSize; + + public void Draw() + { + using var header = ImUtf8.CollapsingHeaderId("Migration"u8); + if (!header) + return; + + _buttonSize = UiHelpers.InputTextWidth; + DrawSettings(); + ImGui.Separator(); + DrawMigration(); + ImGui.Separator(); + DrawCleanup(); + ImGui.Separator(); + DrawRestore(); + } + + private void DrawSettings() + { + var value = config.MigrateImportedModelsToV6; + if (ImUtf8.Checkbox("Automatically Migrate V5 Models to V6 on Import"u8, ref value)) + { + config.MigrateImportedModelsToV6 = value; + config.Save(); + } + } + + private void DrawMigration() + { + ImUtf8.Checkbox("Create Backups During Manual Migration", ref _createBackups); + if (ImUtf8.ButtonEx("Migrate Model Files From V5 to V6"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.MigrateDirectory(config.ModDirectory, _createBackups); + + ImUtf8.SameLineInner(); + DrawCancelButton(0, "Cancel the migration. This does not revert already finished migrations."u8); + DrawSpinner(migrationManager is { IsMigrationTask: true, IsRunning: true }); + + if (!migrationManager.HasMigrationTask) + { + ImUtf8.IconDummy(); + return; + } + + var total = migrationManager.Failed + migrationManager.Migrated + migrationManager.Unchanged; + if (total == 0) + ImUtf8.TextFrameAligned("No model files found."u8); + else + ImUtf8.TextFrameAligned($"{migrationManager.Migrated} files migrated, {migrationManager.Failed} files failed, {total} total files."); + } + + private void DrawCleanup() + { + if (ImUtf8.ButtonEx("Delete Existing Model Backup Files"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.CleanBackups(config.ModDirectory); + + ImUtf8.SameLineInner(); + DrawCancelButton(1, "Cancel the cleanup. This is not revertible."u8); + DrawSpinner(migrationManager is { IsCleanupTask: true, IsRunning: true }); + if (!migrationManager.HasCleanUpTask) + { + ImUtf8.IconDummy(); + return; + } + + var total = migrationManager.CleanedUp + migrationManager.CleanupFails; + if (total == 0) + ImUtf8.TextFrameAligned("No model backup files found."u8); + else + ImUtf8.TextFrameAligned( + $"{migrationManager.CleanedUp} backups deleted, {migrationManager.CleanupFails} deletions failed, {total} total backups."); + } + + private void DrawSpinner(bool enabled) + { + if (!enabled) + return; + ImGui.SameLine(); + ImUtf8.Spinner("Spinner"u8, ImGui.GetTextLineHeight() / 2, 2, ImGui.GetColorU32(ImGuiCol.Text)); + } + + private void DrawRestore() + { + if (ImUtf8.ButtonEx("Restore Model Backups"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.RestoreBackups(config.ModDirectory); + + ImUtf8.SameLineInner(); + DrawCancelButton(2, "Cancel the restoration. This does not revert already finished restoration."u8); + DrawSpinner(migrationManager is { IsRestorationTask: true, IsRunning: true }); + + if (!migrationManager.HasRestoreTask) + { + ImUtf8.IconDummy(); + return; + } + + var total = migrationManager.Restored + migrationManager.RestoreFails; + if (total == 0) + ImUtf8.TextFrameAligned("No model backup files found."u8); + else + ImUtf8.TextFrameAligned( + $"{migrationManager.Restored} backups restored, {migrationManager.RestoreFails} restorations failed, {total} total backups."); + } + + private void DrawCancelButton(int id, ReadOnlySpan tooltip) + { + using var _ = ImUtf8.PushId(id); + if (ImUtf8.ButtonEx("Cancel"u8, tooltip, disabled: !migrationManager.IsRunning)) + migrationManager.Cancel(); + } +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 49e77a4d..8a4d6874 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -41,10 +41,11 @@ public class SettingsTab : ITab, IUiService private readonly DalamudSubstitutionProvider _dalamudSubstitutionProvider; private readonly FileCompactor _compactor; private readonly DalamudConfigService _dalamudConfig; - private readonly IDalamudPluginInterface _pluginInterface; + private readonly IDalamudPluginInterface _pluginInterface; private readonly IDataManager _gameData; private readonly PredefinedTagManager _predefinedTagManager; private readonly CrashHandlerService _crashService; + private readonly MigrationSectionDrawer _migrationDrawer; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -55,7 +56,8 @@ public class SettingsTab : ITab, IUiService Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, - IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService) + IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, + MigrationSectionDrawer migrationDrawer) { _pluginInterface = pluginInterface; _config = config; @@ -77,6 +79,7 @@ public class SettingsTab : ITab, IUiService _compactor.Enabled = _config.UseFileSystemCompression; _predefinedTagManager = predefinedTagConfig; _crashService = crashService; + _migrationDrawer = migrationDrawer; } public void DrawHeader() @@ -102,6 +105,7 @@ public class SettingsTab : ITab, IUiService ImGui.NewLine(); DrawGeneralSettings(); + _migrationDrawer.Draw(); DrawColorSettings(); DrawPredefinedTagsSection(); DrawAdvancedSettings(); From f89eea721f524a4acc9b3e8041871bbbd1d8db66 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 8 Jul 2024 14:59:35 +0200 Subject: [PATCH 0724/1381] Update game data. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index b5eb074d..d7a56b70 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b5eb074d80a4aaa2703a3124d2973a7fa08046ad +Subproject commit d7a56b708c73bc9917baeaa66842c1594ca3067b From 710f39768bec527db1de4172499dee2b80c7ac24 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 8 Jul 2024 15:00:37 +0200 Subject: [PATCH 0725/1381] Disable the required ShadersKnown for the time being. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 91129129..cd7aca9d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -691,8 +691,9 @@ public partial class ModEditWindow _edit._characterBaseDestructor.Unsubscribe(UnbindFromDrawObjectMaterialInstances); } + // TODO Readd ShadersKnown public bool Valid - => ShadersKnown && Mtrl.Valid; + => (true || ShadersKnown) && Mtrl.Valid; public byte[] Write() { From b677a14ceffe6d8a1c0e94d47e1af3bfd19e1616 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Jul 2024 16:34:31 +0200 Subject: [PATCH 0726/1381] Update. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Configuration.cs | 3 +- Penumbra/Import/TexToolsImporter.Archives.cs | 11 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 5 +- .../Animation/ApricotListenerSoundPlay.cs | 2 + Penumbra/Services/MigrationManager.cs | 340 +++++++++++------- Penumbra/UI/Classes/MigrationSectionDrawer.cs | 155 +++++--- Penumbra/UI/Tabs/Debug/DebugTab.cs | 10 +- 9 files changed, 338 insertions(+), 192 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 43b0b47f..f4c6144c 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 43b0b47f2d019af0fe4681dfc578f9232e3ba90c +Subproject commit f4c6144ca2012b279e6d8aa52b2bef6cc2ba32d9 diff --git a/Penumbra.GameData b/Penumbra.GameData index d7a56b70..cf5be8af 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d7a56b708c73bc9917baeaa66842c1594ca3067b +Subproject commit cf5be8af4c9ecbd9190bd3db746743fa5cd1560f diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 8d0f7fd8..f16569b5 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -99,7 +99,8 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool UseFileSystemCompression { get; set; } = true; public bool EnableHttpApi { get; set; } = true; - public bool MigrateImportedModelsToV6 { get; set; } = false; + public bool MigrateImportedModelsToV6 { get; set; } = true; + public bool MigrateImportedMaterialsToLegacy { get; set; } = true; public string DefaultModImportPath { get; set; } = string.Empty; public bool AlwaysOpenDefaultImport { get; set; } = false; diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index a51dbc61..63c170cb 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -1,3 +1,4 @@ +using System.IO; using Dalamud.Utility; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -90,7 +91,7 @@ public partial class TexToolsImporter } else { - HandleFileMigrations(reader); + HandleFileMigrationsAndWrite(reader); } ++_currentFileIdx; @@ -118,13 +119,19 @@ public partial class TexToolsImporter } - private void HandleFileMigrations(IReader reader) + private void HandleFileMigrationsAndWrite(IReader reader) { switch (Path.GetExtension(reader.Entry.Key)) { case ".mdl": _migrationManager.MigrateMdlDuringExtraction(reader, _currentModDirectory!.FullName, _extractionOptions); break; + case ".mtrl": + _migrationManager.MigrateMtrlDuringExtraction(reader, _currentModDirectory!.FullName, _extractionOptions); + break; + default: + reader.WriteEntryToDirectory(_currentModDirectory!.FullName, _extractionOptions); + break; } } diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index ba294353..3ae1eda9 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -255,8 +255,9 @@ public partial class TexToolsImporter data.Data = Path.GetExtension(extractedFile.FullName) switch { - ".mdl" => _migrationManager.MigrateTtmpModel(extractedFile.FullName, data.Data), - _ => data.Data, + ".mdl" => _migrationManager.MigrateTtmpModel(extractedFile.FullName, data.Data), + ".mtrl" => _migrationManager.MigrateTtmpMaterial(extractedFile.FullName, data.Data), + _ => data.Data, }; _compactor.WriteAllBytesAsync(extractedFile.FullName, data.Data, _token).Wait(_token); diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index e58c7268..2e05c1b6 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -1,3 +1,4 @@ +using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; @@ -16,6 +17,7 @@ public sealed unsafe class ApricotListenerSoundPlay : FastHook Changed + Unchanged + Failed; + + public void Init() + { + Changed = 0; + Unchanged = 0; + Failed = 0; + HasData = true; + } + } + private Task? _currentTask; private CancellationTokenSource? _source; - public bool HasCleanUpTask { get; private set; } - public bool HasMigrationTask { get; private set; } - public bool HasRestoreTask { get; private set; } + public TaskType CurrentTask { get; private set; } - public bool IsMigrationTask { get; private set; } - public bool IsRestorationTask { get; private set; } - public bool IsCleanupTask { get; private set; } + public readonly MigrationData MdlMigration = new(true); + public readonly MigrationData MtrlMigration = new(true); + public readonly MigrationData MdlCleanup = new(false); + public readonly MigrationData MtrlCleanup = new(false); + public readonly MigrationData MdlRestoration = new(false); + public readonly MigrationData MtrlRestoration = new(false); - public int Restored { get; private set; } - public int RestoreFails { get; private set; } - - public int CleanedUp { get; private set; } - - public int CleanupFails { get; private set; } - - public int Migrated { get; private set; } - - public int Unchanged { get; private set; } - - public int Failed { get; private set; } - public bool IsRunning => _currentTask is { IsCompleted: false }; - /// Writes or migrates a .mdl file during extraction from a regular archive. - public void MigrateMdlDuringExtraction(IReader reader, string directory, ExtractionOptions options) - { - if (!config.MigrateImportedModelsToV6) - { - reader.WriteEntryToDirectory(directory, options); - return; - } + public void CleanMdlBackups(string path) + => CleanBackups(path, "*.mdl.bak", "model", MdlCleanup, TaskType.MdlCleanup); - var path = Path.Combine(directory, reader.Entry.Key); - using var s = new MemoryStream(); - using var e = reader.OpenEntryStream(); - e.CopyTo(s); - using var b = new BinaryReader(s); - var version = b.ReadUInt32(); - if (version == MdlFile.V5) - { - var data = s.ToArray(); - var mdl = new MdlFile(data); - MigrateModel(path, mdl, false); - Penumbra.Log.Debug($"Migrated model {reader.Entry.Key} from V5 to V6 during import."); - } - else - { - using var f = File.Open(path, FileMode.Create, FileAccess.Write); - s.Seek(0, SeekOrigin.Begin); - s.WriteTo(f); - } - } + public void CleanMtrlBackups(string path) + => CleanBackups(path, "*.mtrl.bak", "material", MtrlCleanup, TaskType.MtrlCleanup); - public void CleanBackups(string path) + private void CleanBackups(string path, string extension, string fileType, MigrationData data, TaskType type) { if (IsRunning) return; @@ -76,13 +72,9 @@ public class MigrationManager(Configuration config) : IService var token = _source.Token; _currentTask = Task.Run(() => { - HasCleanUpTask = true; - IsCleanupTask = true; - IsMigrationTask = false; - IsRestorationTask = false; - CleanedUp = 0; - CleanupFails = 0; - foreach (var file in Directory.EnumerateFiles(path, "*.mdl.bak", SearchOption.AllDirectories)) + CurrentTask = type; + data.Init(); + foreach (var file in Directory.EnumerateFiles(path, extension, SearchOption.AllDirectories)) { if (token.IsCancellationRequested) return; @@ -90,19 +82,25 @@ public class MigrationManager(Configuration config) : IService try { File.Delete(file); - ++CleanedUp; - Penumbra.Log.Debug($"Deleted model backup file {file}."); + ++data.Changed; + Penumbra.Log.Debug($"Deleted {fileType} backup file {file}."); } catch (Exception ex) { - Penumbra.Messager.NotificationMessage(ex, $"Failed to delete model backup file {file}", NotificationType.Warning); - ++CleanupFails; + Penumbra.Messager.NotificationMessage(ex, $"Failed to delete {fileType} backup file {file}", NotificationType.Warning); + ++data.Failed; } } }, token); } - public void RestoreBackups(string path) + public void RestoreMdlBackups(string path) + => RestoreBackups(path, "*.mdl.bak", "model", MdlRestoration, TaskType.MdlRestoration); + + public void RestoreMtrlBackups(string path) + => RestoreBackups(path, "*.mtrl.bak", "material", MtrlRestoration, TaskType.MtrlRestoration); + + private void RestoreBackups(string path, string extension, string fileType, MigrationData data, TaskType type) { if (IsRunning) return; @@ -111,13 +109,9 @@ public class MigrationManager(Configuration config) : IService var token = _source.Token; _currentTask = Task.Run(() => { - HasRestoreTask = true; - IsCleanupTask = false; - IsMigrationTask = false; - IsRestorationTask = true; - CleanedUp = 0; - CleanupFails = 0; - foreach (var file in Directory.EnumerateFiles(path, "*.mdl.bak", SearchOption.AllDirectories)) + CurrentTask = type; + data.Init(); + foreach (var file in Directory.EnumerateFiles(path, extension, SearchOption.AllDirectories)) { if (token.IsCancellationRequested) return; @@ -126,40 +120,38 @@ public class MigrationManager(Configuration config) : IService try { File.Copy(file, target, true); - ++Restored; - Penumbra.Log.Debug($"Restored model backup file {file} to {target}."); + ++data.Changed; + Penumbra.Log.Debug($"Restored {fileType} backup file {file} to {target}."); } catch (Exception ex) { - Penumbra.Messager.NotificationMessage(ex, $"Failed to restore model backup file {file} to {target}", + Penumbra.Messager.NotificationMessage(ex, $"Failed to restore {fileType} backup file {file} to {target}", NotificationType.Warning); - ++RestoreFails; + ++data.Failed; } } }, token); } - /// Update the data of a .mdl file during TTMP extraction. Returns either the existing array or a new one. - public byte[] MigrateTtmpModel(string path, byte[] data) - { - FixLodNum(data); - if (!config.MigrateImportedModelsToV6) - return data; + public void MigrateMdlDirectory(string path, bool createBackups) + => MigrateDirectory(path, createBackups, "*.mdl", "model", MdlMigration, TaskType.MdlMigration, "from V5 to V6", "V6", + (file, fileData, backups) => + { + var mdl = new MdlFile(fileData); + return MigrateModel(file, mdl, backups); + }); - var version = BitConverter.ToUInt32(data); - if (version != 5) - return data; + public void MigrateMtrlDirectory(string path, bool createBackups) + => MigrateDirectory(path, createBackups, "*.mtrl", "material", MtrlMigration, TaskType.MtrlMigration, "to Dawntrail", "Dawntrail", + (file, fileData, backups) => + { + var mtrl = new MtrlFile(fileData); + return MigrateMaterial(file, mtrl, backups); + } + ); - var mdl = new MdlFile(data); - if (!mdl.ConvertV5ToV6()) - return data; - - data = mdl.Write(); - Penumbra.Log.Debug($"Migrated model {path} from V5 to V6 during import."); - return data; - } - - public void MigrateDirectory(string path, bool createBackups) + private void MigrateDirectory(string path, bool createBackups, string extension, string fileType, MigrationData data, TaskType type, + string action, string state, Func func) { if (IsRunning) return; @@ -168,14 +160,9 @@ public class MigrationManager(Configuration config) : IService var token = _source.Token; _currentTask = Task.Run(() => { - HasMigrationTask = true; - IsCleanupTask = false; - IsMigrationTask = true; - IsRestorationTask = false; - Unchanged = 0; - Migrated = 0; - Failed = 0; - foreach (var file in Directory.EnumerateFiles(path, "*.mdl", SearchOption.AllDirectories)) + CurrentTask = type; + data.Init(); + foreach (var file in Directory.EnumerateFiles(path, extension, SearchOption.AllDirectories)) { if (token.IsCancellationRequested) return; @@ -183,24 +170,24 @@ public class MigrationManager(Configuration config) : IService var timer = Stopwatch.StartNew(); try { - var data = File.ReadAllBytes(file); - var mdl = new MdlFile(data); - if (MigrateModel(file, mdl, createBackups)) + var fileData = File.ReadAllBytes(file); + if (func(file, fileData, createBackups)) { - ++Migrated; - Penumbra.Log.Debug($"Migrated model file {file} from V5 to V6 in {timer.ElapsedMilliseconds} ms."); + ++data.Changed; + Penumbra.Log.Debug($"Migrated {fileType} file {file} {action} in {timer.ElapsedMilliseconds} ms."); } else { - ++Unchanged; - Penumbra.Log.Verbose($"Verified that model file {file} is already V6 in {timer.ElapsedMilliseconds} ms."); + ++data.Unchanged; + Penumbra.Log.Verbose($"Verified that {fileType} file {file} is already {state} in {timer.ElapsedMilliseconds} ms."); } } catch (Exception ex) { - Penumbra.Messager.NotificationMessage(ex, $"Failed to migrate model file {file} to V6 in {timer.ElapsedMilliseconds} ms", + ++data.Failed; + Penumbra.Messager.NotificationMessage(ex, + $"Failed to migrate {fileType} file {file} to {state} in {timer.ElapsedMilliseconds} ms", NotificationType.Warning); - ++Failed; } } }, token); @@ -213,22 +200,6 @@ public class MigrationManager(Configuration config) : IService _currentTask = null; } - private static void FixLodNum(byte[] data) - { - const int modelHeaderLodOffset = 22; - - // Model file header LOD num - data[64] = 1; - - // Model header LOD num - var stackSize = BitConverter.ToUInt32(data, 4); - var runtimeBegin = stackSize + 0x44; - var stringsLengthOffset = runtimeBegin + 4; - var stringsLength = BitConverter.ToUInt32(data, (int)stringsLengthOffset); - var modelHeaderStart = stringsLengthOffset + stringsLength + 4; - data[modelHeaderStart + modelHeaderLodOffset] = 1; - } - public static bool TryMigrateSingleModel(string path, bool createBackup) { try @@ -259,6 +230,113 @@ public class MigrationManager(Configuration config) : IService } } + /// Writes or migrates a .mdl file during extraction from a regular archive. + public void MigrateMdlDuringExtraction(IReader reader, string directory, ExtractionOptions options) + { + if (!config.MigrateImportedModelsToV6) + { + reader.WriteEntryToDirectory(directory, options); + return; + } + + var path = Path.Combine(directory, reader.Entry.Key); + using var s = new MemoryStream(); + using var e = reader.OpenEntryStream(); + e.CopyTo(s); + using var b = new BinaryReader(s); + var version = b.ReadUInt32(); + if (version == MdlFile.V5) + { + var data = s.ToArray(); + var mdl = new MdlFile(data); + MigrateModel(path, mdl, false); + Penumbra.Log.Debug($"Migrated model {reader.Entry.Key} from V5 to V6 during import."); + } + else + { + using var f = File.Open(path, FileMode.Create, FileAccess.Write); + s.Seek(0, SeekOrigin.Begin); + s.WriteTo(f); + } + } + + public void MigrateMtrlDuringExtraction(IReader reader, string directory, ExtractionOptions options) + { + if (!config.MigrateImportedMaterialsToLegacy) + { + reader.WriteEntryToDirectory(directory, options); + return; + } + + var path = Path.Combine(directory, reader.Entry.Key); + using var s = new MemoryStream(); + using var e = reader.OpenEntryStream(); + e.CopyTo(s); + var file = new MtrlFile(s.GetBuffer()); + if (!file.IsDawnTrail) + { + file.MigrateToDawntrail(); + Penumbra.Log.Debug($"Migrated material {reader.Entry.Key} to Dawntrail during import."); + } + + using var f = File.Open(path, FileMode.Create, FileAccess.Write); + s.Seek(0, SeekOrigin.Begin); + s.WriteTo(f); + } + + /// Update the data of a .mdl file during TTMP extraction. Returns either the existing array or a new one. + public byte[] MigrateTtmpModel(string path, byte[] data) + { + FixLodNum(data); + if (!config.MigrateImportedModelsToV6) + return data; + + var version = BitConverter.ToUInt32(data); + if (version != 5) + return data; + + try + { + var mdl = new MdlFile(data); + if (!mdl.ConvertV5ToV6()) + return data; + + data = mdl.Write(); + Penumbra.Log.Debug($"Migrated model {path} from V5 to V6 during import."); + return data; + } + catch (Exception ex) + { + Penumbra.Log.Warning($"Failed to migrate model {path} from V5 to V6 during import:\n{ex}"); + return data; + } + } + + /// Update the data of a .mtrl file during TTMP extraction. Returns either the existing array or a new one. + public byte[] MigrateTtmpMaterial(string path, byte[] data) + { + if (!config.MigrateImportedMaterialsToLegacy) + return data; + + try + { + var mtrl = new MtrlFile(data); + if (mtrl.IsDawnTrail) + return data; + + mtrl.MigrateToDawntrail(); + data = mtrl.Write(); + Penumbra.Log.Debug($"Migrated material {path} to Dawntrail during import."); + return data; + } + catch (Exception ex) + { + Penumbra.Log.Warning($"Failed to migrate material {path} to Dawntrail during import:\n{ex}"); + return data; + } + } + + private static bool MigrateModel(string path, MdlFile mdl, bool createBackup) { if (!mdl.ConvertV5ToV6()) @@ -284,4 +362,20 @@ public class MigrationManager(Configuration config) : IService File.WriteAllBytes(path, data); return true; } + + private static void FixLodNum(byte[] data) + { + const int modelHeaderLodOffset = 22; + + // Model file header LOD num + data[64] = 1; + + // Model header LOD num + var stackSize = BitConverter.ToUInt32(data, 4); + var runtimeBegin = stackSize + 0x44; + var stringsLengthOffset = runtimeBegin + 4; + var stringsLength = BitConverter.ToUInt32(data, (int)stringsLengthOffset); + var modelHeaderStart = stringsLengthOffset + stringsLength + 4; + data[modelHeaderStart + modelHeaderLodOffset] = 1; + } } diff --git a/Penumbra/UI/Classes/MigrationSectionDrawer.cs b/Penumbra/UI/Classes/MigrationSectionDrawer.cs index 75d37368..ec76ddae 100644 --- a/Penumbra/UI/Classes/MigrationSectionDrawer.cs +++ b/Penumbra/UI/Classes/MigrationSectionDrawer.cs @@ -19,11 +19,13 @@ public class MigrationSectionDrawer(MigrationManager migrationManager, Configura _buttonSize = UiHelpers.InputTextWidth; DrawSettings(); ImGui.Separator(); - DrawMigration(); + DrawMdlMigration(); + DrawMdlRestore(); + DrawMdlCleanup(); ImGui.Separator(); - DrawCleanup(); - ImGui.Separator(); - DrawRestore(); + DrawMtrlMigration(); + DrawMtrlRestore(); + DrawMtrlCleanup(); } private void DrawSettings() @@ -34,88 +36,125 @@ public class MigrationSectionDrawer(MigrationManager migrationManager, Configura config.MigrateImportedModelsToV6 = value; config.Save(); } - } - private void DrawMigration() - { - ImUtf8.Checkbox("Create Backups During Manual Migration", ref _createBackups); - if (ImUtf8.ButtonEx("Migrate Model Files From V5 to V6"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) - migrationManager.MigrateDirectory(config.ModDirectory, _createBackups); + ImUtf8.HoverTooltip("This increments the version marker and restructures the bone table to the new version."u8); - ImUtf8.SameLineInner(); - DrawCancelButton(0, "Cancel the migration. This does not revert already finished migrations."u8); - DrawSpinner(migrationManager is { IsMigrationTask: true, IsRunning: true }); - - if (!migrationManager.HasMigrationTask) + if (ImUtf8.Checkbox("Automatically Migrate Materials to Dawntrail on Import"u8, ref value)) { - ImUtf8.IconDummy(); - return; + config.MigrateImportedMaterialsToLegacy = value; + config.Save(); } - var total = migrationManager.Failed + migrationManager.Migrated + migrationManager.Unchanged; - if (total == 0) - ImUtf8.TextFrameAligned("No model files found."u8); - else - ImUtf8.TextFrameAligned($"{migrationManager.Migrated} files migrated, {migrationManager.Failed} files failed, {total} total files."); + ImUtf8.HoverTooltip( + "This currently only increases the color-table size and switches the shader from 'character.shpk' to 'characterlegacy.shpk', if the former is used."u8); + + ImUtf8.Checkbox("Create Backups During Manual Migration", ref _createBackups); } - private void DrawCleanup() + private static ReadOnlySpan MigrationTooltip + => "Cancel the migration. This does not revert already finished migrations."u8; + + private void DrawMdlMigration() + { + if (ImUtf8.ButtonEx("Migrate Model Files From V5 to V6"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.MigrateMdlDirectory(config.ModDirectory, _createBackups); + + ImUtf8.SameLineInner(); + DrawCancelButton(MigrationManager.TaskType.MdlMigration, "Cancel the migration. This does not revert already finished migrations."u8); + DrawSpinner(migrationManager is { CurrentTask: MigrationManager.TaskType.MdlMigration, IsRunning: true }); + DrawData(migrationManager.MdlMigration, "No model files found."u8, "migrated"u8); + } + + private void DrawMtrlMigration() + { + if (ImUtf8.ButtonEx("Migrate Material Files to Dawntrail"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.MigrateMtrlDirectory(config.ModDirectory, _createBackups); + + ImUtf8.SameLineInner(); + DrawCancelButton(MigrationManager.TaskType.MtrlMigration, MigrationTooltip); + DrawSpinner(migrationManager is { CurrentTask: MigrationManager.TaskType.MtrlMigration, IsRunning: true }); + DrawData(migrationManager.MtrlMigration, "No material files found."u8, "migrated"u8); + } + + + private static ReadOnlySpan CleanupTooltip + => "Cancel the cleanup. This is not revertible."u8; + + private void DrawMdlCleanup() { if (ImUtf8.ButtonEx("Delete Existing Model Backup Files"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) - migrationManager.CleanBackups(config.ModDirectory); + migrationManager.CleanMdlBackups(config.ModDirectory); ImUtf8.SameLineInner(); - DrawCancelButton(1, "Cancel the cleanup. This is not revertible."u8); - DrawSpinner(migrationManager is { IsCleanupTask: true, IsRunning: true }); - if (!migrationManager.HasCleanUpTask) - { - ImUtf8.IconDummy(); - return; - } - - var total = migrationManager.CleanedUp + migrationManager.CleanupFails; - if (total == 0) - ImUtf8.TextFrameAligned("No model backup files found."u8); - else - ImUtf8.TextFrameAligned( - $"{migrationManager.CleanedUp} backups deleted, {migrationManager.CleanupFails} deletions failed, {total} total backups."); + DrawCancelButton(MigrationManager.TaskType.MdlCleanup, CleanupTooltip); + DrawSpinner(migrationManager is { CurrentTask: MigrationManager.TaskType.MdlCleanup, IsRunning: true }); + DrawData(migrationManager.MdlCleanup, "No model backup files found."u8, "deleted"u8); } - private void DrawSpinner(bool enabled) + private void DrawMtrlCleanup() + { + if (ImUtf8.ButtonEx("Delete Existing Material Backup Files"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.CleanMtrlBackups(config.ModDirectory); + + ImUtf8.SameLineInner(); + DrawCancelButton(MigrationManager.TaskType.MtrlCleanup, CleanupTooltip); + DrawSpinner(migrationManager is { CurrentTask: MigrationManager.TaskType.MtrlCleanup, IsRunning: true }); + DrawData(migrationManager.MtrlCleanup, "No material backup files found."u8, "deleted"u8); + } + + private static ReadOnlySpan RestorationTooltip + => "Cancel the restoration. This does not revert already finished restoration."u8; + + private void DrawMdlRestore() + { + if (ImUtf8.ButtonEx("Restore Model Backups"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.RestoreMdlBackups(config.ModDirectory); + + ImUtf8.SameLineInner(); + DrawCancelButton(MigrationManager.TaskType.MdlRestoration, RestorationTooltip); + DrawSpinner(migrationManager is { CurrentTask: MigrationManager.TaskType.MdlRestoration, IsRunning: true }); + DrawData(migrationManager.MdlRestoration, "No model backup files found."u8, "restored"u8); + } + + private void DrawMtrlRestore() + { + if (ImUtf8.ButtonEx("Restore Material Backups"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) + migrationManager.RestoreMtrlBackups(config.ModDirectory); + + ImUtf8.SameLineInner(); + DrawCancelButton(MigrationManager.TaskType.MtrlRestoration, RestorationTooltip); + DrawSpinner(migrationManager is { CurrentTask: MigrationManager.TaskType.MtrlRestoration, IsRunning: true }); + DrawData(migrationManager.MtrlRestoration, "No material backup files found."u8, "restored"u8); + } + + private static void DrawSpinner(bool enabled) { if (!enabled) return; + ImGui.SameLine(); ImUtf8.Spinner("Spinner"u8, ImGui.GetTextLineHeight() / 2, 2, ImGui.GetColorU32(ImGuiCol.Text)); } - private void DrawRestore() + private void DrawCancelButton(MigrationManager.TaskType task, ReadOnlySpan tooltip) { - if (ImUtf8.ButtonEx("Restore Model Backups"u8, "\0"u8, _buttonSize, migrationManager.IsRunning)) - migrationManager.RestoreBackups(config.ModDirectory); + using var _ = ImUtf8.PushId((int)task); + if (ImUtf8.ButtonEx("Cancel"u8, tooltip, disabled: !migrationManager.IsRunning || task != migrationManager.CurrentTask)) + migrationManager.Cancel(); + } - ImUtf8.SameLineInner(); - DrawCancelButton(2, "Cancel the restoration. This does not revert already finished restoration."u8); - DrawSpinner(migrationManager is { IsRestorationTask: true, IsRunning: true }); - - if (!migrationManager.HasRestoreTask) + private static void DrawData(MigrationManager.MigrationData data, ReadOnlySpan empty, ReadOnlySpan action) + { + if (!data.HasData) { ImUtf8.IconDummy(); return; } - var total = migrationManager.Restored + migrationManager.RestoreFails; + var total = data.Total; if (total == 0) - ImUtf8.TextFrameAligned("No model backup files found."u8); + ImUtf8.TextFrameAligned(empty); else - ImUtf8.TextFrameAligned( - $"{migrationManager.Restored} backups restored, {migrationManager.RestoreFails} restorations failed, {total} total backups."); - } - - private void DrawCancelButton(int id, ReadOnlySpan tooltip) - { - using var _ = ImUtf8.PushId(id); - if (ImUtf8.ButtonEx("Cancel"u8, tooltip, disabled: !migrationManager.IsRunning)) - migrationManager.Cancel(); + ImUtf8.TextFrameAligned($"{data.Changed} files {action}, {data.Failed} files failed, {total} files found."); } } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index ace3d6a3..be92b94e 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -15,6 +15,7 @@ using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections.Manager; @@ -433,10 +434,11 @@ public class DebugTab : Window, ITab, IUiService foreach (var obj in _objects) { ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"{((GameObject*)obj.Address)->ObjectIndex}" : "NULL"); - ImGuiUtil.DrawTableColumn($"0x{obj.Address:X}"); - ImGuiUtil.DrawTableColumn(obj.Address == nint.Zero - ? string.Empty - : $"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); + ImGui.TableNextColumn(); + ImGuiUtil.CopyOnClickSelectable($"0x{obj.Address:X}"); + ImGui.TableNextColumn(); + if (obj.Address != nint.Zero) + ImGuiUtil.CopyOnClickSelectable($"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); var identifier = _actors.FromObject(obj, out _, false, true, false); ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); var id = obj.AsObject->ObjectKind is ObjectKind.BattleNpc From a0a3435918c8f644aa4cedefcd3d9efe8643ccf4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Jul 2024 16:50:48 +0200 Subject: [PATCH 0727/1381] Remove not-yet-existing CS requirement. --- Penumbra.GameData | 2 +- repo.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index cf5be8af..d8c784e4 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit cf5be8af4c9ecbd9190bd3db746743fa5cd1560f +Subproject commit d8c784e443112d17d93ba7e6ab5d54f00f7f1477 diff --git a/repo.json b/repo.json index 3142f8d4..6379595e 100644 --- a/repo.json +++ b/repo.json @@ -9,7 +9,7 @@ "TestingAssemblyVersion": "1.1.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 9, + "DalamudApiLevel": 10, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 56502f19f9aa41003d532d68f225f7c956fa0f22 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 9 Jul 2024 14:55:15 +0000 Subject: [PATCH 0728/1381] [CI] Updating repo.json for testing_1.2.0.0 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 6379595e..c604a0dd 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.1.1.5", + "TestingAssemblyVersion": "1.2.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.1.1.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.0/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From c2517499f27f1a7c83ad9510d3cbf9ad6ad255e1 Mon Sep 17 00:00:00 2001 From: Ottermandias <70807659+Ottermandias@users.noreply.github.com> Date: Tue, 9 Jul 2024 17:04:27 +0200 Subject: [PATCH 0729/1381] Update repo.json --- repo.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/repo.json b/repo.json index c604a0dd..4f567253 100644 --- a/repo.json +++ b/repo.json @@ -11,7 +11,7 @@ "ApplicableVersion": "any", "DalamudApiLevel": 10, "IsHide": "False", - "IsTestingExclusive": "False", + "IsTestingExclusive": "True", "DownloadCount": 0, "LastUpdate": 0, "LoadPriority": 69420, From 3c417d7aeca0fd5668475e7644185c73f31e50b3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Jul 2024 17:48:34 +0200 Subject: [PATCH 0730/1381] Fix extraction of pmp failing --- Penumbra/Services/MigrationManager.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 1e6cb6b6..e377b65e 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -249,11 +249,13 @@ public class MigrationManager(Configuration config) : IService { var data = s.ToArray(); var mdl = new MdlFile(data); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); MigrateModel(path, mdl, false); Penumbra.Log.Debug($"Migrated model {reader.Entry.Key} from V5 to V6 during import."); } else { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); using var f = File.Open(path, FileMode.Create, FileAccess.Write); s.Seek(0, SeekOrigin.Begin); s.WriteTo(f); @@ -279,6 +281,7 @@ public class MigrationManager(Configuration config) : IService Penumbra.Log.Debug($"Migrated material {reader.Entry.Key} to Dawntrail during import."); } + Directory.CreateDirectory(Path.GetDirectoryName(path)!); using var f = File.Open(path, FileMode.Create, FileAccess.Write); s.Seek(0, SeekOrigin.Begin); s.WriteTo(f); From 1efd4938343bb0106d4a2e7c7166c7eebf8c8f12 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 9 Jul 2024 15:52:40 +0000 Subject: [PATCH 0731/1381] [CI] Updating repo.json for testing_1.2.0.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 4f567253..4231cf65 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.0", + "TestingAssemblyVersion": "1.2.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 3b980c1a49e8292d5a602f8852c373345fe767e8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Jul 2024 18:09:37 +0200 Subject: [PATCH 0732/1381] Fix two import bugs. --- Penumbra/Services/MigrationManager.cs | 1 + Penumbra/UI/Classes/MigrationSectionDrawer.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index e377b65e..5b353912 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -243,6 +243,7 @@ public class MigrationManager(Configuration config) : IService using var s = new MemoryStream(); using var e = reader.OpenEntryStream(); e.CopyTo(s); + s.Position = 0; using var b = new BinaryReader(s); var version = b.ReadUInt32(); if (version == MdlFile.V5) diff --git a/Penumbra/UI/Classes/MigrationSectionDrawer.cs b/Penumbra/UI/Classes/MigrationSectionDrawer.cs index ec76ddae..d588eaa0 100644 --- a/Penumbra/UI/Classes/MigrationSectionDrawer.cs +++ b/Penumbra/UI/Classes/MigrationSectionDrawer.cs @@ -39,6 +39,7 @@ public class MigrationSectionDrawer(MigrationManager migrationManager, Configura ImUtf8.HoverTooltip("This increments the version marker and restructures the bone table to the new version."u8); + value = config.MigrateImportedMaterialsToLegacy; if (ImUtf8.Checkbox("Automatically Migrate Materials to Dawntrail on Import"u8, ref value)) { config.MigrateImportedMaterialsToLegacy = value; From 806e001bad44e7bb6748c6ff20856ff9dbb41633 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 9 Jul 2024 16:11:41 +0000 Subject: [PATCH 0733/1381] [CI] Updating repo.json for testing_1.2.0.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 4231cf65..a5ec39b5 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.1", + "TestingAssemblyVersion": "1.2.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From baa439d2463d3de0276005d70d9bc7ca954b9a26 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Jul 2024 18:31:24 +0200 Subject: [PATCH 0734/1381] Fix enable/disable draw offsets. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index d8c784e4..49c5ba01 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d8c784e443112d17d93ba7e6ab5d54f00f7f1477 +Subproject commit 49c5ba0115814f809aaf4f31e6dcf321efb52237 From 37ffe528699191c4a06d7fa2a37412b927d10f04 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 9 Jul 2024 18:36:45 +0200 Subject: [PATCH 0735/1381] Fix issue with file substitutions. --- Penumbra/Api/DalamudSubstitutionProvider.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index 1c2cebcc..6347447a 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -1,3 +1,4 @@ +using Dalamud.Interface; using Dalamud.Plugin.Services; using OtterGui.Services; using Penumbra.Collections; @@ -13,6 +14,7 @@ namespace Penumbra.Api; public class DalamudSubstitutionProvider : IDisposable, IApiService { private readonly ITextureSubstitutionProvider _substitution; + private readonly IUiBuilder _uiBuilder; private readonly ActiveCollectionData _activeCollectionData; private readonly Configuration _config; private readonly CommunicatorService _communicator; @@ -21,9 +23,10 @@ public class DalamudSubstitutionProvider : IDisposable, IApiService => _config.UseDalamudUiTextureRedirection; public DalamudSubstitutionProvider(ITextureSubstitutionProvider substitution, ActiveCollectionData activeCollectionData, - Configuration config, CommunicatorService communicator) + Configuration config, CommunicatorService communicator, IUiBuilder ui) { _substitution = substitution; + _uiBuilder = ui; _activeCollectionData = activeCollectionData; _config = config; _communicator = communicator; @@ -41,6 +44,9 @@ public class DalamudSubstitutionProvider : IDisposable, IApiService public void ResetSubstitutions(IEnumerable paths) { + if (!_uiBuilder.UiPrepared) + return; + var transformed = paths .Where(p => (p.Path.StartsWith("ui/"u8) || p.Path.StartsWith("common/font/"u8)) && p.Path.EndsWith(".tex"u8)) .Select(p => p.ToString()); @@ -91,10 +97,7 @@ public class DalamudSubstitutionProvider : IDisposable, IApiService case ResolvedFileChanged.Type.Added: case ResolvedFileChanged.Type.Removed: case ResolvedFileChanged.Type.Replaced: - ResetSubstitutions(new[] - { - key, - }); + ResetSubstitutions([key]); break; case ResolvedFileChanged.Type.FullRecomputeStart: case ResolvedFileChanged.Type.FullRecomputeFinished: From e2112202a05e50fb5ec1ea7c5f21b0b6f43a08d2 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 9 Jul 2024 16:38:39 +0000 Subject: [PATCH 0736/1381] [CI] Updating repo.json for testing_1.2.0.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a5ec39b5..758a10d0 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.2", + "TestingAssemblyVersion": "1.2.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 1be75444cd8344b8a5774193bdf097c9b9f47d17 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 10 Jul 2024 12:51:47 +0200 Subject: [PATCH 0737/1381] Update BNPC Names --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 49c5ba01..a64a30bf 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 49c5ba0115814f809aaf4f31e6dcf321efb52237 +Subproject commit a64a30bf29cf297285ecde0579830b4d7fbae2d9 From 380dd0cffb8bc675c04c282d8bf92f72c5a1c3bb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 11 Jul 2024 01:40:45 +0200 Subject: [PATCH 0738/1381] Fix texture writing. --- Penumbra/Import/Textures/TexFileParser.cs | 4 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 7 +- Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs | 117 ++++++++++++++++++++++ Penumbra/UI/Tabs/EffectiveTab.cs | 2 +- 4 files changed, 125 insertions(+), 5 deletions(-) create mode 100644 Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 09025b61..ae4a39c0 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -79,8 +79,8 @@ public static class TexFileParser w.Write(header.Width); w.Write(header.Height); w.Write(header.Depth); - w.Write(header.MipCount); - w.Write(header.MipUnknownFlag); // TODO Lumina Update + w.Write((byte)(header.MipCount | (header.MipUnknownFlag ? 0x80 : 0))); + w.Write(header.ArraySize); unsafe { w.Write(header.LodOffset[0]); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index be92b94e..4966dd64 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -15,7 +15,6 @@ using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; using OtterGui.Services; -using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections.Manager; @@ -96,6 +95,7 @@ public class DebugTab : Window, ITab, IUiService private readonly IClientState _clientState; private readonly IpcTester _ipcTester; private readonly CrashHandlerPanel _crashHandlerPanel; + private readonly TexHeaderDrawer _texHeaderDrawer; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, @@ -105,7 +105,7 @@ public class DebugTab : Window, ITab, IUiService DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, - Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel) + Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -141,6 +141,7 @@ public class DebugTab : Window, ITab, IUiService _diagnostics = diagnostics; _ipcTester = ipcTester; _crashHandlerPanel = crashHandlerPanel; + _texHeaderDrawer = texHeaderDrawer; _objects = objects; _clientState = clientState; } @@ -176,6 +177,8 @@ public class DebugTab : Window, ITab, IUiService ImGui.NewLine(); DrawCollectionCaches(); ImGui.NewLine(); + _texHeaderDrawer.Draw(); + ImGui.NewLine(); DrawDebugCharacterUtility(); ImGui.NewLine(); DrawShaderReplacementFixer(); diff --git a/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs b/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs new file mode 100644 index 00000000..08d51184 --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs @@ -0,0 +1,117 @@ +using Dalamud.Interface.DragDrop; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using Lumina.Data.Files; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.Tabs.Debug; + +public class TexHeaderDrawer(IDragDropManager dragDrop) : IUiService +{ + private string? _path; + private TexFile.TexHeader _header; + private byte[]? _tex; + private Exception? _exception; + + public void Draw() + { + using var header = ImUtf8.CollapsingHeaderId("Tex Header"u8); + if (!header) + return; + + DrawDragDrop(); + DrawData(); + } + + private void DrawDragDrop() + { + dragDrop.CreateImGuiSource("TexFileDragDrop", m => m.Files.Count == 1 && m.Extensions.Contains(".tex"), m => + { + ImUtf8.Text($"Dragging {m.Files[0]}..."); + return true; + }); + + ImUtf8.Button("Drag .tex here..."); + if (dragDrop.CreateImGuiTarget("TexFileDragDrop", out var files, out _)) + ReadTex(files[0]); + } + + private void DrawData() + { + if (_path == null) + return; + + ImUtf8.TextFramed(_path, 0, borderColor: 0xFFFFFFFF); + + + if (_exception != null) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); + ImUtf8.TextWrapped($"Failure to load file:\n{_exception}"); + } + else if (_tex != null) + { + using var table = ImRaii.Table("table", 2, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); + if (!table) + return; + + TableLine("Format"u8, _header.Format); + TableLine("Width"u8, _header.Width); + TableLine("Height"u8, _header.Height); + TableLine("Depth"u8, _header.Depth); + TableLine("Mip Levels"u8, _header.MipCount); + TableLine("Array Size"u8, _header.ArraySize); + TableLine("Type"u8, _header.Type); + TableLine("Mip Flag"u8, _header.MipUnknownFlag); + TableLine("Byte Size"u8, _tex.Length); + unsafe + { + TableLine("LoD Offset 0"u8, _header.LodOffset[0]); + TableLine("LoD Offset 1"u8, _header.LodOffset[1]); + TableLine("LoD Offset 2"u8, _header.LodOffset[2]); + TableLine("LoD Offset 0"u8, _header.OffsetToSurface[0]); + TableLine("LoD Offset 1"u8, _header.OffsetToSurface[1]); + TableLine("LoD Offset 2"u8, _header.OffsetToSurface[2]); + TableLine("LoD Offset 3"u8, _header.OffsetToSurface[3]); + TableLine("LoD Offset 4"u8, _header.OffsetToSurface[4]); + TableLine("LoD Offset 5"u8, _header.OffsetToSurface[5]); + TableLine("LoD Offset 6"u8, _header.OffsetToSurface[6]); + TableLine("LoD Offset 7"u8, _header.OffsetToSurface[7]); + TableLine("LoD Offset 8"u8, _header.OffsetToSurface[8]); + TableLine("LoD Offset 9"u8, _header.OffsetToSurface[9]); + TableLine("LoD Offset 10"u8, _header.OffsetToSurface[10]); + TableLine("LoD Offset 11"u8, _header.OffsetToSurface[11]); + TableLine("LoD Offset 12"u8, _header.OffsetToSurface[12]); + } + } + } + + private static void TableLine(ReadOnlySpan text, T value) + { + ImGui.TableNextColumn(); + ImUtf8.Text(text); + ImGui.TableNextColumn(); + ImUtf8.Text($"{value}"); + } + + private unsafe void ReadTex(string path) + { + try + { + _path = path; + _tex = File.ReadAllBytes(_path); + if (_tex.Length < sizeof(TexFile.TexHeader)) + throw new Exception($"Size {_tex.Length} does not include a header."); + + _header = MemoryMarshal.Read(_tex); + _exception = null; + } + catch (Exception ex) + { + _tex = null; + _exception = ex; + } + } +} diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index 1b9af75c..e0cab43f 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -26,7 +26,7 @@ public class EffectiveTab(CollectionManager collectionManager, CollectionSelectH SetupEffectiveSizes(); collectionHeader.Draw(true); DrawFilters(); - using var child = ImRaii.Child("##EffectiveChangesTab", -Vector2.One, false); + using var child = ImRaii.Child("##EffectiveChangesTab", ImGui.GetContentRegionAvail(), false); if (!child) return; From 34cbf37c32a24c9af7f1807653220d9ed0c47974 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 10 Jul 2024 23:43:04 +0000 Subject: [PATCH 0739/1381] [CI] Updating repo.json for testing_1.2.0.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 758a10d0..7e90f7a9 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.3", + "TestingAssemblyVersion": "1.2.0.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 24597d7dc0cfa14bf25928f47b8e1f50665cbeee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Jul 2024 16:20:17 +0200 Subject: [PATCH 0740/1381] Fix mod normalization skipping the default submod. --- Penumbra/Mods/Editor/ModNormalizer.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index c0876f5d..30bf3d3f 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -277,6 +277,7 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) : ISer private void ApplyRedirections() { + _modManager.OptionEditor.SetFiles(Mod.Default, _redirections[0][0]); foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) foreach (var (container, containerIdx) in group.DataContainers.WithIndex()) _modManager.OptionEditor.SetFiles(container, _redirections[groupIdx + 1][containerIdx]); From 40be298d67d7a823ea67f62848028843d1b72244 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Jul 2024 17:37:19 +0200 Subject: [PATCH 0741/1381] Add automatic reduplication for ui files in pmps, test. --- Penumbra/Configuration.cs | 1 + Penumbra/Import/TexToolsImporter.Archives.cs | 4 +- Penumbra/Import/TexToolsImporter.Gui.cs | 66 +++++------ Penumbra/Mods/Editor/ModNormalizer.cs | 109 ++++++++++++++++++- Penumbra/Penumbra.cs | 1 + Penumbra/UI/Tabs/SettingsTab.cs | 3 + 6 files changed, 145 insertions(+), 39 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index f16569b5..63325433 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -96,6 +96,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public DoubleModifier DeleteModModifier { get; set; } = new(ModifierHotkey.Control, ModifierHotkey.Shift); public bool PrintSuccessfulCommandsToChat { get; set; } = true; public bool AutoDeduplicateOnImport { get; set; } = true; + public bool AutoReduplicateUiOnImport { get; set; } = true; public bool UseFileSystemCompression { get; set; } = true; public bool EnableHttpApi { get; set; } = true; diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index 63c170cb..dea343c6 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -1,9 +1,7 @@ -using System.IO; using Dalamud.Utility; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui.Filesystem; -using Penumbra.GameData.Files; using Penumbra.Import.Structs; using Penumbra.Mods; using SharpCompress.Archives; @@ -11,7 +9,6 @@ using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; using SharpCompress.Common; using SharpCompress.Readers; -using static FFXIVClientStructs.FFXIV.Client.UI.Misc.ConfigModule; using ZipArchive = SharpCompress.Archives.Zip.ZipArchive; namespace Penumbra.Import; @@ -114,6 +111,7 @@ public partial class TexToolsImporter _currentModDirectory.Refresh(); _modManager.Creator.SplitMultiGroups(_currentModDirectory); + _editor.ModNormalizer.NormalizeUi(_currentModDirectory); return _currentModDirectory; } diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index 78665f30..309f107a 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -20,59 +20,61 @@ public partial class TexToolsImporter private string _currentOptionName = string.Empty; private string _currentFileName = string.Empty; - public void DrawProgressInfo(Vector2 size) + public bool DrawProgressInfo(Vector2 size) { if (_modPackCount == 0) { ImGuiUtil.Center("Nothing to extract."); + return false; } - else if (_modPackCount == _currentModPackIdx) - { - DrawEndState(); - } + + if (_modPackCount == _currentModPackIdx) + return DrawEndState(); + + ImGui.NewLine(); + var percentage = (float)_currentModPackIdx / _modPackCount; + ImGui.ProgressBar(percentage, size, $"Mod {_currentModPackIdx + 1} / {_modPackCount}"); + ImGui.NewLine(); + if (State == ImporterState.DeduplicatingFiles) + ImGui.TextUnformatted($"Deduplicating {_currentModName}..."); else + ImGui.TextUnformatted($"Extracting {_currentModName}..."); + + if (_currentNumOptions > 1) { ImGui.NewLine(); - var percentage = (float)_currentModPackIdx / _modPackCount; - ImGui.ProgressBar(percentage, size, $"Mod {_currentModPackIdx + 1} / {_modPackCount}"); ImGui.NewLine(); - if (State == ImporterState.DeduplicatingFiles) - ImGui.TextUnformatted($"Deduplicating {_currentModName}..."); - else - ImGui.TextUnformatted($"Extracting {_currentModName}..."); - - if (_currentNumOptions > 1) - { - ImGui.NewLine(); - ImGui.NewLine(); - percentage = _currentNumOptions == 0 ? 1f : _currentOptionIdx / (float)_currentNumOptions; - ImGui.ProgressBar(percentage, size, $"Option {_currentOptionIdx + 1} / {_currentNumOptions}"); - ImGui.NewLine(); - if (State != ImporterState.DeduplicatingFiles) - ImGui.TextUnformatted( - $"Extracting option {(_currentGroupName.Length == 0 ? string.Empty : $"{_currentGroupName} - ")}{_currentOptionName}..."); - } - - ImGui.NewLine(); - ImGui.NewLine(); - percentage = _currentNumFiles == 0 ? 1f : _currentFileIdx / (float)_currentNumFiles; - ImGui.ProgressBar(percentage, size, $"File {_currentFileIdx + 1} / {_currentNumFiles}"); + percentage = _currentNumOptions == 0 ? 1f : _currentOptionIdx / (float)_currentNumOptions; + ImGui.ProgressBar(percentage, size, $"Option {_currentOptionIdx + 1} / {_currentNumOptions}"); ImGui.NewLine(); if (State != ImporterState.DeduplicatingFiles) - ImGui.TextUnformatted($"Extracting file {_currentFileName}..."); + ImGui.TextUnformatted( + $"Extracting option {(_currentGroupName.Length == 0 ? string.Empty : $"{_currentGroupName} - ")}{_currentOptionName}..."); } + + ImGui.NewLine(); + ImGui.NewLine(); + percentage = _currentNumFiles == 0 ? 1f : _currentFileIdx / (float)_currentNumFiles; + ImGui.ProgressBar(percentage, size, $"File {_currentFileIdx + 1} / {_currentNumFiles}"); + ImGui.NewLine(); + if (State != ImporterState.DeduplicatingFiles) + ImGui.TextUnformatted($"Extracting file {_currentFileName}..."); + return false; } - private void DrawEndState() + private bool DrawEndState() { var success = ExtractedMods.Count(t => t.Error == null); + if (ImGui.IsKeyPressed(ImGuiKey.Escape)) + return true; + ImGui.TextUnformatted($"Successfully extracted {success} / {ExtractedMods.Count} files."); ImGui.NewLine(); using var table = ImRaii.Table("##files", 2); if (!table) - return; + return false; foreach (var (file, dir, ex) in ExtractedMods) { @@ -91,6 +93,8 @@ public partial class TexToolsImporter ImGuiUtil.HoverTooltip(ex.ToString()); } } + + return false; } public bool DrawCancelButton(Vector2 size) diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 30bf3d3f..43cfc1ee 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -3,13 +3,15 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Services; using OtterGui.Tasks; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; +using Penumbra.Services; using Penumbra.String.Classes; namespace Penumbra.Mods.Editor; -public class ModNormalizer(ModManager _modManager, Configuration _config) : IService +public class ModNormalizer(ModManager modManager, Configuration config, SaveService saveService) : IService { private readonly List>> _redirections = []; @@ -39,6 +41,103 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) : ISer Worker = TrackedTask.Run(NormalizeSync); } + public void NormalizeUi(DirectoryInfo modDirectory) + { + if (!config.AutoReduplicateUiOnImport) + return; + + if (modManager.Creator.LoadMod(modDirectory, false) is not { } mod) + return; + + Dictionary> paths = []; + Dictionary containers = []; + foreach (var container in mod.AllDataContainers) + { + foreach (var (gamePath, path) in container.Files) + { + if (!gamePath.Path.StartsWith("ui/"u8)) + continue; + + if (!paths.TryGetValue(path, out var list)) + { + list = []; + paths.Add(path, list); + } + + list.Add((container, gamePath)); + containers.TryAdd(container, string.Empty); + } + } + + foreach (var container in containers.Keys.ToList()) + { + if (container.Group == null) + containers[container] = mod.ModPath.FullName; + else + { + var groupDir = ModCreator.NewOptionDirectory(mod.ModPath, container.Group.Name, config.ReplaceNonAsciiOnImport); + var optionDir = ModCreator.NewOptionDirectory(groupDir, container.GetName(), config.ReplaceNonAsciiOnImport); + containers[container] = optionDir.FullName; + } + } + + var anyChanges = 0; + var modRootLength = mod.ModPath.FullName.Length + 1; + foreach (var (file, gamePaths) in paths) + { + if (gamePaths.Count < 2) + continue; + + var keptPath = false; + foreach (var (container, gamePath) in gamePaths) + { + var directory = containers[container]; + var relPath = new Utf8RelPath(gamePath).ToString(); + var newFilePath = Path.Combine(directory, relPath); + if (newFilePath == file.FullName) + { + Penumbra.Log.Verbose($"[UIReduplication] Kept {file.FullName[modRootLength..]} because new path was identical."); + keptPath = true; + continue; + } + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(newFilePath)!); + File.Copy(file.FullName, newFilePath, false); + Penumbra.Log.Verbose($"[UIReduplication] Copied {file.FullName[modRootLength..]} to {newFilePath[modRootLength..]}."); + container.Files[gamePath] = new FullPath(newFilePath); + ++anyChanges; + } + catch (Exception ex) + { + Penumbra.Log.Error( + $"[UIReduplication] Failed to copy {file.FullName[modRootLength..]} to {newFilePath[modRootLength..]}:\n{ex}"); + } + } + + if (keptPath) + continue; + + try + { + File.Delete(file.FullName); + Penumbra.Log.Verbose($"[UIReduplication] Deleted {file.FullName[modRootLength..]} because no new path matched."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"[UIReduplication] Failed to delete {file.FullName[modRootLength..]}:\n{ex}"); + } + } + + if (anyChanges == 0) + return; + + saveService.Save(SaveType.ImmediateSync, new ModSaveGroup(mod.Default, config.ReplaceNonAsciiOnImport)); + saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); + Penumbra.Log.Information($"[UIReduplication] Saved groups after {anyChanges} changes."); + } + private void NormalizeSync() { try @@ -168,7 +267,7 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) : ISer // Normalize all other options. foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) { - var groupDir = ModCreator.CreateModFolder(directory, group.Name, _config.ReplaceNonAsciiOnImport, true); + var groupDir = ModCreator.CreateModFolder(directory, group.Name, config.ReplaceNonAsciiOnImport, true); _redirections[groupIdx + 1].EnsureCapacity(group.DataContainers.Count); for (var i = _redirections[groupIdx + 1].Count; i < group.DataContainers.Count; ++i) _redirections[groupIdx + 1].Add([]); @@ -188,7 +287,7 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) : ISer void HandleSubMod(DirectoryInfo groupDir, IModDataContainer option, Dictionary newDict) { var name = option.GetName(); - var optionDir = ModCreator.CreateModFolder(groupDir, name, _config.ReplaceNonAsciiOnImport, true); + var optionDir = ModCreator.CreateModFolder(groupDir, name, config.ReplaceNonAsciiOnImport, true); newDict.Clear(); newDict.EnsureCapacity(option.Files.Count); @@ -277,10 +376,10 @@ public class ModNormalizer(ModManager _modManager, Configuration _config) : ISer private void ApplyRedirections() { - _modManager.OptionEditor.SetFiles(Mod.Default, _redirections[0][0]); + modManager.OptionEditor.SetFiles(Mod.Default, _redirections[0][0]); foreach (var (group, groupIdx) in Mod.Groups.WithIndex()) foreach (var (container, containerIdx) in group.DataContainers.WithIndex()) - _modManager.OptionEditor.SetFiles(container, _redirections[groupIdx + 1][containerIdx]); + modManager.OptionEditor.SetFiles(container, _redirections[groupIdx + 1][containerIdx]); ++Step; } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 9f2db2e6..5f8d6805 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -213,6 +213,7 @@ public class Penumbra : IDalamudPlugin sb.Append( $"> **`Free Drive Space: `** {(drive != null ? Functions.HumanReadableSize(drive.AvailableFreeSpace) : "Unknown")}\n"); sb.Append($"> **`Auto-Deduplication: `** {_config.AutoDeduplicateOnImport}\n"); + sb.Append($"> **`Auto-UI-Reduplication: `** {_config.AutoReduplicateUiOnImport}\n"); sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); sb.Append( $"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")}\n"); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 8a4d6874..ab47ce7c 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -757,6 +757,9 @@ public class SettingsTab : ITab, IUiService Checkbox("Auto Deduplicate on Import", "Automatically deduplicate mod files on import. This will make mod file sizes smaller, but deletes (binary identical) files.", _config.AutoDeduplicateOnImport, v => _config.AutoDeduplicateOnImport = v); + Checkbox("Auto Reduplicate UI Files on PMP Import", + "Automatically reduplicate and normalize UI-specific files on import from PMP files. This is STRONGLY recommended because deduplicated UI files crash the game.", + _config.AutoReduplicateUiOnImport, v => _config.AutoReduplicateUiOnImport = v); DrawCompressionBox(); Checkbox("Keep Default Metadata Changes on Import", "Normally, metadata changes that equal their default values, which are sometimes exported by TexTools, are discarded. " From 22af545e8db41e6ec712eb3294dfd54dec6b42e1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Jul 2024 17:37:55 +0200 Subject: [PATCH 0742/1381] Add image strings to groups and mods to keep them in the json on saves. --- Penumbra/Mods/Groups/IModGroup.cs | 1 + Penumbra/Mods/Groups/ImcModGroup.cs | 2 ++ Penumbra/Mods/Groups/ModSaveGroup.cs | 2 ++ Penumbra/Mods/Groups/MultiModGroup.cs | 2 ++ Penumbra/Mods/Groups/SingleModGroup.cs | 2 ++ Penumbra/Mods/Manager/ModDataEditor.cs | 8 ++++++++ Penumbra/Mods/Mod.cs | 1 + Penumbra/Mods/ModMeta.cs | 1 + 8 files changed, 19 insertions(+) diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index 00f47e25..9327ced9 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -27,6 +27,7 @@ public interface IModGroup public Mod Mod { get; } public string Name { get; set; } public string Description { get; set; } + public string Image { get; set; } public GroupType Type { get; } public GroupDrawBehaviour Behaviour { get; } public ModPriority Priority { get; set; } diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 46204d6c..03896134 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -20,6 +20,7 @@ public class ImcModGroup(Mod mod) : IModGroup public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; public string Description { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; public GroupType Type => GroupType.Imc; @@ -170,6 +171,7 @@ public class ImcModGroup(Mod mod) : IModGroup { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Image = json[nameof(Image)]?.ToObject() ?? string.Empty, Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), AllVariants = json[nameof(AllVariants)]?.ToObject() ?? false, diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index c82c67c7..c465822b 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -88,6 +88,8 @@ public readonly struct ModSaveGroup : ISavable jWriter.WriteValue(group.Name); jWriter.WritePropertyName(nameof(group.Description)); jWriter.WriteValue(group.Description); + jWriter.WritePropertyName(nameof(group.Image)); + jWriter.WriteValue(group.Image); jWriter.WritePropertyName(nameof(group.Priority)); jWriter.WriteValue(group.Priority.Value); jWriter.WritePropertyName(nameof(group.Type)); diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 95f49230..ee27d534 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -26,6 +26,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public Mod Mod { get; } = mod; public string Name { get; set; } = "Group"; public string Description { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } public readonly List OptionData = []; @@ -69,6 +70,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Image = json[nameof(Image)]?.ToObject() ?? string.Empty, Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index a559d609..cc606f42 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -24,6 +24,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public Mod Mod { get; } = mod; public string Name { get; set; } = "Option"; public string Description { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; public ModPriority Priority { get; set; } public Setting DefaultSettings { get; set; } @@ -65,6 +66,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup { Name = json[nameof(Name)]?.ToObject() ?? string.Empty, Description = json[nameof(Description)]?.ToObject() ?? string.Empty, + Image = json[nameof(Image)]?.ToObject() ?? string.Empty, Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, }; diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 4ab9deb1..91ae4a4c 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -22,6 +22,7 @@ public enum ModDataChangeType : ushort Favorite = 0x0200, LocalTags = 0x0400, Note = 0x0800, + Image = 0x1000, } public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService) : IService @@ -113,6 +114,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic var newName = json[nameof(Mod.Name)]?.Value() ?? string.Empty; var newAuthor = json[nameof(Mod.Author)]?.Value() ?? string.Empty; var newDescription = json[nameof(Mod.Description)]?.Value() ?? string.Empty; + var newImage = json[nameof(Mod.Image)]?.Value() ?? string.Empty; var newVersion = json[nameof(Mod.Version)]?.Value() ?? string.Empty; var newWebsite = json[nameof(Mod.Website)]?.Value() ?? string.Empty; var newFileVersion = json[nameof(ModMeta.FileVersion)]?.Value() ?? 0; @@ -138,6 +140,12 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic mod.Description = newDescription; } + if (mod.Image != newImage) + { + changes |= ModDataChangeType.Image; + mod.Image = newImage; + } + if (mod.Version != newVersion) { changes |= ModDataChangeType.Version; diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index a7f87dcd..fcea7133 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -51,6 +51,7 @@ public sealed class Mod : IMod public string Description { get; internal set; } = string.Empty; public string Version { get; internal set; } = string.Empty; public string Website { get; internal set; } = string.Empty; + public string Image { get; internal set; } = string.Empty; public IReadOnlyList ModTags { get; internal set; } = []; diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index 870d6d4f..39dd20e4 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -19,6 +19,7 @@ public readonly struct ModMeta(Mod mod) : ISavable { nameof(Mod.Name), JToken.FromObject(mod.Name) }, { nameof(Mod.Author), JToken.FromObject(mod.Author) }, { nameof(Mod.Description), JToken.FromObject(mod.Description) }, + { nameof(Mod.Image), JToken.FromObject(mod.Image) }, { nameof(Mod.Version), JToken.FromObject(mod.Version) }, { nameof(Mod.Website), JToken.FromObject(mod.Website) }, { nameof(Mod.ModTags), JToken.FromObject(mod.ModTags) }, From 94a05afbe0ce00f2c1195ca8ac206bc6f29c4584 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Jul 2024 17:54:47 +0200 Subject: [PATCH 0743/1381] Make the import popup closeable by clicking outside if it is finished. --- Penumbra/Import/TexToolsImporter.Gui.cs | 23 ++++++++++------------- Penumbra/UI/ImportPopup.cs | 11 ++++++++--- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index 309f107a..a069204c 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -25,20 +25,22 @@ public partial class TexToolsImporter if (_modPackCount == 0) { ImGuiUtil.Center("Nothing to extract."); - return false; + return true; } if (_modPackCount == _currentModPackIdx) - return DrawEndState(); + { + DrawEndState(); + return true; + } ImGui.NewLine(); var percentage = (float)_currentModPackIdx / _modPackCount; ImGui.ProgressBar(percentage, size, $"Mod {_currentModPackIdx + 1} / {_modPackCount}"); ImGui.NewLine(); - if (State == ImporterState.DeduplicatingFiles) - ImGui.TextUnformatted($"Deduplicating {_currentModName}..."); - else - ImGui.TextUnformatted($"Extracting {_currentModName}..."); + ImGui.TextUnformatted(State == ImporterState.DeduplicatingFiles + ? $"Deduplicating {_currentModName}..." + : $"Extracting {_currentModName}..."); if (_currentNumOptions > 1) { @@ -63,18 +65,15 @@ public partial class TexToolsImporter } - private bool DrawEndState() + private void DrawEndState() { var success = ExtractedMods.Count(t => t.Error == null); - if (ImGui.IsKeyPressed(ImGuiKey.Escape)) - return true; - ImGui.TextUnformatted($"Successfully extracted {success} / {ExtractedMods.Count} files."); ImGui.NewLine(); using var table = ImRaii.Table("##files", 2); if (!table) - return false; + return; foreach (var (file, dir, ex) in ExtractedMods) { @@ -93,8 +92,6 @@ public partial class TexToolsImporter ImGuiUtil.HoverTooltip(ex.ToString()); } } - - return false; } public bool DrawCancelButton(Vector2 size) diff --git a/Penumbra/UI/ImportPopup.cs b/Penumbra/UI/ImportPopup.cs index fb2028b5..28767edc 100644 --- a/Penumbra/UI/ImportPopup.cs +++ b/Penumbra/UI/ImportPopup.cs @@ -1,4 +1,6 @@ +using Dalamud.Game.ClientState.Keys; using Dalamud.Interface.Windowing; +using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; @@ -68,13 +70,16 @@ public sealed class ImportPopup : Window, IUiService ImGui.SetNextWindowSize(size); using var popup = ImRaii.Popup(importPopup, ImGuiWindowFlags.Modal); PopupWasDrawn = true; + var terminate = false; using (var child = ImRaii.Child("##import", new Vector2(-1, size.Y - ImGui.GetFrameHeight() * 2))) { - if (child) - import.DrawProgressInfo(new Vector2(-1, ImGui.GetFrameHeight())); + if (child.Success && import.DrawProgressInfo(new Vector2(-1, ImGui.GetFrameHeight()))) + if (!ImGui.IsMouseHoveringRect(ImGui.GetWindowPos(), ImGui.GetWindowPos() + ImGui.GetWindowSize()) + && ImGui.IsMouseClicked(ImGuiMouseButton.Left)) + terminate = true; } - var terminate = import.State == ImporterState.Done + terminate |= import.State == ImporterState.Done ? ImGui.Button("Close", -Vector2.UnitX) : import.DrawCancelButton(-Vector2.UnitX); if (terminate) From d815266ed7b92ce2c474cd8e4da9c36a2d7fdcf4 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 12 Jul 2024 15:56:58 +0000 Subject: [PATCH 0744/1381] [CI] Updating repo.json for testing_1.2.0.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 7e90f7a9..51e458a8 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.4", + "TestingAssemblyVersion": "1.2.0.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,7 +18,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From d6f61f06cbf16e23900b4f317e5ecc8f63c7fc1b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 12 Jul 2024 22:15:00 +0200 Subject: [PATCH 0745/1381] Add TestingDalamudApiLevel --- repo.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 51e458a8..59daa590 100644 --- a/repo.json +++ b/repo.json @@ -9,9 +9,10 @@ "TestingAssemblyVersion": "1.2.0.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 10, + "DalamudApiLevel": 9, + "TestingDalamudApiLevel": 10, "IsHide": "False", - "IsTestingExclusive": "True", + "IsTestingExclusive": "False", "DownloadCount": 0, "LastUpdate": 0, "LoadPriority": 69420, From e46fcc4af1bbf083ab5ce07edea67ad5a554589d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 14 Jul 2024 20:38:54 +0200 Subject: [PATCH 0746/1381] Gracefully deal with invalid offhand IMCs. --- Penumbra.GameData | 2 +- Penumbra/Meta/Manipulations/Imc.cs | 3 ++- Penumbra/Services/ValidityChecker.cs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index a64a30bf..2c067b4f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit a64a30bf29cf297285ecde0579830b4d7fbae2d9 +Subproject commit 2c067b4f3c1d84888c2b961a93fe2de01fffe5f1 diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index 44c60942..d4887fe2 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -100,7 +100,8 @@ public readonly record struct ImcIdentifier( return false; if (!Enum.IsDefined(ObjectType)) return false; - + if (ItemData.AdaptOffhandImc(PrimaryId, out _)) + return false; break; } diff --git a/Penumbra/Services/ValidityChecker.cs b/Penumbra/Services/ValidityChecker.cs index cefee139..5feeab02 100644 --- a/Penumbra/Services/ValidityChecker.cs +++ b/Penumbra/Services/ValidityChecker.cs @@ -45,7 +45,7 @@ public class ValidityChecker : IService public void LogExceptions() { if (ImcExceptions.Count > 0) - Penumbra.Messager.NotificationMessage($"{ImcExceptions} IMC Exceptions thrown during Penumbra load. Please repair your game files.", + Penumbra.Messager.NotificationMessage($"{ImcExceptions.Count} IMC Exceptions thrown during Penumbra load. Please repair your game files.", NotificationType.Warning); } From 07c3be641ddc7950a3a818a44b5d155e828a3b7d Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 14 Jul 2024 18:41:39 +0000 Subject: [PATCH 0747/1381] [CI] Updating repo.json for testing_1.2.0.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 59daa590..4e1b17ba 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.5", + "TestingAssemblyVersion": "1.2.0.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 9c781f8563fb0bc85247fb83aab79980943cb2d5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jul 2024 22:04:36 +0200 Subject: [PATCH 0748/1381] Disable material migration for now --- Penumbra.GameData | 2 +- Penumbra/Services/MigrationManager.cs | 22 ++++++++++----- Penumbra/UI/Classes/MigrationSectionDrawer.cs | 28 ++++++++++--------- 3 files changed, 31 insertions(+), 21 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2c067b4f..c2a4c4ee 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2c067b4f3c1d84888c2b961a93fe2de01fffe5f1 +Subproject commit c2a4c4ee7470c5afbd3dd7731697ab49c055d1e3 diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 5b353912..7115fe4d 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -233,6 +233,8 @@ public class MigrationManager(Configuration config) : IService /// Writes or migrates a .mdl file during extraction from a regular archive. public void MigrateMdlDuringExtraction(IReader reader, string directory, ExtractionOptions options) { + // TODO reactivate when this works. + return; if (!config.MigrateImportedModelsToV6) { reader.WriteEntryToDirectory(directory, options); @@ -265,6 +267,8 @@ public class MigrationManager(Configuration config) : IService public void MigrateMtrlDuringExtraction(IReader reader, string directory, ExtractionOptions options) { + // TODO reactivate when this works. + return; if (!config.MigrateImportedMaterialsToLegacy) { reader.WriteEntryToDirectory(directory, options); @@ -276,16 +280,20 @@ public class MigrationManager(Configuration config) : IService using var e = reader.OpenEntryStream(); e.CopyTo(s); var file = new MtrlFile(s.GetBuffer()); - if (!file.IsDawnTrail) - { - file.MigrateToDawntrail(); - Penumbra.Log.Debug($"Migrated material {reader.Entry.Key} to Dawntrail during import."); - } Directory.CreateDirectory(Path.GetDirectoryName(path)!); using var f = File.Open(path, FileMode.Create, FileAccess.Write); - s.Seek(0, SeekOrigin.Begin); - s.WriteTo(f); + if (file.IsDawnTrail) + { + file.MigrateToDawntrail(); + Penumbra.Log.Debug($"Migrated material {reader.Entry.Key} to Dawntrail during import."); + f.Write(file.Write()); + } + else + { + s.Seek(0, SeekOrigin.Begin); + s.WriteTo(f); + } } /// Update the data of a .mdl file during TTMP extraction. Returns either the existing array or a new one. diff --git a/Penumbra/UI/Classes/MigrationSectionDrawer.cs b/Penumbra/UI/Classes/MigrationSectionDrawer.cs index d588eaa0..a4a2010f 100644 --- a/Penumbra/UI/Classes/MigrationSectionDrawer.cs +++ b/Penumbra/UI/Classes/MigrationSectionDrawer.cs @@ -22,10 +22,11 @@ public class MigrationSectionDrawer(MigrationManager migrationManager, Configura DrawMdlMigration(); DrawMdlRestore(); DrawMdlCleanup(); - ImGui.Separator(); - DrawMtrlMigration(); - DrawMtrlRestore(); - DrawMtrlCleanup(); + // TODO enable when this works + //ImGui.Separator(); + //DrawMtrlMigration(); + //DrawMtrlRestore(); + //DrawMtrlCleanup(); } private void DrawSettings() @@ -39,15 +40,16 @@ public class MigrationSectionDrawer(MigrationManager migrationManager, Configura ImUtf8.HoverTooltip("This increments the version marker and restructures the bone table to the new version."u8); - value = config.MigrateImportedMaterialsToLegacy; - if (ImUtf8.Checkbox("Automatically Migrate Materials to Dawntrail on Import"u8, ref value)) - { - config.MigrateImportedMaterialsToLegacy = value; - config.Save(); - } - - ImUtf8.HoverTooltip( - "This currently only increases the color-table size and switches the shader from 'character.shpk' to 'characterlegacy.shpk', if the former is used."u8); + // TODO enable when this works + //value = config.MigrateImportedMaterialsToLegacy; + //if (ImUtf8.Checkbox("Automatically Migrate Materials to Dawntrail on Import"u8, ref value)) + //{ + // config.MigrateImportedMaterialsToLegacy = value; + // config.Save(); + //} + // + //ImUtf8.HoverTooltip( + // "This currently only increases the color-table size and switches the shader from 'character.shpk' to 'characterlegacy.shpk', if the former is used."u8); ImUtf8.Checkbox("Create Backups During Manual Migration", ref _createBackups); } From 12dfaaef99192edfd00302d2c249f31f0c7a5509 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jul 2024 22:05:10 +0200 Subject: [PATCH 0749/1381] Fix broken mods being deleted instead of removed. Fix tags crashing when null instead of empty. --- Penumbra/Mods/Manager/ModDataEditor.cs | 4 ++-- Penumbra/Mods/Manager/ModManager.cs | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 91ae4a4c..7a0467d0 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -59,7 +59,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic importDate = json[nameof(Mod.ImportDate)]?.Value() ?? importDate; favorite = json[nameof(Mod.Favorite)]?.Value() ?? favorite; note = json[nameof(Mod.Note)]?.Value() ?? note; - localTags = json[nameof(Mod.LocalTags)]?.Values().OfType() ?? localTags; + localTags = (json[nameof(Mod.LocalTags)] as JArray)?.Values().OfType() ?? localTags; save = false; } catch (Exception e) @@ -119,7 +119,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic var newWebsite = json[nameof(Mod.Website)]?.Value() ?? string.Empty; var newFileVersion = json[nameof(ModMeta.FileVersion)]?.Value() ?? 0; var importDate = json[nameof(Mod.ImportDate)]?.Value(); - var modTags = json[nameof(Mod.ModTags)]?.Values().OfType(); + var modTags = (json[nameof(Mod.ModTags)] as JArray)?.Values().OfType(); ModDataChangeType changes = 0; if (mod.Name != newName) diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 4b19ea4c..f170a31b 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -115,12 +115,21 @@ public sealed class ModManager : ModStorage, IDisposable, IService Penumbra.Log.Error($"Could not delete the mod {mod.ModPath.Name}:\n{e}"); } + RemoveMod(mod); + } + + /// + /// Remove a loaded mod. The event is invoked before the mod is removed from the list. + /// Does not delete the mod from the filesystem. + /// Updates indices of later mods. + /// + public void RemoveMod(Mod mod) + { _communicator.ModPathChanged.Invoke(ModPathChangeType.Deleted, mod, mod.ModPath, null); foreach (var remainingMod in Mods.Skip(mod.Index + 1)) --remainingMod.Index; Mods.RemoveAt(mod.Index); - - Penumbra.Log.Debug($"Deleted mod {mod.Name}."); + Penumbra.Log.Debug($"Removed loaded mod {mod.Name} from list."); } /// @@ -135,10 +144,9 @@ public sealed class ModManager : ModStorage, IDisposable, IService if (!Creator.ReloadMod(mod, true, out var metaChange)) { Penumbra.Log.Warning(mod.Name.Length == 0 - ? $"Reloading mod {oldName} has failed, new name is empty. Deleting instead." - : $"Reloading mod {oldName} failed, {mod.ModPath.FullName} does not exist anymore or it ha. Deleting instead."); - - DeleteMod(mod); + ? $"Reloading mod {oldName} has failed, new name is empty. Removing from loaded mods instead." + : $"Reloading mod {oldName} failed, {mod.ModPath.FullName} does not exist anymore or it has invalid data. Removing from loaded mods instead."); + RemoveMod(mod); return; } From d952d83adf1b61ccb664420b29e7eb81593d3f7b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jul 2024 22:06:02 +0200 Subject: [PATCH 0750/1381] Fix redrawing while fishing while sitting. --- Penumbra/Interop/Services/RedrawService.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 163b2c0e..f288a35e 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -301,9 +301,14 @@ public sealed unsafe partial class RedrawService : IDisposable (CharacterModes)6 => // fishing GetCurrentAnimationId(obj) switch { - 278 => true, // line out. - 283 => true, // reeling in - _ => false, + 278 => true, // line out. + 283 => true, // reeling in + 284 => true, // reeling in + 287 => true, // reeling in 2 + 3149 => true, // line out sitting, + 3155 => true, // reeling in sitting, + 3159 => true, // reeling in sitting 2, + _ => false, }, _ => false, }; @@ -419,7 +424,7 @@ public sealed unsafe partial class RedrawService : IDisposable if (housingManager == null) return; - var currentTerritory = (OutdoorTerritory*) housingManager->CurrentTerritory; + var currentTerritory = (OutdoorTerritory*)housingManager->CurrentTerritory; if (currentTerritory == null || currentTerritory->GetTerritoryType() is not HousingTerritoryType.Outdoor) return; From c98bee67a5bb28adf2f59efbb23968f862d7653a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jul 2024 22:25:28 +0200 Subject: [PATCH 0751/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c2a4c4ee..67109fa9 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c2a4c4ee7470c5afbd3dd7731697ab49c055d1e3 +Subproject commit 67109fa9e89d5ff5c9f93705208db92e836e9ef4 From 78af40d5078dc322174935c76606256fcc08fdc1 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 16 Jul 2024 20:27:30 +0000 Subject: [PATCH 0752/1381] [CI] Updating repo.json for testing_1.2.0.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 4e1b17ba..9f11c118 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.6", + "TestingAssemblyVersion": "1.2.0.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 519b3d4891c67650d3a333fe9d52f77240f989f9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jul 2024 22:36:55 +0200 Subject: [PATCH 0753/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 67109fa9..c9e0d890 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 67109fa9e89d5ff5c9f93705208db92e836e9ef4 +Subproject commit c9e0d8905137fef6ed7c247ee1d2824d3f89f3b2 From 89cbb3f60dde8e72f3b4b8e2887eae5701268d39 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 16 Jul 2024 23:02:17 +0200 Subject: [PATCH 0754/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c9e0d890..45f2c901 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c9e0d8905137fef6ed7c247ee1d2824d3f89f3b2 +Subproject commit 45f2c901b3a0131eaee18b3520184baeb0d1049d From eb784dddf04e4380db02df6f0a58b95bd2635db8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 00:40:49 +0200 Subject: [PATCH 0755/1381] Fix missing file display. --- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 83a8958b..e915a879 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -132,7 +132,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService sb.Append($" | {unused} Unused Files"); if (_editor.Files.Missing.Count > 0) - sb.Append($" | {_editor.Files.Available.Count} Missing Files"); + sb.Append($" | {_editor.Files.Missing.Count} Missing Files"); if (redirections > 0) sb.Append($" | {redirections} Redirections"); From 67a35b9abbb22576dc8d5c5d16e7201d3fbb4fa9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 00:49:40 +0200 Subject: [PATCH 0756/1381] stupid --- Penumbra/Services/MigrationManager.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 7115fe4d..84318da6 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -233,8 +233,6 @@ public class MigrationManager(Configuration config) : IService /// Writes or migrates a .mdl file during extraction from a regular archive. public void MigrateMdlDuringExtraction(IReader reader, string directory, ExtractionOptions options) { - // TODO reactivate when this works. - return; if (!config.MigrateImportedModelsToV6) { reader.WriteEntryToDirectory(directory, options); @@ -267,9 +265,7 @@ public class MigrationManager(Configuration config) : IService public void MigrateMtrlDuringExtraction(IReader reader, string directory, ExtractionOptions options) { - // TODO reactivate when this works. - return; - if (!config.MigrateImportedMaterialsToLegacy) + if (!config.MigrateImportedMaterialsToLegacy || true) // TODO change when this is working { reader.WriteEntryToDirectory(directory, options); return; @@ -327,7 +323,7 @@ public class MigrationManager(Configuration config) : IService /// Update the data of a .mtrl file during TTMP extraction. Returns either the existing array or a new one. public byte[] MigrateTtmpMaterial(string path, byte[] data) { - if (!config.MigrateImportedMaterialsToLegacy) + if (!config.MigrateImportedMaterialsToLegacy || true) // TODO fix when this is working return data; try From ad877e68e610fcdec3f7fee993154a74b8929d3b Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 16 Jul 2024 22:51:33 +0000 Subject: [PATCH 0757/1381] [CI] Updating repo.json for testing_1.2.0.8 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 9f11c118..850acf1b 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.7", + "TestingAssemblyVersion": "1.2.0.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.8/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 4824a96ab0f9854ab75248c38a3f7549b1aad97a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 01:35:56 +0200 Subject: [PATCH 0758/1381] Enable Mtrl Restore and Cleanup again. --- Penumbra/UI/Classes/MigrationSectionDrawer.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/UI/Classes/MigrationSectionDrawer.cs b/Penumbra/UI/Classes/MigrationSectionDrawer.cs index a4a2010f..a3dcd23a 100644 --- a/Penumbra/UI/Classes/MigrationSectionDrawer.cs +++ b/Penumbra/UI/Classes/MigrationSectionDrawer.cs @@ -23,10 +23,10 @@ public class MigrationSectionDrawer(MigrationManager migrationManager, Configura DrawMdlRestore(); DrawMdlCleanup(); // TODO enable when this works - //ImGui.Separator(); + ImGui.Separator(); //DrawMtrlMigration(); - //DrawMtrlRestore(); - //DrawMtrlCleanup(); + DrawMtrlRestore(); + DrawMtrlCleanup(); } private void DrawSettings() From c9379b6d60d2a1f7f133c9fa7da3d7a6952a3651 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 16 Jul 2024 23:38:11 +0000 Subject: [PATCH 0759/1381] [CI] Updating repo.json for testing_1.2.0.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 850acf1b..b4becf0f 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.8", + "TestingAssemblyVersion": "1.2.0.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 1922353ba30e05a2b862f88b74a5e311fe5eb6d0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 02:01:52 +0200 Subject: [PATCH 0760/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 45f2c901..c25ea7b1 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 45f2c901b3a0131eaee18b3520184baeb0d1049d +Subproject commit c25ea7b19a6db37dd36e12b9a7a71f72a192ab57 From e7c786b239a53b3e145cc1e1101324170eb883b2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 18:02:48 +0200 Subject: [PATCH 0761/1381] Add and rework hooks around EST entries. --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/Meta/EstHook.cs | 47 +++++++++++-------- .../Hooks/Resources/ResolvePathHooksBase.cs | 38 ++++++++++++++- 3 files changed, 65 insertions(+), 22 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c25ea7b1..94df458d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c25ea7b19a6db37dd36e12b9a7a71f72a192ab57 +Subproject commit 94df458dfb2a704a611fa77d955808284aeb23ac diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index 5b272019..ce002664 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -3,51 +3,58 @@ using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Structs; using Penumbra.Meta.Manipulations; +using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; namespace Penumbra.Interop.Hooks.Meta; -public class EstHook : FastHook, IDisposable +public unsafe class EstHook : FastHook, IDisposable { - public delegate EstEntry Delegate(uint id, int estType, uint genderRace); + public delegate EstEntry Delegate(ResourceHandle* estResource, uint id, uint genderRace); - private readonly MetaState _metaState; + private readonly CharacterUtility _characterUtility; + private readonly MetaState _metaState; - public EstHook(HookManager hooks, MetaState metaState) + public EstHook(HookManager hooks, MetaState metaState, CharacterUtility characterUtility) { - _metaState = metaState; - Task = hooks.CreateHook("GetEstEntry", Sigs.GetEstEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); + _metaState = metaState; + _characterUtility = characterUtility; + Task = hooks.CreateHook("FindEstEntry", Sigs.FindEstEntry, Detour, + metaState.Config.EnableMods && HookSettings.MetaEntryHooks); _metaState.Config.ModsEnabled += Toggle; } - private EstEntry Detour(uint genderRace, int estType, uint id) + private EstEntry Detour(ResourceHandle* estResource, uint genderRace, uint id) { EstEntry ret; if (_metaState.EstCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache } - && cache.Est.TryGetValue(Convert(genderRace, estType, id), out var entry)) + && cache.Est.TryGetValue(Convert(estResource, genderRace, id), out var entry)) ret = entry.Entry; else - ret = Task.Result.Original(genderRace, estType, id); + ret = Task.Result.Original(estResource, genderRace, id); - Penumbra.Log.Excessive($"[GetEstEntry] Invoked with {genderRace}, {estType}, {id}, returned {ret.Value}."); + Penumbra.Log.Information($"[FindEstEntry] Invoked with 0x{(nint)estResource:X}, {genderRace}, {id}, returned {ret.Value}."); return ret; } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static EstIdentifier Convert(uint genderRace, int estType, uint id) + private EstIdentifier Convert(ResourceHandle* estResource, uint genderRace, uint id) { var i = new PrimaryId((ushort)id); var gr = (GenderRace)genderRace; - var type = estType switch - { - 1 => EstType.Face, - 2 => EstType.Hair, - 3 => EstType.Head, - 4 => EstType.Body, - _ => (EstType)0, - }; - return new EstIdentifier(i, type, gr); + + if (estResource == _characterUtility.Address->BodyEstResource) + return new EstIdentifier(i, EstType.Body, gr); + if (estResource == _characterUtility.Address->HairEstResource) + return new EstIdentifier(i, EstType.Hair, gr); + if (estResource == _characterUtility.Address->FaceEstResource) + return new EstIdentifier(i, EstType.Face, gr); + if (estResource == _characterUtility.Address->HeadEstResource) + return new EstIdentifier(i, EstType.Head, gr); + + return new EstIdentifier(i, 0, gr); } public void Dispose() diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 8fa6d861..e1b6e46e 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -19,6 +19,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private delegate nint NamedResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint name); private delegate nint PerSlotResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex); private delegate nint SingleResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize); + private delegate nint SkeletonVFuncDelegate(nint drawObject, int estType, nint unk); private delegate nint TmbResolveDelegate(nint drawObject, nint pathBuffer, nint pathBufferSize, nint timelineName); @@ -37,6 +38,8 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private readonly Hook _resolveSkpPathHook; private readonly Hook _resolveTmbPathHook; private readonly Hook _resolveVfxPathHook; + private readonly Hook? _vFunc81Hook; + private readonly Hook? _vFunc83Hook; private readonly PathState _parent; @@ -49,6 +52,9 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[78], type, ResolveSkp, ResolveSkpHuman); _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[79], type, ResolvePhyb, ResolvePhybHuman); + _vFunc81Hook = Create( $"{name}.{nameof(VFunc81)}", hooks, vTable[81], type, null, VFunc81); + + _vFunc83Hook = Create( $"{name}.{nameof(VFunc83)}", hooks, vTable[83], type, null, VFunc83); _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[84], type, ResolvePap, ResolvePapHuman); _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[85], ResolveTmb); @@ -58,6 +64,8 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveDecalPathHook = Create($"{name}.{nameof(ResolveDecal)}", hooks, vTable[92], ResolveDecal); _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[93], type, ResolveVfx, ResolveVfxHuman); _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[94], ResolveEid); + + // @formatter:on if (HookSettings.ResourceHooks) Enable(); @@ -77,6 +85,8 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveSkpPathHook.Enable(); _resolveTmbPathHook.Enable(); _resolveVfxPathHook.Enable(); + _vFunc81Hook?.Enable(); + _vFunc83Hook?.Enable(); } public void Disable() @@ -93,6 +103,8 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveSkpPathHook.Disable(); _resolveTmbPathHook.Disable(); _resolveVfxPathHook.Disable(); + _vFunc81Hook?.Disable(); + _vFunc83Hook?.Disable(); } public void Dispose() @@ -109,6 +121,8 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveSkpPathHook.Dispose(); _resolveTmbPathHook.Dispose(); _resolveVfxPathHook.Dispose(); + _vFunc81Hook?.Dispose(); + _vFunc83Hook?.Dispose(); } private nint ResolveDecal(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) @@ -224,14 +238,36 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ResolvePath(drawObject, pathBuffer); } + private nint VFunc81(nint drawObject, int estType, nint unk) + { + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = _vFunc81Hook!.Original(drawObject, estType, unk); + _parent.MetaState.EstCollection.Pop(); + return ret; + } + + private nint VFunc83(nint drawObject, int estType, nint unk) + { + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = _vFunc83Hook!.Original(drawObject, estType, unk); + _parent.MetaState.EstCollection.Pop(); + return ret; + } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static Hook Create(string name, HookManager hooks, nint address, Type type, T other, T human) where T : Delegate + [return: NotNullIfNotNull(nameof(other))] + private static Hook? Create(string name, HookManager hooks, nint address, Type type, T? other, T human) where T : Delegate { var del = type switch { Type.Human => human, _ => other, }; + if (del == null) + return null; + return hooks.CreateHook(name, address, del).Result; } From 6d0562180acbae396cbcbb8c9ed21f0d1b1eec2c Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 17 Jul 2024 16:05:28 +0000 Subject: [PATCH 0762/1381] [CI] Updating repo.json for testing_1.2.0.10 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index b4becf0f..986c1707 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.9", + "TestingAssemblyVersion": "1.2.0.10", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.10/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 9bba1e2b31a26e890e34d72693e7d2521e43fea3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 18:05:57 +0200 Subject: [PATCH 0763/1381] Remove log spamming. --- Penumbra/Interop/Hooks/Meta/EstHook.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index ce002664..825b1244 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -35,7 +35,7 @@ public unsafe class EstHook : FastHook, IDisposable else ret = Task.Result.Original(estResource, genderRace, id); - Penumbra.Log.Information($"[FindEstEntry] Invoked with 0x{(nint)estResource:X}, {genderRace}, {id}, returned {ret.Value}."); + Penumbra.Log.Excessive($"[FindEstEntry] Invoked with 0x{(nint)estResource:X}, {genderRace}, {id}, returned {ret.Value}."); return ret; } From 5abbd8b1101090afba2729cfbbf4adeeb673e615 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Jul 2024 18:34:03 +0200 Subject: [PATCH 0764/1381] Hook UpdateRender despite per-frame calls. --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs | 37 ------------------- .../{GetEqpIndirect2.cs => UpdateRender.cs} | 15 +++----- 3 files changed, 6 insertions(+), 48 deletions(-) delete mode 100644 Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs rename Penumbra/Interop/Hooks/Meta/{GetEqpIndirect2.cs => UpdateRender.cs} (55%) diff --git a/Penumbra.GameData b/Penumbra.GameData index 94df458d..c5ad1f3a 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 94df458dfb2a704a611fa77d955808284aeb23ac +Subproject commit c5ad1f3ae9818baa446327bdcf49fac65088c703 diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs b/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs deleted file mode 100644 index 8bd49500..00000000 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect.cs +++ /dev/null @@ -1,37 +0,0 @@ -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Services; -using Penumbra.Collections; -using Penumbra.GameData; -using Penumbra.Interop.PathResolving; - -namespace Penumbra.Interop.Hooks.Meta; - -public sealed unsafe class GetEqpIndirect : FastHook -{ - private readonly CollectionResolver _collectionResolver; - private readonly MetaState _metaState; - - public GetEqpIndirect(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) - { - _collectionResolver = collectionResolver; - _metaState = metaState; - Task = hooks.CreateHook("Get EQP Indirect", Sigs.GetEqpIndirect, Detour, HookSettings.MetaParentHooks); - } - - public delegate void Delegate(DrawObject* drawObject); - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void Detour(DrawObject* drawObject) - { - // Shortcut because this is also called all the time. - // Same thing is checked at the beginning of the original function. - if ((*(byte*)((nint)drawObject + Offsets.GetEqpIndirectSkip1) & 1) == 0 || *(ulong*)((nint)drawObject + Offsets.GetEqpIndirectSkip2) == 0) - return; - - Penumbra.Log.Excessive($"[Get EQP Indirect] Invoked on {(nint)drawObject:X}."); - var collection = _collectionResolver.IdentifyCollection(drawObject, true); - _metaState.EqpCollection.Push(collection); - Task.Result.Original(drawObject); - _metaState.EqpCollection.Pop(); - } -} diff --git a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs b/Penumbra/Interop/Hooks/Meta/UpdateRender.cs similarity index 55% rename from Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs rename to Penumbra/Interop/Hooks/Meta/UpdateRender.cs index e90674a8..95cc0e15 100644 --- a/Penumbra/Interop/Hooks/Meta/GetEqpIndirect2.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateRender.cs @@ -1,20 +1,20 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; -using Penumbra.GameData; using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Meta; -public sealed unsafe class GetEqpIndirect2 : FastHook +/// The actual function is inlined, so we need to hook its only callsite: Human.UpdateRender instead. +public sealed unsafe class UpdateRender : FastHook { private readonly CollectionResolver _collectionResolver; private readonly MetaState _metaState; - public GetEqpIndirect2(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) + public UpdateRender(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState, CharacterBaseVTables vTables) { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Get EQP Indirect 2", Sigs.GetEqpIndirect2, Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Human.UpdateRender", vTables.HumanVTable[4], Detour, HookSettings.MetaParentHooks); } public delegate void Delegate(DrawObject* drawObject); @@ -22,12 +22,7 @@ public sealed unsafe class GetEqpIndirect2 : FastHook [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void Detour(DrawObject* drawObject) { - // Shortcut because this is also called all the time. - // Same thing is checked at the beginning of the original function. - if (((*(uint*)((nint)drawObject + Offsets.GetEqpIndirect2Skip) >> 0x12) & 1) == 0) - return; - - Penumbra.Log.Excessive($"[Get EQP Indirect 2] Invoked on {(nint)drawObject:X}."); + Penumbra.Log.Excessive($"[Human.UpdateRender] Invoked on {(nint)drawObject:X}."); var collection = _collectionResolver.IdentifyCollection(drawObject, true); _metaState.EqpCollection.Push(collection); Task.Result.Original(drawObject); From defba19b2d7714162d0eca036d212aef48aad667 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 17 Jul 2024 16:36:04 +0000 Subject: [PATCH 0765/1381] [CI] Updating repo.json for testing_1.2.0.11 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 986c1707..d715bca2 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.10", + "TestingAssemblyVersion": "1.2.0.11", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.10/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.11/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From f978b35b764fac7037f72f9ffa6f60dc2cd7bf13 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Jul 2024 14:24:29 +0200 Subject: [PATCH 0766/1381] Make ResourceTrees work with UseNoMods. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/MetaCache.cs | 4 ---- .../Collections/ModCollection.Cache.Access.cs | 9 --------- Penumbra/Import/Models/ModelManager.cs | 6 ++++-- .../ResourceTree/ResolveContext.PathResolution.cs | 15 ++++++++------- Penumbra/Interop/ResourceTree/ResolveContext.cs | 10 ++++++++-- .../Interop/ResourceTree/ResourceTreeFactory.cs | 4 +++- 7 files changed, 24 insertions(+), 26 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c5ad1f3a..a1e637f8 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c5ad1f3ae9818baa446327bdcf49fac65088c703 +Subproject commit a1e637f835c1a42732825e8e0690aeef0024b101 diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 02056fad..1a6924a9 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -103,10 +103,6 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) ~MetaCache() => Dispose(); - /// Try to obtain a manipulated IMC file. - public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out Meta.Files.ImcFile? file) - => Imc.GetFile(path.Path, out file); - internal EqdpEntry GetEqdpEntry(GenderRace race, bool accessory, PrimaryId primaryId) => Eqdp.ApplyFullEntry(primaryId, race, accessory, Meta.Files.ExpandedEqdpFile.GetDefault(manager, race, accessory, primaryId)); diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 81751128..983509a4 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -43,15 +43,6 @@ public partial class ModCollection internal MetaCache? MetaCache => _cache?.Meta; - public bool GetImcFile(Utf8GamePath path, [NotNullWhen(true)] out ImcFile? file) - { - if (_cache != null) - return _cache.Meta.GetImcFile(path, out file); - - file = null; - return false; - } - internal IReadOnlyDictionary ResolvedFiles => _cache?.ResolvedFiles ?? new ConcurrentDictionary(); diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 01396cfb..0c19bc0a 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -12,6 +12,8 @@ using Penumbra.GameData.Structs; using Penumbra.Import.Models.Export; using Penumbra.Import.Models.Import; using Penumbra.Import.Textures; +using Penumbra.Meta; +using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using SharpGLTF.Scenes; using SixLabors.ImageSharp; @@ -22,7 +24,7 @@ namespace Penumbra.Import.Models; using Schema2 = SharpGLTF.Schema2; using LuminaMaterial = Lumina.Models.Materials.Material; -public sealed class ModelManager(IFramework framework, ActiveCollections collections, GamePathParser parser) +public sealed class ModelManager(IFramework framework, MetaFileManager metaFileManager, ActiveCollections collections, GamePathParser parser) : SingleTaskQueue, IDisposable, IService { private readonly IFramework _framework = framework; @@ -97,7 +99,7 @@ public sealed class ModelManager(IFramework framework, ActiveCollections collect // Try to use an entry from provided manipulations, falling back to the current collection. var targetId = modEst?.Value ?? collections.Current.MetaCache?.GetEstEntry(type, info.GenderRace, info.PrimaryId) - ?? EstEntry.Zero; + ?? EstFile.GetDefault(metaFileManager, type, info.GenderRace, info.PrimaryId); // If there's no entries, we can assume that there's no additional skeleton. if (targetId == EstEntry.Zero) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 72cb1681..07f305ac 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -3,6 +3,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.String; @@ -51,10 +52,8 @@ internal partial record ResolveContext return GenderRace.MidlanderMale; var metaCache = Global.Collection.MetaCache; - if (metaCache == null) - return GenderRace.MidlanderMale; - - var entry = metaCache.GetEqdpEntry(characterRaceCode, accessory, primaryId); + var entry = metaCache?.GetEqdpEntry(characterRaceCode, accessory, primaryId) + ?? ExpandedEqdpFile.GetDefault(Global.MetaFileManager, characterRaceCode, accessory, primaryId); if (entry.ToBits(slot).Item2) return characterRaceCode; @@ -62,7 +61,8 @@ internal partial record ResolveContext if (fallbackRaceCode == GenderRace.MidlanderMale) return GenderRace.MidlanderMale; - entry = metaCache.GetEqdpEntry(fallbackRaceCode, accessory, primaryId); + entry = metaCache?.GetEqdpEntry(fallbackRaceCode, accessory, primaryId) + ?? ExpandedEqdpFile.GetDefault(Global.MetaFileManager, fallbackRaceCode, accessory, primaryId); if (entry.ToBits(slot).Item2) return fallbackRaceCode; @@ -271,8 +271,9 @@ internal partial record ResolveContext private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstType type, PrimaryId primary) { - var metaCache = Global.Collection.MetaCache; - var skeletonSet = metaCache?.GetEstEntry(type, raceCode, primary) ?? default; + var metaCache = Global.Collection.MetaCache; + var skeletonSet = metaCache?.GetEstEntry(type, raceCode, primary) + ?? EstFile.GetDefault(Global.MetaFileManager, type, raceCode, primary); return (raceCode, type.ToName(), skeletonSet.AsId); } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index a852a4cc..acb320d4 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -11,6 +11,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.PathResolving; +using Penumbra.Meta; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; @@ -19,7 +20,12 @@ using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.M namespace Penumbra.Interop.ResourceTree; -internal record GlobalResolveContext(ObjectIdentification Identifier, ModCollection Collection, TreeBuildCache TreeBuildCache, bool WithUiData) +internal record GlobalResolveContext( + MetaFileManager MetaFileManager, + ObjectIdentification Identifier, + ModCollection Collection, + TreeBuildCache TreeBuildCache, + bool WithUiData) { public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); @@ -111,7 +117,7 @@ internal unsafe partial record ResolveContext( if (resourceHandle == null) throw new ArgumentNullException(nameof(resourceHandle)); - var fileName = (ReadOnlySpan) resourceHandle->FileName.AsSpan(); + var fileName = (ReadOnlySpan)resourceHandle->FileName.AsSpan(); var additionalData = ByteString.Empty; if (PathDataHandler.Split(fileName, out fileName, out var data)) additionalData = ByteString.FromSpanUnsafe(data, false).Clone(); diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 1f6d1f6f..46c7ce35 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -8,6 +8,7 @@ using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; +using Penumbra.Meta; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; @@ -15,6 +16,7 @@ namespace Penumbra.Interop.ResourceTree; public class ResourceTreeFactory( IDataManager gameData, ObjectManager objects, + MetaFileManager metaFileManager, CollectionResolver resolver, ObjectIdentification identifier, Configuration config, @@ -78,7 +80,7 @@ public class ResourceTreeFactory( var networked = character.EntityId != 0xE0000000; var tree = new ResourceTree(name, anonymizedName, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name, collectionResolveData.ModCollection.AnonymizedName); - var globalContext = new GlobalResolveContext(identifier, collectionResolveData.ModCollection, + var globalContext = new GlobalResolveContext(metaFileManager, identifier, collectionResolveData.ModCollection, cache, (flags & Flags.WithUiData) != 0); using (var _ = pathState.EnterInternalResolve()) { From f533ae66671c49682451982656f268d13192d7a0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Jul 2024 17:33:54 +0200 Subject: [PATCH 0767/1381] Some cleanup. --- .../ResolveContext.PathResolution.cs | 2 -- .../ResourceTree/ResourceTreeFactory.cs | 18 ++++++++++-------- .../Interop/Structs/CharacterUtilityData.cs | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 07f305ac..678dd8a9 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -199,8 +199,6 @@ internal partial record ResolveContext ByteString? path; try { - Penumbra.Log.Information($"{(nint)CharacterBase:X} {ModelType} {SlotIndex} 0x{(ulong)mtrlFileName:X}"); - Penumbra.Log.Information($"{new ByteString(mtrlFileName)}"); path = CharacterBase->ResolveMtrlPathAsByteString(SlotIndex, mtrlFileName); } catch (AccessViolationException) diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 46c7ce35..65fac68f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -18,7 +18,7 @@ public class ResourceTreeFactory( ObjectManager objects, MetaFileManager metaFileManager, CollectionResolver resolver, - ObjectIdentification identifier, + ObjectIdentification objectIdentifier, Configuration config, ActorManager actors, PathState pathState) : IService @@ -80,7 +80,7 @@ public class ResourceTreeFactory( var networked = character.EntityId != 0xE0000000; var tree = new ResourceTree(name, anonymizedName, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Name, collectionResolveData.ModCollection.AnonymizedName); - var globalContext = new GlobalResolveContext(metaFileManager, identifier, collectionResolveData.ModCollection, + var globalContext = new GlobalResolveContext(metaFileManager, objectIdentifier, collectionResolveData.ModCollection, cache, (flags & Flags.WithUiData) != 0); using (var _ = pathState.EnterInternalResolve()) { @@ -125,6 +125,14 @@ public class ResourceTreeFactory( private static void FilterFullPaths(ResourceTree tree, string? onlyWithinPath) { + foreach (var node in tree.FlatNodes) + { + if (!ShallKeepPath(node.FullPath, onlyWithinPath)) + node.FullPath = FullPath.Empty; + } + + return; + static bool ShallKeepPath(FullPath fullPath, string? onlyWithinPath) { if (!fullPath.IsRooted) @@ -139,12 +147,6 @@ public class ResourceTreeFactory( return fullPath.Exists; } - - foreach (var node in tree.FlatNodes) - { - if (!ShallKeepPath(node.FullPath, onlyWithinPath)) - node.FullPath = FullPath.Empty; - } } private static void Cleanup(ResourceTree tree) diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index d33da477..197de0bb 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -15,7 +15,7 @@ public unsafe struct CharacterUtilityData .Where(n => n.First.StartsWith("Eqdp")) .Select(n => n.Second).ToArray(); - public const int TotalNumResources = 89; + public const int TotalNumResources = 114; /// Obtain the index for the eqdp file corresponding to the given race code and accessory. public static MetaIndex EqdpIdx(GenderRace raceCode, bool accessory) From a4548bbf0426fb181e49396147677ebecfe87147 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 00:11:13 +0200 Subject: [PATCH 0768/1381] Apply unprioritized mod groups in reverse order. --- Penumbra/Mods/Mod.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index fcea7133..16f06de2 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -73,7 +73,7 @@ public sealed class Mod : IMod var dictRedirections = new Dictionary(TotalFileCount); var setManips = new MetaDictionary(); - foreach (var (group, groupIndex) in Groups.WithIndex().OrderByDescending(g => g.Value.Priority)) + foreach (var (group, groupIndex) in Groups.WithIndex().Reverse().OrderByDescending(g => g.Value.Priority)) { var config = settings.Settings[groupIndex]; group.AddData(config, dictRedirections, setManips); From 258f7e9732229f754f086fa79126e4246a7eb0b1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 00:13:43 +0200 Subject: [PATCH 0769/1381] Reinstate the inlined ApricotSoundPlay hook one layer hup. --- Penumbra.GameData | 2 +- .../Animation/ApricotListenerSoundPlay.cs | 42 ++++++++++++------- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index a1e637f8..9f1816f1 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit a1e637f835c1a42732825e8e0690aeef0024b101 +Subproject commit 9f1816f1b75003d01c5576769831c10f3d8948a7 diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index 2e05c1b6..361fcd4e 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -1,4 +1,3 @@ -using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; @@ -11,33 +10,48 @@ using Penumbra.Services; namespace Penumbra.Interop.Hooks.Animation; /// Called for some sound effects caused by animations or VFX. -public sealed unsafe class ApricotListenerSoundPlay : FastHook +/// Actual function got inlined. +public sealed unsafe class ApricotListenerSoundPlayCaller : FastHook { private readonly GameState _state; private readonly CollectionResolver _collectionResolver; private readonly CrashHandlerService _crashHandler; - // TODO because of inlining. - public ApricotListenerSoundPlay(HookManager hooks, GameState state, CollectionResolver collectionResolver, CrashHandlerService crashHandler) + public ApricotListenerSoundPlayCaller(HookManager hooks, GameState state, CollectionResolver collectionResolver, + CrashHandlerService crashHandler) { _state = state; _collectionResolver = collectionResolver; _crashHandler = crashHandler; - Task = hooks.CreateHook("Apricot Listener Sound Play", Sigs.ApricotListenerSoundPlay, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Apricot Listener Sound Play Caller", Sigs.ApricotListenerSoundPlayCaller, Detour, + true); //HookSettings.VfxIdentificationHooks); } - public delegate nint Delegate(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6); + public delegate nint Delegate(nint a1, nint a2, float a3); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private nint Detour(nint a1, nint a2, nint a3, nint a4, nint a5, nint a6) + private nint Detour(nint a1, nint unused, float timeOffset) { - Penumbra.Log.Excessive($"[Apricot Listener Sound Play] Invoked on 0x{a1:X} with {a2}, {a3}, {a4}, {a5}, {a6}."); - if (a6 == nint.Zero) - return Task.Result.Original(a1, a2, a3, a4, a5, a6); + // Short-circuiting and sanity checks done by game. + var playTime = a1 == nint.Zero ? -1 : *(float*)(a1 + 0x250); + if (playTime < 0) + return Task.Result.Original(a1, unused, timeOffset); - // a6 is some instance of Apricot.IInstanceListenner, in some cases we can obtain the associated caster via vfunc 1. - var gameObject = (*(delegate* unmanaged**)a6)[1](a6); + var someIntermediate = *(nint*)(a1 + 0x1F8); + var flags = someIntermediate == nint.Zero ? (ushort)0 : *(ushort*)(someIntermediate + 0x49C); + if (((flags >> 13) & 1) == 0) + return Task.Result.Original(a1, unused, timeOffset); + + Penumbra.Log.Information( + $"[Apricot Listener Sound Play Caller] Invoked on 0x{a1:X} with {unused}, {timeOffset}."); + // Fetch the IInstanceListenner (sixth argument to inlined call of SoundPlay) + var apricotIInstanceListenner = *(nint*)(someIntermediate + 0x270); + if (apricotIInstanceListenner == nint.Zero) + return Task.Result.Original(a1, unused, timeOffset); + + // In some cases we can obtain the associated caster via vfunc 1. var newData = ResolveData.Invalid; + var gameObject = (*(delegate* unmanaged**)apricotIInstanceListenner)[1](apricotIInstanceListenner); if (gameObject != null) { newData = _collectionResolver.IdentifyCollection(gameObject, true); @@ -47,14 +61,14 @@ public sealed unsafe class ApricotListenerSoundPlay : FastHook Date: Sun, 21 Jul 2024 00:21:27 +0200 Subject: [PATCH 0770/1381] Fix field. --- .../UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index 15bd7cc9..25c0e448 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -75,7 +75,7 @@ public partial class ModEditWindow ImGui.TableHeader("Dye Preview"); } - for (var i = 0; i < ColorTable.NumUsedRows; ++i) + for (var i = 0; i < ColorTable.NumRows; ++i) { ret |= DrawColorTableRow(tab, i, disabled); ImGui.TableNextRow(); From 5b1c0cf0e3206fff550060f97375aeb8efae7aee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 00:21:41 +0200 Subject: [PATCH 0771/1381] Fix direction of furniture redrawing. --- Penumbra/Interop/Services/RedrawService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index f288a35e..2cdc1137 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -424,8 +424,8 @@ public sealed unsafe partial class RedrawService : IDisposable if (housingManager == null) return; - var currentTerritory = (OutdoorTerritory*)housingManager->CurrentTerritory; - if (currentTerritory == null || currentTerritory->GetTerritoryType() is not HousingTerritoryType.Outdoor) + var currentTerritory = (IndoorTerritory*)housingManager->CurrentTerritory; + if (currentTerritory == null || currentTerritory->GetTerritoryType() is not HousingTerritoryType.Indoor) return; From c3b7ddad2810e4687aec33b4da7f721de3b4625f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 00:48:48 +0200 Subject: [PATCH 0772/1381] Create newly added mods in import folder instead of moving them. --- OtterGui | 2 +- Penumbra/Mods/Manager/ModFileSystem.cs | 21 +++++++++++-- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 31 -------------------- 3 files changed, 20 insertions(+), 34 deletions(-) diff --git a/OtterGui b/OtterGui index 89b3b951..dc17161b 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 89b3b9513f9b4989045517a452ef971e24377203 +Subproject commit dc17161b1d9c47ffd6bcc17e91f4832cf7762993 diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index e32fec0c..693db944 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -1,3 +1,5 @@ +using Dalamud.Interface.ImGuiNotification; +using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.Communication; @@ -10,13 +12,15 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer private readonly ModManager _modManager; private readonly CommunicatorService _communicator; private readonly SaveService _saveService; + private readonly Configuration _config; // Create a new ModFileSystem from the currently loaded mods and the current sort order file. - public ModFileSystem(ModManager modManager, CommunicatorService communicator, SaveService saveService) + public ModFileSystem(ModManager modManager, CommunicatorService communicator, SaveService saveService, Configuration config) { _modManager = modManager; _communicator = communicator; _saveService = saveService; + _config = config; Reload(); Changed += OnChange; _communicator.ModDiscoveryFinished.Subscribe(Reload, ModDiscoveryFinished.Priority.ModFileSystem); @@ -91,7 +95,20 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer switch (type) { case ModPathChangeType.Added: - CreateDuplicateLeaf(Root, mod.Name.Text, mod); + var parent = Root; + if (_config.DefaultImportFolder.Length != 0) + try + { + parent = FindOrCreateAllFolders(_config.DefaultImportFolder); + } + catch (Exception e) + { + Penumbra.Messager.NotificationMessage(e, + $"Could not move newly imported mod {mod.Name} to default import folder {_config.DefaultImportFolder}.", + NotificationType.Warning); + } + + CreateDuplicateLeaf(parent, mod.Name.Text, mod); break; case ModPathChangeType.Deleted: if (FindLeaf(mod, out var leaf)) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 88d6afa2..55405313 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -196,10 +196,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf leaf, in ModState state, bool selected) @@ -379,34 +376,6 @@ public sealed class ModFileSystemSelector : FileSystemSelector - /// If a default import folder is setup, try to move the given mod in there. - /// If the folder does not exist, create it if possible. - /// - /// - private void MoveModToDefaultDirectory(Mod mod) - { - if (_config.DefaultImportFolder.Length == 0) - return; - - try - { - var leaf = FileSystem.Root.GetChildren(ISortMode.Lexicographical) - .FirstOrDefault(f => f is FileSystem.Leaf l && l.Value == mod); - if (leaf == null) - throw new Exception("Mod was not found at root."); - - var folder = FileSystem.FindOrCreateAllFolders(_config.DefaultImportFolder); - FileSystem.Move(leaf, folder); - } - catch (Exception e) - { - _messager.NotificationMessage(e, - $"Could not move newly imported mod {mod.Name} to default import folder {_config.DefaultImportFolder}.", - NotificationType.Warning); - } - } - private void DrawHelpPopup() { ImGuiUtil.HelpPopup("ExtendedHelp", new Vector2(1000 * UiHelpers.Scale, 38.5f * ImGui.GetTextLineHeightWithSpacing()), () => From 48ab98bee69117f5c74c425ab19d9c65fd545041 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 20 Jul 2024 22:53:37 +0000 Subject: [PATCH 0773/1381] [CI] Updating repo.json for testing_1.2.0.12 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index d715bca2..ca13bb5b 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.11", + "TestingAssemblyVersion": "1.2.0.12", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.11/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.12/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 8c34c18643b34586346a902f6b0ffdcca6cc2907 Mon Sep 17 00:00:00 2001 From: pmgr <26606291+pmgr@users.noreply.github.com> Date: Sun, 21 Jul 2024 16:34:27 +0100 Subject: [PATCH 0774/1381] Add scuffed pap handling --- .../Hooks/ResourceLoading/MappedCodeReader.cs | 13 ++ .../Hooks/ResourceLoading/PapHandler.cs | 23 +++ .../Hooks/ResourceLoading/PapRewriter.cs | 181 ++++++++++++++++ .../Hooks/ResourceLoading/PeSigScanner.cs | 194 ++++++++++++++++++ .../Hooks/ResourceLoading/ResourceLoader.cs | 26 +++ Penumbra/Penumbra.csproj | 13 +- 6 files changed, 446 insertions(+), 4 deletions(-) create mode 100644 Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs create mode 100644 Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs create mode 100644 Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs create mode 100644 Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs diff --git a/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs b/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs new file mode 100644 index 00000000..81712cca --- /dev/null +++ b/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs @@ -0,0 +1,13 @@ +using Iced.Intel; + +namespace Penumbra.Interop.Hooks.ResourceLoading; + +public class MappedCodeReader(UnmanagedMemoryAccessor data, long offset) : CodeReader +{ + public override int ReadByte() { + if (offset >= data.Capacity) + return -1; + + return data.ReadByte(offset++); + } +} diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs new file mode 100644 index 00000000..29d77d83 --- /dev/null +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs @@ -0,0 +1,23 @@ +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks.ResourceLoading; + +public sealed class PapHandler(PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable +{ + private readonly PapRewriter _papRewriter = new(papResourceHandler); + + public void Enable() + { + _papRewriter.Rewrite(Sigs.LoadAlwaysResidentMotionPacks); + _papRewriter.Rewrite(Sigs.LoadWeaponDependentResidentMotionPacks); + _papRewriter.Rewrite(Sigs.LoadInitialResidentMotionPacks); + _papRewriter.Rewrite(Sigs.LoadMotionPacks); + _papRewriter.Rewrite(Sigs.LoadMotionPacks2); + _papRewriter.Rewrite(Sigs.LoadMigratoryMotionPack); + } + + public void Dispose() + { + _papRewriter.Dispose(); + } +} diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs new file mode 100644 index 00000000..cb437d9e --- /dev/null +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -0,0 +1,181 @@ +using Dalamud.Hooking; +using Iced.Intel; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Hooks.ResourceLoading; + +public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable +{ + public unsafe delegate int PapResourceHandlerPrototype(void* self, byte* path, int length); + + private PeSigScanner Scanner { get; } = new(); + private Dictionary Hooks { get; }= []; + private List NativeAllocList { get; } = []; + private PapResourceHandlerPrototype PapResourceHandler { get; } = papResourceHandler; + + public void Rewrite(string sig) + { + if (!Scanner.TryScanText(sig, out var addr)) + { + throw new Exception($"Sig is fucked: {sig}"); + } + + var funcInstructions = Scanner.GetFunctionInstructions(addr).ToList(); + + var hookPoints = ScanPapHookPoints(funcInstructions).ToList(); + + foreach (var hookPoint in hookPoints) + { + var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); + + var stringLoc = NativeAlloc(Utf8GamePath.MaxGamePathLength); + + { + // We'll need to grab our true hook point; the location where we can change the path at our leisure. + // This is going to be the first call instruction after our 'hookPoint', so, we'll find that. + // Pretty scuffed, this might need a refactoring at some point. + // We're doing it by skipping to our hookPoint's address in the list of instructions inside the function; then getting next CALL + var detourPoint = funcInstructions.Skip( + funcInstructions.FindIndex(instr => instr.IP == hookPoint.IP) + 1 + ).First(instr => instr.Mnemonic == Mnemonic.Call); + + // We'll also remove all the 'hookPoints' from 'stackAccesses'. + // We're handling the char *path redirection here, so we don't want this to hit the later code + foreach (var hp in hookPoints) + { + stackAccesses.RemoveAll(instr => instr.IP == hp.IP); + } + + var pDetour = Marshal.GetFunctionPointerForDelegate(PapResourceHandler); + var targetRegister = hookPoint.Op0Register.ToString().ToLower(); + var hookAddr = new IntPtr((long)detourPoint.IP); + + var caveLoc = NativeAlloc(16); + var hook = new AsmHook( + hookAddr, + [ + "use64", + $"mov {targetRegister}, 0x{stringLoc:x8}", // Move our char *path into the relevant register (rdx) + + // After this asm stub, we have a call to Crc32(); since r9 is a volatile, unused register, we can use it ourselves + // We're essentially storing the original 2 arguments ('this', 'path'), in case they get mangled in our call + // We technically don't need to save rdx ('path'), since it'll be stringLoc, but eh + $"mov r9, 0x{caveLoc:x8}", + "mov [r9], rcx", + "mov [r9+0x8], rdx", + + // We can use 'rax' here too since it's also volatile, and it'll be overwritten by Crc32()'s return anyway + $"mov rax, 0x{pDetour:x8}", // Get a pointer to our detour in place + "call rax", // Call detour + + // Do the reverse process and retrieve the stored stuff + $"mov r9, 0x{caveLoc:x8}", + "mov rcx, [r9]", + "mov rdx, [r9+0x8]", + + // Plop 'rax' (our return value, the path size) into r8, so it's the third argument for the subsequent Crc32() call + "mov r8, rax", + ], "Pap Redirection" + ); + + Hooks.Add(hookAddr, hook); + hook.Enable(); + } + + // Now we're adjusting every single reference to the stack allocated 'path' to our substantially bigger 'stringLoc' + foreach (var stackAccess in stackAccesses) + { + var hookAddr = new IntPtr((long)stackAccess.IP + stackAccess.Length); + + if (Hooks.ContainsKey(hookAddr)) + { + // Hook already exists, means there's reuse of the same stack address across 2 GetResourceAsync; just skip + continue; + } + + var targetRegister = stackAccess.Op0Register.ToString().ToLower(); + var hook = new AsmHook( + hookAddr, + [ + "use64", + $"mov {targetRegister}, 0x{stringLoc:x8}", + ], "Pap Stack Accesses" + ); + + Hooks.Add(hookAddr, hook); + hook.Enable(); + } + } + + + + } + + private static IEnumerable ScanStackAccesses(IEnumerable instructions, Instruction hookPoint) + { + return instructions.Where(instr => + instr.Code == hookPoint.Code + && instr.Op0Kind == hookPoint.Op0Kind + && instr.Op1Kind == hookPoint.Op1Kind + && instr.MemoryBase == hookPoint.MemoryBase + && instr.MemoryDisplacement64 == hookPoint.MemoryDisplacement64) + .GroupBy(instr => instr.IP) + .Select(grp => grp.First()); + } + + // This is utterly fucked and hardcoded, but, again, it works + // Might be a neat idea for a more versatile kind of signature though + private static IEnumerable ScanPapHookPoints(List funcInstructions) + { + for (var i = 0; i < funcInstructions.Count - 8; i++) + { + if (funcInstructions[i .. (i + 8)] is + [ + {Code : Code.Lea_r64_m}, + {Code : Code.Lea_r64_m}, + {Mnemonic: Mnemonic.Call}, + {Code : Code.Lea_r64_m}, + {Mnemonic: Mnemonic.Call}, + {Code : Code.Lea_r64_m}, + .., + ] + ) + { + yield return funcInstructions[i]; + } + } + } + + private unsafe IntPtr NativeAlloc(nuint size) + { + var caveLoc = new IntPtr(NativeMemory.Alloc(size)); + NativeAllocList.Add(caveLoc); + + return caveLoc; + } + + private static unsafe void NativeFree(IntPtr mem) + { + NativeMemory.Free(mem.ToPointer()); + } + + public void Dispose() + { + Scanner.Dispose(); + + foreach (var hook in Hooks.Values) + { + hook.Disable(); + hook.Dispose(); + } + + Hooks.Clear(); + + foreach (var mem in NativeAllocList) + { + NativeFree(mem); + } + + NativeAllocList.Clear(); + } +} diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs new file mode 100644 index 00000000..231e04f3 --- /dev/null +++ b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs @@ -0,0 +1,194 @@ +using System.IO.MemoryMappedFiles; +using Iced.Intel; +using PeNet; +using Decoder = Iced.Intel.Decoder; + +namespace Penumbra.Interop.Hooks.ResourceLoading; + +// A good chunk of this was blatantly stolen from Dalamud's SigScanner 'cause I could not be faffed, maybe I'll rewrite it later +public class PeSigScanner : IDisposable +{ + private MemoryMappedFile File { get; } + + private uint TextSectionStart { get; } + private uint TextSectionSize { get; } + + private IntPtr ModuleBaseAddress { get; } + private uint TextSectionVirtualAddress { get; } + + private MemoryMappedViewAccessor TextSection { get; } + + + public PeSigScanner() + { + var mainModule = Process.GetCurrentProcess().MainModule!; + var fileName = mainModule.FileName; + ModuleBaseAddress = mainModule.BaseAddress; + + if (fileName == null) + { + throw new Exception("Can't get main module path, the fuck is going on?"); + } + + File = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); + + using var fileStream = File.CreateViewStream(0, 0, MemoryMappedFileAccess.Read); + var pe = new PeFile(fileStream); + + var textSection = pe.ImageSectionHeaders!.First(header => header.Name == ".text"); + + TextSectionStart = textSection.PointerToRawData; + TextSectionSize = textSection.SizeOfRawData; + TextSectionVirtualAddress = textSection.VirtualAddress; + + TextSection = File.CreateViewAccessor(TextSectionStart, TextSectionSize, MemoryMappedFileAccess.Read); + } + + + private IntPtr ScanText(string signature) + { + var scanRet = Scan(TextSection, signature); + + var instrByte = Marshal.ReadByte(scanRet); + + if (instrByte is 0xE8 or 0xE9) + scanRet = ReadJmpCallSig(scanRet); + + return scanRet; + } + + private static IntPtr ReadJmpCallSig(IntPtr sigLocation) + { + var jumpOffset = Marshal.ReadInt32(sigLocation, 1); + return IntPtr.Add(sigLocation, 5 + jumpOffset); + } + + public bool TryScanText(string signature, out IntPtr result) + { + try + { + result = ScanText(signature); + return true; + } + catch (KeyNotFoundException) + { + result = IntPtr.Zero; + return false; + } + } + + private IntPtr Scan(MemoryMappedViewAccessor section, string signature) + { + var (needle, mask) = ParseSignature(signature); + + var index = IndexOf(section, needle, mask); + if (index < 0) + throw new KeyNotFoundException($"Can't find a signature of {signature}"); + return new IntPtr(ModuleBaseAddress + index - section.PointerOffset + TextSectionVirtualAddress); + } + + private static (byte[] Needle, bool[] Mask) ParseSignature(string signature) + { + signature = signature.Replace(" ", string.Empty); + if (signature.Length % 2 != 0) + throw new ArgumentException("Signature without whitespaces must be divisible by two.", nameof(signature)); + + var needleLength = signature.Length / 2; + var needle = new byte[needleLength]; + var mask = new bool[needleLength]; + for (var i = 0; i < needleLength; i++) + { + var hexString = signature.Substring(i * 2, 2); + if (hexString == "??" || hexString == "**") + { + needle[i] = 0; + mask[i] = true; + continue; + } + + needle[i] = byte.Parse(hexString, NumberStyles.AllowHexSpecifier); + mask[i] = false; + } + + return (needle, mask); + } + + private static unsafe int IndexOf(MemoryMappedViewAccessor section, byte[] needle, bool[] mask) + { + if (needle.Length > section.Capacity) return -1; + var badShift = BuildBadCharTable(needle, mask); + var last = needle.Length - 1; + var offset = 0; + var maxOffset = section.Capacity - needle.Length; + + byte* buffer = null; + section.SafeMemoryMappedViewHandle.AcquirePointer(ref buffer); + try + { + while (offset <= maxOffset) + { + int position; + for (position = last; needle[position] == *(buffer + position + offset) || mask[position]; position--) + { + if (position == 0) + return offset; + } + + offset += badShift[*(buffer + offset + last)]; + } + } + finally + { + section.SafeMemoryMappedViewHandle.ReleasePointer(); + } + + return -1; + } + + + private static int[] BuildBadCharTable(byte[] needle, bool[] mask) + { + int idx; + var last = needle.Length - 1; + var badShift = new int[256]; + for (idx = last; idx > 0 && !mask[idx]; --idx) + { + } + + var diff = last - idx; + if (diff == 0) diff = 1; + + for (idx = 0; idx <= 255; ++idx) + badShift[idx] = diff; + for (idx = last - diff; idx < last; ++idx) + badShift[needle[idx]] = last - idx; + return badShift; + } + + // Detects function termination; this is done in a really stupid way that will possibly break if looked at wrong, but it'll work for now + // If this shits itself, go bother Winter to implement proper CFG + basic block detection + public IEnumerable GetFunctionInstructions(IntPtr addr) + { + var fileOffset = addr - TextSectionVirtualAddress - ModuleBaseAddress; + + var codeReader = new MappedCodeReader(TextSection, fileOffset); + var decoder = Decoder.Create(64, codeReader, (ulong)addr.ToInt64()); + + do + { + decoder.Decode(out var instr); + + // Yes, this is catastrophically bad, but it works for some cases okay + if (instr.Mnemonic == Mnemonic.Int3) + break; + + yield return instr; + } while (true); + } + + public void Dispose() + { + TextSection.Dispose(); + File.Dispose(); + } +} diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 195a8b9e..bc28c200 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -16,6 +16,8 @@ public unsafe class ResourceLoader : IDisposable, IService private readonly ResourceService _resources; private readonly FileReadService _fileReadService; private readonly TexMdlService _texMdlService; + + private readonly PapHandler _papHandler; private ResolveData _resolvedData = ResolveData.Invalid; @@ -30,6 +32,29 @@ public unsafe class ResourceLoader : IDisposable, IService _resources.ResourceHandleIncRef += IncRefProtection; _resources.ResourceHandleDecRef += DecRefProtection; _fileReadService.ReadSqPack += ReadSqPackDetour; + + _papHandler = new PapHandler(PapResourceHandler); + _papHandler.Enable(); + } + + private int PapResourceHandler(void* self, byte* path, int length) + { + Utf8GamePath.FromPointer(path, out var gamePath); + + var (resolvedPath, _) = _incMode.Value + ? (null, ResolveData.Invalid) + : _resolvedData.Valid + ? (_resolvedData.ModCollection.ResolvePath(gamePath), _resolvedData) + : ResolvePath(gamePath, ResourceCategory.Chara, ResourceType.Pap); + + if (!resolvedPath.HasValue || !Utf8GamePath.FromString(resolvedPath.Value.FullName, out var utf8ResolvedPath)) + { + return length; + } + + NativeMemory.Copy(utf8ResolvedPath.Path.Path, path, (nuint)utf8ResolvedPath.Length); + path[utf8ResolvedPath.Length] = 0; + return utf8ResolvedPath.Length; } /// Load a resource for a given path and a specific collection. @@ -84,6 +109,7 @@ public unsafe class ResourceLoader : IDisposable, IService _resources.ResourceHandleIncRef -= IncRefProtection; _resources.ResourceHandleDecRef -= DecRefProtection; _fileReadService.ReadSqPack -= ReadSqPackDetour; + _papHandler.Dispose(); } private void ResourceHandler(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 2e53bd22..70208737 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -23,10 +23,10 @@ PROFILING; - - - - + + + + @@ -68,6 +68,10 @@ $(DalamudLibPath)Newtonsoft.Json.dll False + + $(DalamudLibPath)Iced.dll + False + lib\OtterTex.dll @@ -79,6 +83,7 @@ + From 8351b74b21c5dfaca5691bc7e2956715573e7fa5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 22:23:31 +0200 Subject: [PATCH 0775/1381] Update GameData and packages. --- Penumbra.GameData | 2 +- Penumbra/packages.lock.json | 30 +++++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 9f1816f1..f13818fd 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 9f1816f1b75003d01c5576769831c10f3d8948a7 +Subproject commit f13818fd85b436d0a0f66293fe7c6b60d4bffe3c diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index b431e595..42539e78 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -11,6 +11,16 @@ "Unosquare.Swan.Lite": "3.0.0" } }, + "PeNet": { + "type": "Direct", + "requested": "[4.0.5, )", + "resolved": "4.0.5", + "contentHash": "/OUfRnMG8STVuK8kTpdfm+WQGTDoUiJnI845kFw4QrDmv2gYourmSnH84pqVjHT1YHBSuRfCzfioIpHGjFJrGA==", + "dependencies": { + "PeNet.Asn1": "2.0.1", + "System.Security.Cryptography.Pkcs": "8.0.0" + } + }, "SharpCompress": { "type": "Direct", "requested": "[0.33.0, )", @@ -56,6 +66,11 @@ "resolved": "8.0.0", "contentHash": "cjWrLkJXK0rs4zofsK4bSdg+jhDLTaxrkXu4gS6Y7MAlCvRyNNgwY/lJi5RDlQOnSZweHqoyvgvbdvQsRIW+hg==" }, + "PeNet.Asn1": { + "type": "Transitive", + "resolved": "2.0.1", + "contentHash": "YR2O2YokSAYB+7CXkCDN3bd6/p0K3/AicCPkOJHKUz500v1D/hulCuVlggguqNc3M0LgSfOZKGvVYg2ud1GA9A==" + }, "SharpGLTF.Runtime": { "type": "Transitive", "resolved": "1.0.0-alpha0030", @@ -64,6 +79,19 @@ "SharpGLTF.Core": "1.0.0-alpha0030" } }, + "System.Formats.Asn1": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "AJukBuLoe3QeAF+mfaRKQb2dgyrvt340iMBHYv+VdBzCUM06IxGlvl0o/uPOS7lHnXPN6u8fFRHSHudx5aTi8w==" + }, + "System.Security.Cryptography.Pkcs": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "ULmp3xoOwNYjOYp4JZ2NK/6NdTgiN1GQXzVVN1njQ7LOZ0d0B9vyMnhyqbIi9Qw4JXj1JgCsitkTShboHRx7Eg==", + "dependencies": { + "System.Formats.Asn1": "8.0.0" + } + }, "System.ValueTuple": { "type": "Transitive", "resolved": "4.5.0", @@ -94,7 +122,7 @@ "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[5.0.0, )", + "Penumbra.Api": "[5.2.0, )", "Penumbra.String": "[1.0.4, )" } }, From 0db70c89b105ec8b76a0c3a6764ab4c566e016f7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 22:58:03 +0200 Subject: [PATCH 0776/1381] Some cleanup of PeSigScanner. --- .../Hooks/ResourceLoading/PapHandler.cs | 4 +- .../Hooks/ResourceLoading/PeSigScanner.cs | 118 +++++++++--------- 2 files changed, 57 insertions(+), 65 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs index 29d77d83..f0fd8b0e 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs @@ -17,7 +17,5 @@ public sealed class PapHandler(PapRewriter.PapResourceHandlerPrototype papResour } public void Dispose() - { - _papRewriter.Dispose(); - } + => _papRewriter.Dispose(); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs index 231e04f3..f5dd2d45 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs @@ -5,65 +5,56 @@ using Decoder = Iced.Intel.Decoder; namespace Penumbra.Interop.Hooks.ResourceLoading; -// A good chunk of this was blatantly stolen from Dalamud's SigScanner 'cause I could not be faffed, maybe I'll rewrite it later -public class PeSigScanner : IDisposable +// A good chunk of this was blatantly stolen from Dalamud's SigScanner 'cause Winter could not be faffed, Winter will definitely not rewrite it later +public unsafe class PeSigScanner : IDisposable { - private MemoryMappedFile File { get; } + private readonly MemoryMappedFile _file; + private readonly MemoryMappedViewAccessor _textSection; + + private readonly nint _moduleBaseAddress; + private readonly uint _textSectionVirtualAddress; + - private uint TextSectionStart { get; } - private uint TextSectionSize { get; } - - private IntPtr ModuleBaseAddress { get; } - private uint TextSectionVirtualAddress { get; } - - private MemoryMappedViewAccessor TextSection { get; } - - public PeSigScanner() { var mainModule = Process.GetCurrentProcess().MainModule!; - var fileName = mainModule.FileName; - ModuleBaseAddress = mainModule.BaseAddress; + var fileName = mainModule.FileName; + _moduleBaseAddress = mainModule.BaseAddress; if (fileName == null) - { - throw new Exception("Can't get main module path, the fuck is going on?"); - } - - File = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); + throw new Exception("Unable to obtain main module path. This should not happen."); - using var fileStream = File.CreateViewStream(0, 0, MemoryMappedFileAccess.Read); + _file = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, null, 0, MemoryMappedFileAccess.Read); + + using var fileStream = _file.CreateViewStream(0, 0, MemoryMappedFileAccess.Read); var pe = new PeFile(fileStream); var textSection = pe.ImageSectionHeaders!.First(header => header.Name == ".text"); - TextSectionStart = textSection.PointerToRawData; - TextSectionSize = textSection.SizeOfRawData; - TextSectionVirtualAddress = textSection.VirtualAddress; + var textSectionStart = textSection.PointerToRawData; + var textSectionSize = textSection.SizeOfRawData; + _textSectionVirtualAddress = textSection.VirtualAddress; - TextSection = File.CreateViewAccessor(TextSectionStart, TextSectionSize, MemoryMappedFileAccess.Read); + _textSection = _file.CreateViewAccessor(textSectionStart, textSectionSize, MemoryMappedFileAccess.Read); } - private IntPtr ScanText(string signature) + private nint ScanText(string signature) { - var scanRet = Scan(TextSection, signature); - - var instrByte = Marshal.ReadByte(scanRet); - - if (instrByte is 0xE8 or 0xE9) + var scanRet = Scan(_textSection, signature); + if (*(byte*)scanRet is 0xE8 or 0xE9) scanRet = ReadJmpCallSig(scanRet); return scanRet; } - - private static IntPtr ReadJmpCallSig(IntPtr sigLocation) + + private static nint ReadJmpCallSig(nint sigLocation) { - var jumpOffset = Marshal.ReadInt32(sigLocation, 1); - return IntPtr.Add(sigLocation, 5 + jumpOffset); + var jumpOffset = *(int*)(sigLocation + 1); + return sigLocation + 5 + jumpOffset; } - - public bool TryScanText(string signature, out IntPtr result) + + public bool TryScanText(string signature, out nint result) { try { @@ -72,21 +63,22 @@ public class PeSigScanner : IDisposable } catch (KeyNotFoundException) { - result = IntPtr.Zero; + result = nint.Zero; return false; } } - - private IntPtr Scan(MemoryMappedViewAccessor section, string signature) + + private nint Scan(MemoryMappedViewAccessor section, string signature) { var (needle, mask) = ParseSignature(signature); - - var index = IndexOf(section, needle, mask); + + var index = IndexOf(section, needle, mask); if (index < 0) throw new KeyNotFoundException($"Can't find a signature of {signature}"); - return new IntPtr(ModuleBaseAddress + index - section.PointerOffset + TextSectionVirtualAddress); + + return (nint)(_moduleBaseAddress + index - section.PointerOffset + _textSectionVirtualAddress); } - + private static (byte[] Needle, bool[] Mask) ParseSignature(string signature) { signature = signature.Replace(" ", string.Empty); @@ -99,7 +91,7 @@ public class PeSigScanner : IDisposable for (var i = 0; i < needleLength; i++) { var hexString = signature.Substring(i * 2, 2); - if (hexString == "??" || hexString == "**") + if (hexString is "??" or "**") { needle[i] = 0; mask[i] = true; @@ -112,10 +104,12 @@ public class PeSigScanner : IDisposable return (needle, mask); } - - private static unsafe int IndexOf(MemoryMappedViewAccessor section, byte[] needle, bool[] mask) + + private static int IndexOf(MemoryMappedViewAccessor section, byte[] needle, bool[] mask) { - if (needle.Length > section.Capacity) return -1; + if (needle.Length > section.Capacity) + return -1; + var badShift = BuildBadCharTable(needle, mask); var last = needle.Length - 1; var offset = 0; @@ -144,19 +138,19 @@ public class PeSigScanner : IDisposable return -1; } - - + + private static int[] BuildBadCharTable(byte[] needle, bool[] mask) { int idx; var last = needle.Length - 1; var badShift = new int[256]; for (idx = last; idx > 0 && !mask[idx]; --idx) - { - } + { } - var diff = last - idx; - if (diff == 0) diff = 1; + var diff = last - idx; + if (diff == 0) + diff = 1; for (idx = 0; idx <= 255; ++idx) badShift[idx] = diff; @@ -164,16 +158,16 @@ public class PeSigScanner : IDisposable badShift[needle[idx]] = last - idx; return badShift; } - + // Detects function termination; this is done in a really stupid way that will possibly break if looked at wrong, but it'll work for now // If this shits itself, go bother Winter to implement proper CFG + basic block detection - public IEnumerable GetFunctionInstructions(IntPtr addr) + public IEnumerable GetFunctionInstructions(nint address) { - var fileOffset = addr - TextSectionVirtualAddress - ModuleBaseAddress; - - var codeReader = new MappedCodeReader(TextSection, fileOffset); - var decoder = Decoder.Create(64, codeReader, (ulong)addr.ToInt64()); - + var fileOffset = address - _textSectionVirtualAddress - _moduleBaseAddress; + + var codeReader = new MappedCodeReader(_textSection, fileOffset); + var decoder = Decoder.Create(64, codeReader, (ulong)address.ToInt64()); + do { decoder.Decode(out var instr); @@ -188,7 +182,7 @@ public class PeSigScanner : IDisposable public void Dispose() { - TextSection.Dispose(); - File.Dispose(); + _textSection.Dispose(); + _file.Dispose(); } } From ee5a21f7a20dc459b1ec0d903c008f616fbcde3c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 22:58:24 +0200 Subject: [PATCH 0777/1381] Add pap requested event, some cleanup. --- .../Hooks/ResourceLoading/ResourceLoader.cs | 22 +++++---- .../UI/ResourceWatcher/ResourceWatcher.cs | 47 ++++++++++++------- 2 files changed, 44 insertions(+), 25 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index bc28c200..cf87aa2b 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -16,10 +16,10 @@ public unsafe class ResourceLoader : IDisposable, IService private readonly ResourceService _resources; private readonly FileReadService _fileReadService; private readonly TexMdlService _texMdlService; - - private readonly PapHandler _papHandler; + private readonly PapHandler _papHandler; - private ResolveData _resolvedData = ResolveData.Invalid; + private ResolveData _resolvedData = ResolveData.Invalid; + public event Action? PapRequested; public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService) { @@ -36,24 +36,28 @@ public unsafe class ResourceLoader : IDisposable, IService _papHandler = new PapHandler(PapResourceHandler); _papHandler.Enable(); } - + private int PapResourceHandler(void* self, byte* path, int length) { - Utf8GamePath.FromPointer(path, out var gamePath); - + if (!Utf8GamePath.FromPointer(path, out var gamePath)) + return length; + var (resolvedPath, _) = _incMode.Value ? (null, ResolveData.Invalid) : _resolvedData.Valid ? (_resolvedData.ModCollection.ResolvePath(gamePath), _resolvedData) : ResolvePath(gamePath, ResourceCategory.Chara, ResourceType.Pap); - - if (!resolvedPath.HasValue || !Utf8GamePath.FromString(resolvedPath.Value.FullName, out var utf8ResolvedPath)) + + + if (!resolvedPath.HasValue || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var utf8ResolvedPath)) { + PapRequested?.Invoke(gamePath, gamePath, _resolvedData); return length; } - + NativeMemory.Copy(utf8ResolvedPath.Path.Path, path, (nuint)utf8ResolvedPath.Length); path[utf8ResolvedPath.Length] = 0; + PapRequested?.Invoke(gamePath, utf8ResolvedPath, _resolvedData); return utf8ResolvedPath.Length; } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 935f11e3..a00b33c7 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -36,31 +36,47 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService private Regex? _logRegex; private int _newMaxEntries; - public unsafe ResourceWatcher(ActorManager actors, Configuration config, ResourceService resources, ResourceLoader loader, ResourceHandleDestructor destructor) + public unsafe ResourceWatcher(ActorManager actors, Configuration config, ResourceService resources, ResourceLoader loader, + ResourceHandleDestructor destructor) { - _actors = actors; - _config = config; - _ephemeral = config.Ephemeral; - _resources = resources; - _destructor = destructor; - _loader = loader; - _table = new ResourceWatcherTable(config.Ephemeral, _records); - _resources.ResourceRequested += OnResourceRequested; + _actors = actors; + _config = config; + _ephemeral = config.Ephemeral; + _resources = resources; + _destructor = destructor; + _loader = loader; + _table = new ResourceWatcherTable(config.Ephemeral, _records); + _resources.ResourceRequested += OnResourceRequested; _destructor.Subscribe(OnResourceDestroyed, ResourceHandleDestructor.Priority.ResourceWatcher); - _loader.ResourceLoaded += OnResourceLoaded; - _loader.FileLoaded += OnFileLoaded; + _loader.ResourceLoaded += OnResourceLoaded; + _loader.FileLoaded += OnFileLoaded; + _loader.PapRequested += OnPapRequested; UpdateFilter(_ephemeral.ResourceLoggingFilter, false); _newMaxEntries = _config.MaxResourceWatcherRecords; } + private void OnPapRequested(Utf8GamePath original) + { + if (_ephemeral.EnableResourceLogging && FilterMatch(original.Path, out var match)) + Penumbra.Log.Information($"[ResourceLoader] [REQ] {match} was requested asynchronously."); + + if (!_ephemeral.EnableResourceWatcher) + return; + + var record = Record.CreateRequest(original.Path, false); + if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) + _newRecords.Enqueue(record); + } + public unsafe void Dispose() { Clear(); _records.TrimExcess(); - _resources.ResourceRequested -= OnResourceRequested; + _resources.ResourceRequested -= OnResourceRequested; _destructor.Unsubscribe(OnResourceDestroyed); - _loader.ResourceLoaded -= OnResourceLoaded; - _loader.FileLoaded -= OnFileLoaded; + _loader.ResourceLoaded -= OnResourceLoaded; + _loader.FileLoaded -= OnFileLoaded; + _loader.PapRequested -= OnPapRequested; } private void Clear() @@ -200,8 +216,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService private unsafe void OnResourceRequested(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, - Utf8GamePath original, - GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue) + Utf8GamePath original, GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue) { if (_ephemeral.EnableResourceLogging && FilterMatch(original.Path, out var match)) Penumbra.Log.Information($"[ResourceLoader] [REQ] {match} was requested {(sync ? "synchronously." : "asynchronously.")}"); From ceaa9ca29a05125fd08cd76e664145cac37c7343 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 23:26:09 +0200 Subject: [PATCH 0778/1381] Some further cleanup. --- .../Hooks/ResourceLoading/PapHandler.cs | 25 +- .../Hooks/ResourceLoading/PapRewriter.cs | 230 ++++++++---------- .../Hooks/ResourceLoading/ResourceLoader.cs | 4 +- 3 files changed, 127 insertions(+), 132 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs index f0fd8b0e..65add13c 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs @@ -5,17 +5,26 @@ namespace Penumbra.Interop.Hooks.ResourceLoading; public sealed class PapHandler(PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable { private readonly PapRewriter _papRewriter = new(papResourceHandler); - + public void Enable() { - _papRewriter.Rewrite(Sigs.LoadAlwaysResidentMotionPacks); - _papRewriter.Rewrite(Sigs.LoadWeaponDependentResidentMotionPacks); - _papRewriter.Rewrite(Sigs.LoadInitialResidentMotionPacks); - _papRewriter.Rewrite(Sigs.LoadMotionPacks); - _papRewriter.Rewrite(Sigs.LoadMotionPacks2); - _papRewriter.Rewrite(Sigs.LoadMigratoryMotionPack); + ReadOnlySpan signatures = + [ + Sigs.LoadAlwaysResidentMotionPacks, + Sigs.LoadWeaponDependentResidentMotionPacks, + Sigs.LoadInitialResidentMotionPacks, + Sigs.LoadMotionPacks, + Sigs.LoadMotionPacks2, + Sigs.LoadMigratoryMotionPack, + ]; + + var stopwatch = Stopwatch.StartNew(); + foreach (var sig in signatures) + _papRewriter.Rewrite(sig); + Penumbra.Log.Debug( + $"[PapHandler] Rewrote {signatures.Length} .pap functions for inlined GetResourceAsync in {stopwatch.ElapsedMilliseconds} ms."); } - + public void Dispose() => _papRewriter.Dispose(); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index cb437d9e..af16d706 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -1,5 +1,6 @@ using Dalamud.Hooking; using Iced.Intel; +using OtterGui; using Penumbra.String.Classes; namespace Penumbra.Interop.Hooks.ResourceLoading; @@ -7,175 +8,160 @@ namespace Penumbra.Interop.Hooks.ResourceLoading; public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable { public unsafe delegate int PapResourceHandlerPrototype(void* self, byte* path, int length); - - private PeSigScanner Scanner { get; } = new(); - private Dictionary Hooks { get; }= []; - private List NativeAllocList { get; } = []; - private PapResourceHandlerPrototype PapResourceHandler { get; } = papResourceHandler; + + private readonly PeSigScanner _scanner = new(); + private readonly Dictionary _hooks = []; + private readonly List _nativeAllocList = []; public void Rewrite(string sig) { - if (!Scanner.TryScanText(sig, out var addr)) - { - throw new Exception($"Sig is fucked: {sig}"); - } + if (!_scanner.TryScanText(sig, out var address)) + throw new Exception($"Signature [{sig}] could not be found."); - var funcInstructions = Scanner.GetFunctionInstructions(addr).ToList(); - - var hookPoints = ScanPapHookPoints(funcInstructions).ToList(); + var funcInstructions = _scanner.GetFunctionInstructions(address).ToArray(); + var hookPoints = ScanPapHookPoints(funcInstructions).ToList(); foreach (var hookPoint in hookPoints) { - var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); + var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); + var stringAllocation = NativeAlloc(Utf8GamePath.MaxGamePathLength); - var stringLoc = NativeAlloc(Utf8GamePath.MaxGamePathLength); + // We'll need to grab our true hook point; the location where we can change the path at our leisure. + // This is going to be the first call instruction after our 'hookPoint', so, we'll find that. + // Pretty scuffed, this might need a refactoring at some point. + // We're doing it by skipping to our hookPoint's address in the list of instructions inside the function; then getting next CALL + var skipIndex = funcInstructions.IndexOf(instr => instr.IP == hookPoint.IP) + 1; + var detourPoint = funcInstructions.Skip(skipIndex) + .First(instr => instr.Mnemonic == Mnemonic.Call); - { - // We'll need to grab our true hook point; the location where we can change the path at our leisure. - // This is going to be the first call instruction after our 'hookPoint', so, we'll find that. - // Pretty scuffed, this might need a refactoring at some point. - // We're doing it by skipping to our hookPoint's address in the list of instructions inside the function; then getting next CALL - var detourPoint = funcInstructions.Skip( - funcInstructions.FindIndex(instr => instr.IP == hookPoint.IP) + 1 - ).First(instr => instr.Mnemonic == Mnemonic.Call); + // We'll also remove all the 'hookPoints' from 'stackAccesses'. + // We're handling the char *path redirection here, so we don't want this to hit the later code + foreach (var hp in hookPoints) + stackAccesses.RemoveAll(instr => instr.IP == hp.IP); - // We'll also remove all the 'hookPoints' from 'stackAccesses'. - // We're handling the char *path redirection here, so we don't want this to hit the later code - foreach (var hp in hookPoints) - { - stackAccesses.RemoveAll(instr => instr.IP == hp.IP); - } + var detourPointer = Marshal.GetFunctionPointerForDelegate(papResourceHandler); + var targetRegister = hookPoint.Op0Register.ToString().ToLower(); + var hookAddress = new IntPtr((long)detourPoint.IP); - var pDetour = Marshal.GetFunctionPointerForDelegate(PapResourceHandler); - var targetRegister = hookPoint.Op0Register.ToString().ToLower(); - var hookAddr = new IntPtr((long)detourPoint.IP); + var caveAllocation = NativeAlloc(16); + var hook = new AsmHook( + hookAddress, + [ + "use64", + $"mov {targetRegister}, 0x{stringAllocation:x8}", // Move our char *path into the relevant register (rdx) - var caveLoc = NativeAlloc(16); - var hook = new AsmHook( - hookAddr, - [ - "use64", - $"mov {targetRegister}, 0x{stringLoc:x8}", // Move our char *path into the relevant register (rdx) - - // After this asm stub, we have a call to Crc32(); since r9 is a volatile, unused register, we can use it ourselves - // We're essentially storing the original 2 arguments ('this', 'path'), in case they get mangled in our call - // We technically don't need to save rdx ('path'), since it'll be stringLoc, but eh - $"mov r9, 0x{caveLoc:x8}", - "mov [r9], rcx", - "mov [r9+0x8], rdx", - - // We can use 'rax' here too since it's also volatile, and it'll be overwritten by Crc32()'s return anyway - $"mov rax, 0x{pDetour:x8}", // Get a pointer to our detour in place - "call rax", // Call detour - - // Do the reverse process and retrieve the stored stuff - $"mov r9, 0x{caveLoc:x8}", - "mov rcx, [r9]", - "mov rdx, [r9+0x8]", - - // Plop 'rax' (our return value, the path size) into r8, so it's the third argument for the subsequent Crc32() call - "mov r8, rax", - ], "Pap Redirection" - ); + // After this asm stub, we have a call to Crc32(); since r9 is a volatile, unused register, we can use it ourselves + // We're essentially storing the original 2 arguments ('this', 'path'), in case they get mangled in our call + // We technically don't need to save rdx ('path'), since it'll be stringLoc, but eh + $"mov r9, 0x{caveAllocation:x8}", + "mov [r9], rcx", + "mov [r9+0x8], rdx", - Hooks.Add(hookAddr, hook); - hook.Enable(); - } + // We can use 'rax' here too since it's also volatile, and it'll be overwritten by Crc32()'s return anyway + $"mov rax, 0x{detourPointer:x8}", // Get a pointer to our detour in place + "call rax", // Call detour + + // Do the reverse process and retrieve the stored stuff + $"mov r9, 0x{caveAllocation:x8}", + "mov rcx, [r9]", + "mov rdx, [r9+0x8]", + + // Plop 'rax' (our return value, the path size) into r8, so it's the third argument for the subsequent Crc32() call + "mov r8, rax", + ], "Pap Redirection" + ); + + _hooks.Add(hookAddress, hook); + hook.Enable(); // Now we're adjusting every single reference to the stack allocated 'path' to our substantially bigger 'stringLoc' - foreach (var stackAccess in stackAccesses) - { - var hookAddr = new IntPtr((long)stackAccess.IP + stackAccess.Length); - - if (Hooks.ContainsKey(hookAddr)) - { - // Hook already exists, means there's reuse of the same stack address across 2 GetResourceAsync; just skip - continue; - } - - var targetRegister = stackAccess.Op0Register.ToString().ToLower(); - var hook = new AsmHook( - hookAddr, - [ - "use64", - $"mov {targetRegister}, 0x{stringLoc:x8}", - ], "Pap Stack Accesses" - ); - - Hooks.Add(hookAddr, hook); - hook.Enable(); - } + UpdatePathAddresses(stackAccesses, stringAllocation); + } + } + + private void UpdatePathAddresses(IEnumerable stackAccesses, nint stringAllocation) + { + foreach (var stackAccess in stackAccesses) + { + var hookAddress = new IntPtr((long)stackAccess.IP + stackAccess.Length); + + // Hook already exists, means there's reuse of the same stack address across 2 GetResourceAsync; just skip + if (_hooks.ContainsKey(hookAddress)) + continue; + + var targetRegister = stackAccess.Op0Register.ToString().ToLower(); + var hook = new AsmHook( + hookAddress, + [ + "use64", + $"mov {targetRegister}, 0x{stringAllocation:x8}", + ], "Pap Stack Accesses" + ); + + _hooks.Add(hookAddress, hook); + hook.Enable(); } - - - } private static IEnumerable ScanStackAccesses(IEnumerable instructions, Instruction hookPoint) { return instructions.Where(instr => - instr.Code == hookPoint.Code - && instr.Op0Kind == hookPoint.Op0Kind - && instr.Op1Kind == hookPoint.Op1Kind - && instr.MemoryBase == hookPoint.MemoryBase - && instr.MemoryDisplacement64 == hookPoint.MemoryDisplacement64) - .GroupBy(instr => instr.IP) - .Select(grp => grp.First()); + instr.Code == hookPoint.Code + && instr.Op0Kind == hookPoint.Op0Kind + && instr.Op1Kind == hookPoint.Op1Kind + && instr.MemoryBase == hookPoint.MemoryBase + && instr.MemoryDisplacement64 == hookPoint.MemoryDisplacement64) + .GroupBy(instr => instr.IP) + .Select(grp => grp.First()); } // This is utterly fucked and hardcoded, but, again, it works // Might be a neat idea for a more versatile kind of signature though - private static IEnumerable ScanPapHookPoints(List funcInstructions) + private static IEnumerable ScanPapHookPoints(Instruction[] funcInstructions) { - for (var i = 0; i < funcInstructions.Count - 8; i++) + for (var i = 0; i < funcInstructions.Length - 8; i++) { - if (funcInstructions[i .. (i + 8)] is + if (funcInstructions.AsSpan(i, 8) is [ - {Code : Code.Lea_r64_m}, - {Code : Code.Lea_r64_m}, - {Mnemonic: Mnemonic.Call}, - {Code : Code.Lea_r64_m}, - {Mnemonic: Mnemonic.Call}, - {Code : Code.Lea_r64_m}, + { Code : Code.Lea_r64_m }, + { Code : Code.Lea_r64_m }, + { Mnemonic: Mnemonic.Call }, + { Code : Code.Lea_r64_m }, + { Mnemonic: Mnemonic.Call }, + { Code : Code.Lea_r64_m }, .., ] ) - { yield return funcInstructions[i]; - } } } - private unsafe IntPtr NativeAlloc(nuint size) + private unsafe nint NativeAlloc(nuint size) { - var caveLoc = new IntPtr(NativeMemory.Alloc(size)); - NativeAllocList.Add(caveLoc); + var caveLoc = (nint)NativeMemory.Alloc(size); + _nativeAllocList.Add(caveLoc); return caveLoc; } - private static unsafe void NativeFree(IntPtr mem) - { - NativeMemory.Free(mem.ToPointer()); - } + private static unsafe void NativeFree(nint mem) + => NativeMemory.Free((void*)mem); public void Dispose() { - Scanner.Dispose(); - - foreach (var hook in Hooks.Values) + _scanner.Dispose(); + + foreach (var hook in _hooks.Values) { hook.Disable(); hook.Dispose(); } - - Hooks.Clear(); - - foreach (var mem in NativeAllocList) - { - NativeFree(mem); - } - NativeAllocList.Clear(); + _hooks.Clear(); + + foreach (var mem in _nativeAllocList) + NativeFree(mem); + + _nativeAllocList.Clear(); } } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index cf87aa2b..002846fa 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -51,13 +51,13 @@ public unsafe class ResourceLoader : IDisposable, IService if (!resolvedPath.HasValue || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var utf8ResolvedPath)) { - PapRequested?.Invoke(gamePath, gamePath, _resolvedData); + PapRequested?.Invoke(gamePath); return length; } NativeMemory.Copy(utf8ResolvedPath.Path.Path, path, (nuint)utf8ResolvedPath.Length); path[utf8ResolvedPath.Length] = 0; - PapRequested?.Invoke(gamePath, utf8ResolvedPath, _resolvedData); + PapRequested?.Invoke(gamePath); return utf8ResolvedPath.Length; } From cec28a1823fcbb228136705ff98733d70ca71c9e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 21 Jul 2024 23:49:27 +0200 Subject: [PATCH 0779/1381] Provide actual hook names. --- .../Hooks/ResourceLoading/PapHandler.cs | 18 +++++++++--------- .../Hooks/ResourceLoading/PapRewriter.cs | 14 +++++++------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs index 65add13c..ea12a480 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs @@ -8,19 +8,19 @@ public sealed class PapHandler(PapRewriter.PapResourceHandlerPrototype papResour public void Enable() { - ReadOnlySpan signatures = + ReadOnlySpan<(string Sig, string Name)> signatures = [ - Sigs.LoadAlwaysResidentMotionPacks, - Sigs.LoadWeaponDependentResidentMotionPacks, - Sigs.LoadInitialResidentMotionPacks, - Sigs.LoadMotionPacks, - Sigs.LoadMotionPacks2, - Sigs.LoadMigratoryMotionPack, + (Sigs.LoadAlwaysResidentMotionPacks, nameof(Sigs.LoadAlwaysResidentMotionPacks)), + (Sigs.LoadWeaponDependentResidentMotionPacks, nameof(Sigs.LoadWeaponDependentResidentMotionPacks)), + (Sigs.LoadInitialResidentMotionPacks, nameof(Sigs.LoadInitialResidentMotionPacks)), + (Sigs.LoadMotionPacks, nameof(Sigs.LoadMotionPacks)), + (Sigs.LoadMotionPacks2, nameof(Sigs.LoadMotionPacks2)), + (Sigs.LoadMigratoryMotionPack, nameof(Sigs.LoadMigratoryMotionPack)), ]; var stopwatch = Stopwatch.StartNew(); - foreach (var sig in signatures) - _papRewriter.Rewrite(sig); + foreach (var (sig, name) in signatures) + _papRewriter.Rewrite(sig, name); Penumbra.Log.Debug( $"[PapHandler] Rewrote {signatures.Length} .pap functions for inlined GetResourceAsync in {stopwatch.ElapsedMilliseconds} ms."); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index af16d706..5a2b09bf 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -13,10 +13,10 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou private readonly Dictionary _hooks = []; private readonly List _nativeAllocList = []; - public void Rewrite(string sig) + public void Rewrite(string sig, string name) { if (!_scanner.TryScanText(sig, out var address)) - throw new Exception($"Signature [{sig}] could not be found."); + throw new Exception($"Signature for {name} [{sig}] could not be found."); var funcInstructions = _scanner.GetFunctionInstructions(address).ToArray(); var hookPoints = ScanPapHookPoints(funcInstructions).ToList(); @@ -68,20 +68,20 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou // Plop 'rax' (our return value, the path size) into r8, so it's the third argument for the subsequent Crc32() call "mov r8, rax", - ], "Pap Redirection" + ], $"{name}.PapRedirection" ); _hooks.Add(hookAddress, hook); hook.Enable(); // Now we're adjusting every single reference to the stack allocated 'path' to our substantially bigger 'stringLoc' - UpdatePathAddresses(stackAccesses, stringAllocation); + UpdatePathAddresses(stackAccesses, stringAllocation, name); } } - private void UpdatePathAddresses(IEnumerable stackAccesses, nint stringAllocation) + private void UpdatePathAddresses(IEnumerable stackAccesses, nint stringAllocation, string name) { - foreach (var stackAccess in stackAccesses) + foreach (var (stackAccess, index) in stackAccesses.WithIndex()) { var hookAddress = new IntPtr((long)stackAccess.IP + stackAccess.Length); @@ -95,7 +95,7 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou [ "use64", $"mov {targetRegister}, 0x{stringAllocation:x8}", - ], "Pap Stack Accesses" + ], $"{name}.PapStackAccess[{index}]" ); _hooks.Add(hookAddress, hook); From 1501bd4fbf5b05be2b770b0e1b8b856d71f1dce3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jul 2024 12:41:20 +0200 Subject: [PATCH 0780/1381] Fix negative matching on folders with no matches. --- Penumbra/UI/ModsTab/ModSearchStringSplitter.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs b/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs index 1ea70731..e7550eea 100644 --- a/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs +++ b/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs @@ -95,9 +95,9 @@ public sealed class ModSearchStringSplitter : SearchStringSplitter MatchesName(i, folder.Name, fullName)) - && !Negated.Any(i => MatchesName(i, folder.Name, fullName)) - && (General.Count == 0 || General.Any(i => MatchesName(i, folder.Name, fullName))); + return Forced.All(i => MatchesName(i, folder.Name, fullName, false)) + && !Negated.Any(i => MatchesName(i, folder.Name, fullName, true)) + && (General.Count == 0 || General.Any(i => MatchesName(i, folder.Name, fullName, false))); } protected override bool Matches(Entry entry, ModFileSystem.Leaf leaf) @@ -128,11 +128,11 @@ public sealed class ModSearchStringSplitter : SearchStringSplitter true, }; - private static bool MatchesName(Entry entry, ReadOnlySpan name, ReadOnlySpan fullName) + private static bool MatchesName(Entry entry, ReadOnlySpan name, ReadOnlySpan fullName, bool defaultValue) => entry.Type switch { ModSearchType.Default => fullName.Contains(entry.Needle, StringComparison.OrdinalIgnoreCase), ModSearchType.Name => name.Contains(entry.Needle, StringComparison.OrdinalIgnoreCase), - _ => false, + _ => defaultValue, }; } From 29dce8f3ab3656253a6c843edde527d2442f9199 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 22 Jul 2024 13:16:22 +0000 Subject: [PATCH 0781/1381] [CI] Updating repo.json for testing_1.2.0.13 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index ca13bb5b..b6d37a92 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.12", + "TestingAssemblyVersion": "1.2.0.13", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.12/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.13/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From ca648f98a173fa75fc538e0a1c1bc0630b64ac55 Mon Sep 17 00:00:00 2001 From: pmgr <26606291+pmgr@users.noreply.github.com> Date: Mon, 22 Jul 2024 19:37:57 +0100 Subject: [PATCH 0782/1381] Fix for pap weirdness, hopefully --- .../Hooks/ResourceLoading/PapRewriter.cs | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index 5a2b09bf..84cd0c11 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -2,6 +2,7 @@ using Dalamud.Hooking; using Iced.Intel; using OtterGui; using Penumbra.String.Classes; +using Swan; namespace Penumbra.Interop.Hooks.ResourceLoading; @@ -9,9 +10,10 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou { public unsafe delegate int PapResourceHandlerPrototype(void* self, byte* path, int length); - private readonly PeSigScanner _scanner = new(); - private readonly Dictionary _hooks = []; - private readonly List _nativeAllocList = []; + private readonly PeSigScanner _scanner = new(); + private readonly Dictionary _hooks = []; + private readonly Dictionary<(nint, Register, ulong), nint> _nativeAllocPaths = []; + private readonly List _nativeAllocCaves = []; public void Rewrite(string sig, string name) { @@ -24,7 +26,10 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou foreach (var hookPoint in hookPoints) { var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); - var stringAllocation = NativeAlloc(Utf8GamePath.MaxGamePathLength); + var stringAllocation = NativeAllocPath( + address, hookPoint.MemoryBase, hookPoint.MemoryDisplacement64, + Utf8GamePath.MaxGamePathLength + ); // We'll need to grab our true hook point; the location where we can change the path at our leisure. // This is going to be the first call instruction after our 'hookPoint', so, we'll find that. @@ -43,7 +48,7 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou var targetRegister = hookPoint.Op0Register.ToString().ToLower(); var hookAddress = new IntPtr((long)detourPoint.IP); - var caveAllocation = NativeAlloc(16); + var caveAllocation = NativeAllocCave(16); var hook = new AsmHook( hookAddress, [ @@ -136,13 +141,24 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou } } - private unsafe nint NativeAlloc(nuint size) + private unsafe nint NativeAllocCave(nuint size) { var caveLoc = (nint)NativeMemory.Alloc(size); - _nativeAllocList.Add(caveLoc); + _nativeAllocCaves.Add(caveLoc); return caveLoc; } + + // This is a bit conked but, if we identify a path by: + // 1) The function it belongs to (starting address, 'funcAddress') + // 2) The stack register (not strictly necessary - should always be rbp - but abundance of caution, so I don't hit myself in the future) + // 3) The displacement on the stack + // Then we ensure we have a unique identifier for the specific variable location of that specific function + // This is useful because sometimes the stack address is reused within the same function for different GetResourceAsync calls + private unsafe nint NativeAllocPath(nint funcAddress, Register stackRegister, ulong stackDisplacement, nuint size) + { + return _nativeAllocPaths.GetOrAdd((funcAddress, stackRegister, stackDisplacement), _ => (nint)NativeMemory.Alloc(size)); + } private static unsafe void NativeFree(nint mem) => NativeMemory.Free((void*)mem); @@ -159,9 +175,14 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou _hooks.Clear(); - foreach (var mem in _nativeAllocList) + foreach (var mem in _nativeAllocCaves) NativeFree(mem); - _nativeAllocList.Clear(); + _nativeAllocCaves.Clear(); + + foreach (var mem in _nativeAllocPaths.Values) + NativeFree(mem); + + _nativeAllocPaths.Clear(); } } From a4cd5695fb3e4908e7e51c19e2d42551acc27d19 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jul 2024 20:41:57 +0200 Subject: [PATCH 0783/1381] Fix some stuff. --- Penumbra/Api/Api/GameStateApi.cs | 23 +++++++++++++++---- .../Animation/ApricotListenerSoundPlay.cs | 2 +- .../Hooks/ResourceLoading/PapRewriter.cs | 10 +++++++- .../Hooks/ResourceLoading/ResourceLoader.cs | 18 +++++++-------- .../UI/ResourceWatcher/ResourceWatcher.cs | 3 +-- 5 files changed, 39 insertions(+), 17 deletions(-) diff --git a/Penumbra/Api/Api/GameStateApi.cs b/Penumbra/Api/Api/GameStateApi.cs index b035c886..c2cae32b 100644 --- a/Penumbra/Api/Api/GameStateApi.cs +++ b/Penumbra/Api/Api/GameStateApi.cs @@ -25,12 +25,14 @@ public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable _cutsceneService = cutsceneService; _resourceLoader = resourceLoader; _resourceLoader.ResourceLoaded += OnResourceLoaded; + _resourceLoader.PapRequested += OnPapRequested; _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); } public unsafe void Dispose() { _resourceLoader.ResourceLoaded -= OnResourceLoaded; + _resourceLoader.PapRequested -= OnPapRequested; _communicator.CreatedCharacterBase.Unsubscribe(OnCreatedCharacterBase); } @@ -67,14 +69,27 @@ public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable public PenumbraApiEc SetCutsceneParentIndex(int copyIdx, int newParentIdx) => _cutsceneService.SetParentIndex(copyIdx, newParentIdx) - ? PenumbraApiEc.Success + ? PenumbraApiEc.Success : PenumbraApiEc.InvalidArgument; private unsafe void OnResourceLoaded(ResourceHandle* handle, Utf8GamePath originalPath, FullPath? manipulatedPath, ResolveData resolveData) { - if (resolveData.AssociatedGameObject != nint.Zero) - GameObjectResourceResolved?.Invoke(resolveData.AssociatedGameObject, originalPath.ToString(), - manipulatedPath?.ToString() ?? originalPath.ToString()); + if (resolveData.AssociatedGameObject != nint.Zero && GameObjectResourceResolved != null) + { + var original = originalPath.ToString(); + GameObjectResourceResolved.Invoke(resolveData.AssociatedGameObject, original, + manipulatedPath?.ToString() ?? original); + } + } + + private void OnPapRequested(Utf8GamePath originalPath, FullPath? manipulatedPath, ResolveData resolveData) + { + if (resolveData.AssociatedGameObject != nint.Zero && GameObjectResourceResolved != null) + { + var original = originalPath.ToString(); + GameObjectResourceResolved.Invoke(resolveData.AssociatedGameObject, original, + manipulatedPath?.ToString() ?? original); + } } private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index 361fcd4e..96a51027 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -42,7 +42,7 @@ public sealed unsafe class ApricotListenerSoundPlayCaller : FastHook> 13) & 1) == 0) return Task.Result.Original(a1, unused, timeOffset); - Penumbra.Log.Information( + Penumbra.Log.Excessive( $"[Apricot Listener Sound Play Caller] Invoked on 0x{a1:X} with {unused}, {timeOffset}."); // Fetch the IInstanceListenner (sixth argument to inlined call of SoundPlay) var apricotIInstanceListenner = *(nint*)(someIntermediate + 0x270); diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index 5a2b09bf..33b124c8 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -1,3 +1,4 @@ +using System.Text.Unicode; using Dalamud.Hooking; using Iced.Intel; using OtterGui; @@ -25,7 +26,7 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou { var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); var stringAllocation = NativeAlloc(Utf8GamePath.MaxGamePathLength); - + WriteToAlloc(stringAllocation, Utf8GamePath.MaxGamePathLength, name); // We'll need to grab our true hook point; the location where we can change the path at our leisure. // This is going to be the first call instruction after our 'hookPoint', so, we'll find that. // Pretty scuffed, this might need a refactoring at some point. @@ -164,4 +165,11 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou _nativeAllocList.Clear(); } + + [Conditional("DEBUG")] + private static unsafe void WriteToAlloc(nint alloc, int size, string name) + { + var span = new Span((void*)alloc, size); + Utf8.TryWrite(span, $"Penumbra.{name}\0", out _); + } } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 002846fa..10821287 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -18,8 +18,8 @@ public unsafe class ResourceLoader : IDisposable, IService private readonly TexMdlService _texMdlService; private readonly PapHandler _papHandler; - private ResolveData _resolvedData = ResolveData.Invalid; - public event Action? PapRequested; + private ResolveData _resolvedData = ResolveData.Invalid; + public event Action? PapRequested; public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService) { @@ -42,23 +42,23 @@ public unsafe class ResourceLoader : IDisposable, IService if (!Utf8GamePath.FromPointer(path, out var gamePath)) return length; - var (resolvedPath, _) = _incMode.Value + var (resolvedPath, data) = _incMode.Value ? (null, ResolveData.Invalid) : _resolvedData.Valid ? (_resolvedData.ModCollection.ResolvePath(gamePath), _resolvedData) : ResolvePath(gamePath, ResourceCategory.Chara, ResourceType.Pap); - if (!resolvedPath.HasValue || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var utf8ResolvedPath)) + if (!resolvedPath.HasValue) { - PapRequested?.Invoke(gamePath); + PapRequested?.Invoke(gamePath, null, data); return length; } - NativeMemory.Copy(utf8ResolvedPath.Path.Path, path, (nuint)utf8ResolvedPath.Length); - path[utf8ResolvedPath.Length] = 0; - PapRequested?.Invoke(gamePath); - return utf8ResolvedPath.Length; + PapRequested?.Invoke(gamePath, resolvedPath.Value, data); + NativeMemory.Copy(resolvedPath.Value.InternalName.Path, path, (nuint)resolvedPath.Value.InternalName.Length); + path[resolvedPath.Value.InternalName.Length] = 0; + return resolvedPath.Value.InternalName.Length; } /// Load a resource for a given path and a specific collection. diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index a00b33c7..14d69489 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -11,7 +11,6 @@ using Penumbra.GameData.Enums; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.Structs; -using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -55,7 +54,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _newMaxEntries = _config.MaxResourceWatcherRecords; } - private void OnPapRequested(Utf8GamePath original) + private void OnPapRequested(Utf8GamePath original, FullPath? _1, ResolveData _2) { if (_ephemeral.EnableResourceLogging && FilterMatch(original.Path, out var match)) Penumbra.Log.Information($"[ResourceLoader] [REQ] {match} was requested asynchronously."); From df335574778cfee6fa44a5d63a2ef869c5706c11 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 22 Jul 2024 20:54:24 +0200 Subject: [PATCH 0784/1381] Cleanup. --- Penumbra.Api | 2 +- .../Hooks/ResourceLoading/PapRewriter.cs | 22 +++++++++---------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index f4c6144c..86249598 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit f4c6144ca2012b279e6d8aa52b2bef6cc2ba32d9 +Subproject commit 86249598afb71601b247f9629d9c29dbecfe6eb1 diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index afe00b8d..2fb1623d 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -11,10 +11,10 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou { public unsafe delegate int PapResourceHandlerPrototype(void* self, byte* path, int length); - private readonly PeSigScanner _scanner = new(); - private readonly Dictionary _hooks = []; - private readonly Dictionary<(nint, Register, ulong), nint> _nativeAllocPaths = []; - private readonly List _nativeAllocCaves = []; + private readonly PeSigScanner _scanner = new(); + private readonly Dictionary _hooks = []; + private readonly Dictionary<(nint, Register, ulong), nint> _nativeAllocPaths = []; + private readonly List _nativeAllocCaves = []; public void Rewrite(string sig, string name) { @@ -26,13 +26,13 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou foreach (var hookPoint in hookPoints) { - var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); + var stackAccesses = ScanStackAccesses(funcInstructions, hookPoint).ToList(); var stringAllocation = NativeAllocPath( address, hookPoint.MemoryBase, hookPoint.MemoryDisplacement64, Utf8GamePath.MaxGamePathLength - ); + ); WriteToAlloc(stringAllocation, Utf8GamePath.MaxGamePathLength, name); - + // We'll need to grab our true hook point; the location where we can change the path at our leisure. // This is going to be the first call instruction after our 'hookPoint', so, we'll find that. // Pretty scuffed, this might need a refactoring at some point. @@ -150,7 +150,7 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou return caveLoc; } - + // This is a bit conked but, if we identify a path by: // 1) The function it belongs to (starting address, 'funcAddress') // 2) The stack register (not strictly necessary - should always be rbp - but abundance of caution, so I don't hit myself in the future) @@ -158,9 +158,7 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou // Then we ensure we have a unique identifier for the specific variable location of that specific function // This is useful because sometimes the stack address is reused within the same function for different GetResourceAsync calls private unsafe nint NativeAllocPath(nint funcAddress, Register stackRegister, ulong stackDisplacement, nuint size) - { - return _nativeAllocPaths.GetOrAdd((funcAddress, stackRegister, stackDisplacement), _ => (nint)NativeMemory.Alloc(size)); - } + => _nativeAllocPaths.GetOrAdd((funcAddress, stackRegister, stackDisplacement), _ => (nint)NativeMemory.Alloc(size)); private static unsafe void NativeFree(nint mem) => NativeMemory.Free((void*)mem); @@ -181,7 +179,7 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou NativeFree(mem); _nativeAllocCaves.Clear(); - + foreach (var mem in _nativeAllocPaths.Values) NativeFree(mem); From 30f92338627b2d29558a96aa66eb6e1184443138 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 22 Jul 2024 18:56:35 +0000 Subject: [PATCH 0785/1381] [CI] Updating repo.json for testing_1.2.0.14 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index b6d37a92..f1108cfe 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.13", + "TestingAssemblyVersion": "1.2.0.14", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.13/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.14/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From c501d0b36524d163a45758901390cb840f7f1107 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 24 Jul 2024 15:11:35 +0200 Subject: [PATCH 0786/1381] Fix card actor identification. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index f13818fd..f5a74c70 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f13818fd85b436d0a0f66293fe7c6b60d4bffe3c +Subproject commit f5a74c70ad3861c5c66e1df6ae9a29fc7a0d736a From 72f2834dfd13352f70f10e77b1d40a2910198f13 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 24 Jul 2024 15:11:52 +0200 Subject: [PATCH 0787/1381] Add some resource flags. --- Penumbra/Enums/ResourceTypeFlag.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Penumbra/Enums/ResourceTypeFlag.cs b/Penumbra/Enums/ResourceTypeFlag.cs index 0cfc5469..461e7ac1 100644 --- a/Penumbra/Enums/ResourceTypeFlag.cs +++ b/Penumbra/Enums/ResourceTypeFlag.cs @@ -60,6 +60,13 @@ public enum ResourceTypeFlag : ulong Uld = 0x0002_0000_0000_0000, Waoe = 0x0004_0000_0000_0000, Wtd = 0x0008_0000_0000_0000, + Bklb = 0x0010_0000_0000_0000, + Cutb = 0x0020_0000_0000_0000, + Eanb = 0x0040_0000_0000_0000, + Eslb = 0x0080_0000_0000_0000, + Fpeb = 0x0100_0000_0000_0000, + Kdb = 0x0200_0000_0000_0000, + Kdlb = 0x0400_0000_0000_0000, } [Flags] @@ -141,6 +148,13 @@ public static class ResourceExtensions ResourceType.Uld => ResourceTypeFlag.Uld, ResourceType.Waoe => ResourceTypeFlag.Waoe, ResourceType.Wtd => ResourceTypeFlag.Wtd, + ResourceType.Bklb => ResourceTypeFlag.Bklb, + ResourceType.Cutb => ResourceTypeFlag.Cutb, + ResourceType.Eanb => ResourceTypeFlag.Eanb, + ResourceType.Eslb => ResourceTypeFlag.Eslb, + ResourceType.Fpeb => ResourceTypeFlag.Fpeb, + ResourceType.Kdb => ResourceTypeFlag.Kdb , + ResourceType.Kdlb => ResourceTypeFlag.Kdlb, _ => 0, }; @@ -148,7 +162,7 @@ public static class ResourceExtensions => (type.ToFlag() & flags) != 0; public static ResourceCategoryFlag ToFlag(this ResourceCategory type) - => type switch + => (ResourceCategory)((uint) type & 0x00FFFFFF) switch { ResourceCategory.Common => ResourceCategoryFlag.Common, ResourceCategory.BgCommon => ResourceCategoryFlag.BgCommon, From 246f4f65f5bf60a9c1ee8ecc7bc65075346c6229 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 26 Jul 2024 18:42:48 +0200 Subject: [PATCH 0788/1381] Make items changed in a mod sort before other items for item swap, also color them. --- OtterGui | 2 +- Penumbra/Mods/ItemSwap/ItemSwap.cs | 10 ++-- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 65 ++++++++++++++--------- 3 files changed, 44 insertions(+), 33 deletions(-) diff --git a/OtterGui b/OtterGui index dc17161b..87a53262 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit dc17161b1d9c47ffd6bcc17e91f4832cf7762993 +Subproject commit 87a532620d622a00e60059b5dd42a04f0319b5b5 diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 1f4c5e7a..03abfc45 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -15,13 +15,9 @@ public static class ItemSwap public class InvalidItemTypeException : Exception { } - public class MissingFileException : Exception + public class MissingFileException(ResourceType type, object path) : Exception($"Could not load {type} File Data for \"{path}\".") { - public readonly ResourceType Type; - - public MissingFileException(ResourceType type, object path) - : base($"Could not load {type} File Data for \"{path}\".") - => Type = type; + public readonly ResourceType Type = type; } private static bool LoadFile(MetaFileManager manager, FullPath path, out byte[] data) @@ -47,7 +43,7 @@ public static class ItemSwap Penumbra.Log.Debug($"Could not load file {path}:\n{e}"); } - data = Array.Empty(); + data = []; return false; } diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 6db4db5c..da2daeb7 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -22,6 +22,7 @@ using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.UI.Classes; +using Penumbra.UI.ModsTab; namespace Penumbra.UI.AdvancedWindow; @@ -34,7 +35,8 @@ public class ItemSwapTab : IDisposable, ITab, IUiService private readonly MetaFileManager _metaFileManager; public ItemSwapTab(CommunicatorService communicator, ItemData itemService, CollectionManager collectionManager, - ModManager modManager, ObjectIdentification identifier, MetaFileManager metaFileManager, Configuration config) + ModManager modManager, ModFileSystemSelector selector, ObjectIdentification identifier, MetaFileManager metaFileManager, + Configuration config) { _communicator = communicator; _collectionManager = collectionManager; @@ -46,15 +48,15 @@ public class ItemSwapTab : IDisposable, ITab, IUiService _selectors = new Dictionary { // @formatter:off - [SwapType.Hat] = (new ItemSelector(itemService, FullEquipType.Head), new ItemSelector(itemService, FullEquipType.Head), "Take this Hat", "and put it on this one" ), - [SwapType.Top] = (new ItemSelector(itemService, FullEquipType.Body), new ItemSelector(itemService, FullEquipType.Body), "Take this Top", "and put it on this one" ), - [SwapType.Gloves] = (new ItemSelector(itemService, FullEquipType.Hands), new ItemSelector(itemService, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), - [SwapType.Pants] = (new ItemSelector(itemService, FullEquipType.Legs), new ItemSelector(itemService, FullEquipType.Legs), "Take these Pants", "and put them on these" ), - [SwapType.Shoes] = (new ItemSelector(itemService, FullEquipType.Feet), new ItemSelector(itemService, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), - [SwapType.Earrings] = (new ItemSelector(itemService, FullEquipType.Ears), new ItemSelector(itemService, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), - [SwapType.Necklace] = (new ItemSelector(itemService, FullEquipType.Neck), new ItemSelector(itemService, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), - [SwapType.Bracelet] = (new ItemSelector(itemService, FullEquipType.Wrists), new ItemSelector(itemService, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), - [SwapType.Ring] = (new ItemSelector(itemService, FullEquipType.Finger), new ItemSelector(itemService, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), + [SwapType.Hat] = (new ItemSelector(itemService, selector, FullEquipType.Head), new ItemSelector(itemService, null, FullEquipType.Head), "Take this Hat", "and put it on this one" ), + [SwapType.Top] = (new ItemSelector(itemService, selector, FullEquipType.Body), new ItemSelector(itemService, null, FullEquipType.Body), "Take this Top", "and put it on this one" ), + [SwapType.Gloves] = (new ItemSelector(itemService, selector, FullEquipType.Hands), new ItemSelector(itemService, null, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), + [SwapType.Pants] = (new ItemSelector(itemService, selector, FullEquipType.Legs), new ItemSelector(itemService, null, FullEquipType.Legs), "Take these Pants", "and put them on these" ), + [SwapType.Shoes] = (new ItemSelector(itemService, selector, FullEquipType.Feet), new ItemSelector(itemService, null, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), + [SwapType.Earrings] = (new ItemSelector(itemService, selector, FullEquipType.Ears), new ItemSelector(itemService, null, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), + [SwapType.Necklace] = (new ItemSelector(itemService, selector, FullEquipType.Neck), new ItemSelector(itemService, null, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), + [SwapType.Bracelet] = (new ItemSelector(itemService, selector, FullEquipType.Wrists), new ItemSelector(itemService, null, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), + [SwapType.Ring] = (new ItemSelector(itemService, selector, FullEquipType.Finger), new ItemSelector(itemService, null, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), // @formatter:on }; @@ -129,11 +131,24 @@ public class ItemSwapTab : IDisposable, ITab, IUiService Weapon, } - private class ItemSelector(ItemData data, FullEquipType type) - : FilterComboCache(() => data.ByType[type], MouseWheelType.None, Penumbra.Log) + private class ItemSelector(ItemData data, ModFileSystemSelector? selector, FullEquipType type) + : FilterComboCache<(EquipItem Item, bool InMod)>(() => + { + var list = data.ByType[type]; + if (selector?.Selected is { } mod && mod.ChangedItems.Values.Any(o => o is EquipItem i && i.Type == type)) + return list.Select(i => (i, mod.ChangedItems.ContainsKey(i.Name))).OrderByDescending(p => p.Item2).ToList(); + + return list.Select(i => (i, false)).ToList(); + }, MouseWheelType.None, Penumbra.Log) { - protected override string ToString(EquipItem obj) - => obj.Name; + protected override bool DrawSelectable(int globalIdx, bool selected) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ResTreeLocalPlayer.Value(), Items[globalIdx].InMod); + return base.DrawSelectable(globalIdx, selected); + } + + protected override string ToString((EquipItem Item, bool InMod) obj) + => obj.Item.Name; } private readonly Dictionary _selectors; @@ -186,17 +201,17 @@ public class ItemSwapTab : IDisposable, ITab, IUiService case SwapType.Bracelet: case SwapType.Ring: var values = _selectors[_lastTab]; - if (values.Source.CurrentSelection.Type != FullEquipType.Unknown - && values.Target.CurrentSelection.Type != FullEquipType.Unknown) - _affectedItems = _swapData.LoadEquipment(values.Target.CurrentSelection, values.Source.CurrentSelection, + if (values.Source.CurrentSelection.Item.Type != FullEquipType.Unknown + && values.Target.CurrentSelection.Item.Type != FullEquipType.Unknown) + _affectedItems = _swapData.LoadEquipment(values.Target.CurrentSelection.Item, values.Source.CurrentSelection.Item, _useCurrentCollection ? _collectionManager.Active.Current : null, _useRightRing, _useLeftRing); break; case SwapType.BetweenSlots: var (_, _, selectorFrom) = GetAccessorySelector(_slotFrom, true); var (_, _, selectorTo) = GetAccessorySelector(_slotTo, false); - if (selectorFrom.CurrentSelection.Valid && selectorTo.CurrentSelection.Valid) - _affectedItems = _swapData.LoadTypeSwap(_slotTo, selectorTo.CurrentSelection, _slotFrom, selectorFrom.CurrentSelection, + if (selectorFrom.CurrentSelection.Item.Valid && selectorTo.CurrentSelection.Item.Valid) + _affectedItems = _swapData.LoadTypeSwap(_slotTo, selectorTo.CurrentSelection.Item, _slotFrom, selectorFrom.CurrentSelection.Item, _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Hair when _targetId > 0 && _sourceId > 0: @@ -455,7 +470,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService } ImGui.TableNextColumn(); - _dirty |= selector.Draw("##itemSource", selector.CurrentSelection.Name ?? string.Empty, string.Empty, InputWidth * 2 * UiHelpers.Scale, + _dirty |= selector.Draw("##itemSource", selector.CurrentSelection.Item.Name ?? string.Empty, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); (article1, _, selector) = GetAccessorySelector(_slotTo, false); @@ -480,7 +495,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGui.TableNextColumn(); - _dirty |= selector.Draw("##itemTarget", selector.CurrentSelection.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, + _dirty |= selector.Draw("##itemTarget", selector.CurrentSelection.Item.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); if (_affectedItems is not { Length: > 1 }) return; @@ -489,7 +504,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGuiUtil.DrawTextButton($"which will also affect {_affectedItems.Length - 1} other Items.", Vector2.Zero, Colors.PressEnterWarningBg); if (ImGui.IsItemHovered()) - ImGui.SetTooltip(string.Join('\n', _affectedItems.Where(i => !ReferenceEquals(i.Name, selector.CurrentSelection.Name)) + ImGui.SetTooltip(string.Join('\n', _affectedItems.Where(i => !ReferenceEquals(i.Name, selector.CurrentSelection.Item.Name)) .Select(i => i.Name))); } @@ -521,7 +536,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGui.AlignTextToFramePadding(); ImGui.TextUnformatted(text1); ImGui.TableNextColumn(); - _dirty |= sourceSelector.Draw("##itemSource", sourceSelector.CurrentSelection.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, + _dirty |= sourceSelector.Draw("##itemSource", sourceSelector.CurrentSelection.Item.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); if (type == SwapType.Ring) @@ -534,7 +549,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGui.AlignTextToFramePadding(); ImGui.TextUnformatted(text2); ImGui.TableNextColumn(); - _dirty |= targetSelector.Draw("##itemTarget", targetSelector.CurrentSelection.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, + _dirty |= targetSelector.Draw("##itemTarget", targetSelector.CurrentSelection.Item.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); if (type == SwapType.Ring) { @@ -549,7 +564,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGuiUtil.DrawTextButton($"which will also affect {_affectedItems.Length - 1} other Items.", Vector2.Zero, Colors.PressEnterWarningBg); if (ImGui.IsItemHovered()) - ImGui.SetTooltip(string.Join('\n', _affectedItems.Where(i => !ReferenceEquals(i.Name, targetSelector.CurrentSelection.Name)) + ImGui.SetTooltip(string.Join('\n', _affectedItems.Where(i => !ReferenceEquals(i.Name, targetSelector.CurrentSelection.Item.Name)) .Select(i => i.Name))); } From 3ffe6151ffd05b732ac9df38cac17ba70b3a68ce Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 01:08:41 +0200 Subject: [PATCH 0789/1381] Add ToString for InternalEqpEntry. --- Penumbra/Meta/Manipulations/Eqp.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Penumbra/Meta/Manipulations/Eqp.cs b/Penumbra/Meta/Manipulations/Eqp.cs index ec4dd6e7..5d37aac8 100644 --- a/Penumbra/Meta/Manipulations/Eqp.cs +++ b/Penumbra/Meta/Manipulations/Eqp.cs @@ -72,4 +72,7 @@ public readonly record struct EqpEntryInternal(uint Value) var (offset, mask) = Eqp.OffsetAndMask(slot); return (uint)((ulong)(entry & mask) >> offset); } + + public override string ToString() + => Value.ToString("X8"); } From f143601aa00d8807fdf6fb016262afdc57cb00ea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 01:08:58 +0200 Subject: [PATCH 0790/1381] Do not replace paths when mods are not enabled. --- Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 10821287..3f055f64 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -17,15 +17,17 @@ public unsafe class ResourceLoader : IDisposable, IService private readonly FileReadService _fileReadService; private readonly TexMdlService _texMdlService; private readonly PapHandler _papHandler; + private readonly Configuration _config; private ResolveData _resolvedData = ResolveData.Invalid; public event Action? PapRequested; - public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService) + public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService, Configuration config) { _resources = resources; _fileReadService = fileReadService; _texMdlService = texMdlService; + _config = config; ResetResolvePath(); _resources.ResourceRequested += ResourceHandler; @@ -39,7 +41,7 @@ public unsafe class ResourceLoader : IDisposable, IService private int PapResourceHandler(void* self, byte* path, int length) { - if (!Utf8GamePath.FromPointer(path, out var gamePath)) + if (!_config.EnableMods || !Utf8GamePath.FromPointer(path, out var gamePath)) return length; var (resolvedPath, data) = _incMode.Value @@ -119,7 +121,7 @@ public unsafe class ResourceLoader : IDisposable, IService private void ResourceHandler(ref ResourceCategory category, ref ResourceType type, ref int hash, ref Utf8GamePath path, Utf8GamePath original, GetResourceParameters* parameters, ref bool sync, ref ResourceHandle* returnValue) { - if (returnValue != null) + if (!_config.EnableMods || returnValue != null) return; CompareHash(ComputeHash(path.Path, parameters), hash, path); From 6f3d9eb272b7ad35fade8c951df8254285bb7fa5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 01:09:11 +0200 Subject: [PATCH 0791/1381] Fix bug in EquipmentSwap --- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index b7827c47..2c292a14 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -186,7 +186,7 @@ public static class EquipmentSwap PrimaryId idTo, byte mtrlTo) { var eqdpFromIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); - var eqdpToIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); + var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); var meta = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, eqdpFromIdentifier, From cbf5baf65cef7450bbcb2be667d6fe06f69cb7f7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 01:09:48 +0200 Subject: [PATCH 0792/1381] Remove Material Reassignment Tab from advanced editing due to being obsolete. --- .../AdvancedWindow/ModEditWindow.Materials.cs | 72 ++----------------- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 1 - 2 files changed, 7 insertions(+), 66 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 0223ca6b..c3483c35 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -1,5 +1,4 @@ using Dalamud.Interface; -using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; @@ -112,13 +111,13 @@ public partial class ModEditWindow } ImGui.TableNextColumn(); - using (var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont)) - { - ImGui.AlignTextToFramePadding(); - if (description.Length > 0) - ImGuiUtil.LabeledHelpMarker(label, description); - else - ImGui.TextUnformatted(label); + using (ImRaii.PushFont(UiBuilder.MonoFont, monoFont)) + { + ImGui.AlignTextToFramePadding(); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); } if (unfolded) @@ -189,61 +188,4 @@ public partial class ModEditWindow if (t) Widget.DrawHexViewer(file.AdditionalData); } - - private void DrawMaterialReassignmentTab() - { - if (_editor.Files.Mdl.Count == 0) - return; - - using var tab = ImRaii.TabItem("Material Reassignment"); - if (!tab) - return; - - ImGui.NewLine(); - MaterialSuffix.Draw(_editor, ImGuiHelpers.ScaledVector2(175, 0)); - - ImGui.NewLine(); - using var child = ImRaii.Child("##mdlFiles", -Vector2.One, true); - if (!child) - return; - - using var table = ImRaii.Table("##files", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.One); - if (!table) - return; - - var iconSize = ImGui.GetFrameHeight() * Vector2.One; - foreach (var (info, idx) in _editor.MdlMaterialEditor.ModelFiles.WithIndex()) - { - using var id = ImRaii.PushId(idx); - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), iconSize, - "Save the changed mdl file.\nUse at own risk!", !info.Changed, true)) - info.Save(_editor.Compactor); - - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), iconSize, - "Restore current changes to default.", !info.Changed, true)) - info.Restore(); - - ImGui.TableNextColumn(); - ImGui.TextUnformatted(info.Path.FullName[(Mod!.ModPath.FullName.Length + 1)..]); - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(400 * UiHelpers.Scale); - var tmp = info.CurrentMaterials[0]; - if (ImGui.InputText("##0", ref tmp, 64)) - info.SetMaterial(tmp, 0); - - for (var i = 1; i < info.Count; ++i) - { - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(400 * UiHelpers.Scale); - tmp = info.CurrentMaterials[i]; - if (ImGui.InputText($"##{i}", ref tmp, 64)) - info.SetMaterial(tmp, i); - } - } - } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index e915a879..79a8ae34 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -179,7 +179,6 @@ public partial class ModEditWindow : Window, IDisposable, IUiService DrawSwapTab(); _modMergeTab.Draw(); DrawDuplicatesTab(); - DrawMaterialReassignmentTab(); DrawQuickImportTab(); _modelTab.Draw(); _materialTab.Draw(); From a1a7487897aeb8980e82db90b457873c95ae1f49 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 01:11:20 +0200 Subject: [PATCH 0793/1381] Remove Update Bibo Button. --- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index f81b2831..f8874f89 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -111,27 +111,6 @@ public class ModPanelEditTab( MoveDirectory.Draw(modManager, _mod, buttonSize); UiHelpers.DefaultLineSpace(); - DrawUpdateBibo(buttonSize); - - UiHelpers.DefaultLineSpace(); - } - - private void DrawUpdateBibo(Vector2 buttonSize) - { - if (ImGui.Button("Update Bibo Material", buttonSize)) - { - editor.LoadMod(_mod); - editor.MdlMaterialEditor.ReplaceAllMaterials("bibo", "b"); - editor.MdlMaterialEditor.ReplaceAllMaterials("bibopube", "c"); - editor.MdlMaterialEditor.SaveAllModels(editor.Compactor); - editWindow.UpdateModels(); - } - - ImGuiUtil.HoverTooltip( - "For every model in this mod, change all material names that end in a _b or _c suffix to a _bibo or _bibopube suffix respectively.\n" - + "Does nothing if the mod does not contain any such models or no model contains such materials.\n" - + "Use this for outdated mods made for old Bibo bodies.\n" - + "Go to Advanced Editing for more fine-tuned control over material assignment."); } private void BackupButtons(Vector2 buttonSize) From 19166d8cf4951dafe62766832f7bba00ea25971c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 01:11:52 +0200 Subject: [PATCH 0794/1381] Add rudimentary start for knowledge window. --- Penumbra/CommandHandler.cs | 20 ++++++--- Penumbra/UI/Knowledge/IKnowledgeTab.cs | 8 ++++ Penumbra/UI/Knowledge/KnowledgeWindow.cs | 55 ++++++++++++++++++++++++ Penumbra/UI/Knowledge/RaceCodeTab.cs | 42 ++++++++++++++++++ Penumbra/UI/WindowSystem.cs | 17 +++++--- 5 files changed, 131 insertions(+), 11 deletions(-) create mode 100644 Penumbra/UI/Knowledge/IKnowledgeTab.cs create mode 100644 Penumbra/UI/Knowledge/KnowledgeWindow.cs create mode 100644 Penumbra/UI/Knowledge/RaceCodeTab.cs diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 484dd954..db8d9aca 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -12,6 +12,7 @@ using Penumbra.Interop.Services; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.UI; +using Penumbra.UI.Knowledge; namespace Penumbra; @@ -29,11 +30,12 @@ public class CommandHandler : IDisposable, IApiService private readonly CollectionManager _collectionManager; private readonly Penumbra _penumbra; private readonly CollectionEditor _collectionEditor; + private readonly KnowledgeWindow _knowledgeWindow; public CommandHandler(IFramework framework, ICommandManager commandManager, IChatGui chat, RedrawService redrawService, - Configuration config, - ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorManager actors, Penumbra penumbra, - CollectionEditor collectionEditor) + Configuration config, ConfigWindow configWindow, ModManager modManager, CollectionManager collectionManager, ActorManager actors, + Penumbra penumbra, + CollectionEditor collectionEditor, KnowledgeWindow knowledgeWindow) { _commandManager = commandManager; _redrawService = redrawService; @@ -45,6 +47,7 @@ public class CommandHandler : IDisposable, IApiService _chat = chat; _penumbra = penumbra; _collectionEditor = collectionEditor; + _knowledgeWindow = knowledgeWindow; framework.RunOnFrameworkThread(() => { if (_commandManager.Commands.ContainsKey(CommandName)) @@ -69,7 +72,7 @@ public class CommandHandler : IDisposable, IApiService var argumentList = arguments.Split(' ', 2); arguments = argumentList.Length == 2 ? argumentList[1] : string.Empty; - var _ = argumentList[0].ToLowerInvariant() switch + _ = argumentList[0].ToLowerInvariant() switch { "window" => ToggleWindow(arguments), "enable" => SetPenumbraState(arguments, true), @@ -83,6 +86,7 @@ public class CommandHandler : IDisposable, IApiService "collection" => SetCollection(arguments), "mod" => SetMod(arguments), "bulktag" => SetTag(arguments), + "knowledge" => HandleKnowledge(arguments), _ => PrintHelp(argumentList[0]), }; } @@ -304,7 +308,7 @@ public class CommandHandler : IDisposable, IApiService identifiers = _actors.FromUserString(split[2], false); } } - catch (ActorManager.IdentifierParseError e) + catch (ActorIdentifierFactory.IdentifierParseError e) { _chat.Print(new SeStringBuilder().AddText("The argument ").AddRed(split[2], true) .AddText($" could not be converted to an identifier. {e.Message}") @@ -619,4 +623,10 @@ public class CommandHandler : IDisposable, IApiService if (_config.PrintSuccessfulCommandsToChat) _chat.Print(text()); } + + private bool HandleKnowledge(string arguments) + { + _knowledgeWindow.Toggle(); + return true; + } } diff --git a/Penumbra/UI/Knowledge/IKnowledgeTab.cs b/Penumbra/UI/Knowledge/IKnowledgeTab.cs new file mode 100644 index 00000000..568d5fda --- /dev/null +++ b/Penumbra/UI/Knowledge/IKnowledgeTab.cs @@ -0,0 +1,8 @@ +namespace Penumbra.UI.Knowledge; + +public interface IKnowledgeTab +{ + public ReadOnlySpan Name { get; } + public ReadOnlySpan SearchTags { get; } + public void Draw(); +} diff --git a/Penumbra/UI/Knowledge/KnowledgeWindow.cs b/Penumbra/UI/Knowledge/KnowledgeWindow.cs new file mode 100644 index 00000000..de1b36b8 --- /dev/null +++ b/Penumbra/UI/Knowledge/KnowledgeWindow.cs @@ -0,0 +1,55 @@ +using System.Text.Unicode; +using Dalamud.Interface.Utility.Raii; +using Dalamud.Interface.Windowing; +using Dalamud.Memory; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; + +namespace Penumbra.UI.Knowledge; + +/// Draw the progress information for import. +public sealed class KnowledgeWindow() : Window("Penumbra Knowledge Window"), IUiService +{ + private readonly IReadOnlyList _tabs = + [ + new RaceCodeTab(), + ]; + + private IKnowledgeTab? _selected; + private readonly byte[] _filterStore = new byte[256]; + + private TerminatedByteString _filter = TerminatedByteString.Empty; + + public override void Draw() + { + DrawSelector(); + ImUtf8.SameLineInner(); + DrawMain(); + } + + private void DrawSelector() + { + using var child = ImUtf8.Child("KnowledgeSelector"u8, new Vector2(250 * ImUtf8.GlobalScale, ImGui.GetContentRegionAvail().Y), true); + if (!child) + return; + + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); + ImUtf8.InputText("##Filter"u8, _filterStore, out _filter, "Filter..."u8); + + foreach (var tab in _tabs) + { + if (ImUtf8.Selectable(tab.Name, _selected == tab)) + _selected = tab; + } + } + + private void DrawMain() + { + using var child = ImUtf8.Child("KnowledgeMain"u8, ImGui.GetContentRegionAvail(), true); + if (!child || _selected == null) + return; + + _selected.Draw(); + } +} diff --git a/Penumbra/UI/Knowledge/RaceCodeTab.cs b/Penumbra/UI/Knowledge/RaceCodeTab.cs new file mode 100644 index 00000000..988506dd --- /dev/null +++ b/Penumbra/UI/Knowledge/RaceCodeTab.cs @@ -0,0 +1,42 @@ +using ImGuiNET; +using OtterGui.Text; +using Penumbra.GameData.Enums; + +namespace Penumbra.UI.Knowledge; + +public sealed class RaceCodeTab : IKnowledgeTab +{ + public ReadOnlySpan Name + => "Race Codes"u8; + + public ReadOnlySpan SearchTags + => "deformersracecodesmodel"u8; + + public void Draw() + { + using var table = ImUtf8.Table("table"u8, 4, ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImUtf8.TableHeader("Race Code"u8); + ImUtf8.TableHeader("Race"u8); + ImUtf8.TableHeader("Gender"u8); + ImUtf8.TableHeader("NPC"u8); + + foreach (var genderRace in Enum.GetValues()) + { + ImGui.TableNextColumn(); + ImUtf8.Text(genderRace.ToRaceCode()); + + var (gender, race) = genderRace.Split(); + ImGui.TableNextColumn(); + ImUtf8.Text($"{race}"); + + ImGui.TableNextColumn(); + ImUtf8.Text($"{gender}"); + + ImGui.TableNextColumn(); + ImUtf8.Text(((ushort)genderRace & 0xF) != 1 ? "NPC"u8 : "Normal"u8); + } + } +} diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index 72ac0d01..6d382ad4 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin; using OtterGui.Services; using Penumbra.UI.AdvancedWindow; +using Penumbra.UI.Knowledge; using Penumbra.UI.Tabs.Debug; namespace Penumbra.UI; @@ -14,20 +15,24 @@ public class PenumbraWindowSystem : IDisposable, IUiService private readonly FileDialogService _fileDialog; public readonly ConfigWindow Window; public readonly PenumbraChangelog Changelog; + public readonly KnowledgeWindow KnowledgeWindow; public PenumbraWindowSystem(IDalamudPluginInterface pi, Configuration config, PenumbraChangelog changelog, ConfigWindow window, - LaunchButton _, ModEditWindow editWindow, FileDialogService fileDialog, ImportPopup importPopup, DebugTab debugTab) + LaunchButton _, ModEditWindow editWindow, FileDialogService fileDialog, ImportPopup importPopup, DebugTab debugTab, + KnowledgeWindow knowledgeWindow) { - _uiBuilder = pi.UiBuilder; - _fileDialog = fileDialog; - Changelog = changelog; - Window = window; - _windowSystem = new WindowSystem("Penumbra"); + _uiBuilder = pi.UiBuilder; + _fileDialog = fileDialog; + KnowledgeWindow = knowledgeWindow; + Changelog = changelog; + Window = window; + _windowSystem = new WindowSystem("Penumbra"); _windowSystem.AddWindow(changelog.Changelog); _windowSystem.AddWindow(window); _windowSystem.AddWindow(editWindow); _windowSystem.AddWindow(importPopup); _windowSystem.AddWindow(debugTab); + _windowSystem.AddWindow(KnowledgeWindow); _uiBuilder.OpenMainUi += Window.Toggle; _uiBuilder.OpenConfigUi += Window.OpenSettings; _uiBuilder.Draw += _windowSystem.Draw; From d0c4d6984cbd8e40db28e47398a309b71382f6ab Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 12:57:59 +0200 Subject: [PATCH 0795/1381] Dispose collection caches on plugin disposal. --- Penumbra/Collections/Cache/CollectionCacheManager.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 80d4cf1d..a3b6bb83 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -84,6 +84,12 @@ public class CollectionCacheManager : IDisposable, IService _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); _communicator.CollectionInheritanceChanged.Unsubscribe(OnCollectionInheritanceChange); MetaFileManager.CharacterUtility.LoadingFinished -= IncrementCounters; + + foreach (var collection in _storage) + { + collection._cache?.Dispose(); + collection._cache = null; + } } public void AddChange(CollectionCache.ChangeData data) From bb4665c367a876d7bff704794651bd673d9c2978 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 12:58:17 +0200 Subject: [PATCH 0796/1381] Remove unused params. --- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index f8874f89..90d8fb74 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -11,7 +11,6 @@ using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Services; -using Penumbra.UI.AdvancedWindow; using Penumbra.Mods.Settings; using Penumbra.UI.ModsTab.Groups; @@ -22,8 +21,6 @@ public class ModPanelEditTab( ModFileSystemSelector selector, ModFileSystem fileSystem, Services.MessageService messager, - ModEditWindow editWindow, - ModEditor editor, FilenameService filenames, ModExportManager modExportManager, Configuration config, From 4806f8dc3eeea497ce95f52b30ce7b12bf12dc82 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 13:43:01 +0200 Subject: [PATCH 0797/1381] Do not force loaded game paths to lowercase. --- Penumbra/Mods/SubMods/SubMod.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index a8c37369..f6b1be96 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -52,7 +52,7 @@ public static class SubMod if (files != null) foreach (var property in files.Properties()) { - if (Utf8GamePath.FromString(property.Name, out var p, true)) + if (Utf8GamePath.FromString(property.Name, out var p)) data.Files.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); } @@ -60,7 +60,7 @@ public static class SubMod if (swaps != null) foreach (var property in swaps.Properties()) { - if (Utf8GamePath.FromString(property.Name, out var p, true)) + if (Utf8GamePath.FromString(property.Name, out var p)) data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); } From af0bbeb8bfd0c093716f110e77442a60b69543f9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 13:48:11 +0200 Subject: [PATCH 0798/1381] Force saving to be synchronous. --- Penumbra/Mods/TemporaryMod.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index e1cf9f2b..e4049482 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -96,7 +96,7 @@ public class TemporaryMod : IMod var manips = new MetaDictionary(collection.MetaCache); defaultMod.Manipulations.UnionWith(manips); - saveService.ImmediateSave(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); + saveService.ImmediateSaveSync(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir); Penumbra.Log.Information( $"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identifier}."); From 5d50523c72ca2ccdb41392b285711315e90ea998 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 28 Jul 2024 12:12:56 +0000 Subject: [PATCH 0799/1381] [CI] Updating repo.json for testing_1.2.0.15 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index f1108cfe..7bcc18b6 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.14", + "TestingAssemblyVersion": "1.2.0.15", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.14/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.15/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From d30d418afe571b8bde490f1566ee421955757c10 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Jul 2024 23:56:11 +0200 Subject: [PATCH 0800/1381] Remove a ToLower when resolving paths. --- Penumbra/Interop/PathResolving/PathResolver.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 49035dc8..67ec4fc3 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -52,7 +52,6 @@ public class PathResolver : IDisposable, IService if (resourceType is ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb) return (null, ResolveData.Invalid); - path = path.ToLower(); return category switch { // Only Interface collection. From e52b027545e01786dfce4754fe345fabcdae91b0 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 28 Jul 2024 22:03:19 +0000 Subject: [PATCH 0801/1381] [CI] Updating repo.json for testing_1.2.0.16 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 7bcc18b6..9c9e41db 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.15", + "TestingAssemblyVersion": "1.2.0.16", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.15/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.16/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 3754f5713224024aa778456d3ecc7d39b5b483a2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 29 Jul 2024 09:27:00 +0200 Subject: [PATCH 0802/1381] Reinstate spacebar heating --- .../AdvancedWindow/ModEditWindow.Materials.cs | 58 +++++++++++++++++++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 1 + 2 files changed, 59 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index c3483c35..5a8fb13a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; @@ -188,4 +189,61 @@ public partial class ModEditWindow if (t) Widget.DrawHexViewer(file.AdditionalData); } + + private void DrawMaterialReassignmentTab() + { + if (_editor.Files.Mdl.Count == 0) + return; + + using var tab = ImRaii.TabItem("Material Reassignment"); + if (!tab) + return; + + ImGui.NewLine(); + MaterialSuffix.Draw(_editor, ImGuiHelpers.ScaledVector2(175, 0)); + + ImGui.NewLine(); + using var child = ImRaii.Child("##mdlFiles", -Vector2.One, true); + if (!child) + return; + + using var table = ImRaii.Table("##files", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.One); + if (!table) + return; + + var iconSize = ImGui.GetFrameHeight() * Vector2.One; + foreach (var (info, idx) in _editor.MdlMaterialEditor.ModelFiles.WithIndex()) + { + using var id = ImRaii.PushId(idx); + ImGui.TableNextColumn(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), iconSize, + "Save the changed mdl file.\nUse at own risk!", !info.Changed, true)) + info.Save(_editor.Compactor); + + ImGui.TableNextColumn(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), iconSize, + "Restore current changes to default.", !info.Changed, true)) + info.Restore(); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted(info.Path.FullName[(Mod!.ModPath.FullName.Length + 1)..]); + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(400 * UiHelpers.Scale); + var tmp = info.CurrentMaterials[0]; + if (ImGui.InputText("##0", ref tmp, 64)) + info.SetMaterial(tmp, 0); + + for (var i = 1; i < info.Count; ++i) + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(400 * UiHelpers.Scale); + tmp = info.CurrentMaterials[i]; + if (ImGui.InputText($"##{i}", ref tmp, 64)) + info.SetMaterial(tmp, i); + } + } + } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 79a8ae34..e915a879 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -179,6 +179,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService DrawSwapTab(); _modMergeTab.Draw(); DrawDuplicatesTab(); + DrawMaterialReassignmentTab(); DrawQuickImportTab(); _modelTab.Draw(); _materialTab.Draw(); From 5512e0cad2b273caca8f1b10b82a72be2274be80 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 29 Jul 2024 09:43:07 +0200 Subject: [PATCH 0803/1381] Revert no-lowercasing for the moment. --- Penumbra/Interop/PathResolving/PathResolver.cs | 1 + Penumbra/Mods/SubMods/SubMod.cs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 67ec4fc3..49035dc8 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -52,6 +52,7 @@ public class PathResolver : IDisposable, IService if (resourceType is ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb) return (null, ResolveData.Invalid); + path = path.ToLower(); return category switch { // Only Interface collection. diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index f6b1be96..a8c37369 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -52,7 +52,7 @@ public static class SubMod if (files != null) foreach (var property in files.Properties()) { - if (Utf8GamePath.FromString(property.Name, out var p)) + if (Utf8GamePath.FromString(property.Name, out var p, true)) data.Files.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); } @@ -60,7 +60,7 @@ public static class SubMod if (swaps != null) foreach (var property in swaps.Properties()) { - if (Utf8GamePath.FromString(property.Name, out var p)) + if (Utf8GamePath.FromString(property.Name, out var p, true)) data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); } From ee801b637eb6a7b1c2092d0b5e54c532b20a462a Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 29 Jul 2024 07:46:20 +0000 Subject: [PATCH 0804/1381] [CI] Updating repo.json for testing_1.2.0.17 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 9c9e41db..adf152b0 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.16", + "TestingAssemblyVersion": "1.2.0.17", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.16/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.17/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 7ceaeb826f88fc08f35f8e85cba7488a2644453a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 29 Jul 2024 18:25:30 +0200 Subject: [PATCH 0805/1381] Move Material Reassignment to the back (and shoot it) --- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index e915a879..b0e9af7f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -179,7 +179,6 @@ public partial class ModEditWindow : Window, IDisposable, IUiService DrawSwapTab(); _modMergeTab.Draw(); DrawDuplicatesTab(); - DrawMaterialReassignmentTab(); DrawQuickImportTab(); _modelTab.Draw(); _materialTab.Draw(); @@ -192,6 +191,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService } DrawMissingFilesTab(); + DrawMaterialReassignmentTab(); } /// A row of three buttonSizes and a help marker that can be used for material suffix changing. From 8518240bf919a7499953dad8b399114bfa10e1ea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 29 Jul 2024 18:25:41 +0200 Subject: [PATCH 0806/1381] Improve knowledge window somewhat. --- Penumbra/UI/Knowledge/KnowledgeWindow.cs | 37 +++++++++++-- Penumbra/UI/Knowledge/RaceCodeTab.cs | 70 +++++++++++++++++++----- 2 files changed, 86 insertions(+), 21 deletions(-) diff --git a/Penumbra/UI/Knowledge/KnowledgeWindow.cs b/Penumbra/UI/Knowledge/KnowledgeWindow.cs index de1b36b8..b14949de 100644 --- a/Penumbra/UI/Knowledge/KnowledgeWindow.cs +++ b/Penumbra/UI/Knowledge/KnowledgeWindow.cs @@ -5,11 +5,12 @@ using Dalamud.Memory; using ImGuiNET; using OtterGui.Services; using OtterGui.Text; +using Penumbra.String; namespace Penumbra.UI.Knowledge; /// Draw the progress information for import. -public sealed class KnowledgeWindow() : Window("Penumbra Knowledge Window"), IUiService +public sealed class KnowledgeWindow : Window, IUiService { private readonly IReadOnlyList _tabs = [ @@ -19,7 +20,16 @@ public sealed class KnowledgeWindow() : Window("Penumbra Knowledge Window"), IUi private IKnowledgeTab? _selected; private readonly byte[] _filterStore = new byte[256]; - private TerminatedByteString _filter = TerminatedByteString.Empty; + private ByteString _lower = ByteString.Empty; + + /// Draw the progress information for import. + public KnowledgeWindow() + : base("Penumbra Knowledge Window") + => SizeConstraints = new WindowSizeConstraints + { + MaximumSize = new Vector2(10000, 10000), + MinimumSize = new Vector2(400, 200), + }; public override void Draw() { @@ -30,15 +40,23 @@ public sealed class KnowledgeWindow() : Window("Penumbra Knowledge Window"), IUi private void DrawSelector() { - using var child = ImUtf8.Child("KnowledgeSelector"u8, new Vector2(250 * ImUtf8.GlobalScale, ImGui.GetContentRegionAvail().Y), true); + using var group = ImUtf8.Group(); + using (ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0).Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero)) + { + ImGui.SetNextItemWidth(200 * ImUtf8.GlobalScale); + if (ImUtf8.InputText("##Filter"u8, _filterStore, out TerminatedByteString filter, "Filter..."u8)) + _lower = ByteString.FromSpanUnsafe(filter, true, null, null).AsciiToLowerClone(); + } + + using var child = ImUtf8.Child("KnowledgeSelector"u8, new Vector2(200 * ImUtf8.GlobalScale, ImGui.GetContentRegionAvail().Y), true); if (!child) return; - ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); - ImUtf8.InputText("##Filter"u8, _filterStore, out _filter, "Filter..."u8); - foreach (var tab in _tabs) { + if (!_lower.IsEmpty && tab.SearchTags.IndexOf(_lower.Span) < 0) + continue; + if (ImUtf8.Selectable(tab.Name, _selected == tab)) _selected = tab; } @@ -46,6 +64,13 @@ public sealed class KnowledgeWindow() : Window("Penumbra Knowledge Window"), IUi private void DrawMain() { + using var group = ImUtf8.Group(); + using (ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0).Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero)) + { + ImUtf8.TextFramed(_selected == null ? "No Selection"u8 : _selected.Name, ImGui.GetColorU32(ImGuiCol.FrameBg), + new Vector2(ImGui.GetContentRegionAvail().X, 0)); + } + using var child = ImUtf8.Child("KnowledgeMain"u8, ImGui.GetContentRegionAvail(), true); if (!child || _selected == null) return; diff --git a/Penumbra/UI/Knowledge/RaceCodeTab.cs b/Penumbra/UI/Knowledge/RaceCodeTab.cs index 988506dd..36b048aa 100644 --- a/Penumbra/UI/Knowledge/RaceCodeTab.cs +++ b/Penumbra/UI/Knowledge/RaceCodeTab.cs @@ -4,7 +4,7 @@ using Penumbra.GameData.Enums; namespace Penumbra.UI.Knowledge; -public sealed class RaceCodeTab : IKnowledgeTab +public sealed class RaceCodeTab() : IKnowledgeTab { public ReadOnlySpan Name => "Race Codes"u8; @@ -14,29 +14,69 @@ public sealed class RaceCodeTab : IKnowledgeTab public void Draw() { - using var table = ImUtf8.Table("table"u8, 4, ImGuiTableFlags.SizingFixedFit); - if (!table) - return; + var size = new Vector2((ImGui.GetContentRegionAvail().X - ImUtf8.ItemSpacing.X) / 2, 0); + using (var table = ImUtf8.Table("adults"u8, 4, ImGuiTableFlags.BordersOuter, size)) + { + if (!table) + return; - ImUtf8.TableHeader("Race Code"u8); - ImUtf8.TableHeader("Race"u8); - ImUtf8.TableHeader("Gender"u8); - ImUtf8.TableHeader("NPC"u8); + DrawHeaders(); + foreach (var gr in Enum.GetValues()) + { + var (gender, race) = gr.Split(); + if (gender is not Gender.Male and not Gender.Female || race is ModelRace.Unknown) + continue; - foreach (var genderRace in Enum.GetValues()) + DrawRow(gender, race, false); + } + } + + ImGui.SameLine(); + + using (var table = ImUtf8.Table("children"u8, 4, ImGuiTableFlags.BordersOuter, size)) + { + if (!table) + return; + + DrawHeaders(); + foreach (var race in (ReadOnlySpan) + [ModelRace.Midlander, ModelRace.Elezen, ModelRace.Miqote, ModelRace.AuRa, ModelRace.Unknown]) + { + foreach (var gender in (ReadOnlySpan) [Gender.Male, Gender.Female]) + DrawRow(gender, race, true); + } + } + + return; + + static void DrawHeaders() { ImGui.TableNextColumn(); - ImUtf8.Text(genderRace.ToRaceCode()); - - var (gender, race) = genderRace.Split(); + ImUtf8.TableHeader("Race"u8); ImGui.TableNextColumn(); - ImUtf8.Text($"{race}"); + ImUtf8.TableHeader("Gender"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Age"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Race Code"u8); + } + + static void DrawRow(Gender gender, ModelRace race, bool child) + { + var gr = child + ? Names.CombinedRace(gender is Gender.Male ? Gender.MaleNpc : Gender.FemaleNpc, race) + : Names.CombinedRace(gender, race); + ImGui.TableNextColumn(); + ImUtf8.Text(race.ToName()); ImGui.TableNextColumn(); - ImUtf8.Text($"{gender}"); + ImUtf8.Text(gender.ToName()); ImGui.TableNextColumn(); - ImUtf8.Text(((ushort)genderRace & 0xF) != 1 ? "NPC"u8 : "Normal"u8); + ImUtf8.Text(child ? "Child"u8 : "Adult"u8); + + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable(gr.ToRaceCode()); } } } From 5270ad4d0d8637c9c6ff5d3ed715e486236c9a1b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 29 Jul 2024 23:00:03 +0200 Subject: [PATCH 0807/1381] Update ImageSharp --- Penumbra/Penumbra.csproj | 2 +- Penumbra/packages.lock.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 70208737..24ffe469 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -79,7 +79,7 @@ - + diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 42539e78..8e7106dd 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -44,9 +44,9 @@ }, "SixLabors.ImageSharp": { "type": "Direct", - "requested": "[3.1.4, )", - "resolved": "3.1.4", - "contentHash": "lFIdxgGDA5iYkUMRFOze7BGLcdpoLFbR+a20kc1W7NepvzU7ejtxtWOg9RvgG7kb9tBoJ3ONYOK6kLil/dgF1w==" + "requested": "[3.1.5, )", + "resolved": "3.1.5", + "contentHash": "lNtlq7dSI/QEbYey+A0xn48z5w4XHSffF8222cC4F4YwTXfEImuiBavQcWjr49LThT/pRmtWJRcqA/PlL+eJ6g==" }, "JetBrains.Annotations": { "type": "Transitive", From 70281c576e7b16ac5b7551e53472e625b7f44a91 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 30 Jul 2024 18:34:26 +0200 Subject: [PATCH 0808/1381] Update Submodules. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index 87a53262..33ffd7cb 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 87a532620d622a00e60059b5dd42a04f0319b5b5 +Subproject commit 33ffd7cba3e487e98e55adca1677354078089943 diff --git a/Penumbra.GameData b/Penumbra.GameData index f5a74c70..d8ebd63c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f5a74c70ad3861c5c66e1df6ae9a29fc7a0d736a +Subproject commit d8ebd63cec1ac12ea547fd37b6c32bdf9b3f57d1 diff --git a/Penumbra.String b/Penumbra.String index f04abbab..91f0f211 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit f04abbabedf5e757c5cbb970f3e513fef23e53cf +Subproject commit 91f0f21137c61bd39281debf88a8ecc494043330 From 9d128a4d831849c791dbce8efa9dbcda4c75f75f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 30 Jul 2024 18:38:25 +0200 Subject: [PATCH 0809/1381] Fix potential threading issue on launch. --- Penumbra/Interop/PathResolving/DrawObjectState.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 2a9ec7a9..5e413fe2 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; @@ -22,18 +23,19 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _gameState.LastGameObject; public unsafe DrawObjectState(ObjectManager objects, CreateCharacterBase createCharacterBase, WeaponReload weaponReload, - CharacterBaseDestructor characterBaseDestructor, GameState gameState) + CharacterBaseDestructor characterBaseDestructor, GameState gameState, IFramework framework) { _objects = objects; _createCharacterBase = createCharacterBase; _weaponReload = weaponReload; _characterBaseDestructor = characterBaseDestructor; _gameState = gameState; + framework.RunOnFrameworkThread(InitializeDrawObjects); + _weaponReload.Subscribe(OnWeaponReloading, WeaponReload.Priority.DrawObjectState); _weaponReload.Subscribe(OnWeaponReloaded, WeaponReload.PostEvent.Priority.DrawObjectState); _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.DrawObjectState); _characterBaseDestructor.Subscribe(OnCharacterBaseDestructor, CharacterBaseDestructor.Priority.DrawObjectState); - InitializeDrawObjects(); } public bool ContainsKey(nint key) @@ -94,8 +96,8 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary private unsafe void InitializeDrawObjects() { - foreach(var actor in _objects) - { + foreach (var actor in _objects) + { if (actor is { IsCharacter: true, Model.Valid: true }) IterateDrawObjectTree((Object*)actor.Model.Address, actor, false, false); } From d247f83e1db8bf59ea647fdae3e9a22fb4996015 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 30 Jul 2024 18:53:55 +0200 Subject: [PATCH 0810/1381] Use CiByteString for anything path-related. --- Penumbra/Api/Api/ResolveApi.cs | 2 +- Penumbra/Api/Api/TemporaryApi.cs | 2 +- Penumbra/Api/DalamudSubstitutionProvider.cs | 3 +- Penumbra/Collections/Cache/ImcCache.cs | 6 ++-- Penumbra/Enums/ResourceTypeFlag.cs | 6 ++-- .../PostProcessing/PreBoneDeformerReplacer.cs | 3 +- .../Hooks/ResourceLoading/CreateFileWHook.cs | 2 +- .../Hooks/ResourceLoading/ResourceLoader.cs | 21 +++++++------- .../Hooks/ResourceLoading/ResourceService.cs | 8 +++--- .../Interop/MaterialPreview/MaterialInfo.cs | 7 +++-- .../Interop/PathResolving/PathDataHandler.cs | 10 +++---- .../Interop/PathResolving/PathResolver.cs | 1 - Penumbra/Interop/PathResolving/PathState.cs | 2 +- .../Processing/AvfxPathPreProcessor.cs | 2 +- .../Processing/FilePostProcessService.cs | 4 +-- .../Processing/GamePathPreProcessService.cs | 4 +-- .../Processing/ImcFilePostProcessor.cs | 2 +- .../Interop/Processing/ImcPathPreProcessor.cs | 2 +- .../Processing/MaterialFilePostProcessor.cs | 2 +- .../Processing/MtrlPathPreProcessor.cs | 2 +- .../Interop/Processing/TmbPathPreProcessor.cs | 2 +- .../ResolveContext.PathResolution.cs | 9 +++--- .../Interop/ResourceTree/ResolveContext.cs | 20 ++++++------- Penumbra/Interop/ResourceTree/ResourceNode.cs | 12 ++++---- Penumbra/Interop/Services/DecalReverter.cs | 5 ++-- Penumbra/Interop/Structs/ResourceHandle.cs | 4 +-- Penumbra/Interop/Structs/StructExtensions.cs | 24 ++++++++-------- Penumbra/Mods/ModCreator.cs | 4 +-- Penumbra/Mods/SubMods/SubMod.cs | 4 +-- Penumbra/UI/AdvancedWindow/FileEditor.cs | 5 ++-- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 8 +++--- .../ModEditWindow.Materials.MtrlTab.cs | 4 +-- .../ModEditWindow.Models.MdlTab.cs | 2 +- .../ModEditWindow.ShaderPackages.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 28 ++++++++++++------- Penumbra/UI/Knowledge/KnowledgeWindow.cs | 2 -- Penumbra/UI/ResourceWatcher/Record.cs | 18 ++++++------ .../UI/ResourceWatcher/ResourceWatcher.cs | 4 +-- .../ResourceWatcher/ResourceWatcherTable.cs | 4 +-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 28 +++++++++++++++++++ Penumbra/UI/Tabs/EffectiveTab.cs | 5 ++-- 42 files changed, 163 insertions(+), 124 deletions(-) diff --git a/Penumbra/Api/Api/ResolveApi.cs b/Penumbra/Api/Api/ResolveApi.cs index ec57eba7..481ea7ad 100644 --- a/Penumbra/Api/Api/ResolveApi.cs +++ b/Penumbra/Api/Api/ResolveApi.cs @@ -94,7 +94,7 @@ public class ResolveApi( if (!config.EnableMods) return path; - var gamePath = Utf8GamePath.FromString(path, out var p, true) ? p : Utf8GamePath.Empty; + var gamePath = Utf8GamePath.FromString(path, out var p) ? p : Utf8GamePath.Empty; var ret = collection.ResolvePath(gamePath); return ret?.ToString() ?? path; } diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 0894a8e5..f02b0d94 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -137,7 +137,7 @@ public class TemporaryApi( paths = new Dictionary(redirections.Count); foreach (var (gString, fString) in redirections) { - if (!Utf8GamePath.FromString(gString, out var path, false)) + if (!Utf8GamePath.FromString(gString, out var path)) { paths = null; return false; diff --git a/Penumbra/Api/DalamudSubstitutionProvider.cs b/Penumbra/Api/DalamudSubstitutionProvider.cs index 6347447a..e10dc461 100644 --- a/Penumbra/Api/DalamudSubstitutionProvider.cs +++ b/Penumbra/Api/DalamudSubstitutionProvider.cs @@ -4,7 +4,6 @@ using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Communication; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Services; using Penumbra.String.Classes; @@ -130,7 +129,7 @@ public class DalamudSubstitutionProvider : IDisposable, IApiService try { - if (!Utf8GamePath.FromString(path, out var utf8Path, true)) + if (!Utf8GamePath.FromString(path, out var utf8Path)) return; var resolved = _activeCollectionData.Interface.ResolvePath(utf8Path); diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 40c3d2c7..cac52f99 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -8,12 +8,12 @@ namespace Penumbra.Collections.Cache; public sealed class ImcCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - private readonly Dictionary)> _imcFiles = []; + private readonly Dictionary)> _imcFiles = []; - public bool HasFile(ByteString path) + public bool HasFile(CiByteString path) => _imcFiles.ContainsKey(path); - public bool GetFile(ByteString path, [NotNullWhen(true)] out ImcFile? file) + public bool GetFile(CiByteString path, [NotNullWhen(true)] out ImcFile? file) { if (!_imcFiles.TryGetValue(path, out var p)) { diff --git a/Penumbra/Enums/ResourceTypeFlag.cs b/Penumbra/Enums/ResourceTypeFlag.cs index 461e7ac1..920e9780 100644 --- a/Penumbra/Enums/ResourceTypeFlag.cs +++ b/Penumbra/Enums/ResourceTypeFlag.cs @@ -216,10 +216,10 @@ public static class ResourceExtensions }; } - public static ResourceType Type(ByteString path) + public static ResourceType Type(CiByteString path) { var extIdx = path.LastIndexOf((byte)'.'); - var ext = extIdx == -1 ? path : extIdx == path.Length - 1 ? ByteString.Empty : path.Substring(extIdx + 1); + var ext = extIdx == -1 ? path : extIdx == path.Length - 1 ? CiByteString.Empty : path.Substring(extIdx + 1); return ext.Length switch { @@ -231,7 +231,7 @@ public static class ResourceExtensions }; } - public static ResourceCategory Category(ByteString path) + public static ResourceCategory Category(CiByteString path) { if (path.Length < 3) return ResourceCategory.Debug; diff --git a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs index 903484ea..834a7d28 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs @@ -7,6 +7,7 @@ using Penumbra.Api.Enums; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.PathResolving; using Penumbra.Interop.SafeHandles; +using Penumbra.String; using Penumbra.String.Classes; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; @@ -15,7 +16,7 @@ namespace Penumbra.Interop.Hooks.PostProcessing; public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredService { public static readonly Utf8GamePath PreBoneDeformerPath = - Utf8GamePath.FromSpan("chara/xls/boneDeformer/human.pbd"u8, out var p) ? p : Utf8GamePath.Empty; + Utf8GamePath.FromSpan("chara/xls/boneDeformer/human.pbd"u8, MetaDataComputation.All, out var p) ? p : Utf8GamePath.Empty; // Approximate name guesses. private delegate void CharacterBaseSetupScalingDelegate(CharacterBase* drawObject, uint slotIndex); diff --git a/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs index a8ac0608..8d0ac8cb 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs @@ -102,7 +102,7 @@ public unsafe class CreateFileWHook : IDisposable, IRequiredService { // Use static storage. var ptr = WriteFileName(name); - Penumbra.Log.Excessive($"[ResourceHooks] Calling CreateFileWDetour with {ByteString.FromSpanUnsafe(name, false)}."); + Penumbra.Log.Excessive($"[ResourceHooks] Calling CreateFileWDetour with {CiByteString.FromSpanUnsafe(name, false)}."); return _createFileWHook.OriginalDisposeSafe(ptr, access, shareMode, security, creation, flags, template); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 3f055f64..bcd09b37 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -41,7 +41,7 @@ public unsafe class ResourceLoader : IDisposable, IService private int PapResourceHandler(void* self, byte* path, int length) { - if (!_config.EnableMods || !Utf8GamePath.FromPointer(path, out var gamePath)) + if (!_config.EnableMods || !Utf8GamePath.FromPointer(path, MetaDataComputation.CiCrc32, out var gamePath)) return length; var (resolvedPath, data) = _incMode.Value @@ -64,7 +64,7 @@ public unsafe class ResourceLoader : IDisposable, IService } /// Load a resource for a given path and a specific collection. - public ResourceHandle* LoadResolvedResource(ResourceCategory category, ResourceType type, ByteString path, ResolveData resolveData) + public ResourceHandle* LoadResolvedResource(ResourceCategory category, ResourceType type, CiByteString path, ResolveData resolveData) { _resolvedData = resolveData; var ret = _resources.GetResource(category, type, path); @@ -73,7 +73,7 @@ public unsafe class ResourceLoader : IDisposable, IService } /// Load a resource for a given path and a specific collection. - public SafeResourceHandle LoadResolvedSafeResource(ResourceCategory category, ResourceType type, ByteString path, ResolveData resolveData) + public SafeResourceHandle LoadResolvedSafeResource(ResourceCategory category, ResourceType type, CiByteString path, ResolveData resolveData) { _resolvedData = resolveData; var ret = _resources.GetSafeResource(category, type, path); @@ -98,7 +98,7 @@ public unsafe class ResourceLoader : IDisposable, IService /// public event ResourceLoadedDelegate? ResourceLoaded; - public delegate void FileLoadedDelegate(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, + public delegate void FileLoadedDelegate(ResourceHandle* resource, CiByteString path, bool returnValue, bool custom, ReadOnlySpan additionalData); /// @@ -172,7 +172,8 @@ public unsafe class ResourceLoader : IDisposable, IService return; } - var path = ByteString.FromSpanUnsafe(actualPath, gamePath.Path.IsNullTerminated, gamePath.Path.IsAsciiLowerCase, gamePath.Path.IsAscii); + var path = CiByteString.FromSpanUnsafe(actualPath, gamePath.Path.IsNullTerminated, gamePath.Path.IsAsciiLowerCase, + gamePath.Path.IsAscii); fileDescriptor->ResourceHandle->FileNameData = path.Path; fileDescriptor->ResourceHandle->FileNameLength = path.Length; MtrlForceSync(fileDescriptor, ref isSync); @@ -184,7 +185,7 @@ public unsafe class ResourceLoader : IDisposable, IService /// Load a resource by its path. If it is rooted, it will be loaded from the drive, otherwise from the SqPack. - private byte DefaultLoadResource(ByteString gamePath, SeFileDescriptor* fileDescriptor, int priority, + private byte DefaultLoadResource(CiByteString gamePath, SeFileDescriptor* fileDescriptor, int priority, bool isSync, ReadOnlySpan additionalData) { if (Utf8GamePath.IsRooted(gamePath)) @@ -265,7 +266,7 @@ public unsafe class ResourceLoader : IDisposable, IService } /// Compute the CRC32 hash for a given path together with potential resource parameters. - private static int ComputeHash(ByteString path, GetResourceParameters* pGetResParams) + private static int ComputeHash(CiByteString path, GetResourceParameters* pGetResParams) { if (pGetResParams == null || !pGetResParams->IsPartialRead) return path.Crc32; @@ -273,11 +274,11 @@ public unsafe class ResourceLoader : IDisposable, IService // When the game requests file only partially, crc32 includes that information, in format of: // path/to/file.ext.hex_offset.hex_size // ex) music/ex4/BGM_EX4_System_Title.scd.381adc.30000 - return ByteString.Join( + return CiByteString.Join( (byte)'.', path, - ByteString.FromStringUnsafe(pGetResParams->SegmentOffset.ToString("x"), true), - ByteString.FromStringUnsafe(pGetResParams->SegmentLength.ToString("x"), true) + CiByteString.FromString(pGetResParams->SegmentOffset.ToString("x"), out var s1, MetaDataComputation.None) ? s1 : CiByteString.Empty, + CiByteString.FromString(pGetResParams->SegmentLength.ToString("x"), out var s2, MetaDataComputation.None) ? s2 : CiByteString.Empty ).Crc32; } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index 0b00452b..8b99dc37 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -39,14 +39,14 @@ public unsafe class ResourceService : IDisposable, IRequiredService } } - public ResourceHandle* GetResource(ResourceCategory category, ResourceType type, ByteString path) + public ResourceHandle* GetResource(ResourceCategory category, ResourceType type, CiByteString path) { var hash = path.Crc32; return GetResourceHandler(true, (ResourceManager*)_resourceManager.ResourceManagerAddress, &category, &type, &hash, path.Path, null, false); } - public SafeResourceHandle GetSafeResource(ResourceCategory category, ResourceType type, ByteString path) + public SafeResourceHandle GetSafeResource(ResourceCategory category, ResourceType type, CiByteString path) => new((CSResourceHandle*)GetResource(category, type, path), false); public void Dispose() @@ -102,7 +102,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService ResourceType* resourceType, int* resourceHash, byte* path, GetResourceParameters* pGetResParams, bool isUnk) { using var performance = _performance.Measure(PerformanceType.GetResourceHandler); - if (!Utf8GamePath.FromPointer(path, out var gamePath)) + if (!Utf8GamePath.FromPointer(path, MetaDataComputation.CiCrc32, out var gamePath)) { Penumbra.Log.Error("[ResourceService] Could not create GamePath from resource path."); return isSync @@ -120,7 +120,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService } /// Call the original GetResource function. - public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, ByteString path, + public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, GetResourceParameters* resourceParameters = null, bool unk = false) => sync ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index f7e6caf0..f2ea2d6c 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -49,7 +49,10 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy public static unsafe List FindMaterials(IEnumerable gameObjects, string materialPath) { - var needle = ByteString.FromString(materialPath.Replace('\\', '/'), out var m, true) ? m : ByteString.Empty; + var needle = CiByteString.FromString(materialPath.Replace('\\', '/'), out var m, + MetaDataComputation.CiCrc32 | MetaDataComputation.Crc32) + ? m + : CiByteString.Empty; var result = new List(Enum.GetValues().Length); foreach (var objectPtr in gameObjects) @@ -83,7 +86,7 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy continue; PathDataHandler.Split(mtrlHandle->ResourceHandle.FileName.AsSpan(), out var path, out _); - var fileName = ByteString.FromSpanUnsafe(path, true); + var fileName = CiByteString.FromSpanUnsafe(path, true); if (fileName == needle) result.Add(new MaterialInfo(index, type, i, j)); } diff --git a/Penumbra/Interop/PathResolving/PathDataHandler.cs b/Penumbra/Interop/PathResolving/PathDataHandler.cs index a8be97c8..9410ff98 100644 --- a/Penumbra/Interop/PathResolving/PathDataHandler.cs +++ b/Penumbra/Interop/PathResolving/PathDataHandler.cs @@ -31,27 +31,27 @@ public static class PathDataHandler /// Create the encoding path for an IMC file. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static FullPath CreateImc(ByteString path, ModCollection collection) + public static FullPath CreateImc(CiByteString path, ModCollection collection) => new($"|{collection.LocalId.Id}_{collection.ImcChangeCounter}_{DiscriminatorString}|{path}"); /// Create the encoding path for a TMB file. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static FullPath CreateTmb(ByteString path, ModCollection collection) + public static FullPath CreateTmb(CiByteString path, ModCollection collection) => CreateBase(path, collection); /// Create the encoding path for an AVFX file. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static FullPath CreateAvfx(ByteString path, ModCollection collection) + public static FullPath CreateAvfx(CiByteString path, ModCollection collection) => CreateBase(path, collection); /// Create the encoding path for a MTRL file. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static FullPath CreateMtrl(ByteString path, ModCollection collection, Utf8GamePath originalPath) + public static FullPath CreateMtrl(CiByteString path, ModCollection collection, Utf8GamePath originalPath) => new($"|{collection.LocalId.Id}_{collection.ChangeCounter}_{originalPath.Path.Crc32:X8}_{DiscriminatorString}|{path}"); /// The base function shared by most file types. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static FullPath CreateBase(ByteString path, ModCollection collection) + private static FullPath CreateBase(CiByteString path, ModCollection collection) => new($"|{collection.LocalId.Id}_{collection.ChangeCounter}_{DiscriminatorString}|{path}"); /// Read an additional data blurb and parse it into usable data for all file types but Materials. diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 49035dc8..67ec4fc3 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -52,7 +52,6 @@ public class PathResolver : IDisposable, IService if (resourceType is ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb) return (null, ResolveData.Invalid); - path = path.ToLower(); return category switch { // Only Interface collection. diff --git a/Penumbra/Interop/PathResolving/PathState.cs b/Penumbra/Interop/PathResolving/PathState.cs index bf9d1e25..60a61408 100644 --- a/Penumbra/Interop/PathResolving/PathState.cs +++ b/Penumbra/Interop/PathResolving/PathState.cs @@ -28,7 +28,7 @@ public sealed class PathState(CollectionResolver collectionResolver, MetaState m _internalResolve.Dispose(); } - public bool Consume(ByteString _, out ResolveData collection) + public bool Consume(CiByteString _, out ResolveData collection) { if (_resolveData.IsValueCreated) { diff --git a/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs b/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs index 56f693e6..2194354a 100644 --- a/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/AvfxPathPreProcessor.cs @@ -11,6 +11,6 @@ public sealed class AvfxPathPreProcessor : IPathPreProcessor public ResourceType Type => ResourceType.Avfx; - public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) + public FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) => nonDefault ? PathDataHandler.CreateAvfx(path, resolveData.ModCollection) : resolved; } diff --git a/Penumbra/Interop/Processing/FilePostProcessService.cs b/Penumbra/Interop/Processing/FilePostProcessService.cs index bba53c94..ecf78c69 100644 --- a/Penumbra/Interop/Processing/FilePostProcessService.cs +++ b/Penumbra/Interop/Processing/FilePostProcessService.cs @@ -10,7 +10,7 @@ namespace Penumbra.Interop.Processing; public interface IFilePostProcessor : IService { public ResourceType Type { get; } - public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData); + public unsafe void PostProcess(ResourceHandle* resource, CiByteString originalGamePath, ReadOnlySpan additionalData); } public unsafe class FilePostProcessService : IRequiredService, IDisposable @@ -30,7 +30,7 @@ public unsafe class FilePostProcessService : IRequiredService, IDisposable _resourceLoader.FileLoaded -= OnFileLoaded; } - private void OnFileLoaded(ResourceHandle* resource, ByteString path, bool returnValue, bool custom, + private void OnFileLoaded(ResourceHandle* resource, CiByteString path, bool returnValue, bool custom, ReadOnlySpan additionalData) { if (_processors.TryGetValue(resource->FileType, out var processor)) diff --git a/Penumbra/Interop/Processing/GamePathPreProcessService.cs b/Penumbra/Interop/Processing/GamePathPreProcessService.cs index 004b7168..65608ba0 100644 --- a/Penumbra/Interop/Processing/GamePathPreProcessService.cs +++ b/Penumbra/Interop/Processing/GamePathPreProcessService.cs @@ -11,7 +11,7 @@ public interface IPathPreProcessor : IService { public ResourceType Type { get; } - public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved); + public FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved); } public class GamePathPreProcessService : IService @@ -24,7 +24,7 @@ public class GamePathPreProcessService : IService } - public (FullPath? Path, ResolveData Data) PreProcess(ResolveData resolveData, ByteString path, bool nonDefault, ResourceType type, + public (FullPath? Path, ResolveData Data) PreProcess(ResolveData resolveData, CiByteString path, bool nonDefault, ResourceType type, FullPath? resolved, Utf8GamePath originalPath) { diff --git a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs index 4a0ebe22..33a3941a 100644 --- a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs +++ b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs @@ -11,7 +11,7 @@ public sealed class ImcFilePostProcessor(CollectionStorage collections) : IFileP public ResourceType Type => ResourceType.Imc; - public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) + public unsafe void PostProcess(ResourceHandle* resource, CiByteString originalGamePath, ReadOnlySpan additionalData) { if (!PathDataHandler.Read(additionalData, out var data) || data.Discriminator != PathDataHandler.Discriminator) return; diff --git a/Penumbra/Interop/Processing/ImcPathPreProcessor.cs b/Penumbra/Interop/Processing/ImcPathPreProcessor.cs index 907d7587..7030dd8d 100644 --- a/Penumbra/Interop/Processing/ImcPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/ImcPathPreProcessor.cs @@ -11,7 +11,7 @@ public sealed class ImcPathPreProcessor : IPathPreProcessor public ResourceType Type => ResourceType.Imc; - public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath originalGamePath, bool _, FullPath? resolved) + public FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath originalGamePath, bool _, FullPath? resolved) => resolveData.ModCollection.MetaCache?.Imc.HasFile(originalGamePath.Path) ?? false ? PathDataHandler.CreateImc(path, resolveData.ModCollection) : resolved; diff --git a/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs b/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs index 02b5d46c..26956845 100644 --- a/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs +++ b/Penumbra/Interop/Processing/MaterialFilePostProcessor.cs @@ -10,7 +10,7 @@ public sealed class MaterialFilePostProcessor //: IFilePostProcessor public ResourceType Type => ResourceType.Mtrl; - public unsafe void PostProcess(ResourceHandle* resource, ByteString originalGamePath, ReadOnlySpan additionalData) + public unsafe void PostProcess(ResourceHandle* resource, CiByteString originalGamePath, ReadOnlySpan additionalData) { if (!PathDataHandler.ReadMtrl(additionalData, out var data)) return; diff --git a/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs b/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs index 8fb2400b..603781ed 100644 --- a/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/MtrlPathPreProcessor.cs @@ -11,6 +11,6 @@ public sealed class MtrlPathPreProcessor : IPathPreProcessor public ResourceType Type => ResourceType.Mtrl; - public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved) + public FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved) => nonDefault ? PathDataHandler.CreateMtrl(path, resolveData.ModCollection, originalGamePath) : resolved; } diff --git a/Penumbra/Interop/Processing/TmbPathPreProcessor.cs b/Penumbra/Interop/Processing/TmbPathPreProcessor.cs index dd887819..0a7aa16f 100644 --- a/Penumbra/Interop/Processing/TmbPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/TmbPathPreProcessor.cs @@ -11,6 +11,6 @@ public sealed class TmbPathPreProcessor : IPathPreProcessor public ResourceType Type => ResourceType.Tmb; - public FullPath? PreProcess(ResolveData resolveData, ByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) + public FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) => nonDefault ? PathDataHandler.CreateTmb(path, resolveData.ModCollection) : resolved; } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 678dd8a9..85b3284a 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -3,7 +3,6 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; -using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.String; @@ -99,7 +98,7 @@ internal partial record ResolveContext Span pathBuffer = stackalloc byte[260]; pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); - return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; + return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; } [SkipLocalsInit] @@ -133,7 +132,7 @@ internal partial record ResolveContext if (weaponPosition >= 0) WriteZeroPaddedNumber(pathBuffer[(weaponPosition + 9)..(weaponPosition + 13)], mirroredSetId); - return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; + return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; } } @@ -148,7 +147,7 @@ internal partial record ResolveContext Span pathBuffer = stackalloc byte[260]; pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); - return Utf8GamePath.FromSpan(pathBuffer, out var path) ? path.Clone() : Utf8GamePath.Empty; + return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; } private unsafe byte ResolveMaterialVariant(ResourceHandle* imc, Variant variant) @@ -196,7 +195,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveMaterialPathNative(byte* mtrlFileName) { - ByteString? path; + CiByteString? path; try { path = CharacterBase->ResolveMtrlPathAsByteString(SlotIndex, mtrlFileName); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index acb320d4..3fc1ae3c 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -45,25 +45,25 @@ internal unsafe partial record ResolveContext( public CharacterBase* CharacterBase => CharacterBasePointer.Value; - private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); + private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); private ModelType ModelType => CharacterBase->GetModelType(); - private ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, ByteString gamePath) + private ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, CiByteString gamePath) { if (resourceHandle == null) return null; if (gamePath.IsEmpty) return null; - if (!Utf8GamePath.FromByteString(ByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path, false)) + if (!Utf8GamePath.FromByteString(CiByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path)) return null; return GetOrCreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); } [SkipLocalsInit] - private ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, ByteString gamePath, bool dx11) + private ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, CiByteString gamePath, bool dx11) { if (resourceHandle == null) return null; @@ -81,7 +81,7 @@ internal unsafe partial record ResolveContext( prefixed[lastDirectorySeparator + 2] = (byte)'-'; gamePath.Span[(lastDirectorySeparator + 1)..].CopyTo(prefixed[(lastDirectorySeparator + 3)..]); - if (!Utf8GamePath.FromSpan(prefixed[..(gamePath.Length + 2)], out var tmp)) + if (!Utf8GamePath.FromSpan(prefixed[..(gamePath.Length + 2)], MetaDataComputation.None, out var tmp)) return null; path = tmp.Clone(); @@ -118,11 +118,11 @@ internal unsafe partial record ResolveContext( throw new ArgumentNullException(nameof(resourceHandle)); var fileName = (ReadOnlySpan)resourceHandle->FileName.AsSpan(); - var additionalData = ByteString.Empty; + var additionalData = CiByteString.Empty; if (PathDataHandler.Split(fileName, out fileName, out var data)) - additionalData = ByteString.FromSpanUnsafe(data, false).Clone(); + additionalData = CiByteString.FromSpanUnsafe(data, false).Clone(); - var fullPath = Utf8GamePath.FromSpan(fileName, out var p) ? new FullPath(p.Clone()) : FullPath.Empty; + var fullPath = Utf8GamePath.FromSpan(fileName, MetaDataComputation.None, out var p) ? new FullPath(p.Clone()) : FullPath.Empty; var node = new ResourceNode(type, objectAddress, (nint)resourceHandle, GetResourceHandleLength(resourceHandle), this) { @@ -222,7 +222,7 @@ internal unsafe partial record ResolveContext( return cached; var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); - var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new ByteString(resource->ShpkName)); + var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new CiByteString(resource->ShpkName)); if (shpkNode != null) { if (Global.WithUiData) @@ -236,7 +236,7 @@ internal unsafe partial record ResolveContext( var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->TextureCount; i++) { - var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new ByteString(resource->TexturePath(i)), + var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new CiByteString(resource->TexturePath(i)), resource->Textures[i].IsDX11); if (texNode == null) continue; diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 9c911791..de43a874 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -15,7 +15,7 @@ public class ResourceNode : ICloneable public readonly nint ResourceHandle; public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; - public ByteString AdditionalData; + public CiByteString AdditionalData; public readonly ulong Length; public readonly List Children; internal ResolveContext? ResolveContext; @@ -26,9 +26,9 @@ public class ResourceNode : ICloneable set { if (value.IsEmpty) - PossibleGamePaths = Array.Empty(); + PossibleGamePaths = []; else - PossibleGamePaths = new[] { value }; + PossibleGamePaths = [value]; } } @@ -40,8 +40,8 @@ public class ResourceNode : ICloneable Type = type; ObjectAddress = objectAddress; ResourceHandle = resourceHandle; - PossibleGamePaths = Array.Empty(); - AdditionalData = ByteString.Empty; + PossibleGamePaths = []; + AdditionalData = CiByteString.Empty; Length = length; Children = new List(); ResolveContext = resolveContext; @@ -90,7 +90,7 @@ public class ResourceNode : ICloneable public readonly record struct UiData(string? Name, ChangedItemIcon Icon) { - public readonly UiData PrependName(string prefix) + public UiData PrependName(string prefix) => Name == null ? this : new UiData(prefix + Name, Icon); } } diff --git a/Penumbra/Interop/Services/DecalReverter.cs b/Penumbra/Interop/Services/DecalReverter.cs index 21b51fd2..3d5d7845 100644 --- a/Penumbra/Interop/Services/DecalReverter.cs +++ b/Penumbra/Interop/Services/DecalReverter.cs @@ -2,6 +2,7 @@ using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Interop.Hooks.ResourceLoading; +using Penumbra.String; using Penumbra.String.Classes; namespace Penumbra.Interop.Services; @@ -9,10 +10,10 @@ namespace Penumbra.Interop.Services; public sealed unsafe class DecalReverter : IDisposable { public static readonly Utf8GamePath DecalPath = - Utf8GamePath.FromSpan("chara/common/texture/decal_equip/_stigma.tex"u8, out var p) ? p : Utf8GamePath.Empty; + Utf8GamePath.FromSpan("chara/common/texture/decal_equip/_stigma.tex"u8, MetaDataComputation.All, out var p) ? p : Utf8GamePath.Empty; public static readonly Utf8GamePath TransparentPath = - Utf8GamePath.FromSpan("chara/common/texture/transparent.tex"u8, out var p) ? p : Utf8GamePath.Empty; + Utf8GamePath.FromSpan("chara/common/texture/transparent.tex"u8, MetaDataComputation.All, out var p) ? p : Utf8GamePath.Empty; private readonly CharacterUtility _utility; private readonly Structs.TextureResourceHandle* _decal; diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 6e428f25..65550563 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -47,11 +47,11 @@ public unsafe struct ResourceHandle public ulong DataLength; } - public readonly ByteString FileName() + public readonly CiByteString FileName() => CsHandle.FileName.AsByteString(); public readonly bool GamePath(out Utf8GamePath path) - => Utf8GamePath.FromSpan(CsHandle.FileName.AsSpan(), out path); + => Utf8GamePath.FromSpan(CsHandle.FileName.AsSpan(), MetaDataComputation.All, out path); [FieldOffset(0x00)] public CsHandle.ResourceHandle CsHandle; diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index fc8b1c3d..9dd9a96d 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -6,48 +6,48 @@ namespace Penumbra.Interop.Structs; internal static class StructExtensions { - public static unsafe ByteString AsByteString(in this StdString str) - => ByteString.FromSpanUnsafe(str.AsSpan(), true); + public static CiByteString AsByteString(in this StdString str) + => CiByteString.FromSpanUnsafe(str.AsSpan(), true); - public static ByteString ResolveEidPathAsByteString(ref this CharacterBase character) + public static CiByteString ResolveEidPathAsByteString(ref this CharacterBase character) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveEidPath(pathBuffer)); } - public static ByteString ResolveImcPathAsByteString(ref this CharacterBase character, uint slotIndex) + public static CiByteString ResolveImcPathAsByteString(ref this CharacterBase character, uint slotIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveImcPath(pathBuffer, slotIndex)); } - public static ByteString ResolveMdlPathAsByteString(ref this CharacterBase character, uint slotIndex) + public static CiByteString ResolveMdlPathAsByteString(ref this CharacterBase character, uint slotIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveMdlPath(pathBuffer, slotIndex)); } - public static unsafe ByteString ResolveMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex, byte* mtrlFileName) + public static unsafe CiByteString ResolveMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex, byte* mtrlFileName) { var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex, mtrlFileName)); } - public static ByteString ResolveSklbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) + public static CiByteString ResolveSklbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveSklbPath(pathBuffer, partialSkeletonIndex)); } - public static ByteString ResolveSkpPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) + public static CiByteString ResolveSkpPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; return ToOwnedByteString(character.ResolveSkpPath(pathBuffer, partialSkeletonIndex)); } - private static unsafe ByteString ToOwnedByteString(byte* str) - => str == null ? ByteString.Empty : new ByteString(str).Clone(); + private static unsafe CiByteString ToOwnedByteString(byte* str) + => str == null ? CiByteString.Empty : new CiByteString(str).Clone(); - private static ByteString ToOwnedByteString(ReadOnlySpan str) - => str.Length == 0 ? ByteString.Empty : ByteString.FromSpanUnsafe(str, true).Clone(); + private static CiByteString ToOwnedByteString(ReadOnlySpan str) + => str.Length == 0 ? CiByteString.Empty : CiByteString.FromSpanUnsafe(str, true).Clone(); } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 546f5f5c..0f4972e3 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -270,7 +270,7 @@ public partial class ModCreator( public MultiSubMod CreateSubMod(DirectoryInfo baseFolder, DirectoryInfo optionFolder, OptionList option, ModPriority priority) { var list = optionFolder.EnumerateNonHiddenFiles() - .Select(f => (Utf8GamePath.FromFile(f, optionFolder, out var gamePath, true), gamePath, new FullPath(f))) + .Select(f => (Utf8GamePath.FromFile(f, optionFolder, out var gamePath), gamePath, new FullPath(f))) .Where(t => t.Item1); var mod = MultiSubMod.WithoutGroup(option.Name, option.Description, priority); @@ -291,7 +291,7 @@ public partial class ModCreator( ReloadMod(mod, false, out _); foreach (var file in mod.FindUnusedFiles()) { - if (Utf8GamePath.FromFile(new FileInfo(file.FullName), directory, out var gamePath, true)) + if (Utf8GamePath.FromFile(new FileInfo(file.FullName), directory, out var gamePath)) mod.Default.Files.TryAdd(gamePath, file); } diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index a8c37369..f6b1be96 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -52,7 +52,7 @@ public static class SubMod if (files != null) foreach (var property in files.Properties()) { - if (Utf8GamePath.FromString(property.Name, out var p, true)) + if (Utf8GamePath.FromString(property.Name, out var p)) data.Files.TryAdd(p, new FullPath(basePath, property.Value.ToObject())); } @@ -60,7 +60,7 @@ public static class SubMod if (swaps != null) foreach (var property in swaps.Properties()) { - if (Utf8GamePath.FromString(property.Name, out var p, true)) + if (Utf8GamePath.FromString(property.Name, out var p)) data.FileSwaps.TryAdd(p, new FullPath(property.Value.ToObject()!)); } diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index 2c6ac170..c783e17f 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -6,6 +6,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Compression; using OtterGui.Raii; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.GameData.Files; using Penumbra.Mods.Editor; @@ -98,7 +99,7 @@ public class FileEditor( _inInput = ImGui.IsItemActive(); if (ImGui.IsItemDeactivatedAfterEdit() && _defaultPath.Length > 0) { - _isDefaultPathUtf8Valid = Utf8GamePath.FromString(_defaultPath, out _defaultPathUtf8, true); + _isDefaultPathUtf8Valid = Utf8GamePath.FromString(_defaultPath, out _defaultPathUtf8); _quickImport = null; fileDialog.Reset(); try @@ -306,7 +307,7 @@ public class FileEditor( foreach (var (option, gamePath) in file.SubModUsage) { ImGui.TableNextColumn(); - UiHelpers.Text(gamePath.Path); + ImUtf8.Text(gamePath.Path.Span); ImGui.TableNextColumn(); using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ItemId.Value()); ImGui.TextUnformatted(option.GetFullName()); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 107c56e6..ffa7473d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -209,7 +209,7 @@ public partial class ModEditWindow if (ImGui.IsItemDeactivatedAfterEdit()) { - if (Utf8GamePath.FromString(_gamePathEdit, out var path, false)) + if (Utf8GamePath.FromString(_gamePathEdit, out var path)) _editor.FileEditor.SetGamePath(_editor.Option!, _fileIdx, _pathIdx, path); _fileIdx = -1; @@ -217,7 +217,7 @@ public partial class ModEditWindow } else if (_fileIdx == i && _pathIdx == j - && (!Utf8GamePath.FromString(_gamePathEdit, out var path, false) + && (!Utf8GamePath.FromString(_gamePathEdit, out var path) || !path.IsEmpty && !path.Equals(gamePath) && !_editor.FileEditor.CanAddGamePath(path))) { ImGui.SameLine(); @@ -241,7 +241,7 @@ public partial class ModEditWindow if (ImGui.IsItemDeactivatedAfterEdit()) { - if (Utf8GamePath.FromString(_gamePathEdit, out var path, false) && !path.IsEmpty) + if (Utf8GamePath.FromString(_gamePathEdit, out var path) && !path.IsEmpty) _editor.FileEditor.SetGamePath(_editor.Option!, _fileIdx, _pathIdx, path); _fileIdx = -1; @@ -249,7 +249,7 @@ public partial class ModEditWindow } else if (_fileIdx == i && _pathIdx == -1 - && (!Utf8GamePath.FromString(_gamePathEdit, out var path, false) + && (!Utf8GamePath.FromString(_gamePathEdit, out var path) || !path.IsEmpty && !_editor.FileEditor.CanAddGamePath(path))) { ImGui.SameLine(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index cd7aca9d..a50599a1 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -25,7 +25,7 @@ public partial class ModEditWindow { private const int ShpkPrefixLength = 16; - private static readonly ByteString ShpkPrefix = ByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); + private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); private readonly ModEditWindow _edit; public readonly MtrlFile Mtrl; @@ -77,7 +77,7 @@ public partial class ModEditWindow public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) { defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); - if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath, true)) + if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) return FullPath.Empty; return _edit.FindBestMatch(defaultGamePath); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index b05bcac2..b436448f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -271,7 +271,7 @@ public partial class ModEditWindow private byte[]? ReadFile(string path) { // TODO: if cross-collection lookups are turned off, this conversion can be skipped - if (!Utf8GamePath.FromString(path, out var utf8Path, true)) + if (!Utf8GamePath.FromString(path, out var utf8Path)) throw new Exception($"Resolved path {path} could not be converted to a game path."); var resolvedPath = _edit._activeCollections.Current.ResolvePath(utf8Path) ?? new FullPath(utf8Path); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index a22c10ad..017478a7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -16,7 +16,7 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private static readonly ByteString DisassemblyLabel = ByteString.FromSpanUnsafe("##disassembly"u8, true, true, true); + private static readonly CiByteString DisassemblyLabel = CiByteString.FromSpanUnsafe("##disassembly"u8, true, true, true); private readonly FileEditor _shaderPackageTab; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index b0e9af7f..0d3dce8c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -562,7 +562,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService return new FullPath(path); } - private HashSet FindPathsStartingWith(ByteString prefix) + private HashSet FindPathsStartingWith(CiByteString prefix) { var ret = new HashSet(); diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 7315f136..c47414b9 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -84,7 +84,8 @@ public class ResourceTreeViewer using (var c = ImRaii.PushColor(ImGuiCol.Text, CategoryColor(category).Value())) { - var isOpen = ImGui.CollapsingHeader($"{(_incognito.IncognitoMode ? tree.AnonymizedName : tree.Name)}###{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); + var isOpen = ImGui.CollapsingHeader($"{(_incognito.IncognitoMode ? tree.AnonymizedName : tree.Name)}###{index}", + index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); if (debugMode) { using var _ = ImRaii.PushFont(UiBuilder.MonoFont); @@ -149,7 +150,9 @@ public class ResourceTreeViewer var filterChanged = false; ImGui.SetCursorPosY(ImGui.GetCursorPosY() - yOffset); using (ImRaii.Child("##typeFilter", new Vector2(ImGui.GetContentRegionAvail().X, ChangedItemDrawer.TypeFilterIconSize.Y))) + { filterChanged |= _changedItemDrawer.DrawTypeFilter(ref _typeFilter); + } var fieldWidth = (ImGui.GetContentRegionAvail().X - checkSpacing * 2.0f - ImGui.GetFrameHeightWithSpacing()) / 2.0f; ImGui.SetNextItemWidth(fieldWidth); @@ -181,7 +184,8 @@ public class ResourceTreeViewer } }); - private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) + private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash, + ChangedItemDrawer.ChangedItemIcon parentFilterIcon) { var debugMode = _config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); @@ -196,9 +200,9 @@ public class ResourceTreeViewer return true; return node.Name != null && node.Name.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) - || node.FullPath.FullName.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) - || node.FullPath.InternalName.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) - || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); + || node.FullPath.FullName.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || node.FullPath.InternalName.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); } NodeVisibility CalculateNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) @@ -226,10 +230,11 @@ public class ResourceTreeViewer visibility = CalculateNodeVisibility(nodePathHash, node, parentFilterIcon); _filterCache.Add(nodePathHash, visibility); } + return visibility; } - string GetAdditionalDataSuffix(ByteString data) + string GetAdditionalDataSuffix(CiByteString data) => !debugMode || data.IsEmpty ? string.Empty : $"\n\nAdditional Data: {data}"; foreach (var (resourceNode, index) in resourceNodes.WithIndex()) @@ -252,8 +257,9 @@ public class ResourceTreeViewer var unfolded = _unfolded.Contains(nodePathHash); using (var indent = ImRaii.PushIndent(level)) { - var hasVisibleChildren = resourceNode.Children.Any(child => GetNodeVisibility(unchecked(nodePathHash * 31 + child.ResourceHandle), child, filterIcon) != NodeVisibility.Hidden); - var unfoldable = hasVisibleChildren && visibility != NodeVisibility.DescendentsOnly; + var hasVisibleChildren = resourceNode.Children.Any(child + => GetNodeVisibility(unchecked(nodePathHash * 31 + child.ResourceHandle), child, filterIcon) != NodeVisibility.Hidden); + var unfoldable = hasVisibleChildren && visibility != NodeVisibility.DescendentsOnly; if (unfoldable) { using var font = ImRaii.PushFont(UiBuilder.IconFont); @@ -317,13 +323,15 @@ public class ResourceTreeViewer ImGui.Selectable(resourceNode.FullPath.ToPath(), false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); if (ImGui.IsItemClicked()) ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); - ImGuiUtil.HoverTooltip($"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); + ImGuiUtil.HoverTooltip( + $"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } else { ImGui.Selectable("(unavailable)", false, ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); - ImGuiUtil.HoverTooltip($"The actual path to this file is unavailable.\nIt may be managed by another plug-in.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); + ImGuiUtil.HoverTooltip( + $"The actual path to this file is unavailable.\nIt may be managed by another plug-in.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } mutedColor.Dispose(); diff --git a/Penumbra/UI/Knowledge/KnowledgeWindow.cs b/Penumbra/UI/Knowledge/KnowledgeWindow.cs index b14949de..f831975b 100644 --- a/Penumbra/UI/Knowledge/KnowledgeWindow.cs +++ b/Penumbra/UI/Knowledge/KnowledgeWindow.cs @@ -1,7 +1,5 @@ -using System.Text.Unicode; using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; -using Dalamud.Memory; using ImGuiNET; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index 0fc51f26..b69d9944 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -18,8 +18,8 @@ public enum RecordType : byte internal unsafe struct Record { public DateTime Time; - public ByteString Path; - public ByteString OriginalPath; + public CiByteString Path; + public CiByteString OriginalPath; public string AssociatedGameObject; public ModCollection? Collection; public ResourceHandle* Handle; @@ -32,12 +32,12 @@ internal unsafe struct Record public OptionalBool CustomLoad; public LoadState LoadState; - public static Record CreateRequest(ByteString path, bool sync) + public static Record CreateRequest(CiByteString path, bool sync) => new() { Time = DateTime.UtcNow, Path = path.IsOwned ? path : path.Clone(), - OriginalPath = ByteString.Empty, + OriginalPath = CiByteString.Empty, Collection = null, Handle = null, ResourceType = ResourceExtensions.Type(path).ToFlag(), @@ -51,7 +51,7 @@ internal unsafe struct Record LoadState = LoadState.None, }; - public static Record CreateDefaultLoad(ByteString path, ResourceHandle* handle, ModCollection collection, string associatedGameObject) + public static Record CreateDefaultLoad(CiByteString path, ResourceHandle* handle, ModCollection collection, string associatedGameObject) { path = path.IsOwned ? path : path.Clone(); return new Record @@ -73,7 +73,7 @@ internal unsafe struct Record }; } - public static Record CreateLoad(ByteString path, ByteString originalPath, ResourceHandle* handle, ModCollection collection, + public static Record CreateLoad(CiByteString path, CiByteString originalPath, ResourceHandle* handle, ModCollection collection, string associatedGameObject) => new() { @@ -100,7 +100,7 @@ internal unsafe struct Record { Time = DateTime.UtcNow, Path = path, - OriginalPath = ByteString.Empty, + OriginalPath = CiByteString.Empty, Collection = null, Handle = handle, ResourceType = handle->FileType.ToFlag(), @@ -115,12 +115,12 @@ internal unsafe struct Record }; } - public static Record CreateFileLoad(ByteString path, ResourceHandle* handle, bool ret, bool custom) + public static Record CreateFileLoad(CiByteString path, ResourceHandle* handle, bool ret, bool custom) => new() { Time = DateTime.UtcNow, Path = path.IsOwned ? path : path.Clone(), - OriginalPath = ByteString.Empty, + OriginalPath = CiByteString.Empty, Collection = null, Handle = handle, ResourceType = handle->FileType.ToFlag(), diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 14d69489..6f1ce9cf 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -163,7 +163,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService } } - private bool FilterMatch(ByteString path, out string match) + private bool FilterMatch(CiByteString path, out string match) { match = path.ToString(); return _logFilter.Length == 0 || (_logRegex?.IsMatch(match) ?? false) || match.Contains(_logFilter, StringComparison.OrdinalIgnoreCase); @@ -255,7 +255,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _newRecords.Enqueue(record); } - private unsafe void OnFileLoaded(ResourceHandle* resource, ByteString path, bool success, bool custom, ReadOnlySpan _) + private unsafe void OnFileLoaded(ResourceHandle* resource, CiByteString path, bool success, bool custom, ReadOnlySpan _) { if (_ephemeral.EnableResourceLogging && FilterMatch(path, out var match)) Penumbra.Log.Information( diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index b47574d0..33e301ae 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -50,7 +50,7 @@ internal sealed class ResourceWatcherTable : Table => DrawByteString(item.Path, 280 * UiHelpers.Scale); } - private static unsafe void DrawByteString(ByteString path, float length) + private static unsafe void DrawByteString(CiByteString path, float length) { Vector2 vec; ImGuiNative.igCalcTextSize(&vec, path.Path, path.Path + path.Length, 0, 0); @@ -61,7 +61,7 @@ internal sealed class ResourceWatcherTable : Table else { var fileName = path.LastIndexOf((byte)'/'); - ByteString shortPath; + CiByteString shortPath; if (fileName != -1) { using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(2 * UiHelpers.Scale)); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 4966dd64..a1e9da03 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -15,6 +15,7 @@ using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections.Manager; @@ -402,6 +403,33 @@ public class DebugTab : Window, ITab, IUiService } } } + + using (var tree = ImUtf8.TreeNode("String Memory"u8)) + { + if (tree) + { + using (ImUtf8.Group()) + { + ImUtf8.Text("Currently Allocated Strings"u8); + ImUtf8.Text("Total Allocated Strings"u8); + ImUtf8.Text("Free'd Allocated Strings"u8); + ImUtf8.Text("Currently Allocated Bytes"u8); + ImUtf8.Text("Total Allocated Bytes"u8); + ImUtf8.Text("Free'd Allocated Bytes"u8); + } + + ImGui.SameLine(); + using (ImUtf8.Group()) + { + ImUtf8.Text($"{PenumbraStringMemory.CurrentStrings}"); + ImUtf8.Text($"{PenumbraStringMemory.AllocatedStrings}"); + ImUtf8.Text($"{PenumbraStringMemory.FreedStrings}"); + ImUtf8.Text($"{PenumbraStringMemory.CurrentBytes}"); + ImUtf8.Text($"{PenumbraStringMemory.AllocatedBytes}"); + ImUtf8.Text($"{PenumbraStringMemory.FreedBytes}"); + } + } + } } private void DrawPerformanceTab() diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index e0cab43f..ecf9a886 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -4,6 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Cache; @@ -134,12 +135,12 @@ public class EffectiveTab(CollectionManager collectionManager, CollectionSelectH { var (path, name) = pair; ImGui.TableNextColumn(); - UiHelpers.CopyOnClickSelectable(path.Path); + ImUtf8.CopyOnClickSelectable(path.Path.Span); ImGui.TableNextColumn(); ImGuiUtil.PrintIcon(FontAwesomeIcon.LongArrowAltLeft); ImGui.TableNextColumn(); - UiHelpers.CopyOnClickSelectable(name.Path.InternalName); + ImUtf8.CopyOnClickSelectable(name.Path.InternalName.Span); ImGuiUtil.HoverTooltip($"\nChanged by {name.Mod.Name}."); } From 4b9870f09089d58e9171fa39511f93e7c8c9cbc0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 31 Jul 2024 23:09:37 +0200 Subject: [PATCH 0811/1381] Fix some OtterGui changes. --- OtterGui | 2 +- Penumbra.GameData | 2 +- .../ModEditWindow.Materials.MtrlTab.cs | 2 +- .../UI/ModsTab/Groups/ImcModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/ImcManipulationDrawer.cs | 14 -------------- Penumbra/UI/Tabs/ResourceTab.cs | 4 ++-- 6 files changed, 6 insertions(+), 20 deletions(-) delete mode 100644 Penumbra/UI/ModsTab/ImcManipulationDrawer.cs diff --git a/OtterGui b/OtterGui index 33ffd7cb..b0464b7f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 33ffd7cba3e487e98e55adca1677354078089943 +Subproject commit b0464b7f215a0db1393e600968c6666307a3ae05 diff --git a/Penumbra.GameData b/Penumbra.GameData index d8ebd63c..75582ece 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d8ebd63cec1ac12ea547fd37b6c32bdf9b3f57d1 +Subproject commit 75582ece58e6ee311074ff4ecaa68b804677878c diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index a50599a1..29fd7531 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -405,7 +405,7 @@ public partial class ModEditWindow } var fcGroup = FindOrAddGroup(Constants, "Further Constants"); - foreach (var (start, end) in handledElements.Ranges(true)) + foreach (var (start, end) in handledElements.Ranges(complement:true)) { if ((shpkConstant.ByteOffset & 0x3) == 0) { diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 5d10febd..bbb5e54e 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -140,7 +140,7 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr var value = (mask & (1 << i)) != 0; using (ImRaii.Disabled(!cache.CanChange(i))) { - if (ImUtf8.Checkbox(TerminatedByteString.Empty, ref value)) + if (ImUtf8.Checkbox(""u8, ref value)) { if (data is ImcModGroup g) editor.ChangeDefaultAttribute(g, cache, i, value); diff --git a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs b/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs deleted file mode 100644 index 1291f568..00000000 --- a/Penumbra/UI/ModsTab/ImcManipulationDrawer.cs +++ /dev/null @@ -1,14 +0,0 @@ -using ImGuiNET; -using OtterGui.Raii; -using OtterGui.Text; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; -using Penumbra.Meta.Manipulations; -using Penumbra.UI.Classes; - -namespace Penumbra.UI.ModsTab; - -public static class ImcManipulationDrawer -{ - -} diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index a4dbba2f..c54e3433 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -81,7 +81,7 @@ public class ResourceTab(Configuration config, ResourceManagerService resourceMa return; var address = $"0x{(ulong)r:X}"; - ImGuiUtil.TextNextColumn($"0x{hash:X8}"); + ImGuiUtil.DrawTableColumn($"0x{hash:X8}"); ImGui.TableNextColumn(); ImGuiUtil.CopyOnClickSelectable(address); @@ -101,7 +101,7 @@ public class ResourceTab(Configuration config, ResourceManagerService resourceMa ImGuiUtil.HoverTooltip("Click to copy byte-wise file data to clipboard, if any."); - ImGuiUtil.TextNextColumn(r->RefCount.ToString()); + ImGuiUtil.DrawTableColumn(r->RefCount.ToString()); }); } From 67a220f821afac69aeff24bc8e49ec7cc3dcb1b1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 31 Jul 2024 23:24:59 +0200 Subject: [PATCH 0812/1381] Add context menu to change mod state from Collections tab. --- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 86 ++++++++++++++----- 1 file changed, 66 insertions(+), 20 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs index 9f37f847..b7648428 100644 --- a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -11,9 +12,16 @@ using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; -public class ModPanelCollectionsTab(CollectionStorage storage, ModFileSystemSelector selector) : ITab, IUiService +public class ModPanelCollectionsTab(CollectionManager manager, ModFileSystemSelector selector) : ITab, IUiService { - private readonly List<(ModCollection, ModCollection, uint, string)> _cache = []; + private enum ModState + { + Enabled, + Disabled, + Unconfigured, + } + + private readonly List<(ModCollection, ModCollection, uint, ModState)> _cache = []; public ReadOnlySpan Label => "Collections"u8; @@ -23,45 +31,83 @@ public class ModPanelCollectionsTab(CollectionStorage storage, ModFileSystemSele var (direct, inherited) = CountUsage(selector.Selected!); ImGui.NewLine(); if (direct == 1) - ImGui.TextUnformatted("This Mod is directly configured in 1 collection."); + ImUtf8.Text("This Mod is directly configured in 1 collection."u8); else if (direct == 0) - ImGuiUtil.TextColored(Colors.RegexWarningBorder, "This mod is entirely unused."); + ImUtf8.Text("This mod is entirely unused."u8, Colors.RegexWarningBorder); else - ImGui.TextUnformatted($"This Mod is directly configured in {direct} collections."); + ImUtf8.Text($"This Mod is directly configured in {direct} collections."); if (inherited > 0) - ImGui.TextUnformatted( - $"It is also implicitly used in {inherited} {(inherited == 1 ? "collection" : "collections")} through inheritance."); + ImUtf8.Text($"It is also implicitly used in {inherited} {(inherited == 1 ? "collection" : "collections")} through inheritance."); ImGui.NewLine(); ImGui.Separator(); ImGui.NewLine(); - using var table = ImRaii.Table("##modCollections", 3, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##modCollections"u8, 3, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); if (!table) return; - var size = ImGui.CalcTextSize("Unconfigured").X + 20 * ImGuiHelpers.GlobalScale; + var size = ImUtf8.CalcTextSize(ToText(ModState.Unconfigured)).X + 20 * ImGuiHelpers.GlobalScale; var collectionSize = 200 * ImGuiHelpers.GlobalScale; ImGui.TableSetupColumn("Collection", ImGuiTableColumnFlags.WidthFixed, collectionSize); ImGui.TableSetupColumn("State", ImGuiTableColumnFlags.WidthFixed, size); ImGui.TableSetupColumn("Inherited From", ImGuiTableColumnFlags.WidthFixed, collectionSize); ImGui.TableHeadersRow(); - foreach (var (collection, parent, color, text) in _cache) + foreach (var ((collection, parent, color, state), idx) in _cache.WithIndex()) { - ImGui.TableNextColumn(); - ImGui.TextUnformatted(collection.Name); + using var id = ImUtf8.PushId(idx); + ImUtf8.DrawTableColumn(collection.Name); ImGui.TableNextColumn(); - using (var c = ImRaii.PushColor(ImGuiCol.Text, color)) + ImUtf8.Text(ToText(state), color); + + using (var context = ImUtf8.PopupContextItem("Context"u8, ImGuiPopupFlags.MouseButtonRight)) { - ImGui.TextUnformatted(text); + if (context) + { + ImUtf8.Text(collection.Name); + ImGui.Separator(); + using (ImRaii.Disabled(state is ModState.Enabled && parent == collection)) + { + if (ImUtf8.MenuItem("Enable"u8)) + { + if (parent != collection) + manager.Editor.SetModInheritance(collection, selector.Selected!, false); + manager.Editor.SetModState(collection, selector.Selected!, true); + } + } + + using (ImRaii.Disabled(state is ModState.Disabled && parent == collection)) + { + if (ImUtf8.MenuItem("Disable"u8)) + { + if (parent != collection) + manager.Editor.SetModInheritance(collection, selector.Selected!, false); + manager.Editor.SetModState(collection, selector.Selected!, false); + } + } + + using (ImRaii.Disabled(parent != collection)) + { + if (ImUtf8.MenuItem("Inherit"u8)) + manager.Editor.SetModInheritance(collection, selector.Selected!, true); + } + } } - ImGui.TableNextColumn(); - ImGui.TextUnformatted(parent == collection ? string.Empty : parent.Name); + ImUtf8.DrawTableColumn(parent == collection ? string.Empty : parent.Name); } } + private static ReadOnlySpan ToText(ModState state) + => state switch + { + ModState.Unconfigured => "Unconfigured"u8, + ModState.Enabled => "Enabled"u8, + ModState.Disabled => "Disabled"u8, + _ => "Unknown"u8, + }; + private (int Direct, int Inherited) CountUsage(Mod mod) { _cache.Clear(); @@ -72,14 +118,14 @@ public class ModPanelCollectionsTab(CollectionStorage storage, ModFileSystemSele var disInherited = ColorId.InheritedDisabledMod.Value(); var directCount = 0; var inheritedCount = 0; - foreach (var collection in storage) + foreach (var collection in manager.Storage) { var (settings, parent) = collection[mod.Index]; var (color, text) = settings == null - ? (undefined, "Unconfigured") + ? (undefined, ModState.Unconfigured) : settings.Enabled - ? (parent == collection ? enabled : inherited, "Enabled") - : (parent == collection ? disabled : disInherited, "Disabled"); + ? (parent == collection ? enabled : inherited, ModState.Enabled) + : (parent == collection ? disabled : disInherited, ModState.Disabled); _cache.Add((collection, parent, color, text)); if (color == enabled) From 9e15865a99fd78240943f6d11bd784c2c122ca1a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 16:37:31 +0200 Subject: [PATCH 0813/1381] Fix some further issues with empty byte strings. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index b0464b7f..2b79faac 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit b0464b7f215a0db1393e600968c6666307a3ae05 +Subproject commit 2b79faacff30a31e9ad4b0a3c5d57ffd6e34cfa4 From a308fb9f779acf939191cf3c10c8468a440d7ba9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 16:40:37 +0200 Subject: [PATCH 0814/1381] Allow hook overrides. --- .../Animation/ApricotListenerSoundPlay.cs | 2 +- .../Animation/CharacterBaseLoadAnimation.cs | 3 +- Penumbra/Interop/Hooks/Animation/Dismount.cs | 2 +- .../Interop/Hooks/Animation/LoadAreaVfx.cs | 6 +- .../Hooks/Animation/LoadCharacterSound.cs | 2 +- .../Hooks/Animation/LoadCharacterVfx.cs | 2 +- .../Hooks/Animation/LoadTimelineResources.cs | 2 +- .../Interop/Hooks/Animation/PlayFootstep.cs | 2 +- .../Hooks/Animation/ScheduleClipUpdate.cs | 2 +- .../Interop/Hooks/Animation/SomeActionLoad.cs | 2 +- .../Hooks/Animation/SomeMountAnimation.cs | 2 +- .../Interop/Hooks/Animation/SomePapLoad.cs | 2 +- .../Hooks/Animation/SomeParasolAnimation.cs | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 144 ++++++++++++++++-- .../Interop/Hooks/Meta/CalculateHeight.cs | 2 +- .../Interop/Hooks/Meta/ChangeCustomize.cs | 2 +- .../Interop/Hooks/Meta/EqdpAccessoryHook.cs | 6 +- Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs | 5 +- Penumbra/Interop/Hooks/Meta/EqpHook.cs | 6 +- Penumbra/Interop/Hooks/Meta/EstHook.cs | 5 +- Penumbra/Interop/Hooks/Meta/GmpHook.cs | 6 +- .../Interop/Hooks/Meta/ModelLoadComplete.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspBustHook.cs | 10 +- Penumbra/Interop/Hooks/Meta/RspHeightHook.cs | 9 +- .../Interop/Hooks/Meta/RspSetupCharacter.cs | 2 +- Penumbra/Interop/Hooks/Meta/RspTailHook.cs | 10 +- Penumbra/Interop/Hooks/Meta/SetupVisor.cs | 2 +- Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 2 +- Penumbra/Interop/Hooks/Meta/UpdateRender.cs | 4 +- .../Hooks/Objects/CharacterBaseDestructor.cs | 2 +- .../Hooks/Objects/CharacterDestructor.cs | 2 +- .../Interop/Hooks/Objects/CopyCharacter.cs | 2 +- .../Hooks/Objects/CreateCharacterBase.cs | 2 +- Penumbra/Interop/Hooks/Objects/EnableDraw.cs | 2 +- .../Interop/Hooks/Objects/WeaponReload.cs | 2 +- .../PostProcessing/PreBoneDeformerReplacer.cs | 4 +- .../PostProcessing/ShaderReplacementFixer.cs | 34 +++-- .../Hooks/ResourceLoading/CreateFileWHook.cs | 2 +- .../Hooks/ResourceLoading/FileReadService.cs | 2 +- .../Hooks/ResourceLoading/MappedCodeReader.cs | 11 +- .../Hooks/ResourceLoading/PapHandler.cs | 3 + .../Hooks/ResourceLoading/PeSigScanner.cs | 1 - .../Hooks/ResourceLoading/ResourceService.cs | 7 +- .../Hooks/ResourceLoading/TexMdlService.cs | 6 +- .../Hooks/Resources/ApricotResourceLoad.cs | 2 +- .../Interop/Hooks/Resources/LoadMtrlShpk.cs | 2 +- .../Interop/Hooks/Resources/LoadMtrlTex.cs | 2 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 2 +- .../Resources/ResourceHandleDestructor.cs | 3 +- Penumbra/Penumbra.cs | 9 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 21 +-- Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs | 63 ++++++++ 52 files changed, 326 insertions(+), 108 deletions(-) create mode 100644 Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index 96a51027..44eb7ebb 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -24,7 +24,7 @@ public sealed unsafe class ApricotListenerSoundPlayCaller : FastHook("Apricot Listener Sound Play Caller", Sigs.ApricotListenerSoundPlayCaller, Detour, - true); //HookSettings.VfxIdentificationHooks); + !HookOverrides.Instance.Animation.ApricotListenerSoundPlayCaller); } public delegate nint Delegate(nint a1, nint a2, float a3); diff --git a/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs b/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs index f99d8ca4..22609afc 100644 --- a/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs +++ b/Penumbra/Interop/Hooks/Animation/CharacterBaseLoadAnimation.cs @@ -26,7 +26,8 @@ public sealed unsafe class CharacterBaseLoadAnimation : FastHook("CharacterBase Load Animation", Sigs.CharacterBaseLoadAnimation, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("CharacterBase Load Animation", Sigs.CharacterBaseLoadAnimation, Detour, + !HookOverrides.Instance.Animation.CharacterBaseLoadAnimation); } public delegate void Delegate(DrawObject* drawBase); diff --git a/Penumbra/Interop/Hooks/Animation/Dismount.cs b/Penumbra/Interop/Hooks/Animation/Dismount.cs index 034011e7..17151083 100644 --- a/Penumbra/Interop/Hooks/Animation/Dismount.cs +++ b/Penumbra/Interop/Hooks/Animation/Dismount.cs @@ -16,7 +16,7 @@ public sealed unsafe class Dismount : FastHook { _state = state; _collectionResolver = collectionResolver; - Task = hooks.CreateHook("Dismount", Sigs.Dismount, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Dismount", Sigs.Dismount, Detour, !HookOverrides.Instance.Animation.Dismount); } public delegate void Delegate(MountContainer* a1, nint a2); diff --git a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs index 48dc0078..29afd4ea 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadAreaVfx.cs @@ -17,10 +17,10 @@ public sealed unsafe class LoadAreaVfx : FastHook public LoadAreaVfx(HookManager hooks, GameState state, CollectionResolver collectionResolver, CrashHandlerService crashHandler) { - _state = state; + _state = state; _collectionResolver = collectionResolver; - _crashHandler = crashHandler; - Task = hooks.CreateHook("Load Area VFX", Sigs.LoadAreaVfx, Detour, HookSettings.VfxIdentificationHooks); + _crashHandler = crashHandler; + Task = hooks.CreateHook("Load Area VFX", Sigs.LoadAreaVfx, Detour, !HookOverrides.Instance.Animation.LoadAreaVfx); } public delegate nint Delegate(uint vfxId, float* pos, GameObject* caster, float unk1, float unk2, byte unk3); diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs index 8d1096d2..91b70ede 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterSound.cs @@ -20,7 +20,7 @@ public sealed unsafe class LoadCharacterSound : FastHook("Load Character Sound", (nint)VfxContainer.MemberFunctionPointers.LoadCharacterSound, Detour, - HookSettings.VfxIdentificationHooks); + !HookOverrides.Instance.Animation.LoadCharacterSound); } public delegate nint Delegate(VfxContainer* container, int unk1, int unk2, nint unk3, ulong unk4, int unk5, int unk6, ulong unk7); diff --git a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs index af801345..9a57ca12 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadCharacterVfx.cs @@ -26,7 +26,7 @@ public sealed unsafe class LoadCharacterVfx : FastHook("Load Character VFX", Sigs.LoadCharacterVfx, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Load Character VFX", Sigs.LoadCharacterVfx, Detour, !HookOverrides.Instance.Animation.LoadCharacterVfx); } public delegate nint Delegate(byte* vfxPath, VfxParams* vfxParams, byte unk1, byte unk2, float unk3, int unk4); diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index 8bb14db6..cdd82b95 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -31,7 +31,7 @@ public sealed unsafe class LoadTimelineResources : FastHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Load Timeline Resources", Sigs.LoadTimelineResources, Detour, !HookOverrides.Instance.Animation.LoadTimelineResources); } public delegate ulong Delegate(SchedulerTimeline* timeline); diff --git a/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs b/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs index e4a8c83c..858357c8 100644 --- a/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs +++ b/Penumbra/Interop/Hooks/Animation/PlayFootstep.cs @@ -14,7 +14,7 @@ public sealed unsafe class PlayFootstep : FastHook { _state = state; _collectionResolver = collectionResolver; - Task = hooks.CreateHook("Play Footstep", Sigs.FootStepSound, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Play Footstep", Sigs.FootStepSound, Detour, !HookOverrides.Instance.Animation.PlayFootstep); } public delegate void Delegate(GameObject* gameObject, int id, int unk); diff --git a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs index 645b3565..dfbc615a 100644 --- a/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs +++ b/Penumbra/Interop/Hooks/Animation/ScheduleClipUpdate.cs @@ -23,7 +23,7 @@ public sealed unsafe class ScheduleClipUpdate : FastHook("Schedule Clip Update", Sigs.ScheduleClipUpdate, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Schedule Clip Update", Sigs.ScheduleClipUpdate, Detour, !HookOverrides.Instance.Animation.ScheduleClipUpdate); } public delegate void Delegate(ClipScheduler* x); diff --git a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs index 1f3c0e3b..e1751261 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeActionLoad.cs @@ -20,7 +20,7 @@ public sealed unsafe class SomeActionLoad : FastHook _state = state; _collectionResolver = collectionResolver; _crashHandler = crashHandler; - Task = hooks.CreateHook("Some Action Load", Sigs.LoadSomeAction, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Some Action Load", Sigs.LoadSomeAction, Detour, !HookOverrides.Instance.Animation.SomeActionLoad); } public delegate void Delegate(TimelineContainer* timelineManager); diff --git a/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs b/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs index f2b48afe..75f1240a 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeMountAnimation.cs @@ -15,7 +15,7 @@ public sealed unsafe class SomeMountAnimation : FastHook("Some Mount Animation", Sigs.UnkMountAnimation, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Some Mount Animation", Sigs.UnkMountAnimation, Detour, !HookOverrides.Instance.Animation.SomeMountAnimation); } public delegate void Delegate(DrawObject* drawObject, uint unk1, byte unk2, uint unk3); diff --git a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs index 8f952df5..7339c397 100644 --- a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs @@ -22,7 +22,7 @@ public sealed unsafe class SomePapLoad : FastHook _collectionResolver = collectionResolver; _objects = objects; _crashHandler = crashHandler; - Task = hooks.CreateHook("Some PAP Load", Sigs.LoadSomePap, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Some PAP Load", Sigs.LoadSomePap, Detour, !HookOverrides.Instance.Animation.SomePapLoad); } public delegate void Delegate(nint a1, int a2, nint a3, int a4); diff --git a/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs b/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs index 165bd5eb..9df8d4eb 100644 --- a/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs +++ b/Penumbra/Interop/Hooks/Animation/SomeParasolAnimation.cs @@ -15,7 +15,7 @@ public sealed unsafe class SomeParasolAnimation : FastHook("Some Parasol Animation", Sigs.UnkParasolAnimation, Detour, HookSettings.VfxIdentificationHooks); + Task = hooks.CreateHook("Some Parasol Animation", Sigs.UnkParasolAnimation, Detour, !HookOverrides.Instance.Animation.SomeParasolAnimation); } public delegate void Delegate(DrawObject* drawObject, int unk1); diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 9c60096f..a4f4201f 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -1,14 +1,140 @@ +using Dalamud.Plugin; +using Newtonsoft.Json; + namespace Penumbra.Interop.Hooks; -public static class HookSettings +public class HookOverrides { - public const bool AllHooks = true; + public static HookOverrides Instance = new(); - public const bool ObjectHooks = true && AllHooks; - public const bool ReplacementHooks = true && AllHooks; - public const bool ResourceHooks = true && AllHooks; - public const bool MetaEntryHooks = true && AllHooks; - public const bool MetaParentHooks = true && AllHooks; - public const bool VfxIdentificationHooks = true && AllHooks; - public const bool PostProcessingHooks = true && AllHooks; + public AnimationHooks Animation; + public MetaHooks Meta; + public ObjectHooks Objects; + public PostProcessingHooks PostProcessing; + public ResourceLoadingHooks ResourceLoading; + public ResourceHooks Resources; + + public HookOverrides Clone() + => new() + { + Animation = Animation, + Meta = Meta, + Objects = Objects, + PostProcessing = PostProcessing, + ResourceLoading = ResourceLoading, + Resources = Resources, + }; + + public struct AnimationHooks + { + public bool ApricotListenerSoundPlayCaller; + public bool CharacterBaseLoadAnimation; + public bool Dismount; + public bool LoadAreaVfx; + public bool LoadCharacterSound; + public bool LoadCharacterVfx; + public bool LoadTimelineResources; + public bool PlayFootstep; + public bool ScheduleClipUpdate; + public bool SomeActionLoad; + public bool SomeMountAnimation; + public bool SomePapLoad; + public bool SomeParasolAnimation; + } + + public struct MetaHooks + { + public bool CalculateHeight; + public bool ChangeCustomize; + public bool EqdpAccessoryHook; + public bool EqdpEquipHook; + public bool EqpHook; + public bool EstHook; + public bool GmpHook; + public bool ModelLoadComplete; + public bool RspBustHook; + public bool RspHeightHook; + public bool RspSetupCharacter; + public bool RspTailHook; + public bool SetupVisor; + public bool UpdateModel; + public bool UpdateRender; + } + + public struct ObjectHooks + { + public bool CharacterBaseDestructor; + public bool CharacterDestructor; + public bool CopyCharacter; + public bool CreateCharacterBase; + public bool EnableDraw; + public bool WeaponReload; + } + + public struct PostProcessingHooks + { + public bool HumanSetupScaling; + public bool HumanCreateDeformer; + public bool HumanOnRenderMaterial; + public bool ModelRendererOnRenderMaterial; + } + + public struct ResourceLoadingHooks + { + public bool CreateFileWHook; + public bool PapHooks; + public bool ReadSqPack; + public bool IncRef; + public bool DecRef; + public bool GetResourceSync; + public bool GetResourceAsync; + public bool CheckFileState; + public bool TexResourceHandleOnLoad; + public bool LoadMdlFileExtern; + } + + public struct ResourceHooks + { + public bool ApricotResourceLoad; + public bool LoadMtrlShpk; + public bool LoadMtrlTex; + public bool ResolvePathHooks; + public bool ResourceHandleDestructor; + } + + public const string FileName = "HookOverrides.json"; + + public static HookOverrides LoadFile(IDalamudPluginInterface pi) + { + var path = Path.Combine(pi.GetPluginConfigDirectory(), FileName); + if (!File.Exists(path)) + return new HookOverrides(); + + try + { + var text = File.ReadAllText(path); + var ret = JsonConvert.DeserializeObject(text); + Penumbra.Log.Warning("A hook override file was loaded, some hooks may be disabled and Penumbra might not be working as expected."); + return ret; + } + catch (Exception ex) + { + Penumbra.Log.Error($"A hook override file was found at {path}, but could not be loaded:\n{ex}"); + return new HookOverrides(); + } + } + + public void Write(IDalamudPluginInterface pi) + { + var path = Path.Combine(pi.GetPluginConfigDirectory(), FileName); + try + { + var text = JsonConvert.SerializeObject(this, Formatting.Indented); + File.WriteAllText(path, text); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Could not write hook override file to {path}:\n{ex}"); + } + } } diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index aab64871..e71d07dd 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -14,7 +14,7 @@ public sealed unsafe class CalculateHeight : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, !HookOverrides.Instance.Meta.CalculateHeight); } public delegate ulong Delegate(Character* character); diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs index f69e98e7..368845b4 100644 --- a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -16,7 +16,7 @@ public sealed unsafe class ChangeCustomize : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Change Customize", Sigs.ChangeCustomize, Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Change Customize", Sigs.ChangeCustomize, Detour, !HookOverrides.Instance.Meta.ChangeCustomize); } public delegate bool Delegate(Human* human, CustomizeArray* data, byte skipEquipment); diff --git a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs index 63cca53f..43328600 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpAccessoryHook.cs @@ -16,8 +16,10 @@ public unsafe class EqdpAccessoryHook : FastHook, ID public EqdpAccessoryHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpAccessoryEntry", Sigs.GetEqdpAccessoryEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetEqdpAccessoryEntry", Sigs.GetEqdpAccessoryEntry, Detour, + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.EqdpAccessoryHook); + if (!HookOverrides.Instance.Meta.EqdpAccessoryHook) + _metaState.Config.ModsEnabled += Toggle; } private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) diff --git a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs index 5d5d2f84..fa0d5a29 100644 --- a/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqdpEquipHook.cs @@ -16,8 +16,9 @@ public unsafe class EqdpEquipHook : FastHook, IDisposabl public EqdpEquipHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqdpEquipEntry", Sigs.GetEqdpEquipEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetEqdpEquipEntry", Sigs.GetEqdpEquipEntry, Detour, metaState.Config.EnableMods && !HookOverrides.Instance.Meta.EqdpEquipHook); + if (!HookOverrides.Instance.Meta.EqdpEquipHook) + _metaState.Config.ModsEnabled += Toggle; } private void Detour(CharacterUtility* utility, EqdpEntry* entry, uint setId, uint raceCode) diff --git a/Penumbra/Interop/Hooks/Meta/EqpHook.cs b/Penumbra/Interop/Hooks/Meta/EqpHook.cs index f47db795..f35b922b 100644 --- a/Penumbra/Interop/Hooks/Meta/EqpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EqpHook.cs @@ -15,8 +15,10 @@ public unsafe class EqpHook : FastHook, IDisposable public EqpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetEqpFlags", Sigs.GetEqpEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetEqpFlags", Sigs.GetEqpEntry, Detour, + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.EqpHook); + if (!HookOverrides.Instance.Meta.EqpHook) + _metaState.Config.ModsEnabled += Toggle; } private void Detour(CharacterUtility* utility, EqpEntry* flags, CharacterArmor* armor) diff --git a/Penumbra/Interop/Hooks/Meta/EstHook.cs b/Penumbra/Interop/Hooks/Meta/EstHook.cs index 825b1244..8284eb69 100644 --- a/Penumbra/Interop/Hooks/Meta/EstHook.cs +++ b/Penumbra/Interop/Hooks/Meta/EstHook.cs @@ -21,8 +21,9 @@ public unsafe class EstHook : FastHook, IDisposable _metaState = metaState; _characterUtility = characterUtility; Task = hooks.CreateHook("FindEstEntry", Sigs.FindEstEntry, Detour, - metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.EstHook); + if (!HookOverrides.Instance.Meta.EstHook) + _metaState.Config.ModsEnabled += Toggle; } private EstEntry Detour(ResourceHandle* estResource, uint genderRace, uint id) diff --git a/Penumbra/Interop/Hooks/Meta/GmpHook.cs b/Penumbra/Interop/Hooks/Meta/GmpHook.cs index 12b221d9..d656ebdb 100644 --- a/Penumbra/Interop/Hooks/Meta/GmpHook.cs +++ b/Penumbra/Interop/Hooks/Meta/GmpHook.cs @@ -17,8 +17,10 @@ public unsafe class GmpHook : FastHook, IDisposable public GmpHook(HookManager hooks, MetaState metaState) { _metaState = metaState; - Task = hooks.CreateHook("GetGmpEntry", Sigs.GetGmpEntry, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetGmpEntry", Sigs.GetGmpEntry, Detour, + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.GmpHook); + if (!HookOverrides.Instance.Meta.GmpHook) + _metaState.Config.ModsEnabled += Toggle; } private ulong Detour(CharacterUtility* characterUtility, ulong* outputEntry, ushort setId) diff --git a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs index c1803745..4b9b05b1 100644 --- a/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs +++ b/Penumbra/Interop/Hooks/Meta/ModelLoadComplete.cs @@ -13,7 +13,7 @@ public sealed unsafe class ModelLoadComplete : FastHook("Model Load Complete", vtables.HumanVTable[59], Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Model Load Complete", vtables.HumanVTable[59], Detour, !HookOverrides.Instance.Meta.ModelLoadComplete); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs index e08dc393..c49556bf 100644 --- a/Penumbra/Interop/Hooks/Meta/RspBustHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspBustHook.cs @@ -19,8 +19,10 @@ public unsafe class RspBustHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspBust", Sigs.GetRspBust, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetRspBust", Sigs.GetRspBust, Detour, + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.RspBustHook); + if (!HookOverrides.Instance.Meta.RspBustHook) + _metaState.Config.ModsEnabled += Toggle; } private float* Detour(nint cmpResource, float* storage, SubRace clan, byte gender, byte bodyType, byte bustSize) @@ -34,7 +36,9 @@ public unsafe class RspBustHook : FastHook, IDisposable } var ret = storage; - if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (bodyType < 2 + && _metaState.RspCollection.TryPeek(out var collection) + && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var bustScale = bustSize / 100f; var ptr = CmpFile.GetDefaults(_metaFileManager, clan, RspAttribute.BustMinX); diff --git a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs index 20e3c939..49180d6e 100644 --- a/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspHeightHook.cs @@ -17,10 +17,12 @@ public class RspHeightHook : FastHook, IDisposable public RspHeightHook(HookManager hooks, MetaState metaState, MetaFileManager metaFileManager) { - _metaState = metaState; + _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspHeight", Sigs.GetRspHeight, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetRspHeight", Sigs.GetRspHeight, Detour, + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.RspHeightHook); + if (!HookOverrides.Instance.Meta.RspHeightHook) + _metaState.Config.ModsEnabled += Toggle; } private unsafe float Detour(nint cmpResource, SubRace clan, byte gender, byte bodyType, byte height) @@ -33,6 +35,7 @@ public class RspHeightHook : FastHook, IDisposable // Special cases. if (height == 0xFF) return 1.0f; + if (height > 100) height = 0; diff --git a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs index 8bcc7593..952a2e29 100644 --- a/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs +++ b/Penumbra/Interop/Hooks/Meta/RspSetupCharacter.cs @@ -15,7 +15,7 @@ public sealed unsafe class RspSetupCharacter : FastHook("RSP Setup Character", Sigs.RspSetupCharacter, Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("RSP Setup Character", Sigs.RspSetupCharacter, Detour, !HookOverrides.Instance.Meta.RspSetupCharacter); } public delegate void Delegate(DrawObject* drawObject, nint unk2, float unk3, nint unk4, byte unk5); diff --git a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs index 86d21c6f..b434efa6 100644 --- a/Penumbra/Interop/Hooks/Meta/RspTailHook.cs +++ b/Penumbra/Interop/Hooks/Meta/RspTailHook.cs @@ -19,14 +19,18 @@ public class RspTailHook : FastHook, IDisposable { _metaState = metaState; _metaFileManager = metaFileManager; - Task = hooks.CreateHook("GetRspTail", Sigs.GetRspTail, Detour, metaState.Config.EnableMods && HookSettings.MetaEntryHooks); - _metaState.Config.ModsEnabled += Toggle; + Task = hooks.CreateHook("GetRspTail", Sigs.GetRspTail, Detour, + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.RspTailHook); + if (!HookOverrides.Instance.Meta.RspTailHook) + _metaState.Config.ModsEnabled += Toggle; } private unsafe float Detour(nint cmpResource, Race race, byte gender, byte isSecondSubRace, byte bodyType, byte tailLength) { float scale; - if (bodyType < 2 && _metaState.RspCollection.TryPeek(out var collection) && collection is { Valid: true, ModCollection.MetaCache: { } cache }) + if (bodyType < 2 + && _metaState.RspCollection.TryPeek(out var collection) + && collection is { Valid: true, ModCollection.MetaCache: { } cache }) { var clan = (SubRace)(((int)race - 1) * 2 + 1 + isSecondSubRace); var (minIdent, maxIdent) = gender == 0 diff --git a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs index 83c0e0c4..063a9462 100644 --- a/Penumbra/Interop/Hooks/Meta/SetupVisor.cs +++ b/Penumbra/Interop/Hooks/Meta/SetupVisor.cs @@ -19,7 +19,7 @@ public sealed unsafe class SetupVisor : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Setup Visor", Sigs.SetupVisor, Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Setup Visor", Sigs.SetupVisor, Detour, !HookOverrides.Instance.Meta.SetupVisor); } public delegate byte Delegate(DrawObject* drawObject, ushort modelId, byte visorState); diff --git a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs index a088a0f2..72beea0e 100644 --- a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs @@ -15,7 +15,7 @@ public sealed unsafe class UpdateModel : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Update Model", Sigs.UpdateModel, Detour, HookSettings.MetaParentHooks); + Task = hooks.CreateHook("Update Model", Sigs.UpdateModel, Detour, !HookOverrides.Instance.Meta.UpdateModel); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Meta/UpdateRender.cs b/Penumbra/Interop/Hooks/Meta/UpdateRender.cs index 95cc0e15..ef0068b6 100644 --- a/Penumbra/Interop/Hooks/Meta/UpdateRender.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateRender.cs @@ -13,8 +13,8 @@ public sealed unsafe class UpdateRender : FastHook public UpdateRender(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState, CharacterBaseVTables vTables) { _collectionResolver = collectionResolver; - _metaState = metaState; - Task = hooks.CreateHook("Human.UpdateRender", vTables.HumanVTable[4], Detour, HookSettings.MetaParentHooks); + _metaState = metaState; + Task = hooks.CreateHook("Human.UpdateRender", vTables.HumanVTable[4], Detour, !HookOverrides.Instance.Meta.UpdateRender); } public delegate void Delegate(DrawObject* drawObject); diff --git a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs index c67bb9f3..7636718e 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs @@ -19,7 +19,7 @@ public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); + => _task = hooks.CreateHook(Name, Address, Detour, !HookOverrides.Instance.Objects.CharacterBaseDestructor); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs index 618d0bd7..ffe2f72d 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs @@ -19,7 +19,7 @@ public sealed unsafe class CharacterDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Sigs.CharacterDestructor, Detour, HookSettings.ObjectHooks); + => _task = hooks.CreateHook(Name, Sigs.CharacterDestructor, Detour, !HookOverrides.Instance.Objects.CharacterDestructor); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs index d81043c8..bc18a7ad 100644 --- a/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs +++ b/Penumbra/Interop/Hooks/Objects/CopyCharacter.cs @@ -15,7 +15,7 @@ public sealed unsafe class CopyCharacter : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); + => _task = hooks.CreateHook(Name, Address, Detour, !HookOverrides.Instance.Objects.CopyCharacter); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs index f00a9984..e29876ac 100644 --- a/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs +++ b/Penumbra/Interop/Hooks/Objects/CreateCharacterBase.cs @@ -16,7 +16,7 @@ public sealed unsafe class CreateCharacterBase : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); + => _task = hooks.CreateHook(Name, Address, Detour, !HookOverrides.Instance.Objects.CreateCharacterBase); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/Objects/EnableDraw.cs b/Penumbra/Interop/Hooks/Objects/EnableDraw.cs index 8b701fe5..68bb28af 100644 --- a/Penumbra/Interop/Hooks/Objects/EnableDraw.cs +++ b/Penumbra/Interop/Hooks/Objects/EnableDraw.cs @@ -17,7 +17,7 @@ public sealed unsafe class EnableDraw : IHookService public EnableDraw(HookManager hooks, GameState state) { _state = state; - _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, HookSettings.ObjectHooks); + _task = hooks.CreateHook("Enable Draw", Sigs.EnableDraw, Detour, !HookOverrides.Instance.Objects.EnableDraw); } private delegate void Delegate(GameObject* gameObject); diff --git a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs index da31840f..b09103f6 100644 --- a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs +++ b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs @@ -16,7 +16,7 @@ public sealed unsafe class WeaponReload : EventWrapperPtr _task = hooks.CreateHook(Name, Address, Detour, HookSettings.ObjectHooks); + => _task = hooks.CreateHook(Name, Address, Detour, !HookOverrides.Instance.Objects.WeaponReload); private readonly Task> _task; diff --git a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs index 834a7d28..1aa09d7f 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs @@ -38,9 +38,9 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi _resourceLoader = resourceLoader; _framework = framework; _humanSetupScalingHook = hooks.CreateHook("HumanSetupScaling", vTables.HumanVTable[58], SetupScaling, - HookSettings.PostProcessingHooks).Result; + !HookOverrides.Instance.PostProcessing.HumanSetupScaling).Result; _humanCreateDeformerHook = hooks.CreateHook("HumanCreateDeformer", vTables.HumanVTable[101], - CreateDeformer, HookSettings.PostProcessingHooks).Result; + CreateDeformer, !HookOverrides.Instance.PostProcessing.HumanCreateDeformer).Result; } public void Dispose() diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index b87d33ef..53b69741 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -90,20 +90,26 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _modelRenderer = modelRenderer; _communicator = communicator; - _skinState = new( + _skinState = new ModdedShaderPackageState( () => (ShaderPackageResourceHandle**)&_utility.Address->SkinShpkResource, () => (ShaderPackageResourceHandle*)_utility.DefaultSkinShpkResource); - _irisState = new(() => _modelRenderer.IrisShaderPackage, () => _modelRenderer.DefaultIrisShaderPackage); - _characterGlassState = new(() => _modelRenderer.CharacterGlassShaderPackage, () => _modelRenderer.DefaultCharacterGlassShaderPackage); - _characterTransparencyState = new(() => _modelRenderer.CharacterTransparencyShaderPackage, () => _modelRenderer.DefaultCharacterTransparencyShaderPackage); - _characterTattooState = new(() => _modelRenderer.CharacterTattooShaderPackage, () => _modelRenderer.DefaultCharacterTattooShaderPackage); - _characterOcclusionState = new(() => _modelRenderer.CharacterOcclusionShaderPackage, () => _modelRenderer.DefaultCharacterOcclusionShaderPackage); - _hairMaskState = new(() => _modelRenderer.HairMaskShaderPackage, () => _modelRenderer.DefaultHairMaskShaderPackage); + _irisState = new ModdedShaderPackageState(() => _modelRenderer.IrisShaderPackage, () => _modelRenderer.DefaultIrisShaderPackage); + _characterGlassState = new ModdedShaderPackageState(() => _modelRenderer.CharacterGlassShaderPackage, + () => _modelRenderer.DefaultCharacterGlassShaderPackage); + _characterTransparencyState = new ModdedShaderPackageState(() => _modelRenderer.CharacterTransparencyShaderPackage, + () => _modelRenderer.DefaultCharacterTransparencyShaderPackage); + _characterTattooState = new ModdedShaderPackageState(() => _modelRenderer.CharacterTattooShaderPackage, + () => _modelRenderer.DefaultCharacterTattooShaderPackage); + _characterOcclusionState = new ModdedShaderPackageState(() => _modelRenderer.CharacterOcclusionShaderPackage, + () => _modelRenderer.DefaultCharacterOcclusionShaderPackage); + _hairMaskState = + new ModdedShaderPackageState(() => _modelRenderer.HairMaskShaderPackage, () => _modelRenderer.DefaultHairMaskShaderPackage); _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[64], - OnRenderHumanMaterial, HookSettings.PostProcessingHooks).Result; + OnRenderHumanMaterial, !HookOverrides.Instance.PostProcessing.HumanOnRenderMaterial).Result; _modelRendererOnRenderMaterialHook = hooks.CreateHook("ModelRenderer.OnRenderMaterial", - Sigs.ModelRendererOnRenderMaterial, ModelRendererOnRenderMaterialDetour, HookSettings.PostProcessingHooks).Result; + Sigs.ModelRendererOnRenderMaterial, ModelRendererOnRenderMaterialDetour, + !HookOverrides.Instance.PostProcessing.ModelRendererOnRenderMaterial).Result; _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.ShaderReplacementFixer); _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.ShaderReplacementFixer); } @@ -123,7 +129,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _skinState.ClearMaterials(); } - public (ulong Skin, ulong Iris, ulong CharacterGlass, ulong CharacterTransparency, ulong CharacterTattoo, ulong CharacterOcclusion, ulong HairMask) GetAndResetSlowPathCallDeltas() + public (ulong Skin, ulong Iris, ulong CharacterGlass, ulong CharacterTransparency, ulong CharacterTattoo, ulong CharacterOcclusion, ulong + HairMask) GetAndResetSlowPathCallDeltas() => (_skinState.GetAndResetSlowPathCallDelta(), _irisState.GetAndResetSlowPathCallDelta(), _characterGlassState.GetAndResetSlowPathCallDelta(), @@ -208,7 +215,12 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private uint GetTotalMaterialCountForModelRenderer() - => _irisState.MaterialCount + _characterGlassState.MaterialCount + _characterTransparencyState.MaterialCount + _characterTattooState.MaterialCount + _characterOcclusionState.MaterialCount + _hairMaskState.MaterialCount; + => _irisState.MaterialCount + + _characterGlassState.MaterialCount + + _characterTransparencyState.MaterialCount + + _characterTattooState.MaterialCount + + _characterOcclusionState.MaterialCount + + _hairMaskState.MaterialCount; private nint OnRenderHumanMaterial(CharacterBase* human, CSModelRenderer.OnRenderMaterialParams* param) { diff --git a/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs b/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs index 8d0ac8cb..a9a5f41d 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/CreateFileWHook.cs @@ -19,7 +19,7 @@ public unsafe class CreateFileWHook : IDisposable, IRequiredService public CreateFileWHook(IGameInteropProvider interop) { _createFileWHook = interop.HookFromImport(null, "KERNEL32.dll", "CreateFileW", 0, CreateFileWDetour); - if (HookSettings.ReplacementHooks) + if (!HookOverrides.Instance.ResourceLoading.CreateFileWHook) _createFileWHook.Enable(); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs b/Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs index 199525fb..d8801b81 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/FileReadService.cs @@ -15,7 +15,7 @@ public unsafe class FileReadService : IDisposable, IRequiredService _resourceManager = resourceManager; _performance = performance; interop.InitializeFromAttributes(this); - if (HookSettings.ReplacementHooks) + if (!HookOverrides.Instance.ResourceLoading.ReadSqPack) _readSqPackHook.Enable(); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs b/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs index 81712cca..de0014d2 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/MappedCodeReader.cs @@ -4,10 +4,11 @@ namespace Penumbra.Interop.Hooks.ResourceLoading; public class MappedCodeReader(UnmanagedMemoryAccessor data, long offset) : CodeReader { - public override int ReadByte() { - if (offset >= data.Capacity) - return -1; + public override int ReadByte() + { + if (offset >= data.Capacity) + return -1; - return data.ReadByte(offset++); - } + return data.ReadByte(offset++); + } } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs index ea12a480..5ba8c975 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs @@ -8,6 +8,9 @@ public sealed class PapHandler(PapRewriter.PapResourceHandlerPrototype papResour public void Enable() { + if (HookOverrides.Instance.ResourceLoading.PapHooks) + return; + ReadOnlySpan<(string Sig, string Name)> signatures = [ (Sigs.LoadAlwaysResidentMotionPacks, nameof(Sigs.LoadAlwaysResidentMotionPacks)), diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs index f5dd2d45..4be0da00 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs @@ -14,7 +14,6 @@ public unsafe class PeSigScanner : IDisposable private readonly nint _moduleBaseAddress; private readonly uint _textSectionVirtualAddress; - public PeSigScanner() { var mainModule = Process.GetCurrentProcess().MainModule!; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index 8b99dc37..f75b0623 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -30,13 +30,14 @@ public unsafe class ResourceService : IDisposable, IRequiredService _decRefHook = interop.HookFromAddress( (nint)CSResourceHandle.MemberFunctionPointers.DecRef, ResourceHandleDecRefDetour); - if (HookSettings.ReplacementHooks) - { + if (HookOverrides.Instance.ResourceLoading.GetResourceSync) _getResourceSyncHook.Enable(); + if (HookOverrides.Instance.ResourceLoading.GetResourceAsync) _getResourceAsyncHook.Enable(); + if (HookOverrides.Instance.ResourceLoading.IncRef) _incRefHook.Enable(); + if (HookOverrides.Instance.ResourceLoading.DecRef) _decRefHook.Enable(); - } } public ResourceHandle* GetResource(ResourceCategory category, ResourceType type, CiByteString path) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index 80ba5cb9..fc3289bd 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -46,12 +46,12 @@ public unsafe class TexMdlService : IDisposable, IRequiredService { interop.InitializeFromAttributes(this); _lodService = new LodService(interop); - if (HookSettings.ReplacementHooks) - { + if (HookOverrides.Instance.ResourceLoading.CheckFileState) _checkFileStateHook.Enable(); + if (HookOverrides.Instance.ResourceLoading.LoadMdlFileExtern) _loadMdlFileExternHook.Enable(); + if (HookOverrides.Instance.ResourceLoading.TexResourceHandleOnLoad) _textureOnLoadHook.Enable(); - } } /// Add CRC64 if the given file is a model or texture file and has an associated path. diff --git a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs index 511e842f..f6cccc19 100644 --- a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs +++ b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs @@ -11,7 +11,7 @@ public sealed unsafe class ApricotResourceLoad : FastHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, HookSettings.ResourceHooks); + Task = hooks.CreateHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, HookOverrides.Instance.Resources.ApricotResourceLoad); } public delegate byte Delegate(ResourceHandle* handle, nint unk1, byte unk2); diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs index 8447762b..7aaa62d5 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs @@ -14,7 +14,7 @@ public sealed unsafe class LoadMtrlShpk : FastHook { _gameState = gameState; _communicator = communicator; - Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, HookSettings.ResourceHooks); + Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, HookOverrides.Instance.Resources.LoadMtrlShpk); } public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs index 7bc3c7b0..ed0e067b 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs @@ -11,7 +11,7 @@ public sealed unsafe class LoadMtrlTex : FastHook public LoadMtrlTex(HookManager hooks, GameState gameState) { _gameState = gameState; - Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, HookSettings.ResourceHooks); + Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, HookOverrides.Instance.Resources.LoadMtrlTex); } public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index e1b6e46e..66945009 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -67,7 +67,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable // @formatter:on - if (HookSettings.ResourceHooks) + if (HookOverrides.Instance.Resources.ResolvePathHooks) Enable(); } diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index cd4a53c4..5c4b5c90 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -23,7 +23,8 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Sigs.ResourceHandleDestructor, Detour, HookSettings.ResourceHooks); + => _task = hooks.CreateHook(Name, Sigs.ResourceHandleDestructor, Detour, + HookOverrides.Instance.Resources.ResourceHandleDestructor); private readonly Task> _task; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 5f8d6805..8ea74987 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -21,6 +21,7 @@ using Penumbra.GameData.Enums; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using System.Xml.Linq; +using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.ResourceLoading; namespace Penumbra; @@ -52,9 +53,10 @@ public class Penumbra : IDalamudPlugin { try { - _services = StaticServiceManager.CreateProvider(this, pluginInterface, Log); - Messager = _services.GetService(); - _validityChecker = _services.GetService(); + HookOverrides.Instance = HookOverrides.LoadFile(pluginInterface); + _services = StaticServiceManager.CreateProvider(this, pluginInterface, Log); + Messager = _services.GetService(); + _validityChecker = _services.GetService(); _services.EnsureRequiredServices(); var startup = _services.GetService() @@ -215,6 +217,7 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Auto-Deduplication: `** {_config.AutoDeduplicateOnImport}\n"); sb.Append($"> **`Auto-UI-Reduplication: `** {_config.AutoReduplicateUiOnImport}\n"); sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); + sb.Append($"> **`Hook Overrides: `** {HookOverrides.Instance.IsCustomLoaded}\n"); sb.Append( $"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")}\n"); sb.Append( diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index a1e9da03..3a64e556 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -97,6 +97,7 @@ public class DebugTab : Window, ITab, IUiService private readonly IpcTester _ipcTester; private readonly CrashHandlerPanel _crashHandlerPanel; private readonly TexHeaderDrawer _texHeaderDrawer; + private readonly HookOverrideDrawer _hookOverrides; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, @@ -106,7 +107,8 @@ public class DebugTab : Window, ITab, IUiService DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, - Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer) + Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, + HookOverrideDrawer hookOverrides) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -143,6 +145,7 @@ public class DebugTab : Window, ITab, IUiService _ipcTester = ipcTester; _crashHandlerPanel = crashHandlerPanel; _texHeaderDrawer = texHeaderDrawer; + _hookOverrides = hookOverrides; _objects = objects; _clientState = clientState; } @@ -166,34 +169,21 @@ public class DebugTab : Window, ITab, IUiService return; DrawDebugTabGeneral(); - ImGui.NewLine(); _crashHandlerPanel.Draw(); - ImGui.NewLine(); _diagnostics.DrawDiagnostics(); DrawPerformanceTab(); - ImGui.NewLine(); DrawPathResolverDebug(); - ImGui.NewLine(); DrawActorsDebug(); - ImGui.NewLine(); DrawCollectionCaches(); - ImGui.NewLine(); _texHeaderDrawer.Draw(); - ImGui.NewLine(); DrawDebugCharacterUtility(); - ImGui.NewLine(); DrawShaderReplacementFixer(); - ImGui.NewLine(); DrawData(); - ImGui.NewLine(); DrawResourceProblems(); - ImGui.NewLine(); + _hookOverrides.Draw(); DrawPlayerModelInfo(); - ImGui.NewLine(); DrawGlobalVariableInfo(); - ImGui.NewLine(); DrawDebugTabIpc(); - ImGui.NewLine(); } @@ -434,7 +424,6 @@ public class DebugTab : Window, ITab, IUiService private void DrawPerformanceTab() { - ImGui.NewLine(); if (!ImGui.CollapsingHeader("Performance")) return; diff --git a/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs b/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs new file mode 100644 index 00000000..7af1f884 --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs @@ -0,0 +1,63 @@ +using Dalamud.Plugin; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Interop.Hooks; + +namespace Penumbra.UI.Tabs.Debug; + +public class HookOverrideDrawer(IDalamudPluginInterface pluginInterface) : IUiService +{ + private HookOverrides? _overrides; + + public void Draw() + { + using var header = ImUtf8.CollapsingHeaderId("Generate Hook Override"u8); + if (!header) + return; + + _overrides ??= HookOverrides.Instance.Clone(); + + if (ImUtf8.Button("Save"u8)) + _overrides.Write(pluginInterface); + + ImGui.SameLine(); + var path = Path.Combine(pluginInterface.GetPluginConfigDirectory(), HookOverrides.FileName); + var exists = File.Exists(path); + if (ImUtf8.ButtonEx("Delete"u8, disabled: !exists, tooltip: exists ? ""u8 : "File does not exist."u8)) + try + { + File.Delete(path); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Could not delete hook override file at {path}:\n{ex}"); + } + + bool? all = null; + ImGui.SameLine(); + if (ImUtf8.Button("Disable All Hooks"u8)) + all = true; + ImGui.SameLine(); + if (ImUtf8.Button("Enable All Hooks"u8)) + all = false; + + foreach (var propertyField in typeof(HookOverrides).GetFields().Where(f => f is { IsStatic: false, FieldType.IsValueType: true })) + { + using var tree = ImUtf8.TreeNode(propertyField.Name); + if (!tree) + continue; + + var property = propertyField.GetValue(_overrides); + foreach (var valueField in propertyField.FieldType.GetFields()) + { + var value = valueField.GetValue(property) as bool? ?? false; + if (ImUtf8.Checkbox($"Disable {valueField.Name}", ref value) || all.HasValue) + { + valueField.SetValue(property, all ?? value); + propertyField.SetValue(_overrides, property); + } + } + } + } +} From 73b9d1fca0ede105413561ba0d61f17d7b176636 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 16:49:22 +0200 Subject: [PATCH 0815/1381] Meh. --- Penumbra/Interop/Hooks/HookSettings.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index a4f4201f..0c0a4020 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -5,6 +5,9 @@ namespace Penumbra.Interop.Hooks; public class HookOverrides { + [JsonIgnore] + public bool IsCustomLoaded { get; private set; } + public static HookOverrides Instance = new(); public AnimationHooks Animation; @@ -113,7 +116,8 @@ public class HookOverrides try { var text = File.ReadAllText(path); - var ret = JsonConvert.DeserializeObject(text); + var ret = JsonConvert.DeserializeObject(text)!; + ret.IsCustomLoaded = true; Penumbra.Log.Warning("A hook override file was loaded, some hooks may be disabled and Penumbra might not be working as expected."); return ret; } From 7579eaacbe0ffd3fcfcd03e33c6b526d5f2d2310 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 17:14:28 +0200 Subject: [PATCH 0816/1381] Meh. --- Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs | 8 ++++---- Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs | 6 +++--- Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs | 3 ++- Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs | 4 ++-- Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs | 2 +- Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs | 2 +- .../Interop/Hooks/Resources/ResourceHandleDestructor.cs | 2 +- 7 files changed, 14 insertions(+), 13 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index f75b0623..e55c9bb0 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -30,13 +30,13 @@ public unsafe class ResourceService : IDisposable, IRequiredService _decRefHook = interop.HookFromAddress( (nint)CSResourceHandle.MemberFunctionPointers.DecRef, ResourceHandleDecRefDetour); - if (HookOverrides.Instance.ResourceLoading.GetResourceSync) + if (!HookOverrides.Instance.ResourceLoading.GetResourceSync) _getResourceSyncHook.Enable(); - if (HookOverrides.Instance.ResourceLoading.GetResourceAsync) + if (!HookOverrides.Instance.ResourceLoading.GetResourceAsync) _getResourceAsyncHook.Enable(); - if (HookOverrides.Instance.ResourceLoading.IncRef) + if (!HookOverrides.Instance.ResourceLoading.IncRef) _incRefHook.Enable(); - if (HookOverrides.Instance.ResourceLoading.DecRef) + if (!HookOverrides.Instance.ResourceLoading.DecRef) _decRefHook.Enable(); } diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index fc3289bd..d4a2dfba 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -46,11 +46,11 @@ public unsafe class TexMdlService : IDisposable, IRequiredService { interop.InitializeFromAttributes(this); _lodService = new LodService(interop); - if (HookOverrides.Instance.ResourceLoading.CheckFileState) + if (!HookOverrides.Instance.ResourceLoading.CheckFileState) _checkFileStateHook.Enable(); - if (HookOverrides.Instance.ResourceLoading.LoadMdlFileExtern) + if (!HookOverrides.Instance.ResourceLoading.LoadMdlFileExtern) _loadMdlFileExternHook.Enable(); - if (HookOverrides.Instance.ResourceLoading.TexResourceHandleOnLoad) + if (!HookOverrides.Instance.ResourceLoading.TexResourceHandleOnLoad) _textureOnLoadHook.Enable(); } diff --git a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs index f6cccc19..40860b0b 100644 --- a/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs +++ b/Penumbra/Interop/Hooks/Resources/ApricotResourceLoad.cs @@ -11,7 +11,8 @@ public sealed unsafe class ApricotResourceLoad : FastHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, HookOverrides.Instance.Resources.ApricotResourceLoad); + Task = hooks.CreateHook("Load Apricot Resource", Sigs.ApricotResourceLoad, Detour, + !HookOverrides.Instance.Resources.ApricotResourceLoad); } public delegate byte Delegate(ResourceHandle* handle, nint unk1, byte unk2); diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs index 7aaa62d5..8c410ad8 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs @@ -12,9 +12,9 @@ public sealed unsafe class LoadMtrlShpk : FastHook public LoadMtrlShpk(HookManager hooks, GameState gameState, CommunicatorService communicator) { - _gameState = gameState; + _gameState = gameState; _communicator = communicator; - Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, HookOverrides.Instance.Resources.LoadMtrlShpk); + Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, !HookOverrides.Instance.Resources.LoadMtrlShpk); } public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs index ed0e067b..0759d9b1 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs @@ -11,7 +11,7 @@ public sealed unsafe class LoadMtrlTex : FastHook public LoadMtrlTex(HookManager hooks, GameState gameState) { _gameState = gameState; - Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, HookOverrides.Instance.Resources.LoadMtrlTex); + Task = hooks.CreateHook("Load Material Textures", Sigs.LoadMtrlTex, Detour, !HookOverrides.Instance.Resources.LoadMtrlTex); } public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 66945009..b1b23f27 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -67,7 +67,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable // @formatter:on - if (HookOverrides.Instance.Resources.ResolvePathHooks) + if (!HookOverrides.Instance.Resources.ResolvePathHooks) Enable(); } diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index 5c4b5c90..bdb11752 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -24,7 +24,7 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr _task = hooks.CreateHook(Name, Sigs.ResourceHandleDestructor, Detour, - HookOverrides.Instance.Resources.ResourceHandleDestructor); + !HookOverrides.Instance.Resources.ResourceHandleDestructor); private readonly Task> _task; From 1e1637f0e72dff18e6d1beee6c686d5ed509b9f8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 17:14:46 +0200 Subject: [PATCH 0817/1381] Test IMC group toggling off. --- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- .../Manager/OptionEditor/ImcAttributeCache.cs | 34 +++++------------- .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 36 +++++++++++++++---- 3 files changed, 39 insertions(+), 33 deletions(-) diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 03896134..5f99673e 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -242,7 +242,7 @@ public class ImcModGroup(Mod mod) : IModGroup continue; var option = OptionData[i]; - mask |= option.AttributeMask; + mask ^= option.AttributeMask; } return mask; diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs b/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs index e1235c5b..a7b73ac9 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs @@ -21,23 +21,14 @@ public unsafe ref struct ImcAttributeCache _option[i] = byte.MaxValue; var flag = (ushort)(1 << i); - var set = (group.DefaultEntry.AttributeMask & flag) != 0; - if (set) - { - _canChange[i] = true; - _option[i] = byte.MaxValue - 1; - continue; - } - foreach (var (option, idx) in group.OptionData.WithIndex()) { - set = (option.AttributeMask & flag) != 0; - if (set) - { - _canChange[i] = option.AttributeMask != flag; - _option[i] = (byte)idx; - break; - } + if ((option.AttributeMask & flag) == 0) + continue; + + _canChange[i] = option.AttributeMask != flag; + _option[i] = (byte)idx; + break; } if (_option[i] == byte.MaxValue && LowestUnsetMask is 0) @@ -65,25 +56,16 @@ public unsafe ref struct ImcAttributeCache return true; } - if (!_canChange[idx]) - return false; - var mask = (ushort)(oldMask | flag); if (oldMask == mask) return false; group.DefaultEntry = group.DefaultEntry with { AttributeMask = mask }; - if (_option[idx] <= ImcEntry.NumAttributes) - { - var option = group.OptionData[_option[idx]]; - option.AttributeMask = (ushort)(option.AttributeMask & ~flag); - } - return true; } /// Set an attribute flag to a value if possible, remove it from its prior option or the default entry if necessary, and return if anything changed. - public readonly bool Set(ImcSubMod option, int idx, bool value) + public readonly bool Set(ImcSubMod option, int idx, bool value, bool turnOffDefault = false) { if (!_canChange[idx]) return false; @@ -110,7 +92,7 @@ public unsafe ref struct ImcAttributeCache var oldOption = option.Group.OptionData[_option[idx]]; oldOption.AttributeMask = (ushort)(oldOption.AttributeMask & ~flag); } - else if (_option[idx] is byte.MaxValue - 1) + else if (turnOffDefault && _option[idx] is byte.MaxValue - 1) { option.Group.DefaultEntry = option.Group.DefaultEntry with { diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index bbb5e54e..9d1ab78a 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -3,6 +3,9 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Text; +using OtterGui.Text.Widget; +using OtterGui.Widgets; +using OtterGuiInternal.Utility; using Penumbra.GameData.Structs; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager.OptionEditor; @@ -86,7 +89,8 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr foreach (var (option, idx) in group.OptionData.WithIndex().Where(o => !o.Value.IsDisableSubMod)) { using var id = ImUtf8.PushId(idx); - DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option); + DrawAttributes(editor.ModManager.OptionEditor.ImcEditor, attributeCache, option.AttributeMask, option, + group.DefaultEntry.AttributeMask); } } } @@ -132,15 +136,18 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr } } - private static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data) + private static void DrawAttributes(ImcModGroupEditor editor, in ImcAttributeCache cache, ushort mask, object data, + ushort? defaultMask = null) { for (var i = 0; i < ImcEntry.NumAttributes; ++i) { - using var id = ImRaii.PushId(i); - var value = (mask & (1 << i)) != 0; - using (ImRaii.Disabled(!cache.CanChange(i))) + using var id = ImRaii.PushId(i); + var flag = 1 << i; + var value = (mask & flag) != 0; + var inDefault = defaultMask.HasValue && (defaultMask & flag) != 0; + using (ImRaii.Disabled(defaultMask != null && !cache.CanChange(i))) { - if (ImUtf8.Checkbox(""u8, ref value)) + if (inDefault ? NegativeCheckbox.Instance.Draw(""u8, ref value) : ImUtf8.Checkbox(""u8, ref value)) { if (data is ImcModGroup g) editor.ChangeDefaultAttribute(g, cache, i, value); @@ -154,4 +161,21 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr ImUtf8.SameLineInner(); } } + + private sealed class NegativeCheckbox : MultiStateCheckbox + { + public static readonly NegativeCheckbox Instance = new(); + + protected override void RenderSymbol(bool value, Vector2 position, float size) + { + if (value) + SymbolHelpers.RenderCross(ImGui.GetWindowDrawList(), position, ImGui.GetColorU32(ImGuiCol.CheckMark), size); + } + + protected override bool NextValue(bool value) + => !value; + + protected override bool PreviousValue(bool value) + => !value; + } } From 5e9c7f7eac0c6334b3063918bd221a1525e80844 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 22:17:56 +0200 Subject: [PATCH 0818/1381] Fix IMC import sanity check. --- OtterGui | 2 +- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 2b79faac..c53955cb 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 2b79faacff30a31e9ad4b0a3c5d57ffd6e34cfa4 +Subproject commit c53955cb6199dd418c5a9538d3251ac5942e7067 diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 5f99673e..7b0eb094 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -186,7 +186,7 @@ public class ImcModGroup(Mod mod) : IModGroup return null; } - var rollingMask = ret.DefaultEntry.AttributeMask; + var rollingMask = 0ul; if (options != null) foreach (var child in options.Children()) { From d903f1b8c3a61fdadc9387cad59cf7a3f337ab64 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 1 Aug 2024 22:18:26 +0200 Subject: [PATCH 0819/1381] Update GetResourceSync and GetResourceAsync function signatures for testing, including unused stack parameters. --- .../Hooks/ResourceLoading/ResourceService.cs | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index e55c9bb0..126505d1 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -44,7 +44,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService { var hash = path.Crc32; return GetResourceHandler(true, (ResourceManager*)_resourceManager.ResourceManagerAddress, - &category, &type, &hash, path.Path, null, false); + &category, &type, &hash, path.Path, null, 0, 0, 0); } public SafeResourceHandle GetSafeResource(ResourceCategory category, ResourceType type, CiByteString path) @@ -76,10 +76,10 @@ public unsafe class ResourceService : IDisposable, IRequiredService public event GetResourcePreDelegate? ResourceRequested; private delegate ResourceHandle* GetResourceSyncPrototype(ResourceManager* resourceManager, ResourceCategory* pCategoryId, - ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams); + ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams, nint unk7, uint unk8); private delegate ResourceHandle* GetResourceAsyncPrototype(ResourceManager* resourceManager, ResourceCategory* pCategoryId, - ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams, bool isUnknown); + ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams, byte isUnknown, nint unk8, uint unk9); [Signature(Sigs.GetResourceSync, DetourName = nameof(GetResourceSyncDetour))] private readonly Hook _getResourceSyncHook = null!; @@ -88,27 +88,28 @@ public unsafe class ResourceService : IDisposable, IRequiredService private readonly Hook _getResourceAsyncHook = null!; private ResourceHandle* GetResourceSyncDetour(ResourceManager* resourceManager, ResourceCategory* categoryId, ResourceType* resourceType, - int* resourceHash, byte* path, GetResourceParameters* pGetResParams) - => GetResourceHandler(true, resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, false); + int* resourceHash, byte* path, GetResourceParameters* pGetResParams, nint unk8, uint unk9) + => GetResourceHandler(true, resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, 0, unk8, unk9); private ResourceHandle* GetResourceAsyncDetour(ResourceManager* resourceManager, ResourceCategory* categoryId, ResourceType* resourceType, - int* resourceHash, byte* path, GetResourceParameters* pGetResParams, bool isUnk) - => GetResourceHandler(false, resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, isUnk); + int* resourceHash, byte* path, GetResourceParameters* pGetResParams, byte isUnk, nint unk8, uint unk9) + => GetResourceHandler(false, resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, isUnk, unk8, unk9); /// /// Resources can be obtained synchronously and asynchronously. We need to change behaviour in both cases. /// Both work basically the same, so we can reduce the main work to one function used by both hooks. /// private ResourceHandle* GetResourceHandler(bool isSync, ResourceManager* resourceManager, ResourceCategory* categoryId, - ResourceType* resourceType, int* resourceHash, byte* path, GetResourceParameters* pGetResParams, bool isUnk) + ResourceType* resourceType, int* resourceHash, byte* path, GetResourceParameters* pGetResParams, byte isUnk, nint unk8, uint unk9) { using var performance = _performance.Measure(PerformanceType.GetResourceHandler); if (!Utf8GamePath.FromPointer(path, MetaDataComputation.CiCrc32, out var gamePath)) { Penumbra.Log.Error("[ResourceService] Could not create GamePath from resource path."); return isSync - ? _getResourceSyncHook.Original(resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams) - : _getResourceAsyncHook.Original(resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, isUnk); + ? _getResourceSyncHook.Original(resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, unk8, unk9) + : _getResourceAsyncHook.Original(resourceManager, categoryId, resourceType, resourceHash, path, pGetResParams, isUnk, unk8, + unk9); } ResourceHandle* returnValue = null; @@ -117,17 +118,17 @@ public unsafe class ResourceService : IDisposable, IRequiredService if (returnValue != null) return returnValue; - return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk); + return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk, unk8, unk9); } /// Call the original GetResource function. public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, - GetResourceParameters* resourceParameters = null, bool unk = false) + GetResourceParameters* resourceParameters = null, byte unk = 0, nint unk8 = 0, uint unk9 = 0) => sync ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, - resourceParameters) + resourceParameters, unk8, unk9) : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, - resourceParameters, unk); + resourceParameters, unk, unk8, unk9); #endregion From f3e72711578f865e6c94fa68f69d50aa75248d90 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 2 Aug 2024 12:48:57 +0000 Subject: [PATCH 0820/1381] [CI] Updating repo.json for testing_1.2.0.18 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index adf152b0..e1653454 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.17", + "TestingAssemblyVersion": "1.2.0.18", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.17/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.18/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 6241187431f313b6ac9d1959943677d04752546c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 3 Aug 2024 15:15:19 +0200 Subject: [PATCH 0821/1381] Fix span constructors going over boundaries for ByteStrings. --- Penumbra.String | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.String b/Penumbra.String index 91f0f211..bd52d080 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 91f0f21137c61bd39281debf88a8ecc494043330 +Subproject commit bd52d080b72d67263dc47068e461f17c93bdc779 From 4454ac48daadb2375806677f58fe9a7bb5710b8a Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 3 Aug 2024 13:18:14 +0000 Subject: [PATCH 0822/1381] [CI] Updating repo.json for testing_1.2.0.19 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e1653454..cbe2b121 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.18", + "TestingAssemblyVersion": "1.2.0.19", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.18/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.19/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 069b28272bcec59d03fc84e89850e7acf279e180 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:09:20 +0200 Subject: [PATCH 0823/1381] Add TextureArraySlicer --- .../Interop/Services/TextureArraySlicer.cs | 119 ++++++++++++++++++ Penumbra/Penumbra.csproj | 8 ++ Penumbra/UI/WindowSystem.cs | 31 +++-- 3 files changed, 145 insertions(+), 13 deletions(-) create mode 100644 Penumbra/Interop/Services/TextureArraySlicer.cs diff --git a/Penumbra/Interop/Services/TextureArraySlicer.cs b/Penumbra/Interop/Services/TextureArraySlicer.cs new file mode 100644 index 00000000..c934ac2b --- /dev/null +++ b/Penumbra/Interop/Services/TextureArraySlicer.cs @@ -0,0 +1,119 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using OtterGui.Services; +using SharpDX.Direct3D; +using SharpDX.Direct3D11; + +namespace Penumbra.Interop.Services; + +/// +/// Creates ImGui handles over slices of array textures, and manages their lifetime. +/// +public sealed unsafe class TextureArraySlicer : IUiService, IDisposable +{ + private const uint InitialTimeToLive = 2; + + private readonly Dictionary<(nint XivTexture, byte SliceIndex), SliceState> _activeSlices = []; + private readonly HashSet<(nint XivTexture, byte SliceIndex)> _expiredKeys = []; + + /// Caching this across frames will cause a crash to desktop. + public nint GetImGuiHandle(Texture* texture, byte sliceIndex) + { + if (texture == null) + throw new ArgumentNullException(nameof(texture)); + if (sliceIndex >= texture->ArraySize) + throw new ArgumentOutOfRangeException(nameof(sliceIndex), $"Slice index ({sliceIndex}) is greater than or equal to the texture array size ({texture->ArraySize})"); + if (_activeSlices.TryGetValue(((nint)texture, sliceIndex), out var state)) + { + state.Refresh(); + return (nint)state.ShaderResourceView; + } + var srv = (ShaderResourceView)(nint)texture->D3D11ShaderResourceView; + var description = srv.Description; + switch (description.Dimension) + { + case ShaderResourceViewDimension.Texture1D: + case ShaderResourceViewDimension.Texture2D: + case ShaderResourceViewDimension.Texture2DMultisampled: + case ShaderResourceViewDimension.Texture3D: + case ShaderResourceViewDimension.TextureCube: + // This function treats these as single-slice arrays. + // As per the range check above, the only valid slice (i. e. 0) has been requested, therefore there is nothing to do. + break; + case ShaderResourceViewDimension.Texture1DArray: + description.Texture1DArray.FirstArraySlice = sliceIndex; + description.Texture2DArray.ArraySize = 1; + break; + case ShaderResourceViewDimension.Texture2DArray: + description.Texture2DArray.FirstArraySlice = sliceIndex; + description.Texture2DArray.ArraySize = 1; + break; + case ShaderResourceViewDimension.Texture2DMultisampledArray: + description.Texture2DMSArray.FirstArraySlice = sliceIndex; + description.Texture2DMSArray.ArraySize = 1; + break; + case ShaderResourceViewDimension.TextureCubeArray: + description.TextureCubeArray.First2DArrayFace = sliceIndex * 6; + description.TextureCubeArray.CubeCount = 1; + break; + default: + throw new NotSupportedException($"{nameof(TextureArraySlicer)} does not support dimension {description.Dimension}"); + } + state = new SliceState(new ShaderResourceView(srv.Device, srv.Resource, description)); + _activeSlices.Add(((nint)texture, sliceIndex), state); + return (nint)state.ShaderResourceView; + } + + public void Tick() + { + try + { + foreach (var (key, slice) in _activeSlices) + { + if (!slice.Tick()) + _expiredKeys.Add(key); + } + foreach (var key in _expiredKeys) + { + _activeSlices.Remove(key); + } + } + finally + { + _expiredKeys.Clear(); + } + } + + public void Dispose() + { + foreach (var slice in _activeSlices.Values) + { + slice.Dispose(); + } + } + + private sealed class SliceState(ShaderResourceView shaderResourceView) : IDisposable + { + public readonly ShaderResourceView ShaderResourceView = shaderResourceView; + + private uint _timeToLive = InitialTimeToLive; + + public void Refresh() + { + _timeToLive = InitialTimeToLive; + } + + public bool Tick() + { + if (unchecked(_timeToLive--) > 0) + return true; + + ShaderResourceView.Dispose(); + return false; + } + + public void Dispose() + { + ShaderResourceView.Dispose(); + } + } +} diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 24ffe469..8e143e3c 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -72,6 +72,14 @@ $(DalamudLibPath)Iced.dll False + + $(DalamudLibPath)SharpDX.dll + False + + + $(DalamudLibPath)SharpDX.Direct3D11.dll + False + lib\OtterTex.dll diff --git a/Penumbra/UI/WindowSystem.cs b/Penumbra/UI/WindowSystem.cs index 6d382ad4..575a381f 100644 --- a/Penumbra/UI/WindowSystem.cs +++ b/Penumbra/UI/WindowSystem.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using Dalamud.Interface.Windowing; using Dalamud.Plugin; using OtterGui.Services; +using Penumbra.Interop.Services; using Penumbra.UI.AdvancedWindow; using Penumbra.UI.Knowledge; using Penumbra.UI.Tabs.Debug; @@ -10,23 +11,25 @@ namespace Penumbra.UI; public class PenumbraWindowSystem : IDisposable, IUiService { - private readonly IUiBuilder _uiBuilder; - private readonly WindowSystem _windowSystem; - private readonly FileDialogService _fileDialog; - public readonly ConfigWindow Window; - public readonly PenumbraChangelog Changelog; - public readonly KnowledgeWindow KnowledgeWindow; + private readonly IUiBuilder _uiBuilder; + private readonly WindowSystem _windowSystem; + private readonly FileDialogService _fileDialog; + private readonly TextureArraySlicer _textureArraySlicer; + public readonly ConfigWindow Window; + public readonly PenumbraChangelog Changelog; + public readonly KnowledgeWindow KnowledgeWindow; public PenumbraWindowSystem(IDalamudPluginInterface pi, Configuration config, PenumbraChangelog changelog, ConfigWindow window, LaunchButton _, ModEditWindow editWindow, FileDialogService fileDialog, ImportPopup importPopup, DebugTab debugTab, - KnowledgeWindow knowledgeWindow) + KnowledgeWindow knowledgeWindow, TextureArraySlicer textureArraySlicer) { - _uiBuilder = pi.UiBuilder; - _fileDialog = fileDialog; - KnowledgeWindow = knowledgeWindow; - Changelog = changelog; - Window = window; - _windowSystem = new WindowSystem("Penumbra"); + _uiBuilder = pi.UiBuilder; + _fileDialog = fileDialog; + _textureArraySlicer = textureArraySlicer; + KnowledgeWindow = knowledgeWindow; + Changelog = changelog; + Window = window; + _windowSystem = new WindowSystem("Penumbra"); _windowSystem.AddWindow(changelog.Changelog); _windowSystem.AddWindow(window); _windowSystem.AddWindow(editWindow); @@ -37,6 +40,7 @@ public class PenumbraWindowSystem : IDisposable, IUiService _uiBuilder.OpenConfigUi += Window.OpenSettings; _uiBuilder.Draw += _windowSystem.Draw; _uiBuilder.Draw += _fileDialog.Draw; + _uiBuilder.Draw += _textureArraySlicer.Tick; _uiBuilder.DisableGposeUiHide = !config.HideUiInGPose; _uiBuilder.DisableCutsceneUiHide = !config.HideUiInCutscenes; _uiBuilder.DisableUserUiHide = !config.HideUiWhenUiHidden; @@ -51,5 +55,6 @@ public class PenumbraWindowSystem : IDisposable, IUiService _uiBuilder.OpenConfigUi -= Window.OpenSettings; _uiBuilder.Draw -= _windowSystem.Draw; _uiBuilder.Draw -= _fileDialog.Draw; + _uiBuilder.Draw -= _textureArraySlicer.Tick; } } From 60986c78f8449b2e6aed128b5b2b42ce6aafe35a Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:17:48 +0200 Subject: [PATCH 0824/1381] Update GameData --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 75582ece..ee6c6faa 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 75582ece58e6ee311074ff4ecaa68b804677878c +Subproject commit ee6c6faa1e4a3e96279cb6c89df96e351f112c6a From 59b3859f117e083cb105e84838ad3d5bd8c186fc Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:31:12 +0200 Subject: [PATCH 0825/1381] Minor upgrades to follow dependencies --- Penumbra/Import/Models/Export/MaterialExporter.cs | 11 ++++++----- Penumbra/Import/Textures/TextureDrawer.cs | 4 +--- Penumbra/Services/MigrationManager.cs | 4 ++-- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 6 +----- 4 files changed, 10 insertions(+), 15 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 5df9e1c1..62892473 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -49,7 +49,7 @@ public class MaterialExporter private static MaterialBuilder BuildCharacter(Material material, string name) { // Build the textures from the color table. - var table = new LegacyColorTable(material.Mtrl.Table); + var table = new LegacyColorTable(material.Mtrl.Table!); var normal = material.Textures[TextureUsage.SamplerNormal]; @@ -103,6 +103,7 @@ public class MaterialExporter // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. + // TODO(Dawntrail): Use the dedicated index (_id) map, that is not embedded in the normal map's alpha channel anymore. private readonly struct ProcessCharacterNormalOperation(Image normal, LegacyColorTable table) : IRowOperation { public Image Normal { get; } = normal.Clone(); @@ -139,17 +140,17 @@ public class MaterialExporter var nextRow = table[tableRow.Next]; // Base colour (table, .b) - var lerpedDiffuse = Vector3.Lerp(prevRow.Diffuse, nextRow.Diffuse, tableRow.Weight); + var lerpedDiffuse = Vector3.Lerp((Vector3)prevRow.DiffuseColor, (Vector3)nextRow.DiffuseColor, tableRow.Weight); baseColorSpan[x].FromVector4(new Vector4(lerpedDiffuse, 1)); baseColorSpan[x].A = normalPixel.B; // Specular (table) - var lerpedSpecularColor = Vector3.Lerp(prevRow.Specular, nextRow.Specular, tableRow.Weight); - var lerpedSpecularFactor = float.Lerp(prevRow.SpecularStrength, nextRow.SpecularStrength, tableRow.Weight); + var lerpedSpecularColor = Vector3.Lerp((Vector3)prevRow.SpecularColor, (Vector3)nextRow.SpecularColor, tableRow.Weight); + var lerpedSpecularFactor = float.Lerp((float)prevRow.SpecularMask, (float)nextRow.SpecularMask, tableRow.Weight); specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, lerpedSpecularFactor)); // Emissive (table) - var lerpedEmissive = Vector3.Lerp(prevRow.Emissive, nextRow.Emissive, tableRow.Weight); + var lerpedEmissive = Vector3.Lerp((Vector3)prevRow.EmissiveColor, (Vector3)nextRow.EmissiveColor, tableRow.Weight); emissiveSpan[x].FromVector4(new Vector4(lerpedEmissive, 1)); // Normal (.rg) diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index bd95d1ab..c83604e4 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -18,9 +18,7 @@ public static class TextureDrawer { if (texture.TextureWrap != null) { - size = size.X < texture.TextureWrap.Width - ? size with { Y = texture.TextureWrap.Height * size.X / texture.TextureWrap.Width } - : new Vector2(texture.TextureWrap.Width, texture.TextureWrap.Height); + size = texture.TextureWrap.Size.Contain(size); ImGui.Image(texture.TextureWrap.ImGuiHandle, size); DrawData(texture); diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 84318da6..7726f6fd 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -279,7 +279,7 @@ public class MigrationManager(Configuration config) : IService Directory.CreateDirectory(Path.GetDirectoryName(path)!); using var f = File.Open(path, FileMode.Create, FileAccess.Write); - if (file.IsDawnTrail) + if (file.IsDawntrail) { file.MigrateToDawntrail(); Penumbra.Log.Debug($"Migrated material {reader.Entry.Key} to Dawntrail during import."); @@ -329,7 +329,7 @@ public class MigrationManager(Configuration config) : IService try { var mtrl = new MtrlFile(data); - if (mtrl.IsDawnTrail) + if (mtrl.IsDawntrail) return data; mtrl.MigrateToDawntrail(); diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index c47414b9..e2776b2f 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -6,7 +6,6 @@ using OtterGui; using Penumbra.Interop.ResourceTree; using Penumbra.UI.Classes; using Penumbra.String; -using Penumbra.UI.Tabs; namespace Penumbra.UI.AdvancedWindow; @@ -245,10 +244,7 @@ public class ResourceTreeViewer if (visibility == NodeVisibility.Hidden) continue; - var textColor = ImGui.GetColorU32(ImGuiCol.Text); - var textColorInternal = (textColor & 0x00FFFFFFu) | ((textColor & 0xFE000000u) >> 1); // Half opacity - - using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, textColorInternal, resourceNode.Internal); + using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, ImGuiUtil.HalfTransparentText(), resourceNode.Internal); var filterIcon = resourceNode.Icon != 0 ? resourceNode.Icon : parentFilterIcon; From e8182f285e2fd83ee8c6ed532fa14c858f9557c1 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:47:22 +0200 Subject: [PATCH 0826/1381] Update StainService for DT --- .../Interop/Structs/CharacterUtilityData.cs | 28 ++++++- Penumbra/Services/StainService.cs | 84 ++++++++++++++----- Penumbra/UI/Tabs/Debug/DebugTab.cs | 51 +++++++---- 3 files changed, 124 insertions(+), 39 deletions(-) diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 197de0bb..7595353f 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -5,10 +5,15 @@ namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] public unsafe struct CharacterUtilityData { - public const int IndexHumanPbd = 63; - public const int IndexTransparentTex = 79; - public const int IndexDecalTex = 80; - public const int IndexSkinShpk = 83; + public const int IndexHumanPbd = 63; + public const int IndexTransparentTex = 79; + public const int IndexDecalTex = 80; + public const int IndexTileOrbArrayTex = 81; + public const int IndexTileNormArrayTex = 82; + public const int IndexSkinShpk = 83; + public const int IndexGudStm = 94; + public const int IndexLegacyStm = 95; + public const int IndexSphereDArrayTex = 96; public static readonly MetaIndex[] EqdpIndices = Enum.GetNames() .Zip(Enum.GetValues()) @@ -97,8 +102,23 @@ public unsafe struct CharacterUtilityData [FieldOffset(8 + IndexDecalTex * 8)] public TextureResourceHandle* DecalTexResource; + [FieldOffset(8 + IndexTileOrbArrayTex * 8)] + public TextureResourceHandle* TileOrbArrayTexResource; + + [FieldOffset(8 + IndexTileNormArrayTex * 8)] + public TextureResourceHandle* TileNormArrayTexResource; + [FieldOffset(8 + IndexSkinShpk * 8)] public ResourceHandle* SkinShpkResource; + [FieldOffset(8 + IndexGudStm * 8)] + public ResourceHandle* GudStmResource; + + [FieldOffset(8 + IndexLegacyStm * 8)] + public ResourceHandle* LegacyStmResource; + + [FieldOffset(8 + IndexSphereDArrayTex * 8)] + public TextureResourceHandle* SphereDArrayTexResource; + // not included resources have no known use case. } diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 26b39229..50713968 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -6,19 +6,25 @@ using OtterGui.Services; using OtterGui.Widgets; using Penumbra.GameData.DataContainers; using Penumbra.GameData.Files; -using Penumbra.UI.AdvancedWindow; +using Penumbra.GameData.Files.StainMapStructs; +using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; +using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.Services; public class StainService : IService { - public sealed class StainTemplateCombo(FilterComboColors stainCombo, StmFile stmFile) - : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) + public sealed class StainTemplateCombo(FilterComboColors[] stainCombos, StmFile stmFile) + : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) where TDyePack : unmanaged, IDyePack { + // FIXME There might be a better way to handle that. + public int CurrentDyeChannel = 0; + protected override float GetFilterWidth() { var baseSize = ImGui.CalcTextSize("0000").X + ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X; - if (stainCombo.CurrentSelection.Key == 0) + if (stainCombos[CurrentDyeChannel].CurrentSelection.Key == 0) return baseSize; return baseSize + ImGui.GetTextLineHeight() * 3 + ImGui.GetStyle().ItemInnerSpacing.X * 3; @@ -47,33 +53,73 @@ public class StainService : IService protected override bool DrawSelectable(int globalIdx, bool selected) { var ret = base.DrawSelectable(globalIdx, selected); - var selection = stainCombo.CurrentSelection.Key; + var selection = stainCombos[CurrentDyeChannel].CurrentSelection.Key; if (selection == 0 || !stmFile.TryGetValue(Items[globalIdx], selection, out var colors)) return ret; ImGui.SameLine(); var frame = new Vector2(ImGui.GetTextLineHeight()); - ImGui.ColorButton("D", new Vector4(ModEditWindow.PseudoSqrtRgb(colors.Diffuse), 1), 0, frame); + ImGui.ColorButton("D", new Vector4(MtrlTab.PseudoSqrtRgb((Vector3)colors.DiffuseColor), 1), 0, frame); ImGui.SameLine(); - ImGui.ColorButton("S", new Vector4(ModEditWindow.PseudoSqrtRgb(colors.Specular), 1), 0, frame); + ImGui.ColorButton("S", new Vector4(MtrlTab.PseudoSqrtRgb((Vector3)colors.SpecularColor), 1), 0, frame); ImGui.SameLine(); - ImGui.ColorButton("E", new Vector4(ModEditWindow.PseudoSqrtRgb(colors.Emissive), 1), 0, frame); + ImGui.ColorButton("E", new Vector4(MtrlTab.PseudoSqrtRgb((Vector3)colors.EmissiveColor), 1), 0, frame); return ret; } } - public readonly DictStain StainData; - public readonly FilterComboColors StainCombo; - public readonly StmFile StmFile; - public readonly StainTemplateCombo TemplateCombo; + public const int ChannelCount = 2; - public StainService(IDataManager dataManager, DictStain stainData) + public readonly DictStain StainData; + public readonly FilterComboColors StainCombo1; + public readonly FilterComboColors StainCombo2; // FIXME is there a better way to handle this? + public readonly StmFile LegacyStmFile; + public readonly StmFile GudStmFile; + public readonly StainTemplateCombo LegacyTemplateCombo; + public readonly StainTemplateCombo GudTemplateCombo; + + public unsafe StainService(IDataManager dataManager, CharacterUtility characterUtility, DictStain stainData) { - StainData = stainData; - StainCombo = new FilterComboColors(140, MouseWheelType.None, - () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), - Penumbra.Log); - StmFile = new StmFile(dataManager); - TemplateCombo = new StainTemplateCombo(StainCombo, StmFile); + StainData = stainData; + StainCombo1 = CreateStainCombo(); + StainCombo2 = CreateStainCombo(); + LegacyStmFile = LoadStmFile(characterUtility.Address->LegacyStmResource, dataManager); + GudStmFile = LoadStmFile(characterUtility.Address->GudStmResource, dataManager); + + FilterComboColors[] stainCombos = [StainCombo1, StainCombo2]; + + LegacyTemplateCombo = new StainTemplateCombo(stainCombos, LegacyStmFile); + GudTemplateCombo = new StainTemplateCombo(stainCombos, GudStmFile); } + + /// Retrieves the instance for the given channel. Indexing is zero-based. + public FilterComboColors GetStainCombo(int channel) + => channel switch + { + 0 => StainCombo1, + 1 => StainCombo2, + _ => throw new ArgumentOutOfRangeException(nameof(channel), channel, $"Unsupported dye channel {channel} (supported values are 0 and 1)") + }; + + /// Loads a STM file. Opportunistically attempts to re-use the file already read by the game, with Lumina fallback. + private static unsafe StmFile LoadStmFile(ResourceHandle* stmResourceHandle, IDataManager dataManager) where TDyePack : unmanaged, IDyePack + { + if (stmResourceHandle != null) + { + var stmData = stmResourceHandle->CsHandle.GetDataSpan(); + if (stmData.Length > 0) + { + Penumbra.Log.Debug($"[StainService] Loading StmFile<{typeof(TDyePack)}> from ResourceHandle 0x{(nint)stmResourceHandle:X}"); + return new StmFile(stmData); + } + } + + Penumbra.Log.Debug($"[StainService] Loading StmFile<{typeof(TDyePack)}> from Lumina"); + return new StmFile(dataManager); + } + + private FilterComboColors CreateStainCombo() + => new(140, MouseWheelType.None, + () => StainData.Value.Prepend(new KeyValuePair(0, ("None", 0, false))).ToList(), + Penumbra.Log); } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 3a64e556..ead02874 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -42,6 +42,9 @@ using ImGuiClip = OtterGui.ImGuiClip; using Penumbra.Api.IpcTester; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; +using Penumbra.GameData.Files.StainMapStructs; +using Penumbra.UI.AdvancedWindow; +using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.UI.Tabs.Debug; @@ -697,32 +700,48 @@ public class DebugTab : Window, ITab, IUiService if (!mainTree) return; - foreach (var (key, data) in _stains.StmFile.Entries) + using (var legacyTree = TreeNode("stainingtemplate.stm")) + { + if (legacyTree) + DrawStainTemplatesFile(_stains.LegacyStmFile); + } + + using (var gudTree = TreeNode("stainingtemplate_gud.stm")) + { + if (gudTree) + DrawStainTemplatesFile(_stains.GudStmFile); + } + } + + private static void DrawStainTemplatesFile(StmFile stmFile) where TDyePack : unmanaged, IDyePack + { + foreach (var (key, data) in stmFile.Entries) { using var tree = TreeNode($"Template {key}"); if (!tree) continue; - using var table = Table("##table", 5, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); + using var table = Table("##table", data.Colors.Length + data.Scalars.Length, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); if (!table) continue; - for (var i = 0; i < StmFile.StainingTemplateEntry.NumElements; ++i) + for (var i = 0; i < StmFile.StainingTemplateEntry.NumElements; ++i) { - var (r, g, b) = data.DiffuseEntries[i]; - ImGuiUtil.DrawTableColumn($"{r:F6} | {g:F6} | {b:F6}"); + foreach (var list in data.Colors) + { + var color = list[i]; + ImGui.TableNextColumn(); + var frame = new Vector2(ImGui.GetTextLineHeight()); + ImGui.ColorButton("###color", new Vector4(MtrlTab.PseudoSqrtRgb((Vector3)color), 1), 0, frame); + ImGui.SameLine(); + ImGui.TextUnformatted($"{color.Red:F6} | {color.Green:F6} | {color.Blue:F6}"); + } - (r, g, b) = data.SpecularEntries[i]; - ImGuiUtil.DrawTableColumn($"{r:F6} | {g:F6} | {b:F6}"); - - (r, g, b) = data.EmissiveEntries[i]; - ImGuiUtil.DrawTableColumn($"{r:F6} | {g:F6} | {b:F6}"); - - var a = data.SpecularPowerEntries[i]; - ImGuiUtil.DrawTableColumn($"{a:F6}"); - - a = data.GlossEntries[i]; - ImGuiUtil.DrawTableColumn($"{a:F6}"); + foreach (var list in data.Scalars) + { + var scalar = list[i]; + ImGuiUtil.DrawTableColumn($"{scalar:F6}"); + } } } } From 450751e43fe4d9627da938715b3930e9d25ebe10 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:47:36 +0200 Subject: [PATCH 0827/1381] DT material editor, supporting components --- .../Materials/ConstantEditors.cs | 71 +++++++ .../Materials/MaterialTemplatePickers.cs | 177 ++++++++++++++++++ 2 files changed, 248 insertions(+) create mode 100644 Penumbra/UI/AdvancedWindow/Materials/ConstantEditors.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs diff --git a/Penumbra/UI/AdvancedWindow/Materials/ConstantEditors.cs b/Penumbra/UI/AdvancedWindow/Materials/ConstantEditors.cs new file mode 100644 index 00000000..690580df --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/ConstantEditors.cs @@ -0,0 +1,71 @@ +using System.Collections.Frozen; +using OtterGui.Text.Widget.Editors; +using Penumbra.GameData.Files.ShaderStructs; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public static class ConstantEditors +{ + public static readonly IEditor DefaultFloat = Editors.DefaultFloat.AsByteEditor(); + public static readonly IEditor DefaultInt = Editors.DefaultInt.AsByteEditor(); + public static readonly IEditor DefaultIntAsFloat = Editors.DefaultInt.IntAsFloatEditor().AsByteEditor(); + public static readonly IEditor DefaultColor = ColorEditor.HighDynamicRange.Reinterpreting(); + + /// + /// Material constants known to be encoded as native s. + /// + /// A editor is nonfunctional for them, as typical values for these constants would fall into the IEEE 754 denormalized number range. + /// + private static readonly FrozenSet KnownIntConstants; + + static ConstantEditors() + { + IReadOnlyList knownIntConstants = [ + "g_ToonIndex", + "g_ToonSpecIndex", + ]; + + KnownIntConstants = knownIntConstants.ToFrozenSet(); + } + + public static IEditor DefaultFor(Name name, MaterialTemplatePickers? materialTemplatePickers = null) + { + if (materialTemplatePickers != null) + { + if (name == Names.SphereMapIndexConstantName) + return materialTemplatePickers.SphereMapIndexPicker; + else if (name == Names.TileIndexConstantName) + return materialTemplatePickers.TileIndexPicker; + } + + if (name.Value != null && name.Value.EndsWith("Color")) + return DefaultColor; + + if (KnownIntConstants.Contains(name)) + return DefaultInt; + + return DefaultFloat; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEditor AsByteEditor(this IEditor inner) where T : unmanaged + => inner.Reinterpreting(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEditor IntAsFloatEditor(this IEditor inner) + => inner.Converting(value => int.CreateSaturating(MathF.Round(value)), value => value); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEditor WithExponent(this IEditor inner, T exponent) + where T : unmanaged, IPowerFunctions, IComparisonOperators + => exponent == T.MultiplicativeIdentity + ? inner + : inner.Converting(value => value < T.Zero ? -T.Pow(-value, T.MultiplicativeIdentity / exponent) : T.Pow(value, T.MultiplicativeIdentity / exponent), value => value < T.Zero ? -T.Pow(-value, exponent) : T.Pow(value, exponent)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEditor WithFactorAndBias(this IEditor inner, T factor, T bias) + where T : unmanaged, IMultiplicativeIdentity, IAdditiveIdentity, IMultiplyOperators, IAdditionOperators, ISubtractionOperators, IDivisionOperators, IEqualityOperators + => factor == T.MultiplicativeIdentity && bias == T.AdditiveIdentity + ? inner + : inner.Converting(value => (value - bias) / factor, value => value * factor + bias); +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs new file mode 100644 index 00000000..6ffd1f88 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs @@ -0,0 +1,177 @@ +using Dalamud.Interface; +using FFXIVClientStructs.Interop; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using OtterGui.Text.Widget.Editors; +using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public sealed unsafe class MaterialTemplatePickers : IUiService +{ + private const float MaximumTextureSize = 64.0f; + + private readonly TextureArraySlicer _textureArraySlicer; + private readonly CharacterUtility _characterUtility; + + public readonly IEditor TileIndexPicker; + public readonly IEditor SphereMapIndexPicker; + + public MaterialTemplatePickers(TextureArraySlicer textureArraySlicer, CharacterUtility characterUtility) + { + _textureArraySlicer = textureArraySlicer; + _characterUtility = characterUtility; + + TileIndexPicker = new Editor(DrawTileIndexPicker).AsByteEditor(); + SphereMapIndexPicker = new Editor(DrawSphereMapIndexPicker).AsByteEditor(); + } + + public bool DrawTileIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ref ushort value, bool compact) + => _characterUtility.Address != null + && DrawTextureArrayIndexPicker(label, description, ref value, compact, [ + _characterUtility.Address->TileOrbArrayTexResource, + _characterUtility.Address->TileNormArrayTexResource, + ]); + + public bool DrawSphereMapIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ref ushort value, bool compact) + => _characterUtility.Address != null + && DrawTextureArrayIndexPicker(label, description, ref value, compact, [ + _characterUtility.Address->SphereDArrayTexResource, + ]); + + public bool DrawTextureArrayIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ref ushort value, bool compact, ReadOnlySpan> textureRHs) + { + TextureResourceHandle* firstNonNullTextureRH = null; + foreach (var texture in textureRHs) + { + if (texture.Value != null && texture.Value->CsHandle.Texture != null) + { + firstNonNullTextureRH = texture; + break; + } + } + var firstNonNullTexture = firstNonNullTextureRH != null ? firstNonNullTextureRH->CsHandle.Texture : null; + + var textureSize = firstNonNullTexture != null ? new Vector2(firstNonNullTexture->Width, firstNonNullTexture->Height).Contain(new Vector2(MaximumTextureSize)) : Vector2.Zero; + var count = firstNonNullTexture != null ? firstNonNullTexture->ArraySize : 0; + + var ret = false; + + var framePadding = ImGui.GetStyle().FramePadding; + var itemSpacing = ImGui.GetStyle().ItemSpacing; + using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) + { + var spaceSize = ImUtf8.CalcTextSize(" "u8).X; + var spaces = (int)((ImGui.CalcItemWidth() - framePadding.X * 2.0f - (compact ? 0.0f : (textureSize.X + itemSpacing.X) * textureRHs.Length)) / spaceSize); + using var padding = ImRaii.PushStyle(ImGuiStyleVar.FramePadding, framePadding + new Vector2(0.0f, Math.Max(textureSize.Y - ImGui.GetFrameHeight() + itemSpacing.Y, 0.0f) * 0.5f), !compact); + using var combo = ImUtf8.Combo(label, (value == ushort.MaxValue ? "-" : value.ToString()).PadLeft(spaces), ImGuiComboFlags.NoArrowButton | ImGuiComboFlags.HeightLarge); + if (combo.Success && firstNonNullTextureRH != null) + { + var lineHeight = Math.Max(ImGui.GetTextLineHeightWithSpacing(), framePadding.Y * 2.0f + textureSize.Y); + var itemWidth = Math.Max(ImGui.GetContentRegionAvail().X, ImUtf8.CalcTextSize("MMM"u8).X + (itemSpacing.X + textureSize.X) * textureRHs.Length + framePadding.X * 2.0f); + using var center = ImRaii.PushStyle(ImGuiStyleVar.SelectableTextAlign, new Vector2(0, 0.5f)); + using var clipper = ImUtf8.ListClipper(count, lineHeight); + while (clipper.Step()) + { + for (var i = clipper.DisplayStart; i < clipper.DisplayEnd && i < count; i++) + { + if (ImUtf8.Selectable($"{i,3}", i == value, size: new(itemWidth, lineHeight))) + { + ret = value != i; + value = (ushort)i; + } + var rectMin = ImGui.GetItemRectMin(); + var rectMax = ImGui.GetItemRectMax(); + var textureRegionStart = new Vector2( + rectMax.X - framePadding.X - textureSize.X * textureRHs.Length - itemSpacing.X * (textureRHs.Length - 1), + rectMin.Y + framePadding.Y); + var maxSize = new Vector2(textureSize.X, rectMax.Y - framePadding.Y - textureRegionStart.Y); + DrawTextureSlices(textureRegionStart, maxSize, itemSpacing.X, textureRHs, (byte)i); + } + } + } + } + if (!compact && value != ushort.MaxValue) + { + var cbRectMin = ImGui.GetItemRectMin(); + var cbRectMax = ImGui.GetItemRectMax(); + var cbTextureRegionStart = new Vector2(cbRectMax.X - framePadding.X - textureSize.X * textureRHs.Length - itemSpacing.X * (textureRHs.Length - 1), cbRectMin.Y + framePadding.Y); + var cbMaxSize = new Vector2(textureSize.X, cbRectMax.Y - framePadding.Y - cbTextureRegionStart.Y); + DrawTextureSlices(cbTextureRegionStart, cbMaxSize, itemSpacing.X, textureRHs, (byte)value); + } + if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled) && (description.Length > 0 || compact && value != ushort.MaxValue)) + { + using var disabled = ImRaii.Enabled(); + using var tt = ImUtf8.Tooltip(); + if (description.Length > 0) + ImUtf8.Text(description); + if (compact && value != ushort.MaxValue) + { + ImGui.Dummy(new Vector2(textureSize.X * textureRHs.Length + itemSpacing.X * (textureRHs.Length - 1), textureSize.Y)); + var rectMin = ImGui.GetItemRectMin(); + var rectMax = ImGui.GetItemRectMax(); + DrawTextureSlices(rectMin, textureSize, itemSpacing.X, textureRHs, (byte)value); + } + } + + return ret; + } + + public void DrawTextureSlices(Vector2 regionStart, Vector2 itemSize, float itemSpacing, ReadOnlySpan> textureRHs, byte sliceIndex) + { + for (var j = 0; j < textureRHs.Length; ++j) + { + if (textureRHs[j].Value == null) + continue; + var texture = textureRHs[j].Value->CsHandle.Texture; + if (texture == null) + continue; + var handle = _textureArraySlicer.GetImGuiHandle(texture, sliceIndex); + if (handle == 0) + continue; + + var position = regionStart with { X = regionStart.X + (itemSize.X + itemSpacing) * j }; + var size = new Vector2(texture->Width, texture->Height).Contain(itemSize); + position += (itemSize - size) * 0.5f; + ImGui.GetWindowDrawList().AddImage(handle, position, position + size, Vector2.Zero, + new Vector2(texture->Width / (float)texture->Width2, texture->Height / (float)texture->Height2)); + } + } + + private delegate bool DrawEditor(ReadOnlySpan label, ReadOnlySpan description, ref ushort value, bool compact); + + private sealed class Editor(DrawEditor draw) : IEditor + { + public bool Draw(Span values, bool disabled) + { + var helper = Editors.PrepareMultiComponent(values.Length); + var ret = false; + + for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) + { + helper.SetupComponent(valueIdx); + + var value = ushort.CreateSaturating(MathF.Round(values[valueIdx])); + if (disabled) + { + using var _ = ImRaii.Disabled(); + draw(helper.Id, default, ref value, true); + } + else + { + if (draw(helper.Id, default, ref value, true)) + { + values[valueIdx] = value; + ret = true; + } + } + } + + return ret; + } + } +} From 36ab9573aec81e56655be92f62c7e3e473d737f5 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:41:38 +0200 Subject: [PATCH 0828/1381] DT material editor, main part --- Penumbra/Configuration.cs | 1 + .../LiveColorTablePreviewer.cs | 24 +- .../MaterialPreview/LiveMaterialPreviewer.cs | 20 +- .../Materials/MtrlTab.CommonColorTable.cs | 509 ++++++++++++ .../Materials/MtrlTab.Constants.cs | 277 +++++++ .../Materials/MtrlTab.Devkit.cs | 240 ++++++ .../Materials/MtrlTab.LegacyColorTable.cs | 368 ++++++++ .../Materials/MtrlTab.LivePreview.cs | 272 ++++++ .../Materials/MtrlTab.ShaderPackage.cs | 505 +++++++++++ .../Materials/MtrlTab.Textures.cs | 276 ++++++ .../UI/AdvancedWindow/Materials/MtrlTab.cs | 199 +++++ .../Materials/MtrlTabFactory.cs | 18 + .../ModEditWindow.Materials.ColorTable.cs | 538 ------------ .../ModEditWindow.Materials.ConstantEditor.cs | 247 ------ .../ModEditWindow.Materials.MtrlTab.cs | 783 ------------------ .../ModEditWindow.Materials.Shpk.cs | 481 ----------- .../AdvancedWindow/ModEditWindow.Materials.cs | 179 +--- .../ModEditWindow.QuickImport.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 76 +- Penumbra/UI/Classes/Colors.cs | 4 +- Penumbra/UI/Tabs/SettingsTab.cs | 12 + 21 files changed, 2744 insertions(+), 2286 deletions(-) create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 63325433..50426b38 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -107,6 +107,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool AlwaysOpenDefaultImport { get; set; } = false; public bool KeepDefaultMetaChanges { get; set; } = false; public string DefaultModAuthor { get; set; } = DefaultTexToolsData.Author; + public bool EditRawTileTransforms { get; set; } = false; public Dictionary Colors { get; set; } = Enum.GetValues().ToDictionary(c => c, c => c.Data().DefaultColor); diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index 8e75a895..bbd3b16c 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using Penumbra.GameData.Interop; using Penumbra.Interop.SafeHandles; @@ -7,10 +8,6 @@ namespace Penumbra.Interop.MaterialPreview; public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase { - public const int TextureWidth = 4; - public const int TextureHeight = GameData.Files.MaterialStructs.LegacyColorTable.NumUsedRows; - public const int TextureLength = TextureWidth * TextureHeight * 4; - private readonly IFramework _framework; private readonly Texture** _colorTableTexture; @@ -18,6 +15,9 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase private bool _updatePending; + public int Width { get; } + public int Height { get; } + public Half[] ColorTable { get; } public LiveColorTablePreviewer(ObjectManager objects, IFramework framework, MaterialInfo materialInfo) @@ -33,18 +33,24 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (colorSetTextures == null) throw new InvalidOperationException("Draw object doesn't have color table textures"); - _colorTableTexture = colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); + _colorTableTexture = colorSetTextures + (MaterialInfo.ModelSlot * CharacterBase.MaterialsPerSlot + MaterialInfo.MaterialSlot); + _originalColorTableTexture = new SafeTextureHandle(*_colorTableTexture, true); if (_originalColorTableTexture == null) throw new InvalidOperationException("Material doesn't have a color table"); - ColorTable = new Half[TextureLength]; + Width = (int)_originalColorTableTexture.Texture->Width; + Height = (int)_originalColorTableTexture.Texture->Height; + ColorTable = new Half[Width * Height * 4]; _updatePending = true; framework.Update += OnFrameworkUpdate; } + public Span GetColorRow(int i) + => ColorTable.AsSpan().Slice(Width * 4 * i, Width * 4); + protected override void Clear(bool disposing, bool reset) { _framework.Update -= OnFrameworkUpdate; @@ -74,8 +80,8 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase return; var textureSize = stackalloc int[2]; - textureSize[0] = TextureWidth; - textureSize[1] = TextureHeight; + textureSize[0] = Width; + textureSize[1] = Height; using var texture = new SafeTextureHandle(Device.Instance()->CreateTexture2D(textureSize, 1, 0x2460, 0x80000804, 7), false); @@ -104,6 +110,6 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (colorSetTextures == null) return false; - return _colorTableTexture == colorSetTextures + (MaterialInfo.ModelSlot * 4 + MaterialInfo.MaterialSlot); + return _colorTableTexture == colorSetTextures + (MaterialInfo.ModelSlot * CharacterBase.MaterialsPerSlot + MaterialInfo.MaterialSlot); } } diff --git a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs index 0556fdc4..60762ac7 100644 --- a/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveMaterialPreviewer.cs @@ -7,9 +7,9 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase { private readonly ShaderPackage* _shaderPackage; - private readonly uint _originalShPkFlags; - private readonly float[] _originalMaterialParameter; - private readonly uint[] _originalSamplerFlags; + private readonly uint _originalShPkFlags; + private readonly byte[] _originalMaterialParameter; + private readonly uint[] _originalSamplerFlags; public LiveMaterialPreviewer(ObjectManager objects, MaterialInfo materialInfo) : base(objects, materialInfo) @@ -28,7 +28,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase _originalShPkFlags = Material->ShaderFlags; - _originalMaterialParameter = Material->MaterialParameterCBuffer->TryGetBuffer().ToArray(); + _originalMaterialParameter = Material->MaterialParameterCBuffer->TryGetBuffer().ToArray(); _originalSamplerFlags = new uint[Material->TextureCount]; for (var i = 0; i < _originalSamplerFlags.Length; ++i) @@ -43,7 +43,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase return; Material->ShaderFlags = _originalShPkFlags; - var materialParameter = Material->MaterialParameterCBuffer->TryGetBuffer(); + var materialParameter = Material->MaterialParameterCBuffer->TryGetBuffer(); if (!materialParameter.IsEmpty) _originalMaterialParameter.AsSpan().CopyTo(materialParameter); @@ -59,7 +59,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase Material->ShaderFlags = shPkFlags; } - public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) + public void SetMaterialParameter(uint parameterCrc, Index offset, ReadOnlySpan value) { if (!CheckValidity()) return; @@ -68,7 +68,7 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (constantBuffer == null) return; - var buffer = constantBuffer->TryGetBuffer(); + var buffer = constantBuffer->TryGetBuffer(); if (buffer.IsEmpty) return; @@ -78,12 +78,10 @@ public sealed unsafe class LiveMaterialPreviewer : LiveMaterialPreviewerBase if (parameter.CRC != parameterCrc) continue; - if ((parameter.Offset & 0x3) != 0 - || (parameter.Size & 0x3) != 0 - || (parameter.Offset + parameter.Size) >> 2 > buffer.Length) + if (parameter.Offset + parameter.Size > buffer.Length) return; - value.TryCopyTo(buffer.Slice(parameter.Offset >> 2, parameter.Size >> 2)[offset..]); + value.TryCopyTo(buffer.Slice(parameter.Offset, parameter.Size)[offset..]); return; } } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs new file mode 100644 index 00000000..937614de --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -0,0 +1,509 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility; +using ImGuiNET; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Files; +using OtterGui.Text; +using Penumbra.GameData.Structs; +using OtterGui.Raii; +using OtterGui.Text.Widget; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + private static readonly float HalfMinValue = (float)Half.MinValue; + private static readonly float HalfMaxValue = (float)Half.MaxValue; + private static readonly float HalfEpsilon = (float)Half.Epsilon; + + private static readonly FontAwesomeCheckbox ApplyStainCheckbox = new(FontAwesomeIcon.FillDrip); + + private static (Vector2 Scale, float Rotation, float Shear)? _pinnedTileTransform; + + private bool DrawColorTableSection(bool disabled) + { + if ((!ShpkLoading && !SamplerIds.Contains(ShpkFile.TableSamplerId)) || Mtrl.Table == null) + return false; + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + if (!ImGui.CollapsingHeader("Color Table", ImGuiTreeNodeFlags.DefaultOpen)) + return false; + + ColorTableCopyAllClipboardButton(); + ImGui.SameLine(); + var ret = ColorTablePasteAllClipboardButton(disabled); + if (!disabled) + { + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImGui.SameLine(); + ret |= ColorTableDyeableCheckbox(); + } + + if (Mtrl.DyeTable != null) + { + ImGui.SameLine(); + ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImGui.SameLine(); + ret |= DrawPreviewDye(disabled); + } + + ret |= Mtrl.Table switch + { + LegacyColorTable legacyTable => DrawLegacyColorTable(legacyTable, Mtrl.DyeTable as LegacyColorDyeTable, disabled), + ColorTable table when Mtrl.ShaderPackage.Name is "characterlegacy.shpk" => DrawLegacyColorTable(table, Mtrl.DyeTable as ColorDyeTable, disabled), + _ => false, + }; + + return ret; + } + + private void ColorTableCopyAllClipboardButton() + { + if (Mtrl.Table == null) + return; + + if (!ImGui.Button("Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2(200, 0))) + return; + + try + { + var data1 = Mtrl.Table.AsBytes(); + var data2 = Mtrl.DyeTable != null ? Mtrl.DyeTable.AsBytes() : []; + + var array = new byte[data1.Length + data2.Length]; + data1.TryCopyTo(array); + data2.TryCopyTo(array.AsSpan(data1.Length)); + + var text = Convert.ToBase64String(array); + ImGui.SetClipboardText(text); + } + catch + { + // ignored + } + } + + private bool DrawPreviewDye(bool disabled) + { + var (dyeId1, (name1, dyeColor1, gloss1)) = _stainService.StainCombo1.CurrentSelection; + var (dyeId2, (name2, dyeColor2, gloss2)) = _stainService.StainCombo2.CurrentSelection; + var tt = dyeId1 == 0 && dyeId2 == 0 + ? "Select a preview dye first."u8 + : "Apply all preview values corresponding to the dye template and chosen dye where dyeing is enabled."u8; + if (ImUtf8.ButtonEx("Apply Preview Dye"u8, tt, disabled: disabled || dyeId1 == 0 && dyeId2 == 0)) + { + var ret = false; + if (Mtrl.DyeTable != null) + { + ret |= Mtrl.ApplyDye(_stainService.LegacyStmFile, [dyeId1, dyeId2]); + ret |= Mtrl.ApplyDye(_stainService.GudStmFile, [dyeId1, dyeId2]); + } + + UpdateColorTablePreview(); + + return ret; + } + + ImGui.SameLine(); + var label = dyeId1 == 0 ? "Preview Dye 1###previewDye1" : $"{name1} (Preview 1)###previewDye1"; + if (_stainService.StainCombo1.Draw(label, dyeColor1, string.Empty, true, gloss1)) + UpdateColorTablePreview(); + ImGui.SameLine(); + label = dyeId2 == 0 ? "Preview Dye 2###previewDye2" : $"{name2} (Preview 2)###previewDye2"; + if (_stainService.StainCombo2.Draw(label, dyeColor2, string.Empty, true, gloss2)) + UpdateColorTablePreview(); + return false; + } + + private bool ColorTablePasteAllClipboardButton(bool disabled) + { + if (Mtrl.Table == null) + return false; + + if (!ImUtf8.ButtonEx("Import All Rows from Clipboard"u8, ImGuiHelpers.ScaledVector2(200, 0), disabled)) + return false; + + try + { + var text = ImGui.GetClipboardText(); + var data = Convert.FromBase64String(text); + var table = Mtrl.Table.AsBytes(); + var dyeTable = Mtrl.DyeTable != null ? Mtrl.DyeTable.AsBytes() : []; + if (data.Length != table.Length && data.Length != table.Length + dyeTable.Length) + return false; + + data.AsSpan(0, table.Length).TryCopyTo(table); + data.AsSpan(table.Length).TryCopyTo(dyeTable); + + UpdateColorTablePreview(); + + return true; + } + catch + { + return false; + } + } + + [SkipLocalsInit] + private void ColorTableCopyClipboardButton(int rowIdx) + { + if (Mtrl.Table == null) + return; + + if (!ImUtf8.IconButton(FontAwesomeIcon.Clipboard, "Export this row to your clipboard."u8, + ImGui.GetFrameHeight() * Vector2.One)) + return; + + try + { + var data1 = Mtrl.Table.RowAsBytes(rowIdx); + var data2 = Mtrl.DyeTable != null ? Mtrl.DyeTable.RowAsBytes(rowIdx) : []; + + var array = new byte[data1.Length + data2.Length]; + data1.TryCopyTo(array); + data2.TryCopyTo(array.AsSpan(data1.Length)); + + var text = Convert.ToBase64String(array); + ImGui.SetClipboardText(text); + } + catch + { + // ignored + } + } + + private bool ColorTableDyeableCheckbox() + { + var dyeable = Mtrl.DyeTable != null; + var ret = ImGui.Checkbox("Dyeable", ref dyeable); + + if (ret) + { + Mtrl.DyeTable = dyeable ? Mtrl.Table switch + { + ColorTable => new ColorDyeTable(), + LegacyColorTable => new LegacyColorDyeTable(), + _ => null, + } : null; + UpdateColorTablePreview(); + } + + return ret; + } + + private bool ColorTablePasteFromClipboardButton(int rowIdx, bool disabled) + { + if (Mtrl.Table == null) + return false; + + if (!ImUtf8.IconButton(FontAwesomeIcon.Paste, "Import an exported row from your clipboard onto this row."u8, + ImGui.GetFrameHeight() * Vector2.One, disabled)) + return false; + + try + { + var text = ImGui.GetClipboardText(); + var data = Convert.FromBase64String(text); + var row = Mtrl.Table.RowAsBytes(rowIdx); + var dyeRow = Mtrl.DyeTable != null ? Mtrl.DyeTable.RowAsBytes(rowIdx) : []; + if (data.Length != row.Length && data.Length != row.Length + dyeRow.Length) + return false; + + data.AsSpan(0, row.Length).TryCopyTo(row); + data.AsSpan(row.Length).TryCopyTo(dyeRow); + + UpdateColorTableRowPreview(rowIdx); + + return true; + } + catch + { + return false; + } + } + + private void ColorTableHighlightButton(int pairIdx, bool disabled) + { + ImUtf8.IconButton(FontAwesomeIcon.Crosshairs, "Highlight this pair of rows on your character, if possible.\n\nHighlight colors can be configured in Penumbra's settings."u8, + ImGui.GetFrameHeight() * Vector2.One, disabled || ColorTablePreviewers.Count == 0); + + if (ImGui.IsItemHovered()) + HighlightColorTablePair(pairIdx); + else if (HighlightedColorTablePair == pairIdx) + CancelColorTableHighlight(); + } + + private static void CtBlendRect(Vector2 rcMin, Vector2 rcMax, uint topColor, uint bottomColor) + { + var style = ImGui.GetStyle(); + var frameRounding = style.FrameRounding; + var frameThickness = style.FrameBorderSize; + var borderColor = ImGui.GetColorU32(ImGuiCol.Border); + var drawList = ImGui.GetWindowDrawList(); + if (topColor == bottomColor) + drawList.AddRectFilled(rcMin, rcMax, topColor, frameRounding, ImDrawFlags.RoundCornersDefault); + else + { + drawList.AddRectFilled( + rcMin, rcMax with { Y = float.Lerp(rcMin.Y, rcMax.Y, 1.0f / 3) }, + topColor, frameRounding, ImDrawFlags.RoundCornersTopLeft | ImDrawFlags.RoundCornersTopRight); + drawList.AddRectFilledMultiColor( + rcMin with { Y = float.Lerp(rcMin.Y, rcMax.Y, 1.0f / 3) }, + rcMax with { Y = float.Lerp(rcMin.Y, rcMax.Y, 2.0f / 3) }, + topColor, topColor, bottomColor, bottomColor); + drawList.AddRectFilled( + rcMin with { Y = float.Lerp(rcMin.Y, rcMax.Y, 2.0f / 3) }, rcMax, + bottomColor, frameRounding, ImDrawFlags.RoundCornersBottomLeft | ImDrawFlags.RoundCornersBottomRight); + } + drawList.AddRect(rcMin, rcMax, borderColor, frameRounding, ImDrawFlags.RoundCornersDefault, frameThickness); + } + + private static bool CtColorPicker(ReadOnlySpan label, ReadOnlySpan description, HalfColor current, Action setter, ReadOnlySpan letter = default) + { + var ret = false; + var inputSqrt = PseudoSqrtRgb((Vector3)current); + var tmp = inputSqrt; + if (ImUtf8.ColorEdit(label, ref tmp, + ImGuiColorEditFlags.NoInputs + | ImGuiColorEditFlags.DisplayRGB + | ImGuiColorEditFlags.InputRGB + | ImGuiColorEditFlags.NoTooltip + | ImGuiColorEditFlags.HDR) + && tmp != inputSqrt) + { + setter((HalfColor)PseudoSquareRgb(tmp)); + ret = true; + } + + if (letter.Length > 0 && ImGui.IsItemVisible()) + { + var textSize = ImUtf8.CalcTextSize(letter); + var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; + var textColor = inputSqrt.LengthSquared() < 0.25f ? 0x80FFFFFFu : 0x80000000u; + ImGui.GetWindowDrawList().AddText(letter, center, textColor); + } + + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + + return ret; + } + + private static void CtColorPicker(ReadOnlySpan label, ReadOnlySpan description, HalfColor? current, ReadOnlySpan letter = default) + { + if (current.HasValue) + CtColorPicker(label, description, current.Value, Nop, letter); + else + { + var tmp = Vector4.Zero; + ImUtf8.ColorEdit(label, ref tmp, + ImGuiColorEditFlags.NoInputs + | ImGuiColorEditFlags.DisplayRGB + | ImGuiColorEditFlags.InputRGB + | ImGuiColorEditFlags.NoTooltip + | ImGuiColorEditFlags.HDR + | ImGuiColorEditFlags.AlphaPreview); + + if (letter.Length > 0 && ImGui.IsItemVisible()) + { + var textSize = ImUtf8.CalcTextSize(letter); + var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; + ImGui.GetWindowDrawList().AddText(letter, center, 0x80000000u); + } + + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + } + } + + private static bool CtApplyStainCheckbox(ReadOnlySpan label, ReadOnlySpan description, bool current, Action setter) + { + var tmp = current; + var result = ApplyStainCheckbox.Draw(label, ref tmp); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + if (!result || tmp == current) + return false; + + setter(tmp); + return true; + } + + private static bool CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, Half value, ReadOnlySpan format, float min, float max, float speed, Action setter) + { + var tmp = (float)value; + var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + if (!result) + return false; + var newValue = (Half)tmp; + if (newValue == value) + return false; + setter(newValue); + return true; + } + + private static bool CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, ref Half value, ReadOnlySpan format, float min, float max, float speed) + { + var tmp = (float)value; + var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + if (!result) + return false; + var newValue = (Half)tmp; + if (newValue == value) + return false; + value = newValue; + return true; + } + + private static void CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, Half? value, ReadOnlySpan format) + { + using var _ = ImRaii.Disabled(); + var valueOrDefault = value ?? Half.Zero; + var floatValue = (float)valueOrDefault; + CtDragHalf(label, description, valueOrDefault, value.HasValue ? format : "-"u8, floatValue, floatValue, 0.0f, Nop); + } + + private static bool CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, T value, ReadOnlySpan format, T min, T max, float speed, Action setter) where T : unmanaged, INumber + { + var tmp = value; + var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + if (!result || tmp == value) + return false; + setter(tmp); + return true; + } + + private static bool CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, ref T value, ReadOnlySpan format, T min, T max, float speed) where T : unmanaged, INumber + { + var tmp = value; + var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); + if (!result || tmp == value) + return false; + value = tmp; + return true; + } + + private static void CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, T? value, ReadOnlySpan format) where T : unmanaged, INumber + { + using var _ = ImRaii.Disabled(); + var valueOrDefault = value ?? T.Zero; + CtDragScalar(label, description, valueOrDefault, value.HasValue ? format : "-"u8, valueOrDefault, valueOrDefault, 0.0f, Nop); + } + + private bool CtTileIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ushort value, bool compact, Action setter) + { + if (!_materialTemplatePickers.DrawTileIndexPicker(label, description, ref value, compact)) + return false; + setter(value); + return true; + } + + private bool CtSphereMapIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ushort value, bool compact, Action setter) + { + if (!_materialTemplatePickers.DrawSphereMapIndexPicker(label, description, ref value, compact)) + return false; + setter(value); + return true; + } + + private bool CtTileTransformMatrix(HalfMatrix2x2 value, float floatSize, bool twoRowLayout, Action setter) + { + var ret = false; + if (_config.EditRawTileTransforms) + { + var tmp = value; + ImGui.SetNextItemWidth(floatSize); + ret |= CtDragHalf("##TileTransformUU"u8, "Tile Repeat U"u8, ref tmp.UU, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + ret |= CtDragHalf("##TileTransformVV"u8, "Tile Repeat V"u8, ref tmp.VV, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + if (!twoRowLayout) + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + ret |= CtDragHalf("##TileTransformUV"u8, "Tile Skew U"u8, ref tmp.UV, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + ret |= CtDragHalf("##TileTransformVU"u8, "Tile Skew V"u8, ref tmp.VU, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + if (!ret || tmp == value) + return false; + setter(tmp); + } + else + { + value.Decompose(out var scale, out var rotation, out var shear); + rotation *= 180.0f / MathF.PI; + shear *= 180.0f / MathF.PI; + ImGui.SetNextItemWidth(floatSize); + var scaleXChanged = CtDragScalar("##TileScaleU"u8, "Tile Scale U"u8, ref scale.X, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + var activated = ImGui.IsItemActivated(); + var deactivated = ImGui.IsItemDeactivated(); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + var scaleYChanged = CtDragScalar("##TileScaleV"u8, "Tile Scale V"u8, ref scale.Y, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + activated |= ImGui.IsItemActivated(); + deactivated |= ImGui.IsItemDeactivated(); + if (!twoRowLayout) + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + var rotationChanged = CtDragScalar("##TileRotation"u8, "Tile Rotation"u8, ref rotation, "%.0f°"u8, -180.0f, 180.0f, 1.0f); + activated |= ImGui.IsItemActivated(); + deactivated |= ImGui.IsItemDeactivated(); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + var shearChanged = CtDragScalar("##TileShear"u8, "Tile Shear"u8, ref shear, "%.0f°"u8, -90.0f, 90.0f, 1.0f); + activated |= ImGui.IsItemActivated(); + deactivated |= ImGui.IsItemDeactivated(); + if (deactivated) + _pinnedTileTransform = null; + else if (activated) + _pinnedTileTransform = (scale, rotation, shear); + ret = scaleXChanged | scaleYChanged | rotationChanged | shearChanged; + if (!ret) + return false; + if (_pinnedTileTransform.HasValue) + { + var (pinScale, pinRotation, pinShear) = _pinnedTileTransform.Value; + if (!scaleXChanged) + scale.X = pinScale.X; + if (!scaleYChanged) + scale.Y = pinScale.Y; + if (!rotationChanged) + rotation = pinRotation; + if (!shearChanged) + shear = pinShear; + } + var newValue = HalfMatrix2x2.Compose(scale, rotation * MathF.PI / 180.0f, shear * MathF.PI / 180.0f); + if (newValue == value) + return false; + setter(newValue); + } + return true; + } + + /// For use as setter of read-only fields. + private static void Nop(T _) + { } + + // Functions to deal with squared RGB values without making negatives useless. + + internal static float PseudoSquareRgb(float x) + => x < 0.0f ? -(x * x) : x * x; + + internal static Vector3 PseudoSquareRgb(Vector3 vec) + => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z)); + + internal static Vector4 PseudoSquareRgb(Vector4 vec) + => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z), vec.W); + + internal static float PseudoSqrtRgb(float x) + => x < 0.0f ? -MathF.Sqrt(-x) : MathF.Sqrt(x); + + internal static Vector3 PseudoSqrtRgb(Vector3 vec) + => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z)); + + internal static Vector4 PseudoSqrtRgb(Vector4 vec) + => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z), vec.W); +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs new file mode 100644 index 00000000..56496005 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs @@ -0,0 +1,277 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Classes; +using OtterGui.Raii; +using OtterGui.Text; +using OtterGui.Text.Widget.Editors; +using Penumbra.GameData.Files.ShaderStructs; +using static Penumbra.GameData.Files.ShpkFile; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + private const float MaterialConstantSize = 250.0f; + + public readonly + List<(string Header, List<(string Label, int ConstantIndex, Range Slice, string Description, bool MonoFont, IEditor Editor)> + Constants)> Constants = new(16); + + private void UpdateConstants() + { + static List FindOrAddGroup(List<(string, List)> groups, string name) + { + foreach (var (groupName, group) in groups) + { + if (string.Equals(name, groupName, StringComparison.Ordinal)) + return group; + } + + var newGroup = new List(16); + groups.Add((name, newGroup)); + return newGroup; + } + + Constants.Clear(); + string mpPrefix; + if (AssociatedShpk == null) + { + mpPrefix = MaterialParamsConstantName.Value!; + var fcGroup = FindOrAddGroup(Constants, "Further Constants"); + foreach (var (constant, index) in Mtrl.ShaderPackage.Constants.WithIndex()) + { + var values = Mtrl.GetConstantValue(constant); + for (var i = 0; i < values.Length; i += 4) + { + fcGroup.Add(($"0x{constant.Id:X8}", index, i..Math.Min(i + 4, values.Length), string.Empty, true, + ConstantEditors.DefaultFloat)); + } + } + } + else + { + mpPrefix = AssociatedShpk.GetConstantById(MaterialParamsConstantId)?.Name ?? MaterialParamsConstantName.Value!; + var autoNameMaxLength = Math.Max(Names.LongestKnownNameLength, mpPrefix.Length + 8); + foreach (var shpkConstant in AssociatedShpk.MaterialParams) + { + var name = Names.KnownNames.TryResolve(shpkConstant.Id); + var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, AssociatedShpk, out var constantIndex); + var values = Mtrl.GetConstantValue(constant); + var handledElements = new IndexSet(values.Length, false); + + var dkData = TryGetShpkDevkitData("Constants", shpkConstant.Id, true); + if (dkData != null) + foreach (var dkConstant in dkData) + { + var offset = (int)dkConstant.EffectiveByteOffset; + var length = values.Length - offset; + var constantSize = dkConstant.EffectiveByteSize; + if (constantSize.HasValue) + length = Math.Min(length, (int)constantSize.Value); + if (length <= 0) + continue; + + var editor = dkConstant.CreateEditor(_materialTemplatePickers); + if (editor != null) + FindOrAddGroup(Constants, dkConstant.Group.Length > 0 ? dkConstant.Group : "Further Constants") + .Add((dkConstant.Label, constantIndex, offset..(offset + length), dkConstant.Description, false, editor)); + handledElements.AddRange(offset, length); + } + + if (handledElements.IsFull) + continue; + + var fcGroup = FindOrAddGroup(Constants, "Further Constants"); + foreach (var (start, end) in handledElements.Ranges(complement: true)) + { + if (start == 0 && end == values.Length && end - start <= 16) + { + if (name.Value != null) + { + fcGroup.Add(( + $"{name.Value.PadRight(autoNameMaxLength)} (0x{shpkConstant.Id:X8})", + constantIndex, 0..values.Length, string.Empty, true, DefaultConstantEditorFor(name))); + continue; + } + } + + if ((shpkConstant.ByteOffset & 0x3) == 0 && (shpkConstant.ByteSize & 0x3) == 0) + { + var offset = shpkConstant.ByteOffset; + for (int i = (start & ~0xF) - (offset & 0xF), j = offset >> 4; i < end; i += 16, ++j) + { + var rangeStart = Math.Max(i, start); + var rangeEnd = Math.Min(i + 16, end); + if (rangeEnd > rangeStart) + { + var autoName = $"{mpPrefix}[{j,2:D}]{VectorSwizzle(((offset + rangeStart) & 0xF) >> 2, ((offset + rangeEnd - 1) & 0xF) >> 2)}"; + fcGroup.Add(( + $"{autoName.PadRight(autoNameMaxLength)} (0x{shpkConstant.Id:X8})", + constantIndex, rangeStart..rangeEnd, string.Empty, true, DefaultConstantEditorFor(name))); + } + } + } + else + { + for (var i = start; i < end; i += 16) + { + fcGroup.Add(($"{"???".PadRight(autoNameMaxLength)} (0x{shpkConstant.Id:X8})", constantIndex, i..Math.Min(i + 16, end), string.Empty, true, + DefaultConstantEditorFor(name))); + } + } + } + } + } + + Constants.RemoveAll(group => group.Constants.Count == 0); + Constants.Sort((x, y) => + { + if (string.Equals(x.Header, "Further Constants", StringComparison.Ordinal)) + return 1; + if (string.Equals(y.Header, "Further Constants", StringComparison.Ordinal)) + return -1; + + return string.Compare(x.Header, y.Header, StringComparison.Ordinal); + }); + // HACK the Replace makes w appear after xyz, for the cbuffer-location-based naming scheme, and cbuffer-location names appear after known variable names + foreach (var (_, group) in Constants) + { + group.Sort((x, y) => string.CompareOrdinal( + x.MonoFont ? x.Label.Replace("].w", "].{").Replace(mpPrefix, "}_MaterialParameter") : x.Label, + y.MonoFont ? y.Label.Replace("].w", "].{").Replace(mpPrefix, "}_MaterialParameter") : y.Label)); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private IEditor DefaultConstantEditorFor(Name name) + => ConstantEditors.DefaultFor(name, _materialTemplatePickers); + + private bool DrawConstantsSection(bool disabled) + { + if (Constants.Count == 0) + return false; + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + if (!ImGui.CollapsingHeader("Material Constants")) + return false; + + using var _ = ImRaii.PushId("MaterialConstants"); + + var ret = false; + foreach (var (header, group) in Constants) + { + using var t = ImRaii.TreeNode(header, ImGuiTreeNodeFlags.DefaultOpen); + if (!t) + continue; + + foreach (var (label, constantIndex, slice, description, monoFont, editor) in group) + { + var constant = Mtrl.ShaderPackage.Constants[constantIndex]; + var buffer = Mtrl.GetConstantValue(constant); + if (buffer.Length > 0) + { + using var id = ImRaii.PushId($"##{constant.Id:X8}:{slice.Start}"); + ImGui.SetNextItemWidth(MaterialConstantSize * UiHelpers.Scale); + if (editor.Draw(buffer[slice], disabled)) + { + ret = true; + SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); + } + var shpkConstant = AssociatedShpk?.GetMaterialParamById(constant.Id); + var defaultConstantValue = shpkConstant.HasValue ? AssociatedShpk!.GetMaterialParamDefault(shpkConstant.Value) : []; + var defaultValue = IsValid(slice, defaultConstantValue.Length) ? defaultConstantValue[slice] : []; + var canReset = AssociatedShpk?.MaterialParamsDefaults != null + ? defaultValue.Length > 0 && !defaultValue.SequenceEqual(buffer[slice]) + : buffer[slice].ContainsAnyExcept((byte)0); + ImUtf8.SameLineInner(); + if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Backspace.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, + "Reset this constant to its default value.\n\nHold Ctrl to unlock.", !ImGui.GetIO().KeyCtrl || !canReset, true)) + { + ret = true; + if (defaultValue.Length > 0) + defaultValue.CopyTo(buffer[slice]); + else + buffer[slice].Clear(); + + SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); + } + + ImGui.SameLine(); + using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); + } + } + } + + return ret; + } + + private static bool IsValid(Range range, int length) + { + var start = range.Start.GetOffset(length); + var end = range.End.GetOffset(length); + return start >= 0 && start <= length && end >= start && end <= length; + } + + internal static string? MaterialParamName(bool componentOnly, int offset) + { + if (offset < 0) + return null; + + return (componentOnly, offset & 0x3) switch + { + (true, 0) => "x", + (true, 1) => "y", + (true, 2) => "z", + (true, 3) => "w", + (false, 0) => $"[{offset >> 2:D2}].x", + (false, 1) => $"[{offset >> 2:D2}].y", + (false, 2) => $"[{offset >> 2:D2}].z", + (false, 3) => $"[{offset >> 2:D2}].w", + _ => null, + }; + } + + /// Returned string is 4 chars long. + private static string VectorSwizzle(int firstComponent, int lastComponent) + => (firstComponent, lastComponent) switch + { + (0, 4) => " ", + (0, 0) => ".x ", + (0, 1) => ".xy ", + (0, 2) => ".xyz", + (0, 3) => " ", + (1, 1) => ".y ", + (1, 2) => ".yz ", + (1, 3) => ".yzw", + (2, 2) => ".z ", + (2, 3) => ".zw ", + (3, 3) => ".w ", + _ => string.Empty, + }; + + internal static (string? Name, bool ComponentOnly) MaterialParamRangeName(string prefix, int valueOffset, int valueLength) + { + if (valueLength == 0 || valueOffset < 0) + return (null, false); + + var firstVector = valueOffset >> 2; + var lastVector = (valueOffset + valueLength - 1) >> 2; + var firstComponent = valueOffset & 0x3; + var lastComponent = (valueOffset + valueLength - 1) & 0x3; + if (firstVector == lastVector) + return ($"{prefix}[{firstVector}]{VectorSwizzle(firstComponent, lastComponent)}", true); + + var sb = new StringBuilder(128); + sb.Append($"{prefix}[{firstVector}]{VectorSwizzle(firstComponent, 3).TrimEnd()}"); + for (var i = firstVector + 1; i < lastVector; ++i) + sb.Append($", [{i}]"); + + sb.Append($", [{lastVector}]{VectorSwizzle(0, lastComponent)}"); + return (sb.ToString(), false); + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs new file mode 100644 index 00000000..cd62d58f --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs @@ -0,0 +1,240 @@ +using Newtonsoft.Json.Linq; +using OtterGui.Text.Widget.Editors; +using Penumbra.String.Classes; +using static Penumbra.GameData.Files.ShpkFile; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + private JObject? TryLoadShpkDevkit(string shpkBaseName, out string devkitPathName) + { + try + { + if (!Utf8GamePath.FromString("penumbra/shpk_devkit/" + shpkBaseName + ".json", out var devkitPath)) + throw new Exception("Could not assemble ShPk dev-kit path."); + + var devkitFullPath = _edit.FindBestMatch(devkitPath); + if (!devkitFullPath.IsRooted) + throw new Exception("Could not resolve ShPk dev-kit path."); + + devkitPathName = devkitFullPath.FullName; + return JObject.Parse(File.ReadAllText(devkitFullPath.FullName)); + } + catch + { + devkitPathName = string.Empty; + return null; + } + } + + private T? TryGetShpkDevkitData(string category, uint? id, bool mayVary) where T : class + => TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) + ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); + + private T? TryGetShpkDevkitData(JObject? devkit, string devkitPathName, string category, uint? id, bool mayVary) where T : class + { + if (devkit == null) + return null; + + try + { + var data = devkit[category]; + if (id.HasValue) + data = data?[id.Value.ToString()]; + + if (mayVary && (data as JObject)?["Vary"] != null) + { + var selector = BuildSelector(data!["Vary"]! + .Select(key => (uint)key) + .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); + var index = (int)data["Selectors"]![selector.ToString()]!; + data = data["Items"]![index]; + } + + return data?.ToObject(typeof(T)) as T; + } + catch (Exception e) + { + // Some element in the JSON was undefined or invalid (wrong type, key that doesn't exist in the ShPk, index out of range, …) + Penumbra.Log.Error($"Error while traversing the ShPk dev-kit file at {devkitPathName}: {e}"); + return null; + } + } + + private sealed class DevkitShaderKeyValue + { + public string Label = string.Empty; + public string Description = string.Empty; + } + + private sealed class DevkitShaderKey + { + public string Label = string.Empty; + public string Description = string.Empty; + public Dictionary Values = []; + } + + private sealed class DevkitSampler + { + public string Label = string.Empty; + public string Description = string.Empty; + public string DefaultTexture = string.Empty; + } + + private enum DevkitConstantType + { + Hidden = -1, + Float = 0, + /// Integer encoded as a float. + Integer = 1, + Color = 2, + Enum = 3, + /// Native integer. + Int32 = 4, + Int32Enum = 5, + Int8 = 6, + Int8Enum = 7, + Int16 = 8, + Int16Enum = 9, + Int64 = 10, + Int64Enum = 11, + Half = 12, + Double = 13, + TileIndex = 14, + SphereMapIndex = 15, + } + + private sealed class DevkitConstantValue + { + public string Label = string.Empty; + public string Description = string.Empty; + public double Value = 0; + } + + private sealed class DevkitConstant + { + public uint Offset = 0; + public uint? Length = null; + public uint? ByteOffset = null; + public uint? ByteSize = null; + public string Group = string.Empty; + public string Label = string.Empty; + public string Description = string.Empty; + public DevkitConstantType Type = DevkitConstantType.Float; + + public float? Minimum = null; + public float? Maximum = null; + public float Step = 0.0f; + public float StepFast = 0.0f; + public float? Speed = null; + public float RelativeSpeed = 0.0f; + public float Exponent = 1.0f; + public float Factor = 1.0f; + public float Bias = 0.0f; + public byte Precision = 3; + public bool Hex = false; + public bool Slider = true; + public bool Drag = true; + public string Unit = string.Empty; + + public bool SquaredRgb = false; + public bool Clamped = false; + + public DevkitConstantValue[] Values = []; + + public uint EffectiveByteOffset + => ByteOffset ?? Offset * ValueSize; + + public uint? EffectiveByteSize + => ByteSize ?? (Length * ValueSize); + + public unsafe uint ValueSize + => Type switch + { + DevkitConstantType.Hidden => sizeof(byte), + DevkitConstantType.Float => sizeof(float), + DevkitConstantType.Integer => sizeof(float), + DevkitConstantType.Color => sizeof(float), + DevkitConstantType.Enum => sizeof(float), + DevkitConstantType.Int32 => sizeof(int), + DevkitConstantType.Int32Enum => sizeof(int), + DevkitConstantType.Int8 => sizeof(byte), + DevkitConstantType.Int8Enum => sizeof(byte), + DevkitConstantType.Int16 => sizeof(short), + DevkitConstantType.Int16Enum => sizeof(short), + DevkitConstantType.Int64 => sizeof(long), + DevkitConstantType.Int64Enum => sizeof(long), + DevkitConstantType.Half => (uint)sizeof(Half), + DevkitConstantType.Double => sizeof(double), + DevkitConstantType.TileIndex => sizeof(float), + DevkitConstantType.SphereMapIndex => sizeof(float), + _ => sizeof(float), + }; + + public IEditor? CreateEditor(MaterialTemplatePickers? materialTemplatePickers) + => Type switch + { + DevkitConstantType.Hidden => null, + DevkitConstantType.Float => CreateFloatEditor().AsByteEditor(), + DevkitConstantType.Integer => CreateIntegerEditor().IntAsFloatEditor().AsByteEditor(), + DevkitConstantType.Color => ColorEditor.Get(!Clamped).WithExponent(SquaredRgb ? 2.0f : 1.0f).AsByteEditor(), + DevkitConstantType.Enum => CreateEnumEditor(float.CreateSaturating).AsByteEditor(), + DevkitConstantType.Int32 => CreateIntegerEditor().AsByteEditor(), + DevkitConstantType.Int32Enum => CreateEnumEditor(ToInteger).AsByteEditor(), + DevkitConstantType.Int8 => CreateIntegerEditor(), + DevkitConstantType.Int8Enum => CreateEnumEditor(ToInteger), + DevkitConstantType.Int16 => CreateIntegerEditor().AsByteEditor(), + DevkitConstantType.Int16Enum => CreateEnumEditor(ToInteger).AsByteEditor(), + DevkitConstantType.Int64 => CreateIntegerEditor().AsByteEditor(), + DevkitConstantType.Int64Enum => CreateEnumEditor(ToInteger).AsByteEditor(), + DevkitConstantType.Half => CreateFloatEditor().AsByteEditor(), + DevkitConstantType.Double => CreateFloatEditor().AsByteEditor(), + DevkitConstantType.TileIndex => materialTemplatePickers?.TileIndexPicker ?? ConstantEditors.DefaultIntAsFloat, + DevkitConstantType.SphereMapIndex => materialTemplatePickers?.SphereMapIndexPicker ?? ConstantEditors.DefaultIntAsFloat, + _ => ConstantEditors.DefaultFloat, + }; + + private IEditor CreateIntegerEditor() + where T : unmanaged, INumber + => ((Drag || Slider) && !Hex + ? (Drag + ? (IEditor)DragEditor.CreateInteger(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, Unit, 0) + : SliderEditor.CreateInteger(ToInteger(Minimum) ?? default, ToInteger(Maximum) ?? default, Unit, 0)) + : InputEditor.CreateInteger(ToInteger(Minimum), ToInteger(Maximum), ToInteger(Step), ToInteger(StepFast), Hex, Unit, 0)) + .WithFactorAndBias(ToInteger(Factor), ToInteger(Bias)); + + private IEditor CreateFloatEditor() + where T : unmanaged, INumber, IPowerFunctions + => ((Drag || Slider) + ? (Drag + ? (IEditor)DragEditor.CreateFloat(ToFloat(Minimum), ToFloat(Maximum), Speed ?? 0.1f, RelativeSpeed, Precision, Unit, 0) + : SliderEditor.CreateFloat(ToFloat(Minimum) ?? default, ToFloat(Maximum) ?? default, Precision, Unit, 0)) + : InputEditor.CreateFloat(ToFloat(Minimum), ToFloat(Maximum), T.CreateSaturating(Step), T.CreateSaturating(StepFast), Precision, Unit, 0)) + .WithExponent(T.CreateSaturating(Exponent)) + .WithFactorAndBias(T.CreateSaturating(Factor), T.CreateSaturating(Bias)); + + private EnumEditor CreateEnumEditor(Func convertValue) + where T : unmanaged, IUtf8SpanFormattable, IEqualityOperators + => new(Array.ConvertAll(Values, value => (ToUtf8(value.Label), convertValue(value.Value), ToUtf8(value.Description)))); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T ToInteger(float value) where T : struct, INumberBase + => T.CreateSaturating(MathF.Round(value)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T ToInteger(double value) where T : struct, INumberBase + => T.CreateSaturating(Math.Round(value)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T? ToInteger(float? value) where T : struct, INumberBase + => value.HasValue ? ToInteger(value.Value) : null; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T? ToFloat(float? value) where T : struct, INumberBase + => value.HasValue ? T.CreateSaturating(value.Value) : null; + + private static ReadOnlyMemory ToUtf8(string value) + => Encoding.UTF8.GetBytes(value); + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs new file mode 100644 index 00000000..f3ec5307 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -0,0 +1,368 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui; +using OtterGui.Text; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Files.StainMapStructs; +using Penumbra.Services; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + private const float LegacyColorTableFloatSize = 65.0f; + private const float LegacyColorTablePercentageSize = 50.0f; + private const float LegacyColorTableIntegerSize = 40.0f; + private const float LegacyColorTableByteSize = 25.0f; + + private bool DrawLegacyColorTable(LegacyColorTable table, LegacyColorDyeTable? dyeTable, bool disabled) + { + using var imTable = ImUtf8.Table("##ColorTable"u8, dyeTable != null ? 10 : 8, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV); + if (!imTable) + return false; + + DrawLegacyColorTableHeader(dyeTable != null); + + var ret = false; + for (var i = 0; i < LegacyColorTable.NumRows; ++i) + { + if (DrawLegacyColorTableRow(table, dyeTable, i, disabled)) + { + UpdateColorTableRowPreview(i); + ret = true; + } + ImGui.TableNextRow(); + } + + return ret; + } + + private bool DrawLegacyColorTable(ColorTable table, ColorDyeTable? dyeTable, bool disabled) + { + using var imTable = ImUtf8.Table("##ColorTable"u8, dyeTable != null ? 10 : 8, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV); + if (!imTable) + return false; + + DrawLegacyColorTableHeader(dyeTable != null); + + var ret = false; + for (var i = 0; i < ColorTable.NumRows; ++i) + { + if (DrawLegacyColorTableRow(table, dyeTable, i, disabled)) + { + UpdateColorTableRowPreview(i); + ret = true; + } + ImGui.TableNextRow(); + } + + return ret; + } + + private static void DrawLegacyColorTableHeader(bool hasDyeTable) + { + ImGui.TableNextColumn(); + ImUtf8.TableHeader(default(ReadOnlySpan)); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Row"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Diffuse"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Specular"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Emissive"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Gloss"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Tile"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Repeat / Skew"u8); + if (hasDyeTable) + { + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Dye"u8); + ImGui.TableNextColumn(); + ImUtf8.TableHeader("Dye Preview"u8); + } + } + + private bool DrawLegacyColorTableRow(LegacyColorTable table, LegacyColorDyeTable? dyeTable, int rowIdx, bool disabled) + { + using var id = ImRaii.PushId(rowIdx); + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var floatSize = LegacyColorTableFloatSize * UiHelpers.Scale; + var pctSize = LegacyColorTablePercentageSize * UiHelpers.Scale; + var intSize = LegacyColorTableIntegerSize * UiHelpers.Scale; + ImGui.TableNextColumn(); + ColorTableCopyClipboardButton(rowIdx); + ImUtf8.SameLineInner(); + var ret = ColorTablePasteFromClipboardButton(rowIdx, disabled); + if ((rowIdx & 1) == 0) + { + ImUtf8.SameLineInner(); + ColorTableHighlightButton(rowIdx >> 1, disabled); + } + + ImGui.TableNextColumn(); + using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) + ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); + + ImGui.TableNextColumn(); + using var dis = ImRaii.Disabled(disabled); + ret |= CtColorPicker("##Diffuse"u8, "Diffuse Color"u8, row.DiffuseColor, + c => table[rowIdx].DiffuseColor = c); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeDiffuse"u8, "Apply Diffuse Color on Dye"u8, dye.DiffuseColor, + b => dyeTable[rowIdx].DiffuseColor = b); + } + + ImGui.TableNextColumn(); + ret |= CtColorPicker("##Specular"u8, "Specular Color"u8, row.SpecularColor, + c => table[rowIdx].SpecularColor = c); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeSpecular"u8, "Apply Specular Color on Dye"u8, dye.SpecularColor, + b => dyeTable[rowIdx].SpecularColor = b); + } + ImGui.SameLine(); + ImGui.SetNextItemWidth(pctSize); + ret |= CtDragScalar("##SpecularMask"u8, "Specular Strength"u8, (float)row.SpecularMask * 100.0f, "%.0f%%"u8, 0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].SpecularMask = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeSpecularMask"u8, "Apply Specular Strength on Dye"u8, dye.SpecularMask, + b => dyeTable[rowIdx].SpecularMask = b); + } + + ImGui.TableNextColumn(); + ret |= CtColorPicker("##Emissive"u8, "Emissive Color"u8, row.EmissiveColor, + c => table[rowIdx].EmissiveColor = c); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeEmissive"u8, "Apply Emissive Color on Dye"u8, dye.EmissiveColor, + b => dyeTable[rowIdx].EmissiveColor = b); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(floatSize); + var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; + ret |= CtDragHalf("##Shininess"u8, "Gloss Strength"u8, row.Shininess, "%.1f"u8, glossStrengthMin, HalfMaxValue, Math.Max(0.1f, (float)row.Shininess * 0.025f), + v => table[rowIdx].Shininess = v); + + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeShininess"u8, "Apply Gloss Strength on Dye"u8, dye.Shininess, + b => dyeTable[rowIdx].Shininess = b); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(intSize); + ret |= CtTileIndexPicker("##TileIndex"u8, "Tile Index"u8, row.TileIndex, true, + value => table[rowIdx].TileIndex = value); + + ImGui.TableNextColumn(); + ret |= CtTileTransformMatrix(row.TileTransform, floatSize, false, + m => table[rowIdx].TileTransform = m); + + if (dyeTable != null) + { + ImGui.TableNextColumn(); + if (_stainService.LegacyTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) + { + dyeTable[rowIdx].Template = _stainService.LegacyTemplateCombo.CurrentSelection; + ret = true; + } + + ImGuiUtil.HoverTooltip("Dye Template", ImGuiHoveredFlags.AllowWhenDisabled); + + ImGui.TableNextColumn(); + ret |= DrawLegacyDyePreview(rowIdx, disabled, dye, floatSize); + } + + return ret; + } + + private bool DrawLegacyColorTableRow(ColorTable table, ColorDyeTable? dyeTable, int rowIdx, bool disabled) + { + using var id = ImRaii.PushId(rowIdx); + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var floatSize = LegacyColorTableFloatSize * UiHelpers.Scale; + var pctSize = LegacyColorTablePercentageSize * UiHelpers.Scale; + var intSize = LegacyColorTableIntegerSize * UiHelpers.Scale; + var byteSize = LegacyColorTableByteSize * UiHelpers.Scale; + ImGui.TableNextColumn(); + ColorTableCopyClipboardButton(rowIdx); + ImUtf8.SameLineInner(); + var ret = ColorTablePasteFromClipboardButton(rowIdx, disabled); + if ((rowIdx & 1) == 0) + { + ImUtf8.SameLineInner(); + ColorTableHighlightButton(rowIdx >> 1, disabled); + } + + ImGui.TableNextColumn(); + using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) + ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); + + ImGui.TableNextColumn(); + using var dis = ImRaii.Disabled(disabled); + ret |= CtColorPicker("##Diffuse"u8, "Diffuse Color"u8, row.DiffuseColor, + c => table[rowIdx].DiffuseColor = c); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeDiffuse"u8, "Apply Diffuse Color on Dye"u8, dye.DiffuseColor, + b => dyeTable[rowIdx].DiffuseColor = b); + } + + ImGui.TableNextColumn(); + ret |= CtColorPicker("##Specular"u8, "Specular Color"u8, row.SpecularColor, + c => table[rowIdx].SpecularColor = c); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeSpecular"u8, "Apply Specular Color on Dye"u8, dye.SpecularColor, + b => dyeTable[rowIdx].SpecularColor = b); + } + ImGui.SameLine(); + ImGui.SetNextItemWidth(pctSize); + ret |= CtDragScalar("##SpecularMask"u8, "Specular Strength"u8, (float)row.Scalar7 * 100.0f, "%.0f%%"u8, 0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].Scalar7 = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeSpecularMask"u8, "Apply Specular Strength on Dye"u8, dye.Metalness, + b => dyeTable[rowIdx].Metalness = b); + } + + ImGui.TableNextColumn(); + ret |= CtColorPicker("##Emissive"u8, "Emissive Color"u8, row.EmissiveColor, + c => table[rowIdx].EmissiveColor = c); + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeEmissive"u8, "Apply Emissive Color on Dye"u8, dye.EmissiveColor, + b => dyeTable[rowIdx].EmissiveColor = b); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(floatSize); + var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; + ret |= CtDragHalf("##Shininess"u8, "Gloss Strength"u8, row.Scalar3, "%.1f"u8, glossStrengthMin, HalfMaxValue, Math.Max(0.1f, (float)row.Scalar3 * 0.025f), + v => table[rowIdx].Scalar3 = v); + + if (dyeTable != null) + { + ImUtf8.SameLineInner(); + ret |= CtApplyStainCheckbox("##dyeShininess"u8, "Apply Gloss Strength on Dye"u8, dye.Scalar3, + b => dyeTable[rowIdx].Scalar3 = b); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(intSize); + ret |= CtTileIndexPicker("##TileIndex"u8, "Tile Index"u8, row.TileIndex, true, + value => table[rowIdx].TileIndex = value); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(pctSize); + ret |= CtDragScalar("##TileAlpha"u8, "Tile Opacity"u8, (float)row.TileAlpha * 100.0f, "%.0f%%"u8, 0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].TileAlpha = (Half)(v * 0.01f)); + + ImGui.TableNextColumn(); + ret |= CtTileTransformMatrix(row.TileTransform, floatSize, false, + m => table[rowIdx].TileTransform = m); + + if (dyeTable != null) + { + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(byteSize); + ret |= CtDragScalar("##DyeChannel"u8, "Dye Channel"u8, dye.Channel + 1, "%hhd"u8, 1, StainService.ChannelCount, 0.25f, + value => dyeTable[rowIdx].Channel = (byte)(Math.Clamp(value, 1, StainService.ChannelCount) - 1)); + ImUtf8.SameLineInner(); + _stainService.LegacyTemplateCombo.CurrentDyeChannel = dye.Channel; + if (_stainService.LegacyTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) + { + dyeTable[rowIdx].Template = _stainService.LegacyTemplateCombo.CurrentSelection; + ret = true; + } + + ImGuiUtil.HoverTooltip("Dye Template", ImGuiHoveredFlags.AllowWhenDisabled); + + ImGui.TableNextColumn(); + ret |= DrawLegacyDyePreview(rowIdx, disabled, dye, floatSize); + } + + return ret; + } + + private bool DrawLegacyDyePreview(int rowIdx, bool disabled, LegacyColorDyeTable.Row dye, float floatSize) + { + var stain = _stainService.StainCombo1.CurrentSelection.Key; + if (stain == 0 || !_stainService.LegacyStmFile.TryGetValue(dye.Template, stain, out var values)) + return false; + + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing / 2); + + var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), + "Apply the selected dye to this row.", disabled, true); + + ret = ret && Mtrl.ApplyDyeToRow(_stainService.LegacyStmFile, [stain], rowIdx); + + ImGui.SameLine(); + DrawLegacyDyePreview(values, floatSize); + + return ret; + } + + private bool DrawLegacyDyePreview(int rowIdx, bool disabled, ColorDyeTable.Row dye, float floatSize) + { + var stain = _stainService.GetStainCombo(dye.Channel).CurrentSelection.Key; + if (stain == 0 || !_stainService.LegacyStmFile.TryGetValue(dye.Template, stain, out var values)) + return false; + + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing / 2); + + var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), + "Apply the selected dye to this row.", disabled, true); + + ret = ret && Mtrl.ApplyDyeToRow(_stainService.LegacyStmFile, [ + _stainService.StainCombo1.CurrentSelection.Key, + _stainService.StainCombo2.CurrentSelection.Key, + ], rowIdx); + + ImGui.SameLine(); + DrawLegacyDyePreview(values, floatSize); + + return ret; + } + + private static void DrawLegacyDyePreview(LegacyDyePack values, float floatSize) + { + CtColorPicker("##diffusePreview"u8, default, values.DiffuseColor, "D"u8); + ImUtf8.SameLineInner(); + CtColorPicker("##specularPreview"u8, default, values.SpecularColor, "S"u8); + ImUtf8.SameLineInner(); + CtColorPicker("##emissivePreview"u8, default, values.EmissiveColor, "E"u8); + ImUtf8.SameLineInner(); + using var dis = ImRaii.Disabled(); + ImGui.SetNextItemWidth(floatSize); + var shininess = (float)values.Shininess; + ImGui.DragFloat("##shininessPreview", ref shininess, 0, shininess, shininess, "%.1f G"); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(floatSize); + var specularMask = (float)values.SpecularMask * 100.0f; + ImGui.DragFloat("##specularMaskPreview", ref specularMask, 0, specularMask, specularMask, "%.0f%% S"); + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs new file mode 100644 index 00000000..bb346534 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs @@ -0,0 +1,272 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Structs; +using Penumbra.Interop.MaterialPreview; +using Penumbra.Services; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + public readonly List MaterialPreviewers = new(4); + public readonly List ColorTablePreviewers = new(4); + public int HighlightedColorTablePair = -1; + public readonly Stopwatch HighlightTime = new(); + + private void DrawMaterialLivePreviewRebind(bool disabled) + { + if (disabled) + return; + + if (ImGui.Button("Reload live preview")) + BindToMaterialInstances(); + + if (MaterialPreviewers.Count != 0 || ColorTablePreviewers.Count != 0) + return; + + ImGui.SameLine(); + using var c = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); + ImUtf8.Text( + "The current material has not been found on your character. Please check the Import from Screen tab for more information."u8); + } + + public unsafe void BindToMaterialInstances() + { + UnbindFromMaterialInstances(); + + var instances = MaterialInfo.FindMaterials(_resourceTreeFactory.GetLocalPlayerRelatedCharacters().Select(ch => ch.Address), + FilePath); + + var foundMaterials = new HashSet(); + foreach (var materialInfo in instances) + { + var material = materialInfo.GetDrawObjectMaterial(_objects); + if (foundMaterials.Contains((nint)material)) + continue; + + try + { + MaterialPreviewers.Add(new LiveMaterialPreviewer(_objects, materialInfo)); + foundMaterials.Add((nint)material); + } + catch (InvalidOperationException) + { + // Carry on without that previewer. + } + } + + UpdateMaterialPreview(); + + if (Mtrl.Table == null) + return; + + foreach (var materialInfo in instances) + { + try + { + ColorTablePreviewers.Add(new LiveColorTablePreviewer(_objects, _framework, materialInfo)); + } + catch (InvalidOperationException) + { + // Carry on without that previewer. + } + } + + UpdateColorTablePreview(); + } + + private void UnbindFromMaterialInstances() + { + foreach (var previewer in MaterialPreviewers) + previewer.Dispose(); + MaterialPreviewers.Clear(); + + foreach (var previewer in ColorTablePreviewers) + previewer.Dispose(); + ColorTablePreviewers.Clear(); + } + + private unsafe void UnbindFromDrawObjectMaterialInstances(CharacterBase* characterBase) + { + for (var i = MaterialPreviewers.Count; i-- > 0;) + { + var previewer = MaterialPreviewers[i]; + if (previewer.DrawObject != characterBase) + continue; + + previewer.Dispose(); + MaterialPreviewers.RemoveAt(i); + } + + for (var i = ColorTablePreviewers.Count; i-- > 0;) + { + var previewer = ColorTablePreviewers[i]; + if (previewer.DrawObject != characterBase) + continue; + + previewer.Dispose(); + ColorTablePreviewers.RemoveAt(i); + } + } + + public void SetShaderPackageFlags(uint shPkFlags) + { + foreach (var previewer in MaterialPreviewers) + previewer.SetShaderPackageFlags(shPkFlags); + } + + public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) + { + foreach (var previewer in MaterialPreviewers) + previewer.SetMaterialParameter(parameterCrc, offset, value); + } + + public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) + { + foreach (var previewer in MaterialPreviewers) + previewer.SetSamplerFlags(samplerCrc, samplerFlags); + } + + private void UpdateMaterialPreview() + { + SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); + foreach (var constant in Mtrl.ShaderPackage.Constants) + { + var values = Mtrl.GetConstantValue(constant); + if (values != null) + SetMaterialParameter(constant.Id, 0, values); + } + + foreach (var sampler in Mtrl.ShaderPackage.Samplers) + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + public void HighlightColorTablePair(int pairIdx) + { + var oldPairIdx = HighlightedColorTablePair; + + if (HighlightedColorTablePair != pairIdx) + { + HighlightedColorTablePair = pairIdx; + HighlightTime.Restart(); + } + + if (oldPairIdx >= 0) + { + UpdateColorTableRowPreview(oldPairIdx << 1); + UpdateColorTableRowPreview((oldPairIdx << 1) | 1); + } + if (pairIdx >= 0) + { + UpdateColorTableRowPreview(pairIdx << 1); + UpdateColorTableRowPreview((pairIdx << 1) | 1); + } + } + + public void CancelColorTableHighlight() + { + var pairIdx = HighlightedColorTablePair; + + HighlightedColorTablePair = -1; + HighlightTime.Reset(); + + if (pairIdx >= 0) + { + UpdateColorTableRowPreview(pairIdx << 1); + UpdateColorTableRowPreview((pairIdx << 1) | 1); + } + } + + public void UpdateColorTableRowPreview(int rowIdx) + { + if (ColorTablePreviewers.Count == 0) + return; + + if (Mtrl.Table == null) + return; + + var row = Mtrl.Table switch + { + LegacyColorTable legacyTable => new ColorTable.Row(legacyTable[rowIdx]), + ColorTable table => table[rowIdx], + _ => throw new InvalidOperationException($"Unsupported color table type {Mtrl.Table.GetType()}"), + }; + if (Mtrl.DyeTable != null) + { + var dyeRow = Mtrl.DyeTable switch + { + LegacyColorDyeTable legacyDyeTable => new ColorDyeTable.Row(legacyDyeTable[rowIdx]), + ColorDyeTable dyeTable => dyeTable[rowIdx], + _ => throw new InvalidOperationException($"Unsupported color dye table type {Mtrl.DyeTable.GetType()}"), + }; + if (dyeRow.Channel < StainService.ChannelCount) + { + StainId stainId = _stainService.GetStainCombo(dyeRow.Channel).CurrentSelection.Key; + if (_stainService.LegacyStmFile.TryGetValue(dyeRow.Template, stainId, out var legacyDyes)) + row.ApplyDye(dyeRow, legacyDyes); + if (_stainService.GudStmFile.TryGetValue(dyeRow.Template, stainId, out var gudDyes)) + row.ApplyDye(dyeRow, gudDyes); + } + } + + if (HighlightedColorTablePair << 1 == rowIdx) + ApplyHighlight(ref row, ColorId.InGameHighlight, (float)HighlightTime.Elapsed.TotalSeconds); + else if (((HighlightedColorTablePair << 1) | 1) == rowIdx) + ApplyHighlight(ref row, ColorId.InGameHighlight2, (float)HighlightTime.Elapsed.TotalSeconds); + + foreach (var previewer in ColorTablePreviewers) + { + row[..].CopyTo(previewer.GetColorRow(rowIdx)); + previewer.ScheduleUpdate(); + } + } + + public void UpdateColorTablePreview() + { + if (ColorTablePreviewers.Count == 0) + return; + + if (Mtrl.Table == null) + return; + + var rows = new ColorTable(Mtrl.Table); + var dyeRows = Mtrl.DyeTable != null ? ColorDyeTable.CastOrConvert(Mtrl.DyeTable) : null; + if (dyeRows != null) + { + ReadOnlySpan stainIds = [ + _stainService.StainCombo1.CurrentSelection.Key, + _stainService.StainCombo2.CurrentSelection.Key, + ]; + rows.ApplyDye(_stainService.LegacyStmFile, stainIds, dyeRows); + rows.ApplyDye(_stainService.GudStmFile, stainIds, dyeRows); + } + + if (HighlightedColorTablePair >= 0) + { + ApplyHighlight(ref rows[HighlightedColorTablePair << 1], ColorId.InGameHighlight, (float)HighlightTime.Elapsed.TotalSeconds); + ApplyHighlight(ref rows[(HighlightedColorTablePair << 1) | 1], ColorId.InGameHighlight2, (float)HighlightTime.Elapsed.TotalSeconds); + } + + foreach (var previewer in ColorTablePreviewers) + { + rows.AsHalves().CopyTo(previewer.ColorTable); + previewer.ScheduleUpdate(); + } + } + + private static void ApplyHighlight(ref ColorTable.Row row, ColorId colorId, float time) + { + var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; + var baseColor = colorId.Value(); + var color = level * new Vector3(baseColor & 0xFF, (baseColor >> 8) & 0xFF, (baseColor >> 16) & 0xFF); + var halfColor = (HalfColor)(color * color); + + row.DiffuseColor = halfColor; + row.SpecularColor = halfColor; + row.EmissiveColor = halfColor; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs new file mode 100644 index 00000000..21557939 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -0,0 +1,505 @@ +using Dalamud.Interface; +using Dalamud.Interface.ImGuiNotification; +using ImGuiNET; +using Newtonsoft.Json.Linq; +using OtterGui; +using OtterGui.Classes; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.GameData; +using Penumbra.GameData.Data; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.ShaderStructs; +using Penumbra.String.Classes; +using static Penumbra.GameData.Files.ShpkFile; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + // strings path/to/the.exe | grep --fixed-strings '.shpk' | sort -u | sed -e 's#^shader/sm5/shpk/##' + // Apricot shader packages are unlisted because + // 1. they cause severe performance/memory issues when calculating the effective shader set + // 2. they probably aren't intended for use with materials anyway + internal static readonly IReadOnlyList StandardShaderPackages = new[] + { + "3dui.shpk", + // "apricot_decal_dummy.shpk", + // "apricot_decal_ring.shpk", + // "apricot_decal.shpk", + // "apricot_fogModel.shpk", + // "apricot_gbuffer_decal_dummy.shpk", + // "apricot_gbuffer_decal_ring.shpk", + // "apricot_gbuffer_decal.shpk", + // "apricot_lightmodel.shpk", + // "apricot_model_dummy.shpk", + // "apricot_model_morph.shpk", + // "apricot_model.shpk", + // "apricot_powder_dummy.shpk", + // "apricot_powder.shpk", + // "apricot_shape_dummy.shpk", + // "apricot_shape.shpk", + "bgcolorchange.shpk", + "bg_composite.shpk", + "bgcrestchange.shpk", + "bgdecal.shpk", + "bgprop.shpk", + "bg.shpk", + "bguvscroll.shpk", + "characterglass.shpk", + "characterinc.shpk", + "characterlegacy.shpk", + "characterocclusion.shpk", + "characterreflection.shpk", + "characterscroll.shpk", + "charactershadowoffset.shpk", + "character.shpk", + "characterstockings.shpk", + "charactertattoo.shpk", + "charactertransparency.shpk", + "cloud.shpk", + "createviewposition.shpk", + "crystal.shpk", + "directionallighting.shpk", + "directionalshadow.shpk", + "furblur.shpk", + "grassdynamicwave.shpk", + "grass.shpk", + "hairmask.shpk", + "hair.shpk", + "iris.shpk", + "lightshaft.shpk", + "linelighting.shpk", + "planelighting.shpk", + "pointlighting.shpk", + "river.shpk", + "shadowmask.shpk", + "skin.shpk", + "spotlighting.shpk", + "subsurfaceblur.shpk", + "verticalfog.shpk", + "water.shpk", + "weather.shpk", + }; + + private static readonly byte[] UnknownShadersString = Encoding.UTF8.GetBytes("Vertex Shaders: ???\nPixel Shaders: ???"); + + private string[]? _shpkNames; + + public string ShaderHeader = "Shader###Shader"; + public FullPath LoadedShpkPath = FullPath.Empty; + public string LoadedShpkPathName = string.Empty; + public string LoadedShpkDevkitPathName = string.Empty; + public string ShaderComment = string.Empty; + public ShpkFile? AssociatedShpk; + public bool ShpkLoading; + public JObject? AssociatedShpkDevkit; + + public readonly string LoadedBaseDevkitPathName; + public readonly JObject? AssociatedBaseDevkit; + + // Shader Key State + public readonly + List<(string Label, int Index, string Description, bool MonoFont, IReadOnlyList<(string Label, uint Value, string Description)> + Values)> ShaderKeys = new(16); + + public readonly HashSet VertexShaders = new(16); + public readonly HashSet PixelShaders = new(16); + public bool ShadersKnown; + public ReadOnlyMemory ShadersString = UnknownShadersString; + + public string[] GetShpkNames() + { + if (null != _shpkNames) + return _shpkNames; + + var names = new HashSet(StandardShaderPackages); + names.UnionWith(_edit.FindPathsStartingWith(ShpkPrefix).Select(path => path.ToString()[ShpkPrefixLength..])); + + _shpkNames = names.ToArray(); + Array.Sort(_shpkNames); + + return _shpkNames; + } + + public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) + { + defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); + if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) + return FullPath.Empty; + + return _edit.FindBestMatch(defaultGamePath); + } + + public void LoadShpk(FullPath path) + => Task.Run(() => DoLoadShpk(path)); + + private async Task DoLoadShpk(FullPath path) + { + ShadersKnown = false; + ShaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; + ShpkLoading = true; + + try + { + var data = path.IsRooted + ? await File.ReadAllBytesAsync(path.FullName) + : _gameData.GetFile(path.InternalName.ToString())?.Data; + LoadedShpkPath = path; + AssociatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); + LoadedShpkPathName = path.ToPath(); + } + catch (Exception e) + { + LoadedShpkPath = FullPath.Empty; + LoadedShpkPathName = string.Empty; + AssociatedShpk = null; + Penumbra.Messager.NotificationMessage(e, $"Could not load {LoadedShpkPath.ToPath()}.", NotificationType.Error, false); + } + finally + { + ShpkLoading = false; + } + + if (LoadedShpkPath.InternalName.IsEmpty) + { + AssociatedShpkDevkit = null; + LoadedShpkDevkitPathName = string.Empty; + } + else + { + AssociatedShpkDevkit = + TryLoadShpkDevkit(Path.GetFileNameWithoutExtension(Mtrl.ShaderPackage.Name), out LoadedShpkDevkitPathName); + } + + UpdateShaderKeys(); + _updateOnNextFrame = true; + } + + private void UpdateShaderKeys() + { + ShaderKeys.Clear(); + if (AssociatedShpk != null) + foreach (var key in AssociatedShpk.MaterialKeys) + { + var keyName = Names.KnownNames.TryResolve(key.Id); + var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); + var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); + + var valueSet = new HashSet(key.Values); + if (dkData != null) + valueSet.UnionWith(dkData.Values.Keys); + + var valueKnownNames = keyName.WithKnownSuffixes(); + + var mtrlKeyIndex = Mtrl.FindOrAddShaderKey(key.Id, key.DefaultValue); + var values = valueSet.Select(value => + { + var valueName = valueKnownNames.TryResolve(Names.KnownNames, value); + if (dkData != null && dkData.Values.TryGetValue(value, out var dkValue)) + return (dkValue.Label.Length > 0 ? dkValue.Label : valueName.ToString(), value, dkValue.Description); + + return (valueName.ToString(), value, string.Empty); + }).ToArray(); + Array.Sort(values, (x, y) => + { + if (x.Value == key.DefaultValue) + return -1; + if (y.Value == key.DefaultValue) + return 1; + + return string.Compare(x.Label, y.Label, StringComparison.Ordinal); + }); + ShaderKeys.Add((hasDkLabel ? dkData!.Label : keyName.ToString(), mtrlKeyIndex, dkData?.Description ?? string.Empty, + !hasDkLabel, values)); + } + else + foreach (var (key, index) in Mtrl.ShaderPackage.ShaderKeys.WithIndex()) + { + var keyName = Names.KnownNames.TryResolve(key.Category); + var valueName = keyName.WithKnownSuffixes().TryResolve(Names.KnownNames, key.Value); + ShaderKeys.Add((keyName.ToString(), index, string.Empty, true, [(valueName.ToString(), key.Value, string.Empty)])); + } + } + + private void UpdateShaders() + { + static void AddShader(HashSet globalSet, Dictionary> byPassSets, uint passId, int shaderIndex) + { + globalSet.Add(shaderIndex); + if (!byPassSets.TryGetValue(passId, out var passSet)) + { + passSet = []; + byPassSets.Add(passId, passSet); + } + passSet.Add(shaderIndex); + } + + VertexShaders.Clear(); + PixelShaders.Clear(); + + var vertexShadersByPass = new Dictionary>(); + var pixelShadersByPass = new Dictionary>(); + + if (AssociatedShpk == null || !AssociatedShpk.IsExhaustiveNodeAnalysisFeasible()) + { + ShadersKnown = false; + } + else + { + ShadersKnown = true; + var systemKeySelectors = AllSelectors(AssociatedShpk.SystemKeys).ToArray(); + var sceneKeySelectors = AllSelectors(AssociatedShpk.SceneKeys).ToArray(); + var subViewKeySelectors = AllSelectors(AssociatedShpk.SubViewKeys).ToArray(); + var materialKeySelector = + BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); + + foreach (var systemKeySelector in systemKeySelectors) + { + foreach (var sceneKeySelector in sceneKeySelectors) + { + foreach (var subViewKeySelector in subViewKeySelectors) + { + var selector = BuildSelector(systemKeySelector, sceneKeySelector, materialKeySelector, subViewKeySelector); + var node = AssociatedShpk.GetNodeBySelector(selector); + if (node.HasValue) + foreach (var pass in node.Value.Passes) + { + AddShader(VertexShaders, vertexShadersByPass, pass.Id, (int)pass.VertexShader); + AddShader(PixelShaders, pixelShadersByPass, pass.Id, (int)pass.PixelShader); + } + else + ShadersKnown = false; + } + } + } + } + + if (ShadersKnown) + { + var builder = new StringBuilder(); + foreach (var (passId, passVS) in vertexShadersByPass) + { + if (builder.Length > 0) + builder.Append("\n\n"); + + var passName = Names.KnownNames.TryResolve(passId); + var shaders = passVS.OrderBy(i => i).Select(i => $"#{i}"); + builder.Append($"Vertex Shaders ({passName}): {string.Join(", ", shaders)}"); + if (pixelShadersByPass.TryGetValue(passId, out var passPS)) + { + shaders = passPS.OrderBy(i => i).Select(i => $"#{i}"); + builder.Append($"\nPixel Shaders ({passName}): {string.Join(", ", shaders)}"); + } + } + foreach (var (passId, passPS) in pixelShadersByPass) + { + if (vertexShadersByPass.ContainsKey(passId)) + continue; + + if (builder.Length > 0) + builder.Append("\n\n"); + + var passName = Names.KnownNames.TryResolve(passId); + var shaders = passPS.OrderBy(i => i).Select(i => $"#{i}"); + builder.Append($"Pixel Shaders ({passName}): {string.Join(", ", shaders)}"); + } + + ShadersString = Encoding.UTF8.GetBytes(builder.ToString()); + } + else + ShadersString = UnknownShadersString; + + ShaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; + } + + private bool DrawShaderSection(bool disabled) + { + var ret = false; + if (ImGui.CollapsingHeader(ShaderHeader)) + { + ret |= DrawPackageNameInput(disabled); + ret |= DrawShaderFlagsInput(disabled); + DrawCustomAssociations(); + ret |= DrawMaterialShaderKeys(disabled); + DrawMaterialShaders(); + } + + if (!ShpkLoading && (AssociatedShpk == null || AssociatedShpkDevkit == null)) + { + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + + if (AssociatedShpk == null) + { + ImUtf8.Text("Unable to find a suitable shader (.shpk) file for cross-references. Some functionality will be missing."u8, + ImGuiUtil.HalfBlendText(0x80u)); // Half red + } + else + { + ImUtf8.Text("No dev-kit file found for this material's shaders. Please install one for optimal editing experience, such as actual constant names instead of hexadecimal identifiers."u8, + ImGuiUtil.HalfBlendText(0x8080u)); // Half yellow + } + } + + return ret; + } + + private bool DrawPackageNameInput(bool disabled) + { + if (disabled) + { + ImGui.TextUnformatted("Shader Package: " + Mtrl.ShaderPackage.Name); + return false; + } + + var ret = false; + ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); + using var c = ImRaii.Combo("Shader Package", Mtrl.ShaderPackage.Name); + if (c) + foreach (var value in GetShpkNames()) + { + if (ImGui.Selectable(value, value == Mtrl.ShaderPackage.Name)) + { + Mtrl.ShaderPackage.Name = value; + ret = true; + AssociatedShpk = null; + LoadedShpkPath = FullPath.Empty; + LoadShpk(FindAssociatedShpk(out _, out _)); + } + } + + return ret; + } + + private bool DrawShaderFlagsInput(bool disabled) + { + var shpkFlags = (int)Mtrl.ShaderPackage.Flags; + ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); + if (!ImGui.InputInt("Shader Flags", ref shpkFlags, 0, 0, + ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) + return false; + + Mtrl.ShaderPackage.Flags = (uint)shpkFlags; + SetShaderPackageFlags((uint)shpkFlags); + return true; + } + + /// + /// Show the currently associated shpk file, if any, and the buttons to associate + /// a specific shpk from your drive, the modded shpk by path or the default shpk. + /// + private void DrawCustomAssociations() + { + const string tooltip = "Click to copy file path to clipboard."; + var text = AssociatedShpk == null + ? "Associated .shpk file: None" + : $"Associated .shpk file: {LoadedShpkPathName}"; + var devkitText = AssociatedShpkDevkit == null + ? "Associated dev-kit file: None" + : $"Associated dev-kit file: {LoadedShpkDevkitPathName}"; + var baseDevkitText = AssociatedBaseDevkit == null + ? "Base dev-kit file: None" + : $"Base dev-kit file: {LoadedBaseDevkitPathName}"; + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + + ImGuiUtil.CopyOnClickSelectable(text, LoadedShpkPathName, tooltip); + ImGuiUtil.CopyOnClickSelectable(devkitText, LoadedShpkDevkitPathName, tooltip); + ImGuiUtil.CopyOnClickSelectable(baseDevkitText, LoadedBaseDevkitPathName, tooltip); + + if (ImGui.Button("Associate Custom .shpk File")) + _fileDialog.OpenFilePicker("Associate Custom .shpk File...", ".shpk", (success, name) => + { + if (success) + LoadShpk(new FullPath(name[0])); + }, 1, _edit.Mod!.ModPath.FullName, false); + + var moddedPath = FindAssociatedShpk(out var defaultPath, out var gamePath); + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton("Associate Default .shpk File", Vector2.Zero, moddedPath.ToPath(), + moddedPath.Equals(LoadedShpkPath))) + LoadShpk(moddedPath); + + if (!gamePath.Path.Equals(moddedPath.InternalName)) + { + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton("Associate Unmodded .shpk File", Vector2.Zero, defaultPath, + gamePath.Path.Equals(LoadedShpkPath.InternalName))) + LoadShpk(new FullPath(gamePath)); + } + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + } + + private bool DrawMaterialShaderKeys(bool disabled) + { + if (ShaderKeys.Count == 0) + return false; + + var ret = false; + foreach (var (label, index, description, monoFont, values) in ShaderKeys) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); + ref var key = ref Mtrl.ShaderPackage.ShaderKeys[index]; + var shpkKey = AssociatedShpk?.GetMaterialKeyById(key.Category); + var currentValue = key.Value; + var (currentLabel, _, currentDescription) = + values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); + if (!disabled && shpkKey.HasValue) + { + ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); + using (var c = ImRaii.Combo($"##{key.Category:X8}", currentLabel)) + { + if (c) + foreach (var (valueLabel, value, valueDescription) in values) + { + if (ImGui.Selectable(valueLabel, value == currentValue)) + { + key.Value = value; + ret = true; + Update(); + } + + if (valueDescription.Length > 0) + ImGuiUtil.SelectableHelpMarker(valueDescription); + } + } + + ImGui.SameLine(); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); + } + else if (description.Length > 0 || currentDescription.Length > 0) + { + ImGuiUtil.LabeledHelpMarker($"{label}: {currentLabel}", + description + (description.Length > 0 && currentDescription.Length > 0 ? "\n\n" : string.Empty) + currentDescription); + } + else + { + ImGui.TextUnformatted($"{label}: {currentLabel}"); + } + } + + return ret; + } + + private void DrawMaterialShaders() + { + if (AssociatedShpk == null) + return; + + using (var node = ImUtf8.TreeNode("Candidate Shaders"u8)) + { + if (node) + ImUtf8.Text(ShadersString.Span); + } + + if (ShaderComment.Length > 0) + { + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ImGui.TextUnformatted(ShaderComment); + } + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs new file mode 100644 index 00000000..3181dafe --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs @@ -0,0 +1,276 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.GameData; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.String.Classes; +using static Penumbra.GameData.Files.MaterialStructs.SamplerFlags; +using static Penumbra.GameData.Files.ShpkFile; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + public readonly List<(string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont)> Textures = new(4); + + public readonly HashSet UnfoldedTextures = new(4); + public readonly HashSet SamplerIds = new(16); + public float TextureLabelWidth; + + private void UpdateTextures() + { + Textures.Clear(); + SamplerIds.Clear(); + if (AssociatedShpk == null) + { + SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); + if (Mtrl.Table != null) + SamplerIds.Add(TableSamplerId); + + foreach (var (sampler, index) in Mtrl.ShaderPackage.Samplers.WithIndex()) + Textures.Add(($"0x{sampler.SamplerId:X8}", sampler.TextureIndex, index, string.Empty, true)); + } + else + { + foreach (var index in VertexShaders) + SamplerIds.UnionWith(AssociatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); + foreach (var index in PixelShaders) + SamplerIds.UnionWith(AssociatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); + if (!ShadersKnown) + { + SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); + if (Mtrl.Table != null) + SamplerIds.Add(TableSamplerId); + } + + foreach (var samplerId in SamplerIds) + { + var shpkSampler = AssociatedShpk.GetSamplerById(samplerId); + if (shpkSampler is not { Slot: 2 }) + continue; + + var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); + var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); + + var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); + Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, + dkData?.Description ?? string.Empty, !hasDkLabel)); + } + + if (SamplerIds.Contains(TableSamplerId)) + Mtrl.Table ??= new ColorTable(); + } + + Textures.Sort((x, y) => string.CompareOrdinal(x.Label, y.Label)); + + TextureLabelWidth = 50f * UiHelpers.Scale; + + float helpWidth; + using (var _ = ImRaii.PushFont(UiBuilder.IconFont)) + { + helpWidth = ImGui.GetStyle().ItemSpacing.X + ImGui.CalcTextSize(FontAwesomeIcon.InfoCircle.ToIconString()).X; + } + + foreach (var (label, _, _, description, monoFont) in Textures) + { + if (!monoFont) + TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); + } + + using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) + { + foreach (var (label, _, _, description, monoFont) in Textures) + { + if (monoFont) + TextureLabelWidth = Math.Max(TextureLabelWidth, + ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); + } + } + + TextureLabelWidth = TextureLabelWidth / UiHelpers.Scale + 4; + } + + private static ReadOnlySpan TextureAddressModeTooltip(TextureAddressMode addressMode) + => addressMode switch + { + TextureAddressMode.Wrap => "Tile the texture at every UV integer junction.\n\nFor example, for U values between 0 and 3, the texture is repeated three times."u8, + TextureAddressMode.Mirror => "Flip the texture at every UV integer junction.\n\nFor U values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is mirrored; between 2 and 3, the texture is normal again; and so on."u8, + TextureAddressMode.Clamp => "Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively."u8, + TextureAddressMode.Border => "Texture coordinates outside the range [0.0, 1.0] are set to the border color (generally black)."u8, + _ => ""u8, + }; + + private bool DrawTextureSection(bool disabled) + { + if (Textures.Count == 0) + return false; + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + if (!ImGui.CollapsingHeader("Textures and Samplers", ImGuiTreeNodeFlags.DefaultOpen)) + return false; + + var frameHeight = ImGui.GetFrameHeight(); + var ret = false; + using var table = ImRaii.Table("##Textures", 3); + + ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, frameHeight); + ImGui.TableSetupColumn("Path", ImGuiTableColumnFlags.WidthStretch); + ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthFixed, TextureLabelWidth * UiHelpers.Scale); + foreach (var (label, textureI, samplerI, description, monoFont) in Textures) + { + using var _ = ImRaii.PushId(samplerI); + var tmp = Mtrl.Textures[textureI].Path; + var unfolded = UnfoldedTextures.Contains(samplerI); + ImGui.TableNextColumn(); + if (ImGuiUtil.DrawDisabledButton((unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(), + new Vector2(frameHeight), + "Settings for this texture and the associated sampler", false, true)) + { + unfolded = !unfolded; + if (unfolded) + UnfoldedTextures.Add(samplerI); + else + UnfoldedTextures.Remove(samplerI); + } + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); + if (ImGui.InputText(string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, + disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) + && tmp.Length > 0 + && tmp != Mtrl.Textures[textureI].Path) + { + ret = true; + Mtrl.Textures[textureI].Path = tmp; + } + + ImGui.TableNextColumn(); + using (var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont)) + { + ImGui.AlignTextToFramePadding(); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); + } + + if (unfolded) + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + ret |= DrawMaterialSampler(disabled, textureI, samplerI); + ImGui.TableNextColumn(); + } + } + + return ret; + } + + private static bool ComboTextureAddressMode(ReadOnlySpan label, ref TextureAddressMode value) + { + using var c = ImUtf8.Combo(label, value.ToString()); + if (!c) + return false; + + var ret = false; + foreach (var mode in Enum.GetValues()) + { + if (ImGui.Selectable(mode.ToString(), mode == value)) + { + value = mode; + ret = true; + } + + ImUtf8.SelectableHelpMarker(TextureAddressModeTooltip(mode)); + } + + return ret; + } + + private bool DrawMaterialSampler(bool disabled, int textureIdx, int samplerIdx) + { + var ret = false; + ref var texture = ref Mtrl.Textures[textureIdx]; + ref var sampler = ref Mtrl.ShaderPackage.Samplers[samplerIdx]; + + var dx11 = texture.DX11; + if (ImUtf8.Checkbox("Prepend -- to the file name on DirectX 11"u8, ref dx11)) + { + texture.DX11 = dx11; + ret = true; + } + + ref var samplerFlags = ref SamplerFlags.Wrap(ref sampler.Flags); + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + var addressMode = samplerFlags.UAddressMode; + if (ComboTextureAddressMode("##UAddressMode"u8, ref addressMode)) + { + samplerFlags.UAddressMode = addressMode; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("U Address Mode"u8, "Method to use for resolving a U texture coordinate that is outside the 0 to 1 range."); + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + addressMode = samplerFlags.VAddressMode; + if (ComboTextureAddressMode("##VAddressMode"u8, ref addressMode)) + { + samplerFlags.VAddressMode = addressMode; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("V Address Mode"u8, "Method to use for resolving a V texture coordinate that is outside the 0 to 1 range."); + + var lodBias = samplerFlags.LodBias; + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImUtf8.DragScalar("##LoDBias"u8, ref lodBias, -8.0f, 7.984375f, 0.1f)) + { + samplerFlags.LodBias = lodBias; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("Level of Detail Bias"u8, + "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); + + var minLod = samplerFlags.MinLod; + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImUtf8.DragScalar("##MinLoD"u8, ref minLod, 0, 15, 0.1f)) + { + samplerFlags.MinLod = minLod; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("Minimum Level of Detail"u8, + "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); + + using var t = ImUtf8.TreeNode("Advanced Settings"u8); + if (!t) + return ret; + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImUtf8.InputScalar("Texture Flags"u8, ref texture.Flags, "%04X"u8, + flags: disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None)) + ret = true; + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImUtf8.InputScalar("Sampler Flags"u8, ref sampler.Flags, "%08X"u8, + flags: ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) + { + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs new file mode 100644 index 00000000..2d4e93f1 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs @@ -0,0 +1,199 @@ +using Dalamud.Plugin.Services; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using OtterGui.Widgets; +using Penumbra.GameData; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Interop; +using Penumbra.Interop.Hooks.Objects; +using Penumbra.Interop.ResourceTree; +using Penumbra.Services; +using Penumbra.String; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public sealed partial class MtrlTab : IWritable, IDisposable +{ + private const int ShpkPrefixLength = 16; + + private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); + + private readonly IDataManager _gameData; + private readonly IFramework _framework; + private readonly ObjectManager _objects; + private readonly CharacterBaseDestructor _characterBaseDestructor; + private readonly StainService _stainService; + private readonly ResourceTreeFactory _resourceTreeFactory; + private readonly FileDialogService _fileDialog; + private readonly MaterialTemplatePickers _materialTemplatePickers; + private readonly Configuration _config; + + private readonly ModEditWindow _edit; + public readonly MtrlFile Mtrl; + public readonly string FilePath; + public readonly bool Writable; + + private bool _updateOnNextFrame; + + public unsafe MtrlTab(IDataManager gameData, IFramework framework, ObjectManager objects, CharacterBaseDestructor characterBaseDestructor, + StainService stainService, ResourceTreeFactory resourceTreeFactory, FileDialogService fileDialog, MaterialTemplatePickers materialTemplatePickers, + Configuration config, ModEditWindow edit, MtrlFile file, string filePath, bool writable) + { + _gameData = gameData; + _framework = framework; + _objects = objects; + _characterBaseDestructor = characterBaseDestructor; + _stainService = stainService; + _resourceTreeFactory = resourceTreeFactory; + _fileDialog = fileDialog; + _materialTemplatePickers = materialTemplatePickers; + _config = config; + + _edit = edit; + Mtrl = file; + FilePath = filePath; + Writable = writable; + AssociatedBaseDevkit = TryLoadShpkDevkit("_base", out LoadedBaseDevkitPathName); + Update(); + LoadShpk(FindAssociatedShpk(out _, out _)); + if (writable) + { + _characterBaseDestructor.Subscribe(UnbindFromDrawObjectMaterialInstances, CharacterBaseDestructor.Priority.MtrlTab); + BindToMaterialInstances(); + } + } + + public bool DrawVersionUpdate(bool disabled) + { + if (disabled || Mtrl.IsDawntrail) + return false; + + if (!ImUtf8.ButtonEx("Update MTRL Version to Dawntrail"u8, + "Try using this if the material can not be loaded or should use legacy shaders.\n\nThis is not revertible."u8, + new Vector2(-0.1f, 0), false, 0, Colors.PressEnterWarningBg)) + return false; + + Mtrl.MigrateToDawntrail(); + Update(); + LoadShpk(FindAssociatedShpk(out _, out _)); + return true; + } + + public bool DrawPanel(bool disabled) + { + if (_updateOnNextFrame) + { + _updateOnNextFrame = false; + Update(); + } + + DrawMaterialLivePreviewRebind(disabled); + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + var ret = DrawBackFaceAndTransparency(disabled); + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + ret |= DrawShaderSection(disabled); + + ret |= DrawTextureSection(disabled); + ret |= DrawColorTableSection(disabled); + ret |= DrawConstantsSection(disabled); + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + DrawOtherMaterialDetails(disabled); + + return !disabled && ret; + } + + private bool DrawBackFaceAndTransparency(bool disabled) + { + ref var shaderFlags = ref ShaderFlags.Wrap(ref Mtrl.ShaderPackage.Flags); + + var ret = false; + + using var dis = ImRaii.Disabled(disabled); + + var tmp = shaderFlags.EnableTransparency; + if (ImGui.Checkbox("Enable Transparency", ref tmp)) + { + shaderFlags.EnableTransparency = tmp; + ret = true; + SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); + } + + ImGui.SameLine(200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); + tmp = shaderFlags.HideBackfaces; + if (ImGui.Checkbox("Hide Backfaces", ref tmp)) + { + shaderFlags.HideBackfaces = tmp; + ret = true; + SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); + } + + if (ShpkLoading) + { + ImGui.SameLine(400 * UiHelpers.Scale + 2 * ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); + + ImUtf8.Text("Loading shader (.shpk) file. Some functionality will only be available after this is done."u8, + ImGuiUtil.HalfBlendText(0x808000u)); // Half cyan + } + + return ret; + } + + private void DrawOtherMaterialDetails(bool _) + { + if (!ImGui.CollapsingHeader("Further Content")) + return; + + using (var sets = ImRaii.TreeNode("UV Sets", ImGuiTreeNodeFlags.DefaultOpen)) + { + if (sets) + foreach (var set in Mtrl.UvSets) + ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); + } + + using (var sets = ImRaii.TreeNode("Color Sets", ImGuiTreeNodeFlags.DefaultOpen)) + { + if (sets) + foreach (var set in Mtrl.ColorSets) + ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); + } + + if (Mtrl.AdditionalData.Length <= 0) + return; + + using var t = ImRaii.TreeNode($"Additional Data (Size: {Mtrl.AdditionalData.Length})###AdditionalData"); + if (t) + Widget.DrawHexViewer(Mtrl.AdditionalData); + } + + public void Update() + { + UpdateShaders(); + UpdateTextures(); + UpdateConstants(); + } + + public unsafe void Dispose() + { + UnbindFromMaterialInstances(); + if (Writable) + _characterBaseDestructor.Unsubscribe(UnbindFromDrawObjectMaterialInstances); + } + + public bool Valid + => ShadersKnown && Mtrl.Valid; + + public byte[] Write() + { + var output = Mtrl.Clone(); + output.GarbageCollect(AssociatedShpk, SamplerIds); + + return output.Write(); + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs new file mode 100644 index 00000000..af8b7db2 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs @@ -0,0 +1,18 @@ +using Dalamud.Plugin.Services; +using OtterGui.Services; +using Penumbra.GameData.Files; +using Penumbra.GameData.Interop; +using Penumbra.Interop.Hooks.Objects; +using Penumbra.Interop.ResourceTree; +using Penumbra.Services; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public sealed class MtrlTabFactory(IDataManager gameData, IFramework framework, ObjectManager objects, + CharacterBaseDestructor characterBaseDestructor, StainService stainService, ResourceTreeFactory resourceTreeFactory, + FileDialogService fileDialog, MaterialTemplatePickers materialTemplatePickers, Configuration config) : IUiService +{ + public MtrlTab Create(ModEditWindow edit, MtrlFile file, string filePath, bool writable) + => new(gameData, framework, objects, characterBaseDestructor, stainService, resourceTreeFactory, fileDialog, + materialTemplatePickers, config, edit, file, filePath, writable); +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs deleted file mode 100644 index 25c0e448..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ /dev/null @@ -1,538 +0,0 @@ -using Dalamud.Interface; -using Dalamud.Interface.Utility; -using ImGuiNET; -using OtterGui; -using OtterGui.Raii; -using Penumbra.GameData.Files; -using Penumbra.GameData.Files.MaterialStructs; -using Penumbra.String.Functions; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private static readonly float HalfMinValue = (float)Half.MinValue; - private static readonly float HalfMaxValue = (float)Half.MaxValue; - private static readonly float HalfEpsilon = (float)Half.Epsilon; - - private bool DrawMaterialColorTableChange(MtrlTab tab, bool disabled) - { - if (!tab.SamplerIds.Contains(ShpkFile.TableSamplerId) || !tab.Mtrl.HasTable) - return false; - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (!ImGui.CollapsingHeader("Color Table", ImGuiTreeNodeFlags.DefaultOpen)) - return false; - - ColorTableCopyAllClipboardButton(tab.Mtrl); - ImGui.SameLine(); - var ret = ColorTablePasteAllClipboardButton(tab, disabled); - if (!disabled) - { - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); - ImGui.SameLine(); - ret |= ColorTableDyeableCheckbox(tab); - } - - var hasDyeTable = tab.Mtrl.HasDyeTable; - if (hasDyeTable) - { - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); - ImGui.SameLine(); - ret |= DrawPreviewDye(tab, disabled); - } - - using var table = ImRaii.Table("##ColorTable", hasDyeTable ? 11 : 9, - ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV); - if (!table) - return false; - - ImGui.TableNextColumn(); - ImGui.TableHeader(string.Empty); - ImGui.TableNextColumn(); - ImGui.TableHeader("Row"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Diffuse"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Specular"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Emissive"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Gloss"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Tile"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Repeat"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Skew"); - if (hasDyeTable) - { - ImGui.TableNextColumn(); - ImGui.TableHeader("Dye"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Dye Preview"); - } - - for (var i = 0; i < ColorTable.NumRows; ++i) - { - ret |= DrawColorTableRow(tab, i, disabled); - ImGui.TableNextRow(); - } - - return ret; - } - - - private static void ColorTableCopyAllClipboardButton(MtrlFile file) - { - if (!ImGui.Button("Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2(200, 0))) - return; - - try - { - var data1 = file.Table.AsBytes(); - var data2 = file.HasDyeTable ? file.DyeTable.AsBytes() : ReadOnlySpan.Empty; - var array = new byte[data1.Length + data2.Length]; - data1.TryCopyTo(array); - data2.TryCopyTo(array.AsSpan(data1.Length)); - var text = Convert.ToBase64String(array); - ImGui.SetClipboardText(text); - } - catch - { - // ignored - } - } - - private bool DrawPreviewDye(MtrlTab tab, bool disabled) - { - var (dyeId, (name, dyeColor, gloss)) = _stainService.StainCombo.CurrentSelection; - var tt = dyeId == 0 - ? "Select a preview dye first." - : "Apply all preview values corresponding to the dye template and chosen dye where dyeing is enabled."; - if (ImGuiUtil.DrawDisabledButton("Apply Preview Dye", Vector2.Zero, tt, disabled || dyeId == 0)) - { - var ret = false; - if (tab.Mtrl.HasDyeTable) - for (var i = 0; i < LegacyColorTable.NumUsedRows; ++i) - ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId, 0); - - tab.UpdateColorTablePreview(); - - return ret; - } - - ImGui.SameLine(); - var label = dyeId == 0 ? "Preview Dye###previewDye" : $"{name} (Preview)###previewDye"; - if (_stainService.StainCombo.Draw(label, dyeColor, string.Empty, true, gloss)) - tab.UpdateColorTablePreview(); - return false; - } - - private static unsafe bool ColorTablePasteAllClipboardButton(MtrlTab tab, bool disabled) - { - if (!ImGuiUtil.DrawDisabledButton("Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2(200, 0), string.Empty, disabled) - || !tab.Mtrl.HasTable) - return false; - - try - { - var text = ImGui.GetClipboardText(); - var data = Convert.FromBase64String(text); - if (data.Length < Marshal.SizeOf()) - return false; - - ref var rows = ref tab.Mtrl.Table; - fixed (void* ptr = data, output = &rows) - { - MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); - if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() - && tab.Mtrl.HasDyeTable) - { - ref var dyeRows = ref tab.Mtrl.DyeTable; - fixed (void* output2 = &dyeRows) - { - MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), - Marshal.SizeOf()); - } - } - } - - tab.UpdateColorTablePreview(); - - return true; - } - catch - { - return false; - } - } - - [SkipLocalsInit] - private static unsafe void ColorTableCopyClipboardButton(ColorTable.Row row, ColorDyeTable.Row dye) - { - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Export this row to your clipboard.", false, true)) - return; - - try - { - Span data = stackalloc byte[ColorTable.Row.Size + ColorDyeTable.Row.Size]; - fixed (byte* ptr = data) - { - MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTable.Row.Size); - MemoryUtility.MemCpyUnchecked(ptr + ColorTable.Row.Size, &dye, ColorDyeTable.Row.Size); - } - - var text = Convert.ToBase64String(data); - ImGui.SetClipboardText(text); - } - catch - { - // ignored - } - } - - private static bool ColorTableDyeableCheckbox(MtrlTab tab) - { - var dyeable = tab.Mtrl.HasDyeTable; - var ret = ImGui.Checkbox("Dyeable", ref dyeable); - - if (ret) - { - tab.Mtrl.HasDyeTable = dyeable; - tab.UpdateColorTablePreview(); - } - - return ret; - } - - private static unsafe bool ColorTablePasteFromClipboardButton(MtrlTab tab, int rowIdx, bool disabled) - { - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Import an exported row from your clipboard onto this row.", disabled, true)) - return false; - - try - { - var text = ImGui.GetClipboardText(); - var data = Convert.FromBase64String(text); - if (data.Length != ColorTable.Row.Size + ColorDyeTable.Row.Size - || !tab.Mtrl.HasTable) - return false; - - fixed (byte* ptr = data) - { - tab.Mtrl.Table[rowIdx] = *(ColorTable.Row*)ptr; - if (tab.Mtrl.HasDyeTable) - tab.Mtrl.DyeTable[rowIdx] = *(ColorDyeTable.Row*)(ptr + ColorTable.Row.Size); - } - - tab.UpdateColorTableRowPreview(rowIdx); - - return true; - } - catch - { - return false; - } - } - - private static void ColorTableHighlightButton(MtrlTab tab, int rowIdx, bool disabled) - { - ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Crosshairs.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Highlight this row on your character, if possible.", disabled || tab.ColorTablePreviewers.Count == 0, true); - - if (ImGui.IsItemHovered()) - tab.HighlightColorTableRow(rowIdx); - else if (tab.HighlightedColorTableRow == rowIdx) - tab.CancelColorTableHighlight(); - } - - private bool DrawColorTableRow(MtrlTab tab, int rowIdx, bool disabled) - { - static bool FixFloat(ref float val, float current) - { - val = (float)(Half)val; - return val != current; - } - - using var id = ImRaii.PushId(rowIdx); - ref var row = ref tab.Mtrl.Table[rowIdx]; - var hasDye = tab.Mtrl.HasDyeTable; - ref var dye = ref tab.Mtrl.DyeTable[rowIdx]; - var floatSize = 70 * UiHelpers.Scale; - var intSize = 45 * UiHelpers.Scale; - ImGui.TableNextColumn(); - ColorTableCopyClipboardButton(row, dye); - ImGui.SameLine(); - var ret = ColorTablePasteFromClipboardButton(tab, rowIdx, disabled); - ImGui.SameLine(); - ColorTableHighlightButton(tab, rowIdx, disabled); - - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"#{rowIdx + 1:D2}"); - - ImGui.TableNextColumn(); - using var dis = ImRaii.Disabled(disabled); - ret |= ColorPicker("##Diffuse", "Diffuse Color", row.Diffuse, c => - { - tab.Mtrl.Table[rowIdx].Diffuse = c; - tab.UpdateColorTableRowPreview(rowIdx); - }); - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeDiffuse", "Apply Diffuse Color on Dye", dye.Diffuse, - b => - { - tab.Mtrl.DyeTable[rowIdx].Diffuse = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - ret |= ColorPicker("##Specular", "Specular Color", row.Specular, c => - { - tab.Mtrl.Table[rowIdx].Specular = c; - tab.UpdateColorTableRowPreview(rowIdx); - }); - ImGui.SameLine(); - var tmpFloat = row.SpecularStrength; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.01f, 0f, HalfMaxValue, "%.2f") - && FixFloat(ref tmpFloat, row.SpecularStrength)) - { - row.SpecularStrength = tmpFloat; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Specular Strength", ImGuiHoveredFlags.AllowWhenDisabled); - - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeSpecular", "Apply Specular Color on Dye", dye.Specular, - b => - { - tab.Mtrl.DyeTable[rowIdx].Specular = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeSpecularStrength", "Apply Specular Strength on Dye", dye.SpecularStrength, - b => - { - tab.Mtrl.DyeTable[rowIdx].SpecularStrength = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - ret |= ColorPicker("##Emissive", "Emissive Color", row.Emissive, c => - { - tab.Mtrl.Table[rowIdx].Emissive = c; - tab.UpdateColorTableRowPreview(rowIdx); - }); - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeEmissive", "Apply Emissive Color on Dye", dye.Emissive, - b => - { - tab.Mtrl.DyeTable[rowIdx].Emissive = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - tmpFloat = row.GlossStrength; - ImGui.SetNextItemWidth(floatSize); - var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; - if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), glossStrengthMin, HalfMaxValue, "%.1f") - && FixFloat(ref tmpFloat, row.GlossStrength)) - { - row.GlossStrength = Math.Max(tmpFloat, glossStrengthMin); - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Gloss Strength", ImGuiHoveredFlags.AllowWhenDisabled); - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeGloss", "Apply Gloss Strength on Dye", dye.Gloss, - b => - { - tab.Mtrl.DyeTable[rowIdx].Gloss = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - int tmpInt = row.TileSet; - ImGui.SetNextItemWidth(intSize); - if (ImGui.DragInt("##TileSet", ref tmpInt, 0.25f, 0, 63) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue) - { - row.TileSet = (ushort)Math.Clamp(tmpInt, 0, 63); - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Tile Set", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.TableNextColumn(); - tmpFloat = row.MaterialRepeat.X; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##RepeatX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") - && FixFloat(ref tmpFloat, row.MaterialRepeat.X)) - { - row.MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Repeat X", ImGuiHoveredFlags.AllowWhenDisabled); - ImGui.SameLine(); - tmpFloat = row.MaterialRepeat.Y; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##RepeatY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") - && FixFloat(ref tmpFloat, row.MaterialRepeat.Y)) - { - row.MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Repeat Y", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.TableNextColumn(); - tmpFloat = row.MaterialSkew.X; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SkewX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.X)) - { - row.MaterialSkew = row.MaterialSkew with { X = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Skew X", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.SameLine(); - tmpFloat = row.MaterialSkew.Y; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SkewY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.Y)) - { - row.MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Skew Y", ImGuiHoveredFlags.AllowWhenDisabled); - - if (hasDye) - { - ImGui.TableNextColumn(); - if (_stainService.TemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize - + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) - { - dye.Template = _stainService.TemplateCombo.CurrentSelection; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Dye Template", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.TableNextColumn(); - ret |= DrawDyePreview(tab, rowIdx, disabled, dye, floatSize); - } - - - return ret; - } - - private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, ColorDyeTable.Row dye, float floatSize) - { - var stain = _stainService.StainCombo.CurrentSelection.Key; - if (stain == 0 || !_stainService.StmFile.Entries.TryGetValue(dye.Template, out var entry)) - return false; - - var values = entry[(int)stain]; - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing / 2); - - var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), - "Apply the selected dye to this row.", disabled, true); - - ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, rowIdx, stain, 0); - if (ret) - tab.UpdateColorTableRowPreview(rowIdx); - - ImGui.SameLine(); - ColorPicker("##diffusePreview", string.Empty, values.Diffuse, _ => { }, "D"); - ImGui.SameLine(); - ColorPicker("##specularPreview", string.Empty, values.Specular, _ => { }, "S"); - ImGui.SameLine(); - ColorPicker("##emissivePreview", string.Empty, values.Emissive, _ => { }, "E"); - ImGui.SameLine(); - using var dis = ImRaii.Disabled(); - ImGui.SetNextItemWidth(floatSize); - ImGui.DragFloat("##gloss", ref values.Gloss, 0, values.Gloss, values.Gloss, "%.1f G"); - ImGui.SameLine(); - ImGui.SetNextItemWidth(floatSize); - ImGui.DragFloat("##specularStrength", ref values.SpecularPower, 0, values.SpecularPower, values.SpecularPower, "%.2f S"); - - return ret; - } - - private static bool ColorPicker(string label, string tooltip, Vector3 input, Action setter, string letter = "") - { - var ret = false; - var inputSqrt = PseudoSqrtRgb(input); - var tmp = inputSqrt; - if (ImGui.ColorEdit3(label, ref tmp, - ImGuiColorEditFlags.NoInputs - | ImGuiColorEditFlags.DisplayRGB - | ImGuiColorEditFlags.InputRGB - | ImGuiColorEditFlags.NoTooltip - | ImGuiColorEditFlags.HDR) - && tmp != inputSqrt) - { - setter(PseudoSquareRgb(tmp)); - ret = true; - } - - if (letter.Length > 0 && ImGui.IsItemVisible()) - { - var textSize = ImGui.CalcTextSize(letter); - var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; - var textColor = input.LengthSquared() < 0.25f ? 0x80FFFFFFu : 0x80000000u; - ImGui.GetWindowDrawList().AddText(center, textColor, letter); - } - - ImGuiUtil.HoverTooltip(tooltip, ImGuiHoveredFlags.AllowWhenDisabled); - - return ret; - } - - // Functions to deal with squared RGB values without making negatives useless. - - private static float PseudoSquareRgb(float x) - => x < 0.0f ? -(x * x) : x * x; - - private static Vector3 PseudoSquareRgb(Vector3 vec) - => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z)); - - private static Vector4 PseudoSquareRgb(Vector4 vec) - => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z), vec.W); - - private static float PseudoSqrtRgb(float x) - => x < 0.0f ? -MathF.Sqrt(-x) : MathF.Sqrt(x); - - internal static Vector3 PseudoSqrtRgb(Vector3 vec) - => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z)); - - private static Vector4 PseudoSqrtRgb(Vector4 vec) - => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z), vec.W); -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs deleted file mode 100644 index 1f5db38e..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ConstantEditor.cs +++ /dev/null @@ -1,247 +0,0 @@ -using ImGuiNET; -using OtterGui.Raii; -using OtterGui; -using Penumbra.GameData; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private interface IConstantEditor - { - bool Draw(Span values, bool disabled); - } - - private sealed class FloatConstantEditor : IConstantEditor - { - public static readonly FloatConstantEditor Default = new(null, null, 0.1f, 0.0f, 1.0f, 0.0f, 3, string.Empty); - - private readonly float? _minimum; - private readonly float? _maximum; - private readonly float _speed; - private readonly float _relativeSpeed; - private readonly float _factor; - private readonly float _bias; - private readonly string _format; - - public FloatConstantEditor(float? minimum, float? maximum, float speed, float relativeSpeed, float factor, float bias, byte precision, - string unit) - { - _minimum = minimum; - _maximum = maximum; - _speed = speed; - _relativeSpeed = relativeSpeed; - _factor = factor; - _bias = bias; - _format = $"%.{Math.Min(precision, (byte)9)}f"; - if (unit.Length > 0) - _format = $"{_format} {unit.Replace("%", "%%")}"; - } - - public bool Draw(Span values, bool disabled) - { - var spacing = ImGui.GetStyle().ItemInnerSpacing.X; - var fieldWidth = (ImGui.CalcItemWidth() - (values.Length - 1) * spacing) / values.Length; - - var ret = false; - - // Not using DragScalarN because of _relativeSpeed and other points of lost flexibility. - for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) - { - if (valueIdx > 0) - ImGui.SameLine(0.0f, spacing); - - ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); - - var value = (values[valueIdx] - _bias) / _factor; - if (disabled) - { - ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), value, value, _format); - } - else - { - if (ImGui.DragFloat($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0.0f, - _maximum ?? 0.0f, _format)) - { - values[valueIdx] = Clamp(value) * _factor + _bias; - ret = true; - } - } - } - - return ret; - } - - private float Clamp(float value) - => Math.Clamp(value, _minimum ?? float.NegativeInfinity, _maximum ?? float.PositiveInfinity); - } - - private sealed class IntConstantEditor : IConstantEditor - { - private readonly int? _minimum; - private readonly int? _maximum; - private readonly float _speed; - private readonly float _relativeSpeed; - private readonly float _factor; - private readonly float _bias; - private readonly string _format; - - public IntConstantEditor(int? minimum, int? maximum, float speed, float relativeSpeed, float factor, float bias, string unit) - { - _minimum = minimum; - _maximum = maximum; - _speed = speed; - _relativeSpeed = relativeSpeed; - _factor = factor; - _bias = bias; - _format = "%d"; - if (unit.Length > 0) - _format = $"{_format} {unit.Replace("%", "%%")}"; - } - - public bool Draw(Span values, bool disabled) - { - var spacing = ImGui.GetStyle().ItemInnerSpacing.X; - var fieldWidth = (ImGui.CalcItemWidth() - (values.Length - 1) * spacing) / values.Length; - - var ret = false; - - // Not using DragScalarN because of _relativeSpeed and other points of lost flexibility. - for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) - { - if (valueIdx > 0) - ImGui.SameLine(0.0f, spacing); - - ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); - - var value = (int)Math.Clamp(MathF.Round((values[valueIdx] - _bias) / _factor), int.MinValue, int.MaxValue); - if (disabled) - { - ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), value, value, _format); - } - else - { - if (ImGui.DragInt($"##{valueIdx}", ref value, Math.Max(_speed, value * _relativeSpeed), _minimum ?? 0, _maximum ?? 0, - _format)) - { - values[valueIdx] = Clamp(value) * _factor + _bias; - ret = true; - } - } - } - - return ret; - } - - private int Clamp(int value) - => Math.Clamp(value, _minimum ?? int.MinValue, _maximum ?? int.MaxValue); - } - - private sealed class ColorConstantEditor : IConstantEditor - { - private readonly bool _squaredRgb; - private readonly bool _clamped; - - public ColorConstantEditor(bool squaredRgb, bool clamped) - { - _squaredRgb = squaredRgb; - _clamped = clamped; - } - - public bool Draw(Span values, bool disabled) - { - switch (values.Length) - { - case 3: - { - var value = new Vector3(values); - if (_squaredRgb) - value = PseudoSqrtRgb(value); - if (!ImGui.ColorEdit3("##0", ref value, ImGuiColorEditFlags.Float | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) || disabled) - return false; - - if (_squaredRgb) - value = PseudoSquareRgb(value); - if (_clamped) - value = Vector3.Clamp(value, Vector3.Zero, Vector3.One); - value.CopyTo(values); - return true; - } - case 4: - { - var value = new Vector4(values); - if (_squaredRgb) - value = PseudoSqrtRgb(value); - if (!ImGui.ColorEdit4("##0", ref value, - ImGuiColorEditFlags.Float | ImGuiColorEditFlags.AlphaPreviewHalf | (_clamped ? 0 : ImGuiColorEditFlags.HDR)) - || disabled) - return false; - - if (_squaredRgb) - value = PseudoSquareRgb(value); - if (_clamped) - value = Vector4.Clamp(value, Vector4.Zero, Vector4.One); - value.CopyTo(values); - return true; - } - default: return FloatConstantEditor.Default.Draw(values, disabled); - } - } - } - - private sealed class EnumConstantEditor : IConstantEditor - { - private readonly IReadOnlyList<(string Label, float Value, string Description)> _values; - - public EnumConstantEditor(IReadOnlyList<(string Label, float Value, string Description)> values) - => _values = values; - - public bool Draw(Span values, bool disabled) - { - var spacing = ImGui.GetStyle().ItemInnerSpacing.X; - var fieldWidth = (ImGui.CalcItemWidth() - (values.Length - 1) * spacing) / values.Length; - - var ret = false; - - for (var valueIdx = 0; valueIdx < values.Length; ++valueIdx) - { - using var id = ImRaii.PushId(valueIdx); - if (valueIdx > 0) - ImGui.SameLine(0.0f, spacing); - - ImGui.SetNextItemWidth(MathF.Round(fieldWidth * (valueIdx + 1)) - MathF.Round(fieldWidth * valueIdx)); - - var currentValue = values[valueIdx]; - var currentLabel = _values.FirstOrNull(v => v.Value == currentValue)?.Label - ?? currentValue.ToString(CultureInfo.CurrentCulture); - ret = disabled - ? ImGui.InputText(string.Empty, ref currentLabel, (uint)currentLabel.Length, ImGuiInputTextFlags.ReadOnly) - : DrawCombo(currentLabel, ref values[valueIdx]); - } - - return ret; - } - - private bool DrawCombo(string label, ref float currentValue) - { - using var c = ImRaii.Combo(string.Empty, label); - if (!c) - return false; - - var ret = false; - foreach (var (valueLabel, value, valueDescription) in _values) - { - if (ImGui.Selectable(valueLabel, value == currentValue)) - { - currentValue = value; - ret = true; - } - - if (valueDescription.Length > 0) - ImGuiUtil.SelectableHelpMarker(valueDescription); - } - - return ret; - } - } -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs deleted file mode 100644 index 29fd7531..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ /dev/null @@ -1,783 +0,0 @@ -using Dalamud.Interface; -using Dalamud.Interface.ImGuiNotification; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using ImGuiNET; -using Newtonsoft.Json.Linq; -using OtterGui; -using OtterGui.Classes; -using OtterGui.Raii; -using Penumbra.GameData.Data; -using Penumbra.GameData.Files; -using Penumbra.GameData.Files.MaterialStructs; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Hooks.Objects; -using Penumbra.Interop.MaterialPreview; -using Penumbra.String; -using Penumbra.String.Classes; -using Penumbra.UI.Classes; -using static Penumbra.GameData.Files.ShpkFile; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private sealed class MtrlTab : IWritable, IDisposable - { - private const int ShpkPrefixLength = 16; - - private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); - - private readonly ModEditWindow _edit; - public readonly MtrlFile Mtrl; - public readonly string FilePath; - public readonly bool Writable; - - private string[]? _shpkNames; - - public string ShaderHeader = "Shader###Shader"; - public FullPath LoadedShpkPath = FullPath.Empty; - public string LoadedShpkPathName = string.Empty; - public string LoadedShpkDevkitPathName = string.Empty; - public string ShaderComment = string.Empty; - public ShpkFile? AssociatedShpk; - public JObject? AssociatedShpkDevkit; - - public readonly string LoadedBaseDevkitPathName; - public readonly JObject? AssociatedBaseDevkit; - - // Shader Key State - public readonly - List<(string Label, int Index, string Description, bool MonoFont, IReadOnlyList<(string Label, uint Value, string Description)> - Values)> ShaderKeys = new(16); - - public readonly HashSet VertexShaders = new(16); - public readonly HashSet PixelShaders = new(16); - public bool ShadersKnown; - public string VertexShadersString = "Vertex Shaders: ???"; - public string PixelShadersString = "Pixel Shaders: ???"; - - // Textures & Samplers - public readonly List<(string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont)> Textures = new(4); - - public readonly HashSet UnfoldedTextures = new(4); - public readonly HashSet SamplerIds = new(16); - public float TextureLabelWidth; - - // Material Constants - public readonly - List<(string Header, List<(string Label, int ConstantIndex, Range Slice, string Description, bool MonoFont, IConstantEditor Editor)> - Constants)> Constants = new(16); - - // Live-Previewers - public readonly List MaterialPreviewers = new(4); - public readonly List ColorTablePreviewers = new(4); - public int HighlightedColorTableRow = -1; - public readonly Stopwatch HighlightTime = new(); - - public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) - { - defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); - if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) - return FullPath.Empty; - - return _edit.FindBestMatch(defaultGamePath); - } - - public string[] GetShpkNames() - { - if (null != _shpkNames) - return _shpkNames; - - var names = new HashSet(StandardShaderPackages); - names.UnionWith(_edit.FindPathsStartingWith(ShpkPrefix).Select(path => path.ToString()[ShpkPrefixLength..])); - - _shpkNames = names.ToArray(); - Array.Sort(_shpkNames); - - return _shpkNames; - } - - public void LoadShpk(FullPath path) - { - ShaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; - - try - { - LoadedShpkPath = path; - var data = LoadedShpkPath.IsRooted - ? File.ReadAllBytes(LoadedShpkPath.FullName) - : _edit._gameData.GetFile(LoadedShpkPath.InternalName.ToString())?.Data; - AssociatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); - LoadedShpkPathName = path.ToPath(); - } - catch (Exception e) - { - LoadedShpkPath = FullPath.Empty; - LoadedShpkPathName = string.Empty; - AssociatedShpk = null; - Penumbra.Messager.NotificationMessage(e, $"Could not load {LoadedShpkPath.ToPath()}.", NotificationType.Error, false); - } - - if (LoadedShpkPath.InternalName.IsEmpty) - { - AssociatedShpkDevkit = null; - LoadedShpkDevkitPathName = string.Empty; - } - else - { - AssociatedShpkDevkit = - TryLoadShpkDevkit(Path.GetFileNameWithoutExtension(Mtrl.ShaderPackage.Name), out LoadedShpkDevkitPathName); - } - - UpdateShaderKeys(); - Update(); - } - - private JObject? TryLoadShpkDevkit(string shpkBaseName, out string devkitPathName) - { - try - { - if (!Utf8GamePath.FromString("penumbra/shpk_devkit/" + shpkBaseName + ".json", out var devkitPath)) - throw new Exception("Could not assemble ShPk dev-kit path."); - - var devkitFullPath = _edit.FindBestMatch(devkitPath); - if (!devkitFullPath.IsRooted) - throw new Exception("Could not resolve ShPk dev-kit path."); - - devkitPathName = devkitFullPath.FullName; - return JObject.Parse(File.ReadAllText(devkitFullPath.FullName)); - } - catch - { - devkitPathName = string.Empty; - return null; - } - } - - private T? TryGetShpkDevkitData(string category, uint? id, bool mayVary) where T : class - => TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) - ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); - - private T? TryGetShpkDevkitData(JObject? devkit, string devkitPathName, string category, uint? id, bool mayVary) where T : class - { - if (devkit == null) - return null; - - try - { - var data = devkit[category]; - if (id.HasValue) - data = data?[id.Value.ToString()]; - - if (mayVary && (data as JObject)?["Vary"] != null) - { - var selector = BuildSelector(data!["Vary"]! - .Select(key => (uint)key) - .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); - var index = (int)data["Selectors"]![selector.ToString()]!; - data = data["Items"]![index]; - } - - return data?.ToObject(typeof(T)) as T; - } - catch (Exception e) - { - // Some element in the JSON was undefined or invalid (wrong type, key that doesn't exist in the ShPk, index out of range, …) - Penumbra.Log.Error($"Error while traversing the ShPk dev-kit file at {devkitPathName}: {e}"); - return null; - } - } - - private void UpdateShaderKeys() - { - ShaderKeys.Clear(); - if (AssociatedShpk != null) - foreach (var key in AssociatedShpk.MaterialKeys) - { - var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); - var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); - - var valueSet = new HashSet(key.Values); - if (dkData != null) - valueSet.UnionWith(dkData.Values.Keys); - - var mtrlKeyIndex = Mtrl.FindOrAddShaderKey(key.Id, key.DefaultValue); - var values = valueSet.Select(value => - { - if (dkData != null && dkData.Values.TryGetValue(value, out var dkValue)) - return (dkValue.Label.Length > 0 ? dkValue.Label : $"0x{value:X8}", value, dkValue.Description); - - return ($"0x{value:X8}", value, string.Empty); - }).ToArray(); - Array.Sort(values, (x, y) => - { - if (x.Value == key.DefaultValue) - return -1; - if (y.Value == key.DefaultValue) - return 1; - - return string.Compare(x.Label, y.Label, StringComparison.Ordinal); - }); - ShaderKeys.Add((hasDkLabel ? dkData!.Label : $"0x{key.Id:X8}", mtrlKeyIndex, dkData?.Description ?? string.Empty, - !hasDkLabel, values)); - } - else - foreach (var (key, index) in Mtrl.ShaderPackage.ShaderKeys.WithIndex()) - ShaderKeys.Add(($"0x{key.Category:X8}", index, string.Empty, true, Array.Empty<(string, uint, string)>())); - } - - private void UpdateShaders() - { - VertexShaders.Clear(); - PixelShaders.Clear(); - if (AssociatedShpk == null) - { - ShadersKnown = false; - } - else - { - ShadersKnown = true; - var systemKeySelectors = AllSelectors(AssociatedShpk.SystemKeys).ToArray(); - var sceneKeySelectors = AllSelectors(AssociatedShpk.SceneKeys).ToArray(); - var subViewKeySelectors = AllSelectors(AssociatedShpk.SubViewKeys).ToArray(); - var materialKeySelector = - BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); - foreach (var systemKeySelector in systemKeySelectors) - { - foreach (var sceneKeySelector in sceneKeySelectors) - { - foreach (var subViewKeySelector in subViewKeySelectors) - { - var selector = BuildSelector(systemKeySelector, sceneKeySelector, materialKeySelector, subViewKeySelector); - var node = AssociatedShpk.GetNodeBySelector(selector); - if (node.HasValue) - foreach (var pass in node.Value.Passes) - { - VertexShaders.Add((int)pass.VertexShader); - PixelShaders.Add((int)pass.PixelShader); - } - else - ShadersKnown = false; - } - } - } - } - - var vertexShaders = VertexShaders.OrderBy(i => i).Select(i => $"#{i}"); - var pixelShaders = PixelShaders.OrderBy(i => i).Select(i => $"#{i}"); - - VertexShadersString = $"Vertex Shaders: {string.Join(", ", ShadersKnown ? vertexShaders : vertexShaders.Append("???"))}"; - PixelShadersString = $"Pixel Shaders: {string.Join(", ", ShadersKnown ? pixelShaders : pixelShaders.Append("???"))}"; - - ShaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; - } - - private void UpdateTextures() - { - Textures.Clear(); - SamplerIds.Clear(); - if (AssociatedShpk == null) - { - SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.HasTable) - SamplerIds.Add(TableSamplerId); - - foreach (var (sampler, index) in Mtrl.ShaderPackage.Samplers.WithIndex()) - Textures.Add(($"0x{sampler.SamplerId:X8}", sampler.TextureIndex, index, string.Empty, true)); - } - else - { - foreach (var index in VertexShaders) - SamplerIds.UnionWith(AssociatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); - foreach (var index in PixelShaders) - SamplerIds.UnionWith(AssociatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); - if (!ShadersKnown) - { - SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.HasTable) - SamplerIds.Add(TableSamplerId); - } - - foreach (var samplerId in SamplerIds) - { - var shpkSampler = AssociatedShpk.GetSamplerById(samplerId); - if (shpkSampler is not { Slot: 2 }) - continue; - - var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); - var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); - - var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); - Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, - dkData?.Description ?? string.Empty, !hasDkLabel)); - } - - if (SamplerIds.Contains(TableSamplerId)) - Mtrl.HasTable = true; - } - - Textures.Sort((x, y) => string.CompareOrdinal(x.Label, y.Label)); - - TextureLabelWidth = 50f * UiHelpers.Scale; - - float helpWidth; - using (var _ = ImRaii.PushFont(UiBuilder.IconFont)) - { - helpWidth = ImGui.GetStyle().ItemSpacing.X + ImGui.CalcTextSize(FontAwesomeIcon.InfoCircle.ToIconString()).X; - } - - foreach (var (label, _, _, description, monoFont) in Textures) - { - if (!monoFont) - TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); - } - - using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) - { - foreach (var (label, _, _, description, monoFont) in Textures) - { - if (monoFont) - TextureLabelWidth = Math.Max(TextureLabelWidth, - ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); - } - } - - TextureLabelWidth = TextureLabelWidth / UiHelpers.Scale + 4; - } - - private void UpdateConstants() - { - static List FindOrAddGroup(List<(string, List)> groups, string name) - { - foreach (var (groupName, group) in groups) - { - if (string.Equals(name, groupName, StringComparison.Ordinal)) - return group; - } - - var newGroup = new List(16); - groups.Add((name, newGroup)); - return newGroup; - } - - Constants.Clear(); - if (AssociatedShpk == null) - { - var fcGroup = FindOrAddGroup(Constants, "Further Constants"); - foreach (var (constant, index) in Mtrl.ShaderPackage.Constants.WithIndex()) - { - var values = Mtrl.GetConstantValues(constant); - for (var i = 0; i < values.Length; i += 4) - { - fcGroup.Add(($"0x{constant.Id:X8}", index, i..Math.Min(i + 4, values.Length), string.Empty, true, - FloatConstantEditor.Default)); - } - } - } - else - { - var prefix = AssociatedShpk.GetConstantById(MaterialParamsConstantId)?.Name ?? string.Empty; - foreach (var shpkConstant in AssociatedShpk.MaterialParams) - { - if ((shpkConstant.ByteSize & 0x3) != 0) - continue; - - var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, shpkConstant.ByteSize >> 2, out var constantIndex); - var values = Mtrl.GetConstantValues(constant); - var handledElements = new IndexSet(values.Length, false); - - var dkData = TryGetShpkDevkitData("Constants", shpkConstant.Id, true); - if (dkData != null) - foreach (var dkConstant in dkData) - { - var offset = (int)dkConstant.Offset; - var length = values.Length - offset; - if (dkConstant.Length.HasValue) - length = Math.Min(length, (int)dkConstant.Length.Value); - if (length <= 0) - continue; - - var editor = dkConstant.CreateEditor(); - if (editor != null) - FindOrAddGroup(Constants, dkConstant.Group.Length > 0 ? dkConstant.Group : "Further Constants") - .Add((dkConstant.Label, constantIndex, offset..(offset + length), dkConstant.Description, false, editor)); - handledElements.AddRange(offset, length); - } - - var fcGroup = FindOrAddGroup(Constants, "Further Constants"); - foreach (var (start, end) in handledElements.Ranges(complement:true)) - { - if ((shpkConstant.ByteOffset & 0x3) == 0) - { - var offset = shpkConstant.ByteOffset >> 2; - for (int i = (start & ~0x3) - (offset & 0x3), j = offset >> 2; i < end; i += 4, ++j) - { - var rangeStart = Math.Max(i, start); - var rangeEnd = Math.Min(i + 4, end); - if (rangeEnd > rangeStart) - fcGroup.Add(( - $"{prefix}[{j:D2}]{VectorSwizzle((offset + rangeStart) & 0x3, (offset + rangeEnd - 1) & 0x3)} (0x{shpkConstant.Id:X8})", - constantIndex, rangeStart..rangeEnd, string.Empty, true, FloatConstantEditor.Default)); - } - } - else - { - for (var i = start; i < end; i += 4) - { - fcGroup.Add(($"0x{shpkConstant.Id:X8}", constantIndex, i..Math.Min(i + 4, end), string.Empty, true, - FloatConstantEditor.Default)); - } - } - } - } - } - - Constants.RemoveAll(group => group.Constants.Count == 0); - Constants.Sort((x, y) => - { - if (string.Equals(x.Header, "Further Constants", StringComparison.Ordinal)) - return 1; - if (string.Equals(y.Header, "Further Constants", StringComparison.Ordinal)) - return -1; - - return string.Compare(x.Header, y.Header, StringComparison.Ordinal); - }); - // HACK the Replace makes w appear after xyz, for the cbuffer-location-based naming scheme - foreach (var (_, group) in Constants) - { - group.Sort((x, y) => string.CompareOrdinal( - x.MonoFont ? x.Label.Replace("].w", "].{") : x.Label, - y.MonoFont ? y.Label.Replace("].w", "].{") : y.Label)); - } - } - - public unsafe void BindToMaterialInstances() - { - UnbindFromMaterialInstances(); - - var instances = MaterialInfo.FindMaterials(_edit._resourceTreeFactory.GetLocalPlayerRelatedCharacters().Select(ch => ch.Address), - FilePath); - - var foundMaterials = new HashSet(); - foreach (var materialInfo in instances) - { - var material = materialInfo.GetDrawObjectMaterial(_edit._objects); - if (foundMaterials.Contains((nint)material)) - continue; - - try - { - MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._objects, materialInfo)); - foundMaterials.Add((nint)material); - } - catch (InvalidOperationException) - { - // Carry on without that previewer. - } - } - - UpdateMaterialPreview(); - - if (!Mtrl.HasTable) - return; - - foreach (var materialInfo in instances) - { - try - { - ColorTablePreviewers.Add(new LiveColorTablePreviewer(_edit._objects, _edit._framework, materialInfo)); - } - catch (InvalidOperationException) - { - // Carry on without that previewer. - } - } - - UpdateColorTablePreview(); - } - - private void UnbindFromMaterialInstances() - { - foreach (var previewer in MaterialPreviewers) - previewer.Dispose(); - MaterialPreviewers.Clear(); - - foreach (var previewer in ColorTablePreviewers) - previewer.Dispose(); - ColorTablePreviewers.Clear(); - } - - private unsafe void UnbindFromDrawObjectMaterialInstances(CharacterBase* characterBase) - { - for (var i = MaterialPreviewers.Count; i-- > 0;) - { - var previewer = MaterialPreviewers[i]; - if (previewer.DrawObject != characterBase) - continue; - - previewer.Dispose(); - MaterialPreviewers.RemoveAt(i); - } - - for (var i = ColorTablePreviewers.Count; i-- > 0;) - { - var previewer = ColorTablePreviewers[i]; - if (previewer.DrawObject != characterBase) - continue; - - previewer.Dispose(); - ColorTablePreviewers.RemoveAt(i); - } - } - - public void SetShaderPackageFlags(uint shPkFlags) - { - foreach (var previewer in MaterialPreviewers) - previewer.SetShaderPackageFlags(shPkFlags); - } - - public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) - { - foreach (var previewer in MaterialPreviewers) - previewer.SetMaterialParameter(parameterCrc, offset, value); - } - - public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) - { - foreach (var previewer in MaterialPreviewers) - previewer.SetSamplerFlags(samplerCrc, samplerFlags); - } - - private void UpdateMaterialPreview() - { - SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); - foreach (var constant in Mtrl.ShaderPackage.Constants) - { - var values = Mtrl.GetConstantValues(constant); - if (values != null) - SetMaterialParameter(constant.Id, 0, values); - } - - foreach (var sampler in Mtrl.ShaderPackage.Samplers) - SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - public void HighlightColorTableRow(int rowIdx) - { - var oldRowIdx = HighlightedColorTableRow; - - if (HighlightedColorTableRow != rowIdx) - { - HighlightedColorTableRow = rowIdx; - HighlightTime.Restart(); - } - - if (oldRowIdx >= 0) - UpdateColorTableRowPreview(oldRowIdx); - if (rowIdx >= 0) - UpdateColorTableRowPreview(rowIdx); - } - - public void CancelColorTableHighlight() - { - var rowIdx = HighlightedColorTableRow; - - HighlightedColorTableRow = -1; - HighlightTime.Reset(); - - if (rowIdx >= 0) - UpdateColorTableRowPreview(rowIdx); - } - - public void UpdateColorTableRowPreview(int rowIdx) - { - if (ColorTablePreviewers.Count == 0) - return; - - if (!Mtrl.HasTable) - return; - - var row = new LegacyColorTable.Row(Mtrl.Table[rowIdx]); - if (Mtrl.HasDyeTable) - { - var stm = _edit._stainService.StmFile; - var dye = new LegacyColorDyeTable.Row(Mtrl.DyeTable[rowIdx]); - if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) - row.ApplyDyeTemplate(dye, dyes); - } - - if (HighlightedColorTableRow == rowIdx) - ApplyHighlight(ref row, (float)HighlightTime.Elapsed.TotalSeconds); - - foreach (var previewer in ColorTablePreviewers) - { - row.AsHalves().CopyTo(previewer.ColorTable.AsSpan() - .Slice(LiveColorTablePreviewer.TextureWidth * 4 * rowIdx, LiveColorTablePreviewer.TextureWidth * 4)); - previewer.ScheduleUpdate(); - } - } - - public void UpdateColorTablePreview() - { - if (ColorTablePreviewers.Count == 0) - return; - - if (!Mtrl.HasTable) - return; - - var rows = new LegacyColorTable(Mtrl.Table); - var dyeRows = new LegacyColorDyeTable(Mtrl.DyeTable); - if (Mtrl.HasDyeTable) - { - var stm = _edit._stainService.StmFile; - var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; - for (var i = 0; i < LegacyColorTable.NumUsedRows; ++i) - { - ref var row = ref rows[i]; - var dye = dyeRows[i]; - if (stm.TryGetValue(dye.Template, stainId, out var dyes)) - row.ApplyDyeTemplate(dye, dyes); - } - } - - if (HighlightedColorTableRow >= 0) - ApplyHighlight(ref rows[HighlightedColorTableRow], (float)HighlightTime.Elapsed.TotalSeconds); - - foreach (var previewer in ColorTablePreviewers) - { - // TODO: Dawntrail - rows.AsHalves().CopyTo(previewer.ColorTable); - previewer.ScheduleUpdate(); - } - } - - private static void ApplyHighlight(ref LegacyColorTable.Row row, float time) - { - var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; - var baseColor = ColorId.InGameHighlight.Value(); - var color = level * new Vector3(baseColor & 0xFF, (baseColor >> 8) & 0xFF, (baseColor >> 16) & 0xFF); - - row.Diffuse = Vector3.Zero; - row.Specular = Vector3.Zero; - row.Emissive = color * color; - } - - public void Update() - { - UpdateShaders(); - UpdateTextures(); - UpdateConstants(); - } - - public unsafe MtrlTab(ModEditWindow edit, MtrlFile file, string filePath, bool writable) - { - _edit = edit; - Mtrl = file; - FilePath = filePath; - Writable = writable; - AssociatedBaseDevkit = TryLoadShpkDevkit("_base", out LoadedBaseDevkitPathName); - LoadShpk(FindAssociatedShpk(out _, out _)); - if (writable) - { - _edit._characterBaseDestructor.Subscribe(UnbindFromDrawObjectMaterialInstances, CharacterBaseDestructor.Priority.MtrlTab); - BindToMaterialInstances(); - } - } - - public unsafe void Dispose() - { - UnbindFromMaterialInstances(); - if (Writable) - _edit._characterBaseDestructor.Unsubscribe(UnbindFromDrawObjectMaterialInstances); - } - - // TODO Readd ShadersKnown - public bool Valid - => (true || ShadersKnown) && Mtrl.Valid; - - public byte[] Write() - { - var output = Mtrl.Clone(); - output.GarbageCollect(AssociatedShpk, SamplerIds); - - return output.Write(); - } - - private sealed class DevkitShaderKeyValue - { - public string Label = string.Empty; - public string Description = string.Empty; - } - - private sealed class DevkitShaderKey - { - public string Label = string.Empty; - public string Description = string.Empty; - public Dictionary Values = new(); - } - - private sealed class DevkitSampler - { - public string Label = string.Empty; - public string Description = string.Empty; - public string DefaultTexture = string.Empty; - } - - private enum DevkitConstantType - { - Hidden = -1, - Float = 0, - Integer = 1, - Color = 2, - Enum = 3, - } - - private sealed class DevkitConstantValue - { - public string Label = string.Empty; - public string Description = string.Empty; - public float Value = 0; - } - - private sealed class DevkitConstant - { - public uint Offset = 0; - public uint? Length = null; - public string Group = string.Empty; - public string Label = string.Empty; - public string Description = string.Empty; - public DevkitConstantType Type = DevkitConstantType.Float; - - public float? Minimum = null; - public float? Maximum = null; - public float? Speed = null; - public float RelativeSpeed = 0.0f; - public float Factor = 1.0f; - public float Bias = 0.0f; - public byte Precision = 3; - public string Unit = string.Empty; - - public bool SquaredRgb = false; - public bool Clamped = false; - - public DevkitConstantValue[] Values = Array.Empty(); - - public IConstantEditor? CreateEditor() - => Type switch - { - DevkitConstantType.Hidden => null, - DevkitConstantType.Float => new FloatConstantEditor(Minimum, Maximum, Speed ?? 0.1f, RelativeSpeed, Factor, Bias, Precision, - Unit), - DevkitConstantType.Integer => new IntConstantEditor(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, - Factor, Bias, Unit), - DevkitConstantType.Color => new ColorConstantEditor(SquaredRgb, Clamped), - DevkitConstantType.Enum => new EnumConstantEditor(Array.ConvertAll(Values, - value => (value.Label, value.Value, value.Description))), - _ => FloatConstantEditor.Default, - }; - - private static int? ToInteger(float? value) - => value.HasValue ? (int)Math.Clamp(MathF.Round(value.Value), int.MinValue, int.MaxValue) : null; - } - } -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs deleted file mode 100644 index b9525b29..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.Shpk.cs +++ /dev/null @@ -1,481 +0,0 @@ -using Dalamud.Interface; -using ImGuiNET; -using OtterGui; -using OtterGui.Raii; -using Penumbra.GameData; -using Penumbra.String.Classes; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private readonly FileDialogService _fileDialog; - - // strings path/to/the.exe | grep --fixed-strings '.shpk' | sort -u | sed -e 's#^shader/sm5/shpk/##' - // Apricot shader packages are unlisted because - // 1. they cause performance/memory issues when calculating the effective shader set - // 2. they probably aren't intended for use with materials anyway - private static readonly IReadOnlyList StandardShaderPackages = new[] - { - "3dui.shpk", - // "apricot_decal_dummy.shpk", - // "apricot_decal_ring.shpk", - // "apricot_decal.shpk", - // "apricot_lightmodel.shpk", - // "apricot_model_dummy.shpk", - // "apricot_model_morph.shpk", - // "apricot_model.shpk", - // "apricot_powder_dummy.shpk", - // "apricot_powder.shpk", - // "apricot_shape_dummy.shpk", - // "apricot_shape.shpk", - "bgcolorchange.shpk", - "bgcrestchange.shpk", - "bgdecal.shpk", - "bg.shpk", - "bguvscroll.shpk", - "channeling.shpk", - "characterglass.shpk", - "charactershadowoffset.shpk", - "character.shpk", - "cloud.shpk", - "createviewposition.shpk", - "crystal.shpk", - "directionallighting.shpk", - "directionalshadow.shpk", - "grass.shpk", - "hair.shpk", - "iris.shpk", - "lightshaft.shpk", - "linelighting.shpk", - "planelighting.shpk", - "pointlighting.shpk", - "river.shpk", - "shadowmask.shpk", - "skin.shpk", - "spotlighting.shpk", - "verticalfog.shpk", - "water.shpk", - "weather.shpk", - }; - - private enum TextureAddressMode : uint - { - Wrap = 0, - Mirror = 1, - Clamp = 2, - Border = 3, - } - - private static readonly IReadOnlyList TextureAddressModeTooltips = new[] - { - "Tile the texture at every UV integer junction.\n\nFor example, for U values between 0 and 3, the texture is repeated three times.", - "Flip the texture at every UV integer junction.\n\nFor U values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is mirrored; between 2 and 3, the texture is normal again; and so on.", - "Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.", - "Texture coordinates outside the range [0.0, 1.0] are set to the border color (generally black).", - }; - - private static bool DrawPackageNameInput(MtrlTab tab, bool disabled) - { - if (disabled) - { - ImGui.TextUnformatted("Shader Package: " + tab.Mtrl.ShaderPackage.Name); - return false; - } - - var ret = false; - ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); - using var c = ImRaii.Combo("Shader Package", tab.Mtrl.ShaderPackage.Name); - if (c) - foreach (var value in tab.GetShpkNames()) - { - if (ImGui.Selectable(value, value == tab.Mtrl.ShaderPackage.Name)) - { - tab.Mtrl.ShaderPackage.Name = value; - ret = true; - tab.AssociatedShpk = null; - tab.LoadedShpkPath = FullPath.Empty; - tab.LoadShpk(tab.FindAssociatedShpk(out _, out _)); - } - } - - return ret; - } - - private static bool DrawShaderFlagsInput(MtrlTab tab, bool disabled) - { - var shpkFlags = (int)tab.Mtrl.ShaderPackage.Flags; - ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); - if (!ImGui.InputInt("Shader Flags", ref shpkFlags, 0, 0, - ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) - return false; - - tab.Mtrl.ShaderPackage.Flags = (uint)shpkFlags; - tab.SetShaderPackageFlags((uint)shpkFlags); - return true; - } - - /// - /// Show the currently associated shpk file, if any, and the buttons to associate - /// a specific shpk from your drive, the modded shpk by path or the default shpk. - /// - private void DrawCustomAssociations(MtrlTab tab) - { - const string tooltip = "Click to copy file path to clipboard."; - var text = tab.AssociatedShpk == null - ? "Associated .shpk file: None" - : $"Associated .shpk file: {tab.LoadedShpkPathName}"; - var devkitText = tab.AssociatedShpkDevkit == null - ? "Associated dev-kit file: None" - : $"Associated dev-kit file: {tab.LoadedShpkDevkitPathName}"; - var baseDevkitText = tab.AssociatedBaseDevkit == null - ? "Base dev-kit file: None" - : $"Base dev-kit file: {tab.LoadedBaseDevkitPathName}"; - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - - ImGuiUtil.CopyOnClickSelectable(text, tab.LoadedShpkPathName, tooltip); - ImGuiUtil.CopyOnClickSelectable(devkitText, tab.LoadedShpkDevkitPathName, tooltip); - ImGuiUtil.CopyOnClickSelectable(baseDevkitText, tab.LoadedBaseDevkitPathName, tooltip); - - if (ImGui.Button("Associate Custom .shpk File")) - _fileDialog.OpenFilePicker("Associate Custom .shpk File...", ".shpk", (success, name) => - { - if (success) - tab.LoadShpk(new FullPath(name[0])); - }, 1, Mod!.ModPath.FullName, false); - - var moddedPath = tab.FindAssociatedShpk(out var defaultPath, out var gamePath); - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Associate Default .shpk File", Vector2.Zero, moddedPath.ToPath(), - moddedPath.Equals(tab.LoadedShpkPath))) - tab.LoadShpk(moddedPath); - - if (!gamePath.Path.Equals(moddedPath.InternalName)) - { - ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Associate Unmodded .shpk File", Vector2.Zero, defaultPath, - gamePath.Path.Equals(tab.LoadedShpkPath.InternalName))) - tab.LoadShpk(new FullPath(gamePath)); - } - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - } - - private static bool DrawMaterialShaderKeys(MtrlTab tab, bool disabled) - { - if (tab.ShaderKeys.Count == 0) - return false; - - var ret = false; - foreach (var (label, index, description, monoFont, values) in tab.ShaderKeys) - { - using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); - ref var key = ref tab.Mtrl.ShaderPackage.ShaderKeys[index]; - var shpkKey = tab.AssociatedShpk?.GetMaterialKeyById(key.Category); - var currentValue = key.Value; - var (currentLabel, _, currentDescription) = - values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); - if (!disabled && shpkKey.HasValue) - { - ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); - using (var c = ImRaii.Combo($"##{key.Category:X8}", currentLabel)) - { - if (c) - foreach (var (valueLabel, value, valueDescription) in values) - { - if (ImGui.Selectable(valueLabel, value == currentValue)) - { - key.Value = value; - ret = true; - tab.Update(); - } - - if (valueDescription.Length > 0) - ImGuiUtil.SelectableHelpMarker(valueDescription); - } - } - - ImGui.SameLine(); - if (description.Length > 0) - ImGuiUtil.LabeledHelpMarker(label, description); - else - ImGui.TextUnformatted(label); - } - else if (description.Length > 0 || currentDescription.Length > 0) - { - ImGuiUtil.LabeledHelpMarker($"{label}: {currentLabel}", - description + (description.Length > 0 && currentDescription.Length > 0 ? "\n\n" : string.Empty) + currentDescription); - } - else - { - ImGui.TextUnformatted($"{label}: {currentLabel}"); - } - } - - return ret; - } - - private static void DrawMaterialShaders(MtrlTab tab) - { - if (tab.AssociatedShpk == null) - return; - - ImRaii.TreeNode(tab.VertexShadersString, ImGuiTreeNodeFlags.Leaf).Dispose(); - ImRaii.TreeNode(tab.PixelShadersString, ImGuiTreeNodeFlags.Leaf).Dispose(); - - if (tab.ShaderComment.Length > 0) - { - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - ImGui.TextUnformatted(tab.ShaderComment); - } - } - - private static bool DrawMaterialConstants(MtrlTab tab, bool disabled) - { - if (tab.Constants.Count == 0) - return false; - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (!ImGui.CollapsingHeader("Material Constants")) - return false; - - using var _ = ImRaii.PushId("MaterialConstants"); - - var ret = false; - foreach (var (header, group) in tab.Constants) - { - using var t = ImRaii.TreeNode(header, ImGuiTreeNodeFlags.DefaultOpen); - if (!t) - continue; - - foreach (var (label, constantIndex, slice, description, monoFont, editor) in group) - { - var constant = tab.Mtrl.ShaderPackage.Constants[constantIndex]; - var buffer = tab.Mtrl.GetConstantValues(constant); - if (buffer.Length > 0) - { - using var id = ImRaii.PushId($"##{constant.Id:X8}:{slice.Start}"); - ImGui.SetNextItemWidth(250.0f); - if (editor.Draw(buffer[slice], disabled)) - { - ret = true; - tab.SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); - } - - ImGui.SameLine(); - using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); - if (description.Length > 0) - ImGuiUtil.LabeledHelpMarker(label, description); - else - ImGui.TextUnformatted(label); - } - } - } - - return ret; - } - - private static bool DrawMaterialSampler(MtrlTab tab, bool disabled, int textureIdx, int samplerIdx) - { - var ret = false; - ref var texture = ref tab.Mtrl.Textures[textureIdx]; - ref var sampler = ref tab.Mtrl.ShaderPackage.Samplers[samplerIdx]; - - // FIXME this probably doesn't belong here - static unsafe bool InputHexUInt16(string label, ref ushort v, ImGuiInputTextFlags flags) - { - fixed (ushort* v2 = &v) - { - return ImGui.InputScalar(label, ImGuiDataType.U16, (nint)v2, nint.Zero, nint.Zero, "%04X", flags); - } - } - - static bool ComboTextureAddressMode(string label, ref uint samplerFlags, int bitOffset) - { - var current = (TextureAddressMode)((samplerFlags >> bitOffset) & 0x3u); - using var c = ImRaii.Combo(label, current.ToString()); - if (!c) - return false; - - var ret = false; - foreach (var value in Enum.GetValues()) - { - if (ImGui.Selectable(value.ToString(), value == current)) - { - samplerFlags = (samplerFlags & ~(0x3u << bitOffset)) | ((uint)value << bitOffset); - ret = true; - } - - ImGuiUtil.SelectableHelpMarker(TextureAddressModeTooltips[(int)value]); - } - - return ret; - } - - var dx11 = texture.DX11; - if (ImGui.Checkbox("Prepend -- to the file name on DirectX 11", ref dx11)) - { - texture.DX11 = dx11; - ret = true; - } - - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ComboTextureAddressMode("##UAddressMode", ref sampler.Flags, 2)) - { - ret = true; - tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("U Address Mode", "Method to use for resolving a U texture coordinate that is outside the 0 to 1 range."); - - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ComboTextureAddressMode("##VAddressMode", ref sampler.Flags, 0)) - { - ret = true; - tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("V Address Mode", "Method to use for resolving a V texture coordinate that is outside the 0 to 1 range."); - - var lodBias = ((int)(sampler.Flags << 12) >> 22) / 64.0f; - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ImGui.DragFloat("##LoDBias", ref lodBias, 0.1f, -8.0f, 7.984375f)) - { - sampler.Flags = (uint)((sampler.Flags & ~0x000FFC00) - | ((uint)((int)Math.Round(Math.Clamp(lodBias, -8.0f, 7.984375f) * 64.0f) & 0x3FF) << 10)); - ret = true; - tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Level of Detail Bias", - "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); - - var minLod = (int)((sampler.Flags >> 20) & 0xF); - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ImGui.DragInt("##MinLoD", ref minLod, 0.1f, 0, 15)) - { - sampler.Flags = (uint)((sampler.Flags & ~0x00F00000) | ((uint)Math.Clamp(minLod, 0, 15) << 20)); - ret = true; - tab.SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Minimum Level of Detail", - "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); - - using var t = ImRaii.TreeNode("Advanced Settings"); - if (!t) - return ret; - - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (InputHexUInt16("Texture Flags", ref texture.Flags, - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None)) - ret = true; - - var samplerFlags = (int)sampler.Flags; - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ImGui.InputInt("Sampler Flags", ref samplerFlags, 0, 0, - ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) - { - sampler.Flags = (uint)samplerFlags; - ret = true; - tab.SetSamplerFlags(sampler.SamplerId, (uint)samplerFlags); - } - - return ret; - } - - private bool DrawMaterialShader(MtrlTab tab, bool disabled) - { - var ret = false; - if (ImGui.CollapsingHeader(tab.ShaderHeader)) - { - ret |= DrawPackageNameInput(tab, disabled); - ret |= DrawShaderFlagsInput(tab, disabled); - DrawCustomAssociations(tab); - ret |= DrawMaterialShaderKeys(tab, disabled); - DrawMaterialShaders(tab); - } - - if (tab.AssociatedShpkDevkit == null) - { - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - GC.KeepAlive(tab); - - var textColor = ImGui.GetColorU32(ImGuiCol.Text); - var textColorWarning = - (textColor & 0xFF000000u) - | ((textColor & 0x00FEFEFE) >> 1) - | (tab.AssociatedShpk == null ? 0x80u : 0x8080u); // Half red or yellow - - using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); - - ImGui.TextUnformatted(tab.AssociatedShpk == null - ? "Unable to find a suitable .shpk file for cross-references. Some functionality will be missing." - : "No dev-kit file found for this material's shaders. Please install one for optimal editing experience, such as actual constant names instead of hexadecimal identifiers."); - } - - return ret; - } - - private static string? MaterialParamName(bool componentOnly, int offset) - { - if (offset < 0) - return null; - - return (componentOnly, offset & 0x3) switch - { - (true, 0) => "x", - (true, 1) => "y", - (true, 2) => "z", - (true, 3) => "w", - (false, 0) => $"[{offset >> 2:D2}].x", - (false, 1) => $"[{offset >> 2:D2}].y", - (false, 2) => $"[{offset >> 2:D2}].z", - (false, 3) => $"[{offset >> 2:D2}].w", - _ => null, - }; - } - - private static string VectorSwizzle(int firstComponent, int lastComponent) - => (firstComponent, lastComponent) switch - { - (0, 4) => " ", - (0, 0) => ".x ", - (0, 1) => ".xy ", - (0, 2) => ".xyz ", - (0, 3) => " ", - (1, 1) => ".y ", - (1, 2) => ".yz ", - (1, 3) => ".yzw ", - (2, 2) => ".z ", - (2, 3) => ".zw ", - (3, 3) => ".w ", - _ => string.Empty, - }; - - private static (string? Name, bool ComponentOnly) MaterialParamRangeName(string prefix, int valueOffset, int valueLength) - { - if (valueLength == 0 || valueOffset < 0) - return (null, false); - - var firstVector = valueOffset >> 2; - var lastVector = (valueOffset + valueLength - 1) >> 2; - var firstComponent = valueOffset & 0x3; - var lastComponent = (valueOffset + valueLength - 1) & 0x3; - if (firstVector == lastVector) - return ($"{prefix}[{firstVector}]{VectorSwizzle(firstComponent, lastComponent)}", true); - - var sb = new StringBuilder(128); - sb.Append($"{prefix}[{firstVector}]{VectorSwizzle(firstComponent, 3).TrimEnd()}"); - for (var i = firstVector + 1; i < lastVector; ++i) - sb.Append($", [{i}]"); - - sb.Append($", [{lastVector}]{VectorSwizzle(0, lastComponent)}"); - return (sb.ToString(), false); - } -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 5a8fb13a..ee883daf 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -3,11 +3,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; -using OtterGui.Text; -using OtterGui.Widgets; -using Penumbra.GameData.Files; -using Penumbra.String.Classes; -using Penumbra.UI.Classes; +using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.UI.AdvancedWindow; @@ -17,177 +13,10 @@ public partial class ModEditWindow private bool DrawMaterialPanel(MtrlTab tab, bool disabled) { - DrawVersionUpdate(tab, disabled); - DrawMaterialLivePreviewRebind(tab, disabled); + if (tab.DrawVersionUpdate(disabled)) + _materialTab.SaveFile(); - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - var ret = DrawBackFaceAndTransparency(tab, disabled); - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - ret |= DrawMaterialShader(tab, disabled); - - ret |= DrawMaterialTextureChange(tab, disabled); - ret |= DrawMaterialColorTableChange(tab, disabled); - ret |= DrawMaterialConstants(tab, disabled); - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - DrawOtherMaterialDetails(tab.Mtrl, disabled); - - return !disabled && ret; - } - - private void DrawVersionUpdate(MtrlTab tab, bool disabled) - { - if (disabled || tab.Mtrl.IsDawnTrail) - return; - - if (!ImUtf8.ButtonEx("Update MTRL Version to Dawntrail"u8, - "Try using this if the material can not be loaded or should use legacy shaders.\n\nThis is not revertible."u8, - new Vector2(-0.1f, 0), false, 0, Colors.PressEnterWarningBg)) - return; - - tab.Mtrl.MigrateToDawntrail(); - _materialTab.SaveFile(); - } - - private static void DrawMaterialLivePreviewRebind(MtrlTab tab, bool disabled) - { - if (disabled) - return; - - if (ImGui.Button("Reload live preview")) - tab.BindToMaterialInstances(); - - if (tab.MaterialPreviewers.Count != 0 || tab.ColorTablePreviewers.Count != 0) - return; - - ImGui.SameLine(); - using var c = ImRaii.PushColor(ImGuiCol.Text, Colors.RegexWarningBorder); - ImGui.TextUnformatted( - "The current material has not been found on your character. Please check the Import from Screen tab for more information."); - } - - private static bool DrawMaterialTextureChange(MtrlTab tab, bool disabled) - { - if (tab.Textures.Count == 0) - return false; - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (!ImGui.CollapsingHeader("Textures and Samplers", ImGuiTreeNodeFlags.DefaultOpen)) - return false; - - var frameHeight = ImGui.GetFrameHeight(); - var ret = false; - using var table = ImRaii.Table("##Textures", 3); - - ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, frameHeight); - ImGui.TableSetupColumn("Path", ImGuiTableColumnFlags.WidthStretch); - ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.WidthFixed, tab.TextureLabelWidth * UiHelpers.Scale); - foreach (var (label, textureI, samplerI, description, monoFont) in tab.Textures) - { - using var _ = ImRaii.PushId(samplerI); - var tmp = tab.Mtrl.Textures[textureI].Path; - var unfolded = tab.UnfoldedTextures.Contains(samplerI); - ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton((unfolded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight).ToIconString(), - new Vector2(frameHeight), - "Settings for this texture and the associated sampler", false, true)) - { - unfolded = !unfolded; - if (unfolded) - tab.UnfoldedTextures.Add(samplerI); - else - tab.UnfoldedTextures.Remove(samplerI); - } - - ImGui.TableNextColumn(); - ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); - if (ImGui.InputText(string.Empty, ref tmp, Utf8GamePath.MaxGamePathLength, - disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None) - && tmp.Length > 0 - && tmp != tab.Mtrl.Textures[textureI].Path) - { - ret = true; - tab.Mtrl.Textures[textureI].Path = tmp; - } - - ImGui.TableNextColumn(); - using (ImRaii.PushFont(UiBuilder.MonoFont, monoFont)) - { - ImGui.AlignTextToFramePadding(); - if (description.Length > 0) - ImGuiUtil.LabeledHelpMarker(label, description); - else - ImGui.TextUnformatted(label); - } - - if (unfolded) - { - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - ret |= DrawMaterialSampler(tab, disabled, textureI, samplerI); - ImGui.TableNextColumn(); - } - } - - return ret; - } - - private static bool DrawBackFaceAndTransparency(MtrlTab tab, bool disabled) - { - const uint transparencyBit = 0x10; - const uint backfaceBit = 0x01; - - var ret = false; - - using var dis = ImRaii.Disabled(disabled); - - var tmp = (tab.Mtrl.ShaderPackage.Flags & transparencyBit) != 0; - if (ImGui.Checkbox("Enable Transparency", ref tmp)) - { - tab.Mtrl.ShaderPackage.Flags = - tmp ? tab.Mtrl.ShaderPackage.Flags | transparencyBit : tab.Mtrl.ShaderPackage.Flags & ~transparencyBit; - ret = true; - tab.SetShaderPackageFlags(tab.Mtrl.ShaderPackage.Flags); - } - - ImGui.SameLine(200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); - tmp = (tab.Mtrl.ShaderPackage.Flags & backfaceBit) != 0; - if (ImGui.Checkbox("Hide Backfaces", ref tmp)) - { - tab.Mtrl.ShaderPackage.Flags = tmp ? tab.Mtrl.ShaderPackage.Flags | backfaceBit : tab.Mtrl.ShaderPackage.Flags & ~backfaceBit; - ret = true; - tab.SetShaderPackageFlags(tab.Mtrl.ShaderPackage.Flags); - } - - return ret; - } - - private static void DrawOtherMaterialDetails(MtrlFile file, bool _) - { - if (!ImGui.CollapsingHeader("Further Content")) - return; - - using (var sets = ImRaii.TreeNode("UV Sets", ImGuiTreeNodeFlags.DefaultOpen)) - { - if (sets) - foreach (var set in file.UvSets) - ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); - } - - using (var sets = ImRaii.TreeNode("Color Sets", ImGuiTreeNodeFlags.DefaultOpen)) - { - if (sets) - foreach (var set in file.ColorSets) - ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); - } - - if (file.AdditionalData.Length <= 0) - return; - - using var t = ImRaii.TreeNode($"Additional Data (Size: {file.AdditionalData.Length})###AdditionalData"); - if (t) - Widget.DrawHexViewer(file.AdditionalData); + return tab.DrawPanel(disabled); } private void DrawMaterialReassignmentTab() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 55b7e748..6fb223df 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -15,6 +15,7 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { + private readonly FileDialogService _fileDialog; private readonly ResourceTreeFactory _resourceTreeFactory; private readonly ResourceTreeViewer _quickImportViewer; private readonly Dictionary _quickImportWritables = new(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 0d3dce8c..f28cb632 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -13,10 +13,8 @@ using Penumbra.Collections.Manager; using Penumbra.Communication; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; -using Penumbra.GameData.Interop; using Penumbra.Import.Models; using Penumbra.Import.Textures; -using Penumbra.Interop.Hooks.Objects; using Penumbra.Interop.ResourceTree; using Penumbra.Meta; using Penumbra.Mods; @@ -26,6 +24,7 @@ using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; +using Penumbra.UI.AdvancedWindow.Materials; using Penumbra.UI.AdvancedWindow.Meta; using Penumbra.UI.Classes; using Penumbra.Util; @@ -39,20 +38,17 @@ public partial class ModEditWindow : Window, IDisposable, IUiService public readonly MigrationManager MigrationManager; - private readonly PerformanceTracker _performance; - private readonly ModEditor _editor; - private readonly Configuration _config; - private readonly ItemSwapTab _itemSwapTab; - private readonly MetaFileManager _metaFileManager; - private readonly ActiveCollections _activeCollections; - private readonly StainService _stainService; - private readonly ModMergeTab _modMergeTab; - private readonly CommunicatorService _communicator; - private readonly IDragDropManager _dragDropManager; - private readonly IDataManager _gameData; - private readonly IFramework _framework; - private readonly ObjectManager _objects; - private readonly CharacterBaseDestructor _characterBaseDestructor; + private readonly PerformanceTracker _performance; + private readonly ModEditor _editor; + private readonly Configuration _config; + private readonly ItemSwapTab _itemSwapTab; + private readonly MetaFileManager _metaFileManager; + private readonly ActiveCollections _activeCollections; + private readonly ModMergeTab _modMergeTab; + private readonly CommunicatorService _communicator; + private readonly IDragDropManager _dragDropManager; + private readonly IDataManager _gameData; + private readonly IFramework _framework; private Vector2 _iconSize = Vector2.Zero; private bool _allowReduplicate; @@ -541,7 +537,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService /// If none exists, goes through all options in the currently selected mod (if any) in order of priority and resolves in them. /// If no redirection is found in either of those options, returns the original path. /// - private FullPath FindBestMatch(Utf8GamePath path) + internal FullPath FindBestMatch(Utf8GamePath path) { var currentFile = _activeCollections.Current.ResolvePath(path); if (currentFile != null) @@ -562,7 +558,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService return new FullPath(path); } - private HashSet FindPathsStartingWith(CiByteString prefix) + internal HashSet FindPathsStartingWith(CiByteString prefix) { var ret = new HashSet(); @@ -587,34 +583,32 @@ public partial class ModEditWindow : Window, IDisposable, IUiService public ModEditWindow(PerformanceTracker performance, FileDialogService fileDialog, ItemSwapTab itemSwapTab, IDataManager gameData, Configuration config, ModEditor editor, ResourceTreeFactory resourceTreeFactory, MetaFileManager metaFileManager, - StainService stainService, ActiveCollections activeCollections, ModMergeTab modMergeTab, + ActiveCollections activeCollections, ModMergeTab modMergeTab, CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, - ResourceTreeViewerFactory resourceTreeViewerFactory, ObjectManager objects, IFramework framework, - CharacterBaseDestructor characterBaseDestructor, MetaDrawers metaDrawers, MigrationManager migrationManager) + ResourceTreeViewerFactory resourceTreeViewerFactory, IFramework framework, + MetaDrawers metaDrawers, MigrationManager migrationManager, + MtrlTabFactory mtrlTabFactory) : base(WindowBaseLabel) { - _performance = performance; - _itemSwapTab = itemSwapTab; - _gameData = gameData; - _config = config; - _editor = editor; - _metaFileManager = metaFileManager; - _stainService = stainService; - _activeCollections = activeCollections; - _modMergeTab = modMergeTab; - _communicator = communicator; - _dragDropManager = dragDropManager; - _textures = textures; - _models = models; - _fileDialog = fileDialog; - _objects = objects; - _framework = framework; - _characterBaseDestructor = characterBaseDestructor; - MigrationManager = migrationManager; - _metaDrawers = metaDrawers; + _performance = performance; + _itemSwapTab = itemSwapTab; + _gameData = gameData; + _config = config; + _editor = editor; + _metaFileManager = metaFileManager; + _activeCollections = activeCollections; + _modMergeTab = modMergeTab; + _communicator = communicator; + _dragDropManager = dragDropManager; + _textures = textures; + _models = models; + _fileDialog = fileDialog; + _framework = framework; + MigrationManager = migrationManager; + _metaDrawers = metaDrawers; _materialTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => Mod?.ModPath.FullName ?? string.Empty, - (bytes, path, writable) => new MtrlTab(this, new MtrlFile(bytes), path, writable)); + (bytes, path, writable) => mtrlTabFactory.Create(this, new MtrlFile(bytes), path, writable)); _modelTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Models", ".mdl", () => PopulateIsOnPlayer(_editor.Files.Mdl, ResourceType.Mdl), DrawModelPanel, () => Mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new MdlTab(this, bytes, path)); diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 4d0c62af..d135e10c 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -24,6 +24,7 @@ public enum ColorId NoAssignment, SelectorPriority, InGameHighlight, + InGameHighlight2, ResTreeLocalPlayer, ResTreePlayer, ResTreeNetworked, @@ -70,7 +71,8 @@ public static class Colors ColorId.NoModsAssignment => ( 0x50000080, "'Use No Mods' Collection Assignment", "A collection assignment set to not use any mods at all."), ColorId.NoAssignment => ( 0x00000000, "Unassigned Collection Assignment", "A collection assignment that is not configured to any collection and thus just has no specific treatment."), ColorId.SelectorPriority => ( 0xFF808080, "Mod Selector Priority", "The priority displayed for non-zero priority mods in the mod selector."), - ColorId.InGameHighlight => ( 0xFFEBCF89, "In-Game Highlight", "An in-game element that has been highlighted for ease of editing."), + ColorId.InGameHighlight => ( 0xFFEBCF89, "In-Game Highlight (Primary)", "An in-game element that has been highlighted for ease of editing."), + ColorId.InGameHighlight2 => ( 0xFF446CC0, "In-Game Highlight (Secondary)", "Another in-game element that has been highlighted for ease of editing."), ColorId.ResTreeLocalPlayer => ( 0xFFFFE0A0, "On-Screen: You", "You and what you own (mount, minion, accessory, pets and so on), in the On-Screen tab." ), ColorId.ResTreePlayer => ( 0xFFC0FFC0, "On-Screen: Other Players", "Other players and what they own, in the On-Screen tab." ), ColorId.ResTreeNetworked => ( 0xFFFFFFFF, "On-Screen: Non-Players (Networked)", "Non-player entities handled by the game server, in the On-Screen tab." ), diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index ab47ce7c..41ca8d6e 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -327,6 +327,9 @@ public class SettingsTab : ITab, IUiService UiHelpers.DefaultLineSpace(); DrawModHandlingSettings(); + UiHelpers.DefaultLineSpace(); + + DrawModEditorSettings(); ImGui.NewLine(); } @@ -723,6 +726,15 @@ public class SettingsTab : ITab, IUiService "Set the default Penumbra mod folder to place newly imported mods into.\nLeave blank to import into Root."); } + + /// Draw all settings pertaining to advanced editing of mods. + private void DrawModEditorSettings() + { + Checkbox("Advanced Editing: Edit Raw Tile UV Transforms", + "Edit the raw matrix components of tile UV transforms, instead of having them decomposed into scale, rotation and shear.", + _config.EditRawTileTransforms, v => _config.EditRawTileTransforms = v); + } + #endregion /// Draw the entire Color subsection. From f4fe3605f003456a2ba7d1310c907b2d54d9547b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:42:32 +0200 Subject: [PATCH 0829/1381] DT material editor, new color tables --- .../Materials/MtrlTab.ColorTable.cs | 562 ++++++++++++++++++ .../Materials/MtrlTab.CommonColorTable.cs | 1 + 2 files changed, 563 insertions(+) create mode 100644 Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs new file mode 100644 index 00000000..dc87ec41 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -0,0 +1,562 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Files.StainMapStructs; +using Penumbra.Services; + +namespace Penumbra.UI.AdvancedWindow.Materials; + +public partial class MtrlTab +{ + private const float ColorTableScalarSize = 65.0f; + + private int _colorTableSelectedPair = 0; + + private bool DrawColorTable(ColorTable table, ColorDyeTable? dyeTable, bool disabled) + { + DrawColorTablePairSelector(table, disabled); + return DrawColorTablePairEditor(table, dyeTable, disabled); + } + + private void DrawColorTablePairSelector(ColorTable table, bool disabled) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var alignment = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); + var style = ImGui.GetStyle(); + var itemSpacing = style.ItemSpacing.X; + var itemInnerSpacing = style.ItemInnerSpacing.X; + var framePadding = style.FramePadding; + var buttonWidth = (ImGui.GetContentRegionAvail().X - itemSpacing * 7.0f) * 0.125f; + var frameHeight = ImGui.GetFrameHeight(); + var highlighterSize = ImUtf8.CalcIconSize(FontAwesomeIcon.Crosshairs) + framePadding * 2.0f; + var spaceWidth = ImUtf8.CalcTextSize(" "u8).X; + var spacePadding = (int)MathF.Ceiling((highlighterSize.X + framePadding.X + itemInnerSpacing) / spaceWidth); + for (var i = 0; i < ColorTable.NumRows >> 1; i += 8) + { + for (var j = 0; j < 8; ++j) + { + var pairIndex = i + j; + using (var color = ImRaii.PushColor(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.ButtonActive), pairIndex == _colorTableSelectedPair)) + { + if (ImUtf8.Button($"#{pairIndex + 1}".PadLeft(3 + spacePadding), new Vector2(buttonWidth, ImGui.GetFrameHeightWithSpacing() + frameHeight))) + _colorTableSelectedPair = pairIndex; + } + + var rcMin = ImGui.GetItemRectMin() + framePadding; + var rcMax = ImGui.GetItemRectMax() - framePadding; + CtBlendRect( + rcMin with { X = rcMax.X - frameHeight * 3 - itemInnerSpacing * 2 }, + rcMax with { X = rcMax.X - (frameHeight + itemInnerSpacing) * 2 }, + ImGuiUtil.ColorConvertFloat3ToU32(PseudoSqrtRgb((Vector3)table[pairIndex << 1].DiffuseColor)), + ImGuiUtil.ColorConvertFloat3ToU32(PseudoSqrtRgb((Vector3)table[(pairIndex << 1) | 1].DiffuseColor)) + ); + CtBlendRect( + rcMin with { X = rcMax.X - frameHeight * 2 - itemInnerSpacing }, + rcMax with { X = rcMax.X - frameHeight - itemInnerSpacing }, + ImGuiUtil.ColorConvertFloat3ToU32(PseudoSqrtRgb((Vector3)table[pairIndex << 1].SpecularColor)), + ImGuiUtil.ColorConvertFloat3ToU32(PseudoSqrtRgb((Vector3)table[(pairIndex << 1) | 1].SpecularColor)) + ); + CtBlendRect( + rcMin with { X = rcMax.X - frameHeight }, rcMax, + ImGuiUtil.ColorConvertFloat3ToU32(PseudoSqrtRgb((Vector3)table[pairIndex << 1].EmissiveColor)), + ImGuiUtil.ColorConvertFloat3ToU32(PseudoSqrtRgb((Vector3)table[(pairIndex << 1) | 1].EmissiveColor)) + ); + if (j < 7) + ImGui.SameLine(); + + var cursor = ImGui.GetCursorScreenPos(); + ImGui.SetCursorScreenPos(rcMin with { Y = float.Lerp(rcMin.Y, rcMax.Y, 0.5f) - highlighterSize.Y * 0.5f }); + font.Pop(); + ColorTableHighlightButton(pairIndex, disabled); + font.Push(UiBuilder.MonoFont); + ImGui.SetCursorScreenPos(cursor); + } + } + } + + private bool DrawColorTablePairEditor(ColorTable table, ColorDyeTable? dyeTable, bool disabled) + { + var retA = false; + var retB = false; + ref var rowA = ref table[_colorTableSelectedPair << 1]; + ref var rowB = ref table[(_colorTableSelectedPair << 1) | 1]; + var dyeA = dyeTable != null ? dyeTable[_colorTableSelectedPair << 1] : default; + var dyeB = dyeTable != null ? dyeTable[(_colorTableSelectedPair << 1) | 1] : default; + var previewDyeA = _stainService.GetStainCombo(dyeA.Channel).CurrentSelection.Key; + var previewDyeB = _stainService.GetStainCombo(dyeB.Channel).CurrentSelection.Key; + var dyePackA = _stainService.GudStmFile.GetValueOrNull(dyeA.Template, previewDyeA); + var dyePackB = _stainService.GudStmFile.GetValueOrNull(dyeB.Template, previewDyeB); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + ColorTableCopyClipboardButton(_colorTableSelectedPair << 1); + ImUtf8.SameLineInner(); + retA |= ColorTablePasteFromClipboardButton(_colorTableSelectedPair << 1, disabled); + ImGui.SameLine(); + CenteredTextInRest($"Row {_colorTableSelectedPair + 1}A"); + columns.Next(); + ColorTableCopyClipboardButton((_colorTableSelectedPair << 1) | 1); + ImUtf8.SameLineInner(); + retB |= ColorTablePasteFromClipboardButton((_colorTableSelectedPair << 1) | 1, disabled); + ImGui.SameLine(); + CenteredTextInRest($"Row {_colorTableSelectedPair + 1}B"); + } + + DrawHeader(" Colors"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("ColorsA"u8)) + retA |= DrawColors(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("ColorsB"u8)) + retB |= DrawColors(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + + DrawHeader(" Physical Parameters"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("PbrA"u8)) + retA |= DrawPbr(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("PbrB"u8)) + retB |= DrawPbr(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + + DrawHeader(" Sheen Layer Parameters"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("SheenA"u8)) + retA |= DrawSheen(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("SheenB"u8)) + retB |= DrawSheen(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + + DrawHeader(" Pair Blending"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("BlendingA"u8)) + retA |= DrawBlending(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("BlendingB"u8)) + retB |= DrawBlending(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + + DrawHeader(" Material Template"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("TemplateA"u8)) + retA |= DrawTemplate(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("TemplateB"u8)) + retB |= DrawTemplate(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + + if (dyeTable != null) + { + DrawHeader(" Dye Properties"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("DyeA"u8)) + retA |= DrawDye(dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("DyeB"u8)) + retB |= DrawDye(dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + } + + DrawHeader(" Further Content"u8); + using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + { + using var dis = ImRaii.Disabled(disabled); + using (var id = ImUtf8.PushId("FurtherA"u8)) + retA |= DrawFurther(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + columns.Next(); + using (var id = ImUtf8.PushId("FurtherB"u8)) + retB |= DrawFurther(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } + + if (retA) + UpdateColorTableRowPreview(_colorTableSelectedPair << 1); + if (retB) + UpdateColorTableRowPreview((_colorTableSelectedPair << 1) | 1); + + return retA | retB; + } + + /// Padding styles do not seem to apply to this component. It is recommended to prepend two spaces. + private static void DrawHeader(ReadOnlySpan label) + { + var headerColor = ImGui.GetColorU32(ImGuiCol.Header); + using var _ = ImRaii.PushColor(ImGuiCol.HeaderHovered, headerColor).Push(ImGuiCol.HeaderActive, headerColor); + ImUtf8.CollapsingHeader(label, ImGuiTreeNodeFlags.Leaf); + } + + private static bool DrawColors(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) + { + var dyeOffset = ImGui.GetContentRegionAvail().X + ImGui.GetStyle().ItemSpacing.X - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() * 2.0f; + + var ret = false; + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + + ret |= CtColorPicker("Diffuse Color"u8, default, row.DiffuseColor, + c => table[rowIdx].DiffuseColor = c); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeDiffuseColor"u8, "Apply Diffuse Color on Dye"u8, dye.DiffuseColor, + b => dyeTable[rowIdx].DiffuseColor = b); + ImUtf8.SameLineInner(); + CtColorPicker("##dyePreviewDiffuseColor"u8, "Dye Preview for Diffuse Color"u8, dyePack?.DiffuseColor); + } + + ret |= CtColorPicker("Specular Color"u8, default, row.SpecularColor, + c => table[rowIdx].SpecularColor = c); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeSpecularColor"u8, "Apply Specular Color on Dye"u8, dye.SpecularColor, + b => dyeTable[rowIdx].SpecularColor = b); + ImUtf8.SameLineInner(); + CtColorPicker("##dyePreviewSpecularColor"u8, "Dye Preview for Specular Color"u8, dyePack?.SpecularColor); + } + + ret |= CtColorPicker("Emissive Color"u8, default, row.EmissiveColor, + c => table[rowIdx].EmissiveColor = c); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeEmissiveColor"u8, "Apply Emissive Color on Dye"u8, dye.EmissiveColor, + b => dyeTable[rowIdx].EmissiveColor = b); + ImUtf8.SameLineInner(); + CtColorPicker("##dyePreviewEmissiveColor"u8, "Dye Preview for Emissive Color"u8, dyePack?.EmissiveColor); + } + + return ret; + } + + private static bool DrawBlending(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) + { + var scalarSize = ColorTableScalarSize * UiHelpers.Scale; + var dyeOffset = ImGui.GetContentRegionAvail().X + ImGui.GetStyle().ItemSpacing.X - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + + var isRowB = (rowIdx & 1) != 0; + + var ret = false; + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf(isRowB ? "Field #19"u8 : "Anisotropy Degree"u8, default, row.Anisotropy, "%.2f"u8, 0.0f, HalfMaxValue, 0.1f, + v => table[rowIdx].Anisotropy = v); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeAnisotropy"u8, isRowB ? "Apply Field #19 on Dye"u8 : "Apply Anisotropy Degree on Dye"u8, dye.Anisotropy, + b => dyeTable[rowIdx].Anisotropy = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragHalf("##dyePreviewAnisotropy"u8, isRowB ? "Dye Preview for Field #19"u8 : "Dye Preview for Anisotropy Degree"u8, dyePack?.Anisotropy, "%.2f"u8); + } + + return ret; + } + + private bool DrawTemplate(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) + { + var scalarSize = ColorTableScalarSize * UiHelpers.Scale; + var itemSpacing = ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize - 64.0f; + var subcolWidth = CalculateSubcolumnWidth(2); + + var ret = false; + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Shader ID"u8, default, row.ShaderId, "%d"u8, (ushort)0, (ushort)255, 0.25f, + v => table[rowIdx].ShaderId = v); + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + + ImGui.SetNextItemWidth(scalarSize + itemSpacing + 64.0f); + ret |= CtSphereMapIndexPicker("###SphereMapIndex"u8, default, row.SphereMapIndex, false, + v => table[rowIdx].SphereMapIndex = v); + ImUtf8.SameLineInner(); + ImUtf8.Text("Sphere Map"u8); + if (dyeTable != null) + { + var textRectMin = ImGui.GetItemRectMin(); + var textRectMax = ImGui.GetItemRectMax(); + ImGui.SameLine(dyeOffset); + var cursor = ImGui.GetCursorScreenPos(); + ImGui.SetCursorScreenPos(cursor with { Y = float.Lerp(textRectMin.Y, textRectMax.Y, 0.5f) - ImGui.GetFrameHeight() * 0.5f }); + ret |= CtApplyStainCheckbox("##dyeSphereMapIndex"u8, "Apply Sphere Map on Dye"u8, dye.SphereMapIndex, + b => dyeTable[rowIdx].SphereMapIndex = b); + ImUtf8.SameLineInner(); + ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() with { Y = cursor.Y }); + ImGui.SetNextItemWidth(scalarSize + itemSpacing + 64.0f); + using var dis = ImRaii.Disabled(); + CtSphereMapIndexPicker("###SphereMapIndexDye"u8, "Dye Preview for Sphere Map"u8, dyePack?.SphereMapIndex ?? ushort.MaxValue, false, Nop); + } + + ImGui.Dummy(new Vector2(64.0f, 0.0f)); + ImGui.SameLine(); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Sphere Map Intensity"u8, default, (float)row.SphereMapMask * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].SphereMapMask = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeSphereMapMask"u8, "Apply Sphere Map Intensity on Dye"u8, dye.SphereMapMask, + b => dyeTable[rowIdx].SphereMapMask = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragScalar("##dyeSphereMapMask"u8, "Dye Preview for Sphere Map Intensity"u8, (float?)dyePack?.SphereMapMask * 100.0f, "%.0f%%"u8); + } + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + + var leftLineHeight = 64.0f + ImGui.GetStyle().FramePadding.Y * 2.0f; + var rightLineHeight = 3.0f * ImGui.GetFrameHeight() + 2.0f * ImGui.GetStyle().ItemSpacing.Y; + var lineHeight = Math.Max(leftLineHeight, rightLineHeight); + var cursorPos = ImGui.GetCursorScreenPos(); + ImGui.SetCursorScreenPos(cursorPos + new Vector2(0.0f, (lineHeight - leftLineHeight) * 0.5f)); + ImGui.SetNextItemWidth(scalarSize + (itemSpacing + 64.0f) * 2.0f); + ret |= CtTileIndexPicker("###TileIndex"u8, default, row.TileIndex, false, + v => table[rowIdx].TileIndex = v); + ImUtf8.SameLineInner(); + ImUtf8.Text("Tile"u8); + + ImGui.SameLine(subcolWidth); + ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() with { Y = cursorPos.Y + (lineHeight - rightLineHeight) * 0.5f, }); + using (var cld = ImUtf8.Child("###TileProperties"u8, new(ImGui.GetContentRegionAvail().X, float.Lerp(rightLineHeight, lineHeight, 0.5f)), false)) + { + ImGui.Dummy(new Vector2(scalarSize, 0.0f)); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Tile Opacity"u8, default, (float)row.TileAlpha * 100.0f, "%.0f%%"u8, 0.0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].TileAlpha = (Half)(v * 0.01f)); + + ret |= CtTileTransformMatrix(row.TileTransform, scalarSize, true, + m => table[rowIdx].TileTransform = m); + ImUtf8.SameLineInner(); + ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() - new Vector2(0.0f, (ImGui.GetFrameHeight() + ImGui.GetStyle().ItemSpacing.Y) * 0.5f)); + ImUtf8.Text("Tile Transform"u8); + } + + return ret; + } + + private static bool DrawPbr(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) + { + var scalarSize = ColorTableScalarSize * UiHelpers.Scale; + var subcolWidth = CalculateSubcolumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = subcolWidth - ImGui.GetStyle().ItemSpacing.X * 2.0f - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + + var ret = false; + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Roughness"u8, default, (float)row.Roughness * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].Roughness = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeRoughness"u8, "Apply Roughness on Dye"u8, dye.Roughness, + b => dyeTable[rowIdx].Roughness = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragScalar("##dyePreviewRoughness"u8, "Dye Preview for Roughness"u8, (float?)dyePack?.Roughness * 100.0f, "%.0f%%"u8); + } + + ImGui.SameLine(subcolWidth); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Metalness"u8, default, (float)row.Metalness * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].Metalness = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImGui.SameLine(subcolWidth + dyeOffset); + ret |= CtApplyStainCheckbox("##dyeMetalness"u8, "Apply Metalness on Dye"u8, dye.Metalness, + b => dyeTable[rowIdx].Metalness = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragScalar("##dyePreviewMetalness"u8, "Dye Preview for Metalness"u8, (float?)dyePack?.Metalness * 100.0f, "%.0f%%"u8); + } + + return ret; + } + + private static bool DrawSheen(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) + { + var scalarSize = ColorTableScalarSize * UiHelpers.Scale; + var subcolWidth = CalculateSubcolumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = subcolWidth - ImGui.GetStyle().ItemSpacing.X * 2.0f - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + + var ret = false; + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Sheen"u8, default, (float)row.SheenRate * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].SheenRate = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeSheenRate"u8, "Apply Sheen on Dye"u8, dye.SheenRate, + b => dyeTable[rowIdx].SheenRate = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragScalar("##dyePreviewSheenRate"u8, "Dye Preview for Sheen"u8, (float?)dyePack?.SheenRate * 100.0f, "%.0f%%"u8); + } + + ImGui.SameLine(subcolWidth); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Sheen Tint"u8, default, (float)row.SheenTintRate * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + v => table[rowIdx].SheenTintRate = (Half)(v * 0.01f)); + if (dyeTable != null) + { + ImGui.SameLine(subcolWidth + dyeOffset); + ret |= CtApplyStainCheckbox("##dyeSheenTintRate"u8, "Apply Sheen Tint on Dye"u8, dye.SheenTintRate, + b => dyeTable[rowIdx].SheenTintRate = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragScalar("##dyePreviewSheenTintRate"u8, "Dye Preview for Sheen Tint"u8, (float?)dyePack?.SheenTintRate * 100.0f, "%.0f%%"u8); + } + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Sheen Roughness"u8, default, 100.0f / (float)row.SheenAperture, "%.0f%%"u8, 100.0f / HalfMaxValue, 100.0f / HalfEpsilon, 1.0f, + v => table[rowIdx].SheenAperture = (Half)(100.0f / v)); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeSheenRoughness"u8, "Apply Sheen Roughness on Dye"u8, dye.SheenAperture, + b => dyeTable[rowIdx].SheenAperture = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragScalar("##dyePreviewSheenRoughness"u8, "Dye Preview for Sheen Roughness"u8, 100.0f / (float?)dyePack?.SheenAperture, "%.0f%%"u8); + } + + return ret; + } + + private static bool DrawFurther(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) + { + var scalarSize = ColorTableScalarSize * UiHelpers.Scale; + var subcolWidth = CalculateSubcolumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = subcolWidth - ImGui.GetStyle().ItemSpacing.X * 2.0f - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + + var ret = false; + ref var row = ref table[rowIdx]; + var dye = dyeTable != null ? dyeTable[rowIdx] : default; + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #11"u8, default, row.Scalar11, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar11 = v); + if (dyeTable != null) + { + ImGui.SameLine(dyeOffset); + ret |= CtApplyStainCheckbox("##dyeScalar11"u8, "Apply Field #11 on Dye"u8, dye.Scalar3, + b => dyeTable[rowIdx].Scalar3 = b); + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(scalarSize); + CtDragHalf("##dyePreviewScalar11"u8, "Dye Preview for Field #11"u8, dyePack?.Scalar3, "%.2f"u8); + } + + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #3"u8, default, row.Scalar3, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar3 = v); + + ImGui.SameLine(subcolWidth); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #7"u8, default, row.Scalar7, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar7 = v); + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #15"u8, default, row.Scalar15, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar15 = v); + + ImGui.SameLine(subcolWidth); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #17"u8, default, row.Scalar17, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar17 = v); + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #20"u8, default, row.Scalar20, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar20 = v); + + ImGui.SameLine(subcolWidth); + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #22"u8, default, row.Scalar22, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar22 = v); + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragHalf("Field #23"u8, default, row.Scalar23, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, + v => table[rowIdx].Scalar23 = v); + + return ret; + } + + private bool DrawDye(ColorDyeTable dyeTable, DyePack? dyePack, int rowIdx) + { + var scalarSize = ColorTableScalarSize * UiHelpers.Scale; + var applyButtonWidth = ImUtf8.CalcTextSize("Apply Preview Dye"u8).X + ImGui.GetStyle().FramePadding.X * 2.0f; + var subcolWidth = CalculateSubcolumnWidth(2, applyButtonWidth); + + var ret = false; + ref var dye = ref dyeTable[rowIdx]; + + ImGui.SetNextItemWidth(scalarSize); + ret |= CtDragScalar("Dye Channel"u8, default, dye.Channel + 1, "%d"u8, 1, StainService.ChannelCount, 0.1f, + value => dyeTable[rowIdx].Channel = (byte)(Math.Clamp(value, 1, StainService.ChannelCount) - 1)); + ImGui.SameLine(subcolWidth); + ImGui.SetNextItemWidth(scalarSize); + if (_stainService.GudTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, + scalarSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) + { + dye.Template = _stainService.LegacyTemplateCombo.CurrentSelection; + ret = true; + } + ImUtf8.SameLineInner(); + ImUtf8.Text("Dye Template"u8); + ImGui.SameLine(ImGui.GetContentRegionAvail().X - applyButtonWidth + ImGui.GetStyle().ItemSpacing.X); + using var dis = ImRaii.Disabled(!dyePack.HasValue); + if (ImUtf8.Button("Apply Preview Dye"u8)) + { + ret |= Mtrl.ApplyDyeToRow(_stainService.GudStmFile, [ + _stainService.StainCombo1.CurrentSelection.Key, + _stainService.StainCombo2.CurrentSelection.Key, + ], rowIdx); + } + + return ret; + } + + private static void CenteredTextInRest(string text) + => AlignedTextInRest(text, 0.5f); + + private static void AlignedTextInRest(string text, float alignment) + { + var width = ImGui.CalcTextSize(text).X; + ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() + new Vector2((ImGui.GetContentRegionAvail().X - width) * alignment, 0.0f)); + ImGui.TextUnformatted(text); + } + + private static float CalculateSubcolumnWidth(int numSubcolumns, float reservedSpace = 0.0f) + { + var itemSpacing = ImGui.GetStyle().ItemSpacing.X; + return (ImGui.GetContentRegionAvail().X - reservedSpace - itemSpacing * (numSubcolumns - 1)) / numSubcolumns + itemSpacing; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index 937614de..2b093e23 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -52,6 +52,7 @@ public partial class MtrlTab { LegacyColorTable legacyTable => DrawLegacyColorTable(legacyTable, Mtrl.DyeTable as LegacyColorDyeTable, disabled), ColorTable table when Mtrl.ShaderPackage.Name is "characterlegacy.shpk" => DrawLegacyColorTable(table, Mtrl.DyeTable as ColorDyeTable, disabled), + ColorTable table => DrawColorTable(table, Mtrl.DyeTable as ColorDyeTable, disabled), _ => false, }; From 5323add662874d3b0286f8ed35930b620fd99630 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:45:52 +0200 Subject: [PATCH 0830/1381] Improve ShPk tab --- .../ModEditWindow.ShaderPackages.cs | 287 ++++++++++++++---- .../AdvancedWindow/ModEditWindow.ShpkTab.cs | 287 ++++++++++++++++-- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- 3 files changed, 494 insertions(+), 82 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 017478a7..8a1c729c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -1,7 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; using ImGuiNET; -using Lumina.Misc; using OtterGui.Raii; using OtterGui; using OtterGui.Classes; @@ -11,6 +10,9 @@ using Penumbra.GameData.Interop; using Penumbra.String; using static Penumbra.GameData.Files.ShpkFile; using OtterGui.Widgets; +using Penumbra.GameData.Files.ShaderStructs; +using OtterGui.Text; +using Penumbra.GameData.Structs; namespace Penumbra.UI.AdvancedWindow; @@ -24,6 +26,9 @@ public partial class ModEditWindow { DrawShaderPackageSummary(file); + ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); + DrawShaderPackageFilterSection(file); + var ret = false; ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); ret |= DrawShaderPackageShaderArray(file, "Vertex Shader", file.Shpk.VertexShaders, disabled); @@ -50,15 +55,16 @@ public partial class ModEditWindow private static void DrawShaderPackageSummary(ShpkTab tab) { + if (tab.Shpk.IsLegacy) + { + ImUtf8.Text("This legacy shader package will not work in the current version of the game. Do not attempt to load it.", + ImGuiUtil.HalfBlendText(0x80u)); // Half red + } ImGui.TextUnformatted(tab.Header); if (!tab.Shpk.Disassembled) { - var textColor = ImGui.GetColorU32(ImGuiCol.Text); - var textColorWarning = (textColor & 0xFF000000u) | ((textColor & 0x00FEFEFE) >> 1) | 0x80u; // Half red - - using var c = ImRaii.PushColor(ImGuiCol.Text, textColorWarning); - - ImGui.TextUnformatted("Your system doesn't support disassembling shaders. Some functionality will be missing."); + ImUtf8.Text("Your system doesn't support disassembling shaders. Some functionality will be missing.", + ImGuiUtil.HalfBlendText(0x80u)); // Half red } } @@ -123,6 +129,7 @@ public partial class ModEditWindow { shaders[idx].UpdateResources(tab.Shpk); tab.Shpk.UpdateResources(); + tab.UpdateFilteredUsed(); } catch (Exception e) { @@ -149,6 +156,97 @@ public partial class ModEditWindow ImGuiInputTextFlags.ReadOnly, null, null); } + private static void DrawShaderUsage(ShpkTab tab, Shader shader) + { + using (var node = ImUtf8.TreeNode("Used with Shader Keys"u8)) + { + if (node) + { + foreach (var (key, keyIdx) in shader.SystemValues!.WithIndex()) + { + ImRaii.TreeNode($"Used with System Key {tab.TryResolveName(tab.Shpk.SystemKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } + + foreach (var (key, keyIdx) in shader.SceneValues!.WithIndex()) + { + ImRaii.TreeNode($"Used with Scene Key {tab.TryResolveName(tab.Shpk.SceneKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } + + foreach (var (key, keyIdx) in shader.MaterialValues!.WithIndex()) + { + ImRaii.TreeNode($"Used with Material Key {tab.TryResolveName(tab.Shpk.MaterialKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } + + foreach (var (key, keyIdx) in shader.SubViewValues!.WithIndex()) + { + ImRaii.TreeNode($"Used with Sub-View Key #{keyIdx} \u2208 {{ {tab.NameSetToString(key)} }}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } + } + } + + ImRaii.TreeNode($"Used in Passes: {tab.NameSetToString(shader.Passes)}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } + + private static void DrawShaderPackageFilterSection(ShpkTab tab) + { + if (!ImUtf8.CollapsingHeader(tab.FilterPopCount == tab.FilterMaximumPopCount ? "Filters###Filters"u8 : "Filters (ACTIVE)###Filters"u8)) + return; + + foreach (var (key, keyIdx) in tab.Shpk.SystemKeys.WithIndex()) + DrawShaderPackageFilterSet(tab, $"System Key {tab.TryResolveName(key.Id)}", ref tab.FilterSystemValues[keyIdx]); + + foreach (var (key, keyIdx) in tab.Shpk.SceneKeys.WithIndex()) + DrawShaderPackageFilterSet(tab, $"Scene Key {tab.TryResolveName(key.Id)}", ref tab.FilterSceneValues[keyIdx]); + + foreach (var (key, keyIdx) in tab.Shpk.MaterialKeys.WithIndex()) + DrawShaderPackageFilterSet(tab, $"Material Key {tab.TryResolveName(key.Id)}", ref tab.FilterMaterialValues[keyIdx]); + + foreach (var (_, keyIdx) in tab.Shpk.SubViewKeys.WithIndex()) + DrawShaderPackageFilterSet(tab, $"Sub-View Key #{keyIdx}", ref tab.FilterSubViewValues[keyIdx]); + + DrawShaderPackageFilterSet(tab, "Passes", ref tab.FilterPasses); + } + + private static void DrawShaderPackageFilterSet(ShpkTab tab, string label, ref SharedSet values) + { + if (values.PossibleValues == null) + { + ImRaii.TreeNode(label, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + return; + } + + using var node = ImRaii.TreeNode(label); + if (!node) + return; + + foreach (var value in values.PossibleValues) + { + var contains = values.Contains(value); + if (!ImGui.Checkbox($"{tab.TryResolveName(value)}", ref contains)) + continue; + if (contains) + { + if (values.AddExisting(value)) + { + ++tab.FilterPopCount; + tab.UpdateFilteredUsed(); + } + } + else + { + if (values.Remove(value)) + { + --tab.FilterPopCount; + tab.UpdateFilteredUsed(); + } + } + } + } + private static bool DrawShaderPackageShaderArray(ShpkTab tab, string objectName, Shader[] shaders, bool disabled) { if (shaders.Length == 0 || !ImGui.CollapsingHeader($"{objectName}s")) @@ -157,8 +255,11 @@ public partial class ModEditWindow var ret = false; for (var idx = 0; idx < shaders.Length; ++idx) { - var shader = shaders[idx]; - using var t = ImRaii.TreeNode($"{objectName} #{idx}"); + var shader = shaders[idx]; + if (!tab.IsFilterMatch(shader)) + continue; + + using var t = ImRaii.TreeNode($"{objectName} #{idx}"); if (!t) continue; @@ -169,9 +270,11 @@ public partial class ModEditWindow DrawShaderImportButton(tab, objectName, shaders, idx); } - ret |= DrawShaderPackageResourceArray("Constant Buffers", "slot", true, shader.Constants, true); - ret |= DrawShaderPackageResourceArray("Samplers", "slot", false, shader.Samplers, true); - ret |= DrawShaderPackageResourceArray("Unordered Access Views", "slot", true, shader.Uavs, true); + ret |= DrawShaderPackageResourceArray("Constant Buffers", "slot", true, shader.Constants, false, true); + ret |= DrawShaderPackageResourceArray("Samplers", "slot", false, shader.Samplers, false, true); + if (!tab.Shpk.IsLegacy) + ret |= DrawShaderPackageResourceArray("Textures", "slot", false, shader.Textures, false, true); + ret |= DrawShaderPackageResourceArray("Unordered Access Views", "slot", true, shader.Uavs, false, true); if (shader.DeclaredInputs != 0) ImRaii.TreeNode($"Declared Inputs: {shader.DeclaredInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); @@ -187,12 +290,14 @@ public partial class ModEditWindow if (tab.Shpk.Disassembled) DrawRawDisassembly(shader); + + DrawShaderUsage(tab, shader); } return ret; } - private static bool DrawShaderPackageResource(string slotLabel, bool withSize, ref Resource resource, bool disabled) + private static bool DrawShaderPackageResource(string slotLabel, bool withSize, ref Resource resource, bool hasFilter, bool disabled) { var ret = false; if (!disabled) @@ -205,16 +310,26 @@ public partial class ModEditWindow if (resource.Used == null) return ret; - var usedString = UsedComponentString(withSize, resource); + var usedString = UsedComponentString(withSize, false, resource); if (usedString.Length > 0) - ImRaii.TreeNode($"Used: {usedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + { + ImRaii.TreeNode(hasFilter ? $"Globally Used: {usedString}" : $"Used: {usedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + if (hasFilter) + { + var filteredUsedString = UsedComponentString(withSize, true, resource); + if (filteredUsedString.Length > 0) + ImRaii.TreeNode($"Used within Filters: {filteredUsedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + else + ImRaii.TreeNode("Unused within Filters", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } + } else - ImRaii.TreeNode("Unused", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImRaii.TreeNode(hasFilter ? "Globally Unused" : "Unused", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); return ret; } - private static bool DrawShaderPackageResourceArray(string arrayName, string slotLabel, bool withSize, Resource[] resources, bool disabled) + private static bool DrawShaderPackageResourceArray(string arrayName, string slotLabel, bool withSize, Resource[] resources, bool hasFilter, bool disabled) { if (resources.Length == 0) return false; @@ -233,7 +348,7 @@ public partial class ModEditWindow using var t2 = ImRaii.TreeNode(name, !disabled || buf.Used != null ? 0 : ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); font.Dispose(); if (t2) - ret |= DrawShaderPackageResource(slotLabel, withSize, ref buf, disabled); + ret |= DrawShaderPackageResource(slotLabel, withSize, ref buf, hasFilter, disabled); } return ret; @@ -268,7 +383,7 @@ public partial class ModEditWindow private static bool DrawShaderPackageMaterialMatrix(ShpkTab tab, bool disabled) { ImGui.TextUnformatted(tab.Shpk.Disassembled - ? "Parameter positions (continuations are grayed out, unused values are red):" + ? "Parameter positions (continuations are grayed out, globally unused values are red, unused values within filters are yellow):" : "Parameter positions (continuations are grayed out):"); using var table = ImRaii.Table("##MaterialParamLayout", 5, @@ -276,17 +391,17 @@ public partial class ModEditWindow if (!table) return false; - ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, 25 * UiHelpers.Scale); - ImGui.TableSetupColumn("x", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); - ImGui.TableSetupColumn("y", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); - ImGui.TableSetupColumn("z", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); - ImGui.TableSetupColumn("w", ImGuiTableColumnFlags.WidthFixed, 100 * UiHelpers.Scale); + ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, 40 * UiHelpers.Scale); + ImGui.TableSetupColumn("x", ImGuiTableColumnFlags.WidthFixed, 250 * UiHelpers.Scale); + ImGui.TableSetupColumn("y", ImGuiTableColumnFlags.WidthFixed, 250 * UiHelpers.Scale); + ImGui.TableSetupColumn("z", ImGuiTableColumnFlags.WidthFixed, 250 * UiHelpers.Scale); + ImGui.TableSetupColumn("w", ImGuiTableColumnFlags.WidthFixed, 250 * UiHelpers.Scale); ImGui.TableHeadersRow(); var textColorStart = ImGui.GetColorU32(ImGuiCol.Text); - var textColorCont = (textColorStart & 0x00FFFFFFu) | ((textColorStart & 0xFE000000u) >> 1); // Half opacity - var textColorUnusedStart = (textColorStart & 0xFF000000u) | ((textColorStart & 0x00FEFEFE) >> 1) | 0x80u; // Half red - var textColorUnusedCont = (textColorUnusedStart & 0x00FFFFFFu) | ((textColorUnusedStart & 0xFE000000u) >> 1); + var textColorCont = ImGuiUtil.HalfTransparent(textColorStart); // Half opacity + var textColorUnusedStart = ImGuiUtil.HalfBlend(textColorStart, 0x80u); // Half red + var textColorUnusedCont = ImGuiUtil.HalfTransparent(textColorUnusedStart); var ret = false; for (var i = 0; i < tab.Matrix.GetLength(0); ++i) @@ -296,14 +411,13 @@ public partial class ModEditWindow for (var j = 0; j < 4; ++j) { var (name, tooltip, idx, colorType) = tab.Matrix[i, j]; - var color = colorType switch - { - ShpkTab.ColorType.Unused => textColorUnusedStart, - ShpkTab.ColorType.Used => textColorStart, - ShpkTab.ColorType.Continuation => textColorUnusedCont, - ShpkTab.ColorType.Continuation | ShpkTab.ColorType.Used => textColorCont, - _ => textColorStart, - }; + var color = textColorStart; + if (!colorType.HasFlag(ShpkTab.ColorType.Used)) + color = ImGuiUtil.HalfBlend(color, 0x80u); // Half red + else if (!colorType.HasFlag(ShpkTab.ColorType.FilteredUsed)) + color = ImGuiUtil.HalfBlend(color, 0x8080u); // Half yellow + if (colorType.HasFlag(ShpkTab.ColorType.Continuation)) + color = ImGuiUtil.HalfTransparent(color); // Half opacity using var _ = ImRaii.PushId(i * 4 + j); var deletable = !disabled && idx >= 0; using (var font = ImRaii.PushFont(UiBuilder.MonoFont, tooltip.Length > 0)) @@ -331,6 +445,35 @@ public partial class ModEditWindow return ret; } + private static void DrawShaderPackageMaterialDevkitExport(ShpkTab tab) + { + if (!ImUtf8.Button("Export globally unused parameters as material dev-kit file"u8)) + return; + + tab.FileDialog.OpenSavePicker("Export material dev-kit file", ".json", $"{Path.GetFileNameWithoutExtension(tab.FilePath)}.json", ".json", DoSave, null, false); + + void DoSave(bool success, string path) + { + if (!success) + return; + + try + { + File.WriteAllText(path, tab.ExportDevkit().ToString()); + } + catch (Exception e) + { + Penumbra.Messager.NotificationMessage(e, $"Could not export dev-kit for {Path.GetFileName(tab.FilePath)} to {path}.", + NotificationType.Error, false); + return; + } + + Penumbra.Messager.NotificationMessage( + $"Material dev-kit file for {Path.GetFileName(tab.FilePath)} exported successfully to {Path.GetFileName(path)}.", + NotificationType.Success, false); + } + } + private static void DrawShaderPackageMisalignedParameters(ShpkTab tab) { using var t = ImRaii.TreeNode("Misaligned / Overflowing Parameters"); @@ -396,23 +539,25 @@ public partial class ModEditWindow DrawShaderPackageEndCombo(tab); ImGui.SetNextItemWidth(UiHelpers.Scale * 400); - if (ImGui.InputText("Name", ref tab.NewMaterialParamName, 63)) - tab.NewMaterialParamId = Crc32.Get(tab.NewMaterialParamName, 0xFFFFFFFFu); + var newName = tab.NewMaterialParamName.Value!; + if (ImGui.InputText("Name", ref newName, 63)) + tab.NewMaterialParamName = newName; - var tooltip = tab.UsedIds.Contains(tab.NewMaterialParamId) + var tooltip = tab.UsedIds.Contains(tab.NewMaterialParamName.Crc32) ? "The ID is already in use. Please choose a different name." : string.Empty; - if (!ImGuiUtil.DrawDisabledButton($"Add ID 0x{tab.NewMaterialParamId:X8}", new Vector2(400 * UiHelpers.Scale, ImGui.GetFrameHeight()), + if (!ImGuiUtil.DrawDisabledButton($"Add {tab.NewMaterialParamName} (0x{tab.NewMaterialParamName.Crc32:X8})", new Vector2(400 * UiHelpers.Scale, ImGui.GetFrameHeight()), tooltip, tooltip.Length > 0)) return false; tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.AddItem(new MaterialParam { - Id = tab.NewMaterialParamId, + Id = tab.NewMaterialParamName.Crc32, ByteOffset = (ushort)(tab.Orphans[tab.NewMaterialParamStart].Index << 2), ByteSize = (ushort)((tab.NewMaterialParamEnd - tab.NewMaterialParamStart + 1) << 2), }); + tab.AddNameToCache(tab.NewMaterialParamName); tab.Update(); return true; } @@ -434,6 +579,9 @@ public partial class ModEditWindow else if (!disabled && sizeWellDefined) ret |= DrawShaderPackageNewParameter(tab); + if (tab.Shpk.Disassembled) + DrawShaderPackageMaterialDevkitExport(tab); + return ret; } @@ -444,14 +592,17 @@ public partial class ModEditWindow if (!ImGui.CollapsingHeader("Shader Resources")) return false; - ret |= DrawShaderPackageResourceArray("Constant Buffers", "type", true, tab.Shpk.Constants, disabled); - ret |= DrawShaderPackageResourceArray("Samplers", "type", false, tab.Shpk.Samplers, disabled); - ret |= DrawShaderPackageResourceArray("Unordered Access Views", "type", false, tab.Shpk.Uavs, disabled); + var hasFilters = tab.FilterPopCount != tab.FilterMaximumPopCount; + ret |= DrawShaderPackageResourceArray("Constant Buffers", "type", true, tab.Shpk.Constants, hasFilters, disabled); + ret |= DrawShaderPackageResourceArray("Samplers", "type", false, tab.Shpk.Samplers, hasFilters, disabled); + if (!tab.Shpk.IsLegacy) + ret |= DrawShaderPackageResourceArray("Textures", "type", false, tab.Shpk.Textures, hasFilters, disabled); + ret |= DrawShaderPackageResourceArray("Unordered Access Views", "type", false, tab.Shpk.Uavs, hasFilters, disabled); return ret; } - private static void DrawKeyArray(string arrayName, bool withId, IReadOnlyCollection keys) + private static void DrawKeyArray(ShpkTab tab, string arrayName, bool withId, IReadOnlyCollection keys) { if (keys.Count == 0) return; @@ -463,12 +614,11 @@ public partial class ModEditWindow using var font = ImRaii.PushFont(UiBuilder.MonoFont); foreach (var (key, idx) in keys.WithIndex()) { - using var t2 = ImRaii.TreeNode(withId ? $"#{idx}: ID: 0x{key.Id:X8}" : $"#{idx}"); + using var t2 = ImRaii.TreeNode(withId ? $"#{idx}: {tab.TryResolveName(key.Id)} (0x{key.Id:X8})" : $"#{idx}"); if (t2) { - ImRaii.TreeNode($"Default Value: 0x{key.DefaultValue:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - ImRaii.TreeNode($"Known Values: {string.Join(", ", Array.ConvertAll(key.Values, value => $"0x{value:X8}"))}", - ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImRaii.TreeNode($"Default Value: {tab.TryResolveName(key.DefaultValue)} (0x{key.DefaultValue:X8})", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImRaii.TreeNode($"Known Values: {tab.NameSetToString(key.Values, true)}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } } } @@ -482,39 +632,46 @@ public partial class ModEditWindow if (!t) return; + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + foreach (var (node, idx) in tab.Shpk.Nodes.WithIndex()) { - using var font = ImRaii.PushFont(UiBuilder.MonoFont); - using var t2 = ImRaii.TreeNode($"#{idx:D4}: Selector: 0x{node.Selector:X8}"); + if (!tab.IsFilterMatch(node)) + continue; + + using var t2 = ImRaii.TreeNode($"#{idx:D4}: Selector: 0x{node.Selector:X8}"); if (!t2) continue; foreach (var (key, keyIdx) in node.SystemKeys.WithIndex()) { - ImRaii.TreeNode($"System Key 0x{tab.Shpk.SystemKeys[keyIdx].Id:X8} = 0x{key:X8}", + ImRaii.TreeNode($"System Key {tab.TryResolveName(tab.Shpk.SystemKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SystemValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in node.SceneKeys.WithIndex()) { - ImRaii.TreeNode($"Scene Key 0x{tab.Shpk.SceneKeys[keyIdx].Id:X8} = 0x{key:X8}", + ImRaii.TreeNode($"Scene Key {tab.TryResolveName(tab.Shpk.SceneKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SceneValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in node.MaterialKeys.WithIndex()) { - ImRaii.TreeNode($"Material Key 0x{tab.Shpk.MaterialKeys[keyIdx].Id:X8} = 0x{key:X8}", + ImRaii.TreeNode($"Material Key {tab.TryResolveName(tab.Shpk.MaterialKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.MaterialValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in node.SubViewKeys.WithIndex()) - ImRaii.TreeNode($"Sub-View Key #{keyIdx} = 0x{key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + { + ImRaii.TreeNode($"Sub-View Key #{keyIdx} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SubViewValues![keyIdx])} }}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } ImRaii.TreeNode($"Pass Indices: {string.Join(' ', node.PassIndices.Select(c => $"{c:X2}"))}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); foreach (var (pass, passIdx) in node.Passes.WithIndex()) { - ImRaii.TreeNode($"Pass #{passIdx}: ID: 0x{pass.Id:X8}, Vertex Shader #{pass.VertexShader}, Pixel Shader #{pass.PixelShader}", + ImRaii.TreeNode($"Pass #{passIdx}: ID: {tab.TryResolveName(pass.Id)}, Vertex Shader #{pass.VertexShader}, Pixel Shader #{pass.PixelShader}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) .Dispose(); } @@ -526,10 +683,10 @@ public partial class ModEditWindow if (!ImGui.CollapsingHeader("Shader Selection")) return; - DrawKeyArray("System Keys", true, tab.Shpk.SystemKeys); - DrawKeyArray("Scene Keys", true, tab.Shpk.SceneKeys); - DrawKeyArray("Material Keys", true, tab.Shpk.MaterialKeys); - DrawKeyArray("Sub-View Keys", false, tab.Shpk.SubViewKeys); + DrawKeyArray(tab, "System Keys", true, tab.Shpk.SystemKeys); + DrawKeyArray(tab, "Scene Keys", true, tab.Shpk.SceneKeys); + DrawKeyArray(tab, "Material Keys", true, tab.Shpk.MaterialKeys); + DrawKeyArray(tab, "Sub-View Keys", false, tab.Shpk.SubViewKeys); DrawShaderPackageNodes(tab); using var t = ImRaii.TreeNode($"Node Selectors ({tab.Shpk.NodeSelectors.Count})###NodeSelectors"); @@ -559,12 +716,14 @@ public partial class ModEditWindow } } - private static string UsedComponentString(bool withSize, in Resource resource) + private static string UsedComponentString(bool withSize, bool filtered, in Resource resource) { + var used = filtered ? resource.FilteredUsed : resource.Used; + var usedDynamically = filtered ? resource.FilteredUsedDynamically : resource.UsedDynamically; var sb = new StringBuilder(256); if (withSize) { - foreach (var (components, i) in (resource.Used ?? Array.Empty()).WithIndex()) + foreach (var (components, i) in (used ?? Array.Empty()).WithIndex()) { switch (components) { @@ -582,7 +741,7 @@ public partial class ModEditWindow } } - switch (resource.UsedDynamically ?? 0) + switch (usedDynamically ?? 0) { case 0: break; case DisassembledShader.VectorComponents.All: @@ -590,7 +749,7 @@ public partial class ModEditWindow break; default: sb.Append("[*]."); - foreach (var c in resource.UsedDynamically!.Value.ToString().Where(char.IsUpper)) + foreach (var c in usedDynamically!.Value.ToString().Where(char.IsUpper)) sb.Append(char.ToLower(c)); sb.Append(", "); @@ -599,7 +758,7 @@ public partial class ModEditWindow } else { - var components = (resource.Used is { Length: > 0 } ? resource.Used[0] : 0) | (resource.UsedDynamically ?? 0); + var components = (used is { Length: > 0 } ? used[0] : 0) | (usedDynamically ?? 0); if ((components & DisassembledShader.VectorComponents.X) != 0) sb.Append("Red, "); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index 12b8d761..de20aa9f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -1,9 +1,12 @@ using Dalamud.Utility; -using Lumina.Misc; +using Newtonsoft.Json.Linq; using OtterGui; -using Penumbra.GameData.Data; +using OtterGui.Classes; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.ShaderStructs; using Penumbra.GameData.Interop; +using Penumbra.GameData.Structs; +using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.UI.AdvancedWindow; @@ -12,18 +15,27 @@ public partial class ModEditWindow private class ShpkTab : IWritable { public readonly ShpkFile Shpk; + public readonly string FilePath; - public string NewMaterialParamName = string.Empty; - public uint NewMaterialParamId = Crc32.Get(string.Empty, 0xFFFFFFFFu); - public short NewMaterialParamStart; - public short NewMaterialParamEnd; + public Name NewMaterialParamName = string.Empty; + public short NewMaterialParamStart; + public short NewMaterialParamEnd; + + public SharedSet[] FilterSystemValues; + public SharedSet[] FilterSceneValues; + public SharedSet[] FilterMaterialValues; + public SharedSet[] FilterSubViewValues; + public SharedSet FilterPasses; + + public readonly int FilterMaximumPopCount; + public int FilterPopCount; public readonly FileDialogService FileDialog; public readonly string Header; public readonly string Extension; - public ShpkTab(FileDialogService fileDialog, byte[] bytes) + public ShpkTab(FileDialogService fileDialog, byte[] bytes, string filePath) { FileDialog = fileDialog; try @@ -34,6 +46,7 @@ public partial class ModEditWindow { Shpk = new ShpkFile(bytes, false); } + FilePath = filePath; Header = $"Shader Package for DirectX {(int)Shpk.DirectXVersion}"; Extension = Shpk.DirectXVersion switch @@ -42,15 +55,36 @@ public partial class ModEditWindow ShpkFile.DxVersion.DirectX11 => ".dxbc", _ => throw new NotImplementedException(), }; + + FilterSystemValues = Array.ConvertAll(Shpk.SystemKeys, key => key.Values.FullSet()); + FilterSceneValues = Array.ConvertAll(Shpk.SceneKeys, key => key.Values.FullSet()); + FilterMaterialValues = Array.ConvertAll(Shpk.MaterialKeys, key => key.Values.FullSet()); + FilterSubViewValues = Array.ConvertAll(Shpk.SubViewKeys, key => key.Values.FullSet()); + FilterPasses = Shpk.Passes.FullSet(); + + FilterMaximumPopCount = FilterPasses.Count; + foreach (var key in Shpk.SystemKeys) + FilterMaximumPopCount += key.Values.Count; + foreach (var key in Shpk.SceneKeys) + FilterMaximumPopCount += key.Values.Count; + foreach (var key in Shpk.MaterialKeys) + FilterMaximumPopCount += key.Values.Count; + foreach (var key in Shpk.SubViewKeys) + FilterMaximumPopCount += key.Values.Count; + + FilterPopCount = FilterMaximumPopCount; + + UpdateNameCache(); + Shpk.UpdateFilteredUsed(IsFilterMatch); Update(); } [Flags] public enum ColorType : byte { - Unused = 0, Used = 1, - Continuation = 2, + FilteredUsed = 2, + Continuation = 4, } public (string Name, string Tooltip, short Index, ColorType Color)[,] Matrix = null!; @@ -58,10 +92,87 @@ public partial class ModEditWindow public readonly HashSet UsedIds = new(16); public readonly List<(string Name, short Index)> Orphans = new(16); + private readonly Dictionary _nameCache = []; + private readonly Dictionary, string> _nameSetCache = []; + private readonly Dictionary, string> _nameSetWithIdsCache = []; + + public void AddNameToCache(Name name) + { + if (name.Value != null) + _nameCache.TryAdd(name.Crc32, name); + + _nameSetCache.Clear(); + _nameSetWithIdsCache.Clear(); + } + + public void UpdateNameCache() + { + static void CollectResourceNames(Dictionary nameCache, ShpkFile.Resource[] resources) + { + foreach (var resource in resources) + nameCache.TryAdd(resource.Id, resource.Name); + } + + static void CollectKeyNames(Dictionary nameCache, ShpkFile.Key[] keys) + { + foreach (var key in keys) + { + var keyName = nameCache.TryResolve(Names.KnownNames, key.Id); + var valueNames = keyName.WithKnownSuffixes(); + foreach (var value in key.Values) + { + var valueName = valueNames.TryResolve(value); + if (valueName.Value != null) + nameCache.TryAdd(value, valueName); + } + } + } + + CollectResourceNames(_nameCache, Shpk.Constants); + CollectResourceNames(_nameCache, Shpk.Samplers); + CollectResourceNames(_nameCache, Shpk.Textures); + CollectResourceNames(_nameCache, Shpk.Uavs); + + CollectKeyNames(_nameCache, Shpk.SystemKeys); + CollectKeyNames(_nameCache, Shpk.SceneKeys); + CollectKeyNames(_nameCache, Shpk.MaterialKeys); + CollectKeyNames(_nameCache, Shpk.SubViewKeys); + + _nameSetCache.Clear(); + _nameSetWithIdsCache.Clear(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Name TryResolveName(uint crc32) + => _nameCache.TryResolve(Names.KnownNames, crc32); + + public string NameSetToString(SharedSet nameSet, bool withIds = false) + { + var cache = withIds ? _nameSetWithIdsCache : _nameSetCache; + if (cache.TryGetValue(nameSet, out var nameSetStr)) + return nameSetStr; + if (withIds) + nameSetStr = string.Join(", ", nameSet.Select(id => $"{TryResolveName(id)} (0x{id:X8})")); + else + nameSetStr = string.Join(", ", nameSet.Select(TryResolveName)); + cache.Add(nameSet, nameSetStr); + return nameSetStr; + } + + public void UpdateFilteredUsed() + { + Shpk.UpdateFilteredUsed(IsFilterMatch); + + var materialParams = Shpk.GetConstantById(ShpkFile.MaterialParamsConstantId); + UpdateColors(materialParams); + } + public void Update() { var materialParams = Shpk.GetConstantById(ShpkFile.MaterialParamsConstantId); var numParameters = ((Shpk.MaterialParamsSize + 0xFu) & ~0xFu) >> 4; + var defaults = Shpk.MaterialParamsDefaults != null ? (ReadOnlySpan)Shpk.MaterialParamsDefaults : []; + var defaultFloats = MemoryMarshal.Cast(defaults); Matrix = new (string Name, string Tooltip, short Index, ColorType Color)[numParameters, 4]; MalformedParameters.Clear(); @@ -75,14 +186,14 @@ public partial class ModEditWindow var jEnd = ((param.ByteOffset + param.ByteSize - 1) >> 2) & 3; if ((param.ByteOffset & 0x3) != 0 || (param.ByteSize & 0x3) != 0) { - MalformedParameters.Add($"ID: 0x{param.Id:X8}, offset: 0x{param.ByteOffset:X4}, size: 0x{param.ByteSize:X4}"); + MalformedParameters.Add($"ID: {TryResolveName(param.Id)} (0x{param.Id:X8}), offset: 0x{param.ByteOffset:X4}, size: 0x{param.ByteSize:X4}"); continue; } if (iEnd >= numParameters) { MalformedParameters.Add( - $"{MaterialParamRangeName(materialParams?.Name ?? string.Empty, param.ByteOffset >> 2, param.ByteSize >> 2)} (ID: 0x{param.Id:X8})"); + $"{MtrlTab.MaterialParamRangeName(materialParams?.Name ?? string.Empty, param.ByteOffset >> 2, param.ByteSize >> 2)} ({TryResolveName(param.Id)}, 0x{param.Id:X8})"); continue; } @@ -91,9 +202,12 @@ public partial class ModEditWindow var end = i == iEnd ? jEnd : 3; for (var j = i == iStart ? jStart : 0; j <= end; ++j) { + var component = (i << 2) | j; var tt = - $"{MaterialParamRangeName(materialParams?.Name ?? string.Empty, param.ByteOffset >> 2, param.ByteSize >> 2).Item1} (ID: 0x{param.Id:X8})"; - Matrix[i, j] = ($"0x{param.Id:X8}", tt, (short)idx, 0); + $"{MtrlTab.MaterialParamRangeName(materialParams?.Name ?? string.Empty, param.ByteOffset >> 2, param.ByteSize >> 2).Item1} ({TryResolveName(param.Id)}, 0x{param.Id:X8})"; + if (component < defaultFloats.Length) + tt += $"\n\nDefault value: {defaultFloats[component]} ({defaults[component << 2]:X2} {defaults[(component << 2) | 1]:X2} {defaults[(component << 2) | 2]:X2} {defaults[(component << 2) | 3]:X2})"; + Matrix[i, j] = (TryResolveName(param.Id).ToString(), tt, (short)idx, 0); } } } @@ -151,7 +265,7 @@ public partial class ModEditWindow if (oldStart == linear) newMaterialParamStart = (short)Orphans.Count; - Orphans.Add(($"{materialParams?.Name ?? string.Empty}{MaterialParamName(false, linear)}", linear)); + Orphans.Add(($"{materialParams?.Name ?? ShpkFile.MaterialParamsConstantName}{MtrlTab.MaterialParamName(false, linear)}", linear)); } } @@ -168,11 +282,15 @@ public partial class ModEditWindow { var usedComponents = (materialParams?.Used?[i] ?? DisassembledShader.VectorComponents.All) | (materialParams?.UsedDynamically ?? 0); + var filteredUsedComponents = (materialParams?.FilteredUsed?[i] ?? DisassembledShader.VectorComponents.All) + | (materialParams?.FilteredUsedDynamically ?? 0); for (var j = 0; j < 4; ++j) { - var color = ((byte)usedComponents & (1 << j)) != 0 - ? ColorType.Used - : 0; + ColorType color = 0; + if (((byte)usedComponents & (1 << j)) != 0) + color |= ColorType.Used; + if (((byte)filteredUsedComponents & (1 << j)) != 0) + color |= ColorType.FilteredUsed; if (Matrix[i, j].Index == lastIndex || Matrix[i, j].Index < 0) color |= ColorType.Continuation; @@ -182,6 +300,141 @@ public partial class ModEditWindow } } + public bool IsFilterMatch(ShpkFile.Shader shader) + { + if (!FilterPasses.Overlaps(shader.Passes)) + return false; + + for (var i = 0; i < shader.SystemValues!.Length; ++i) + { + if (!FilterSystemValues[i].Overlaps(shader.SystemValues[i])) + return false; + } + + for (var i = 0; i < shader.SceneValues!.Length; ++i) + { + if (!FilterSceneValues[i].Overlaps(shader.SceneValues[i])) + return false; + } + + for (var i = 0; i < shader.MaterialValues!.Length; ++i) + { + if (!FilterMaterialValues[i].Overlaps(shader.MaterialValues[i])) + return false; + } + + for (var i = 0; i < shader.SubViewValues!.Length; ++i) + { + if (!FilterSubViewValues[i].Overlaps(shader.SubViewValues[i])) + return false; + } + + return true; + } + + public bool IsFilterMatch(ShpkFile.Node node) + { + if (!node.Passes.Any(pass => FilterPasses.Contains(pass.Id))) + return false; + + for (var i = 0; i < node.SystemValues!.Length; ++i) + { + if (!FilterSystemValues[i].Overlaps(node.SystemValues[i])) + return false; + } + + for (var i = 0; i < node.SceneValues!.Length; ++i) + { + if (!FilterSceneValues[i].Overlaps(node.SceneValues[i])) + return false; + } + + for (var i = 0; i < node.MaterialValues!.Length; ++i) + { + if (!FilterMaterialValues[i].Overlaps(node.MaterialValues[i])) + return false; + } + + for (var i = 0; i < node.SubViewValues!.Length; ++i) + { + if (!FilterSubViewValues[i].Overlaps(node.SubViewValues[i])) + return false; + } + + return true; + } + + /// + /// Generates a minimal material dev-kit file for the given shader package. + /// + /// This file currently only hides globally unused material constants. + /// + public JObject ExportDevkit() + { + var devkit = new JObject(); + + var maybeMaterialParameter = Shpk.GetConstantById(ShpkFile.MaterialParamsConstantId); + if (maybeMaterialParameter.HasValue) + { + var materialParameter = maybeMaterialParameter.Value; + var materialParameterUsage = new IndexSet(materialParameter.Size << 2, true); + + var used = materialParameter.Used ?? []; + var usedDynamically = materialParameter.UsedDynamically ?? 0; + for (var i = 0; i < used.Length; ++i) + { + for (var j = 0; j < 4; ++j) + { + if (!(used[i] | usedDynamically).HasFlag((DisassembledShader.VectorComponents)(1 << j))) + materialParameterUsage[(i << 2) | j] = false; + } + } + + var dkConstants = new JObject(); + foreach (var param in Shpk.MaterialParams) + { + // Don't handle misaligned parameters. + if ((param.ByteOffset & 0x3) != 0 || (param.ByteSize & 0x3) != 0) + continue; + + var start = param.ByteOffset >> 2; + var length = param.ByteSize >> 2; + + // If the parameter is fully used, don't include it. + if (!materialParameterUsage.Indices(start, length, true).Any()) + continue; + + var unusedSlices = new JArray(); + + if (materialParameterUsage.Indices(start, length).Any()) + { + foreach (var (rgStart, rgEnd) in materialParameterUsage.Ranges(start, length, true)) + { + unusedSlices.Add(new JObject + { + ["Type"] = "Hidden", + ["Offset"] = rgStart, + ["Length"] = rgEnd - rgStart, + }); + } + } + else + { + unusedSlices.Add(new JObject + { + ["Type"] = "Hidden", + }); + } + + dkConstants[param.Id.ToString()] = unusedSlices; + } + + devkit["Constants"] = dkConstants; + } + + return devkit; + } + public bool Valid => Shpk.Valid; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index f28cb632..13458252 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -615,7 +615,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _shaderPackageTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Shaders", ".shpk", () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => Mod?.ModPath.FullName ?? string.Empty, - (bytes, _, _) => new ShpkTab(_fileDialog, bytes)); + (bytes, path, _) => new ShpkTab(_fileDialog, bytes, path)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); _resourceTreeFactory = resourceTreeFactory; From c01aa000fb94afcbfc13fcfe87c4ab6bd5b5f86d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 17:46:29 +0200 Subject: [PATCH 0831/1381] Optimize I/O of ShPk for ResourceTree generation --- Penumbra/Interop/ResourceTree/ResolveContext.cs | 11 ++++++++--- Penumbra/Interop/ResourceTree/TreeBuildCache.cs | 14 +++++++++----- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 3fc1ae3c..41485d75 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -230,8 +230,8 @@ internal unsafe partial record ResolveContext( node.Children.Add(shpkNode); } - var shpkFile = Global.WithUiData && shpkNode != null ? Global.TreeBuildCache.ReadShaderPackage(shpkNode.FullPath) : null; - var shpk = Global.WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; + var shpkNames = Global.WithUiData && shpkNode != null ? Global.TreeBuildCache.ReadShaderPackageNames(shpkNode.FullPath) : null; + var shpk = Global.WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->TextureCount; i++) @@ -255,7 +255,12 @@ internal unsafe partial record ResolveContext( alreadyProcessedSamplerIds.Add(samplerId.Value); var samplerCrc = GetSamplerCrcById(shpk, samplerId.Value); if (samplerCrc.HasValue) - name = shpkFile?.GetSamplerById(samplerCrc.Value)?.Name ?? $"Texture 0x{samplerCrc.Value:X8}"; + { + if (shpkNames != null && shpkNames.TryGetValue(samplerCrc.Value, out var samplerName)) + name = samplerName.Value; + else + name = $"Texture 0x{samplerCrc.Value:X8}"; + } } } diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index ca5ff736..49e00547 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -1,8 +1,11 @@ +using System.IO.MemoryMappedFiles; using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.ShaderStructs; +using Penumbra.GameData.Files.Utility; using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; using Penumbra.String.Classes; @@ -11,7 +14,7 @@ namespace Penumbra.Interop.ResourceTree; internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager dataManager, ActorManager actors) { - private readonly Dictionary _shaderPackages = []; + private readonly Dictionary?> _shaderPackageNames = []; public unsafe bool IsLocalPlayerRelated(ICharacter character) { @@ -68,10 +71,10 @@ internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager data } /// Try to read a shpk file from the given path and cache it on success. - public ShpkFile? ReadShaderPackage(FullPath path) - => ReadFile(dataManager, path, _shaderPackages, bytes => new ShpkFile(bytes)); + public IReadOnlyDictionary? ReadShaderPackageNames(FullPath path) + => ReadFile(dataManager, path, _shaderPackageNames, bytes => ShpkFile.FastExtractNames(bytes.Span)); - private static T? ReadFile(IDataManager dataManager, FullPath path, Dictionary cache, Func parseFile) + private static T? ReadFile(IDataManager dataManager, FullPath path, Dictionary cache, Func, T> parseFile) where T : class { if (path.FullName.Length == 0) @@ -86,7 +89,8 @@ internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager data { if (path.IsRooted) { - parsed = parseFile(File.ReadAllBytes(pathStr)); + using var mmFile = MmioMemoryManager.CreateFromFile(pathStr, access: MemoryMappedFileAccess.Read); + parsed = parseFile(mmFile.Memory); } else { From c849e310343b465d88619f05e9b30384d1caa709 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 19:48:42 +0200 Subject: [PATCH 0832/1381] RT: Use SpanTextWriter to assemble paths --- .../ResolveContext.PathResolution.cs | 28 +++++++++++++------ .../Interop/ResourceTree/ResolveContext.cs | 25 +++++++++-------- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 85b3284a..b99468f8 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using OtterGui.Text.HelperObjects; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -8,6 +9,7 @@ using Penumbra.Meta.Manipulations; using Penumbra.String; using Penumbra.String.Classes; using static Penumbra.Interop.Structs.StructExtensions; +using CharaBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase; using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; namespace Penumbra.Interop.ResourceTree; @@ -95,7 +97,7 @@ internal partial record ResolveContext var variant = ResolveMaterialVariant(imc, Equipment.Variant); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); - Span pathBuffer = stackalloc byte[260]; + Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; @@ -125,7 +127,7 @@ internal partial record ResolveContext fileName.CopyTo(mirroredFileName); WriteZeroPaddedNumber(mirroredFileName[4..8], mirroredSetId); - Span pathBuffer = stackalloc byte[260]; + Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, mirroredFileName); var weaponPosition = pathBuffer.IndexOf("/weapon/w"u8); @@ -144,7 +146,7 @@ internal partial record ResolveContext var variant = ResolveMaterialVariant(imc, (byte)((Monster*)CharacterBase)->Variant); var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); - Span pathBuffer = stackalloc byte[260]; + Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; @@ -175,13 +177,21 @@ internal partial record ResolveContext var baseDirectory = modelPath[..modelPosition]; - baseDirectory.CopyTo(materialPathBuffer); - "/material/v"u8.CopyTo(materialPathBuffer[baseDirectory.Length..]); - WriteZeroPaddedNumber(materialPathBuffer.Slice(baseDirectory.Length + 11, 4), variant); - materialPathBuffer[baseDirectory.Length + 15] = (byte)'/'; - mtrlFileName.CopyTo(materialPathBuffer[(baseDirectory.Length + 16)..]); + var writer = new SpanTextWriter(materialPathBuffer); + writer.Append(baseDirectory); + writer.Append("/material/v"u8); + WriteZeroPaddedNumber(ref writer, 4, variant); + writer.Append((byte)'/'); + writer.Append(mtrlFileName); + writer.EnsureNullTerminated(); - return materialPathBuffer[..(baseDirectory.Length + 16 + mtrlFileName.Length)]; + return materialPathBuffer[..writer.Position]; + } + + private static void WriteZeroPaddedNumber(ref SpanTextWriter writer, int width, ushort number) + { + WriteZeroPaddedNumber(writer.GetRemainingSpan()[..width], number); + writer.Advance(width); } private static void WriteZeroPaddedNumber(Span destination, ushort number) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 3fc1ae3c..29e15055 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -1,9 +1,9 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; using OtterGui; +using OtterGui.Text.HelperObjects; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.GameData.Data; @@ -16,7 +16,7 @@ using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; using static Penumbra.Interop.Structs.StructExtensions; -using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; +using CharaBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase; namespace Penumbra.Interop.ResourceTree; @@ -29,25 +29,25 @@ internal record GlobalResolveContext( { public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); - public unsafe ResolveContext CreateContext(CharacterBase* characterBase, uint slotIndex = 0xFFFFFFFFu, + public unsafe ResolveContext CreateContext(CharaBase* characterBase, uint slotIndex = 0xFFFFFFFFu, EquipSlot slot = EquipSlot.Unknown, CharacterArmor equipment = default, SecondaryId secondaryId = default) => new(this, characterBase, slotIndex, slot, equipment, secondaryId); } internal unsafe partial record ResolveContext( GlobalResolveContext Global, - Pointer CharacterBasePointer, + Pointer CharacterBasePointer, uint SlotIndex, EquipSlot Slot, CharacterArmor Equipment, SecondaryId SecondaryId) { - public CharacterBase* CharacterBase + public CharaBase* CharacterBase => CharacterBasePointer.Value; private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk"u8, true, true, true); - private ModelType ModelType + private CharaBase.ModelType ModelType => CharacterBase->GetModelType(); private ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, CiByteString gamePath) @@ -75,11 +75,14 @@ internal unsafe partial record ResolveContext( if (lastDirectorySeparator == -1 || lastDirectorySeparator > gamePath.Length - 3) return null; - Span prefixed = stackalloc byte[260]; - gamePath.Span[..(lastDirectorySeparator + 1)].CopyTo(prefixed); - prefixed[lastDirectorySeparator + 1] = (byte)'-'; - prefixed[lastDirectorySeparator + 2] = (byte)'-'; - gamePath.Span[(lastDirectorySeparator + 1)..].CopyTo(prefixed[(lastDirectorySeparator + 3)..]); + Span prefixed = stackalloc byte[CharaBase.PathBufferSize]; + + var writer = new SpanTextWriter(prefixed); + writer.Append(gamePath.Span[..(lastDirectorySeparator + 1)]); + writer.Append((byte)'-'); + writer.Append((byte)'-'); + writer.Append(gamePath.Span[(lastDirectorySeparator + 1)..]); + writer.EnsureNullTerminated(); if (!Utf8GamePath.FromSpan(prefixed[..(gamePath.Length + 2)], MetaDataComputation.None, out var tmp)) return null; From 243593e30f74c43a14b7d0ccdd9a264830158a59 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 19:52:39 +0200 Subject: [PATCH 0833/1381] RT: Fix VPR offhand material paths --- .../ResolveContext.PathResolution.cs | 34 ++++++++----------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index b99468f8..c3894b05 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -111,31 +111,25 @@ internal partial record ResolveContext if (setIdHigh is 20 && mtrlFileName[14] == (byte)'c') return Utf8GamePath.FromString(GamePaths.Weapon.Mtrl.Path(2001, 1, 1, "c"), out var path) ? path : Utf8GamePath.Empty; - // MNK (03??, 16??), NIN (18??) and DNC (26??) offhands share materials with the corresponding mainhand - if (setIdHigh is 3 or 16 or 18 or 26) + // Some offhands share materials with the corresponding mainhand + if (ItemData.AdaptOffhandImc(Equipment.Set.Id, out var mirroredSetId)) { - var setIdLow = Equipment.Set.Id % 100; - if (setIdLow > 50) - { - var variant = ResolveMaterialVariant(imc, Equipment.Variant); - var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); + var variant = ResolveMaterialVariant(imc, Equipment.Variant); + var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); - var mirroredSetId = (ushort)(Equipment.Set.Id - 50); + Span mirroredFileName = stackalloc byte[32]; + mirroredFileName = mirroredFileName[..fileName.Length]; + fileName.CopyTo(mirroredFileName); + WriteZeroPaddedNumber(mirroredFileName[4..8], mirroredSetId.Id); - Span mirroredFileName = stackalloc byte[32]; - mirroredFileName = mirroredFileName[..fileName.Length]; - fileName.CopyTo(mirroredFileName); - WriteZeroPaddedNumber(mirroredFileName[4..8], mirroredSetId); + Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; + pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, mirroredFileName); - Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; - pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, mirroredFileName); + var weaponPosition = pathBuffer.IndexOf("/weapon/w"u8); + if (weaponPosition >= 0) + WriteZeroPaddedNumber(pathBuffer[(weaponPosition + 9)..(weaponPosition + 13)], mirroredSetId.Id); - var weaponPosition = pathBuffer.IndexOf("/weapon/w"u8); - if (weaponPosition >= 0) - WriteZeroPaddedNumber(pathBuffer[(weaponPosition + 9)..(weaponPosition + 13)], mirroredSetId); - - return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; - } + return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; } return ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName); From 75e3ef72f3dbaff37db0ba18d2770a5e7885f3ae Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 3 Aug 2024 20:27:16 +0200 Subject: [PATCH 0834/1381] RT: Fix Facewear --- .../ResolveContext.PathResolution.cs | 16 ++++++---- Penumbra/Interop/ResourceTree/ResourceTree.cs | 30 ++++++++++++------- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index c3894b05..43324516 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -16,20 +16,26 @@ namespace Penumbra.Interop.ResourceTree; internal partial record ResolveContext { + private static bool IsEquipmentOrAccessorySlot(uint slotIndex) + => slotIndex is < 10 or 16 or 17; + + private static bool IsEquipmentSlot(uint slotIndex) + => slotIndex is < 5 or 16 or 17; + private Utf8GamePath ResolveModelPath() { // Correctness: // Resolving a model path through the game's code can use EQDP metadata for human equipment models. return ModelType switch { - ModelType.Human when SlotIndex < 10 => ResolveEquipmentModelPath(), - _ => ResolveModelPathNative(), + ModelType.Human when IsEquipmentOrAccessorySlot(SlotIndex) => ResolveEquipmentModelPath(), + _ => ResolveModelPathNative(), }; } private Utf8GamePath ResolveEquipmentModelPath() { - var path = SlotIndex < 5 + var path = IsEquipmentSlot(SlotIndex) ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot) : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; @@ -41,7 +47,7 @@ internal partial record ResolveContext private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, PrimaryId primaryId) { var slotIndex = slot.ToIndex(); - if (slotIndex >= 10 || ModelType != ModelType.Human) + if (!IsEquipmentOrAccessorySlot(slotIndex) || ModelType != ModelType.Human) return GenderRace.MidlanderMale; var characterRaceCode = (GenderRace)((Human*)CharacterBase)->RaceSexId; @@ -82,7 +88,7 @@ internal partial record ResolveContext // Resolving a material path through the game's code can dereference null pointers for materials that involve IMC metadata. return ModelType switch { - ModelType.Human when SlotIndex is < 10 or 16 && mtrlFileName[8] != (byte)'b' + ModelType.Human when IsEquipmentOrAccessorySlot(SlotIndex) && mtrlFileName[8] != (byte)'b' => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imc, mtrlFileName), diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 6663fb40..f1507294 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -9,6 +9,7 @@ using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; using CustomizeIndex = Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex; +using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; namespace Penumbra.Interop.ResourceTree; @@ -44,8 +45,8 @@ public class ResourceTree PlayerRelated = playerRelated; CollectionName = collectionName; AnonymizedCollectionName = anonymizedCollectionName; - Nodes = new List(); - FlatNodes = new HashSet(); + Nodes = []; + FlatNodes = []; } public void ProcessPostfix(Action action) @@ -59,13 +60,13 @@ public class ResourceTree var character = (Character*)GameObjectAddress; var model = (CharacterBase*)DrawObjectAddress; var modelType = model->GetModelType(); - var human = modelType == CharacterBase.ModelType.Human ? (Human*)model : null; + var human = modelType == ModelType.Human ? (Human*)model : null; var equipment = modelType switch { - CharacterBase.ModelType.Human => new ReadOnlySpan(&human->Head, 10), - CharacterBase.ModelType.DemiHuman => new ReadOnlySpan( + ModelType.Human => new ReadOnlySpan(&human->Head, 12), + ModelType.DemiHuman => new ReadOnlySpan( Unsafe.AsPointer(ref character->DrawData.EquipmentModelIds[0]), 10), - _ => ReadOnlySpan.Empty, + _ => [], }; ModelId = character->CharacterData.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; @@ -75,9 +76,18 @@ public class ResourceTree for (var i = 0u; i < model->SlotCount; ++i) { - var slotContext = i < equipment.Length - ? globalContext.CreateContext(model, i, i.ToEquipSlot(), equipment[(int)i]) - : globalContext.CreateContext(model, i); + var slotContext = modelType switch + { + ModelType.Human => i switch + { + < 10 => globalContext.CreateContext(model, i, i.ToEquipSlot(), equipment[(int)i]), + 16 or 17 => globalContext.CreateContext(model, i, EquipSlot.Head, equipment[(int)(i - 6)]), + _ => globalContext.CreateContext(model, i), + }, + _ => i < equipment.Length + ? globalContext.CreateContext(model, i, i.ToEquipSlot(), equipment[(int)i]) + : globalContext.CreateContext(model, i), + }; var imc = (ResourceHandle*)model->IMCArray[i]; var imcNode = slotContext.CreateNodeFromImc(imc); @@ -117,7 +127,7 @@ public class ResourceTree var subObject = (CharacterBase*)baseSubObject; - if (subObject->GetModelType() != CharacterBase.ModelType.Weapon) + if (subObject->GetModelType() != ModelType.Weapon) continue; var weapon = (Weapon*)subObject; From da3f3b8df39c24a84b92d34ee730e7ffc74abe84 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 3 Aug 2024 22:45:38 +0200 Subject: [PATCH 0835/1381] Start rework of identified objects. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/Api/CollectionApi.cs | 2 +- Penumbra/Api/Api/ModsApi.cs | 2 +- Penumbra/Api/Api/UiApi.cs | 10 +- .../Api/IpcTester/CollectionsIpcTester.cs | 16 +- Penumbra/Collections/Cache/CollectionCache.cs | 25 +- .../Collections/ModCollection.Cache.Access.cs | 6 +- Penumbra/Communication/ChangedItemClick.cs | 3 +- Penumbra/Communication/ChangedItemHover.cs | 3 +- Penumbra/EphemeralConfig.cs | 36 +- .../Interop/ResourceTree/ResolveContext.cs | 12 +- Penumbra/Interop/ResourceTree/ResourceNode.cs | 12 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 6 +- .../ResourceTree/ResourceTreeApiHelper.cs | 4 +- Penumbra/Meta/Manipulations/Eqdp.cs | 2 +- Penumbra/Meta/Manipulations/Eqp.cs | 2 +- Penumbra/Meta/Manipulations/Est.cs | 2 +- .../Manipulations/GlobalEqpManipulation.cs | 2 +- Penumbra/Meta/Manipulations/Gmp.cs | 2 +- .../Meta/Manipulations/IMetaIdentifier.cs | 2 +- Penumbra/Meta/Manipulations/Imc.cs | 4 +- Penumbra/Meta/Manipulations/Rsp.cs | 3 +- Penumbra/Mods/Groups/IModGroup.cs | 2 +- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 2 +- Penumbra/Mods/Groups/SingleModGroup.cs | 2 +- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 5 +- Penumbra/Mods/Mod.cs | 3 +- Penumbra/Penumbra.cs | 9 +- Penumbra/Services/ConfigMigrationService.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 20 +- Penumbra/UI/ChangedItemDrawer.cs | 354 +++++------------- Penumbra/UI/ChangedItemIconFlag.cs | 122 ++++++ Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 2 +- .../UI/ModsTab/ModPanelChangedItemsTab.cs | 11 +- .../UI/ModsTab/ModSearchStringSplitter.cs | 12 +- Penumbra/UI/Tabs/ChangedItemsTab.cs | 9 +- Penumbra/UI/Tabs/SettingsTab.cs | 2 +- Penumbra/Util/IdentifierExtensions.cs | 10 +- 41 files changed, 342 insertions(+), 389 deletions(-) create mode 100644 Penumbra/UI/ChangedItemIconFlag.cs diff --git a/Penumbra.Api b/Penumbra.Api index 86249598..759a8e9d 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 86249598afb71601b247f9629d9c29dbecfe6eb1 +Subproject commit 759a8e9dc50b3453cdb7c3cba76de7174c94aba0 diff --git a/Penumbra.GameData b/Penumbra.GameData index 75582ece..44427ad0 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 75582ece58e6ee311074ff4ecaa68b804677878c +Subproject commit 44427ad0149059ab5ccb4e4a2f42a1a43423e4c5 diff --git a/Penumbra/Api/Api/CollectionApi.cs b/Penumbra/Api/Api/CollectionApi.cs index ff393aaf..04299187 100644 --- a/Penumbra/Api/Api/CollectionApi.cs +++ b/Penumbra/Api/Api/CollectionApi.cs @@ -36,7 +36,7 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : collection = ModCollection.Empty; if (collection.HasCache) - return collection.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Item2); + return collection.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Item2?.ToInternalObject()); Penumbra.Log.Warning($"Collection {collectionId} does not exist or is not loaded."); return []; diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 60b00d37..790121d5 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -134,6 +134,6 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable public Dictionary GetChangedItems(string modDirectory, string modName) => _modManager.TryGetMod(modDirectory, modName, out var mod) - ? mod.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + ? mod.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value?.ToInternalObject()) : []; } diff --git a/Penumbra/Api/Api/UiApi.cs b/Penumbra/Api/Api/UiApi.cs index cf3cd8f2..515874c0 100644 --- a/Penumbra/Api/Api/UiApi.cs +++ b/Penumbra/Api/Api/UiApi.cs @@ -1,7 +1,7 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Communication; -using Penumbra.GameData.Enums; +using Penumbra.GameData.Data; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; @@ -81,21 +81,21 @@ public class UiApi : IPenumbraApiUi, IApiService, IDisposable public void CloseMainWindow() => _configWindow.IsOpen = false; - private void OnChangedItemClick(MouseButton button, object? data) + private void OnChangedItemClick(MouseButton button, IIdentifiedObjectData? data) { if (ChangedItemClicked == null) return; - var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(data); + var (type, id) = data?.ToApiObject() ?? (ChangedItemType.None, 0); ChangedItemClicked.Invoke(button, type, id); } - private void OnChangedItemHover(object? data) + private void OnChangedItemHover(IIdentifiedObjectData? data) { if (ChangedItemTooltip == null) return; - var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(data); + var (type, id) = data?.ToApiObject() ?? (ChangedItemType.None, 0); ChangedItemTooltip.Invoke(type, id); } } diff --git a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs index 026fabbc..1d516eba 100644 --- a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs +++ b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs @@ -8,7 +8,7 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Api.IpcSubscribers; using Penumbra.Collections.Manager; -using Penumbra.GameData.Enums; +using Penumbra.GameData.Data; using ImGuiClip = OtterGui.ImGuiClip; namespace Penumbra.Api.IpcTester; @@ -17,10 +17,10 @@ public class CollectionsIpcTester(IDalamudPluginInterface pi) : IUiService { private int _objectIdx; private string _collectionIdString = string.Empty; - private Guid? _collectionId = null; - private bool _allowCreation = true; - private bool _allowDeletion = true; - private ApiCollectionType _type = ApiCollectionType.Yourself; + private Guid? _collectionId; + private bool _allowCreation = true; + private bool _allowDeletion = true; + private ApiCollectionType _type = ApiCollectionType.Yourself; private Dictionary _collections = []; private (string, ChangedItemType, uint)[] _changedItems = []; @@ -116,7 +116,7 @@ public class CollectionsIpcTester(IDalamudPluginInterface pi) : IUiService var items = new GetChangedItemsForCollection(pi).Invoke(_collectionId.GetValueOrDefault(Guid.Empty)); _changedItems = items.Select(kvp => { - var (type, id) = ChangedItemExtensions.ChangedItemToTypeAndId(kvp.Value); + var (type, id) = kvp.Value.ToApiObject(); return (kvp.Key, type, id); }).ToArray(); ImGui.OpenPopup("Changed Item List"); @@ -130,9 +130,9 @@ public class CollectionsIpcTester(IDalamudPluginInterface pi) : IUiService if (!p) return; - using (var t = ImRaii.Table("##ChangedItems", 3, ImGuiTableFlags.SizingFixedFit)) + using (var table = ImRaii.Table("##ChangedItems", 3, ImGuiTableFlags.SizingFixedFit)) { - if (t) + if (table) ImGuiClip.ClippedDraw(_changedItems, t => { ImGuiUtil.DrawTableColumn(t.Item1); diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 4755840e..abc0dff8 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -6,6 +6,7 @@ using Penumbra.Communication; using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Util; +using Penumbra.GameData.Data; namespace Penumbra.Collections.Cache; @@ -18,14 +19,14 @@ public record ModConflicts(IMod Mod2, List Conflicts, bool HasPriority, /// public sealed class CollectionCache : IDisposable { - private readonly CollectionCacheManager _manager; - private readonly ModCollection _collection; - public readonly CollectionModData ModData = new(); - private readonly SortedList, object?)> _changedItems = []; - public readonly ConcurrentDictionary ResolvedFiles = new(); - public readonly CustomResourceCache CustomResources; - public readonly MetaCache Meta; - public readonly Dictionary> ConflictDict = []; + private readonly CollectionCacheManager _manager; + private readonly ModCollection _collection; + public readonly CollectionModData ModData = new(); + private readonly SortedList, IIdentifiedObjectData?)> _changedItems = []; + public readonly ConcurrentDictionary ResolvedFiles = new(); + public readonly CustomResourceCache CustomResources; + public readonly MetaCache Meta; + public readonly Dictionary> ConflictDict = []; public int Calculating = -1; @@ -41,7 +42,7 @@ public sealed class CollectionCache : IDisposable private int _changedItemsSaveCounter = -1; // Obtain currently changed items. Computes them if they haven't been computed before. - public IReadOnlyDictionary, object?)> ChangedItems + public IReadOnlyDictionary, IIdentifiedObjectData?)> ChangedItems { get { @@ -412,7 +413,7 @@ public sealed class CollectionCache : IDisposable // Skip IMCs because they would result in far too many false-positive items, // since they are per set instead of per item-slot/item/variant. var identifier = _manager.MetaFileManager.Identifier; - var items = new SortedList(512); + var items = new SortedList(512); void AddItems(IMod mod) { @@ -421,8 +422,8 @@ public sealed class CollectionCache : IDisposable if (!_changedItems.TryGetValue(name, out var data)) _changedItems.Add(name, (new SingleArray(mod), obj)); else if (!data.Item1.Contains(mod)) - _changedItems[name] = (data.Item1.Append(mod), obj is int x && data.Item2 is int y ? x + y : obj); - else if (obj is int x && data.Item2 is int y) + _changedItems[name] = (data.Item1.Append(mod), obj is IdentifiedCounter x && data.Item2 is IdentifiedCounter y ? x + y : obj); + else if (obj is IdentifiedCounter x && data.Item2 is IdentifiedCounter y) _changedItems[name] = (data.Item1, x + y); } diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 983509a4..0b38dde8 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -1,8 +1,8 @@ using OtterGui.Classes; using Penumbra.Mods; -using Penumbra.Meta.Files; using Penumbra.String.Classes; using Penumbra.Collections.Cache; +using Penumbra.GameData.Data; using Penumbra.Mods.Editor; namespace Penumbra.Collections; @@ -46,8 +46,8 @@ public partial class ModCollection internal IReadOnlyDictionary ResolvedFiles => _cache?.ResolvedFiles ?? new ConcurrentDictionary(); - internal IReadOnlyDictionary, object?)> ChangedItems - => _cache?.ChangedItems ?? new Dictionary, object?)>(); + internal IReadOnlyDictionary, IIdentifiedObjectData?)> ChangedItems + => _cache?.ChangedItems ?? new Dictionary, IIdentifiedObjectData?)>(); internal IEnumerable> AllConflicts => _cache?.AllConflicts ?? Array.Empty>(); diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index 554e2221..1aac4454 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; using Penumbra.Api.Api; using Penumbra.Api.Enums; +using Penumbra.GameData.Data; namespace Penumbra.Communication; @@ -11,7 +12,7 @@ namespace Penumbra.Communication; /// Parameter is the clicked object data if any. /// /// -public sealed class ChangedItemClick() : EventWrapper(nameof(ChangedItemClick)) +public sealed class ChangedItemClick() : EventWrapper(nameof(ChangedItemClick)) { public enum Priority { diff --git a/Penumbra/Communication/ChangedItemHover.cs b/Penumbra/Communication/ChangedItemHover.cs index 2dcced35..4e72b558 100644 --- a/Penumbra/Communication/ChangedItemHover.cs +++ b/Penumbra/Communication/ChangedItemHover.cs @@ -1,5 +1,6 @@ using OtterGui.Classes; using Penumbra.Api.Api; +using Penumbra.GameData.Data; namespace Penumbra.Communication; @@ -9,7 +10,7 @@ namespace Penumbra.Communication; /// Parameter is the hovered object data if any. /// /// -public sealed class ChangedItemHover() : EventWrapper(nameof(ChangedItemHover)) +public sealed class ChangedItemHover() : EventWrapper(nameof(ChangedItemHover)) { public enum Priority { diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 7457c910..24ab466b 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -23,24 +23,24 @@ public class EphemeralConfig : ISavable, IDisposable, IService [JsonIgnore] private readonly ModPathChanged _modPathChanged; - public int Version { get; set; } = Configuration.Constants.CurrentVersion; - public int LastSeenVersion { get; set; } = PenumbraChangelog.LastChangelogVersion; - public bool DebugSeparateWindow { get; set; } = false; - public int TutorialStep { get; set; } = 0; - public bool EnableResourceLogging { get; set; } = false; - public string ResourceLoggingFilter { get; set; } = string.Empty; - public bool EnableResourceWatcher { get; set; } = false; - public bool OnlyAddMatchingResources { get; set; } = true; - public ResourceTypeFlag ResourceWatcherResourceTypes { get; set; } = ResourceExtensions.AllResourceTypes; - public ResourceCategoryFlag ResourceWatcherResourceCategories { get; set; } = ResourceExtensions.AllResourceCategories; - public RecordType ResourceWatcherRecordTypes { get; set; } = ResourceWatcher.AllRecords; - public CollectionsTab.PanelMode CollectionPanel { get; set; } = CollectionsTab.PanelMode.SimpleAssignment; - public TabType SelectedTab { get; set; } = TabType.Settings; - public ChangedItemDrawer.ChangedItemIcon ChangedItemFilter { get; set; } = ChangedItemDrawer.DefaultFlags; - public bool FixMainWindow { get; set; } = false; - public string LastModPath { get; set; } = string.Empty; - public bool AdvancedEditingOpen { get; set; } = false; - public bool ForceRedrawOnFileChange { get; set; } = false; + public int Version { get; set; } = Configuration.Constants.CurrentVersion; + public int LastSeenVersion { get; set; } = PenumbraChangelog.LastChangelogVersion; + public bool DebugSeparateWindow { get; set; } = false; + public int TutorialStep { get; set; } = 0; + public bool EnableResourceLogging { get; set; } = false; + public string ResourceLoggingFilter { get; set; } = string.Empty; + public bool EnableResourceWatcher { get; set; } = false; + public bool OnlyAddMatchingResources { get; set; } = true; + public ResourceTypeFlag ResourceWatcherResourceTypes { get; set; } = ResourceExtensions.AllResourceTypes; + public ResourceCategoryFlag ResourceWatcherResourceCategories { get; set; } = ResourceExtensions.AllResourceCategories; + public RecordType ResourceWatcherRecordTypes { get; set; } = ResourceWatcher.AllRecords; + public CollectionsTab.PanelMode CollectionPanel { get; set; } = CollectionsTab.PanelMode.SimpleAssignment; + public TabType SelectedTab { get; set; } = TabType.Settings; + public ChangedItemIconFlag ChangedItemFilter { get; set; } = ChangedItemFlagExtensions.DefaultFlags; + public bool FixMainWindow { get; set; } = false; + public string LastModPath { get; set; } = string.Empty; + public bool AdvancedEditingOpen { get; set; } = false; + public bool ForceRedrawOnFileChange { get; set; } = false; /// /// Load the current configuration. diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 3fc1ae3c..9d0f1e46 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -345,7 +345,7 @@ internal unsafe partial record ResolveContext( _ => string.Empty, } + item.Name; - return new ResourceNode.UiData(name, ChangedItemDrawer.GetCategoryIcon(item.Name, item)); + return new ResourceNode.UiData(name, item.Type.GetCategoryIcon().ToFlag()); } var dataFromPath = GuessUiDataFromPath(gamePath); @@ -353,8 +353,8 @@ internal unsafe partial record ResolveContext( return dataFromPath; return isEquipment - ? new ResourceNode.UiData(Slot.ToName(), ChangedItemDrawer.GetCategoryIcon(Slot.ToSlot())) - : new ResourceNode.UiData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); + ? new ResourceNode.UiData(Slot.ToName(), Slot.ToEquipType().GetCategoryIcon().ToFlag()) + : new ResourceNode.UiData(null, ChangedItemIconFlag.Unknown); } internal ResourceNode.UiData GuessUiDataFromPath(Utf8GamePath gamePath) @@ -362,13 +362,13 @@ internal unsafe partial record ResolveContext( foreach (var obj in Global.Identifier.Identify(gamePath.ToString())) { var name = obj.Key; - if (name.StartsWith("Customization:")) + if (obj.Value is IdentifiedCustomization) name = name[14..].Trim(); if (name != "Unknown") - return new ResourceNode.UiData(name, ChangedItemDrawer.GetCategoryIcon(obj.Key, obj.Value)); + return new ResourceNode.UiData(name, obj.Value.GetIcon().ToFlag()); } - return new ResourceNode.UiData(null, ChangedItemDrawer.ChangedItemIcon.Unknown); + return new ResourceNode.UiData(null, ChangedItemIconFlag.Unknown); } private static string? SafeGet(ReadOnlySpan array, Index index) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index de43a874..6ab48325 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -1,7 +1,7 @@ using Penumbra.Api.Enums; using Penumbra.String; using Penumbra.String.Classes; -using ChangedItemIcon = Penumbra.UI.ChangedItemDrawer.ChangedItemIcon; +using Penumbra.UI; namespace Penumbra.Interop.ResourceTree; @@ -9,7 +9,7 @@ public class ResourceNode : ICloneable { public string? Name; public string? FallbackName; - public ChangedItemIcon Icon; + public ChangedItemIconFlag IconFlag; public readonly ResourceType Type; public readonly nint ObjectAddress; public readonly nint ResourceHandle; @@ -51,7 +51,7 @@ public class ResourceNode : ICloneable { Name = other.Name; FallbackName = other.FallbackName; - Icon = other.Icon; + IconFlag = other.IconFlag; Type = other.Type; ObjectAddress = other.ObjectAddress; ResourceHandle = other.ResourceHandle; @@ -79,7 +79,7 @@ public class ResourceNode : ICloneable public void SetUiData(UiData uiData) { Name = uiData.Name; - Icon = uiData.Icon; + IconFlag = uiData.IconFlag; } public void PrependName(string prefix) @@ -88,9 +88,9 @@ public class ResourceNode : ICloneable Name = prefix + Name; } - public readonly record struct UiData(string? Name, ChangedItemIcon Icon) + public readonly record struct UiData(string? Name, ChangedItemIconFlag IconFlag) { public UiData PrependName(string prefix) - => Name == null ? this : new UiData(prefix + Name, Icon); + => Name == null ? this : new UiData(prefix + Name, IconFlag); } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 6663fb40..dc83fa65 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -174,7 +174,7 @@ public class ResourceTree { pbdNode = pbdNode.Clone(); pbdNode.FallbackName = "Racial Deformer"; - pbdNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + pbdNode.IconFlag = ChangedItemIconFlag.Customization; } Nodes.Add(pbdNode); @@ -192,7 +192,7 @@ public class ResourceTree { decalNode = decalNode.Clone(); decalNode.FallbackName = "Face Decal"; - decalNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + decalNode.IconFlag = ChangedItemIconFlag.Customization; } Nodes.Add(decalNode); @@ -209,7 +209,7 @@ public class ResourceTree { legacyDecalNode = legacyDecalNode.Clone(); legacyDecalNode.FallbackName = "Legacy Body Decal"; - legacyDecalNode.Icon = ChangedItemDrawer.ChangedItemIcon.Customization; + legacyDecalNode.IconFlag = ChangedItemIconFlag.Customization; } Nodes.Add(legacyDecalNode); diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs index 22025dd6..48690e98 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeApiHelper.cs @@ -67,7 +67,7 @@ internal static class ResourceTreeApiHelper continue; var fullPath = node.FullPath.ToPath(); - resDictionary.Add(node.ResourceHandle, (fullPath, node.Name ?? string.Empty, (uint)ChangedItemDrawer.ToApiIcon(node.Icon))); + resDictionary.Add(node.ResourceHandle, (fullPath, node.Name ?? string.Empty, (uint)node.IconFlag.ToApiIcon())); } } @@ -106,7 +106,7 @@ internal static class ResourceTreeApiHelper var ret = new JObject { [nameof(ResourceNodeDto.Type)] = new JValue(node.Type), - [nameof(ResourceNodeDto.Icon)] = new JValue(ChangedItemDrawer.ToApiIcon(node.Icon)), + [nameof(ResourceNodeDto.Icon)] = new JValue(node.IconFlag.ToApiIcon()), [nameof(ResourceNodeDto.Name)] = node.Name, [nameof(ResourceNodeDto.GamePath)] = node.GamePath.Equals(Utf8GamePath.Empty) ? null : node.GamePath.ToString(), [nameof(ResourceNodeDto.ActualPath)] = node.FullPath.ToString(), diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs index 3f856bd2..3a804d0c 100644 --- a/Penumbra/Meta/Manipulations/Eqdp.cs +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -15,7 +15,7 @@ public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, Ge public Gender Gender => GenderRace.Split().Item1; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, Slot)); public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/Eqp.cs b/Penumbra/Meta/Manipulations/Eqp.cs index 5d37aac8..f758126c 100644 --- a/Penumbra/Meta/Manipulations/Eqp.cs +++ b/Penumbra/Meta/Manipulations/Eqp.cs @@ -8,7 +8,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct EqpIdentifier(PrimaryId SetId, EquipSlot Slot) : IMetaIdentifier, IComparable { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace.MidlanderMale, Slot)); public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs index 2955dba4..cfe9b7d4 100644 --- a/Penumbra/Meta/Manipulations/Est.cs +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -24,7 +24,7 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende public Gender Gender => GenderRace.Split().Item1; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { switch (Slot) { diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs index 2b88d962..ec59762b 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -70,7 +70,7 @@ public readonly struct GlobalEqpManipulation : IMetaIdentifier public override string ToString() => $"Global EQP - {Type}{(Condition != 0 ? $" - {Condition.Id}" : string.Empty)}"; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { var path = Type switch { diff --git a/Penumbra/Meta/Manipulations/Gmp.cs b/Penumbra/Meta/Manipulations/Gmp.cs index a6fcf58b..1f41adfb 100644 --- a/Penumbra/Meta/Manipulations/Gmp.cs +++ b/Penumbra/Meta/Manipulations/Gmp.cs @@ -8,7 +8,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct GmpIdentifier(PrimaryId SetId) : IMetaIdentifier, IComparable { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace.MidlanderMale, EquipSlot.Head)); public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs index 5707ffca..d1668a4d 100644 --- a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -18,7 +18,7 @@ public enum MetaManipulationType : byte public interface IMetaIdentifier { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); public MetaIndex FileIndex(); diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index d4887fe2..1b2492ee 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -27,10 +27,10 @@ public readonly record struct ImcIdentifier( : this(primaryId, variant, slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, BodySlot.Unknown) { } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => AddChangedItems(identifier, changedItems, false); - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems, bool allVariants) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems, bool allVariants) { var path = ObjectType switch { diff --git a/Penumbra/Meta/Manipulations/Rsp.cs b/Penumbra/Meta/Manipulations/Rsp.cs index 73d1d7e5..2d73ec7f 100644 --- a/Penumbra/Meta/Manipulations/Rsp.cs +++ b/Penumbra/Meta/Manipulations/Rsp.cs @@ -1,4 +1,3 @@ -using Lumina.Excel.GeneratedSheets; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.GameData.Data; @@ -9,7 +8,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct RspIdentifier(SubRace SubRace, RspAttribute Attribute) : IMetaIdentifier { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => changedItems.TryAdd($"{SubRace.ToName()} {Attribute.ToFullString()}", null); public MetaIndex FileIndex() diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index 9327ced9..c5654019 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -45,7 +45,7 @@ public interface IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer); public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations); - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); /// Ensure that a value is valid for a group. public Setting FixSetting(Setting setting); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 7b0eb094..d42804ba 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -121,7 +121,7 @@ public class ImcModGroup(Mod mod) : IModGroup } } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => Identifier.AddChangedItems(identifier, changedItems, AllVariants); public Setting FixSetting(Setting setting) diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index ee27d534..9cf7e6a3 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -126,7 +126,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup } } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { foreach (var container in DataContainers) identifier.AddChangedItems(container, changedItems); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index cc606f42..723cd5b1 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -111,7 +111,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { foreach (var container in DataContainers) identifier.AddChangedItems(container, changedItems); diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 2c292a14..1a2f2798 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -186,7 +186,7 @@ public static class EquipmentSwap PrimaryId idTo, byte mtrlTo) { var eqdpFromIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); - var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); + var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); var meta = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, eqdpFromIdentifier, @@ -255,7 +255,8 @@ public static class EquipmentSwap { items = identifier.Identify(slotFrom.IsEquipment() ? GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom) - : GamePaths.Accessory.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom)).Select(kvp => kvp.Value).OfType() + : GamePaths.Accessory.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom)) + .Select(kvp => kvp.Value).OfType().Select(i => i.Item) .ToArray(); variants = Enumerable.Range(0, imc.Count + 1).Select(i => (Variant)i).ToArray(); } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 16f06de2..488e3dc1 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,5 +1,6 @@ using OtterGui; using OtterGui.Classes; +using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; @@ -100,7 +101,7 @@ public sealed class Mod : IMod } // Cache - public readonly SortedList ChangedItems = new(); + public readonly SortedList ChangedItems = new(); public string LowerChangedItemsString { get; internal set; } = string.Empty; public string AllTagsLower { get; internal set; } = string.Empty; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 8ea74987..dbe06803 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -21,6 +21,8 @@ using Penumbra.GameData.Enums; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using System.Xml.Linq; +using Dalamud.Plugin.Services; +using Penumbra.GameData.Data; using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.ResourceLoading; @@ -109,16 +111,17 @@ public class Penumbra : IDalamudPlugin private void SetupApi() { _services.GetService(); + var itemSheet = _services.GetService().GetExcelSheet()!; _communicatorService.ChangedItemHover.Subscribe(it => { - if (it is (Item, FullEquipType)) + if (it is IdentifiedItem) ImGui.TextUnformatted("Left Click to create an item link in chat."); }, ChangedItemHover.Priority.Link); _communicatorService.ChangedItemClick.Subscribe((button, it) => { - if (button == MouseButton.Left && it is (Item item, FullEquipType type)) - Messager.LinkItem(item); + if (button == MouseButton.Left && it is IdentifiedItem item && itemSheet.GetRow(item.Item.ItemId.Id) is { } i) + Messager.LinkItem(i); }, ChangedItemClick.Priority.Link); } diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index 70b05a73..5ba57cf4 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -115,7 +115,7 @@ public class ConfigMigrationService(SaveService saveService, BackupService backu _data["ResourceWatcherRecordTypes"]?.ToObject() ?? _config.Ephemeral.ResourceWatcherRecordTypes; _config.Ephemeral.CollectionPanel = _data["CollectionPanel"]?.ToObject() ?? _config.Ephemeral.CollectionPanel; _config.Ephemeral.SelectedTab = _data["SelectedTab"]?.ToObject() ?? _config.Ephemeral.SelectedTab; - _config.Ephemeral.ChangedItemFilter = _data["ChangedItemFilter"]?.ToObject() + _config.Ephemeral.ChangedItemFilter = _data["ChangedItemFilter"]?.ToObject() ?? _config.Ephemeral.ChangedItemFilter; _config.Ephemeral.FixMainWindow = _data["FixMainWindow"]?.ToObject() ?? _config.Ephemeral.FixMainWindow; _config.Ephemeral.Save(); diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index da2daeb7..b75c5aef 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -135,7 +135,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService : FilterComboCache<(EquipItem Item, bool InMod)>(() => { var list = data.ByType[type]; - if (selector?.Selected is { } mod && mod.ChangedItems.Values.Any(o => o is EquipItem i && i.Type == type)) + if (selector?.Selected is { } mod && mod.ChangedItems.Values.Any(o => o is IdentifiedItem i && i.Item.Type == type)) return list.Select(i => (i, mod.ChangedItems.ContainsKey(i.Name))).OrderByDescending(p => p.Item2).ToList(); return list.Select(i => (i, false)).ToList(); diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index c47414b9..9834d9f0 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -27,7 +27,7 @@ public class ResourceTreeViewer private readonly Dictionary _filterCache; private TreeCategory _categoryFilter; - private ChangedItemDrawer.ChangedItemIcon _typeFilter; + private ChangedItemIconFlag _typeFilter; private string _nameFilter; private string _nodeFilter; @@ -48,7 +48,7 @@ public class ResourceTreeViewer _filterCache = []; _categoryFilter = AllCategories; - _typeFilter = ChangedItemDrawer.AllFlags; + _typeFilter = ChangedItemFlagExtensions.AllFlags; _nameFilter = string.Empty; _nodeFilter = string.Empty; } @@ -185,13 +185,13 @@ public class ResourceTreeViewer }); private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash, - ChangedItemDrawer.ChangedItemIcon parentFilterIcon) + ChangedItemIconFlag parentFilterIconFlag) { var debugMode = _config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); var cellHeight = _actionCapacity > 0 ? frameHeight : 0.0f; - bool MatchesFilter(ResourceNode node, ChangedItemDrawer.ChangedItemIcon filterIcon) + bool MatchesFilter(ResourceNode node, ChangedItemIconFlag filterIcon) { if (!_typeFilter.HasFlag(filterIcon)) return false; @@ -205,12 +205,12 @@ public class ResourceTreeViewer || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); } - NodeVisibility CalculateNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) + NodeVisibility CalculateNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemIconFlag parentFilterIcon) { if (node.Internal && !debugMode) return NodeVisibility.Hidden; - var filterIcon = node.Icon != 0 ? node.Icon : parentFilterIcon; + var filterIcon = node.IconFlag != 0 ? node.IconFlag : parentFilterIcon; if (MatchesFilter(node, filterIcon)) return NodeVisibility.Visible; @@ -223,7 +223,7 @@ public class ResourceTreeViewer return NodeVisibility.Hidden; } - NodeVisibility GetNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemDrawer.ChangedItemIcon parentFilterIcon) + NodeVisibility GetNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemIconFlag parentFilterIcon) { if (!_filterCache.TryGetValue(nodePathHash, out var visibility)) { @@ -241,7 +241,7 @@ public class ResourceTreeViewer { var nodePathHash = unchecked(pathHash + resourceNode.ResourceHandle); - var visibility = GetNodeVisibility(nodePathHash, resourceNode, parentFilterIcon); + var visibility = GetNodeVisibility(nodePathHash, resourceNode, parentFilterIconFlag); if (visibility == NodeVisibility.Hidden) continue; @@ -250,7 +250,7 @@ public class ResourceTreeViewer using var mutedColor = ImRaii.PushColor(ImGuiCol.Text, textColorInternal, resourceNode.Internal); - var filterIcon = resourceNode.Icon != 0 ? resourceNode.Icon : parentFilterIcon; + var filterIcon = resourceNode.IconFlag != 0 ? resourceNode.IconFlag : parentFilterIconFlag; using var id = ImRaii.PushId(index); ImGui.TableNextColumn(); @@ -281,7 +281,7 @@ public class ResourceTreeViewer ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); } - _changedItemDrawer.DrawCategoryIcon(resourceNode.Icon); + _changedItemDrawer.DrawCategoryIcon(resourceNode.IconFlag); ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); ImGui.TableHeader(resourceNode.Name); if (ImGui.IsItemClicked() && unfoldable) diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index 72bfa266..af9782d5 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -3,72 +3,24 @@ using Dalamud.Interface.Textures; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Services; using Dalamud.Utility; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using ImGuiNET; using Lumina.Data.Files; -using Lumina.Excel; -using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Api.Enums; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Structs; +using Penumbra.GameData.Data; using Penumbra.Services; using Penumbra.UI.Classes; -using ApiChangedItemIcon = Penumbra.Api.Enums.ChangedItemIcon; namespace Penumbra.UI; public class ChangedItemDrawer : IDisposable, IUiService { - [Flags] - public enum ChangedItemIcon : uint - { - Head = 0x00_00_01, - Body = 0x00_00_02, - Hands = 0x00_00_04, - Legs = 0x00_00_08, - Feet = 0x00_00_10, - Ears = 0x00_00_20, - Neck = 0x00_00_40, - Wrists = 0x00_00_80, - Finger = 0x00_01_00, - Monster = 0x00_02_00, - Demihuman = 0x00_04_00, - Customization = 0x00_08_00, - Action = 0x00_10_00, - Mainhand = 0x00_20_00, - Offhand = 0x00_40_00, - Unknown = 0x00_80_00, - Emote = 0x01_00_00, - } + private static readonly string[] LowerNames = ChangedItemFlagExtensions.Order.Select(f => f.ToDescription().ToLowerInvariant()).ToArray(); - private static readonly ChangedItemIcon[] Order = - [ - ChangedItemIcon.Head, - ChangedItemIcon.Body, - ChangedItemIcon.Hands, - ChangedItemIcon.Legs, - ChangedItemIcon.Feet, - ChangedItemIcon.Ears, - ChangedItemIcon.Neck, - ChangedItemIcon.Wrists, - ChangedItemIcon.Finger, - ChangedItemIcon.Mainhand, - ChangedItemIcon.Offhand, - ChangedItemIcon.Customization, - ChangedItemIcon.Action, - ChangedItemIcon.Emote, - ChangedItemIcon.Monster, - ChangedItemIcon.Demihuman, - ChangedItemIcon.Unknown, - ]; - - private static readonly string[] LowerNames = Order.Select(f => ToDescription(f).ToLowerInvariant()).ToArray(); - - public static bool TryParseIndex(ReadOnlySpan input, out ChangedItemIcon slot) + public static bool TryParseIndex(ReadOnlySpan input, out ChangedItemIconFlag slot) { // Handle numeric cases before TryParse because numbers // are not logical otherwise. @@ -77,15 +29,15 @@ public class ChangedItemDrawer : IDisposable, IUiService // We assume users will use 1-based index, but if they enter 0, just use the first. if (idx == 0) { - slot = Order[0]; + slot = ChangedItemFlagExtensions.Order[0]; return true; } // Use 1-based index. --idx; - if (idx >= 0 && idx < Order.Length) + if (idx >= 0 && idx < ChangedItemFlagExtensions.Order.Count) { - slot = Order[idx]; + slot = ChangedItemFlagExtensions.Order[idx]; return true; } } @@ -94,13 +46,13 @@ public class ChangedItemDrawer : IDisposable, IUiService return false; } - public static bool TryParsePartial(string lowerInput, out ChangedItemIcon slot) + public static bool TryParsePartial(string lowerInput, out ChangedItemIconFlag slot) { if (TryParseIndex(lowerInput, out slot)) return true; slot = 0; - foreach (var (item, flag) in LowerNames.Zip(Order)) + foreach (var (item, flag) in LowerNames.Zip(ChangedItemFlagExtensions.Order)) { if (item.Contains(lowerInput, StringComparison.Ordinal)) slot |= flag; @@ -109,15 +61,11 @@ public class ChangedItemDrawer : IDisposable, IUiService return slot != 0; } - public const ChangedItemIcon AllFlags = (ChangedItemIcon)0x01FFFF; - public static readonly int NumCategories = Order.Length; - public const ChangedItemIcon DefaultFlags = AllFlags & ~ChangedItemIcon.Offhand; - private readonly Configuration _config; - private readonly ExcelSheet _items; - private readonly CommunicatorService _communicator; - private readonly Dictionary _icons = new(16); - private float _smallestIconWidth; + private readonly Configuration _config; + private readonly CommunicatorService _communicator; + private readonly Dictionary _icons = new(16); + private float _smallestIconWidth; public static Vector2 TypeFilterIconSize => new(2 * ImGui.GetTextLineHeight()); @@ -125,7 +73,6 @@ public class ChangedItemDrawer : IDisposable, IUiService public ChangedItemDrawer(IUiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider, CommunicatorService communicator, Configuration config) { - _items = gameData.GetExcelSheet()!; uiBuilder.RunWhenUiPrepared(() => CreateEquipSlotIcons(uiBuilder, gameData, textureProvider), true); _communicator = communicator; _config = config; @@ -139,18 +86,19 @@ public class ChangedItemDrawer : IDisposable, IUiService } /// Check if a changed item should be drawn based on its category. - public bool FilterChangedItem(string name, object? data, LowerString filter) - => (_config.Ephemeral.ChangedItemFilter == AllFlags || _config.Ephemeral.ChangedItemFilter.HasFlag(GetCategoryIcon(name, data))) - && (filter.IsEmpty || filter.IsContained(ChangedItemFilterName(name, data))); + public bool FilterChangedItem(string name, IIdentifiedObjectData? data, LowerString filter) + => (_config.Ephemeral.ChangedItemFilter == ChangedItemFlagExtensions.AllFlags + || _config.Ephemeral.ChangedItemFilter.HasFlag(data.GetIcon().ToFlag())) + && (filter.IsEmpty || !data.IsFilteredOut(name, filter)); /// Draw the icon corresponding to the category of a changed item. - public void DrawCategoryIcon(string name, object? data) - => DrawCategoryIcon(GetCategoryIcon(name, data)); + public void DrawCategoryIcon(IIdentifiedObjectData? data) + => DrawCategoryIcon(data.GetIcon().ToFlag()); - public void DrawCategoryIcon(ChangedItemIcon iconType) + public void DrawCategoryIcon(ChangedItemIconFlag iconFlagType) { var height = ImGui.GetFrameHeight(); - if (!_icons.TryGetValue(iconType, out var icon)) + if (!_icons.TryGetValue(iconFlagType, out var icon)) { ImGui.Dummy(new Vector2(height)); return; @@ -162,18 +110,18 @@ public class ChangedItemDrawer : IDisposable, IUiService using var tt = ImRaii.Tooltip(); ImGui.Image(icon.ImGuiHandle, new Vector2(_smallestIconWidth)); ImGui.SameLine(); - ImGuiUtil.DrawTextButton(ToDescription(iconType), new Vector2(0, _smallestIconWidth), 0); + ImGuiUtil.DrawTextButton(iconFlagType.ToDescription(), new Vector2(0, _smallestIconWidth), 0); } } /// /// Draw a changed item, invoking the Api-Events for clicks and tooltips. - /// Also draw the item Id in grey if requested. + /// Also draw the item ID in grey if requested. /// - public void DrawChangedItem(string name, object? data) + public void DrawChangedItem(string name, IIdentifiedObjectData? data) { - name = ChangedItemName(name, data); - using (var style = ImRaii.PushStyle(ImGuiStyleVar.SelectableTextAlign, new Vector2(0, 0.5f)) + name = data?.ToName(name) ?? name; + using (ImRaii.PushStyle(ImGuiStyleVar.SelectableTextAlign, new Vector2(0, 0.5f)) .Push(ImGuiStyleVar.ItemSpacing, new Vector2(ImGui.GetStyle().ItemSpacing.X, ImGui.GetStyle().CellPadding.Y * 2))) { var ret = ImGui.Selectable(name, false, ImGuiSelectableFlags.None, new Vector2(0, ImGui.GetFrameHeight())) @@ -182,31 +130,34 @@ public class ChangedItemDrawer : IDisposable, IUiService ret = ImGui.IsItemClicked(ImGuiMouseButton.Right) ? MouseButton.Right : ret; ret = ImGui.IsItemClicked(ImGuiMouseButton.Middle) ? MouseButton.Middle : ret; if (ret != MouseButton.None) - _communicator.ChangedItemClick.Invoke(ret, Convert(data)); + _communicator.ChangedItemClick.Invoke(ret, data); } if (_communicator.ChangedItemHover.HasTooltip && ImGui.IsItemHovered()) { // We can not be sure that any subscriber actually prints something in any case. // Circumvent ugly blank tooltip with less-ugly useless tooltip. - using var tt = ImRaii.Tooltip(); - using var group = ImRaii.Group(); - _communicator.ChangedItemHover.Invoke(Convert(data)); - group.Dispose(); + using var tt = ImRaii.Tooltip(); + using (ImRaii.Group()) + { + _communicator.ChangedItemHover.Invoke(data); + } + if (ImGui.GetItemRectSize() == Vector2.Zero) ImGui.TextUnformatted("No actions available."); } } /// Draw the model information, right-justified. - public void DrawModelData(object? data) + public static void DrawModelData(IIdentifiedObjectData? data) { - if (!GetChangedItemObject(data, out var text)) + var additionalData = data?.AdditionalData ?? string.Empty; + if (additionalData.Length == 0) return; ImGui.SameLine(ImGui.GetContentRegionAvail().X); ImGui.AlignTextToFramePadding(); - ImGuiUtil.RightJustify(text, ColorId.ItemId.Value()); + ImGuiUtil.RightJustify(additionalData, ColorId.ItemId.Value()); } /// Draw a header line with the different icon types to filter them. @@ -224,7 +175,7 @@ public class ChangedItemDrawer : IDisposable, IUiService } /// Draw a header line with the different icon types to filter them. - public bool DrawTypeFilter(ref ChangedItemIcon typeFilter) + public bool DrawTypeFilter(ref ChangedItemIconFlag typeFilter) { var ret = false; using var _ = ImRaii.PushId("ChangedItemIconFilter"); @@ -232,16 +183,38 @@ public class ChangedItemDrawer : IDisposable, IUiService using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero); - bool DrawIcon(ChangedItemIcon type, ref ChangedItemIcon typeFilter) + foreach (var iconType in ChangedItemFlagExtensions.Order) { - var ret = false; - var icon = _icons[type]; - var flag = typeFilter.HasFlag(type); + ret |= DrawIcon(iconType, ref typeFilter); + ImGui.SameLine(); + } + + ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); + ImGui.Image(_icons[ChangedItemFlagExtensions.AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, + typeFilter switch + { + 0 => new Vector4(0.6f, 0.3f, 0.3f, 1f), + ChangedItemFlagExtensions.AllFlags => new Vector4(0.75f, 0.75f, 0.75f, 1f), + _ => new Vector4(0.5f, 0.5f, 1f, 1f), + }); + if (ImGui.IsItemClicked()) + { + typeFilter = typeFilter == ChangedItemFlagExtensions.AllFlags ? 0 : ChangedItemFlagExtensions.AllFlags; + ret = true; + } + + return ret; + + bool DrawIcon(ChangedItemIconFlag type, ref ChangedItemIconFlag typeFilter) + { + var localRet = false; + var icon = _icons[type]; + var flag = typeFilter.HasFlag(type); ImGui.Image(icon.ImGuiHandle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); if (ImGui.IsItemClicked(ImGuiMouseButton.Left)) { typeFilter = flag ? typeFilter & ~type : typeFilter | type; - ret = true; + localRet = true; } using var popup = ImRaii.ContextPopupItem(type.ToString()); @@ -249,7 +222,7 @@ public class ChangedItemDrawer : IDisposable, IUiService if (ImGui.MenuItem("Enable Only This")) { typeFilter = type; - ret = true; + localRet = true; ImGui.CloseCurrentPopup(); } @@ -258,165 +231,13 @@ public class ChangedItemDrawer : IDisposable, IUiService using var tt = ImRaii.Tooltip(); ImGui.Image(icon.ImGuiHandle, new Vector2(_smallestIconWidth)); ImGui.SameLine(); - ImGuiUtil.DrawTextButton(ToDescription(type), new Vector2(0, _smallestIconWidth), 0); + ImGuiUtil.DrawTextButton(type.ToDescription(), new Vector2(0, _smallestIconWidth), 0); } - return ret; - } - - foreach (var iconType in Order) - { - ret |= DrawIcon(iconType, ref typeFilter); - ImGui.SameLine(); - } - - ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); - ImGui.Image(_icons[AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, - typeFilter == 0 ? new Vector4(0.6f, 0.3f, 0.3f, 1f) : - typeFilter == AllFlags ? new Vector4(0.75f, 0.75f, 0.75f, 1f) : new Vector4(0.5f, 0.5f, 1f, 1f)); - if (ImGui.IsItemClicked()) - { - typeFilter = typeFilter == AllFlags ? 0 : AllFlags; - ret = true; - } - - return ret; - } - - /// Obtain the icon category corresponding to a changed item. - internal static ChangedItemIcon GetCategoryIcon(string name, object? obj) - { - var iconType = ChangedItemIcon.Unknown; - switch (obj) - { - case EquipItem it: - iconType = GetCategoryIcon(it.Type.ToSlot()); - break; - case ModelChara m: - iconType = (CharacterBase.ModelType)m.Type switch - { - CharacterBase.ModelType.DemiHuman => ChangedItemIcon.Demihuman, - CharacterBase.ModelType.Monster => ChangedItemIcon.Monster, - _ => ChangedItemIcon.Unknown, - }; - break; - default: - { - if (name.StartsWith("Action: ")) - iconType = ChangedItemIcon.Action; - else if (name.StartsWith("Emote: ")) - iconType = ChangedItemIcon.Emote; - else if (name.StartsWith("Customization: ")) - iconType = ChangedItemIcon.Customization; - break; - } - } - - return iconType; - } - - internal static ChangedItemIcon GetCategoryIcon(EquipSlot slot) - => slot switch - { - EquipSlot.MainHand => ChangedItemIcon.Mainhand, - EquipSlot.OffHand => ChangedItemIcon.Offhand, - EquipSlot.Head => ChangedItemIcon.Head, - EquipSlot.Body => ChangedItemIcon.Body, - EquipSlot.Hands => ChangedItemIcon.Hands, - EquipSlot.Legs => ChangedItemIcon.Legs, - EquipSlot.Feet => ChangedItemIcon.Feet, - EquipSlot.Ears => ChangedItemIcon.Ears, - EquipSlot.Neck => ChangedItemIcon.Neck, - EquipSlot.Wrists => ChangedItemIcon.Wrists, - EquipSlot.RFinger => ChangedItemIcon.Finger, - _ => ChangedItemIcon.Unknown, - }; - - /// Return more detailed object information in text, if it exists. - private static bool GetChangedItemObject(object? obj, out string text) - { - switch (obj) - { - case EquipItem it: - text = it.ModelString; - return true; - case ModelChara m: - text = $"({((CharacterBase.ModelType)m.Type).ToName()} {m.Model}-{m.Base}-{m.Variant})"; - return true; - default: - text = string.Empty; - return false; + return localRet; } } - /// We need to transform the internal EquipItem type to the Lumina Item type for API-events. - private object? Convert(object? data) - { - if (data is EquipItem it) - return (_items.GetRow(it.ItemId.Id), it.Type); - - return data; - } - - private static string ToDescription(ChangedItemIcon icon) - => icon switch - { - ChangedItemIcon.Head => EquipSlot.Head.ToName(), - ChangedItemIcon.Body => EquipSlot.Body.ToName(), - ChangedItemIcon.Hands => EquipSlot.Hands.ToName(), - ChangedItemIcon.Legs => EquipSlot.Legs.ToName(), - ChangedItemIcon.Feet => EquipSlot.Feet.ToName(), - ChangedItemIcon.Ears => EquipSlot.Ears.ToName(), - ChangedItemIcon.Neck => EquipSlot.Neck.ToName(), - ChangedItemIcon.Wrists => EquipSlot.Wrists.ToName(), - ChangedItemIcon.Finger => "Ring", - ChangedItemIcon.Monster => "Monster", - ChangedItemIcon.Demihuman => "Demi-Human", - ChangedItemIcon.Customization => "Customization", - ChangedItemIcon.Action => "Action", - ChangedItemIcon.Emote => "Emote", - ChangedItemIcon.Mainhand => "Weapon (Mainhand)", - ChangedItemIcon.Offhand => "Weapon (Offhand)", - _ => "Other", - }; - - internal static ApiChangedItemIcon ToApiIcon(ChangedItemIcon icon) - => icon switch - { - ChangedItemIcon.Head => ApiChangedItemIcon.Head, - ChangedItemIcon.Body => ApiChangedItemIcon.Body, - ChangedItemIcon.Hands => ApiChangedItemIcon.Hands, - ChangedItemIcon.Legs => ApiChangedItemIcon.Legs, - ChangedItemIcon.Feet => ApiChangedItemIcon.Feet, - ChangedItemIcon.Ears => ApiChangedItemIcon.Ears, - ChangedItemIcon.Neck => ApiChangedItemIcon.Neck, - ChangedItemIcon.Wrists => ApiChangedItemIcon.Wrists, - ChangedItemIcon.Finger => ApiChangedItemIcon.Finger, - ChangedItemIcon.Monster => ApiChangedItemIcon.Monster, - ChangedItemIcon.Demihuman => ApiChangedItemIcon.Demihuman, - ChangedItemIcon.Customization => ApiChangedItemIcon.Customization, - ChangedItemIcon.Action => ApiChangedItemIcon.Action, - ChangedItemIcon.Emote => ApiChangedItemIcon.Emote, - ChangedItemIcon.Mainhand => ApiChangedItemIcon.Mainhand, - ChangedItemIcon.Offhand => ApiChangedItemIcon.Offhand, - ChangedItemIcon.Unknown => ApiChangedItemIcon.Unknown, - _ => ApiChangedItemIcon.None, - }; - - /// Apply Changed Item Counters to the Name if necessary. - private static string ChangedItemName(string name, object? data) - => data is int counter ? $"{counter} Files Manipulating {name}s" : name; - - /// Add filterable information to the string. - private static string ChangedItemFilterName(string name, object? data) - => data switch - { - int counter => $"{counter} Files Manipulating {name}s", - EquipItem it => $"{name}\0{(GetChangedItemObject(it, out var t) ? t : string.Empty)}", - ModelChara m => $"{name}\0{(GetChangedItemObject(m, out var t) ? t : string.Empty)}", - _ => name, - }; - /// Initialize the icons. private bool CreateEquipSlotIcons(IUiBuilder uiBuilder, IDataManager gameData, ITextureProvider textureProvider) { @@ -425,30 +246,30 @@ public class ChangedItemDrawer : IDisposable, IUiService if (!equipTypeIcons.Valid) return false; - void Add(ChangedItemIcon icon, IDalamudTextureWrap? tex) + void Add(ChangedItemIconFlag icon, IDalamudTextureWrap? tex) { if (tex != null) _icons.Add(icon, tex); } - Add(ChangedItemIcon.Mainhand, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 0)); - Add(ChangedItemIcon.Head, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 1)); - Add(ChangedItemIcon.Body, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 2)); - Add(ChangedItemIcon.Hands, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 3)); - Add(ChangedItemIcon.Legs, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 5)); - Add(ChangedItemIcon.Feet, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 6)); - Add(ChangedItemIcon.Offhand, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 7)); - Add(ChangedItemIcon.Ears, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 8)); - Add(ChangedItemIcon.Neck, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 9)); - Add(ChangedItemIcon.Wrists, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 10)); - Add(ChangedItemIcon.Finger, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 11)); - Add(ChangedItemIcon.Monster, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062042_hr1.tex")!)); - Add(ChangedItemIcon.Demihuman, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062041_hr1.tex")!)); - Add(ChangedItemIcon.Customization, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062043_hr1.tex")!)); - Add(ChangedItemIcon.Action, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062001_hr1.tex")!)); - Add(ChangedItemIcon.Emote, LoadEmoteTexture(gameData, textureProvider)); - Add(ChangedItemIcon.Unknown, LoadUnknownTexture(gameData, textureProvider)); - Add(AllFlags, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/114000/114052_hr1.tex")!)); + Add(ChangedItemIconFlag.Mainhand, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 0)); + Add(ChangedItemIconFlag.Head, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 1)); + Add(ChangedItemIconFlag.Body, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 2)); + Add(ChangedItemIconFlag.Hands, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 3)); + Add(ChangedItemIconFlag.Legs, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 5)); + Add(ChangedItemIconFlag.Feet, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 6)); + Add(ChangedItemIconFlag.Offhand, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 7)); + Add(ChangedItemIconFlag.Ears, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 8)); + Add(ChangedItemIconFlag.Neck, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 9)); + Add(ChangedItemIconFlag.Wrists, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 10)); + Add(ChangedItemIconFlag.Finger, equipTypeIcons.LoadTexturePart("ui/uld/ArmouryBoard_hr1.tex", 11)); + Add(ChangedItemIconFlag.Monster, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062044_hr1.tex")!)); + Add(ChangedItemIconFlag.Demihuman, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062043_hr1.tex")!)); + Add(ChangedItemIconFlag.Customization, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062045_hr1.tex")!)); + Add(ChangedItemIconFlag.Action, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/062000/062001_hr1.tex")!)); + Add(ChangedItemIconFlag.Emote, LoadEmoteTexture(gameData, textureProvider)); + Add(ChangedItemIconFlag.Unknown, LoadUnknownTexture(gameData, textureProvider)); + Add(ChangedItemFlagExtensions.AllFlags, textureProvider.CreateFromTexFile(gameData.GetFile("ui/icon/114000/114052_hr1.tex")!)); _smallestIconWidth = _icons.Values.Min(i => i.Width); @@ -487,6 +308,7 @@ public class ChangedItemDrawer : IDisposable, IUiService } } - return textureProvider.CreateFromRaw(RawImageSpecification.Rgba32(emote.Header.Width, emote.Header.Height), image2, "Penumbra.EmoteItemIcon"); + return textureProvider.CreateFromRaw(RawImageSpecification.Rgba32(emote.Header.Width, emote.Header.Height), image2, + "Penumbra.EmoteItemIcon"); } } diff --git a/Penumbra/UI/ChangedItemIconFlag.cs b/Penumbra/UI/ChangedItemIconFlag.cs new file mode 100644 index 00000000..fc7073f2 --- /dev/null +++ b/Penumbra/UI/ChangedItemIconFlag.cs @@ -0,0 +1,122 @@ +using Penumbra.Api.Enums; +using Penumbra.GameData.Enums; + +namespace Penumbra.UI; + +[Flags] +public enum ChangedItemIconFlag : uint +{ + Head = 0x00_00_01, + Body = 0x00_00_02, + Hands = 0x00_00_04, + Legs = 0x00_00_08, + Feet = 0x00_00_10, + Ears = 0x00_00_20, + Neck = 0x00_00_40, + Wrists = 0x00_00_80, + Finger = 0x00_01_00, + Monster = 0x00_02_00, + Demihuman = 0x00_04_00, + Customization = 0x00_08_00, + Action = 0x00_10_00, + Mainhand = 0x00_20_00, + Offhand = 0x00_40_00, + Unknown = 0x00_80_00, + Emote = 0x01_00_00, +} + +public static class ChangedItemFlagExtensions +{ + public static readonly IReadOnlyList Order = + [ + ChangedItemIconFlag.Head, + ChangedItemIconFlag.Body, + ChangedItemIconFlag.Hands, + ChangedItemIconFlag.Legs, + ChangedItemIconFlag.Feet, + ChangedItemIconFlag.Ears, + ChangedItemIconFlag.Neck, + ChangedItemIconFlag.Wrists, + ChangedItemIconFlag.Finger, + ChangedItemIconFlag.Mainhand, + ChangedItemIconFlag.Offhand, + ChangedItemIconFlag.Customization, + ChangedItemIconFlag.Action, + ChangedItemIconFlag.Emote, + ChangedItemIconFlag.Monster, + ChangedItemIconFlag.Demihuman, + ChangedItemIconFlag.Unknown, + ]; + + public const ChangedItemIconFlag AllFlags = (ChangedItemIconFlag)0x01FFFF; + public static readonly int NumCategories = Order.Count; + public const ChangedItemIconFlag DefaultFlags = AllFlags & ~ChangedItemIconFlag.Offhand; + + public static string ToDescription(this ChangedItemIconFlag iconFlag) + => iconFlag switch + { + ChangedItemIconFlag.Head => EquipSlot.Head.ToName(), + ChangedItemIconFlag.Body => EquipSlot.Body.ToName(), + ChangedItemIconFlag.Hands => EquipSlot.Hands.ToName(), + ChangedItemIconFlag.Legs => EquipSlot.Legs.ToName(), + ChangedItemIconFlag.Feet => EquipSlot.Feet.ToName(), + ChangedItemIconFlag.Ears => EquipSlot.Ears.ToName(), + ChangedItemIconFlag.Neck => EquipSlot.Neck.ToName(), + ChangedItemIconFlag.Wrists => EquipSlot.Wrists.ToName(), + ChangedItemIconFlag.Finger => "Ring", + ChangedItemIconFlag.Monster => "Monster", + ChangedItemIconFlag.Demihuman => "Demi-Human", + ChangedItemIconFlag.Customization => "Customization", + ChangedItemIconFlag.Action => "Action", + ChangedItemIconFlag.Emote => "Emote", + ChangedItemIconFlag.Mainhand => "Weapon (Mainhand)", + ChangedItemIconFlag.Offhand => "Weapon (Offhand)", + _ => "Other", + }; + + public static ChangedItemIcon ToApiIcon(this ChangedItemIconFlag iconFlag) + => iconFlag switch + { + ChangedItemIconFlag.Head => ChangedItemIcon.Head, + ChangedItemIconFlag.Body => ChangedItemIcon.Body, + ChangedItemIconFlag.Hands => ChangedItemIcon.Hands, + ChangedItemIconFlag.Legs => ChangedItemIcon.Legs, + ChangedItemIconFlag.Feet => ChangedItemIcon.Feet, + ChangedItemIconFlag.Ears => ChangedItemIcon.Ears, + ChangedItemIconFlag.Neck => ChangedItemIcon.Neck, + ChangedItemIconFlag.Wrists => ChangedItemIcon.Wrists, + ChangedItemIconFlag.Finger => ChangedItemIcon.Finger, + ChangedItemIconFlag.Monster => ChangedItemIcon.Monster, + ChangedItemIconFlag.Demihuman => ChangedItemIcon.Demihuman, + ChangedItemIconFlag.Customization => ChangedItemIcon.Customization, + ChangedItemIconFlag.Action => ChangedItemIcon.Action, + ChangedItemIconFlag.Emote => ChangedItemIcon.Emote, + ChangedItemIconFlag.Mainhand => ChangedItemIcon.Mainhand, + ChangedItemIconFlag.Offhand => ChangedItemIcon.Offhand, + ChangedItemIconFlag.Unknown => ChangedItemIcon.Unknown, + _ => ChangedItemIcon.None, + }; + + public static ChangedItemIconFlag ToFlag(this ChangedItemIcon icon) + => icon switch + { + ChangedItemIcon.Unknown => ChangedItemIconFlag.Unknown, + ChangedItemIcon.Head => ChangedItemIconFlag.Head, + ChangedItemIcon.Body => ChangedItemIconFlag.Body, + ChangedItemIcon.Hands => ChangedItemIconFlag.Hands, + ChangedItemIcon.Legs => ChangedItemIconFlag.Legs, + ChangedItemIcon.Feet => ChangedItemIconFlag.Feet, + ChangedItemIcon.Ears => ChangedItemIconFlag.Ears, + ChangedItemIcon.Neck => ChangedItemIconFlag.Neck, + ChangedItemIcon.Wrists => ChangedItemIconFlag.Wrists, + ChangedItemIcon.Finger => ChangedItemIconFlag.Finger, + ChangedItemIcon.Mainhand => ChangedItemIconFlag.Mainhand, + ChangedItemIcon.Offhand => ChangedItemIconFlag.Offhand, + ChangedItemIcon.Customization => ChangedItemIconFlag.Customization, + ChangedItemIcon.Monster => ChangedItemIconFlag.Monster, + ChangedItemIcon.Demihuman => ChangedItemIconFlag.Demihuman, + ChangedItemIcon.Action => ChangedItemIconFlag.Action, + ChangedItemIcon.Emote => ChangedItemIconFlag.Emote, + _ => ChangedItemIconFlag.Unknown, + }; +} diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 55405313..42689efb 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -550,7 +550,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector)selector.Selected!.ChangedItems); + var zipList = ZipList.FromSortedList(selector.Selected!.ChangedItems); var height = ImGui.GetFrameHeightWithSpacing(); ImGui.TableNextColumn(); var skips = ImGuiClip.GetNecessarySkips(height); @@ -32,15 +33,15 @@ public class ModPanelChangedItemsTab(ModFileSystemSelector selector, ChangedItem ImGuiClip.DrawEndDummy(remainder, height); } - private bool CheckFilter((string Name, object? Data) kvp) + private bool CheckFilter((string Name, IIdentifiedObjectData? Data) kvp) => drawer.FilterChangedItem(kvp.Name, kvp.Data, LowerString.Empty); - private void DrawChangedItem((string Name, object? Data) kvp) + private void DrawChangedItem((string Name, IIdentifiedObjectData? Data) kvp) { ImGui.TableNextColumn(); - drawer.DrawCategoryIcon(kvp.Name, kvp.Data); + drawer.DrawCategoryIcon(kvp.Data); ImGui.SameLine(); drawer.DrawChangedItem(kvp.Name, kvp.Data); - drawer.DrawModelData(kvp.Data); + ChangedItemDrawer.DrawModelData(kvp.Data); } } diff --git a/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs b/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs index e7550eea..1eff1919 100644 --- a/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs +++ b/Penumbra/UI/ModsTab/ModSearchStringSplitter.cs @@ -19,16 +19,16 @@ public sealed class ModSearchStringSplitter : SearchStringSplitter { - public string Needle { get; init; } - public ModSearchType Type { get; init; } - public ChangedItemDrawer.ChangedItemIcon IconFilter { get; init; } + public string Needle { get; init; } + public ModSearchType Type { get; init; } + public ChangedItemIconFlag IconFlagFilter { get; init; } public bool Contains(Entry other) { if (Type != other.Type) return false; if (Type is ModSearchType.Category) - return IconFilter == other.IconFilter; + return IconFlagFilter == other.IconFlagFilter; return Needle.Contains(other.Needle); } @@ -77,7 +77,7 @@ public sealed class ModSearchStringSplitter : SearchStringSplitter leaf.Value.Name.Lower.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), ModSearchType.Author => leaf.Value.Author.Lower.AsSpan().Contains(entry.Needle, StringComparison.Ordinal), ModSearchType.Category => leaf.Value.ChangedItems.Any(p - => (ChangedItemDrawer.GetCategoryIcon(p.Key, p.Value) & entry.IconFilter) != 0), + => ((p.Value?.Icon.ToFlag() ?? ChangedItemIconFlag.Unknown) & entry.IconFlagFilter) != 0), _ => true, }; diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index 2aeaaea0..256b0d79 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -6,6 +6,7 @@ using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; +using Penumbra.GameData.Data; using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.Services; @@ -66,22 +67,22 @@ public class ChangedItemsTab( } /// Apply the current filters. - private bool FilterChangedItem(KeyValuePair, object?)> item) + private bool FilterChangedItem(KeyValuePair, IIdentifiedObjectData?)> item) => drawer.FilterChangedItem(item.Key, item.Value.Item2, _changedItemFilter) && (_changedItemModFilter.IsEmpty || item.Value.Item1.Any(m => m.Name.Contains(_changedItemModFilter))); /// Draw a full column for a changed item. - private void DrawChangedItemColumn(KeyValuePair, object?)> item) + private void DrawChangedItemColumn(KeyValuePair, IIdentifiedObjectData?)> item) { ImGui.TableNextColumn(); - drawer.DrawCategoryIcon(item.Key, item.Value.Item2); + drawer.DrawCategoryIcon(item.Value.Item2); ImGui.SameLine(); drawer.DrawChangedItem(item.Key, item.Value.Item2); ImGui.TableNextColumn(); DrawModColumn(item.Value.Item1); ImGui.TableNextColumn(); - drawer.DrawModelData(item.Value.Item2); + ChangedItemDrawer.DrawModelData(item.Value.Item2); } private void DrawModColumn(SingleArray mods) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index ab47ce7c..6c36e49a 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -429,7 +429,7 @@ public class SettingsTab : ITab, IUiService _config.HideChangedItemFilters = v; if (v) { - _config.Ephemeral.ChangedItemFilter = ChangedItemDrawer.AllFlags; + _config.Ephemeral.ChangedItemFilter = ChangedItemFlagExtensions.AllFlags; _config.Ephemeral.Save(); } }); diff --git a/Penumbra/Util/IdentifierExtensions.cs b/Penumbra/Util/IdentifierExtensions.cs index cb43ac06..5bd3f77c 100644 --- a/Penumbra/Util/IdentifierExtensions.cs +++ b/Penumbra/Util/IdentifierExtensions.cs @@ -10,7 +10,7 @@ namespace Penumbra.Util; public static class IdentifierExtensions { public static void AddChangedItems(this ObjectIdentification identifier, IModDataContainer container, - IDictionary changedItems) + IDictionary changedItems) { foreach (var gamePath in container.Files.Keys.Concat(container.FileSwaps.Keys)) identifier.Identify(changedItems, gamePath.ToString()); @@ -19,25 +19,25 @@ public static class IdentifierExtensions manip.AddChangedItems(identifier, changedItems); } - public static void RemoveMachinistOffhands(this SortedList changedItems) + public static void RemoveMachinistOffhands(this SortedList changedItems) { for (var i = 0; i < changedItems.Count; i++) { { var value = changedItems.Values[i]; - if (value is EquipItem { Type: FullEquipType.GunOff }) + if (value is IdentifiedItem { Item.Type: FullEquipType.GunOff }) changedItems.RemoveAt(i--); } } } - public static void RemoveMachinistOffhands(this SortedList, object?)> changedItems) + public static void RemoveMachinistOffhands(this SortedList, IIdentifiedObjectData?)> changedItems) { for (var i = 0; i < changedItems.Count; i++) { { var value = changedItems.Values[i].Item2; - if (value is EquipItem { Type: FullEquipType.GunOff }) + if (value is IdentifiedItem { Item.Type: FullEquipType.GunOff }) changedItems.RemoveAt(i--); } } From ee086e3e7698a846cefa20c23dc09408b76caad8 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 4 Aug 2024 00:57:39 +0200 Subject: [PATCH 0836/1381] Update GameData --- Penumbra.GameData | 2 +- Penumbra/Services/StainService.cs | 4 ++-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ee6c6faa..1ec903d5 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ee6c6faa1e4a3e96279cb6c89df96e351f112c6a +Subproject commit 1ec903d53747fc16f62139e2ed3541f224ee3403 diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 50713968..ba5c3e63 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -16,7 +16,7 @@ namespace Penumbra.Services; public class StainService : IService { public sealed class StainTemplateCombo(FilterComboColors[] stainCombos, StmFile stmFile) - : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) where TDyePack : unmanaged, IDyePack + : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) where TDyePack : unmanaged, IDyePack { // FIXME There might be a better way to handle that. public int CurrentDyeChannel = 0; @@ -102,7 +102,7 @@ public class StainService : IService }; /// Loads a STM file. Opportunistically attempts to re-use the file already read by the game, with Lumina fallback. - private static unsafe StmFile LoadStmFile(ResourceHandle* stmResourceHandle, IDataManager dataManager) where TDyePack : unmanaged, IDyePack + private static unsafe StmFile LoadStmFile(ResourceHandle* stmResourceHandle, IDataManager dataManager) where TDyePack : unmanaged, IDyePack { if (stmResourceHandle != null) { diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index ead02874..7dae19c8 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -713,7 +713,7 @@ public class DebugTab : Window, ITab, IUiService } } - private static void DrawStainTemplatesFile(StmFile stmFile) where TDyePack : unmanaged, IDyePack + private static void DrawStainTemplatesFile(StmFile stmFile) where TDyePack : unmanaged, IDyePack { foreach (var (key, data) in stmFile.Entries) { From d90c3dd1af6e256932140ce84ddba78d4f233616 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 4 Aug 2024 15:35:27 +0200 Subject: [PATCH 0837/1381] Update row type names. --- Penumbra.GameData | 2 +- .../ModEditWindow.Materials.ColorTable.cs | 16 ++++++++-------- .../ModEditWindow.Materials.MtrlTab.cs | 6 +++--- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 44427ad0..f2734d54 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 44427ad0149059ab5ccb4e4a2f42a1a43423e4c5 +Subproject commit f2734d543d9b2debecb8feb6d6fa928801eb2bcb diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs index 25c0e448..cb04dc0a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs @@ -171,7 +171,7 @@ public partial class ModEditWindow } [SkipLocalsInit] - private static unsafe void ColorTableCopyClipboardButton(ColorTable.Row row, ColorDyeTable.Row dye) + private static unsafe void ColorTableCopyClipboardButton(ColorTableRow row, ColorDyeTableRow dye) { if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, "Export this row to your clipboard.", false, true)) @@ -179,11 +179,11 @@ public partial class ModEditWindow try { - Span data = stackalloc byte[ColorTable.Row.Size + ColorDyeTable.Row.Size]; + Span data = stackalloc byte[ColorTableRow.Size + ColorDyeTableRow.Size]; fixed (byte* ptr = data) { - MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTable.Row.Size); - MemoryUtility.MemCpyUnchecked(ptr + ColorTable.Row.Size, &dye, ColorDyeTable.Row.Size); + MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTableRow.Size); + MemoryUtility.MemCpyUnchecked(ptr + ColorTableRow.Size, &dye, ColorDyeTableRow.Size); } var text = Convert.ToBase64String(data); @@ -219,15 +219,15 @@ public partial class ModEditWindow { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - if (data.Length != ColorTable.Row.Size + ColorDyeTable.Row.Size + if (data.Length != ColorTableRow.Size + ColorDyeTableRow.Size || !tab.Mtrl.HasTable) return false; fixed (byte* ptr = data) { - tab.Mtrl.Table[rowIdx] = *(ColorTable.Row*)ptr; + tab.Mtrl.Table[rowIdx] = *(ColorTableRow*)ptr; if (tab.Mtrl.HasDyeTable) - tab.Mtrl.DyeTable[rowIdx] = *(ColorDyeTable.Row*)(ptr + ColorTable.Row.Size); + tab.Mtrl.DyeTable[rowIdx] = *(ColorDyeTableRow*)(ptr + ColorTableRow.Size); } tab.UpdateColorTableRowPreview(rowIdx); @@ -453,7 +453,7 @@ public partial class ModEditWindow return ret; } - private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, ColorDyeTable.Row dye, float floatSize) + private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, ColorDyeTableRow dye, float floatSize) { var stain = _stainService.StainCombo.CurrentSelection.Key; if (stain == 0 || !_stainService.StmFile.Entries.TryGetValue(dye.Template, out var entry)) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs index 29fd7531..b95eca9d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs @@ -597,11 +597,11 @@ public partial class ModEditWindow if (!Mtrl.HasTable) return; - var row = new LegacyColorTable.Row(Mtrl.Table[rowIdx]); + var row = new LegacyColorTableRow(Mtrl.Table[rowIdx]); if (Mtrl.HasDyeTable) { var stm = _edit._stainService.StmFile; - var dye = new LegacyColorDyeTable.Row(Mtrl.DyeTable[rowIdx]); + var dye = new LegacyColorDyeTableRow(Mtrl.DyeTable[rowIdx]); if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) row.ApplyDyeTemplate(dye, dyes); } @@ -651,7 +651,7 @@ public partial class ModEditWindow } } - private static void ApplyHighlight(ref LegacyColorTable.Row row, float time) + private static void ApplyHighlight(ref LegacyColorTableRow row, float time) { var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; var baseColor = ColorId.InGameHighlight.Value(); From c8e859ae05ebb9d9b7f0fbce17d3223c19c88be3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 4 Aug 2024 15:41:40 +0200 Subject: [PATCH 0838/1381] Fixups. --- .../Materials/MtrlTab.LegacyColorTable.cs | 38 +- .../Materials/MtrlTab.LivePreview.cs | 6 +- .../ModEditWindow.Materials.ColorTable.cs | 538 ------------ .../ModEditWindow.Materials.MtrlTab.cs | 783 ------------------ 4 files changed, 28 insertions(+), 1337 deletions(-) delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs delete mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs index f3ec5307..a2165760 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -33,6 +33,7 @@ public partial class MtrlTab UpdateColorTableRowPreview(i); ret = true; } + ImGui.TableNextRow(); } @@ -56,6 +57,7 @@ public partial class MtrlTab UpdateColorTableRowPreview(i); ret = true; } + ImGui.TableNextRow(); } @@ -108,8 +110,10 @@ public partial class MtrlTab } ImGui.TableNextColumn(); - using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) - ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); + } ImGui.TableNextColumn(); using var dis = ImRaii.Disabled(disabled); @@ -131,9 +135,11 @@ public partial class MtrlTab ret |= CtApplyStainCheckbox("##dyeSpecular"u8, "Apply Specular Color on Dye"u8, dye.SpecularColor, b => dyeTable[rowIdx].SpecularColor = b); } + ImGui.SameLine(); ImGui.SetNextItemWidth(pctSize); - ret |= CtDragScalar("##SpecularMask"u8, "Specular Strength"u8, (float)row.SpecularMask * 100.0f, "%.0f%%"u8, 0f, HalfMaxValue * 100.0f, 1.0f, + ret |= CtDragScalar("##SpecularMask"u8, "Specular Strength"u8, (float)row.SpecularMask * 100.0f, "%.0f%%"u8, 0f, HalfMaxValue * 100.0f, + 1.0f, v => table[rowIdx].SpecularMask = (Half)(v * 0.01f)); if (dyeTable != null) { @@ -155,7 +161,8 @@ public partial class MtrlTab ImGui.TableNextColumn(); ImGui.SetNextItemWidth(floatSize); var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; - ret |= CtDragHalf("##Shininess"u8, "Gloss Strength"u8, row.Shininess, "%.1f"u8, glossStrengthMin, HalfMaxValue, Math.Max(0.1f, (float)row.Shininess * 0.025f), + ret |= CtDragHalf("##Shininess"u8, "Gloss Strength"u8, row.Shininess, "%.1f"u8, glossStrengthMin, HalfMaxValue, + Math.Max(0.1f, (float)row.Shininess * 0.025f), v => table[rowIdx].Shininess = v); if (dyeTable != null) @@ -197,7 +204,7 @@ public partial class MtrlTab { using var id = ImRaii.PushId(rowIdx); ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; var floatSize = LegacyColorTableFloatSize * UiHelpers.Scale; var pctSize = LegacyColorTablePercentageSize * UiHelpers.Scale; var intSize = LegacyColorTableIntegerSize * UiHelpers.Scale; @@ -213,8 +220,10 @@ public partial class MtrlTab } ImGui.TableNextColumn(); - using (var font = ImRaii.PushFont(UiBuilder.MonoFont)) + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); + } ImGui.TableNextColumn(); using var dis = ImRaii.Disabled(disabled); @@ -236,6 +245,7 @@ public partial class MtrlTab ret |= CtApplyStainCheckbox("##dyeSpecular"u8, "Apply Specular Color on Dye"u8, dye.SpecularColor, b => dyeTable[rowIdx].SpecularColor = b); } + ImGui.SameLine(); ImGui.SetNextItemWidth(pctSize); ret |= CtDragScalar("##SpecularMask"u8, "Specular Strength"u8, (float)row.Scalar7 * 100.0f, "%.0f%%"u8, 0f, HalfMaxValue * 100.0f, 1.0f, @@ -260,7 +270,8 @@ public partial class MtrlTab ImGui.TableNextColumn(); ImGui.SetNextItemWidth(floatSize); var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; - ret |= CtDragHalf("##Shininess"u8, "Gloss Strength"u8, row.Scalar3, "%.1f"u8, glossStrengthMin, HalfMaxValue, Math.Max(0.1f, (float)row.Scalar3 * 0.025f), + ret |= CtDragHalf("##Shininess"u8, "Gloss Strength"u8, row.Scalar3, "%.1f"u8, glossStrengthMin, HalfMaxValue, + Math.Max(0.1f, (float)row.Scalar3 * 0.025f), v => table[rowIdx].Scalar3 = v); if (dyeTable != null) @@ -307,7 +318,7 @@ public partial class MtrlTab return ret; } - private bool DrawLegacyDyePreview(int rowIdx, bool disabled, LegacyColorDyeTable.Row dye, float floatSize) + private bool DrawLegacyDyePreview(int rowIdx, bool disabled, LegacyColorDyeTableRow dye, float floatSize) { var stain = _stainService.StainCombo1.CurrentSelection.Key; if (stain == 0 || !_stainService.LegacyStmFile.TryGetValue(dye.Template, stain, out var values)) @@ -326,7 +337,7 @@ public partial class MtrlTab return ret; } - private bool DrawLegacyDyePreview(int rowIdx, bool disabled, ColorDyeTable.Row dye, float floatSize) + private bool DrawLegacyDyePreview(int rowIdx, bool disabled, ColorDyeTableRow dye, float floatSize) { var stain = _stainService.GetStainCombo(dye.Channel).CurrentSelection.Key; if (stain == 0 || !_stainService.LegacyStmFile.TryGetValue(dye.Template, stain, out var values)) @@ -337,10 +348,11 @@ public partial class MtrlTab var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Apply the selected dye to this row.", disabled, true); - ret = ret && Mtrl.ApplyDyeToRow(_stainService.LegacyStmFile, [ - _stainService.StainCombo1.CurrentSelection.Key, - _stainService.StainCombo2.CurrentSelection.Key, - ], rowIdx); + ret = ret + && Mtrl.ApplyDyeToRow(_stainService.LegacyStmFile, [ + _stainService.StainCombo1.CurrentSelection.Key, + _stainService.StainCombo2.CurrentSelection.Key, + ], rowIdx); ImGui.SameLine(); DrawLegacyDyePreview(values, floatSize); diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs index bb346534..3482e581 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs @@ -191,7 +191,7 @@ public partial class MtrlTab var row = Mtrl.Table switch { - LegacyColorTable legacyTable => new ColorTable.Row(legacyTable[rowIdx]), + LegacyColorTable legacyTable => new ColorTableRow(legacyTable[rowIdx]), ColorTable table => table[rowIdx], _ => throw new InvalidOperationException($"Unsupported color table type {Mtrl.Table.GetType()}"), }; @@ -199,7 +199,7 @@ public partial class MtrlTab { var dyeRow = Mtrl.DyeTable switch { - LegacyColorDyeTable legacyDyeTable => new ColorDyeTable.Row(legacyDyeTable[rowIdx]), + LegacyColorDyeTable legacyDyeTable => new ColorDyeTableRow(legacyDyeTable[rowIdx]), ColorDyeTable dyeTable => dyeTable[rowIdx], _ => throw new InvalidOperationException($"Unsupported color dye table type {Mtrl.DyeTable.GetType()}"), }; @@ -258,7 +258,7 @@ public partial class MtrlTab } } - private static void ApplyHighlight(ref ColorTable.Row row, ColorId colorId, float time) + private static void ApplyHighlight(ref ColorTableRow row, ColorId colorId, float time) { var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; var baseColor = colorId.Value(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs deleted file mode 100644 index cb04dc0a..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.ColorTable.cs +++ /dev/null @@ -1,538 +0,0 @@ -using Dalamud.Interface; -using Dalamud.Interface.Utility; -using ImGuiNET; -using OtterGui; -using OtterGui.Raii; -using Penumbra.GameData.Files; -using Penumbra.GameData.Files.MaterialStructs; -using Penumbra.String.Functions; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private static readonly float HalfMinValue = (float)Half.MinValue; - private static readonly float HalfMaxValue = (float)Half.MaxValue; - private static readonly float HalfEpsilon = (float)Half.Epsilon; - - private bool DrawMaterialColorTableChange(MtrlTab tab, bool disabled) - { - if (!tab.SamplerIds.Contains(ShpkFile.TableSamplerId) || !tab.Mtrl.HasTable) - return false; - - ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (!ImGui.CollapsingHeader("Color Table", ImGuiTreeNodeFlags.DefaultOpen)) - return false; - - ColorTableCopyAllClipboardButton(tab.Mtrl); - ImGui.SameLine(); - var ret = ColorTablePasteAllClipboardButton(tab, disabled); - if (!disabled) - { - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); - ImGui.SameLine(); - ret |= ColorTableDyeableCheckbox(tab); - } - - var hasDyeTable = tab.Mtrl.HasDyeTable; - if (hasDyeTable) - { - ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); - ImGui.SameLine(); - ret |= DrawPreviewDye(tab, disabled); - } - - using var table = ImRaii.Table("##ColorTable", hasDyeTable ? 11 : 9, - ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV); - if (!table) - return false; - - ImGui.TableNextColumn(); - ImGui.TableHeader(string.Empty); - ImGui.TableNextColumn(); - ImGui.TableHeader("Row"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Diffuse"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Specular"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Emissive"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Gloss"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Tile"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Repeat"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Skew"); - if (hasDyeTable) - { - ImGui.TableNextColumn(); - ImGui.TableHeader("Dye"); - ImGui.TableNextColumn(); - ImGui.TableHeader("Dye Preview"); - } - - for (var i = 0; i < ColorTable.NumRows; ++i) - { - ret |= DrawColorTableRow(tab, i, disabled); - ImGui.TableNextRow(); - } - - return ret; - } - - - private static void ColorTableCopyAllClipboardButton(MtrlFile file) - { - if (!ImGui.Button("Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2(200, 0))) - return; - - try - { - var data1 = file.Table.AsBytes(); - var data2 = file.HasDyeTable ? file.DyeTable.AsBytes() : ReadOnlySpan.Empty; - var array = new byte[data1.Length + data2.Length]; - data1.TryCopyTo(array); - data2.TryCopyTo(array.AsSpan(data1.Length)); - var text = Convert.ToBase64String(array); - ImGui.SetClipboardText(text); - } - catch - { - // ignored - } - } - - private bool DrawPreviewDye(MtrlTab tab, bool disabled) - { - var (dyeId, (name, dyeColor, gloss)) = _stainService.StainCombo.CurrentSelection; - var tt = dyeId == 0 - ? "Select a preview dye first." - : "Apply all preview values corresponding to the dye template and chosen dye where dyeing is enabled."; - if (ImGuiUtil.DrawDisabledButton("Apply Preview Dye", Vector2.Zero, tt, disabled || dyeId == 0)) - { - var ret = false; - if (tab.Mtrl.HasDyeTable) - for (var i = 0; i < LegacyColorTable.NumUsedRows; ++i) - ret |= tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, i, dyeId, 0); - - tab.UpdateColorTablePreview(); - - return ret; - } - - ImGui.SameLine(); - var label = dyeId == 0 ? "Preview Dye###previewDye" : $"{name} (Preview)###previewDye"; - if (_stainService.StainCombo.Draw(label, dyeColor, string.Empty, true, gloss)) - tab.UpdateColorTablePreview(); - return false; - } - - private static unsafe bool ColorTablePasteAllClipboardButton(MtrlTab tab, bool disabled) - { - if (!ImGuiUtil.DrawDisabledButton("Import All Rows from Clipboard", ImGuiHelpers.ScaledVector2(200, 0), string.Empty, disabled) - || !tab.Mtrl.HasTable) - return false; - - try - { - var text = ImGui.GetClipboardText(); - var data = Convert.FromBase64String(text); - if (data.Length < Marshal.SizeOf()) - return false; - - ref var rows = ref tab.Mtrl.Table; - fixed (void* ptr = data, output = &rows) - { - MemoryUtility.MemCpyUnchecked(output, ptr, Marshal.SizeOf()); - if (data.Length >= Marshal.SizeOf() + Marshal.SizeOf() - && tab.Mtrl.HasDyeTable) - { - ref var dyeRows = ref tab.Mtrl.DyeTable; - fixed (void* output2 = &dyeRows) - { - MemoryUtility.MemCpyUnchecked(output2, (byte*)ptr + Marshal.SizeOf(), - Marshal.SizeOf()); - } - } - } - - tab.UpdateColorTablePreview(); - - return true; - } - catch - { - return false; - } - } - - [SkipLocalsInit] - private static unsafe void ColorTableCopyClipboardButton(ColorTableRow row, ColorDyeTableRow dye) - { - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Export this row to your clipboard.", false, true)) - return; - - try - { - Span data = stackalloc byte[ColorTableRow.Size + ColorDyeTableRow.Size]; - fixed (byte* ptr = data) - { - MemoryUtility.MemCpyUnchecked(ptr, &row, ColorTableRow.Size); - MemoryUtility.MemCpyUnchecked(ptr + ColorTableRow.Size, &dye, ColorDyeTableRow.Size); - } - - var text = Convert.ToBase64String(data); - ImGui.SetClipboardText(text); - } - catch - { - // ignored - } - } - - private static bool ColorTableDyeableCheckbox(MtrlTab tab) - { - var dyeable = tab.Mtrl.HasDyeTable; - var ret = ImGui.Checkbox("Dyeable", ref dyeable); - - if (ret) - { - tab.Mtrl.HasDyeTable = dyeable; - tab.UpdateColorTablePreview(); - } - - return ret; - } - - private static unsafe bool ColorTablePasteFromClipboardButton(MtrlTab tab, int rowIdx, bool disabled) - { - if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Paste.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Import an exported row from your clipboard onto this row.", disabled, true)) - return false; - - try - { - var text = ImGui.GetClipboardText(); - var data = Convert.FromBase64String(text); - if (data.Length != ColorTableRow.Size + ColorDyeTableRow.Size - || !tab.Mtrl.HasTable) - return false; - - fixed (byte* ptr = data) - { - tab.Mtrl.Table[rowIdx] = *(ColorTableRow*)ptr; - if (tab.Mtrl.HasDyeTable) - tab.Mtrl.DyeTable[rowIdx] = *(ColorDyeTableRow*)(ptr + ColorTableRow.Size); - } - - tab.UpdateColorTableRowPreview(rowIdx); - - return true; - } - catch - { - return false; - } - } - - private static void ColorTableHighlightButton(MtrlTab tab, int rowIdx, bool disabled) - { - ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Crosshairs.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Highlight this row on your character, if possible.", disabled || tab.ColorTablePreviewers.Count == 0, true); - - if (ImGui.IsItemHovered()) - tab.HighlightColorTableRow(rowIdx); - else if (tab.HighlightedColorTableRow == rowIdx) - tab.CancelColorTableHighlight(); - } - - private bool DrawColorTableRow(MtrlTab tab, int rowIdx, bool disabled) - { - static bool FixFloat(ref float val, float current) - { - val = (float)(Half)val; - return val != current; - } - - using var id = ImRaii.PushId(rowIdx); - ref var row = ref tab.Mtrl.Table[rowIdx]; - var hasDye = tab.Mtrl.HasDyeTable; - ref var dye = ref tab.Mtrl.DyeTable[rowIdx]; - var floatSize = 70 * UiHelpers.Scale; - var intSize = 45 * UiHelpers.Scale; - ImGui.TableNextColumn(); - ColorTableCopyClipboardButton(row, dye); - ImGui.SameLine(); - var ret = ColorTablePasteFromClipboardButton(tab, rowIdx, disabled); - ImGui.SameLine(); - ColorTableHighlightButton(tab, rowIdx, disabled); - - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"#{rowIdx + 1:D2}"); - - ImGui.TableNextColumn(); - using var dis = ImRaii.Disabled(disabled); - ret |= ColorPicker("##Diffuse", "Diffuse Color", row.Diffuse, c => - { - tab.Mtrl.Table[rowIdx].Diffuse = c; - tab.UpdateColorTableRowPreview(rowIdx); - }); - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeDiffuse", "Apply Diffuse Color on Dye", dye.Diffuse, - b => - { - tab.Mtrl.DyeTable[rowIdx].Diffuse = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - ret |= ColorPicker("##Specular", "Specular Color", row.Specular, c => - { - tab.Mtrl.Table[rowIdx].Specular = c; - tab.UpdateColorTableRowPreview(rowIdx); - }); - ImGui.SameLine(); - var tmpFloat = row.SpecularStrength; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SpecularStrength", ref tmpFloat, 0.01f, 0f, HalfMaxValue, "%.2f") - && FixFloat(ref tmpFloat, row.SpecularStrength)) - { - row.SpecularStrength = tmpFloat; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Specular Strength", ImGuiHoveredFlags.AllowWhenDisabled); - - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeSpecular", "Apply Specular Color on Dye", dye.Specular, - b => - { - tab.Mtrl.DyeTable[rowIdx].Specular = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeSpecularStrength", "Apply Specular Strength on Dye", dye.SpecularStrength, - b => - { - tab.Mtrl.DyeTable[rowIdx].SpecularStrength = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - ret |= ColorPicker("##Emissive", "Emissive Color", row.Emissive, c => - { - tab.Mtrl.Table[rowIdx].Emissive = c; - tab.UpdateColorTableRowPreview(rowIdx); - }); - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeEmissive", "Apply Emissive Color on Dye", dye.Emissive, - b => - { - tab.Mtrl.DyeTable[rowIdx].Emissive = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - tmpFloat = row.GlossStrength; - ImGui.SetNextItemWidth(floatSize); - var glossStrengthMin = ImGui.GetIO().KeyCtrl ? 0.0f : HalfEpsilon; - if (ImGui.DragFloat("##GlossStrength", ref tmpFloat, Math.Max(0.1f, tmpFloat * 0.025f), glossStrengthMin, HalfMaxValue, "%.1f") - && FixFloat(ref tmpFloat, row.GlossStrength)) - { - row.GlossStrength = Math.Max(tmpFloat, glossStrengthMin); - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Gloss Strength", ImGuiHoveredFlags.AllowWhenDisabled); - if (hasDye) - { - ImGui.SameLine(); - ret |= ImGuiUtil.Checkbox("##dyeGloss", "Apply Gloss Strength on Dye", dye.Gloss, - b => - { - tab.Mtrl.DyeTable[rowIdx].Gloss = b; - tab.UpdateColorTableRowPreview(rowIdx); - }, ImGuiHoveredFlags.AllowWhenDisabled); - } - - ImGui.TableNextColumn(); - int tmpInt = row.TileSet; - ImGui.SetNextItemWidth(intSize); - if (ImGui.DragInt("##TileSet", ref tmpInt, 0.25f, 0, 63) && tmpInt != row.TileSet && tmpInt is >= 0 and <= ushort.MaxValue) - { - row.TileSet = (ushort)Math.Clamp(tmpInt, 0, 63); - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Tile Set", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.TableNextColumn(); - tmpFloat = row.MaterialRepeat.X; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##RepeatX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") - && FixFloat(ref tmpFloat, row.MaterialRepeat.X)) - { - row.MaterialRepeat = row.MaterialRepeat with { X = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Repeat X", ImGuiHoveredFlags.AllowWhenDisabled); - ImGui.SameLine(); - tmpFloat = row.MaterialRepeat.Y; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##RepeatY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") - && FixFloat(ref tmpFloat, row.MaterialRepeat.Y)) - { - row.MaterialRepeat = row.MaterialRepeat with { Y = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Repeat Y", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.TableNextColumn(); - tmpFloat = row.MaterialSkew.X; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SkewX", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.X)) - { - row.MaterialSkew = row.MaterialSkew with { X = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Skew X", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.SameLine(); - tmpFloat = row.MaterialSkew.Y; - ImGui.SetNextItemWidth(floatSize); - if (ImGui.DragFloat("##SkewY", ref tmpFloat, 0.1f, HalfMinValue, HalfMaxValue, "%.2f") && FixFloat(ref tmpFloat, row.MaterialSkew.Y)) - { - row.MaterialSkew = row.MaterialSkew with { Y = tmpFloat }; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Skew Y", ImGuiHoveredFlags.AllowWhenDisabled); - - if (hasDye) - { - ImGui.TableNextColumn(); - if (_stainService.TemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize - + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) - { - dye.Template = _stainService.TemplateCombo.CurrentSelection; - ret = true; - tab.UpdateColorTableRowPreview(rowIdx); - } - - ImGuiUtil.HoverTooltip("Dye Template", ImGuiHoveredFlags.AllowWhenDisabled); - - ImGui.TableNextColumn(); - ret |= DrawDyePreview(tab, rowIdx, disabled, dye, floatSize); - } - - - return ret; - } - - private bool DrawDyePreview(MtrlTab tab, int rowIdx, bool disabled, ColorDyeTableRow dye, float floatSize) - { - var stain = _stainService.StainCombo.CurrentSelection.Key; - if (stain == 0 || !_stainService.StmFile.Entries.TryGetValue(dye.Template, out var entry)) - return false; - - var values = entry[(int)stain]; - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing / 2); - - var ret = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.PaintBrush.ToIconString(), new Vector2(ImGui.GetFrameHeight()), - "Apply the selected dye to this row.", disabled, true); - - ret = ret && tab.Mtrl.ApplyDyeTemplate(_stainService.StmFile, rowIdx, stain, 0); - if (ret) - tab.UpdateColorTableRowPreview(rowIdx); - - ImGui.SameLine(); - ColorPicker("##diffusePreview", string.Empty, values.Diffuse, _ => { }, "D"); - ImGui.SameLine(); - ColorPicker("##specularPreview", string.Empty, values.Specular, _ => { }, "S"); - ImGui.SameLine(); - ColorPicker("##emissivePreview", string.Empty, values.Emissive, _ => { }, "E"); - ImGui.SameLine(); - using var dis = ImRaii.Disabled(); - ImGui.SetNextItemWidth(floatSize); - ImGui.DragFloat("##gloss", ref values.Gloss, 0, values.Gloss, values.Gloss, "%.1f G"); - ImGui.SameLine(); - ImGui.SetNextItemWidth(floatSize); - ImGui.DragFloat("##specularStrength", ref values.SpecularPower, 0, values.SpecularPower, values.SpecularPower, "%.2f S"); - - return ret; - } - - private static bool ColorPicker(string label, string tooltip, Vector3 input, Action setter, string letter = "") - { - var ret = false; - var inputSqrt = PseudoSqrtRgb(input); - var tmp = inputSqrt; - if (ImGui.ColorEdit3(label, ref tmp, - ImGuiColorEditFlags.NoInputs - | ImGuiColorEditFlags.DisplayRGB - | ImGuiColorEditFlags.InputRGB - | ImGuiColorEditFlags.NoTooltip - | ImGuiColorEditFlags.HDR) - && tmp != inputSqrt) - { - setter(PseudoSquareRgb(tmp)); - ret = true; - } - - if (letter.Length > 0 && ImGui.IsItemVisible()) - { - var textSize = ImGui.CalcTextSize(letter); - var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; - var textColor = input.LengthSquared() < 0.25f ? 0x80FFFFFFu : 0x80000000u; - ImGui.GetWindowDrawList().AddText(center, textColor, letter); - } - - ImGuiUtil.HoverTooltip(tooltip, ImGuiHoveredFlags.AllowWhenDisabled); - - return ret; - } - - // Functions to deal with squared RGB values without making negatives useless. - - private static float PseudoSquareRgb(float x) - => x < 0.0f ? -(x * x) : x * x; - - private static Vector3 PseudoSquareRgb(Vector3 vec) - => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z)); - - private static Vector4 PseudoSquareRgb(Vector4 vec) - => new(PseudoSquareRgb(vec.X), PseudoSquareRgb(vec.Y), PseudoSquareRgb(vec.Z), vec.W); - - private static float PseudoSqrtRgb(float x) - => x < 0.0f ? -MathF.Sqrt(-x) : MathF.Sqrt(x); - - internal static Vector3 PseudoSqrtRgb(Vector3 vec) - => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z)); - - private static Vector4 PseudoSqrtRgb(Vector4 vec) - => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z), vec.W); -} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs deleted file mode 100644 index b95eca9d..00000000 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.MtrlTab.cs +++ /dev/null @@ -1,783 +0,0 @@ -using Dalamud.Interface; -using Dalamud.Interface.ImGuiNotification; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using ImGuiNET; -using Newtonsoft.Json.Linq; -using OtterGui; -using OtterGui.Classes; -using OtterGui.Raii; -using Penumbra.GameData.Data; -using Penumbra.GameData.Files; -using Penumbra.GameData.Files.MaterialStructs; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Hooks.Objects; -using Penumbra.Interop.MaterialPreview; -using Penumbra.String; -using Penumbra.String.Classes; -using Penumbra.UI.Classes; -using static Penumbra.GameData.Files.ShpkFile; - -namespace Penumbra.UI.AdvancedWindow; - -public partial class ModEditWindow -{ - private sealed class MtrlTab : IWritable, IDisposable - { - private const int ShpkPrefixLength = 16; - - private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); - - private readonly ModEditWindow _edit; - public readonly MtrlFile Mtrl; - public readonly string FilePath; - public readonly bool Writable; - - private string[]? _shpkNames; - - public string ShaderHeader = "Shader###Shader"; - public FullPath LoadedShpkPath = FullPath.Empty; - public string LoadedShpkPathName = string.Empty; - public string LoadedShpkDevkitPathName = string.Empty; - public string ShaderComment = string.Empty; - public ShpkFile? AssociatedShpk; - public JObject? AssociatedShpkDevkit; - - public readonly string LoadedBaseDevkitPathName; - public readonly JObject? AssociatedBaseDevkit; - - // Shader Key State - public readonly - List<(string Label, int Index, string Description, bool MonoFont, IReadOnlyList<(string Label, uint Value, string Description)> - Values)> ShaderKeys = new(16); - - public readonly HashSet VertexShaders = new(16); - public readonly HashSet PixelShaders = new(16); - public bool ShadersKnown; - public string VertexShadersString = "Vertex Shaders: ???"; - public string PixelShadersString = "Pixel Shaders: ???"; - - // Textures & Samplers - public readonly List<(string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont)> Textures = new(4); - - public readonly HashSet UnfoldedTextures = new(4); - public readonly HashSet SamplerIds = new(16); - public float TextureLabelWidth; - - // Material Constants - public readonly - List<(string Header, List<(string Label, int ConstantIndex, Range Slice, string Description, bool MonoFont, IConstantEditor Editor)> - Constants)> Constants = new(16); - - // Live-Previewers - public readonly List MaterialPreviewers = new(4); - public readonly List ColorTablePreviewers = new(4); - public int HighlightedColorTableRow = -1; - public readonly Stopwatch HighlightTime = new(); - - public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) - { - defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); - if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) - return FullPath.Empty; - - return _edit.FindBestMatch(defaultGamePath); - } - - public string[] GetShpkNames() - { - if (null != _shpkNames) - return _shpkNames; - - var names = new HashSet(StandardShaderPackages); - names.UnionWith(_edit.FindPathsStartingWith(ShpkPrefix).Select(path => path.ToString()[ShpkPrefixLength..])); - - _shpkNames = names.ToArray(); - Array.Sort(_shpkNames); - - return _shpkNames; - } - - public void LoadShpk(FullPath path) - { - ShaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; - - try - { - LoadedShpkPath = path; - var data = LoadedShpkPath.IsRooted - ? File.ReadAllBytes(LoadedShpkPath.FullName) - : _edit._gameData.GetFile(LoadedShpkPath.InternalName.ToString())?.Data; - AssociatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); - LoadedShpkPathName = path.ToPath(); - } - catch (Exception e) - { - LoadedShpkPath = FullPath.Empty; - LoadedShpkPathName = string.Empty; - AssociatedShpk = null; - Penumbra.Messager.NotificationMessage(e, $"Could not load {LoadedShpkPath.ToPath()}.", NotificationType.Error, false); - } - - if (LoadedShpkPath.InternalName.IsEmpty) - { - AssociatedShpkDevkit = null; - LoadedShpkDevkitPathName = string.Empty; - } - else - { - AssociatedShpkDevkit = - TryLoadShpkDevkit(Path.GetFileNameWithoutExtension(Mtrl.ShaderPackage.Name), out LoadedShpkDevkitPathName); - } - - UpdateShaderKeys(); - Update(); - } - - private JObject? TryLoadShpkDevkit(string shpkBaseName, out string devkitPathName) - { - try - { - if (!Utf8GamePath.FromString("penumbra/shpk_devkit/" + shpkBaseName + ".json", out var devkitPath)) - throw new Exception("Could not assemble ShPk dev-kit path."); - - var devkitFullPath = _edit.FindBestMatch(devkitPath); - if (!devkitFullPath.IsRooted) - throw new Exception("Could not resolve ShPk dev-kit path."); - - devkitPathName = devkitFullPath.FullName; - return JObject.Parse(File.ReadAllText(devkitFullPath.FullName)); - } - catch - { - devkitPathName = string.Empty; - return null; - } - } - - private T? TryGetShpkDevkitData(string category, uint? id, bool mayVary) where T : class - => TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) - ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); - - private T? TryGetShpkDevkitData(JObject? devkit, string devkitPathName, string category, uint? id, bool mayVary) where T : class - { - if (devkit == null) - return null; - - try - { - var data = devkit[category]; - if (id.HasValue) - data = data?[id.Value.ToString()]; - - if (mayVary && (data as JObject)?["Vary"] != null) - { - var selector = BuildSelector(data!["Vary"]! - .Select(key => (uint)key) - .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); - var index = (int)data["Selectors"]![selector.ToString()]!; - data = data["Items"]![index]; - } - - return data?.ToObject(typeof(T)) as T; - } - catch (Exception e) - { - // Some element in the JSON was undefined or invalid (wrong type, key that doesn't exist in the ShPk, index out of range, …) - Penumbra.Log.Error($"Error while traversing the ShPk dev-kit file at {devkitPathName}: {e}"); - return null; - } - } - - private void UpdateShaderKeys() - { - ShaderKeys.Clear(); - if (AssociatedShpk != null) - foreach (var key in AssociatedShpk.MaterialKeys) - { - var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); - var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); - - var valueSet = new HashSet(key.Values); - if (dkData != null) - valueSet.UnionWith(dkData.Values.Keys); - - var mtrlKeyIndex = Mtrl.FindOrAddShaderKey(key.Id, key.DefaultValue); - var values = valueSet.Select(value => - { - if (dkData != null && dkData.Values.TryGetValue(value, out var dkValue)) - return (dkValue.Label.Length > 0 ? dkValue.Label : $"0x{value:X8}", value, dkValue.Description); - - return ($"0x{value:X8}", value, string.Empty); - }).ToArray(); - Array.Sort(values, (x, y) => - { - if (x.Value == key.DefaultValue) - return -1; - if (y.Value == key.DefaultValue) - return 1; - - return string.Compare(x.Label, y.Label, StringComparison.Ordinal); - }); - ShaderKeys.Add((hasDkLabel ? dkData!.Label : $"0x{key.Id:X8}", mtrlKeyIndex, dkData?.Description ?? string.Empty, - !hasDkLabel, values)); - } - else - foreach (var (key, index) in Mtrl.ShaderPackage.ShaderKeys.WithIndex()) - ShaderKeys.Add(($"0x{key.Category:X8}", index, string.Empty, true, Array.Empty<(string, uint, string)>())); - } - - private void UpdateShaders() - { - VertexShaders.Clear(); - PixelShaders.Clear(); - if (AssociatedShpk == null) - { - ShadersKnown = false; - } - else - { - ShadersKnown = true; - var systemKeySelectors = AllSelectors(AssociatedShpk.SystemKeys).ToArray(); - var sceneKeySelectors = AllSelectors(AssociatedShpk.SceneKeys).ToArray(); - var subViewKeySelectors = AllSelectors(AssociatedShpk.SubViewKeys).ToArray(); - var materialKeySelector = - BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); - foreach (var systemKeySelector in systemKeySelectors) - { - foreach (var sceneKeySelector in sceneKeySelectors) - { - foreach (var subViewKeySelector in subViewKeySelectors) - { - var selector = BuildSelector(systemKeySelector, sceneKeySelector, materialKeySelector, subViewKeySelector); - var node = AssociatedShpk.GetNodeBySelector(selector); - if (node.HasValue) - foreach (var pass in node.Value.Passes) - { - VertexShaders.Add((int)pass.VertexShader); - PixelShaders.Add((int)pass.PixelShader); - } - else - ShadersKnown = false; - } - } - } - } - - var vertexShaders = VertexShaders.OrderBy(i => i).Select(i => $"#{i}"); - var pixelShaders = PixelShaders.OrderBy(i => i).Select(i => $"#{i}"); - - VertexShadersString = $"Vertex Shaders: {string.Join(", ", ShadersKnown ? vertexShaders : vertexShaders.Append("???"))}"; - PixelShadersString = $"Pixel Shaders: {string.Join(", ", ShadersKnown ? pixelShaders : pixelShaders.Append("???"))}"; - - ShaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; - } - - private void UpdateTextures() - { - Textures.Clear(); - SamplerIds.Clear(); - if (AssociatedShpk == null) - { - SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.HasTable) - SamplerIds.Add(TableSamplerId); - - foreach (var (sampler, index) in Mtrl.ShaderPackage.Samplers.WithIndex()) - Textures.Add(($"0x{sampler.SamplerId:X8}", sampler.TextureIndex, index, string.Empty, true)); - } - else - { - foreach (var index in VertexShaders) - SamplerIds.UnionWith(AssociatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); - foreach (var index in PixelShaders) - SamplerIds.UnionWith(AssociatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); - if (!ShadersKnown) - { - SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.HasTable) - SamplerIds.Add(TableSamplerId); - } - - foreach (var samplerId in SamplerIds) - { - var shpkSampler = AssociatedShpk.GetSamplerById(samplerId); - if (shpkSampler is not { Slot: 2 }) - continue; - - var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); - var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); - - var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); - Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, - dkData?.Description ?? string.Empty, !hasDkLabel)); - } - - if (SamplerIds.Contains(TableSamplerId)) - Mtrl.HasTable = true; - } - - Textures.Sort((x, y) => string.CompareOrdinal(x.Label, y.Label)); - - TextureLabelWidth = 50f * UiHelpers.Scale; - - float helpWidth; - using (var _ = ImRaii.PushFont(UiBuilder.IconFont)) - { - helpWidth = ImGui.GetStyle().ItemSpacing.X + ImGui.CalcTextSize(FontAwesomeIcon.InfoCircle.ToIconString()).X; - } - - foreach (var (label, _, _, description, monoFont) in Textures) - { - if (!monoFont) - TextureLabelWidth = Math.Max(TextureLabelWidth, ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); - } - - using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) - { - foreach (var (label, _, _, description, monoFont) in Textures) - { - if (monoFont) - TextureLabelWidth = Math.Max(TextureLabelWidth, - ImGui.CalcTextSize(label).X + (description.Length > 0 ? helpWidth : 0.0f)); - } - } - - TextureLabelWidth = TextureLabelWidth / UiHelpers.Scale + 4; - } - - private void UpdateConstants() - { - static List FindOrAddGroup(List<(string, List)> groups, string name) - { - foreach (var (groupName, group) in groups) - { - if (string.Equals(name, groupName, StringComparison.Ordinal)) - return group; - } - - var newGroup = new List(16); - groups.Add((name, newGroup)); - return newGroup; - } - - Constants.Clear(); - if (AssociatedShpk == null) - { - var fcGroup = FindOrAddGroup(Constants, "Further Constants"); - foreach (var (constant, index) in Mtrl.ShaderPackage.Constants.WithIndex()) - { - var values = Mtrl.GetConstantValues(constant); - for (var i = 0; i < values.Length; i += 4) - { - fcGroup.Add(($"0x{constant.Id:X8}", index, i..Math.Min(i + 4, values.Length), string.Empty, true, - FloatConstantEditor.Default)); - } - } - } - else - { - var prefix = AssociatedShpk.GetConstantById(MaterialParamsConstantId)?.Name ?? string.Empty; - foreach (var shpkConstant in AssociatedShpk.MaterialParams) - { - if ((shpkConstant.ByteSize & 0x3) != 0) - continue; - - var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, shpkConstant.ByteSize >> 2, out var constantIndex); - var values = Mtrl.GetConstantValues(constant); - var handledElements = new IndexSet(values.Length, false); - - var dkData = TryGetShpkDevkitData("Constants", shpkConstant.Id, true); - if (dkData != null) - foreach (var dkConstant in dkData) - { - var offset = (int)dkConstant.Offset; - var length = values.Length - offset; - if (dkConstant.Length.HasValue) - length = Math.Min(length, (int)dkConstant.Length.Value); - if (length <= 0) - continue; - - var editor = dkConstant.CreateEditor(); - if (editor != null) - FindOrAddGroup(Constants, dkConstant.Group.Length > 0 ? dkConstant.Group : "Further Constants") - .Add((dkConstant.Label, constantIndex, offset..(offset + length), dkConstant.Description, false, editor)); - handledElements.AddRange(offset, length); - } - - var fcGroup = FindOrAddGroup(Constants, "Further Constants"); - foreach (var (start, end) in handledElements.Ranges(complement:true)) - { - if ((shpkConstant.ByteOffset & 0x3) == 0) - { - var offset = shpkConstant.ByteOffset >> 2; - for (int i = (start & ~0x3) - (offset & 0x3), j = offset >> 2; i < end; i += 4, ++j) - { - var rangeStart = Math.Max(i, start); - var rangeEnd = Math.Min(i + 4, end); - if (rangeEnd > rangeStart) - fcGroup.Add(( - $"{prefix}[{j:D2}]{VectorSwizzle((offset + rangeStart) & 0x3, (offset + rangeEnd - 1) & 0x3)} (0x{shpkConstant.Id:X8})", - constantIndex, rangeStart..rangeEnd, string.Empty, true, FloatConstantEditor.Default)); - } - } - else - { - for (var i = start; i < end; i += 4) - { - fcGroup.Add(($"0x{shpkConstant.Id:X8}", constantIndex, i..Math.Min(i + 4, end), string.Empty, true, - FloatConstantEditor.Default)); - } - } - } - } - } - - Constants.RemoveAll(group => group.Constants.Count == 0); - Constants.Sort((x, y) => - { - if (string.Equals(x.Header, "Further Constants", StringComparison.Ordinal)) - return 1; - if (string.Equals(y.Header, "Further Constants", StringComparison.Ordinal)) - return -1; - - return string.Compare(x.Header, y.Header, StringComparison.Ordinal); - }); - // HACK the Replace makes w appear after xyz, for the cbuffer-location-based naming scheme - foreach (var (_, group) in Constants) - { - group.Sort((x, y) => string.CompareOrdinal( - x.MonoFont ? x.Label.Replace("].w", "].{") : x.Label, - y.MonoFont ? y.Label.Replace("].w", "].{") : y.Label)); - } - } - - public unsafe void BindToMaterialInstances() - { - UnbindFromMaterialInstances(); - - var instances = MaterialInfo.FindMaterials(_edit._resourceTreeFactory.GetLocalPlayerRelatedCharacters().Select(ch => ch.Address), - FilePath); - - var foundMaterials = new HashSet(); - foreach (var materialInfo in instances) - { - var material = materialInfo.GetDrawObjectMaterial(_edit._objects); - if (foundMaterials.Contains((nint)material)) - continue; - - try - { - MaterialPreviewers.Add(new LiveMaterialPreviewer(_edit._objects, materialInfo)); - foundMaterials.Add((nint)material); - } - catch (InvalidOperationException) - { - // Carry on without that previewer. - } - } - - UpdateMaterialPreview(); - - if (!Mtrl.HasTable) - return; - - foreach (var materialInfo in instances) - { - try - { - ColorTablePreviewers.Add(new LiveColorTablePreviewer(_edit._objects, _edit._framework, materialInfo)); - } - catch (InvalidOperationException) - { - // Carry on without that previewer. - } - } - - UpdateColorTablePreview(); - } - - private void UnbindFromMaterialInstances() - { - foreach (var previewer in MaterialPreviewers) - previewer.Dispose(); - MaterialPreviewers.Clear(); - - foreach (var previewer in ColorTablePreviewers) - previewer.Dispose(); - ColorTablePreviewers.Clear(); - } - - private unsafe void UnbindFromDrawObjectMaterialInstances(CharacterBase* characterBase) - { - for (var i = MaterialPreviewers.Count; i-- > 0;) - { - var previewer = MaterialPreviewers[i]; - if (previewer.DrawObject != characterBase) - continue; - - previewer.Dispose(); - MaterialPreviewers.RemoveAt(i); - } - - for (var i = ColorTablePreviewers.Count; i-- > 0;) - { - var previewer = ColorTablePreviewers[i]; - if (previewer.DrawObject != characterBase) - continue; - - previewer.Dispose(); - ColorTablePreviewers.RemoveAt(i); - } - } - - public void SetShaderPackageFlags(uint shPkFlags) - { - foreach (var previewer in MaterialPreviewers) - previewer.SetShaderPackageFlags(shPkFlags); - } - - public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) - { - foreach (var previewer in MaterialPreviewers) - previewer.SetMaterialParameter(parameterCrc, offset, value); - } - - public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) - { - foreach (var previewer in MaterialPreviewers) - previewer.SetSamplerFlags(samplerCrc, samplerFlags); - } - - private void UpdateMaterialPreview() - { - SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); - foreach (var constant in Mtrl.ShaderPackage.Constants) - { - var values = Mtrl.GetConstantValues(constant); - if (values != null) - SetMaterialParameter(constant.Id, 0, values); - } - - foreach (var sampler in Mtrl.ShaderPackage.Samplers) - SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - public void HighlightColorTableRow(int rowIdx) - { - var oldRowIdx = HighlightedColorTableRow; - - if (HighlightedColorTableRow != rowIdx) - { - HighlightedColorTableRow = rowIdx; - HighlightTime.Restart(); - } - - if (oldRowIdx >= 0) - UpdateColorTableRowPreview(oldRowIdx); - if (rowIdx >= 0) - UpdateColorTableRowPreview(rowIdx); - } - - public void CancelColorTableHighlight() - { - var rowIdx = HighlightedColorTableRow; - - HighlightedColorTableRow = -1; - HighlightTime.Reset(); - - if (rowIdx >= 0) - UpdateColorTableRowPreview(rowIdx); - } - - public void UpdateColorTableRowPreview(int rowIdx) - { - if (ColorTablePreviewers.Count == 0) - return; - - if (!Mtrl.HasTable) - return; - - var row = new LegacyColorTableRow(Mtrl.Table[rowIdx]); - if (Mtrl.HasDyeTable) - { - var stm = _edit._stainService.StmFile; - var dye = new LegacyColorDyeTableRow(Mtrl.DyeTable[rowIdx]); - if (stm.TryGetValue(dye.Template, _edit._stainService.StainCombo.CurrentSelection.Key, out var dyes)) - row.ApplyDyeTemplate(dye, dyes); - } - - if (HighlightedColorTableRow == rowIdx) - ApplyHighlight(ref row, (float)HighlightTime.Elapsed.TotalSeconds); - - foreach (var previewer in ColorTablePreviewers) - { - row.AsHalves().CopyTo(previewer.ColorTable.AsSpan() - .Slice(LiveColorTablePreviewer.TextureWidth * 4 * rowIdx, LiveColorTablePreviewer.TextureWidth * 4)); - previewer.ScheduleUpdate(); - } - } - - public void UpdateColorTablePreview() - { - if (ColorTablePreviewers.Count == 0) - return; - - if (!Mtrl.HasTable) - return; - - var rows = new LegacyColorTable(Mtrl.Table); - var dyeRows = new LegacyColorDyeTable(Mtrl.DyeTable); - if (Mtrl.HasDyeTable) - { - var stm = _edit._stainService.StmFile; - var stainId = (StainId)_edit._stainService.StainCombo.CurrentSelection.Key; - for (var i = 0; i < LegacyColorTable.NumUsedRows; ++i) - { - ref var row = ref rows[i]; - var dye = dyeRows[i]; - if (stm.TryGetValue(dye.Template, stainId, out var dyes)) - row.ApplyDyeTemplate(dye, dyes); - } - } - - if (HighlightedColorTableRow >= 0) - ApplyHighlight(ref rows[HighlightedColorTableRow], (float)HighlightTime.Elapsed.TotalSeconds); - - foreach (var previewer in ColorTablePreviewers) - { - // TODO: Dawntrail - rows.AsHalves().CopyTo(previewer.ColorTable); - previewer.ScheduleUpdate(); - } - } - - private static void ApplyHighlight(ref LegacyColorTableRow row, float time) - { - var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; - var baseColor = ColorId.InGameHighlight.Value(); - var color = level * new Vector3(baseColor & 0xFF, (baseColor >> 8) & 0xFF, (baseColor >> 16) & 0xFF); - - row.Diffuse = Vector3.Zero; - row.Specular = Vector3.Zero; - row.Emissive = color * color; - } - - public void Update() - { - UpdateShaders(); - UpdateTextures(); - UpdateConstants(); - } - - public unsafe MtrlTab(ModEditWindow edit, MtrlFile file, string filePath, bool writable) - { - _edit = edit; - Mtrl = file; - FilePath = filePath; - Writable = writable; - AssociatedBaseDevkit = TryLoadShpkDevkit("_base", out LoadedBaseDevkitPathName); - LoadShpk(FindAssociatedShpk(out _, out _)); - if (writable) - { - _edit._characterBaseDestructor.Subscribe(UnbindFromDrawObjectMaterialInstances, CharacterBaseDestructor.Priority.MtrlTab); - BindToMaterialInstances(); - } - } - - public unsafe void Dispose() - { - UnbindFromMaterialInstances(); - if (Writable) - _edit._characterBaseDestructor.Unsubscribe(UnbindFromDrawObjectMaterialInstances); - } - - // TODO Readd ShadersKnown - public bool Valid - => (true || ShadersKnown) && Mtrl.Valid; - - public byte[] Write() - { - var output = Mtrl.Clone(); - output.GarbageCollect(AssociatedShpk, SamplerIds); - - return output.Write(); - } - - private sealed class DevkitShaderKeyValue - { - public string Label = string.Empty; - public string Description = string.Empty; - } - - private sealed class DevkitShaderKey - { - public string Label = string.Empty; - public string Description = string.Empty; - public Dictionary Values = new(); - } - - private sealed class DevkitSampler - { - public string Label = string.Empty; - public string Description = string.Empty; - public string DefaultTexture = string.Empty; - } - - private enum DevkitConstantType - { - Hidden = -1, - Float = 0, - Integer = 1, - Color = 2, - Enum = 3, - } - - private sealed class DevkitConstantValue - { - public string Label = string.Empty; - public string Description = string.Empty; - public float Value = 0; - } - - private sealed class DevkitConstant - { - public uint Offset = 0; - public uint? Length = null; - public string Group = string.Empty; - public string Label = string.Empty; - public string Description = string.Empty; - public DevkitConstantType Type = DevkitConstantType.Float; - - public float? Minimum = null; - public float? Maximum = null; - public float? Speed = null; - public float RelativeSpeed = 0.0f; - public float Factor = 1.0f; - public float Bias = 0.0f; - public byte Precision = 3; - public string Unit = string.Empty; - - public bool SquaredRgb = false; - public bool Clamped = false; - - public DevkitConstantValue[] Values = Array.Empty(); - - public IConstantEditor? CreateEditor() - => Type switch - { - DevkitConstantType.Hidden => null, - DevkitConstantType.Float => new FloatConstantEditor(Minimum, Maximum, Speed ?? 0.1f, RelativeSpeed, Factor, Bias, Precision, - Unit), - DevkitConstantType.Integer => new IntConstantEditor(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, - Factor, Bias, Unit), - DevkitConstantType.Color => new ColorConstantEditor(SquaredRgb, Clamped), - DevkitConstantType.Enum => new EnumConstantEditor(Array.ConvertAll(Values, - value => (value.Label, value.Value, value.Description))), - _ => FloatConstantEditor.Default, - }; - - private static int? ToInteger(float? value) - => value.HasValue ? (int)Math.Clamp(MathF.Round(value.Value), int.MinValue, int.MaxValue) : null; - } - } -} From f3ab1ddbb48f8e1bab94c59d7628b83ed9d29ba8 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 4 Aug 2024 22:27:34 +0200 Subject: [PATCH 0839/1381] Add game data file status to support info --- Penumbra/Penumbra.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index dbe06803..557e011c 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -46,6 +46,7 @@ public class Penumbra : IDalamudPlugin private readonly CharacterUtility _characterUtility; private readonly RedrawService _redrawService; private readonly CommunicatorService _communicatorService; + private readonly IDataManager _gameData; private PenumbraWindowSystem? _windowSystem; private bool _disposed; @@ -78,6 +79,7 @@ public class Penumbra : IDalamudPlugin _tempCollections = _services.GetService(); _redrawService = _services.GetService(); _communicatorService = _services.GetService(); + _gameData = _services.GetService(); _services.GetService(); // Initialize because not required anywhere else. _services.GetService(); // Initialize because not required anywhere else. _collectionManager.Caches.CreateNecessaryCaches(); @@ -217,6 +219,7 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Root Directory: `** `{_config.ModDirectory}`, {(exists ? "Exists" : "Not Existing")}\n"); sb.Append( $"> **`Free Drive Space: `** {(drive != null ? Functions.HumanReadableSize(drive.AvailableFreeSpace) : "Unknown")}\n"); + sb.Append($"> **`Game Data Files: `** {(_gameData.HasModifiedGameDataFiles ? "Modified" : "Pristine")}\n"); sb.Append($"> **`Auto-Deduplication: `** {_config.AutoDeduplicateOnImport}\n"); sb.Append($"> **`Auto-UI-Reduplication: `** {_config.AutoReduplicateUiOnImport}\n"); sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); From f8b034c42d14c038ed79183a37bee8262b9c8a7b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 4 Aug 2024 22:48:15 +0200 Subject: [PATCH 0840/1381] Auto-formatting, generous application of ImUtf8, minor cleanups. --- .../Materials/MtrlTab.ColorTable.cs | 246 +++++++++++------- .../Materials/MtrlTab.CommonColorTable.cs | 142 ++++++---- .../Materials/MtrlTab.Constants.cs | 29 ++- .../Materials/MtrlTab.Devkit.cs | 50 ++-- .../Materials/MtrlTab.LegacyColorTable.cs | 6 +- .../Materials/MtrlTab.LivePreview.cs | 129 ++++----- .../Materials/MtrlTab.ShaderPackage.cs | 218 ++++++++-------- .../Materials/MtrlTab.Textures.cs | 29 ++- .../UI/AdvancedWindow/Materials/MtrlTab.cs | 40 +-- .../Materials/MtrlTabFactory.cs | 13 +- .../AdvancedWindow/ModEditWindow.Materials.cs | 21 +- .../ModEditWindow.ShaderPackages.cs | 179 +++++++------ .../AdvancedWindow/ModEditWindow.ShpkTab.cs | 62 ++--- 13 files changed, 647 insertions(+), 517 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index dc87ec41..352681bb 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -13,7 +13,7 @@ public partial class MtrlTab { private const float ColorTableScalarSize = 65.0f; - private int _colorTableSelectedPair = 0; + private int _colorTableSelectedPair; private bool DrawColorTable(ColorTable table, ColorDyeTable? dyeTable, bool disabled) { @@ -23,25 +23,27 @@ public partial class MtrlTab private void DrawColorTablePairSelector(ColorTable table, bool disabled) { + var style = ImGui.GetStyle(); + var itemSpacing = style.ItemSpacing.X; + var itemInnerSpacing = style.ItemInnerSpacing.X; + var framePadding = style.FramePadding; + var buttonWidth = (ImGui.GetContentRegionAvail().X - itemSpacing * 7.0f) * 0.125f; + var frameHeight = ImGui.GetFrameHeight(); + var highlighterSize = ImUtf8.CalcIconSize(FontAwesomeIcon.Crosshairs) + framePadding * 2.0f; + var spaceWidth = ImUtf8.CalcTextSize(" "u8).X; + var spacePadding = (int)MathF.Ceiling((highlighterSize.X + framePadding.X + itemInnerSpacing) / spaceWidth); + using var font = ImRaii.PushFont(UiBuilder.MonoFont); using var alignment = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); - var style = ImGui.GetStyle(); - var itemSpacing = style.ItemSpacing.X; - var itemInnerSpacing = style.ItemInnerSpacing.X; - var framePadding = style.FramePadding; - var buttonWidth = (ImGui.GetContentRegionAvail().X - itemSpacing * 7.0f) * 0.125f; - var frameHeight = ImGui.GetFrameHeight(); - var highlighterSize = ImUtf8.CalcIconSize(FontAwesomeIcon.Crosshairs) + framePadding * 2.0f; - var spaceWidth = ImUtf8.CalcTextSize(" "u8).X; - var spacePadding = (int)MathF.Ceiling((highlighterSize.X + framePadding.X + itemInnerSpacing) / spaceWidth); for (var i = 0; i < ColorTable.NumRows >> 1; i += 8) { for (var j = 0; j < 8; ++j) { var pairIndex = i + j; - using (var color = ImRaii.PushColor(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.ButtonActive), pairIndex == _colorTableSelectedPair)) + using (ImRaii.PushColor(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.ButtonActive), pairIndex == _colorTableSelectedPair)) { - if (ImUtf8.Button($"#{pairIndex + 1}".PadLeft(3 + spacePadding), new Vector2(buttonWidth, ImGui.GetFrameHeightWithSpacing() + frameHeight))) + if (ImUtf8.Button($"#{pairIndex + 1}".PadLeft(3 + spacePadding), + new Vector2(buttonWidth, ImGui.GetFrameHeightWithSpacing() + frameHeight))) _colorTableSelectedPair = pairIndex; } @@ -79,12 +81,10 @@ public partial class MtrlTab private bool DrawColorTablePairEditor(ColorTable table, ColorDyeTable? dyeTable, bool disabled) { - var retA = false; - var retB = false; - ref var rowA = ref table[_colorTableSelectedPair << 1]; - ref var rowB = ref table[(_colorTableSelectedPair << 1) | 1]; - var dyeA = dyeTable != null ? dyeTable[_colorTableSelectedPair << 1] : default; - var dyeB = dyeTable != null ? dyeTable[(_colorTableSelectedPair << 1) | 1] : default; + var retA = false; + var retB = false; + var dyeA = dyeTable?[_colorTableSelectedPair << 1] ?? default; + var dyeB = dyeTable?[(_colorTableSelectedPair << 1) | 1] ?? default; var previewDyeA = _stainService.GetStainCombo(dyeA.Channel).CurrentSelection.Key; var previewDyeB = _stainService.GetStainCombo(dyeB.Channel).CurrentSelection.Key; var dyePackA = _stainService.GudStmFile.GetValueOrNull(dyeA.Template, previewDyeA); @@ -108,68 +108,96 @@ public partial class MtrlTab using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("ColorsA"u8)) + using (ImUtf8.PushId("ColorsA"u8)) + { retA |= DrawColors(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + columns.Next(); - using (var id = ImUtf8.PushId("ColorsB"u8)) + using (ImUtf8.PushId("ColorsB"u8)) + { retB |= DrawColors(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } } DrawHeader(" Physical Parameters"u8); using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("PbrA"u8)) + using (ImUtf8.PushId("PbrA"u8)) + { retA |= DrawPbr(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + columns.Next(); - using (var id = ImUtf8.PushId("PbrB"u8)) + using (ImUtf8.PushId("PbrB"u8)) + { retB |= DrawPbr(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } } DrawHeader(" Sheen Layer Parameters"u8); using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("SheenA"u8)) + using (ImUtf8.PushId("SheenA"u8)) + { retA |= DrawSheen(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + columns.Next(); - using (var id = ImUtf8.PushId("SheenB"u8)) + using (ImUtf8.PushId("SheenB"u8)) + { retB |= DrawSheen(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } } DrawHeader(" Pair Blending"u8); using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("BlendingA"u8)) + using (ImUtf8.PushId("BlendingA"u8)) + { retA |= DrawBlending(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + columns.Next(); - using (var id = ImUtf8.PushId("BlendingB"u8)) + using (ImUtf8.PushId("BlendingB"u8)) + { retB |= DrawBlending(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } } DrawHeader(" Material Template"u8); using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("TemplateA"u8)) + using (ImUtf8.PushId("TemplateA"u8)) + { retA |= DrawTemplate(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + columns.Next(); - using (var id = ImUtf8.PushId("TemplateB"u8)) + using (ImUtf8.PushId("TemplateB"u8)) + { retB |= DrawTemplate(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } } if (dyeTable != null) { DrawHeader(" Dye Properties"u8); - using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) + using var columns = ImUtf8.Columns(2, "ColorTable"u8); + using var dis = ImRaii.Disabled(disabled); + using (ImUtf8.PushId("DyeA"u8)) { - using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("DyeA"u8)) - retA |= DrawDye(dyeTable, dyePackA, _colorTableSelectedPair << 1); - columns.Next(); - using (var id = ImUtf8.PushId("DyeB"u8)) - retB |= DrawDye(dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retA |= DrawDye(dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + + columns.Next(); + using (ImUtf8.PushId("DyeB"u8)) + { + retB |= DrawDye(dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); } } @@ -177,11 +205,16 @@ public partial class MtrlTab using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { using var dis = ImRaii.Disabled(disabled); - using (var id = ImUtf8.PushId("FurtherA"u8)) + using (ImUtf8.PushId("FurtherA"u8)) + { retA |= DrawFurther(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + } + columns.Next(); - using (var id = ImUtf8.PushId("FurtherB"u8)) + using (ImUtf8.PushId("FurtherB"u8)) + { retB |= DrawFurther(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + } } if (retA) @@ -195,18 +228,21 @@ public partial class MtrlTab /// Padding styles do not seem to apply to this component. It is recommended to prepend two spaces. private static void DrawHeader(ReadOnlySpan label) { - var headerColor = ImGui.GetColorU32(ImGuiCol.Header); - using var _ = ImRaii.PushColor(ImGuiCol.HeaderHovered, headerColor).Push(ImGuiCol.HeaderActive, headerColor); + var headerColor = ImGui.GetColorU32(ImGuiCol.Header); + using var _ = ImRaii.PushColor(ImGuiCol.HeaderHovered, headerColor).Push(ImGuiCol.HeaderActive, headerColor); ImUtf8.CollapsingHeader(label, ImGuiTreeNodeFlags.Leaf); } private static bool DrawColors(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) { - var dyeOffset = ImGui.GetContentRegionAvail().X + ImGui.GetStyle().ItemSpacing.X - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() * 2.0f; + var dyeOffset = ImGui.GetContentRegionAvail().X + + ImGui.GetStyle().ItemSpacing.X + - ImGui.GetStyle().ItemInnerSpacing.X + - ImGui.GetFrameHeight() * 2.0f; - var ret = false; + var ret = false; ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; ret |= CtColorPicker("Diffuse Color"u8, default, row.DiffuseColor, c => table[rowIdx].DiffuseColor = c); @@ -247,13 +283,17 @@ public partial class MtrlTab private static bool DrawBlending(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) { var scalarSize = ColorTableScalarSize * UiHelpers.Scale; - var dyeOffset = ImGui.GetContentRegionAvail().X + ImGui.GetStyle().ItemSpacing.X - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + var dyeOffset = ImGui.GetContentRegionAvail().X + + ImGui.GetStyle().ItemSpacing.X + - ImGui.GetStyle().ItemInnerSpacing.X + - ImGui.GetFrameHeight() + - scalarSize; var isRowB = (rowIdx & 1) != 0; - var ret = false; + var ret = false; ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; ImGui.SetNextItemWidth(scalarSize); ret |= CtDragHalf(isRowB ? "Field #19"u8 : "Anisotropy Degree"u8, default, row.Anisotropy, "%.2f"u8, 0.0f, HalfMaxValue, 0.1f, @@ -261,11 +301,13 @@ public partial class MtrlTab if (dyeTable != null) { ImGui.SameLine(dyeOffset); - ret |= CtApplyStainCheckbox("##dyeAnisotropy"u8, isRowB ? "Apply Field #19 on Dye"u8 : "Apply Anisotropy Degree on Dye"u8, dye.Anisotropy, + ret |= CtApplyStainCheckbox("##dyeAnisotropy"u8, isRowB ? "Apply Field #19 on Dye"u8 : "Apply Anisotropy Degree on Dye"u8, + dye.Anisotropy, b => dyeTable[rowIdx].Anisotropy = b); ImUtf8.SameLineInner(); ImGui.SetNextItemWidth(scalarSize); - CtDragHalf("##dyePreviewAnisotropy"u8, isRowB ? "Dye Preview for Field #19"u8 : "Dye Preview for Anisotropy Degree"u8, dyePack?.Anisotropy, "%.2f"u8); + CtDragHalf("##dyePreviewAnisotropy"u8, isRowB ? "Dye Preview for Field #19"u8 : "Dye Preview for Anisotropy Degree"u8, + dyePack?.Anisotropy, "%.2f"u8); } return ret; @@ -276,11 +318,11 @@ public partial class MtrlTab var scalarSize = ColorTableScalarSize * UiHelpers.Scale; var itemSpacing = ImGui.GetStyle().ItemSpacing.X; var dyeOffset = ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize - 64.0f; - var subcolWidth = CalculateSubcolumnWidth(2); + var subColWidth = CalculateSubColumnWidth(2); - var ret = false; + var ret = false; ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; ImGui.SetNextItemWidth(scalarSize); ret |= CtDragScalar("Shader ID"u8, default, row.ShaderId, "%d"u8, (ushort)0, (ushort)255, 0.25f, @@ -306,13 +348,15 @@ public partial class MtrlTab ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() with { Y = cursor.Y }); ImGui.SetNextItemWidth(scalarSize + itemSpacing + 64.0f); using var dis = ImRaii.Disabled(); - CtSphereMapIndexPicker("###SphereMapIndexDye"u8, "Dye Preview for Sphere Map"u8, dyePack?.SphereMapIndex ?? ushort.MaxValue, false, Nop); + CtSphereMapIndexPicker("###SphereMapIndexDye"u8, "Dye Preview for Sphere Map"u8, dyePack?.SphereMapIndex ?? ushort.MaxValue, false, + Nop); } ImGui.Dummy(new Vector2(64.0f, 0.0f)); ImGui.SameLine(); ImGui.SetNextItemWidth(scalarSize); - ret |= CtDragScalar("Sphere Map Intensity"u8, default, (float)row.SphereMapMask * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + ret |= CtDragScalar("Sphere Map Intensity"u8, default, (float)row.SphereMapMask * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, + HalfMaxValue * 100.0f, 1.0f, v => table[rowIdx].SphereMapMask = (Half)(v * 0.01f)); if (dyeTable != null) { @@ -326,10 +370,10 @@ public partial class MtrlTab ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - var leftLineHeight = 64.0f + ImGui.GetStyle().FramePadding.Y * 2.0f; + var leftLineHeight = 64.0f + ImGui.GetStyle().FramePadding.Y * 2.0f; var rightLineHeight = 3.0f * ImGui.GetFrameHeight() + 2.0f * ImGui.GetStyle().ItemSpacing.Y; - var lineHeight = Math.Max(leftLineHeight, rightLineHeight); - var cursorPos = ImGui.GetCursorScreenPos(); + var lineHeight = Math.Max(leftLineHeight, rightLineHeight); + var cursorPos = ImGui.GetCursorScreenPos(); ImGui.SetCursorScreenPos(cursorPos + new Vector2(0.0f, (lineHeight - leftLineHeight) * 0.5f)); ImGui.SetNextItemWidth(scalarSize + (itemSpacing + 64.0f) * 2.0f); ret |= CtTileIndexPicker("###TileIndex"u8, default, row.TileIndex, false, @@ -337,9 +381,10 @@ public partial class MtrlTab ImUtf8.SameLineInner(); ImUtf8.Text("Tile"u8); - ImGui.SameLine(subcolWidth); - ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() with { Y = cursorPos.Y + (lineHeight - rightLineHeight) * 0.5f, }); - using (var cld = ImUtf8.Child("###TileProperties"u8, new(ImGui.GetContentRegionAvail().X, float.Lerp(rightLineHeight, lineHeight, 0.5f)), false)) + ImGui.SameLine(subColWidth); + ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() with { Y = cursorPos.Y + (lineHeight - rightLineHeight) * 0.5f }); + using (ImUtf8.Child("###TileProperties"u8, + new Vector2(ImGui.GetContentRegionAvail().X, float.Lerp(rightLineHeight, lineHeight, 0.5f)))) { ImGui.Dummy(new Vector2(scalarSize, 0.0f)); ImUtf8.SameLineInner(); @@ -350,7 +395,8 @@ public partial class MtrlTab ret |= CtTileTransformMatrix(row.TileTransform, scalarSize, true, m => table[rowIdx].TileTransform = m); ImUtf8.SameLineInner(); - ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() - new Vector2(0.0f, (ImGui.GetFrameHeight() + ImGui.GetStyle().ItemSpacing.Y) * 0.5f)); + ImGui.SetCursorScreenPos(ImGui.GetCursorScreenPos() + - new Vector2(0.0f, (ImGui.GetFrameHeight() + ImGui.GetStyle().ItemSpacing.Y) * 0.5f)); ImUtf8.Text("Tile Transform"u8); } @@ -360,15 +406,20 @@ public partial class MtrlTab private static bool DrawPbr(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) { var scalarSize = ColorTableScalarSize * UiHelpers.Scale; - var subcolWidth = CalculateSubcolumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; - var dyeOffset = subcolWidth - ImGui.GetStyle().ItemSpacing.X * 2.0f - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + var subColWidth = CalculateSubColumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = subColWidth + - ImGui.GetStyle().ItemSpacing.X * 2.0f + - ImGui.GetStyle().ItemInnerSpacing.X + - ImGui.GetFrameHeight() + - scalarSize; - var ret = false; + var ret = false; ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; ImGui.SetNextItemWidth(scalarSize); - ret |= CtDragScalar("Roughness"u8, default, (float)row.Roughness * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + ret |= CtDragScalar("Roughness"u8, default, (float)row.Roughness * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, + 1.0f, v => table[rowIdx].Roughness = (Half)(v * 0.01f)); if (dyeTable != null) { @@ -380,13 +431,14 @@ public partial class MtrlTab CtDragScalar("##dyePreviewRoughness"u8, "Dye Preview for Roughness"u8, (float?)dyePack?.Roughness * 100.0f, "%.0f%%"u8); } - ImGui.SameLine(subcolWidth); + ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); - ret |= CtDragScalar("Metalness"u8, default, (float)row.Metalness * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + ret |= CtDragScalar("Metalness"u8, default, (float)row.Metalness * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, + 1.0f, v => table[rowIdx].Metalness = (Half)(v * 0.01f)); if (dyeTable != null) { - ImGui.SameLine(subcolWidth + dyeOffset); + ImGui.SameLine(subColWidth + dyeOffset); ret |= CtApplyStainCheckbox("##dyeMetalness"u8, "Apply Metalness on Dye"u8, dye.Metalness, b => dyeTable[rowIdx].Metalness = b); ImUtf8.SameLineInner(); @@ -400,12 +452,16 @@ public partial class MtrlTab private static bool DrawSheen(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) { var scalarSize = ColorTableScalarSize * UiHelpers.Scale; - var subcolWidth = CalculateSubcolumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; - var dyeOffset = subcolWidth - ImGui.GetStyle().ItemSpacing.X * 2.0f - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + var subColWidth = CalculateSubColumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = subColWidth + - ImGui.GetStyle().ItemSpacing.X * 2.0f + - ImGui.GetStyle().ItemInnerSpacing.X + - ImGui.GetFrameHeight() + - scalarSize; - var ret = false; + var ret = false; ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; ImGui.SetNextItemWidth(scalarSize); ret |= CtDragScalar("Sheen"u8, default, (float)row.SheenRate * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, @@ -420,13 +476,14 @@ public partial class MtrlTab CtDragScalar("##dyePreviewSheenRate"u8, "Dye Preview for Sheen"u8, (float?)dyePack?.SheenRate * 100.0f, "%.0f%%"u8); } - ImGui.SameLine(subcolWidth); + ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); - ret |= CtDragScalar("Sheen Tint"u8, default, (float)row.SheenTintRate * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, HalfMaxValue * 100.0f, 1.0f, + ret |= CtDragScalar("Sheen Tint"u8, default, (float)row.SheenTintRate * 100.0f, "%.0f%%"u8, HalfMinValue * 100.0f, + HalfMaxValue * 100.0f, 1.0f, v => table[rowIdx].SheenTintRate = (Half)(v * 0.01f)); if (dyeTable != null) { - ImGui.SameLine(subcolWidth + dyeOffset); + ImGui.SameLine(subColWidth + dyeOffset); ret |= CtApplyStainCheckbox("##dyeSheenTintRate"u8, "Apply Sheen Tint on Dye"u8, dye.SheenTintRate, b => dyeTable[rowIdx].SheenTintRate = b); ImUtf8.SameLineInner(); @@ -435,7 +492,8 @@ public partial class MtrlTab } ImGui.SetNextItemWidth(scalarSize); - ret |= CtDragScalar("Sheen Roughness"u8, default, 100.0f / (float)row.SheenAperture, "%.0f%%"u8, 100.0f / HalfMaxValue, 100.0f / HalfEpsilon, 1.0f, + ret |= CtDragScalar("Sheen Roughness"u8, default, 100.0f / (float)row.SheenAperture, "%.0f%%"u8, 100.0f / HalfMaxValue, + 100.0f / HalfEpsilon, 1.0f, v => table[rowIdx].SheenAperture = (Half)(100.0f / v)); if (dyeTable != null) { @@ -444,7 +502,8 @@ public partial class MtrlTab b => dyeTable[rowIdx].SheenAperture = b); ImUtf8.SameLineInner(); ImGui.SetNextItemWidth(scalarSize); - CtDragScalar("##dyePreviewSheenRoughness"u8, "Dye Preview for Sheen Roughness"u8, 100.0f / (float?)dyePack?.SheenAperture, "%.0f%%"u8); + CtDragScalar("##dyePreviewSheenRoughness"u8, "Dye Preview for Sheen Roughness"u8, 100.0f / (float?)dyePack?.SheenAperture, + "%.0f%%"u8); } return ret; @@ -453,12 +512,16 @@ public partial class MtrlTab private static bool DrawFurther(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) { var scalarSize = ColorTableScalarSize * UiHelpers.Scale; - var subcolWidth = CalculateSubcolumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; - var dyeOffset = subcolWidth - ImGui.GetStyle().ItemSpacing.X * 2.0f - ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() - scalarSize; + var subColWidth = CalculateSubColumnWidth(2) + ImGui.GetStyle().ItemSpacing.X; + var dyeOffset = subColWidth + - ImGui.GetStyle().ItemSpacing.X * 2.0f + - ImGui.GetStyle().ItemInnerSpacing.X + - ImGui.GetFrameHeight() + - scalarSize; - var ret = false; + var ret = false; ref var row = ref table[rowIdx]; - var dye = dyeTable != null ? dyeTable[rowIdx] : default; + var dye = dyeTable?[rowIdx] ?? default; ImGui.SetNextItemWidth(scalarSize); ret |= CtDragHalf("Field #11"u8, default, row.Scalar11, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, @@ -479,7 +542,7 @@ public partial class MtrlTab ret |= CtDragHalf("Field #3"u8, default, row.Scalar3, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, v => table[rowIdx].Scalar3 = v); - ImGui.SameLine(subcolWidth); + ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); ret |= CtDragHalf("Field #7"u8, default, row.Scalar7, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, v => table[rowIdx].Scalar7 = v); @@ -488,7 +551,7 @@ public partial class MtrlTab ret |= CtDragHalf("Field #15"u8, default, row.Scalar15, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, v => table[rowIdx].Scalar15 = v); - ImGui.SameLine(subcolWidth); + ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); ret |= CtDragHalf("Field #17"u8, default, row.Scalar17, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, v => table[rowIdx].Scalar17 = v); @@ -497,7 +560,7 @@ public partial class MtrlTab ret |= CtDragHalf("Field #20"u8, default, row.Scalar20, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, v => table[rowIdx].Scalar20 = v); - ImGui.SameLine(subcolWidth); + ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); ret |= CtDragHalf("Field #22"u8, default, row.Scalar22, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f, v => table[rowIdx].Scalar22 = v); @@ -513,33 +576,32 @@ public partial class MtrlTab { var scalarSize = ColorTableScalarSize * UiHelpers.Scale; var applyButtonWidth = ImUtf8.CalcTextSize("Apply Preview Dye"u8).X + ImGui.GetStyle().FramePadding.X * 2.0f; - var subcolWidth = CalculateSubcolumnWidth(2, applyButtonWidth); - - var ret = false; + var subColWidth = CalculateSubColumnWidth(2, applyButtonWidth); + + var ret = false; ref var dye = ref dyeTable[rowIdx]; ImGui.SetNextItemWidth(scalarSize); ret |= CtDragScalar("Dye Channel"u8, default, dye.Channel + 1, "%d"u8, 1, StainService.ChannelCount, 0.1f, value => dyeTable[rowIdx].Channel = (byte)(Math.Clamp(value, 1, StainService.ChannelCount) - 1)); - ImGui.SameLine(subcolWidth); + ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); if (_stainService.GudTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, - scalarSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) + scalarSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { dye.Template = _stainService.LegacyTemplateCombo.CurrentSelection; ret = true; } + ImUtf8.SameLineInner(); ImUtf8.Text("Dye Template"u8); ImGui.SameLine(ImGui.GetContentRegionAvail().X - applyButtonWidth + ImGui.GetStyle().ItemSpacing.X); using var dis = ImRaii.Disabled(!dyePack.HasValue); if (ImUtf8.Button("Apply Preview Dye"u8)) - { ret |= Mtrl.ApplyDyeToRow(_stainService.GudStmFile, [ _stainService.StainCombo1.CurrentSelection.Key, _stainService.StainCombo2.CurrentSelection.Key, ], rowIdx); - } return ret; } @@ -554,9 +616,9 @@ public partial class MtrlTab ImGui.TextUnformatted(text); } - private static float CalculateSubcolumnWidth(int numSubcolumns, float reservedSpace = 0.0f) + private static float CalculateSubColumnWidth(int numSubColumns, float reservedSpace = 0.0f) { var itemSpacing = ImGui.GetStyle().ItemSpacing.X; - return (ImGui.GetContentRegionAvail().X - reservedSpace - itemSpacing * (numSubcolumns - 1)) / numSubcolumns + itemSpacing; + return (ImGui.GetContentRegionAvail().X - reservedSpace - itemSpacing * (numSubColumns - 1)) / numSubColumns + itemSpacing; } } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index 2b093e23..09c8ea61 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -12,9 +12,9 @@ namespace Penumbra.UI.AdvancedWindow.Materials; public partial class MtrlTab { - private static readonly float HalfMinValue = (float)Half.MinValue; - private static readonly float HalfMaxValue = (float)Half.MaxValue; - private static readonly float HalfEpsilon = (float)Half.Epsilon; + private static readonly float HalfMinValue = (float)Half.MinValue; + private static readonly float HalfMaxValue = (float)Half.MaxValue; + private static readonly float HalfEpsilon = (float)Half.Epsilon; private static readonly FontAwesomeCheckbox ApplyStainCheckbox = new(FontAwesomeIcon.FillDrip); @@ -22,11 +22,11 @@ public partial class MtrlTab private bool DrawColorTableSection(bool disabled) { - if ((!ShpkLoading && !SamplerIds.Contains(ShpkFile.TableSamplerId)) || Mtrl.Table == null) + if (!_shpkLoading && !SamplerIds.Contains(ShpkFile.TableSamplerId) || Mtrl.Table == null) return false; ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (!ImGui.CollapsingHeader("Color Table", ImGuiTreeNodeFlags.DefaultOpen)) + if (!ImUtf8.CollapsingHeader("Color Table"u8, ImGuiTreeNodeFlags.DefaultOpen)) return false; ColorTableCopyAllClipboardButton(); @@ -35,7 +35,7 @@ public partial class MtrlTab if (!disabled) { ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImUtf8.IconDummy(); ImGui.SameLine(); ret |= ColorTableDyeableCheckbox(); } @@ -43,17 +43,18 @@ public partial class MtrlTab if (Mtrl.DyeTable != null) { ImGui.SameLine(); - ImGui.Dummy(ImGuiHelpers.ScaledVector2(20, 0)); + ImUtf8.IconDummy(); ImGui.SameLine(); ret |= DrawPreviewDye(disabled); } ret |= Mtrl.Table switch { - LegacyColorTable legacyTable => DrawLegacyColorTable(legacyTable, Mtrl.DyeTable as LegacyColorDyeTable, disabled), - ColorTable table when Mtrl.ShaderPackage.Name is "characterlegacy.shpk" => DrawLegacyColorTable(table, Mtrl.DyeTable as ColorDyeTable, disabled), - ColorTable table => DrawColorTable(table, Mtrl.DyeTable as ColorDyeTable, disabled), - _ => false, + LegacyColorTable legacyTable => DrawLegacyColorTable(legacyTable, Mtrl.DyeTable as LegacyColorDyeTable, disabled), + ColorTable table when Mtrl.ShaderPackage.Name is "characterlegacy.shpk" => DrawLegacyColorTable(table, + Mtrl.DyeTable as ColorDyeTable, disabled), + ColorTable table => DrawColorTable(table, Mtrl.DyeTable as ColorDyeTable, disabled), + _ => false, }; return ret; @@ -64,7 +65,7 @@ public partial class MtrlTab if (Mtrl.Table == null) return; - if (!ImGui.Button("Export All Rows to Clipboard", ImGuiHelpers.ScaledVector2(200, 0))) + if (!ImUtf8.Button("Export All Rows to Clipboard"u8, ImGuiHelpers.ScaledVector2(200, 0))) return; try @@ -178,16 +179,18 @@ public partial class MtrlTab private bool ColorTableDyeableCheckbox() { var dyeable = Mtrl.DyeTable != null; - var ret = ImGui.Checkbox("Dyeable", ref dyeable); + var ret = ImUtf8.Checkbox("Dyeable"u8, ref dyeable); if (ret) { - Mtrl.DyeTable = dyeable ? Mtrl.Table switch - { - ColorTable => new ColorDyeTable(), - LegacyColorTable => new LegacyColorDyeTable(), - _ => null, - } : null; + Mtrl.DyeTable = dyeable + ? Mtrl.Table switch + { + ColorTable => new ColorDyeTable(), + LegacyColorTable => new LegacyColorDyeTable(), + _ => null, + } + : null; UpdateColorTablePreview(); } @@ -227,24 +230,27 @@ public partial class MtrlTab private void ColorTableHighlightButton(int pairIdx, bool disabled) { - ImUtf8.IconButton(FontAwesomeIcon.Crosshairs, "Highlight this pair of rows on your character, if possible.\n\nHighlight colors can be configured in Penumbra's settings."u8, - ImGui.GetFrameHeight() * Vector2.One, disabled || ColorTablePreviewers.Count == 0); + ImUtf8.IconButton(FontAwesomeIcon.Crosshairs, + "Highlight this pair of rows on your character, if possible.\n\nHighlight colors can be configured in Penumbra's settings."u8, + ImGui.GetFrameHeight() * Vector2.One, disabled || _colorTablePreviewers.Count == 0); if (ImGui.IsItemHovered()) HighlightColorTablePair(pairIdx); - else if (HighlightedColorTablePair == pairIdx) + else if (_highlightedColorTablePair == pairIdx) CancelColorTableHighlight(); } private static void CtBlendRect(Vector2 rcMin, Vector2 rcMax, uint topColor, uint bottomColor) { - var style = ImGui.GetStyle(); - var frameRounding = style.FrameRounding; + var style = ImGui.GetStyle(); + var frameRounding = style.FrameRounding; var frameThickness = style.FrameBorderSize; - var borderColor = ImGui.GetColorU32(ImGuiCol.Border); - var drawList = ImGui.GetWindowDrawList(); + var borderColor = ImGui.GetColorU32(ImGuiCol.Border); + var drawList = ImGui.GetWindowDrawList(); if (topColor == bottomColor) + { drawList.AddRectFilled(rcMin, rcMax, topColor, frameRounding, ImDrawFlags.RoundCornersDefault); + } else { drawList.AddRectFilled( @@ -258,10 +264,12 @@ public partial class MtrlTab rcMin with { Y = float.Lerp(rcMin.Y, rcMax.Y, 2.0f / 3) }, rcMax, bottomColor, frameRounding, ImDrawFlags.RoundCornersBottomLeft | ImDrawFlags.RoundCornersBottomRight); } + drawList.AddRect(rcMin, rcMax, borderColor, frameRounding, ImDrawFlags.RoundCornersDefault, frameThickness); } - private static bool CtColorPicker(ReadOnlySpan label, ReadOnlySpan description, HalfColor current, Action setter, ReadOnlySpan letter = default) + private static bool CtColorPicker(ReadOnlySpan label, ReadOnlySpan description, HalfColor current, Action setter, + ReadOnlySpan letter = default) { var ret = false; var inputSqrt = PseudoSqrtRgb((Vector3)current); @@ -291,10 +299,13 @@ public partial class MtrlTab return ret; } - private static void CtColorPicker(ReadOnlySpan label, ReadOnlySpan description, HalfColor? current, ReadOnlySpan letter = default) + private static void CtColorPicker(ReadOnlySpan label, ReadOnlySpan description, HalfColor? current, + ReadOnlySpan letter = default) { if (current.HasValue) + { CtColorPicker(label, description, current.Value, Nop, letter); + } else { var tmp = Vector4.Zero; @@ -308,8 +319,8 @@ public partial class MtrlTab if (letter.Length > 0 && ImGui.IsItemVisible()) { - var textSize = ImUtf8.CalcTextSize(letter); - var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; + var textSize = ImUtf8.CalcTextSize(letter); + var center = ImGui.GetItemRectMin() + (ImGui.GetItemRectSize() - textSize) / 2; ImGui.GetWindowDrawList().AddText(letter, center, 0x80000000u); } @@ -319,7 +330,7 @@ public partial class MtrlTab private static bool CtApplyStainCheckbox(ReadOnlySpan label, ReadOnlySpan description, bool current, Action setter) { - var tmp = current; + var tmp = current; var result = ApplyStainCheckbox.Draw(label, ref tmp); ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); if (!result || tmp == current) @@ -329,68 +340,79 @@ public partial class MtrlTab return true; } - private static bool CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, Half value, ReadOnlySpan format, float min, float max, float speed, Action setter) + private static bool CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, Half value, ReadOnlySpan format, float min, + float max, float speed, Action setter) { - var tmp = (float)value; + var tmp = (float)value; var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); if (!result) return false; + var newValue = (Half)tmp; if (newValue == value) return false; + setter(newValue); return true; } - private static bool CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, ref Half value, ReadOnlySpan format, float min, float max, float speed) + private static bool CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, ref Half value, ReadOnlySpan format, + float min, float max, float speed) { - var tmp = (float)value; + var tmp = (float)value; var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); if (!result) return false; + var newValue = (Half)tmp; if (newValue == value) return false; + value = newValue; return true; } private static void CtDragHalf(ReadOnlySpan label, ReadOnlySpan description, Half? value, ReadOnlySpan format) { - using var _ = ImRaii.Disabled(); - var valueOrDefault = value ?? Half.Zero; - var floatValue = (float)valueOrDefault; + using var _ = ImRaii.Disabled(); + var valueOrDefault = value ?? Half.Zero; + var floatValue = (float)valueOrDefault; CtDragHalf(label, description, valueOrDefault, value.HasValue ? format : "-"u8, floatValue, floatValue, 0.0f, Nop); } - private static bool CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, T value, ReadOnlySpan format, T min, T max, float speed, Action setter) where T : unmanaged, INumber + private static bool CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, T value, ReadOnlySpan format, T min, + T max, float speed, Action setter) where T : unmanaged, INumber { - var tmp = value; + var tmp = value; var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); if (!result || tmp == value) return false; + setter(tmp); return true; } - private static bool CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, ref T value, ReadOnlySpan format, T min, T max, float speed) where T : unmanaged, INumber + private static bool CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, ref T value, ReadOnlySpan format, T min, + T max, float speed) where T : unmanaged, INumber { - var tmp = value; + var tmp = value; var result = ImUtf8.DragScalar(label, ref tmp, format, min, max, speed); ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, description); if (!result || tmp == value) return false; + value = tmp; return true; } - private static void CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, T? value, ReadOnlySpan format) where T : unmanaged, INumber + private static void CtDragScalar(ReadOnlySpan label, ReadOnlySpan description, T? value, ReadOnlySpan format) + where T : unmanaged, INumber { - using var _ = ImRaii.Disabled(); - var valueOrDefault = value ?? T.Zero; + using var _ = ImRaii.Disabled(); + var valueOrDefault = value ?? T.Zero; CtDragScalar(label, description, valueOrDefault, value.HasValue ? format : "-"u8, valueOrDefault, valueOrDefault, 0.0f, Nop); } @@ -398,14 +420,17 @@ public partial class MtrlTab { if (!_materialTemplatePickers.DrawTileIndexPicker(label, description, ref value, compact)) return false; + setter(value); return true; } - private bool CtSphereMapIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ushort value, bool compact, Action setter) + private bool CtSphereMapIndexPicker(ReadOnlySpan label, ReadOnlySpan description, ushort value, bool compact, + Action setter) { if (!_materialTemplatePickers.DrawSphereMapIndexPicker(label, description, ref value, compact)) return false; + setter(value); return true; } @@ -430,33 +455,34 @@ public partial class MtrlTab ret |= CtDragHalf("##TileTransformVU"u8, "Tile Skew V"u8, ref tmp.VU, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); if (!ret || tmp == value) return false; + setter(tmp); } else { value.Decompose(out var scale, out var rotation, out var shear); rotation *= 180.0f / MathF.PI; - shear *= 180.0f / MathF.PI; + shear *= 180.0f / MathF.PI; ImGui.SetNextItemWidth(floatSize); var scaleXChanged = CtDragScalar("##TileScaleU"u8, "Tile Scale U"u8, ref scale.X, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); var activated = ImGui.IsItemActivated(); var deactivated = ImGui.IsItemDeactivated(); ImUtf8.SameLineInner(); ImGui.SetNextItemWidth(floatSize); - var scaleYChanged = CtDragScalar("##TileScaleV"u8, "Tile Scale V"u8, ref scale.Y, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); - activated |= ImGui.IsItemActivated(); - deactivated |= ImGui.IsItemDeactivated(); + var scaleYChanged = CtDragScalar("##TileScaleV"u8, "Tile Scale V"u8, ref scale.Y, "%.2f"u8, HalfMinValue, HalfMaxValue, 0.1f); + activated |= ImGui.IsItemActivated(); + deactivated |= ImGui.IsItemDeactivated(); if (!twoRowLayout) ImUtf8.SameLineInner(); ImGui.SetNextItemWidth(floatSize); - var rotationChanged = CtDragScalar("##TileRotation"u8, "Tile Rotation"u8, ref rotation, "%.0f°"u8, -180.0f, 180.0f, 1.0f); - activated |= ImGui.IsItemActivated(); - deactivated |= ImGui.IsItemDeactivated(); + var rotationChanged = CtDragScalar("##TileRotation"u8, "Tile Rotation"u8, ref rotation, "%.0f°"u8, -180.0f, 180.0f, 1.0f); + activated |= ImGui.IsItemActivated(); + deactivated |= ImGui.IsItemDeactivated(); ImUtf8.SameLineInner(); ImGui.SetNextItemWidth(floatSize); - var shearChanged = CtDragScalar("##TileShear"u8, "Tile Shear"u8, ref shear, "%.0f°"u8, -90.0f, 90.0f, 1.0f); - activated |= ImGui.IsItemActivated(); - deactivated |= ImGui.IsItemDeactivated(); + var shearChanged = CtDragScalar("##TileShear"u8, "Tile Shear"u8, ref shear, "%.0f°"u8, -90.0f, 90.0f, 1.0f); + activated |= ImGui.IsItemActivated(); + deactivated |= ImGui.IsItemDeactivated(); if (deactivated) _pinnedTileTransform = null; else if (activated) @@ -464,6 +490,7 @@ public partial class MtrlTab ret = scaleXChanged | scaleYChanged | rotationChanged | shearChanged; if (!ret) return false; + if (_pinnedTileTransform.HasValue) { var (pinScale, pinRotation, pinShear) = _pinnedTileTransform.Value; @@ -476,11 +503,14 @@ public partial class MtrlTab if (!shearChanged) shear = pinShear; } + var newValue = HalfMatrix2x2.Compose(scale, rotation * MathF.PI / 180.0f, shear * MathF.PI / 180.0f); if (newValue == value) return false; + setter(newValue); } + return true; } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs index 56496005..176ec3f4 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs @@ -35,7 +35,7 @@ public partial class MtrlTab Constants.Clear(); string mpPrefix; - if (AssociatedShpk == null) + if (_associatedShpk == null) { mpPrefix = MaterialParamsConstantName.Value!; var fcGroup = FindOrAddGroup(Constants, "Further Constants"); @@ -51,12 +51,12 @@ public partial class MtrlTab } else { - mpPrefix = AssociatedShpk.GetConstantById(MaterialParamsConstantId)?.Name ?? MaterialParamsConstantName.Value!; + mpPrefix = _associatedShpk.GetConstantById(MaterialParamsConstantId)?.Name ?? MaterialParamsConstantName.Value!; var autoNameMaxLength = Math.Max(Names.LongestKnownNameLength, mpPrefix.Length + 8); - foreach (var shpkConstant in AssociatedShpk.MaterialParams) + foreach (var shpkConstant in _associatedShpk.MaterialParams) { var name = Names.KnownNames.TryResolve(shpkConstant.Id); - var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, AssociatedShpk, out var constantIndex); + var constant = Mtrl.GetOrAddConstant(shpkConstant.Id, _associatedShpk, out var constantIndex); var values = Mtrl.GetConstantValue(constant); var handledElements = new IndexSet(values.Length, false); @@ -64,8 +64,8 @@ public partial class MtrlTab if (dkData != null) foreach (var dkConstant in dkData) { - var offset = (int)dkConstant.EffectiveByteOffset; - var length = values.Length - offset; + var offset = (int)dkConstant.EffectiveByteOffset; + var length = values.Length - offset; var constantSize = dkConstant.EffectiveByteSize; if (constantSize.HasValue) length = Math.Min(length, (int)constantSize.Value); @@ -86,7 +86,6 @@ public partial class MtrlTab foreach (var (start, end) in handledElements.Ranges(complement: true)) { if (start == 0 && end == values.Length && end - start <= 16) - { if (name.Value != null) { fcGroup.Add(( @@ -94,7 +93,6 @@ public partial class MtrlTab constantIndex, 0..values.Length, string.Empty, true, DefaultConstantEditorFor(name))); continue; } - } if ((shpkConstant.ByteOffset & 0x3) == 0 && (shpkConstant.ByteSize & 0x3) == 0) { @@ -105,7 +103,8 @@ public partial class MtrlTab var rangeEnd = Math.Min(i + 16, end); if (rangeEnd > rangeStart) { - var autoName = $"{mpPrefix}[{j,2:D}]{VectorSwizzle(((offset + rangeStart) & 0xF) >> 2, ((offset + rangeEnd - 1) & 0xF) >> 2)}"; + var autoName = + $"{mpPrefix}[{j,2:D}]{VectorSwizzle(((offset + rangeStart) & 0xF) >> 2, ((offset + rangeEnd - 1) & 0xF) >> 2)}"; fcGroup.Add(( $"{autoName.PadRight(autoNameMaxLength)} (0x{shpkConstant.Id:X8})", constantIndex, rangeStart..rangeEnd, string.Empty, true, DefaultConstantEditorFor(name))); @@ -116,7 +115,8 @@ public partial class MtrlTab { for (var i = start; i < end; i += 16) { - fcGroup.Add(($"{"???".PadRight(autoNameMaxLength)} (0x{shpkConstant.Id:X8})", constantIndex, i..Math.Min(i + 16, end), string.Empty, true, + fcGroup.Add(($"{"???".PadRight(autoNameMaxLength)} (0x{shpkConstant.Id:X8})", constantIndex, + i..Math.Min(i + 16, end), string.Empty, true, DefaultConstantEditorFor(name))); } } @@ -178,15 +178,16 @@ public partial class MtrlTab ret = true; SetMaterialParameter(constant.Id, slice.Start, buffer[slice]); } - var shpkConstant = AssociatedShpk?.GetMaterialParamById(constant.Id); - var defaultConstantValue = shpkConstant.HasValue ? AssociatedShpk!.GetMaterialParamDefault(shpkConstant.Value) : []; + + var shpkConstant = _associatedShpk?.GetMaterialParamById(constant.Id); + var defaultConstantValue = shpkConstant.HasValue ? _associatedShpk!.GetMaterialParamDefault(shpkConstant.Value) : []; var defaultValue = IsValid(slice, defaultConstantValue.Length) ? defaultConstantValue[slice] : []; - var canReset = AssociatedShpk?.MaterialParamsDefaults != null + var canReset = _associatedShpk?.MaterialParamsDefaults != null ? defaultValue.Length > 0 && !defaultValue.SequenceEqual(buffer[slice]) : buffer[slice].ContainsAnyExcept((byte)0); ImUtf8.SameLineInner(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Backspace.ToIconString(), ImGui.GetFrameHeight() * Vector2.One, - "Reset this constant to its default value.\n\nHold Ctrl to unlock.", !ImGui.GetIO().KeyCtrl || !canReset, true)) + "Reset this constant to its default value.\n\nHold Ctrl to unlock.", !ImGui.GetIO().KeyCtrl || !canReset, true)) { ret = true; if (defaultValue.Length > 0) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs index cd62d58f..26fe3dcb 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Devkit.cs @@ -1,3 +1,4 @@ +using JetBrains.Annotations; using Newtonsoft.Json.Linq; using OtterGui.Text.Widget.Editors; using Penumbra.String.Classes; @@ -29,8 +30,8 @@ public partial class MtrlTab } private T? TryGetShpkDevkitData(string category, uint? id, bool mayVary) where T : class - => TryGetShpkDevkitData(AssociatedShpkDevkit, LoadedShpkDevkitPathName, category, id, mayVary) - ?? TryGetShpkDevkitData(AssociatedBaseDevkit, LoadedBaseDevkitPathName, category, id, mayVary); + => TryGetShpkDevkitData(_associatedShpkDevkit, _loadedShpkDevkitPathName, category, id, mayVary) + ?? TryGetShpkDevkitData(_associatedBaseDevkit, _loadedBaseDevkitPathName, category, id, mayVary); private T? TryGetShpkDevkitData(JObject? devkit, string devkitPathName, string category, uint? id, bool mayVary) where T : class { @@ -47,7 +48,7 @@ public partial class MtrlTab { var selector = BuildSelector(data!["Vary"]! .Select(key => (uint)key) - .Select(key => Mtrl.GetShaderKey(key)?.Value ?? AssociatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); + .Select(key => Mtrl.GetShaderKey(key)?.Value ?? _associatedShpk!.GetMaterialKeyById(key)!.Value.DefaultValue)); var index = (int)data["Selectors"]![selector.ToString()]!; data = data["Items"]![index]; } @@ -62,12 +63,14 @@ public partial class MtrlTab } } + [UsedImplicitly] private sealed class DevkitShaderKeyValue { public string Label = string.Empty; public string Description = string.Empty; } + [UsedImplicitly] private sealed class DevkitShaderKey { public string Label = string.Empty; @@ -75,6 +78,7 @@ public partial class MtrlTab public Dictionary Values = []; } + [UsedImplicitly] private sealed class DevkitSampler { public string Label = string.Empty; @@ -84,14 +88,16 @@ public partial class MtrlTab private enum DevkitConstantType { - Hidden = -1, - Float = 0, + Hidden = -1, + Float = 0, + /// Integer encoded as a float. - Integer = 1, - Color = 2, - Enum = 3, + Integer = 1, + Color = 2, + Enum = 3, + /// Native integer. - Int32 = 4, + Int32 = 4, Int32Enum = 5, Int8 = 6, Int8Enum = 7, @@ -105,6 +111,7 @@ public partial class MtrlTab SphereMapIndex = 15, } + [UsedImplicitly] private sealed class DevkitConstantValue { public string Label = string.Empty; @@ -112,6 +119,7 @@ public partial class MtrlTab public double Value = 0; } + [UsedImplicitly] private sealed class DevkitConstant { public uint Offset = 0; @@ -147,7 +155,7 @@ public partial class MtrlTab => ByteOffset ?? Offset * ValueSize; public uint? EffectiveByteSize - => ByteSize ?? (Length * ValueSize); + => ByteSize ?? Length * ValueSize; public unsafe uint ValueSize => Type switch @@ -198,19 +206,23 @@ public partial class MtrlTab private IEditor CreateIntegerEditor() where T : unmanaged, INumber => ((Drag || Slider) && !Hex - ? (Drag - ? (IEditor)DragEditor.CreateInteger(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, Unit, 0) - : SliderEditor.CreateInteger(ToInteger(Minimum) ?? default, ToInteger(Maximum) ?? default, Unit, 0)) - : InputEditor.CreateInteger(ToInteger(Minimum), ToInteger(Maximum), ToInteger(Step), ToInteger(StepFast), Hex, Unit, 0)) + ? Drag + ? (IEditor)DragEditor.CreateInteger(ToInteger(Minimum), ToInteger(Maximum), Speed ?? 0.25f, RelativeSpeed, + Unit, 0) + : SliderEditor.CreateInteger(ToInteger(Minimum) ?? default, ToInteger(Maximum) ?? default, Unit, 0) + : InputEditor.CreateInteger(ToInteger(Minimum), ToInteger(Maximum), ToInteger(Step), ToInteger(StepFast), + Hex, Unit, 0)) .WithFactorAndBias(ToInteger(Factor), ToInteger(Bias)); private IEditor CreateFloatEditor() where T : unmanaged, INumber, IPowerFunctions - => ((Drag || Slider) - ? (Drag - ? (IEditor)DragEditor.CreateFloat(ToFloat(Minimum), ToFloat(Maximum), Speed ?? 0.1f, RelativeSpeed, Precision, Unit, 0) - : SliderEditor.CreateFloat(ToFloat(Minimum) ?? default, ToFloat(Maximum) ?? default, Precision, Unit, 0)) - : InputEditor.CreateFloat(ToFloat(Minimum), ToFloat(Maximum), T.CreateSaturating(Step), T.CreateSaturating(StepFast), Precision, Unit, 0)) + => (Drag || Slider + ? Drag + ? (IEditor)DragEditor.CreateFloat(ToFloat(Minimum), ToFloat(Maximum), Speed ?? 0.1f, RelativeSpeed, + Precision, Unit, 0) + : SliderEditor.CreateFloat(ToFloat(Minimum) ?? default, ToFloat(Maximum) ?? default, Precision, Unit, 0) + : InputEditor.CreateFloat(ToFloat(Minimum), ToFloat(Maximum), T.CreateSaturating(Step), + T.CreateSaturating(StepFast), Precision, Unit, 0)) .WithExponent(T.CreateSaturating(Exponent)) .WithFactorAndBias(T.CreateSaturating(Factor), T.CreateSaturating(Bias)); diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs index a2165760..0ff2b01f 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -110,9 +110,9 @@ public partial class MtrlTab } ImGui.TableNextColumn(); - using (ImRaii.PushFont(UiBuilder.MonoFont)) - { - ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); + using (ImRaii.PushFont(UiBuilder.MonoFont)) + { + ImUtf8.Text($"{(rowIdx >> 1) + 1,2:D}{"AB"[rowIdx & 1]}"); } ImGui.TableNextColumn(); diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs index 3482e581..6089f2d5 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs @@ -12,20 +12,20 @@ namespace Penumbra.UI.AdvancedWindow.Materials; public partial class MtrlTab { - public readonly List MaterialPreviewers = new(4); - public readonly List ColorTablePreviewers = new(4); - public int HighlightedColorTablePair = -1; - public readonly Stopwatch HighlightTime = new(); + private readonly List _materialPreviewers = new(4); + private readonly List _colorTablePreviewers = new(4); + private int _highlightedColorTablePair = -1; + private readonly Stopwatch _highlightTime = new(); private void DrawMaterialLivePreviewRebind(bool disabled) { if (disabled) return; - if (ImGui.Button("Reload live preview")) + if (ImUtf8.Button("Reload live preview"u8)) BindToMaterialInstances(); - if (MaterialPreviewers.Count != 0 || ColorTablePreviewers.Count != 0) + if (_materialPreviewers.Count != 0 || _colorTablePreviewers.Count != 0) return; ImGui.SameLine(); @@ -34,7 +34,7 @@ public partial class MtrlTab "The current material has not been found on your character. Please check the Import from Screen tab for more information."u8); } - public unsafe void BindToMaterialInstances() + private unsafe void BindToMaterialInstances() { UnbindFromMaterialInstances(); @@ -50,7 +50,7 @@ public partial class MtrlTab try { - MaterialPreviewers.Add(new LiveMaterialPreviewer(_objects, materialInfo)); + _materialPreviewers.Add(new LiveMaterialPreviewer(_objects, materialInfo)); foundMaterials.Add((nint)material); } catch (InvalidOperationException) @@ -68,7 +68,7 @@ public partial class MtrlTab { try { - ColorTablePreviewers.Add(new LiveColorTablePreviewer(_objects, _framework, materialInfo)); + _colorTablePreviewers.Add(new LiveColorTablePreviewer(_objects, _framework, materialInfo)); } catch (InvalidOperationException) { @@ -81,53 +81,53 @@ public partial class MtrlTab private void UnbindFromMaterialInstances() { - foreach (var previewer in MaterialPreviewers) + foreach (var previewer in _materialPreviewers) previewer.Dispose(); - MaterialPreviewers.Clear(); + _materialPreviewers.Clear(); - foreach (var previewer in ColorTablePreviewers) + foreach (var previewer in _colorTablePreviewers) previewer.Dispose(); - ColorTablePreviewers.Clear(); + _colorTablePreviewers.Clear(); } private unsafe void UnbindFromDrawObjectMaterialInstances(CharacterBase* characterBase) { - for (var i = MaterialPreviewers.Count; i-- > 0;) + for (var i = _materialPreviewers.Count; i-- > 0;) { - var previewer = MaterialPreviewers[i]; + var previewer = _materialPreviewers[i]; if (previewer.DrawObject != characterBase) continue; previewer.Dispose(); - MaterialPreviewers.RemoveAt(i); + _materialPreviewers.RemoveAt(i); } - for (var i = ColorTablePreviewers.Count; i-- > 0;) + for (var i = _colorTablePreviewers.Count; i-- > 0;) { - var previewer = ColorTablePreviewers[i]; + var previewer = _colorTablePreviewers[i]; if (previewer.DrawObject != characterBase) continue; previewer.Dispose(); - ColorTablePreviewers.RemoveAt(i); + _colorTablePreviewers.RemoveAt(i); } } - public void SetShaderPackageFlags(uint shPkFlags) + private void SetShaderPackageFlags(uint shPkFlags) { - foreach (var previewer in MaterialPreviewers) + foreach (var previewer in _materialPreviewers) previewer.SetShaderPackageFlags(shPkFlags); } - public void SetMaterialParameter(uint parameterCrc, Index offset, Span value) + private void SetMaterialParameter(uint parameterCrc, Index offset, Span value) { - foreach (var previewer in MaterialPreviewers) + foreach (var previewer in _materialPreviewers) previewer.SetMaterialParameter(parameterCrc, offset, value); } - public void SetSamplerFlags(uint samplerCrc, uint samplerFlags) + private void SetSamplerFlags(uint samplerCrc, uint samplerFlags) { - foreach (var previewer in MaterialPreviewers) + foreach (var previewer in _materialPreviewers) previewer.SetSamplerFlags(samplerCrc, samplerFlags); } @@ -145,14 +145,14 @@ public partial class MtrlTab SetSamplerFlags(sampler.SamplerId, sampler.Flags); } - public void HighlightColorTablePair(int pairIdx) + private void HighlightColorTablePair(int pairIdx) { - var oldPairIdx = HighlightedColorTablePair; + var oldPairIdx = _highlightedColorTablePair; - if (HighlightedColorTablePair != pairIdx) + if (_highlightedColorTablePair != pairIdx) { - HighlightedColorTablePair = pairIdx; - HighlightTime.Restart(); + _highlightedColorTablePair = pairIdx; + _highlightTime.Restart(); } if (oldPairIdx >= 0) @@ -160,19 +160,6 @@ public partial class MtrlTab UpdateColorTableRowPreview(oldPairIdx << 1); UpdateColorTableRowPreview((oldPairIdx << 1) | 1); } - if (pairIdx >= 0) - { - UpdateColorTableRowPreview(pairIdx << 1); - UpdateColorTableRowPreview((pairIdx << 1) | 1); - } - } - - public void CancelColorTableHighlight() - { - var pairIdx = HighlightedColorTablePair; - - HighlightedColorTablePair = -1; - HighlightTime.Reset(); if (pairIdx >= 0) { @@ -181,9 +168,23 @@ public partial class MtrlTab } } - public void UpdateColorTableRowPreview(int rowIdx) + private void CancelColorTableHighlight() { - if (ColorTablePreviewers.Count == 0) + var pairIdx = _highlightedColorTablePair; + + _highlightedColorTablePair = -1; + _highlightTime.Reset(); + + if (pairIdx >= 0) + { + UpdateColorTableRowPreview(pairIdx << 1); + UpdateColorTableRowPreview((pairIdx << 1) | 1); + } + } + + private void UpdateColorTableRowPreview(int rowIdx) + { + if (_colorTablePreviewers.Count == 0) return; if (Mtrl.Table == null) @@ -192,7 +193,7 @@ public partial class MtrlTab var row = Mtrl.Table switch { LegacyColorTable legacyTable => new ColorTableRow(legacyTable[rowIdx]), - ColorTable table => table[rowIdx], + ColorTable table => table[rowIdx], _ => throw new InvalidOperationException($"Unsupported color table type {Mtrl.Table.GetType()}"), }; if (Mtrl.DyeTable != null) @@ -200,8 +201,8 @@ public partial class MtrlTab var dyeRow = Mtrl.DyeTable switch { LegacyColorDyeTable legacyDyeTable => new ColorDyeTableRow(legacyDyeTable[rowIdx]), - ColorDyeTable dyeTable => dyeTable[rowIdx], - _ => throw new InvalidOperationException($"Unsupported color dye table type {Mtrl.DyeTable.GetType()}"), + ColorDyeTable dyeTable => dyeTable[rowIdx], + _ => throw new InvalidOperationException($"Unsupported color dye table type {Mtrl.DyeTable.GetType()}"), }; if (dyeRow.Channel < StainService.ChannelCount) { @@ -213,21 +214,21 @@ public partial class MtrlTab } } - if (HighlightedColorTablePair << 1 == rowIdx) - ApplyHighlight(ref row, ColorId.InGameHighlight, (float)HighlightTime.Elapsed.TotalSeconds); - else if (((HighlightedColorTablePair << 1) | 1) == rowIdx) - ApplyHighlight(ref row, ColorId.InGameHighlight2, (float)HighlightTime.Elapsed.TotalSeconds); + if (_highlightedColorTablePair << 1 == rowIdx) + ApplyHighlight(ref row, ColorId.InGameHighlight, (float)_highlightTime.Elapsed.TotalSeconds); + else if (((_highlightedColorTablePair << 1) | 1) == rowIdx) + ApplyHighlight(ref row, ColorId.InGameHighlight2, (float)_highlightTime.Elapsed.TotalSeconds); - foreach (var previewer in ColorTablePreviewers) + foreach (var previewer in _colorTablePreviewers) { row[..].CopyTo(previewer.GetColorRow(rowIdx)); previewer.ScheduleUpdate(); } } - public void UpdateColorTablePreview() + private void UpdateColorTablePreview() { - if (ColorTablePreviewers.Count == 0) + if (_colorTablePreviewers.Count == 0) return; if (Mtrl.Table == null) @@ -237,7 +238,8 @@ public partial class MtrlTab var dyeRows = Mtrl.DyeTable != null ? ColorDyeTable.CastOrConvert(Mtrl.DyeTable) : null; if (dyeRows != null) { - ReadOnlySpan stainIds = [ + ReadOnlySpan stainIds = + [ _stainService.StainCombo1.CurrentSelection.Key, _stainService.StainCombo2.CurrentSelection.Key, ]; @@ -245,13 +247,14 @@ public partial class MtrlTab rows.ApplyDye(_stainService.GudStmFile, stainIds, dyeRows); } - if (HighlightedColorTablePair >= 0) + if (_highlightedColorTablePair >= 0) { - ApplyHighlight(ref rows[HighlightedColorTablePair << 1], ColorId.InGameHighlight, (float)HighlightTime.Elapsed.TotalSeconds); - ApplyHighlight(ref rows[(HighlightedColorTablePair << 1) | 1], ColorId.InGameHighlight2, (float)HighlightTime.Elapsed.TotalSeconds); + ApplyHighlight(ref rows[_highlightedColorTablePair << 1], ColorId.InGameHighlight, (float)_highlightTime.Elapsed.TotalSeconds); + ApplyHighlight(ref rows[(_highlightedColorTablePair << 1) | 1], ColorId.InGameHighlight2, + (float)_highlightTime.Elapsed.TotalSeconds); } - foreach (var previewer in ColorTablePreviewers) + foreach (var previewer in _colorTablePreviewers) { rows.AsHalves().CopyTo(previewer.ColorTable); previewer.ScheduleUpdate(); @@ -260,11 +263,11 @@ public partial class MtrlTab private static void ApplyHighlight(ref ColorTableRow row, ColorId colorId, float time) { - var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; - var baseColor = colorId.Value(); + var level = (MathF.Sin(time * 2.0f * MathF.PI) + 2.0f) / 3.0f / 255.0f; + var baseColor = colorId.Value(); var color = level * new Vector3(baseColor & 0xFF, (baseColor >> 8) & 0xFF, (baseColor >> 16) & 0xFF); var halfColor = (HalfColor)(color * color); - + row.DiffuseColor = halfColor; row.SpecularColor = halfColor; row.EmissiveColor = halfColor; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs index 21557939..ae57a122 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -21,8 +21,8 @@ public partial class MtrlTab // Apricot shader packages are unlisted because // 1. they cause severe performance/memory issues when calculating the effective shader set // 2. they probably aren't intended for use with materials anyway - internal static readonly IReadOnlyList StandardShaderPackages = new[] - { + private static readonly IReadOnlyList StandardShaderPackages = + [ "3dui.shpk", // "apricot_decal_dummy.shpk", // "apricot_decal_ring.shpk", @@ -80,35 +80,35 @@ public partial class MtrlTab "verticalfog.shpk", "water.shpk", "weather.shpk", - }; + ]; - private static readonly byte[] UnknownShadersString = Encoding.UTF8.GetBytes("Vertex Shaders: ???\nPixel Shaders: ???"); + private static readonly byte[] UnknownShadersString = "Vertex Shaders: ???\nPixel Shaders: ???"u8.ToArray(); private string[]? _shpkNames; - public string ShaderHeader = "Shader###Shader"; - public FullPath LoadedShpkPath = FullPath.Empty; - public string LoadedShpkPathName = string.Empty; - public string LoadedShpkDevkitPathName = string.Empty; - public string ShaderComment = string.Empty; - public ShpkFile? AssociatedShpk; - public bool ShpkLoading; - public JObject? AssociatedShpkDevkit; + private string _shaderHeader = "Shader###Shader"; + private FullPath _loadedShpkPath = FullPath.Empty; + private string _loadedShpkPathName = string.Empty; + private string _loadedShpkDevkitPathName = string.Empty; + private string _shaderComment = string.Empty; + private ShpkFile? _associatedShpk; + private bool _shpkLoading; + private JObject? _associatedShpkDevkit; - public readonly string LoadedBaseDevkitPathName; - public readonly JObject? AssociatedBaseDevkit; + private readonly string _loadedBaseDevkitPathName; + private readonly JObject? _associatedBaseDevkit; // Shader Key State - public readonly + private readonly List<(string Label, int Index, string Description, bool MonoFont, IReadOnlyList<(string Label, uint Value, string Description)> - Values)> ShaderKeys = new(16); + Values)> _shaderKeys = new(16); - public readonly HashSet VertexShaders = new(16); - public readonly HashSet PixelShaders = new(16); - public bool ShadersKnown; - public ReadOnlyMemory ShadersString = UnknownShadersString; + private readonly HashSet _vertexShaders = new(16); + private readonly HashSet _pixelShaders = new(16); + private bool _shadersKnown; + private ReadOnlyMemory _shadersString = UnknownShadersString; - public string[] GetShpkNames() + private string[] GetShpkNames() { if (null != _shpkNames) return _shpkNames; @@ -122,7 +122,7 @@ public partial class MtrlTab return _shpkNames; } - public FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) + private FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) { defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) @@ -131,45 +131,45 @@ public partial class MtrlTab return _edit.FindBestMatch(defaultGamePath); } - public void LoadShpk(FullPath path) + private void LoadShpk(FullPath path) => Task.Run(() => DoLoadShpk(path)); private async Task DoLoadShpk(FullPath path) { - ShadersKnown = false; - ShaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; - ShpkLoading = true; + _shadersKnown = false; + _shaderHeader = $"Shader ({Mtrl.ShaderPackage.Name})###Shader"; + _shpkLoading = true; try { var data = path.IsRooted ? await File.ReadAllBytesAsync(path.FullName) : _gameData.GetFile(path.InternalName.ToString())?.Data; - LoadedShpkPath = path; - AssociatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); - LoadedShpkPathName = path.ToPath(); + _loadedShpkPath = path; + _associatedShpk = data?.Length > 0 ? new ShpkFile(data) : throw new Exception("Failure to load file data."); + _loadedShpkPathName = path.ToPath(); } catch (Exception e) { - LoadedShpkPath = FullPath.Empty; - LoadedShpkPathName = string.Empty; - AssociatedShpk = null; - Penumbra.Messager.NotificationMessage(e, $"Could not load {LoadedShpkPath.ToPath()}.", NotificationType.Error, false); + _loadedShpkPath = FullPath.Empty; + _loadedShpkPathName = string.Empty; + _associatedShpk = null; + Penumbra.Messager.NotificationMessage(e, $"Could not load {_loadedShpkPath.ToPath()}.", NotificationType.Error, false); } finally { - ShpkLoading = false; + _shpkLoading = false; } - if (LoadedShpkPath.InternalName.IsEmpty) + if (_loadedShpkPath.InternalName.IsEmpty) { - AssociatedShpkDevkit = null; - LoadedShpkDevkitPathName = string.Empty; + _associatedShpkDevkit = null; + _loadedShpkDevkitPathName = string.Empty; } else { - AssociatedShpkDevkit = - TryLoadShpkDevkit(Path.GetFileNameWithoutExtension(Mtrl.ShaderPackage.Name), out LoadedShpkDevkitPathName); + _associatedShpkDevkit = + TryLoadShpkDevkit(Path.GetFileNameWithoutExtension(Mtrl.ShaderPackage.Name), out _loadedShpkDevkitPathName); } UpdateShaderKeys(); @@ -178,9 +178,9 @@ public partial class MtrlTab private void UpdateShaderKeys() { - ShaderKeys.Clear(); - if (AssociatedShpk != null) - foreach (var key in AssociatedShpk.MaterialKeys) + _shaderKeys.Clear(); + if (_associatedShpk != null) + foreach (var key in _associatedShpk.MaterialKeys) { var keyName = Names.KnownNames.TryResolve(key.Id); var dkData = TryGetShpkDevkitData("ShaderKeys", key.Id, false); @@ -210,7 +210,7 @@ public partial class MtrlTab return string.Compare(x.Label, y.Label, StringComparison.Ordinal); }); - ShaderKeys.Add((hasDkLabel ? dkData!.Label : keyName.ToString(), mtrlKeyIndex, dkData?.Description ?? string.Empty, + _shaderKeys.Add((hasDkLabel ? dkData!.Label : keyName.ToString(), mtrlKeyIndex, dkData?.Description ?? string.Empty, !hasDkLabel, values)); } else @@ -218,7 +218,7 @@ public partial class MtrlTab { var keyName = Names.KnownNames.TryResolve(key.Category); var valueName = keyName.WithKnownSuffixes().TryResolve(Names.KnownNames, key.Value); - ShaderKeys.Add((keyName.ToString(), index, string.Empty, true, [(valueName.ToString(), key.Value, string.Empty)])); + _shaderKeys.Add((keyName.ToString(), index, string.Empty, true, [(valueName.ToString(), key.Value, string.Empty)])); } } @@ -232,27 +232,28 @@ public partial class MtrlTab passSet = []; byPassSets.Add(passId, passSet); } + passSet.Add(shaderIndex); } - VertexShaders.Clear(); - PixelShaders.Clear(); + _vertexShaders.Clear(); + _pixelShaders.Clear(); var vertexShadersByPass = new Dictionary>(); var pixelShadersByPass = new Dictionary>(); - if (AssociatedShpk == null || !AssociatedShpk.IsExhaustiveNodeAnalysisFeasible()) + if (_associatedShpk == null || !_associatedShpk.IsExhaustiveNodeAnalysisFeasible()) { - ShadersKnown = false; + _shadersKnown = false; } else { - ShadersKnown = true; - var systemKeySelectors = AllSelectors(AssociatedShpk.SystemKeys).ToArray(); - var sceneKeySelectors = AllSelectors(AssociatedShpk.SceneKeys).ToArray(); - var subViewKeySelectors = AllSelectors(AssociatedShpk.SubViewKeys).ToArray(); + _shadersKnown = true; + var systemKeySelectors = AllSelectors(_associatedShpk.SystemKeys).ToArray(); + var sceneKeySelectors = AllSelectors(_associatedShpk.SceneKeys).ToArray(); + var subViewKeySelectors = AllSelectors(_associatedShpk.SubViewKeys).ToArray(); var materialKeySelector = - BuildSelector(AssociatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); + BuildSelector(_associatedShpk.MaterialKeys.Select(key => Mtrl.GetOrAddShaderKey(key.Id, key.DefaultValue).Value)); foreach (var systemKeySelector in systemKeySelectors) { @@ -261,38 +262,39 @@ public partial class MtrlTab foreach (var subViewKeySelector in subViewKeySelectors) { var selector = BuildSelector(systemKeySelector, sceneKeySelector, materialKeySelector, subViewKeySelector); - var node = AssociatedShpk.GetNodeBySelector(selector); + var node = _associatedShpk.GetNodeBySelector(selector); if (node.HasValue) foreach (var pass in node.Value.Passes) { - AddShader(VertexShaders, vertexShadersByPass, pass.Id, (int)pass.VertexShader); - AddShader(PixelShaders, pixelShadersByPass, pass.Id, (int)pass.PixelShader); + AddShader(_vertexShaders, vertexShadersByPass, pass.Id, (int)pass.VertexShader); + AddShader(_pixelShaders, pixelShadersByPass, pass.Id, (int)pass.PixelShader); } else - ShadersKnown = false; + _shadersKnown = false; } } } } - if (ShadersKnown) + if (_shadersKnown) { var builder = new StringBuilder(); - foreach (var (passId, passVS) in vertexShadersByPass) + foreach (var (passId, passVertexShader) in vertexShadersByPass) { if (builder.Length > 0) builder.Append("\n\n"); var passName = Names.KnownNames.TryResolve(passId); - var shaders = passVS.OrderBy(i => i).Select(i => $"#{i}"); + var shaders = passVertexShader.OrderBy(i => i).Select(i => $"#{i}"); builder.Append($"Vertex Shaders ({passName}): {string.Join(", ", shaders)}"); - if (pixelShadersByPass.TryGetValue(passId, out var passPS)) + if (pixelShadersByPass.TryGetValue(passId, out var passPixelShader)) { - shaders = passPS.OrderBy(i => i).Select(i => $"#{i}"); + shaders = passPixelShader.OrderBy(i => i).Select(i => $"#{i}"); builder.Append($"\nPixel Shaders ({passName}): {string.Join(", ", shaders)}"); } } - foreach (var (passId, passPS) in pixelShadersByPass) + + foreach (var (passId, passPixelShader) in pixelShadersByPass) { if (vertexShadersByPass.ContainsKey(passId)) continue; @@ -301,22 +303,24 @@ public partial class MtrlTab builder.Append("\n\n"); var passName = Names.KnownNames.TryResolve(passId); - var shaders = passPS.OrderBy(i => i).Select(i => $"#{i}"); + var shaders = passPixelShader.OrderBy(i => i).Select(i => $"#{i}"); builder.Append($"Pixel Shaders ({passName}): {string.Join(", ", shaders)}"); } - ShadersString = Encoding.UTF8.GetBytes(builder.ToString()); + _shadersString = Encoding.UTF8.GetBytes(builder.ToString()); } else - ShadersString = UnknownShadersString; + { + _shadersString = UnknownShadersString; + } - ShaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; + _shaderComment = TryGetShpkDevkitData("Comment", null, true) ?? string.Empty; } private bool DrawShaderSection(bool disabled) { var ret = false; - if (ImGui.CollapsingHeader(ShaderHeader)) + if (ImGui.CollapsingHeader(_shaderHeader)) { ret |= DrawPackageNameInput(disabled); ret |= DrawShaderFlagsInput(disabled); @@ -325,20 +329,17 @@ public partial class MtrlTab DrawMaterialShaders(); } - if (!ShpkLoading && (AssociatedShpk == null || AssociatedShpkDevkit == null)) + if (!_shpkLoading && (_associatedShpk == null || _associatedShpkDevkit == null)) { ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - if (AssociatedShpk == null) - { + if (_associatedShpk == null) ImUtf8.Text("Unable to find a suitable shader (.shpk) file for cross-references. Some functionality will be missing."u8, ImGuiUtil.HalfBlendText(0x80u)); // Half red - } else - { - ImUtf8.Text("No dev-kit file found for this material's shaders. Please install one for optimal editing experience, such as actual constant names instead of hexadecimal identifiers."u8, + ImUtf8.Text( + "No dev-kit file found for this material's shaders. Please install one for optimal editing experience, such as actual constant names instead of hexadecimal identifiers."u8, ImGuiUtil.HalfBlendText(0x8080u)); // Half yellow - } } return ret; @@ -358,14 +359,14 @@ public partial class MtrlTab if (c) foreach (var value in GetShpkNames()) { - if (ImGui.Selectable(value, value == Mtrl.ShaderPackage.Name)) - { - Mtrl.ShaderPackage.Name = value; - ret = true; - AssociatedShpk = null; - LoadedShpkPath = FullPath.Empty; - LoadShpk(FindAssociatedShpk(out _, out _)); - } + if (!ImGui.Selectable(value, value == Mtrl.ShaderPackage.Name)) + continue; + + Mtrl.ShaderPackage.Name = value; + ret = true; + _associatedShpk = null; + _loadedShpkPath = FullPath.Empty; + LoadShpk(FindAssociatedShpk(out _, out _)); } return ret; @@ -391,23 +392,23 @@ public partial class MtrlTab private void DrawCustomAssociations() { const string tooltip = "Click to copy file path to clipboard."; - var text = AssociatedShpk == null + var text = _associatedShpk == null ? "Associated .shpk file: None" - : $"Associated .shpk file: {LoadedShpkPathName}"; - var devkitText = AssociatedShpkDevkit == null + : $"Associated .shpk file: {_loadedShpkPathName}"; + var devkitText = _associatedShpkDevkit == null ? "Associated dev-kit file: None" - : $"Associated dev-kit file: {LoadedShpkDevkitPathName}"; - var baseDevkitText = AssociatedBaseDevkit == null + : $"Associated dev-kit file: {_loadedShpkDevkitPathName}"; + var baseDevkitText = _associatedBaseDevkit == null ? "Base dev-kit file: None" - : $"Base dev-kit file: {LoadedBaseDevkitPathName}"; + : $"Base dev-kit file: {_loadedBaseDevkitPathName}"; ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - ImGuiUtil.CopyOnClickSelectable(text, LoadedShpkPathName, tooltip); - ImGuiUtil.CopyOnClickSelectable(devkitText, LoadedShpkDevkitPathName, tooltip); - ImGuiUtil.CopyOnClickSelectable(baseDevkitText, LoadedBaseDevkitPathName, tooltip); + ImUtf8.CopyOnClickSelectable(text, _loadedShpkPathName, tooltip); + ImUtf8.CopyOnClickSelectable(devkitText, _loadedShpkDevkitPathName, tooltip); + ImUtf8.CopyOnClickSelectable(baseDevkitText, _loadedBaseDevkitPathName, tooltip); - if (ImGui.Button("Associate Custom .shpk File")) + if (ImUtf8.Button("Associate Custom .shpk File"u8)) _fileDialog.OpenFilePicker("Associate Custom .shpk File...", ".shpk", (success, name) => { if (success) @@ -416,15 +417,15 @@ public partial class MtrlTab var moddedPath = FindAssociatedShpk(out var defaultPath, out var gamePath); ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Associate Default .shpk File", Vector2.Zero, moddedPath.ToPath(), - moddedPath.Equals(LoadedShpkPath))) + if (ImUtf8.ButtonEx("Associate Default .shpk File"u8, moddedPath.ToPath(), Vector2.Zero, + moddedPath.Equals(_loadedShpkPath))) LoadShpk(moddedPath); if (!gamePath.Path.Equals(moddedPath.InternalName)) { ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Associate Unmodded .shpk File", Vector2.Zero, defaultPath, - gamePath.Path.Equals(LoadedShpkPath.InternalName))) + if (ImUtf8.ButtonEx("Associate Unmodded .shpk File", defaultPath, Vector2.Zero, + gamePath.Path.Equals(_loadedShpkPath.InternalName))) LoadShpk(new FullPath(gamePath)); } @@ -433,22 +434,23 @@ public partial class MtrlTab private bool DrawMaterialShaderKeys(bool disabled) { - if (ShaderKeys.Count == 0) + if (_shaderKeys.Count == 0) return false; var ret = false; - foreach (var (label, index, description, monoFont, values) in ShaderKeys) + foreach (var (label, index, description, monoFont, values) in _shaderKeys) { using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); ref var key = ref Mtrl.ShaderPackage.ShaderKeys[index]; - var shpkKey = AssociatedShpk?.GetMaterialKeyById(key.Category); + using var id = ImUtf8.PushId((int)key.Category); + var shpkKey = _associatedShpk?.GetMaterialKeyById(key.Category); var currentValue = key.Value; var (currentLabel, _, currentDescription) = values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); if (!disabled && shpkKey.HasValue) { ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); - using (var c = ImRaii.Combo($"##{key.Category:X8}", currentLabel)) + using (var c = ImUtf8.Combo(""u8, currentLabel)) { if (c) foreach (var (valueLabel, value, valueDescription) in values) @@ -469,16 +471,16 @@ public partial class MtrlTab if (description.Length > 0) ImGuiUtil.LabeledHelpMarker(label, description); else - ImGui.TextUnformatted(label); + ImUtf8.Text(label); } else if (description.Length > 0 || currentDescription.Length > 0) { - ImGuiUtil.LabeledHelpMarker($"{label}: {currentLabel}", + ImUtf8.LabeledHelpMarker($"{label}: {currentLabel}", description + (description.Length > 0 && currentDescription.Length > 0 ? "\n\n" : string.Empty) + currentDescription); } else { - ImGui.TextUnformatted($"{label}: {currentLabel}"); + ImUtf8.Text($"{label}: {currentLabel}"); } } @@ -487,19 +489,19 @@ public partial class MtrlTab private void DrawMaterialShaders() { - if (AssociatedShpk == null) + if (_associatedShpk == null) return; using (var node = ImUtf8.TreeNode("Candidate Shaders"u8)) { if (node) - ImUtf8.Text(ShadersString.Span); + ImUtf8.Text(_shadersString.Span); } - if (ShaderComment.Length > 0) + if (_shaderComment.Length > 0) { ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); - ImGui.TextUnformatted(ShaderComment); + ImUtf8.Text(_shaderComment); } } } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs index 3181dafe..7ab2900d 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs @@ -23,7 +23,7 @@ public partial class MtrlTab { Textures.Clear(); SamplerIds.Clear(); - if (AssociatedShpk == null) + if (_associatedShpk == null) { SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); if (Mtrl.Table != null) @@ -34,11 +34,11 @@ public partial class MtrlTab } else { - foreach (var index in VertexShaders) - SamplerIds.UnionWith(AssociatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); - foreach (var index in PixelShaders) - SamplerIds.UnionWith(AssociatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); - if (!ShadersKnown) + foreach (var index in _vertexShaders) + SamplerIds.UnionWith(_associatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); + foreach (var index in _pixelShaders) + SamplerIds.UnionWith(_associatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); + if (!_shadersKnown) { SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); if (Mtrl.Table != null) @@ -47,11 +47,11 @@ public partial class MtrlTab foreach (var samplerId in SamplerIds) { - var shpkSampler = AssociatedShpk.GetSamplerById(samplerId); + var shpkSampler = _associatedShpk.GetSamplerById(samplerId); if (shpkSampler is not { Slot: 2 }) continue; - var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); + var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); @@ -95,9 +95,12 @@ public partial class MtrlTab private static ReadOnlySpan TextureAddressModeTooltip(TextureAddressMode addressMode) => addressMode switch { - TextureAddressMode.Wrap => "Tile the texture at every UV integer junction.\n\nFor example, for U values between 0 and 3, the texture is repeated three times."u8, - TextureAddressMode.Mirror => "Flip the texture at every UV integer junction.\n\nFor U values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is mirrored; between 2 and 3, the texture is normal again; and so on."u8, - TextureAddressMode.Clamp => "Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively."u8, + TextureAddressMode.Wrap => + "Tile the texture at every UV integer junction.\n\nFor example, for U values between 0 and 3, the texture is repeated three times."u8, + TextureAddressMode.Mirror => + "Flip the texture at every UV integer junction.\n\nFor U values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is mirrored; between 2 and 3, the texture is normal again; and so on."u8, + TextureAddressMode.Clamp => + "Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively."u8, TextureAddressMode.Border => "Texture coordinates outside the range [0.0, 1.0] are set to the border color (generally black)."u8, _ => ""u8, }; @@ -167,7 +170,7 @@ public partial class MtrlTab return ret; } - + private static bool ComboTextureAddressMode(ReadOnlySpan label, ref TextureAddressMode value) { using var c = ImUtf8.Combo(label, value.ToString()); @@ -202,7 +205,7 @@ public partial class MtrlTab ret = true; } - ref var samplerFlags = ref SamplerFlags.Wrap(ref sampler.Flags); + ref var samplerFlags = ref Wrap(ref sampler.Flags); ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); var addressMode = samplerFlags.UAddressMode; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs index 2d4e93f1..6e16de99 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs @@ -4,7 +4,6 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Widgets; -using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.GameData.Files.MaterialStructs; using Penumbra.GameData.Interop; @@ -21,7 +20,7 @@ public sealed partial class MtrlTab : IWritable, IDisposable private const int ShpkPrefixLength = 16; private static readonly CiByteString ShpkPrefix = CiByteString.FromSpanUnsafe("shader/sm5/shpk/"u8, true, true, true); - + private readonly IDataManager _gameData; private readonly IFramework _framework; private readonly ObjectManager _objects; @@ -40,7 +39,8 @@ public sealed partial class MtrlTab : IWritable, IDisposable private bool _updateOnNextFrame; public unsafe MtrlTab(IDataManager gameData, IFramework framework, ObjectManager objects, CharacterBaseDestructor characterBaseDestructor, - StainService stainService, ResourceTreeFactory resourceTreeFactory, FileDialogService fileDialog, MaterialTemplatePickers materialTemplatePickers, + StainService stainService, ResourceTreeFactory resourceTreeFactory, FileDialogService fileDialog, + MaterialTemplatePickers materialTemplatePickers, Configuration config, ModEditWindow edit, MtrlFile file, string filePath, bool writable) { _gameData = gameData; @@ -53,11 +53,11 @@ public sealed partial class MtrlTab : IWritable, IDisposable _materialTemplatePickers = materialTemplatePickers; _config = config; - _edit = edit; - Mtrl = file; - FilePath = filePath; - Writable = writable; - AssociatedBaseDevkit = TryLoadShpkDevkit("_base", out LoadedBaseDevkitPathName); + _edit = edit; + Mtrl = file; + FilePath = filePath; + Writable = writable; + _associatedBaseDevkit = TryLoadShpkDevkit("_base", out _loadedBaseDevkitPathName); Update(); LoadShpk(FindAssociatedShpk(out _, out _)); if (writable) @@ -118,7 +118,7 @@ public sealed partial class MtrlTab : IWritable, IDisposable using var dis = ImRaii.Disabled(disabled); var tmp = shaderFlags.EnableTransparency; - if (ImGui.Checkbox("Enable Transparency", ref tmp)) + if (ImUtf8.Checkbox("Enable Transparency"u8, ref tmp)) { shaderFlags.EnableTransparency = tmp; ret = true; @@ -127,14 +127,14 @@ public sealed partial class MtrlTab : IWritable, IDisposable ImGui.SameLine(200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); tmp = shaderFlags.HideBackfaces; - if (ImGui.Checkbox("Hide Backfaces", ref tmp)) + if (ImUtf8.Checkbox("Hide Backfaces"u8, ref tmp)) { shaderFlags.HideBackfaces = tmp; ret = true; SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); } - if (ShpkLoading) + if (_shpkLoading) { ImGui.SameLine(400 * UiHelpers.Scale + 2 * ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); @@ -147,32 +147,32 @@ public sealed partial class MtrlTab : IWritable, IDisposable private void DrawOtherMaterialDetails(bool _) { - if (!ImGui.CollapsingHeader("Further Content")) + if (!ImUtf8.CollapsingHeader("Further Content"u8)) return; - using (var sets = ImRaii.TreeNode("UV Sets", ImGuiTreeNodeFlags.DefaultOpen)) + using (var sets = ImUtf8.TreeNode("UV Sets"u8, ImGuiTreeNodeFlags.DefaultOpen)) { if (sets) foreach (var set in Mtrl.UvSets) - ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); + ImUtf8.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); } - using (var sets = ImRaii.TreeNode("Color Sets", ImGuiTreeNodeFlags.DefaultOpen)) + using (var sets = ImUtf8.TreeNode("Color Sets"u8, ImGuiTreeNodeFlags.DefaultOpen)) { if (sets) foreach (var set in Mtrl.ColorSets) - ImRaii.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); + ImUtf8.TreeNode($"#{set.Index:D2} - {set.Name}", ImGuiTreeNodeFlags.Leaf).Dispose(); } if (Mtrl.AdditionalData.Length <= 0) return; - using var t = ImRaii.TreeNode($"Additional Data (Size: {Mtrl.AdditionalData.Length})###AdditionalData"); + using var t = ImUtf8.TreeNode($"Additional Data (Size: {Mtrl.AdditionalData.Length})###AdditionalData"); if (t) Widget.DrawHexViewer(Mtrl.AdditionalData); } - public void Update() + private void Update() { UpdateShaders(); UpdateTextures(); @@ -187,12 +187,12 @@ public sealed partial class MtrlTab : IWritable, IDisposable } public bool Valid - => ShadersKnown && Mtrl.Valid; + => _shadersKnown && Mtrl.Valid; public byte[] Write() { var output = Mtrl.Clone(); - output.GarbageCollect(AssociatedShpk, SamplerIds); + output.GarbageCollect(_associatedShpk, SamplerIds); return output.Write(); } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs index af8b7db2..09db4277 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTabFactory.cs @@ -8,9 +8,16 @@ using Penumbra.Services; namespace Penumbra.UI.AdvancedWindow.Materials; -public sealed class MtrlTabFactory(IDataManager gameData, IFramework framework, ObjectManager objects, - CharacterBaseDestructor characterBaseDestructor, StainService stainService, ResourceTreeFactory resourceTreeFactory, - FileDialogService fileDialog, MaterialTemplatePickers materialTemplatePickers, Configuration config) : IUiService +public sealed class MtrlTabFactory( + IDataManager gameData, + IFramework framework, + ObjectManager objects, + CharacterBaseDestructor characterBaseDestructor, + StainService stainService, + ResourceTreeFactory resourceTreeFactory, + FileDialogService fileDialog, + MaterialTemplatePickers materialTemplatePickers, + Configuration config) : IUiService { public MtrlTab Create(ModEditWindow edit, MtrlFile file, string filePath, bool writable) => new(gameData, framework, objects, characterBaseDestructor, stainService, resourceTreeFactory, fileDialog, diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index ee883daf..59b38465 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; using OtterGui.Raii; +using OtterGui.Text; using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.UI.AdvancedWindow; @@ -24,7 +25,7 @@ public partial class ModEditWindow if (_editor.Files.Mdl.Count == 0) return; - using var tab = ImRaii.TabItem("Material Reassignment"); + using var tab = ImUtf8.TabItem("Material Reassignment"u8); if (!tab) return; @@ -32,45 +33,43 @@ public partial class ModEditWindow MaterialSuffix.Draw(_editor, ImGuiHelpers.ScaledVector2(175, 0)); ImGui.NewLine(); - using var child = ImRaii.Child("##mdlFiles", -Vector2.One, true); + using var child = ImUtf8.Child("##mdlFiles"u8, -Vector2.One, true); if (!child) return; - using var table = ImRaii.Table("##files", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.One); + using var table = ImUtf8.Table("##files"u8, 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.One); if (!table) return; - var iconSize = ImGui.GetFrameHeight() * Vector2.One; foreach (var (info, idx) in _editor.MdlMaterialEditor.ModelFiles.WithIndex()) { using var id = ImRaii.PushId(idx); ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), iconSize, - "Save the changed mdl file.\nUse at own risk!", !info.Changed, true)) + if (ImUtf8.IconButton(FontAwesomeIcon.Save, "Save the changed mdl file.\nUse at own risk!"u8, disabled: !info.Changed)) info.Save(_editor.Compactor); ImGui.TableNextColumn(); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Recycle.ToIconString(), iconSize, - "Restore current changes to default.", !info.Changed, true)) + if (ImUtf8.IconButton(FontAwesomeIcon.Recycle, "Restore current changes to default."u8, disabled: !info.Changed)) info.Restore(); ImGui.TableNextColumn(); - ImGui.TextUnformatted(info.Path.FullName[(Mod!.ModPath.FullName.Length + 1)..]); + ImUtf8.Text(info.Path.InternalName.Span[(Mod!.ModPath.FullName.Length + 1)..]); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(400 * UiHelpers.Scale); var tmp = info.CurrentMaterials[0]; - if (ImGui.InputText("##0", ref tmp, 64)) + if (ImUtf8.InputText("##0"u8, ref tmp)) info.SetMaterial(tmp, 0); for (var i = 1; i < info.Count; ++i) { + using var id2 = ImUtf8.PushId(i); ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.SetNextItemWidth(400 * UiHelpers.Scale); tmp = info.CurrentMaterials[i]; - if (ImGui.InputText($"##{i}", ref tmp, 64)) + if (ImUtf8.InputText(""u8, ref tmp)) info.SetMaterial(tmp, i); } } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 8a1c729c..41f1da26 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -10,7 +10,6 @@ using Penumbra.GameData.Interop; using Penumbra.String; using static Penumbra.GameData.Files.ShpkFile; using OtterGui.Widgets; -using Penumbra.GameData.Files.ShaderStructs; using OtterGui.Text; using Penumbra.GameData.Structs; @@ -56,21 +55,17 @@ public partial class ModEditWindow private static void DrawShaderPackageSummary(ShpkTab tab) { if (tab.Shpk.IsLegacy) - { ImUtf8.Text("This legacy shader package will not work in the current version of the game. Do not attempt to load it.", ImGuiUtil.HalfBlendText(0x80u)); // Half red - } - ImGui.TextUnformatted(tab.Header); + ImUtf8.Text(tab.Header); if (!tab.Shpk.Disassembled) - { ImUtf8.Text("Your system doesn't support disassembling shaders. Some functionality will be missing.", ImGuiUtil.HalfBlendText(0x80u)); // Half red - } } private static void DrawShaderExportButton(ShpkTab tab, string objectName, Shader shader, int idx) { - if (!ImGui.Button($"Export Shader Program Blob ({shader.Blob.Length} bytes)")) + if (!ImUtf8.Button($"Export Shader Program Blob ({shader.Blob.Length} bytes)")) return; var defaultName = objectName[0] switch @@ -106,7 +101,7 @@ public partial class ModEditWindow private static void DrawShaderImportButton(ShpkTab tab, string objectName, Shader[] shaders, int idx) { - if (!ImGui.Button("Replace Shader Program Blob")) + if (!ImUtf8.Button("Replace Shader Program Blob"u8)) return; tab.FileDialog.OpenFilePicker($"Replace {objectName} #{idx} Program Blob...", "Shader Program Blobs{.o,.cso,.dxbc,.dxil}", @@ -145,8 +140,8 @@ public partial class ModEditWindow private static unsafe void DrawRawDisassembly(Shader shader) { - using var t2 = ImRaii.TreeNode("Raw Program Disassembly"); - if (!t2) + using var tree = ImUtf8.TreeNode("Raw Program Disassembly"u8); + if (!tree) return; using var font = ImRaii.PushFont(UiBuilder.MonoFont); @@ -164,31 +159,34 @@ public partial class ModEditWindow { foreach (var (key, keyIdx) in shader.SystemValues!.WithIndex()) { - ImRaii.TreeNode($"Used with System Key {tab.TryResolveName(tab.Shpk.SystemKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", + ImUtf8.TreeNode( + $"Used with System Key {tab.TryResolveName(tab.Shpk.SystemKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in shader.SceneValues!.WithIndex()) { - ImRaii.TreeNode($"Used with Scene Key {tab.TryResolveName(tab.Shpk.SceneKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", + ImUtf8.TreeNode( + $"Used with Scene Key {tab.TryResolveName(tab.Shpk.SceneKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in shader.MaterialValues!.WithIndex()) { - ImRaii.TreeNode($"Used with Material Key {tab.TryResolveName(tab.Shpk.MaterialKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", + ImUtf8.TreeNode( + $"Used with Material Key {tab.TryResolveName(tab.Shpk.MaterialKeys[keyIdx].Id)} \u2208 {{ {tab.NameSetToString(key)} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in shader.SubViewValues!.WithIndex()) { - ImRaii.TreeNode($"Used with Sub-View Key #{keyIdx} \u2208 {{ {tab.NameSetToString(key)} }}", + ImUtf8.TreeNode($"Used with Sub-View Key #{keyIdx} \u2208 {{ {tab.NameSetToString(key)} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } } } - ImRaii.TreeNode($"Used in Passes: {tab.NameSetToString(shader.Passes)}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Used in Passes: {tab.NameSetToString(shader.Passes)}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } private static void DrawShaderPackageFilterSection(ShpkTab tab) @@ -215,19 +213,20 @@ public partial class ModEditWindow { if (values.PossibleValues == null) { - ImRaii.TreeNode(label, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode(label, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); return; } - using var node = ImRaii.TreeNode(label); + using var node = ImUtf8.TreeNode(label); if (!node) return; foreach (var value in values.PossibleValues) { var contains = values.Contains(value); - if (!ImGui.Checkbox($"{tab.TryResolveName(value)}", ref contains)) + if (!ImUtf8.Checkbox($"{tab.TryResolveName(value)}", ref contains)) continue; + if (contains) { if (values.AddExisting(value)) @@ -249,7 +248,7 @@ public partial class ModEditWindow private static bool DrawShaderPackageShaderArray(ShpkTab tab, string objectName, Shader[] shaders, bool disabled) { - if (shaders.Length == 0 || !ImGui.CollapsingHeader($"{objectName}s")) + if (shaders.Length == 0 || !ImUtf8.CollapsingHeader($"{objectName}s")) return false; var ret = false; @@ -259,7 +258,7 @@ public partial class ModEditWindow if (!tab.IsFilterMatch(shader)) continue; - using var t = ImRaii.TreeNode($"{objectName} #{idx}"); + using var t = ImUtf8.TreeNode($"{objectName} #{idx}"); if (!t) continue; @@ -270,20 +269,20 @@ public partial class ModEditWindow DrawShaderImportButton(tab, objectName, shaders, idx); } - ret |= DrawShaderPackageResourceArray("Constant Buffers", "slot", true, shader.Constants, false, true); - ret |= DrawShaderPackageResourceArray("Samplers", "slot", false, shader.Samplers, false, true); + ret |= DrawShaderPackageResourceArray("Constant Buffers", "slot", true, shader.Constants, false, true); + ret |= DrawShaderPackageResourceArray("Samplers", "slot", false, shader.Samplers, false, true); if (!tab.Shpk.IsLegacy) - ret |= DrawShaderPackageResourceArray("Textures", "slot", false, shader.Textures, false, true); - ret |= DrawShaderPackageResourceArray("Unordered Access Views", "slot", true, shader.Uavs, false, true); + ret |= DrawShaderPackageResourceArray("Textures", "slot", false, shader.Textures, false, true); + ret |= DrawShaderPackageResourceArray("Unordered Access Views", "slot", true, shader.Uavs, false, true); if (shader.DeclaredInputs != 0) - ImRaii.TreeNode($"Declared Inputs: {shader.DeclaredInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Declared Inputs: {shader.DeclaredInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); if (shader.UsedInputs != 0) - ImRaii.TreeNode($"Used Inputs: {shader.UsedInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Used Inputs: {shader.UsedInputs}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); if (shader.AdditionalHeader.Length > 8) { - using var t2 = ImRaii.TreeNode($"Additional Header (Size: {shader.AdditionalHeader.Length})###AdditionalHeader"); + using var t2 = ImUtf8.TreeNode($"Additional Header (Size: {shader.AdditionalHeader.Length})###AdditionalHeader"); if (t2) Widget.DrawHexViewer(shader.AdditionalHeader); } @@ -313,23 +312,28 @@ public partial class ModEditWindow var usedString = UsedComponentString(withSize, false, resource); if (usedString.Length > 0) { - ImRaii.TreeNode(hasFilter ? $"Globally Used: {usedString}" : $"Used: {usedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode(hasFilter ? $"Globally Used: {usedString}" : $"Used: {usedString}", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); if (hasFilter) { var filteredUsedString = UsedComponentString(withSize, true, resource); if (filteredUsedString.Length > 0) - ImRaii.TreeNode($"Used within Filters: {filteredUsedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Used within Filters: {filteredUsedString}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) + .Dispose(); else - ImRaii.TreeNode("Unused within Filters", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode("Unused within Filters"u8, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } } else - ImRaii.TreeNode(hasFilter ? "Globally Unused" : "Unused", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + { + ImUtf8.TreeNode(hasFilter ? "Globally Unused"u8 : "Unused"u8, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + } return ret; } - private static bool DrawShaderPackageResourceArray(string arrayName, string slotLabel, bool withSize, Resource[] resources, bool hasFilter, bool disabled) + private static bool DrawShaderPackageResourceArray(string arrayName, string slotLabel, bool withSize, Resource[] resources, bool hasFilter, + bool disabled) { if (resources.Length == 0) return false; @@ -345,8 +349,8 @@ public partial class ModEditWindow var name = $"#{idx}: {buf.Name} (ID: 0x{buf.Id:X8}), {slotLabel}: {buf.Slot}" + (withSize ? $", size: {buf.Size} registers###{idx}: {buf.Name} (ID: 0x{buf.Id:X8})" : string.Empty); using var font = ImRaii.PushFont(UiBuilder.MonoFont); - using var t2 = ImRaii.TreeNode(name, !disabled || buf.Used != null ? 0 : ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); - font.Dispose(); + using var t2 = ImUtf8.TreeNode(name, !disabled || buf.Used != null ? 0 : ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); + font.Pop(); if (t2) ret |= DrawShaderPackageResource(slotLabel, withSize, ref buf, hasFilter, disabled); } @@ -361,7 +365,7 @@ public partial class ModEditWindow + new Vector2(ImGui.CalcTextSize(label).X + 3 * ImGui.GetStyle().ItemInnerSpacing.X + ImGui.GetFrameHeight(), ImGui.GetStyle().FramePadding.Y); - var ret = ImGui.CollapsingHeader(label); + var ret = ImUtf8.CollapsingHeader(label); ImGui.GetWindowDrawList() .AddText(UiBuilder.DefaultFont, UiBuilder.DefaultFont.FontSize, pos, ImGui.GetColorU32(ImGuiCol.Text), "Layout"); return ret; @@ -374,7 +378,7 @@ public partial class ModEditWindow if (isSizeWellDefined) return true; - ImGui.TextUnformatted(materialParams.HasValue + ImUtf8.Text(materialParams.HasValue ? $"Buffer size mismatch: {file.MaterialParamsSize} bytes ≠ {materialParams.Value.Size} registers ({materialParams.Value.Size << 4} bytes)" : $"Buffer size mismatch: {file.MaterialParamsSize} bytes, not a multiple of 16"); return false; @@ -382,7 +386,7 @@ public partial class ModEditWindow private static bool DrawShaderPackageMaterialMatrix(ShpkTab tab, bool disabled) { - ImGui.TextUnformatted(tab.Shpk.Disassembled + ImUtf8.Text(tab.Shpk.Disassembled ? "Parameter positions (continuations are grayed out, globally unused values are red, unused values within filters are yellow):" : "Parameter positions (continuations are grayed out):"); @@ -398,10 +402,7 @@ public partial class ModEditWindow ImGui.TableSetupColumn("w", ImGuiTableColumnFlags.WidthFixed, 250 * UiHelpers.Scale); ImGui.TableHeadersRow(); - var textColorStart = ImGui.GetColorU32(ImGuiCol.Text); - var textColorCont = ImGuiUtil.HalfTransparent(textColorStart); // Half opacity - var textColorUnusedStart = ImGuiUtil.HalfBlend(textColorStart, 0x80u); // Half red - var textColorUnusedCont = ImGuiUtil.HalfTransparent(textColorUnusedStart); + var textColorStart = ImGui.GetColorU32(ImGuiCol.Text); var ret = false; for (var i = 0; i < tab.Matrix.GetLength(0); ++i) @@ -420,12 +421,12 @@ public partial class ModEditWindow color = ImGuiUtil.HalfTransparent(color); // Half opacity using var _ = ImRaii.PushId(i * 4 + j); var deletable = !disabled && idx >= 0; - using (var font = ImRaii.PushFont(UiBuilder.MonoFont, tooltip.Length > 0)) + using (ImRaii.PushFont(UiBuilder.MonoFont, tooltip.Length > 0)) { - using (var c = ImRaii.PushColor(ImGuiCol.Text, color)) + using (ImRaii.PushColor(ImGuiCol.Text, color)) { ImGui.TableNextColumn(); - ImGui.Selectable(name); + ImUtf8.Selectable(name); if (deletable && ImGui.IsItemClicked(ImGuiMouseButton.Right) && ImGui.GetIO().KeyCtrl) { tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.RemoveItems(idx); @@ -434,11 +435,11 @@ public partial class ModEditWindow } } - ImGuiUtil.HoverTooltip(tooltip); + ImUtf8.HoverTooltip(tooltip); } if (deletable) - ImGuiUtil.HoverTooltip("\nControl + Right-Click to remove."); + ImUtf8.HoverTooltip("\nControl + Right-Click to remove."u8); } } @@ -450,7 +451,9 @@ public partial class ModEditWindow if (!ImUtf8.Button("Export globally unused parameters as material dev-kit file"u8)) return; - tab.FileDialog.OpenSavePicker("Export material dev-kit file", ".json", $"{Path.GetFileNameWithoutExtension(tab.FilePath)}.json", ".json", DoSave, null, false); + tab.FileDialog.OpenSavePicker("Export material dev-kit file", ".json", $"{Path.GetFileNameWithoutExtension(tab.FilePath)}.json", + ".json", DoSave, null, false); + return; void DoSave(bool success, string path) { @@ -476,22 +479,22 @@ public partial class ModEditWindow private static void DrawShaderPackageMisalignedParameters(ShpkTab tab) { - using var t = ImRaii.TreeNode("Misaligned / Overflowing Parameters"); + using var t = ImUtf8.TreeNode("Misaligned / Overflowing Parameters"u8); if (!t) return; using var _ = ImRaii.PushFont(UiBuilder.MonoFont); foreach (var name in tab.MalformedParameters) - ImRaii.TreeNode(name, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode(name, ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } private static void DrawShaderPackageStartCombo(ShpkTab tab) { using var s = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemInnerSpacing); - using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) + using (ImRaii.PushFont(UiBuilder.MonoFont)) { ImGui.SetNextItemWidth(UiHelpers.Scale * 400); - using var c = ImRaii.Combo("##Start", tab.Orphans[tab.NewMaterialParamStart].Name); + using var c = ImUtf8.Combo("##Start", tab.Orphans[tab.NewMaterialParamStart].Name); if (c) foreach (var (start, idx) in tab.Orphans.WithIndex()) { @@ -501,7 +504,7 @@ public partial class ModEditWindow } ImGui.SameLine(); - ImGui.TextUnformatted("Start"); + ImUtf8.Text("Start"u8); } private static void DrawShaderPackageEndCombo(ShpkTab tab) @@ -510,7 +513,7 @@ public partial class ModEditWindow using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) { ImGui.SetNextItemWidth(UiHelpers.Scale * 400); - using var c = ImRaii.Combo("##End", tab.Orphans[tab.NewMaterialParamEnd].Name); + using var c = ImUtf8.Combo("##End", tab.Orphans[tab.NewMaterialParamEnd].Name); if (c) { var current = tab.Orphans[tab.NewMaterialParamStart].Index; @@ -527,7 +530,7 @@ public partial class ModEditWindow } ImGui.SameLine(); - ImGui.TextUnformatted("End"); + ImUtf8.Text("End"u8); } private static bool DrawShaderPackageNewParameter(ShpkTab tab) @@ -540,15 +543,14 @@ public partial class ModEditWindow ImGui.SetNextItemWidth(UiHelpers.Scale * 400); var newName = tab.NewMaterialParamName.Value!; - if (ImGui.InputText("Name", ref newName, 63)) + if (ImUtf8.InputText("Name", ref newName)) tab.NewMaterialParamName = newName; var tooltip = tab.UsedIds.Contains(tab.NewMaterialParamName.Crc32) - ? "The ID is already in use. Please choose a different name." - : string.Empty; - if (!ImGuiUtil.DrawDisabledButton($"Add {tab.NewMaterialParamName} (0x{tab.NewMaterialParamName.Crc32:X8})", new Vector2(400 * UiHelpers.Scale, ImGui.GetFrameHeight()), - tooltip, - tooltip.Length > 0)) + ? "The ID is already in use. Please choose a different name."u8 + : ""u8; + if (!ImUtf8.ButtonEx($"Add {tab.NewMaterialParamName} (0x{tab.NewMaterialParamName.Crc32:X8})", tooltip, + new Vector2(400 * UiHelpers.Scale, ImGui.GetFrameHeight()), tooltip.Length > 0)) return false; tab.Shpk.MaterialParams = tab.Shpk.MaterialParams.AddItem(new MaterialParam @@ -589,15 +591,15 @@ public partial class ModEditWindow { var ret = false; - if (!ImGui.CollapsingHeader("Shader Resources")) + if (!ImUtf8.CollapsingHeader("Shader Resources"u8)) return false; var hasFilters = tab.FilterPopCount != tab.FilterMaximumPopCount; - ret |= DrawShaderPackageResourceArray("Constant Buffers", "type", true, tab.Shpk.Constants, hasFilters, disabled); - ret |= DrawShaderPackageResourceArray("Samplers", "type", false, tab.Shpk.Samplers, hasFilters, disabled); + ret |= DrawShaderPackageResourceArray("Constant Buffers", "type", true, tab.Shpk.Constants, hasFilters, disabled); + ret |= DrawShaderPackageResourceArray("Samplers", "type", false, tab.Shpk.Samplers, hasFilters, disabled); if (!tab.Shpk.IsLegacy) - ret |= DrawShaderPackageResourceArray("Textures", "type", false, tab.Shpk.Textures, hasFilters, disabled); - ret |= DrawShaderPackageResourceArray("Unordered Access Views", "type", false, tab.Shpk.Uavs, hasFilters, disabled); + ret |= DrawShaderPackageResourceArray("Textures", "type", false, tab.Shpk.Textures, hasFilters, disabled); + ret |= DrawShaderPackageResourceArray("Unordered Access Views", "type", false, tab.Shpk.Uavs, hasFilters, disabled); return ret; } @@ -607,18 +609,20 @@ public partial class ModEditWindow if (keys.Count == 0) return; - using var t = ImRaii.TreeNode(arrayName); + using var t = ImUtf8.TreeNode(arrayName); if (!t) return; using var font = ImRaii.PushFont(UiBuilder.MonoFont); foreach (var (key, idx) in keys.WithIndex()) { - using var t2 = ImRaii.TreeNode(withId ? $"#{idx}: {tab.TryResolveName(key.Id)} (0x{key.Id:X8})" : $"#{idx}"); + using var t2 = ImUtf8.TreeNode(withId ? $"#{idx}: {tab.TryResolveName(key.Id)} (0x{key.Id:X8})" : $"#{idx}"); if (t2) { - ImRaii.TreeNode($"Default Value: {tab.TryResolveName(key.DefaultValue)} (0x{key.DefaultValue:X8})", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); - ImRaii.TreeNode($"Known Values: {tab.NameSetToString(key.Values, true)}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Default Value: {tab.TryResolveName(key.DefaultValue)} (0x{key.DefaultValue:X8})", + ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Known Values: {tab.NameSetToString(key.Values, true)}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) + .Dispose(); } } } @@ -628,7 +632,7 @@ public partial class ModEditWindow if (tab.Shpk.Nodes.Length <= 0) return; - using var t = ImRaii.TreeNode($"Nodes ({tab.Shpk.Nodes.Length})###Nodes"); + using var t = ImUtf8.TreeNode($"Nodes ({tab.Shpk.Nodes.Length})###Nodes"); if (!t) return; @@ -639,39 +643,44 @@ public partial class ModEditWindow if (!tab.IsFilterMatch(node)) continue; - using var t2 = ImRaii.TreeNode($"#{idx:D4}: Selector: 0x{node.Selector:X8}"); + using var t2 = ImUtf8.TreeNode($"#{idx:D4}: Selector: 0x{node.Selector:X8}"); if (!t2) continue; foreach (var (key, keyIdx) in node.SystemKeys.WithIndex()) { - ImRaii.TreeNode($"System Key {tab.TryResolveName(tab.Shpk.SystemKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SystemValues![keyIdx])} }}", + ImUtf8.TreeNode( + $"System Key {tab.TryResolveName(tab.Shpk.SystemKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SystemValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in node.SceneKeys.WithIndex()) { - ImRaii.TreeNode($"Scene Key {tab.TryResolveName(tab.Shpk.SceneKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SceneValues![keyIdx])} }}", + ImUtf8.TreeNode( + $"Scene Key {tab.TryResolveName(tab.Shpk.SceneKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SceneValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in node.MaterialKeys.WithIndex()) { - ImRaii.TreeNode($"Material Key {tab.TryResolveName(tab.Shpk.MaterialKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.MaterialValues![keyIdx])} }}", + ImUtf8.TreeNode( + $"Material Key {tab.TryResolveName(tab.Shpk.MaterialKeys[keyIdx].Id)} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.MaterialValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } foreach (var (key, keyIdx) in node.SubViewKeys.WithIndex()) { - ImRaii.TreeNode($"Sub-View Key #{keyIdx} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SubViewValues![keyIdx])} }}", + ImUtf8.TreeNode( + $"Sub-View Key #{keyIdx} = {tab.TryResolveName(key)} / \u2208 {{ {tab.NameSetToString(node.SubViewValues![keyIdx])} }}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); } - ImRaii.TreeNode($"Pass Indices: {string.Join(' ', node.PassIndices.Select(c => $"{c:X2}"))}", + ImUtf8.TreeNode($"Pass Indices: {string.Join(' ', node.PassIndices.Select(c => $"{c:X2}"))}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); foreach (var (pass, passIdx) in node.Passes.WithIndex()) { - ImRaii.TreeNode($"Pass #{passIdx}: ID: {tab.TryResolveName(pass.Id)}, Vertex Shader #{pass.VertexShader}, Pixel Shader #{pass.PixelShader}", + ImUtf8.TreeNode( + $"Pass #{passIdx}: ID: {tab.TryResolveName(pass.Id)}, Vertex Shader #{pass.VertexShader}, Pixel Shader #{pass.PixelShader}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) .Dispose(); } @@ -680,7 +689,7 @@ public partial class ModEditWindow private static void DrawShaderPackageSelection(ShpkTab tab) { - if (!ImGui.CollapsingHeader("Shader Selection")) + if (!ImUtf8.CollapsingHeader("Shader Selection"u8)) return; DrawKeyArray(tab, "System Keys", true, tab.Shpk.SystemKeys); @@ -689,13 +698,13 @@ public partial class ModEditWindow DrawKeyArray(tab, "Sub-View Keys", false, tab.Shpk.SubViewKeys); DrawShaderPackageNodes(tab); - using var t = ImRaii.TreeNode($"Node Selectors ({tab.Shpk.NodeSelectors.Count})###NodeSelectors"); + using var t = ImUtf8.TreeNode($"Node Selectors ({tab.Shpk.NodeSelectors.Count})###NodeSelectors"); if (t) { using var font = ImRaii.PushFont(UiBuilder.MonoFont); foreach (var selector in tab.Shpk.NodeSelectors) { - ImRaii.TreeNode($"#{selector.Value:D4}: Selector: 0x{selector.Key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) + ImUtf8.TreeNode($"#{selector.Value:D4}: Selector: 0x{selector.Key:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet) .Dispose(); } } @@ -703,14 +712,14 @@ public partial class ModEditWindow private static void DrawOtherShaderPackageDetails(ShpkTab tab) { - if (!ImGui.CollapsingHeader("Further Content")) + if (!ImUtf8.CollapsingHeader("Further Content"u8)) return; - ImRaii.TreeNode($"Version: 0x{tab.Shpk.Version:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); + ImUtf8.TreeNode($"Version: 0x{tab.Shpk.Version:X8}", ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet).Dispose(); if (tab.Shpk.AdditionalData.Length > 0) { - using var t = ImRaii.TreeNode($"Additional Data (Size: {tab.Shpk.AdditionalData.Length})###AdditionalData"); + using var t = ImUtf8.TreeNode($"Additional Data (Size: {tab.Shpk.AdditionalData.Length})###AdditionalData"); if (t) Widget.DrawHexViewer(tab.Shpk.AdditionalData); } @@ -718,9 +727,9 @@ public partial class ModEditWindow private static string UsedComponentString(bool withSize, bool filtered, in Resource resource) { - var used = filtered ? resource.FilteredUsed : resource.Used; + var used = filtered ? resource.FilteredUsed : resource.Used; var usedDynamically = filtered ? resource.FilteredUsedDynamically : resource.UsedDynamically; - var sb = new StringBuilder(256); + var sb = new StringBuilder(256); if (withSize) { foreach (var (components, i) in (used ?? Array.Empty()).WithIndex()) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index de20aa9f..b5b39e90 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -21,11 +21,11 @@ public partial class ModEditWindow public short NewMaterialParamStart; public short NewMaterialParamEnd; - public SharedSet[] FilterSystemValues; - public SharedSet[] FilterSceneValues; - public SharedSet[] FilterMaterialValues; - public SharedSet[] FilterSubViewValues; - public SharedSet FilterPasses; + public readonly SharedSet[] FilterSystemValues; + public readonly SharedSet[] FilterSceneValues; + public readonly SharedSet[] FilterMaterialValues; + public readonly SharedSet[] FilterSubViewValues; + public SharedSet FilterPasses; public readonly int FilterMaximumPopCount; public int FilterPopCount; @@ -46,6 +46,7 @@ public partial class ModEditWindow { Shpk = new ShpkFile(bytes, false); } + FilePath = filePath; Header = $"Shader Package for DirectX {(int)Shpk.DirectXVersion}"; @@ -105,13 +106,21 @@ public partial class ModEditWindow _nameSetWithIdsCache.Clear(); } - public void UpdateNameCache() + private void UpdateNameCache() { - static void CollectResourceNames(Dictionary nameCache, ShpkFile.Resource[] resources) - { - foreach (var resource in resources) - nameCache.TryAdd(resource.Id, resource.Name); - } + CollectResourceNames(_nameCache, Shpk.Constants); + CollectResourceNames(_nameCache, Shpk.Samplers); + CollectResourceNames(_nameCache, Shpk.Textures); + CollectResourceNames(_nameCache, Shpk.Uavs); + + CollectKeyNames(_nameCache, Shpk.SystemKeys); + CollectKeyNames(_nameCache, Shpk.SceneKeys); + CollectKeyNames(_nameCache, Shpk.MaterialKeys); + CollectKeyNames(_nameCache, Shpk.SubViewKeys); + + _nameSetCache.Clear(); + _nameSetWithIdsCache.Clear(); + return; static void CollectKeyNames(Dictionary nameCache, ShpkFile.Key[] keys) { @@ -128,18 +137,11 @@ public partial class ModEditWindow } } - CollectResourceNames(_nameCache, Shpk.Constants); - CollectResourceNames(_nameCache, Shpk.Samplers); - CollectResourceNames(_nameCache, Shpk.Textures); - CollectResourceNames(_nameCache, Shpk.Uavs); - - CollectKeyNames(_nameCache, Shpk.SystemKeys); - CollectKeyNames(_nameCache, Shpk.SceneKeys); - CollectKeyNames(_nameCache, Shpk.MaterialKeys); - CollectKeyNames(_nameCache, Shpk.SubViewKeys); - - _nameSetCache.Clear(); - _nameSetWithIdsCache.Clear(); + static void CollectResourceNames(Dictionary nameCache, ShpkFile.Resource[] resources) + { + foreach (var resource in resources) + nameCache.TryAdd(resource.Id, resource.Name); + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -151,6 +153,7 @@ public partial class ModEditWindow var cache = withIds ? _nameSetWithIdsCache : _nameSetCache; if (cache.TryGetValue(nameSet, out var nameSetStr)) return nameSetStr; + if (withIds) nameSetStr = string.Join(", ", nameSet.Select(id => $"{TryResolveName(id)} (0x{id:X8})")); else @@ -186,7 +189,8 @@ public partial class ModEditWindow var jEnd = ((param.ByteOffset + param.ByteSize - 1) >> 2) & 3; if ((param.ByteOffset & 0x3) != 0 || (param.ByteSize & 0x3) != 0) { - MalformedParameters.Add($"ID: {TryResolveName(param.Id)} (0x{param.Id:X8}), offset: 0x{param.ByteOffset:X4}, size: 0x{param.ByteSize:X4}"); + MalformedParameters.Add( + $"ID: {TryResolveName(param.Id)} (0x{param.Id:X8}), offset: 0x{param.ByteOffset:X4}, size: 0x{param.ByteSize:X4}"); continue; } @@ -206,7 +210,8 @@ public partial class ModEditWindow var tt = $"{MtrlTab.MaterialParamRangeName(materialParams?.Name ?? string.Empty, param.ByteOffset >> 2, param.ByteSize >> 2).Item1} ({TryResolveName(param.Id)}, 0x{param.Id:X8})"; if (component < defaultFloats.Length) - tt += $"\n\nDefault value: {defaultFloats[component]} ({defaults[component << 2]:X2} {defaults[(component << 2) | 1]:X2} {defaults[(component << 2) | 2]:X2} {defaults[(component << 2) | 3]:X2})"; + tt += + $"\n\nDefault value: {defaultFloats[component]} ({defaults[component << 2]:X2} {defaults[(component << 2) | 1]:X2} {defaults[(component << 2) | 2]:X2} {defaults[(component << 2) | 3]:X2})"; Matrix[i, j] = (TryResolveName(param.Id).ToString(), tt, (short)idx, 0); } } @@ -265,7 +270,8 @@ public partial class ModEditWindow if (oldStart == linear) newMaterialParamStart = (short)Orphans.Count; - Orphans.Add(($"{materialParams?.Name ?? ShpkFile.MaterialParamsConstantName}{MtrlTab.MaterialParamName(false, linear)}", linear)); + Orphans.Add(($"{materialParams?.Name ?? ShpkFile.MaterialParamsConstantName}{MtrlTab.MaterialParamName(false, linear)}", + linear)); } } @@ -407,7 +413,6 @@ public partial class ModEditWindow var unusedSlices = new JArray(); if (materialParameterUsage.Indices(start, length).Any()) - { foreach (var (rgStart, rgEnd) in materialParameterUsage.Ranges(start, length, true)) { unusedSlices.Add(new JObject @@ -417,14 +422,11 @@ public partial class ModEditWindow ["Length"] = rgEnd - rgStart, }); } - } else - { unusedSlices.Add(new JObject { ["Type"] = "Hidden", }); - } dkConstants[param.Id.ToString()] = unusedSlices; } From 6d42673aa4a3d9e289cc7d1ed1a8993ce1980a9e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 4 Aug 2024 22:52:53 +0200 Subject: [PATCH 0841/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index f2734d54..8ee82929 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f2734d543d9b2debecb8feb6d6fa928801eb2bcb +Subproject commit 8ee82929fa6c725b8f556904ba022fb418991b5c From e91e0b23f8ffd9e01e9e139786ff0f7167a9e78a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 4 Aug 2024 23:18:18 +0200 Subject: [PATCH 0842/1381] Unused usings. --- Penumbra/Penumbra.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 557e011c..438cdc49 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -17,10 +17,8 @@ using Penumbra.UI.Tabs; using ChangedItemClick = Penumbra.Communication.ChangedItemClick; using ChangedItemHover = Penumbra.Communication.ChangedItemHover; using OtterGui.Tasks; -using Penumbra.GameData.Enums; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; -using System.Xml.Linq; using Dalamud.Plugin.Services; using Penumbra.GameData.Data; using Penumbra.Interop.Hooks; From 0064c4c96e04f29a90018e84e3a1fd3747eef0b7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 4 Aug 2024 21:23:13 +0000 Subject: [PATCH 0843/1381] [CI] Updating repo.json for testing_1.2.0.20 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index cbe2b121..ad1cbef0 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.19", + "TestingAssemblyVersion": "1.2.0.20", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.19/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.20/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a5859761906db84e24ae1fcf8648530f9940c5aa Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 5 Aug 2024 00:41:39 +0200 Subject: [PATCH 0844/1381] Make ImcChecker threadsafe. --- Penumbra/Meta/ImcChecker.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Penumbra/Meta/ImcChecker.cs b/Penumbra/Meta/ImcChecker.cs index 751113a0..4e3ff11b 100644 --- a/Penumbra/Meta/ImcChecker.cs +++ b/Penumbra/Meta/ImcChecker.cs @@ -12,12 +12,16 @@ public class ImcChecker public static int GetVariantCount(ImcIdentifier identifier) { - if (VariantCounts.TryGetValue(identifier, out var count)) - return count; + lock (VariantCounts) + { + if (VariantCounts.TryGetValue(identifier, out var count)) + return count; - count = GetFile(identifier)?.Count ?? 0; - VariantCounts[identifier] = count; - return count; + count = GetFile(identifier)?.Count ?? 0; + VariantCounts[identifier] = count; + + return count; + } } public readonly record struct CachedEntry(ImcEntry Entry, bool FileExists, bool VariantExists); From 2534f119e9c6a35c5280309f64cb3bdd9289d8c7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 5 Aug 2024 00:41:55 +0200 Subject: [PATCH 0845/1381] Make StainService deal with early-loading. --- Penumbra/Services/StainService.cs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index ba5c3e63..0a437da0 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -16,7 +16,8 @@ namespace Penumbra.Services; public class StainService : IService { public sealed class StainTemplateCombo(FilterComboColors[] stainCombos, StmFile stmFile) - : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) where TDyePack : unmanaged, IDyePack + : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) + where TDyePack : unmanaged, IDyePack { // FIXME There might be a better way to handle that. public int CurrentDyeChannel = 0; @@ -80,11 +81,21 @@ public class StainService : IService public unsafe StainService(IDataManager dataManager, CharacterUtility characterUtility, DictStain stainData) { - StainData = stainData; - StainCombo1 = CreateStainCombo(); - StainCombo2 = CreateStainCombo(); - LegacyStmFile = LoadStmFile(characterUtility.Address->LegacyStmResource, dataManager); - GudStmFile = LoadStmFile(characterUtility.Address->GudStmResource, dataManager); + StainData = stainData; + StainCombo1 = CreateStainCombo(); + StainCombo2 = CreateStainCombo(); + + if (characterUtility.Address == null) + { + LegacyStmFile = LoadStmFile(null, dataManager); + GudStmFile = LoadStmFile(null, dataManager); + } + else + { + LegacyStmFile = LoadStmFile(characterUtility.Address->LegacyStmResource, dataManager); + GudStmFile = LoadStmFile(characterUtility.Address->GudStmResource, dataManager); + } + FilterComboColors[] stainCombos = [StainCombo1, StainCombo2]; @@ -98,11 +109,13 @@ public class StainService : IService { 0 => StainCombo1, 1 => StainCombo2, - _ => throw new ArgumentOutOfRangeException(nameof(channel), channel, $"Unsupported dye channel {channel} (supported values are 0 and 1)") + _ => throw new ArgumentOutOfRangeException(nameof(channel), channel, + $"Unsupported dye channel {channel} (supported values are 0 and 1)"), }; /// Loads a STM file. Opportunistically attempts to re-use the file already read by the game, with Lumina fallback. - private static unsafe StmFile LoadStmFile(ResourceHandle* stmResourceHandle, IDataManager dataManager) where TDyePack : unmanaged, IDyePack + private static unsafe StmFile LoadStmFile(ResourceHandle* stmResourceHandle, IDataManager dataManager) + where TDyePack : unmanaged, IDyePack { if (stmResourceHandle != null) { From 1b5553284c102449bbd986be10e57259f2cb4bf4 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 4 Aug 2024 22:44:50 +0000 Subject: [PATCH 0846/1381] [CI] Updating repo.json for testing_1.2.0.21 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index ad1cbef0..10a08fa1 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.20", + "TestingAssemblyVersion": "1.2.0.21", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.20/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.21/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 700fef4f04c283aada11ac2379bde2d5de7fb98a Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 5 Aug 2024 03:41:35 +0200 Subject: [PATCH 0847/1381] Move hook to MaterialResourceHandle.Load (inlining my beloathed) --- Penumbra.GameData | 2 +- .../{MtrlShpkLoaded.cs => MtrlLoaded.cs} | 4 ++-- Penumbra/Interop/Hooks/HookSettings.cs | 2 +- .../Hooks/PostProcessing/ShaderReplacementFixer.cs | 6 +++--- .../Resources/{LoadMtrlShpk.cs => LoadMtrl.cs} | 14 +++++++------- Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs | 1 + Penumbra/Services/CommunicatorService.cs | 6 +++--- 7 files changed, 18 insertions(+), 17 deletions(-) rename Penumbra/Communication/{MtrlShpkLoaded.cs => MtrlLoaded.cs} (73%) rename Penumbra/Interop/Hooks/Resources/{LoadMtrlShpk.cs => LoadMtrl.cs} (55%) diff --git a/Penumbra.GameData b/Penumbra.GameData index 8ee82929..ac9d9c78 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 8ee82929fa6c725b8f556904ba022fb418991b5c +Subproject commit ac9d9c78ae0025489b80ce2e798cdaacb0b43947 diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlLoaded.cs similarity index 73% rename from Penumbra/Communication/MtrlShpkLoaded.cs rename to Penumbra/Communication/MtrlLoaded.cs index 9d3597a8..78498844 100644 --- a/Penumbra/Communication/MtrlShpkLoaded.cs +++ b/Penumbra/Communication/MtrlLoaded.cs @@ -6,11 +6,11 @@ namespace Penumbra.Communication; /// Parameter is the material resource handle for which the shader package has been loaded. /// Parameter is the associated game object. /// -public sealed class MtrlShpkLoaded() : EventWrapper(nameof(MtrlShpkLoaded)) +public sealed class MtrlLoaded() : EventWrapper(nameof(MtrlLoaded)) { public enum Priority { - /// + /// ShaderReplacementFixer = 0, } } diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 0c0a4020..0bc55dc5 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -99,7 +99,7 @@ public class HookOverrides public struct ResourceHooks { public bool ApricotResourceLoad; - public bool LoadMtrlShpk; + public bool LoadMtrl; public bool LoadMtrlTex; public bool ResolvePathHooks; public bool ResourceHandleDestructor; diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 53b69741..d02e18bb 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -110,7 +110,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _modelRendererOnRenderMaterialHook = hooks.CreateHook("ModelRenderer.OnRenderMaterial", Sigs.ModelRendererOnRenderMaterial, ModelRendererOnRenderMaterialDetour, !HookOverrides.Instance.PostProcessing.ModelRendererOnRenderMaterial).Result; - _communicator.MtrlShpkLoaded.Subscribe(OnMtrlShpkLoaded, MtrlShpkLoaded.Priority.ShaderReplacementFixer); + _communicator.MtrlLoaded.Subscribe(OnMtrlLoaded, MtrlLoaded.Priority.ShaderReplacementFixer); _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.ShaderReplacementFixer); } @@ -118,7 +118,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic { _modelRendererOnRenderMaterialHook.Dispose(); _humanOnRenderMaterialHook.Dispose(); - _communicator.MtrlShpkLoaded.Unsubscribe(OnMtrlShpkLoaded); + _communicator.MtrlLoaded.Unsubscribe(OnMtrlLoaded); _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); _hairMaskState.ClearMaterials(); _characterOcclusionState.ClearMaterials(); @@ -147,7 +147,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic return shpkName.SequenceEqual(mtrlResource->ShpkNameSpan); } - private void OnMtrlShpkLoaded(nint mtrlResourceHandle, nint gameObject) + private void OnMtrlLoaded(nint mtrlResourceHandle, nint gameObject) { var mtrl = (MaterialResourceHandle*)mtrlResourceHandle; var shpk = mtrl->ShaderPackageResourceHandle; diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrl.cs similarity index 55% rename from Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs rename to Penumbra/Interop/Hooks/Resources/LoadMtrl.cs index 8c410ad8..f56177e4 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlShpk.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrl.cs @@ -5,28 +5,28 @@ using Penumbra.Services; namespace Penumbra.Interop.Hooks.Resources; -public sealed unsafe class LoadMtrlShpk : FastHook +public sealed unsafe class LoadMtrl : FastHook { private readonly GameState _gameState; private readonly CommunicatorService _communicator; - public LoadMtrlShpk(HookManager hooks, GameState gameState, CommunicatorService communicator) + public LoadMtrl(HookManager hooks, GameState gameState, CommunicatorService communicator) { _gameState = gameState; _communicator = communicator; - Task = hooks.CreateHook("Load Material Shaders", Sigs.LoadMtrlShpk, Detour, !HookOverrides.Instance.Resources.LoadMtrlShpk); + Task = hooks.CreateHook("Load Material", Sigs.LoadMtrl, Detour, !HookOverrides.Instance.Resources.LoadMtrl); } - public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle); + public delegate byte Delegate(MaterialResourceHandle* mtrlResourceHandle, void* unk1, byte unk2); - private byte Detour(MaterialResourceHandle* handle) + private byte Detour(MaterialResourceHandle* handle, void* unk1, byte unk2) { var last = _gameState.MtrlData.Value; var mtrlData = _gameState.LoadSubFileHelper((nint)handle); _gameState.MtrlData.Value = mtrlData; - var ret = Task.Result.Original(handle); + var ret = Task.Result.Original(handle, unk1, unk2); _gameState.MtrlData.Value = last; - _communicator.MtrlShpkLoaded.Invoke((nint)handle, mtrlData.AssociatedGameObject); + _communicator.MtrlLoaded.Invoke((nint)handle, mtrlData.AssociatedGameObject); return ret; } } diff --git a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs index 0759d9b1..1866e859 100644 --- a/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs +++ b/Penumbra/Interop/Hooks/Resources/LoadMtrlTex.cs @@ -4,6 +4,7 @@ using Penumbra.GameData; namespace Penumbra.Interop.Hooks.Resources; +// TODO check if this is still needed, as our hooked function is called by LoadMtrl's hooked function public sealed unsafe class LoadMtrlTex : FastHook { private readonly GameState _gameState; diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index cacbe689..5d745419 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -24,8 +24,8 @@ public class CommunicatorService : IDisposable, IService /// public readonly CreatedCharacterBase CreatedCharacterBase = new(); - /// - public readonly MtrlShpkLoaded MtrlShpkLoaded = new(); + /// + public readonly MtrlLoaded MtrlLoaded = new(); /// public readonly ModDataChanged ModDataChanged = new(); @@ -87,7 +87,7 @@ public class CommunicatorService : IDisposable, IService TemporaryGlobalModChange.Dispose(); CreatingCharacterBase.Dispose(); CreatedCharacterBase.Dispose(); - MtrlShpkLoaded.Dispose(); + MtrlLoaded.Dispose(); ModDataChanged.Dispose(); ModOptionChanged.Dispose(); ModDiscoveryStarted.Dispose(); From dba85f5da3774706f6005ddd56859bc78362afef Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 5 Aug 2024 03:43:18 +0200 Subject: [PATCH 0848/1381] Sanity check ShPk mods, ban incompatible ones --- .../Processing/ShpkPathPreProcessor.cs | 85 +++++++++++++++++++ Penumbra/Mods/Manager/ModManager.cs | 18 ++++ Penumbra/UI/ChatWarningService.cs | 56 ++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 Penumbra/Interop/Processing/ShpkPathPreProcessor.cs create mode 100644 Penumbra/UI/ChatWarningService.cs diff --git a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs new file mode 100644 index 00000000..2c6f6901 --- /dev/null +++ b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs @@ -0,0 +1,85 @@ +using FFXIVClientStructs.FFXIV.Client.System.Resource; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.Utility; +using Penumbra.Interop.Hooks.ResourceLoading; +using Penumbra.String; +using Penumbra.String.Classes; +using Penumbra.UI; + +namespace Penumbra.Interop.Processing; + +/// +/// Path pre-processor for shader packages that reverts redirects to known invalid files, as bad ShPks can crash the game. +/// +public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, ChatWarningService chatWarningService) : IPathPreProcessor +{ + public ResourceType Type + => ResourceType.Shpk; + + public unsafe FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved) + { + chatWarningService.CleanLastFileWarnings(false); + + if (!resolved.HasValue) + return null; + + // Skip the sanity check for game files. We are not considering the case where the user has modified game file: it's at their own risk. + var resolvedPath = resolved.Value; + if (!resolvedPath.IsRooted) + return resolvedPath; + + // If the ShPk is already loaded, it means that it already passed the sanity check. + var existingResource = resourceManager.FindResource(ResourceCategory.Shader, ResourceType.Shpk, unchecked((uint)resolvedPath.InternalName.Crc32)); + if (existingResource != null) + return resolvedPath; + + var checkResult = SanityCheck(resolvedPath.FullName); + if (checkResult == SanityCheckResult.Success) + return resolvedPath; + + Penumbra.Log.Warning($"Refusing to honor file redirection because of failed sanity check (result: {checkResult}). Original path: {originalGamePath} Redirected path: {resolvedPath}"); + chatWarningService.PrintFileWarning(resolvedPath.FullName, originalGamePath, WarningMessageComplement(checkResult)); + + return null; + } + + private static SanityCheckResult SanityCheck(string path) + { + try + { + using var file = MmioMemoryManager.CreateFromFile(path); + var bytes = file.GetSpan(); + + return ShpkFile.FastIsLegacy(bytes) + ? SanityCheckResult.Legacy + : SanityCheckResult.Success; + } + catch (FileNotFoundException) + { + return SanityCheckResult.NotFound; + } + catch (IOException) + { + return SanityCheckResult.IoError; + } + } + + private static string WarningMessageComplement(SanityCheckResult result) + => result switch + { + SanityCheckResult.IoError => "cannot read the modded file.", + SanityCheckResult.NotFound => "the modded file does not exist.", + SanityCheckResult.Legacy => "this mod is not compatible with Dawntrail. Get an updated version, if possible, or disable it.", + _ => string.Empty, + }; + + private enum SanityCheckResult + { + Success, + IoError, + NotFound, + Legacy, + } +} diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index f170a31b..59f8906e 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -350,4 +350,22 @@ public sealed class ModManager : ModStorage, IDisposable, IService Penumbra.Log.Error($"Could not scan for mods:\n{ex}"); } } + + public bool TryIdentifyPath(string path, [NotNullWhen(true)] out Mod? mod, [NotNullWhen(true)] out string? relativePath) + { + var relPath = Path.GetRelativePath(BasePath.FullName, path); + if (relPath != "." && (relPath.StartsWith('.') || Path.IsPathRooted(relPath))) + { + mod = null; + relativePath = null; + return false; + } + + var modDirectorySeparator = relPath.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]); + + var modDirectory = modDirectorySeparator < 0 ? relPath : relPath[..modDirectorySeparator]; + relativePath = modDirectorySeparator < 0 ? string.Empty : relPath[(modDirectorySeparator + 1)..]; + + return TryGetMod(modDirectory, "\0", out mod); + } } diff --git a/Penumbra/UI/ChatWarningService.cs b/Penumbra/UI/ChatWarningService.cs new file mode 100644 index 00000000..84ede2fb --- /dev/null +++ b/Penumbra/UI/ChatWarningService.cs @@ -0,0 +1,56 @@ +using Dalamud.Plugin.Services; +using OtterGui.Services; +using Penumbra.Mods.Manager; +using Penumbra.String.Classes; + +namespace Penumbra.UI; + +public sealed class ChatWarningService(IChatGui chatGui, IClientState clientState, ModManager modManager) : IUiService +{ + private readonly Dictionary _lastFileWarnings = []; + private int _lastFileWarningsCleanCounter; + + private const int LastFileWarningsCleanCycle = 100; + private static readonly TimeSpan LastFileWarningsMaxAge = new(1, 0, 0); + + public void CleanLastFileWarnings(bool force) + { + if (!force) + { + _lastFileWarningsCleanCounter = (_lastFileWarningsCleanCounter + 1) % LastFileWarningsCleanCycle; + if (_lastFileWarningsCleanCounter != 0) + return; + } + + var expiredDate = DateTime.Now - LastFileWarningsMaxAge; + var toRemove = new HashSet(); + foreach (var (key, value) in _lastFileWarnings) + { + if (value.Item1 <= expiredDate) + toRemove.Add(key); + } + foreach (var key in toRemove) + _lastFileWarnings.Remove(key); + } + + public void PrintFileWarning(string fullPath, Utf8GamePath originalGamePath, string messageComplement) + { + CleanLastFileWarnings(true); + + // Don't warn twice for the same file within a certain time interval unless the reason changed. + if (_lastFileWarnings.TryGetValue(fullPath, out var lastWarning) && lastWarning.Item2 == messageComplement) + return; + + // Don't warn for files managed by other plugins, or files we aren't sure about. + if (!modManager.TryIdentifyPath(fullPath, out var mod, out _)) + return; + + // Don't warn if there's no local player (as an approximation of no chat), so as not to trigger the cooldown. + if (clientState.LocalPlayer == null) + return; + + // The wording is an allusion to tar's "Cowardly refusing to create an empty archive" + chatGui.PrintError($"Cowardly refusing to load replacement for {originalGamePath.Filename().ToString().ToLowerInvariant()} by {mod.Name}{(messageComplement.Length > 0 ? ": " : ".")}{messageComplement}", "Penumbra"); + _lastFileWarnings[fullPath] = (DateTime.Now, messageComplement); + } +} From a36f9ccec7f4a1adf6e95c484da5a5a9ae9c2d3b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 5 Aug 2024 03:45:02 +0200 Subject: [PATCH 0849/1381] Improve ResourceTree display with new function --- Penumbra/Interop/ResourceTree/ResourceNode.cs | 4 ++++ .../ResourceTree/ResourceTreeFactory.cs | 19 ++++++++++++++++++- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 5 ++++- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 6ab48325..85d12ce7 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -15,6 +15,8 @@ public class ResourceNode : ICloneable public readonly nint ResourceHandle; public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; + public string? ModName; + public string? ModRelativePath; public CiByteString AdditionalData; public readonly ulong Length; public readonly List Children; @@ -57,6 +59,8 @@ public class ResourceNode : ICloneable ResourceHandle = other.ResourceHandle; PossibleGamePaths = other.PossibleGamePaths; FullPath = other.FullPath; + ModName = other.ModName; + ModRelativePath = other.ModRelativePath; AdditionalData = other.AdditionalData; Length = other.Length; Children = other.Children; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 65fac68f..9738148f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -9,6 +9,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; using Penumbra.Meta; +using Penumbra.Mods.Manager; using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; @@ -21,7 +22,8 @@ public class ResourceTreeFactory( ObjectIdentification objectIdentifier, Configuration config, ActorManager actors, - PathState pathState) : IService + PathState pathState, + ModManager modManager) : IService { private TreeBuildCache CreateTreeBuildCache() => new(objects, gameData, actors); @@ -93,7 +95,10 @@ public class ResourceTreeFactory( // This is currently unneeded as we can resolve all paths by querying the draw object: // ResolveGamePaths(tree, collectionResolveData.ModCollection); if (globalContext.WithUiData) + { ResolveUiData(tree); + ResolveModData(tree); + } FilterFullPaths(tree, (flags & Flags.RedactExternalPaths) != 0 ? config.ModDirectory : null); Cleanup(tree); @@ -123,6 +128,18 @@ public class ResourceTreeFactory( }); } + private void ResolveModData(ResourceTree tree) + { + foreach (var node in tree.FlatNodes) + { + if (node.FullPath.IsRooted && modManager.TryIdentifyPath(node.FullPath.FullName, out var mod, out var relativePath)) + { + node.ModName = mod.Name; + node.ModRelativePath = relativePath; + } + } + } + private static void FilterFullPaths(ResourceTree tree, string? onlyWithinPath) { foreach (var node in tree.FlatNodes) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index a991c948..361094c4 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -316,7 +316,10 @@ public class ResourceTreeViewer ImGui.TableNextColumn(); if (resourceNode.FullPath.FullName.Length > 0) { - ImGui.Selectable(resourceNode.FullPath.ToPath(), false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + var uiFullPathStr = resourceNode.ModName != null && resourceNode.ModRelativePath != null + ? $"[{resourceNode.ModName}] {resourceNode.ModRelativePath}" + : resourceNode.FullPath.ToPath(); + ImGui.Selectable(uiFullPathStr, false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); if (ImGui.IsItemClicked()) ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); ImGuiUtil.HoverTooltip( From f68e919421f46ec24e9acf21bff5416f39d73a66 Mon Sep 17 00:00:00 2001 From: "N. Lo." Date: Mon, 5 Aug 2024 04:08:24 +0200 Subject: [PATCH 0850/1381] Fix LiveCTPreviewer instantiation --- Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index bbd3b16c..61ccc95c 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -37,7 +37,7 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase _originalColorTableTexture = new SafeTextureHandle(*_colorTableTexture, true); - if (_originalColorTableTexture == null) + if (_originalColorTableTexture.Texture == null) throw new InvalidOperationException("Material doesn't have a color table"); Width = (int)_originalColorTableTexture.Texture->Width; From 0d1ed6a926ccb593bffa95d78a96b48bd222ecf7 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 5 Aug 2024 09:18:57 +0200 Subject: [PATCH 0851/1381] No, ImGui, these buttons aren't the same. --- .../Materials/MtrlTab.ColorTable.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index 352681bb..df8485c9 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -91,15 +91,21 @@ public partial class MtrlTab var dyePackB = _stainService.GudStmFile.GetValueOrNull(dyeB.Template, previewDyeB); using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { - ColorTableCopyClipboardButton(_colorTableSelectedPair << 1); - ImUtf8.SameLineInner(); - retA |= ColorTablePasteFromClipboardButton(_colorTableSelectedPair << 1, disabled); + using (ImUtf8.PushId("ClipboardA"u8)) + { + ColorTableCopyClipboardButton(_colorTableSelectedPair << 1); + ImUtf8.SameLineInner(); + retA |= ColorTablePasteFromClipboardButton(_colorTableSelectedPair << 1, disabled); + } ImGui.SameLine(); CenteredTextInRest($"Row {_colorTableSelectedPair + 1}A"); columns.Next(); - ColorTableCopyClipboardButton((_colorTableSelectedPair << 1) | 1); - ImUtf8.SameLineInner(); - retB |= ColorTablePasteFromClipboardButton((_colorTableSelectedPair << 1) | 1, disabled); + using (ImUtf8.PushId("ClipboardB"u8)) + { + ColorTableCopyClipboardButton((_colorTableSelectedPair << 1) | 1); + ImUtf8.SameLineInner(); + retB |= ColorTablePasteFromClipboardButton((_colorTableSelectedPair << 1) | 1, disabled); + } ImGui.SameLine(); CenteredTextInRest($"Row {_colorTableSelectedPair + 1}B"); } From 1187efa243fe4e645770ca8dc1b80a6159ce0932 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 5 Aug 2024 23:02:34 +0200 Subject: [PATCH 0852/1381] Reinstate single-row CT highlight --- .../Materials/MtrlTab.ColorTable.cs | 73 +++++++++++-------- .../Materials/MtrlTab.CommonColorTable.cs | 14 +++- .../Materials/MtrlTab.LegacyColorTable.cs | 14 +--- .../Materials/MtrlTab.LivePreview.cs | 28 ++++++- 4 files changed, 86 insertions(+), 43 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index df8485c9..0fa38a5d 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -30,11 +30,14 @@ public partial class MtrlTab var buttonWidth = (ImGui.GetContentRegionAvail().X - itemSpacing * 7.0f) * 0.125f; var frameHeight = ImGui.GetFrameHeight(); var highlighterSize = ImUtf8.CalcIconSize(FontAwesomeIcon.Crosshairs) + framePadding * 2.0f; - var spaceWidth = ImUtf8.CalcTextSize(" "u8).X; - var spacePadding = (int)MathF.Ceiling((highlighterSize.X + framePadding.X + itemInnerSpacing) / spaceWidth); using var font = ImRaii.PushFont(UiBuilder.MonoFont); using var alignment = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); + + // This depends on the font being pushed for "proper" alignment of the pair indices in the buttons. + var spaceWidth = ImUtf8.CalcTextSize(" "u8).X; + var spacePadding = (int)MathF.Ceiling((highlighterSize.X + framePadding.X + itemInnerSpacing) / spaceWidth); + for (var i = 0; i < ColorTable.NumRows >> 1; i += 8) { for (var j = 0; j < 8; ++j) @@ -72,7 +75,7 @@ public partial class MtrlTab var cursor = ImGui.GetCursorScreenPos(); ImGui.SetCursorScreenPos(rcMin with { Y = float.Lerp(rcMin.Y, rcMax.Y, 0.5f) - highlighterSize.Y * 0.5f }); font.Pop(); - ColorTableHighlightButton(pairIndex, disabled); + ColorTablePairHighlightButton(pairIndex, disabled); font.Push(UiBuilder.MonoFont); ImGui.SetCursorScreenPos(cursor); } @@ -83,6 +86,8 @@ public partial class MtrlTab { var retA = false; var retB = false; + var rowAIdx = _colorTableSelectedPair << 1; + var rowBIdx = rowAIdx | 1; var dyeA = dyeTable?[_colorTableSelectedPair << 1] ?? default; var dyeB = dyeTable?[(_colorTableSelectedPair << 1) | 1] ?? default; var previewDyeA = _stainService.GetStainCombo(dyeA.Channel).CurrentSelection.Key; @@ -91,23 +96,15 @@ public partial class MtrlTab var dyePackB = _stainService.GudStmFile.GetValueOrNull(dyeB.Template, previewDyeB); using (var columns = ImUtf8.Columns(2, "ColorTable"u8)) { - using (ImUtf8.PushId("ClipboardA"u8)) + using (ImUtf8.PushId("RowHeaderA"u8)) { - ColorTableCopyClipboardButton(_colorTableSelectedPair << 1); - ImUtf8.SameLineInner(); - retA |= ColorTablePasteFromClipboardButton(_colorTableSelectedPair << 1, disabled); + retA |= DrawRowHeader(rowAIdx, disabled); } - ImGui.SameLine(); - CenteredTextInRest($"Row {_colorTableSelectedPair + 1}A"); columns.Next(); - using (ImUtf8.PushId("ClipboardB"u8)) + using (ImUtf8.PushId("RowHeaderB"u8)) { - ColorTableCopyClipboardButton((_colorTableSelectedPair << 1) | 1); - ImUtf8.SameLineInner(); - retB |= ColorTablePasteFromClipboardButton((_colorTableSelectedPair << 1) | 1, disabled); + retB |= DrawRowHeader(rowBIdx, disabled); } - ImGui.SameLine(); - CenteredTextInRest($"Row {_colorTableSelectedPair + 1}B"); } DrawHeader(" Colors"u8); @@ -116,13 +113,13 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("ColorsA"u8)) { - retA |= DrawColors(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawColors(table, dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("ColorsB"u8)) { - retB |= DrawColors(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawColors(table, dyeTable, dyePackB, rowBIdx); } } @@ -132,13 +129,13 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("PbrA"u8)) { - retA |= DrawPbr(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawPbr(table, dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("PbrB"u8)) { - retB |= DrawPbr(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawPbr(table, dyeTable, dyePackB, rowBIdx); } } @@ -148,13 +145,13 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("SheenA"u8)) { - retA |= DrawSheen(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawSheen(table, dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("SheenB"u8)) { - retB |= DrawSheen(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawSheen(table, dyeTable, dyePackB, rowBIdx); } } @@ -164,13 +161,13 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("BlendingA"u8)) { - retA |= DrawBlending(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawBlending(table, dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("BlendingB"u8)) { - retB |= DrawBlending(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawBlending(table, dyeTable, dyePackB, rowBIdx); } } @@ -180,13 +177,13 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("TemplateA"u8)) { - retA |= DrawTemplate(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawTemplate(table, dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("TemplateB"u8)) { - retB |= DrawTemplate(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawTemplate(table, dyeTable, dyePackB, rowBIdx); } } @@ -197,13 +194,13 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("DyeA"u8)) { - retA |= DrawDye(dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawDye(dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("DyeB"u8)) { - retB |= DrawDye(dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawDye(dyeTable, dyePackB, rowBIdx); } } @@ -213,20 +210,20 @@ public partial class MtrlTab using var dis = ImRaii.Disabled(disabled); using (ImUtf8.PushId("FurtherA"u8)) { - retA |= DrawFurther(table, dyeTable, dyePackA, _colorTableSelectedPair << 1); + retA |= DrawFurther(table, dyeTable, dyePackA, rowAIdx); } columns.Next(); using (ImUtf8.PushId("FurtherB"u8)) { - retB |= DrawFurther(table, dyeTable, dyePackB, (_colorTableSelectedPair << 1) | 1); + retB |= DrawFurther(table, dyeTable, dyePackB, rowBIdx); } } if (retA) - UpdateColorTableRowPreview(_colorTableSelectedPair << 1); + UpdateColorTableRowPreview(rowAIdx); if (retB) - UpdateColorTableRowPreview((_colorTableSelectedPair << 1) | 1); + UpdateColorTableRowPreview(rowBIdx); return retA | retB; } @@ -239,6 +236,20 @@ public partial class MtrlTab ImUtf8.CollapsingHeader(label, ImGuiTreeNodeFlags.Leaf); } + private bool DrawRowHeader(int rowIdx, bool disabled) + { + ColorTableCopyClipboardButton(rowIdx); + ImUtf8.SameLineInner(); + var ret = ColorTablePasteFromClipboardButton(rowIdx, disabled); + ImUtf8.SameLineInner(); + ColorTableRowHighlightButton(rowIdx, disabled); + + ImGui.SameLine(); + CenteredTextInRest($"Row {(rowIdx >> 1) + 1}{"AB"[rowIdx & 1]}"); + + return ret; + } + private static bool DrawColors(ColorTable table, ColorDyeTable? dyeTable, DyePack? dyePack, int rowIdx) { var dyeOffset = ImGui.GetContentRegionAvail().X diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index 09c8ea61..38f02100 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -228,7 +228,7 @@ public partial class MtrlTab } } - private void ColorTableHighlightButton(int pairIdx, bool disabled) + private void ColorTablePairHighlightButton(int pairIdx, bool disabled) { ImUtf8.IconButton(FontAwesomeIcon.Crosshairs, "Highlight this pair of rows on your character, if possible.\n\nHighlight colors can be configured in Penumbra's settings."u8, @@ -240,6 +240,18 @@ public partial class MtrlTab CancelColorTableHighlight(); } + private void ColorTableRowHighlightButton(int rowIdx, bool disabled) + { + ImUtf8.IconButton(FontAwesomeIcon.Crosshairs, + "Highlight this row on your character, if possible.\n\nHighlight colors can be configured in Penumbra's settings."u8, + ImGui.GetFrameHeight() * Vector2.One, disabled || _colorTablePreviewers.Count == 0); + + if (ImGui.IsItemHovered()) + HighlightColorTableRow(rowIdx); + else if (_highlightedColorTableRow == rowIdx) + CancelColorTableHighlight(); + } + private static void CtBlendRect(Vector2 rcMin, Vector2 rcMax, uint topColor, uint bottomColor) { var style = ImGui.GetStyle(); diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs index 0ff2b01f..f21d86a9 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -103,11 +103,8 @@ public partial class MtrlTab ColorTableCopyClipboardButton(rowIdx); ImUtf8.SameLineInner(); var ret = ColorTablePasteFromClipboardButton(rowIdx, disabled); - if ((rowIdx & 1) == 0) - { - ImUtf8.SameLineInner(); - ColorTableHighlightButton(rowIdx >> 1, disabled); - } + ImUtf8.SameLineInner(); + ColorTableRowHighlightButton(rowIdx, disabled); ImGui.TableNextColumn(); using (ImRaii.PushFont(UiBuilder.MonoFont)) @@ -213,11 +210,8 @@ public partial class MtrlTab ColorTableCopyClipboardButton(rowIdx); ImUtf8.SameLineInner(); var ret = ColorTablePasteFromClipboardButton(rowIdx, disabled); - if ((rowIdx & 1) == 0) - { - ImUtf8.SameLineInner(); - ColorTableHighlightButton(rowIdx >> 1, disabled); - } + ImUtf8.SameLineInner(); + ColorTableRowHighlightButton(rowIdx, disabled); ImGui.TableNextColumn(); using (ImRaii.PushFont(UiBuilder.MonoFont)) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs index 6089f2d5..01a40980 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs @@ -14,6 +14,7 @@ public partial class MtrlTab { private readonly List _materialPreviewers = new(4); private readonly List _colorTablePreviewers = new(4); + private int _highlightedColorTableRow = -1; private int _highlightedColorTablePair = -1; private readonly Stopwatch _highlightTime = new(); @@ -168,13 +169,35 @@ public partial class MtrlTab } } + private void HighlightColorTableRow(int rowIdx) + { + var oldRowIdx = _highlightedColorTableRow; + + if (_highlightedColorTableRow != rowIdx) + { + _highlightedColorTableRow = rowIdx; + _highlightTime.Restart(); + } + + if (oldRowIdx >= 0) + UpdateColorTableRowPreview(oldRowIdx); + + if (rowIdx >= 0) + UpdateColorTableRowPreview(rowIdx); + } + private void CancelColorTableHighlight() { + var rowIdx = _highlightedColorTableRow; var pairIdx = _highlightedColorTablePair; + _highlightedColorTableRow = -1; _highlightedColorTablePair = -1; _highlightTime.Reset(); + if (rowIdx >= 0) + UpdateColorTableRowPreview(rowIdx); + if (pairIdx >= 0) { UpdateColorTableRowPreview(pairIdx << 1); @@ -214,7 +237,7 @@ public partial class MtrlTab } } - if (_highlightedColorTablePair << 1 == rowIdx) + if (_highlightedColorTablePair << 1 == rowIdx || _highlightedColorTableRow == rowIdx) ApplyHighlight(ref row, ColorId.InGameHighlight, (float)_highlightTime.Elapsed.TotalSeconds); else if (((_highlightedColorTablePair << 1) | 1) == rowIdx) ApplyHighlight(ref row, ColorId.InGameHighlight2, (float)_highlightTime.Elapsed.TotalSeconds); @@ -247,6 +270,9 @@ public partial class MtrlTab rows.ApplyDye(_stainService.GudStmFile, stainIds, dyeRows); } + if (_highlightedColorTableRow >= 0) + ApplyHighlight(ref rows[_highlightedColorTableRow], ColorId.InGameHighlight, (float)_highlightTime.Elapsed.TotalSeconds); + if (_highlightedColorTablePair >= 0) { ApplyHighlight(ref rows[_highlightedColorTablePair << 1], ColorId.InGameHighlight, (float)_highlightTime.Elapsed.TotalSeconds); From 2bf08c8c899dcb2111098affc6902b60ffcca9c6 Mon Sep 17 00:00:00 2001 From: "N. Lo." Date: Tue, 6 Aug 2024 13:05:21 +0200 Subject: [PATCH 0853/1381] Fix dye template combo (aka "git gud") --- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index df8485c9..13a36c71 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -595,7 +595,7 @@ public partial class MtrlTab if (_stainService.GudTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, scalarSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { - dye.Template = _stainService.LegacyTemplateCombo.CurrentSelection; + dye.Template = _stainService.GudTemplateCombo.CurrentSelection; ret = true; } From df58ac7e9248fdf3fcf465c1a6c2880577331d79 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 7 Aug 2024 15:44:21 +0200 Subject: [PATCH 0854/1381] Fix ref. --- Penumbra/Communication/MtrlShpkLoaded.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Communication/MtrlShpkLoaded.cs b/Penumbra/Communication/MtrlShpkLoaded.cs index 9d3597a8..2b286bb9 100644 --- a/Penumbra/Communication/MtrlShpkLoaded.cs +++ b/Penumbra/Communication/MtrlShpkLoaded.cs @@ -10,7 +10,7 @@ public sealed class MtrlShpkLoaded() : EventWrapper + /// ShaderReplacementFixer = 0, } } From fe4a046cc99b7ede7777c233df4089992931e914 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 7 Aug 2024 16:37:58 +0200 Subject: [PATCH 0855/1381] Make ChatWarningService part of the MessageService. --- OtterGui | 2 +- .../Processing/ShpkPathPreProcessor.cs | 27 +++++---- Penumbra/Services/MessageService.cs | 16 ++++++ Penumbra/UI/ChatWarningService.cs | 56 ------------------- 4 files changed, 32 insertions(+), 69 deletions(-) delete mode 100644 Penumbra/UI/ChatWarningService.cs diff --git a/OtterGui b/OtterGui index c53955cb..d9486ae5 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c53955cb6199dd418c5a9538d3251ac5942e7067 +Subproject commit d9486ae54b5a4b61cf74f79ed27daa659eb1ce5b diff --git a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs index 2c6f6901..96d9daff 100644 --- a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs @@ -4,23 +4,26 @@ using Penumbra.Collections; using Penumbra.GameData.Files; using Penumbra.GameData.Files.Utility; using Penumbra.Interop.Hooks.ResourceLoading; +using Penumbra.Mods.Manager; +using Penumbra.Services; using Penumbra.String; using Penumbra.String.Classes; -using Penumbra.UI; namespace Penumbra.Interop.Processing; /// /// Path pre-processor for shader packages that reverts redirects to known invalid files, as bad ShPks can crash the game. /// -public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, ChatWarningService chatWarningService) : IPathPreProcessor +public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, MessageService messager, ModManager modManager) + : IPathPreProcessor { public ResourceType Type => ResourceType.Shpk; - public unsafe FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath originalGamePath, bool nonDefault, FullPath? resolved) + public unsafe FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath originalGamePath, bool nonDefault, + FullPath? resolved) { - chatWarningService.CleanLastFileWarnings(false); + messager.CleanTaggedMessages(false); if (!resolved.HasValue) return null; @@ -31,7 +34,8 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, return resolvedPath; // If the ShPk is already loaded, it means that it already passed the sanity check. - var existingResource = resourceManager.FindResource(ResourceCategory.Shader, ResourceType.Shpk, unchecked((uint)resolvedPath.InternalName.Crc32)); + var existingResource = + resourceManager.FindResource(ResourceCategory.Shader, ResourceType.Shpk, unchecked((uint)resolvedPath.InternalName.Crc32)); if (existingResource != null) return resolvedPath; @@ -39,8 +43,7 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, if (checkResult == SanityCheckResult.Success) return resolvedPath; - Penumbra.Log.Warning($"Refusing to honor file redirection because of failed sanity check (result: {checkResult}). Original path: {originalGamePath} Redirected path: {resolvedPath}"); - chatWarningService.PrintFileWarning(resolvedPath.FullName, originalGamePath, WarningMessageComplement(checkResult)); + messager.PrintFileWarning(modManager, resolvedPath.FullName, originalGamePath, WarningMessageComplement(checkResult)); return null; } @@ -49,8 +52,8 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, { try { - using var file = MmioMemoryManager.CreateFromFile(path); - var bytes = file.GetSpan(); + using var file = MmioMemoryManager.CreateFromFile(path); + var bytes = file.GetSpan(); return ShpkFile.FastIsLegacy(bytes) ? SanityCheckResult.Legacy @@ -69,9 +72,9 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, private static string WarningMessageComplement(SanityCheckResult result) => result switch { - SanityCheckResult.IoError => "cannot read the modded file.", - SanityCheckResult.NotFound => "the modded file does not exist.", - SanityCheckResult.Legacy => "this mod is not compatible with Dawntrail. Get an updated version, if possible, or disable it.", + SanityCheckResult.IoError => "Cannot read the modded file.", + SanityCheckResult.NotFound => "The modded file does not exist.", + SanityCheckResult.Legacy => "This mod is not compatible with Dawntrail. Get an updated version, if possible, or disable it.", _ => string.Empty, }; diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index 08118483..a35a67f1 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -2,10 +2,14 @@ using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface; +using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin.Services; using Lumina.Excel.GeneratedSheets; using OtterGui.Log; using OtterGui.Services; +using Penumbra.Mods.Manager; +using Penumbra.String.Classes; +using Notification = OtterGui.Classes.Notification; namespace Penumbra.Services; @@ -38,4 +42,16 @@ public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INoti Message = payload, }); } + + public void PrintFileWarning(ModManager modManager, string fullPath, Utf8GamePath originalGamePath, string messageComplement) + { + // Don't warn for files managed by other plugins, or files we aren't sure about. + if (!modManager.TryIdentifyPath(fullPath, out var mod, out _)) + return; + + AddTaggedMessage($"{fullPath}.{messageComplement}", + new Notification( + $"Cowardly refusing to load replacement for {originalGamePath.Filename().ToString().ToLowerInvariant()} by {mod.Name}{(messageComplement.Length > 0 ? ":\n" : ".")}{messageComplement}", + NotificationType.Warning, 10000)); + } } diff --git a/Penumbra/UI/ChatWarningService.cs b/Penumbra/UI/ChatWarningService.cs deleted file mode 100644 index 84ede2fb..00000000 --- a/Penumbra/UI/ChatWarningService.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Dalamud.Plugin.Services; -using OtterGui.Services; -using Penumbra.Mods.Manager; -using Penumbra.String.Classes; - -namespace Penumbra.UI; - -public sealed class ChatWarningService(IChatGui chatGui, IClientState clientState, ModManager modManager) : IUiService -{ - private readonly Dictionary _lastFileWarnings = []; - private int _lastFileWarningsCleanCounter; - - private const int LastFileWarningsCleanCycle = 100; - private static readonly TimeSpan LastFileWarningsMaxAge = new(1, 0, 0); - - public void CleanLastFileWarnings(bool force) - { - if (!force) - { - _lastFileWarningsCleanCounter = (_lastFileWarningsCleanCounter + 1) % LastFileWarningsCleanCycle; - if (_lastFileWarningsCleanCounter != 0) - return; - } - - var expiredDate = DateTime.Now - LastFileWarningsMaxAge; - var toRemove = new HashSet(); - foreach (var (key, value) in _lastFileWarnings) - { - if (value.Item1 <= expiredDate) - toRemove.Add(key); - } - foreach (var key in toRemove) - _lastFileWarnings.Remove(key); - } - - public void PrintFileWarning(string fullPath, Utf8GamePath originalGamePath, string messageComplement) - { - CleanLastFileWarnings(true); - - // Don't warn twice for the same file within a certain time interval unless the reason changed. - if (_lastFileWarnings.TryGetValue(fullPath, out var lastWarning) && lastWarning.Item2 == messageComplement) - return; - - // Don't warn for files managed by other plugins, or files we aren't sure about. - if (!modManager.TryIdentifyPath(fullPath, out var mod, out _)) - return; - - // Don't warn if there's no local player (as an approximation of no chat), so as not to trigger the cooldown. - if (clientState.LocalPlayer == null) - return; - - // The wording is an allusion to tar's "Cowardly refusing to create an empty archive" - chatGui.PrintError($"Cowardly refusing to load replacement for {originalGamePath.Filename().ToString().ToLowerInvariant()} by {mod.Name}{(messageComplement.Length > 0 ? ": " : ".")}{messageComplement}", "Penumbra"); - _lastFileWarnings[fullPath] = (DateTime.Now, messageComplement); - } -} From d630a3dff42295b972a0c1d864468d4d384edb9b Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 7 Aug 2024 14:47:58 +0000 Subject: [PATCH 0856/1381] [CI] Updating repo.json for testing_1.2.0.22 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 10a08fa1..3de0c5c8 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.21", + "TestingAssemblyVersion": "1.2.0.22", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.21/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.22/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From fb58a9c27194d2107cd926d3a31f5a8d4600a1d4 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 8 Aug 2024 23:19:18 +0200 Subject: [PATCH 0857/1381] Add/improve ShaderReplacementFixer hooks --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 2 + .../PostProcessing/HumanSetupScalingHook.cs | 55 ++++ .../PostProcessing/PreBoneDeformerReplacer.cs | 49 +-- .../PostProcessing/ShaderReplacementFixer.cs | 284 ++++++++++++++++-- Penumbra/Interop/Services/CharacterUtility.cs | 32 +- Penumbra/Interop/Services/ModelRenderer.cs | 44 +-- .../Interop/Structs/CharacterUtilityData.cs | 26 +- .../Interop/Structs/ModelRendererStructs.cs | 35 +++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 62 ++-- 10 files changed, 478 insertions(+), 113 deletions(-) create mode 100644 Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs create mode 100644 Penumbra/Interop/Structs/ModelRendererStructs.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index ac9d9c78..2fd5aa44 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ac9d9c78ae0025489b80ce2e798cdaacb0b43947 +Subproject commit 2fd5aa44056a906df90c9a826d1d17f6fdafebff diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 0bc55dc5..a1dd374f 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -80,6 +80,8 @@ public class HookOverrides public bool HumanCreateDeformer; public bool HumanOnRenderMaterial; public bool ModelRendererOnRenderMaterial; + public bool ModelRendererUnkFunc; + public bool PrepareColorTable; } public struct ResourceLoadingHooks diff --git a/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs b/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs new file mode 100644 index 00000000..5783c099 --- /dev/null +++ b/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs @@ -0,0 +1,55 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; + +namespace Penumbra.Interop.Hooks.PostProcessing; + +// TODO: "SetupScaling" does not seem to only set up scaling -> find a better name? +public unsafe class HumanSetupScalingHook : FastHook +{ + private const int ReplacementCapacity = 2; + + public event EventDelegate? SetupReplacements; + + public HumanSetupScalingHook(HookManager hooks, CharacterBaseVTables vTables) + { + Task = hooks.CreateHook("Human.SetupScaling", vTables.HumanVTable[58], Detour, + !HookOverrides.Instance.PostProcessing.HumanSetupScaling); + } + + private void Detour(CharacterBase* drawObject, uint slotIndex) + { + Span replacements = stackalloc Replacement[ReplacementCapacity]; + var numReplacements = 0; + IDisposable? pbdDisposable = null; + object? shpkLock = null; + var releaseLock = false; + + try + { + SetupReplacements?.Invoke(drawObject, slotIndex, replacements, ref numReplacements, ref pbdDisposable, ref shpkLock); + if (shpkLock != null) + { + Monitor.Enter(shpkLock); + releaseLock = true; + } + for (var i = 0; i < numReplacements; ++i) + *(nint*)replacements[i].AddressToReplace = replacements[i].ValueToSet; + Task.Result.Original(drawObject, slotIndex); + } + finally + { + for (var i = numReplacements; i-- > 0;) + *(nint*)replacements[i].AddressToReplace = replacements[i].ValueToRestore; + if (releaseLock) + Monitor.Exit(shpkLock!); + pbdDisposable?.Dispose(); + } + } + + public delegate void Delegate(CharacterBase* drawObject, uint slotIndex); + + public delegate void EventDelegate(CharacterBase* drawObject, uint slotIndex, Span replacements, ref int numReplacements, + ref IDisposable? pbdDisposable, ref object? shpkLock); + + public readonly record struct Replacement(nint AddressToReplace, nint ValueToSet, nint ValueToRestore); +} diff --git a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs index 1aa09d7f..9273a2cb 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs @@ -18,27 +18,26 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi public static readonly Utf8GamePath PreBoneDeformerPath = Utf8GamePath.FromSpan("chara/xls/boneDeformer/human.pbd"u8, MetaDataComputation.All, out var p) ? p : Utf8GamePath.Empty; - // Approximate name guesses. - private delegate void CharacterBaseSetupScalingDelegate(CharacterBase* drawObject, uint slotIndex); - private delegate void* CharacterBaseCreateDeformerDelegate(CharacterBase* drawObject, uint slotIndex); + // Approximate name guess. + private delegate void* CharacterBaseCreateDeformerDelegate(CharacterBase* drawObject, uint slotIndex); - private readonly Hook _humanSetupScalingHook; private readonly Hook _humanCreateDeformerHook; - private readonly CharacterUtility _utility; - private readonly CollectionResolver _collectionResolver; - private readonly ResourceLoader _resourceLoader; - private readonly IFramework _framework; + private readonly CharacterUtility _utility; + private readonly CollectionResolver _collectionResolver; + private readonly ResourceLoader _resourceLoader; + private readonly IFramework _framework; + private readonly HumanSetupScalingHook _humanSetupScalingHook; public PreBoneDeformerReplacer(CharacterUtility utility, CollectionResolver collectionResolver, ResourceLoader resourceLoader, - HookManager hooks, IFramework framework, CharacterBaseVTables vTables) + HookManager hooks, IFramework framework, CharacterBaseVTables vTables, HumanSetupScalingHook humanSetupScalingHook) { - _utility = utility; - _collectionResolver = collectionResolver; - _resourceLoader = resourceLoader; - _framework = framework; - _humanSetupScalingHook = hooks.CreateHook("HumanSetupScaling", vTables.HumanVTable[58], SetupScaling, - !HookOverrides.Instance.PostProcessing.HumanSetupScaling).Result; + _utility = utility; + _collectionResolver = collectionResolver; + _resourceLoader = resourceLoader; + _framework = framework; + _humanSetupScalingHook = humanSetupScalingHook; + _humanSetupScalingHook.SetupReplacements += SetupHSSReplacements; _humanCreateDeformerHook = hooks.CreateHook("HumanCreateDeformer", vTables.HumanVTable[101], CreateDeformer, !HookOverrides.Instance.PostProcessing.HumanCreateDeformer).Result; } @@ -46,7 +45,7 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi public void Dispose() { _humanCreateDeformerHook.Dispose(); - _humanSetupScalingHook.Dispose(); + _humanSetupScalingHook.SetupReplacements -= SetupHSSReplacements; } private SafeResourceHandle GetPreBoneDeformerForCharacter(CharacterBase* drawObject) @@ -58,22 +57,24 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi return cache.CustomResources.Get(ResourceCategory.Chara, ResourceType.Pbd, PreBoneDeformerPath, resolveData); } - private void SetupScaling(CharacterBase* drawObject, uint slotIndex) + private void SetupHSSReplacements(CharacterBase* drawObject, uint slotIndex, Span replacements, + ref int numReplacements, ref IDisposable? pbdDisposable, ref object? shpkLock) { if (!_framework.IsInFrameworkUpdateThread) Penumbra.Log.Warning( - $"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupScaling)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); + $"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupHSSReplacements)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); - using var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); + var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); try { - if (!preBoneDeformer.IsInvalid) - _utility.Address->HumanPbdResource = (Structs.ResourceHandle*)preBoneDeformer.ResourceHandle; - _humanSetupScalingHook.Original(drawObject, slotIndex); + pbdDisposable = preBoneDeformer; + replacements[numReplacements++] = new((nint)(&_utility.Address->HumanPbdResource), (nint)preBoneDeformer.ResourceHandle, + _utility.DefaultHumanPbdResource); } - finally + catch { - _utility.Address->HumanPbdResource = (Structs.ResourceHandle*)_utility.DefaultHumanPbdResource; + preBoneDeformer.Dispose(); + throw; } } diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index d02e18bb..20db7e25 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; @@ -7,6 +8,8 @@ using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData; using Penumbra.Interop.Hooks.Resources; +using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; using Penumbra.Services; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using CSModelRenderer = FFXIVClientStructs.FFXIV.Client.Graphics.Render.ModelRenderer; @@ -19,6 +22,12 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic public static ReadOnlySpan SkinShpkName => "skin.shpk"u8; + public static ReadOnlySpan CharacterStockingsShpkName + => "characterstockings.shpk"u8; + + public static ReadOnlySpan CharacterLegacyShpkName + => "characterlegacy.shpk"u8; + public static ReadOnlySpan IrisShpkName => "iris.shpk"u8; @@ -42,16 +51,26 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private delegate nint ModelRendererOnRenderMaterialDelegate(CSModelRenderer* modelRenderer, ushort* outFlags, CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex); + private delegate void ModelRendererUnkFuncDelegate(CSModelRenderer* modelRenderer, ModelRendererStructs.UnkPayload* unkPayload, uint unk2, + uint unk3, uint unk4, uint unk5); + private readonly Hook _humanOnRenderMaterialHook; private readonly Hook _modelRendererOnRenderMaterialHook; + private readonly Hook _modelRendererUnkFuncHook; + + private readonly Hook _prepareColorTableHook; + private readonly ResourceHandleDestructor _resourceHandleDestructor; private readonly CommunicatorService _communicator; private readonly CharacterUtility _utility; private readonly ModelRenderer _modelRenderer; + private readonly HumanSetupScalingHook _humanSetupScalingHook; private readonly ModdedShaderPackageState _skinState; + private readonly ModdedShaderPackageState _characterStockingsState; + private readonly ModdedShaderPackageState _characterLegacyState; private readonly ModdedShaderPackageState _irisState; private readonly ModdedShaderPackageState _characterGlassState; private readonly ModdedShaderPackageState _characterTransparencyState; @@ -64,6 +83,12 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic public uint ModdedSkinShpkCount => _skinState.MaterialCount; + public uint ModdedCharacterStockingsShpkCount + => _characterStockingsState.MaterialCount; + + public uint ModdedCharacterLegacyShpkCount + => _characterLegacyState.MaterialCount; + public uint ModdedIrisShpkCount => _irisState.MaterialCount; @@ -83,16 +108,23 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic => _hairMaskState.MaterialCount; public ShaderReplacementFixer(ResourceHandleDestructor resourceHandleDestructor, CharacterUtility utility, ModelRenderer modelRenderer, - CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables) + CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables, HumanSetupScalingHook humanSetupScalingHook) { _resourceHandleDestructor = resourceHandleDestructor; _utility = utility; _modelRenderer = modelRenderer; _communicator = communicator; + _humanSetupScalingHook = humanSetupScalingHook; _skinState = new ModdedShaderPackageState( () => (ShaderPackageResourceHandle**)&_utility.Address->SkinShpkResource, () => (ShaderPackageResourceHandle*)_utility.DefaultSkinShpkResource); + _characterStockingsState = new ModdedShaderPackageState( + () => (ShaderPackageResourceHandle**)&_utility.Address->CharacterStockingsShpkResource, + () => (ShaderPackageResourceHandle*)_utility.DefaultCharacterStockingsShpkResource); + _characterLegacyState = new ModdedShaderPackageState( + () => (ShaderPackageResourceHandle**)&_utility.Address->CharacterLegacyShpkResource, + () => (ShaderPackageResourceHandle*)_utility.DefaultCharacterLegacyShpkResource); _irisState = new ModdedShaderPackageState(() => _modelRenderer.IrisShaderPackage, () => _modelRenderer.DefaultIrisShaderPackage); _characterGlassState = new ModdedShaderPackageState(() => _modelRenderer.CharacterGlassShaderPackage, () => _modelRenderer.DefaultCharacterGlassShaderPackage); @@ -105,33 +137,50 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _hairMaskState = new ModdedShaderPackageState(() => _modelRenderer.HairMaskShaderPackage, () => _modelRenderer.DefaultHairMaskShaderPackage); + _humanSetupScalingHook.SetupReplacements += SetupHSSReplacements; _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[64], OnRenderHumanMaterial, !HookOverrides.Instance.PostProcessing.HumanOnRenderMaterial).Result; _modelRendererOnRenderMaterialHook = hooks.CreateHook("ModelRenderer.OnRenderMaterial", Sigs.ModelRendererOnRenderMaterial, ModelRendererOnRenderMaterialDetour, !HookOverrides.Instance.PostProcessing.ModelRendererOnRenderMaterial).Result; + _modelRendererUnkFuncHook = hooks.CreateHook("ModelRenderer.UnkFunc", + Sigs.ModelRendererUnkFunc, ModelRendererUnkFuncDetour, + !HookOverrides.Instance.PostProcessing.ModelRendererUnkFunc).Result; + _prepareColorTableHook = hooks.CreateHook("MaterialResourceHandle.PrepareColorTable", + Sigs.PrepareColorSet, PrepareColorTableDetour, + !HookOverrides.Instance.PostProcessing.PrepareColorTable).Result; + _communicator.MtrlLoaded.Subscribe(OnMtrlLoaded, MtrlLoaded.Priority.ShaderReplacementFixer); _resourceHandleDestructor.Subscribe(OnResourceHandleDestructor, ResourceHandleDestructor.Priority.ShaderReplacementFixer); } public void Dispose() { + _prepareColorTableHook.Dispose(); + _modelRendererUnkFuncHook.Dispose(); _modelRendererOnRenderMaterialHook.Dispose(); _humanOnRenderMaterialHook.Dispose(); + _humanSetupScalingHook.SetupReplacements -= SetupHSSReplacements; + _communicator.MtrlLoaded.Unsubscribe(OnMtrlLoaded); _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); + _hairMaskState.ClearMaterials(); _characterOcclusionState.ClearMaterials(); _characterTattooState.ClearMaterials(); _characterTransparencyState.ClearMaterials(); _characterGlassState.ClearMaterials(); _irisState.ClearMaterials(); + _characterLegacyState.ClearMaterials(); + _characterStockingsState.ClearMaterials(); _skinState.ClearMaterials(); } - public (ulong Skin, ulong Iris, ulong CharacterGlass, ulong CharacterTransparency, ulong CharacterTattoo, ulong CharacterOcclusion, ulong - HairMask) GetAndResetSlowPathCallDeltas() + public (ulong Skin, ulong CharacterStockings, ulong CharacterLegacy, ulong Iris, ulong CharacterGlass, ulong CharacterTransparency, ulong + CharacterTattoo, ulong CharacterOcclusion, ulong HairMask) GetAndResetSlowPathCallDeltas() => (_skinState.GetAndResetSlowPathCallDelta(), + _characterStockingsState.GetAndResetSlowPathCallDelta(), + _characterLegacyState.GetAndResetSlowPathCallDelta(), _irisState.GetAndResetSlowPathCallDelta(), _characterGlassState.GetAndResetSlowPathCallDelta(), _characterTransparencyState.GetAndResetSlowPathCallDelta(), @@ -155,7 +204,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic return; var shpkName = mtrl->ShpkNameSpan; - var shpkState = GetStateForHuman(shpkName) ?? GetStateForModelRenderer(shpkName); + var shpkState = GetStateForHumanSetup(shpkName) ?? GetStateForHumanRender(shpkName) ?? GetStateForModelRendererRender(shpkName) + ?? GetStateForModelRendererUnk(shpkName) ?? GetStateForColorTable(shpkName); if (shpkState != null && shpk != shpkState.DefaultShaderPackage) shpkState.TryAddMaterial(mtrlResourceHandle); @@ -164,6 +214,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private void OnResourceHandleDestructor(Structs.ResourceHandle* handle) { _skinState.TryRemoveMaterial(handle); + _characterStockingsState.TryRemoveMaterial(handle); + _characterLegacyState.TryRemoveMaterial(handle); _irisState.TryRemoveMaterial(handle); _characterGlassState.TryRemoveMaterial(handle); _characterTransparencyState.TryRemoveMaterial(handle); @@ -172,10 +224,25 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _hairMaskState.TryRemoveMaterial(handle); } - private ModdedShaderPackageState? GetStateForHuman(MaterialResourceHandle* mtrlResource) - => mtrlResource == null ? null : GetStateForHuman(mtrlResource->ShpkNameSpan); + private ModdedShaderPackageState? GetStateForHumanSetup(MaterialResourceHandle* mtrlResource) + => mtrlResource == null ? null : GetStateForHumanSetup(mtrlResource->ShpkNameSpan); - private ModdedShaderPackageState? GetStateForHuman(ReadOnlySpan shpkName) + private ModdedShaderPackageState? GetStateForHumanSetup(ReadOnlySpan shpkName) + { + if (CharacterStockingsShpkName.SequenceEqual(shpkName)) + return _characterStockingsState; + + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private uint GetTotalMaterialCountForHumanSetup() + => _characterStockingsState.MaterialCount; + + private ModdedShaderPackageState? GetStateForHumanRender(MaterialResourceHandle* mtrlResource) + => mtrlResource == null ? null : GetStateForHumanRender(mtrlResource->ShpkNameSpan); + + private ModdedShaderPackageState? GetStateForHumanRender(ReadOnlySpan shpkName) { if (SkinShpkName.SequenceEqual(shpkName)) return _skinState; @@ -184,17 +251,14 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private uint GetTotalMaterialCountForHuman() + private uint GetTotalMaterialCountForHumanRender() => _skinState.MaterialCount; - private ModdedShaderPackageState? GetStateForModelRenderer(MaterialResourceHandle* mtrlResource) - => mtrlResource == null ? null : GetStateForModelRenderer(mtrlResource->ShpkNameSpan); + private ModdedShaderPackageState? GetStateForModelRendererRender(MaterialResourceHandle* mtrlResource) + => mtrlResource == null ? null : GetStateForModelRendererRender(mtrlResource->ShpkNameSpan); - private ModdedShaderPackageState? GetStateForModelRenderer(ReadOnlySpan shpkName) + private ModdedShaderPackageState? GetStateForModelRendererRender(ReadOnlySpan shpkName) { - if (IrisShpkName.SequenceEqual(shpkName)) - return _irisState; - if (CharacterGlassShpkName.SequenceEqual(shpkName)) return _characterGlassState; @@ -204,9 +268,6 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (CharacterTattooShpkName.SequenceEqual(shpkName)) return _characterTattooState; - if (CharacterOcclusionShpkName.SequenceEqual(shpkName)) - return _characterOcclusionState; - if (HairMaskShpkName.SequenceEqual(shpkName)) return _hairMaskState; @@ -214,24 +275,93 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private uint GetTotalMaterialCountForModelRenderer() - => _irisState.MaterialCount - + _characterGlassState.MaterialCount + private uint GetTotalMaterialCountForModelRendererRender() + => _characterGlassState.MaterialCount + _characterTransparencyState.MaterialCount + _characterTattooState.MaterialCount - + _characterOcclusionState.MaterialCount + _hairMaskState.MaterialCount; + private ModdedShaderPackageState? GetStateForModelRendererUnk(MaterialResourceHandle* mtrlResource) + => mtrlResource == null ? null : GetStateForModelRendererUnk(mtrlResource->ShpkNameSpan); + + private ModdedShaderPackageState? GetStateForModelRendererUnk(ReadOnlySpan shpkName) + { + if (IrisShpkName.SequenceEqual(shpkName)) + return _irisState; + + if (CharacterOcclusionShpkName.SequenceEqual(shpkName)) + return _characterOcclusionState; + + if (CharacterStockingsShpkName.SequenceEqual(shpkName)) + return _characterStockingsState; + + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private uint GetTotalMaterialCountForModelRendererUnk() + => _irisState.MaterialCount + + _characterOcclusionState.MaterialCount + + _characterStockingsState.MaterialCount; + + private ModdedShaderPackageState? GetStateForColorTable(ReadOnlySpan shpkName) + { + if (CharacterLegacyShpkName.SequenceEqual(shpkName)) + return _characterLegacyState; + + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private uint GetTotalMaterialCountForColorTable() + => _characterLegacyState.MaterialCount; + + private void SetupHSSReplacements(CharacterBase* drawObject, uint slotIndex, Span replacements, + ref int numReplacements, ref IDisposable? pbdDisposable, ref object? shpkLock) + { + // If we don't have any on-screen instances of modded characterstockings.shpk, we don't need the slow path at all. + if (!Enabled || GetTotalMaterialCountForHumanSetup() == 0) + return; + + var model = drawObject->Models[slotIndex]; + if (model == null) + return; + MaterialResourceHandle* mtrlResource = null; + ModdedShaderPackageState? shpkState = null; + foreach (var material in model->MaterialsSpan) + { + if (material.Value == null) + continue; + + mtrlResource = material.Value->MaterialResourceHandle; + shpkState = GetStateForHumanSetup(mtrlResource); + // Despite this function being called with what designates a model (and therefore potentially many materials), + // we currently don't need to handle more than one modded ShPk. + if (shpkState != null) + break; + } + if (shpkState == null || shpkState.MaterialCount == 0) + return; + + shpkState.IncrementSlowPathCallDelta(); + + // This is less performance-critical than the others, as this is called by the game only on draw object creation and slot update. + // There are still thread safety concerns as it might be called in other threads by plugins. + shpkLock = shpkState; + replacements[numReplacements++] = new((nint)shpkState.ShaderPackageReference, (nint)mtrlResource->ShaderPackageResourceHandle, + (nint)shpkState.DefaultShaderPackage); + } + private nint OnRenderHumanMaterial(CharacterBase* human, CSModelRenderer.OnRenderMaterialParams* param) { // If we don't have any on-screen instances of modded skin.shpk, we don't need the slow path at all. - if (!Enabled || GetTotalMaterialCountForHuman() == 0) + if (!Enabled || GetTotalMaterialCountForHumanRender() == 0) return _humanOnRenderMaterialHook.Original(human, param); var material = param->Model->Materials[param->MaterialIndex]; var mtrlResource = material->MaterialResourceHandle; - var shpkState = GetStateForHuman(mtrlResource); - if (shpkState == null) + var shpkState = GetStateForHumanRender(mtrlResource); + if (shpkState == null || shpkState.MaterialCount == 0) return _humanOnRenderMaterialHook.Original(human, param); shpkState.IncrementSlowPathCallDelta(); @@ -259,18 +389,18 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private nint ModelRendererOnRenderMaterialDetour(CSModelRenderer* modelRenderer, ushort* outFlags, CSModelRenderer.OnRenderModelParams* param, Material* material, uint materialIndex) { - // If we don't have any on-screen instances of modded characterglass.shpk, we don't need the slow path at all. - if (!Enabled || GetTotalMaterialCountForModelRenderer() == 0) + // If we don't have any on-screen instances of modded characterglass.shpk or others, we don't need the slow path at all. + if (!Enabled || GetTotalMaterialCountForModelRendererRender() == 0) return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); var mtrlResource = material->MaterialResourceHandle; - var shpkState = GetStateForModelRenderer(mtrlResource); - if (shpkState == null) + var shpkState = GetStateForModelRendererRender(mtrlResource); + if (shpkState == null || shpkState.MaterialCount == 0) return _modelRendererOnRenderMaterialHook.Original(modelRenderer, outFlags, param, material, materialIndex); shpkState.IncrementSlowPathCallDelta(); - // Same performance considerations as above. + // Same performance considerations as OnRenderHumanMaterial. lock (shpkState) { var shpkReference = shpkState.ShaderPackageReference; @@ -286,6 +416,102 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic } } + private void ModelRendererUnkFuncDetour(CSModelRenderer* modelRenderer, ModelRendererStructs.UnkPayload* unkPayload, uint unk2, uint unk3, + uint unk4, uint unk5) + { + // If we don't have any on-screen instances of modded iris.shpk or others, we don't need the slow path at all. + if (!Enabled || GetTotalMaterialCountForModelRendererUnk() == 0) + { + _modelRendererUnkFuncHook.Original(modelRenderer, unkPayload, unk2, unk3, unk4, unk5); + return; + } + + var mtrlResource = GetMaterialResourceHandle(unkPayload); + var shpkState = GetStateForModelRendererUnk(mtrlResource); + if (shpkState == null || shpkState.MaterialCount == 0) + { + _modelRendererUnkFuncHook.Original(modelRenderer, unkPayload, unk2, unk3, unk4, unk5); + return; + } + + shpkState.IncrementSlowPathCallDelta(); + + // Same performance considerations as OnRenderHumanMaterial. + lock (shpkState) + { + var shpkReference = shpkState.ShaderPackageReference; + try + { + *shpkReference = mtrlResource->ShaderPackageResourceHandle; + _modelRendererUnkFuncHook.Original(modelRenderer, unkPayload, unk2, unk3, unk4, unk5); + } + finally + { + *shpkReference = shpkState.DefaultShaderPackage; + } + } + } + + private MaterialResourceHandle* GetMaterialResourceHandle(ModelRendererStructs.UnkPayload* unkPayload) + { + // TODO ClientStructs-ify + var unkPointer = *(nint*)((nint)unkPayload->ModelResourceHandle + 0xE8) + unkPayload->UnkIndex * 0x24; + var materialIndex = *(ushort*)(unkPointer + 8); + var material = unkPayload->Params->Model->Materials[materialIndex]; + if (material == null) + return null; + + var mtrlResource = material->MaterialResourceHandle; + if (mtrlResource == null) + return null; + + if (mtrlResource->ShaderPackageResourceHandle == null) + { + Penumbra.Log.Warning($"ShaderReplacementFixer found a MaterialResourceHandle with no shader package"); + return null; + } + + if (mtrlResource->ShaderPackageResourceHandle->ShaderPackage != unkPayload->ShaderWrapper->ShaderPackage) + { + Penumbra.Log.Warning($"ShaderReplacementFixer found a MaterialResourceHandle (0x{(nint)mtrlResource:X}) with an inconsistent shader package (got 0x{(nint)mtrlResource->ShaderPackageResourceHandle->ShaderPackage:X}, expected 0x{(nint)unkPayload->ShaderWrapper->ShaderPackage:X})"); + return null; + } + + return mtrlResource; + } + + private Texture* PrepareColorTableDetour(MaterialResourceHandle* thisPtr, byte stain0Id, byte stain1Id) + { + // If we don't have any on-screen instances of modded characterlegacy.shpk, we don't need the slow path at all. + if (!Enabled || GetTotalMaterialCountForColorTable() == 0) + return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); + + var material = thisPtr->Material; + if (material == null) + return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); + + var shpkState = GetStateForColorTable(thisPtr->ShpkNameSpan); + if (shpkState == null || shpkState.MaterialCount == 0) + return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); + + shpkState.IncrementSlowPathCallDelta(); + + // Same performance considerations as HumanSetupScalingDetour. + lock (shpkState) + { + var shpkReference = shpkState.ShaderPackageReference; + try + { + *shpkReference = thisPtr->ShaderPackageResourceHandle; + return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); + } + finally + { + *shpkReference = shpkState.DefaultShaderPackage; + } + } + } + private sealed class ModdedShaderPackageState(ShaderPackageReferenceGetter referenceGetter, DefaultShaderPackageGetter defaultGetter) { // MaterialResourceHandle set diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 532dc823..4ab156a9 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -28,10 +28,12 @@ public unsafe class CharacterUtility : IDisposable, IRequiredService public bool Ready { get; private set; } public event Action LoadingFinished; - public nint DefaultHumanPbdResource { get; private set; } - public nint DefaultTransparentResource { get; private set; } - public nint DefaultDecalResource { get; private set; } - public nint DefaultSkinShpkResource { get; private set; } + public nint DefaultHumanPbdResource { get; private set; } + public nint DefaultTransparentResource { get; private set; } + public nint DefaultDecalResource { get; private set; } + public nint DefaultSkinShpkResource { get; private set; } + public nint DefaultCharacterStockingsShpkResource { get; private set; } + public nint DefaultCharacterLegacyShpkResource { get; private set; } /// /// The relevant indices depend on which meta manipulations we allow for. @@ -108,6 +110,18 @@ public unsafe class CharacterUtility : IDisposable, IRequiredService anyMissing |= DefaultSkinShpkResource == nint.Zero; } + if (DefaultCharacterStockingsShpkResource == nint.Zero) + { + DefaultCharacterStockingsShpkResource = (nint)Address->CharacterStockingsShpkResource; + anyMissing |= DefaultCharacterStockingsShpkResource == nint.Zero; + } + + if (DefaultCharacterLegacyShpkResource == nint.Zero) + { + DefaultCharacterLegacyShpkResource = (nint)Address->CharacterLegacyShpkResource; + anyMissing |= DefaultCharacterLegacyShpkResource == nint.Zero; + } + if (anyMissing) return; @@ -122,10 +136,12 @@ public unsafe class CharacterUtility : IDisposable, IRequiredService if (!Ready) return; - Address->HumanPbdResource = (ResourceHandle*)DefaultHumanPbdResource; - Address->TransparentTexResource = (TextureResourceHandle*)DefaultTransparentResource; - Address->DecalTexResource = (TextureResourceHandle*)DefaultDecalResource; - Address->SkinShpkResource = (ResourceHandle*)DefaultSkinShpkResource; + Address->HumanPbdResource = (ResourceHandle*)DefaultHumanPbdResource; + Address->TransparentTexResource = (TextureResourceHandle*)DefaultTransparentResource; + Address->DecalTexResource = (TextureResourceHandle*)DefaultDecalResource; + Address->SkinShpkResource = (ResourceHandle*)DefaultSkinShpkResource; + Address->CharacterStockingsShpkResource = (ResourceHandle*)DefaultCharacterStockingsShpkResource; + Address->CharacterLegacyShpkResource = (ResourceHandle*)DefaultCharacterLegacyShpkResource; } public void Dispose() diff --git a/Penumbra/Interop/Services/ModelRenderer.cs b/Penumbra/Interop/Services/ModelRenderer.cs index 10f3977f..5e2cd1fb 100644 --- a/Penumbra/Interop/Services/ModelRenderer.cs +++ b/Penumbra/Interop/Services/ModelRenderer.cs @@ -2,6 +2,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using OtterGui.Services; +using ModelRendererData = FFXIVClientStructs.FFXIV.Client.Graphics.Render.ModelRenderer; namespace Penumbra.Interop.Services; @@ -9,46 +10,53 @@ public unsafe class ModelRenderer : IDisposable, IRequiredService { public bool Ready { get; private set; } - public ShaderPackageResourceHandle** IrisShaderPackage + public ModelRendererData* Address => Manager.Instance() switch { null => null, - var renderManager => &renderManager->ModelRenderer.IrisShaderPackage, + var renderManager => &renderManager->ModelRenderer, + }; + + public ShaderPackageResourceHandle** IrisShaderPackage + => Address switch + { + null => null, + var data => &data->IrisShaderPackage, }; public ShaderPackageResourceHandle** CharacterGlassShaderPackage - => Manager.Instance() switch + => Address switch { - null => null, - var renderManager => &renderManager->ModelRenderer.CharacterGlassShaderPackage, + null => null, + var data => &data->CharacterGlassShaderPackage, }; public ShaderPackageResourceHandle** CharacterTransparencyShaderPackage - => Manager.Instance() switch + => Address switch { - null => null, - var renderManager => &renderManager->ModelRenderer.CharacterTransparencyShaderPackage, + null => null, + var data => &data->CharacterTransparencyShaderPackage, }; public ShaderPackageResourceHandle** CharacterTattooShaderPackage - => Manager.Instance() switch + => Address switch { - null => null, - var renderManager => &renderManager->ModelRenderer.CharacterTattooShaderPackage, + null => null, + var data => &data->CharacterTattooShaderPackage, }; public ShaderPackageResourceHandle** CharacterOcclusionShaderPackage - => Manager.Instance() switch + => Address switch { - null => null, - var renderManager => &renderManager->ModelRenderer.CharacterOcclusionShaderPackage, + null => null, + var data => &data->CharacterOcclusionShaderPackage, }; public ShaderPackageResourceHandle** HairMaskShaderPackage - => Manager.Instance() switch + => Address switch { - null => null, - var renderManager => &renderManager->ModelRenderer.HairMaskShaderPackage, + null => null, + var data => &data->HairMaskShaderPackage, }; public ShaderPackageResourceHandle* DefaultIrisShaderPackage { get; private set; } @@ -96,7 +104,7 @@ public unsafe class ModelRenderer : IDisposable, IRequiredService if (DefaultCharacterTransparencyShaderPackage == null) { DefaultCharacterTransparencyShaderPackage = *CharacterTransparencyShaderPackage; - anyMissing |= DefaultCharacterTransparencyShaderPackage == null; + anyMissing |= DefaultCharacterTransparencyShaderPackage == null; } if (DefaultCharacterTattooShaderPackage == null) diff --git a/Penumbra/Interop/Structs/CharacterUtilityData.cs b/Penumbra/Interop/Structs/CharacterUtilityData.cs index 7595353f..8543466d 100644 --- a/Penumbra/Interop/Structs/CharacterUtilityData.cs +++ b/Penumbra/Interop/Structs/CharacterUtilityData.cs @@ -5,15 +5,17 @@ namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] public unsafe struct CharacterUtilityData { - public const int IndexHumanPbd = 63; - public const int IndexTransparentTex = 79; - public const int IndexDecalTex = 80; - public const int IndexTileOrbArrayTex = 81; - public const int IndexTileNormArrayTex = 82; - public const int IndexSkinShpk = 83; - public const int IndexGudStm = 94; - public const int IndexLegacyStm = 95; - public const int IndexSphereDArrayTex = 96; + public const int IndexHumanPbd = 63; + public const int IndexTransparentTex = 79; + public const int IndexDecalTex = 80; + public const int IndexTileOrbArrayTex = 81; + public const int IndexTileNormArrayTex = 82; + public const int IndexSkinShpk = 83; + public const int IndexCharacterStockingsShpk = 84; + public const int IndexCharacterLegacyShpk = 85; + public const int IndexGudStm = 94; + public const int IndexLegacyStm = 95; + public const int IndexSphereDArrayTex = 96; public static readonly MetaIndex[] EqdpIndices = Enum.GetNames() .Zip(Enum.GetValues()) @@ -111,6 +113,12 @@ public unsafe struct CharacterUtilityData [FieldOffset(8 + IndexSkinShpk * 8)] public ResourceHandle* SkinShpkResource; + [FieldOffset(8 + IndexCharacterStockingsShpk * 8)] + public ResourceHandle* CharacterStockingsShpkResource; + + [FieldOffset(8 + IndexCharacterLegacyShpk * 8)] + public ResourceHandle* CharacterLegacyShpkResource; + [FieldOffset(8 + IndexGudStm * 8)] public ResourceHandle* GudStmResource; diff --git a/Penumbra/Interop/Structs/ModelRendererStructs.cs b/Penumbra/Interop/Structs/ModelRendererStructs.cs new file mode 100644 index 00000000..551a32e3 --- /dev/null +++ b/Penumbra/Interop/Structs/ModelRendererStructs.cs @@ -0,0 +1,35 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; + +namespace Penumbra.Interop.Structs; + +public static unsafe class ModelRendererStructs +{ + [StructLayout(LayoutKind.Explicit, Size = 0x28)] + public struct UnkShaderWrapper + { + [FieldOffset(0)] + public void* Vtbl; + + [FieldOffset(8)] + public ShaderPackage* ShaderPackage; + } + + // Unknown size, this is allocated on FUN_1404446c0's stack (E8 ?? ?? ?? ?? FF C3 41 3B DE 72 ?? 48 C7 85) + [StructLayout(LayoutKind.Explicit)] + public struct UnkPayload + { + [FieldOffset(0)] + public ModelRenderer.OnRenderModelParams* Params; + + [FieldOffset(8)] + public ModelResourceHandle* ModelResourceHandle; + + [FieldOffset(0x10)] + public UnkShaderWrapper* ShaderWrapper; + + [FieldOffset(0x1C)] + public ushort UnkIndex; + } +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 7dae19c8..5b82a523 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -833,20 +833,6 @@ public class DebugTab : Window, ITab, IUiService ImGui.TableSetupColumn("\u0394 Slow-Path Calls", ImGuiTableColumnFlags.WidthStretch, 0.2f); ImGui.TableHeadersRow(); - ImGui.TableNextColumn(); - ImGui.TextUnformatted("skin.shpk"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedSkinShpkCount}"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{slowPathCallDeltas.Skin}"); - - ImGui.TableNextColumn(); - ImGui.TextUnformatted("iris.shpk"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedIrisShpkCount}"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{slowPathCallDeltas.Iris}"); - ImGui.TableNextColumn(); ImGui.TextUnformatted("characterglass.shpk"); ImGui.TableNextColumn(); @@ -855,18 +841,11 @@ public class DebugTab : Window, ITab, IUiService ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterGlass}"); ImGui.TableNextColumn(); - ImGui.TextUnformatted("charactertransparency.shpk"); + ImGui.TextUnformatted("characterlegacy.shpk"); ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterTransparencyShpkCount}"); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterLegacyShpkCount}"); ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterTransparency}"); - - ImGui.TableNextColumn(); - ImGui.TextUnformatted("charactertattoo.shpk"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterTattooShpkCount}"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterTattoo}"); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterLegacy}"); ImGui.TableNextColumn(); ImGui.TextUnformatted("characterocclusion.shpk"); @@ -875,12 +854,47 @@ public class DebugTab : Window, ITab, IUiService ImGui.TableNextColumn(); ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterOcclusion}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted("characterstockings.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterStockingsShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterStockings}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("charactertattoo.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterTattooShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterTattoo}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("charactertransparency.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedCharacterTransparencyShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.CharacterTransparency}"); + ImGui.TableNextColumn(); ImGui.TextUnformatted("hairmask.shpk"); ImGui.TableNextColumn(); ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedHairMaskShpkCount}"); ImGui.TableNextColumn(); ImGui.TextUnformatted($"{slowPathCallDeltas.HairMask}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("iris.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedIrisShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.Iris}"); + + ImGui.TableNextColumn(); + ImGui.TextUnformatted("skin.shpk"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{_shaderReplacementFixer.ModdedSkinShpkCount}"); + ImGui.TableNextColumn(); + ImGui.TextUnformatted($"{slowPathCallDeltas.Skin}"); } /// Draw information about the resident resource files. From 03e9dc55dfebc6de1fb3290fdd6b041f547a08e2 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 8 Aug 2024 23:19:44 +0200 Subject: [PATCH 0858/1381] Use read-only MMIO for legacy ShPk ban --- Penumbra/Interop/Processing/ShpkPathPreProcessor.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs index 96d9daff..2fb35ae0 100644 --- a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs @@ -1,3 +1,4 @@ +using System.IO.MemoryMappedFiles; using FFXIVClientStructs.FFXIV.Client.System.Resource; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -52,7 +53,7 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, { try { - using var file = MmioMemoryManager.CreateFromFile(path); + using var file = MmioMemoryManager.CreateFromFile(path, access: MemoryMappedFileAccess.Read); var bytes = file.GetSpan(); return ShpkFile.FastIsLegacy(bytes) From c265b917b4e56ea359a1337a06cb9cf5da155cce Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 9 Aug 2024 00:02:36 +0200 Subject: [PATCH 0859/1381] "This is how you end up on a list." --- Penumbra/Penumbra.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 438cdc49..d99e3fcd 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -186,6 +186,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", + "IllusioVitae", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) From a52a43bd86cfb193204ac3bcf8d94dd8e2bf3fc6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 9 Aug 2024 01:15:05 +0200 Subject: [PATCH 0860/1381] Minor cleanup. --- .../PostProcessing/HumanSetupScalingHook.cs | 7 +-- .../PostProcessing/PreBoneDeformerReplacer.cs | 23 +++---- .../PostProcessing/ShaderReplacementFixer.cs | 61 +++++++------------ Penumbra/Interop/Services/CharacterUtility.cs | 2 +- 4 files changed, 38 insertions(+), 55 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs b/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs index 5783c099..870229d6 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/HumanSetupScalingHook.cs @@ -11,10 +11,8 @@ public unsafe class HumanSetupScalingHook : FastHook("Human.SetupScaling", vTables.HumanVTable[58], Detour, + => Task = hooks.CreateHook("Human.SetupScaling", vTables.HumanVTable[58], Detour, !HookOverrides.Instance.PostProcessing.HumanSetupScaling); - } private void Detour(CharacterBase* drawObject, uint slotIndex) { @@ -32,6 +30,7 @@ public unsafe class HumanSetupScalingHook : FastHook replacements, ref int numReplacements, ref IDisposable? pbdDisposable, ref object? shpkLock); - + public readonly record struct Replacement(nint AddressToReplace, nint ValueToSet, nint ValueToRestore); } diff --git a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs index 9273a2cb..30e643c7 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs @@ -19,7 +19,7 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi Utf8GamePath.FromSpan("chara/xls/boneDeformer/human.pbd"u8, MetaDataComputation.All, out var p) ? p : Utf8GamePath.Empty; // Approximate name guess. - private delegate void* CharacterBaseCreateDeformerDelegate(CharacterBase* drawObject, uint slotIndex); + private delegate void* CharacterBaseCreateDeformerDelegate(CharacterBase* drawObject, uint slotIndex); private readonly Hook _humanCreateDeformerHook; @@ -32,12 +32,12 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi public PreBoneDeformerReplacer(CharacterUtility utility, CollectionResolver collectionResolver, ResourceLoader resourceLoader, HookManager hooks, IFramework framework, CharacterBaseVTables vTables, HumanSetupScalingHook humanSetupScalingHook) { - _utility = utility; - _collectionResolver = collectionResolver; - _resourceLoader = resourceLoader; - _framework = framework; - _humanSetupScalingHook = humanSetupScalingHook; - _humanSetupScalingHook.SetupReplacements += SetupHSSReplacements; + _utility = utility; + _collectionResolver = collectionResolver; + _resourceLoader = resourceLoader; + _framework = framework; + _humanSetupScalingHook = humanSetupScalingHook; + _humanSetupScalingHook.SetupReplacements += SetupHssReplacements; _humanCreateDeformerHook = hooks.CreateHook("HumanCreateDeformer", vTables.HumanVTable[101], CreateDeformer, !HookOverrides.Instance.PostProcessing.HumanCreateDeformer).Result; } @@ -45,7 +45,7 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi public void Dispose() { _humanCreateDeformerHook.Dispose(); - _humanSetupScalingHook.SetupReplacements -= SetupHSSReplacements; + _humanSetupScalingHook.SetupReplacements -= SetupHssReplacements; } private SafeResourceHandle GetPreBoneDeformerForCharacter(CharacterBase* drawObject) @@ -57,18 +57,19 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi return cache.CustomResources.Get(ResourceCategory.Chara, ResourceType.Pbd, PreBoneDeformerPath, resolveData); } - private void SetupHSSReplacements(CharacterBase* drawObject, uint slotIndex, Span replacements, + private void SetupHssReplacements(CharacterBase* drawObject, uint slotIndex, Span replacements, ref int numReplacements, ref IDisposable? pbdDisposable, ref object? shpkLock) { if (!_framework.IsInFrameworkUpdateThread) Penumbra.Log.Warning( - $"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupHSSReplacements)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); + $"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupHssReplacements)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); try { pbdDisposable = preBoneDeformer; - replacements[numReplacements++] = new((nint)(&_utility.Address->HumanPbdResource), (nint)preBoneDeformer.ResourceHandle, + replacements[numReplacements++] = new HumanSetupScalingHook.Replacement((nint)(&_utility.Address->HumanPbdResource), + (nint)preBoneDeformer.ResourceHandle, _utility.DefaultHumanPbdResource); } catch diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 20db7e25..80892b0f 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -8,7 +8,6 @@ using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData; using Penumbra.Interop.Hooks.Resources; -using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.Services; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; @@ -137,7 +136,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _hairMaskState = new ModdedShaderPackageState(() => _modelRenderer.HairMaskShaderPackage, () => _modelRenderer.DefaultHairMaskShaderPackage); - _humanSetupScalingHook.SetupReplacements += SetupHSSReplacements; + _humanSetupScalingHook.SetupReplacements += SetupHssReplacements; _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[64], OnRenderHumanMaterial, !HookOverrides.Instance.PostProcessing.HumanOnRenderMaterial).Result; _modelRendererOnRenderMaterialHook = hooks.CreateHook("ModelRenderer.OnRenderMaterial", @@ -146,7 +145,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _modelRendererUnkFuncHook = hooks.CreateHook("ModelRenderer.UnkFunc", Sigs.ModelRendererUnkFunc, ModelRendererUnkFuncDetour, !HookOverrides.Instance.PostProcessing.ModelRendererUnkFunc).Result; - _prepareColorTableHook = hooks.CreateHook("MaterialResourceHandle.PrepareColorTable", + _prepareColorTableHook = hooks.CreateHook( + "MaterialResourceHandle.PrepareColorTable", Sigs.PrepareColorSet, PrepareColorTableDetour, !HookOverrides.Instance.PostProcessing.PrepareColorTable).Result; @@ -160,7 +160,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _modelRendererUnkFuncHook.Dispose(); _modelRendererOnRenderMaterialHook.Dispose(); _humanOnRenderMaterialHook.Dispose(); - _humanSetupScalingHook.SetupReplacements -= SetupHSSReplacements; + _humanSetupScalingHook.SetupReplacements -= SetupHssReplacements; _communicator.MtrlLoaded.Unsubscribe(OnMtrlLoaded); _resourceHandleDestructor.Unsubscribe(OnResourceHandleDestructor); @@ -188,14 +188,6 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic _characterOcclusionState.GetAndResetSlowPathCallDelta(), _hairMaskState.GetAndResetSlowPathCallDelta()); - private static bool IsMaterialWithShpk(MaterialResourceHandle* mtrlResource, ReadOnlySpan shpkName) - { - if (mtrlResource == null) - return false; - - return shpkName.SequenceEqual(mtrlResource->ShpkNameSpan); - } - private void OnMtrlLoaded(nint mtrlResourceHandle, nint gameObject) { var mtrl = (MaterialResourceHandle*)mtrlResourceHandle; @@ -203,9 +195,11 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (shpk == null) return; - var shpkName = mtrl->ShpkNameSpan; - var shpkState = GetStateForHumanSetup(shpkName) ?? GetStateForHumanRender(shpkName) ?? GetStateForModelRendererRender(shpkName) - ?? GetStateForModelRendererUnk(shpkName) ?? GetStateForColorTable(shpkName); + var shpkName = mtrl->ShpkNameSpan; + var shpkState = GetStateForHumanSetup(shpkName) + ?? GetStateForHumanRender(shpkName) + ?? GetStateForModelRendererRender(shpkName) + ?? GetStateForModelRendererUnk(shpkName) ?? GetStateForColorTable(shpkName); if (shpkState != null && shpk != shpkState.DefaultShaderPackage) shpkState.TryAddMaterial(mtrlResourceHandle); @@ -228,12 +222,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic => mtrlResource == null ? null : GetStateForHumanSetup(mtrlResource->ShpkNameSpan); private ModdedShaderPackageState? GetStateForHumanSetup(ReadOnlySpan shpkName) - { - if (CharacterStockingsShpkName.SequenceEqual(shpkName)) - return _characterStockingsState; - - return null; - } + => CharacterStockingsShpkName.SequenceEqual(shpkName) ? _characterStockingsState : null; [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private uint GetTotalMaterialCountForHumanSetup() @@ -243,12 +232,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic => mtrlResource == null ? null : GetStateForHumanRender(mtrlResource->ShpkNameSpan); private ModdedShaderPackageState? GetStateForHumanRender(ReadOnlySpan shpkName) - { - if (SkinShpkName.SequenceEqual(shpkName)) - return _skinState; - - return null; - } + => SkinShpkName.SequenceEqual(shpkName) ? _skinState : null; [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private uint GetTotalMaterialCountForHumanRender() @@ -305,18 +289,13 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic + _characterStockingsState.MaterialCount; private ModdedShaderPackageState? GetStateForColorTable(ReadOnlySpan shpkName) - { - if (CharacterLegacyShpkName.SequenceEqual(shpkName)) - return _characterLegacyState; - - return null; - } + => CharacterLegacyShpkName.SequenceEqual(shpkName) ? _characterLegacyState : null; [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private uint GetTotalMaterialCountForColorTable() => _characterLegacyState.MaterialCount; - private void SetupHSSReplacements(CharacterBase* drawObject, uint slotIndex, Span replacements, + private void SetupHssReplacements(CharacterBase* drawObject, uint slotIndex, Span replacements, ref int numReplacements, ref IDisposable? pbdDisposable, ref object? shpkLock) { // If we don't have any on-screen instances of modded characterstockings.shpk, we don't need the slow path at all. @@ -326,6 +305,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic var model = drawObject->Models[slotIndex]; if (model == null) return; + MaterialResourceHandle* mtrlResource = null; ModdedShaderPackageState? shpkState = null; foreach (var material in model->MaterialsSpan) @@ -340,6 +320,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (shpkState != null) break; } + if (shpkState == null || shpkState.MaterialCount == 0) return; @@ -348,7 +329,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic // This is less performance-critical than the others, as this is called by the game only on draw object creation and slot update. // There are still thread safety concerns as it might be called in other threads by plugins. shpkLock = shpkState; - replacements[numReplacements++] = new((nint)shpkState.ShaderPackageReference, (nint)mtrlResource->ShaderPackageResourceHandle, + replacements[numReplacements++] = new HumanSetupScalingHook.Replacement((nint)shpkState.ShaderPackageReference, + (nint)mtrlResource->ShaderPackageResourceHandle, (nint)shpkState.DefaultShaderPackage); } @@ -439,7 +421,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic // Same performance considerations as OnRenderHumanMaterial. lock (shpkState) { - var shpkReference = shpkState.ShaderPackageReference; + var shpkReference = shpkState.ShaderPackageReference; try { *shpkReference = mtrlResource->ShaderPackageResourceHandle; @@ -452,7 +434,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic } } - private MaterialResourceHandle* GetMaterialResourceHandle(ModelRendererStructs.UnkPayload* unkPayload) + private static MaterialResourceHandle* GetMaterialResourceHandle(ModelRendererStructs.UnkPayload* unkPayload) { // TODO ClientStructs-ify var unkPointer = *(nint*)((nint)unkPayload->ModelResourceHandle + 0xE8) + unkPayload->UnkIndex * 0x24; @@ -467,13 +449,14 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (mtrlResource->ShaderPackageResourceHandle == null) { - Penumbra.Log.Warning($"ShaderReplacementFixer found a MaterialResourceHandle with no shader package"); + Penumbra.Log.Warning("ShaderReplacementFixer found a MaterialResourceHandle with no shader package"); return null; } if (mtrlResource->ShaderPackageResourceHandle->ShaderPackage != unkPayload->ShaderWrapper->ShaderPackage) { - Penumbra.Log.Warning($"ShaderReplacementFixer found a MaterialResourceHandle (0x{(nint)mtrlResource:X}) with an inconsistent shader package (got 0x{(nint)mtrlResource->ShaderPackageResourceHandle->ShaderPackage:X}, expected 0x{(nint)unkPayload->ShaderWrapper->ShaderPackage:X})"); + Penumbra.Log.Warning( + $"ShaderReplacementFixer found a MaterialResourceHandle (0x{(nint)mtrlResource:X}) with an inconsistent shader package (got 0x{(nint)mtrlResource->ShaderPackageResourceHandle->ShaderPackage:X}, expected 0x{(nint)unkPayload->ShaderWrapper->ShaderPackage:X})"); return null; } diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 4ab156a9..1641e42d 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -67,7 +67,7 @@ public unsafe class CharacterUtility : IDisposable, IRequiredService _framework.Update += LoadDefaultResources; } - /// We store the default data of the resources so we can always restore them. + /// We store the default data of the resources, so we can always restore them. private void LoadDefaultResources(object _) { if (Address == null) From 465e65e8fec7a3a3c1a51174ee99955390c15506 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 8 Aug 2024 23:17:52 +0000 Subject: [PATCH 0861/1381] [CI] Updating repo.json for testing_1.2.0.23 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 3de0c5c8..efb71542 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.22", + "TestingAssemblyVersion": "1.2.0.23", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.22/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.23/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From e44b450548f42bac821d3c3746a868e976aec420 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 9 Aug 2024 22:17:23 +0200 Subject: [PATCH 0862/1381] Disable model import/export for now. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index de088736..490fa147 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -97,7 +97,9 @@ public partial class ModEditWindow private void DrawImportExport(MdlTab tab, bool disabled) { - if (!ImGui.CollapsingHeader("Import / Export")) + // TODO: Enable when functional. + using var dawntrailDisabled = ImRaii.Disabled(); + if (!ImGui.CollapsingHeader("Import / Export (currently disabled due to Dawntrail format changes)") || true) return; var childSize = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); From b5f7f03e11cc9dc26555667f3f90448413d20d3c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 9 Aug 2024 22:46:34 +0200 Subject: [PATCH 0863/1381] Update BNPC Names. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2fd5aa44..bf020ebf 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2fd5aa44056a906df90c9a826d1d17f6fdafebff +Subproject commit bf020ebf5e4980f1814b336aabbaba5e2e00c362 From 1b671b95ab2c95b4af554430746f18d82d50e806 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 9 Aug 2024 23:04:07 +0200 Subject: [PATCH 0864/1381] 1.2.1.0 --- Penumbra/UI/Changelog.cs | 63 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index f4cedf7d..55ce70e4 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -52,18 +52,68 @@ public class PenumbraChangelog : IUiService AddDummy(Changelog); Add1_1_0_0(Changelog); Add1_1_1_0(Changelog); - } - + Add1_2_1_0(Changelog); + } + #region Changelogs + private static void Add1_2_1_0(Changelog log) + => log.NextVersion("Version 1.2.1.0") + .RegisterHighlight("Penumbra is now released for Dawntrail.") + .RegisterEntry("Mods themselves may have to be updated. TexTools provides options for this.", 1) + .RegisterEntry("For model files, Penumbra provides a rudimentary update function, but prefer using TexTools if possible.", 1) + .RegisterEntry("Other files, like materials and textures, will have to go through TexTools for the moment.", 1) + .RegisterImportant("I am sorry that it took this long, but there was an immense amount of work to be done from the start.") + .RegisterImportant( + "Since Penumbra has been in Testing for quite a while, multitudes of bugs and issues cropped up that needed to be dealt with.", + 1) + .RegisterEntry("There very well may still be a lot of issues, so please report any you find.", 1) + .RegisterImportant("BUT, please make sure that those issues are not caused by outdated mods before reporting them.", 1) + .RegisterEntry( + "This changelog may seem rather short for the timespan, but I omitted hundreds of smaller fixes and the details of getting Penumbra to work in Dawntrail.", + 1) + .RegisterHighlight("The Material Editing tab in the Advanced Editing Window has been heavily improved (by Ny).") + .RegisterEntry( + "Especially for Dawntrail materials using the new shaders, the window provides much more in-depth and user-friendly editing options.", + 1) + .RegisterHighlight("Many advancements regarding modded shaders, and modding bone deformers have been made.") + .RegisterHighlight("IMC groups now allow their options to toggle attributes off that are on in the default entry.") + .RegisterImportant( + "The 'Update Bibo' button was removed. The functionality is redundant since any mods that old need to be updated anyway.") + .RegisterEntry("Clicking the button on modern mods generally caused more harm than benefit.", 1) + .RegisterImportant("Model Import/Export is temporarily disabled until Dawntrail-related changes can be made.") + .RegisterEntry( + "If you somehow still need to mass-migrate materials in your models, the Material Reassignment tab in Advanced Editing is still available for this.", + 1) + .RegisterHighlight("You can now change a mods state in any collection from its Collections tab via right-clicking the state.") + .RegisterHighlight("Items changed in a mod now sort before other items in the Item Swap tab, and are highlighted.") + .RegisterEntry("Path handling was improved in regards to case-sensitivity.") + .RegisterEntry("Fixed an issue with negative search matching on folders with no matches") + .RegisterEntry("Mod option groups on the same priority are now applied in reverse index order. (1.2.0.12)") + .RegisterEntry("Fixed the display of missing files in the Advanced Editing Window's header. (1.2.0.8)") + .RegisterEntry( + "Fixed some, but not all soft-locks that occur when your character gets redrawn while fishing. Just do not do that. (1.2.0.7)") + .RegisterEntry("Improved handling of invalid Offhand IMC files for certain jobs. (1.2.0.6)") + .RegisterEntry("Added automatic reduplication for files in the UI category, as they cause crashes when not unique. (1.2.0.5)") + .RegisterEntry("The mod import popup can now be closed by clicking outside of it, if it is finished. (1.2.0.5)") + .RegisterEntry("Fixed an issue with Mod Normalization skipping the default option. (1.2.0.5)") + .RegisterEntry("Improved the Support Info output. (1.1.1.5)") + .RegisterEntry("Reworked the handling of Meta Manipulations entirely. (1.1.1.3)") + .RegisterEntry("Added a configuration option to disable showing mods in the character lobby and at the aesthetician. (1.1.1.1)") + .RegisterEntry("Fixed an issue with the AddMods API and the root directory. (1.1.1.2)") + .RegisterEntry("Fixed an issue with the Mod Merger file lookup and casing. (1.1.1.2)") + .RegisterEntry("Fixed an issue with file saving not happening when merging mods or swapping items in some cases. (1.1.1.2)"); + private static void Add1_1_1_0(Changelog log) => log.NextVersion("Version 1.1.1.0") .RegisterHighlight("Filtering for mods is now tokenized and can filter for multiple things at once, or exclude specific things.") .RegisterEntry("Hover over the filter to see the new available options in the tooltip.", 1) - .RegisterEntry("Be aware that the tokenization changed the prior behavior slightly.", 1) - .RegisterEntry("This is open to improvements, if you have any ideas, let me know!", 1) + .RegisterEntry("Be aware that the tokenization changed the prior behavior slightly.", 1) + .RegisterEntry("This is open to improvements, if you have any ideas, let me know!", 1) .RegisterHighlight("Added initial identification of characters in the login-screen by name.") - .RegisterEntry("Those characters can not be redrawn and re-use some things, so this may not always behave as expected, but should work in general. Let me know if you encounter edge cases!", 1) + .RegisterEntry( + "Those characters can not be redrawn and re-use some things, so this may not always behave as expected, but should work in general. Let me know if you encounter edge cases!", + 1) .RegisterEntry("Added functionality for IMC groups to apply to all variants for a model instead of a specific one.") .RegisterEntry("Improved the resource tree view with filters and incognito mode. (by Ny)") .RegisterEntry("Added a tooltip to the global EQP condition.") @@ -131,7 +181,8 @@ public class PenumbraChangelog : IUiService .RegisterEntry( "Made some improvements to the Advanced Editing window, for example a much better and more performant Hex Viewer for unstructured data was added.") .RegisterEntry("Various improvements to model import/export by ackwell (throughout all patches).") - .RegisterEntry("Hovering over meta manipulations in other options in the advanced editing window now shows a list of those options.") + .RegisterEntry( + "Hovering over meta manipulations in other options in the advanced editing window now shows a list of those options.") .RegisterEntry("Reworked the API and IPC structure heavily.") .RegisterImportant("This means some plugins interacting with Penumbra may not work correctly until they update.", 1) .RegisterEntry("Worked around the UI IPC possibly displacing all settings when the drawn additions became too big.") From 741141f22769fe8af8991545867d44082a65a466 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 9 Aug 2024 23:52:12 +0200 Subject: [PATCH 0865/1381] Woops. --- Penumbra/UI/Changelog.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 55ce70e4..5bf4f59d 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -59,7 +59,7 @@ public class PenumbraChangelog : IUiService private static void Add1_2_1_0(Changelog log) => log.NextVersion("Version 1.2.1.0") - .RegisterHighlight("Penumbra is now released for Dawntrail.") + .RegisterHighlight("Penumbra is now released for Dawntrail!") .RegisterEntry("Mods themselves may have to be updated. TexTools provides options for this.", 1) .RegisterEntry("For model files, Penumbra provides a rudimentary update function, but prefer using TexTools if possible.", 1) .RegisterEntry("Other files, like materials and textures, will have to go through TexTools for the moment.", 1) @@ -81,10 +81,10 @@ public class PenumbraChangelog : IUiService .RegisterImportant( "The 'Update Bibo' button was removed. The functionality is redundant since any mods that old need to be updated anyway.") .RegisterEntry("Clicking the button on modern mods generally caused more harm than benefit.", 1) - .RegisterImportant("Model Import/Export is temporarily disabled until Dawntrail-related changes can be made.") .RegisterEntry( "If you somehow still need to mass-migrate materials in your models, the Material Reassignment tab in Advanced Editing is still available for this.", 1) + .RegisterImportant("Model Import/Export is temporarily disabled until Dawntrail-related changes can be made.") .RegisterHighlight("You can now change a mods state in any collection from its Collections tab via right-clicking the state.") .RegisterHighlight("Items changed in a mod now sort before other items in the Item Swap tab, and are highlighted.") .RegisterEntry("Path handling was improved in regards to case-sensitivity.") From 421fde70b08db075c359bd699a079bf64e8297e9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 9 Aug 2024 23:57:42 +0200 Subject: [PATCH 0866/1381] Addendum --- Penumbra/UI/Changelog.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 5bf4f59d..41920d1c 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -63,6 +63,8 @@ public class PenumbraChangelog : IUiService .RegisterEntry("Mods themselves may have to be updated. TexTools provides options for this.", 1) .RegisterEntry("For model files, Penumbra provides a rudimentary update function, but prefer using TexTools if possible.", 1) .RegisterEntry("Other files, like materials and textures, will have to go through TexTools for the moment.", 1) + .RegisterEntry( + "Some outdated mods can be identified by Penumbra and are prevented from loading entirely (specifically shaders, by Ny).", 1) .RegisterImportant("I am sorry that it took this long, but there was an immense amount of work to be done from the start.") .RegisterImportant( "Since Penumbra has been in Testing for quite a while, multitudes of bugs and issues cropped up that needed to be dealt with.", @@ -84,6 +86,7 @@ public class PenumbraChangelog : IUiService .RegisterEntry( "If you somehow still need to mass-migrate materials in your models, the Material Reassignment tab in Advanced Editing is still available for this.", 1) + .RegisterEntry("The On-Screen tab was updated and improved and can now display modded actual paths in more useful form.") .RegisterImportant("Model Import/Export is temporarily disabled until Dawntrail-related changes can be made.") .RegisterHighlight("You can now change a mods state in any collection from its Collections tab via right-clicking the state.") .RegisterHighlight("Items changed in a mod now sort before other items in the Item Swap tab, and are highlighted.") From 7ba7a6e31915ba84c05fd41ffc46b486b67e9caa Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 10 Aug 2024 11:55:30 +0200 Subject: [PATCH 0867/1381] API 5.3 --- Penumbra.Api | 2 +- Penumbra/Api/Api/PenumbraApi.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 759a8e9d..552246e5 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 759a8e9dc50b3453cdb7c3cba76de7174c94aba0 +Subproject commit 552246e595ffab2aaba2c75f578d564f8938fc9a diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 0400c694..eaaf9f38 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -22,7 +22,7 @@ public class PenumbraApi( } public (int Breaking, int Feature) ApiVersion - => (5, 1); + => (5, 3); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; From ccce087b8706b95997f2c97e8df7c8ee3d9ff44c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 10 Aug 2024 11:59:18 +0200 Subject: [PATCH 0868/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index bf020ebf..3a65ed1c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit bf020ebf5e4980f1814b336aabbaba5e2e00c362 +Subproject commit 3a65ed1c86a2d5fd5794ff5c0559b02fc25d7224 From 5c9e158da36bbae9fb1299da16ef918b1aef1417 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 10 Aug 2024 10:01:17 +0000 Subject: [PATCH 0869/1381] [CI] Updating repo.json for 1.2.1.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index efb71542..0e5c7799 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.1.1.2", - "TestingAssemblyVersion": "1.2.0.23", + "AssemblyVersion": "1.2.1.0", + "TestingAssemblyVersion": "1.2.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 9, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.0.23/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.1.1.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a27ce6b0a78243708c1134fcc945a09f05796351 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 10 Aug 2024 12:23:17 +0200 Subject: [PATCH 0870/1381] Update non-testing DalamudApiLevel. --- Penumbra.sln | 3 ++- repo.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Penumbra.sln b/Penumbra.sln index 78fa1543..46609f85 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -8,6 +8,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F89C9EAE-25C8-43BE-8108-5921E5A93502}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig + repo.json = repo.json EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.GameData", "Penumbra.GameData\Penumbra.GameData.csproj", "{EE551E87-FDB3-4612-B500-DC870C07C605}" @@ -18,7 +19,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.Api", "Penumbra.Ap EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.String", "Penumbra.String\Penumbra.String.csproj", "{5549BAFD-6357-4B1A-800C-75AC36E5B76D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Penumbra.CrashHandler", "Penumbra.CrashHandler\Penumbra.CrashHandler.csproj", "{EE834491-A98F-4395-BE0D-6861AE5AD953}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.CrashHandler", "Penumbra.CrashHandler\Penumbra.CrashHandler.csproj", "{EE834491-A98F-4395-BE0D-6861AE5AD953}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/repo.json b/repo.json index 0e5c7799..73ae9eff 100644 --- a/repo.json +++ b/repo.json @@ -9,7 +9,7 @@ "TestingAssemblyVersion": "1.2.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 9, + "DalamudApiLevel": 10, "TestingDalamudApiLevel": 10, "IsHide": "False", "IsTestingExclusive": "False", From 7710d9249675e6550f9db2eaaf94e1c570929c23 Mon Sep 17 00:00:00 2001 From: "N. Lo." Date: Sat, 10 Aug 2024 18:59:02 +0200 Subject: [PATCH 0871/1381] Add another plugin to Copy Support Info --- Penumbra/Penumbra.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index d99e3fcd..6f0b63ce 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -186,7 +186,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", - "IllusioVitae", + "IllusioVitae", "Aetherment", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) From 6b0b1629bd2e828d6f237fe64f84c84d6066534c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 11 Aug 2024 23:22:05 +0200 Subject: [PATCH 0872/1381] Move GuidExtensions to OtterGui (unused atm) --- OtterGui | 2 +- Penumbra/GuidExtensions.cs | 254 ------------------------------------- 2 files changed, 1 insertion(+), 255 deletions(-) delete mode 100644 Penumbra/GuidExtensions.cs diff --git a/OtterGui b/OtterGui index d9486ae5..07a00913 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit d9486ae54b5a4b61cf74f79ed27daa659eb1ce5b +Subproject commit 07a009134bf5eb7da9a54ba40e82c88fc613544a diff --git a/Penumbra/GuidExtensions.cs b/Penumbra/GuidExtensions.cs deleted file mode 100644 index fcbc8a3b..00000000 --- a/Penumbra/GuidExtensions.cs +++ /dev/null @@ -1,254 +0,0 @@ -using System.Collections.Frozen; -using OtterGui; - -namespace Penumbra; - -public static class GuidExtensions -{ - private const string Chars = - "0123456789" - + "abcdefghij" - + "klmnopqrst" - + "uv"; - - private static ReadOnlySpan Bytes - => "0123456789abcdefghijklmnopqrstuv"u8; - - private static readonly FrozenDictionary - ReverseChars = Chars.WithIndex().ToFrozenDictionary(t => t.Value, t => (byte)t.Index); - - private static readonly FrozenDictionary ReverseBytes = - ReverseChars.ToFrozenDictionary(kvp => (byte)kvp.Key, kvp => kvp.Value); - - public static unsafe string OptimizedString(this Guid guid) - { - var bytes = stackalloc ulong[2]; - if (!guid.TryWriteBytes(new Span(bytes, 16))) - return guid.ToString("N"); - - var u1 = bytes[0]; - var u2 = bytes[1]; - Span text = - [ - Chars[(int)(u1 & 0x1F)], - Chars[(int)((u1 >> 5) & 0x1F)], - Chars[(int)((u1 >> 10) & 0x1F)], - Chars[(int)((u1 >> 15) & 0x1F)], - Chars[(int)((u1 >> 20) & 0x1F)], - Chars[(int)((u1 >> 25) & 0x1F)], - Chars[(int)((u1 >> 30) & 0x1F)], - Chars[(int)((u1 >> 35) & 0x1F)], - Chars[(int)((u1 >> 40) & 0x1F)], - Chars[(int)((u1 >> 45) & 0x1F)], - Chars[(int)((u1 >> 50) & 0x1F)], - Chars[(int)((u1 >> 55) & 0x1F)], - Chars[(int)((u1 >> 60) | ((u2 & 0x01) << 4))], - Chars[(int)((u2 >> 1) & 0x1F)], - Chars[(int)((u2 >> 6) & 0x1F)], - Chars[(int)((u2 >> 11) & 0x1F)], - Chars[(int)((u2 >> 16) & 0x1F)], - Chars[(int)((u2 >> 21) & 0x1F)], - Chars[(int)((u2 >> 26) & 0x1F)], - Chars[(int)((u2 >> 31) & 0x1F)], - Chars[(int)((u2 >> 36) & 0x1F)], - Chars[(int)((u2 >> 41) & 0x1F)], - Chars[(int)((u2 >> 46) & 0x1F)], - Chars[(int)((u2 >> 51) & 0x1F)], - Chars[(int)((u2 >> 56) & 0x1F)], - Chars[(int)((u2 >> 61) & 0x1F)], - ]; - return new string(text); - } - - public static unsafe bool FromOptimizedString(ReadOnlySpan text, out Guid guid) - { - if (text.Length != 26) - return Return(out guid); - - var bytes = stackalloc ulong[2]; - if (!ReverseChars.TryGetValue(text[0], out var b0)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[1], out var b1)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[2], out var b2)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[3], out var b3)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[4], out var b4)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[5], out var b5)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[6], out var b6)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[7], out var b7)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[8], out var b8)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[9], out var b9)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[10], out var b10)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[11], out var b11)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[12], out var b12)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[13], out var b13)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[14], out var b14)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[15], out var b15)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[16], out var b16)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[17], out var b17)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[18], out var b18)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[19], out var b19)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[20], out var b20)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[21], out var b21)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[22], out var b22)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[23], out var b23)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[24], out var b24)) - return Return(out guid); - if (!ReverseChars.TryGetValue(text[25], out var b25)) - return Return(out guid); - - bytes[0] = b0 - | ((ulong)b1 << 5) - | ((ulong)b2 << 10) - | ((ulong)b3 << 15) - | ((ulong)b4 << 20) - | ((ulong)b5 << 25) - | ((ulong)b6 << 30) - | ((ulong)b7 << 35) - | ((ulong)b8 << 40) - | ((ulong)b9 << 45) - | ((ulong)b10 << 50) - | ((ulong)b11 << 55) - | ((ulong)b12 << 60); - bytes[1] = ((ulong)b12 >> 4) - | ((ulong)b13 << 1) - | ((ulong)b14 << 6) - | ((ulong)b15 << 11) - | ((ulong)b16 << 16) - | ((ulong)b17 << 21) - | ((ulong)b18 << 26) - | ((ulong)b19 << 31) - | ((ulong)b20 << 36) - | ((ulong)b21 << 41) - | ((ulong)b22 << 46) - | ((ulong)b23 << 51) - | ((ulong)b24 << 56) - | ((ulong)b25 << 61); - guid = new Guid(new Span(bytes, 16)); - return true; - - static bool Return(out Guid guid) - { - guid = Guid.Empty; - return false; - } - } - - public static unsafe bool FromOptimizedString(ReadOnlySpan text, out Guid guid) - { - if (text.Length != 26) - return Return(out guid); - - var bytes = stackalloc ulong[2]; - if (!ReverseBytes.TryGetValue(text[0], out var b0)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[1], out var b1)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[2], out var b2)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[3], out var b3)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[4], out var b4)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[5], out var b5)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[6], out var b6)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[7], out var b7)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[8], out var b8)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[9], out var b9)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[10], out var b10)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[11], out var b11)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[12], out var b12)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[13], out var b13)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[14], out var b14)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[15], out var b15)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[16], out var b16)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[17], out var b17)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[18], out var b18)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[19], out var b19)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[20], out var b20)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[21], out var b21)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[22], out var b22)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[23], out var b23)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[24], out var b24)) - return Return(out guid); - if (!ReverseBytes.TryGetValue(text[25], out var b25)) - return Return(out guid); - - bytes[0] = b0 - | ((ulong)b1 << 5) - | ((ulong)b2 << 10) - | ((ulong)b3 << 15) - | ((ulong)b4 << 20) - | ((ulong)b5 << 25) - | ((ulong)b6 << 30) - | ((ulong)b7 << 35) - | ((ulong)b8 << 40) - | ((ulong)b9 << 45) - | ((ulong)b10 << 50) - | ((ulong)b11 << 55) - | ((ulong)b12 << 60); - bytes[1] = ((ulong)b12 >> 4) - | ((ulong)b13 << 1) - | ((ulong)b14 << 6) - | ((ulong)b15 << 11) - | ((ulong)b16 << 16) - | ((ulong)b17 << 21) - | ((ulong)b18 << 26) - | ((ulong)b19 << 31) - | ((ulong)b20 << 36) - | ((ulong)b21 << 41) - | ((ulong)b22 << 46) - | ((ulong)b23 << 51) - | ((ulong)b24 << 56) - | ((ulong)b25 << 61); - guid = new Guid(new Span(bytes, 16)); - return true; - - static bool Return(out Guid guid) - { - guid = Guid.Empty; - return false; - } - } -} From 47268ab377db99a91cfc14e7560e459bbb095171 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 11 Aug 2024 23:22:42 +0200 Subject: [PATCH 0873/1381] Prevent loading crashy shpks. --- Penumbra/Interop/PathResolving/PathResolver.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 67ec4fc3..63bbc8d8 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -61,7 +61,7 @@ public class PathResolver : IDisposable, IService ResourceCategory.GameScript => (null, ResolveData.Invalid), // Use actual resolving. ResourceCategory.Chara => Resolve(path, resourceType), - ResourceCategory.Shader => Resolve(path, resourceType), + ResourceCategory.Shader => ResolveShader(path, resourceType), ResourceCategory.Vfx => Resolve(path, resourceType), ResourceCategory.Sound => Resolve(path, resourceType), // EXD Modding in general should probably be prohibited but is currently used for fan translations. @@ -83,6 +83,19 @@ public class PathResolver : IDisposable, IService }; } + /// Replacing the characterstockings.shpk or the characterocclusion.shpk files currently causes crashes, so we just entirely prevent that. + private (FullPath?, ResolveData) ResolveShader(Utf8GamePath gamePath, ResourceType type) + { + if (type is not ResourceType.Shpk) + return Resolve(gamePath, type); + + if (gamePath.Path.EndsWith("occlusion.shpk"u8) + || gamePath.Path.EndsWith("stockings.shpk"u8)) + return (null, ResolveData.Invalid); + + return Resolve(gamePath, type); + } + public (FullPath?, ResolveData) Resolve(Utf8GamePath gamePath, ResourceType type) { using var performance = _performance.Measure(PerformanceType.CharacterResolver); From 8ee326853d3e15c8b4e949dfdacfb0e5f5c1c817 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 11 Aug 2024 23:24:18 +0200 Subject: [PATCH 0874/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 3a65ed1c..b7fdfe9d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3a65ed1c86a2d5fd5794ff5c0559b02fc25d7224 +Subproject commit b7fdfe9d19f7e3229834480db446478b0bf6acee From 6e351aa68b5903ff0b691eed43ed1c1d72ae65ff Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 12 Aug 2024 20:57:06 +0200 Subject: [PATCH 0875/1381] Make mods added via API migrate models if enabled. --- Penumbra/Api/Api/ModsApi.cs | 11 ++++++++++- Penumbra/Services/MigrationManager.cs | 3 +++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 790121d5..2acdf031 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -15,15 +15,17 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable private readonly ModImportManager _modImportManager; private readonly Configuration _config; private readonly ModFileSystem _modFileSystem; + private readonly MigrationManager _migrationManager; public ModsApi(ModManager modManager, ModImportManager modImportManager, Configuration config, ModFileSystem modFileSystem, - CommunicatorService communicator) + CommunicatorService communicator, MigrationManager migrationManager) { _modManager = modManager; _modImportManager = modImportManager; _config = config; _modFileSystem = modFileSystem; _communicator = communicator; + _migrationManager = migrationManager; _communicator.ModPathChanged.Subscribe(OnModPathChanged, ModPathChanged.Priority.ApiMods); } @@ -81,9 +83,16 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); _modManager.AddMod(dir); + if (_config.MigrateImportedModelsToV6) + { + _migrationManager.MigrateMdlDirectory(dir.FullName, false); + _migrationManager.Await(); + } + if (_config.UseFileSystemCompression) new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K); + return ApiHelpers.Return(PenumbraApiEc.Success, args); } diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 7726f6fd..9041fbd0 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -63,6 +63,9 @@ public class MigrationManager(Configuration config) : IService public void CleanMtrlBackups(string path) => CleanBackups(path, "*.mtrl.bak", "material", MtrlCleanup, TaskType.MtrlCleanup); + public void Await() + => _currentTask?.Wait(); + private void CleanBackups(string path, string extension, string fileType, MigrationData data, TaskType type) { if (IsRunning) From 3135d5e7e656cc37b6a60744f3cb63d50ca79b08 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 12 Aug 2024 20:57:38 +0200 Subject: [PATCH 0876/1381] Make collection combo mousewheel-scrollable with ctrl. --- Penumbra/UI/CollectionTab/CollectionCombo.cs | 23 +++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index 9d195eed..1670be5e 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -1,14 +1,15 @@ using ImGuiNET; +using OtterGui; using OtterGui.Raii; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Manager; -using Penumbra.GameData.Actors; namespace Penumbra.UI.CollectionTab; public sealed class CollectionCombo(CollectionManager manager, Func> items) - : FilterComboCache(items, MouseWheelType.None, Penumbra.Log) + : FilterComboCache(items, MouseWheelType.Control, Penumbra.Log) { private readonly ImRaii.Color _color = new(); @@ -20,14 +21,26 @@ public sealed class CollectionCombo(CollectionManager manager, Func obj.Name; + + protected override void DrawCombo(string label, string preview, string tooltip, int currentSelected, float previewWidth, float itemHeight, + ImGuiComboFlags flags) + { + base.DrawCombo(label, preview, tooltip, currentSelected, previewWidth, itemHeight, flags); + ImUtf8.HoverTooltip("Control and mouse wheel to scroll."u8); + } } From bb9dd184a369513bd872cdb2e5c866f0d1b96b33 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 12 Aug 2024 20:57:52 +0200 Subject: [PATCH 0877/1381] Fix order of gender and model in EQDP drawer. --- Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index 970b70cb..5206ece8 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -86,11 +86,11 @@ public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFil ImUtf8.HoverTooltip("Model Set ID"u8); ImGui.TableNextColumn(); - ImUtf8.TextFramed(identifier.Gender.ToName(), FrameColor); + ImUtf8.TextFramed(identifier.Race.ToName(), FrameColor); ImUtf8.HoverTooltip("Model Race"u8); ImGui.TableNextColumn(); - ImUtf8.TextFramed(identifier.Race.ToName(), FrameColor); + ImUtf8.TextFramed(identifier.Gender.ToName(), FrameColor); ImUtf8.HoverTooltip("Gender"u8); ImGui.TableNextColumn(); From bedf5dab794b1ddbe4a2c5edcd60074d239963f4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 12 Aug 2024 20:58:17 +0200 Subject: [PATCH 0878/1381] Make collection resolver not cache early resolved actors that aren't characters. --- Penumbra/Interop/PathResolving/CollectionResolver.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 136da0f5..313c4f8b 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -216,10 +216,13 @@ public sealed unsafe class CollectionResolver( private ModCollection? CollectionByAttributes(Actor actor, ref bool notYetReady) { if (!actor.IsCharacter) + { + Penumbra.Log.Excessive($"Actor to be identified was not yet a Character."); + notYetReady = true; return null; + } // Only handle human models. - if (!IsModelHuman((uint)actor.AsCharacter->CharacterData.ModelCharaId)) return null; From 1da095be9946e9fa2879ef8b61d201f25b3086d6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 12 Aug 2024 19:00:43 +0000 Subject: [PATCH 0879/1381] [CI] Updating repo.json for 1.2.1.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 73ae9eff..5a274d73 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.2.1.0", - "TestingAssemblyVersion": "1.2.1.0", + "AssemblyVersion": "1.2.1.1", + "TestingAssemblyVersion": "1.2.1.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 96f0479b53b62b41f9ccd136c87884d35ecc1234 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Aug 2024 20:42:29 +0200 Subject: [PATCH 0880/1381] Some cleanup. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs | 1 - Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs | 1 - Penumbra/UI/Tabs/Debug/DebugTab.cs | 5 ++--- 5 files changed, 4 insertions(+), 7 deletions(-) diff --git a/OtterGui b/OtterGui index 07a00913..276327f8 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 07a009134bf5eb7da9a54ba40e82c88fc613544a +Subproject commit 276327f812e2f7e6aac7aee9e5ef0a560b065765 diff --git a/Penumbra.GameData b/Penumbra.GameData index b7fdfe9d..c8708ec5 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b7fdfe9d19f7e3229834480db446478b0bf6acee +Subproject commit c8708ec5153cb60c9e43b2c53d02b81b2c8175f9 diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index 4aae45a2..515f6ff4 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -2,7 +2,6 @@ using OtterGui.Classes; using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.GameData.Structs; -using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 9d1ab78a..4ab1c6aa 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -4,7 +4,6 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Text.Widget; -using OtterGui.Widgets; using OtterGuiInternal.Utility; using Penumbra.GameData.Structs; using Penumbra.Mods.Groups; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 5b82a523..7c6cd01e 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -1,5 +1,4 @@ using Dalamud.Interface; -using Dalamud.Interface.Utility; using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; @@ -43,7 +42,6 @@ using Penumbra.Api.IpcTester; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.GameData.Files.StainMapStructs; -using Penumbra.UI.AdvancedWindow; using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.UI.Tabs.Debug; @@ -721,7 +719,8 @@ public class DebugTab : Window, ITab, IUiService if (!tree) continue; - using var table = Table("##table", data.Colors.Length + data.Scalars.Length, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); + using var table = Table("##table", data.Colors.Length + data.Scalars.Length, + ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); if (!table) continue; From 35492837690b93761a7e9c2c52f2c20cb28b5765 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Aug 2024 20:42:47 +0200 Subject: [PATCH 0881/1381] Order meta entries. --- .../UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 5 ++++- .../UI/AdvancedWindow/Meta/EqpMetaDrawer.cs | 5 ++++- .../UI/AdvancedWindow/Meta/EstMetaDrawer.cs | 6 +++++- .../Meta/GlobalEqpMetaDrawer.cs | 5 ++++- .../UI/AdvancedWindow/Meta/GmpMetaDrawer.cs | 4 +++- .../UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 21 ++++++++++++------- .../UI/AdvancedWindow/Meta/RspMetaDrawer.cs | 5 ++++- 7 files changed, 38 insertions(+), 13 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index 5206ece8..f586045c 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -61,7 +61,10 @@ public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFil } protected override IEnumerable<(EqdpIdentifier, EqdpEntryInternal)> Enumerate() - => Editor.Eqdp.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Eqdp.OrderBy(kvp => kvp.Key.SetId) + .ThenBy(kvp => kvp.Key.GenderRace) + .ThenBy(kvp => kvp.Key.Slot) + .Select(kvp => (kvp.Key, kvp.Value)); private static bool DrawIdentifierInput(ref EqdpIdentifier identifier) { diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs index 56c06bc9..b1031b44 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs @@ -59,7 +59,10 @@ public sealed class EqpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } protected override IEnumerable<(EqpIdentifier, EqpEntryInternal)> Enumerate() - => Editor.Eqp.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Eqp + .OrderBy(kvp => kvp.Key.SetId) + .ThenBy(kvp => kvp.Key.Slot) + .Select(kvp => (kvp.Key, kvp.Value)); private static bool DrawIdentifierInput(ref EqpIdentifier identifier) { diff --git a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs index 5c3c5df5..628cee40 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs @@ -58,7 +58,11 @@ public sealed class EstMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } protected override IEnumerable<(EstIdentifier, EstEntry)> Enumerate() - => Editor.Est.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Est + .OrderBy(kvp => kvp.Key.SetId) + .ThenBy(kvp => kvp.Key.GenderRace) + .ThenBy(kvp => kvp.Key.Slot) + .Select(kvp => (kvp.Key, kvp.Value)); private static bool DrawIdentifierInput(ref EstIdentifier identifier) { diff --git a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs index 130831a0..bc2e1bde 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs @@ -47,7 +47,10 @@ public sealed class GlobalEqpMetaDrawer(ModMetaEditor editor, MetaFileManager me } protected override IEnumerable<(GlobalEqpManipulation, byte)> Enumerate() - => Editor.GlobalEqp.Select(identifier => (identifier, (byte)0)); + => Editor.GlobalEqp + .OrderBy(identifier => identifier.Type) + .ThenBy(identifier => identifier.Condition) + .Select(identifier => (identifier, (byte)0)); private static void DrawIdentifierInput(ref GlobalEqpManipulation identifier) { diff --git a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs index 87ed21dc..1e91731d 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs @@ -57,7 +57,9 @@ public sealed class GmpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } protected override IEnumerable<(GmpIdentifier, GmpEntry)> Enumerate() - => Editor.Gmp.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Gmp + .OrderBy(kvp => kvp.Key.SetId) + .Select(kvp => (kvp.Key, kvp.Value)); private static bool DrawIdentifierInput(ref GmpIdentifier identifier) { diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index 58f626fc..e33eb1aa 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -140,7 +140,14 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override IEnumerable<(ImcIdentifier, ImcEntry)> Enumerate() - => Editor.Imc.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Imc + .OrderBy(kvp => kvp.Key.ObjectType) + .ThenBy(kvp => kvp.Key.PrimaryId) + .ThenBy(kvp => kvp.Key.EquipSlot) + .ThenBy(kvp => kvp.Key.BodySlot) + .ThenBy(kvp => kvp.Key.SecondaryId) + .ThenBy(kvp => kvp.Key.Variant) + .Select(kvp => (kvp.Key, kvp.Value)); public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) { @@ -149,18 +156,18 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile if (ret) { - var equipSlot = type switch + var (equipSlot, secondaryId) = type switch { - ObjectType.Equipment => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, - ObjectType.DemiHuman => identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, - ObjectType.Accessory => identifier.EquipSlot.IsAccessory() ? identifier.EquipSlot : EquipSlot.Ears, - _ => EquipSlot.Unknown, + ObjectType.Equipment => (identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, (SecondaryId) 0), + ObjectType.DemiHuman => (identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId), + ObjectType.Accessory => (identifier.EquipSlot.IsAccessory() ? identifier.EquipSlot : EquipSlot.Ears, (SecondaryId)0), + _ => (EquipSlot.Unknown, identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId), }; identifier = identifier with { ObjectType = type, EquipSlot = equipSlot, - SecondaryId = identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId, + SecondaryId = secondaryId, }; } diff --git a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs index be02e321..6d819b16 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs @@ -58,7 +58,10 @@ public sealed class RspMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } protected override IEnumerable<(RspIdentifier, RspEntry)> Enumerate() - => Editor.Rsp.Select(kvp => (kvp.Key, kvp.Value)); + => Editor.Rsp + .OrderBy(kvp => kvp.Key.SubRace) + .ThenBy(kvp => kvp.Key.Attribute) + .Select(kvp => (kvp.Key, kvp.Value)); private static bool DrawIdentifierInput(ref RspIdentifier identifier) { From a2237773e315be9f3209ab8c6a462e5cdcf8837e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Aug 2024 20:43:11 +0200 Subject: [PATCH 0882/1381] Update packages. --- Penumbra/Import/Models/Export/MeshExporter.cs | 13 +- .../Import/Models/Export/VertexFragment.cs | 140 ++++++++++++------ .../Import/Models/Import/SubMeshImporter.cs | 2 +- Penumbra/Import/TexToolsImport.cs | 2 +- Penumbra/Import/TexToolsImporter.Archives.cs | 12 +- Penumbra/Penumbra.csproj | 8 +- Penumbra/Services/MigrationManager.cs | 2 +- Penumbra/packages.lock.json | 54 ++++--- 8 files changed, 139 insertions(+), 94 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 219a046e..3a57ab55 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -1,4 +1,6 @@ using System.Collections.Immutable; +using System.Text.Json; +using System.Text.Json.Nodes; using Lumina.Extensions; using OtterGui; using Penumbra.GameData.Files; @@ -23,11 +25,11 @@ public class MeshExporter ? scene.AddSkinnedMesh(data.Mesh, Matrix4x4.Identity, [.. skeleton.Value.Joints]) : scene.AddRigidMesh(data.Mesh, Matrix4x4.Identity); - var extras = new Dictionary(data.Attributes.Length); + var node = new JsonObject(); foreach (var attribute in data.Attributes) - extras.Add(attribute, true); + node[attribute] = true; - instance.WithExtras(JsonContent.CreateFrom(extras)); + instance.WithExtras(node); } } } @@ -233,10 +235,7 @@ public class MeshExporter // Named morph targets aren't part of the specification, however `MESH.extras.targetNames` // is a commonly-accepted means of providing the data. - meshBuilder.Extras = JsonContent.CreateFrom(new Dictionary() - { - { "targetNames", shapeNames }, - }); + meshBuilder.Extras = new JsonObject { ["targetNames"] = JsonSerializer.SerializeToNode(shapeNames) }; string[] attributes = []; var maxAttribute = 31 - BitOperations.LeadingZeroCount(attributeMask); diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index 7a82e994..eff34d54 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -1,4 +1,6 @@ +using System; using SharpGLTF.Geometry.VertexTypes; +using SharpGLTF.Memory; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Export; @@ -11,35 +13,40 @@ and there's reason to overhaul the export pipeline. public struct VertexColorFfxiv : IVertexCustom { - // NOTE: We only realistically require UNSIGNED_BYTE for this, however Blender 3.6 errors on that (fixed in 4.0). - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, true)] + public IEnumerable> GetEncodingAttributes() + { + // NOTE: We only realistically require UNSIGNED_BYTE for this, however Blender 3.6 errors on that (fixed in 4.0). + yield return new KeyValuePair("_FFXIV_COLOR", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + public Vector4 FfxivColor; - public int MaxColors => 0; + public int MaxColors + => 0; - public int MaxTextCoords => 0; + public int MaxTextCoords + => 0; private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; - public IEnumerable CustomAttributes => CustomNames; + + public IEnumerable CustomAttributes + => CustomNames; public VertexColorFfxiv(Vector4 ffxivColor) - { - FfxivColor = ffxivColor; - } + => FfxivColor = ffxivColor; public void Add(in VertexMaterialDelta delta) - { - } + { } public VertexMaterialDelta Subtract(IVertexMaterial baseValue) - => new VertexMaterialDelta(Vector4.Zero, Vector4.Zero, Vector2.Zero, Vector2.Zero); + => new(Vector4.Zero, Vector4.Zero, Vector2.Zero, Vector2.Zero); public Vector2 GetTexCoord(int index) => throw new ArgumentOutOfRangeException(nameof(index)); public void SetTexCoord(int setIndex, Vector2 coord) - { - } + { } public bool TryGetCustomAttribute(string attributeName, out object? value) { @@ -65,12 +72,17 @@ public struct VertexColorFfxiv : IVertexCustom => throw new ArgumentOutOfRangeException(nameof(index)); public void SetColor(int setIndex, Vector4 color) - { - } + { } public void Validate() { - var components = new[] { FfxivColor.X, FfxivColor.Y, FfxivColor.Z, FfxivColor.W }; + var components = new[] + { + FfxivColor.X, + FfxivColor.Y, + FfxivColor.Z, + FfxivColor.W, + }; if (components.Any(component => component < 0 || component > 1)) throw new ArgumentOutOfRangeException(nameof(FfxivColor)); } @@ -78,22 +90,32 @@ public struct VertexColorFfxiv : IVertexCustom public struct VertexTexture1ColorFfxiv : IVertexCustom { - [VertexAttribute("TEXCOORD_0")] + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("TEXCOORD_0", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("_FFXIV_COLOR", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + public Vector2 TexCoord0; - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, true)] public Vector4 FfxivColor; - public int MaxColors => 0; + public int MaxColors + => 0; - public int MaxTextCoords => 1; + public int MaxTextCoords + => 1; private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; - public IEnumerable CustomAttributes => CustomNames; + + public IEnumerable CustomAttributes + => CustomNames; public VertexTexture1ColorFfxiv(Vector2 texCoord0, Vector4 ffxivColor) { - TexCoord0 = texCoord0; + TexCoord0 = texCoord0; FfxivColor = ffxivColor; } @@ -103,9 +125,7 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom } public VertexMaterialDelta Subtract(IVertexMaterial baseValue) - { - return new VertexMaterialDelta(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), Vector2.Zero); - } + => new(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), Vector2.Zero); public Vector2 GetTexCoord(int index) => index switch @@ -116,8 +136,10 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom public void SetTexCoord(int setIndex, Vector2 coord) { - if (setIndex == 0) TexCoord0 = coord; - if (setIndex >= 1) throw new ArgumentOutOfRangeException(nameof(setIndex)); + if (setIndex == 0) + TexCoord0 = coord; + if (setIndex >= 1) + throw new ArgumentOutOfRangeException(nameof(setIndex)); } public bool TryGetCustomAttribute(string attributeName, out object? value) @@ -144,12 +166,17 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom => throw new ArgumentOutOfRangeException(nameof(index)); public void SetColor(int setIndex, Vector4 color) - { - } + { } public void Validate() { - var components = new[] { FfxivColor.X, FfxivColor.Y, FfxivColor.Z, FfxivColor.W }; + var components = new[] + { + FfxivColor.X, + FfxivColor.Y, + FfxivColor.Z, + FfxivColor.W, + }; if (components.Any(component => component < 0 || component > 1)) throw new ArgumentOutOfRangeException(nameof(FfxivColor)); } @@ -157,26 +184,35 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom public struct VertexTexture2ColorFfxiv : IVertexCustom { - [VertexAttribute("TEXCOORD_0")] + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("TEXCOORD_0", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("TEXCOORD_1", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("_FFXIV_COLOR", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + public Vector2 TexCoord0; - - [VertexAttribute("TEXCOORD_1")] public Vector2 TexCoord1; - - [VertexAttribute("_FFXIV_COLOR", EncodingType.UNSIGNED_SHORT, true)] public Vector4 FfxivColor; - public int MaxColors => 0; + public int MaxColors + => 0; - public int MaxTextCoords => 2; + public int MaxTextCoords + => 2; private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; - public IEnumerable CustomAttributes => CustomNames; + + public IEnumerable CustomAttributes + => CustomNames; public VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor) { - TexCoord0 = texCoord0; - TexCoord1 = texCoord1; + TexCoord0 = texCoord0; + TexCoord1 = texCoord1; FfxivColor = ffxivColor; } @@ -187,9 +223,7 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom } public VertexMaterialDelta Subtract(IVertexMaterial baseValue) - { - return new VertexMaterialDelta(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), TexCoord1 - baseValue.GetTexCoord(1)); - } + => new(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), TexCoord1 - baseValue.GetTexCoord(1)); public Vector2 GetTexCoord(int index) => index switch @@ -201,9 +235,12 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom public void SetTexCoord(int setIndex, Vector2 coord) { - if (setIndex == 0) TexCoord0 = coord; - if (setIndex == 1) TexCoord1 = coord; - if (setIndex >= 2) throw new ArgumentOutOfRangeException(nameof(setIndex)); + if (setIndex == 0) + TexCoord0 = coord; + if (setIndex == 1) + TexCoord1 = coord; + if (setIndex >= 2) + throw new ArgumentOutOfRangeException(nameof(setIndex)); } public bool TryGetCustomAttribute(string attributeName, out object? value) @@ -230,12 +267,17 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom => throw new ArgumentOutOfRangeException(nameof(index)); public void SetColor(int setIndex, Vector4 color) - { - } + { } public void Validate() { - var components = new[] { FfxivColor.X, FfxivColor.Y, FfxivColor.Z, FfxivColor.W }; + var components = new[] + { + FfxivColor.X, + FfxivColor.Y, + FfxivColor.Z, + FfxivColor.W, + }; if (components.Any(component => component < 0 || component > 1)) throw new ArgumentOutOfRangeException(nameof(FfxivColor)); } diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index e81bb622..df08eea3 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -61,7 +61,7 @@ public class SubMeshImporter try { - _morphNames = node.Mesh.Extras.GetNode("targetNames").Deserialize>(); + _morphNames = node.Mesh.Extras["targetNames"].Deserialize>(); } catch { diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index ba089662..fed06573 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -148,7 +148,7 @@ public partial class TexToolsImporter : IDisposable // You can in no way rely on any file paths in TTMPs so we need to just do this, sorry private static ZipArchiveEntry? FindZipEntry(ZipArchive file, string fileName) - => file.Entries.FirstOrDefault(e => !e.IsDirectory && e.Key.Contains(fileName)); + => file.Entries.FirstOrDefault(e => e is { IsDirectory: false, Key: not null } && e.Key.Contains(fileName)); private static string GetStringFromZipEntry(ZipArchiveEntry entry, Encoding encoding) { diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index dea343c6..febbe179 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -82,7 +82,7 @@ public partial class TexToolsImporter if (name.Length == 0) throw new Exception("Invalid mod archive: mod meta has no name."); - using var f = File.OpenWrite(Path.Combine(_currentModDirectory.FullName, reader.Entry.Key)); + using var f = File.OpenWrite(Path.Combine(_currentModDirectory.FullName, reader.Entry.Key!)); s.Seek(0, SeekOrigin.Begin); s.WriteTo(f); } @@ -155,13 +155,9 @@ public partial class TexToolsImporter ret = directory; // Check that all other files are also contained in the top-level directory. - if (ret.IndexOfAny(new[] - { - '/', - '\\', - }) - >= 0 - || !archive.Entries.All(e => e.Key.StartsWith(ret) && (e.Key.Length == ret.Length || e.Key[ret.Length] is '/' or '\\'))) + if (ret.IndexOfAny(['/', '\\']) >= 0 + || !archive.Entries.All(e + => e.Key != null && e.Key.StartsWith(ret) && (e.Key.Length == ret.Length || e.Key[ret.Length] is '/' or '\\'))) throw new Exception( "Invalid mod archive: meta.json in wrong location. It needs to be either at root or one directory deep, in which all other files must be nested too."); } diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 8e143e3c..f42d16ad 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -86,11 +86,11 @@ - + - - - + + + diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 9041fbd0..aa2d445e 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -242,7 +242,7 @@ public class MigrationManager(Configuration config) : IService return; } - var path = Path.Combine(directory, reader.Entry.Key); + var path = Path.Combine(directory, reader.Entry.Key!); using var s = new MemoryStream(); using var e = reader.OpenEntryStream(); e.CopyTo(s); diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 8e7106dd..fd3a0a9e 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -4,11 +4,11 @@ "net8.0-windows7.0": { "EmbedIO": { "type": "Direct", - "requested": "[3.4.3, )", - "resolved": "3.4.3", - "contentHash": "YM6hpZNAfvbbixfG9T4lWDGfF0D/TqutbTROL4ogVcHKwPF1hp+xS3ABwd3cxxTxvDFkj/zZl57QgWuFA8Igxw==", + "requested": "[3.5.2, )", + "resolved": "3.5.2", + "contentHash": "YU4j+3XvuO8/VPkNf7KWOF1TpMhnyVhXnPsG1mvnDhTJ9D5BZOFXVDvCpE/SkQ1AJ0Aa+dXOVSW3ntgmLL7aJg==", "dependencies": { - "Unosquare.Swan.Lite": "3.0.0" + "Unosquare.Swan.Lite": "3.1.0" } }, "PeNet": { @@ -23,23 +23,26 @@ }, "SharpCompress": { "type": "Direct", - "requested": "[0.33.0, )", - "resolved": "0.33.0", - "contentHash": "FlHfpTAADzaSlVCBF33iKJk9UhOr3Xj+r5LXbW2GzqYr0SrhiOf6shLX2LC2fqs7g7d+YlwKbBXqWFtb+e7icw==" + "requested": "[0.37.2, )", + "resolved": "0.37.2", + "contentHash": "cFBpTct57aubLQXkdqMmgP8GGTFRh7fnRWP53lgE/EYUpDZJ27SSvTkdjB4OYQRZ20SJFpzczUquKLbt/9xkhw==", + "dependencies": { + "ZstdSharp.Port": "0.8.0" + } }, "SharpGLTF.Core": { "type": "Direct", - "requested": "[1.0.0-alpha0030, )", - "resolved": "1.0.0-alpha0030", - "contentHash": "HVL6PcrM0H/uEk96nRZfhtPeYvSFGHnni3g1aIckot2IWVp0jLMH5KWgaWfsatEz4Yds3XcdSLUWmJZivDBUPA==" + "requested": "[1.0.1, )", + "resolved": "1.0.1", + "contentHash": "ykeV1oNHcJrEJE7s0pGAsf/nYGYY7wqF9nxCMxJUjp/WdW+UUgR1cGdbAa2lVZPkiXEwLzWenZ5wPz7yS0Gj9w==" }, "SharpGLTF.Toolkit": { "type": "Direct", - "requested": "[1.0.0-alpha0030, )", - "resolved": "1.0.0-alpha0030", - "contentHash": "nsoJWAFhXgEky9bVCY0zLeZVDx+S88u7VjvuebvMb6dJiNyFOGF6FrrMHiJe+x5pcVBxxlc3VoXliBF7r/EqYA==", + "requested": "[1.0.1, )", + "resolved": "1.0.1", + "contentHash": "LYBjHdHW5Z8R1oT1iI04si3559tWdZ3jTdHfDEu0jqhuyU8w3oJRLFUoDfVeCOI5zWXlVQPtlpjhH9XTfFFAcA==", "dependencies": { - "SharpGLTF.Runtime": "1.0.0-alpha0030" + "SharpGLTF.Runtime": "1.0.1" } }, "SixLabors.ImageSharp": { @@ -50,8 +53,8 @@ }, "JetBrains.Annotations": { "type": "Transitive", - "resolved": "2023.3.0", - "contentHash": "PHfnvdBUdGaTVG9bR/GEfxgTwWM0Z97Y6X3710wiljELBISipSfF5okn/vz+C2gfO+ihoEyVPjaJwn8ZalVukA==" + "resolved": "2024.2.0", + "contentHash": "GNnqCFW/163p1fOehKx0CnAqjmpPrUSqrgfHM6qca+P+RN39C9rhlfZHQpJhxmQG/dkOYe/b3Z0P8b6Kv5m1qw==" }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", @@ -73,10 +76,10 @@ }, "SharpGLTF.Runtime": { "type": "Transitive", - "resolved": "1.0.0-alpha0030", - "contentHash": "Ysn+fyj9EVXj6mfG0BmzSTBGNi/QvcnTrMd54dBMOlI/TsMRvnOY3JjTn0MpeH2CgHXX4qogzlDt4m+rb3n4Og==", + "resolved": "1.0.1", + "contentHash": "KsgEBKLfsEnu2IPeKaWp4Ih97+kby17IohrAB6Ev8gET18iS80nKMW/APytQWpenMmcWU06utInpANqyrwRlDg==", "dependencies": { - "SharpGLTF.Core": "1.0.0-alpha0030" + "SharpGLTF.Core": "1.0.1" } }, "System.Formats.Asn1": { @@ -99,16 +102,21 @@ }, "Unosquare.Swan.Lite": { "type": "Transitive", - "resolved": "3.0.0", - "contentHash": "noPwJJl1Q9uparXy1ogtkmyAPGNfSGb0BLT1292nFH1jdMKje6o2kvvrQUvF9Xklj+IoiAI0UzF6Aqxlvo10lw==", + "resolved": "3.1.0", + "contentHash": "X3s5QE/KMj3WAPFqFve7St+Ds10BB50u8kW8PmKIn7FVkn7yEXe9Yxr2htt1WV85DRqfFR0MN/BUNHkGHtL4OQ==", "dependencies": { "System.ValueTuple": "4.5.0" } }, + "ZstdSharp.Port": { + "type": "Transitive", + "resolved": "0.8.0", + "contentHash": "Z62eNBIu8E8YtbqlMy57tK3dV1+m2b9NhPeaYovB5exmLKvrGCqOhJTzrEUH5VyUWU6vwX3c1XHJGhW5HVs8dA==" + }, "ottergui": { "type": "Project", "dependencies": { - "JetBrains.Annotations": "[2023.3.0, )", + "JetBrains.Annotations": "[2024.2.0, )", "Microsoft.Extensions.DependencyInjection": "[8.0.0, )" } }, @@ -122,7 +130,7 @@ "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[5.2.0, )", + "Penumbra.Api": "[5.3.0, )", "Penumbra.String": "[1.0.4, )" } }, From 726340e4f8cc4a8ab22f9629e5362a800f3ae962 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 24 Aug 2024 20:45:18 +0200 Subject: [PATCH 0883/1381] Meh. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c8708ec5..c43c5cac 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c8708ec5153cb60c9e43b2c53d02b81b2c8175f9 +Subproject commit c43c5cac4cee092bf0aed8d46bab112b037ef8f2 From f3346c5d7e52f1ba86332ee2e30f77f144bf9ee3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 26 Aug 2024 18:20:29 +0200 Subject: [PATCH 0884/1381] Add Targa support. --- Penumbra/Import/Textures/Texture.cs | 15 ++++++++++++ Penumbra/Import/Textures/TextureDrawer.cs | 2 +- Penumbra/Import/Textures/TextureManager.cs | 23 +++++++++++-------- .../AdvancedWindow/ModEditWindow.Textures.cs | 1 + 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/Penumbra/Import/Textures/Texture.cs b/Penumbra/Import/Textures/Texture.cs index c5207e94..ae0aabd9 100644 --- a/Penumbra/Import/Textures/Texture.cs +++ b/Penumbra/Import/Textures/Texture.cs @@ -10,6 +10,21 @@ public enum TextureType Tex, Png, Bitmap, + Targa, +} + +internal static class TextureTypeExtensions +{ + public static TextureType ReduceToBehaviour(this TextureType type) + => type switch + { + TextureType.Dds => TextureType.Dds, + TextureType.Tex => TextureType.Tex, + TextureType.Png => TextureType.Png, + TextureType.Bitmap => TextureType.Png, + TextureType.Targa => TextureType.Png, + _ => TextureType.Unknown, + }; } public sealed class Texture : IDisposable diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index c83604e4..b0a65ac0 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -66,7 +66,7 @@ public static class TextureDrawer current.Load(textures, paths[0]); } - fileDialog.OpenFilePicker("Open Image...", "Textures{.png,.dds,.tex}", UpdatePath, 1, startPath, false); + fileDialog.OpenFilePicker("Open Image...", "Textures{.png,.dds,.tex,.tga}", UpdatePath, 1, startPath, false); } ImGui.SameLine(); diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index cc785d02..4afc8a56 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -165,11 +165,13 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur return; } + var imageTypeBehaviour = image.Type.ReduceToBehaviour(); var dds = _type switch { - CombinedTexture.TextureSaveType.AsIs when image.Type is TextureType.Png => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, + CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Png => ConvertToRgbaDds(image, _mipMaps, + cancel, rgba, width, height), - CombinedTexture.TextureSaveType.AsIs when image.Type is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), + CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), CombinedTexture.TextureSaveType.BC7 => ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), @@ -218,7 +220,9 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur => Path.GetExtension(path).ToLowerInvariant() switch { ".dds" => (LoadDds(path), TextureType.Dds), - ".png" => (LoadPng(path), TextureType.Png), + ".png" => (LoadImageSharp(path), TextureType.Png), + ".tga" => (LoadImageSharp(path), TextureType.Targa), + ".bmp" => (LoadImageSharp(path), TextureType.Bitmap), ".tex" => (LoadTex(path), TextureType.Tex), _ => throw new Exception($"Extension {Path.GetExtension(path)} unknown."), }; @@ -234,17 +238,17 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public BaseImage LoadDds(string path) => ScratchImage.LoadDDS(path); - /// Load a .png file from drive using ImageSharp. - public BaseImage LoadPng(string path) + /// Load a supported file type from drive using ImageSharp. + public BaseImage LoadImageSharp(string path) { using var stream = File.OpenRead(path); return Image.Load(stream); } - /// Convert an existing image to .png. Does not create a deep copy of an existing .png and just returns the existing one. + /// Convert an existing image to ImageSharp. Does not create a deep copy of an existing ImageSharp file and just returns the existing one. public static BaseImage ConvertToPng(BaseImage input, CancellationToken cancel, byte[]? rgba = null, int width = 0, int height = 0) { - switch (input.Type) + switch (input.Type.ReduceToBehaviour()) { case TextureType.Png: return input; case TextureType.Dds: @@ -261,7 +265,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public static BaseImage ConvertToRgbaDds(BaseImage input, bool mipMaps, CancellationToken cancel, byte[]? rgba = null, int width = 0, int height = 0) { - switch (input.Type) + switch (input.Type.ReduceToBehaviour()) { case TextureType.Png: { @@ -291,7 +295,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public static BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, CancellationToken cancel, byte[]? rgba = null, int width = 0, int height = 0) { - switch (input.Type) + switch (input.Type.ReduceToBehaviour()) { case TextureType.Png: { @@ -470,6 +474,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur TextureType.Dds => $"Custom {_width} x {_height} {_image.Format} Image", TextureType.Tex => $"Custom {_width} x {_height} {_image.Format} Image", TextureType.Png => $"Custom {_width} x {_height} .png Image", + TextureType.Targa => $"Custom {_width} x {_height} .tga Image", TextureType.Bitmap => $"Custom {_width} x {_height} RGBA Image", _ => "Unknown Image", }; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 652ecb49..67a27a0b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -329,5 +329,6 @@ public partial class ModEditWindow ".png", ".dds", ".tex", + ".tga", }; } From c4853434c8842ee8fa390e5b716134eca407dbfd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 26 Aug 2024 18:25:43 +0200 Subject: [PATCH 0885/1381] Whatever. --- Penumbra/Import/Textures/TextureManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 4afc8a56..996b5dbf 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -474,7 +474,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur TextureType.Dds => $"Custom {_width} x {_height} {_image.Format} Image", TextureType.Tex => $"Custom {_width} x {_height} {_image.Format} Image", TextureType.Png => $"Custom {_width} x {_height} .png Image", - TextureType.Targa => $"Custom {_width} x {_height} .tga Image", + TextureType.Targa => $"Custom {_width} x {_height} .tga Image", TextureType.Bitmap => $"Custom {_width} x {_height} RGBA Image", _ => "Unknown Image", }; From ded910d8a128b7ffb9cc9483c201df847a2b9e4c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 26 Aug 2024 21:21:38 +0200 Subject: [PATCH 0886/1381] Add Targa export. --- Penumbra.Api | 2 +- Penumbra/Api/Api/EditingApi.cs | 2 + Penumbra/Import/Textures/CombinedTexture.cs | 12 ++++ Penumbra/Import/Textures/TextureManager.cs | 56 ++++++++++++++----- .../AdvancedWindow/ModEditWindow.Textures.cs | 17 +++--- 5 files changed, 67 insertions(+), 22 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 552246e5..a38e9bcf 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 552246e595ffab2aaba2c75f578d564f8938fc9a +Subproject commit a38e9bcfb80c456102945bbb4c59f5621cae0442 diff --git a/Penumbra/Api/Api/EditingApi.cs b/Penumbra/Api/Api/EditingApi.cs index 93345053..e50b7a1b 100644 --- a/Penumbra/Api/Api/EditingApi.cs +++ b/Penumbra/Api/Api/EditingApi.cs @@ -10,6 +10,7 @@ public class EditingApi(TextureManager textureManager) : IPenumbraApiEditing, IA => textureType switch { TextureType.Png => textureManager.SavePng(inputFile, outputFile), + TextureType.Targa => textureManager.SaveTga(inputFile, outputFile), TextureType.AsIsTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, inputFile, outputFile), TextureType.AsIsDds => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, inputFile, outputFile), TextureType.RgbaTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, inputFile, outputFile), @@ -26,6 +27,7 @@ public class EditingApi(TextureManager textureManager) : IPenumbraApiEditing, IA => textureType switch { TextureType.Png => textureManager.SavePng(new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Targa => textureManager.SaveTga(new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), TextureType.AsIsTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), TextureType.AsIsDds => textureManager.SaveAs(CombinedTexture.TextureSaveType.AsIs, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), TextureType.RgbaTex => textureManager.SaveAs(CombinedTexture.TextureSaveType.Bitmap, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index 98b87ac3..c1a22088 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -55,6 +55,14 @@ public partial class CombinedTexture : IDisposable SaveTask = textures.SavePng(_current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, _current.TextureWrap!.Height); } + public void SaveAsTarga(TextureManager textures, string path) + { + if (!IsLoaded || _current == null) + return; + + SaveTask = textures.SaveTga(_current.BaseImage, path, _current.RgbaPixels, _current.TextureWrap!.Width, _current.TextureWrap!.Height); + } + private void SaveAs(TextureManager textures, string path, TextureSaveType type, bool mipMaps, bool writeTex) { if (!IsLoaded || _current == null) @@ -72,6 +80,7 @@ public partial class CombinedTexture : IDisposable ".tex" => TextureType.Tex, ".dds" => TextureType.Dds, ".png" => TextureType.Png, + ".tga" => TextureType.Targa, _ => TextureType.Unknown, }; @@ -85,6 +94,9 @@ public partial class CombinedTexture : IDisposable break; case TextureType.Png: SaveAsPng(textures, path); + break; + case TextureType.Targa: + SaveAsTarga(textures, path); break; default: throw new ArgumentException( diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 996b5dbf..7118f8af 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -8,6 +8,7 @@ using OtterGui.Tasks; using OtterTex; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.Formats.Tga; using SixLabors.ImageSharp.PixelFormats; using Image = SixLabors.ImageSharp.Image; @@ -33,10 +34,17 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } public Task SavePng(string input, string output) - => Enqueue(new SavePngAction(this, input, output)); + => Enqueue(new SaveImageSharpAction(this, input, output, TextureType.Png)); public Task SavePng(BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) - => Enqueue(new SavePngAction(this, image, path, rgba, width, height)); + => Enqueue(new SaveImageSharpAction(this, image, path, TextureType.Png, rgba, width, height)); + + public Task SaveTga(string input, string output) + => Enqueue(new SaveImageSharpAction(this, input, output, TextureType.Targa)); + + public Task SaveTga(BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) + => Enqueue(new SaveImageSharpAction(this, image, path, TextureType.Targa, rgba, width, height)); + public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, string output) => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, input, output)); @@ -66,44 +74,65 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur return t; } - private class SavePngAction : IAction + private class SaveImageSharpAction : IAction { private readonly TextureManager _textures; private readonly string _outputPath; private readonly ImageInputData _input; + private readonly TextureType _type; - public SavePngAction(TextureManager textures, string input, string output) + public SaveImageSharpAction(TextureManager textures, string input, string output, TextureType type) { _textures = textures; _input = new ImageInputData(input); _outputPath = output; + _type = type; + if (_type.ReduceToBehaviour() is not TextureType.Png) + throw new ArgumentOutOfRangeException(nameof(type), type, $"Can not save as {type} with ImageSharp."); } - public SavePngAction(TextureManager textures, BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) + public SaveImageSharpAction(TextureManager textures, BaseImage image, string path, TextureType type, byte[]? rgba = null, int width = 0, + int height = 0) { _textures = textures; _input = new ImageInputData(image, rgba, width, height); _outputPath = path; + _type = type; + if (_type.ReduceToBehaviour() is not TextureType.Png) + throw new ArgumentOutOfRangeException(nameof(type), type, $"Can not save as {type} with ImageSharp."); } public void Execute(CancellationToken cancel) { - _textures._logger.Information($"[{nameof(TextureManager)}] Saving {_input} as .png to {_outputPath}..."); + _textures._logger.Information($"[{nameof(TextureManager)}] Saving {_input} as {_type} to {_outputPath}..."); var (image, rgba, width, height) = _input.GetData(_textures); cancel.ThrowIfCancellationRequested(); - Image? png = null; + Image? data = null; if (image.Type is TextureType.Unknown) { if (rgba != null && width > 0 && height > 0) - png = ConvertToPng(rgba, width, height).AsPng!; + data = ConvertToPng(rgba, width, height).AsPng!; } else { - png = ConvertToPng(image, cancel, rgba).AsPng!; + data = ConvertToPng(image, cancel, rgba).AsPng!; } cancel.ThrowIfCancellationRequested(); - png?.SaveAsync(_outputPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.NoCompression }, cancel).Wait(cancel); + switch (_type) + { + case TextureType.Png: + data?.SaveAsync(_outputPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.NoCompression }, cancel) + .Wait(cancel); + return; + case TextureType.Targa: + data?.SaveAsync(_outputPath, new TgaEncoder() + { + Compression = TgaCompression.None, + BitsPerPixel = TgaBitsPerPixel.Pixel32, + }, cancel).Wait(cancel); + return; + } } public override string ToString() @@ -111,7 +140,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public bool Equals(IAction? other) { - if (other is not SavePngAction rhs) + if (other is not SaveImageSharpAction rhs) return false; return string.Equals(_outputPath, rhs._outputPath, StringComparison.OrdinalIgnoreCase) && _input.Equals(rhs._input); @@ -168,9 +197,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur var imageTypeBehaviour = image.Type.ReduceToBehaviour(); var dds = _type switch { - CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Png => ConvertToRgbaDds(image, _mipMaps, - cancel, rgba, - width, height), + CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Png => ConvertToRgbaDds(image, _mipMaps, cancel, + rgba, width, height), CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 67a27a0b..c08e8a8e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -85,7 +85,7 @@ public partial class ModEditWindow ImGuiUtil.SelectableHelpMarker(newDesc); } - } + } private void RedrawOnSaveBox() { @@ -128,7 +128,8 @@ public partial class ModEditWindow ? "This saves the texture in place. This is not revertible." : $"This saves the texture in place. This is not revertible. Hold {_config.DeleteModModifier} to save."; - var buttonSize2 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); + var buttonSize2 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); + var buttonSize3 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X * 2) / 3, 0); if (ImGuiUtil.DrawDisabledButton("Save in place", buttonSize2, tt, !isActive || !canSaveInPlace || _center.IsLeftCopy && _currentSaveAs == (int)CombinedTexture.TextureSaveType.AsIs)) { @@ -141,17 +142,18 @@ public partial class ModEditWindow if (ImGui.Button("Save as TEX", buttonSize2)) OpenSaveAsDialog(".tex"); - if (ImGui.Button("Export as PNG", buttonSize2)) + if (ImGui.Button("Export as TGA", buttonSize3)) + OpenSaveAsDialog(".tga"); + ImGui.SameLine(); + if (ImGui.Button("Export as PNG", buttonSize3)) OpenSaveAsDialog(".png"); ImGui.SameLine(); - if (ImGui.Button("Export as DDS", buttonSize2)) + if (ImGui.Button("Export as DDS", buttonSize3)) OpenSaveAsDialog(".dds"); - ImGui.NewLine(); var canConvertInPlace = canSaveInPlace && _left.Type is TextureType.Tex && _center.IsLeftCopy; - var buttonSize3 = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X * 2) / 3, 0); if (ImGuiUtil.DrawDisabledButton("Convert to BC7", buttonSize3, "This converts the texture to BC7 format in place. This is not revertible.", !canConvertInPlace || _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) @@ -226,7 +228,8 @@ public partial class ModEditWindow private void OpenSaveAsDialog(string defaultExtension) { var fileName = Path.GetFileNameWithoutExtension(_left.Path.Length > 0 ? _left.Path : _right.Path); - _fileDialog.OpenSavePicker("Save Texture as TEX, DDS or PNG...", "Textures{.png,.dds,.tex},.tex,.dds,.png", fileName, defaultExtension, + _fileDialog.OpenSavePicker("Save Texture as TEX, DDS, PNG or TGA...", "Textures{.png,.dds,.tex,.tga},.tex,.dds,.png,.tga", fileName, + defaultExtension, (a, b) => { if (a) From 3e2c9177a71ecd9a64493b02359b7ba16188c651 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 15:48:02 +0200 Subject: [PATCH 0887/1381] Prepare API for new meta format. --- Penumbra/Api/Api/MetaApi.cs | 258 ++++++++++++++++++++++++++++++- Penumbra/Api/Api/TemporaryApi.cs | 26 +--- 2 files changed, 257 insertions(+), 27 deletions(-) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index ce1a9def..6f3ed51e 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -1,16 +1,21 @@ +using Dalamud.Plugin.Services; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Services; using Penumbra.Collections; +using Penumbra.Collections.Cache; +using Penumbra.GameData.Files.Utility; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; using Penumbra.Meta.Manipulations; namespace Penumbra.Api.Api; -public class MetaApi(CollectionResolver collectionResolver, ApiHelpers helpers) : IPenumbraApiMeta, IApiService +public class MetaApi(IFramework framework, CollectionResolver collectionResolver, ApiHelpers helpers) + : IPenumbraApiMeta, IApiService { - public const int CurrentVersion = 0; + public const int CurrentVersion = 1; public string GetPlayerMetaManipulations() { @@ -24,7 +29,32 @@ public class MetaApi(CollectionResolver collectionResolver, ApiHelpers helpers) return CompressMetaManipulations(collection); } + public Task GetPlayerMetaManipulationsAsync() + { + return Task.Run(async () => + { + var playerCollection = await framework.RunOnFrameworkThread(collectionResolver.PlayerCollection).ConfigureAwait(false); + return CompressMetaManipulations(playerCollection); + }); + } + + public Task GetMetaManipulationsAsync(int gameObjectIdx) + { + return Task.Run(async () => + { + var playerCollection = await framework.RunOnFrameworkThread(() => + { + helpers.AssociatedCollection(gameObjectIdx, out var collection); + return collection; + }).ConfigureAwait(false); + return CompressMetaManipulations(playerCollection); + }); + } + internal static string CompressMetaManipulations(ModCollection collection) + => CompressMetaManipulationsV0(collection); + + private static string CompressMetaManipulationsV0(ModCollection collection) { var array = new JArray(); if (collection.MetaCache is { } cache) @@ -38,6 +68,228 @@ public class MetaApi(CollectionResolver collectionResolver, ApiHelpers helpers) MetaDictionary.SerializeTo(array, cache.Gmp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); } - return Functions.ToCompressedBase64(array, CurrentVersion); + return Functions.ToCompressedBase64(array, 0); + } + + private static unsafe string CompressMetaManipulationsV1(ModCollection? collection) + { + using var ms = new MemoryStream(); + ms.Capacity = 1024; + using (var zipStream = new GZipStream(ms, CompressionMode.Compress, true)) + { + zipStream.Write((byte)1); + zipStream.Write("META0001"u8); + if (collection?.MetaCache is not { } cache) + { + zipStream.Write(0); + zipStream.Write(0); + zipStream.Write(0); + zipStream.Write(0); + zipStream.Write(0); + zipStream.Write(0); + zipStream.Write(0); + } + else + { + WriteCache(zipStream, cache.Imc); + WriteCache(zipStream, cache.Eqp); + WriteCache(zipStream, cache.Eqdp); + WriteCache(zipStream, cache.Est); + WriteCache(zipStream, cache.Rsp); + WriteCache(zipStream, cache.Gmp); + cache.GlobalEqp.EnterReadLock(); + + try + { + zipStream.Write(cache.GlobalEqp.Count); + foreach (var (globalEqp, _) in cache.GlobalEqp) + zipStream.Write(new ReadOnlySpan(&globalEqp, sizeof(GlobalEqpManipulation))); + } + finally + { + cache.GlobalEqp.ExitReadLock(); + } + } + } + + ms.Flush(); + ms.Position = 0; + var data = ms.GetBuffer().AsSpan(0, (int)ms.Length); + return Convert.ToBase64String(data); + + void WriteCache(Stream stream, MetaCacheBase metaCache) + where TKey : unmanaged, IMetaIdentifier + where TValue : unmanaged + { + metaCache.EnterReadLock(); + try + { + stream.Write(metaCache.Count); + foreach (var (identifier, (_, value)) in metaCache) + { + stream.Write(identifier); + stream.Write(value); + } + } + finally + { + metaCache.ExitReadLock(); + } + } + } + + /// + /// Convert manipulations from a transmitted base64 string to actual manipulations. + /// The empty string is treated as an empty set. + /// Only returns true if all conversions are successful and distinct. + /// + internal static bool ConvertManips(string manipString, [NotNullWhen(true)] out MetaDictionary? manips) + { + if (manipString.Length == 0) + { + manips = new MetaDictionary(); + return true; + } + + try + { + var bytes = Convert.FromBase64String(manipString); + using var compressedStream = new MemoryStream(bytes); + using var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress); + using var resultStream = new MemoryStream(); + zipStream.CopyTo(resultStream); + resultStream.Flush(); + resultStream.Position = 0; + var data = resultStream.GetBuffer().AsSpan(0, (int)resultStream.Length); + var version = data[0]; + data = data[1..]; + switch (version) + { + case 0: return ConvertManipsV0(data, out manips); + case 1: return ConvertManipsV1(data, out manips); + default: + Penumbra.Log.Debug($"Invalid version for manipulations: {version}."); + manips = null; + return false; + } + } + catch (Exception ex) + { + Penumbra.Log.Debug($"Error decompressing manipulations:\n{ex}"); + manips = null; + return false; + } + } + + private static bool ConvertManipsV1(ReadOnlySpan data, [NotNullWhen(true)] out MetaDictionary? manips) + { + if (!data.StartsWith("META0001"u8)) + { + Penumbra.Log.Debug($"Invalid manipulations of version 1, does not start with valid prefix."); + manips = null; + return false; + } + + manips = new MetaDictionary(); + var r = new SpanBinaryReader(data[8..]); + var imcCount = r.ReadInt32(); + for (var i = 0; i < imcCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var eqpCount = r.ReadInt32(); + for (var i = 0; i < eqpCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var eqdpCount = r.ReadInt32(); + for (var i = 0; i < eqdpCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var estCount = r.ReadInt32(); + for (var i = 0; i < estCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var rspCount = r.ReadInt32(); + for (var i = 0; i < rspCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var gmpCount = r.ReadInt32(); + for (var i = 0; i < gmpCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var globalEqpCount = r.ReadInt32(); + for (var i = 0; i < globalEqpCount; ++i) + { + var manip = r.Read(); + if (!manip.Validate() || !manips.TryAdd(manip)) + return false; + } + + return true; + } + + private static bool ConvertManipsV0(ReadOnlySpan data, [NotNullWhen(true)] out MetaDictionary? manips) + { + var json = Encoding.UTF8.GetString(data); + manips = JsonConvert.DeserializeObject(json); + return manips != null; + } + + internal void TestMetaManipulations() + { + var collection = collectionResolver.PlayerCollection(); + var dict = new MetaDictionary(collection.MetaCache); + var count = dict.Count; + + var watch = Stopwatch.StartNew(); + var v0 = CompressMetaManipulationsV0(collection); + var v0Time = watch.ElapsedMilliseconds; + + watch.Restart(); + var v1 = CompressMetaManipulationsV1(collection); + var v1Time = watch.ElapsedMilliseconds; + + watch.Restart(); + var v1Success = ConvertManips(v1, out var v1Roundtrip); + var v1RoundtripTime = watch.ElapsedMilliseconds; + + watch.Restart(); + var v0Success = ConvertManips(v0, out var v0Roundtrip); + var v0RoundtripTime = watch.ElapsedMilliseconds; + + Penumbra.Log.Information($"Version | Count | Time | Length | Success | ReCount | ReTime | Equal"); + Penumbra.Log.Information( + $"0 | {count} | {v0Time} | {v0.Length} | {v0Success} | {v0Roundtrip?.Count} | {v0RoundtripTime} | {v0Roundtrip?.Equals(dict)}"); + Penumbra.Log.Information( + $"1 | {count} | {v1Time} | {v1.Length} | {v1Success} | {v1Roundtrip?.Count} | {v1RoundtripTime} | {v0Roundtrip?.Equals(dict)}"); } } diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index f02b0d94..516b4347 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -1,10 +1,8 @@ -using OtterGui; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.Interop; -using Penumbra.Meta.Manipulations; using Penumbra.Mods.Settings; using Penumbra.String.Classes; @@ -62,7 +60,7 @@ public class TemporaryApi( if (!ConvertPaths(paths, out var p)) return ApiHelpers.Return(PenumbraApiEc.InvalidGamePath, args); - if (!ConvertManips(manipString, out var m)) + if (!MetaApi.ConvertManips(manipString, out var m)) return ApiHelpers.Return(PenumbraApiEc.InvalidManipulation, args); var ret = tempMods.Register(tag, null, p, m, new ModPriority(priority)) switch @@ -88,7 +86,7 @@ public class TemporaryApi( if (!ConvertPaths(paths, out var p)) return ApiHelpers.Return(PenumbraApiEc.InvalidGamePath, args); - if (!ConvertManips(manipString, out var m)) + if (!MetaApi.ConvertManips(manipString, out var m)) return ApiHelpers.Return(PenumbraApiEc.InvalidManipulation, args); var ret = tempMods.Register(tag, collection, p, m, new ModPriority(priority)) switch @@ -153,24 +151,4 @@ public class TemporaryApi( return true; } - - /// - /// Convert manipulations from a transmitted base64 string to actual manipulations. - /// The empty string is treated as an empty set. - /// Only returns true if all conversions are successful and distinct. - /// - private static bool ConvertManips(string manipString, [NotNullWhen(true)] out MetaDictionary? manips) - { - if (manipString.Length == 0) - { - manips = new MetaDictionary(); - return true; - } - - if (Functions.FromCompressedBase64(manipString, out manips!) == MetaApi.CurrentVersion) - return true; - - manips = null; - return false; - } } From 233a9996507521c6a184743cc2b0314d73ac427b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 15:48:42 +0200 Subject: [PATCH 0888/1381] Add button to remove default-valued meta entries. --- Penumbra/Mods/Editor/ModMetaEditor.cs | 64 ++++++++++++++++++- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 15 +++-- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index bacf4122..d9018ff6 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,12 +1,15 @@ using System.Collections.Frozen; using OtterGui.Services; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Editor; -public class ModMetaEditor(ModManager modManager) : MetaDictionary, IService +public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManager, ImcChecker imcChecker) : MetaDictionary, IService { public sealed class OtherOptionData : HashSet { @@ -62,6 +65,65 @@ public class ModMetaEditor(ModManager modManager) : MetaDictionary, IService Changes = false; } + public void DeleteDefaultValues() + { + var clone = Clone(); + Clear(); + foreach (var (key, value) in clone.Imc) + { + var defaultEntry = imcChecker.GetDefaultEntry(key, false); + if (!defaultEntry.Entry.Equals(value)) + TryAdd(key, value); + else + Changes = true; + } + + foreach (var (key, value) in clone.Eqp) + { + var defaultEntry = new EqpEntryInternal(ExpandedEqpFile.GetDefault(metaFileManager, key.SetId), key.Slot); + if (!defaultEntry.Equals(value)) + TryAdd(key, value); + else + Changes = true; + } + + foreach (var (key, value) in clone.Eqdp) + { + var defaultEntry = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(metaFileManager, key), key.Slot); + if (!defaultEntry.Equals(value)) + TryAdd(key, value); + else + Changes = true; + } + + foreach (var (key, value) in clone.Est) + { + var defaultEntry = EstFile.GetDefault(metaFileManager, key); + if (!defaultEntry.Equals(value)) + TryAdd(key, value); + else + Changes = true; + } + + foreach (var (key, value) in clone.Gmp) + { + var defaultEntry = ExpandedGmpFile.GetDefault(metaFileManager, key); + if (!defaultEntry.Equals(value)) + TryAdd(key, value); + else + Changes = true; + } + + foreach (var (key, value) in clone.Rsp) + { + var defaultEntry = CmpFile.GetDefault(metaFileManager, key.SubRace, key.Attribute); + if (!defaultEntry.Equals(value)) + TryAdd(key, value); + else + Changes = true; + } + } + public void Apply(IModDataContainer container) { if (!Changes) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 3ec6a4d5..49eac96e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -16,21 +16,21 @@ public partial class ModEditWindow private void DrawMetaTab() { - using var tab = ImRaii.TabItem("Meta Manipulations"); + using var tab = ImUtf8.TabItem("Meta Manipulations"u8); if (!tab) return; DrawOptionSelectHeader(); var setsEqual = !_editor.MetaEditor.Changes; - var tt = setsEqual ? "No changes staged." : "Apply the currently staged changes to the option."; + var tt = setsEqual ? "No changes staged."u8 : "Apply the currently staged changes to the option."u8; ImGui.NewLine(); - if (ImGuiUtil.DrawDisabledButton("Apply Changes", Vector2.Zero, tt, setsEqual)) + if (ImUtf8.ButtonEx("Apply Changes"u8, tt, Vector2.Zero, setsEqual)) _editor.MetaEditor.Apply(_editor.Option!); ImGui.SameLine(); - tt = setsEqual ? "No changes staged." : "Revert all currently staged changes."; - if (ImGuiUtil.DrawDisabledButton("Revert Changes", Vector2.Zero, tt, setsEqual)) + tt = setsEqual ? "No changes staged."u8 : "Revert all currently staged changes."u8; + if (ImUtf8.ButtonEx("Revert Changes"u8, tt, Vector2.Zero, setsEqual)) _editor.MetaEditor.Load(_editor.Mod!, _editor.Option!); ImGui.SameLine(); @@ -40,8 +40,11 @@ public partial class ModEditWindow ImGui.SameLine(); CopyToClipboardButton("Copy all current manipulations to clipboard.", _iconSize, _editor.MetaEditor); ImGui.SameLine(); - if (ImGui.Button("Write as TexTools Files")) + if (ImUtf8.Button("Write as TexTools Files"u8)) _metaFileManager.WriteAllTexToolsMeta(Mod!); + ImGui.SameLine(); + if (ImUtf8.ButtonEx("Remove All Default-Values", "Delete any entries from all lists that set the value to its default value."u8)) + _editor.MetaEditor.DeleteDefaultValues(); using var child = ImRaii.Child("##meta", -Vector2.One, true); if (!child) From a3c22f2826b4091010e6f76ad5a236e1c92b44fb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 15:49:07 +0200 Subject: [PATCH 0889/1381] Fix ordering of meta entries. --- Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 6 +++--- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index f586045c..aea2ef78 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -61,7 +61,7 @@ public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFil } protected override IEnumerable<(EqdpIdentifier, EqdpEntryInternal)> Enumerate() - => Editor.Eqdp.OrderBy(kvp => kvp.Key.SetId) + => Editor.Eqdp.OrderBy(kvp => kvp.Key.SetId.Id) .ThenBy(kvp => kvp.Key.GenderRace) .ThenBy(kvp => kvp.Key.Slot) .Select(kvp => (kvp.Key, kvp.Value)); diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs index b1031b44..733517f3 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs @@ -60,7 +60,7 @@ public sealed class EqpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override IEnumerable<(EqpIdentifier, EqpEntryInternal)> Enumerate() => Editor.Eqp - .OrderBy(kvp => kvp.Key.SetId) + .OrderBy(kvp => kvp.Key.SetId.Id) .ThenBy(kvp => kvp.Key.Slot) .Select(kvp => (kvp.Key, kvp.Value)); diff --git a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs index 628cee40..a33f8b7b 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs @@ -59,7 +59,7 @@ public sealed class EstMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override IEnumerable<(EstIdentifier, EstEntry)> Enumerate() => Editor.Est - .OrderBy(kvp => kvp.Key.SetId) + .OrderBy(kvp => kvp.Key.SetId.Id) .ThenBy(kvp => kvp.Key.GenderRace) .ThenBy(kvp => kvp.Key.Slot) .Select(kvp => (kvp.Key, kvp.Value)); diff --git a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs index bc2e1bde..5d67ddcf 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs @@ -49,7 +49,7 @@ public sealed class GlobalEqpMetaDrawer(ModMetaEditor editor, MetaFileManager me protected override IEnumerable<(GlobalEqpManipulation, byte)> Enumerate() => Editor.GlobalEqp .OrderBy(identifier => identifier.Type) - .ThenBy(identifier => identifier.Condition) + .ThenBy(identifier => identifier.Condition.Id) .Select(identifier => (identifier, (byte)0)); private static void DrawIdentifierInput(ref GlobalEqpManipulation identifier) diff --git a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs index 1e91731d..bd42b60a 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs @@ -58,7 +58,7 @@ public sealed class GmpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override IEnumerable<(GmpIdentifier, GmpEntry)> Enumerate() => Editor.Gmp - .OrderBy(kvp => kvp.Key.SetId) + .OrderBy(kvp => kvp.Key.SetId.Id) .Select(kvp => (kvp.Key, kvp.Value)); private static bool DrawIdentifierInput(ref GmpIdentifier identifier) diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index e33eb1aa..4e949b98 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -142,11 +142,11 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override IEnumerable<(ImcIdentifier, ImcEntry)> Enumerate() => Editor.Imc .OrderBy(kvp => kvp.Key.ObjectType) - .ThenBy(kvp => kvp.Key.PrimaryId) + .ThenBy(kvp => kvp.Key.PrimaryId.Id) .ThenBy(kvp => kvp.Key.EquipSlot) .ThenBy(kvp => kvp.Key.BodySlot) - .ThenBy(kvp => kvp.Key.SecondaryId) - .ThenBy(kvp => kvp.Key.Variant) + .ThenBy(kvp => kvp.Key.SecondaryId.Id) + .ThenBy(kvp => kvp.Key.Variant.Id) .Select(kvp => (kvp.Key, kvp.Value)); public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) From d713d5a112d138d43fc6d4470711cd8d1c711631 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 18:28:49 +0200 Subject: [PATCH 0890/1381] Improve handling of mod selection. --- Penumbra/Communication/CollectionChange.cs | 3 + .../CollectionInheritanceChanged.cs | 3 + Penumbra/Communication/ModSettingChanged.cs | 4 +- Penumbra/Mods/Editor/ModMerger.cs | 39 ++++--- Penumbra/Mods/ModSelection.cs | 104 ++++++++++++++++++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 7 +- Penumbra/UI/Classes/CollectionSelectHeader.cs | 18 +-- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 82 ++++---------- Penumbra/UI/ModsTab/ModPanel.cs | 35 +++--- Penumbra/UI/ModsTab/ModPanelHeader.cs | 34 ++++-- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 43 ++++---- Penumbra/UI/Tabs/ModsTab.cs | 3 +- 12 files changed, 227 insertions(+), 148 deletions(-) create mode 100644 Penumbra/Mods/ModSelection.cs diff --git a/Penumbra/Communication/CollectionChange.cs b/Penumbra/Communication/CollectionChange.cs index 95d4ac4d..2788177d 100644 --- a/Penumbra/Communication/CollectionChange.cs +++ b/Penumbra/Communication/CollectionChange.cs @@ -46,5 +46,8 @@ public sealed class CollectionChange() /// ModFileSystemSelector = 0, + + /// + ModSelection = 10, } } diff --git a/Penumbra/Communication/CollectionInheritanceChanged.cs b/Penumbra/Communication/CollectionInheritanceChanged.cs index dbcf9e4a..30af2b20 100644 --- a/Penumbra/Communication/CollectionInheritanceChanged.cs +++ b/Penumbra/Communication/CollectionInheritanceChanged.cs @@ -23,5 +23,8 @@ public sealed class CollectionInheritanceChanged() /// ModFileSystemSelector = 0, + + /// + ModSelection = 10, } } diff --git a/Penumbra/Communication/ModSettingChanged.cs b/Penumbra/Communication/ModSettingChanged.cs index 7fda2f35..d4bf00be 100644 --- a/Penumbra/Communication/ModSettingChanged.cs +++ b/Penumbra/Communication/ModSettingChanged.cs @@ -1,5 +1,4 @@ using OtterGui.Classes; -using Penumbra.Api; using Penumbra.Api.Api; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -35,5 +34,8 @@ public sealed class ModSettingChanged() /// ModFileSystemSelector = 0, + + /// + ModSelection = 10, } } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index b059813b..d75ac671 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -10,22 +10,21 @@ using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; using Penumbra.Services; using Penumbra.String.Classes; -using Penumbra.UI.ModsTab; namespace Penumbra.Mods.Editor; public class ModMerger : IDisposable, IService { - private readonly Configuration _config; - private readonly CommunicatorService _communicator; - private readonly ModGroupEditor _editor; - private readonly ModFileSystemSelector _selector; - private readonly DuplicateManager _duplicates; - private readonly ModManager _mods; - private readonly ModCreator _creator; + private readonly Configuration _config; + private readonly CommunicatorService _communicator; + private readonly ModGroupEditor _editor; + private readonly ModSelection _selection; + private readonly DuplicateManager _duplicates; + private readonly ModManager _mods; + private readonly ModCreator _creator; public Mod? MergeFromMod - => _selector.Selected; + => _selection.Mod; public Mod? MergeToMod; public string OptionGroupName = "Merges"; @@ -41,23 +40,23 @@ public class ModMerger : IDisposable, IService public readonly IReadOnlyList Warnings = new List(); public Exception? Error { get; private set; } - public ModMerger(ModManager mods, ModGroupEditor editor, ModFileSystemSelector selector, DuplicateManager duplicates, + public ModMerger(ModManager mods, ModGroupEditor editor, ModSelection selection, DuplicateManager duplicates, CommunicatorService communicator, ModCreator creator, Configuration config) { - _editor = editor; - _selector = selector; - _duplicates = duplicates; - _communicator = communicator; - _creator = creator; - _config = config; - _mods = mods; - _selector.SelectionChanged += OnSelectionChange; + _editor = editor; + _selection = selection; + _duplicates = duplicates; + _communicator = communicator; + _creator = creator; + _config = config; + _mods = mods; + _selection.Subscribe(OnSelectionChange, ModSelection.Priority.ModMerger); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModMerger); } public void Dispose() { - _selector.SelectionChanged -= OnSelectionChange; + _selection.Unsubscribe(OnSelectionChange); _communicator.ModPathChanged.Unsubscribe(OnModPathChange); } @@ -390,7 +389,7 @@ public class ModMerger : IDisposable, IService } } - private void OnSelectionChange(Mod? oldSelection, Mod? newSelection, in ModFileSystemSelector.ModState state) + private void OnSelectionChange(Mod? oldSelection, Mod? newSelection) { if (OptionGroupName == "Merges" && OptionName.Length == 0 || OptionName == oldSelection?.Name.Text) OptionName = newSelection?.Name.Text ?? string.Empty; diff --git a/Penumbra/Mods/ModSelection.cs b/Penumbra/Mods/ModSelection.cs new file mode 100644 index 00000000..73d0272b --- /dev/null +++ b/Penumbra/Mods/ModSelection.cs @@ -0,0 +1,104 @@ +using OtterGui.Classes; +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.Communication; +using Penumbra.Mods.Manager; +using Penumbra.Mods.Settings; +using Penumbra.Services; + +namespace Penumbra.Mods; + +/// +/// Triggered whenever the selected mod changes +/// +/// Parameter is the old selected mod. +/// Parameter is the new selected mod +/// +/// +public class ModSelection : EventWrapper +{ + private readonly ActiveCollections _collections; + private readonly EphemeralConfig _config; + private readonly CommunicatorService _communicator; + + public ModSelection(CommunicatorService communicator, ModManager mods, ActiveCollections collections, EphemeralConfig config) + : base(nameof(ModSelection)) + { + _communicator = communicator; + _collections = collections; + _config = config; + if (_config.LastModPath.Length > 0) + SelectMod(mods.FirstOrDefault(m => string.Equals(m.Identifier, config.LastModPath, StringComparison.OrdinalIgnoreCase))); + + _communicator.CollectionChange.Subscribe(OnCollectionChange, CollectionChange.Priority.ModSelection); + _communicator.CollectionInheritanceChanged.Subscribe(OnInheritanceChange, CollectionInheritanceChanged.Priority.ModSelection); + _communicator.ModSettingChanged.Subscribe(OnSettingChange, ModSettingChanged.Priority.ModSelection); + } + + public ModSettings Settings { get; private set; } = ModSettings.Empty; + public ModCollection Collection { get; private set; } = ModCollection.Empty; + public Mod? Mod { get; private set; } + + + public void SelectMod(Mod? mod) + { + if (mod == Mod) + return; + + var oldMod = Mod; + Mod = mod; + OnCollectionChange(CollectionType.Current, null, _collections.Current, string.Empty); + Invoke(oldMod, Mod); + _config.LastModPath = mod?.ModPath.Name ?? string.Empty; + _config.Save(); + } + + protected override void Dispose(bool _) + { + _communicator.CollectionChange.Unsubscribe(OnCollectionChange); + _communicator.CollectionInheritanceChanged.Unsubscribe(OnInheritanceChange); + _communicator.ModSettingChanged.Unsubscribe(OnSettingChange); + } + + private void OnCollectionChange(CollectionType type, ModCollection? oldCollection, ModCollection? newCollection, string _2) + { + if (type is CollectionType.Current && oldCollection != newCollection) + UpdateSettings(); + } + + private void OnSettingChange(ModCollection collection, ModSettingChange _1, Mod? mod, Setting _2, int _3, bool _4) + { + if (collection == _collections.Current && mod == Mod) + UpdateSettings(); + } + + private void OnInheritanceChange(ModCollection collection, bool arg2) + { + if (collection == _collections.Current) + UpdateSettings(); + } + + private void UpdateSettings() + { + if (Mod == null) + { + Settings = ModSettings.Empty; + Collection = ModCollection.Empty; + } + else + { + (var settings, Collection) = _collections.Current[Mod.Index]; + Settings = settings ?? ModSettings.Empty; + } + } + + public enum Priority + { + /// + ModPanel = 0, + + /// + ModMerger = 0, + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 13458252..7bb067d8 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -36,8 +36,6 @@ public partial class ModEditWindow : Window, IDisposable, IUiService { private const string WindowBaseLabel = "###SubModEdit"; - public readonly MigrationManager MigrationManager; - private readonly PerformanceTracker _performance; private readonly ModEditor _editor; private readonly Configuration _config; @@ -587,7 +585,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService CommunicatorService communicator, TextureManager textures, ModelManager models, IDragDropManager dragDropManager, ResourceTreeViewerFactory resourceTreeViewerFactory, IFramework framework, MetaDrawers metaDrawers, MigrationManager migrationManager, - MtrlTabFactory mtrlTabFactory) + MtrlTabFactory mtrlTabFactory, ModSelection selection) : base(WindowBaseLabel) { _performance = performance; @@ -604,7 +602,6 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _models = models; _fileDialog = fileDialog; _framework = framework; - MigrationManager = migrationManager; _metaDrawers = metaDrawers; _materialTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => Mod?.ModPath.FullName ?? string.Empty, @@ -622,6 +619,8 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _quickImportViewer = resourceTreeViewerFactory.Create(2, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModEditWindow); IsOpen = _config is { OpenWindowAtStart: true, Ephemeral.AdvancedEditingOpen: true }; + if (IsOpen && selection.Mod != null) + ChangeMod(selection.Mod); } public void Dispose() diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index 0f9b2518..3972e350 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -5,24 +5,24 @@ using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; +using Penumbra.Mods; using Penumbra.UI.CollectionTab; -using Penumbra.UI.ModsTab; namespace Penumbra.UI.Classes; public class CollectionSelectHeader : IUiService { - private readonly CollectionCombo _collectionCombo; - private readonly ActiveCollections _activeCollections; - private readonly TutorialService _tutorial; - private readonly ModFileSystemSelector _selector; - private readonly CollectionResolver _resolver; + private readonly CollectionCombo _collectionCombo; + private readonly ActiveCollections _activeCollections; + private readonly TutorialService _tutorial; + private readonly ModSelection _selection; + private readonly CollectionResolver _resolver; - public CollectionSelectHeader(CollectionManager collectionManager, TutorialService tutorial, ModFileSystemSelector selector, + public CollectionSelectHeader(CollectionManager collectionManager, TutorialService tutorial, ModSelection selection, CollectionResolver resolver) { _tutorial = tutorial; - _selector = selector; + _selection = selection; _resolver = resolver; _activeCollections = collectionManager.Active; _collectionCombo = new CollectionCombo(collectionManager, () => collectionManager.Storage.OrderBy(c => c.Name).ToList()); @@ -115,7 +115,7 @@ public class CollectionSelectHeader : IUiService private (ModCollection?, string, string, bool) GetInheritedCollectionInfo() { - var collection = _selector.Selected == null ? null : _selector.SelectedSettingCollection; + var collection = _selection.Mod == null ? null : _selection.Collection; return CheckCollection(collection, true) switch { CollectionState.Unavailable => (null, "Not Inherited", diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 42689efb..2f76340b 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -25,7 +25,6 @@ namespace Penumbra.UI.ModsTab; public sealed class ModFileSystemSelector : FileSystemSelector, IUiService { private readonly CommunicatorService _communicator; - private readonly MessageService _messager; private readonly Configuration _config; private readonly FileDialogService _fileDialog; private readonly ModManager _modManager; @@ -33,15 +32,12 @@ public sealed class ModFileSystemSelector : FileSystemSelector 0) - { - var mod = _modManager.FirstOrDefault(m - => string.Equals(m.Identifier, _config.Ephemeral.LastModPath, StringComparison.OrdinalIgnoreCase)); - if (mod != null) - SelectByValue(mod); - } - + if (_selection.Mod != null) + SelectByValue(_selection.Mod); _communicator.CollectionChange.Subscribe(OnCollectionChange, CollectionChange.Priority.ModFileSystemSelector); _communicator.ModSettingChanged.Subscribe(OnSettingChange, ModSettingChanged.Priority.ModFileSystemSelector); _communicator.CollectionInheritanceChanged.Subscribe(OnInheritanceChange, CollectionInheritanceChanged.Priority.ModFileSystemSelector); _communicator.ModDataChanged.Subscribe(OnModDataChange, ModDataChanged.Priority.ModFileSystemSelector); _communicator.ModDiscoveryStarted.Subscribe(StoreCurrentSelection, ModDiscoveryStarted.Priority.ModFileSystemSelector); _communicator.ModDiscoveryFinished.Subscribe(RestoreLastSelection, ModDiscoveryFinished.Priority.ModFileSystemSelector); - OnCollectionChange(CollectionType.Current, null, _collectionManager.Active.Current, ""); - } - + SetFilterDirty(); + SelectionChanged += OnSelectionChanged; + } + public void SetRenameSearchPath(RenameField value) { switch (value) @@ -449,12 +439,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector _selection.SelectMod(newSelection); + #endregion #region Filters @@ -567,7 +529,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Appropriately identify and set the string filter and its type. protected override bool ChangeFilter(string filterValue) { - Filter.Parse(filterValue); + _filter.Parse(filterValue); return true; } @@ -597,7 +559,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Apply the string filters. private bool ApplyStringFilters(ModFileSystem.Leaf leaf, Mod mod) - => !Filter.IsVisible(leaf); + => !_filter.IsVisible(leaf); /// Only get the text color for a mod if no filters are set. private ColorId GetTextColor(Mod mod, ModSettings? settings, ModCollection collection) diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index ee6fab1f..9d6ead62 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -10,22 +10,23 @@ namespace Penumbra.UI.ModsTab; public class ModPanel : IDisposable, IUiService { - private readonly MultiModPanel _multiModPanel; - private readonly ModFileSystemSelector _selector; - private readonly ModEditWindow _editWindow; - private readonly ModPanelHeader _header; - private readonly ModPanelTabBar _tabs; - private bool _resetCursor; + private readonly MultiModPanel _multiModPanel; + private readonly ModSelection _selection; + private readonly ModEditWindow _editWindow; + private readonly ModPanelHeader _header; + private readonly ModPanelTabBar _tabs; + private bool _resetCursor; - public ModPanel(IDalamudPluginInterface pi, ModFileSystemSelector selector, ModEditWindow editWindow, ModPanelTabBar tabs, + public ModPanel(IDalamudPluginInterface pi, ModSelection selection, ModEditWindow editWindow, ModPanelTabBar tabs, MultiModPanel multiModPanel, CommunicatorService communicator) { - _selector = selector; - _editWindow = editWindow; - _tabs = tabs; - _multiModPanel = multiModPanel; - _header = new ModPanelHeader(pi, communicator); - _selector.SelectionChanged += OnSelectionChange; + _selection = selection; + _editWindow = editWindow; + _tabs = tabs; + _multiModPanel = multiModPanel; + _header = new ModPanelHeader(pi, communicator); + _selection.Subscribe(OnSelectionChange, ModSelection.Priority.ModPanel); + OnSelectionChange(null, _selection.Mod); } public void Draw() @@ -52,17 +53,17 @@ public class ModPanel : IDisposable, IUiService public void Dispose() { - _selector.SelectionChanged -= OnSelectionChange; + _selection.Unsubscribe(OnSelectionChange); _header.Dispose(); } private bool _valid; private Mod _mod = null!; - private void OnSelectionChange(Mod? old, Mod? mod, in ModFileSystemSelector.ModState _) + private void OnSelectionChange(Mod? old, Mod? mod) { _resetCursor = true; - if (mod == null || _selector.Selected == null) + if (mod == null || _selection.Mod == null) { _editWindow.IsOpen = false; _valid = false; @@ -73,7 +74,7 @@ public class ModPanel : IDisposable, IUiService _editWindow.ChangeMod(mod); _valid = true; _mod = mod; - _header.UpdateModData(_mod); + _header.ChangeMod(_mod); _tabs.Settings.Reset(); _tabs.Edit.Reset(); } diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index 6c974f9c..aafbffa6 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -18,7 +18,8 @@ public class ModPanelHeader : IDisposable private readonly IFontHandle _nameFont; private readonly CommunicatorService _communicator; - private float _lastPreSettingsHeight = 0; + private float _lastPreSettingsHeight; + private bool _dirty = true; public ModPanelHeader(IDalamudPluginInterface pi, CommunicatorService communicator) { @@ -33,6 +34,7 @@ public class ModPanelHeader : IDisposable /// public void Draw() { + UpdateModData(); var height = ImGui.GetContentRegionAvail().Y; var maxHeight = 3 * height / 4; using var child = _lastPreSettingsHeight > maxHeight && _communicator.PreSettingsTabBarDraw.HasSubscribers @@ -49,16 +51,25 @@ public class ModPanelHeader : IDisposable _lastPreSettingsHeight = ImGui.GetCursorPosY(); } + public void ChangeMod(Mod mod) + { + _mod = mod; + _dirty = true; + } + /// /// Update all mod header data. Should someone change frame padding or item spacing, /// or his default font, this will break, but he will just have to select a different mod to restore. /// - public void UpdateModData(Mod mod) + private void UpdateModData() { + if (!_dirty) + return; + + _dirty = false; _lastPreSettingsHeight = 0; - _mod = mod; // Name - var name = $" {mod.Name} "; + var name = $" {_mod.Name} "; if (name != _modName) { using var f = _nameFont.Push(); @@ -67,16 +78,16 @@ public class ModPanelHeader : IDisposable } // Author - if (mod.Author != _modAuthor) + if (_mod.Author != _modAuthor) { - var author = mod.Author.IsEmpty ? string.Empty : $"by {mod.Author}"; - _modAuthor = mod.Author.Text; + var author = _mod.Author.IsEmpty ? string.Empty : $"by {_mod.Author}"; + _modAuthor = _mod.Author.Text; _modAuthorWidth = ImGui.CalcTextSize(author).X; _secondRowWidth = _modAuthorWidth + _modWebsiteButtonWidth + ImGui.GetStyle().ItemSpacing.X; } // Version - var version = mod.Version.Length > 0 ? $"({mod.Version})" : string.Empty; + var version = _mod.Version.Length > 0 ? $"({_mod.Version})" : string.Empty; if (version != _modVersion) { _modVersion = version; @@ -84,9 +95,9 @@ public class ModPanelHeader : IDisposable } // Website - if (_modWebsite != mod.Website) + if (_modWebsite != _mod.Website) { - _modWebsite = mod.Website; + _modWebsite = _mod.Website; _websiteValid = Uri.TryCreate(_modWebsite, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttps || uriResult.Scheme == Uri.UriSchemeHttp); _modWebsiteButton = _websiteValid ? "Open Website" : _modWebsite.Length == 0 ? string.Empty : $"from {_modWebsite}"; @@ -253,7 +264,6 @@ public class ModPanelHeader : IDisposable { const ModDataChangeType relevantChanges = ModDataChangeType.Author | ModDataChangeType.Name | ModDataChangeType.Website | ModDataChangeType.Version; - if ((changeType & relevantChanges) != 0) - UpdateModData(mod); + _dirty = (changeType & relevantChanges) != 0; } } diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 7e3b8a95..d2fbd0cd 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -3,9 +3,9 @@ using OtterGui.Raii; using OtterGui; using OtterGui.Services; using OtterGui.Widgets; -using Penumbra.Collections; using Penumbra.UI.Classes; using Penumbra.Collections.Manager; +using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.Mods.Settings; @@ -16,16 +16,14 @@ namespace Penumbra.UI.ModsTab; public class ModPanelSettingsTab( CollectionManager collectionManager, ModManager modManager, - ModFileSystemSelector selector, + ModSelection selection, TutorialService tutorial, CommunicatorService communicator, ModGroupDrawer modGroupDrawer) : ITab, IUiService { - private bool _inherited; - private ModSettings _settings = null!; - private ModCollection _collection = null!; - private int? _currentPriority; + private bool _inherited; + private int? _currentPriority; public ReadOnlySpan Label => "Settings"u8; @@ -42,12 +40,10 @@ public class ModPanelSettingsTab( if (!child) return; - _settings = selector.SelectedSettings; - _collection = selector.SelectedSettingCollection; - _inherited = _collection != collectionManager.Active.Current; + _inherited = selection.Collection != collectionManager.Active.Current; DrawInheritedWarning(); UiHelpers.DefaultLineSpace(); - communicator.PreSettingsPanelDraw.Invoke(selector.Selected!.Identifier); + communicator.PreSettingsPanelDraw.Invoke(selection.Mod!.Identifier); DrawEnabledInput(); tutorial.OpenTutorial(BasicTutorialSteps.EnablingMods); ImGui.SameLine(); @@ -55,11 +51,11 @@ public class ModPanelSettingsTab( tutorial.OpenTutorial(BasicTutorialSteps.Priority); DrawRemoveSettings(); - communicator.PostEnabledDraw.Invoke(selector.Selected!.Identifier); + communicator.PostEnabledDraw.Invoke(selection.Mod!.Identifier); - modGroupDrawer.Draw(selector.Selected!, _settings); + modGroupDrawer.Draw(selection.Mod!, selection.Settings); UiHelpers.DefaultLineSpace(); - communicator.PostSettingsPanelDraw.Invoke(selector.Selected!.Identifier); + communicator.PostSettingsPanelDraw.Invoke(selection.Mod!.Identifier); } /// Draw a big red bar if the current setting is inherited. @@ -70,8 +66,8 @@ public class ModPanelSettingsTab( using var color = ImRaii.PushColor(ImGuiCol.Button, Colors.PressEnterWarningBg); var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); - if (ImGui.Button($"These settings are inherited from {_collection.Name}.", width)) - collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selector.Selected!, false); + if (ImGui.Button($"These settings are inherited from {selection.Collection.Name}.", width)) + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, false); ImGuiUtil.HoverTooltip("You can click this button to copy the current settings to the current selection.\n" + "You can also just change any setting, which will copy the settings with the single setting changed to the current selection."); @@ -80,12 +76,12 @@ public class ModPanelSettingsTab( /// Draw a checkbox for the enabled status of the mod. private void DrawEnabledInput() { - var enabled = _settings.Enabled; + var enabled = selection.Settings.Enabled; if (!ImGui.Checkbox("Enabled", ref enabled)) return; - modManager.SetKnown(selector.Selected!); - collectionManager.Editor.SetModState(collectionManager.Active.Current, selector.Selected!, enabled); + modManager.SetKnown(selection.Mod!); + collectionManager.Editor.SetModState(collectionManager.Active.Current, selection.Mod!, enabled); } /// @@ -95,15 +91,16 @@ public class ModPanelSettingsTab( private void DrawPriorityInput() { using var group = ImRaii.Group(); - var priority = _currentPriority ?? _settings.Priority.Value; + var settings = selection.Settings; + var priority = _currentPriority ?? settings.Priority.Value; ImGui.SetNextItemWidth(50 * UiHelpers.Scale); if (ImGui.InputInt("##Priority", ref priority, 0, 0)) _currentPriority = priority; if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { - if (_currentPriority != _settings.Priority.Value) - collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selector.Selected!, + if (_currentPriority != settings.Priority.Value) + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selection.Mod!, new ModPriority(_currentPriority.Value)); _currentPriority = null; @@ -120,13 +117,13 @@ public class ModPanelSettingsTab( private void DrawRemoveSettings() { const string text = "Inherit Settings"; - if (_inherited || _settings == ModSettings.Empty) + if (_inherited || selection.Settings == ModSettings.Empty) return; var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0; ImGui.SameLine(ImGui.GetWindowWidth() - ImGui.CalcTextSize(text).X - ImGui.GetStyle().FramePadding.X * 2 - scroll); if (ImGui.Button(text)) - collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selector.Selected!, true); + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, true); ImGuiUtil.HoverTooltip("Remove current settings from this collection so that it can inherit them.\n" + "If no inherited collection has settings for this mod, it will be disabled."); diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 50fdc1d3..87338bdb 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -82,8 +82,7 @@ public class ModsTab( + $"{selector.SortMode.Name} Sort Mode\n" + $"{selector.SelectedLeaf?.Name ?? "NULL"} Selected Leaf\n" + $"{selector.Selected?.Name ?? "NULL"} Selected Mod\n" - + $"{string.Join(", ", _activeCollections.Current.DirectlyInheritsFrom.Select(c => c.AnonymizedName))} Inheritances\n" - + $"{selector.SelectedSettingCollection.AnonymizedName} Collection\n"); + + $"{string.Join(", ", _activeCollections.Current.DirectlyInheritsFrom.Select(c => c.AnonymizedName))} Inheritances\n"); } } From 4970e571316fc6b6394b029e03bd26119fde98bd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 18:29:12 +0200 Subject: [PATCH 0891/1381] Improve tooltip of file redirections tab. --- OtterGui | 2 +- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 28 +++++++++++-------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/OtterGui b/OtterGui index 276327f8..9217ac56 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 276327f812e2f7e6aac7aee9e5ef0a560b065765 +Subproject commit 9217ac56697bc8285ced483b1fd4734fd36ba64d diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index ffa7473d..b07633b6 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -1,8 +1,10 @@ +using System.Linq; using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; +using OtterGui.Text; using Penumbra.Mods.Editor; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; @@ -144,22 +146,20 @@ public partial class ModEditWindow private static string DrawFileTooltip(FileRegistry registry, ColorId color) { - (string, int) GetMulti() - { - var groups = registry.SubModUsage.GroupBy(s => s.Item1).ToArray(); - return (string.Join("\n", groups.Select(g => g.Key.GetName())), groups.Length); - } - var (text, groupCount) = color switch { - ColorId.ConflictingMod => (string.Empty, 0), - ColorId.NewMod => (registry.SubModUsage[0].Item1.GetName(), 1), + ColorId.ConflictingMod => (null, 0), + ColorId.NewMod => ([registry.SubModUsage[0].Item1.GetName()], 1), ColorId.InheritedMod => GetMulti(), - _ => (string.Empty, 0), + _ => (null, 0), }; - if (text.Length > 0 && ImGui.IsItemHovered()) - ImGui.SetTooltip(text); + if (text != null && ImGui.IsItemHovered()) + { + using var tt = ImUtf8.Tooltip(); + using var c = ImRaii.DefaultColors(); + ImUtf8.Text(string.Join('\n', text)); + } return (groupCount, registry.SubModUsage.Count) switch @@ -169,6 +169,12 @@ public partial class ModEditWindow (1, > 1) => $"(used {registry.SubModUsage.Count} times in 1 group)", _ => $"(used {registry.SubModUsage.Count} times over {groupCount} groups)", }; + + (IEnumerable, int) GetMulti() + { + var groups = registry.SubModUsage.GroupBy(s => s.Item1).ToArray(); + return (groups.Select(g => g.Key.GetName()), groups.Length); + } } private void DrawSelectable(FileRegistry registry) From 6d408ba695666e67be5d77d5387b676be839a744 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 18:29:47 +0200 Subject: [PATCH 0892/1381] Clip meta changes. --- Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 3 +++ Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs | 3 +++ Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs | 3 +++ .../UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs | 3 +++ Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs | 5 ++++- Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 3 +++ Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 15 +++++++++------ Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs | 3 +++ 8 files changed, 31 insertions(+), 7 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index aea2ef78..f9baddbe 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -66,6 +66,9 @@ public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFil .ThenBy(kvp => kvp.Key.Slot) .Select(kvp => (kvp.Key, kvp.Value)); + protected override int Count + => Editor.Eqdp.Count; + private static bool DrawIdentifierInput(ref EqdpIdentifier identifier) { ImGui.TableNextColumn(); diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs index 733517f3..51b14459 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs @@ -64,6 +64,9 @@ public sealed class EqpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile .ThenBy(kvp => kvp.Key.Slot) .Select(kvp => (kvp.Key, kvp.Value)); + protected override int Count + => Editor.Eqp.Count; + private static bool DrawIdentifierInput(ref EqpIdentifier identifier) { ImGui.TableNextColumn(); diff --git a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs index a33f8b7b..09075319 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs @@ -64,6 +64,9 @@ public sealed class EstMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile .ThenBy(kvp => kvp.Key.Slot) .Select(kvp => (kvp.Key, kvp.Value)); + protected override int Count + => Editor.Est.Count; + private static bool DrawIdentifierInput(ref EstIdentifier identifier) { ImGui.TableNextColumn(); diff --git a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs index 5d67ddcf..1aa9060e 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs @@ -52,6 +52,9 @@ public sealed class GlobalEqpMetaDrawer(ModMetaEditor editor, MetaFileManager me .ThenBy(identifier => identifier.Condition.Id) .Select(identifier => (identifier, (byte)0)); + protected override int Count + => Editor.GlobalEqp.Count; + private static void DrawIdentifierInput(ref GlobalEqpManipulation identifier) { ImGui.TableNextColumn(); diff --git a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs index bd42b60a..9532d8e7 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs @@ -59,7 +59,10 @@ public sealed class GmpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override IEnumerable<(GmpIdentifier, GmpEntry)> Enumerate() => Editor.Gmp .OrderBy(kvp => kvp.Key.SetId.Id) - .Select(kvp => (kvp.Key, kvp.Value)); + .Select(kvp => (kvp.Key, kvp.Value)); + + protected override int Count + => Editor.Gmp.Count; private static bool DrawIdentifierInput(ref GmpIdentifier identifier) { diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index 4e949b98..53c61292 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -149,6 +149,9 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile .ThenBy(kvp => kvp.Key.Variant.Id) .Select(kvp => (kvp.Key, kvp.Value)); + protected override int Count + => Editor.Imc.Count; + public static bool DrawObjectType(ref ImcIdentifier identifier, float width = 110) { var ret = Combos.ImcType("##imcType", identifier.ObjectType, out var type, width); diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs index 229526c4..75de20a7 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -41,12 +41,14 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta using var id = ImUtf8.PushId((int)Identifier.Type); DrawNew(); - foreach (var ((identifier, entry), idx) in Enumerate().WithIndex()) - { - id.Push(idx); - DrawEntry(identifier, entry); - id.Pop(); - } + + var height = ImUtf8.FrameHeightSpacing; + var skips = ImGuiClip.GetNecessarySkipsAtPos(height, ImGui.GetCursorPosY()); + var remainder = ImGuiClip.ClippedTableDraw(Enumerate(), skips, DrawLine, Count); + ImGuiClip.DrawEndDummy(remainder, height); + + void DrawLine((TIdentifier Identifier, TEntry Value) pair) + => DrawEntry(pair.Identifier, pair.Value); } public abstract ReadOnlySpan Label { get; } @@ -57,6 +59,7 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta protected abstract void DrawEntry(TIdentifier identifier, TEntry entry); protected abstract IEnumerable<(TIdentifier, TEntry)> Enumerate(); + protected abstract int Count { get; } /// diff --git a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs index 6d819b16..87e8c5b8 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs @@ -63,6 +63,9 @@ public sealed class RspMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile .ThenBy(kvp => kvp.Key.Attribute) .Select(kvp => (kvp.Key, kvp.Value)); + protected override int Count + => Editor.Rsp.Count; + private static bool DrawIdentifierInput(ref RspIdentifier identifier) { ImGui.TableNextColumn(); From 4117d45d152e9c6c3f29656c0f103f1884a5e38a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 18:32:22 +0200 Subject: [PATCH 0893/1381] Use ReadWriteDictionary as base for meta changes. --- OtterGui | 2 +- Penumbra/Collections/Cache/GlobalEqpCache.cs | 3 +- Penumbra/Collections/Cache/MetaCache.cs | 6 ++- .../Cache/{IMetaCache.cs => MetaCacheBase.cs} | 37 ++++++------------- 4 files changed, 20 insertions(+), 28 deletions(-) rename Penumbra/Collections/Cache/{IMetaCache.cs => MetaCacheBase.cs} (52%) diff --git a/OtterGui b/OtterGui index 9217ac56..bfbde4f8 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9217ac56697bc8285ced483b1fd4734fd36ba64d +Subproject commit bfbde4f8aa6acc8eb3ed8bc419d5ae2afc77b5f1 diff --git a/Penumbra/Collections/Cache/GlobalEqpCache.cs b/Penumbra/Collections/Cache/GlobalEqpCache.cs index 1c80b47d..efcab109 100644 --- a/Penumbra/Collections/Cache/GlobalEqpCache.cs +++ b/Penumbra/Collections/Cache/GlobalEqpCache.cs @@ -1,3 +1,4 @@ +using OtterGui.Classes; using OtterGui.Services; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; @@ -5,7 +6,7 @@ using Penumbra.Mods.Editor; namespace Penumbra.Collections.Cache; -public class GlobalEqpCache : Dictionary, IService +public class GlobalEqpCache : ReadWriteDictionary, IService { private readonly HashSet _doNotHideEarrings = []; private readonly HashSet _doNotHideNecklace = []; diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 1a6924a9..05a94ac5 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -3,7 +3,6 @@ using Penumbra.GameData.Structs; using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; -using Penumbra.String.Classes; namespace Penumbra.Collections.Cache; @@ -16,6 +15,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public readonly RspCache Rsp = new(manager, collection); public readonly ImcCache Imc = new(manager, collection); public readonly GlobalEqpCache GlobalEqp = new(); + public bool IsDisposed { get; private set; } public int Count => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + GlobalEqp.Count; @@ -42,6 +42,10 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public void Dispose() { + if (IsDisposed) + return; + + IsDisposed = true; Eqp.Dispose(); Eqdp.Dispose(); Est.Dispose(); diff --git a/Penumbra/Collections/Cache/IMetaCache.cs b/Penumbra/Collections/Cache/MetaCacheBase.cs similarity index 52% rename from Penumbra/Collections/Cache/IMetaCache.cs rename to Penumbra/Collections/Cache/MetaCacheBase.cs index fecc6f50..98a87e3f 100644 --- a/Penumbra/Collections/Cache/IMetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCacheBase.cs @@ -1,3 +1,4 @@ +using OtterGui.Classes; using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; @@ -5,27 +6,19 @@ using Penumbra.Mods.Editor; namespace Penumbra.Collections.Cache; public abstract class MetaCacheBase(MetaFileManager manager, ModCollection collection) - : Dictionary + : ReadWriteDictionary where TIdentifier : unmanaged, IMetaIdentifier where TEntry : unmanaged { - protected readonly MetaFileManager Manager = manager; - protected readonly ModCollection Collection = collection; - - public void Dispose() - { - Dispose(true); - } + protected readonly MetaFileManager Manager = manager; + protected readonly ModCollection Collection = collection; public bool ApplyMod(IMod source, TIdentifier identifier, TEntry entry) { - lock (this) - { - if (TryGetValue(identifier, out var pair) && pair.Source == source && EqualityComparer.Default.Equals(pair.Entry, entry)) - return false; + if (TryGetValue(identifier, out var pair) && pair.Source == source && EqualityComparer.Default.Equals(pair.Entry, entry)) + return false; - this[identifier] = (source, entry); - } + this[identifier] = (source, entry); ApplyModInternal(identifier, entry); return true; @@ -33,17 +26,14 @@ public abstract class MetaCacheBase(MetaFileManager manager public bool RevertMod(TIdentifier identifier, [NotNullWhen(true)] out IMod? mod) { - lock (this) + if (!Remove(identifier, out var pair)) { - if (!Remove(identifier, out var pair)) - { - mod = null; - return false; - } - - mod = pair.Source; + mod = null; + return false; } + mod = pair.Source; + RevertModInternal(identifier); return true; } @@ -54,7 +44,4 @@ public abstract class MetaCacheBase(MetaFileManager manager protected virtual void RevertModInternal(TIdentifier identifier) { } - - protected virtual void Dispose(bool _) - { } } From f04331188252806b983adac72aa99134d36bc5c5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 23:10:22 +0200 Subject: [PATCH 0894/1381] Fix vulnerability warning. --- Penumbra/Penumbra.csproj | 2 ++ Penumbra/packages.lock.json | 11 ++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index f42d16ad..9b613729 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -86,6 +86,8 @@ + + diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index fd3a0a9e..5b868212 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -51,6 +51,12 @@ "resolved": "3.1.5", "contentHash": "lNtlq7dSI/QEbYey+A0xn48z5w4XHSffF8222cC4F4YwTXfEImuiBavQcWjr49LThT/pRmtWJRcqA/PlL+eJ6g==" }, + "System.Formats.Asn1": { + "type": "Direct", + "requested": "[8.0.1, )", + "resolved": "8.0.1", + "contentHash": "XqKba7Mm/koKSjKMfW82olQdmfbI5yqeoLV/tidRp7fbh5rmHAQ5raDI/7SU0swTzv+jgqtUGkzmFxuUg0it1A==" + }, "JetBrains.Annotations": { "type": "Transitive", "resolved": "2024.2.0", @@ -82,11 +88,6 @@ "SharpGLTF.Core": "1.0.1" } }, - "System.Formats.Asn1": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "AJukBuLoe3QeAF+mfaRKQb2dgyrvt340iMBHYv+VdBzCUM06IxGlvl0o/uPOS7lHnXPN6u8fFRHSHudx5aTi8w==" - }, "System.Security.Cryptography.Pkcs": { "type": "Transitive", "resolved": "8.0.0", From f8e3b6777fd347ff5c19899fcf1d0b695486c901 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 Aug 2024 23:10:59 +0200 Subject: [PATCH 0895/1381] Add DeleteDefaultValues on general dicts. --- Penumbra/Mods/Editor/ModMetaEditor.cs | 67 ++++++++++++++++++++------- 1 file changed, 51 insertions(+), 16 deletions(-) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index d9018ff6..6b5ec378 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,6 +1,5 @@ using System.Collections.Frozen; using OtterGui.Services; -using Penumbra.GameData.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -65,65 +64,101 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage Changes = false; } - public void DeleteDefaultValues() + public bool DeleteDefaultValues(MetaDictionary dict) { - var clone = Clone(); - Clear(); + var clone = dict.Clone(); + dict.Clear(); + var ret = false; foreach (var (key, value) in clone.Imc) { var defaultEntry = imcChecker.GetDefaultEntry(key, false); if (!defaultEntry.Entry.Equals(value)) - TryAdd(key, value); + { + dict.TryAdd(key, value); + } else - Changes = true; + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ret = true; + } } foreach (var (key, value) in clone.Eqp) { var defaultEntry = new EqpEntryInternal(ExpandedEqpFile.GetDefault(metaFileManager, key.SetId), key.Slot); if (!defaultEntry.Equals(value)) - TryAdd(key, value); + { + dict.TryAdd(key, value); + } else - Changes = true; + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ret = true; + } } foreach (var (key, value) in clone.Eqdp) { var defaultEntry = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(metaFileManager, key), key.Slot); if (!defaultEntry.Equals(value)) - TryAdd(key, value); + { + dict.TryAdd(key, value); + } else - Changes = true; + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ret = true; + } } foreach (var (key, value) in clone.Est) { var defaultEntry = EstFile.GetDefault(metaFileManager, key); if (!defaultEntry.Equals(value)) - TryAdd(key, value); + { + dict.TryAdd(key, value); + } else - Changes = true; + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ret = true; + } } foreach (var (key, value) in clone.Gmp) { var defaultEntry = ExpandedGmpFile.GetDefault(metaFileManager, key); if (!defaultEntry.Equals(value)) - TryAdd(key, value); + { + dict.TryAdd(key, value); + } else - Changes = true; + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ret = true; + } } foreach (var (key, value) in clone.Rsp) { var defaultEntry = CmpFile.GetDefault(metaFileManager, key.SubRace, key.Attribute); if (!defaultEntry.Equals(value)) - TryAdd(key, value); + { + dict.TryAdd(key, value); + } else - Changes = true; + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ret = true; + } } + + return ret; } + public void DeleteDefaultValues() + => Changes = DeleteDefaultValues(this); + public void Apply(IModDataContainer container) { if (!Changes) From f5e61324627be7e192ce124d2a59154673adb857 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 29 Aug 2024 17:47:51 +0200 Subject: [PATCH 0896/1381] Delete default meta entries from archives and api added mods if not configured otherwise. --- Penumbra/Api/Api/ModsApi.cs | 2 +- Penumbra/Mods/Editor/DuplicateManager.cs | 2 +- Penumbra/Mods/Editor/ModFileEditor.cs | 2 +- Penumbra/Mods/Editor/ModMerger.cs | 2 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 33 +++++---- Penumbra/Mods/Editor/ModNormalizer.cs | 2 +- Penumbra/Mods/Manager/ModImportManager.cs | 2 +- Penumbra/Mods/Manager/ModManager.cs | 10 +-- Penumbra/Mods/Manager/ModMigration.cs | 6 +- .../Manager/OptionEditor/ModGroupEditor.cs | 30 ++++---- Penumbra/Mods/ModCreator.cs | 71 +++++++++++-------- Penumbra/Mods/TemporaryMod.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 2 +- 14 files changed, 95 insertions(+), 73 deletions(-) diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 2acdf031..31f20c5e 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -82,7 +82,7 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable != Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir.Parent.FullName))) return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); - _modManager.AddMod(dir); + _modManager.AddMod(dir, true); if (_config.MigrateImportedModelsToV6) { _migrationManager.MigrateMdlDirectory(dir.FullName, false); diff --git a/Penumbra/Mods/Editor/DuplicateManager.cs b/Penumbra/Mods/Editor/DuplicateManager.cs index bcecf264..56a19766 100644 --- a/Penumbra/Mods/Editor/DuplicateManager.cs +++ b/Penumbra/Mods/Editor/DuplicateManager.cs @@ -225,7 +225,7 @@ public class DuplicateManager(ModManager modManager, SaveService saveService, Co if (!useModManager || !modManager.TryGetMod(modDirectory.Name, string.Empty, out var mod)) { mod = new Mod(modDirectory); - modManager.Creator.ReloadMod(mod, true, out _); + modManager.Creator.ReloadMod(mod, true, true, out _); } Clear(); diff --git a/Penumbra/Mods/Editor/ModFileEditor.cs b/Penumbra/Mods/Editor/ModFileEditor.cs index 55e0e94e..3b765215 100644 --- a/Penumbra/Mods/Editor/ModFileEditor.cs +++ b/Penumbra/Mods/Editor/ModFileEditor.cs @@ -151,7 +151,7 @@ public class ModFileEditor(ModFileCollection files, ModManager modManager, Commu if (deletions <= 0) return; - modManager.Creator.ReloadMod(mod, false, out _); + modManager.Creator.ReloadMod(mod, false, false, out _); files.UpdateAll(mod, option); } diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index d75ac671..e3eb5f54 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -256,7 +256,7 @@ public class ModMerger : IDisposable, IService if (dir == null) throw new Exception($"Could not split off mods, unable to create new mod with name {modName}."); - _mods.AddMod(dir); + _mods.AddMod(dir, false); result = _mods[^1]; if (mods.Count == 1) { diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 6b5ec378..81a33db6 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -3,12 +3,15 @@ using OtterGui.Services; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; -using Penumbra.Mods.Manager; +using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; namespace Penumbra.Mods.Editor; -public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManager, ImcChecker imcChecker) : MetaDictionary, IService +public class ModMetaEditor( + ModGroupEditor groupEditor, + MetaFileManager metaFileManager, + ImcChecker imcChecker) : MetaDictionary, IService { public sealed class OtherOptionData : HashSet { @@ -64,11 +67,11 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage Changes = false; } - public bool DeleteDefaultValues(MetaDictionary dict) + public static bool DeleteDefaultValues(MetaFileManager metaFileManager, ImcChecker imcChecker, MetaDictionary dict) { var clone = dict.Clone(); dict.Clear(); - var ret = false; + var count = 0; foreach (var (key, value) in clone.Imc) { var defaultEntry = imcChecker.GetDefaultEntry(key, false); @@ -79,7 +82,7 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage else { Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); - ret = true; + ++count; } } @@ -93,7 +96,7 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage else { Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); - ret = true; + ++count; } } @@ -107,7 +110,7 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage else { Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); - ret = true; + ++count; } } @@ -121,7 +124,7 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage else { Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); - ret = true; + ++count; } } @@ -135,7 +138,7 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage else { Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); - ret = true; + ++count; } } @@ -149,22 +152,26 @@ public class ModMetaEditor(ModManager modManager, MetaFileManager metaFileManage else { Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); - ret = true; + ++count; } } - return ret; + if (count <= 0) + return false; + + Penumbra.Log.Debug($"Deleted {count} default-valued meta-entries from a mod option."); + return true; } public void DeleteDefaultValues() - => Changes = DeleteDefaultValues(this); + => Changes = DeleteDefaultValues(metaFileManager, imcChecker, this); public void Apply(IModDataContainer container) { if (!Changes) return; - modManager.OptionEditor.SetManipulations(container, this); + groupEditor.SetManipulations(container, this); Changes = false; } } diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 43cfc1ee..3e367a3b 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -46,7 +46,7 @@ public class ModNormalizer(ModManager modManager, Configuration config, SaveServ if (!config.AutoReduplicateUiOnImport) return; - if (modManager.Creator.LoadMod(modDirectory, false) is not { } mod) + if (modManager.Creator.LoadMod(modDirectory, false, false) is not { } mod) return; Dictionary> paths = []; diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index d984d374..22cc0c86 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -79,7 +79,7 @@ public class ModImportManager(ModManager modManager, Configuration config, ModEd return false; } - modManager.AddMod(directory); + modManager.AddMod(directory, true); mod = modManager.LastOrDefault(); return mod != null && mod.ModPath == directory; } diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 59f8906e..bf1b6637 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -81,13 +81,13 @@ public sealed class ModManager : ModStorage, IDisposable, IService } /// Load a new mod and add it to the manager if successful. - public void AddMod(DirectoryInfo modFolder) + public void AddMod(DirectoryInfo modFolder, bool deleteDefaultMeta) { if (this.Any(m => m.ModPath.Name == modFolder.Name)) return; Creator.SplitMultiGroups(modFolder); - var mod = Creator.LoadMod(modFolder, true); + var mod = Creator.LoadMod(modFolder, true, deleteDefaultMeta); if (mod == null) return; @@ -141,7 +141,7 @@ public sealed class ModManager : ModStorage, IDisposable, IService var oldName = mod.Name; _communicator.ModPathChanged.Invoke(ModPathChangeType.StartingReload, mod, mod.ModPath, mod.ModPath); - if (!Creator.ReloadMod(mod, true, out var metaChange)) + if (!Creator.ReloadMod(mod, true, false, out var metaChange)) { Penumbra.Log.Warning(mod.Name.Length == 0 ? $"Reloading mod {oldName} has failed, new name is empty. Removing from loaded mods instead." @@ -206,7 +206,7 @@ public sealed class ModManager : ModStorage, IDisposable, IService dir.Refresh(); mod.ModPath = dir; - if (!Creator.ReloadMod(mod, false, out var metaChange)) + if (!Creator.ReloadMod(mod, false, false, out var metaChange)) { Penumbra.Log.Error($"Error reloading moved mod {mod.Name}."); return; @@ -332,7 +332,7 @@ public sealed class ModManager : ModStorage, IDisposable, IService var queue = new ConcurrentQueue(); Parallel.ForEach(BasePath.EnumerateDirectories(), options, dir => { - var mod = Creator.LoadMod(dir, false); + var mod = Creator.LoadMod(dir, false, false); if (mod != null) queue.Enqueue(mod); }); diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index c7eb7cc5..3e58c515 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -82,7 +82,7 @@ public static partial class ModMigration foreach (var (gamePath, swapPath) in swaps) mod.Default.FileSwaps.Add(gamePath, swapPath); - creator.IncorporateMetaChanges(mod.Default, mod.ModPath, true); + creator.IncorporateMetaChanges(mod.Default, mod.ModPath, true, true); foreach (var group in mod.Groups) saveService.ImmediateSave(new ModSaveGroup(group, creator.Config.ReplaceNonAsciiOnImport)); @@ -182,7 +182,7 @@ public static partial class ModMigration Description = option.OptionDesc, }; AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); - creator.IncorporateMetaChanges(subMod, mod.ModPath, false); + creator.IncorporateMetaChanges(subMod, mod.ModPath, false, true); return subMod; } @@ -196,7 +196,7 @@ public static partial class ModMigration Priority = priority, }; AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); - creator.IncorporateMetaChanges(subMod, mod.ModPath, false); + creator.IncorporateMetaChanges(subMod, mod.ModPath, false, true); return subMod; } diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 712630c6..7f18852d 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -39,7 +39,7 @@ public class ModGroupEditor( ImcModGroupEditor imcEditor, CommunicatorService communicator, SaveService saveService, - Configuration Config) : IService + Configuration config) : IService { public SingleModGroupEditor SingleEditor => singleEditor; @@ -57,7 +57,7 @@ public class ModGroupEditor( return; group.DefaultSettings = defaultOption; - saveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + saveService.QueueSave(new ModSaveGroup(group, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DefaultOptionChanged, group.Mod, group, null, null, -1); } @@ -68,9 +68,9 @@ public class ModGroupEditor( if (oldName == newName || !VerifyFileName(group.Mod, group, newName, true)) return; - saveService.ImmediateDelete(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + saveService.ImmediateDelete(new ModSaveGroup(group, config.ReplaceNonAsciiOnImport)); group.Name = newName; - saveService.ImmediateSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + saveService.ImmediateSave(new ModSaveGroup(group, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupRenamed, group.Mod, group, null, null, -1); } @@ -81,7 +81,7 @@ public class ModGroupEditor( var idx = group.GetIndex(); communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, null, null, -1); mod.Groups.RemoveAt(idx); - saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupDeleted, mod, null, null, null, idx); } @@ -93,7 +93,7 @@ public class ModGroupEditor( if (!mod.Groups.Move(idxFrom, groupIdxTo)) return; - saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupMoved, mod, group, null, null, idxFrom); } @@ -104,7 +104,7 @@ public class ModGroupEditor( return; group.Priority = newPriority; - saveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + saveService.QueueSave(new ModSaveGroup(group, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.PriorityChanged, group.Mod, group, null, null, -1); } @@ -115,7 +115,7 @@ public class ModGroupEditor( return; group.Description = newDescription; - saveService.QueueSave(new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + saveService.QueueSave(new ModSaveGroup(group, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, group.Mod, group, null, null, -1); } @@ -126,7 +126,7 @@ public class ModGroupEditor( return; option.Name = newName; - saveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + saveService.QueueSave(new ModSaveGroup(option.Group, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); } @@ -137,7 +137,7 @@ public class ModGroupEditor( return; option.Description = newDescription; - saveService.QueueSave(new ModSaveGroup(option.Group, Config.ReplaceNonAsciiOnImport)); + saveService.QueueSave(new ModSaveGroup(option.Group, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, option.Mod, option.Group, option, null, -1); } @@ -149,7 +149,7 @@ public class ModGroupEditor( communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); subMod.Manipulations.SetTo(manipulations); - saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(subMod, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } @@ -161,13 +161,13 @@ public class ModGroupEditor( communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); subMod.Files.SetTo(replacements); - saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(subMod, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } /// Forces a file save of the given container's group. public void ForceSave(IModDataContainer subMod, SaveType saveType = SaveType.Queue) - => saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + => saveService.Save(saveType, new ModSaveGroup(subMod, config.ReplaceNonAsciiOnImport)); /// Add additional file redirections to a given option, keeping already existing ones. Only fires an event if anything is actually added. public void AddFiles(IModDataContainer subMod, IReadOnlyDictionary additions) @@ -176,7 +176,7 @@ public class ModGroupEditor( subMod.Files.AddFrom(additions); if (oldCount != subMod.Files.Count) { - saveService.QueueSave(new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + saveService.QueueSave(new ModSaveGroup(subMod, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionFilesAdded, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } } @@ -189,7 +189,7 @@ public class ModGroupEditor( communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); subMod.FileSwaps.SetTo(swaps); - saveService.Save(saveType, new ModSaveGroup(subMod, Config.ReplaceNonAsciiOnImport)); + saveService.Save(saveType, new ModSaveGroup(subMod, config.ReplaceNonAsciiOnImport)); communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionSwapsChanged, (Mod)subMod.Mod, subMod.Group, null, subMod, -1); } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 0f4972e3..8cfdc9a7 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -10,6 +10,7 @@ using Penumbra.GameData.Data; using Penumbra.Import; using Penumbra.Import.Structs; using Penumbra.Meta; +using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; @@ -20,11 +21,12 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; public partial class ModCreator( - SaveService _saveService, + SaveService saveService, Configuration config, - ModDataEditor _dataEditor, - MetaFileManager _metaFileManager, - GamePathParser _gamePathParser) : IService + ModDataEditor dataEditor, + MetaFileManager metaFileManager, + GamePathParser gamePathParser, + ImcChecker imcChecker) : IService { public readonly Configuration Config = config; @@ -34,7 +36,7 @@ public partial class ModCreator( try { var newDir = CreateModFolder(basePath, newName, Config.ReplaceNonAsciiOnImport, true); - _dataEditor.CreateMeta(newDir, newName, Config.DefaultModAuthor, description, "1.0", string.Empty); + dataEditor.CreateMeta(newDir, newName, Config.DefaultModAuthor, description, "1.0", string.Empty); CreateDefaultFiles(newDir); return newDir; } @@ -46,7 +48,7 @@ public partial class ModCreator( } /// Load a mod by its directory. - public Mod? LoadMod(DirectoryInfo modPath, bool incorporateMetaChanges) + public Mod? LoadMod(DirectoryInfo modPath, bool incorporateMetaChanges, bool deleteDefaultMetaChanges) { modPath.Refresh(); if (!modPath.Exists) @@ -56,7 +58,7 @@ public partial class ModCreator( } var mod = new Mod(modPath); - if (ReloadMod(mod, incorporateMetaChanges, out _)) + if (ReloadMod(mod, incorporateMetaChanges, deleteDefaultMetaChanges, out _)) return mod; // Can not be base path not existing because that is checked before. @@ -65,21 +67,29 @@ public partial class ModCreator( } /// Reload a mod from its mod path. - public bool ReloadMod(Mod mod, bool incorporateMetaChanges, out ModDataChangeType modDataChange) + public bool ReloadMod(Mod mod, bool incorporateMetaChanges, bool deleteDefaultMetaChanges, out ModDataChangeType modDataChange) { modDataChange = ModDataChangeType.Deletion; if (!Directory.Exists(mod.ModPath.FullName)) return false; - modDataChange = _dataEditor.LoadMeta(this, mod); + modDataChange = dataEditor.LoadMeta(this, mod); if (modDataChange.HasFlag(ModDataChangeType.Deletion) || mod.Name.Length == 0) return false; - _dataEditor.LoadLocalData(mod); + dataEditor.LoadLocalData(mod); LoadDefaultOption(mod); LoadAllGroups(mod); if (incorporateMetaChanges) IncorporateAllMetaChanges(mod, true); + if (deleteDefaultMetaChanges && !Config.KeepDefaultMetaChanges) + { + foreach (var container in mod.AllDataContainers) + { + if (ModMetaEditor.DeleteDefaultValues(metaFileManager, imcChecker, container.Manipulations)) + saveService.ImmediateSaveSync(new ModSaveGroup(container, Config.ReplaceNonAsciiOnImport)); + } + } return true; } @@ -89,13 +99,13 @@ public partial class ModCreator( { mod.Groups.Clear(); var changes = false; - foreach (var file in _saveService.FileNames.GetOptionGroupFiles(mod)) + foreach (var file in saveService.FileNames.GetOptionGroupFiles(mod)) { var group = LoadModGroup(mod, file); if (group != null && mod.Groups.All(g => g.Name != group.Name)) { changes = changes - || _saveService.FileNames.OptionGroupFile(mod.ModPath.FullName, mod.Groups.Count, group.Name, true) + || saveService.FileNames.OptionGroupFile(mod.ModPath.FullName, mod.Groups.Count, group.Name, true) != Path.Combine(file.DirectoryName!, ReplaceBadXivSymbols(file.Name, true)); mod.Groups.Add(group); } @@ -106,13 +116,13 @@ public partial class ModCreator( } if (changes) - _saveService.SaveAllOptionGroups(mod, true, Config.ReplaceNonAsciiOnImport); + saveService.SaveAllOptionGroups(mod, true, Config.ReplaceNonAsciiOnImport); } /// Load the default option for a given mod. public void LoadDefaultOption(Mod mod) { - var defaultFile = _saveService.FileNames.OptionGroupFile(mod, -1, Config.ReplaceNonAsciiOnImport); + var defaultFile = saveService.FileNames.OptionGroupFile(mod, -1, Config.ReplaceNonAsciiOnImport); try { var jObject = File.Exists(defaultFile) ? JObject.Parse(File.ReadAllText(defaultFile)) : new JObject(); @@ -157,7 +167,7 @@ public partial class ModCreator( List deleteList = new(); foreach (var subMod in mod.AllDataContainers) { - var (localChanges, localDeleteList) = IncorporateMetaChanges(subMod, mod.ModPath, false); + var (localChanges, localDeleteList) = IncorporateMetaChanges(subMod, mod.ModPath, false, true); changes |= localChanges; if (delete) deleteList.AddRange(localDeleteList); @@ -168,8 +178,8 @@ public partial class ModCreator( if (!changes) return; - _saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); - _saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); + saveService.SaveAllOptionGroups(mod, false, Config.ReplaceNonAsciiOnImport); + saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); } @@ -177,7 +187,7 @@ public partial class ModCreator( /// If .meta or .rgsp files are encountered, parse them and incorporate their meta changes into the mod. /// If delete is true, the files are deleted afterwards. /// - public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete) + public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete, bool deleteDefault) { var deleteList = new List(); var oldSize = option.Manipulations.Count; @@ -194,7 +204,7 @@ public partial class ModCreator( if (!file.Exists) continue; - var meta = new TexToolsMeta(_metaFileManager, _gamePathParser, File.ReadAllBytes(file.FullName), + var meta = new TexToolsMeta(metaFileManager, gamePathParser, File.ReadAllBytes(file.FullName), Config.KeepDefaultMetaChanges); Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); @@ -207,7 +217,7 @@ public partial class ModCreator( if (!file.Exists) continue; - var rgsp = TexToolsMeta.FromRgspFile(_metaFileManager, file.FullName, File.ReadAllBytes(file.FullName), + var rgsp = TexToolsMeta.FromRgspFile(metaFileManager, file.FullName, File.ReadAllBytes(file.FullName), Config.KeepDefaultMetaChanges); Penumbra.Log.Verbose( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); @@ -223,7 +233,11 @@ public partial class ModCreator( } DeleteDeleteList(deleteList, delete); - return (oldSize < option.Manipulations.Count, deleteList); + var changes = oldSize < option.Manipulations.Count; + if (deleteDefault && !Config.KeepDefaultMetaChanges) + changes |= ModMetaEditor.DeleteDefaultValues(metaFileManager, imcChecker, option.Manipulations); + + return (changes, deleteList); } /// @@ -250,7 +264,7 @@ public partial class ModCreator( group.Priority = priority; group.DefaultSettings = defaultSettings; group.OptionData.AddRange(subMods.Select(s => s.Clone(group))); - _saveService.ImmediateSaveSync(ModSaveGroup.WithoutMod(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); + saveService.ImmediateSaveSync(ModSaveGroup.WithoutMod(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } case GroupType.Single: @@ -260,7 +274,7 @@ public partial class ModCreator( group.Priority = priority; group.DefaultSettings = defaultSettings; group.OptionData.AddRange(subMods.Select(s => s.ConvertToSingle(group))); - _saveService.ImmediateSaveSync(ModSaveGroup.WithoutMod(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); + saveService.ImmediateSaveSync(ModSaveGroup.WithoutMod(baseFolder, group, index, Config.ReplaceNonAsciiOnImport)); break; } } @@ -277,7 +291,8 @@ public partial class ModCreator( foreach (var (_, gamePath, file) in list) mod.Files.TryAdd(gamePath, file); - IncorporateMetaChanges(mod, baseFolder, true); + IncorporateMetaChanges(mod, baseFolder, true, true); + return mod; } @@ -288,15 +303,15 @@ public partial class ModCreator( internal void CreateDefaultFiles(DirectoryInfo directory) { var mod = new Mod(directory); - ReloadMod(mod, false, out _); + ReloadMod(mod, false, false, out _); foreach (var file in mod.FindUnusedFiles()) { if (Utf8GamePath.FromFile(new FileInfo(file.FullName), directory, out var gamePath)) mod.Default.Files.TryAdd(gamePath, file); } - IncorporateMetaChanges(mod.Default, directory, true); - _saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); + IncorporateMetaChanges(mod.Default, directory, true, true); + saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); } /// Return the name of a new valid directory based on the base directory and the given name. @@ -333,7 +348,7 @@ public partial class ModCreator( { var mod = new Mod(baseDir); - var files = _saveService.FileNames.GetOptionGroupFiles(mod).ToList(); + var files = saveService.FileNames.GetOptionGroupFiles(mod).ToList(); var idx = 0; var reorder = false; foreach (var groupFile in files) diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index e4049482..b5499624 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -97,7 +97,7 @@ public class TemporaryMod : IMod defaultMod.Manipulations.UnionWith(manips); saveService.ImmediateSaveSync(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); - modManager.AddMod(dir); + modManager.AddMod(dir, false); Penumbra.Log.Information( $"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identifier}."); } diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index b75c5aef..6ed1b55d 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -281,7 +281,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService if (newDir == null) return; - _modManager.AddMod(newDir); + _modManager.AddMod(newDir, false); var mod = _modManager[^1]; if (!_swapData.WriteMod(_modManager, mod, mod.Default, _useFileSwaps ? ItemSwapContainer.WriteType.UseSwaps : ItemSwapContainer.WriteType.NoSwaps)) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 2f76340b..8bdd95ab 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -180,7 +180,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Thu, 29 Aug 2024 18:38:09 +0200 Subject: [PATCH 0897/1381] Stop raising errors when compressing the deleted files after updating Heliosphere mods. --- OtterGui | 2 +- Penumbra/Api/Api/ModsApi.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/OtterGui b/OtterGui index bfbde4f8..17bd4b75 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit bfbde4f8aa6acc8eb3ed8bc419d5ae2afc77b5f1 +Subproject commit 17bd4b75b6d7750c92b65caf09715886d4df57cf diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 31f20c5e..64e201be 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -91,7 +91,7 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable if (_config.UseFileSystemCompression) new FileCompactor(Penumbra.Log).StartMassCompact(dir.EnumerateFiles("*.*", SearchOption.AllDirectories), - CompressionAlgorithm.Xpress8K); + CompressionAlgorithm.Xpress8K, false); return ApiHelpers.Return(PenumbraApiEc.Success, args); } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 27c7f2ed..9d8ea21c 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -816,13 +816,13 @@ public class SettingsTab : ITab, IUiService if (ImGuiUtil.DrawDisabledButton("Compress Existing Files", Vector2.Zero, "Try to compress all files in your root directory. This will take a while.", _compactor.MassCompactRunning || !_modManager.Valid)) - _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K); + _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K, true); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Decompress Existing Files", Vector2.Zero, "Try to decompress all files in your root directory. This will take a while.", _compactor.MassCompactRunning || !_modManager.Valid)) - _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.None); + _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.None, true); if (_compactor.MassCompactRunning) { From 5c5e45114f25f9429d8757b6edf852ecc37173c9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 29 Aug 2024 18:38:37 +0200 Subject: [PATCH 0898/1381] Make loading mods for advanced editing async. --- Penumbra/Mods/Editor/ModEditor.cs | 65 +++++++++---- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 102 +++++++++++++++----- 2 files changed, 124 insertions(+), 43 deletions(-) diff --git a/Penumbra/Mods/Editor/ModEditor.cs b/Penumbra/Mods/Editor/ModEditor.cs index cacb7f88..19ca7022 100644 --- a/Penumbra/Mods/Editor/ModEditor.cs +++ b/Penumbra/Mods/Editor/ModEditor.cs @@ -25,6 +25,21 @@ public class ModEditor( public readonly MdlMaterialEditor MdlMaterialEditor = mdlMaterialEditor; public readonly FileCompactor Compactor = compactor; + + public bool IsLoading + { + get + { + lock (_lock) + { + return _loadingMod is { IsCompleted: false }; + } + } + } + + private readonly object _lock = new(); + private Task? _loadingMod; + public Mod? Mod { get; private set; } public int GroupIdx { get; private set; } public int DataIdx { get; private set; } @@ -32,28 +47,42 @@ public class ModEditor( public IModGroup? Group { get; private set; } public IModDataContainer? Option { get; private set; } - public void LoadMod(Mod mod) - => LoadMod(mod, -1, 0); - - public void LoadMod(Mod mod, int groupIdx, int dataIdx) + public async Task LoadMod(Mod mod, int groupIdx, int dataIdx) { - Mod = mod; - LoadOption(groupIdx, dataIdx, true); - Files.UpdateAll(mod, Option!); - SwapEditor.Revert(Option!); - MetaEditor.Load(Mod!, Option!); - Duplicates.Clear(); - MdlMaterialEditor.ScanModels(Mod!); + await AppendTask(() => + { + Mod = mod; + LoadOption(groupIdx, dataIdx, true); + Files.UpdateAll(mod, Option!); + SwapEditor.Revert(Option!); + MetaEditor.Load(Mod!, Option!); + Duplicates.Clear(); + MdlMaterialEditor.ScanModels(Mod!); + }); } - public void LoadOption(int groupIdx, int dataIdx) + private Task AppendTask(Action run) { - LoadOption(groupIdx, dataIdx, true); - SwapEditor.Revert(Option!); - Files.UpdatePaths(Mod!, Option!); - MetaEditor.Load(Mod!, Option!); - FileEditor.Clear(); - Duplicates.Clear(); + lock (_lock) + { + if (_loadingMod == null || _loadingMod.IsCompleted) + return _loadingMod = Task.Run(run); + + return _loadingMod = _loadingMod.ContinueWith(_ => run()); + } + } + + public async Task LoadOption(int groupIdx, int dataIdx) + { + await AppendTask(() => + { + LoadOption(groupIdx, dataIdx, true); + SwapEditor.Revert(Option!); + Files.UpdatePaths(Mod!, Option!); + MetaEditor.Load(Mod!, Option!); + FileEditor.Clear(); + Duplicates.Clear(); + }); } /// Load the correct option by indices for the currently loaded mod if possible, unload if not. diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 7bb067d8..f2fe8b9e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -8,6 +8,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -51,34 +52,68 @@ public partial class ModEditWindow : Window, IDisposable, IUiService private Vector2 _iconSize = Vector2.Zero; private bool _allowReduplicate; - public Mod? Mod { get; private set; } + public Mod? Mod { get; private set; } + + + public bool IsLoading + { + get + { + lock (_lock) + { + return _editor.IsLoading || _loadingMod is { IsCompleted: false }; + } + } + } + + private readonly object _lock = new(); + private Task? _loadingMod; + + + private void AppendTask(Action run) + { + lock (_lock) + { + if (_loadingMod == null || _loadingMod.IsCompleted) + _loadingMod = Task.Run(run); + else + _loadingMod = _loadingMod.ContinueWith(_ => run()); + } + } public void ChangeMod(Mod mod) { if (mod == Mod) return; - _editor.LoadMod(mod, -1, 0); - Mod = mod; - - SizeConstraints = new WindowSizeConstraints + WindowName = $"{mod.Name} (LOADING){WindowBaseLabel}"; + AppendTask(() => { - MinimumSize = new Vector2(1240, 600), - MaximumSize = 4000 * Vector2.One, - }; - _selectedFiles.Clear(); - _modelTab.Reset(); - _materialTab.Reset(); - _shaderPackageTab.Reset(); - _itemSwapTab.UpdateMod(mod, _activeCollections.Current[mod.Index].Settings); - UpdateModels(); - _forceTextureStartPath = true; + _editor.LoadMod(mod, -1, 0).Wait(); + Mod = mod; + + SizeConstraints = new WindowSizeConstraints + { + MinimumSize = new Vector2(1240, 600), + MaximumSize = 4000 * Vector2.One, + }; + _selectedFiles.Clear(); + _modelTab.Reset(); + _materialTab.Reset(); + _shaderPackageTab.Reset(); + _itemSwapTab.UpdateMod(mod, _activeCollections.Current[mod.Index].Settings); + UpdateModels(); + _forceTextureStartPath = true; + }); } public void ChangeOption(IModDataContainer? subMod) { - var (groupIdx, dataIdx) = subMod?.GetDataIndices() ?? (-1, 0); - _editor.LoadOption(groupIdx, dataIdx); + AppendTask(() => + { + var (groupIdx, dataIdx) = subMod?.GetDataIndices() ?? (-1, 0); + _editor.LoadOption(groupIdx, dataIdx).Wait(); + }); } public void UpdateModels() @@ -92,6 +127,9 @@ public partial class ModEditWindow : Window, IDisposable, IUiService public override void PreDraw() { + if (IsLoading) + return; + using var performance = _performance.Measure(PerformanceType.UiAdvancedWindow); var sb = new StringBuilder(256); @@ -144,13 +182,16 @@ public partial class ModEditWindow : Window, IDisposable, IUiService public override void OnClose() { - _left.Dispose(); - _right.Dispose(); - _materialTab.Reset(); - _modelTab.Reset(); - _shaderPackageTab.Reset(); _config.Ephemeral.AdvancedEditingOpen = false; _config.Ephemeral.Save(); + AppendTask(() => + { + _left.Dispose(); + _right.Dispose(); + _materialTab.Reset(); + _modelTab.Reset(); + _shaderPackageTab.Reset(); + }); } public override void Draw() @@ -163,6 +204,17 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _config.Ephemeral.Save(); } + if (IsLoading) + { + var radius = 100 * ImUtf8.GlobalScale; + var thickness = (int) (20 * ImUtf8.GlobalScale); + var offsetX = ImGui.GetContentRegionAvail().X / 2 - radius; + var offsetY = ImGui.GetContentRegionAvail().Y / 2 - radius; + ImGui.SetCursorPos(ImGui.GetCursorPos() + new Vector2(offsetX, offsetY)); + ImUtf8.Spinner("##spinner"u8, radius, thickness, ImGui.GetColorU32(ImGuiCol.Text)); + return; + } + using var tabBar = ImRaii.TabBar("##tabs"); if (!tabBar) return; @@ -405,14 +457,14 @@ public partial class ModEditWindow : Window, IDisposable, IUiService if (ImGuiUtil.DrawDisabledButton(defaultOption, width, "Switch to the default option for the mod.\nThis resets unsaved changes.", _editor.Option is DefaultSubMod)) { - _editor.LoadOption(-1, 0); + _editor.LoadOption(-1, 0).Wait(); ret = true; } ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Refresh Data", width, "Refresh data for the current option.\nThis resets unsaved changes.", false)) { - _editor.LoadMod(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx); + _editor.LoadMod(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx).Wait(); ret = true; } @@ -430,7 +482,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService if (ImGui.Selectable(option.GetFullName(), option == _editor.Option)) { var (groupIdx, dataIdx) = option.GetDataIndices(); - _editor.LoadOption(groupIdx, dataIdx); + _editor.LoadOption(groupIdx, dataIdx).Wait(); ret = true; } } From de3644e9e131baf5f4f953bc0d034a116c7da4d3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 29 Aug 2024 18:46:37 +0200 Subject: [PATCH 0899/1381] Make BC4 textures importable. --- Penumbra/Import/Textures/TexFileParser.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index ae4a39c0..1bf282e5 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -177,6 +177,7 @@ public static class TexFileParser DXGIFormat.BC1UNorm => TexFile.TextureFormat.BC1, DXGIFormat.BC2UNorm => TexFile.TextureFormat.BC2, DXGIFormat.BC3UNorm => TexFile.TextureFormat.BC3, + DXGIFormat.BC4UNorm => (TexFile.TextureFormat)0x6120, DXGIFormat.BC5UNorm => TexFile.TextureFormat.BC5, DXGIFormat.BC7UNorm => TexFile.TextureFormat.BC7, DXGIFormat.R16G16B16A16Typeless => TexFile.TextureFormat.D16, @@ -202,6 +203,7 @@ public static class TexFileParser TexFile.TextureFormat.BC1 => DXGIFormat.BC1UNorm, TexFile.TextureFormat.BC2 => DXGIFormat.BC2UNorm, TexFile.TextureFormat.BC3 => DXGIFormat.BC3UNorm, + (TexFile.TextureFormat)0x6120 => DXGIFormat.BC4UNorm, TexFile.TextureFormat.BC5 => DXGIFormat.BC5UNorm, TexFile.TextureFormat.BC7 => DXGIFormat.BC7UNorm, TexFile.TextureFormat.D16 => DXGIFormat.R16G16B16A16Typeless, From 2a7d2ef0d5cef009c60a701235a1786e56d191b2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 29 Aug 2024 18:58:30 +0200 Subject: [PATCH 0900/1381] Allow reading BC6. --- Penumbra/Import/Textures/TexFileParser.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 1bf282e5..0d817fa1 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -177,8 +177,9 @@ public static class TexFileParser DXGIFormat.BC1UNorm => TexFile.TextureFormat.BC1, DXGIFormat.BC2UNorm => TexFile.TextureFormat.BC2, DXGIFormat.BC3UNorm => TexFile.TextureFormat.BC3, - DXGIFormat.BC4UNorm => (TexFile.TextureFormat)0x6120, + DXGIFormat.BC4UNorm => (TexFile.TextureFormat)0x6120, // TODO: upstream to Lumina DXGIFormat.BC5UNorm => TexFile.TextureFormat.BC5, + DXGIFormat.BC6HUF16 => (TexFile.TextureFormat)0x6330, // TODO: upstream to Lumina DXGIFormat.BC7UNorm => TexFile.TextureFormat.BC7, DXGIFormat.R16G16B16A16Typeless => TexFile.TextureFormat.D16, DXGIFormat.R24G8Typeless => TexFile.TextureFormat.D24S8, @@ -203,8 +204,9 @@ public static class TexFileParser TexFile.TextureFormat.BC1 => DXGIFormat.BC1UNorm, TexFile.TextureFormat.BC2 => DXGIFormat.BC2UNorm, TexFile.TextureFormat.BC3 => DXGIFormat.BC3UNorm, - (TexFile.TextureFormat)0x6120 => DXGIFormat.BC4UNorm, + (TexFile.TextureFormat)0x6120 => DXGIFormat.BC4UNorm, // TODO: upstream to Lumina TexFile.TextureFormat.BC5 => DXGIFormat.BC5UNorm, + (TexFile.TextureFormat)0x6330 => DXGIFormat.BC6HUF16, // TODO: upstream to Lumina TexFile.TextureFormat.BC7 => DXGIFormat.BC7UNorm, TexFile.TextureFormat.D16 => DXGIFormat.R16G16B16A16Typeless, TexFile.TextureFormat.D24S8 => DXGIFormat.R24G8Typeless, From 176001195ba16d69c4540d2dbed9607932337ee6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 29 Aug 2024 21:13:33 +0200 Subject: [PATCH 0901/1381] Improve mod filters. --- OtterGui | 2 +- Penumbra/Import/Textures/TexFileParser.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 23 +++++---- Penumbra/UI/ModsTab/ModFilter.cs | 49 ++++++++++---------- 4 files changed, 41 insertions(+), 35 deletions(-) diff --git a/OtterGui b/OtterGui index 17bd4b75..3e6b0857 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 17bd4b75b6d7750c92b65caf09715886d4df57cf +Subproject commit 3e6b085749741f35dd6732c33d0720c6a51ebb97 diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 0d817fa1..979e4d3c 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -204,7 +204,7 @@ public static class TexFileParser TexFile.TextureFormat.BC1 => DXGIFormat.BC1UNorm, TexFile.TextureFormat.BC2 => DXGIFormat.BC2UNorm, TexFile.TextureFormat.BC3 => DXGIFormat.BC3UNorm, - (TexFile.TextureFormat)0x6120 => DXGIFormat.BC4UNorm, // TODO: upstream to Lumina + (TexFile.TextureFormat)0x6120 => DXGIFormat.BC4UNorm, // TODO: upstream to Lumina TexFile.TextureFormat.BC5 => DXGIFormat.BC5UNorm, (TexFile.TextureFormat)0x6330 => DXGIFormat.BC6HUF16, // TODO: upstream to Lumina TexFile.TextureFormat.BC7 => DXGIFormat.BC7UNorm, diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 8bdd95ab..7a165feb 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -9,6 +9,8 @@ using OtterGui.Filesystem; using OtterGui.FileSystem.Selector; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; +using OtterGui.Text.Widget; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -84,8 +86,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector filter switch - { - ModFilter.Enabled => "Enabled", - ModFilter.Disabled => "Disabled", - ModFilter.Favorite => "Favorite", - ModFilter.NotFavorite => "No Favorite", - ModFilter.NoConflict => "No Conflicts", - ModFilter.SolvedConflict => "Solved Conflicts", - ModFilter.UnsolvedConflict => "Unsolved Conflicts", - ModFilter.HasNoMetaManipulations => "No Meta Manipulations", - ModFilter.HasMetaManipulations => "Meta Manipulations", - ModFilter.HasNoFileSwaps => "No File Swaps", - ModFilter.HasFileSwaps => "File Swaps", - ModFilter.HasNoConfig => "No Configuration", - ModFilter.HasConfig => "Configuration", - ModFilter.HasNoFiles => "No Files", - ModFilter.HasFiles => "Files", - ModFilter.IsNew => "Newly Imported", - ModFilter.NotNew => "Not Newly Imported", - ModFilter.Inherited => "Inherited Configuration", - ModFilter.Uninherited => "Own Configuration", - ModFilter.Undefined => "Not Configured", - _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), - }; + public static IReadOnlyList<(ModFilter On, ModFilter Off, string Name)> TriStatePairs = + [ + (ModFilter.Enabled, ModFilter.Disabled, "Enabled"), + (ModFilter.IsNew, ModFilter.NotNew, "Newly Imported"), + (ModFilter.Favorite, ModFilter.NotFavorite, "Favorite"), + (ModFilter.HasConfig, ModFilter.HasNoConfig, "Has Options"), + (ModFilter.HasFiles, ModFilter.HasNoFiles, "Has Redirections"), + (ModFilter.HasMetaManipulations, ModFilter.HasNoMetaManipulations, "Has Meta Manipulations"), + (ModFilter.HasFileSwaps, ModFilter.HasNoFileSwaps, "Has File Swaps"), + ]; + + public static IReadOnlyList> Groups = + [ + [ + (ModFilter.NoConflict, "Has No Conflicts"), + (ModFilter.SolvedConflict, "Has Solved Conflicts"), + (ModFilter.UnsolvedConflict, "Has Unsolved Conflicts"), + ], + [ + (ModFilter.Undefined, "Not Configured"), + (ModFilter.Inherited, "Inherited Configuration"), + (ModFilter.Uninherited, "Own Configuration"), + ], + ]; } From ff3e5410aac9e23606317e179f6278e710cb11ee Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 29 Aug 2024 19:18:17 +0000 Subject: [PATCH 0902/1381] [CI] Updating repo.json for testing_1.2.1.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 5a274d73..6f9b8c69 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.1", + "TestingAssemblyVersion": "1.2.1.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From fb144d0b74ce1b263eb3e69625c37518e3725a1b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 31 Aug 2024 14:20:19 +0200 Subject: [PATCH 0903/1381] Cleanup. --- Penumbra/Import/Textures/TexFileParser.cs | 4 ++-- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 979e4d3c..220095c1 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -179,7 +179,7 @@ public static class TexFileParser DXGIFormat.BC3UNorm => TexFile.TextureFormat.BC3, DXGIFormat.BC4UNorm => (TexFile.TextureFormat)0x6120, // TODO: upstream to Lumina DXGIFormat.BC5UNorm => TexFile.TextureFormat.BC5, - DXGIFormat.BC6HUF16 => (TexFile.TextureFormat)0x6330, // TODO: upstream to Lumina + DXGIFormat.BC6HSF16 => (TexFile.TextureFormat)0x6330, // TODO: upstream to Lumina DXGIFormat.BC7UNorm => TexFile.TextureFormat.BC7, DXGIFormat.R16G16B16A16Typeless => TexFile.TextureFormat.D16, DXGIFormat.R24G8Typeless => TexFile.TextureFormat.D24S8, @@ -206,7 +206,7 @@ public static class TexFileParser TexFile.TextureFormat.BC3 => DXGIFormat.BC3UNorm, (TexFile.TextureFormat)0x6120 => DXGIFormat.BC4UNorm, // TODO: upstream to Lumina TexFile.TextureFormat.BC5 => DXGIFormat.BC5UNorm, - (TexFile.TextureFormat)0x6330 => DXGIFormat.BC6HUF16, // TODO: upstream to Lumina + (TexFile.TextureFormat)0x6330 => DXGIFormat.BC6HSF16, // TODO: upstream to Lumina TexFile.TextureFormat.BC7 => DXGIFormat.BC7UNorm, TexFile.TextureFormat.D16 => DXGIFormat.R16G16B16A16Typeless, TexFile.TextureFormat.D24S8 => DXGIFormat.R24G8Typeless, diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 81a33db6..07a54391 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -156,7 +156,7 @@ public class ModMetaEditor( } } - if (count <= 0) + if (count == 0) return false; Penumbra.Log.Debug($"Deleted {count} default-valued meta-entries from a mod option."); From 04582ba00b8fedfb32a8ad7fbed0230ea89126f7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 31 Aug 2024 14:20:31 +0200 Subject: [PATCH 0904/1381] Add CustomArmor to UI events. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index a38e9bcf..97e9f427 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit a38e9bcfb80c456102945bbb4c59f5621cae0442 +Subproject commit 97e9f427406f82a59ddef764b44ecea654a51623 diff --git a/Penumbra.GameData b/Penumbra.GameData index c43c5cac..bb281fb0 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c43c5cac4cee092bf0aed8d46bab112b037ef8f2 +Subproject commit bb281fb01d88d6fd815a286f87049978ef05de59 From 75858a61b5092b1567e332417610ef36a4f7e122 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 31 Aug 2024 14:20:44 +0200 Subject: [PATCH 0905/1381] Fix MetaManipulations not resetting count when clearing. --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 1093c6c5..70d4fd47 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -69,6 +69,7 @@ public class MetaDictionary public void Clear() { + Count = 0; _imc.Clear(); _eqp.Clear(); _eqdp.Clear(); From 6b858dc5ac9d9cd967601a3fdac91048c87bf7c5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 31 Aug 2024 14:23:34 +0200 Subject: [PATCH 0906/1381] Hmpf. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index bb281fb0..66bc00dc 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit bb281fb01d88d6fd815a286f87049978ef05de59 +Subproject commit 66bc00dc8517204e58c6515af5aec0ba6d196716 From 1b17404876d9248c77649b7831eda57332f84f96 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 31 Aug 2024 20:52:01 +0200 Subject: [PATCH 0907/1381] Fix small issue with changed item tooltips. --- Penumbra/Penumbra.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 6f0b63ce..b6b19ef2 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -114,7 +114,7 @@ public class Penumbra : IDalamudPlugin var itemSheet = _services.GetService().GetExcelSheet()!; _communicatorService.ChangedItemHover.Subscribe(it => { - if (it is IdentifiedItem) + if (it is IdentifiedItem { Item.Id.IsItem: true }) ImGui.TextUnformatted("Left Click to create an item link in chat."); }, ChangedItemHover.Priority.Link); From 22cbecc6a459a3700b0d5f663847f098c69963aa Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 8 Sep 2024 22:48:15 +0200 Subject: [PATCH 0908/1381] Add Page to mod group data for TT interop. --- Penumbra/Mods/Groups/IModGroup.cs | 23 +++++++++++++++-------- Penumbra/Mods/Groups/ImcModGroup.cs | 1 + Penumbra/Mods/Groups/MultiModGroup.cs | 1 + Penumbra/Mods/Groups/SingleModGroup.cs | 1 + 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index c5654019..a6f6e20d 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -24,14 +24,21 @@ public interface IModGroup { public const int MaxMultiOptions = 32; - public Mod Mod { get; } - public string Name { get; set; } - public string Description { get; set; } - public string Image { get; set; } - public GroupType Type { get; } - public GroupDrawBehaviour Behaviour { get; } - public ModPriority Priority { get; set; } - public Setting DefaultSettings { get; set; } + public Mod Mod { get; } + public string Name { get; set; } + public string Description { get; set; } + + /// Unused in Penumbra but for better TexTools interop. + public string Image { get; set; } + + public GroupType Type { get; } + public GroupDrawBehaviour Behaviour { get; } + public ModPriority Priority { get; set; } + + /// Unused in Penumbra but for better TexTools interop. + public int Page { get; set; } + + public Setting DefaultSettings { get; set; } public FullPath? FindBestMatch(Utf8GamePath gamePath); public IModOption? AddOption(string name, string description = ""); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index d42804ba..2b020184 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -29,6 +29,7 @@ public class ImcModGroup(Mod mod) : IModGroup => GroupDrawBehaviour.MultiSelection; public ModPriority Priority { get; set; } = ModPriority.Default; + public int Page { get; set; } public Setting DefaultSettings { get; set; } = Setting.Zero; public ImcIdentifier Identifier; diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 9cf7e6a3..24dcc849 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -28,6 +28,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public string Description { get; set; } = string.Empty; public string Image { get; set; } = string.Empty; public ModPriority Priority { get; set; } + public int Page { get; set; } public Setting DefaultSettings { get; set; } public readonly List OptionData = []; diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index 723cd5b1..fddb96d6 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -26,6 +26,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public string Description { get; set; } = string.Empty; public string Image { get; set; } = string.Empty; public ModPriority Priority { get; set; } + public int Page { get; set; } public Setting DefaultSettings { get; set; } public readonly List OptionData = []; From bd59591ed8650c5ae544fa3546fbc5e4fa5e813b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 8 Sep 2024 23:42:19 +0200 Subject: [PATCH 0909/1381] Add display of ImportDate and allow resetting it, add button to open local data json. --- Penumbra/Mods/Manager/ModDataEditor.cs | 11 ++++++ Penumbra/Mods/ModCreator.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 19 +++++----- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 37 ++++++++++++++++++++ 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 7a0467d0..933620d9 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -249,6 +249,17 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic communicatorService.ModDataChanged.Invoke(ModDataChangeType.Favorite, mod, null); } + public void ResetModImportDate(Mod mod) + { + var newDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + if (mod.ImportDate == newDate) + return; + + mod.ImportDate = newDate; + saveService.QueueSave(new ModLocalData(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.ImportDate, mod, null); + } + public void ChangeModNote(Mod mod, string newNote) { if (mod.Note == newNote) diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 8cfdc9a7..fe027ca4 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -77,7 +77,7 @@ public partial class ModCreator( if (modDataChange.HasFlag(ModDataChangeType.Deletion) || mod.Name.Length == 0) return false; - dataEditor.LoadLocalData(mod); + modDataChange |= dataEditor.LoadLocalData(mod); LoadDefaultOption(mod); LoadAllGroups(mod); if (incorporateMetaChanges) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 7a165feb..0781312c 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -447,16 +447,15 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Mon, 9 Sep 2024 14:10:54 +0200 Subject: [PATCH 0910/1381] Allow copying paths out of the resource logger. --- .../ResourceWatcher/ResourceWatcherTable.cs | 50 +++++++++++-------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 33e301ae..2bb71b87 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -4,6 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Table; +using OtterGui.Text; using Penumbra.Enums; using Penumbra.Interop.Structs; using Penumbra.String; @@ -52,36 +53,41 @@ internal sealed class ResourceWatcherTable : Table private static unsafe void DrawByteString(CiByteString path, float length) { - Vector2 vec; - ImGuiNative.igCalcTextSize(&vec, path.Path, path.Path + path.Length, 0, 0); - if (vec.X <= length) + if (path.IsEmpty) + return; + + var size = ImUtf8.CalcTextSize(path.Span); + var clicked = false; + if (size.X <= length) { - ImGuiNative.igTextUnformatted(path.Path, path.Path + path.Length); + clicked = ImUtf8.Selectable(path.Span); } else { - var fileName = path.LastIndexOf((byte)'/'); - CiByteString shortPath; - if (fileName != -1) + var fileName = path.LastIndexOf((byte)'/'); + using (ImRaii.Group()) { - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(2 * UiHelpers.Scale)); - using var font = ImRaii.PushFont(UiBuilder.IconFont); - ImGui.TextUnformatted(FontAwesomeIcon.EllipsisH.ToIconString()); - ImGui.SameLine(); - shortPath = path.Substring(fileName, path.Length - fileName); - } - else - { - shortPath = path; + CiByteString shortPath; + if (fileName != -1) + { + using var font = ImRaii.PushFont(UiBuilder.IconFont); + clicked = ImUtf8.Selectable(FontAwesomeIcon.EllipsisH.ToIconString()); + ImUtf8.SameLineInner(); + shortPath = path.Substring(fileName, path.Length - fileName); + } + else + { + shortPath = path; + } + + clicked |= ImUtf8.Selectable(shortPath.Span, false, ImGuiSelectableFlags.AllowItemOverlap); } - ImGuiNative.igTextUnformatted(shortPath.Path, shortPath.Path + shortPath.Length); - if (ImGui.IsItemClicked()) - ImGuiNative.igSetClipboardText(path.Path); - - if (ImGui.IsItemHovered()) - ImGuiNative.igSetTooltip(path.Path); + ImUtf8.HoverTooltip(path.Span); } + + if (clicked) + ImUtf8.SetClipboardText(path.Span); } private sealed class RecordTypeColumn : ColumnFlags From 10ce5da8c9bb5d2b226a940a23f1ef57026aec81 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 9 Sep 2024 13:42:42 +0000 Subject: [PATCH 0911/1381] [CI] Updating repo.json for testing_1.2.1.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 6f9b8c69..cdd622c9 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.2", + "TestingAssemblyVersion": "1.2.1.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 26371d42f75768a0bda28da0f2fc8976075fdb82 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 9 Sep 2024 16:51:23 +0200 Subject: [PATCH 0912/1381] Be less dumb. --- Penumbra/Mods/Groups/ImcModGroup.cs | 7 +------ Penumbra/Mods/Groups/ModSaveGroup.cs | 17 +++++++++++++++++ Penumbra/Mods/Groups/MultiModGroup.cs | 13 ++++--------- Penumbra/Mods/Groups/SingleModGroup.cs | 13 ++++--------- 4 files changed, 26 insertions(+), 24 deletions(-) diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 2b020184..f8b4b2ef 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -170,14 +170,10 @@ public class ImcModGroup(Mod mod) : IModGroup var identifier = ImcIdentifier.FromJson(json[nameof(Identifier)] as JObject); var ret = new ImcModGroup(mod) { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Image = json[nameof(Image)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), AllVariants = json[nameof(AllVariants)]?.ToObject() ?? false, }; - if (ret.Name.Length == 0) + if (!ModSaveGroup.ReadJsonBase(json, ret)) return null; if (!identifier.HasValue || ret.DefaultEntry.MaterialId == 0) @@ -216,7 +212,6 @@ public class ImcModGroup(Mod mod) : IModGroup } ret.Identifier = identifier.Value; - ret.DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero; ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); return ret; } diff --git a/Penumbra/Mods/Groups/ModSaveGroup.cs b/Penumbra/Mods/Groups/ModSaveGroup.cs index c465822b..bda70b54 100644 --- a/Penumbra/Mods/Groups/ModSaveGroup.cs +++ b/Penumbra/Mods/Groups/ModSaveGroup.cs @@ -1,4 +1,7 @@ using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Files.ShaderStructs; +using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; using Penumbra.Services; @@ -90,6 +93,8 @@ public readonly struct ModSaveGroup : ISavable jWriter.WriteValue(group.Description); jWriter.WritePropertyName(nameof(group.Image)); jWriter.WriteValue(group.Image); + jWriter.WritePropertyName(nameof(group.Page)); + jWriter.WriteValue(group.Page); jWriter.WritePropertyName(nameof(group.Priority)); jWriter.WriteValue(group.Priority.Value); jWriter.WritePropertyName(nameof(group.Type)); @@ -97,4 +102,16 @@ public readonly struct ModSaveGroup : ISavable jWriter.WritePropertyName(nameof(group.DefaultSettings)); jWriter.WriteValue(group.DefaultSettings.Value); } + + public static bool ReadJsonBase(JObject json, IModGroup group) + { + group.Name = json[nameof(IModGroup.Name)]?.ToObject() ?? string.Empty; + group.Description = json[nameof(IModGroup.Description)]?.ToObject() ?? string.Empty; + group.Image = json[nameof(IModGroup.Image)]?.ToObject() ?? string.Empty; + group.Page = json[nameof(IModGroup.Page)]?.ToObject() ?? 0; + group.Priority = json[nameof(IModGroup.Priority)]?.ToObject() ?? ModPriority.Default; + group.DefaultSettings = json[nameof(IModGroup.DefaultSettings)]?.ToObject() ?? Setting.Zero; + + return group.Name.Length > 0; + } } diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 24dcc849..0c9aa805 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -67,15 +67,8 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup public static MultiModGroup? Load(Mod mod, JObject json) { - var ret = new MultiModGroup(mod) - { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Image = json[nameof(Image)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, - DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, - }; - if (ret.Name.Length == 0) + var ret = new MultiModGroup(mod); + if (!ModSaveGroup.ReadJsonBase(json, ret)) return null; var options = json["Options"]; @@ -106,6 +99,8 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup Name = Name, Description = Description, Priority = Priority, + Image = Image, + Page = Page, DefaultSettings = DefaultSettings.TurnMulti(OptionData.Count), }; single.OptionData.AddRange(OptionData.Select(o => o.ConvertToSingle(single))); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index fddb96d6..ab0c2d4f 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -63,15 +63,8 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup public static SingleModGroup? Load(Mod mod, JObject json) { var options = json["Options"]; - var ret = new SingleModGroup(mod) - { - Name = json[nameof(Name)]?.ToObject() ?? string.Empty, - Description = json[nameof(Description)]?.ToObject() ?? string.Empty, - Image = json[nameof(Image)]?.ToObject() ?? string.Empty, - Priority = json[nameof(Priority)]?.ToObject() ?? ModPriority.Default, - DefaultSettings = json[nameof(DefaultSettings)]?.ToObject() ?? Setting.Zero, - }; - if (ret.Name.Length == 0) + var ret = new SingleModGroup(mod); + if (!ModSaveGroup.ReadJsonBase(json, ret)) return null; if (options != null) @@ -92,6 +85,8 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup Name = Name, Description = Description, Priority = Priority, + Image = Image, + Page = Page, DefaultSettings = Setting.Multi((int)DefaultSettings.Value), }; multi.OptionData.AddRange(OptionData.Select((o, i) => o.ConvertToMulti(multi, new ModPriority(i)))); From ac1ea124d93e9a17e6fe0fe71b920d31d4c5fe99 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 9 Sep 2024 14:53:17 +0000 Subject: [PATCH 0913/1381] [CI] Updating repo.json for testing_1.2.1.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index cdd622c9..6625cb24 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.3", + "TestingAssemblyVersion": "1.2.1.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 00fbb2686b864dcfe91bb9e67415b9059fc53a55 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 16 Sep 2024 22:54:06 +0200 Subject: [PATCH 0914/1381] Add option to apply only attributes from IMC group. --- Penumbra/Meta/ImcChecker.cs | 25 +++++++--------- Penumbra/Mods/Editor/ModMetaEditor.cs | 9 +++--- Penumbra/Mods/Groups/ImcModGroup.cs | 30 +++++++++++++------ .../Manager/OptionEditor/ImcModGroupEditor.cs | 10 +++++++ Penumbra/Mods/ModCreator.cs | 7 ++--- .../UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 4 +-- Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs | 6 ++-- .../ModsTab/Groups/ImcModGroupEditDrawer.cs | 12 ++++++-- 8 files changed, 63 insertions(+), 40 deletions(-) diff --git a/Penumbra/Meta/ImcChecker.cs b/Penumbra/Meta/ImcChecker.cs index 4e3ff11b..a415c9b0 100644 --- a/Penumbra/Meta/ImcChecker.cs +++ b/Penumbra/Meta/ImcChecker.cs @@ -6,9 +6,9 @@ namespace Penumbra.Meta; public class ImcChecker { - private static readonly Dictionary VariantCounts = []; - private static MetaFileManager? _dataManager; - + private static readonly Dictionary VariantCounts = []; + private static MetaFileManager? _dataManager; + private static readonly ConcurrentDictionary GlobalCachedDefaultEntries = []; public static int GetVariantCount(ImcIdentifier identifier) { @@ -26,23 +26,20 @@ public class ImcChecker public readonly record struct CachedEntry(ImcEntry Entry, bool FileExists, bool VariantExists); - private readonly Dictionary _cachedDefaultEntries = new(); - private readonly MetaFileManager _metaFileManager; - public ImcChecker(MetaFileManager metaFileManager) - { - _metaFileManager = metaFileManager; - _dataManager = metaFileManager; - } + => _dataManager = metaFileManager; - public CachedEntry GetDefaultEntry(ImcIdentifier identifier, bool storeCache) + public static CachedEntry GetDefaultEntry(ImcIdentifier identifier, bool storeCache) { - if (_cachedDefaultEntries.TryGetValue(identifier, out var entry)) + if (GlobalCachedDefaultEntries.TryGetValue(identifier, out var entry)) return entry; + if (_dataManager == null) + return new CachedEntry(default, false, false); + try { - var e = ImcFile.GetDefault(_metaFileManager, identifier.GamePath(), identifier.EquipSlot, identifier.Variant, out var entryExists); + var e = ImcFile.GetDefault(_dataManager, identifier.GamePath(), identifier.EquipSlot, identifier.Variant, out var entryExists); entry = new CachedEntry(e, true, entryExists); } catch (Exception) @@ -51,7 +48,7 @@ public class ImcChecker } if (storeCache) - _cachedDefaultEntries.Add(identifier, entry); + GlobalCachedDefaultEntries.TryAdd(identifier, entry); return entry; } diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 07a54391..64c585ea 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -10,8 +10,7 @@ namespace Penumbra.Mods.Editor; public class ModMetaEditor( ModGroupEditor groupEditor, - MetaFileManager metaFileManager, - ImcChecker imcChecker) : MetaDictionary, IService + MetaFileManager metaFileManager) : MetaDictionary, IService { public sealed class OtherOptionData : HashSet { @@ -67,14 +66,14 @@ public class ModMetaEditor( Changes = false; } - public static bool DeleteDefaultValues(MetaFileManager metaFileManager, ImcChecker imcChecker, MetaDictionary dict) + public static bool DeleteDefaultValues(MetaFileManager metaFileManager, MetaDictionary dict) { var clone = dict.Clone(); dict.Clear(); var count = 0; foreach (var (key, value) in clone.Imc) { - var defaultEntry = imcChecker.GetDefaultEntry(key, false); + var defaultEntry = ImcChecker.GetDefaultEntry(key, false); if (!defaultEntry.Entry.Equals(value)) { dict.TryAdd(key, value); @@ -164,7 +163,7 @@ public class ModMetaEditor( } public void DeleteDefaultValues() - => Changes = DeleteDefaultValues(metaFileManager, imcChecker, this); + => Changes = DeleteDefaultValues(metaFileManager, this); public void Apply(IModDataContainer container) { diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index f8b4b2ef..2a1854ed 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -35,6 +35,7 @@ public class ImcModGroup(Mod mod) : IModGroup public ImcIdentifier Identifier; public ImcEntry DefaultEntry; public bool AllVariants; + public bool OnlyAttributes; public FullPath? FindBestMatch(Utf8GamePath gamePath) @@ -97,28 +98,36 @@ public class ImcModGroup(Mod mod) : IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) => new ImcModGroupEditDrawer(editDrawer, this); - public ImcEntry GetEntry(ushort mask) - => DefaultEntry with { AttributeMask = mask }; + private ImcEntry GetEntry(Variant variant, ushort mask) + { + if (!OnlyAttributes) + return DefaultEntry with { AttributeMask = mask }; + + var defaultEntry = ImcChecker.GetDefaultEntry(Identifier with { Variant = variant }, true); + if (defaultEntry.VariantExists) + return defaultEntry.Entry with { AttributeMask = mask }; + + return DefaultEntry with { AttributeMask = mask }; + } public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) { if (IsDisabled(setting)) return; - var mask = GetCurrentMask(setting); - var entry = GetEntry(mask); + var mask = GetCurrentMask(setting); if (AllVariants) { var count = ImcChecker.GetVariantCount(Identifier); if (count == 0) - manipulations.TryAdd(Identifier, entry); + manipulations.TryAdd(Identifier, GetEntry(Identifier.Variant, mask)); else for (var i = 0; i <= count; ++i) - manipulations.TryAdd(Identifier with { Variant = (Variant)i }, entry); + manipulations.TryAdd(Identifier with { Variant = (Variant)i }, GetEntry((Variant)i, mask)); } else { - manipulations.TryAdd(Identifier, entry); + manipulations.TryAdd(Identifier, GetEntry(Identifier.Variant, mask)); } } @@ -138,6 +147,8 @@ public class ImcModGroup(Mod mod) : IModGroup serializer.Serialize(jWriter, DefaultEntry); jWriter.WritePropertyName(nameof(AllVariants)); jWriter.WriteValue(AllVariants); + jWriter.WritePropertyName(nameof(OnlyAttributes)); + jWriter.WriteValue(OnlyAttributes); jWriter.WritePropertyName("Options"); jWriter.WriteStartArray(); foreach (var option in OptionData) @@ -170,8 +181,9 @@ public class ImcModGroup(Mod mod) : IModGroup var identifier = ImcIdentifier.FromJson(json[nameof(Identifier)] as JObject); var ret = new ImcModGroup(mod) { - DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), - AllVariants = json[nameof(AllVariants)]?.ToObject() ?? false, + DefaultEntry = json[nameof(DefaultEntry)]?.ToObject() ?? new ImcEntry(), + AllVariants = json[nameof(AllVariants)]?.ToObject() ?? false, + OnlyAttributes = json[nameof(OnlyAttributes)]?.ToObject() ?? false, }; if (!ModSaveGroup.ReadJsonBase(json, ret)) return null; diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index 515f6ff4..dc94c881 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -89,6 +89,16 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, group.Mod, group, null, null, -1); } + public void ChangeOnlyAttributes(ImcModGroup group, bool onlyAttributes, SaveType saveType = SaveType.Queue) + { + if (group.OnlyAttributes == onlyAttributes) + return; + + group.OnlyAttributes = onlyAttributes; + SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMetaChanged, group.Mod, group, null, null, -1); + } + public void ChangeCanBeDisabled(ImcModGroup group, bool canBeDisabled, SaveType saveType = SaveType.Queue) { if (group.CanBeDisabled == canBeDisabled) diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index fe027ca4..1af9c1db 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -25,8 +25,7 @@ public partial class ModCreator( Configuration config, ModDataEditor dataEditor, MetaFileManager metaFileManager, - GamePathParser gamePathParser, - ImcChecker imcChecker) : IService + GamePathParser gamePathParser) : IService { public readonly Configuration Config = config; @@ -86,7 +85,7 @@ public partial class ModCreator( { foreach (var container in mod.AllDataContainers) { - if (ModMetaEditor.DeleteDefaultValues(metaFileManager, imcChecker, container.Manipulations)) + if (ModMetaEditor.DeleteDefaultValues(metaFileManager, container.Manipulations)) saveService.ImmediateSaveSync(new ModSaveGroup(container, Config.ReplaceNonAsciiOnImport)); } } @@ -235,7 +234,7 @@ public partial class ModCreator( DeleteDeleteList(deleteList, delete); var changes = oldSize < option.Manipulations.Count; if (deleteDefault && !Config.KeepDefaultMetaChanges) - changes |= ModMetaEditor.DeleteDefaultValues(metaFileManager, imcChecker, option.Manipulations); + changes |= ModMetaEditor.DeleteDefaultValues(metaFileManager, option.Manipulations); return (changes, deleteList); } diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index 53c61292..c8310cf7 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -30,7 +30,7 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } private void UpdateEntry() - => (Entry, _fileExists, _) = MetaFiles.ImcChecker.GetDefaultEntry(Identifier, true); + => (Entry, _fileExists, _) = ImcChecker.GetDefaultEntry(Identifier, true); protected override void DrawNew() { @@ -54,7 +54,7 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile DrawMetaButtons(identifier, entry); DrawIdentifier(identifier); - var defaultEntry = MetaFiles.ImcChecker.GetDefaultEntry(identifier, true).Entry; + var defaultEntry = ImcChecker.GetDefaultEntry(identifier, true).Entry; if (DrawEntry(defaultEntry, ref entry, true)) Editor.Changes |= Editor.Update(identifier, entry); } diff --git a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index 689571f3..c30239bc 100644 --- a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -24,13 +24,11 @@ public class AddGroupDrawer : IUiService private bool _imcFileExists; private bool _entryExists; private bool _entryInvalid; - private readonly ImcChecker _imcChecker; private readonly ModManager _modManager; - public AddGroupDrawer(ModManager modManager, ImcChecker imcChecker) + public AddGroupDrawer(ModManager modManager) { _modManager = modManager; - _imcChecker = imcChecker; UpdateEntry(); } @@ -142,7 +140,7 @@ public class AddGroupDrawer : IUiService private void UpdateEntry() { - (_defaultEntry, _imcFileExists, _entryExists) = _imcChecker.GetDefaultEntry(_imcIdentifier, false); + (_defaultEntry, _imcFileExists, _entryExists) = ImcChecker.GetDefaultEntry(_imcIdentifier, false); _entryInvalid = !_imcIdentifier.Validate() || _defaultEntry.MaterialId == 0 || !_entryExists; } } diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 4ab1c6aa..786bb8ff 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -6,6 +6,7 @@ using OtterGui.Text; using OtterGui.Text.Widget; using OtterGuiInternal.Utility; using Penumbra.GameData.Structs; +using Penumbra.Meta; using Penumbra.Mods.Groups; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; @@ -18,18 +19,25 @@ public readonly struct ImcModGroupEditDrawer(ModGroupEditDrawer editor, ImcModGr public void Draw() { var identifier = group.Identifier; - var defaultEntry = editor.ImcChecker.GetDefaultEntry(identifier, true).Entry; + var defaultEntry = ImcChecker.GetDefaultEntry(identifier, true).Entry; var entry = group.DefaultEntry; var changes = false; - var width = editor.AvailableWidth.X - ImUtf8.ItemInnerSpacing.X - ImUtf8.CalcTextSize("All Variants"u8).X; + var width = editor.AvailableWidth.X - 3 * ImUtf8.ItemInnerSpacing.X - ImUtf8.ItemSpacing.X - ImUtf8.CalcTextSize("All Variants"u8).X - ImUtf8.CalcTextSize("Only Attributes"u8).X - 2 * ImUtf8.FrameHeight; ImUtf8.TextFramed(identifier.ToString(), 0, new Vector2(width, 0), borderColor: ImGui.GetColorU32(ImGuiCol.Border)); + ImUtf8.SameLineInner(); var allVariants = group.AllVariants; if (ImUtf8.Checkbox("All Variants"u8, ref allVariants)) editor.ModManager.OptionEditor.ImcEditor.ChangeAllVariants(group, allVariants); ImUtf8.HoverTooltip("Make this group overwrite all corresponding variants for this identifier, not just the one specified."u8); + ImGui.SameLine(); + var onlyAttributes = group.OnlyAttributes; + if (ImUtf8.Checkbox("Only Attributes"u8, ref onlyAttributes)) + editor.ModManager.OptionEditor.ImcEditor.ChangeOnlyAttributes(group, onlyAttributes); + ImUtf8.HoverTooltip("Only overwrite the attribute flags and take all the other values from the game's default entry instead of the one configured here.\n\nMainly useful if used with All Variants to keep the material IDs for each variant."u8); + using (ImUtf8.Group()) { ImUtf8.TextFrameAligned("Material ID"u8); From 9b958a9d37856e060f66643ad306de3ea63b0bf2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 16 Sep 2024 23:16:43 +0200 Subject: [PATCH 0915/1381] Update actions. --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/test_release.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b40b2538..1783c9a4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -29,7 +29,7 @@ jobs: - name: Archive run: Compress-Archive -Path Penumbra/bin/Release/* -DestinationPath Penumbra.zip - name: Upload a Build Artifact - uses: actions/upload-artifact@v2.2.1 + uses: actions/upload-artifact@v4 with: path: | ./Penumbra/bin/Release/* diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7c9e2909..4799cbed 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,7 +37,7 @@ jobs: - name: Archive run: Compress-Archive -Path Penumbra/bin/Release/* -DestinationPath Penumbra.zip - name: Upload a Build Artifact - uses: actions/upload-artifact@v2.2.1 + uses: actions/upload-artifact@v4 with: path: | ./Penumbra/bin/Release/* diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 91361646..0718ded2 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -37,7 +37,7 @@ jobs: - name: Archive run: Compress-Archive -Path Penumbra/bin/Debug/* -DestinationPath Penumbra.zip - name: Upload a Build Artifact - uses: actions/upload-artifact@v2.2.1 + uses: actions/upload-artifact@v4 with: path: | ./Penumbra/bin/Debug/* From af2a14826cdee2472b9ac872e1808d505aae14e2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 19 Sep 2024 22:50:00 +0200 Subject: [PATCH 0916/1381] Add potential hidden priorities. --- Penumbra/Mods/Settings/ModPriority.cs | 6 ++++++ Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 5 +++-- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 4 ++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Penumbra/Mods/Settings/ModPriority.cs b/Penumbra/Mods/Settings/ModPriority.cs index 993bd577..cf234c00 100644 --- a/Penumbra/Mods/Settings/ModPriority.cs +++ b/Penumbra/Mods/Settings/ModPriority.cs @@ -66,4 +66,10 @@ public readonly record struct ModPriority(int Value) : public int CompareTo(ModPriority other) => Value.CompareTo(other.Value); + + public const int HiddenMin = -84037; + public const int HiddenMax = HiddenMin + 1000; + + public bool IsHidden + => Value is > HiddenMin and < HiddenMax; } diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index bee48068..bc18ac51 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -25,7 +25,7 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy => "Conflicts"u8; public bool IsVisible - => collectionManager.Active.Current.Conflicts(selector.Selected!).Count > 0; + => collectionManager.Active.Current.Conflicts(selector.Selected!).Any(c => !GetPriority(c).IsHidden); private readonly ConditionalWeakTable _expandedMods = []; @@ -58,7 +58,8 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy // Can not be null because otherwise the tab bar is never drawn. var mod = selector.Selected!; - foreach (var (conflict, index) in collectionManager.Active.Current.Conflicts(mod).OrderByDescending(GetPriority) + foreach (var (conflict, index) in collectionManager.Active.Current.Conflicts(mod).Where(c => !c.Mod2.Priority.IsHidden) + .OrderByDescending(GetPriority) .ThenBy(c => c.Mod2.Name.Lower).WithIndex()) { using var id = ImRaii.PushId(index); diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index d2fbd0cd..8d889c3b 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -2,6 +2,7 @@ using ImGuiNET; using OtterGui.Raii; using OtterGui; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.UI.Classes; using Penumbra.Collections.Manager; @@ -96,6 +97,9 @@ public class ModPanelSettingsTab( ImGui.SetNextItemWidth(50 * UiHelpers.Scale); if (ImGui.InputInt("##Priority", ref priority, 0, 0)) _currentPriority = priority; + if (new ModPriority(priority).IsHidden) + ImUtf8.HoverTooltip($"This priority is special-cased to hide this mod in conflict tabs ({ModPriority.HiddenMin}, {ModPriority.HiddenMax})."); + if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { From 22aca49112b7f9d6feca07c999507a08ff41935c Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 22 Sep 2024 19:47:34 +0000 Subject: [PATCH 0917/1381] [CI] Updating repo.json for testing_1.2.1.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 6625cb24..36b27682 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.4", + "TestingAssemblyVersion": "1.2.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From caf4382e1f17b8fccd1bfc2f03293fd149596971 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 6 Oct 2024 11:50:49 +0200 Subject: [PATCH 0918/1381] Update BNPCs --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 66bc00dc..fd50cb3d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 66bc00dc8517204e58c6515af5aec0ba6d196716 +Subproject commit fd50cb3d33e8f59e8b60474c3def914a6952c485 From 776b4e9efbd1835cc0332d7f1ea9b68c4267bf72 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 6 Oct 2024 11:58:00 +0200 Subject: [PATCH 0919/1381] Update obsolete properties from CS. --- Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs | 4 ++-- .../UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index 61ccc95c..c459a67a 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -40,8 +40,8 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase if (_originalColorTableTexture.Texture == null) throw new InvalidOperationException("Material doesn't have a color table"); - Width = (int)_originalColorTableTexture.Texture->Width; - Height = (int)_originalColorTableTexture.Texture->Height; + Width = (int)_originalColorTableTexture.Texture->ActualWidth; + Height = (int)_originalColorTableTexture.Texture->ActualHeight; ColorTable = new Half[Width * Height * 4]; _updatePending = true; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs index 6ffd1f88..5c636b1d 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs @@ -56,7 +56,7 @@ public sealed unsafe class MaterialTemplatePickers : IUiService } var firstNonNullTexture = firstNonNullTextureRH != null ? firstNonNullTextureRH->CsHandle.Texture : null; - var textureSize = firstNonNullTexture != null ? new Vector2(firstNonNullTexture->Width, firstNonNullTexture->Height).Contain(new Vector2(MaximumTextureSize)) : Vector2.Zero; + var textureSize = firstNonNullTexture != null ? new Vector2(firstNonNullTexture->ActualWidth, firstNonNullTexture->ActualHeight).Contain(new Vector2(MaximumTextureSize)) : Vector2.Zero; var count = firstNonNullTexture != null ? firstNonNullTexture->ArraySize : 0; var ret = false; @@ -135,10 +135,10 @@ public sealed unsafe class MaterialTemplatePickers : IUiService continue; var position = regionStart with { X = regionStart.X + (itemSize.X + itemSpacing) * j }; - var size = new Vector2(texture->Width, texture->Height).Contain(itemSize); + var size = new Vector2(texture->ActualWidth, texture->ActualHeight).Contain(itemSize); position += (itemSize - size) * 0.5f; ImGui.GetWindowDrawList().AddImage(handle, position, position + size, Vector2.Zero, - new Vector2(texture->Width / (float)texture->Width2, texture->Height / (float)texture->Height2)); + new Vector2(texture->ActualWidth / (float)texture->AllocatedWidth, texture->ActualHeight / (float)texture->AllocatedHeight)); } } From 389c42e68f2d65eaa7ec8eff6a1fd38c955faf54 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 6 Oct 2024 13:02:28 +0200 Subject: [PATCH 0920/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fd50cb3d..dd86dafb 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fd50cb3d33e8f59e8b60474c3def914a6952c485 +Subproject commit dd86dafb88ca4c7b662938bbc1310729ba7f788d From 8084f481446dd601761c0c96bf6baf1d1366fb63 Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Mon, 22 Jul 2024 18:29:39 +1000 Subject: [PATCH 0921/1381] Init support for DT model i/o --- Penumbra/Import/Models/Export/MeshExporter.cs | 62 +++- Penumbra/Import/Models/Import/MeshImporter.cs | 32 ++- .../Import/Models/Import/VertexAttribute.cs | 265 ++++++++++++++---- 3 files changed, 281 insertions(+), 78 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 3a57ab55..20158776 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -311,15 +311,28 @@ public class MeshExporter MdlFile.VertexType.Single3 => new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.Single4 => new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), MdlFile.VertexType.UByte4 => reader.ReadBytes(4), - MdlFile.VertexType.NByte4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, - reader.ReadByte() / 255f), + MdlFile.VertexType.NByte4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), - MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), - (float)reader.ReadHalf()), - + MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), + MdlFile.VertexType.UShort4 => ReadUShort4(reader), var other => throw _notifier.Exception($"Unhandled vertex type {other}"), }; } + + private byte[] ReadUShort4(BinaryReader reader) + { + var buffer = reader.ReadBytes(8); + var byteValues = new byte[8]; + byteValues[0] = buffer[0]; + byteValues[4] = buffer[1]; + byteValues[1] = buffer[2]; + byteValues[5] = buffer[3]; + byteValues[2] = buffer[4]; + byteValues[6] = buffer[5]; + byteValues[3] = buffer[6]; + byteValues[7] = buffer[7]; + return byteValues; + } /// Get the vertex geometry type for this mesh's vertex usages. private Type GetGeometryType(IReadOnlyDictionary usages) @@ -444,7 +457,16 @@ public class MeshExporter private static Type GetSkinningType(IReadOnlyDictionary usages) { if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) - return typeof(VertexJoints4); + { + if (usages[MdlFile.VertexUsage.BlendWeights] == MdlFile.VertexType.UShort4) + { + return typeof(VertexJoints8); + } + else + { + return typeof(VertexJoints4); + } + } return typeof(VertexEmpty); } @@ -455,15 +477,17 @@ public class MeshExporter if (_skinningType == typeof(VertexEmpty)) return new VertexEmpty(); - if (_skinningType == typeof(VertexJoints4)) + if (_skinningType == typeof(VertexJoints4) || _skinningType == typeof(VertexJoints8)) { if (_boneIndexMap == null) throw _notifier.Exception("Tried to build skinned vertex but no bone mappings are available."); - var indices = ToByteArray(attributes[MdlFile.VertexUsage.BlendIndices]); - var weights = ToVector4(attributes[MdlFile.VertexUsage.BlendWeights]); - - var bindings = Enumerable.Range(0, 4) + var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices]; + var weightsData = attributes[MdlFile.VertexUsage.BlendWeights]; + var indices = ToByteArray(indiciesData); + var weights = ToFloatArray(weightsData); + + var bindings = Enumerable.Range(0, indices.Length) .Select(bindingIndex => { // NOTE: I've not seen any files that throw this error that aren't completely broken. @@ -474,7 +498,13 @@ public class MeshExporter return (jointIndex, weights[bindingIndex]); }) .ToArray(); - return new VertexJoints4(bindings); + + return bindings.Length switch + { + 4 => new VertexJoints4(bindings), + 8 => new VertexJoints8(bindings), + _ => throw _notifier.Exception($"Invalid number of bone bindings {bindings.Length}.") + }; } throw _notifier.Exception($"Unknown skinning type {_skinningType}"); @@ -517,4 +547,12 @@ public class MeshExporter byte[] value => value, _ => throw new ArgumentOutOfRangeException($"Invalid byte[] input {data}"), }; + + private static float[] ToFloatArray(object data) + => data switch + { + byte[] value => value.Select(x => x / 255f).ToArray(), + _ => throw new ArgumentOutOfRangeException($"Invalid float[] input {data}"), + }; } + diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 1df97907..e3567780 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -194,17 +194,37 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) foreach (var (primitive, primitiveIndex) in node.Mesh.Primitives.WithIndex()) { // Per glTF specification, an asset with a skin MUST contain skinning attributes on its meshes. - var jointsAccessor = primitive.GetVertexAccessor("JOINTS_0")?.AsVector4Array(); - var weightsAccessor = primitive.GetVertexAccessor("WEIGHTS_0")?.AsVector4Array(); + var joints0Accessor = primitive.GetVertexAccessor("JOINTS_0")?.AsVector4Array(); + var weights0Accessor = primitive.GetVertexAccessor("WEIGHTS_0")?.AsVector4Array(); - if (jointsAccessor == null || weightsAccessor == null) + if (joints0Accessor == null || weights0Accessor == null) throw notifier.Exception($"Primitive {primitiveIndex} is skinned but does not contain skinning vertex attributes."); // Build a set of joints that are referenced by this mesh. - for (var i = 0; i < jointsAccessor.Count; i++) + for (var i = 0; i < joints0Accessor.Count; i++) { - var joints = jointsAccessor[i]; - var weights = weightsAccessor[i]; + var joints = joints0Accessor[i]; + var weights = weights0Accessor[i]; + for (var index = 0; index < 4; index++) + { + // If a joint has absolutely no weight, we omit the bone entirely. + if (weights[index] == 0) + continue; + + usedJoints.Add((ushort)joints[index]); + } + } + + var joints1Accessor = primitive.GetVertexAccessor("JOINTS_1")?.AsVector4Array(); + var weights1Accessor = primitive.GetVertexAccessor("WEIGHTS_1")?.AsVector4Array(); + + if (joints1Accessor == null || weights1Accessor == null) + continue; + + for (var i = 0; i < joints1Accessor.Count; i++) + { + var joints = joints1Accessor[i]; + var weights = weights1Accessor[i]; for (var index = 0; index < 4; index++) { // If a joint has absolutely no weight, we omit the bone entirely. diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index af401ec1..b71ad429 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -40,6 +40,7 @@ public class VertexAttribute MdlFile.VertexType.NByte4 => 4, MdlFile.VertexType.Half2 => 4, MdlFile.VertexType.Half4 => 8, + MdlFile.VertexType.UShort4 => 8, _ => throw new Exception($"Unhandled vertex type {(MdlFile.VertexType)Element.Type}"), }; @@ -121,89 +122,219 @@ public class VertexAttribute public static VertexAttribute? BlendWeight(Accessors accessors, IoNotifier notifier) { - if (!accessors.TryGetValue("WEIGHTS_0", out var accessor)) + if (!accessors.TryGetValue("WEIGHTS_0", out var weights0Accessor)) return null; if (!accessors.ContainsKey("JOINTS_0")) throw notifier.Exception("Mesh contained WEIGHTS_0 attribute but no corresponding JOINTS_0 attribute."); - var element = new MdlStructs.VertexElement() + if (accessors.TryGetValue("WEIGHTS_1", out var weights1Accessor)) { - Stream = 0, - Type = (byte)MdlFile.VertexType.NByte4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, - }; + if (!accessors.ContainsKey("JOINTS_1")) + throw notifier.Exception("Mesh contained WEIGHTS_1 attribute but no corresponding JOINTS_1 attribute."); + + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.UShort4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; - var values = accessor.AsVector4Array(); + var weights0 = weights0Accessor.AsVector4Array(); + var weights1 = weights1Accessor.AsVector4Array(); - return new VertexAttribute( - element, - index => { - // Blend weights are _very_ sensitive to float imprecision - a vertex sum being off - // by one, such as 256, is enough to cause a visible defect. To avoid this, we tweak - // the converted values to have the expected sum, preferencing values with minimal differences. - var originalValues = values[index]; - var byteValues = BuildNByte4(originalValues); - - var adjustment = 255 - byteValues.Select(value => (int)value).Sum(); - while (adjustment != 0) - { - var convertedValues = byteValues.Select(value => value * (1f / 255f)).ToArray(); - var closestIndex = Enumerable.Range(0, 4) - .Where(index => { - var byteValue = byteValues[index]; - if (adjustment < 0) return byteValue > 0; - if (adjustment > 0) return byteValue < 255; - return true; - }) - .Select(index => (index, delta: Math.Abs(originalValues[index] - convertedValues[index]))) - .MinBy(x => x.delta) - .index; - byteValues[closestIndex] = (byte)(byteValues[closestIndex] + Math.CopySign(1, adjustment)); - adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + return new VertexAttribute( + element, + index => { + var weight0 = weights0[index]; + var weight1 = weights1[index]; + var originalData = BuildUshort4(weight0, weight1); + var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); + return AdjustByteArray(byteValues, originalData); } - - return byteValues; - } - ); + ); + } + else + { + var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.UShort4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; + + var weights0 = weights0Accessor.AsVector4Array(); + + return new VertexAttribute( + element, + index => { + var weight0 = weights0[index]; + var weight1 = Vector4.Zero; + var originalData = BuildUshort4(weight0, weight1); + var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); + return AdjustByteArray(byteValues, originalData); + } + ); + + /*var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.NByte4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; + + var weights0 = weights0Accessor.AsVector4Array(); + + return new VertexAttribute( + element, + index => + { + var weight0 = weights0[index]; + var originalData = new[] { weight0.X, weight0.Y, weight0.Z, weight0.W }; + var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); + var newByteValues = AdjustByteArray(byteValues, originalData); + if (!newByteValues.SequenceEqual(byteValues)) + notifier.Warning("Adjusted blend weights to maintain precision."); + return newByteValues; + });*/ + } + } + + private static byte[] AdjustByteArray(byte[] byteValues, float[] originalValues) + { + // Blend weights are _very_ sensitive to float imprecision - a vertex sum being off + // by one, such as 256, is enough to cause a visible defect. To avoid this, we tweak + // the converted values to have the expected sum, preferencing values with minimal differences. + var adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + while (adjustment != 0) + { + var convertedValues = byteValues.Select(value => value * (1f / 255f)).ToArray(); + var closestIndex = Enumerable.Range(0, byteValues.Length) + .Where(index => + { + var byteValue = byteValues[index]; + if (adjustment < 0) + return byteValue > 0; + if (adjustment > 0) + return byteValue < 255; + + return true; + }) + .Select(index => (index, delta: Math.Abs(originalValues[index] - convertedValues[index]))) + .MinBy(x => x.delta) + .index; + byteValues[closestIndex] = (byte)(byteValues[closestIndex] + Math.CopySign(1, adjustment)); + adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + } + + return byteValues; } public static VertexAttribute? BlendIndex(Accessors accessors, IDictionary? boneMap, IoNotifier notifier) { - if (!accessors.TryGetValue("JOINTS_0", out var jointsAccessor)) + if (!accessors.TryGetValue("JOINTS_0", out var joints0Accessor)) return null; - if (!accessors.TryGetValue("WEIGHTS_0", out var weightsAccessor)) + if (!accessors.TryGetValue("WEIGHTS_0", out var weights0Accessor)) throw notifier.Exception("Mesh contained JOINTS_0 attribute but no corresponding WEIGHTS_0 attribute."); if (boneMap == null) throw notifier.Exception("Mesh contained JOINTS_0 attribute but no bone mapping was created."); - var element = new MdlStructs.VertexElement() + var joints0 = joints0Accessor.AsVector4Array(); + var weights0 = weights0Accessor.AsVector4Array(); + + if (accessors.TryGetValue("JOINTS_1", out var joints1Accessor)) { - Stream = 0, - Type = (byte)MdlFile.VertexType.UByte4, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, - }; + if (!accessors.TryGetValue("WEIGHTS_1", out var weights1Accessor)) + throw notifier.Exception("Mesh contained JOINTS_1 attribute but no corresponding WEIGHTS_1 attribute."); - var joints = jointsAccessor.AsVector4Array(); - var weights = weightsAccessor.AsVector4Array(); - - return new VertexAttribute( - element, - index => + var element = new MdlStructs.VertexElement { - var gltfIndices = joints[index]; - var gltfWeights = weights[index]; + Stream = 0, + Type = (byte)MdlFile.VertexType.UShort4, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; - return BuildUByte4(new Vector4( - gltfWeights.X == 0 ? 0 : boneMap[(ushort)gltfIndices.X], - gltfWeights.Y == 0 ? 0 : boneMap[(ushort)gltfIndices.Y], - gltfWeights.Z == 0 ? 0 : boneMap[(ushort)gltfIndices.Z], - gltfWeights.W == 0 ? 0 : boneMap[(ushort)gltfIndices.W] - )); - } - ); + var joints1 = joints1Accessor.AsVector4Array(); + var weights1 = weights1Accessor.AsVector4Array(); + + return new VertexAttribute( + element, + index => + { + var gltfIndices0 = joints0[index]; + var gltfWeights0 = weights0[index]; + var gltfIndices1 = joints1[index]; + var gltfWeights1 = weights1[index]; + var v0 = new Vector4( + gltfWeights0.X == 0 ? 0 : boneMap[(ushort)gltfIndices0.X], + gltfWeights0.Y == 0 ? 0 : boneMap[(ushort)gltfIndices0.Y], + gltfWeights0.Z == 0 ? 0 : boneMap[(ushort)gltfIndices0.Z], + gltfWeights0.W == 0 ? 0 : boneMap[(ushort)gltfIndices0.W] + ); + var v1 = new Vector4( + gltfWeights1.X == 0 ? 0 : boneMap[(ushort)gltfIndices1.X], + gltfWeights1.Y == 0 ? 0 : boneMap[(ushort)gltfIndices1.Y], + gltfWeights1.Z == 0 ? 0 : boneMap[(ushort)gltfIndices1.Z], + gltfWeights1.W == 0 ? 0 : boneMap[(ushort)gltfIndices1.W] + ); + + var byteValues = BuildUshort4(v0, v1); + + return byteValues.Select(x => (byte)x).ToArray(); + } + ); + } + else + { + var element = new MdlStructs.VertexElement + { + Stream = 0, + Type = (byte)MdlFile.VertexType.UShort4, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; + + return new VertexAttribute( + element, + index => + { + var gltfIndices0 = joints0[index]; + var gltfWeights0 = weights0[index]; + var v0 = new Vector4( + gltfWeights0.X == 0 ? 0 : boneMap[(ushort)gltfIndices0.X], + gltfWeights0.Y == 0 ? 0 : boneMap[(ushort)gltfIndices0.Y], + gltfWeights0.Z == 0 ? 0 : boneMap[(ushort)gltfIndices0.Z], + gltfWeights0.W == 0 ? 0 : boneMap[(ushort)gltfIndices0.W] + ); + var v1 = Vector4.Zero; + var byteValues = BuildUshort4(v0, v1); + + return byteValues.Select(x => (byte)x).ToArray(); + } + ); + /*var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.UByte4, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; + + return new VertexAttribute( + element, + index => + { + var gltfIndices = joints0[index]; + var gltfWeights = weights0[index]; + return BuildUByte4(new Vector4( + gltfWeights.X == 0 ? 0 : boneMap[(ushort)gltfIndices.X], + gltfWeights.Y == 0 ? 0 : boneMap[(ushort)gltfIndices.Y], + gltfWeights.Z == 0 ? 0 : boneMap[(ushort)gltfIndices.Z], + gltfWeights.W == 0 ? 0 : boneMap[(ushort)gltfIndices.W] + )); + } + );*/ + } } public static VertexAttribute? Normal(Accessors accessors, IEnumerable morphAccessors) @@ -232,7 +363,7 @@ public class VertexAttribute var value = values[vertexIndex]; var delta = morphValues[morphIndex]?[vertexIndex]; - if (delta != null) + if (delta != null) value += delta.Value; return BuildSingle3(value); @@ -489,4 +620,18 @@ public class VertexAttribute (byte)Math.Round(input.Z * 255f), (byte)Math.Round(input.W * 255f), ]; + + private static float[] BuildUshort4(Vector4 v0, Vector4 v1) + { + var buf = new float[8]; + buf[0] = v0.X; + buf[4] = v1.X; + buf[1] = v0.Y; + buf[5] = v1.Y; + buf[2] = v0.Z; + buf[6] = v1.Z; + buf[3] = v0.W; + buf[7] = v1.W; + return buf; + } } From fecdee05bda2de924b4b46aebf7c6f7d9ff3ccdd Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Mon, 22 Jul 2024 19:35:35 +1000 Subject: [PATCH 0922/1381] Cleanup --- Penumbra/Import/Models/Export/MeshExporter.cs | 17 +- Penumbra/Import/Models/Import/MeshImporter.cs | 31 +- .../Import/Models/Import/VertexAttribute.cs | 272 +++++++----------- 3 files changed, 121 insertions(+), 199 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 20158776..3707ff79 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -314,25 +314,10 @@ public class MeshExporter MdlFile.VertexType.NByte4 => new Vector4(reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f, reader.ReadByte() / 255f), MdlFile.VertexType.Half2 => new Vector2((float)reader.ReadHalf(), (float)reader.ReadHalf()), MdlFile.VertexType.Half4 => new Vector4((float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf(), (float)reader.ReadHalf()), - MdlFile.VertexType.UShort4 => ReadUShort4(reader), + MdlFile.VertexType.UShort4 => reader.ReadBytes(8), var other => throw _notifier.Exception($"Unhandled vertex type {other}"), }; } - - private byte[] ReadUShort4(BinaryReader reader) - { - var buffer = reader.ReadBytes(8); - var byteValues = new byte[8]; - byteValues[0] = buffer[0]; - byteValues[4] = buffer[1]; - byteValues[1] = buffer[2]; - byteValues[5] = buffer[3]; - byteValues[2] = buffer[4]; - byteValues[6] = buffer[5]; - byteValues[3] = buffer[6]; - byteValues[7] = buffer[7]; - return byteValues; - } /// Get the vertex geometry type for this mesh's vertex usages. private Type GetGeometryType(IReadOnlyDictionary usages) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index e3567780..813ef422 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -196,7 +196,9 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) // Per glTF specification, an asset with a skin MUST contain skinning attributes on its meshes. var joints0Accessor = primitive.GetVertexAccessor("JOINTS_0")?.AsVector4Array(); var weights0Accessor = primitive.GetVertexAccessor("WEIGHTS_0")?.AsVector4Array(); - + var joints1Accessor = primitive.GetVertexAccessor("JOINTS_1")?.AsVector4Array(); + var weights1Accessor = primitive.GetVertexAccessor("WEIGHTS_1")?.AsVector4Array(); + if (joints0Accessor == null || weights0Accessor == null) throw notifier.Exception($"Primitive {primitiveIndex} is skinned but does not contain skinning vertex attributes."); @@ -205,6 +207,8 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) { var joints = joints0Accessor[i]; var weights = weights0Accessor[i]; + var joints1 = joints1Accessor?[i]; + var weights1 = weights1Accessor?[i]; for (var index = 0; index < 4; index++) { // If a joint has absolutely no weight, we omit the bone entirely. @@ -212,26 +216,11 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) continue; usedJoints.Add((ushort)joints[index]); - } - } - - var joints1Accessor = primitive.GetVertexAccessor("JOINTS_1")?.AsVector4Array(); - var weights1Accessor = primitive.GetVertexAccessor("WEIGHTS_1")?.AsVector4Array(); - - if (joints1Accessor == null || weights1Accessor == null) - continue; - - for (var i = 0; i < joints1Accessor.Count; i++) - { - var joints = joints1Accessor[i]; - var weights = weights1Accessor[i]; - for (var index = 0; index < 4; index++) - { - // If a joint has absolutely no weight, we omit the bone entirely. - if (weights[index] == 0) - continue; - - usedJoints.Add((ushort)joints[index]); + + if (joints1 != null && weights1 != null && weights1.Value[index] != 0) + { + usedJoints.Add((ushort)joints1.Value[index]); + } } } } diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index b71ad429..12ceba23 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -132,72 +132,50 @@ public class VertexAttribute { if (!accessors.ContainsKey("JOINTS_1")) throw notifier.Exception("Mesh contained WEIGHTS_1 attribute but no corresponding JOINTS_1 attribute."); - - var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.UShort4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, - }; - - var weights0 = weights0Accessor.AsVector4Array(); - var weights1 = weights1Accessor.AsVector4Array(); - - return new VertexAttribute( - element, - index => { - var weight0 = weights0[index]; - var weight1 = weights1[index]; - var originalData = BuildUshort4(weight0, weight1); - var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); - return AdjustByteArray(byteValues, originalData); - } - ); } - else + + var element = new MdlStructs.VertexElement() { - var element = new MdlStructs.VertexElement() + Stream = 0, + Type = (byte)MdlFile.VertexType.UShort4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; + + var weights0 = weights0Accessor.AsVector4Array(); + var weights1 = weights1Accessor?.AsVector4Array(); + + return new VertexAttribute( + element, + index => { + var weight0 = weights0[index]; + var weight1 = weights1?[index]; + var originalData = BuildUshort4(weight0, weight1 ?? Vector4.Zero); + var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); + return AdjustByteArray(byteValues, originalData); + } + ); + + /*var element = new MdlStructs.VertexElement() + { + Stream = 0, + Type = (byte)MdlFile.VertexType.NByte4, + Usage = (byte)MdlFile.VertexUsage.BlendWeights, + }; + + var weights0 = weights0Accessor.AsVector4Array(); + + return new VertexAttribute( + element, + index => { - Stream = 0, - Type = (byte)MdlFile.VertexType.UShort4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, - }; - - var weights0 = weights0Accessor.AsVector4Array(); - - return new VertexAttribute( - element, - index => { - var weight0 = weights0[index]; - var weight1 = Vector4.Zero; - var originalData = BuildUshort4(weight0, weight1); - var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); - return AdjustByteArray(byteValues, originalData); - } - ); - - /*var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.NByte4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, - }; - - var weights0 = weights0Accessor.AsVector4Array(); - - return new VertexAttribute( - element, - index => - { - var weight0 = weights0[index]; - var originalData = new[] { weight0.X, weight0.Y, weight0.Z, weight0.W }; - var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); - var newByteValues = AdjustByteArray(byteValues, originalData); - if (!newByteValues.SequenceEqual(byteValues)) - notifier.Warning("Adjusted blend weights to maintain precision."); - return newByteValues; - });*/ - } + var weight0 = weights0[index]; + var originalData = new[] { weight0.X, weight0.Y, weight0.Z, weight0.W }; + var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); + var newByteValues = AdjustByteArray(byteValues, originalData); + if (!newByteValues.SequenceEqual(byteValues)) + notifier.Warning("Adjusted blend weights to maintain precision."); + return newByteValues; + });*/ } private static byte[] AdjustByteArray(byte[] byteValues, float[] originalValues) @@ -241,100 +219,77 @@ public class VertexAttribute if (boneMap == null) throw notifier.Exception("Mesh contained JOINTS_0 attribute but no bone mapping was created."); - var joints0 = joints0Accessor.AsVector4Array(); - var weights0 = weights0Accessor.AsVector4Array(); - - if (accessors.TryGetValue("JOINTS_1", out var joints1Accessor)) + var joints0 = joints0Accessor.AsVector4Array(); + var weights0 = weights0Accessor.AsVector4Array(); + accessors.TryGetValue("JOINTS_1", out var joints1Accessor); + accessors.TryGetValue("WEIGHTS_1", out var weights1Accessor); + var element = new MdlStructs.VertexElement { - if (!accessors.TryGetValue("WEIGHTS_1", out var weights1Accessor)) - throw notifier.Exception("Mesh contained JOINTS_1 attribute but no corresponding WEIGHTS_1 attribute."); + Stream = 0, + Type = (byte)MdlFile.VertexType.UShort4, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; - var element = new MdlStructs.VertexElement + var joints1 = joints1Accessor?.AsVector4Array(); + var weights1 = weights1Accessor?.AsVector4Array(); + + return new VertexAttribute( + element, + index => { - Stream = 0, - Type = (byte)MdlFile.VertexType.UShort4, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, - }; - - var joints1 = joints1Accessor.AsVector4Array(); - var weights1 = weights1Accessor.AsVector4Array(); - - return new VertexAttribute( - element, - index => + var gltfIndices0 = joints0[index]; + var gltfWeights0 = weights0[index]; + var gltfIndices1 = joints1?[index]; + var gltfWeights1 = weights1?[index]; + var v0 = new Vector4( + gltfWeights0.X == 0 ? 0 : boneMap[(ushort)gltfIndices0.X], + gltfWeights0.Y == 0 ? 0 : boneMap[(ushort)gltfIndices0.Y], + gltfWeights0.Z == 0 ? 0 : boneMap[(ushort)gltfIndices0.Z], + gltfWeights0.W == 0 ? 0 : boneMap[(ushort)gltfIndices0.W] + ); + + Vector4 v1; + if (gltfIndices1 != null && gltfWeights1 != null) { - var gltfIndices0 = joints0[index]; - var gltfWeights0 = weights0[index]; - var gltfIndices1 = joints1[index]; - var gltfWeights1 = weights1[index]; - var v0 = new Vector4( - gltfWeights0.X == 0 ? 0 : boneMap[(ushort)gltfIndices0.X], - gltfWeights0.Y == 0 ? 0 : boneMap[(ushort)gltfIndices0.Y], - gltfWeights0.Z == 0 ? 0 : boneMap[(ushort)gltfIndices0.Z], - gltfWeights0.W == 0 ? 0 : boneMap[(ushort)gltfIndices0.W] + v1 = new Vector4( + gltfWeights1.Value.X == 0 ? 0 : boneMap[(ushort)gltfIndices1.Value.X], + gltfWeights1.Value.Y == 0 ? 0 : boneMap[(ushort)gltfIndices1.Value.Y], + gltfWeights1.Value.Z == 0 ? 0 : boneMap[(ushort)gltfIndices1.Value.Z], + gltfWeights1.Value.W == 0 ? 0 : boneMap[(ushort)gltfIndices1.Value.W] ); - var v1 = new Vector4( - gltfWeights1.X == 0 ? 0 : boneMap[(ushort)gltfIndices1.X], - gltfWeights1.Y == 0 ? 0 : boneMap[(ushort)gltfIndices1.Y], - gltfWeights1.Z == 0 ? 0 : boneMap[(ushort)gltfIndices1.Z], - gltfWeights1.W == 0 ? 0 : boneMap[(ushort)gltfIndices1.W] - ); - - var byteValues = BuildUshort4(v0, v1); - - return byteValues.Select(x => (byte)x).ToArray(); } - ); - } - else + else + { + v1 = Vector4.Zero; + } + + var byteValues = BuildUshort4(v0, v1); + + return byteValues.Select(x => (byte)x).ToArray(); + } + ); + + /*var element = new MdlStructs.VertexElement() { - var element = new MdlStructs.VertexElement - { - Stream = 0, - Type = (byte)MdlFile.VertexType.UShort4, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, - }; - - return new VertexAttribute( - element, - index => - { - var gltfIndices0 = joints0[index]; - var gltfWeights0 = weights0[index]; - var v0 = new Vector4( - gltfWeights0.X == 0 ? 0 : boneMap[(ushort)gltfIndices0.X], - gltfWeights0.Y == 0 ? 0 : boneMap[(ushort)gltfIndices0.Y], - gltfWeights0.Z == 0 ? 0 : boneMap[(ushort)gltfIndices0.Z], - gltfWeights0.W == 0 ? 0 : boneMap[(ushort)gltfIndices0.W] - ); - var v1 = Vector4.Zero; - var byteValues = BuildUshort4(v0, v1); + Stream = 0, + Type = (byte)MdlFile.VertexType.UByte4, + Usage = (byte)MdlFile.VertexUsage.BlendIndices, + }; - return byteValues.Select(x => (byte)x).ToArray(); - } - ); - /*var element = new MdlStructs.VertexElement() + return new VertexAttribute( + element, + index => { - Stream = 0, - Type = (byte)MdlFile.VertexType.UByte4, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, - }; - - return new VertexAttribute( - element, - index => - { - var gltfIndices = joints0[index]; - var gltfWeights = weights0[index]; - return BuildUByte4(new Vector4( - gltfWeights.X == 0 ? 0 : boneMap[(ushort)gltfIndices.X], - gltfWeights.Y == 0 ? 0 : boneMap[(ushort)gltfIndices.Y], - gltfWeights.Z == 0 ? 0 : boneMap[(ushort)gltfIndices.Z], - gltfWeights.W == 0 ? 0 : boneMap[(ushort)gltfIndices.W] - )); - } - );*/ - } + var gltfIndices = joints0[index]; + var gltfWeights = weights0[index]; + return BuildUByte4(new Vector4( + gltfWeights.X == 0 ? 0 : boneMap[(ushort)gltfIndices.X], + gltfWeights.Y == 0 ? 0 : boneMap[(ushort)gltfIndices.Y], + gltfWeights.Z == 0 ? 0 : boneMap[(ushort)gltfIndices.Z], + gltfWeights.W == 0 ? 0 : boneMap[(ushort)gltfIndices.W] + )); + } + );*/ } public static VertexAttribute? Normal(Accessors accessors, IEnumerable morphAccessors) @@ -620,18 +575,11 @@ public class VertexAttribute (byte)Math.Round(input.Z * 255f), (byte)Math.Round(input.W * 255f), ]; - - private static float[] BuildUshort4(Vector4 v0, Vector4 v1) - { - var buf = new float[8]; - buf[0] = v0.X; - buf[4] = v1.X; - buf[1] = v0.Y; - buf[5] = v1.Y; - buf[2] = v0.Z; - buf[6] = v1.Z; - buf[3] = v0.W; - buf[7] = v1.W; - return buf; - } + + private static float[] BuildUshort4(Vector4 v0, Vector4 v1) => + new[] + { + v0.X, v0.Y, v0.Z, v0.W, + v1.X, v1.Y, v1.Z, v1.W, + }; } From 9de6b3a9055bcd9e80a8c6d694bfbd22d5a37155 Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Tue, 23 Jul 2024 21:41:58 +1000 Subject: [PATCH 0923/1381] Vector4 to float array --- Penumbra/Import/Models/Export/MeshExporter.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 3707ff79..73160615 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -537,6 +537,7 @@ public class MeshExporter => data switch { byte[] value => value.Select(x => x / 255f).ToArray(), + Vector4 v4 => new[] { v4.X, v4.Y, v4.Z, v4.W }, _ => throw new ArgumentOutOfRangeException($"Invalid float[] input {data}"), }; } From 9c6498e0282aa6626edc243abe4d364e1964e4c2 Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Tue, 13 Aug 2024 22:40:47 +1000 Subject: [PATCH 0924/1381] Conditionally still check for weights1 even if weights0 is 0 --- Penumbra/Import/Models/Import/MeshImporter.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 813ef422..6a46fb9f 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -205,17 +205,18 @@ public class MeshImporter(IEnumerable nodes, IoNotifier notifier) // Build a set of joints that are referenced by this mesh. for (var i = 0; i < joints0Accessor.Count; i++) { - var joints = joints0Accessor[i]; - var weights = weights0Accessor[i]; + var joints0 = joints0Accessor[i]; + var weights0 = weights0Accessor[i]; var joints1 = joints1Accessor?[i]; var weights1 = weights1Accessor?[i]; for (var index = 0; index < 4; index++) { // If a joint has absolutely no weight, we omit the bone entirely. - if (weights[index] == 0) - continue; + if (weights0[index] != 0) + { + usedJoints.Add((ushort)joints0[index]); + } - usedJoints.Add((ushort)joints[index]); if (joints1 != null && weights1 != null && weights1.Value[index] != 0) { From 3e90524b0613fca177414b011ce00b59ac64039c Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Tue, 13 Aug 2024 22:40:59 +1000 Subject: [PATCH 0925/1381] Remove old impl comments --- .../Import/Models/Import/VertexAttribute.cs | 44 ------------------- 1 file changed, 44 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 12ceba23..743ee773 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -154,28 +154,6 @@ public class VertexAttribute return AdjustByteArray(byteValues, originalData); } ); - - /*var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.NByte4, - Usage = (byte)MdlFile.VertexUsage.BlendWeights, - }; - - var weights0 = weights0Accessor.AsVector4Array(); - - return new VertexAttribute( - element, - index => - { - var weight0 = weights0[index]; - var originalData = new[] { weight0.X, weight0.Y, weight0.Z, weight0.W }; - var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); - var newByteValues = AdjustByteArray(byteValues, originalData); - if (!newByteValues.SequenceEqual(byteValues)) - notifier.Warning("Adjusted blend weights to maintain precision."); - return newByteValues; - });*/ } private static byte[] AdjustByteArray(byte[] byteValues, float[] originalValues) @@ -268,28 +246,6 @@ public class VertexAttribute return byteValues.Select(x => (byte)x).ToArray(); } ); - - /*var element = new MdlStructs.VertexElement() - { - Stream = 0, - Type = (byte)MdlFile.VertexType.UByte4, - Usage = (byte)MdlFile.VertexUsage.BlendIndices, - }; - - return new VertexAttribute( - element, - index => - { - var gltfIndices = joints0[index]; - var gltfWeights = weights0[index]; - return BuildUByte4(new Vector4( - gltfWeights.X == 0 ? 0 : boneMap[(ushort)gltfIndices.X], - gltfWeights.Y == 0 ? 0 : boneMap[(ushort)gltfIndices.Y], - gltfWeights.Z == 0 ? 0 : boneMap[(ushort)gltfIndices.Z], - gltfWeights.W == 0 ? 0 : boneMap[(ushort)gltfIndices.W] - )); - } - );*/ } public static VertexAttribute? Normal(Accessors accessors, IEnumerable morphAccessors) From 5258c600b7f458aa37d60654378eb58b22372c5c Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Tue, 13 Aug 2024 23:35:11 +1000 Subject: [PATCH 0926/1381] Rework AdjustByteArray --- .../Import/Models/Import/VertexAttribute.cs | 48 ++++++++----------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 743ee773..14a830d4 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -146,43 +146,39 @@ public class VertexAttribute return new VertexAttribute( element, - index => { - var weight0 = weights0[index]; - var weight1 = weights1?[index]; - var originalData = BuildUshort4(weight0, weight1 ?? Vector4.Zero); - var byteValues = originalData.Select(x => (byte)Math.Round(x * 255f)).ToArray(); - return AdjustByteArray(byteValues, originalData); - } + index => BuildBlendWeights(weights0[index], weights1?[index] ?? Vector4.Zero) ); } - - private static byte[] AdjustByteArray(byte[] byteValues, float[] originalValues) + + private static byte[] BuildBlendWeights(Vector4 v1, Vector4 v2) { + var originalData = BuildUshort4(v1, v2); + var byteValues = new byte[originalData.Length]; + for (var i = 0; i < originalData.Length; i++) + { + byteValues[i] = (byte)Math.Round(originalData[i] * 255f); + } + // Blend weights are _very_ sensitive to float imprecision - a vertex sum being off // by one, such as 256, is enough to cause a visible defect. To avoid this, we tweak // the converted values to have the expected sum, preferencing values with minimal differences. - var adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + var adjustment = 255 - byteValues.Sum(value => value); while (adjustment != 0) { - var convertedValues = byteValues.Select(value => value * (1f / 255f)).ToArray(); var closestIndex = Enumerable.Range(0, byteValues.Length) - .Where(index => + .Where(i => adjustment switch { - var byteValue = byteValues[index]; - if (adjustment < 0) - return byteValue > 0; - if (adjustment > 0) - return byteValue < 255; - - return true; + < 0 when byteValues[i] > 0 => true, + > 0 when byteValues[i] < 255 => true, + _ => true, }) - .Select(index => (index, delta: Math.Abs(originalValues[index] - convertedValues[index]))) + .Select(index => (index, delta: Math.Abs(originalData[index] - (byteValues[index] * (1f / 255f))))) .MinBy(x => x.delta) .index; - byteValues[closestIndex] = (byte)(byteValues[closestIndex] + Math.CopySign(1, adjustment)); - adjustment = 255 - byteValues.Select(value => (int)value).Sum(); + byteValues[closestIndex] += (byte)Math.CopySign(1, adjustment); + adjustment = 255 - byteValues.Sum(value => value); } - + return byteValues; } @@ -226,7 +222,7 @@ public class VertexAttribute gltfWeights0.W == 0 ? 0 : boneMap[(ushort)gltfIndices0.W] ); - Vector4 v1; + var v1 = Vector4.Zero; if (gltfIndices1 != null && gltfWeights1 != null) { v1 = new Vector4( @@ -236,10 +232,6 @@ public class VertexAttribute gltfWeights1.Value.W == 0 ? 0 : boneMap[(ushort)gltfIndices1.Value.W] ); } - else - { - v1 = Vector4.Zero; - } var byteValues = BuildUshort4(v0, v1); From 4719f413b6b7c101239490223f90c5e32a5f5de6 Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Tue, 13 Aug 2024 23:42:21 +1000 Subject: [PATCH 0927/1381] Fix adjustment switch --- Penumbra/Import/Models/Import/VertexAttribute.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index 14a830d4..a1c3246b 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -168,9 +168,9 @@ public class VertexAttribute var closestIndex = Enumerable.Range(0, byteValues.Length) .Where(i => adjustment switch { - < 0 when byteValues[i] > 0 => true, - > 0 when byteValues[i] < 255 => true, - _ => true, + < 0 => byteValues[i] > 0, + > 0 => byteValues[i] < 255, + _ => true, }) .Select(index => (index, delta: Math.Abs(originalData[index] - (byteValues[index] * (1f / 255f))))) .MinBy(x => x.delta) From 8fa0875ec6bf37e2d48ddde571c77c724c528ccc Mon Sep 17 00:00:00 2001 From: ackwell Date: Sun, 1 Sep 2024 21:32:31 +1000 Subject: [PATCH 0928/1381] Fix character*.shpk exports --- .../Import/Models/Export/MaterialExporter.cs | 188 ++++++++++-------- 1 file changed, 107 insertions(+), 81 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 62892473..0f98e5c4 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -36,12 +36,13 @@ public class MaterialExporter return material.Mtrl.ShaderPackage.Name switch { // NOTE: this isn't particularly precise to game behavior (it has some fade around high opacity), but good enough for now. - "character.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), - "characterglass.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.BLEND), - "hair.shpk" => BuildHair(material, name), - "iris.shpk" => BuildIris(material, name), - "skin.shpk" => BuildSkin(material, name), - _ => BuildFallback(material, name, notifier), + "character.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), + "characterlegacy.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), + "characterglass.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.BLEND), + "hair.shpk" => BuildHair(material, name), + "iris.shpk" => BuildIris(material, name), + "skin.shpk" => BuildSkin(material, name), + _ => BuildFallback(material, name, notifier), }; } @@ -49,70 +50,65 @@ public class MaterialExporter private static MaterialBuilder BuildCharacter(Material material, string name) { // Build the textures from the color table. - var table = new LegacyColorTable(material.Mtrl.Table!); + var table = new ColorTable(material.Mtrl.Table!); + var indexTexture = material.Textures[(TextureUsage)1449103320]; + var indexOperation = new ProcessCharacterIndexOperation(indexTexture, table); + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, indexTexture.Bounds, in indexOperation); - var normal = material.Textures[TextureUsage.SamplerNormal]; + var normalTexture = material.Textures[TextureUsage.SamplerNormal]; + var normalOperation = new ProcessCharacterNormalOperation(normalTexture); + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normalTexture.Bounds, in normalOperation); - var operation = new ProcessCharacterNormalOperation(normal, table); - ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, normal.Bounds, in operation); + // Merge in opacity from the normal. + var baseColor = indexOperation.BaseColor; + MultiplyOperation.Execute(baseColor, normalOperation.BaseColorOpacity); - // Check if full textures are provided, and merge in if available. - var baseColor = operation.BaseColor; + // Check if a full diffuse is provided, and merge in if available. if (material.Textures.TryGetValue(TextureUsage.SamplerDiffuse, out var diffuse)) { - MultiplyOperation.Execute(diffuse, operation.BaseColor); + MultiplyOperation.Execute(diffuse, indexOperation.BaseColor); baseColor = diffuse; } - Image specular = operation.Specular; + var specular = indexOperation.Specular; if (material.Textures.TryGetValue(TextureUsage.SamplerSpecular, out var specularTexture)) { - MultiplyOperation.Execute(specularTexture, operation.Specular); + MultiplyOperation.Execute(specularTexture, indexOperation.Specular); specular = specularTexture; } // Pull further information from the mask. if (material.Textures.TryGetValue(TextureUsage.SamplerMask, out var maskTexture)) { - // Extract the red channel for "ambient occlusion". - maskTexture.Mutate(context => context.Resize(baseColor.Width, baseColor.Height)); - maskTexture.ProcessPixelRows(baseColor, (maskAccessor, baseColorAccessor) => - { - for (var y = 0; y < maskAccessor.Height; y++) - { - var maskSpan = maskAccessor.GetRowSpan(y); - var baseColorSpan = baseColorAccessor.GetRowSpan(y); + var maskOperation = new ProcessCharacterMaskOperation(maskTexture); + ParallelRowIterator.IterateRows(ImageSharpConfiguration.Default, maskTexture.Bounds, in maskOperation); - for (var x = 0; x < maskSpan.Length; x++) - baseColorSpan[x].FromVector4(baseColorSpan[x].ToVector4() * new Vector4(maskSpan[x].R / 255f)); - } - }); - // TODO: handle other textures stored in the mask? + // TODO: consider using the occusion gltf material property. + MultiplyOperation.Execute(baseColor, maskOperation.Occlusion); + + // Similar to base color's alpha, this is a pretty wasteful operation for a single channel. + MultiplyOperation.Execute(specular, maskOperation.SpecularFactor); } // Specular extension puts colour on RGB and factor on A. We're already packing like that, so we can reuse the texture. var specularImage = BuildImage(specular, name, "specular"); return BuildSharedBase(material, name) - .WithBaseColor(BuildImage(baseColor, name, "basecolor")) - .WithNormal(BuildImage(operation.Normal, name, "normal")) - .WithEmissive(BuildImage(operation.Emissive, name, "emissive"), Vector3.One, 1) + .WithBaseColor(BuildImage(baseColor, name, "basecolor")) + .WithNormal(BuildImage(normalOperation.Normal, name, "normal")) + .WithEmissive(BuildImage(indexOperation.Emissive, name, "emissive"), Vector3.One, 1) .WithSpecularFactor(specularImage, 1) .WithSpecularColor(specularImage); } - // TODO: It feels a little silly to request the entire normal here when extracting the normal only needs some of the components. - // As a future refactor, it would be neat to accept a single-channel field here, and then do composition of other stuff later. - // TODO(Dawntrail): Use the dedicated index (_id) map, that is not embedded in the normal map's alpha channel anymore. - private readonly struct ProcessCharacterNormalOperation(Image normal, LegacyColorTable table) : IRowOperation + private readonly struct ProcessCharacterIndexOperation(Image index, ColorTable table) : IRowOperation { - public Image Normal { get; } = normal.Clone(); - public Image BaseColor { get; } = new(normal.Width, normal.Height); - public Image Specular { get; } = new(normal.Width, normal.Height); - public Image Emissive { get; } = new(normal.Width, normal.Height); + public Image BaseColor { get; } = new(index.Width, index.Height); + public Image Specular { get; } = new(index.Width, index.Height); + public Image Emissive { get; } = new(index.Width, index.Height); - private Buffer2D NormalBuffer - => Normal.Frames.RootFrame.PixelBuffer; + private Buffer2D IndexBuffer + => index.Frames.RootFrame.PixelBuffer; private Buffer2D BaseColorBuffer => BaseColor.Frames.RootFrame.PixelBuffer; @@ -125,66 +121,96 @@ public class MaterialExporter public void Invoke(int y) { - var normalSpan = NormalBuffer.DangerousGetRowSpan(y); + var indexSpan = IndexBuffer.DangerousGetRowSpan(y); var baseColorSpan = BaseColorBuffer.DangerousGetRowSpan(y); var specularSpan = SpecularBuffer.DangerousGetRowSpan(y); var emissiveSpan = EmissiveBuffer.DangerousGetRowSpan(y); + for (var x = 0; x < indexSpan.Length; x++) + { + ref var indexPixel = ref indexSpan[x]; + + // Calculate and fetch the color table rows being used for this pixel. + var tablePair = (int) Math.Round(indexPixel.R / 17f); + var rowBlend = 1.0f - indexPixel.G / 255f; + + var prevRow = table[tablePair * 2]; + var nextRow = table[Math.Min(tablePair * 2 + 1, ColorTable.NumRows)]; + + // Lerp between table row values to fetch final pixel values for each subtexture. + var lerpedDiffuse = Vector3.Lerp((Vector3)prevRow.DiffuseColor, (Vector3)nextRow.DiffuseColor, rowBlend); + baseColorSpan[x].FromVector4(new Vector4(lerpedDiffuse, 1)); + + var lerpedSpecularColor = Vector3.Lerp((Vector3)prevRow.SpecularColor, (Vector3)nextRow.SpecularColor, rowBlend); + specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, 1)); + + var lerpedEmissive = Vector3.Lerp((Vector3)prevRow.EmissiveColor, (Vector3)nextRow.EmissiveColor, rowBlend); + emissiveSpan[x].FromVector4(new Vector4(lerpedEmissive, 1)); + } + } + } + + private readonly struct ProcessCharacterNormalOperation(Image normal) : IRowOperation + { + // TODO: Consider omitting the alpha channel here. + public Image Normal { get; } = normal.Clone(); + // TODO: We only really need the alpha here, however using A8 will result in the multiply later zeroing out the RGB channels. + public Image BaseColorOpacity { get; } = new(normal.Width, normal.Height); + + private Buffer2D NormalBuffer + => Normal.Frames.RootFrame.PixelBuffer; + + private Buffer2D BaseColorOpacityBuffer + => BaseColorOpacity.Frames.RootFrame.PixelBuffer; + + public void Invoke(int y) + { + var normalSpan = NormalBuffer.DangerousGetRowSpan(y); + var baseColorOpacitySpan = BaseColorOpacityBuffer.DangerousGetRowSpan(y); + for (var x = 0; x < normalSpan.Length; x++) { ref var normalPixel = ref normalSpan[x]; - // Table row data (.a) - var tableRow = GetTableRowIndices(normalPixel.A / 255f); - var prevRow = table[tableRow.Previous]; - var nextRow = table[tableRow.Next]; + baseColorOpacitySpan[x].FromVector4(Vector4.One); + baseColorOpacitySpan[x].A = normalPixel.B; - // Base colour (table, .b) - var lerpedDiffuse = Vector3.Lerp((Vector3)prevRow.DiffuseColor, (Vector3)nextRow.DiffuseColor, tableRow.Weight); - baseColorSpan[x].FromVector4(new Vector4(lerpedDiffuse, 1)); - baseColorSpan[x].A = normalPixel.B; - - // Specular (table) - var lerpedSpecularColor = Vector3.Lerp((Vector3)prevRow.SpecularColor, (Vector3)nextRow.SpecularColor, tableRow.Weight); - var lerpedSpecularFactor = float.Lerp((float)prevRow.SpecularMask, (float)nextRow.SpecularMask, tableRow.Weight); - specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, lerpedSpecularFactor)); - - // Emissive (table) - var lerpedEmissive = Vector3.Lerp((Vector3)prevRow.EmissiveColor, (Vector3)nextRow.EmissiveColor, tableRow.Weight); - emissiveSpan[x].FromVector4(new Vector4(lerpedEmissive, 1)); - - // Normal (.rg) - // TODO: we don't actually need alpha at all for normal, but _not_ using the existing rgba texture means I'll need a new one, with a new accessor. Think about it. normalPixel.B = byte.MaxValue; normalPixel.A = byte.MaxValue; } } } - private static TableRow GetTableRowIndices(float input) + private readonly struct ProcessCharacterMaskOperation(Image mask) : IRowOperation { - // These calculations are ported from character.shpk. - var smoothed = MathF.Floor(input * 7.5f % 1.0f * 2) - * (-input * 15 + MathF.Floor(input * 15 + 0.5f)) - + input * 15; + public Image Occlusion { get; } = new(mask.Width, mask.Height); + public Image SpecularFactor { get; } = new(mask.Width, mask.Height); - var stepped = MathF.Floor(smoothed + 0.5f); + private Buffer2D MaskBuffer + => mask.Frames.RootFrame.PixelBuffer; - return new TableRow + private Buffer2D OcclusionBuffer + => Occlusion.Frames.RootFrame.PixelBuffer; + + private Buffer2D SpecularFactorBuffer + => SpecularFactor.Frames.RootFrame.PixelBuffer; + + public void Invoke(int y) { - Stepped = (int)stepped, - Previous = (int)MathF.Floor(smoothed), - Next = (int)MathF.Ceiling(smoothed), - Weight = smoothed % 1, - }; - } + var maskSpan = MaskBuffer.DangerousGetRowSpan(y); + var occlusionSpan = OcclusionBuffer.DangerousGetRowSpan(y); + var specularFactorSpan = SpecularFactorBuffer.DangerousGetRowSpan(y); - private ref struct TableRow - { - public int Stepped; - public int Previous; - public int Next; - public float Weight; + for (var x = 0; x < maskSpan.Length; x++) + { + ref var maskPixel = ref maskSpan[x]; + + occlusionSpan[x].FromL8(new L8(maskPixel.B)); + + specularFactorSpan[x].FromVector4(Vector4.One); + specularFactorSpan[x].A = maskPixel.R; + } + } } private readonly struct MultiplyOperation From 8468ed2c07f808c60c00e1ddd09fd7f9a5aadc06 Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 2 Sep 2024 00:01:30 +1000 Subject: [PATCH 0929/1381] Fix skin.shpk --- .../Import/Models/Export/MaterialExporter.cs | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 0f98e5c4..ee8484f0 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -340,21 +340,7 @@ public class MaterialExporter var diffuse = material.Textures[TextureUsage.SamplerDiffuse]; var normal = material.Textures[TextureUsage.SamplerNormal]; - // Create a copy of the normal that's the same size as the diffuse for purposes of copying the opacity across. - var resizedNormal = normal.Clone(context => context.Resize(diffuse.Width, diffuse.Height)); - diffuse.ProcessPixelRows(resizedNormal, (diffuseAccessor, normalAccessor) => - { - for (var y = 0; y < diffuseAccessor.Height; y++) - { - var diffuseSpan = diffuseAccessor.GetRowSpan(y); - var normalSpan = normalAccessor.GetRowSpan(y); - - for (var x = 0; x < diffuseSpan.Length; x++) - diffuseSpan[x].A = normalSpan[x].B; - } - }); - - // Clear the blue channel out of the normal now that we're done with it. + // The normal also stores the skin color influence (.b) and wetness mask (.a) - remove. normal.ProcessPixelRows(normalAccessor => { for (var y = 0; y < normalAccessor.Height; y++) @@ -362,7 +348,10 @@ public class MaterialExporter var normalSpan = normalAccessor.GetRowSpan(y); for (var x = 0; x < normalSpan.Length; x++) + { normalSpan[x].B = byte.MaxValue; + normalSpan[x].A = byte.MaxValue; + } } }); From efd08ae0534cd6fc3489e3e605a4e38c52bb040e Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 2 Sep 2024 00:51:51 +1000 Subject: [PATCH 0930/1381] Add charactertattoo.shpk support --- .../Import/Models/Export/MaterialExporter.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index ee8484f0..31590400 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -39,6 +39,7 @@ public class MaterialExporter "character.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), "characterlegacy.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.MASK, 0.5f), "characterglass.shpk" => BuildCharacter(material, name).WithAlpha(AlphaMode.BLEND), + "charactertattoo.shpk" => BuildCharacterTattoo(material, name), "hair.shpk" => BuildHair(material, name), "iris.shpk" => BuildIris(material, name), "skin.shpk" => BuildSkin(material, name), @@ -244,6 +245,37 @@ public class MaterialExporter } } + private static readonly Vector4 DefaultTattooColor = new Vector4(38, 112, 102, 255) / new Vector4(255); + + private static MaterialBuilder BuildCharacterTattoo(Material material, string name) + { + var normal = material.Textures[TextureUsage.SamplerNormal]; + var baseColor = new Image(normal.Width, normal.Height); + + normal.ProcessPixelRows(baseColor, (normalAccessor, baseColorAccessor) => + { + for (var y = 0; y < normalAccessor.Height; y++) + { + var normalSpan = normalAccessor.GetRowSpan(y); + var baseColorSpan = baseColorAccessor.GetRowSpan(y); + + for (var x = 0; x < normalSpan.Length; x++) + { + baseColorSpan[x].FromVector4(DefaultTattooColor); + baseColorSpan[x].A = normalSpan[x].A; + + normalSpan[x].B = byte.MaxValue; + normalSpan[x].A = byte.MaxValue; + } + } + }); + + return BuildSharedBase(material, name) + .WithBaseColor(BuildImage(baseColor, name, "basecolor")) + .WithNormal(BuildImage(normal, name, "normal")) + .WithAlpha(AlphaMode.BLEND); + } + // TODO: These are hardcoded colours - I'm not keen on supporting highly customizable exports, but there's possibly some more sensible values to use here. private static readonly Vector4 DefaultHairColor = new Vector4(130, 64, 13, 255) / new Vector4(255); private static readonly Vector4 DefaultHighlightColor = new Vector4(77, 126, 240, 255) / new Vector4(255); From 3b21de35cc0e0fac14d4d13600f4adffa2aa60cc Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 2 Sep 2024 01:06:51 +1000 Subject: [PATCH 0931/1381] Fix iris.shpk --- .../Import/Models/Export/MaterialExporter.cs | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 31590400..bcacf371 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -327,26 +327,23 @@ public class MaterialExporter // NOTE: This is largely the same as the hair material, but is also missing a few features that would cause it to diverge. Keeping separate for now. private static MaterialBuilder BuildIris(Material material, string name) { - var normal = material.Textures[TextureUsage.SamplerNormal]; - var mask = material.Textures[TextureUsage.SamplerMask]; + var normal = material.Textures[TextureUsage.SamplerNormal]; + var mask = material.Textures[TextureUsage.SamplerMask]; + var baseColor = material.Textures[TextureUsage.SamplerDiffuse]; - mask.Mutate(context => context.Resize(normal.Width, normal.Height)); + mask.Mutate(context => context.Resize(baseColor.Width, baseColor.Height)); - var baseColor = new Image(normal.Width, normal.Height); - normal.ProcessPixelRows(mask, baseColor, (normalAccessor, maskAccessor, baseColorAccessor) => + baseColor.ProcessPixelRows(mask, (baseColorAccessor, maskAccessor) => { - for (var y = 0; y < normalAccessor.Height; y++) + for (var y = 0; y < baseColor.Height; y++) { - var normalSpan = normalAccessor.GetRowSpan(y); - var maskSpan = maskAccessor.GetRowSpan(y); var baseColorSpan = baseColorAccessor.GetRowSpan(y); + var maskSpan = maskAccessor.GetRowSpan(y); - for (var x = 0; x < normalSpan.Length; x++) + for (var x = 0; x < baseColorSpan.Length; x++) { - baseColorSpan[x].FromVector4(DefaultEyeColor * new Vector4(maskSpan[x].R / 255f)); - baseColorSpan[x].A = normalSpan[x].A; - - normalSpan[x].A = byte.MaxValue; + var eyeColor = Vector4.Lerp(Vector4.One, DefaultEyeColor, maskSpan[x].B / 255f); + baseColorSpan[x].FromVector4(baseColorSpan[x].ToVector4() * eyeColor); } } }); From a1a880a0f4a85bdbe823e6e972f0bc59e2b8305f Mon Sep 17 00:00:00 2001 From: ackwell Date: Mon, 2 Sep 2024 01:30:21 +1000 Subject: [PATCH 0932/1381] Fix hair.shpk --- Penumbra/Import/Models/Export/MaterialExporter.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index bcacf371..121e6eed 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -306,10 +306,11 @@ public class MaterialExporter for (var x = 0; x < normalSpan.Length; x++) { - var color = Vector4.Lerp(DefaultHairColor, DefaultHighlightColor, maskSpan[x].A / 255f); - baseColorSpan[x].FromVector4(color * new Vector4(maskSpan[x].R / 255f)); + var color = Vector4.Lerp(DefaultHairColor, DefaultHighlightColor, normalSpan[x].B / 255f); + baseColorSpan[x].FromVector4(color * new Vector4(maskSpan[x].A / 255f)); baseColorSpan[x].A = normalSpan[x].A; + normalSpan[x].B = byte.MaxValue; normalSpan[x].A = byte.MaxValue; } } From 76c0264cbee424429b7b6c611378015d227fd4c0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 6 Oct 2024 14:05:13 +0200 Subject: [PATCH 0933/1381] Reenable model IO for testing. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 490fa147..de088736 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -97,9 +97,7 @@ public partial class ModEditWindow private void DrawImportExport(MdlTab tab, bool disabled) { - // TODO: Enable when functional. - using var dawntrailDisabled = ImRaii.Disabled(); - if (!ImGui.CollapsingHeader("Import / Export (currently disabled due to Dawntrail format changes)") || true) + if (!ImGui.CollapsingHeader("Import / Export")) return; var childSize = new Vector2((ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); From df0526e6e510c5129aa0deaf5038728318e5552f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 6 Oct 2024 14:23:36 +0200 Subject: [PATCH 0934/1381] Fix readoing and displaying DemiHuman IMC Identifiers. --- Penumbra/Meta/Manipulations/Imc.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index 1b2492ee..cba6c379 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -68,9 +68,13 @@ public readonly record struct ImcIdentifier( => (MetaIndex)(-1); public override string ToString() - => ObjectType is ObjectType.Equipment or ObjectType.Accessory - ? $"Imc - {PrimaryId} - {EquipSlot.ToName()} - {Variant}" - : $"Imc - {PrimaryId} - {ObjectType.ToName()} - {SecondaryId} - {BodySlot} - {Variant}"; + => ObjectType switch + { + ObjectType.Equipment or ObjectType.Accessory => $"Imc - {PrimaryId} - {EquipSlot.ToName()} - {Variant}", + ObjectType.DemiHuman => $"Imc - {PrimaryId} - DemiHuman - {SecondaryId} - {EquipSlot.ToName()} - {Variant}", + _ => $"Imc - {PrimaryId} - {ObjectType.ToName()} - {SecondaryId} - {BodySlot} - {Variant}", + }; + public bool Validate() { @@ -102,6 +106,7 @@ public readonly record struct ImcIdentifier( return false; if (ItemData.AdaptOffhandImc(PrimaryId, out _)) return false; + break; } @@ -163,7 +168,7 @@ public readonly record struct ImcIdentifier( case ObjectType.DemiHuman: { var secondaryId = new SecondaryId(jObj["SecondaryId"]?.ToObject() ?? 0); - var slot = jObj["Slot"]?.ToObject() ?? EquipSlot.Unknown; + var slot = jObj["EquipSlot"]?.ToObject() ?? EquipSlot.Unknown; ret = new ImcIdentifier(primaryId, (Variant)variant, objectType, secondaryId, slot, BodySlot.Unknown); break; } From 740816f3a670d9f53759d674795456a193ca202d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 6 Oct 2024 14:51:52 +0200 Subject: [PATCH 0935/1381] Fix accessory VFX change not working. --- .../Hooks/Resources/ResolvePathHooksBase.cs | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index b1b23f27..a31dee4c 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -3,6 +3,8 @@ using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Services; using Penumbra.Collections; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; namespace Penumbra.Interop.Hooks.Resources; @@ -212,25 +214,39 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ret; } + [StructLayout(LayoutKind.Explicit)] + private struct ChangedEquipData + { + [FieldOffset(0)] + public PrimaryId Model; + + [FieldOffset(2)] + public Variant Variant; + + [FieldOffset(20)] + public ushort VfxId; + + [FieldOffset(22)] + public GenderRace GenderRace; + } + private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) { if (slotIndex is <= 4 or >= 10) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - var changedEquipData = ((Human*)drawObject)->ChangedEquipData; + var changedEquipData = (ChangedEquipData*)((Human*)drawObject)->ChangedEquipData; // Enable vfxs for accessories if (changedEquipData == null) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - var slot = (ushort*)(changedEquipData + 12 * (nint)slotIndex); - var model = slot[0]; - var variant = slot[1]; - var vfxId = slot[4]; + ref var slot = ref changedEquipData[slotIndex]; - if (model == 0 || variant == 0 || vfxId == 0) + if (slot.Model == 0 || slot.Variant == 0 || slot.VfxId == 0) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), $"chara/accessory/a{model:D4}/vfx/eff/va{vfxId:D4}.avfx\0", + if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), + $"chara/accessory/a{slot.Model.Id:D4}/vfx/eff/va{slot.VfxId:D4}.avfx\0", out _)) return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); From c4b59295cb4db0ab1782fec14137d85b9e6de153 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 6 Oct 2024 12:54:51 +0000 Subject: [PATCH 0936/1381] [CI] Updating repo.json for testing_1.2.1.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 36b27682..38ea45c0 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.5", + "TestingAssemblyVersion": "1.2.1.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 2e424a693d67f16c02e154c28a8f63d9f7056fb2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 7 Oct 2024 16:18:51 +0200 Subject: [PATCH 0937/1381] Update GameData --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index dd86dafb..34c96a55 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit dd86dafb88ca4c7b662938bbc1310729ba7f788d +Subproject commit 34c96a55efe1ce1296d9edcd8296f6396998cc6a From 4a0c996ff6d492d887a4712606f15e7cf69cb73a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 9 Oct 2024 18:47:30 +0200 Subject: [PATCH 0938/1381] Fix some off-by-one errors with the import progress reports, add test implementation for pbd editing. --- Penumbra.GameData | 2 +- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 17 +- Penumbra/Import/TexToolsImporter.Gui.cs | 19 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 2 + Penumbra/Mods/Editor/ModFileCollection.cs | 18 +- .../AdvancedWindow/ModEditWindow.Deformers.cs | 324 ++++++++++++++++++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 6 + 7 files changed, 368 insertions(+), 20 deletions(-) create mode 100644 Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 34c96a55..07b01ec9 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 34c96a55efe1ce1296d9edcd8296f6396998cc6a +Subproject commit 07b01ec9b043e4b8f56d084f5d6cde1ed4ed9a58 diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 6d4f17b2..f6d1c9eb 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -9,7 +9,6 @@ using Penumbra.Api.Api; using Penumbra.Api.Enums; using Penumbra.Api.IpcSubscribers; using Penumbra.Collections.Manager; -using Penumbra.Meta.Manipulations; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; @@ -28,6 +27,8 @@ public class TemporaryIpcTester( { public Guid LastCreatedCollectionId = Guid.Empty; + private readonly bool _debug = Assembly.GetAssembly(typeof(TemporaryIpcTester))?.GetName().Version?.Major >= 9; + private Guid? _tempGuid; private string _tempCollectionName = string.Empty; private string _tempCollectionGuidName = string.Empty; @@ -48,9 +49,9 @@ public class TemporaryIpcTester( ImGui.InputTextWithHint("##tempCollection", "Collection Name...", ref _tempCollectionName, 128); ImGuiUtil.GuidInput("##guid", "Collection GUID...", string.Empty, ref _tempGuid, ref _tempCollectionGuidName); ImGui.InputInt("##tempActorIndex", ref _tempActorIndex, 0, 0); - ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); - ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); - ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); + ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); + ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); + ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); ImUtf8.InputText("##tempManip"u8, ref _tempManipulation, "Manipulation Base64 String..."u8); ImGui.Checkbox("Force Character Collection Overwrite", ref _forceOverwrite); @@ -102,7 +103,7 @@ public class TemporaryIpcTester( !collections.Storage.ByName(_tempModName, out var copyCollection)) && copyCollection is { HasCache: true }) { - var files = copyCollection.ResolvedFiles.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.Path.ToString()); + var files = copyCollection.ResolvedFiles.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.Path.ToString()); var manips = MetaApi.CompressMetaManipulations(copyCollection); _lastTempError = new AddTemporaryMod(pi).Invoke(_tempModName, guid, files, manips, 999); } @@ -124,11 +125,11 @@ public class TemporaryIpcTester( public void DrawCollections() { - using var collTree = ImRaii.TreeNode("Temporary Collections##TempCollections"); + using var collTree = ImUtf8.TreeNode("Temporary Collections##TempCollections"u8); if (!collTree) return; - using var table = ImRaii.Table("##collTree", 6, ImGuiTableFlags.SizingFixedFit); + using var table = ImUtf8.Table("##collTree"u8, 6, ImGuiTableFlags.SizingFixedFit); if (!table) return; @@ -139,7 +140,7 @@ public class TemporaryIpcTester( var character = tempCollections.Collections.Where(p => p.Collection == collection).Select(p => p.DisplayName) .FirstOrDefault() ?? "Unknown"; - if (ImGui.Button("Save##Collection")) + if (_debug && ImUtf8.Button("Save##Collection"u8)) TemporaryMod.SaveTempCollection(config, saveService, modManager, collection, character); using (ImRaii.PushFont(UiBuilder.MonoFont)) diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index a069204c..f145f560 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -46,21 +46,28 @@ public partial class TexToolsImporter { ImGui.NewLine(); ImGui.NewLine(); - percentage = _currentNumOptions == 0 ? 1f : _currentOptionIdx / (float)_currentNumOptions; - ImGui.ProgressBar(percentage, size, $"Option {_currentOptionIdx + 1} / {_currentNumOptions}"); + if (_currentOptionIdx >= _currentNumOptions) + ImGui.ProgressBar(1f, size, $"Extracted {_currentNumOptions} Options"); + else + ImGui.ProgressBar(_currentOptionIdx / (float)_currentNumOptions, size, + $"Extracting Option {_currentOptionIdx + 1} / {_currentNumOptions}..."); + ImGui.NewLine(); if (State != ImporterState.DeduplicatingFiles) ImGui.TextUnformatted( - $"Extracting option {(_currentGroupName.Length == 0 ? string.Empty : $"{_currentGroupName} - ")}{_currentOptionName}..."); + $"Extracting Option {(_currentGroupName.Length == 0 ? string.Empty : $"{_currentGroupName} - ")}{_currentOptionName}..."); } ImGui.NewLine(); ImGui.NewLine(); - percentage = _currentNumFiles == 0 ? 1f : _currentFileIdx / (float)_currentNumFiles; - ImGui.ProgressBar(percentage, size, $"File {_currentFileIdx + 1} / {_currentNumFiles}"); + if (_currentFileIdx >= _currentNumFiles) + ImGui.ProgressBar(1f, size, $"Extracted {_currentNumFiles} Files"); + else + ImGui.ProgressBar(_currentFileIdx / (float)_currentNumFiles, size, $"Extracting File {_currentFileIdx + 1} / {_currentNumFiles}..."); + ImGui.NewLine(); if (State != ImporterState.DeduplicatingFiles) - ImGui.TextUnformatted($"Extracting file {_currentFileName}..."); + ImGui.TextUnformatted($"Extracting File {_currentFileName}..."); return false; } diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 3ae1eda9..7bbb762e 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -151,6 +151,7 @@ public partial class TexToolsImporter _currentGroupName = string.Empty; _currentOptionName = "Default"; ExtractSimpleModList(_currentModDirectory, modList.SimpleModsList); + ++_currentOptionIdx; } // Iterate through all pages @@ -208,6 +209,7 @@ public partial class TexToolsImporter options.Insert(idx, MultiSubMod.WithoutGroup(option.Name, option.Description, ModPriority.Default)); if (option.IsChecked) defaultSettings = Setting.Single(idx); + ++_currentOptionIdx; } } diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 241f5b3b..20423493 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -12,6 +12,7 @@ public class ModFileCollection : IDisposable, IService private readonly List _mdl = []; private readonly List _tex = []; private readonly List _shpk = []; + private readonly List _pbd = []; private readonly SortedSet _missing = []; private readonly HashSet _usedPaths = []; @@ -23,19 +24,22 @@ public class ModFileCollection : IDisposable, IService => Ready ? _usedPaths : []; public IReadOnlyList Available - => Ready ? _available : Array.Empty(); + => Ready ? _available : []; public IReadOnlyList Mtrl - => Ready ? _mtrl : Array.Empty(); + => Ready ? _mtrl : []; public IReadOnlyList Mdl - => Ready ? _mdl : Array.Empty(); + => Ready ? _mdl : []; public IReadOnlyList Tex - => Ready ? _tex : Array.Empty(); + => Ready ? _tex : []; public IReadOnlyList Shpk - => Ready ? _shpk : Array.Empty(); + => Ready ? _shpk : []; + + public IReadOnlyList Pbd + => Ready ? _pbd : []; public bool Ready { get; private set; } = true; @@ -128,6 +132,9 @@ public class ModFileCollection : IDisposable, IService case ".shpk": _shpk.Add(registry); break; + case ".pbd": + _pbd.Add(registry); + break; } } } @@ -139,6 +146,7 @@ public class ModFileCollection : IDisposable, IService _mdl.Clear(); _tex.Clear(); _shpk.Clear(); + _pbd.Clear(); } private void ClearPaths(bool clearRegistries, CancellationToken tok) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs new file mode 100644 index 00000000..1b6535a7 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs @@ -0,0 +1,324 @@ +using Dalamud.Interface; +using Dalamud.Interface.ImGuiNotification; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui; +using OtterGui.Text; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Files; +using Penumbra.UI.Classes; +using Notification = OtterGui.Classes.Notification; + +namespace Penumbra.UI.AdvancedWindow; + +public partial class ModEditWindow +{ + private readonly FileEditor _pbdTab; + private readonly PbdData _pbdData = new(); + + private bool DrawDeformerPanel(PbdTab tab, bool disabled) + { + _pbdData.Update(tab.File); + DrawGenderRaceSelector(tab); + ImGui.SameLine(); + DrawBoneSelector(); + ImGui.SameLine(); + return DrawBoneData(tab, disabled); + } + + private void DrawGenderRaceSelector(PbdTab tab) + { + using var group = ImUtf8.Group(); + var width = ImUtf8.CalcTextSize("Hellsguard - Female (Child)____0000"u8).X + 2 * ImGui.GetStyle().WindowPadding.X; + using (ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0) + .Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero)) + { + ImGui.SetNextItemWidth(width); + ImUtf8.InputText("##grFilter"u8, ref _pbdData.RaceCodeFilter, "Filter..."u8); + } + + using var child = ImUtf8.Child("GenderRace"u8, new Vector2(width, ImGui.GetContentRegionMax().Y), true); + if (!child) + return; + + var metaColor = ColorId.ItemId.Value(); + foreach (var (deformer, index) in tab.File.Deformers.WithIndex()) + { + var name = deformer.GenderRace.ToName(); + var raceCode = deformer.GenderRace.ToRaceCode(); + // No clipping necessary since this are not that many objects anyway. + if (!name.Contains(_pbdData.RaceCodeFilter) && !raceCode.Contains(_pbdData.RaceCodeFilter)) + continue; + + using var id = ImUtf8.PushId(index); + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), deformer.RacialDeformer.IsEmpty); + if (ImUtf8.Selectable(name, deformer.GenderRace == _pbdData.SelectedRaceCode)) + { + _pbdData.SelectedRaceCode = deformer.GenderRace; + _pbdData.SelectedDeformer = deformer.RacialDeformer; + } + + ImGui.SameLine(); + color.Push(ImGuiCol.Text, metaColor); + ImUtf8.TextRightAligned(raceCode); + } + } + + private void DrawBoneSelector() + { + using var group = ImUtf8.Group(); + var width = 200 * ImUtf8.GlobalScale; + using (ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0) + .Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero)) + { + ImGui.SetNextItemWidth(width); + ImUtf8.InputText("##boneFilter"u8, ref _pbdData.BoneFilter, "Filter..."u8); + } + + using var child = ImUtf8.Child("Bone"u8, new Vector2(width, ImGui.GetContentRegionMax().Y), true); + if (!child) + return; + + if (_pbdData.SelectedDeformer == null) + return; + + if (_pbdData.SelectedDeformer.IsEmpty) + { + ImUtf8.Text(""u8); + } + else + { + var height = ImGui.GetTextLineHeightWithSpacing(); + var skips = ImGuiClip.GetNecessarySkips(height); + var remainder = ImGuiClip.FilteredClippedDraw(_pbdData.SelectedDeformer.DeformMatrices.Keys, skips, + b => b.Contains(_pbdData.BoneFilter), bone + => + { + if (ImUtf8.Selectable(bone, bone == _pbdData.SelectedBone)) + _pbdData.SelectedBone = bone; + }); + ImGuiClip.DrawEndDummy(remainder, height); + } + } + + private bool DrawBoneData(PbdTab tab, bool disabled) + { + using var child = ImUtf8.Child("Data"u8, ImGui.GetContentRegionMax() with { X = ImGui.GetContentRegionAvail().X}, true); + if (!child) + return false; + + if (_pbdData.SelectedBone == null) + return false; + + if (!_pbdData.SelectedDeformer!.DeformMatrices.TryGetValue(_pbdData.SelectedBone, out var matrix)) + return false; + + var width = UiBuilder.MonoFont.GetCharAdvance('0') * 12 + ImGui.GetStyle().FramePadding.X * 2; + var dummyHeight = ImGui.GetTextLineHeight() / 2; + var ret = DrawAddNewBone(tab, disabled, width); + + ImUtf8.Dummy(0, dummyHeight); + ImGui.Separator(); + ImUtf8.Dummy(0, dummyHeight); + ret |= DrawDeformerMatrix(disabled, matrix, width); + ImUtf8.Dummy(0, dummyHeight); + ret |= DrawCopyPasteButtons(disabled, matrix, width); + + + ImUtf8.Dummy(0, dummyHeight); + ImGui.Separator(); + ImUtf8.Dummy(0, dummyHeight); + ret |= DrawDecomposedData(disabled, matrix, width); + + return ret; + } + + private bool DrawAddNewBone(PbdTab tab, bool disabled, float width) + { + var ret = false; + ImUtf8.TextFrameAligned("Copy the values of the bone "u8); + ImGui.SameLine(0, 0); + using (ImRaii.PushColor(ImGuiCol.Text, ColorId.NewMod.Value())) + { + ImUtf8.TextFrameAligned(_pbdData.SelectedBone); + } + ImGui.SameLine(0, 0); + ImUtf8.TextFrameAligned(" to a new bone of name"u8); + + var fullWidth = width * 4 + ImGui.GetStyle().ItemSpacing.X * 3; + ImGui.SetNextItemWidth(fullWidth); + ImUtf8.InputText("##newBone"u8, ref _pbdData.NewBoneName, "New Bone Name..."u8); + ImUtf8.TextFrameAligned("for all races that have a corresponding bone."u8); + ImGui.SameLine(0, fullWidth - width - ImGui.GetItemRectSize().X); + if (!ImUtf8.ButtonEx("Apply"u8, ""u8, new Vector2(width, 0), + disabled || _pbdData.NewBoneName.Length == 0 || _pbdData.SelectedBone == null)) + return ret; + + foreach (var deformer in tab.File.Deformers) + { + if (!deformer.RacialDeformer.DeformMatrices.TryGetValue(_pbdData.SelectedBone!, out var existingMatrix)) + continue; + + if (!deformer.RacialDeformer.DeformMatrices.TryAdd(_pbdData.NewBoneName, existingMatrix) + && deformer.RacialDeformer.DeformMatrices.TryGetValue(_pbdData.NewBoneName, out var newBoneMatrix) + && !newBoneMatrix.Equals(existingMatrix)) + Penumbra.Messager.AddMessage(new Notification( + $"Could not add deformer matrix to {deformer.GenderRace.ToName()}, Bone {_pbdData.NewBoneName} because it already has a deformer that differs from the intended one.", + NotificationType.Warning)); + else + ret = true; + } + + _pbdData.NewBoneName = string.Empty; + return ret; + } + + private bool DrawDeformerMatrix(bool disabled, in TransformMatrix matrix, float width) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var _ = ImRaii.Disabled(disabled); + var ret = false; + for (var i = 0; i < 3; ++i) + { + for (var j = 0; j < 4; ++j) + { + using var id = ImUtf8.PushId(i * 4 + j); + ImGui.SetNextItemWidth(width); + var tmp = matrix[i, j]; + if (ImUtf8.InputScalar(""u8, ref tmp, "% 12.8f"u8)) + { + ret = true; + _pbdData.SelectedDeformer!.DeformMatrices[_pbdData.SelectedBone!] = matrix.ChangeValue(i, j, tmp); + } + + ImGui.SameLine(); + } + + ImGui.NewLine(); + } + + return ret; + } + + private bool DrawCopyPasteButtons(bool disabled, in TransformMatrix matrix, float width) + { + var size = new Vector2(width, 0); + if (ImUtf8.Button("Copy Values"u8, size)) + _pbdData.CopiedMatrix = matrix; + + ImGui.SameLine(); + + if (ImUtf8.ButtonEx("Paste Values"u8, ""u8, size, disabled || !_pbdData.CopiedMatrix.HasValue)) + { + _pbdData.SelectedDeformer!.DeformMatrices[_pbdData.SelectedBone!] = _pbdData.CopiedMatrix!.Value; + return true; + } + + return false; + } + + private bool DrawDecomposedData(bool disabled, in TransformMatrix matrix, float width) + { + var ret = false; + + + if (!matrix.TryDecompose(out var scale, out var rotation, out var translation)) + return false; + + using (ImUtf8.Group()) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + using var _ = ImRaii.Disabled(disabled); + + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##ScaleX"u8, ref scale.X, "% 12.8f"u8); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##ScaleY"u8, ref scale.Y, "% 12.8f"u8); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##ScaleZ"u8, ref scale.Z, "% 12.8f"u8); + + + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##TranslationX"u8, ref translation.X, "% 12.8f"u8); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##TranslationY"u8, ref translation.Y, "% 12.8f"u8); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##TranslationZ"u8, ref translation.Z, "% 12.8f"u8); + + + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##RotationR"u8, ref rotation.W, "% 12.8f"u8); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##RotationI"u8, ref rotation.X, "% 12.8f"u8); + + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##RotationJ"u8, ref rotation.Y, "% 12.8f"u8); + ImGui.SameLine(); + ImGui.SetNextItemWidth(width); + ret |= ImUtf8.InputScalar("##RotationK"u8, ref rotation.Z, "% 12.8f"u8); + } + + ImGui.SameLine(); + using (ImUtf8.Group()) + { + ImUtf8.TextFrameAligned("Scale"u8); + ImUtf8.TextFrameAligned("Translation"u8); + ImUtf8.TextFrameAligned("Rotation (Quaternion, rijk)"u8); + } + + if (ret) + _pbdData.SelectedDeformer!.DeformMatrices[_pbdData.SelectedBone!] = TransformMatrix.Compose(scale, rotation, translation); + return ret; + } + + public class PbdTab(byte[] data, string filePath) : IWritable + { + public readonly string FilePath = filePath; + + public readonly PbdFile File = new(data); + + public bool Valid + => File.Valid; + + public byte[] Write() + => File.Write(); + } + + private class PbdData + { + public GenderRace SelectedRaceCode = GenderRace.Unknown; + public RacialDeformer? SelectedDeformer; + public string? SelectedBone; + public string NewBoneName = string.Empty; + public string BoneFilter = string.Empty; + public string RaceCodeFilter = string.Empty; + + public TransformMatrix? CopiedMatrix; + + public void Update(PbdFile file) + { + if (SelectedRaceCode is GenderRace.Unknown) + { + SelectedDeformer = null; + } + else + { + SelectedDeformer = file.Deformers.FirstOrDefault(p => p.GenderRace == SelectedRaceCode).RacialDeformer; + if (SelectedDeformer is null) + SelectedRaceCode = GenderRace.Unknown; + } + } + } +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index f2fe8b9e..1a4065bb 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -236,6 +236,8 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _itemSwapTab.DrawContent(); } + _pbdTab.Draw(); + DrawMissingFilesTab(); DrawMaterialReassignmentTab(); } @@ -665,6 +667,10 @@ public partial class ModEditWindow : Window, IDisposable, IUiService () => PopulateIsOnPlayer(_editor.Files.Shpk, ResourceType.Shpk), DrawShaderPackagePanel, () => Mod?.ModPath.FullName ?? string.Empty, (bytes, path, _) => new ShpkTab(_fileDialog, bytes, path)); + _pbdTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Deformers", ".pbd", + () => _editor.Files.Pbd, DrawDeformerPanel, + () => Mod?.ModPath.FullName ?? string.Empty, + (bytes, path, _) => new PbdTab(bytes, path)); _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); _resourceTreeFactory = resourceTreeFactory; From 40c772a9da9f8b41dad7e023b7a47c48ea8b338e Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 9 Oct 2024 16:49:59 +0000 Subject: [PATCH 0939/1381] [CI] Updating repo.json for testing_1.2.1.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 38ea45c0..0d9e071f 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.6", + "TestingAssemblyVersion": "1.2.1.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 2c5ffc1bc583db158c932ab057a686d6275186a2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Oct 2024 16:50:05 +0200 Subject: [PATCH 0940/1381] Add delete and single add button and fix child sizes. --- .../AdvancedWindow/ModEditWindow.Deformers.cs | 74 +++++++++++++------ 1 file changed, 52 insertions(+), 22 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs index 1b6535a7..258e51ff 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs @@ -38,7 +38,8 @@ public partial class ModEditWindow ImUtf8.InputText("##grFilter"u8, ref _pbdData.RaceCodeFilter, "Filter..."u8); } - using var child = ImUtf8.Child("GenderRace"u8, new Vector2(width, ImGui.GetContentRegionMax().Y), true); + using var child = ImUtf8.Child("GenderRace"u8, + new Vector2(width, ImGui.GetContentRegionMax().Y - ImGui.GetFrameHeight() - ImGui.GetStyle().WindowPadding.Y), true); if (!child) return; @@ -76,7 +77,8 @@ public partial class ModEditWindow ImUtf8.InputText("##boneFilter"u8, ref _pbdData.BoneFilter, "Filter..."u8); } - using var child = ImUtf8.Child("Bone"u8, new Vector2(width, ImGui.GetContentRegionMax().Y), true); + using var child = ImUtf8.Child("Bone"u8, + new Vector2(width, ImGui.GetContentRegionMax().Y - ImGui.GetFrameHeight() - ImGui.GetStyle().WindowPadding.Y), true); if (!child) return; @@ -104,7 +106,8 @@ public partial class ModEditWindow private bool DrawBoneData(PbdTab tab, bool disabled) { - using var child = ImUtf8.Child("Data"u8, ImGui.GetContentRegionMax() with { X = ImGui.GetContentRegionAvail().X}, true); + using var child = ImUtf8.Child("Data"u8, + ImGui.GetContentRegionAvail() with { Y = ImGui.GetContentRegionMax().Y - ImGui.GetStyle().WindowPadding.Y }, true); if (!child) return false; @@ -116,7 +119,7 @@ public partial class ModEditWindow var width = UiBuilder.MonoFont.GetCharAdvance('0') * 12 + ImGui.GetStyle().FramePadding.X * 2; var dummyHeight = ImGui.GetTextLineHeight() / 2; - var ret = DrawAddNewBone(tab, disabled, width); + var ret = DrawAddNewBone(tab, disabled, matrix, width); ImUtf8.Dummy(0, dummyHeight); ImGui.Separator(); @@ -134,7 +137,7 @@ public partial class ModEditWindow return ret; } - private bool DrawAddNewBone(PbdTab tab, bool disabled, float width) + private bool DrawAddNewBone(PbdTab tab, bool disabled, in TransformMatrix matrix, float width) { var ret = false; ImUtf8.TextFrameAligned("Copy the values of the bone "u8); @@ -143,6 +146,7 @@ public partial class ModEditWindow { ImUtf8.TextFrameAligned(_pbdData.SelectedBone); } + ImGui.SameLine(0, 0); ImUtf8.TextFrameAligned(" to a new bone of name"u8); @@ -151,26 +155,36 @@ public partial class ModEditWindow ImUtf8.InputText("##newBone"u8, ref _pbdData.NewBoneName, "New Bone Name..."u8); ImUtf8.TextFrameAligned("for all races that have a corresponding bone."u8); ImGui.SameLine(0, fullWidth - width - ImGui.GetItemRectSize().X); - if (!ImUtf8.ButtonEx("Apply"u8, ""u8, new Vector2(width, 0), + if (ImUtf8.ButtonEx("Apply"u8, ""u8, new Vector2(width, 0), disabled || _pbdData.NewBoneName.Length == 0 || _pbdData.SelectedBone == null)) - return ret; - - foreach (var deformer in tab.File.Deformers) { - if (!deformer.RacialDeformer.DeformMatrices.TryGetValue(_pbdData.SelectedBone!, out var existingMatrix)) - continue; + foreach (var deformer in tab.File.Deformers) + { + if (!deformer.RacialDeformer.DeformMatrices.TryGetValue(_pbdData.SelectedBone!, out var existingMatrix)) + continue; - if (!deformer.RacialDeformer.DeformMatrices.TryAdd(_pbdData.NewBoneName, existingMatrix) - && deformer.RacialDeformer.DeformMatrices.TryGetValue(_pbdData.NewBoneName, out var newBoneMatrix) - && !newBoneMatrix.Equals(existingMatrix)) - Penumbra.Messager.AddMessage(new Notification( - $"Could not add deformer matrix to {deformer.GenderRace.ToName()}, Bone {_pbdData.NewBoneName} because it already has a deformer that differs from the intended one.", - NotificationType.Warning)); - else - ret = true; + if (!deformer.RacialDeformer.DeformMatrices.TryAdd(_pbdData.NewBoneName, existingMatrix) + && deformer.RacialDeformer.DeformMatrices.TryGetValue(_pbdData.NewBoneName, out var newBoneMatrix) + && !newBoneMatrix.Equals(existingMatrix)) + Penumbra.Messager.AddMessage(new Notification( + $"Could not add deformer matrix to {deformer.GenderRace.ToName()}, Bone {_pbdData.NewBoneName} because it already has a deformer that differs from the intended one.", + NotificationType.Warning)); + else + ret = true; + } + + _pbdData.NewBoneName = string.Empty; } - _pbdData.NewBoneName = string.Empty; + if (ImUtf8.ButtonEx("Copy Values to Single New Bone Entry"u8, ""u8, new Vector2(fullWidth, 0), + disabled || _pbdData.NewBoneName.Length == 0 || _pbdData.SelectedDeformer!.DeformMatrices.ContainsKey(_pbdData.NewBoneName))) + { + _pbdData.SelectedDeformer!.DeformMatrices[_pbdData.NewBoneName] = matrix; + ret = true; + _pbdData.NewBoneName = string.Empty; + } + + return ret; } @@ -209,13 +223,29 @@ public partial class ModEditWindow ImGui.SameLine(); + var ret = false; if (ImUtf8.ButtonEx("Paste Values"u8, ""u8, size, disabled || !_pbdData.CopiedMatrix.HasValue)) { _pbdData.SelectedDeformer!.DeformMatrices[_pbdData.SelectedBone!] = _pbdData.CopiedMatrix!.Value; - return true; + ret = true; } - return false; + var modifier = _config.DeleteModModifier.IsActive(); + ImGui.SameLine(); + if (modifier) + { + if (ImUtf8.ButtonEx("Delete"u8, "Delete this bone entry."u8, size, disabled)) + { + ret |= _pbdData.SelectedDeformer!.DeformMatrices.Remove(_pbdData.SelectedBone!); + _pbdData.SelectedBone = null; + } + } + else + { + ImUtf8.ButtonEx("Delete"u8, $"Delete this bone entry. Hold {_config.DeleteModModifier} to delete.", size, true); + } + + return ret; } private bool DrawDecomposedData(bool disabled, in TransformMatrix matrix, float width) From 1d5a7a41ab9e056d7070d188d01f414debc1f81f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 11 Oct 2024 16:35:47 +0200 Subject: [PATCH 0941/1381] Remove BonusItem from use and update ResourceTree a bit. --- Penumbra.GameData | 2 +- .../ResolveContext.PathResolution.cs | 8 +- .../Interop/ResourceTree/ResolveContext.cs | 19 ++-- Penumbra/Interop/ResourceTree/ResourceTree.cs | 11 ++- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 94 ++++++++++--------- 5 files changed, 69 insertions(+), 65 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 07b01ec9..61e06785 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 07b01ec9b043e4b8f56d084f5d6cde1ed4ed9a58 +Subproject commit 61e067857c2cf62bf8426ff6b305e37990f7767a diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 43324516..c554d97a 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -36,13 +36,13 @@ internal partial record ResolveContext private Utf8GamePath ResolveEquipmentModelPath() { var path = IsEquipmentSlot(SlotIndex) - ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot) - : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot); + ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot.ToSlot()) + : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot.ToSlot()); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } private GenderRace ResolveModelRaceCode() - => ResolveEqdpRaceCode(Slot, Equipment.Set); + => ResolveEqdpRaceCode(Slot.ToSlot(), Equipment.Set); private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, PrimaryId primaryId) { @@ -161,7 +161,7 @@ internal partial record ResolveContext return variant.Id; } - var entry = ImcFile.GetEntry(imcFileData, Slot, variant, out var exists); + var entry = ImcFile.GetEntry(imcFileData, Slot.ToSlot(), variant, out var exists); if (!exists) return variant.Id; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index b99ee235..207551e7 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -30,7 +30,7 @@ internal record GlobalResolveContext( public readonly Dictionary<(Utf8GamePath, nint), ResourceNode> Nodes = new(128); public unsafe ResolveContext CreateContext(CharaBase* characterBase, uint slotIndex = 0xFFFFFFFFu, - EquipSlot slot = EquipSlot.Unknown, CharacterArmor equipment = default, SecondaryId secondaryId = default) + FullEquipType slot = FullEquipType.Unknown, CharacterArmor equipment = default, SecondaryId secondaryId = default) => new(this, characterBase, slotIndex, slot, equipment, secondaryId); } @@ -38,7 +38,7 @@ internal unsafe partial record ResolveContext( GlobalResolveContext Global, Pointer CharacterBasePointer, uint SlotIndex, - EquipSlot Slot, + FullEquipType Slot, CharacterArmor Equipment, SecondaryId SecondaryId) { @@ -346,13 +346,14 @@ internal unsafe partial record ResolveContext( if (isEquipment) foreach (var item in Global.Identifier.Identify(Equipment.Set, 0, Equipment.Variant, Slot.ToSlot())) { - var name = Slot switch + var name = item.Name; + if (Slot is FullEquipType.Finger) + name = SlotIndex switch { - EquipSlot.RFinger => "R: ", - EquipSlot.LFinger => "L: ", - _ => string.Empty, - } - + item.Name; + 8 => "R: " + name, + 9 => "L: " + name, + _ => name, + }; return new ResourceNode.UiData(name, item.Type.GetCategoryIcon().ToFlag()); } @@ -361,7 +362,7 @@ internal unsafe partial record ResolveContext( return dataFromPath; return isEquipment - ? new ResourceNode.UiData(Slot.ToName(), Slot.ToEquipType().GetCategoryIcon().ToFlag()) + ? new ResourceNode.UiData(Slot.ToName(), Slot.GetCategoryIcon().ToFlag()) : new ResourceNode.UiData(null, ChangedItemIconFlag.Unknown); } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 38f6fe97..246a4508 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -80,12 +80,13 @@ public class ResourceTree { ModelType.Human => i switch { - < 10 => globalContext.CreateContext(model, i, i.ToEquipSlot(), equipment[(int)i]), - 16 or 17 => globalContext.CreateContext(model, i, EquipSlot.Head, equipment[(int)(i - 6)]), - _ => globalContext.CreateContext(model, i), + < 10 => globalContext.CreateContext(model, i, i.ToEquipSlot().ToEquipType(), equipment[(int)i]), + 16 => globalContext.CreateContext(model, i, FullEquipType.Glasses, equipment[10]), + 17 => globalContext.CreateContext(model, i, FullEquipType.Unknown, equipment[11]), + _ => globalContext.CreateContext(model, i), }, _ => i < equipment.Length - ? globalContext.CreateContext(model, i, i.ToEquipSlot(), equipment[(int)i]) + ? globalContext.CreateContext(model, i, i.ToEquipSlot().ToEquipType(), equipment[(int)i]) : globalContext.CreateContext(model, i), }; @@ -133,7 +134,7 @@ public class ResourceTree var weapon = (Weapon*)subObject; // This way to tell apart MainHand and OffHand is not always accurate, but seems good enough for what we're doing with it. - var slot = weaponIndex > 0 ? EquipSlot.OffHand : EquipSlot.MainHand; + var slot = weaponIndex > 0 ? FullEquipType.UnknownOffhand : FullEquipType.UnknownMainhand; var equipment = new CharacterArmor(weapon->ModelSetId, (byte)weapon->Variant, new StainIds(weapon->Stain0, weapon->Stain1)); var weaponType = weapon->SecondaryId; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 361094c4..3aff2ac9 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -190,52 +190,6 @@ public class ResourceTreeViewer var frameHeight = ImGui.GetFrameHeight(); var cellHeight = _actionCapacity > 0 ? frameHeight : 0.0f; - bool MatchesFilter(ResourceNode node, ChangedItemIconFlag filterIcon) - { - if (!_typeFilter.HasFlag(filterIcon)) - return false; - - if (_nodeFilter.Length == 0) - return true; - - return node.Name != null && node.Name.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) - || node.FullPath.FullName.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) - || node.FullPath.InternalName.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) - || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); - } - - NodeVisibility CalculateNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemIconFlag parentFilterIcon) - { - if (node.Internal && !debugMode) - return NodeVisibility.Hidden; - - var filterIcon = node.IconFlag != 0 ? node.IconFlag : parentFilterIcon; - if (MatchesFilter(node, filterIcon)) - return NodeVisibility.Visible; - - foreach (var child in node.Children) - { - if (GetNodeVisibility(unchecked(nodePathHash * 31 + child.ResourceHandle), child, filterIcon) != NodeVisibility.Hidden) - return NodeVisibility.DescendentsOnly; - } - - return NodeVisibility.Hidden; - } - - NodeVisibility GetNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemIconFlag parentFilterIcon) - { - if (!_filterCache.TryGetValue(nodePathHash, out var visibility)) - { - visibility = CalculateNodeVisibility(nodePathHash, node, parentFilterIcon); - _filterCache.Add(nodePathHash, visibility); - } - - return visibility; - } - - string GetAdditionalDataSuffix(CiByteString data) - => !debugMode || data.IsEmpty ? string.Empty : $"\n\nAdditional Data: {data}"; - foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { var nodePathHash = unchecked(pathHash + resourceNode.ResourceHandle); @@ -346,6 +300,54 @@ public class ResourceTreeViewer if (unfolded) DrawNodes(resourceNode.Children, level + 1, unchecked(nodePathHash * 31), filterIcon); } + + return; + + string GetAdditionalDataSuffix(CiByteString data) + => !debugMode || data.IsEmpty ? string.Empty : $"\n\nAdditional Data: {data}"; + + NodeVisibility GetNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemIconFlag parentFilterIcon) + { + if (!_filterCache.TryGetValue(nodePathHash, out var visibility)) + { + visibility = CalculateNodeVisibility(nodePathHash, node, parentFilterIcon); + _filterCache.Add(nodePathHash, visibility); + } + + return visibility; + } + + NodeVisibility CalculateNodeVisibility(nint nodePathHash, ResourceNode node, ChangedItemIconFlag parentFilterIcon) + { + if (node.Internal && !debugMode) + return NodeVisibility.Hidden; + + var filterIcon = node.IconFlag != 0 ? node.IconFlag : parentFilterIcon; + if (MatchesFilter(node, filterIcon)) + return NodeVisibility.Visible; + + foreach (var child in node.Children) + { + if (GetNodeVisibility(unchecked(nodePathHash * 31 + child.ResourceHandle), child, filterIcon) != NodeVisibility.Hidden) + return NodeVisibility.DescendentsOnly; + } + + return NodeVisibility.Hidden; + } + + bool MatchesFilter(ResourceNode node, ChangedItemIconFlag filterIcon) + { + if (!_typeFilter.HasFlag(filterIcon)) + return false; + + if (_nodeFilter.Length == 0) + return true; + + return node.Name != null && node.Name.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || node.FullPath.FullName.Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || node.FullPath.InternalName.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) + || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); + } } [Flags] From db2ce1328ff058548ed159b6ac5908f43a6f2045 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 11 Oct 2024 18:19:12 +0200 Subject: [PATCH 0942/1381] Enable VFX for the glasses slot. --- Penumbra.GameData | 2 +- .../Hooks/Resources/ResolvePathHooksBase.cs | 61 ++++++++++++++----- 2 files changed, 47 insertions(+), 16 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 61e06785..2f6acca6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 61e067857c2cf62bf8426ff6b305e37990f7767a +Subproject commit 2f6acca678b71203763ac4404c3f054747c14f75 diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index a31dee4c..d55caf34 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -6,6 +6,7 @@ using Penumbra.Collections; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; +using static FFXIVClientStructs.FFXIV.Client.Game.Character.ActionEffectHandler; namespace Penumbra.Interop.Hooks.Resources; @@ -223,6 +224,12 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable [FieldOffset(2)] public Variant Variant; + [FieldOffset(8)] + public PrimaryId BonusModel; + + [FieldOffset(10)] + public Variant BonusVariant; + [FieldOffset(20)] public ushort VfxId; @@ -232,26 +239,50 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) { - if (slotIndex is <= 4 or >= 10) - return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + switch (slotIndex) + { + case <= 4: return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + case <= 10: + { + // Enable vfxs for accessories + var changedEquipData = (ChangedEquipData*)((Human*)drawObject)->ChangedEquipData; + if (changedEquipData == null) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - var changedEquipData = (ChangedEquipData*)((Human*)drawObject)->ChangedEquipData; - // Enable vfxs for accessories - if (changedEquipData == null) - return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + ref var slot = ref changedEquipData[slotIndex]; - ref var slot = ref changedEquipData[slotIndex]; + if (slot.Model == 0 || slot.Variant == 0 || slot.VfxId == 0) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - if (slot.Model == 0 || slot.Variant == 0 || slot.VfxId == 0) - return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), + $"chara/accessory/a{slot.Model.Id:D4}/vfx/eff/va{slot.VfxId:D4}.avfx\0", + out _)) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), - $"chara/accessory/a{slot.Model.Id:D4}/vfx/eff/va{slot.VfxId:D4}.avfx\0", - out _)) - return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + *(ulong*)unkOutParam = 4; + return ResolvePath(drawObject, pathBuffer); + } + case 16: + { + // Enable vfxs for glasses + var changedEquipData = (ChangedEquipData*)((Human*)drawObject)->ChangedEquipData; + if (changedEquipData == null) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); - *(ulong*)unkOutParam = 4; - return ResolvePath(drawObject, pathBuffer); + ref var slot = ref changedEquipData[slotIndex - 6]; + + if (slot.BonusModel == 0 || slot.BonusVariant == 0 || slot.VfxId == 0) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + if (!Utf8.TryWrite(new Span((void*)pathBuffer, (int)pathBufferSize), + $"chara/equipment/e{slot.BonusModel.Id:D4}/vfx/eff/ve{slot.VfxId:D4}.avfx\0", + out _)) + return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + + *(ulong*)unkOutParam = 4; + return ResolvePath(drawObject, pathBuffer); + } + default: return ResolveVfx(drawObject, pathBuffer, pathBufferSize, slotIndex, unkOutParam); + } } private nint VFunc81(nint drawObject, int estType, nint unk) From 97b310ca3ffa9397e722a429b8fc2665c4728e37 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 12 Oct 2024 15:13:06 +0200 Subject: [PATCH 0943/1381] Fix issue with meta file not being saved synchronously on creation. --- Penumbra/Mods/Manager/ModDataEditor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 933620d9..162f823d 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -37,7 +37,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic mod.Description = description ?? mod.Description; mod.Version = version ?? mod.Version; mod.Website = website ?? mod.Website; - saveService.ImmediateSave(new ModMeta(mod)); + saveService.ImmediateSaveSync(new ModMeta(mod)); } public ModDataChangeType LoadLocalData(Mod mod) From e646b48afaa58db4d1ac6c19fc7661cc8bbdbcc8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 12 Oct 2024 15:13:22 +0200 Subject: [PATCH 0944/1381] Add swaps to and from Glasses. --- Penumbra.GameData | 2 +- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 77 ++++++------ Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 135 ++++++++++++++++------ 3 files changed, 138 insertions(+), 76 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2f6acca6..63cbf824 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2f6acca678b71203763ac4404c3f054747c14f75 +Subproject commit 63cbf824178b5b1f91fd9edc22a6c2bbc2e1cd23 diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 1a2f2798..c7e43a26 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -32,26 +32,26 @@ public static class EquipmentSwap EquipSlot slotFrom, EquipItem itemFrom, EquipSlot slotTo, EquipItem itemTo) { LookupItem(itemFrom, out var actualSlotFrom, out var idFrom, out var variantFrom); - LookupItem(itemTo, out var actualSlotTo, out var idTo, out var variantTo); + LookupItem(itemTo, out var actualSlotTo, out var idTo, out var variantTo); if (actualSlotFrom != slotFrom.ToSlot() || actualSlotTo != slotTo.ToSlot()) throw new ItemSwap.InvalidItemTypeException(); var (imcFileFrom, variants, affectedItems) = GetVariants(manager, identifier, slotFrom, idFrom, idTo, variantFrom); var imcIdentifierTo = new ImcIdentifier(slotTo, idTo, variantTo); - var imcFileTo = new ImcFile(manager, imcIdentifierTo); + var imcFileTo = new ImcFile(manager, imcIdentifierTo); var imcEntry = manips.TryGetValue(imcIdentifierTo, out var entry) ? entry : imcFileTo.GetEntry(imcIdentifierTo.EquipSlot, imcIdentifierTo.Variant); var mtrlVariantTo = imcEntry.MaterialId; - var skipFemale = false; - var skipMale = false; + var skipFemale = false; + var skipMale = false; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) { - case Gender.Male when skipMale: continue; - case Gender.Female when skipFemale: continue; - case Gender.MaleNpc when skipMale: continue; + case Gender.Male when skipMale: continue; + case Gender.Female when skipFemale: continue; + case Gender.MaleNpc when skipMale: continue; case Gender.FemaleNpc when skipFemale: continue; } @@ -94,7 +94,7 @@ public static class EquipmentSwap { // Check actual ids, variants and slots. We only support using the same slot. LookupItem(itemFrom, out var slotFrom, out var idFrom, out var variantFrom); - LookupItem(itemTo, out var slotTo, out var idTo, out var variantTo); + LookupItem(itemTo, out var slotTo, out var idTo, out var variantTo); if (slotFrom != slotTo) throw new ItemSwap.InvalidItemTypeException(); @@ -111,7 +111,7 @@ public static class EquipmentSwap { (var imcFileFrom, var variants, affectedItems) = GetVariants(manager, identifier, slot, idFrom, idTo, variantFrom); var imcIdentifierTo = new ImcIdentifier(slotTo, idTo, variantTo); - var imcFileTo = new ImcFile(manager, imcIdentifierTo); + var imcFileTo = new ImcFile(manager, imcIdentifierTo); var imcEntry = manips.TryGetValue(imcIdentifierTo, out var entry) ? entry : imcFileTo.GetEntry(imcIdentifierTo.EquipSlot, imcIdentifierTo.Variant); @@ -122,18 +122,18 @@ public static class EquipmentSwap { EquipSlot.Head => EstType.Head, EquipSlot.Body => EstType.Body, - _ => (EstType)0, + _ => (EstType)0, }; var skipFemale = false; - var skipMale = false; + var skipMale = false; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) { - case Gender.Male when skipMale: continue; - case Gender.Female when skipFemale: continue; - case Gender.MaleNpc when skipMale: continue; + case Gender.Male when skipMale: continue; + case Gender.Female when skipFemale: continue; + case Gender.MaleNpc when skipMale: continue; case Gender.FemaleNpc when skipFemale: continue; } @@ -148,7 +148,7 @@ public static class EquipmentSwap swaps.Add(eqdp); var ownMdl = eqdp?.SwapToModdedEntry.Model ?? false; - var est = ItemSwap.CreateEst(manager, redirections, manips, estType, gr, idFrom, idTo, ownMdl); + var est = ItemSwap.CreateEst(manager, redirections, manips, estType, gr, idFrom, idTo, ownMdl); if (est != null) swaps.Add(est); } @@ -176,7 +176,6 @@ public static class EquipmentSwap return affectedItems; } - public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, MetaDictionary manips, EquipSlot slot, GenderRace gr, PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) => CreateEqdp(manager, redirections, manips, slot, slot, gr, idFrom, idTo, mtrlTo); @@ -186,9 +185,9 @@ public static class EquipmentSwap PrimaryId idTo, byte mtrlTo) { var eqdpFromIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); - var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); - var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); - var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); + var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); + var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); + var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); var meta = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, eqdpFromIdentifier, eqdpFromDefault, eqdpToIdentifier, eqdpToDefault); @@ -217,7 +216,7 @@ public static class EquipmentSwap ? GamePaths.Accessory.Mdl.Path(idFrom, gr, slotFrom) : GamePaths.Equipment.Mdl.Path(idFrom, gr, slotFrom); var mdlPathTo = slotTo.IsAccessory() ? GamePaths.Accessory.Mdl.Path(idTo, gr, slotTo) : GamePaths.Equipment.Mdl.Path(idTo, gr, slotTo); - var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); + var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); foreach (ref var fileName in mdl.AsMdl()!.Materials.AsSpan()) { @@ -242,13 +241,13 @@ public static class EquipmentSwap private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, ObjectIdentification identifier, EquipSlot slotFrom, PrimaryId idFrom, PrimaryId idTo, Variant variantFrom) { - var ident = new ImcIdentifier(slotFrom, idFrom, variantFrom); - var imc = new ImcFile(manager, ident); + var ident = new ImcIdentifier(slotFrom, idFrom, variantFrom); + var imc = new ImcFile(manager, ident); EquipItem[] items; - Variant[] variants; + Variant[] variants; if (idFrom == idTo) { - items = identifier.Identify(idFrom, 0, variantFrom, slotFrom).ToArray(); + items = identifier.Identify(idFrom, 0, variantFrom, slotFrom).ToArray(); variants = [variantFrom]; } else @@ -271,9 +270,9 @@ public static class EquipmentSwap return null; var manipFromIdentifier = new GmpIdentifier(idFrom); - var manipToIdentifier = new GmpIdentifier(idTo); - var manipFromDefault = ExpandedGmpFile.GetDefault(manager, manipFromIdentifier); - var manipToDefault = ExpandedGmpFile.GetDefault(manager, manipToIdentifier); + var manipToIdentifier = new GmpIdentifier(idTo); + var manipFromDefault = ExpandedGmpFile.GetDefault(manager, manipFromIdentifier); + var manipToDefault = ExpandedGmpFile.GetDefault(manager, manipToIdentifier); return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); } @@ -288,9 +287,9 @@ public static class EquipmentSwap Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) { var manipFromIdentifier = new ImcIdentifier(slotFrom, idFrom, variantFrom); - var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); - var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); - var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); + var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); + var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); + var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); var imc = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); @@ -329,7 +328,7 @@ public static class EquipmentSwap var vfxPathFrom = GamePaths.Equipment.Avfx.Path(idFrom, vfxId); vfxPathFrom = ItemSwap.ReplaceType(vfxPathFrom, slotFrom, slotTo, idFrom); var vfxPathTo = GamePaths.Equipment.Avfx.Path(idTo, vfxId); - var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); + var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); foreach (ref var filePath in avfx.AsAvfx()!.Textures.AsSpan()) { @@ -347,9 +346,9 @@ public static class EquipmentSwap return null; var manipFromIdentifier = new EqpIdentifier(idFrom, slot); - var manipToIdentifier = new EqpIdentifier(idTo, slot); - var manipFromDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idFrom), slot); - var manipToDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idTo), slot); + var manipToIdentifier = new EqpIdentifier(idTo, slot); + var manipFromDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idFrom), slot); + var manipToDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idTo), slot); return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); } @@ -381,7 +380,7 @@ public static class EquipmentSwap if (newFileName != fileName) { - fileName = newFileName; + fileName = newFileName; dataWasChanged = true; } @@ -406,13 +405,13 @@ public static class EquipmentSwap EquipSlot slotTo, PrimaryId idFrom, PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) { var addedDashes = GamePaths.Tex.HandleDx11Path(texture, out var path); - var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); + var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); newPath = ItemSwap.ReplaceSlot(newPath, slotTo, slotFrom, slotTo != slotFrom); newPath = ItemSwap.ReplaceType(newPath, slotFrom, slotTo, idFrom); newPath = ItemSwap.AddSuffix(newPath, ".tex", $"_{Path.GetFileName(texture.Path).GetStableHashCode():x8}"); if (newPath != path) { - texture.Path = addedDashes ? newPath.Replace("--", string.Empty) : newPath; + texture.Path = addedDashes ? newPath.Replace("--", string.Empty) : newPath; dataWasChanged = true; } @@ -430,8 +429,8 @@ public static class EquipmentSwap PrimaryId idFrom, ref string filePath, ref bool dataWasChanged) { var oldPath = filePath; - filePath = ItemSwap.AddSuffix(filePath, ".atex", $"_{Path.GetFileName(filePath).GetStableHashCode():x8}"); - filePath = ItemSwap.ReplaceType(filePath, slotFrom, slotTo, idFrom); + filePath = ItemSwap.AddSuffix(filePath, ".atex", $"_{Path.GetFileName(filePath).GetStableHashCode():x8}"); + filePath = ItemSwap.ReplaceType(filePath, slotFrom, slotTo, idFrom); dataWasChanged = true; return FileSwap.CreateSwap(manager, ResourceType.Atex, redirections, filePath, oldPath, oldPath); diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 6ed1b55d..3f7f2f6c 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -48,15 +48,16 @@ public class ItemSwapTab : IDisposable, ITab, IUiService _selectors = new Dictionary { // @formatter:off - [SwapType.Hat] = (new ItemSelector(itemService, selector, FullEquipType.Head), new ItemSelector(itemService, null, FullEquipType.Head), "Take this Hat", "and put it on this one" ), - [SwapType.Top] = (new ItemSelector(itemService, selector, FullEquipType.Body), new ItemSelector(itemService, null, FullEquipType.Body), "Take this Top", "and put it on this one" ), - [SwapType.Gloves] = (new ItemSelector(itemService, selector, FullEquipType.Hands), new ItemSelector(itemService, null, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), - [SwapType.Pants] = (new ItemSelector(itemService, selector, FullEquipType.Legs), new ItemSelector(itemService, null, FullEquipType.Legs), "Take these Pants", "and put them on these" ), - [SwapType.Shoes] = (new ItemSelector(itemService, selector, FullEquipType.Feet), new ItemSelector(itemService, null, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), - [SwapType.Earrings] = (new ItemSelector(itemService, selector, FullEquipType.Ears), new ItemSelector(itemService, null, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), - [SwapType.Necklace] = (new ItemSelector(itemService, selector, FullEquipType.Neck), new ItemSelector(itemService, null, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), - [SwapType.Bracelet] = (new ItemSelector(itemService, selector, FullEquipType.Wrists), new ItemSelector(itemService, null, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), - [SwapType.Ring] = (new ItemSelector(itemService, selector, FullEquipType.Finger), new ItemSelector(itemService, null, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), + [SwapType.Hat] = (new ItemSelector(itemService, selector, FullEquipType.Head), new ItemSelector(itemService, null, FullEquipType.Head), "Take this Hat", "and put it on this one" ), + [SwapType.Top] = (new ItemSelector(itemService, selector, FullEquipType.Body), new ItemSelector(itemService, null, FullEquipType.Body), "Take this Top", "and put it on this one" ), + [SwapType.Gloves] = (new ItemSelector(itemService, selector, FullEquipType.Hands), new ItemSelector(itemService, null, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), + [SwapType.Pants] = (new ItemSelector(itemService, selector, FullEquipType.Legs), new ItemSelector(itemService, null, FullEquipType.Legs), "Take these Pants", "and put them on these" ), + [SwapType.Shoes] = (new ItemSelector(itemService, selector, FullEquipType.Feet), new ItemSelector(itemService, null, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), + [SwapType.Earrings] = (new ItemSelector(itemService, selector, FullEquipType.Ears), new ItemSelector(itemService, null, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), + [SwapType.Necklace] = (new ItemSelector(itemService, selector, FullEquipType.Neck), new ItemSelector(itemService, null, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), + [SwapType.Bracelet] = (new ItemSelector(itemService, selector, FullEquipType.Wrists), new ItemSelector(itemService, null, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), + [SwapType.Ring] = (new ItemSelector(itemService, selector, FullEquipType.Finger), new ItemSelector(itemService, null, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), + [SwapType.Glasses] = (new ItemSelector(itemService, selector, FullEquipType.Glasses), new ItemSelector(itemService, null, FullEquipType.Glasses), "Take these Glasses", "and put them on these" ), // @formatter:on }; @@ -129,6 +130,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService Ears, Tail, Weapon, + Glasses, } private class ItemSelector(ItemData data, ModFileSystemSelector? selector, FullEquipType type) @@ -158,14 +160,14 @@ public class ItemSwapTab : IDisposable, ITab, IUiService private ModSettings? _modSettings; private bool _dirty; - private SwapType _lastTab = SwapType.Hair; - private Gender _currentGender = Gender.Male; - private ModelRace _currentRace = ModelRace.Midlander; - private int _targetId; - private int _sourceId; - private Exception? _loadException; - private EquipSlot _slotFrom = EquipSlot.Head; - private EquipSlot _slotTo = EquipSlot.Ears; + private SwapType _lastTab = SwapType.Hair; + private Gender _currentGender = Gender.Male; + private ModelRace _currentRace = ModelRace.Midlander; + private int _targetId; + private int _sourceId; + private Exception? _loadException; + private BetweenSlotTypes _slotFrom = BetweenSlotTypes.Hat; + private BetweenSlotTypes _slotTo = BetweenSlotTypes.Earrings; private string _newModName = string.Empty; private string _newGroupName = "Swaps"; @@ -200,18 +202,19 @@ public class ItemSwapTab : IDisposable, ITab, IUiService case SwapType.Necklace: case SwapType.Bracelet: case SwapType.Ring: + case SwapType.Glasses: var values = _selectors[_lastTab]; if (values.Source.CurrentSelection.Item.Type != FullEquipType.Unknown && values.Target.CurrentSelection.Item.Type != FullEquipType.Unknown) _affectedItems = _swapData.LoadEquipment(values.Target.CurrentSelection.Item, values.Source.CurrentSelection.Item, _useCurrentCollection ? _collectionManager.Active.Current : null, _useRightRing, _useLeftRing); - break; case SwapType.BetweenSlots: var (_, _, selectorFrom) = GetAccessorySelector(_slotFrom, true); var (_, _, selectorTo) = GetAccessorySelector(_slotTo, false); if (selectorFrom.CurrentSelection.Item.Valid && selectorTo.CurrentSelection.Item.Valid) - _affectedItems = _swapData.LoadTypeSwap(_slotTo, selectorTo.CurrentSelection.Item, _slotFrom, selectorFrom.CurrentSelection.Item, + _affectedItems = _swapData.LoadTypeSwap(ToEquipSlot(_slotTo), selectorTo.CurrentSelection.Item, ToEquipSlot(_slotFrom), + selectorFrom.CurrentSelection.Item, _useCurrentCollection ? _collectionManager.Active.Current : null); break; case SwapType.Hair when _targetId > 0 && _sourceId > 0: @@ -264,7 +267,23 @@ public class ItemSwapTab : IDisposable, ITab, IUiService } private string CreateDescription() - => $"Created by swapping {_lastTab} {_sourceId} onto {_lastTab} {_targetId} for {_currentRace.ToName()} {_currentGender.ToName()}s in {_mod!.Name}."; + { + switch (_lastTab) + { + case SwapType.Ears: + case SwapType.Face: + case SwapType.Hair: + case SwapType.Tail: + return + $"Created by swapping {_lastTab} {_sourceId} onto {_lastTab} {_targetId} for {_currentRace.ToName()} {_currentGender.ToName()}s in {_mod!.Name}."; + case SwapType.BetweenSlots: + return + $"Created by swapping {GetAccessorySelector(_slotFrom, true).Item3.CurrentSelection.Item.Name} onto {GetAccessorySelector(_slotTo, false).Item3.CurrentSelection.Item.Name} in {_mod!.Name}."; + default: + return + $"Created by swapping {_selectors[_lastTab].Source.CurrentSelection.Item.Name} onto {_selectors[_lastTab].Target.CurrentSelection.Item.Name} in {_mod!.Name}."; + } + } private void UpdateOption() { @@ -416,6 +435,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService DrawEquipmentSwap(SwapType.Necklace); DrawEquipmentSwap(SwapType.Bracelet); DrawEquipmentSwap(SwapType.Ring); + DrawEquipmentSwap(SwapType.Glasses); DrawAccessorySwap(); DrawHairSwap(); //DrawFaceSwap(); @@ -454,23 +474,24 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGui.TableNextColumn(); ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - using (var combo = ImRaii.Combo("##fromType", _slotFrom is EquipSlot.Head ? "Hat" : _slotFrom.ToName())) + using (var combo = ImRaii.Combo("##fromType", ToName(_slotFrom))) { if (combo) - foreach (var slot in EquipSlotExtensions.AccessorySlots.Prepend(EquipSlot.Head)) + foreach (var slot in Enum.GetValues()) { - if (!ImGui.Selectable(slot is EquipSlot.Head ? "Hat" : slot.ToName(), slot == _slotFrom) || slot == _slotFrom) + if (!ImGui.Selectable(ToName(slot), slot == _slotFrom) || slot == _slotFrom) continue; _dirty = true; _slotFrom = slot; if (slot == _slotTo) - _slotTo = EquipSlotExtensions.AccessorySlots.First(s => slot != s); + _slotTo = AvailableToTypes.First(s => slot != s); } } ImGui.TableNextColumn(); - _dirty |= selector.Draw("##itemSource", selector.CurrentSelection.Item.Name ?? string.Empty, string.Empty, InputWidth * 2 * UiHelpers.Scale, + _dirty |= selector.Draw("##itemSource", selector.CurrentSelection.Item.Name ?? string.Empty, string.Empty, + InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); (article1, _, selector) = GetAccessorySelector(_slotTo, false); @@ -480,12 +501,12 @@ public class ItemSwapTab : IDisposable, ITab, IUiService ImGui.TableNextColumn(); ImGui.SetNextItemWidth(100 * UiHelpers.Scale); - using (var combo = ImRaii.Combo("##toType", _slotTo.ToName())) + using (var combo = ImRaii.Combo("##toType", ToName(_slotTo))) { if (combo) - foreach (var slot in EquipSlotExtensions.AccessorySlots.Where(s => s != _slotFrom)) + foreach (var slot in AvailableToTypes.Where(t => t != _slotFrom)) { - if (!ImGui.Selectable(slot.ToName(), slot == _slotTo) || slot == _slotTo) + if (!ImGui.Selectable(ToName(slot), slot == _slotTo) || slot == _slotTo) continue; _dirty = true; @@ -508,17 +529,18 @@ public class ItemSwapTab : IDisposable, ITab, IUiService .Select(i => i.Name))); } - private (string, string, ItemSelector) GetAccessorySelector(EquipSlot slot, bool source) + private (string, string, ItemSelector) GetAccessorySelector(BetweenSlotTypes slot, bool source) { var (type, article1, article2) = slot switch { - EquipSlot.Head => (SwapType.Hat, "this", "it"), - EquipSlot.Ears => (SwapType.Earrings, "these", "them"), - EquipSlot.Neck => (SwapType.Necklace, "this", "it"), - EquipSlot.Wrists => (SwapType.Bracelet, "these", "them"), - EquipSlot.RFinger => (SwapType.Ring, "this", "it"), - EquipSlot.LFinger => (SwapType.Ring, "this", "it"), - _ => (SwapType.Ring, "this", "it"), + BetweenSlotTypes.Hat => (SwapType.Hat, "this", "it"), + BetweenSlotTypes.Earrings => (SwapType.Earrings, "these", "them"), + BetweenSlotTypes.Necklace => (SwapType.Necklace, "this", "it"), + BetweenSlotTypes.Bracelets => (SwapType.Bracelet, "these", "them"), + BetweenSlotTypes.RightRing => (SwapType.Ring, "this", "it"), + BetweenSlotTypes.LeftRing => (SwapType.Ring, "this", "it"), + BetweenSlotTypes.Glasses => (SwapType.Glasses, "these", "them"), + _ => (SwapType.Ring, "this", "it"), }; var (itemSelector, target, _, _) = _selectors[type]; return (article1, article2, source ? itemSelector : target); @@ -689,6 +711,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService SwapType.Necklace => "One of the selected necklaces does not seem to exist.", SwapType.Bracelet => "One of the selected bracelets does not seem to exist.", SwapType.Ring => "One of the selected rings does not seem to exist.", + SwapType.Glasses => "One of the selected glasses does not seem to exist.", SwapType.Hair => "One of the selected hairstyles does not seem to exist for this gender and race combo.", SwapType.Face => "One of the selected faces does not seem to exist for this gender and race combo.", SwapType.Ears => "One of the selected ear types does not seem to exist for this gender and race combo.", @@ -746,4 +769,44 @@ public class ItemSwapTab : IDisposable, ITab, IUiService UpdateOption(); _dirty = true; } + + private enum BetweenSlotTypes + { + Hat, + Earrings, + Necklace, + Bracelets, + RightRing, + LeftRing, + Glasses, + } + + private static EquipSlot ToEquipSlot(BetweenSlotTypes type) + => type switch + { + BetweenSlotTypes.Hat => EquipSlot.Head, + BetweenSlotTypes.Earrings => EquipSlot.Ears, + BetweenSlotTypes.Necklace => EquipSlot.Neck, + BetweenSlotTypes.Bracelets => EquipSlot.Wrists, + BetweenSlotTypes.RightRing => EquipSlot.RFinger, + BetweenSlotTypes.LeftRing => EquipSlot.LFinger, + BetweenSlotTypes.Glasses => BonusItemFlag.Glasses.ToEquipSlot(), + _ => EquipSlot.Unknown, + }; + + private static string ToName(BetweenSlotTypes type) + => type switch + { + BetweenSlotTypes.Hat => "Hat", + BetweenSlotTypes.Earrings => "Earrings", + BetweenSlotTypes.Necklace => "Necklace", + BetweenSlotTypes.Bracelets => "Bracelets", + BetweenSlotTypes.RightRing => "Right Ring", + BetweenSlotTypes.LeftRing => "Left Ring", + BetweenSlotTypes.Glasses => "Glasses", + _ => "Unknown", + }; + + private static readonly IReadOnlyList AvailableToTypes = + Enum.GetValues().Where(s => s is not BetweenSlotTypes.Hat).ToArray(); } From a54e45f9c3b59e0532d422230a23c0a2748172b8 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 12 Oct 2024 13:15:18 +0000 Subject: [PATCH 0945/1381] [CI] Updating repo.json for testing_1.2.1.8 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 0d9e071f..4e8b1ed8 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.7", + "TestingAssemblyVersion": "1.2.1.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.8/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 50db83146adab19207e9b867ca8768ae1d7cc06f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 13 Oct 2024 13:55:01 +0200 Subject: [PATCH 0946/1381] Maybe fix left finger resource nodes. --- .../ResolveContext.PathResolution.cs | 2 +- .../Interop/ResourceTree/ResolveContext.cs | 4 +-- Penumbra/Interop/ResourceTree/ResourceNode.cs | 32 +++++++++---------- Penumbra/Interop/ResourceTree/ResourceTree.cs | 10 +++--- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index c554d97a..79f97881 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -37,7 +37,7 @@ internal partial record ResolveContext { var path = IsEquipmentSlot(SlotIndex) ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot.ToSlot()) - : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot.ToSlot()); + : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 207551e7..54612070 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -340,9 +340,9 @@ internal unsafe partial record ResolveContext( internal ResourceNode.UiData GuessModelUiData(Utf8GamePath gamePath) { - var path = gamePath.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries); + var path = gamePath.Path.Split((byte)'/'); // Weapons intentionally left out. - var isEquipment = SafeGet(path, 0) == "chara" && SafeGet(path, 1) is "accessory" or "equipment"; + var isEquipment = path.Count >= 2 && path[0].Span.SequenceEqual("chara"u8) && (path[1].Span.SequenceEqual("accessory"u8) || path[1].Span.SequenceEqual("equipment"u8)); if (isEquipment) foreach (var item in Global.Identifier.Identify(Equipment.Set, 0, Equipment.Variant, Slot.ToSlot())) { diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 85d12ce7..6c3e1ebe 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -7,20 +7,20 @@ namespace Penumbra.Interop.ResourceTree; public class ResourceNode : ICloneable { - public string? Name; - public string? FallbackName; - public ChangedItemIconFlag IconFlag; - public readonly ResourceType Type; - public readonly nint ObjectAddress; - public readonly nint ResourceHandle; - public Utf8GamePath[] PossibleGamePaths; - public FullPath FullPath; - public string? ModName; - public string? ModRelativePath; - public CiByteString AdditionalData; - public readonly ulong Length; - public readonly List Children; - internal ResolveContext? ResolveContext; + public string? Name; + public string? FallbackName; + public ChangedItemIconFlag IconFlag; + public readonly ResourceType Type; + public readonly nint ObjectAddress; + public readonly nint ResourceHandle; + public Utf8GamePath[] PossibleGamePaths; + public FullPath FullPath; + public string? ModName; + public string? ModRelativePath; + public CiByteString AdditionalData; + public readonly ulong Length; + public readonly List Children; + internal ResolveContext? ResolveContext; public Utf8GamePath GamePath { @@ -53,7 +53,7 @@ public class ResourceNode : ICloneable { Name = other.Name; FallbackName = other.FallbackName; - IconFlag = other.IconFlag; + IconFlag = other.IconFlag; Type = other.Type; ObjectAddress = other.ObjectAddress; ResourceHandle = other.ResourceHandle; @@ -82,7 +82,7 @@ public class ResourceNode : ICloneable public void SetUiData(UiData uiData) { - Name = uiData.Name; + Name = uiData.Name; IconFlag = uiData.IconFlag; } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 246a4508..89e0c62b 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -81,8 +81,8 @@ public class ResourceTree ModelType.Human => i switch { < 10 => globalContext.CreateContext(model, i, i.ToEquipSlot().ToEquipType(), equipment[(int)i]), - 16 => globalContext.CreateContext(model, i, FullEquipType.Glasses, equipment[10]), - 17 => globalContext.CreateContext(model, i, FullEquipType.Unknown, equipment[11]), + 16 => globalContext.CreateContext(model, i, FullEquipType.Glasses, equipment[10]), + 17 => globalContext.CreateContext(model, i, FullEquipType.Unknown, equipment[11]), _ => globalContext.CreateContext(model, i), }, _ => i < equipment.Length @@ -185,7 +185,7 @@ public class ResourceTree { pbdNode = pbdNode.Clone(); pbdNode.FallbackName = "Racial Deformer"; - pbdNode.IconFlag = ChangedItemIconFlag.Customization; + pbdNode.IconFlag = ChangedItemIconFlag.Customization; } Nodes.Add(pbdNode); @@ -203,7 +203,7 @@ public class ResourceTree { decalNode = decalNode.Clone(); decalNode.FallbackName = "Face Decal"; - decalNode.IconFlag = ChangedItemIconFlag.Customization; + decalNode.IconFlag = ChangedItemIconFlag.Customization; } Nodes.Add(decalNode); @@ -220,7 +220,7 @@ public class ResourceTree { legacyDecalNode = legacyDecalNode.Clone(); legacyDecalNode.FallbackName = "Legacy Body Decal"; - legacyDecalNode.IconFlag = ChangedItemIconFlag.Customization; + legacyDecalNode.IconFlag = ChangedItemIconFlag.Customization; } Nodes.Add(legacyDecalNode); From 9bd1f86a1d31efe180cc5755852bc6f129e4a187 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 13 Oct 2024 11:57:07 +0000 Subject: [PATCH 0947/1381] [CI] Updating repo.json for testing_1.2.1.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 4e8b1ed8..2ead369a 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.8", + "TestingAssemblyVersion": "1.2.1.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 339d1f8caf00e6afe3fde06ea20685523020887d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 13 Oct 2024 14:41:21 +0200 Subject: [PATCH 0948/1381] Update GameData --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 63cbf824..554e28a3 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 63cbf824178b5b1f91fd9edc22a6c2bbc2e1cd23 +Subproject commit 554e28a3d1fca9394a20fd9856f6387e2a5e4a57 From 9ddb011545c3b94b7c4958eb47f674627f93bc29 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 18 Oct 2024 16:03:08 +0200 Subject: [PATCH 0949/1381] Fix issue with long mod titles in the merge mods tab. --- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 26 +++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index b5f0255c..bd62089f 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Mods.SubMods; @@ -45,9 +46,30 @@ public class ModMergeTab(ModMerger modMerger) : IUiService private void DrawMergeInto(float size) { - using var bigGroup = ImRaii.Group(); + using var bigGroup = ImRaii.Group(); + var minComboSize = 300 * ImGuiHelpers.GlobalScale; + var textSize = ImUtf8.CalcTextSize($"Merge {modMerger.MergeFromMod!.Name} into ").X; + ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted($"Merge {modMerger.MergeFromMod!.Name} into "); + + using (ImRaii.Group()) + { + ImUtf8.Text("Merge "u8); + ImGui.SameLine(0, 0); + if (size - textSize < minComboSize) + { + ImUtf8.Text("selected mod"u8, ColorId.FolderLine.Value()); + ImUtf8.HoverTooltip(modMerger.MergeFromMod!.Name.Text); + } + else + { + ImUtf8.Text(modMerger.MergeFromMod!.Name.Text, ColorId.FolderLine.Value()); + } + + ImGui.SameLine(0, 0); + ImUtf8.Text(" into"u8); + } + ImGui.SameLine(); DrawCombo(size - ImGui.GetItemRectSize().X - ImGui.GetStyle().ItemSpacing.X); From 472d803141dab3baa9cf59bef4461986ad1a1f84 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 18 Oct 2024 16:24:30 +0200 Subject: [PATCH 0950/1381] 1.3.0.0 --- Penumbra/UI/Changelog.cs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 41920d1c..48ac90d8 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -53,10 +53,42 @@ public class PenumbraChangelog : IUiService Add1_1_0_0(Changelog); Add1_1_1_0(Changelog); Add1_2_1_0(Changelog); + Add1_3_0_0(Changelog); } #region Changelogs + private static void Add1_3_0_0(Changelog log) + => log.NextVersion("Version 1.3.0.0") + + .RegisterHighlight("The textures tab in the advanced editing window can now import and export .tga files.") + .RegisterEntry("BC4 and BC6 textures can now also be imported.", 1) + .RegisterHighlight("Added item swapping from and to the Glasses slot.") + .RegisterEntry("Reworked quite a bit of things around face wear / bonus items. Please let me know if anything broke.", 1) + .RegisterEntry("The import date of a mod is now shown in the Edit Mod tab, and can be reset via button.") + .RegisterEntry("A button to open the file containing local mod data for a mod was also added.", 1) + .RegisterHighlight("IMC groups can now be configured to only apply the attribute flags for their entry, and take the other values from the default value.") + .RegisterEntry("This allows keeping the material index of every IMC entry of a group, while setting the attributes.", 1) + .RegisterHighlight("Model Import/Export was fixed and re-enabled (thanks ackwell and ramen).") + .RegisterHighlight("Added a hack to allow bonus items (face wear, glasses) to have VFX.") + .RegisterEntry("Also fixed the hack that allowed accessories to have VFX not working anymore.", 1) + .RegisterHighlight("Added rudimentary options to edit PBD files in the advanced editing window.") + .RegisterEntry("Preparing the advanced editing window for a mod now does not freeze the game until it is ready.") + .RegisterEntry("Meta Manipulations in the advanced editing window are now ordered and do not eat into performance as much when drawn.") + .RegisterEntry("Added a button to the advanced editing window to remove all default-valued meta manipulations from a mod") + .RegisterEntry("Default-valued manipulations will now also be removed on import from archives and .pmps, not just .ttmps, if not configured otherwise.", 1) + .RegisterEntry("Checkbox-based mod filters are now tri-state checkboxes instead of two disjoint checkboxes.") + .RegisterEntry("Paths from the resource logger can now be copied.") + .RegisterEntry("Silenced some redundant error logs when updating mods via Heliosphere.") + .RegisterEntry("Added 'Page' to imported mod data for TexTools interop. The value is not used in Penumbra, just persisted.") + .RegisterEntry("Updated all external dependencies.") + .RegisterEntry("Fixed issue with Demihuman IMC entries.") + .RegisterEntry("Fixed some off-by-one errors on the mod import window.") + .RegisterEntry("Fixed a race-condition concerning the first-time creation of mod-meta files.") + .RegisterEntry("Fixed an issue with long mod titles in the merge mods tab.") + .RegisterEntry("A bunch of other miscellaneous fixes."); + + private static void Add1_2_1_0(Changelog log) => log.NextVersion("Version 1.2.1.0") .RegisterHighlight("Penumbra is now released for Dawntrail!") From 71101ef553dd19f50678fae379a8f617bb5cd9fb Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 18 Oct 2024 14:26:25 +0000 Subject: [PATCH 0951/1381] [CI] Updating repo.json for 1.3.0.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 2ead369a..cba274c8 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.2.1.1", - "TestingAssemblyVersion": "1.2.1.9", + "AssemblyVersion": "1.3.0.0", + "TestingAssemblyVersion": "1.3.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.2.1.9/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.2.1.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 69971c12afd084192dbf40b1f45068d1b6d93916 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 19 Oct 2024 19:23:51 +0200 Subject: [PATCH 0952/1381] Fix EQP entries for earring hiding. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/GlobalEqpCache.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 554e28a3..e9fc5930 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 554e28a3d1fca9394a20fd9856f6387e2a5e4a57 +Subproject commit e9fc5930a9c035c1e1e3c87ee9bcc4f05eb3015b diff --git a/Penumbra/Collections/Cache/GlobalEqpCache.cs b/Penumbra/Collections/Cache/GlobalEqpCache.cs index efcab109..60e782b5 100644 --- a/Penumbra/Collections/Cache/GlobalEqpCache.cs +++ b/Penumbra/Collections/Cache/GlobalEqpCache.cs @@ -40,7 +40,7 @@ public class GlobalEqpCache : ReadWriteDictionary, original |= EqpEntry.HeadShowHrothgarHat; if (_doNotHideEarrings.Contains(armor[5].Set)) - original |= EqpEntry.HeadShowEarrings | EqpEntry.HeadShowEarringsAura | EqpEntry.HeadShowEarringsHuman; + original |= EqpEntry.HeadShowEarringsHyurRoe | EqpEntry.HeadShowEarringsLalaElezen | EqpEntry.HeadShowEarringsMiqoHrothViera | EqpEntry.HeadShowEarringsAura; if (_doNotHideNecklace.Contains(armor[6].Set)) original |= EqpEntry.BodyShowNecklace | EqpEntry.HeadShowNecklace; From 7e6ea5008c3f2ee678a8f0505354fb63676d49fd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 30 Oct 2024 17:30:45 +0100 Subject: [PATCH 0953/1381] Maybe fix other issue with left rings and resource trees. --- Penumbra.GameData | 2 +- .../ResourceTree/ResolveContext.PathResolution.cs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index e9fc5930..e39a04c8 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e9fc5930a9c035c1e1e3c87ee9bcc4f05eb3015b +Subproject commit e39a04c83b67246580492677414888357b5ebed8 diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 79f97881..b1cbb74d 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -36,17 +36,16 @@ internal partial record ResolveContext private Utf8GamePath ResolveEquipmentModelPath() { var path = IsEquipmentSlot(SlotIndex) - ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), Slot.ToSlot()) + ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()) : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } private GenderRace ResolveModelRaceCode() - => ResolveEqdpRaceCode(Slot.ToSlot(), Equipment.Set); + => ResolveEqdpRaceCode(SlotIndex, Equipment.Set); - private unsafe GenderRace ResolveEqdpRaceCode(EquipSlot slot, PrimaryId primaryId) + private unsafe GenderRace ResolveEqdpRaceCode(uint slotIndex, PrimaryId primaryId) { - var slotIndex = slot.ToIndex(); if (!IsEquipmentOrAccessorySlot(slotIndex) || ModelType != ModelType.Human) return GenderRace.MidlanderMale; @@ -61,6 +60,7 @@ internal partial record ResolveContext var metaCache = Global.Collection.MetaCache; var entry = metaCache?.GetEqdpEntry(characterRaceCode, accessory, primaryId) ?? ExpandedEqdpFile.GetDefault(Global.MetaFileManager, characterRaceCode, accessory, primaryId); + var slot = slotIndex.ToEquipSlot(); if (entry.ToBits(slot).Item2) return characterRaceCode; @@ -272,7 +272,7 @@ internal partial record ResolveContext { var human = (Human*)CharacterBase; var equipment = ((CharacterArmor*)&human->Head)[slot.ToIndex()]; - return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot, equipment.Set), type, equipment.Set); + return ResolveHumanExtraSkeletonData(ResolveEqdpRaceCode(slot.ToIndex(), equipment.Set), type, equipment.Set); } private (GenderRace RaceCode, string Slot, PrimaryId Set) ResolveHumanExtraSkeletonData(GenderRace raceCode, EstType type, From 2358eb378deebd960b16619f243e16fc9a86e845 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 30 Oct 2024 17:31:38 +0100 Subject: [PATCH 0954/1381] Fix issue with characters in login screen, maybe. --- .../PathResolving/CollectionResolver.cs | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 313c4f8b..1705f871 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.UI.Agent; +using OtterGui; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -62,10 +63,11 @@ public sealed unsafe class CollectionResolver( try { - if (useCache && cache.TryGetValue(gameObject, out var data)) + // Login screen reuses the same actors and can not be cached. + if (LoginScreen(gameObject, out var data)) return data; - if (LoginScreen(gameObject, out data)) + if (useCache && cache.TryGetValue(gameObject, out data)) return data; if (Aesthetician(gameObject, out data)) @@ -116,16 +118,17 @@ public sealed unsafe class CollectionResolver( return true; } - var notYetReady = false; - var lobby = AgentLobby.Instance(); - if (lobby != null) + var notYetReady = false; + var lobby = AgentLobby.Instance(); + var characterList = CharaSelectCharacterList.Instance(); + if (lobby != null && characterList != null) { - var span = lobby->LobbyData.CharaSelectEntries.AsSpan(); // The lobby uses the first 8 cutscene actors. var idx = gameObject->ObjectIndex - ObjectIndex.CutsceneStart.Index; - if (idx >= 0 && idx < span.Length && span[idx].Value != null) + if (characterList->CharacterMapping.FindFirst(m => m.ClientObjectIndex == idx, out var mapping) + && lobby->LobbyData.CharaSelectEntries.FindFirst(e => e.Value->ContentId == mapping.ContentId, out var charaEntry)) { - var item = span[idx].Value; + var item = charaEntry.Value; var identifier = actors.CreatePlayer(new ByteString(item->Name), item->HomeWorldId); Penumbra.Log.Verbose( $"Identified {identifier.Incognito(null)} in cutscene for actor {idx + 200} at 0x{(ulong)gameObject:X} of race {(gameObject->IsCharacter() ? ((Character*)gameObject)->DrawData.CustomizeData.Race.ToString() : "Unknown")}."); @@ -141,7 +144,7 @@ public sealed unsafe class CollectionResolver( var collection = collectionManager.Active.ByType(CollectionType.Yourself) ?? CollectionByAttributes(gameObject, ref notYetReady) ?? collectionManager.Active.Default; - ret = notYetReady ? collection.ToResolveData(gameObject) : cache.Set(collection, ActorIdentifier.Invalid, gameObject); + ret = collection.ToResolveData(gameObject); return true; } From c4f6038d1ef629515e830e316ef11dc4871868da Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 30 Oct 2024 20:40:10 +0100 Subject: [PATCH 0955/1381] Make temporary collection always respect ownership. --- .../PathResolving/CollectionResolver.cs | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 1705f871..36c31af3 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -126,7 +126,7 @@ public sealed unsafe class CollectionResolver( // The lobby uses the first 8 cutscene actors. var idx = gameObject->ObjectIndex - ObjectIndex.CutsceneStart.Index; if (characterList->CharacterMapping.FindFirst(m => m.ClientObjectIndex == idx, out var mapping) - && lobby->LobbyData.CharaSelectEntries.FindFirst(e => e.Value->ContentId == mapping.ContentId, out var charaEntry)) + && lobby->LobbyData.CharaSelectEntries.FindFirst(e => e.Value->ContentId == mapping.ContentId, out var charaEntry)) { var item = charaEntry.Value; var identifier = actors.CreatePlayer(new ByteString(item->Name), item->HomeWorldId); @@ -199,10 +199,24 @@ public sealed unsafe class CollectionResolver( /// Check both temporary and permanent character collections. Temporary first. private ModCollection? CollectionByIdentifier(ActorIdentifier identifier) - => tempCollections.Collections.TryGetCollection(identifier, out var collection) - || collectionManager.Active.Individuals.TryGetCollection(identifier, out collection) - ? collection - : null; + { + if (tempCollections.Collections.TryGetCollection(identifier, out var collection)) + return collection; + + // Always inherit ownership for temporary collections. + if (identifier.Type is IdentifierType.Owned) + { + var playerIdentifier = actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, + identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); + if (tempCollections.Collections.TryGetCollection(playerIdentifier, out collection)) + return collection; + } + + if (collectionManager.Active.Individuals.TryGetCollection(identifier, out collection)) + return collection; + + return null; + } /// Check for the Yourself collection. private ModCollection? CheckYourself(ActorIdentifier identifier, Actor actor) From ed717c69f9676a3314e0235829539ab3a819a5be Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 30 Oct 2024 20:40:10 +0100 Subject: [PATCH 0956/1381] Make temporary collection always respect ownership. --- .../Manager/IndividualCollections.Access.cs | 6 ++--- .../PathResolving/CollectionResolver.cs | 24 +++++++++++++++---- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/Penumbra/Collections/Manager/IndividualCollections.Access.cs b/Penumbra/Collections/Manager/IndividualCollections.Access.cs index 6b90a333..d0a70630 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Access.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Access.cs @@ -48,8 +48,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa // Handle generic NPC var npcIdentifier = _actors.CreateIndividualUnchecked(IdentifierType.Npc, ByteString.Empty, - ushort.MaxValue, - identifier.Kind, identifier.DataId); + ushort.MaxValue, identifier.Kind, identifier.DataId); if (npcIdentifier.IsValid && _individuals.TryGetValue(npcIdentifier, out collection)) return true; @@ -58,8 +57,7 @@ public sealed partial class IndividualCollections : IReadOnlyList<(string Displa return false; identifier = _actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, - identifier.HomeWorld.Id, - ObjectKind.None, uint.MaxValue); + identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); return CheckWorlds(identifier, out collection); } case IdentifierType.Npc: return _individuals.TryGetValue(identifier, out collection); diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 1705f871..36c31af3 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -126,7 +126,7 @@ public sealed unsafe class CollectionResolver( // The lobby uses the first 8 cutscene actors. var idx = gameObject->ObjectIndex - ObjectIndex.CutsceneStart.Index; if (characterList->CharacterMapping.FindFirst(m => m.ClientObjectIndex == idx, out var mapping) - && lobby->LobbyData.CharaSelectEntries.FindFirst(e => e.Value->ContentId == mapping.ContentId, out var charaEntry)) + && lobby->LobbyData.CharaSelectEntries.FindFirst(e => e.Value->ContentId == mapping.ContentId, out var charaEntry)) { var item = charaEntry.Value; var identifier = actors.CreatePlayer(new ByteString(item->Name), item->HomeWorldId); @@ -199,10 +199,24 @@ public sealed unsafe class CollectionResolver( /// Check both temporary and permanent character collections. Temporary first. private ModCollection? CollectionByIdentifier(ActorIdentifier identifier) - => tempCollections.Collections.TryGetCollection(identifier, out var collection) - || collectionManager.Active.Individuals.TryGetCollection(identifier, out collection) - ? collection - : null; + { + if (tempCollections.Collections.TryGetCollection(identifier, out var collection)) + return collection; + + // Always inherit ownership for temporary collections. + if (identifier.Type is IdentifierType.Owned) + { + var playerIdentifier = actors.CreateIndividualUnchecked(IdentifierType.Player, identifier.PlayerName, + identifier.HomeWorld.Id, ObjectKind.None, uint.MaxValue); + if (tempCollections.Collections.TryGetCollection(playerIdentifier, out collection)) + return collection; + } + + if (collectionManager.Active.Individuals.TryGetCollection(identifier, out collection)) + return collection; + + return null; + } /// Check for the Yourself collection. private ModCollection? CheckYourself(ActorIdentifier identifier, Actor actor) From 7dfc564a4cbafd26633aeff3cf8cc37d4a2e2e61 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 4 Nov 2024 13:55:45 +0100 Subject: [PATCH 0957/1381] Add path resolving / est handling for kdb and bnmb files. --- .../Hooks/Resources/ResolvePathHooksBase.cs | 37 +++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index d55caf34..54066782 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -36,7 +36,9 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private readonly Hook _resolveMdlPathHook; private readonly Hook _resolveMtrlPathHook; private readonly Hook _resolvePapPathHook; + private readonly Hook _resolveKdbPathHook; private readonly Hook _resolvePhybPathHook; + private readonly Hook _resolveBnmbPathHook; private readonly Hook _resolveSklbPathHook; private readonly Hook _resolveSkpPathHook; private readonly Hook _resolveTmbPathHook; @@ -54,11 +56,10 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMdlPathHook = Create($"{name}.{nameof(ResolveMdl)}", hooks, vTable[77], type, ResolveMdl, ResolveMdlHuman); _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[78], type, ResolveSkp, ResolveSkpHuman); _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[79], type, ResolvePhyb, ResolvePhybHuman); - + _resolveKdbPathHook = Create($"{name}.{nameof(ResolveKdb)}", hooks, vTable[80], type, ResolveKdb, ResolveKdbHuman); _vFunc81Hook = Create( $"{name}.{nameof(VFunc81)}", hooks, vTable[81], type, null, VFunc81); - + _resolveBnmbPathHook = Create($"{name}.{nameof(ResolveBnmb)}", hooks, vTable[82], type, ResolveBnmb, ResolveBnmbHuman); _vFunc83Hook = Create( $"{name}.{nameof(VFunc83)}", hooks, vTable[83], type, null, VFunc83); - _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[84], type, ResolvePap, ResolvePapHuman); _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[85], ResolveTmb); _resolveMPapPathHook = Create( $"{name}.{nameof(ResolveMPap)}", hooks, vTable[87], ResolveMPap); @@ -83,7 +84,9 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMdlPathHook.Enable(); _resolveMtrlPathHook.Enable(); _resolvePapPathHook.Enable(); + _resolveKdbPathHook.Enable(); _resolvePhybPathHook.Enable(); + _resolveBnmbPathHook.Enable(); _resolveSklbPathHook.Enable(); _resolveSkpPathHook.Enable(); _resolveTmbPathHook.Enable(); @@ -101,7 +104,9 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMdlPathHook.Disable(); _resolveMtrlPathHook.Disable(); _resolvePapPathHook.Disable(); + _resolveKdbPathHook.Disable(); _resolvePhybPathHook.Disable(); + _resolveBnmbPathHook.Disable(); _resolveSklbPathHook.Disable(); _resolveSkpPathHook.Disable(); _resolveTmbPathHook.Disable(); @@ -119,7 +124,9 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMdlPathHook.Dispose(); _resolveMtrlPathHook.Dispose(); _resolvePapPathHook.Dispose(); + _resolveKdbPathHook.Dispose(); _resolvePhybPathHook.Dispose(); + _resolveBnmbPathHook.Dispose(); _resolveSklbPathHook.Dispose(); _resolveSkpPathHook.Dispose(); _resolveTmbPathHook.Dispose(); @@ -149,9 +156,15 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolvePap(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) => ResolvePath(drawObject, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); + private nint ResolveKdb(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + => ResolvePath(drawObject, _resolveKdbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + private nint ResolvePhyb(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) => ResolvePath(drawObject, _resolvePhybPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + private nint ResolveBnmb(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + => ResolvePath(drawObject, _resolveBnmbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + private nint ResolveSklb(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) => ResolvePath(drawObject, _resolveSklbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); @@ -188,6 +201,15 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ret; } + private nint ResolveKdbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + { + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = ResolvePath(collection, _resolveKdbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection.Pop(); + return ret; + } + private nint ResolvePhybHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); @@ -197,6 +219,15 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ret; } + private nint ResolveBnmbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) + { + var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); + _parent.MetaState.EstCollection.Push(collection); + var ret = ResolvePath(collection, _resolveBnmbPathHook.Original(drawObject, pathBuffer, pathBufferSize, partialSkeletonIndex)); + _parent.MetaState.EstCollection.Pop(); + return ret; + } + private nint ResolveSklbHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint partialSkeletonIndex) { var collection = _parent.CollectionResolver.IdentifyCollection((DrawObject*)drawObject, true); From c54141be5489753ce6fa4ad862478615ab25fbae Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 4 Nov 2024 12:59:01 +0000 Subject: [PATCH 0958/1381] [CI] Updating repo.json for testing_1.3.0.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index cba274c8..686549c9 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.0.0", - "TestingAssemblyVersion": "1.3.0.0", + "TestingAssemblyVersion": "1.3.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From e3a1ae693813eb06d96d311958aabb5b3abfef55 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Nov 2024 00:50:14 +0100 Subject: [PATCH 0959/1381] Current state. --- OtterGui | 2 +- Penumbra.GameData | 2 +- .../Animation/ApricotListenerSoundPlay.cs | 14 ++++--- .../Interop/Hooks/Animation/SomePapLoad.cs | 2 +- .../Interop/Hooks/Meta/CalculateHeight.cs | 17 ++++---- Penumbra/Interop/Hooks/Meta/UpdateModel.cs | 2 +- .../PostProcessing/ShaderReplacementFixer.cs | 1 - .../PathResolving/CollectionResolver.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- Penumbra/Interop/Services/FontReloader.cs | 2 +- Penumbra/Interop/Services/RedrawService.cs | 4 +- Penumbra/Interop/VolatileOffsets.cs | 35 ++++++++++++++++ .../Manager/OptionEditor/ImcModGroupEditor.cs | 2 +- .../Manager/OptionEditor/ModGroupEditor.cs | 2 +- .../OptionEditor/MultiModGroupEditor.cs | 2 +- .../OptionEditor/SingleModGroupEditor.cs | 2 +- Penumbra/Penumbra.cs | 4 +- Penumbra/Services/MessageService.cs | 6 +-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 3 ++ Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs | 41 ++++++++++++++----- 20 files changed, 104 insertions(+), 43 deletions(-) create mode 100644 Penumbra/Interop/VolatileOffsets.cs diff --git a/OtterGui b/OtterGui index 3e6b0857..8ba88eff 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3e6b085749741f35dd6732c33d0720c6a51ebb97 +Subproject commit 8ba88eff15326bb28ed5e6157f5252c114d40b5f diff --git a/Penumbra.GameData b/Penumbra.GameData index e39a04c8..fb81a0b5 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e39a04c83b67246580492677414888357b5ebed8 +Subproject commit fb81a0b55d3c68f2b26357fac3049c79fb0c22fb diff --git a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs index 44eb7ebb..8838971c 100644 --- a/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs +++ b/Penumbra/Interop/Hooks/Animation/ApricotListenerSoundPlay.cs @@ -33,25 +33,27 @@ public sealed unsafe class ApricotListenerSoundPlayCaller : FastHook> 13) & 1) == 0) + var someIntermediate = *(nint*)(a1 + VolatileOffsets.ApricotListenerSoundPlayCaller.SomeIntermediate); + var flags = someIntermediate == nint.Zero + ? (ushort)0 + : *(ushort*)(someIntermediate + VolatileOffsets.ApricotListenerSoundPlayCaller.Flags); + if (((flags >> VolatileOffsets.ApricotListenerSoundPlayCaller.BitShift) & 1) == 0) return Task.Result.Original(a1, unused, timeOffset); Penumbra.Log.Excessive( $"[Apricot Listener Sound Play Caller] Invoked on 0x{a1:X} with {unused}, {timeOffset}."); // Fetch the IInstanceListenner (sixth argument to inlined call of SoundPlay) - var apricotIInstanceListenner = *(nint*)(someIntermediate + 0x270); + var apricotIInstanceListenner = *(nint*)(someIntermediate + VolatileOffsets.ApricotListenerSoundPlayCaller.IInstanceListenner); if (apricotIInstanceListenner == nint.Zero) return Task.Result.Original(a1, unused, timeOffset); // In some cases we can obtain the associated caster via vfunc 1. var newData = ResolveData.Invalid; - var gameObject = (*(delegate* unmanaged**)apricotIInstanceListenner)[1](apricotIInstanceListenner); + var gameObject = (*(delegate* unmanaged**)apricotIInstanceListenner)[VolatileOffsets.ApricotListenerSoundPlayCaller.CasterVFunc](apricotIInstanceListenner); if (gameObject != null) { newData = _collectionResolver.IdentifyCollection(gameObject, true); diff --git a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs index 7339c397..f19e4ce2 100644 --- a/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs +++ b/Penumbra/Interop/Hooks/Animation/SomePapLoad.cs @@ -31,7 +31,7 @@ public sealed unsafe class SomePapLoad : FastHook private void Detour(nint a1, int a2, nint a3, int a4) { Penumbra.Log.Excessive($"[Some PAP Load] Invoked on 0x{a1:X} with {a2}, {a3}, {a4}."); - var timelinePtr = a1 + Offsets.TimeLinePtr; + var timelinePtr = a1 + VolatileOffsets.AnimationState.TimeLinePtr; if (timelinePtr != nint.Zero) { var actorIdx = (int)(*(*(ulong**)timelinePtr + 1) >> 3); diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index e71d07dd..327e3d1e 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -1,7 +1,7 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Object; using OtterGui.Services; using Penumbra.Interop.PathResolving; -using Character = FFXIVClientStructs.FFXIV.Client.Game.Character.Character; namespace Penumbra.Interop.Hooks.Meta; @@ -13,19 +13,20 @@ public sealed unsafe class CalculateHeight : FastHook public CalculateHeight(HookManager hooks, CollectionResolver collectionResolver, MetaState metaState) { _collectionResolver = collectionResolver; - _metaState = metaState; - Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, !HookOverrides.Instance.Meta.CalculateHeight); + _metaState = metaState; + Task = hooks.CreateHook("Calculate Height", (nint)HeightContainer.MemberFunctionPointers.CalculateHeight, Detour, + !HookOverrides.Instance.Meta.CalculateHeight); } - public delegate ulong Delegate(Character* character); + public delegate ulong Delegate(HeightContainer* character); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private ulong Detour(Character* character) + private ulong Detour(HeightContainer* container) { - var collection = _collectionResolver.IdentifyCollection((GameObject*)character, true); + var collection = _collectionResolver.IdentifyCollection((GameObject*)container->OwnerObject, true); _metaState.RspCollection.Push(collection); - var ret = Task.Result.Original.Invoke(character); - Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)character:X} -> {ret}."); + var ret = Task.Result.Original.Invoke(container); + Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)container:X} -> {ret}."); _metaState.RspCollection.Pop(); return ret; } diff --git a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs index 72beea0e..9189ce3b 100644 --- a/Penumbra/Interop/Hooks/Meta/UpdateModel.cs +++ b/Penumbra/Interop/Hooks/Meta/UpdateModel.cs @@ -25,7 +25,7 @@ public sealed unsafe class UpdateModel : FastHook { // Shortcut because this is called all the time. // Same thing is checked at the beginning of the original function. - if (*(int*)((nint)drawObject + Offsets.UpdateModelSkip) == 0) + if (*(int*)((nint)drawObject + VolatileOffsets.UpdateModel.ShortCircuit) == 0) return; Penumbra.Log.Excessive($"[Update Model] Invoked on {(nint)drawObject:X}."); diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 80892b0f..40958eb4 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -401,7 +401,6 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private void ModelRendererUnkFuncDetour(CSModelRenderer* modelRenderer, ModelRendererStructs.UnkPayload* unkPayload, uint unk2, uint unk3, uint unk4, uint unk5) { - // If we don't have any on-screen instances of modded iris.shpk or others, we don't need the slow path at all. if (!Enabled || GetTotalMaterialCountForModelRendererUnk() == 0) { _modelRendererUnkFuncHook.Original(modelRenderer, unkPayload, unk2, unk3, unk4, unk5); diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 36c31af3..50088008 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -240,7 +240,7 @@ public sealed unsafe class CollectionResolver( } // Only handle human models. - if (!IsModelHuman((uint)actor.AsCharacter->CharacterData.ModelCharaId)) + if (!IsModelHuman((uint)actor.AsCharacter->ModelCharaId)) return null; if (actor.Customize->Data[0] == 0) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 89e0c62b..62f4febe 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -68,7 +68,7 @@ public class ResourceTree Unsafe.AsPointer(ref character->DrawData.EquipmentModelIds[0]), 10), _ => [], }; - ModelId = character->CharacterData.ModelCharaId; + ModelId = character->ModelCharaId; CustomizeData = character->DrawData.CustomizeData; RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; diff --git a/Penumbra/Interop/Services/FontReloader.cs b/Penumbra/Interop/Services/FontReloader.cs index 4f48f08f..3a2c7022 100644 --- a/Penumbra/Interop/Services/FontReloader.cs +++ b/Penumbra/Interop/Services/FontReloader.cs @@ -43,7 +43,7 @@ public unsafe class FontReloader : IService return; _atkModule = &atkModule->AtkModule; - _reloadFontsFunc = ((delegate* unmanaged*)_atkModule->VirtualTable)[Offsets.ReloadFontsVfunc]; + _reloadFontsFunc = ((delegate* unmanaged*)_atkModule->VirtualTable)[VolatileOffsets.FontReloader.ReloadFontsVFunc]; }); } } diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 2cdc1137..8f20ca5e 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -38,10 +38,10 @@ public unsafe partial class RedrawService : IService // VFuncs that disable and enable draw, used only for GPose actors. private static void DisableDraw(IGameObject actor) - => ((delegate* unmanaged**)actor.Address)[0][Offsets.DisableDrawVfunc](actor.Address); + => ((delegate* unmanaged**)actor.Address)[0][VolatileOffsets.RedrawService.DisableDrawVFunc](actor.Address); private static void EnableDraw(IGameObject actor) - => ((delegate* unmanaged**)actor.Address)[0][Offsets.EnableDrawVfunc](actor.Address); + => ((delegate* unmanaged**)actor.Address)[0][VolatileOffsets.RedrawService.EnableDrawVFunc](actor.Address); // Check whether we currently are in GPose. // Also clear the name list. diff --git a/Penumbra/Interop/VolatileOffsets.cs b/Penumbra/Interop/VolatileOffsets.cs new file mode 100644 index 00000000..2c6e3180 --- /dev/null +++ b/Penumbra/Interop/VolatileOffsets.cs @@ -0,0 +1,35 @@ +namespace Penumbra.Interop; + +public static class VolatileOffsets +{ + public static class ApricotListenerSoundPlayCaller + { + public const int PlayTimeOffset = 0x254; + public const int SomeIntermediate = 0x1F8; + public const int Flags = 0x4A4; + public const int IInstanceListenner = 0x270; + public const int BitShift = 13; + public const int CasterVFunc = 1; + } + + public static class AnimationState + { + public const int TimeLinePtr = 0x50; + } + + public static class UpdateModel + { + public const int ShortCircuit = 0xA2C; + } + + public static class FontReloader + { + public const int ReloadFontsVFunc = 43; + } + + public static class RedrawService + { + public const int EnableDrawVFunc = 12; + public const int DisableDrawVFunc = 13; + } +} diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs index dc94c881..f8760625 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcModGroupEditor.cs @@ -138,7 +138,7 @@ public sealed class ImcModGroupEditor(CommunicatorService communicator, SaveServ protected override bool MoveOption(ImcModGroup group, int optionIdxFrom, int optionIdxTo) { - if (!group.OptionData.Move(optionIdxFrom, optionIdxTo)) + if (!group.OptionData.Move(ref optionIdxFrom, ref optionIdxTo)) return false; group.DefaultSettings = group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index 7f18852d..d01297db 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -90,7 +90,7 @@ public class ModGroupEditor( { var mod = group.Mod; var idxFrom = group.GetIndex(); - if (!mod.Groups.Move(idxFrom, groupIdxTo)) + if (!mod.Groups.Move(ref idxFrom, ref groupIdxTo)) return; saveService.SaveAllOptionGroups(mod, false, config.ReplaceNonAsciiOnImport); diff --git a/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs index 74362325..2446ae80 100644 --- a/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/MultiModGroupEditor.cs @@ -75,7 +75,7 @@ public sealed class MultiModGroupEditor(CommunicatorService communicator, SaveSe protected override bool MoveOption(MultiModGroup group, int optionIdxFrom, int optionIdxTo) { - if (!group.OptionData.Move(optionIdxFrom, optionIdxTo)) + if (!group.OptionData.Move(ref optionIdxFrom, ref optionIdxTo)) return false; group.DefaultSettings = group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); diff --git a/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs index 15a899a0..5fd785cf 100644 --- a/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/SingleModGroupEditor.cs @@ -48,7 +48,7 @@ public sealed class SingleModGroupEditor(CommunicatorService communicator, SaveS protected override bool MoveOption(SingleModGroup group, int optionIdxFrom, int optionIdxTo) { - if (!group.OptionData.Move(optionIdxFrom, optionIdxTo)) + if (!group.OptionData.Move(ref optionIdxFrom, ref optionIdxTo)) return false; group.DefaultSettings = group.DefaultSettings.MoveSingle(optionIdxFrom, optionIdxTo); diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b6b19ef2..41d8f668 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -1,6 +1,5 @@ using Dalamud.Plugin; using ImGuiNET; -using Lumina.Excel.GeneratedSheets; using OtterGui; using OtterGui.Log; using OtterGui.Services; @@ -20,6 +19,7 @@ using OtterGui.Tasks; using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using Dalamud.Plugin.Services; +using Lumina.Excel.Sheets; using Penumbra.GameData.Data; using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.ResourceLoading; @@ -111,7 +111,7 @@ public class Penumbra : IDalamudPlugin private void SetupApi() { _services.GetService(); - var itemSheet = _services.GetService().GetExcelSheet()!; + var itemSheet = _services.GetService().GetExcelSheet(); _communicatorService.ChangedItemHover.Subscribe(it => { if (it is IdentifiedItem { Item.Id.IsItem: true }) diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index a35a67f1..e610cb6a 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -4,7 +4,7 @@ using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin.Services; -using Lumina.Excel.GeneratedSheets; +using Lumina.Excel.Sheets; using OtterGui.Log; using OtterGui.Services; using Penumbra.Mods.Manager; @@ -16,7 +16,7 @@ namespace Penumbra.Services; public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INotificationManager notificationManager) : OtterGui.Classes.MessageService(log, builder, chat, notificationManager), IService { - public void LinkItem(Item item) + public void LinkItem(in Item item) { // @formatter:off var payloadList = new List @@ -29,7 +29,7 @@ public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INoti new TextPayload($"{(char)SeIconChar.LinkMarker}"), new UIForegroundPayload(0), new UIGlowPayload(0), - new TextPayload(item.Name), + new TextPayload(item.Name.ExtractText()), new RawPayload([0x02, 0x27, 0x07, 0xCF, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03]), new RawPayload([0x02, 0x13, 0x02, 0xEC, 0x03]), }; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 7c6cd01e..47c2c16c 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -54,6 +54,9 @@ public class Diagnostics(ServiceManager provider) : IUiService return; using var table = ImRaii.Table("##data", 4, ImGuiTableFlags.RowBg); + if (!table) + return; + foreach (var type in typeof(ActorManager).Assembly.GetTypes() .Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IAsyncDataContainer)))) { diff --git a/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs b/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs index 7af1f884..e8ff9b9c 100644 --- a/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs @@ -34,28 +34,49 @@ public class HookOverrideDrawer(IDalamudPluginInterface pluginInterface) : IUiSe Penumbra.Log.Error($"Could not delete hook override file at {path}:\n{ex}"); } + bool? allVisible = null; + ImGui.SameLine(); + if (ImUtf8.Button("Disable All Visible Hooks"u8)) + allVisible = true; + ImGui.SameLine(); + if (ImUtf8.Button("Enable All VisibleHooks"u8)) + allVisible = false; + bool? all = null; ImGui.SameLine(); - if (ImUtf8.Button("Disable All Hooks"u8)) + if (ImUtf8.Button("Disable All Hooks")) all = true; ImGui.SameLine(); - if (ImUtf8.Button("Enable All Hooks"u8)) + if (ImUtf8.Button("Enable All Hooks")) all = false; foreach (var propertyField in typeof(HookOverrides).GetFields().Where(f => f is { IsStatic: false, FieldType.IsValueType: true })) { using var tree = ImUtf8.TreeNode(propertyField.Name); if (!tree) - continue; - - var property = propertyField.GetValue(_overrides); - foreach (var valueField in propertyField.FieldType.GetFields()) { - var value = valueField.GetValue(property) as bool? ?? false; - if (ImUtf8.Checkbox($"Disable {valueField.Name}", ref value) || all.HasValue) + if (all.HasValue) { - valueField.SetValue(property, all ?? value); - propertyField.SetValue(_overrides, property); + var property = propertyField.GetValue(_overrides); + foreach (var valueField in propertyField.FieldType.GetFields()) + { + valueField.SetValue(property, all.Value); + propertyField.SetValue(_overrides, property); + } + } + } + else + { + allVisible ??= all; + var property = propertyField.GetValue(_overrides); + foreach (var valueField in propertyField.FieldType.GetFields()) + { + var value = valueField.GetValue(property) as bool? ?? false; + if (ImUtf8.Checkbox($"Disable {valueField.Name}", ref value) || allVisible.HasValue) + { + valueField.SetValue(property, allVisible ?? value); + propertyField.SetValue(_overrides, property); + } } } } From 5599f12753624981a79609bbc17a283e24bd0dc6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Nov 2024 14:28:33 +0100 Subject: [PATCH 0960/1381] Further fixes. --- Penumbra/Interop/Hooks/Meta/CalculateHeight.cs | 12 ++++++------ Penumbra/Interop/PathResolving/CollectionResolver.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index 327e3d1e..0e85b3ae 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -14,19 +14,19 @@ public sealed unsafe class CalculateHeight : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Calculate Height", (nint)HeightContainer.MemberFunctionPointers.CalculateHeight, Detour, + Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, !HookOverrides.Instance.Meta.CalculateHeight); } - public delegate ulong Delegate(HeightContainer* character); + public delegate ulong Delegate(Character* character); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private ulong Detour(HeightContainer* container) + private ulong Detour(Character* character) { - var collection = _collectionResolver.IdentifyCollection((GameObject*)container->OwnerObject, true); + var collection = _collectionResolver.IdentifyCollection((GameObject*)character, true); _metaState.RspCollection.Push(collection); - var ret = Task.Result.Original.Invoke(container); - Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)container:X} -> {ret}."); + var ret = Task.Result.Original.Invoke(character); + Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)character:X} -> {ret}."); _metaState.RspCollection.Pop(); return ret; } diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 50088008..576b61bb 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -240,7 +240,7 @@ public sealed unsafe class CollectionResolver( } // Only handle human models. - if (!IsModelHuman((uint)actor.AsCharacter->ModelCharaId)) + if (!IsModelHuman((uint)actor.AsCharacter->ModelContainer.ModelCharaId)) return null; if (actor.Customize->Data[0] == 0) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 62f4febe..b50fc695 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -68,7 +68,7 @@ public class ResourceTree Unsafe.AsPointer(ref character->DrawData.EquipmentModelIds[0]), 10), _ => [], }; - ModelId = character->ModelCharaId; + ModelId = character->ModelContainer.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; From 83e5feb7dbbe452d8499562733dc9ba0edcee1bf Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Nov 2024 14:30:47 +0100 Subject: [PATCH 0961/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 8ba88eff..95b8d177 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 8ba88eff15326bb28ed5e6157f5252c114d40b5f +Subproject commit 95b8d177883b03f804d77434f45e9de97fdb9adf From a864ac196550776a4870b7fc646591a4f1d55632 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Nov 2024 22:00:07 +0100 Subject: [PATCH 0962/1381] 1.3.0.2 --- .github/workflows/test_release.yml | 2 +- Penumbra/Penumbra.json | 2 +- repo.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 0718ded2..549c967a 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 805f4d85..4790da18 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -8,7 +8,7 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], - "DalamudApiLevel": 10, + "DalamudApiLevel": 11, "LoadPriority": 69420, "LoadState": 2, "LoadSync": true, diff --git a/repo.json b/repo.json index 686549c9..71d8fad4 100644 --- a/repo.json +++ b/repo.json @@ -10,7 +10,7 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, - "TestingDalamudApiLevel": 10, + "TestingDalamudApiLevel": 11, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 597380355a4a769de852a0e4e03656163f34fa56 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 17 Nov 2024 21:02:11 +0000 Subject: [PATCH 0963/1381] [CI] Updating repo.json for testing_1.3.0.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 71d8fad4..651802a6 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.0.0", - "TestingAssemblyVersion": "1.3.0.1", + "TestingAssemblyVersion": "1.3.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 7ab5299f7ae77c93e5f318529d1071ec3dfd4931 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Nov 2024 00:28:27 +0100 Subject: [PATCH 0964/1381] Add SCD handling and crc cache visualization. --- Penumbra.sln | 3 + .../Hooks/ResourceLoading/ResourceLoader.cs | 8 +-- .../Hooks/ResourceLoading/TexMdlService.cs | 62 ++++++++++++++----- Penumbra/UI/Tabs/Debug/DebugTab.cs | 29 ++++++++- 4 files changed, 80 insertions(+), 22 deletions(-) diff --git a/Penumbra.sln b/Penumbra.sln index 46609f85..94a04ef3 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -8,7 +8,10 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F89C9EAE-25C8-43BE-8108-5921E5A93502}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig + .github\workflows\build.yml = .github\workflows\build.yml + .github\workflows\release.yml = .github\workflows\release.yml repo.json = repo.json + .github\workflows\test_release.yml = .github\workflows\test_release.yml EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.GameData", "Penumbra.GameData\Penumbra.GameData.csproj", "{EE551E87-FDB3-4612-B500-DC870C07C605}" diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index bcd09b37..442bac15 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -15,18 +15,18 @@ public unsafe class ResourceLoader : IDisposable, IService { private readonly ResourceService _resources; private readonly FileReadService _fileReadService; - private readonly TexMdlService _texMdlService; + private readonly TexMdlScdService _texMdlScdService; private readonly PapHandler _papHandler; private readonly Configuration _config; private ResolveData _resolvedData = ResolveData.Invalid; public event Action? PapRequested; - public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlService texMdlService, Configuration config) + public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlScdService texMdlScdService, Configuration config) { _resources = resources; _fileReadService = fileReadService; - _texMdlService = texMdlService; + _texMdlScdService = texMdlScdService; _config = config; ResetResolvePath(); @@ -140,7 +140,7 @@ public unsafe class ResourceLoader : IDisposable, IService return; } - _texMdlService.AddCrc(type, resolvedPath); + _texMdlScdService.AddCrc(type, resolvedPath); // Replace the hash and path with the correct one for the replacement. hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index d4a2dfba..9c17e0cf 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -10,7 +10,7 @@ using ResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.Re namespace Penumbra.Interop.Hooks.ResourceLoading; -public unsafe class TexMdlService : IDisposable, IRequiredService +public unsafe class TexMdlScdService : IDisposable, IRequiredService { /// /// We need to be able to obtain the requested LoD level. @@ -42,7 +42,7 @@ public unsafe class TexMdlService : IDisposable, IRequiredService private readonly LodService _lodService; - public TexMdlService(IGameInteropProvider interop) + public TexMdlScdService(IGameInteropProvider interop) { interop.InitializeFromAttributes(this); _lodService = new LodService(interop); @@ -52,6 +52,7 @@ public unsafe class TexMdlService : IDisposable, IRequiredService _loadMdlFileExternHook.Enable(); if (!HookOverrides.Instance.ResourceLoading.TexResourceHandleOnLoad) _textureOnLoadHook.Enable(); + _soundOnLoadHook.Enable(); } /// Add CRC64 if the given file is a model or texture file and has an associated path. @@ -59,8 +60,9 @@ public unsafe class TexMdlService : IDisposable, IRequiredService { _ = type switch { - ResourceType.Mdl when path.HasValue => _customMdlCrc.Add(path.Value.Crc64), - ResourceType.Tex when path.HasValue => _customTexCrc.Add(path.Value.Crc64), + ResourceType.Mdl when path.HasValue => _customFileCrc.TryAdd(path.Value.Crc64, ResourceType.Mdl), + ResourceType.Tex when path.HasValue => _customFileCrc.TryAdd(path.Value.Crc64, ResourceType.Tex), + ResourceType.Scd when path.HasValue => _customFileCrc.TryAdd(path.Value.Crc64, ResourceType.Scd), _ => false, }; } @@ -70,15 +72,16 @@ public unsafe class TexMdlService : IDisposable, IRequiredService _checkFileStateHook.Dispose(); _loadMdlFileExternHook.Dispose(); _textureOnLoadHook.Dispose(); + _soundOnLoadHook.Dispose(); } /// /// We need to keep a list of all CRC64 hash values of our replaced Mdl and Tex files, /// i.e. CRC32 of filename in the lower bytes, CRC32 of parent path in the upper bytes. /// - private readonly HashSet _customMdlCrc = []; - - private readonly HashSet _customTexCrc = []; + private readonly Dictionary _customFileCrc = []; + public IReadOnlyDictionary CustomCache + => _customFileCrc; private delegate nint CheckFileStatePrototype(nint unk1, ulong crc64); @@ -86,12 +89,34 @@ public unsafe class TexMdlService : IDisposable, IRequiredService private readonly Hook _checkFileStateHook = null!; private readonly ThreadLocal _texReturnData = new(() => default); + private readonly ThreadLocal _scdReturnData = new(() => default); private delegate void UpdateCategoryDelegate(TextureResourceHandle* resourceHandle); [Signature(Sigs.TexHandleUpdateCategory)] private readonly UpdateCategoryDelegate _updateCategory = null!; + private delegate byte SoundOnLoadDelegate(ResourceHandle* handle, SeFileDescriptor* descriptor, byte unk); + + [Signature("48 89 5C 24 ?? 48 89 74 24 ?? 57 48 83 EC 30 8B 79 ?? 48 8B DA 8B D7")] + private readonly delegate* unmanaged _loadScdFileLocal = null!; + + [Signature("40 56 57 41 54 48 81 EC 90 00 00 00 80 3A 0B 45 0F B6 E0 48 8B F2", DetourName = nameof(OnScdLoadDetour))] + private readonly Hook _soundOnLoadHook = null!; + + private byte OnScdLoadDetour(ResourceHandle* handle, SeFileDescriptor* descriptor, byte unk) + { + var ret = _soundOnLoadHook.Original(handle, descriptor, unk); + if (!_scdReturnData.Value) + return ret; + + // Function failed on a replaced scd, call local. + _scdReturnData.Value = false; + ret = _loadScdFileLocal(handle, descriptor, unk); + _updateCategory((TextureResourceHandle*)handle); + return ret; + } + /// /// The function that checks a files CRC64 to determine whether it is 'protected'. /// We use it to check against our stored CRC64s and if it corresponds, we return the custom flag for models. @@ -100,14 +125,17 @@ public unsafe class TexMdlService : IDisposable, IRequiredService /// private nint CheckFileStateDetour(nint ptr, ulong crc64) { - if (_customMdlCrc.Contains(crc64)) - return CustomFileFlag; - - if (_customTexCrc.Contains(crc64)) - { - _texReturnData.Value = true; - return nint.Zero; - } + if (_customFileCrc.TryGetValue(crc64, out var type)) + switch (type) + { + case ResourceType.Mdl: return CustomFileFlag; + case ResourceType.Tex: + _texReturnData.Value = true; + return nint.Zero; + case ResourceType.Scd: + _scdReturnData.Value = true; + return nint.Zero; + } var ret = _checkFileStateHook.Original(ptr, crc64); Penumbra.Log.Excessive($"[CheckFileState] Called on 0x{ptr:X} with CRC {crc64:X16}, returned 0x{ret:X}."); @@ -128,10 +156,10 @@ public unsafe class TexMdlService : IDisposable, IRequiredService private delegate byte TexResourceHandleOnLoadPrototype(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2); - [Signature(Sigs.TexHandleOnLoad, DetourName = nameof(OnLoadDetour))] + [Signature(Sigs.TexHandleOnLoad, DetourName = nameof(OnTexLoadDetour))] private readonly Hook _textureOnLoadHook = null!; - private byte OnLoadDetour(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2) + private byte OnTexLoadDetour(TextureResourceHandle* handle, SeFileDescriptor* descriptor, byte unk2) { var ret = _textureOnLoadHook.Original(handle, descriptor, unk2); if (!_texReturnData.Value) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 47c2c16c..9184ffe8 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -102,6 +102,7 @@ public class DebugTab : Window, ITab, IUiService private readonly CrashHandlerPanel _crashHandlerPanel; private readonly TexHeaderDrawer _texHeaderDrawer; private readonly HookOverrideDrawer _hookOverrides; + private readonly TexMdlScdService _texMdlScdService; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, @@ -112,7 +113,7 @@ public class DebugTab : Window, ITab, IUiService CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, - HookOverrideDrawer hookOverrides) + HookOverrideDrawer hookOverrides, TexMdlScdService texMdlScdService) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -150,6 +151,7 @@ public class DebugTab : Window, ITab, IUiService _crashHandlerPanel = crashHandlerPanel; _texHeaderDrawer = texHeaderDrawer; _hookOverrides = hookOverrides; + _texMdlScdService = texMdlScdService; _objects = objects; _clientState = clientState; } @@ -183,6 +185,7 @@ public class DebugTab : Window, ITab, IUiService DrawDebugCharacterUtility(); DrawShaderReplacementFixer(); DrawData(); + DrawCrcCache(); DrawResourceProblems(); _hookOverrides.Draw(); DrawPlayerModelInfo(); @@ -1021,6 +1024,30 @@ public class DebugTab : Window, ITab, IUiService DrawDebugResidentResources(); } + private unsafe void DrawCrcCache() + { + var header = ImUtf8.CollapsingHeader("CRC Cache"u8); + if (!header) + return; + + using var table = ImUtf8.Table("table"u8, 2); + if (!table) + return; + + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + ImUtf8.TableSetupColumn("Hash"u8, ImGuiTableColumnFlags.WidthFixed, 18 * UiBuilder.MonoFont.GetCharAdvance('0')); + ImUtf8.TableSetupColumn("Type"u8, ImGuiTableColumnFlags.WidthFixed, 5 * UiBuilder.MonoFont.GetCharAdvance('0')); + ImGui.TableHeadersRow(); + + foreach (var (hash, type) in _texMdlScdService.CustomCache) + { + ImGui.TableNextColumn(); + ImUtf8.Text($"{hash:X16}"); + ImGui.TableNextColumn(); + ImUtf8.Text($"{type}"); + } + } + /// Draw resources with unusual reference count. private unsafe void DrawResourceProblems() { From 41718d8f8fd9106136691f14588fab33b3073269 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Nov 2024 00:28:36 +0100 Subject: [PATCH 0965/1381] Fix screen actor indices. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fb81a0b5..79d8d782 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fb81a0b55d3c68f2b26357fac3049c79fb0c22fb +Subproject commit 79d8d782b3b454a41f7f87f398806ec4d08d485f From 0928d712c91e7ea893c8088d51af63221be486fe Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 17 Nov 2024 23:30:41 +0000 Subject: [PATCH 0966/1381] [CI] Updating repo.json for testing_1.3.0.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 651802a6..77f5012e 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.0.0", - "TestingAssemblyVersion": "1.3.0.2", + "TestingAssemblyVersion": "1.3.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 8a53313c33d0a42edfbbdf09a141525f7db14794 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Nov 2024 20:14:06 +0100 Subject: [PATCH 0967/1381] Add .atch file debugging. --- Penumbra.GameData | 2 +- Penumbra/UI/Tabs/Debug/AtchDrawer.cs | 56 ++++++++++++++++++++++++++++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 29 +++++++++++++- 3 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 Penumbra/UI/Tabs/Debug/AtchDrawer.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 79d8d782..1c82c086 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 79d8d782b3b454a41f7f87f398806ec4d08d485f +Subproject commit 1c82c086704e2f1b3608644a9b1d70628fbe0ca9 diff --git a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs new file mode 100644 index 00000000..f6f6c50e --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs @@ -0,0 +1,56 @@ +using ImGuiNET; +using OtterGui; +using OtterGui.Text; +using Penumbra.GameData.Files; + +namespace Penumbra.UI.Tabs.Debug; + +public static class AtchDrawer +{ + public static void Draw(AtchFile file) + { + using (ImUtf8.Group()) + { + ImUtf8.Text("Entries: "u8); + ImUtf8.Text("States: "u8); + } + + ImGui.SameLine(); + using (ImUtf8.Group()) + { + ImUtf8.Text($"{file.Entries.Count}"); + if (file.Entries.Count == 0) + { + ImUtf8.Text("0"u8); + return; + } + + ImUtf8.Text($"{file.Entries[0].States.Count}"); + } + + foreach (var (entry, index) in file.Entries.WithIndex()) + { + using var id = ImUtf8.PushId(index); + using var tree = ImUtf8.TreeNode(entry.Name.Span); + if (tree) + { + ImUtf8.TreeNode(entry.Accessory ? "Accessory"u8 : "Weapon"u8, ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + foreach (var (state, i) in entry.States.WithIndex()) + { + id.Push(i); + using var t = ImUtf8.TreeNode(state.Bone.Span); + if (t) + { + ImUtf8.TreeNode($"Scale: {state.Scale}", ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + ImUtf8.TreeNode($"Offset: {state.Offset.X} | {state.Offset.Y} | {state.Offset.Z}", + ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + ImUtf8.TreeNode($"Rotation: {state.Rotation.X} | {state.Rotation.Y} | {state.Rotation.Z}", + ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + } + + id.Pop(); + } + } + } + } +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 9184ffe8..cdaaadaa 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -98,6 +98,7 @@ public class DebugTab : Window, ITab, IUiService private readonly Diagnostics _diagnostics; private readonly ObjectManager _objects; private readonly IClientState _clientState; + private readonly IDataManager _dataManager; private readonly IpcTester _ipcTester; private readonly CrashHandlerPanel _crashHandlerPanel; private readonly TexHeaderDrawer _texHeaderDrawer; @@ -105,7 +106,7 @@ public class DebugTab : Window, ITab, IUiService private readonly TexMdlScdService _texMdlScdService; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, - IClientState clientState, + IClientState clientState, IDataManager dataManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, CharacterUtility characterUtility, ResidentResourceManager residentResources, ResourceManagerService resourceManager, CollectionResolver collectionResolver, @@ -154,6 +155,7 @@ public class DebugTab : Window, ITab, IUiService _texMdlScdService = texMdlScdService; _objects = objects; _clientState = clientState; + _dataManager = dataManager; } public ReadOnlySpan Label @@ -665,11 +667,36 @@ public class DebugTab : Window, ITab, IUiService DrawEmotes(); DrawStainTemplates(); + DrawAtch(); } private string _emoteSearchFile = string.Empty; private string _emoteSearchName = string.Empty; + + private AtchFile? _atchFile; + + private void DrawAtch() + { + try + { + _atchFile ??= new AtchFile(_dataManager.GetFile("chara/xls/attachOffset/c0101.atch")!.Data); + } + catch + { + // ignored + } + + if (_atchFile == null) + return; + + using var mainTree = ImUtf8.TreeNode("Atch File C0101"u8); + if (!mainTree) + return; + + AtchDrawer.Draw(_atchFile); + } + private void DrawEmotes() { using var mainTree = TreeNode("Emotes"); From 3beef61c6f04e6bc40ffb40be998d8cf14546cee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Nov 2024 10:44:09 +0100 Subject: [PATCH 0968/1381] Some debug vis improvements, disable .atch file modding for the moment until modular .atch file modding is implemented. --- .../Interop/PathResolving/PathResolver.cs | 4 ++ Penumbra/UI/Tabs/Debug/AtchDrawer.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 51 +++++++++++++------ 3 files changed, 41 insertions(+), 16 deletions(-) diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 63bbc8d8..a7af42e3 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -52,6 +52,10 @@ public class PathResolver : IDisposable, IService if (resourceType is ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb) return (null, ResolveData.Invalid); + // Prevent .atch loading to prevent crashes on outdated .atch files. TODO: handle atch modding differently. + if (resourceType is ResourceType.Atch) + return (null, ResolveData.Invalid); + return category switch { // Only Interface collection. diff --git a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs index f6f6c50e..3e407e99 100644 --- a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs @@ -31,7 +31,7 @@ public static class AtchDrawer foreach (var (entry, index) in file.Entries.WithIndex()) { using var id = ImUtf8.PushId(index); - using var tree = ImUtf8.TreeNode(entry.Name.Span); + using var tree = ImUtf8.TreeNode($"{index:D3}: {entry.Name.Span}"); if (tree) { ImUtf8.TreeNode(entry.Accessory ? "Accessory"u8 : "Weapon"u8, ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index cdaaadaa..28911b05 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -42,6 +42,7 @@ using Penumbra.Api.IpcTester; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.GameData.Files.StainMapStructs; +using Penumbra.String.Classes; using Penumbra.UI.AdvancedWindow.Materials; namespace Penumbra.UI.Tabs.Debug; @@ -196,7 +197,7 @@ public class DebugTab : Window, ITab, IUiService } - private void DrawCollectionCaches() + private unsafe void DrawCollectionCaches() { if (!ImGui.CollapsingHeader( $"Collections ({_collectionManager.Caches.Count}/{_collectionManager.Storage.Count - 1} Caches)###Collections")) @@ -207,25 +208,35 @@ public class DebugTab : Window, ITab, IUiService if (collection.HasCache) { using var color = PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()); - using var node = TreeNode($"{collection.AnonymizedName} (Change Counter {collection.ChangeCounter})"); + using var node = TreeNode($"{collection.Name} (Change Counter {collection.ChangeCounter})###{collection.Name}"); if (!node) continue; color.Pop(); - foreach (var (mod, paths, manips) in collection._cache!.ModData.Data.OrderBy(t => t.Item1.Name)) + using (var resourceNode = ImUtf8.TreeNode("Custom Resources"u8)) { - using var id = mod is TemporaryMod t ? PushId(t.Priority.Value) : PushId(((Mod)mod).ModPath.Name); - using var node2 = TreeNode(mod.Name.Text); - if (!node2) - continue; - - foreach (var path in paths) - - TreeNode(path.ToString(), ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); - - foreach (var manip in manips) - TreeNode(manip.ToString(), ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + if (resourceNode) + foreach (var (path, resource) in collection._cache!.CustomResources) + ImUtf8.TreeNode($"{path} -> 0x{(ulong)resource.ResourceHandle:X}", + ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); } + + using var modNode = ImUtf8.TreeNode("Enabled Mods"u8); + if (modNode) + foreach (var (mod, paths, manips) in collection._cache!.ModData.Data.OrderBy(t => t.Item1.Name)) + { + using var id = mod is TemporaryMod t ? PushId(t.Priority.Value) : PushId(((Mod)mod).ModPath.Name); + using var node2 = TreeNode(mod.Name.Text); + if (!node2) + continue; + + foreach (var path in paths) + + TreeNode(path.ToString(), ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + + foreach (var manip in manips) + TreeNode(manip.ToString(), ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + } } else { @@ -1051,17 +1062,27 @@ public class DebugTab : Window, ITab, IUiService DrawDebugResidentResources(); } + private string _crcInput = string.Empty; + private FullPath _crcPath = FullPath.Empty; + private unsafe void DrawCrcCache() { var header = ImUtf8.CollapsingHeader("CRC Cache"u8); if (!header) return; + if (ImUtf8.InputText("##crcInput"u8, ref _crcInput, "Input path for CRC..."u8)) + _crcPath = new FullPath(_crcInput); + + using var font = ImRaii.PushFont(UiBuilder.MonoFont); + ImUtf8.Text($" CRC32: {_crcPath.InternalName.CiCrc32:X8}"); + ImUtf8.Text($"CI CRC32: {_crcPath.InternalName.Crc32:X8}"); + ImUtf8.Text($" CRC64: {_crcPath.Crc64:X16}"); + using var table = ImUtf8.Table("table"u8, 2); if (!table) return; - using var font = ImRaii.PushFont(UiBuilder.MonoFont); ImUtf8.TableSetupColumn("Hash"u8, ImGuiTableColumnFlags.WidthFixed, 18 * UiBuilder.MonoFont.GetCharAdvance('0')); ImUtf8.TableSetupColumn("Type"u8, ImGuiTableColumnFlags.WidthFixed, 5 * UiBuilder.MonoFont.GetCharAdvance('0')); ImGui.TableHeadersRow(); From 688b84141f3ea1964f7f589503d3af516b1531d4 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 20 Nov 2024 09:46:01 +0000 Subject: [PATCH 0969/1381] [CI] Updating repo.json for testing_1.3.0.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 77f5012e..02437b14 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.0.0", - "TestingAssemblyVersion": "1.3.0.3", + "TestingAssemblyVersion": "1.3.0.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From ce75471e5129068ba765cbff8cdad5626866c31d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Nov 2024 18:08:24 +0100 Subject: [PATCH 0970/1381] Fix issue with resetting GEQP parameters on reload (again?) --- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Meta/Manipulations/MetaDictionary.cs | 11 +++++++++++ Penumbra/Mods/Editor/ModMetaEditor.cs | 3 ++- 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 1c82c086..c855c17c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1c82c086704e2f1b3608644a9b1d70628fbe0ca9 +Subproject commit c855c17cffd7d270c3f013e01767cd052c24c462 diff --git a/Penumbra.String b/Penumbra.String index bd52d080..dd83f972 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit bd52d080b72d67263dc47068e461f17c93bdc779 +Subproject commit dd83f97299ac33cfacb1064bde4f4d1f6a260936 diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 70d4fd47..da061bec 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -79,6 +79,17 @@ public class MetaDictionary _globalEqp.Clear(); } + public void ClearForDefault() + { + Count = _globalEqp.Count; + _imc.Clear(); + _eqp.Clear(); + _eqdp.Clear(); + _est.Clear(); + _rsp.Clear(); + _gmp.Clear(); + } + public bool Equals(MetaDictionary other) => Count == other.Count && _imc.SetEquals(other._imc) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 64c585ea..217ba93d 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -69,7 +69,8 @@ public class ModMetaEditor( public static bool DeleteDefaultValues(MetaFileManager metaFileManager, MetaDictionary dict) { var clone = dict.Clone(); - dict.Clear(); + dict.ClearForDefault(); + var count = 0; foreach (var (key, value) in clone.Imc) { From f2bdaf1b490204de39f668707b3f6d319f5e0eb9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Nov 2024 00:35:17 +0100 Subject: [PATCH 0971/1381] Circumvent rsf not existing. --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 1 + .../Hooks/ResourceLoading/TexMdlService.cs | 27 ++++++++++++++++--- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c855c17c..07d18f7f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c855c17cffd7d270c3f013e01767cd052c24c462 +Subproject commit 07d18f7f7218811956e6663592e53c4145f2d862 diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index a1dd374f..3deeb107 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -96,6 +96,7 @@ public class HookOverrides public bool CheckFileState; public bool TexResourceHandleOnLoad; public bool LoadMdlFileExtern; + public bool SoundOnLoad; } public struct ResourceHooks diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs index 9c17e0cf..b43f1ed5 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs @@ -7,6 +7,7 @@ using Penumbra.GameData; using Penumbra.Interop.Structs; using Penumbra.String.Classes; using ResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle; +using TextureResourceHandle = Penumbra.Interop.Structs.TextureResourceHandle; namespace Penumbra.Interop.Hooks.ResourceLoading; @@ -52,7 +53,8 @@ public unsafe class TexMdlScdService : IDisposable, IRequiredService _loadMdlFileExternHook.Enable(); if (!HookOverrides.Instance.ResourceLoading.TexResourceHandleOnLoad) _textureOnLoadHook.Enable(); - _soundOnLoadHook.Enable(); + if (!HookOverrides.Instance.ResourceLoading.SoundOnLoad) + _soundOnLoadHook.Enable(); } /// Add CRC64 if the given file is a model or texture file and has an associated path. @@ -80,6 +82,7 @@ public unsafe class TexMdlScdService : IDisposable, IRequiredService /// i.e. CRC32 of filename in the lower bytes, CRC32 of parent path in the upper bytes. /// private readonly Dictionary _customFileCrc = []; + public IReadOnlyDictionary CustomCache => _customFileCrc; @@ -98,15 +101,31 @@ public unsafe class TexMdlScdService : IDisposable, IRequiredService private delegate byte SoundOnLoadDelegate(ResourceHandle* handle, SeFileDescriptor* descriptor, byte unk); - [Signature("48 89 5C 24 ?? 48 89 74 24 ?? 57 48 83 EC 30 8B 79 ?? 48 8B DA 8B D7")] + [Signature(Sigs.LoadScdFileLocal)] private readonly delegate* unmanaged _loadScdFileLocal = null!; - [Signature("40 56 57 41 54 48 81 EC 90 00 00 00 80 3A 0B 45 0F B6 E0 48 8B F2", DetourName = nameof(OnScdLoadDetour))] + [Signature(Sigs.SoundOnLoad, DetourName = nameof(OnScdLoadDetour))] private readonly Hook _soundOnLoadHook = null!; + [Signature(Sigs.RsfServiceAddress, ScanType = ScanType.StaticAddress)] + private readonly nint* _rsfService = null; + private byte OnScdLoadDetour(ResourceHandle* handle, SeFileDescriptor* descriptor, byte unk) { - var ret = _soundOnLoadHook.Original(handle, descriptor, unk); + byte ret; + if (*_rsfService == nint.Zero) + { + Penumbra.Log.Debug( + $"Resource load of {handle->FileName} before FFXIV RSF-service was instantiated, workaround by setting pointer."); + *_rsfService = 1; + ret = _soundOnLoadHook.Original(handle, descriptor, unk); + *_rsfService = nint.Zero; + } + else + { + ret = _soundOnLoadHook.Original(handle, descriptor, unk); + } + if (!_scdReturnData.Value) return ret; From ee48ea0166171e5437a5d5731a069aeb6aabc99f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Nov 2024 00:43:36 +0100 Subject: [PATCH 0972/1381] Some stashed changes already applied. --- Penumbra/Collections/ModCollection.cs | 1 + .../Hooks/ResourceLoading/ResourceLoader.cs | 8 ++++---- .../{TexMdlService.cs => RsfService.cs} | 4 ++-- .../Interop/PathResolving/PathDataHandler.cs | 5 +++++ .../Interop/Processing/ImcFilePostProcessor.cs | 3 ++- Penumbra/UI/ResourceWatcher/Record.cs | 14 +++++++++++--- Penumbra/UI/ResourceWatcher/ResourceWatcher.cs | 2 +- .../UI/ResourceWatcher/ResourceWatcherTable.cs | 18 +++++++++++++++++- Penumbra/UI/Tabs/Debug/AtchDrawer.cs | 15 ++++++++------- Penumbra/UI/Tabs/Debug/DebugTab.cs | 8 ++++---- 10 files changed, 55 insertions(+), 23 deletions(-) rename Penumbra/Interop/Hooks/ResourceLoading/{TexMdlService.cs => RsfService.cs} (96%) diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index eb5ab46a..db9c19cb 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -57,6 +57,7 @@ public partial class ModCollection public int ChangeCounter { get; private set; } public uint ImcChangeCounter { get; set; } + public uint AtchChangeCounter { get; set; } /// Increment the number of changes in the effective file list. public int IncrementCounter() diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 442bac15..47f96d98 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -15,18 +15,18 @@ public unsafe class ResourceLoader : IDisposable, IService { private readonly ResourceService _resources; private readonly FileReadService _fileReadService; - private readonly TexMdlScdService _texMdlScdService; + private readonly RsfService _rsfService; private readonly PapHandler _papHandler; private readonly Configuration _config; private ResolveData _resolvedData = ResolveData.Invalid; public event Action? PapRequested; - public ResourceLoader(ResourceService resources, FileReadService fileReadService, TexMdlScdService texMdlScdService, Configuration config) + public ResourceLoader(ResourceService resources, FileReadService fileReadService, RsfService rsfService, Configuration config) { _resources = resources; _fileReadService = fileReadService; - _texMdlScdService = texMdlScdService; + _rsfService = rsfService; _config = config; ResetResolvePath(); @@ -140,7 +140,7 @@ public unsafe class ResourceLoader : IDisposable, IService return; } - _texMdlScdService.AddCrc(type, resolvedPath); + _rsfService.AddCrc(type, resolvedPath); // Replace the hash and path with the correct one for the replacement. hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs b/Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs similarity index 96% rename from Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs rename to Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs index b43f1ed5..7ac1563f 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/TexMdlService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs @@ -11,7 +11,7 @@ using TextureResourceHandle = Penumbra.Interop.Structs.TextureResourceHandle; namespace Penumbra.Interop.Hooks.ResourceLoading; -public unsafe class TexMdlScdService : IDisposable, IRequiredService +public unsafe class RsfService : IDisposable, IRequiredService { /// /// We need to be able to obtain the requested LoD level. @@ -43,7 +43,7 @@ public unsafe class TexMdlScdService : IDisposable, IRequiredService private readonly LodService _lodService; - public TexMdlScdService(IGameInteropProvider interop) + public RsfService(IGameInteropProvider interop) { interop.InitializeFromAttributes(this); _lodService = new LodService(interop); diff --git a/Penumbra/Interop/PathResolving/PathDataHandler.cs b/Penumbra/Interop/PathResolving/PathDataHandler.cs index 9410ff98..5439151f 100644 --- a/Penumbra/Interop/PathResolving/PathDataHandler.cs +++ b/Penumbra/Interop/PathResolving/PathDataHandler.cs @@ -44,6 +44,11 @@ public static class PathDataHandler public static FullPath CreateAvfx(CiByteString path, ModCollection collection) => CreateBase(path, collection); + /// Create the encoding path for an ATCH file. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static FullPath CreateAtch(CiByteString path, ModCollection collection) + => new($"|{collection.LocalId.Id}_{collection.AtchChangeCounter}_{DiscriminatorString}|{path}"); + /// Create the encoding path for a MTRL file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateMtrl(CiByteString path, ModCollection collection, Utf8GamePath originalPath) diff --git a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs index 33a3941a..a3233cfb 100644 --- a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs +++ b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs @@ -1,3 +1,4 @@ +using Dalamud.Game.ClientState.JobGauge.Types; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; @@ -24,7 +25,7 @@ public sealed class ImcFilePostProcessor(CollectionStorage collections) : IFileP return; file.Replace(resource); - Penumbra.Log.Information( + Penumbra.Log.Verbose( $"[ResourceLoader] Loaded {originalGamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); } } diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index b69d9944..7338e5a9 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -3,6 +3,7 @@ using Penumbra.Collections; using Penumbra.Enums; using Penumbra.Interop.Structs; using Penumbra.String; +using Penumbra.String.Classes; namespace Penumbra.UI.ResourceWatcher; @@ -24,14 +25,16 @@ internal unsafe struct Record public ModCollection? Collection; public ResourceHandle* Handle; public ResourceTypeFlag ResourceType; - public ResourceCategoryFlag Category; + public ulong Crc64; public uint RefCount; + public ResourceCategoryFlag Category; public RecordType RecordType; public OptionalBool Synchronously; public OptionalBool ReturnValue; public OptionalBool CustomLoad; public LoadState LoadState; + public static Record CreateRequest(CiByteString path, bool sync) => new() { @@ -49,6 +52,7 @@ internal unsafe struct Record CustomLoad = OptionalBool.Null, AssociatedGameObject = string.Empty, LoadState = LoadState.None, + Crc64 = 0, }; public static Record CreateDefaultLoad(CiByteString path, ResourceHandle* handle, ModCollection collection, string associatedGameObject) @@ -70,15 +74,16 @@ internal unsafe struct Record CustomLoad = false, AssociatedGameObject = associatedGameObject, LoadState = handle->LoadState, + Crc64 = 0, }; } - public static Record CreateLoad(CiByteString path, CiByteString originalPath, ResourceHandle* handle, ModCollection collection, + public static Record CreateLoad(FullPath path, CiByteString originalPath, ResourceHandle* handle, ModCollection collection, string associatedGameObject) => new() { Time = DateTime.UtcNow, - Path = path.IsOwned ? path : path.Clone(), + Path = path.InternalName.IsOwned ? path.InternalName : path.InternalName.Clone(), OriginalPath = originalPath.IsOwned ? originalPath : originalPath.Clone(), Collection = collection, Handle = handle, @@ -91,6 +96,7 @@ internal unsafe struct Record CustomLoad = true, AssociatedGameObject = associatedGameObject, LoadState = handle->LoadState, + Crc64 = path.Crc64, }; public static Record CreateDestruction(ResourceHandle* handle) @@ -112,6 +118,7 @@ internal unsafe struct Record CustomLoad = OptionalBool.Null, AssociatedGameObject = string.Empty, LoadState = handle->LoadState, + Crc64 = 0, }; } @@ -132,5 +139,6 @@ internal unsafe struct Record CustomLoad = custom, AssociatedGameObject = string.Empty, LoadState = handle->LoadState, + Crc64 = 0, }; } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 6f1ce9cf..d432e97e 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -250,7 +250,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService var record = manipulatedPath == null ? Record.CreateDefaultLoad(path.Path, handle, data.ModCollection, Name(data)) - : Record.CreateLoad(manipulatedPath.Value.InternalName, path.Path, handle, data.ModCollection, Name(data)); + : Record.CreateLoad(manipulatedPath.Value, path.Path, handle, data.ModCollection, Name(data)); if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 2bb71b87..88b7120d 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -29,7 +29,8 @@ internal sealed class ResourceWatcherTable : Table new HandleColumn { Label = "Resource" }, new LoadStateColumn { Label = "State" }, new RefCountColumn { Label = "#Ref" }, - new DateColumn { Label = "Time" } + new DateColumn { Label = "Time" }, + new Crc64Column { Label = "Crc64" } ) { } @@ -144,6 +145,21 @@ internal sealed class ResourceWatcherTable : Table => ImGui.TextUnformatted($"{item.Time.ToLongTimeString()}.{item.Time.Millisecond:D4}"); } + private sealed class Crc64Column : ColumnString + { + public override float Width + => UiBuilder.MonoFont.GetCharAdvance('0') * 17; + + public override unsafe string ToName(Record item) + => item.Crc64 != 0 ? $"{item.Crc64:X16}" : string.Empty; + + public override unsafe void DrawColumn(Record item, int _) + { + using var font = ImRaii.PushFont(UiBuilder.MonoFont, item.Handle != null); + ImUtf8.Text(ToName(item)); + } + } + private sealed class CollectionColumn : ColumnString { diff --git a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs index 3e407e99..d9058083 100644 --- a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs @@ -2,6 +2,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Text; using Penumbra.GameData.Files; +using Penumbra.GameData.Files.AtchStructs; namespace Penumbra.UI.Tabs.Debug; @@ -18,27 +19,27 @@ public static class AtchDrawer ImGui.SameLine(); using (ImUtf8.Group()) { - ImUtf8.Text($"{file.Entries.Count}"); - if (file.Entries.Count == 0) + ImUtf8.Text($"{file.Points.Count}"); + if (file.Points.Count == 0) { ImUtf8.Text("0"u8); return; } - ImUtf8.Text($"{file.Entries[0].States.Count}"); + ImUtf8.Text($"{file.Points[0].Entries.Length}"); } - foreach (var (entry, index) in file.Entries.WithIndex()) + foreach (var (entry, index) in file.Points.WithIndex()) { using var id = ImUtf8.PushId(index); - using var tree = ImUtf8.TreeNode($"{index:D3}: {entry.Name.Span}"); + using var tree = ImUtf8.TreeNode($"{index:D3}: {entry.Type.ToName()}"); if (tree) { ImUtf8.TreeNode(entry.Accessory ? "Accessory"u8 : "Weapon"u8, ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); - foreach (var (state, i) in entry.States.WithIndex()) + foreach (var (state, i) in entry.Entries.WithIndex()) { id.Push(i); - using var t = ImUtf8.TreeNode(state.Bone.Span); + using var t = ImUtf8.TreeNode(state.Bone); if (t) { ImUtf8.TreeNode($"Scale: {state.Scale}", ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 28911b05..fc735d04 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -104,7 +104,7 @@ public class DebugTab : Window, ITab, IUiService private readonly CrashHandlerPanel _crashHandlerPanel; private readonly TexHeaderDrawer _texHeaderDrawer; private readonly HookOverrideDrawer _hookOverrides; - private readonly TexMdlScdService _texMdlScdService; + private readonly RsfService _rsfService; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -115,7 +115,7 @@ public class DebugTab : Window, ITab, IUiService CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, - HookOverrideDrawer hookOverrides, TexMdlScdService texMdlScdService) + HookOverrideDrawer hookOverrides, RsfService rsfService) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -153,7 +153,7 @@ public class DebugTab : Window, ITab, IUiService _crashHandlerPanel = crashHandlerPanel; _texHeaderDrawer = texHeaderDrawer; _hookOverrides = hookOverrides; - _texMdlScdService = texMdlScdService; + _rsfService = rsfService; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -1087,7 +1087,7 @@ public class DebugTab : Window, ITab, IUiService ImUtf8.TableSetupColumn("Type"u8, ImGuiTableColumnFlags.WidthFixed, 5 * UiBuilder.MonoFont.GetCharAdvance('0')); ImGui.TableHeadersRow(); - foreach (var (hash, type) in _texMdlScdService.CustomCache) + foreach (var (hash, type) in _rsfService.CustomCache) { ImGui.TableNextColumn(); ImUtf8.Text($"{hash:X16}"); From 37332c432b4128008538058e2088ed305117f26c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Nov 2024 12:34:45 +0100 Subject: [PATCH 0973/1381] 1.3.1.0 --- Penumbra/Penumbra.cs | 2 +- Penumbra/UI/Changelog.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 41d8f668..2c70816e 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -186,7 +186,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", - "IllusioVitae", "Aetherment", + "IllusioVitae", "Aetherment", "LoporritSync", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 48ac90d8..0b0ca81a 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -54,10 +54,28 @@ public class PenumbraChangelog : IUiService Add1_1_1_0(Changelog); Add1_2_1_0(Changelog); Add1_3_0_0(Changelog); + Add1_3_1_0(Changelog); } #region Changelogs + private static void Add1_3_1_0(Changelog log) + => log.NextVersion("Version 1.3.1.0") + .RegisterEntry("Penumbra has been updated for Dalamud API 11 and patch 7.1.") + .RegisterImportant("There are some known issues with potential crashes using certain VFX/SFX mods, probably related to sound files.") + .RegisterEntry("If you encounter those issues, please report them in the discord and potentially disable the corresponding mods for the time being.", 1) + .RegisterImportant("The modding of .atch files has been disabled. Outdated modded versions of these files cause crashes when loaded.") + .RegisterEntry("A better way for modular modding of .atch files via meta changes will release to the testing branch soonish.", 1) + .RegisterHighlight("Temporary collections (as created by Mare) will now always respect ownership.") + .RegisterEntry("This means that you can toggle this setting off if you do not want it, and Mare will still work for minions and mounts of other players.", 1) + .RegisterEntry("The new physics and animation engine files (.kdb and .bnmb) should now be correctly redirected and respect EST changes.") + .RegisterEntry("Fixed issues with EQP entries being labeled wrongly and global EQP not changing all required values for earrings.") + .RegisterEntry("Fixed an issue with global EQP changes of a mod being reset upon reloading the mod.") + .RegisterEntry("Fixed another issue with left rings and mare synchronization / the on-screen tab.") + .RegisterEntry("Maybe fixed some issues with characters appearing in the login screen being misidentified.") + .RegisterEntry("Some improvements for debug visualization have been made."); + + private static void Add1_3_0_0(Changelog log) => log.NextVersion("Version 1.3.0.0") From 977cb2196a138ed6cb6f4a14d939ea1272ff72b8 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Nov 2024 13:29:57 +0000 Subject: [PATCH 0974/1381] [CI] Updating repo.json for 1.3.1.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 02437b14..e7ad4df3 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.0.0", - "TestingAssemblyVersion": "1.3.0.4", + "AssemblyVersion": "1.3.1.0", + "TestingAssemblyVersion": "1.3.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 10, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.0.4/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.0.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 234130cf862ee821e9dd6e0eb9470d68adb38a06 Mon Sep 17 00:00:00 2001 From: Ottermandias <70807659+Ottermandias@users.noreply.github.com> Date: Fri, 22 Nov 2024 14:44:00 +0100 Subject: [PATCH 0975/1381] Update repo.json --- repo.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/repo.json b/repo.json index e7ad4df3..659f4c24 100644 --- a/repo.json +++ b/repo.json @@ -9,7 +9,7 @@ "TestingAssemblyVersion": "1.3.1.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 10, + "DalamudApiLevel": 11, "TestingDalamudApiLevel": 11, "IsHide": "False", "IsTestingExclusive": "False", From 06ba0ba956b0d4d121e5949e9b7c69c56fe3fa0c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Nov 2024 17:31:53 +0100 Subject: [PATCH 0976/1381] Fix glasses issue with resource trees. --- Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index b1cbb74d..e67bf913 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -53,7 +53,7 @@ internal partial record ResolveContext if (characterRaceCode == GenderRace.MidlanderMale) return GenderRace.MidlanderMale; - var accessory = slotIndex >= 5; + var accessory = IsEquipmentSlot(slotIndex); if ((ushort)characterRaceCode % 10 != 1 && accessory) return GenderRace.MidlanderMale; From 22be9f2d0726f78dd335b96fd84e4000bb8972c6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Nov 2024 16:34:25 +0000 Subject: [PATCH 0977/1381] [CI] Updating repo.json for 1.3.1.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 659f4c24..f1734ed7 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.1.0", - "TestingAssemblyVersion": "1.3.1.0", + "AssemblyVersion": "1.3.1.1", + "TestingAssemblyVersion": "1.3.1.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 17d8826ae920b1509cef8b9612fdaf5cef93f17a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Nov 2024 19:12:53 +0100 Subject: [PATCH 0978/1381] This time correctly, maybe? --- Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index e67bf913..0c36b745 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -53,7 +53,7 @@ internal partial record ResolveContext if (characterRaceCode == GenderRace.MidlanderMale) return GenderRace.MidlanderMale; - var accessory = IsEquipmentSlot(slotIndex); + var accessory = !IsEquipmentSlot(slotIndex); if ((ushort)characterRaceCode % 10 != 1 && accessory) return GenderRace.MidlanderMale; From 5a46361d4f478eeecc45cc82fdde609e7aa92e98 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Nov 2024 18:16:51 +0000 Subject: [PATCH 0979/1381] [CI] Updating repo.json for 1.3.1.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index f1734ed7..a714fbe0 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.1.1", - "TestingAssemblyVersion": "1.3.1.1", + "AssemblyVersion": "1.3.1.2", + "TestingAssemblyVersion": "1.3.1.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 25aac1a03e2b197f32f493835393c809654fbaf2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 23 Nov 2024 13:57:54 +0100 Subject: [PATCH 0980/1381] Fix CalculateHeight. --- Penumbra/Interop/Hooks/Meta/CalculateHeight.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs index 0e85b3ae..3dac17bd 100644 --- a/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs +++ b/Penumbra/Interop/Hooks/Meta/CalculateHeight.cs @@ -14,19 +14,19 @@ public sealed unsafe class CalculateHeight : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Calculate Height", (nint)Character.MemberFunctionPointers.CalculateHeight, Detour, + Task = hooks.CreateHook("Calculate Height", (nint)ModelContainer.MemberFunctionPointers.CalculateHeight, Detour, !HookOverrides.Instance.Meta.CalculateHeight); } - public delegate ulong Delegate(Character* character); + public delegate float Delegate(ModelContainer* character); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private ulong Detour(Character* character) + private float Detour(ModelContainer* container) { - var collection = _collectionResolver.IdentifyCollection((GameObject*)character, true); + var collection = _collectionResolver.IdentifyCollection((GameObject*)container->OwnerObject, true); _metaState.RspCollection.Push(collection); - var ret = Task.Result.Original.Invoke(character); - Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)character:X} -> {ret}."); + var ret = Task.Result.Original.Invoke(container); + Penumbra.Log.Excessive($"[Calculate Height] Invoked on {(nint)container:X} -> {ret}."); _metaState.RspCollection.Pop(); return ret; } From 9822ab4128dedc12d9c5cd08af502dce3f06bb53 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Nov 2024 16:59:07 +0100 Subject: [PATCH 0981/1381] Add some debug helper output for SeFileDescriptor. --- Penumbra/Interop/Structs/SeFileDescriptor.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Penumbra/Interop/Structs/SeFileDescriptor.cs b/Penumbra/Interop/Structs/SeFileDescriptor.cs index 67730799..02ab4dc8 100644 --- a/Penumbra/Interop/Structs/SeFileDescriptor.cs +++ b/Penumbra/Interop/Structs/SeFileDescriptor.cs @@ -1,3 +1,6 @@ +using Dalamud.Memory; +using Penumbra.String.Functions; + namespace Penumbra.Interop.Structs; [StructLayout(LayoutKind.Explicit)] @@ -14,4 +17,18 @@ public unsafe struct SeFileDescriptor [FieldOffset(0x70)] public char Utf16FileName; + + public FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle* CsResourceHandele + => (FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle*)ResourceHandle; + + public string FileName + { + get + { + fixed (char* ptr = &Utf16FileName) + { + return MemoryMarshal.CreateReadOnlySpanFromNullTerminated(ptr).ToString(); + } + } + } } From d0e0ae46e67fc7e5c5a7af663811521cb1080c5a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Nov 2024 17:46:14 +0100 Subject: [PATCH 0982/1381] Push an ID in itemselector. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 95b8d177..215e0172 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 95b8d177883b03f804d77434f45e9de97fdb9adf +Subproject commit 215e01722a319c70b271dd23a40d99edc3fc197e From d2a015f32ad859b703449fc025546a30bed7156f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 26 Nov 2024 01:58:44 +0100 Subject: [PATCH 0983/1381] Ughhhhhhhhhh --- Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs | 1 - Penumbra/Penumbra.cs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs b/Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs index 7ac1563f..e7f06f91 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/RsfService.cs @@ -132,7 +132,6 @@ public unsafe class RsfService : IDisposable, IRequiredService // Function failed on a replaced scd, call local. _scdReturnData.Value = false; ret = _loadScdFileLocal(handle, descriptor, unk); - _updateCategory((TextureResourceHandle*)handle); return ret; } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 2c70816e..1bf8844c 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -186,7 +186,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", - "IllusioVitae", "Aetherment", "LoporritSync", + "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) From cc49bdcb3669452debf57879d9ec4a2c78cfbd94 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 26 Nov 2024 01:02:41 +0000 Subject: [PATCH 0984/1381] [CI] Updating repo.json for 1.3.1.3 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index a714fbe0..f5a8e2f1 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.1.2", - "TestingAssemblyVersion": "1.3.1.2", + "AssemblyVersion": "1.3.1.3", + "TestingAssemblyVersion": "1.3.1.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 65538868c314557be65cf0e2b2e2231de1b15f45 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 26 Nov 2024 15:49:33 +0100 Subject: [PATCH 0985/1381] Add Artemis --- Penumbra/Penumbra.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 1bf8844c..917dba6c 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -186,7 +186,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", - "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", + "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", "RoleplayingVoiceDalamud", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) From b1be868a6a9eaa94fec3f307cd0223e0c6b38e3c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Nov 2024 12:19:14 +0100 Subject: [PATCH 0986/1381] Atch stuff. --- Penumbra.GameData | 2 +- Penumbra/Api/Api/MetaApi.cs | 12 + Penumbra/Collections/Cache/AtchCache.cs | 122 +++++++++ Penumbra/Collections/Cache/CollectionCache.cs | 33 ++- Penumbra/Collections/Cache/MetaCache.cs | 10 +- Penumbra/Interop/Hooks/DebugHook.cs | 10 +- Penumbra/Interop/Hooks/HookSettings.cs | 2 + .../Interop/Hooks/Meta/AtchCallerHook1.cs | 39 +++ .../Interop/Hooks/Meta/AtchCallerHook2.cs | 38 +++ Penumbra/Interop/PathResolving/MetaState.cs | 1 + .../Interop/PathResolving/PathResolver.cs | 9 +- .../Processing/AtchFilePostProcessor.cs | 43 +++ .../Processing/AtchPathPreProcessor.cs | 44 ++++ .../Processing/GamePathPreProcessService.cs | 3 +- Penumbra/Meta/AtchManager.cs | 26 ++ Penumbra/Meta/Manipulations/AtchIdentifier.cs | 77 ++++++ .../Meta/Manipulations/IMetaIdentifier.cs | 1 + Penumbra/Meta/Manipulations/MetaDictionary.cs | 72 ++++- Penumbra/Meta/MetaFileManager.cs | 5 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 1 + Penumbra/Penumbra.cs | 1 + .../UI/AdvancedWindow/Meta/AtchMetaDrawer.cs | 245 ++++++++++++++++++ .../UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 3 +- .../UI/AdvancedWindow/Meta/EqpMetaDrawer.cs | 3 +- .../UI/AdvancedWindow/Meta/EstMetaDrawer.cs | 3 +- .../Meta/GlobalEqpMetaDrawer.cs | 3 +- .../UI/AdvancedWindow/Meta/GmpMetaDrawer.cs | 3 +- .../UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 9 +- Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 14 +- .../UI/AdvancedWindow/Meta/MetaDrawers.cs | 7 +- .../UI/AdvancedWindow/Meta/RspMetaDrawer.cs | 3 +- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 1 + 32 files changed, 802 insertions(+), 43 deletions(-) create mode 100644 Penumbra/Collections/Cache/AtchCache.cs create mode 100644 Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs create mode 100644 Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs create mode 100644 Penumbra/Interop/Processing/AtchFilePostProcessor.cs create mode 100644 Penumbra/Interop/Processing/AtchPathPreProcessor.cs create mode 100644 Penumbra/Meta/AtchManager.cs create mode 100644 Penumbra/Meta/Manipulations/AtchIdentifier.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 07d18f7f..2b0c7f3b 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 07d18f7f7218811956e6663592e53c4145f2d862 +Subproject commit 2b0c7f3bee0bc2eb466540d2fac265804354493d diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index 6f3ed51e..217cb1e3 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -5,6 +5,7 @@ using OtterGui; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Cache; +using Penumbra.GameData.Files.AtchStructs; using Penumbra.GameData.Files.Utility; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; @@ -66,6 +67,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver MetaDictionary.SerializeTo(array, cache.Est.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); MetaDictionary.SerializeTo(array, cache.Rsp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); MetaDictionary.SerializeTo(array, cache.Gmp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Atch.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); } return Functions.ToCompressedBase64(array, 0); @@ -97,6 +99,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver WriteCache(zipStream, cache.Est); WriteCache(zipStream, cache.Rsp); WriteCache(zipStream, cache.Gmp); + WriteCache(zipStream, cache.Atch); cache.GlobalEqp.EnterReadLock(); try @@ -246,6 +249,15 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver return false; } + var atchCount = r.ReadInt32(); + for (var i = 0; i < atchCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + var globalEqpCount = r.ReadInt32(); for (var i = 0; i < globalEqpCount; ++i) { diff --git a/Penumbra/Collections/Cache/AtchCache.cs b/Penumbra/Collections/Cache/AtchCache.cs new file mode 100644 index 00000000..9e0f6caf --- /dev/null +++ b/Penumbra/Collections/Cache/AtchCache.cs @@ -0,0 +1,122 @@ +using Penumbra.GameData.Enums; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.AtchStructs; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Collections.Cache; + +public sealed class AtchCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) +{ + private readonly Dictionary)> _atchFiles = []; + + public bool HasFile(GenderRace gr) + => _atchFiles.ContainsKey(gr); + + public bool GetFile(GenderRace gr, [NotNullWhen(true)] out AtchFile? file) + { + if (!_atchFiles.TryGetValue(gr, out var p)) + { + file = null; + return false; + } + + file = p.Item1; + return true; + } + + public void Reset() + { + foreach (var (_, (_, set)) in _atchFiles) + set.Clear(); + + _atchFiles.Clear(); + Clear(); + } + + protected override void ApplyModInternal(AtchIdentifier identifier, AtchEntry entry) + { + ++Collection.AtchChangeCounter; + ApplyFile(identifier, entry); + } + + private void ApplyFile(AtchIdentifier identifier, AtchEntry entry) + { + try + { + if (!_atchFiles.TryGetValue(identifier.GenderRace, out var pair)) + { + if (!Manager.AtchManager.AtchFileBase.TryGetValue(identifier.GenderRace, out var baseFile)) + throw new Exception($"Invalid Atch File for {identifier.GenderRace.ToName()} requested."); + + pair = (baseFile.Clone(), []); + } + + + if (!Apply(pair.Item1, identifier, entry)) + return; + + pair.Item2.Add(identifier); + _atchFiles[identifier.GenderRace] = pair; + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not apply ATCH Manipulation {identifier}:\n{e}"); + } + } + + protected override void RevertModInternal(AtchIdentifier identifier) + { + ++Collection.AtchChangeCounter; + if (!_atchFiles.TryGetValue(identifier.GenderRace, out var pair)) + return; + + if (!pair.Item2.Remove(identifier)) + return; + + if (pair.Item2.Count == 0) + { + _atchFiles.Remove(identifier.GenderRace); + return; + } + + var def = GetDefault(Manager, identifier); + if (def == null) + throw new Exception($"Reverting an .atch mod had no default value for the identifier to revert to."); + + Apply(pair.Item1, identifier, def.Value); + } + + public static AtchEntry? GetDefault(MetaFileManager manager, AtchIdentifier identifier) + { + if (!manager.AtchManager.AtchFileBase.TryGetValue(identifier.GenderRace, out var baseFile)) + return null; + + if (baseFile.Points.FirstOrDefault(p => p.Type == identifier.Type) is not { } point) + return null; + + if (point.Entries.Length <= identifier.EntryIndex) + return null; + + return point.Entries[identifier.EntryIndex]; + } + + public static bool Apply(AtchFile file, AtchIdentifier identifier, in AtchEntry entry) + { + if (file.Points.FirstOrDefault(p => p.Type == identifier.Type) is not { } point) + return false; + + if (point.Entries.Length <= identifier.EntryIndex) + return false; + + point.Entries[identifier.EntryIndex] = entry; + return true; + } + + protected override void Dispose(bool _) + { + Clear(); + _atchFiles.Clear(); + } +} diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index abc0dff8..64cf54ea 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -228,20 +228,25 @@ public sealed class CollectionCache : IDisposable foreach (var (path, file) in files.FileRedirections) AddFile(path, file, mod); - foreach (var (identifier, entry) in files.Manipulations.Eqp) - AddManipulation(mod, identifier, entry); - foreach (var (identifier, entry) in files.Manipulations.Eqdp) - AddManipulation(mod, identifier, entry); - foreach (var (identifier, entry) in files.Manipulations.Est) - AddManipulation(mod, identifier, entry); - foreach (var (identifier, entry) in files.Manipulations.Gmp) - AddManipulation(mod, identifier, entry); - foreach (var (identifier, entry) in files.Manipulations.Rsp) - AddManipulation(mod, identifier, entry); - foreach (var (identifier, entry) in files.Manipulations.Imc) - AddManipulation(mod, identifier, entry); - foreach (var identifier in files.Manipulations.GlobalEqp) - AddManipulation(mod, identifier, null!); + if (files.Manipulations.Count > 0) + { + foreach (var (identifier, entry) in files.Manipulations.Eqp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Eqdp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Est) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Gmp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Rsp) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Imc) + AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Atch) + AddManipulation(mod, identifier, entry); + foreach (var identifier in files.Manipulations.GlobalEqp) + AddManipulation(mod, identifier, null!); + } if (addMetaChanges) { diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 05a94ac5..7d8586c3 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -1,4 +1,5 @@ using Penumbra.GameData.Enums; +using Penumbra.GameData.Files.AtchStructs; using Penumbra.GameData.Structs; using Penumbra.Meta; using Penumbra.Meta.Manipulations; @@ -14,11 +15,12 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public readonly GmpCache Gmp = new(manager, collection); public readonly RspCache Rsp = new(manager, collection); public readonly ImcCache Imc = new(manager, collection); + public readonly AtchCache Atch = new(manager, collection); public readonly GlobalEqpCache GlobalEqp = new(); public bool IsDisposed { get; private set; } public int Count - => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + GlobalEqp.Count; + => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + Atch.Count + GlobalEqp.Count; public IEnumerable<(IMetaIdentifier, IMod)> IdentifierSources => Eqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source)) @@ -27,6 +29,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) .Concat(Gmp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(Rsp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(Imc.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Atch.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(GlobalEqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value))); public void Reset() @@ -37,6 +40,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Gmp.Reset(); Rsp.Reset(); Imc.Reset(); + Atch.Reset(); GlobalEqp.Clear(); } @@ -52,6 +56,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Gmp.Dispose(); Rsp.Dispose(); Imc.Dispose(); + Atch.Dispose(); } public bool TryGetMod(IMetaIdentifier identifier, [NotNullWhen(true)] out IMod? mod) @@ -65,6 +70,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) GmpIdentifier i => Gmp.TryGetValue(i, out var p) && Convert(p, out mod), ImcIdentifier i => Imc.TryGetValue(i, out var p) && Convert(p, out mod), RspIdentifier i => Rsp.TryGetValue(i, out var p) && Convert(p, out mod), + AtchIdentifier i => Atch.TryGetValue(i, out var p) && Convert(p, out mod), GlobalEqpManipulation i => GlobalEqp.TryGetValue(i, out mod), _ => false, }; @@ -85,6 +91,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) GmpIdentifier i => Gmp.RevertMod(i, out mod), ImcIdentifier i => Imc.RevertMod(i, out mod), RspIdentifier i => Rsp.RevertMod(i, out mod), + AtchIdentifier i => Atch.RevertMod(i, out mod), GlobalEqpManipulation i => GlobalEqp.RevertMod(i, out mod), _ => (mod = null) != null, }; @@ -100,6 +107,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) GmpIdentifier i when entry is GmpEntry e => Gmp.ApplyMod(mod, i, e), ImcIdentifier i when entry is ImcEntry e => Imc.ApplyMod(mod, i, e), RspIdentifier i when entry is RspEntry e => Rsp.ApplyMod(mod, i, e), + AtchIdentifier i when entry is AtchEntry e => Atch.ApplyMod(mod, i, e), GlobalEqpManipulation i => GlobalEqp.ApplyMod(mod, i), _ => false, }; diff --git a/Penumbra/Interop/Hooks/DebugHook.cs b/Penumbra/Interop/Hooks/DebugHook.cs index db14805c..fe9754f9 100644 --- a/Penumbra/Interop/Hooks/DebugHook.cs +++ b/Penumbra/Interop/Hooks/DebugHook.cs @@ -1,5 +1,6 @@ using Dalamud.Hooking; using OtterGui.Services; +using Penumbra.Interop.Structs; namespace Penumbra.Interop.Hooks; @@ -31,12 +32,13 @@ public sealed unsafe class DebugHook : IHookService public bool Finished => _task?.IsCompletedSuccessfully ?? true; - private delegate void Delegate(nint a, int b, nint c, float* d); + private delegate nint Delegate(ResourceHandle* a, int b, int c); - private void Detour(nint a, int b, nint c, float* d) + private nint Detour(ResourceHandle* a, int b, int c) { - _task!.Result.Original(a, b, c, d); - Penumbra.Log.Information($"[Debug Hook] Results with 0x{a:X} {b} {c:X} {d[0]} {d[1]} {d[2]} {d[3]}."); + var ret = _task!.Result.Original(a, b, c); + Penumbra.Log.Information($"[Debug Hook] Results with 0x{(nint)a:X}, {b}, {c} -> 0x{ret:X}."); + return ret; } } #endif diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 3deeb107..63d93c9d 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -62,6 +62,8 @@ public class HookOverrides public bool SetupVisor; public bool UpdateModel; public bool UpdateRender; + public bool AtchCaller1; + public bool AtchCaller2; } public struct ObjectHooks diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs new file mode 100644 index 00000000..748ca93a --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs @@ -0,0 +1,39 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class AtchCallerHook1 : FastHook, IDisposable +{ + public delegate void Delegate(DrawObjectData* data, uint slot, nint unk, Model playerModel); + + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public AtchCallerHook1(HookManager hooks, MetaState metaState, CollectionResolver collectionResolver) + { + _metaState = metaState; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("AtchCaller1", Sigs.AtchCaller1, Detour, + metaState.Config.EnableMods && HookOverrides.Instance.Meta.AtchCaller1); + if (!HookOverrides.Instance.Meta.AtchCaller1) + _metaState.Config.ModsEnabled += Toggle; + } + + private void Detour(DrawObjectData* data, uint slot, nint unk, Model playerModel) + { + var collection = _collectionResolver.IdentifyCollection(playerModel.AsDrawObject, true); + _metaState.AtchCollection.Push(collection); + Task.Result.Original(data, slot, unk, playerModel); + _metaState.AtchCollection.Pop(); + Penumbra.Log.Excessive( + $"[AtchCaller1] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, identified to {collection.ModCollection.AnonymizedName}."); + } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; +} diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs new file mode 100644 index 00000000..9b3349f2 --- /dev/null +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs @@ -0,0 +1,38 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Interop.Hooks.Meta; + +public unsafe class AtchCallerHook2 : FastHook, IDisposable +{ + public delegate void Delegate(DrawObjectData* data, uint slot, nint unk, Model playerModel, uint unk2); + + private readonly CollectionResolver _collectionResolver; + private readonly MetaState _metaState; + + public AtchCallerHook2(HookManager hooks, MetaState metaState, CollectionResolver collectionResolver) + { + _metaState = metaState; + _collectionResolver = collectionResolver; + Task = hooks.CreateHook("AtchCaller2", Sigs.AtchCaller2, Detour, + metaState.Config.EnableMods && HookOverrides.Instance.Meta.AtchCaller2); + if (!HookOverrides.Instance.Meta.AtchCaller2) + _metaState.Config.ModsEnabled += Toggle; + } + + private void Detour(DrawObjectData* data, uint slot, nint unk, Model playerModel, uint unk2) + { + var collection = _collectionResolver.IdentifyCollection(playerModel.AsDrawObject, true); + _metaState.AtchCollection.Push(collection); + Task.Result.Original(data, slot, unk, playerModel, unk2); + _metaState.AtchCollection.Pop(); + Penumbra.Log.Excessive( + $"[AtchCaller2] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, {unk2}, identified to {collection.ModCollection.AnonymizedName}."); + } + + public void Dispose() + => _metaState.Config.ModsEnabled -= Toggle; +} diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index e709c210..e7fc3176 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -49,6 +49,7 @@ public sealed unsafe class MetaState : IDisposable, IService public readonly Stack EqdpCollection = []; public readonly Stack EstCollection = []; public readonly Stack RspCollection = []; + public readonly Stack AtchCollection = []; public readonly Stack<(ResolveData Collection, PrimaryId Id)> GmpCollection = []; diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index a7af42e3..0b6c8340 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,3 +1,4 @@ +using System.Linq; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui.Services; using Penumbra.Api.Enums; @@ -54,7 +55,7 @@ public class PathResolver : IDisposable, IService // Prevent .atch loading to prevent crashes on outdated .atch files. TODO: handle atch modding differently. if (resourceType is ResourceType.Atch) - return (null, ResolveData.Invalid); + return ResolveAtch(path); return category switch { @@ -142,4 +143,10 @@ public class PathResolver : IDisposable, IService private (FullPath?, ResolveData) ResolveUi(Utf8GamePath path) => (_collectionManager.Active.Interface.ResolvePath(path), _collectionManager.Active.Interface.ToResolveData()); + + public (FullPath?, ResolveData) ResolveAtch(Utf8GamePath gamePath) + { + _metaState.AtchCollection.TryPeek(out var resolveData); + return _preprocessor.PreProcess(resolveData, gamePath.Path, false, ResourceType.Atch, null, gamePath); + } } diff --git a/Penumbra/Interop/Processing/AtchFilePostProcessor.cs b/Penumbra/Interop/Processing/AtchFilePostProcessor.cs new file mode 100644 index 00000000..e4fab022 --- /dev/null +++ b/Penumbra/Interop/Processing/AtchFilePostProcessor.cs @@ -0,0 +1,43 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Enums; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Structs; +using Penumbra.Meta.Files; +using Penumbra.String; + +namespace Penumbra.Interop.Processing; + +public sealed class AtchFilePostProcessor(CollectionStorage collections, XivFileAllocator allocator) + : IFilePostProcessor +{ + private readonly IFileAllocator _allocator = allocator; + + public ResourceType Type + => ResourceType.Atch; + + public unsafe void PostProcess(ResourceHandle* resource, CiByteString originalGamePath, ReadOnlySpan additionalData) + { + if (!PathDataHandler.Read(additionalData, out var data) || data.Discriminator != PathDataHandler.Discriminator) + return; + + var collection = collections.ByLocalId(data.Collection); + if (collection.MetaCache is not { } cache) + return; + + if (!AtchPathPreProcessor.TryGetAtchGenderRace(originalGamePath, out var gr)) + return; + + if (!collection.MetaCache.Atch.GetFile(gr, out var file)) + return; + + using var bytes = file.Write(); + var length = (int)bytes.Position; + var alloc = _allocator.Allocate(length, 1); + bytes.GetBuffer().AsSpan(0, length).CopyTo(new Span(alloc, length)); + var (oldData, oldLength) = resource->GetData(); + _allocator.Release((void*)oldData, oldLength); + resource->SetData((nint)alloc, length); + Penumbra.Log.Information($"Post-Processed {originalGamePath} on resource 0x{(nint)resource:X} with {collection} for {gr.ToName()}."); + } +} diff --git a/Penumbra/Interop/Processing/AtchPathPreProcessor.cs b/Penumbra/Interop/Processing/AtchPathPreProcessor.cs new file mode 100644 index 00000000..9a9096f3 --- /dev/null +++ b/Penumbra/Interop/Processing/AtchPathPreProcessor.cs @@ -0,0 +1,44 @@ +using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.GameData.Enums; +using Penumbra.Interop.PathResolving; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Processing; + +public sealed class AtchPathPreProcessor : IPathPreProcessor +{ + public ResourceType Type + => ResourceType.Atch; + + public FullPath? PreProcess(ResolveData resolveData, CiByteString path, Utf8GamePath _, bool nonDefault, FullPath? resolved) + { + if (!resolveData.Valid) + return resolved; + + if (!TryGetAtchGenderRace(path, out var gr)) + return resolved; + + Penumbra.Log.Information($"Pre-Processed {path} with {resolveData.ModCollection} for {gr.ToName()}."); + if (resolveData.ModCollection.MetaCache?.Atch.GetFile(gr, out var file) == true) + return PathDataHandler.CreateAtch(path, resolveData.ModCollection); + + return resolved; + } + + public static bool TryGetAtchGenderRace(CiByteString originalGamePath, out GenderRace genderRace) + { + if (originalGamePath[^6] != '1' + || originalGamePath[^7] != '0' + || !ushort.TryParse(originalGamePath.Span[^9..^7], out var grInt) + || grInt > 18) + { + genderRace = GenderRace.Unknown; + return false; + } + + genderRace = (GenderRace)(grInt * 100 + 1); + return true; + } +} diff --git a/Penumbra/Interop/Processing/GamePathPreProcessService.cs b/Penumbra/Interop/Processing/GamePathPreProcessService.cs index 65608ba0..875eb254 100644 --- a/Penumbra/Interop/Processing/GamePathPreProcessService.cs +++ b/Penumbra/Interop/Processing/GamePathPreProcessService.cs @@ -25,8 +25,7 @@ public class GamePathPreProcessService : IService public (FullPath? Path, ResolveData Data) PreProcess(ResolveData resolveData, CiByteString path, bool nonDefault, ResourceType type, - FullPath? resolved, - Utf8GamePath originalPath) + FullPath? resolved, Utf8GamePath originalPath) { if (!_processors.TryGetValue(type, out var processor)) return (resolved, resolveData); diff --git a/Penumbra/Meta/AtchManager.cs b/Penumbra/Meta/AtchManager.cs new file mode 100644 index 00000000..68f2f815 --- /dev/null +++ b/Penumbra/Meta/AtchManager.cs @@ -0,0 +1,26 @@ +using System.Collections.Frozen; +using Dalamud.Plugin.Services; +using OtterGui.Services; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Files; + +namespace Penumbra.Interop.Hooks.Meta; + +public sealed unsafe class AtchManager : IService +{ + private static readonly IReadOnlyList GenderRaces = + [ + GenderRace.MidlanderMale, GenderRace.MidlanderFemale, GenderRace.HighlanderMale, GenderRace.HighlanderFemale, GenderRace.ElezenMale, + GenderRace.ElezenFemale, GenderRace.MiqoteMale, GenderRace.MiqoteFemale, GenderRace.RoegadynMale, GenderRace.RoegadynFemale, + GenderRace.LalafellMale, GenderRace.LalafellFemale, GenderRace.AuRaMale, GenderRace.AuRaFemale, GenderRace.HrothgarMale, + GenderRace.HrothgarFemale, GenderRace.VieraMale, GenderRace.VieraFemale, + ]; + + public readonly IReadOnlyDictionary AtchFileBase; + + public AtchManager(IDataManager manager) + { + AtchFileBase = GenderRaces.ToFrozenDictionary(gr => gr, + gr => new AtchFile(manager.GetFile($"chara/xls/attachOffset/c{gr.ToRaceCode()}.atch")!.DataSpan)); + } +} diff --git a/Penumbra/Meta/Manipulations/AtchIdentifier.cs b/Penumbra/Meta/Manipulations/AtchIdentifier.cs new file mode 100644 index 00000000..bce37620 --- /dev/null +++ b/Penumbra/Meta/Manipulations/AtchIdentifier.cs @@ -0,0 +1,77 @@ +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Files.AtchStructs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct AtchIdentifier(AtchType Type, GenderRace GenderRace, ushort EntryIndex) + : IComparable, IMetaIdentifier +{ + public Gender Gender + => GenderRace.Split().Item1; + + public ModelRace Race + => GenderRace.Split().Item2; + + public int CompareTo(AtchIdentifier other) + { + var typeComparison = Type.CompareTo(other.Type); + if (typeComparison != 0) + return typeComparison; + + var genderRaceComparison = GenderRace.CompareTo(other.GenderRace); + if (genderRaceComparison != 0) + return genderRaceComparison; + + return EntryIndex.CompareTo(other.EntryIndex); + } + + public override string ToString() + => $"Atch - {Type.ToAbbreviation()} - {GenderRace.ToName()} - {EntryIndex}"; + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + // Nothing specific + } + + public MetaIndex FileIndex() + => (MetaIndex)(-1); + + public bool Validate() + { + var race = (int)GenderRace / 100; + var remainder = (int)GenderRace - 100 * race; + if (remainder != 1) + return false; + + return race is >= 0 and <= 18; + } + + public JObject AddToJson(JObject jObj) + { + var (gender, race) = GenderRace.Split(); + jObj["Gender"] = gender.ToString(); + jObj["Race"] = race.ToString(); + jObj["Type"] = Type.ToAbbreviation(); + jObj["Index"] = EntryIndex; + return jObj; + } + + public static AtchIdentifier? FromJson(JObject jObj) + { + var gender = jObj["Gender"]?.ToObject() ?? Gender.Unknown; + var race = jObj["Race"]?.ToObject() ?? ModelRace.Unknown; + var type = AtchExtensions.FromString(jObj["Type"]?.ToObject() ?? string.Empty); + var entryIndex = jObj["Index"]?.ToObject() ?? ushort.MaxValue; + if (entryIndex == ushort.MaxValue || type is AtchType.Unknown) + return null; + + var ret = new AtchIdentifier(type, Names.CombinedRace(gender, race), entryIndex); + return ret.Validate() ? ret : null; + } + + MetaManipulationType IMetaIdentifier.Type + => MetaManipulationType.Atch; +} diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs index d1668a4d..999fd906 100644 --- a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -14,6 +14,7 @@ public enum MetaManipulationType : byte Gmp = 5, Rsp = 6, GlobalEqp = 7, + Atch = 8, } public interface IMetaIdentifier diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index da061bec..ca45c777 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -1,6 +1,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Collections.Cache; +using Penumbra.GameData.Files.AtchStructs; using Penumbra.GameData.Structs; using Penumbra.Util; using ImcEntry = Penumbra.GameData.Structs.ImcEntry; @@ -16,6 +17,7 @@ public class MetaDictionary private readonly Dictionary _est = []; private readonly Dictionary _rsp = []; private readonly Dictionary _gmp = []; + private readonly Dictionary _atch = []; private readonly HashSet _globalEqp = []; public IReadOnlyDictionary Imc @@ -36,6 +38,9 @@ public class MetaDictionary public IReadOnlyDictionary Rsp => _rsp; + public IReadOnlyDictionary Atch + => _atch; + public IReadOnlySet GlobalEqp => _globalEqp; @@ -50,6 +55,7 @@ public class MetaDictionary MetaManipulationType.Est => _est.Count, MetaManipulationType.Gmp => _gmp.Count, MetaManipulationType.Rsp => _rsp.Count, + MetaManipulationType.Atch => _atch.Count, MetaManipulationType.GlobalEqp => _globalEqp.Count, _ => 0, }; @@ -63,6 +69,7 @@ public class MetaDictionary GlobalEqpManipulation i => _globalEqp.Contains(i), GmpIdentifier i => _gmp.ContainsKey(i), ImcIdentifier i => _imc.ContainsKey(i), + AtchIdentifier i => _atch.ContainsKey(i), RspIdentifier i => _rsp.ContainsKey(i), _ => false, }; @@ -76,6 +83,7 @@ public class MetaDictionary _est.Clear(); _rsp.Clear(); _gmp.Clear(); + _atch.Clear(); _globalEqp.Clear(); } @@ -88,6 +96,7 @@ public class MetaDictionary _est.Clear(); _rsp.Clear(); _gmp.Clear(); + _atch.Clear(); } public bool Equals(MetaDictionary other) @@ -98,6 +107,7 @@ public class MetaDictionary && _est.SetEquals(other._est) && _rsp.SetEquals(other._rsp) && _gmp.SetEquals(other._gmp) + && _atch.SetEquals(other._atch) && _globalEqp.SetEquals(other._globalEqp); public IEnumerable Identifiers @@ -107,6 +117,7 @@ public class MetaDictionary .Concat(_est.Keys.Cast()) .Concat(_gmp.Keys.Cast()) .Concat(_rsp.Keys.Cast()) + .Concat(_atch.Keys.Cast()) .Concat(_globalEqp.Cast()); #region TryAdd @@ -171,6 +182,15 @@ public class MetaDictionary return true; } + public bool TryAdd(AtchIdentifier identifier, in AtchEntry entry) + { + if (!_atch.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + public bool TryAdd(GlobalEqpManipulation identifier) { if (!_globalEqp.Add(identifier)) @@ -244,6 +264,15 @@ public class MetaDictionary return true; } + public bool Update(AtchIdentifier identifier, in AtchEntry entry) + { + if (!_atch.ContainsKey(identifier)) + return false; + + _atch[identifier] = entry; + return true; + } + #endregion #region TryGetValue @@ -266,6 +295,9 @@ public class MetaDictionary public bool TryGetValue(ImcIdentifier identifier, out ImcEntry value) => _imc.TryGetValue(identifier, out value); + public bool TryGetValue(AtchIdentifier identifier, out AtchEntry value) + => _atch.TryGetValue(identifier, out value); + #endregion public bool Remove(IMetaIdentifier identifier) @@ -279,6 +311,7 @@ public class MetaDictionary GmpIdentifier i => _gmp.Remove(i), ImcIdentifier i => _imc.Remove(i), RspIdentifier i => _rsp.Remove(i), + AtchIdentifier i => _atch.Remove(i), _ => false, }; if (ret) @@ -308,6 +341,9 @@ public class MetaDictionary foreach (var (identifier, entry) in manips._est) TryAdd(identifier, entry); + foreach (var (identifier, entry) in manips._atch) + TryAdd(identifier, entry); + foreach (var identifier in manips._globalEqp) TryAdd(identifier); } @@ -351,6 +387,12 @@ public class MetaDictionary return false; } + foreach (var (identifier, _) in manips._atch.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + { + failedIdentifier = identifier; + return false; + } + foreach (var identifier in manips._globalEqp.Where(identifier => !TryAdd(identifier))) { failedIdentifier = identifier; @@ -369,8 +411,9 @@ public class MetaDictionary _est.SetTo(other._est); _rsp.SetTo(other._rsp); _gmp.SetTo(other._gmp); + _atch.SetTo(other._atch); _globalEqp.SetTo(other._globalEqp); - Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _globalEqp.Count; + Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _globalEqp.Count; } public void UpdateTo(MetaDictionary other) @@ -381,8 +424,9 @@ public class MetaDictionary _est.UpdateTo(other._est); _rsp.UpdateTo(other._rsp); _gmp.UpdateTo(other._gmp); + _atch.UpdateTo(other._atch); _globalEqp.UnionWith(other._globalEqp); - Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _globalEqp.Count; + Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _globalEqp.Count; } #endregion @@ -460,6 +504,16 @@ public class MetaDictionary }), }; + public static JObject Serialize(AtchIdentifier identifier, AtchEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Atch.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = entry.ToJson(), + }), + }; + public static JObject Serialize(GlobalEqpManipulation identifier) => new() { @@ -487,6 +541,8 @@ public class MetaDictionary return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); if (typeof(TIdentifier) == typeof(ImcIdentifier) && typeof(TEntry) == typeof(ImcEntry)) return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(AtchIdentifier) && typeof(TEntry) == typeof(AtchEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); if (typeof(TIdentifier) == typeof(GlobalEqpManipulation)) return Serialize(Unsafe.As(ref identifier)); @@ -531,6 +587,7 @@ public class MetaDictionary SerializeTo(array, value._est); SerializeTo(array, value._rsp); SerializeTo(array, value._gmp); + SerializeTo(array, value._atch); SerializeTo(array, value._globalEqp); array.WriteTo(writer); } @@ -618,6 +675,16 @@ public class MetaDictionary Penumbra.Log.Warning("Invalid RSP Manipulation encountered."); break; } + case MetaManipulationType.Atch: + { + var identifier = AtchIdentifier.FromJson(manip); + var entry = AtchEntry.FromJson(manip["Entry"] as JObject); + if (identifier.HasValue && entry.HasValue) + dict.TryAdd(identifier.Value, entry.Value); + else + Penumbra.Log.Warning("Invalid ATCH Manipulation encountered."); + break; + } case MetaManipulationType.GlobalEqp: { var identifier = GlobalEqpManipulation.FromJson(manip); @@ -648,6 +715,7 @@ public class MetaDictionary _est = cache.Est.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); _gmp = cache.Gmp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); _rsp = cache.Rsp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + _atch = cache.Atch.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); _globalEqp = cache.GlobalEqp.Select(kvp => kvp.Key).ToHashSet(); Count = cache.Count; } diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 3755afa2..5250273b 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -5,6 +5,7 @@ using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Data; using Penumbra.Import; +using Penumbra.Interop.Hooks.Meta; using Penumbra.Interop.Services; using Penumbra.Meta.Files; using Penumbra.Mods; @@ -25,13 +26,14 @@ public class MetaFileManager : IService internal readonly ObjectIdentification Identifier; internal readonly FileCompactor Compactor; internal readonly ImcChecker ImcChecker; + internal readonly AtchManager AtchManager; internal readonly IFileAllocator MarshalAllocator = new MarshalAllocator(); internal readonly IFileAllocator XivAllocator; public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, ObjectIdentification identifier, - FileCompactor compactor, IGameInteropProvider interop) + FileCompactor compactor, IGameInteropProvider interop, AtchManager atchManager) { CharacterUtility = characterUtility; ResidentResources = residentResources; @@ -41,6 +43,7 @@ public class MetaFileManager : IService ValidityChecker = validityChecker; Identifier = identifier; Compactor = compactor; + AtchManager = atchManager; ImcChecker = new ImcChecker(this); XivAllocator = new XivFileAllocator(interop); interop.InitializeFromAttributes(this); diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 217ba93d..7a5142dc 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -58,6 +58,7 @@ public class ModMetaEditor( OtherData[MetaManipulationType.Gmp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Gmp)); OtherData[MetaManipulationType.Est].Add(name, option.Manipulations.GetCount(MetaManipulationType.Est)); OtherData[MetaManipulationType.Rsp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Rsp)); + OtherData[MetaManipulationType.Atch].Add(name, option.Manipulations.GetCount(MetaManipulationType.Atch)); OtherData[MetaManipulationType.GlobalEqp].Add(name, option.Manipulations.GetCount(MetaManipulationType.GlobalEqp)); } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 917dba6c..534911df 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -21,6 +21,7 @@ using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManage using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; using Penumbra.GameData.Data; +using Penumbra.GameData.Files; using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.ResourceLoading; diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs new file mode 100644 index 00000000..4cf01faa --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs @@ -0,0 +1,245 @@ +using Dalamud.Interface; +using ImGuiNET; +using Newtonsoft.Json.Linq; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using OtterGui.Widgets; +using Penumbra.Collections.Cache; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.AtchStructs; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class AtchMetaDrawer : MetaDrawer, IService +{ + public override ReadOnlySpan Label + => "Attachment Points (ATCH)###ATCH"u8; + + public override int NumColumns + => 10; + + public override float ColumnHeight + => 2 * ImUtf8.FrameHeightSpacing; + + private AtchFile? _currentBaseAtchFile; + private AtchPoint? _currentBaseAtchPoint; + private AtchPointCombo _combo; + + public AtchMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : base(editor, metaFiles) + { + _combo = new AtchPointCombo(() => _currentBaseAtchFile?.Points.Select(p => p.Type).ToList() ?? []); + } + + private sealed class AtchPointCombo(Func> generator) + : FilterComboCache(generator, MouseWheelType.Control, Penumbra.Log) + { + protected override string ToString(AtchType obj) + => obj.ToName(); + } + + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current ATCH manipulations to clipboard."u8, + new Lazy(() => MetaDictionary.SerializeTo([], Editor.Atch))); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier); + var tt = canAdd ? "Stage this edit."u8 : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, Entry); + + if (DrawIdentifierInput(ref Identifier)) + UpdateEntry(); + + var defaultEntry = AtchCache.GetDefault(MetaFiles, Identifier) ?? default; + DrawEntry(defaultEntry, ref defaultEntry, true); + } + + private void UpdateEntry() + => Entry = _currentBaseAtchPoint!.Entries[Identifier.EntryIndex]; + + protected override void Initialize() + { + _currentBaseAtchFile = MetaFiles.AtchManager.AtchFileBase[GenderRace.MidlanderMale]; + _currentBaseAtchPoint = _currentBaseAtchFile.Points.First(); + Identifier = new AtchIdentifier(_currentBaseAtchPoint.Type, GenderRace.MidlanderMale, 0); + Entry = _currentBaseAtchPoint.Entries[0]; + } + + protected override void DrawEntry(AtchIdentifier identifier, AtchEntry entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + var defaultEntry = AtchCache.GetDefault(MetaFiles, identifier) ?? default; + if (DrawEntry(defaultEntry, ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(AtchIdentifier, AtchEntry)> Enumerate() + => Editor.Atch.Select(kvp => (kvp.Key, kvp.Value)) + .OrderBy(p => p.Key.GenderRace) + .ThenBy(p => p.Key.Type) + .ThenBy(p => p.Key.EntryIndex); + + protected override int Count + => Editor.Atch.Count; + + private bool DrawIdentifierInput(ref AtchIdentifier identifier) + { + var changes = false; + ImGui.TableNextColumn(); + changes |= DrawRace(ref identifier); + ImGui.TableNextColumn(); + changes |= DrawGender(ref identifier, false); + if (changes) + UpdateFile(); + ImGui.TableNextColumn(); + if (DrawPointInput(ref identifier, _combo)) + { + _currentBaseAtchPoint = _currentBaseAtchFile?.GetPoint(identifier.Type); + changes = true; + } + + ImGui.TableNextColumn(); + changes |= DrawEntryIndexInput(ref identifier, _currentBaseAtchPoint!); + + return changes; + } + + private void UpdateFile() + { + _currentBaseAtchFile = MetaFiles.AtchManager.AtchFileBase[Identifier.GenderRace]; + _currentBaseAtchPoint = _currentBaseAtchFile.GetPoint(Identifier.Type); + if (_currentBaseAtchPoint == null) + { + _currentBaseAtchPoint = _currentBaseAtchFile.Points.First(); + Identifier = Identifier with { Type = _currentBaseAtchPoint.Type }; + } + + if (Identifier.EntryIndex >= _currentBaseAtchPoint.Entries.Length) + Identifier = Identifier with { EntryIndex = 0 }; + } + + private static void DrawIdentifier(AtchIdentifier identifier) + { + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Race.ToName(), FrameColor); + ImUtf8.HoverTooltip("Model Race"u8); + + ImGui.TableNextColumn(); + DrawGender(ref identifier, true); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Type.ToName(), FrameColor); + ImUtf8.HoverTooltip("Attachment Point Type"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.EntryIndex.ToString(), FrameColor); + ImUtf8.HoverTooltip("State Entry Index"u8); + } + + private static bool DrawEntry(in AtchEntry defaultEntry, ref AtchEntry entry, bool disabled) + { + var changes = false; + using var dis = ImRaii.Disabled(disabled); + if (defaultEntry.Bone.Length == 0) + return false; + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(200 * ImUtf8.GlobalScale); + if (ImUtf8.InputText("##BoneName"u8, entry.FullSpan, out TerminatedByteString newBone)) + { + entry.SetBoneName(newBone); + changes = true; + } + + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Bone Name"u8); + + ImGui.SetNextItemWidth(200 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchScale"u8, ref entry.Scale); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Scale"u8); + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(120 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchOffsetX"u8, ref entry.OffsetX); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Offset X-Coordinate"u8); + ImGui.SetNextItemWidth(120 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchRotationX"u8, ref entry.RotationX); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Rotation X-Axis"u8); + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(120 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchOffsetY"u8, ref entry.OffsetY); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Offset Y-Coordinate"u8); + ImGui.SetNextItemWidth(120 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchRotationY"u8, ref entry.RotationY); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Rotation Y-Axis"u8); + + ImGui.TableNextColumn(); + ImGui.SetNextItemWidth(120 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchOffsetZ"u8, ref entry.OffsetZ); + ImUtf8.HoverTooltip("Offset Z-Coordinate"u8); + ImGui.SetNextItemWidth(120 * ImUtf8.GlobalScale); + changes |= ImUtf8.InputScalar("##AtchRotationZ"u8, ref entry.RotationZ); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "Rotation Z-Axis"u8); + + return changes; + } + + private static bool DrawRace(ref AtchIdentifier identifier, float unscaledWidth = 100) + { + var ret = Combos.Race("##atchRace", identifier.Race, out var race, unscaledWidth); + ImUtf8.HoverTooltip("Model Race"u8); + if (ret) + identifier = identifier with { GenderRace = Names.CombinedRace(identifier.Gender, race) }; + + return ret; + } + + private static bool DrawGender(ref AtchIdentifier identifier, bool disabled) + { + var isMale = identifier.Gender is Gender.Male; + + if (!ImUtf8.IconButton(isMale ? FontAwesomeIcon.Mars : FontAwesomeIcon.Venus, "Gender"u8, buttonColor: disabled ? 0x000F0000u : 0) + || disabled) + return false; + + identifier = identifier with { GenderRace = Names.CombinedRace(isMale ? Gender.Female : Gender.Male, identifier.Race) }; + return true; + } + + private static bool DrawPointInput(ref AtchIdentifier identifier, AtchPointCombo combo) + { + if (!combo.Draw("##AtchPoint", identifier.Type.ToName(), "Attachment Point Type", 160 * ImUtf8.GlobalScale, + ImGui.GetTextLineHeightWithSpacing())) + return false; + + identifier = identifier with { Type = combo.CurrentSelection }; + return true; + } + + private static bool DrawEntryIndexInput(ref AtchIdentifier identifier, AtchPoint currentAtchPoint) + { + var index = identifier.EntryIndex; + ImGui.SetNextItemWidth(40 * ImUtf8.GlobalScale); + var ret = ImUtf8.DragScalar("##AtchEntry"u8, ref index, 0, (ushort)(currentAtchPoint.Entries.Length - 1), 0.05f, + ImGuiSliderFlags.AlwaysClamp); + ImUtf8.HoverTooltip("State Entry Index"u8); + if (!ret) + return false; + + index = Math.Clamp(index, (ushort)0, (ushort)(currentAtchPoint!.Entries.Length - 1)); + identifier = identifier with { EntryIndex = index }; + return true; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index f9baddbe..348a0d4c 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; using Penumbra.GameData.Enums; @@ -34,7 +35,7 @@ public sealed class EqdpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFil protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current EQDP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Eqdp)); + CopyToClipboardButton("Copy all current EQDP manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.Eqdp))); ImGui.TableNextColumn(); var validRaceCode = CharacterUtilityData.EqdpIdx(Identifier.GenderRace, false) >= 0; diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs index 51b14459..d6df95cb 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs @@ -1,5 +1,6 @@ using Dalamud.Interface; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; @@ -34,7 +35,7 @@ public sealed class EqpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current EQP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Eqp)); + CopyToClipboardButton("Copy all current EQP manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.Eqp))); ImGui.TableNextColumn(); var canAdd = !Editor.Contains(Identifier); diff --git a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs index 09075319..e5e28a3d 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; using Penumbra.GameData.Enums; @@ -33,7 +34,7 @@ public sealed class EstMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current EST manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Est)); + CopyToClipboardButton("Copy all current EST manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.Est))); ImGui.TableNextColumn(); var canAdd = !Editor.Contains(Identifier); diff --git a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs index 1aa9060e..929feadd 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs @@ -1,5 +1,6 @@ using Dalamud.Interface; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; using Penumbra.Meta; @@ -29,7 +30,7 @@ public sealed class GlobalEqpMetaDrawer(ModMetaEditor editor, MetaFileManager me protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current global EQP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.GlobalEqp)); + CopyToClipboardButton("Copy all current global EQP manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.GlobalEqp))); ImGui.TableNextColumn(); var canAdd = !Editor.Contains(Identifier); diff --git a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs index 9532d8e7..3691a4f7 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs @@ -8,6 +8,7 @@ using Penumbra.Meta.Files; using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; +using Newtonsoft.Json.Linq; namespace Penumbra.UI.AdvancedWindow.Meta; @@ -32,7 +33,7 @@ public sealed class GmpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current Gmp manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Gmp)); + CopyToClipboardButton("Copy all current Gmp manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.Gmp))); ImGui.TableNextColumn(); var canAdd = !Editor.Contains(Identifier); diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index c8310cf7..34488a87 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -1,5 +1,6 @@ using Dalamud.Interface; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; @@ -35,7 +36,7 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current IMC manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Imc)); + CopyToClipboardButton("Copy all current IMC manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.Imc))); ImGui.TableNextColumn(); var canAdd = _fileExists && !Editor.Contains(Identifier); var tt = canAdd ? "Stage this edit."u8 : !_fileExists ? "This IMC file does not exist."u8 : "This entry is already edited."u8; @@ -116,7 +117,6 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ImUtf8.TextFramed(identifier.EquipSlot.ToName(), FrameColor); ImUtf8.HoverTooltip("Equip Slot"u8); } - } private static bool DrawEntry(ImcEntry defaultEntry, ref ImcEntry entry, bool addDefault) @@ -161,8 +161,9 @@ public sealed class ImcMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile { var (equipSlot, secondaryId) = type switch { - ObjectType.Equipment => (identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, (SecondaryId) 0), - ObjectType.DemiHuman => (identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId), + ObjectType.Equipment => (identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, (SecondaryId)0), + ObjectType.DemiHuman => (identifier.EquipSlot.IsEquipment() ? identifier.EquipSlot : EquipSlot.Head, + identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId), ObjectType.Accessory => (identifier.EquipSlot.IsAccessory() ? identifier.EquipSlot : EquipSlot.Ears, (SecondaryId)0), _ => (EquipSlot.Unknown, identifier.SecondaryId == 0 ? 1 : identifier.SecondaryId), }; diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs index 75de20a7..4c9142d8 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -14,8 +14,9 @@ namespace Penumbra.UI.AdvancedWindow.Meta; public interface IMetaDrawer { - public ReadOnlySpan Label { get; } - public int NumColumns { get; } + public ReadOnlySpan Label { get; } + public int NumColumns { get; } + public float ColumnHeight { get; } public void Draw(); } @@ -42,7 +43,7 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta using var id = ImUtf8.PushId((int)Identifier.Type); DrawNew(); - var height = ImUtf8.FrameHeightSpacing; + var height = ColumnHeight; var skips = ImGuiClip.GetNecessarySkipsAtPos(height, ImGui.GetCursorPosY()); var remainder = ImGuiClip.ClippedTableDraw(Enumerate(), skips, DrawLine, Count); ImGuiClip.DrawEndDummy(remainder, height); @@ -54,6 +55,9 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta public abstract ReadOnlySpan Label { get; } public abstract int NumColumns { get; } + public virtual float ColumnHeight + => ImUtf8.FrameHeightSpacing; + protected abstract void DrawNew(); protected abstract void Initialize(); protected abstract void DrawEntry(TIdentifier identifier, TEntry entry); @@ -138,14 +142,14 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta protected void DrawMetaButtons(TIdentifier identifier, TEntry entry) { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy this manipulation to clipboard."u8, new JArray { MetaDictionary.Serialize(identifier, entry)! }); + CopyToClipboardButton("Copy this manipulation to clipboard."u8, new Lazy(() => new JArray { MetaDictionary.Serialize(identifier, entry)! })); ImGui.TableNextColumn(); if (ImUtf8.IconButton(FontAwesomeIcon.Trash, "Delete this meta manipulation."u8)) Editor.Changes |= Editor.Remove(identifier); } - protected void CopyToClipboardButton(ReadOnlySpan tooltip, JToken? manipulations) + protected void CopyToClipboardButton(ReadOnlySpan tooltip, Lazy manipulations) { if (!ImUtf8.IconButton(FontAwesomeIcon.Clipboard, tooltip)) return; diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs index b3dd9299..d1c7cd52 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs @@ -10,7 +10,8 @@ public class MetaDrawers( GlobalEqpMetaDrawer globalEqp, GmpMetaDrawer gmp, ImcMetaDrawer imc, - RspMetaDrawer rsp) : IService + RspMetaDrawer rsp, + AtchMetaDrawer atch) : IService { public readonly EqdpMetaDrawer Eqdp = eqdp; public readonly EqpMetaDrawer Eqp = eqp; @@ -19,6 +20,7 @@ public class MetaDrawers( public readonly RspMetaDrawer Rsp = rsp; public readonly ImcMetaDrawer Imc = imc; public readonly GlobalEqpMetaDrawer GlobalEqp = globalEqp; + public readonly AtchMetaDrawer Atch = atch; public IMetaDrawer? Get(MetaManipulationType type) => type switch @@ -29,7 +31,8 @@ public class MetaDrawers( MetaManipulationType.Est => Est, MetaManipulationType.Gmp => Gmp, MetaManipulationType.Rsp => Rsp, + MetaManipulationType.Atch => Atch, MetaManipulationType.GlobalEqp => GlobalEqp, - _ => null, + _ => null, }; } diff --git a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs index 87e8c5b8..d60f877b 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; using ImGuiNET; +using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; using Penumbra.GameData.Enums; @@ -33,7 +34,7 @@ public sealed class RspMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override void DrawNew() { ImGui.TableNextColumn(); - CopyToClipboardButton("Copy all current RSP manipulations to clipboard."u8, MetaDictionary.SerializeTo([], Editor.Rsp)); + CopyToClipboardButton("Copy all current RSP manipulations to clipboard."u8, new Lazy(() => MetaDictionary.SerializeTo([], Editor.Rsp))); ImGui.TableNextColumn(); var canAdd = !Editor.Contains(Identifier); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 49eac96e..22271d38 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -56,6 +56,7 @@ public partial class ModEditWindow DrawEditHeader(MetaManipulationType.Est); DrawEditHeader(MetaManipulationType.Gmp); DrawEditHeader(MetaManipulationType.Rsp); + DrawEditHeader(MetaManipulationType.Atch); DrawEditHeader(MetaManipulationType.GlobalEqp); } From 10279fdc187d23c64ee158d89e3903137b085a00 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 26 Nov 2024 17:04:38 +0100 Subject: [PATCH 0987/1381] fix inverted hook logic. --- Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs | 5 ++--- Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs index 748ca93a..07e34a66 100644 --- a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs @@ -1,4 +1,3 @@ -using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Game.Character; using OtterGui.Services; using Penumbra.GameData; @@ -19,7 +18,7 @@ public unsafe class AtchCallerHook1 : FastHook, IDispo _metaState = metaState; _collectionResolver = collectionResolver; Task = hooks.CreateHook("AtchCaller1", Sigs.AtchCaller1, Detour, - metaState.Config.EnableMods && HookOverrides.Instance.Meta.AtchCaller1); + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.AtchCaller1); if (!HookOverrides.Instance.Meta.AtchCaller1) _metaState.Config.ModsEnabled += Toggle; } @@ -30,7 +29,7 @@ public unsafe class AtchCallerHook1 : FastHook, IDispo _metaState.AtchCollection.Push(collection); Task.Result.Original(data, slot, unk, playerModel); _metaState.AtchCollection.Pop(); - Penumbra.Log.Excessive( + Penumbra.Log.Information( $"[AtchCaller1] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, identified to {collection.ModCollection.AnonymizedName}."); } diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs index 9b3349f2..aa2d3f31 100644 --- a/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs @@ -18,7 +18,7 @@ public unsafe class AtchCallerHook2 : FastHook, IDispo _metaState = metaState; _collectionResolver = collectionResolver; Task = hooks.CreateHook("AtchCaller2", Sigs.AtchCaller2, Detour, - metaState.Config.EnableMods && HookOverrides.Instance.Meta.AtchCaller2); + metaState.Config.EnableMods && !HookOverrides.Instance.Meta.AtchCaller2); if (!HookOverrides.Instance.Meta.AtchCaller2) _metaState.Config.ModsEnabled += Toggle; } From 28250a9304f77be0dcfcc071f16a626e10785a0a Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 26 Nov 2024 16:11:29 +0000 Subject: [PATCH 0988/1381] [CI] Updating repo.json for testing_1.3.1.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index f5a8e2f1..bfea1e12 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.1.3", - "TestingAssemblyVersion": "1.3.1.3", + "TestingAssemblyVersion": "1.3.1.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.1.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 8242cde15cfd5da17c3819157d3b61900bce92e2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 18:00:42 +0100 Subject: [PATCH 0989/1381] Don't spam logs. --- Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs index 07e34a66..dcbaedc8 100644 --- a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs @@ -29,7 +29,7 @@ public unsafe class AtchCallerHook1 : FastHook, IDispo _metaState.AtchCollection.Push(collection); Task.Result.Original(data, slot, unk, playerModel); _metaState.AtchCollection.Pop(); - Penumbra.Log.Information( + Penumbra.Log.Excessive( $"[AtchCaller1] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, identified to {collection.ModCollection.AnonymizedName}."); } From 0aa8a44b8d878e6f383aeaf927d8237db32023ab Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 18:00:57 +0100 Subject: [PATCH 0990/1381] Fix meta manipulation copy/paste. --- Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs index 4c9142d8..2b9285ef 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -154,7 +154,7 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta if (!ImUtf8.IconButton(FontAwesomeIcon.Clipboard, tooltip)) return; - var text = Functions.ToCompressedBase64(manipulations, MetaApi.CurrentVersion); + var text = Functions.ToCompressedBase64(manipulations.Value, MetaApi.CurrentVersion); if (text.Length > 0) ImGui.SetClipboardText(text); } From ac2631384f09c5bb927588f0133620e0dfd0a503 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 18:01:10 +0100 Subject: [PATCH 0991/1381] Fix mod reload of atch manipulations. --- Penumbra/Mods/Editor/ModMetaEditor.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 7a5142dc..876fe12f 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,5 +1,6 @@ using System.Collections.Frozen; using OtterGui.Services; +using Penumbra.Collections.Cache; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -157,6 +158,23 @@ public class ModMetaEditor( } } + foreach (var (key, value) in clone.Atch) + { + var defaultEntry = AtchCache.GetDefault(metaFileManager, key); + if (!defaultEntry.HasValue) + continue; + + if (!defaultEntry.Value.Equals(value)) + { + dict.TryAdd(key, value); + } + else + { + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {key}."); + ++count; + } + } + if (count == 0) return false; From c8ad4bc1062fc9ec7885fcdcabed2e4d15c3efc6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 18:01:42 +0100 Subject: [PATCH 0992/1381] Use meta transfer v1. --- Penumbra/Api/Api/MetaApi.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index 217cb1e3..871fe18b 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -53,7 +53,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver } internal static string CompressMetaManipulations(ModCollection collection) - => CompressMetaManipulationsV0(collection); + => CompressMetaManipulationsV1(collection); private static string CompressMetaManipulationsV0(ModCollection collection) { From 242c0ee38fd0265db808e04d33e2c6d44768cf01 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 18:41:16 +0100 Subject: [PATCH 0993/1381] Add testing to IPC Meta. --- Penumbra/Api/Api/MetaApi.cs | 20 ++++++++++--------- Penumbra/Api/Api/TemporaryApi.cs | 4 ++-- Penumbra/Api/IpcTester/MetaIpcTester.cs | 16 ++++++++++++++- Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 2 +- 4 files changed, 29 insertions(+), 13 deletions(-) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index 871fe18b..3f876bbf 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -146,11 +146,12 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver /// The empty string is treated as an empty set. /// Only returns true if all conversions are successful and distinct. /// - internal static bool ConvertManips(string manipString, [NotNullWhen(true)] out MetaDictionary? manips) + internal static bool ConvertManips(string manipString, [NotNullWhen(true)] out MetaDictionary? manips, out byte version) { if (manipString.Length == 0) { - manips = new MetaDictionary(); + manips = new MetaDictionary(); + version = byte.MaxValue; return true; } @@ -163,9 +164,9 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver zipStream.CopyTo(resultStream); resultStream.Flush(); resultStream.Position = 0; - var data = resultStream.GetBuffer().AsSpan(0, (int)resultStream.Length); - var version = data[0]; - data = data[1..]; + var data = resultStream.GetBuffer().AsSpan(0, (int)resultStream.Length); + version = data[0]; + data = data[1..]; switch (version) { case 0: return ConvertManipsV0(data, out manips); @@ -179,7 +180,8 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver catch (Exception ex) { Penumbra.Log.Debug($"Error decompressing manipulations:\n{ex}"); - manips = null; + manips = null; + version = byte.MaxValue; return false; } } @@ -274,7 +276,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver var json = Encoding.UTF8.GetString(data); manips = JsonConvert.DeserializeObject(json); return manips != null; - } + } internal void TestMetaManipulations() { @@ -291,11 +293,11 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver var v1Time = watch.ElapsedMilliseconds; watch.Restart(); - var v1Success = ConvertManips(v1, out var v1Roundtrip); + var v1Success = ConvertManips(v1, out var v1Roundtrip, out _); var v1RoundtripTime = watch.ElapsedMilliseconds; watch.Restart(); - var v0Success = ConvertManips(v0, out var v0Roundtrip); + var v0Success = ConvertManips(v0, out var v0Roundtrip, out _); var v0RoundtripTime = watch.ElapsedMilliseconds; Penumbra.Log.Information($"Version | Count | Time | Length | Success | ReCount | ReTime | Equal"); diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 516b4347..201839e7 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -60,7 +60,7 @@ public class TemporaryApi( if (!ConvertPaths(paths, out var p)) return ApiHelpers.Return(PenumbraApiEc.InvalidGamePath, args); - if (!MetaApi.ConvertManips(manipString, out var m)) + if (!MetaApi.ConvertManips(manipString, out var m, out _)) return ApiHelpers.Return(PenumbraApiEc.InvalidManipulation, args); var ret = tempMods.Register(tag, null, p, m, new ModPriority(priority)) switch @@ -86,7 +86,7 @@ public class TemporaryApi( if (!ConvertPaths(paths, out var p)) return ApiHelpers.Return(PenumbraApiEc.InvalidGamePath, args); - if (!MetaApi.ConvertManips(manipString, out var m)) + if (!MetaApi.ConvertManips(manipString, out var m, out _)) return ApiHelpers.Return(PenumbraApiEc.InvalidManipulation, args); var ret = tempMods.Register(tag, collection, p, m, new ModPriority(priority)) switch diff --git a/Penumbra/Api/IpcTester/MetaIpcTester.cs b/Penumbra/Api/IpcTester/MetaIpcTester.cs index 8b393ade..010e3c5a 100644 --- a/Penumbra/Api/IpcTester/MetaIpcTester.cs +++ b/Penumbra/Api/IpcTester/MetaIpcTester.cs @@ -2,13 +2,19 @@ using Dalamud.Plugin; using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Api.Api; using Penumbra.Api.IpcSubscribers; +using Penumbra.Meta.Manipulations; namespace Penumbra.Api.IpcTester; public class MetaIpcTester(IDalamudPluginInterface pi) : IUiService { - private int _gameObjectIndex; + private int _gameObjectIndex; + private string _metaBase64 = string.Empty; + private MetaDictionary _metaDict = new(); + private byte _parsedVersion = byte.MaxValue; public void Draw() { @@ -17,6 +23,11 @@ public class MetaIpcTester(IDalamudPluginInterface pi) : IUiService return; ImGui.InputInt("##metaIdx", ref _gameObjectIndex, 0, 0); + if (ImUtf8.InputText("##metaText"u8, ref _metaBase64, "Base64 Metadata..."u8)) + if (!MetaApi.ConvertManips(_metaBase64, out _metaDict, out _parsedVersion)) + _metaDict ??= new MetaDictionary(); + + using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); if (!table) return; @@ -34,5 +45,8 @@ public class MetaIpcTester(IDalamudPluginInterface pi) : IUiService var base64 = new GetMetaManipulations(pi).Invoke(_gameObjectIndex); ImGui.SetClipboardText(base64); } + + IpcTester.DrawIntro(string.Empty, "Parsed Data"); + ImUtf8.Text($"Version: {_parsedVersion}, Count: {_metaDict.Count}"); } } diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs index 2b9285ef..a6f042b7 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -154,7 +154,7 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta if (!ImUtf8.IconButton(FontAwesomeIcon.Clipboard, tooltip)) return; - var text = Functions.ToCompressedBase64(manipulations.Value, MetaApi.CurrentVersion); + var text = Functions.ToCompressedBase64(manipulations.Value, 0); if (text.Length > 0) ImGui.SetClipboardText(text); } From 9787e5a85228d28b686a301296a528747ca0a910 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 18:49:04 +0100 Subject: [PATCH 0994/1381] Fix some meta issues. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 22271d38..7d688df9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -111,7 +111,7 @@ public partial class ModEditWindow if (!ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Clipboard.ToIconString(), iconSize, tooltip, false, true)) return; - var text = Functions.ToCompressedBase64(manipulations, MetaApi.CurrentVersion); + var text = Functions.ToCompressedBase64(manipulations, 0); if (text.Length > 0) ImGui.SetClipboardText(text); } @@ -122,8 +122,7 @@ public partial class ModEditWindow { var clipboard = ImGuiUtil.GetClipboardText(); - var version = Functions.FromCompressedBase64(clipboard, out var manips); - if (version == MetaApi.CurrentVersion && manips != null) + if (MetaApi.ConvertManips(clipboard, out var manips, out _)) { _editor.MetaEditor.UpdateTo(manips); _editor.MetaEditor.Changes = true; @@ -139,8 +138,7 @@ public partial class ModEditWindow if (ImGui.Button("Set from Clipboard")) { var clipboard = ImGuiUtil.GetClipboardText(); - var version = Functions.FromCompressedBase64(clipboard, out var manips); - if (version == MetaApi.CurrentVersion && manips != null) + if (MetaApi.ConvertManips(clipboard, out var manips, out _)) { _editor.MetaEditor.SetTo(manips); _editor.MetaEditor.Changes = true; From 97d7ea7759898f721df7b743cb86d154813e71b5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 22:51:14 +0100 Subject: [PATCH 0995/1381] tmp --- Penumbra/Api/Api/MetaApi.cs | 27 ++++++++++--------- Penumbra/Api/IpcTester/MetaIpcTester.cs | 2 +- .../Processing/AtchPathPreProcessor.cs | 2 +- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index 3f876bbf..7c0cd5fc 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -16,8 +16,6 @@ namespace Penumbra.Api.Api; public class MetaApi(IFramework framework, CollectionResolver collectionResolver, ApiHelpers helpers) : IPenumbraApiMeta, IApiService { - public const int CurrentVersion = 1; - public string GetPlayerMetaManipulations() { var collection = collectionResolver.PlayerCollection(); @@ -99,7 +97,6 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver WriteCache(zipStream, cache.Est); WriteCache(zipStream, cache.Rsp); WriteCache(zipStream, cache.Gmp); - WriteCache(zipStream, cache.Atch); cache.GlobalEqp.EnterReadLock(); try @@ -112,6 +109,8 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver { cache.GlobalEqp.ExitReadLock(); } + + WriteCache(zipStream, cache.Atch); } } @@ -251,15 +250,6 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver return false; } - var atchCount = r.ReadInt32(); - for (var i = 0; i < atchCount; ++i) - { - var identifier = r.Read(); - var value = r.Read(); - if (!identifier.Validate() || !manips.TryAdd(identifier, value)) - return false; - } - var globalEqpCount = r.ReadInt32(); for (var i = 0; i < globalEqpCount; ++i) { @@ -268,6 +258,19 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver return false; } + // Atch was added after there were already some V1 around, so check for size here. + if (r.Position < r.Count) + { + var atchCount = r.ReadInt32(); + for (var i = 0; i < atchCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + } + return true; } diff --git a/Penumbra/Api/IpcTester/MetaIpcTester.cs b/Penumbra/Api/IpcTester/MetaIpcTester.cs index 010e3c5a..9cf20cd7 100644 --- a/Penumbra/Api/IpcTester/MetaIpcTester.cs +++ b/Penumbra/Api/IpcTester/MetaIpcTester.cs @@ -24,7 +24,7 @@ public class MetaIpcTester(IDalamudPluginInterface pi) : IUiService ImGui.InputInt("##metaIdx", ref _gameObjectIndex, 0, 0); if (ImUtf8.InputText("##metaText"u8, ref _metaBase64, "Base64 Metadata..."u8)) - if (!MetaApi.ConvertManips(_metaBase64, out _metaDict, out _parsedVersion)) + if (!MetaApi.ConvertManips(_metaBase64, out _metaDict!, out _parsedVersion)) _metaDict ??= new MetaDictionary(); diff --git a/Penumbra/Interop/Processing/AtchPathPreProcessor.cs b/Penumbra/Interop/Processing/AtchPathPreProcessor.cs index 9a9096f3..428826bc 100644 --- a/Penumbra/Interop/Processing/AtchPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/AtchPathPreProcessor.cs @@ -20,7 +20,7 @@ public sealed class AtchPathPreProcessor : IPathPreProcessor if (!TryGetAtchGenderRace(path, out var gr)) return resolved; - Penumbra.Log.Information($"Pre-Processed {path} with {resolveData.ModCollection} for {gr.ToName()}."); + Penumbra.Log.Excessive($"Pre-Processed {path} with {resolveData.ModCollection} for {gr.ToName()}."); if (resolveData.ModCollection.MetaCache?.Atch.GetFile(gr, out var file) == true) return PathDataHandler.CreateAtch(path, resolveData.ModCollection); From 8b9f59426e3dba01e4f16267b05bf804ceca881d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 27 Nov 2024 23:07:08 +0100 Subject: [PATCH 0996/1381] No V1 Meta yet... wait until next version ban or API increase. --- Penumbra/Api/Api/MetaApi.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index 7c0cd5fc..ff88ae4e 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -51,7 +51,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver } internal static string CompressMetaManipulations(ModCollection collection) - => CompressMetaManipulationsV1(collection); + => CompressMetaManipulationsV0(collection); private static string CompressMetaManipulationsV0(ModCollection collection) { From d7095af89b322af9bd81acb80a9bab842fbee90f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 29 Nov 2024 17:33:05 +0100 Subject: [PATCH 0997/1381] Add jumping to mods in OnScreen tab. --- Penumbra/Interop/ResourceTree/ResourceNode.cs | 3 + .../ResourceTree/ResourceTreeFactory.cs | 1 + .../UI/AdvancedWindow/ResourceTreeViewer.cs | 112 +++++++++--------- .../ResourceTreeViewerFactory.cs | 6 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 8 +- 5 files changed, 73 insertions(+), 57 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 6c3e1ebe..088527ca 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -1,4 +1,5 @@ using Penumbra.Api.Enums; +using Penumbra.Mods; using Penumbra.String; using Penumbra.String.Classes; using Penumbra.UI; @@ -16,6 +17,7 @@ public class ResourceNode : ICloneable public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; public string? ModName; + public readonly WeakReference Mod = new(null!); public string? ModRelativePath; public CiByteString AdditionalData; public readonly ulong Length; @@ -60,6 +62,7 @@ public class ResourceNode : ICloneable PossibleGamePaths = other.PossibleGamePaths; FullPath = other.FullPath; ModName = other.ModName; + Mod = other.Mod; ModRelativePath = other.ModRelativePath; AdditionalData = other.AdditionalData; Length = other.Length; diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 9738148f..7e378f41 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -135,6 +135,7 @@ public class ResourceTreeFactory( if (node.FullPath.IsRooted && modManager.TryIdentifyPath(node.FullPath.FullName, out var mod, out var relativePath)) { node.ModName = mod.Name; + node.Mod.SetTarget(mod); node.ModRelativePath = relativePath; } } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 3aff2ac9..7bad64f9 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -3,55 +3,40 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui.Raii; using OtterGui; +using OtterGui.Text; +using Penumbra.Api.Enums; using Penumbra.Interop.ResourceTree; +using Penumbra.Services; using Penumbra.UI.Classes; using Penumbra.String; namespace Penumbra.UI.AdvancedWindow; -public class ResourceTreeViewer +public class ResourceTreeViewer( + Configuration config, + ResourceTreeFactory treeFactory, + ChangedItemDrawer changedItemDrawer, + IncognitoService incognito, + int actionCapacity, + Action onRefresh, + Action drawActions, + CommunicatorService communicator) { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; - private readonly Configuration _config; - private readonly ResourceTreeFactory _treeFactory; - private readonly ChangedItemDrawer _changedItemDrawer; - private readonly IncognitoService _incognito; - private readonly int _actionCapacity; - private readonly Action _onRefresh; - private readonly Action _drawActions; - private readonly HashSet _unfolded; + private readonly CommunicatorService _communicator = communicator; + private readonly HashSet _unfolded = []; - private readonly Dictionary _filterCache; + private readonly Dictionary _filterCache = []; - private TreeCategory _categoryFilter; - private ChangedItemIconFlag _typeFilter; - private string _nameFilter; - private string _nodeFilter; + private TreeCategory _categoryFilter = AllCategories; + private ChangedItemIconFlag _typeFilter = ChangedItemFlagExtensions.AllFlags; + private string _nameFilter = string.Empty; + private string _nodeFilter = string.Empty; private Task? _task; - public ResourceTreeViewer(Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, - IncognitoService incognito, int actionCapacity, Action onRefresh, Action drawActions) - { - _config = config; - _treeFactory = treeFactory; - _changedItemDrawer = changedItemDrawer; - _incognito = incognito; - _actionCapacity = actionCapacity; - _onRefresh = onRefresh; - _drawActions = drawActions; - _unfolded = []; - - _filterCache = []; - - _categoryFilter = AllCategories; - _typeFilter = ChangedItemFlagExtensions.AllFlags; - _nameFilter = string.Empty; - _nodeFilter = string.Empty; - } - public void Draw() { DrawControls(); @@ -74,7 +59,7 @@ public class ResourceTreeViewer } else if (_task.IsCompletedSuccessfully) { - var debugMode = _config.DebugMode; + var debugMode = config.DebugMode; foreach (var (tree, index) in _task.Result.WithIndex()) { var category = Classify(tree); @@ -83,7 +68,7 @@ public class ResourceTreeViewer using (var c = ImRaii.PushColor(ImGuiCol.Text, CategoryColor(category).Value())) { - var isOpen = ImGui.CollapsingHeader($"{(_incognito.IncognitoMode ? tree.AnonymizedName : tree.Name)}###{index}", + var isOpen = ImGui.CollapsingHeader($"{(incognito.IncognitoMode ? tree.AnonymizedName : tree.Name)}###{index}", index == 0 ? ImGuiTreeNodeFlags.DefaultOpen : 0); if (debugMode) { @@ -98,9 +83,9 @@ public class ResourceTreeViewer using var id = ImRaii.PushId(index); - ImGui.TextUnformatted($"Collection: {(_incognito.IncognitoMode ? tree.AnonymizedCollectionName : tree.CollectionName)}"); + ImGui.TextUnformatted($"Collection: {(incognito.IncognitoMode ? tree.AnonymizedCollectionName : tree.CollectionName)}"); - using var table = ImRaii.Table("##ResourceTree", _actionCapacity > 0 ? 4 : 3, + using var table = ImRaii.Table("##ResourceTree", actionCapacity > 0 ? 4 : 3, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); if (!table) continue; @@ -108,9 +93,9 @@ public class ResourceTreeViewer ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthStretch, 0.2f); ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.3f); ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); - if (_actionCapacity > 0) + if (actionCapacity > 0) ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, - (_actionCapacity - 1) * 3 * ImGuiHelpers.GlobalScale + _actionCapacity * ImGui.GetFrameHeight()); + (actionCapacity - 1) * 3 * ImGuiHelpers.GlobalScale + actionCapacity * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); DrawNodes(tree.Nodes, 0, unchecked(tree.DrawObjectAddress * 31), 0); @@ -150,7 +135,7 @@ public class ResourceTreeViewer ImGui.SetCursorPosY(ImGui.GetCursorPosY() - yOffset); using (ImRaii.Child("##typeFilter", new Vector2(ImGui.GetContentRegionAvail().X, ChangedItemDrawer.TypeFilterIconSize.Y))) { - filterChanged |= _changedItemDrawer.DrawTypeFilter(ref _typeFilter); + filterChanged |= changedItemDrawer.DrawTypeFilter(ref _typeFilter); } var fieldWidth = (ImGui.GetContentRegionAvail().X - checkSpacing * 2.0f - ImGui.GetFrameHeightWithSpacing()) / 2.0f; @@ -160,7 +145,7 @@ public class ResourceTreeViewer ImGui.SetNextItemWidth(fieldWidth); filterChanged |= ImGui.InputTextWithHint("##NodeFilter", "Filter by Item/Part Name or Path...", ref _nodeFilter, 128); ImGui.SameLine(0, checkSpacing); - _incognito.DrawToggle(ImGui.GetFrameHeightWithSpacing()); + incognito.DrawToggle(ImGui.GetFrameHeightWithSpacing()); if (filterChanged) _filterCache.Clear(); @@ -171,7 +156,7 @@ public class ResourceTreeViewer { try { - return _treeFactory.FromObjectTable(ResourceTreeFactoryFlags) + return treeFactory.FromObjectTable(ResourceTreeFactoryFlags) .Select(entry => entry.ResourceTree) .ToArray(); } @@ -179,16 +164,16 @@ public class ResourceTreeViewer { _filterCache.Clear(); _unfolded.Clear(); - _onRefresh(); + onRefresh(); } }); private void DrawNodes(IEnumerable resourceNodes, int level, nint pathHash, ChangedItemIconFlag parentFilterIconFlag) { - var debugMode = _config.DebugMode; + var debugMode = config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); - var cellHeight = _actionCapacity > 0 ? frameHeight : 0.0f; + var cellHeight = actionCapacity > 0 ? frameHeight : 0.0f; foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { @@ -231,7 +216,7 @@ public class ResourceTreeViewer ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); } - _changedItemDrawer.DrawCategoryIcon(resourceNode.IconFlag); + changedItemDrawer.DrawCategoryIcon(resourceNode.IconFlag); ImGui.SameLine(0f, ImGui.GetStyle().ItemInnerSpacing.X); ImGui.TableHeader(resourceNode.Name); if (ImGui.IsItemClicked() && unfoldable) @@ -270,14 +255,33 @@ public class ResourceTreeViewer ImGui.TableNextColumn(); if (resourceNode.FullPath.FullName.Length > 0) { - var uiFullPathStr = resourceNode.ModName != null && resourceNode.ModRelativePath != null - ? $"[{resourceNode.ModName}] {resourceNode.ModRelativePath}" - : resourceNode.FullPath.ToPath(); - ImGui.Selectable(uiFullPathStr, false, 0, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + var hasMod = resourceNode.Mod.TryGetTarget(out var mod); + if (resourceNode is { ModName: not null, ModRelativePath: not null }) + { + var modName = $"[{(hasMod ? mod!.Name : resourceNode.ModName)}]"; + var textPos = ImGui.GetCursorPosX() + ImUtf8.CalcTextSize(modName).X + ImGui.GetStyle().ItemInnerSpacing.X; + using var group = ImUtf8.Group(); + using (var color = ImRaii.PushColor(ImGuiCol.Text, (hasMod ? ColorId.NewMod : ColorId.DisabledMod).Value())) + { + ImUtf8.Selectable(modName, false, ImGuiSelectableFlags.AllowItemOverlap, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + } + + ImGui.SameLine(); + ImGui.SetCursorPosX(textPos); + ImUtf8.Text(resourceNode.ModRelativePath); + } + else + { + ImGui.Selectable(resourceNode.FullPath.ToPath(), false, ImGuiSelectableFlags.AllowItemOverlap, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + } + if (ImGui.IsItemClicked()) ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); + if (hasMod && ImGui.IsItemClicked(ImGuiMouseButton.Right) && ImGui.GetIO().KeyCtrl) + _communicator.SelectTab.Invoke(TabType.Mods, mod); + ImGuiUtil.HoverTooltip( - $"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); + $"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard.{(hasMod ? "\nControl + Right-Click to jump to mod." : string.Empty)}{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } else { @@ -289,12 +293,12 @@ public class ResourceTreeViewer mutedColor.Dispose(); - if (_actionCapacity > 0) + if (actionCapacity > 0) { ImGui.TableNextColumn(); using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, ImGui.GetStyle().ItemSpacing with { X = 3 * ImGuiHelpers.GlobalScale }); - _drawActions(resourceNode, new Vector2(frameHeight)); + drawActions(resourceNode, new Vector2(frameHeight)); } if (unfolded) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs index ea64c0bf..10a4aea2 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs @@ -1,5 +1,6 @@ using OtterGui.Services; using Penumbra.Interop.ResourceTree; +using Penumbra.Services; namespace Penumbra.UI.AdvancedWindow; @@ -7,8 +8,9 @@ public class ResourceTreeViewerFactory( Configuration config, ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, - IncognitoService incognito) : IService + IncognitoService incognito, + CommunicatorService communicator) : IService { public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) - => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions); + => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator); } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index fc735d04..46e427ed 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -461,7 +461,7 @@ public class DebugTab : Window, ITab, IUiService if (!ImGui.CollapsingHeader("Actors")) return; - using var table = Table("##actors", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + using var table = Table("##actors", 8, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) return; @@ -485,6 +485,9 @@ public class DebugTab : Window, ITab, IUiService ? $"{identifier.DataId} | {obj.AsObject->BaseId}" : identifier.DataId.ToString(); ImGuiUtil.DrawTableColumn(id); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{(*(nint*)obj.Address):X}" : "NULL"); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{obj.AsObject->EntityId:X}" : "NULL"); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? obj.AsObject->IsCharacter() ? $"Character: {obj.AsCharacter->ObjectKind}" : "No Character" : "NULL"); } return; @@ -499,6 +502,9 @@ public class DebugTab : Window, ITab, IUiService ImGuiUtil.DrawTableColumn(string.Empty); ImGuiUtil.DrawTableColumn(_actors.ToString(id)); ImGuiUtil.DrawTableColumn(string.Empty); + ImGuiUtil.DrawTableColumn(string.Empty); + ImGuiUtil.DrawTableColumn(string.Empty); + ImGuiUtil.DrawTableColumn(string.Empty); } } From b377ca372ce2d349292b89c467948f659e312c24 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 29 Nov 2024 16:35:08 +0000 Subject: [PATCH 0998/1381] [CI] Updating repo.json for testing_1.3.1.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index bfea1e12..59ca83be 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.1.3", - "TestingAssemblyVersion": "1.3.1.4", + "TestingAssemblyVersion": "1.3.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.1.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.1.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 22541b3fd894a244ee8160845ce52d9939c29c1e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Dec 2024 20:23:15 +0100 Subject: [PATCH 0999/1381] Update variables drawer. --- Penumbra/UI/Tabs/Debug/DebugTab.cs | 160 +++--------------- .../UI/Tabs/Debug/GlobalVariablesDrawer.cs | 126 ++++++++++++++ 2 files changed, 154 insertions(+), 132 deletions(-) create mode 100644 Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 46e427ed..30605101 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -6,7 +6,6 @@ using Dalamud.Utility; using FFXIVClientStructs.FFXIV.Client.Game.Character; using FFXIVClientStructs.FFXIV.Client.Game.Group; using FFXIVClientStructs.FFXIV.Client.Game.Object; -using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.UI.Agent; using ImGuiNET; @@ -35,8 +34,6 @@ using Penumbra.UI.Classes; using Penumbra.Util; using static OtterGui.Raii.ImRaii; using CharacterBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase; -using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; -using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using ImGuiClip = OtterGui.ImGuiClip; using Penumbra.Api.IpcTester; using Penumbra.Interop.Hooks.PostProcessing; @@ -80,8 +77,7 @@ public class DebugTab : Window, ITab, IUiService private readonly HttpApi _httpApi; private readonly ActorManager _actors; private readonly StainService _stains; - private readonly CharacterUtility _characterUtility; - private readonly ResidentResourceManager _residentResources; + private readonly GlobalVariablesDrawer _globalVariablesDrawer; private readonly ResourceManagerService _resourceManager; private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; @@ -104,18 +100,17 @@ public class DebugTab : Window, ITab, IUiService private readonly CrashHandlerPanel _crashHandlerPanel; private readonly TexHeaderDrawer _texHeaderDrawer; private readonly HookOverrideDrawer _hookOverrides; - private readonly RsfService _rsfService; + private readonly RsfService _rsfService; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, - CharacterUtility characterUtility, ResidentResourceManager residentResources, ResourceManagerService resourceManager, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, - HookOverrideDrawer hookOverrides, RsfService rsfService) + HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -132,8 +127,6 @@ public class DebugTab : Window, ITab, IUiService _httpApi = httpApi; _actors = actors; _stains = stains; - _characterUtility = characterUtility; - _residentResources = residentResources; _resourceManager = resourceManager; _collectionResolver = collectionResolver; _drawObjectState = drawObjectState; @@ -153,7 +146,8 @@ public class DebugTab : Window, ITab, IUiService _crashHandlerPanel = crashHandlerPanel; _texHeaderDrawer = texHeaderDrawer; _hookOverrides = hookOverrides; - _rsfService = rsfService; + _rsfService = rsfService; + _globalVariablesDrawer = globalVariablesDrawer; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -185,14 +179,13 @@ public class DebugTab : Window, ITab, IUiService DrawActorsDebug(); DrawCollectionCaches(); _texHeaderDrawer.Draw(); - DrawDebugCharacterUtility(); DrawShaderReplacementFixer(); DrawData(); DrawCrcCache(); DrawResourceProblems(); _hookOverrides.Draw(); DrawPlayerModelInfo(); - DrawGlobalVariableInfo(); + _globalVariablesDrawer.Draw(); DrawDebugTabIpc(); } @@ -217,8 +210,10 @@ public class DebugTab : Window, ITab, IUiService { if (resourceNode) foreach (var (path, resource) in collection._cache!.CustomResources) + { ImUtf8.TreeNode($"{path} -> 0x{(ulong)resource.ResourceHandle:X}", ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); + } } using var modNode = ImUtf8.TreeNode("Enabled Mods"u8); @@ -485,9 +480,11 @@ public class DebugTab : Window, ITab, IUiService ? $"{identifier.DataId} | {obj.AsObject->BaseId}" : identifier.DataId.ToString(); ImGuiUtil.DrawTableColumn(id); - ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{(*(nint*)obj.Address):X}" : "NULL"); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{*(nint*)obj.Address:X}" : "NULL"); ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{obj.AsObject->EntityId:X}" : "NULL"); - ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? obj.AsObject->IsCharacter() ? $"Character: {obj.AsCharacter->ObjectKind}" : "No Character" : "NULL"); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero + ? obj.AsObject->IsCharacter() ? $"Character: {obj.AsCharacter->ObjectKind}" : "No Character" + : "NULL"); } return; @@ -795,68 +792,6 @@ public class DebugTab : Window, ITab, IUiService } } - /// - /// Draw information about the character utility class from SE, - /// displaying all files, their sizes, the default files and the default sizes. - /// - private unsafe void DrawDebugCharacterUtility() - { - if (!ImGui.CollapsingHeader("Character Utility")) - return; - - using var table = Table("##CharacterUtility", 7, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, - -Vector2.UnitX); - if (!table) - return; - - for (var idx = 0; idx < CharacterUtility.ReverseIndices.Length; ++idx) - { - var intern = CharacterUtility.ReverseIndices[idx]; - var resource = _characterUtility.Address->Resource(idx); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"[{idx}]"); - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"0x{(ulong)resource:X}"); - ImGui.TableNextColumn(); - if (resource == null) - { - ImGui.TableNextRow(); - continue; - } - - UiHelpers.Text(resource); - ImGui.TableNextColumn(); - var data = (nint)resource->CsHandle.GetData(); - var length = resource->CsHandle.GetLength(); - if (ImGui.Selectable($"0x{data:X}")) - if (data != nint.Zero && length > 0) - ImGui.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); - - ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(length.ToString()); - - ImGui.TableNextColumn(); - if (intern.Value != -1) - { - ImGui.Selectable($"0x{_characterUtility.DefaultResource(intern).Address:X}"); - if (ImGui.IsItemClicked()) - ImGui.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)_characterUtility.DefaultResource(intern).Address, - _characterUtility.DefaultResource(intern).Size).ToArray().Select(b => b.ToString("X2")))); - - ImGuiUtil.HoverTooltip("Click to copy bytes to clipboard."); - - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"{_characterUtility.DefaultResource(intern).Size}"); - } - else - { - ImGui.TableNextColumn(); - } - } - } private void DrawShaderReplacementFixer() { @@ -946,45 +881,6 @@ public class DebugTab : Window, ITab, IUiService ImGui.TextUnformatted($"{slowPathCallDeltas.Skin}"); } - /// Draw information about the resident resource files. - private unsafe void DrawDebugResidentResources() - { - using var tree = TreeNode("Resident Resources"); - if (!tree) - return; - - if (_residentResources.Address == null || _residentResources.Address->NumResources == 0) - return; - - using var table = Table("##ResidentResources", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, - -Vector2.UnitX); - if (!table) - return; - - for (var i = 0; i < _residentResources.Address->NumResources; ++i) - { - var resource = _residentResources.Address->ResourceList[i]; - ImGui.TableNextColumn(); - ImGui.TextUnformatted($"0x{(ulong)resource:X}"); - ImGui.TableNextColumn(); - UiHelpers.Text(resource); - } - } - - private static void DrawCopyableAddress(string label, nint address) - { - using (var _ = PushFont(UiBuilder.MonoFont)) - { - if (ImGui.Selectable($"0x{address:X16} {label}")) - ImGui.SetClipboardText($"{address:X16}"); - } - - ImGuiUtil.HoverTooltip("Click to copy address to clipboard."); - } - - private static unsafe void DrawCopyableAddress(string label, void* address) - => DrawCopyableAddress(label, (nint)address); - /// Draw information about the models, materials and resources currently loaded by the local player. private unsafe void DrawPlayerModelInfo() { @@ -993,13 +889,13 @@ public class DebugTab : Window, ITab, IUiService if (!ImGui.CollapsingHeader($"Player Model Info: {name}##Draw") || player == null) return; - DrawCopyableAddress("PlayerCharacter", player.Address); + DrawCopyableAddress("PlayerCharacter"u8, player.Address); var model = (CharacterBase*)((Character*)player.Address)->GameObject.GetDrawObject(); if (model == null) return; - DrawCopyableAddress("CharacterBase", model); + DrawCopyableAddress("CharacterBase"u8, model); using (var t1 = Table("##table", 2, ImGuiTableFlags.SizingFixedFit)) { @@ -1054,20 +950,6 @@ public class DebugTab : Window, ITab, IUiService } } - /// Draw information about some game global variables. - private unsafe void DrawGlobalVariableInfo() - { - var header = ImGui.CollapsingHeader("Global Variables"); - ImGuiUtil.HoverTooltip("Draw information about global variables. Can provide useful starting points for a memory viewer."); - if (!header) - return; - - DrawCopyableAddress("CharacterUtility", _characterUtility.Address); - DrawCopyableAddress("ResidentResourceManager", _residentResources.Address); - DrawCopyableAddress("Device", Device.Instance()); - DrawDebugResidentResources(); - } - private string _crcInput = string.Empty; private FullPath _crcPath = FullPath.Empty; @@ -1169,4 +1051,18 @@ public class DebugTab : Window, ITab, IUiService _config.Ephemeral.DebugSeparateWindow = false; _config.Ephemeral.Save(); } + + public static unsafe void DrawCopyableAddress(ReadOnlySpan label, void* address) + { + using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) + { + if (ImUtf8.Selectable($"0x{(nint)address:X16} {label}")) + ImUtf8.SetClipboardText($"0x{(nint)address:X16}"); + } + + ImUtf8.HoverTooltip("Click to copy address to clipboard."u8); + } + + public static unsafe void DrawCopyableAddress(ReadOnlySpan label, nint address) + => DrawCopyableAddress(label, (void*)address); } diff --git a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs new file mode 100644 index 00000000..601e9b4d --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs @@ -0,0 +1,126 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Interop.Services; + +namespace Penumbra.UI.Tabs.Debug; + +public unsafe class GlobalVariablesDrawer(CharacterUtility characterUtility, ResidentResourceManager residentResources) : IUiService +{ + /// Draw information about some game global variables. + public void Draw() + { + var header = ImUtf8.CollapsingHeader("Global Variables"u8); + ImUtf8.HoverTooltip("Draw information about global variables. Can provide useful starting points for a memory viewer."u8); + if (!header) + return; + + DebugTab.DrawCopyableAddress("CharacterUtility"u8, characterUtility.Address); + DebugTab.DrawCopyableAddress("ResidentResourceManager"u8, residentResources.Address); + DebugTab.DrawCopyableAddress("Device"u8, Device.Instance()); + DrawCharacterUtility(); + DrawResidentResources(); + } + + /// + /// Draw information about the character utility class from SE, + /// displaying all files, their sizes, the default files and the default sizes. + /// + private void DrawCharacterUtility() + { + using var tree = ImUtf8.TreeNode("Character Utility"u8); + if (!tree) + return; + + using var table = ImUtf8.Table("##CharacterUtility"u8, 7, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + -Vector2.UnitX); + if (!table) + return; + + for (var idx = 0; idx < CharacterUtility.ReverseIndices.Length; ++idx) + { + var intern = CharacterUtility.ReverseIndices[idx]; + var resource = characterUtility.Address->Resource(idx); + ImUtf8.DrawTableColumn($"[{idx}]"); + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + if (resource == null) + { + ImGui.TableNextRow(); + continue; + } + + ImUtf8.DrawTableColumn(resource->CsHandle.FileName.AsSpan()); + ImGui.TableNextColumn(); + var data = (nint)resource->CsHandle.GetData(); + var length = resource->CsHandle.GetLength(); + if (ImUtf8.Selectable($"0x{data:X}")) + if (data != nint.Zero && length > 0) + ImUtf8.SetClipboardText(string.Join("\n", + new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); + + ImUtf8.HoverTooltip("Click to copy bytes to clipboard."u8); + ImUtf8.DrawTableColumn(length.ToString()); + + ImGui.TableNextColumn(); + if (intern.Value != -1) + { + ImUtf8.Selectable($"0x{characterUtility.DefaultResource(intern).Address:X}"); + if (ImGui.IsItemClicked()) + ImUtf8.SetClipboardText(string.Join("\n", + new ReadOnlySpan((byte*)characterUtility.DefaultResource(intern).Address, + characterUtility.DefaultResource(intern).Size).ToArray().Select(b => b.ToString("X2")))); + + ImUtf8.HoverTooltip("Click to copy bytes to clipboard."u8); + + ImUtf8.DrawTableColumn($"{characterUtility.DefaultResource(intern).Size}"); + } + else + { + ImGui.TableNextColumn(); + } + } + } + + /// Draw information about the resident resource files. + private void DrawResidentResources() + { + using var tree = ImUtf8.TreeNode("Resident Resources"u8); + if (!tree) + return; + + if (residentResources.Address == null || residentResources.Address->NumResources == 0) + return; + + using var table = ImUtf8.Table("##ResidentResources"u8, 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + -Vector2.UnitX); + if (!table) + return; + + for (var idx = 0; idx < residentResources.Address->NumResources; ++idx) + { + var resource = residentResources.Address->ResourceList[idx]; + ImUtf8.DrawTableColumn($"[{idx}]"); + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + if (resource == null) + { + ImGui.TableNextRow(); + continue; + } + + ImUtf8.DrawTableColumn(resource->CsHandle.FileName.AsSpan()); + ImGui.TableNextColumn(); + var data = (nint)resource->CsHandle.GetData(); + var length = resource->CsHandle.GetLength(); + if (ImUtf8.Selectable($"0x{data:X}")) + if (data != nint.Zero && length > 0) + ImUtf8.SetClipboardText(string.Join("\n", + new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); + + ImUtf8.HoverTooltip("Click to copy bytes to clipboard."u8); + ImUtf8.DrawTableColumn(length.ToString()); + } + } +} From 1434ad6190f0afb145eb502cad065131b50d600e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 5 Dec 2024 20:35:53 +0100 Subject: [PATCH 1000/1381] Add context menu copying for paths in advanced editing. --- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 63 +++++++++++++++---- 1 file changed, 51 insertions(+), 12 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index b07633b6..5cabd14b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -1,4 +1,3 @@ -using System.Linq; using Dalamud.Interface; using ImGuiNET; using OtterGui; @@ -15,6 +14,7 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { private readonly HashSet _selectedFiles = new(256); + private readonly HashSet _cutPaths = []; private LowerString _fileFilter = LowerString.Empty; private bool _showGamePaths = true; private string _gamePathEdit = string.Empty; @@ -125,7 +125,7 @@ public partial class ModEditWindow using var id = ImRaii.PushId(i); ImGui.TableNextColumn(); - DrawSelectable(registry); + DrawSelectable(registry, i); if (!_showGamePaths) continue; @@ -177,24 +177,63 @@ public partial class ModEditWindow } } - private void DrawSelectable(FileRegistry registry) + private void DrawSelectable(FileRegistry registry, int i) { var selected = _selectedFiles.Contains(registry); var color = registry.SubModUsage.Count == 0 ? ColorId.ConflictingMod : registry.CurrentUsage == registry.SubModUsage.Count ? ColorId.NewMod : ColorId.InheritedMod; - using var c = ImRaii.PushColor(ImGuiCol.Text, color.Value()); - if (UiHelpers.Selectable(registry.RelPath.Path, selected)) + using (ImRaii.PushColor(ImGuiCol.Text, color.Value())) { - if (selected) - _selectedFiles.Remove(registry); - else - _selectedFiles.Add(registry); + if (UiHelpers.Selectable(registry.RelPath.Path, selected)) + { + if (selected) + _selectedFiles.Remove(registry); + else + _selectedFiles.Add(registry); + } + + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImUtf8.OpenPopup("context"u8); + + var rightText = DrawFileTooltip(registry, color); + + ImGui.SameLine(); + ImGuiUtil.RightAlign(rightText); } - var rightText = DrawFileTooltip(registry, color); + DrawContextMenu(registry, i); + } - ImGui.SameLine(); - ImGuiUtil.RightAlign(rightText); + private void DrawContextMenu(FileRegistry registry, int i) + { + using var context = ImUtf8.Popup("context"u8); + if (!context) + return; + + using (ImRaii.Disabled(registry.CurrentUsage == 0)) + { + if (ImUtf8.Selectable("Cut Game Paths"u8)) + { + _cutPaths.Clear(); + for (var j = 0; j < registry.SubModUsage.Count; ++j) + { + if (registry.SubModUsage[j].Item1 != _editor.Option) + continue; + + _cutPaths.Add(registry.SubModUsage[j].Item2); + _editor.FileEditor.SetGamePath(_editor.Option, i, j--, Utf8GamePath.Empty); + } + } + } + + using (ImRaii.Disabled(_cutPaths.Count == 0)) + { + if (ImUtf8.Selectable("Paste Game Paths"u8)) + { + foreach (var path in _cutPaths) + _editor.FileEditor.SetGamePath(_editor.Option!, i, -1, path); + } + } } private void PrintGamePath(int i, int j, FileRegistry registry, IModDataContainer subMod, Utf8GamePath gamePath) From e9014fe4c3de3d3f24adb96cd9d4d84e6d045960 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 5 Dec 2024 19:38:51 +0000 Subject: [PATCH 1001/1381] [CI] Updating repo.json for testing_1.3.1.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 59ca83be..50838b67 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.1.3", - "TestingAssemblyVersion": "1.3.1.5", + "TestingAssemblyVersion": "1.3.1.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.1.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.1.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 01db37cbd4724e173433e01d7ec381a7ae356569 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 9 Dec 2024 21:22:21 +0100 Subject: [PATCH 1002/1381] Add Copy for paths, update npc names --- Penumbra.GameData | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2b0c7f3b..da74a4be 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2b0c7f3bee0bc2eb466540d2fac265804354493d +Subproject commit da74a4be9c9728c6c52134c42603cd8a7040c568 diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 5cabd14b..6792c359 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -210,6 +210,21 @@ public partial class ModEditWindow if (!context) return; + using (ImRaii.Disabled(registry.CurrentUsage == 0)) + { + if (ImUtf8.Selectable("Copy Game Paths"u8)) + { + _cutPaths.Clear(); + for (var j = 0; j < registry.SubModUsage.Count; ++j) + { + if (registry.SubModUsage[j].Item1 != _editor.Option) + continue; + + _cutPaths.Add(registry.SubModUsage[j].Item2); + } + } + } + using (ImRaii.Disabled(registry.CurrentUsage == 0)) { if (ImUtf8.Selectable("Cut Game Paths"u8)) From 4cc7d1930b04d951e0255e2c9b82395ed51ea2b9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 9 Dec 2024 21:30:00 +0100 Subject: [PATCH 1003/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index da74a4be..fb692d13 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit da74a4be9c9728c6c52134c42603cd8a7040c568 +Subproject commit fb692d13205fed5e6c5f4c939477c28473198a3b From 22c3b3b629c3d997f0a6a7d689196977d0e5b6b2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 13 Dec 2024 15:43:09 +0100 Subject: [PATCH 1004/1381] Again. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fb692d13..315258f4 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fb692d13205fed5e6c5f4c939477c28473198a3b +Subproject commit 315258f4f8a59d744aa4d2d1f8c31d410d041729 From 08ff9b679e86d3ab9d76f64c781cf83989617cb5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 13 Dec 2024 17:48:54 +0100 Subject: [PATCH 1005/1381] Add changing mod settings to command / macro API. --- Penumbra/Api/Api/ModSettingsApi.cs | 70 +++++++++++++++++------------- Penumbra/CommandHandler.cs | 61 ++++++++++++++++++++++---- 2 files changed, 93 insertions(+), 38 deletions(-) diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index e046ce30..8c34c249 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -184,36 +184,9 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); - var groupIdx = mod.Groups.IndexOf(g => g.Name == optionGroupName); - if (groupIdx < 0) - return ApiHelpers.Return(PenumbraApiEc.OptionGroupMissing, args); - - var setting = Setting.Zero; - switch (mod.Groups[groupIdx]) - { - case { Behaviour: GroupDrawBehaviour.SingleSelection } single: - { - var optionIdx = optionNames.Count == 0 ? -1 : single.Options.IndexOf(o => o.Name == optionNames[^1]); - if (optionIdx < 0) - return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); - - setting = Setting.Single(optionIdx); - break; - } - case { Behaviour: GroupDrawBehaviour.MultiSelection } multi: - { - foreach (var name in optionNames) - { - var optionIdx = multi.Options.IndexOf(o => o.Name == name); - if (optionIdx < 0) - return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); - - setting |= Setting.Multi(optionIdx); - } - - break; - } - } + var settingSuccess = ConvertModSetting(mod, optionGroupName, optionNames, out var groupIdx, out var setting); + if (settingSuccess is not PenumbraApiEc.Success) + return ApiHelpers.Return(settingSuccess, args); var ret = _collectionEditor.SetModSetting(collection, mod, groupIdx, setting) ? PenumbraApiEc.Success @@ -283,4 +256,41 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable TriggerSettingEdited(mod); } + + public static PenumbraApiEc ConvertModSetting(Mod mod, string groupName, IReadOnlyList optionNames, out int groupIndex, + out Setting setting) + { + groupIndex = mod.Groups.IndexOf(g => g.Name.Equals(groupName, StringComparison.OrdinalIgnoreCase)); + setting = Setting.Zero; + if (groupIndex < 0) + return PenumbraApiEc.OptionGroupMissing; + + switch (mod.Groups[groupIndex]) + { + case { Behaviour: GroupDrawBehaviour.SingleSelection } single: + { + var optionIdx = optionNames.Count == 0 ? -1 : single.Options.IndexOf(o => o.Name == optionNames[^1]); + if (optionIdx < 0) + return PenumbraApiEc.OptionMissing; + + setting = Setting.Single(optionIdx); + break; + } + case { Behaviour: GroupDrawBehaviour.MultiSelection } multi: + { + foreach (var name in optionNames) + { + var optionIdx = multi.Options.IndexOf(o => o.Name == name); + if (optionIdx < 0) + return PenumbraApiEc.OptionMissing; + + setting |= Setting.Multi(optionIdx); + } + + break; + } + } + + return PenumbraApiEc.Success; + } } diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index db8d9aca..9c3eb988 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -4,6 +4,7 @@ using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui.Classes; using OtterGui.Services; +using Penumbra.Api.Api; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -379,16 +380,18 @@ public class CommandHandler : IDisposable, IApiService if (arguments.Length == 0) { var seString = new SeStringBuilder() - .AddText("Use with /penumbra mod ").AddBlue("[enable|disable|inherit|toggle]").AddText(" ").AddYellow("[Collection Name]") + .AddText("Use with /penumbra mod ").AddBlue("[enable|disable|inherit|toggle|setting]").AddText(" ") + .AddYellow("[Collection Name]") .AddText(" | ") - .AddPurple("[Mod Name or Mod Directory Name]"); + .AddPurple("[Mod Name or Mod Directory Name]") + .AddGreen(" <| [Option Group Name] | [Option1;Option2;...]>"); _chat.Print(seString.BuiltString); return true; } var split = arguments.Split(' ', 2, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); var nameSplit = split.Length != 2 - ? Array.Empty() + ? [] : split[1].Split('|', 2, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); if (nameSplit.Length != 2) { @@ -406,6 +409,23 @@ public class CommandHandler : IDisposable, IApiService if (!GetModCollection(nameSplit[0], out var collection) || collection == ModCollection.Empty) return false; + var groupName = string.Empty; + var optionNames = Array.Empty(); + if (state is 4) + { + var split2 = nameSplit[1].Split('|', 3, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + if (split2.Length < 2) + { + _chat.Print("Not enough arguments for changing settings provided."); + return false; + } + + nameSplit[1] = split2[0]; + groupName = split2[1]; + if (split2.Length == 3) + optionNames = split2[2].Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + } + if (!_modManager.TryGetMod(nameSplit[1], nameSplit[1], out var mod)) { _chat.Print(new SeStringBuilder().AddText("The mod ").AddRed(nameSplit[1], true).AddText(" does not exist.") @@ -413,12 +433,35 @@ public class CommandHandler : IDisposable, IApiService return false; } - if (HandleModState(state, collection!, mod)) - return true; + if (state < 4) + { + if (HandleModState(state, collection!, mod)) + return true; + + _chat.Print(new SeStringBuilder().AddText("Mod ").AddPurple(mod.Name, true) + .AddText("already had the desired state in collection ") + .AddYellow(collection!.Name, true).AddText(".").BuiltString); + return false; + } + + switch (ModSettingsApi.ConvertModSetting(mod, groupName, optionNames, out var groupIndex, out var setting)) + { + case PenumbraApiEc.OptionGroupMissing: + _chat.Print(new SeStringBuilder().AddText("The mod ").AddRed(nameSplit[1], true).AddText(" has no group ") + .AddGreen(groupName, true).AddText(".").BuiltString); + return false; + case PenumbraApiEc.OptionMissing: + _chat.Print(new SeStringBuilder().AddText("Not all set options in the mod ").AddRed(nameSplit[1], true) + .AddText(" could be found in group ").AddGreen(groupName, true).AddText(".").BuiltString); + return false; + case PenumbraApiEc.Success: + _collectionEditor.SetModSetting(collection!, mod, groupIndex, setting); + Print(() => new SeStringBuilder().AddText("Changed settings of group ").AddGreen(groupName, true).AddText(" in mod ") + .AddPurple(mod.Name, true).AddText(" in collection ") + .AddYellow(collection!.Name, true).AddText(".").BuiltString); + return true; + } - _chat.Print(new SeStringBuilder().AddText("Mod ").AddPurple(mod.Name, true) - .AddText("already had the desired state in collection ") - .AddYellow(collection!.Name, true).AddText(".").BuiltString); return false; } @@ -556,6 +599,8 @@ public class CommandHandler : IDisposable, IApiService "toggle" => 2, "inherit" => 3, "inherited" => 3, + "setting" => 4, + "settings" => 4, _ => -1, }; From 5db3d53994d5a7beb0b617078f3becfe04ad5010 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 13 Dec 2024 17:56:27 +0100 Subject: [PATCH 1006/1381] Small improvements. --- Penumbra/CommandHandler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 9c3eb988..aff7f16f 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -380,7 +380,7 @@ public class CommandHandler : IDisposable, IApiService if (arguments.Length == 0) { var seString = new SeStringBuilder() - .AddText("Use with /penumbra mod ").AddBlue("[enable|disable|inherit|toggle|setting]").AddText(" ") + .AddText("Use with /penumbra mod ").AddBlue("[enable|disable|inherit|toggle|").AddGreen("setting").AddBlue("]").AddText(" ") .AddYellow("[Collection Name]") .AddText(" | ") .AddPurple("[Mod Name or Mod Directory Name]") @@ -416,7 +416,7 @@ public class CommandHandler : IDisposable, IApiService var split2 = nameSplit[1].Split('|', 3, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); if (split2.Length < 2) { - _chat.Print("Not enough arguments for changing settings provided."); + _chat.Print("Not enough arguments for changing settings provided. Please add a group name and a list of setting names - which can be empty for multi options."); return false; } From 510b9a5f1f638151eab715f0f9eb7c09b990cff0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 13 Dec 2024 18:11:17 +0100 Subject: [PATCH 1007/1381] 1.3.2.0 --- Penumbra/UI/Changelog.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 0b0ca81a..ec2a716c 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -55,10 +55,24 @@ public class PenumbraChangelog : IUiService Add1_2_1_0(Changelog); Add1_3_0_0(Changelog); Add1_3_1_0(Changelog); - } - + Add1_3_2_0(Changelog); + } + #region Changelogs + private static void Add1_3_2_0(Changelog log) + => log.NextVersion("Version 1.3.2.0") + .RegisterHighlight("Added ATCH meta manipulations that allow the composite editing of attachment points across multiple mods.") + .RegisterEntry("Those ATCH manipulations should be shared via Mare Synchronos.", 1) + .RegisterEntry("This is an early implementation and might be bug-prone. Let me know of any issues. It was in testing for quite a while without reports.", 1) + .RegisterEntry("Added jumping to identified mods in the On-Screen tab via Control + Right-Click and improved their display slightly.") + .RegisterEntry("Added some right-click context menu copy options in the File Redirections editor for paths.") + .RegisterHighlight("Added the option to change a specific mod's settings via chat commands by using '/penumbra mod settings'.") + .RegisterEntry("Fixed issues with the copy-pasting of meta manipulations.") + .RegisterEntry("Fixed some other issues related to meta manipulations.") + .RegisterEntry("Updated available NPC names and fixed an issue with some supposedly invisible characters in names showing in ImGui."); + + private static void Add1_3_1_0(Changelog log) => log.NextVersion("Version 1.3.1.0") .RegisterEntry("Penumbra has been updated for Dalamud API 11 and patch 7.1.") From b5a469c5245d43c2831fa692d5f54b7f79c4fb24 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 13 Dec 2024 17:13:38 +0000 Subject: [PATCH 1008/1381] [CI] Updating repo.json for 1.3.2.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 50838b67..c0e561da 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.1.3", - "TestingAssemblyVersion": "1.3.1.6", + "AssemblyVersion": "1.3.2.0", + "TestingAssemblyVersion": "1.3.2.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.1.6/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.1.3/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From cc97ea0ce938a6c4f561c01991249cd768a613ae Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 16 Dec 2024 17:52:57 +0100 Subject: [PATCH 1009/1381] Add an option to automatically select the collection assigned to the current character on login. --- .../Collections/CollectionAutoSelector.cs | 75 +++++++++++++++++++ Penumbra/Configuration.cs | 4 +- Penumbra/Services/MessageService.cs | 3 +- Penumbra/UI/Changelog.cs | 1 - Penumbra/UI/Tabs/SettingsTab.cs | 15 +++- 5 files changed, 92 insertions(+), 6 deletions(-) create mode 100644 Penumbra/Collections/CollectionAutoSelector.cs diff --git a/Penumbra/Collections/CollectionAutoSelector.cs b/Penumbra/Collections/CollectionAutoSelector.cs new file mode 100644 index 00000000..e24fa6a9 --- /dev/null +++ b/Penumbra/Collections/CollectionAutoSelector.cs @@ -0,0 +1,75 @@ +using Dalamud.Plugin.Services; +using OtterGui.Services; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; + +namespace Penumbra.Collections; + +public sealed class CollectionAutoSelector : IService, IDisposable +{ + private readonly Configuration _config; + private readonly ActiveCollections _collections; + private readonly IClientState _clientState; + private readonly CollectionResolver _resolver; + private readonly ObjectManager _objects; + + public CollectionAutoSelector(Configuration config, ActiveCollections collections, IClientState clientState, CollectionResolver resolver, + ObjectManager objects) + { + _config = config; + _collections = collections; + _clientState = clientState; + _resolver = resolver; + _objects = objects; + + if (_config.AutoSelectCollection) + Attach(); + } + + public bool Disposed { get; private set; } + + public void SetAutomaticSelection(bool value) + { + _config.AutoSelectCollection = value; + if (value) + Attach(); + else + Detach(); + } + + private void Attach() + { + if (Disposed) + return; + + _clientState.Login += OnLogin; + Select(); + } + + private void OnLogin() + => Select(); + + private void Detach() + => _clientState.Login -= OnLogin; + + private void Select() + { + if (!_objects[0].IsCharacter) + return; + + var collection = _resolver.PlayerCollection(); + Penumbra.Log.Debug($"Setting current collection to {collection.Identifier} through automatic collection selection."); + _collections.SetCollection(collection, CollectionType.Current); + } + + + public void Dispose() + { + if (Disposed) + return; + + Disposed = true; + Detach(); + } +} diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 50426b38..ec5784f8 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -56,6 +56,8 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HideUiWhenUiHidden { get; set; } = false; public bool UseDalamudUiTextureRedirection { get; set; } = true; + public bool AutoSelectCollection { get; set; } = false; + public bool ShowModsInLobby { get; set; } = true; public bool UseCharacterCollectionInMainWindow { get; set; } = true; public bool UseCharacterCollectionsInCards { get; set; } = true; @@ -100,7 +102,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool UseFileSystemCompression { get; set; } = true; public bool EnableHttpApi { get; set; } = true; - public bool MigrateImportedModelsToV6 { get; set; } = true; + public bool MigrateImportedModelsToV6 { get; set; } = true; public bool MigrateImportedMaterialsToLegacy { get; set; } = true; public string DefaultModImportPath { get; set; } = string.Empty; diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index e610cb6a..70ccf47b 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -7,6 +7,7 @@ using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; using OtterGui.Log; using OtterGui.Services; +using Penumbra.GameData.Data; using Penumbra.Mods.Manager; using Penumbra.String.Classes; using Notification = OtterGui.Classes.Notification; @@ -29,7 +30,7 @@ public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INoti new TextPayload($"{(char)SeIconChar.LinkMarker}"), new UIForegroundPayload(0), new UIGlowPayload(0), - new TextPayload(item.Name.ExtractText()), + new TextPayload(item.Name.ExtractTextExtended()), new RawPayload([0x02, 0x27, 0x07, 0xCF, 0x01, 0x01, 0x01, 0xFF, 0x01, 0x03]), new RawPayload([0x02, 0x13, 0x02, 0xEC, 0x03]), }; diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index ec2a716c..c78ca290 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -92,7 +92,6 @@ public class PenumbraChangelog : IUiService private static void Add1_3_0_0(Changelog log) => log.NextVersion("Version 1.3.0.0") - .RegisterHighlight("The textures tab in the advanced editing window can now import and export .tga files.") .RegisterEntry("BC4 and BC6 textures can now also be imported.", 1) .RegisterHighlight("Added item swapping from and to the Glasses slot.") diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 9d8ea21c..46e214cf 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -12,6 +12,7 @@ using OtterGui.Raii; using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api; +using Penumbra.Collections; using Penumbra.Interop.Services; using Penumbra.Mods.Manager; using Penumbra.Services; @@ -46,6 +47,7 @@ public class SettingsTab : ITab, IUiService private readonly PredefinedTagManager _predefinedTagManager; private readonly CrashHandlerService _crashService; private readonly MigrationSectionDrawer _migrationDrawer; + private readonly CollectionAutoSelector _autoSelector; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -57,7 +59,7 @@ public class SettingsTab : ITab, IUiService CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, - MigrationSectionDrawer migrationDrawer) + MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector) { _pluginInterface = pluginInterface; _config = config; @@ -80,6 +82,7 @@ public class SettingsTab : ITab, IUiService _predefinedTagManager = predefinedTagConfig; _crashService = crashService; _migrationDrawer = migrationDrawer; + _autoSelector = autoSelector; } public void DrawHeader() @@ -421,6 +424,10 @@ public class SettingsTab : ITab, IUiService /// Draw all settings that do not fit into other categories. private void DrawMiscSettings() { + Checkbox("Automatically Select Character-Associated Collection", + "On every login, automatically select the collection associated with the current character as the current collection for editing.", + _config.AutoSelectCollection, _autoSelector.SetAutomaticSelection); + Checkbox("Print Chat Command Success Messages to Chat", "Chat Commands usually print messages on failure but also on success to confirm your action. You can disable this here.", _config.PrintSuccessfulCommandsToChat, v => _config.PrintSuccessfulCommandsToChat = v); @@ -816,13 +823,15 @@ public class SettingsTab : ITab, IUiService if (ImGuiUtil.DrawDisabledButton("Compress Existing Files", Vector2.Zero, "Try to compress all files in your root directory. This will take a while.", _compactor.MassCompactRunning || !_modManager.Valid)) - _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K, true); + _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.Xpress8K, + true); ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton("Decompress Existing Files", Vector2.Zero, "Try to decompress all files in your root directory. This will take a while.", _compactor.MassCompactRunning || !_modManager.Valid)) - _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.None, true); + _compactor.StartMassCompact(_modManager.BasePath.EnumerateFiles("*.*", SearchOption.AllDirectories), CompressionAlgorithm.None, + true); if (_compactor.MassCompactRunning) { From 18288815b294ce54549da904b40a6bb0c09dd854 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 17 Dec 2024 18:04:17 +0100 Subject: [PATCH 1010/1381] Add partial copying of color and colordye tables. --- Penumbra.GameData | 2 +- .../Materials/MtrlTab.CommonColorTable.cs | 62 +++++++++++++++++-- 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 315258f4..6848397d 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 315258f4f8a59d744aa4d2d1f8c31d410d041729 +Subproject commit 6848397dd77cfcdbff1accd860d5b7e95f8c9fe5 diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index 38f02100..236a66c3 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -202,24 +202,74 @@ public partial class MtrlTab if (Mtrl.Table == null) return false; - if (!ImUtf8.IconButton(FontAwesomeIcon.Paste, "Import an exported row from your clipboard onto this row."u8, + if (ImUtf8.IconButton(FontAwesomeIcon.Paste, + "Import an exported row from your clipboard onto this row.\n\nRight-Click for more options."u8, ImGui.GetFrameHeight() * Vector2.One, disabled)) + try + { + var text = ImGui.GetClipboardText(); + var data = Convert.FromBase64String(text); + var row = Mtrl.Table.RowAsBytes(rowIdx); + var dyeRow = Mtrl.DyeTable != null ? Mtrl.DyeTable.RowAsBytes(rowIdx) : []; + if (data.Length != row.Length && data.Length != row.Length + dyeRow.Length) + return false; + + data.AsSpan(0, row.Length).TryCopyTo(row); + data.AsSpan(row.Length).TryCopyTo(dyeRow); + + UpdateColorTableRowPreview(rowIdx); + + return true; + } + catch + { + return false; + } + + return ColorTablePasteFromClipboardContext(rowIdx, disabled); + } + + private unsafe bool ColorTablePasteFromClipboardContext(int rowIdx, bool disabled) + { + if (!disabled && ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImUtf8.OpenPopup("context"u8); + + using var context = ImUtf8.Popup("context"u8); + if (!context) + return false; + + using var _ = ImRaii.Disabled(disabled); + + IColorTable.ValueTypes copy = 0; + IColorDyeTable.ValueTypes dyeCopy = 0; + if (ImUtf8.Selectable("Import Colors Only"u8)) + { + copy = IColorTable.ValueTypes.Colors; + dyeCopy = IColorDyeTable.ValueTypes.Colors; + } + + if (ImUtf8.Selectable("Import Other Values Only"u8)) + { + copy = ~IColorTable.ValueTypes.Colors; + dyeCopy = ~IColorDyeTable.ValueTypes.Colors; + } + + if (copy == 0) return false; try { var text = ImGui.GetClipboardText(); var data = Convert.FromBase64String(text); - var row = Mtrl.Table.RowAsBytes(rowIdx); + var row = Mtrl.Table!.RowAsHalves(rowIdx); + var halves = new Span(Unsafe.AsPointer(ref data[0]), row.Length); var dyeRow = Mtrl.DyeTable != null ? Mtrl.DyeTable.RowAsBytes(rowIdx) : []; - if (data.Length != row.Length && data.Length != row.Length + dyeRow.Length) + if (!Mtrl.Table.MergeSpecificValues(row, halves, copy)) return false; - data.AsSpan(0, row.Length).TryCopyTo(row); - data.AsSpan(row.Length).TryCopyTo(dyeRow); + Mtrl.DyeTable?.MergeSpecificValues(dyeRow, data.AsSpan(row.Length * 2), dyeCopy); UpdateColorTableRowPreview(rowIdx); - return true; } catch From f679e0cceeba9751f216c7c82734a25c71945da8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 25 Dec 2024 21:58:43 +0100 Subject: [PATCH 1011/1381] Fix some imgui assertions. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 215e0172..d9caded5 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 215e01722a319c70b271dd23a40d99edc3fc197e +Subproject commit d9caded5efb7c9db0a273a43bb5f6d53cf4ace7f diff --git a/Penumbra.GameData b/Penumbra.GameData index 6848397d..ffc149cc 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 6848397dd77cfcdbff1accd860d5b7e95f8c9fe5 +Subproject commit ffc149cc8c169c2c6e838cbd138676f6fe4daeea From b3883c1306ed9b1b0a90699353efb2bf9f1bfdfa Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 26 Dec 2024 00:06:51 +0100 Subject: [PATCH 1012/1381] Add handling for cached TMBs. --- Penumbra.GameData | 2 +- Penumbra/Communication/ResolvedFileChanged.cs | 4 +- Penumbra/Interop/GameState.cs | 3 + .../Animation/GetCachedScheduleResource.cs | 53 +++++++ .../Interop/Hooks/Animation/LoadActionTmb.cs | 55 +++++++ Penumbra/Interop/Hooks/HookSettings.cs | 2 + .../SchedulerResourceManagementService.cs | 92 ++++++++++++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 109 +++++++++----- .../UI/Tabs/Debug/GlobalVariablesDrawer.cs | 135 +++++++++++++++++- 9 files changed, 415 insertions(+), 40 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Animation/GetCachedScheduleResource.cs create mode 100644 Penumbra/Interop/Hooks/Animation/LoadActionTmb.cs create mode 100644 Penumbra/Interop/Services/SchedulerResourceManagementService.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index ffc149cc..19355cfa 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ffc149cc8c169c2c6e838cbd138676f6fe4daeea +Subproject commit 19355cfa0ec80e8d5a91de11ecffc49257b37b53 diff --git a/Penumbra/Communication/ResolvedFileChanged.cs b/Penumbra/Communication/ResolvedFileChanged.cs index 75444340..0c91a18b 100644 --- a/Penumbra/Communication/ResolvedFileChanged.cs +++ b/Penumbra/Communication/ResolvedFileChanged.cs @@ -1,6 +1,5 @@ using OtterGui.Classes; using Penumbra.Collections; -using Penumbra.Mods; using Penumbra.Mods.Editor; using Penumbra.String.Classes; @@ -33,5 +32,8 @@ public sealed class ResolvedFileChanged() { /// DalamudSubstitutionProvider = 0, + + /// + SchedulerResourceManagementService = 0, } } diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs index 7e7abcd8..f80ef696 100644 --- a/Penumbra/Interop/GameState.cs +++ b/Penumbra/Interop/GameState.cs @@ -49,6 +49,9 @@ public class GameState : IService public void RestoreAnimationData(ResolveData old) => _animationLoadData.Value = old; + public readonly ThreadLocal InLoadActionTmb = new(() => false); + public readonly ThreadLocal SkipTmbCache = new(() => false); + #endregion #region Sound Data diff --git a/Penumbra/Interop/Hooks/Animation/GetCachedScheduleResource.cs b/Penumbra/Interop/Hooks/Animation/GetCachedScheduleResource.cs new file mode 100644 index 00000000..6ce1f899 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/GetCachedScheduleResource.cs @@ -0,0 +1,53 @@ +using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Resource; +using JetBrains.Annotations; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.Structs; +using Penumbra.String; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Load a cached TMB resource from SchedulerResourceManagement. +public sealed unsafe class GetCachedScheduleResource : FastHook +{ + private readonly GameState _state; + + public GetCachedScheduleResource(HookManager hooks, GameState state) + { + _state = state; + Task = hooks.CreateHook("Get Cached Schedule Resource", Sigs.GetCachedScheduleResource, Detour, + !HookOverrides.Instance.Animation.GetCachedScheduleResource); + } + + public delegate SchedulerResource* Delegate(SchedulerResourceManagement* a, ScheduleResourceLoadData* b, byte useMap); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private SchedulerResource* Detour(SchedulerResourceManagement* a, ScheduleResourceLoadData* b, byte c) + { + if (_state.SkipTmbCache.Value) + { + Penumbra.Log.Verbose( + $"[GetCachedScheduleResource] Called with 0x{(ulong)a:X}, {b->Id}, {new CiByteString(b->Path, MetaDataComputation.None)}, {c} from LoadActionTmb with forced skipping of cache, returning NULL."); + return null; + } + + var ret = Task.Result.Original(a, b, c); + Penumbra.Log.Excessive( + $"[GetCachedScheduleResource] Called with 0x{(ulong)a:X}, {b->Id}, {new CiByteString(b->Path, MetaDataComputation.None)}, {c}, returning 0x{(ulong)ret:X} ({(ret != null && Resource(ret) != null ? Resource(ret)->FileName().ToString() : "No Path")})."); + return ret; + } + + public struct ScheduleResourceLoadData + { + [UsedImplicitly] + public byte* Path; + + [UsedImplicitly] + public uint Id; + } + + + // #TODO: remove when fixed in CS. + public static ResourceHandle* Resource(SchedulerResource* r) + => ((ResourceHandle**)r)[3]; +} diff --git a/Penumbra/Interop/Hooks/Animation/LoadActionTmb.cs b/Penumbra/Interop/Hooks/Animation/LoadActionTmb.cs new file mode 100644 index 00000000..457465d2 --- /dev/null +++ b/Penumbra/Interop/Hooks/Animation/LoadActionTmb.cs @@ -0,0 +1,55 @@ +using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Resource; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.Interop.Services; +using Penumbra.String; + +namespace Penumbra.Interop.Hooks.Animation; + +/// Load a Action TMB. +public sealed unsafe class LoadActionTmb : FastHook +{ + private readonly GameState _state; + private readonly SchedulerResourceManagementService _scheduler; + + public LoadActionTmb(HookManager hooks, GameState state, SchedulerResourceManagementService scheduler) + { + _state = state; + _scheduler = scheduler; + Task = hooks.CreateHook("Load Action TMB", Sigs.LoadActionTmb, Detour, !HookOverrides.Instance.Animation.LoadActionTmb); + } + + public delegate SchedulerResource* Delegate(SchedulerResourceManagement* scheduler, + GetCachedScheduleResource.ScheduleResourceLoadData* loadData, nint b, byte c, byte d, byte e); + + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private SchedulerResource* Detour(SchedulerResourceManagement* scheduler, GetCachedScheduleResource.ScheduleResourceLoadData* loadData, + nint b, byte c, byte d, byte e) + { + _state.InLoadActionTmb.Value = true; + SchedulerResource* ret; + if (ShouldSkipCache(loadData)) + { + _state.SkipTmbCache.Value = true; + ret = Task.Result.Original(scheduler, loadData, b, c, d, 1); + Penumbra.Log.Verbose( + $"[LoadActionTMB] Called with 0x{(ulong)scheduler:X}, {loadData->Id}, {new CiByteString(loadData->Path, MetaDataComputation.None)}, 0x{b:X}, {c}, {d}, {e}, forced no-cache use, returned 0x{(ulong)ret:X} ({(ret != null && GetCachedScheduleResource.Resource(ret) != null ? GetCachedScheduleResource.Resource(ret)->FileName().ToString() : "No Path")})."); + _state.SkipTmbCache.Value = false; + } + else + { + ret = Task.Result.Original(scheduler, loadData, b, c, d, e); + Penumbra.Log.Excessive( + $"[LoadActionTMB] Called with 0x{(ulong)scheduler:X}, {loadData->Id}, {new CiByteString(loadData->Path)}, 0x{b:X}, {c}, {d}, {e}, returned 0x{(ulong)ret:X} ({(ret != null && GetCachedScheduleResource.Resource(ret) != null ? GetCachedScheduleResource.Resource(ret)->FileName().ToString() : "No Path")})."); + } + + _state.InLoadActionTmb.Value = false; + + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private bool ShouldSkipCache(GetCachedScheduleResource.ScheduleResourceLoadData* loadData) + => _scheduler.Contains(loadData->Id); +} diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 63d93c9d..2aeeb14b 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -43,6 +43,8 @@ public class HookOverrides public bool SomeMountAnimation; public bool SomePapLoad; public bool SomeParasolAnimation; + public bool GetCachedScheduleResource; + public bool LoadActionTmb; } public struct MetaHooks diff --git a/Penumbra/Interop/Services/SchedulerResourceManagementService.cs b/Penumbra/Interop/Services/SchedulerResourceManagementService.cs new file mode 100644 index 00000000..1d56fcdb --- /dev/null +++ b/Penumbra/Interop/Services/SchedulerResourceManagementService.cs @@ -0,0 +1,92 @@ +using System.Collections.Frozen; +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Resource; +using Lumina.Excel.Sheets; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Communication; +using Penumbra.GameData; +using Penumbra.Mods.Editor; +using Penumbra.Services; +using Penumbra.String; +using Penumbra.String.Classes; + +namespace Penumbra.Interop.Services; + +public unsafe class SchedulerResourceManagementService : IService, IDisposable +{ + private static readonly CiByteString TmbExtension = new(".tmb"u8, MetaDataComputation.All); + private static readonly CiByteString FolderPrefix = new("chara/action/"u8, MetaDataComputation.All); + + private readonly CommunicatorService _communicator; + private readonly FrozenDictionary _actionTmbs; + + private readonly ConcurrentDictionary _listedTmbIds = []; + + public bool Contains(uint tmbId) + => _listedTmbIds.ContainsKey(tmbId); + + public IReadOnlyDictionary ListedTmbs + => _listedTmbIds; + + public IReadOnlyDictionary ActionTmbs + => _actionTmbs; + + public SchedulerResourceManagementService(IGameInteropProvider interop, CommunicatorService communicator, IDataManager dataManager) + { + _communicator = communicator; + _actionTmbs = CreateActionTmbs(dataManager); + _communicator.ResolvedFileChanged.Subscribe(OnResolvedFileChange, ResolvedFileChanged.Priority.SchedulerResourceManagementService); + interop.InitializeFromAttributes(this); + } + + private void OnResolvedFileChange(ModCollection collection, ResolvedFileChanged.Type type, Utf8GamePath gamePath, FullPath oldPath, + FullPath newPath, IMod? mod) + { + switch (type) + { + case ResolvedFileChanged.Type.Added: + CheckFile(gamePath); + return; + case ResolvedFileChanged.Type.FullRecomputeFinished: + foreach (var path in collection.ResolvedFiles.Keys) + CheckFile(path); + return; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void CheckFile(Utf8GamePath gamePath) + { + if (!gamePath.Extension().Equals(TmbExtension)) + return; + + if (!gamePath.Path.StartsWith(FolderPrefix)) + return; + + var tmb = gamePath.Path.Substring(FolderPrefix.Length, gamePath.Length - FolderPrefix.Length - TmbExtension.Length).Clone(); + if (_actionTmbs.TryGetValue(tmb, out var rowId)) + _listedTmbIds[rowId] = tmb; + else + Penumbra.Log.Debug($"Action TMB {gamePath} encountered with no corresponding row ID."); + } + + [Signature(Sigs.SchedulerResourceManagementInstance, ScanType = ScanType.StaticAddress)] + public readonly SchedulerResourceManagement** Address = null; + + public SchedulerResourceManagement* Scheduler + => *Address; + + public void Dispose() + { + _listedTmbIds.Clear(); + _communicator.ResolvedFileChanged.Unsubscribe(OnResolvedFileChange); + } + + private static FrozenDictionary CreateActionTmbs(IDataManager dataManager) + { + var sheet = dataManager.GetExcelSheet(); + return sheet.Where(row => !row.Key.IsEmpty).DistinctBy(row => row.Key).ToFrozenDictionary(row => new CiByteString(row.Key, MetaDataComputation.All).Clone(), row => row.RowId); + } +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 30605101..125dbfa1 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -69,38 +69,39 @@ public class Diagnostics(ServiceManager provider) : IUiService public class DebugTab : Window, ITab, IUiService { - private readonly PerformanceTracker _performance; - private readonly Configuration _config; - private readonly CollectionManager _collectionManager; - private readonly ModManager _modManager; - private readonly ValidityChecker _validityChecker; - private readonly HttpApi _httpApi; - private readonly ActorManager _actors; - private readonly StainService _stains; - private readonly GlobalVariablesDrawer _globalVariablesDrawer; - private readonly ResourceManagerService _resourceManager; - private readonly CollectionResolver _collectionResolver; - private readonly DrawObjectState _drawObjectState; - private readonly PathState _pathState; - private readonly SubfileHelper _subfileHelper; - private readonly IdentifiedCollectionCache _identifiedCollectionCache; - private readonly CutsceneService _cutsceneService; - private readonly ModImportManager _modImporter; - private readonly ImportPopup _importPopup; - private readonly FrameworkManager _framework; - private readonly TextureManager _textureManager; - private readonly ShaderReplacementFixer _shaderReplacementFixer; - private readonly RedrawService _redraws; - private readonly DictEmote _emotes; - private readonly Diagnostics _diagnostics; - private readonly ObjectManager _objects; - private readonly IClientState _clientState; - private readonly IDataManager _dataManager; - private readonly IpcTester _ipcTester; - private readonly CrashHandlerPanel _crashHandlerPanel; - private readonly TexHeaderDrawer _texHeaderDrawer; - private readonly HookOverrideDrawer _hookOverrides; - private readonly RsfService _rsfService; + private readonly PerformanceTracker _performance; + private readonly Configuration _config; + private readonly CollectionManager _collectionManager; + private readonly ModManager _modManager; + private readonly ValidityChecker _validityChecker; + private readonly HttpApi _httpApi; + private readonly ActorManager _actors; + private readonly StainService _stains; + private readonly GlobalVariablesDrawer _globalVariablesDrawer; + private readonly ResourceManagerService _resourceManager; + private readonly CollectionResolver _collectionResolver; + private readonly DrawObjectState _drawObjectState; + private readonly PathState _pathState; + private readonly SubfileHelper _subfileHelper; + private readonly IdentifiedCollectionCache _identifiedCollectionCache; + private readonly CutsceneService _cutsceneService; + private readonly ModImportManager _modImporter; + private readonly ImportPopup _importPopup; + private readonly FrameworkManager _framework; + private readonly TextureManager _textureManager; + private readonly ShaderReplacementFixer _shaderReplacementFixer; + private readonly RedrawService _redraws; + private readonly DictEmote _emotes; + private readonly Diagnostics _diagnostics; + private readonly ObjectManager _objects; + private readonly IClientState _clientState; + private readonly IDataManager _dataManager; + private readonly IpcTester _ipcTester; + private readonly CrashHandlerPanel _crashHandlerPanel; + private readonly TexHeaderDrawer _texHeaderDrawer; + private readonly HookOverrideDrawer _hookOverrides; + private readonly RsfService _rsfService; + private readonly SchedulerResourceManagementService _schedulerService; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -110,7 +111,8 @@ public class DebugTab : Window, ITab, IUiService CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, - HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer) + HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer, + SchedulerResourceManagementService schedulerService) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -148,6 +150,7 @@ public class DebugTab : Window, ITab, IUiService _hookOverrides = hookOverrides; _rsfService = rsfService; _globalVariablesDrawer = globalVariablesDrawer; + _schedulerService = schedulerService; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -672,6 +675,22 @@ public class DebugTab : Window, ITab, IUiService } } } + + using (var tmbCache = TreeNode("TMB Cache")) + { + if (tmbCache) + { + using var table = Table("###TmbTable", 2, ImGuiTableFlags.SizingFixedFit); + if (table) + { + foreach (var (id, name) in _schedulerService.ListedTmbs.OrderBy(kvp => kvp.Key)) + { + ImUtf8.DrawTableColumn($"{id:D6}"); + ImUtf8.DrawTableColumn(name.Span); + } + } + } + } } private void DrawData() @@ -680,6 +699,7 @@ public class DebugTab : Window, ITab, IUiService return; DrawEmotes(); + DrawActionTmbs(); DrawStainTemplates(); DrawAtch(); } @@ -739,6 +759,27 @@ public class DebugTab : Window, ITab, IUiService ImGuiClip.DrawEndDummy(dummy, ImGui.GetTextLineHeightWithSpacing()); } + private void DrawActionTmbs() + { + using var mainTree = TreeNode("Action TMBs"); + if (!mainTree) + return; + + using var table = Table("##table", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingFixedFit, + new Vector2(-1, 12 * ImGui.GetTextLineHeightWithSpacing())); + if (!table) + return; + + var skips = ImGuiClip.GetNecessarySkips(ImGui.GetTextLineHeightWithSpacing()); + var dummy = ImGuiClip.ClippedDraw(_schedulerService.ActionTmbs.OrderBy(r => r.Value), skips, + p => + { + ImUtf8.DrawTableColumn($"{p.Value}"); + ImUtf8.DrawTableColumn(p.Key.Span); + }); + ImGuiClip.DrawEndDummy(dummy, ImGui.GetTextLineHeightWithSpacing()); + } + private void DrawStainTemplates() { using var mainTree = TreeNode("Staining Templates"); @@ -1061,7 +1102,7 @@ public class DebugTab : Window, ITab, IUiService } ImUtf8.HoverTooltip("Click to copy address to clipboard."u8); - } + } public static unsafe void DrawCopyableAddress(ReadOnlySpan label, nint address) => DrawCopyableAddress(label, (void*)address); diff --git a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs index 601e9b4d..4e6cf62c 100644 --- a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs @@ -1,12 +1,23 @@ +using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.System.Scheduler; +using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Resource; +using FFXIVClientStructs.Interop; +using FFXIVClientStructs.STD; using ImGuiNET; using OtterGui.Services; using OtterGui.Text; using Penumbra.Interop.Services; +using Penumbra.Interop.Structs; +using Penumbra.String; +using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra.UI.Tabs.Debug; -public unsafe class GlobalVariablesDrawer(CharacterUtility characterUtility, ResidentResourceManager residentResources) : IUiService +public unsafe class GlobalVariablesDrawer( + CharacterUtility characterUtility, + ResidentResourceManager residentResources, + SchedulerResourceManagementService scheduler) : IUiService { /// Draw information about some game global variables. public void Draw() @@ -16,13 +27,22 @@ public unsafe class GlobalVariablesDrawer(CharacterUtility characterUtility, Res if (!header) return; - DebugTab.DrawCopyableAddress("CharacterUtility"u8, characterUtility.Address); - DebugTab.DrawCopyableAddress("ResidentResourceManager"u8, residentResources.Address); - DebugTab.DrawCopyableAddress("Device"u8, Device.Instance()); + var actionManager = (ActionTimelineManager**)ActionTimelineManager.Instance(); + DebugTab.DrawCopyableAddress("CharacterUtility"u8, characterUtility.Address); + DebugTab.DrawCopyableAddress("ResidentResourceManager"u8, residentResources.Address); + DebugTab.DrawCopyableAddress("ScheduleManagement"u8, ScheduleManagement.Instance()); + DebugTab.DrawCopyableAddress("ActionTimelineManager*"u8, actionManager); + DebugTab.DrawCopyableAddress("ActionTimelineManager"u8, actionManager != null ? *actionManager : null); + DebugTab.DrawCopyableAddress("SchedulerResourceManagement*"u8, scheduler.Address); + DebugTab.DrawCopyableAddress("SchedulerResourceManagement"u8, scheduler.Address != null ? *scheduler.Address : null); + DebugTab.DrawCopyableAddress("Device"u8, Device.Instance()); DrawCharacterUtility(); DrawResidentResources(); + DrawSchedulerResourcesMap(); + DrawSchedulerResourcesList(); } + /// /// Draw information about the character utility class from SE, /// displaying all files, their sizes, the default files and the default sizes. @@ -123,4 +143,111 @@ public unsafe class GlobalVariablesDrawer(CharacterUtility characterUtility, Res ImUtf8.DrawTableColumn(length.ToString()); } } + + private string _schedulerFilterList = string.Empty; + private string _schedulerFilterMap = string.Empty; + private CiByteString _schedulerFilterListU8 = CiByteString.Empty; + private CiByteString _schedulerFilterMapU8 = CiByteString.Empty; + private int _shownResourcesList = 0; + private int _shownResourcesMap = 0; + + private void DrawSchedulerResourcesMap() + { + using var tree = ImUtf8.TreeNode("Scheduler Resources (Map)"u8); + if (!tree) + return; + + if (scheduler.Address == null || scheduler.Scheduler == null) + return; + + if (ImUtf8.InputText("##SchedulerMapFilter"u8, ref _schedulerFilterMap, "Filter..."u8)) + _schedulerFilterMapU8 = CiByteString.FromString(_schedulerFilterMap, out var t, MetaDataComputation.All, false) + ? t + : CiByteString.Empty; + ImUtf8.Text($"{_shownResourcesMap} / {scheduler.Scheduler->NumResources}"); + using var table = ImUtf8.Table("##SchedulerMapResources"u8, 10, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + -Vector2.UnitX); + if (!table) + return; + + var map = (StdMap>*)&scheduler.Scheduler->Unknown; + var total = 0; + _shownResourcesMap = 0; + foreach (var (key, resourcePtr) in *map) + { + var resource = resourcePtr.Value; + if (_schedulerFilterMap.Length is 0 || resource->Name.Buffer.IndexOf(_schedulerFilterMapU8.Span) >= 0) + { + ImUtf8.DrawTableColumn($"[{total:D4}]"); + ImUtf8.DrawTableColumn($"{resource->Name.Unk1}"); + ImUtf8.DrawTableColumn(new CiByteString(resource->Name.Buffer, MetaDataComputation.None).Span); + ImUtf8.DrawTableColumn($"{resource->Consumers}"); + ImUtf8.DrawTableColumn($"{resource->Unk1}"); // key + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + ImGui.TableNextColumn(); + var resourceHandle = *((ResourceHandle**)resource + 3); + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resourceHandle:X}"); + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable(resourceHandle->FileName().Span); + ImGui.TableNextColumn(); + uint dataLength = 0; + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource->GetResourceData(&dataLength):X}"); + ImUtf8.DrawTableColumn($"{dataLength}"); + ++_shownResourcesMap; + } + + ++total; + } + } + + private void DrawSchedulerResourcesList() + { + using var tree = ImUtf8.TreeNode("Scheduler Resources (List)"u8); + if (!tree) + return; + + if (scheduler.Address == null || scheduler.Scheduler == null) + return; + + if (ImUtf8.InputText("##SchedulerListFilter"u8, ref _schedulerFilterList, "Filter..."u8)) + _schedulerFilterListU8 = CiByteString.FromString(_schedulerFilterList, out var t, MetaDataComputation.All, false) + ? t + : CiByteString.Empty; + ImUtf8.Text($"{_shownResourcesList} / {scheduler.Scheduler->NumResources}"); + using var table = ImUtf8.Table("##SchedulerListResources"u8, 10, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + -Vector2.UnitX); + if (!table) + return; + + var resource = scheduler.Scheduler->Begin; + var total = 0; + _shownResourcesList = 0; + while (resource != null && total < (int)scheduler.Scheduler->NumResources) + { + if (_schedulerFilterList.Length is 0 || resource->Name.Buffer.IndexOf(_schedulerFilterListU8.Span) >= 0) + { + ImUtf8.DrawTableColumn($"[{total:D4}]"); + ImUtf8.DrawTableColumn($"{resource->Name.Unk1}"); + ImUtf8.DrawTableColumn(new CiByteString(resource->Name.Buffer, MetaDataComputation.None).Span); + ImUtf8.DrawTableColumn($"{resource->Consumers}"); + ImUtf8.DrawTableColumn($"{resource->Unk1}"); // key + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + ImGui.TableNextColumn(); + var resourceHandle = *((ResourceHandle**)resource + 3); + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resourceHandle:X}"); + ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable(resourceHandle->FileName().Span); + ImGui.TableNextColumn(); + uint dataLength = 0; + ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource->GetResourceData(&dataLength):X}"); + ImUtf8.DrawTableColumn($"{dataLength}"); + ++_shownResourcesList; + } + + resource = resource->Previous; + ++total; + } + } } From f24056ea3101a4ead083ea26a27caab23d77fb8a Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 25 Dec 2024 23:08:52 +0000 Subject: [PATCH 1013/1381] [CI] Updating repo.json for testing_1.3.2.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index c0e561da..97e55af0 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.2.0", - "TestingAssemblyVersion": "1.3.2.0", + "TestingAssemblyVersion": "1.3.2.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.2.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 25d0a2c9a83323336bbff7865e3cd054b5488075 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 29 Dec 2024 23:04:32 +0100 Subject: [PATCH 1014/1381] Fix issue with ring IMCs in resource tree. --- Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index 0c36b745..bdf66a16 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -161,7 +161,7 @@ internal partial record ResolveContext return variant.Id; } - var entry = ImcFile.GetEntry(imcFileData, Slot.ToSlot(), variant, out var exists); + var entry = ImcFile.GetEntry(imcFileData, SlotIndex.ToEquipSlot(), variant, out var exists); if (!exists) return variant.Id; From 0e2364497f2b16fbfd23aa0b6d9bfac9825a1da7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 30 Dec 2024 00:33:46 +0100 Subject: [PATCH 1015/1381] Maybe fix mtrl file issues. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 19355cfa..33de79bc 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 19355cfa0ec80e8d5a91de11ecffc49257b37b53 +Subproject commit 33de79bc62eb014298856ed5c6b6edbe819db26c From 2483f3dcdf776a1255b9400f1d5f26ea719cc5e6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 10:08:10 +0100 Subject: [PATCH 1016/1381] Add Temporary Settings class --- Penumbra/Mods/Settings/TemporaryModSettings.cs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Penumbra/Mods/Settings/TemporaryModSettings.cs diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs new file mode 100644 index 00000000..a0cdc2bb --- /dev/null +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -0,0 +1,8 @@ +namespace Penumbra.Mods.Settings; + +public sealed class TemporaryModSettings : ModSettings +{ + public string Source = string.Empty; + public int Lock = 0; + public bool ForceInherit; +} From 50b5eeb700fab8d40880a8fa1839cfe598e0b5bd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 10:08:35 +0100 Subject: [PATCH 1017/1381] Add FullModSettings struct. --- Penumbra/Mods/Settings/FullModSettings.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Penumbra/Mods/Settings/FullModSettings.cs diff --git a/Penumbra/Mods/Settings/FullModSettings.cs b/Penumbra/Mods/Settings/FullModSettings.cs new file mode 100644 index 00000000..904b56bd --- /dev/null +++ b/Penumbra/Mods/Settings/FullModSettings.cs @@ -0,0 +1,19 @@ +namespace Penumbra.Mods.Settings; + +public readonly record struct FullModSettings(ModSettings? Settings = null, TemporaryModSettings? TempSettings = null) +{ + public static readonly FullModSettings Empty = new(); + + public ModSettings? Resolve() + { + if (TempSettings == null) + return Settings; + if (TempSettings.ForceInherit) + return null; + + return TempSettings; + } + + public FullModSettings DeepCopy() + => new(Settings?.DeepCopy()); +} From 7a2691b9429cf801981389207ef563c5240b004a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 10:23:29 +0100 Subject: [PATCH 1018/1381] Add colors for temporary settings. --- Penumbra/UI/Classes/Colors.cs | 64 ++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index d135e10c..0389730d 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -31,6 +31,10 @@ public enum ColorId ResTreeNonNetworked, PredefinedTagAdd, PredefinedTagRemove, + TemporaryEnabledMod, + TemporaryDisabledMod, + TemporaryInheritedMod, + TemporaryInheritedDisabledMod, } public static class Colors @@ -52,34 +56,38 @@ public static class Colors => color switch { // @formatter:off - ColorId.EnabledMod => ( 0xFFFFFFFF, "Enabled Mod", "A mod that is enabled by the currently selected collection." ), - ColorId.DisabledMod => ( 0xFF686880, "Disabled Mod", "A mod that is disabled by the currently selected collection." ), - ColorId.UndefinedMod => ( 0xFF808080, "Mod With No Settings", "A mod that is not configured in the currently selected collection or any of the collections it inherits from, and thus implicitly disabled." ), - ColorId.InheritedMod => ( 0xFFD0FFFF, "Mod Enabled By Inheritance", "A mod that is not configured in the currently selected collection, but enabled in a collection it inherits from." ), - ColorId.InheritedDisabledMod => ( 0xFF688080, "Mod Disabled By Inheritance", "A mod that is not configured in the currently selected collection, but disabled in a collection it inherits from."), - ColorId.NewMod => ( 0xFF66DD66, "New Mod", "A mod that was newly imported or created during this session and has not been enabled yet." ), - ColorId.ConflictingMod => ( 0xFFAAAAFF, "Mod With Unresolved Conflicts", "An enabled mod that has conflicts with another enabled mod on the same priority level." ), - ColorId.HandledConflictMod => ( 0xFFD0FFD0, "Mod With Resolved Conflicts", "An enabled mod that has conflicts with another enabled mod on a different priority level." ), - ColorId.FolderExpanded => ( 0xFFFFF0C0, "Expanded Mod Folder", "A mod folder that is currently expanded." ), - ColorId.FolderCollapsed => ( 0xFFFFF0C0, "Collapsed Mod Folder", "A mod folder that is currently collapsed." ), - ColorId.FolderLine => ( 0xFFFFF0C0, "Expanded Mod Folder Line", "The line signifying which descendants belong to an expanded mod folder." ), - ColorId.ItemId => ( 0xFF808080, "Item Id", "The numeric model id of the given item to the right of changed items." ), - ColorId.IncreasedMetaValue => ( 0x80008000, "Increased Meta Manipulation Value", "An increased meta manipulation value for floats or an enabled toggle where the default is disabled."), - ColorId.DecreasedMetaValue => ( 0x80000080, "Decreased Meta Manipulation Value", "A decreased meta manipulation value for floats or a disabled toggle where the default is enabled."), - ColorId.SelectedCollection => ( 0x6069C056, "Currently Selected Collection", "The collection that is currently selected and being edited."), - ColorId.RedundantAssignment => ( 0x6050D0D0, "Redundant Collection Assignment", "A collection assignment that currently has no effect as it is redundant with more general assignments."), - ColorId.NoModsAssignment => ( 0x50000080, "'Use No Mods' Collection Assignment", "A collection assignment set to not use any mods at all."), - ColorId.NoAssignment => ( 0x00000000, "Unassigned Collection Assignment", "A collection assignment that is not configured to any collection and thus just has no specific treatment."), - ColorId.SelectorPriority => ( 0xFF808080, "Mod Selector Priority", "The priority displayed for non-zero priority mods in the mod selector."), - ColorId.InGameHighlight => ( 0xFFEBCF89, "In-Game Highlight (Primary)", "An in-game element that has been highlighted for ease of editing."), - ColorId.InGameHighlight2 => ( 0xFF446CC0, "In-Game Highlight (Secondary)", "Another in-game element that has been highlighted for ease of editing."), - ColorId.ResTreeLocalPlayer => ( 0xFFFFE0A0, "On-Screen: You", "You and what you own (mount, minion, accessory, pets and so on), in the On-Screen tab." ), - ColorId.ResTreePlayer => ( 0xFFC0FFC0, "On-Screen: Other Players", "Other players and what they own, in the On-Screen tab." ), - ColorId.ResTreeNetworked => ( 0xFFFFFFFF, "On-Screen: Non-Players (Networked)", "Non-player entities handled by the game server, in the On-Screen tab." ), - ColorId.ResTreeNonNetworked => ( 0xFFC0C0FF, "On-Screen: Non-Players (Local)", "Non-player entities handled locally, in the On-Screen tab." ), - ColorId.PredefinedTagAdd => ( 0xFF44AA44, "Predefined Tags: Add Tag", "A predefined tag that is not present on the current mod and can be added." ), - ColorId.PredefinedTagRemove => ( 0xFF2222AA, "Predefined Tags: Remove Tag", "A predefined tag that is already present on the current mod and can be removed." ), - _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), + ColorId.EnabledMod => ( 0xFFFFFFFF, "Enabled Mod", "A mod that is enabled by the currently selected collection." ), + ColorId.DisabledMod => ( 0xFF686880, "Disabled Mod", "A mod that is disabled by the currently selected collection." ), + ColorId.UndefinedMod => ( 0xFF808080, "Mod With No Settings", "A mod that is not configured in the currently selected collection or any of the collections it inherits from, and thus implicitly disabled." ), + ColorId.InheritedMod => ( 0xFFD0FFFF, "Mod Enabled By Inheritance", "A mod that is not configured in the currently selected collection, but enabled in a collection it inherits from." ), + ColorId.InheritedDisabledMod => ( 0xFF688080, "Mod Disabled By Inheritance", "A mod that is not configured in the currently selected collection, but disabled in a collection it inherits from."), + ColorId.NewMod => ( 0xFF66DD66, "New Mod", "A mod that was newly imported or created during this session and has not been enabled yet." ), + ColorId.ConflictingMod => ( 0xFFAAAAFF, "Mod With Unresolved Conflicts", "An enabled mod that has conflicts with another enabled mod on the same priority level." ), + ColorId.HandledConflictMod => ( 0xFFD0FFD0, "Mod With Resolved Conflicts", "An enabled mod that has conflicts with another enabled mod on a different priority level." ), + ColorId.FolderExpanded => ( 0xFFFFF0C0, "Expanded Mod Folder", "A mod folder that is currently expanded." ), + ColorId.FolderCollapsed => ( 0xFFFFF0C0, "Collapsed Mod Folder", "A mod folder that is currently collapsed." ), + ColorId.FolderLine => ( 0xFFFFF0C0, "Expanded Mod Folder Line", "The line signifying which descendants belong to an expanded mod folder." ), + ColorId.ItemId => ( 0xFF808080, "Item Id", "The numeric model id of the given item to the right of changed items." ), + ColorId.IncreasedMetaValue => ( 0x80008000, "Increased Meta Manipulation Value", "An increased meta manipulation value for floats or an enabled toggle where the default is disabled."), + ColorId.DecreasedMetaValue => ( 0x80000080, "Decreased Meta Manipulation Value", "A decreased meta manipulation value for floats or a disabled toggle where the default is enabled."), + ColorId.SelectedCollection => ( 0x6069C056, "Currently Selected Collection", "The collection that is currently selected and being edited."), + ColorId.RedundantAssignment => ( 0x6050D0D0, "Redundant Collection Assignment", "A collection assignment that currently has no effect as it is redundant with more general assignments."), + ColorId.NoModsAssignment => ( 0x50000080, "'Use No Mods' Collection Assignment", "A collection assignment set to not use any mods at all."), + ColorId.NoAssignment => ( 0x00000000, "Unassigned Collection Assignment", "A collection assignment that is not configured to any collection and thus just has no specific treatment."), + ColorId.SelectorPriority => ( 0xFF808080, "Mod Selector Priority", "The priority displayed for non-zero priority mods in the mod selector."), + ColorId.InGameHighlight => ( 0xFFEBCF89, "In-Game Highlight (Primary)", "An in-game element that has been highlighted for ease of editing."), + ColorId.InGameHighlight2 => ( 0xFF446CC0, "In-Game Highlight (Secondary)", "Another in-game element that has been highlighted for ease of editing."), + ColorId.ResTreeLocalPlayer => ( 0xFFFFE0A0, "On-Screen: You", "You and what you own (mount, minion, accessory, pets and so on), in the On-Screen tab." ), + ColorId.ResTreePlayer => ( 0xFFC0FFC0, "On-Screen: Other Players", "Other players and what they own, in the On-Screen tab." ), + ColorId.ResTreeNetworked => ( 0xFFFFFFFF, "On-Screen: Non-Players (Networked)", "Non-player entities handled by the game server, in the On-Screen tab." ), + ColorId.ResTreeNonNetworked => ( 0xFFC0C0FF, "On-Screen: Non-Players (Local)", "Non-player entities handled locally, in the On-Screen tab." ), + ColorId.PredefinedTagAdd => ( 0xFF44AA44, "Predefined Tags: Add Tag", "A predefined tag that is not present on the current mod and can be added." ), + ColorId.PredefinedTagRemove => ( 0xFF2222AA, "Predefined Tags: Remove Tag", "A predefined tag that is already present on the current mod and can be removed." ), + ColorId.TemporaryEnabledMod => ( 0xFFFFC0A0, "Mod Enabled By Temporary Settings", "A mod that is enabled by temporary settings in the currently selected collection." ), + ColorId.TemporaryDisabledMod => ( 0xFFB08070, "Mod Disabled By Temporary Settings", "A mod that is disabled by temporary settings in the currently selected collection." ), + ColorId.TemporaryInheritedMod => ( 0xFFE8FFB0, "Mod Enabled By Temporary Inheritance", "A mod that is forced to inherit by temporary settings in the currently selected collection." ), + ColorId.TemporaryInheritedDisabledMod => ( 0xFF90A080, "Mod Disabled By Temporary Inheritance", "A mod that is forced to inherit by temporary settings in the currently selected collection." ), + _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; From fbbfe5e00d8b53b2e103c6bf29f7ea870f348b0a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 10:39:24 +0100 Subject: [PATCH 1019/1381] Extract collection counters. --- Penumbra/Collections/Cache/AtchCache.cs | 5 ++-- Penumbra/Collections/Cache/CollectionCache.cs | 8 +++--- .../Cache/CollectionCacheManager.cs | 4 +-- Penumbra/Collections/Cache/ImcCache.cs | 4 +-- Penumbra/Collections/CollectionCounters.cs | 28 +++++++++++++++++++ .../Collections/Manager/CollectionStorage.cs | 2 +- .../Manager/TempCollectionManager.cs | 2 +- Penumbra/Collections/ModCollection.cs | 15 ++-------- .../Interop/PathResolving/PathDataHandler.cs | 8 +++--- Penumbra/UI/Tabs/Debug/DebugTab.cs | 4 +-- 10 files changed, 48 insertions(+), 32 deletions(-) create mode 100644 Penumbra/Collections/CollectionCounters.cs diff --git a/Penumbra/Collections/Cache/AtchCache.cs b/Penumbra/Collections/Cache/AtchCache.cs index 9e0f6caf..10990553 100644 --- a/Penumbra/Collections/Cache/AtchCache.cs +++ b/Penumbra/Collections/Cache/AtchCache.cs @@ -2,7 +2,6 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.GameData.Files.AtchStructs; using Penumbra.Meta; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Collections.Cache; @@ -37,7 +36,7 @@ public sealed class AtchCache(MetaFileManager manager, ModCollection collection) protected override void ApplyModInternal(AtchIdentifier identifier, AtchEntry entry) { - ++Collection.AtchChangeCounter; + Collection.Counters.IncrementAtch(); ApplyFile(identifier, entry); } @@ -68,7 +67,7 @@ public sealed class AtchCache(MetaFileManager manager, ModCollection collection) protected override void RevertModInternal(AtchIdentifier identifier) { - ++Collection.AtchChangeCounter; + Collection.Counters.IncrementAtch(); if (!_atchFiles.TryGetValue(identifier.GenderRace, out var pair)) return; diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 64cf54ea..bc431e88 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -177,7 +177,7 @@ public sealed class CollectionCache : IDisposable var (paths, manipulations) = ModData.RemoveMod(mod); if (addMetaChanges) - _collection.IncrementCounter(); + _collection.Counters.IncrementChange(); foreach (var path in paths) { @@ -250,7 +250,7 @@ public sealed class CollectionCache : IDisposable if (addMetaChanges) { - _collection.IncrementCounter(); + _collection.Counters.IncrementChange(); _manager.MetaFileManager.ApplyDefaultFiles(_collection); } } @@ -408,12 +408,12 @@ public sealed class CollectionCache : IDisposable // Identify and record all manipulated objects for this entire collection. private void SetChangedItems() { - if (_changedItemsSaveCounter == _collection.ChangeCounter) + if (_changedItemsSaveCounter == _collection.Counters.Change) return; try { - _changedItemsSaveCounter = _collection.ChangeCounter; + _changedItemsSaveCounter = _collection.Counters.Change; _changedItems.Clear(); // Skip IMCs because they would result in far too many false-positive items, // since they are per set instead of per item-slot/item/variant. diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index a3b6bb83..c3e00502 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -187,7 +187,7 @@ public class CollectionCacheManager : IDisposable, IService foreach (var mod in _modStorage) cache.AddModSync(mod, false); - collection.IncrementCounter(); + collection.Counters.IncrementChange(); MetaFileManager.ApplyDefaultFiles(collection); ResolvedFileChanged.Invoke(collection, ResolvedFileChanged.Type.FullRecomputeFinished, Utf8GamePath.Empty, FullPath.Empty, @@ -297,7 +297,7 @@ public class CollectionCacheManager : IDisposable, IService private void IncrementCounters() { foreach (var collection in _storage.Where(c => c.HasCache)) - collection.IncrementCounter(); + collection.Counters.IncrementChange(); MetaFileManager.CharacterUtility.LoadingFinished -= IncrementCounters; } diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index cac52f99..0f610d90 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -39,7 +39,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) protected override void ApplyModInternal(ImcIdentifier identifier, ImcEntry entry) { - ++Collection.ImcChangeCounter; + Collection.Counters.IncrementImc(); ApplyFile(identifier, entry); } @@ -71,7 +71,7 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) protected override void RevertModInternal(ImcIdentifier identifier) { - ++Collection.ImcChangeCounter; + Collection.Counters.IncrementImc(); var path = identifier.GamePath().Path; if (!_imcFiles.TryGetValue(path, out var pair)) return; diff --git a/Penumbra/Collections/CollectionCounters.cs b/Penumbra/Collections/CollectionCounters.cs new file mode 100644 index 00000000..91d240d6 --- /dev/null +++ b/Penumbra/Collections/CollectionCounters.cs @@ -0,0 +1,28 @@ +namespace Penumbra.Collections; + +public struct CollectionCounters(int changeCounter) +{ + /// Count the number of changes of the effective file list. + public int Change { get; private set; } = changeCounter; + + /// Count the number of IMC-relevant changes of the effective file list. + public int Imc { get; private set; } + + /// Count the number of ATCH-relevant changes of the effective file list. + public int Atch { get; private set; } + + /// Increment the number of changes in the effective file list. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IncrementChange() + => ++Change; + + /// Increment the number of IMC-relevant changes in the effective file list. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IncrementImc() + => ++Imc; + + /// Increment the number of ATCH-relevant changes in the effective file list. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IncrementAtch() + => ++Imc; +} diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index a326fb92..cdbe11dc 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -372,7 +372,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer { var (settings, _) = collection[mod.Index]; if (settings is { Enabled: true }) - collection.IncrementCounter(); + collection.Counters.IncrementChange(); } } } diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index 5c893232..e5b844c8 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -75,7 +75,7 @@ public class TempCollectionManager : IDisposable, IService _storage.Delete(collection); Penumbra.Log.Debug($"Deleted temporary collection {collection.Id}."); - GlobalChangeCounter += Math.Max(collection.ChangeCounter + 1 - GlobalChangeCounter, 0); + GlobalChangeCounter += Math.Max(collection.Counters.Change + 1 - GlobalChangeCounter, 0); for (var i = 0; i < Collections.Count; ++i) { if (Collections[i].Collection != collection) diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index db9c19cb..95e78da0 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -50,18 +50,7 @@ public partial class ModCollection /// The index of the collection is set and kept up-to-date by the CollectionManager. public int Index { get; internal set; } - /// - /// Count the number of changes of the effective file list. - /// This is used for material and imc changes. - /// - public int ChangeCounter { get; private set; } - - public uint ImcChangeCounter { get; set; } - public uint AtchChangeCounter { get; set; } - - /// Increment the number of changes in the effective file list. - public int IncrementCounter() - => ++ChangeCounter; + public CollectionCounters Counters; /// /// If a ModSetting is null, it can be inherited from other collections. @@ -213,7 +202,7 @@ public partial class ModCollection Id = id; LocalId = localId; Index = index; - ChangeCounter = changeCounter; + Counters = new CollectionCounters(changeCounter); Settings = appliedSettings; UnusedSettings = settings; DirectlyInheritsFrom = inheritsFrom; diff --git a/Penumbra/Interop/PathResolving/PathDataHandler.cs b/Penumbra/Interop/PathResolving/PathDataHandler.cs index 5439151f..25d4f7ea 100644 --- a/Penumbra/Interop/PathResolving/PathDataHandler.cs +++ b/Penumbra/Interop/PathResolving/PathDataHandler.cs @@ -32,7 +32,7 @@ public static class PathDataHandler /// Create the encoding path for an IMC file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateImc(CiByteString path, ModCollection collection) - => new($"|{collection.LocalId.Id}_{collection.ImcChangeCounter}_{DiscriminatorString}|{path}"); + => new($"|{collection.LocalId.Id}_{collection.Counters.Imc}_{DiscriminatorString}|{path}"); /// Create the encoding path for a TMB file. [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -47,17 +47,17 @@ public static class PathDataHandler /// Create the encoding path for an ATCH file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateAtch(CiByteString path, ModCollection collection) - => new($"|{collection.LocalId.Id}_{collection.AtchChangeCounter}_{DiscriminatorString}|{path}"); + => new($"|{collection.LocalId.Id}_{collection.Counters.Atch}_{DiscriminatorString}|{path}"); /// Create the encoding path for a MTRL file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateMtrl(CiByteString path, ModCollection collection, Utf8GamePath originalPath) - => new($"|{collection.LocalId.Id}_{collection.ChangeCounter}_{originalPath.Path.Crc32:X8}_{DiscriminatorString}|{path}"); + => new($"|{collection.LocalId.Id}_{collection.Counters.Change}_{originalPath.Path.Crc32:X8}_{DiscriminatorString}|{path}"); /// The base function shared by most file types. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static FullPath CreateBase(CiByteString path, ModCollection collection) - => new($"|{collection.LocalId.Id}_{collection.ChangeCounter}_{DiscriminatorString}|{path}"); + => new($"|{collection.LocalId.Id}_{collection.Counters.Change}_{DiscriminatorString}|{path}"); /// Read an additional data blurb and parse it into usable data for all file types but Materials. [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 125dbfa1..95afb10f 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -204,7 +204,7 @@ public class DebugTab : Window, ITab, IUiService if (collection.HasCache) { using var color = PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()); - using var node = TreeNode($"{collection.Name} (Change Counter {collection.ChangeCounter})###{collection.Name}"); + using var node = TreeNode($"{collection.Name} (Change Counter {collection.Counters.Change})###{collection.Name}"); if (!node) continue; @@ -239,7 +239,7 @@ public class DebugTab : Window, ITab, IUiService else { using var color = PushColor(ImGuiCol.Text, ColorId.UndefinedMod.Value()); - TreeNode($"{collection.AnonymizedName} (Change Counter {collection.ChangeCounter})", + TreeNode($"{collection.AnonymizedName} (Change Counter {collection.Counters.Change})", ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); } } From 67305d507a4e496202a66096050a9ffadedc5f52 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 11:36:30 +0100 Subject: [PATCH 1020/1381] Extract ModCollectionIdentity. --- OtterGui | 2 +- Penumbra/Api/Api/CollectionApi.cs | 32 +++++----- Penumbra/Api/Api/GameStateApi.cs | 4 +- Penumbra/Api/Api/ModSettingsApi.cs | 6 +- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 6 +- Penumbra/Api/TempModManager.cs | 4 +- Penumbra/Collections/Cache/CollectionCache.cs | 2 +- .../Cache/CollectionCacheManager.cs | 36 +++++------ .../Collections/CollectionAutoSelector.cs | 2 +- .../Manager/ActiveCollectionMigration.cs | 2 +- .../Collections/Manager/ActiveCollections.cs | 46 +++++++------- .../Collections/Manager/CollectionStorage.cs | 36 +++++------ .../Manager/IndividualCollections.Files.cs | 10 +-- .../Collections/Manager/InheritanceManager.cs | 14 ++--- .../Manager/TempCollectionManager.cs | 16 ++--- Penumbra/Collections/ModCollection.cs | 63 ++++++------------- Penumbra/Collections/ModCollectionIdentity.cs | 42 +++++++++++++ Penumbra/Collections/ModCollectionSave.cs | 16 ++--- Penumbra/Collections/ResolveData.cs | 2 +- Penumbra/CommandHandler.cs | 22 +++---- .../Interop/Hooks/Meta/AtchCallerHook1.cs | 2 +- .../Interop/Hooks/Meta/AtchCallerHook2.cs | 2 +- Penumbra/Interop/PathResolving/MetaState.cs | 2 +- .../Interop/PathResolving/PathDataHandler.cs | 8 +-- .../Processing/ImcFilePostProcessor.cs | 2 +- .../ResourceTree/ResourceTreeFactory.cs | 2 +- Penumbra/Mods/TemporaryMod.cs | 10 +-- Penumbra/Penumbra.cs | 12 ++-- Penumbra/Services/ConfigMigrationService.cs | 8 +-- Penumbra/Services/CrashHandlerService.cs | 4 +- Penumbra/Services/FilenameService.cs | 2 +- Penumbra/UI/Classes/CollectionSelectHeader.cs | 25 ++++---- Penumbra/UI/CollectionTab/CollectionCombo.cs | 4 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 16 ++--- .../UI/CollectionTab/CollectionSelector.cs | 6 +- Penumbra/UI/CollectionTab/InheritanceUi.cs | 10 +-- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 6 +- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 2 +- .../UI/ResourceWatcher/ResourceWatcher.cs | 2 +- .../ResourceWatcher/ResourceWatcherTable.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 22 +++---- Penumbra/UI/Tabs/ModsTab.cs | 4 +- Penumbra/UI/TutorialService.cs | 6 +- 43 files changed, 270 insertions(+), 252 deletions(-) create mode 100644 Penumbra/Collections/ModCollectionIdentity.cs diff --git a/OtterGui b/OtterGui index d9caded5..fcc96daa 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit d9caded5efb7c9db0a273a43bb5f6d53cf4ace7f +Subproject commit fcc96daa02633f673325c14aeea6b6b568924f1e diff --git a/Penumbra/Api/Api/CollectionApi.cs b/Penumbra/Api/Api/CollectionApi.cs index 04299187..964da1a5 100644 --- a/Penumbra/Api/Api/CollectionApi.cs +++ b/Penumbra/Api/Api/CollectionApi.cs @@ -8,7 +8,7 @@ namespace Penumbra.Api.Api; public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : IPenumbraApiCollection, IApiService { public Dictionary GetCollections() - => collections.Storage.ToDictionary(c => c.Id, c => c.Name); + => collections.Storage.ToDictionary(c => c.Identity.Id, c => c.Identity.Name); public List<(Guid Id, string Name)> GetCollectionsByIdentifier(string identifier) { @@ -17,14 +17,14 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : var list = new List<(Guid Id, string Name)>(4); if (Guid.TryParse(identifier, out var guid) && collections.Storage.ById(guid, out var collection) && collection != ModCollection.Empty) - list.Add((collection.Id, collection.Name)); + list.Add((collection.Identity.Id, collection.Identity.Name)); else if (identifier.Length >= 8) - list.AddRange(collections.Storage.Where(c => c.Identifier.StartsWith(identifier, StringComparison.OrdinalIgnoreCase)) - .Select(c => (c.Id, c.Name))); + list.AddRange(collections.Storage.Where(c => c.Identity.Identifier.StartsWith(identifier, StringComparison.OrdinalIgnoreCase)) + .Select(c => (c.Identity.Id, c.Identity.Name))); list.AddRange(collections.Storage - .Where(c => string.Equals(c.Name, identifier, StringComparison.OrdinalIgnoreCase) && !list.Contains((c.Id, c.Name))) - .Select(c => (c.Id, c.Name))); + .Where(c => string.Equals(c.Identity.Name, identifier, StringComparison.OrdinalIgnoreCase) && !list.Contains((c.Identity.Id, c.Identity.Name))) + .Select(c => (c.Identity.Id, c.Identity.Name))); return list; } @@ -54,7 +54,7 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : return null; var collection = collections.Active.ByType((CollectionType)type); - return collection == null ? null : (collection.Id, collection.Name); + return collection == null ? null : (collection.Identity.Id, collection.Identity.Name); } internal (Guid Id, string Name)? GetCollection(byte type) @@ -64,17 +64,17 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : { var id = helpers.AssociatedIdentifier(gameObjectIdx); if (!id.IsValid) - return (false, false, (collections.Active.Default.Id, collections.Active.Default.Name)); + return (false, false, (collections.Active.Default.Identity.Id, collections.Active.Default.Identity.Name)); if (collections.Active.Individuals.TryGetValue(id, out var collection)) - return (true, true, (collection.Id, collection.Name)); + return (true, true, (collection.Identity.Id, collection.Identity.Name)); helpers.AssociatedCollection(gameObjectIdx, out collection); - return (true, false, (collection.Id, collection.Name)); + return (true, false, (collection.Identity.Id, collection.Identity.Name)); } public Guid[] GetCollectionByName(string name) - => collections.Storage.Where(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase)).Select(c => c.Id).ToArray(); + => collections.Storage.Where(c => string.Equals(name, c.Identity.Name, StringComparison.OrdinalIgnoreCase)).Select(c => c.Identity.Id).ToArray(); public (PenumbraApiEc, (Guid Id, string Name)? OldCollection) SetCollection(ApiCollectionType type, Guid? collectionId, bool allowCreateNew, bool allowDelete) @@ -83,7 +83,7 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : return (PenumbraApiEc.InvalidArgument, null); var oldCollection = collections.Active.ByType((CollectionType)type); - var old = oldCollection != null ? (oldCollection.Id, oldCollection.Name) : new ValueTuple?(); + var old = oldCollection != null ? (oldCollection.Identity.Id, oldCollection.Identity.Name) : new ValueTuple?(); if (collectionId == null) { if (old == null) @@ -106,7 +106,7 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : collections.Active.CreateSpecialCollection((CollectionType)type); } - else if (old.Value.Item1 == collection.Id) + else if (old.Value.Item1 == collection.Identity.Id) { return (PenumbraApiEc.NothingChanged, old); } @@ -120,10 +120,10 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : { var id = helpers.AssociatedIdentifier(gameObjectIdx); if (!id.IsValid) - return (PenumbraApiEc.InvalidIdentifier, (collections.Active.Default.Id, collections.Active.Default.Name)); + return (PenumbraApiEc.InvalidIdentifier, (collections.Active.Default.Identity.Id, collections.Active.Default.Identity.Name)); var oldCollection = collections.Active.Individuals.TryGetValue(id, out var c) ? c : null; - var old = oldCollection != null ? (oldCollection.Id, oldCollection.Name) : new ValueTuple?(); + var old = oldCollection != null ? (oldCollection.Identity.Id, oldCollection.Identity.Name) : new ValueTuple?(); if (collectionId == null) { if (old == null) @@ -148,7 +148,7 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : var ids = collections.Active.Individuals.GetGroup(id); collections.Active.CreateIndividualCollection(ids); } - else if (old.Value.Item1 == collection.Id) + else if (old.Value.Item1 == collection.Identity.Id) { return (PenumbraApiEc.NothingChanged, old); } diff --git a/Penumbra/Api/Api/GameStateApi.cs b/Penumbra/Api/Api/GameStateApi.cs index c2cae32b..7f70c6bf 100644 --- a/Penumbra/Api/Api/GameStateApi.cs +++ b/Penumbra/Api/Api/GameStateApi.cs @@ -61,7 +61,7 @@ public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable public unsafe (nint GameObject, (Guid Id, string Name) Collection) GetDrawObjectInfo(nint drawObject) { var data = _collectionResolver.IdentifyCollection((DrawObject*)drawObject, true); - return (data.AssociatedGameObject, (data.ModCollection.Id, data.ModCollection.Name)); + return (data.AssociatedGameObject, (Id: data.ModCollection.Identity.Id, Name: data.ModCollection.Identity.Name)); } public int GetCutsceneParentIndex(int actorIdx) @@ -93,5 +93,5 @@ public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable } private void OnCreatedCharacterBase(nint gameObject, ModCollection collection, nint drawObject) - => CreatedCharacterBase?.Invoke(gameObject, collection.Id, drawObject); + => CreatedCharacterBase?.Invoke(gameObject, collection.Identity.Id, drawObject); } diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 8c34c249..3dc900fc 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -77,7 +77,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable if (!_collectionManager.Storage.ById(collectionId, out var collection)) return (PenumbraApiEc.CollectionMissing, null); - var settings = collection.Id == Guid.Empty + var settings = collection.Identity.Id == Guid.Empty ? null : ignoreInheritance ? collection.Settings[mod.Index] @@ -217,7 +217,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable var collection = _collectionResolver.PlayerCollection(); var (settings, parent) = collection[mod.Index]; if (settings is { Enabled: true }) - ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Id, mod.Identifier, parent != collection); + ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Identity.Id, mod.Identifier, parent != collection); } private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? _1, DirectoryInfo? _2) @@ -227,7 +227,7 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable } private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting _1, int _2, bool inherited) - => ModSettingChanged?.Invoke(type, collection.Id, mod?.ModPath.Name ?? string.Empty, inherited); + => ModSettingChanged?.Invoke(type, collection.Identity.Id, mod?.ModPath.Name ?? string.Empty, inherited); private void OnModOptionEdited(ModOptionChangeType type, Mod mod, IModGroup? group, IModOption? option, IModDataContainer? container, int moveIndex) diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index f6d1c9eb..f3c23831 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -146,10 +146,10 @@ public class TemporaryIpcTester( using (ImRaii.PushFont(UiBuilder.MonoFont)) { ImGui.TableNextColumn(); - ImGuiUtil.CopyOnClickSelectable(collection.Identifier); + ImGuiUtil.CopyOnClickSelectable(collection.Identity.Identifier); } - ImGuiUtil.DrawTableColumn(collection.Name); + ImGuiUtil.DrawTableColumn(collection.Identity.Name); ImGuiUtil.DrawTableColumn(collection.ResolvedFiles.Count.ToString()); ImGuiUtil.DrawTableColumn(collection.MetaCache?.Count.ToString() ?? "0"); ImGuiUtil.DrawTableColumn(string.Join(", ", @@ -199,7 +199,7 @@ public class TemporaryIpcTester( { PrintList("All", tempMods.ModsForAllCollections); foreach (var (collection, list) in tempMods.Mods) - PrintList(collection.Name, list); + PrintList(collection.Identity.Name, list); } } } diff --git a/Penumbra/Api/TempModManager.cs b/Penumbra/Api/TempModManager.cs index 0b52e64a..b3c6066a 100644 --- a/Penumbra/Api/TempModManager.cs +++ b/Penumbra/Api/TempModManager.cs @@ -85,13 +85,13 @@ public class TempModManager : IDisposable, IService { if (removed) { - Penumbra.Log.Verbose($"Removing temporary Mod {mod.Name} from {collection.AnonymizedName}."); + Penumbra.Log.Verbose($"Removing temporary Mod {mod.Name} from {collection.Identity.AnonymizedName}."); collection.Remove(mod); _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, Setting.False, 0, false); } else { - Penumbra.Log.Verbose($"Adding {(created ? "new " : string.Empty)}temporary Mod {mod.Name} to {collection.AnonymizedName}."); + Penumbra.Log.Verbose($"Adding {(created ? "new " : string.Empty)}temporary Mod {mod.Name} to {collection.Identity.AnonymizedName}."); collection.Apply(mod, created); _communicator.ModSettingChanged.Invoke(collection, ModSettingChange.TemporaryMod, null, Setting.True, 0, false); } diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index bc431e88..ad902aac 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -31,7 +31,7 @@ public sealed class CollectionCache : IDisposable public int Calculating = -1; public string AnonymizedName - => _collection.AnonymizedName; + => _collection.Identity.AnonymizedName; public IEnumerable> AllConflicts => ConflictDict.Values; diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index c3e00502..0a851154 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -114,16 +114,16 @@ public class CollectionCacheManager : IDisposable, IService /// Only creates a new cache, does not update an existing one. public bool CreateCache(ModCollection collection) { - if (collection.Index == ModCollection.Empty.Index) + if (collection.Identity.Index == ModCollection.Empty.Identity.Index) return false; if (collection._cache != null) return false; collection._cache = new CollectionCache(this, collection); - if (collection.Index > 0) + if (collection.Identity.Index > 0) Interlocked.Increment(ref _count); - Penumbra.Log.Verbose($"Created new cache for collection {collection.AnonymizedName}."); + Penumbra.Log.Verbose($"Created new cache for collection {collection.Identity.AnonymizedName}."); return true; } @@ -132,32 +132,32 @@ public class CollectionCacheManager : IDisposable, IService /// Does not create caches. /// public void CalculateEffectiveFileList(ModCollection collection) - => _framework.RegisterImportant(nameof(CalculateEffectiveFileList) + collection.Identifier, + => _framework.RegisterImportant(nameof(CalculateEffectiveFileList) + collection.Identity.Identifier, () => CalculateEffectiveFileListInternal(collection)); private void CalculateEffectiveFileListInternal(ModCollection collection) { // Skip the empty collection. - if (collection.Index == 0) + if (collection.Identity.Index == 0) return; - Penumbra.Log.Debug($"[{Environment.CurrentManagedThreadId}] Recalculating effective file list for {collection.AnonymizedName}"); + Penumbra.Log.Debug($"[{Environment.CurrentManagedThreadId}] Recalculating effective file list for {collection.Identity.AnonymizedName}"); if (!collection.HasCache) { Penumbra.Log.Error( - $"[{Environment.CurrentManagedThreadId}] Recalculating effective file list for {collection.AnonymizedName} failed, no cache exists."); + $"[{Environment.CurrentManagedThreadId}] Recalculating effective file list for {collection.Identity.AnonymizedName} failed, no cache exists."); } else if (collection._cache!.Calculating != -1) { Penumbra.Log.Error( - $"[{Environment.CurrentManagedThreadId}] Recalculating effective file list for {collection.AnonymizedName} failed, already in calculation on [{collection._cache!.Calculating}]."); + $"[{Environment.CurrentManagedThreadId}] Recalculating effective file list for {collection.Identity.AnonymizedName} failed, already in calculation on [{collection._cache!.Calculating}]."); } else { FullRecalculation(collection); Penumbra.Log.Debug( - $"[{Environment.CurrentManagedThreadId}] Recalculation of effective file list for {collection.AnonymizedName} finished."); + $"[{Environment.CurrentManagedThreadId}] Recalculation of effective file list for {collection.Identity.AnonymizedName} finished."); } } @@ -213,7 +213,7 @@ public class CollectionCacheManager : IDisposable, IService else { RemoveCache(old); - if (type is not CollectionType.Inactive && newCollection != null && newCollection.Index != 0 && CreateCache(newCollection)) + if (type is not CollectionType.Inactive && newCollection != null && newCollection.Identity.Index != 0 && CreateCache(newCollection)) CalculateEffectiveFileList(newCollection); if (type is CollectionType.Default) @@ -258,12 +258,12 @@ public class CollectionCacheManager : IDisposable, IService private void RemoveCache(ModCollection? collection) { if (collection != null - && collection.Index > ModCollection.Empty.Index - && collection.Index != _active.Default.Index - && collection.Index != _active.Interface.Index - && collection.Index != _active.Current.Index - && _active.SpecialAssignments.All(c => c.Value.Index != collection.Index) - && _active.Individuals.All(c => c.Collection.Index != collection.Index)) + && collection.Identity.Index > ModCollection.Empty.Identity.Index + && collection.Identity.Index != _active.Default.Identity.Index + && collection.Identity.Index != _active.Interface.Identity.Index + && collection.Identity.Index != _active.Current.Identity.Index + && _active.SpecialAssignments.All(c => c.Value.Identity.Index != collection.Identity.Index) + && _active.Individuals.All(c => c.Collection.Identity.Index != collection.Identity.Index)) ClearCache(collection); } @@ -359,9 +359,9 @@ public class CollectionCacheManager : IDisposable, IService collection._cache!.Dispose(); collection._cache = null; - if (collection.Index > 0) + if (collection.Identity.Index > 0) Interlocked.Decrement(ref _count); - Penumbra.Log.Verbose($"Cleared cache of collection {collection.AnonymizedName}."); + Penumbra.Log.Verbose($"Cleared cache of collection {collection.Identity.AnonymizedName}."); } /// diff --git a/Penumbra/Collections/CollectionAutoSelector.cs b/Penumbra/Collections/CollectionAutoSelector.cs index e24fa6a9..68dac914 100644 --- a/Penumbra/Collections/CollectionAutoSelector.cs +++ b/Penumbra/Collections/CollectionAutoSelector.cs @@ -59,7 +59,7 @@ public sealed class CollectionAutoSelector : IService, IDisposable return; var collection = _resolver.PlayerCollection(); - Penumbra.Log.Debug($"Setting current collection to {collection.Identifier} through automatic collection selection."); + Penumbra.Log.Debug($"Setting current collection to {collection.Identity.Identifier} through automatic collection selection."); _collections.SetCollection(collection, CollectionType.Current); } diff --git a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs index 19f781fc..b4af0998 100644 --- a/Penumbra/Collections/Manager/ActiveCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ActiveCollectionMigration.cs @@ -48,7 +48,7 @@ public static class ActiveCollectionMigration if (!storage.ByName(collectionName, out var collection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of <{player}>'s Collection {collectionName} is not available, reset to {ModCollection.Empty.Name}.", NotificationType.Warning); + $"Last choice of <{player}>'s Collection {collectionName} is not available, reset to {ModCollection.Empty.Identity.Name}.", NotificationType.Warning); dict.Add(player, ModCollection.Empty); } else diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 60f9a427..07fcb430 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -219,7 +219,7 @@ public class ActiveCollections : ISavable, IDisposable, IService _ => null, }; - if (oldCollection == null || collection == oldCollection || collection.Index >= _storage.Count) + if (oldCollection == null || collection == oldCollection || collection.Identity.Index >= _storage.Count) return; switch (collectionType) @@ -262,13 +262,13 @@ public class ActiveCollections : ISavable, IDisposable, IService var jObj = new JObject { { nameof(Version), Version }, - { nameof(Default), Default.Id }, - { nameof(Interface), Interface.Id }, - { nameof(Current), Current.Id }, + { nameof(Default), Default.Identity.Id }, + { nameof(Interface), Interface.Identity.Id }, + { nameof(Current), Current.Identity.Id }, }; foreach (var (type, collection) in SpecialCollections.WithIndex().Where(p => p.Value != null) .Select(p => ((CollectionType)p.Index, p.Value!))) - jObj.Add(type.ToString(), collection.Id); + jObj.Add(type.ToString(), collection.Identity.Id); jObj.Add(nameof(Individuals), Individuals.ToJObject()); using var j = new JsonTextWriter(writer); @@ -300,7 +300,7 @@ public class ActiveCollections : ISavable, IDisposable, IService if (oldCollection == Interface) SetCollection(ModCollection.Empty, CollectionType.Interface); if (oldCollection == Current) - SetCollection(Default.Index > ModCollection.Empty.Index ? Default : _storage.DefaultNamed, CollectionType.Current); + SetCollection(Default.Identity.Index > ModCollection.Empty.Identity.Index ? Default : _storage.DefaultNamed, CollectionType.Current); for (var i = 0; i < SpecialCollections.Length; ++i) { @@ -325,11 +325,11 @@ public class ActiveCollections : ISavable, IDisposable, IService { var configChanged = false; // Load the default collection. If the name does not exist take the empty collection. - var defaultName = jObject[nameof(Default)]?.ToObject() ?? ModCollection.Empty.Name; + var defaultName = jObject[nameof(Default)]?.ToObject() ?? ModCollection.Empty.Identity.Name; if (!_storage.ByName(defaultName, out var defaultCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.DefaultCollection} {defaultName} is not available, reset to {ModCollection.Empty.Name}.", + $"Last choice of {TutorialService.DefaultCollection} {defaultName} is not available, reset to {ModCollection.Empty.Identity.Name}.", NotificationType.Warning); Default = ModCollection.Empty; configChanged = true; @@ -340,11 +340,11 @@ public class ActiveCollections : ISavable, IDisposable, IService } // Load the interface collection. If no string is set, use the name of whatever was set as Default. - var interfaceName = jObject[nameof(Interface)]?.ToObject() ?? Default.Name; + var interfaceName = jObject[nameof(Interface)]?.ToObject() ?? Default.Identity.Name; if (!_storage.ByName(interfaceName, out var interfaceCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.InterfaceCollection} {interfaceName} is not available, reset to {ModCollection.Empty.Name}.", + $"Last choice of {TutorialService.InterfaceCollection} {interfaceName} is not available, reset to {ModCollection.Empty.Identity.Name}.", NotificationType.Warning); Interface = ModCollection.Empty; configChanged = true; @@ -355,11 +355,11 @@ public class ActiveCollections : ISavable, IDisposable, IService } // Load the current collection. - var currentName = jObject[nameof(Current)]?.ToObject() ?? Default.Name; + var currentName = jObject[nameof(Current)]?.ToObject() ?? Default.Identity.Name; if (!_storage.ByName(currentName, out var currentCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.SelectedCollection} {currentName} is not available, reset to {ModCollection.DefaultCollectionName}.", + $"Last choice of {TutorialService.SelectedCollection} {currentName} is not available, reset to {ModCollectionIdentity.DefaultCollectionName}.", NotificationType.Warning); Current = _storage.DefaultNamed; configChanged = true; @@ -404,7 +404,7 @@ public class ActiveCollections : ISavable, IDisposable, IService if (!_storage.ById(defaultId, out var defaultCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.DefaultCollection} {defaultId} is not available, reset to {ModCollection.Empty.Name}.", + $"Last choice of {TutorialService.DefaultCollection} {defaultId} is not available, reset to {ModCollection.Empty.Identity.Name}.", NotificationType.Warning); Default = ModCollection.Empty; configChanged = true; @@ -415,11 +415,11 @@ public class ActiveCollections : ISavable, IDisposable, IService } // Load the interface collection. If no string is set, use the name of whatever was set as Default. - var interfaceId = jObject[nameof(Interface)]?.ToObject() ?? Default.Id; + var interfaceId = jObject[nameof(Interface)]?.ToObject() ?? Default.Identity.Id; if (!_storage.ById(interfaceId, out var interfaceCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.InterfaceCollection} {interfaceId} is not available, reset to {ModCollection.Empty.Name}.", + $"Last choice of {TutorialService.InterfaceCollection} {interfaceId} is not available, reset to {ModCollection.Empty.Identity.Name}.", NotificationType.Warning); Interface = ModCollection.Empty; configChanged = true; @@ -430,11 +430,11 @@ public class ActiveCollections : ISavable, IDisposable, IService } // Load the current collection. - var currentId = jObject[nameof(Current)]?.ToObject() ?? _storage.DefaultNamed.Id; + var currentId = jObject[nameof(Current)]?.ToObject() ?? _storage.DefaultNamed.Identity.Id; if (!_storage.ById(currentId, out var currentCollection)) { Penumbra.Messager.NotificationMessage( - $"Last choice of {TutorialService.SelectedCollection} {currentId} is not available, reset to {ModCollection.DefaultCollectionName}.", + $"Last choice of {TutorialService.SelectedCollection} {currentId} is not available, reset to {ModCollectionIdentity.DefaultCollectionName}.", NotificationType.Warning); Current = _storage.DefaultNamed; configChanged = true; @@ -587,7 +587,7 @@ public class ActiveCollections : ISavable, IDisposable, IService case IdentifierType.Player when id.HomeWorld != ushort.MaxValue: { var global = ByType(CollectionType.Individual, _actors.CreatePlayer(id.PlayerName, ushort.MaxValue)); - return global?.Index == checkAssignment.Index + return (global != null ? global.Identity.Index : null) == checkAssignment.Identity.Index ? "Assignment is redundant due to an identical Any-World assignment existing.\nYou can remove it." : string.Empty; } @@ -596,12 +596,12 @@ public class ActiveCollections : ISavable, IDisposable, IService { var global = ByType(CollectionType.Individual, _actors.CreateOwned(id.PlayerName, ushort.MaxValue, id.Kind, id.DataId)); - if (global?.Index == checkAssignment.Index) + if ((global != null ? global.Identity.Index : null) == checkAssignment.Identity.Index) return "Assignment is redundant due to an identical Any-World assignment existing.\nYou can remove it."; } var unowned = ByType(CollectionType.Individual, _actors.CreateNpc(id.Kind, id.DataId)); - return unowned?.Index == checkAssignment.Index + return (unowned != null ? unowned.Identity.Index : null) == checkAssignment.Identity.Index ? "Assignment is redundant due to an identical unowned NPC assignment existing.\nYou can remove it." : string.Empty; } @@ -617,7 +617,7 @@ public class ActiveCollections : ISavable, IDisposable, IService if (maleNpc == null) { maleNpc = Default; - if (maleNpc.Index != checkAssignment.Index) + if (maleNpc.Identity.Index != checkAssignment.Identity.Index) return string.Empty; collection1 = CollectionType.Default; @@ -626,7 +626,7 @@ public class ActiveCollections : ISavable, IDisposable, IService if (femaleNpc == null) { femaleNpc = Default; - if (femaleNpc.Index != checkAssignment.Index) + if (femaleNpc.Identity.Index != checkAssignment.Identity.Index) return string.Empty; collection2 = CollectionType.Default; @@ -646,7 +646,7 @@ public class ActiveCollections : ISavable, IDisposable, IService if (assignment == null) continue; - if (assignment.Index == checkAssignment.Index) + if (assignment.Identity.Index == checkAssignment.Identity.Index) return $"Assignment is currently redundant due to overwriting {parentType.ToName()} with an identical collection.\nYou can remove it."; } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index cdbe11dc..2ed395ae 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -41,7 +41,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer public ModCollection CreateFromData(Guid id, string name, int version, Dictionary allSettings, IReadOnlyList inheritances) { - var newCollection = ModCollection.CreateFromData(_saveService, _modStorage, id, name, CurrentCollectionId, version, Count, allSettings, + var newCollection = ModCollection.CreateFromData(_saveService, _modStorage, new ModCollectionIdentity(id, CurrentCollectionId, name, Count), version, allSettings, inheritances); _collectionsByLocal[CurrentCollectionId] = newCollection; CurrentCollectionId += 1; @@ -57,7 +57,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer } public void Delete(ModCollection collection) - => _collectionsByLocal.Remove(collection.LocalId); + => _collectionsByLocal.Remove(collection.Identity.LocalId); /// The empty collection is always available at Index 0. private readonly List _collections = @@ -92,7 +92,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer public bool ByName(string name, [NotNullWhen(true)] out ModCollection? collection) { if (name.Length != 0) - return _collections.FindFirst(c => string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase), out collection); + return _collections.FindFirst(c => string.Equals(c.Identity.Name, name, StringComparison.OrdinalIgnoreCase), out collection); collection = ModCollection.Empty; return true; @@ -102,7 +102,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer public bool ById(Guid id, [NotNullWhen(true)] out ModCollection? collection) { if (id != Guid.Empty) - return _collections.FindFirst(c => c.Id == id, out collection); + return _collections.FindFirst(c => c.Identity.Id == id, out collection); collection = ModCollection.Empty; return true; @@ -158,7 +158,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer var newCollection = Create(name, _collections.Count, duplicate); _collections.Add(newCollection); _saveService.ImmediateSave(new ModCollectionSave(_modStorage, newCollection)); - Penumbra.Messager.NotificationMessage($"Created new collection {newCollection.AnonymizedName}.", NotificationType.Success, false); + Penumbra.Messager.NotificationMessage($"Created new collection {newCollection.Identity.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, null, newCollection, string.Empty); return true; } @@ -168,13 +168,13 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer /// public bool RemoveCollection(ModCollection collection) { - if (collection.Index <= ModCollection.Empty.Index || collection.Index >= _collections.Count) + if (collection.Identity.Index <= ModCollection.Empty.Identity.Index || collection.Identity.Index >= _collections.Count) { Penumbra.Messager.NotificationMessage("Can not remove the empty collection.", NotificationType.Error, false); return false; } - if (collection.Index == DefaultNamed.Index) + if (collection.Identity.Index == DefaultNamed.Identity.Index) { Penumbra.Messager.NotificationMessage("Can not remove the default collection.", NotificationType.Error, false); return false; @@ -182,13 +182,13 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer Delete(collection); _saveService.ImmediateDelete(new ModCollectionSave(_modStorage, collection)); - _collections.RemoveAt(collection.Index); + _collections.RemoveAt(collection.Identity.Index); // Update indices. - for (var i = collection.Index; i < Count; ++i) - _collections[i].Index = i; - _collectionsByLocal.Remove(collection.LocalId); + for (var i = collection.Identity.Index; i < Count; ++i) + _collections[i].Identity.Index = i; + _collectionsByLocal.Remove(collection.Identity.LocalId); - Penumbra.Messager.NotificationMessage($"Deleted collection {collection.AnonymizedName}.", NotificationType.Success, false); + Penumbra.Messager.NotificationMessage($"Deleted collection {collection.Identity.AnonymizedName}.", NotificationType.Success, false); _communicator.CollectionChange.Invoke(CollectionType.Inactive, collection, null, string.Empty); return true; } @@ -246,13 +246,13 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer { File.Move(file.FullName, correctName, false); Penumbra.Messager.NotificationMessage( - $"Collection {file.Name} does not correspond to {collection.Identifier}, renamed.", + $"Collection {file.Name} does not correspond to {collection.Identity.Identifier}, renamed.", NotificationType.Warning); } catch (Exception ex) { Penumbra.Messager.NotificationMessage( - $"Collection {file.Name} does not correspond to {collection.Identifier}, rename failed:\n{ex}", + $"Collection {file.Name} does not correspond to {collection.Identity.Identifier}, rename failed:\n{ex}", NotificationType.Warning); } } @@ -273,7 +273,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer catch (Exception e) { Penumbra.Messager.NotificationMessage(e, - $"Collection {file.Name} does not correspond to {collection.Identifier}, but could not rename.", + $"Collection {file.Name} does not correspond to {collection.Identity.Identifier}, but could not rename.", NotificationType.Error); } @@ -291,14 +291,14 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer /// private ModCollection SetDefaultNamedCollection() { - if (ByName(ModCollection.DefaultCollectionName, out var collection)) + if (ByName(ModCollectionIdentity.DefaultCollectionName, out var collection)) return collection; - if (AddCollection(ModCollection.DefaultCollectionName, null)) + if (AddCollection(ModCollectionIdentity.DefaultCollectionName, null)) return _collections[^1]; Penumbra.Messager.NotificationMessage( - $"Unknown problem creating a collection with the name {ModCollection.DefaultCollectionName}, which is required to exist.", + $"Unknown problem creating a collection with the name {ModCollectionIdentity.DefaultCollectionName}, which is required to exist.", NotificationType.Error); return Count > 1 ? _collections[1] : _collections[0]; } diff --git a/Penumbra/Collections/Manager/IndividualCollections.Files.cs b/Penumbra/Collections/Manager/IndividualCollections.Files.cs index f7a26384..60e9fc5f 100644 --- a/Penumbra/Collections/Manager/IndividualCollections.Files.cs +++ b/Penumbra/Collections/Manager/IndividualCollections.Files.cs @@ -18,7 +18,7 @@ public partial class IndividualCollections foreach (var (name, identifiers, collection) in Assignments) { var tmp = identifiers[0].ToJson(); - tmp.Add("Collection", collection.Id); + tmp.Add("Collection", collection.Identity.Id); tmp.Add("Display", name); ret.Add(tmp); } @@ -182,7 +182,7 @@ public partial class IndividualCollections Penumbra.Log.Information($"Migrated {name} ({kind.ToName()}) to NPC Identifiers [{ids}]."); else Penumbra.Messager.NotificationMessage( - $"Could not migrate {name} ({collection.AnonymizedName}) which was assumed to be a {kind.ToName()} with IDs [{ids}], please look through your individual collections.", + $"Could not migrate {name} ({collection.Identity.AnonymizedName}) which was assumed to be a {kind.ToName()} with IDs [{ids}], please look through your individual collections.", NotificationType.Error); } // If it is not a valid NPC name, check if it can be a player name. @@ -192,16 +192,16 @@ public partial class IndividualCollections var shortName = string.Join(" ", name.Split().Select(n => $"{n[0]}.")); // Try to migrate the player name without logging full names. if (Add($"{name} ({_actors.Data.ToWorldName(identifier.HomeWorld)})", [identifier], collection)) - Penumbra.Log.Information($"Migrated {shortName} ({collection.AnonymizedName}) to Player Identifier."); + Penumbra.Log.Information($"Migrated {shortName} ({collection.Identity.AnonymizedName}) to Player Identifier."); else Penumbra.Messager.NotificationMessage( - $"Could not migrate {shortName} ({collection.AnonymizedName}), please look through your individual collections.", + $"Could not migrate {shortName} ({collection.Identity.AnonymizedName}), please look through your individual collections.", NotificationType.Error); } else { Penumbra.Messager.NotificationMessage( - $"Could not migrate {name} ({collection.AnonymizedName}), which can not be a player name nor is it a known NPC name, please look through your individual collections.", + $"Could not migrate {name} ({collection.Identity.AnonymizedName}), which can not be a player name nor is it a known NPC name, please look through your individual collections.", NotificationType.Error); } } diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index bc1a362c..e003ad6b 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -89,7 +89,7 @@ public class InheritanceManager : IDisposable, IService _saveService.QueueSave(new ModCollectionSave(_modStorage, inheritor)); _communicator.CollectionInheritanceChanged.Invoke(inheritor, false); RecurseInheritanceChanges(inheritor); - Penumbra.Log.Debug($"Removed {parent.AnonymizedName} from {inheritor.AnonymizedName} inheritances."); + Penumbra.Log.Debug($"Removed {parent.Identity.AnonymizedName} from {inheritor.Identity.AnonymizedName} inheritances."); } /// Order in the inheritance list is relevant. @@ -101,7 +101,7 @@ public class InheritanceManager : IDisposable, IService _saveService.QueueSave(new ModCollectionSave(_modStorage, inheritor)); _communicator.CollectionInheritanceChanged.Invoke(inheritor, false); RecurseInheritanceChanges(inheritor); - Penumbra.Log.Debug($"Moved {inheritor.AnonymizedName}s inheritance {from} to {to}."); + Penumbra.Log.Debug($"Moved {inheritor.Identity.AnonymizedName}s inheritance {from} to {to}."); } /// @@ -119,7 +119,7 @@ public class InheritanceManager : IDisposable, IService RecurseInheritanceChanges(inheritor); } - Penumbra.Log.Debug($"Added {parent.AnonymizedName} to {inheritor.AnonymizedName} inheritances."); + Penumbra.Log.Debug($"Added {parent.Identity.AnonymizedName} to {inheritor.Identity.AnonymizedName} inheritances."); return true; } @@ -143,23 +143,23 @@ public class InheritanceManager : IDisposable, IService continue; changes = true; - Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", + Penumbra.Messager.NotificationMessage($"{collection.Identity.Name} can not inherit from {subCollection.Identity.Name}, removed.", NotificationType.Warning); } else if (_storage.ByName(subCollectionName, out subCollection)) { changes = true; - Penumbra.Log.Information($"Migrating inheritance for {collection.AnonymizedName} from name to GUID."); + Penumbra.Log.Information($"Migrating inheritance for {collection.Identity.AnonymizedName} from name to GUID."); if (AddInheritance(collection, subCollection, false)) continue; - Penumbra.Messager.NotificationMessage($"{collection.Name} can not inherit from {subCollection.Name}, removed.", + Penumbra.Messager.NotificationMessage($"{collection.Identity.Name} can not inherit from {subCollection.Identity.Name}, removed.", NotificationType.Warning); } else { Penumbra.Messager.NotificationMessage( - $"Inherited collection {subCollectionName} for {collection.AnonymizedName} does not exist, it was removed.", + $"Inherited collection {subCollectionName} for {collection.Identity.AnonymizedName} does not exist, it was removed.", NotificationType.Warning); changes = true; } diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index e5b844c8..8aab5297 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -44,7 +44,7 @@ public class TempCollectionManager : IDisposable, IService => _customCollections.Values; public bool CollectionByName(string name, [NotNullWhen(true)] out ModCollection? collection) - => _customCollections.Values.FindFirst(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase), out collection); + => _customCollections.Values.FindFirst(c => string.Equals(name, c.Identity.Name, StringComparison.OrdinalIgnoreCase), out collection); public bool CollectionById(Guid id, [NotNullWhen(true)] out ModCollection? collection) => _customCollections.TryGetValue(id, out collection); @@ -54,12 +54,12 @@ public class TempCollectionManager : IDisposable, IService if (GlobalChangeCounter == int.MaxValue) GlobalChangeCounter = 0; var collection = _storage.CreateTemporary(name, ~Count, GlobalChangeCounter++); - Penumbra.Log.Debug($"Creating temporary collection {collection.Name} with {collection.Id}."); - if (_customCollections.TryAdd(collection.Id, collection)) + Penumbra.Log.Debug($"Creating temporary collection {collection.Identity.Name} with {collection.Identity.Id}."); + if (_customCollections.TryAdd(collection.Identity.Id, collection)) { // Temporary collection created. _communicator.CollectionChange.Invoke(CollectionType.Temporary, null, collection, string.Empty); - return collection.Id; + return collection.Identity.Id; } return Guid.Empty; @@ -74,7 +74,7 @@ public class TempCollectionManager : IDisposable, IService } _storage.Delete(collection); - Penumbra.Log.Debug($"Deleted temporary collection {collection.Id}."); + Penumbra.Log.Debug($"Deleted temporary collection {collection.Identity.Id}."); GlobalChangeCounter += Math.Max(collection.Counters.Change + 1 - GlobalChangeCounter, 0); for (var i = 0; i < Collections.Count; ++i) { @@ -83,7 +83,7 @@ public class TempCollectionManager : IDisposable, IService // Temporary collection assignment removed. _communicator.CollectionChange.Invoke(CollectionType.Temporary, collection, null, Collections[i].DisplayName); - Penumbra.Log.Verbose($"Unassigned temporary collection {collection.Id} from {Collections[i].DisplayName}."); + Penumbra.Log.Verbose($"Unassigned temporary collection {collection.Identity.Id} from {Collections[i].DisplayName}."); Collections.Delete(i--); } @@ -96,7 +96,7 @@ public class TempCollectionManager : IDisposable, IService return false; // Temporary collection assignment added. - Penumbra.Log.Verbose($"Assigned temporary collection {collection.AnonymizedName} to {Collections.Last().DisplayName}."); + Penumbra.Log.Verbose($"Assigned temporary collection {collection.Identity.AnonymizedName} to {Collections.Last().DisplayName}."); _communicator.CollectionChange.Invoke(CollectionType.Temporary, null, collection, Collections.Last().DisplayName); return true; } @@ -127,6 +127,6 @@ public class TempCollectionManager : IDisposable, IService return false; var identifier = _actors.CreatePlayer(byteString, worldId); - return Collections.TryGetValue(identifier, out var collection) && RemoveTemporaryCollection(collection.Id); + return Collections.TryGetValue(identifier, out var collection) && RemoveTemporaryCollection(collection.Identity.Id); } } diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index 95e78da0..9b33c1f4 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -13,42 +13,21 @@ namespace Penumbra.Collections; /// - Index is the collections index in the ModCollection.Manager /// - Settings has the same size as ModManager.Mods. /// - any change in settings or inheritance of the collection causes a Save. -/// - the name can not contain invalid path characters and has to be unique when lower-cased. /// public partial class ModCollection { - public const int CurrentVersion = 2; - public const string DefaultCollectionName = "Default"; - public const string EmptyCollectionName = "None"; + public const int CurrentVersion = 2; /// /// Create the always available Empty Collection that will always sit at index 0, /// can not be deleted and does never create a cache. /// - public static readonly ModCollection Empty = new(Guid.Empty, EmptyCollectionName, LocalCollectionId.Zero, 0, 0, CurrentVersion, [], [], []); + public static readonly ModCollection Empty = new(ModCollectionIdentity.Empty, 0, CurrentVersion, [], [], []); - /// The name of a collection. - public string Name { get; set; } - - public Guid Id { get; } - - public LocalCollectionId LocalId { get; } - - public string Identifier - => Id.ToString(); - - public string ShortIdentifier - => Identifier[..8]; + public ModCollectionIdentity Identity; public override string ToString() - => Name.Length > 0 ? Name : ShortIdentifier; - - /// Get the first two letters of a collection name and its Index (or None if it is the empty collection). - public string AnonymizedName - => this == Empty ? Empty.Name : Name == DefaultCollectionName ? Name : ShortIdentifier; - - /// The index of the collection is set and kept up-to-date by the CollectionManager. - public int Index { get; internal set; } + => Identity.ToString(); public CollectionCounters Counters; @@ -90,7 +69,7 @@ public partial class ModCollection { get { - if (Index <= 0) + if (Identity.Index <= 0) return (ModSettings.Empty, this); foreach (var collection in GetFlattenedInheritance()) @@ -114,17 +93,17 @@ public partial class ModCollection public ModCollection Duplicate(string name, LocalCollectionId localId, int index) { Debug.Assert(index > 0, "Collection duplicated with non-positive index."); - return new ModCollection(Guid.NewGuid(), name, localId, index, 0, CurrentVersion, Settings.Select(s => s?.DeepCopy()).ToList(), - [.. DirectlyInheritsFrom], UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); + return new ModCollection(ModCollectionIdentity.New(name, localId, index), 0, CurrentVersion, + Settings.Select(s => s?.DeepCopy()).ToList(), [.. DirectlyInheritsFrom], + UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); } /// Constructor for reading from files. - public static ModCollection CreateFromData(SaveService saver, ModStorage mods, Guid id, string name, LocalCollectionId localId, int version, - int index, + public static ModCollection CreateFromData(SaveService saver, ModStorage mods, ModCollectionIdentity identity, int version, Dictionary allSettings, IReadOnlyList inheritances) { - Debug.Assert(index > 0, "Collection read with non-positive index."); - var ret = new ModCollection(id, name, localId, index, 0, version, [], [], allSettings) + Debug.Assert(identity.Index > 0, "Collection read with non-positive index."); + var ret = new ModCollection(identity, 0, version, [], [], allSettings) { InheritanceByName = inheritances, }; @@ -137,7 +116,7 @@ public partial class ModCollection public static ModCollection CreateTemporary(string name, LocalCollectionId localId, int index, int changeCounter) { Debug.Assert(index < 0, "Temporary collection created with non-negative index."); - var ret = new ModCollection(Guid.NewGuid(), name, localId, index, changeCounter, CurrentVersion, [], [], []); + var ret = new ModCollection(ModCollectionIdentity.New(name, localId, index), changeCounter, CurrentVersion, [], [], []); return ret; } @@ -145,9 +124,8 @@ public partial class ModCollection public static ModCollection CreateEmpty(string name, LocalCollectionId localId, int index, int modCount) { Debug.Assert(index >= 0, "Empty collection created with negative index."); - return new ModCollection(Guid.NewGuid(), name, localId, index, 0, CurrentVersion, - Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], - []); + return new ModCollection(ModCollectionIdentity.New(name, localId, index), 0, CurrentVersion, + Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], []); } /// Add settings for a new appended mod, by checking if the mod had settings from a previous deletion. @@ -195,16 +173,13 @@ public partial class ModCollection saver.ImmediateSave(new ModCollectionSave(mods, this)); } - private ModCollection(Guid id, string name, LocalCollectionId localId, int index, int changeCounter, int version, - List appliedSettings, List inheritsFrom, Dictionary settings) + private ModCollection(ModCollectionIdentity identity, int changeCounter, int version, List appliedSettings, + List inheritsFrom, Dictionary settings) { - Name = name; - Id = id; - LocalId = localId; - Index = index; + Identity = identity; Counters = new CollectionCounters(changeCounter); - Settings = appliedSettings; - UnusedSettings = settings; + Settings = appliedSettings; + UnusedSettings = settings; DirectlyInheritsFrom = inheritsFrom; foreach (var c in DirectlyInheritsFrom) ((List)c.DirectParentOf).Add(this); diff --git a/Penumbra/Collections/ModCollectionIdentity.cs b/Penumbra/Collections/ModCollectionIdentity.cs new file mode 100644 index 00000000..c7f60005 --- /dev/null +++ b/Penumbra/Collections/ModCollectionIdentity.cs @@ -0,0 +1,42 @@ +using OtterGui; +using Penumbra.Collections.Manager; + +namespace Penumbra.Collections; + +public struct ModCollectionIdentity(Guid id, LocalCollectionId localId) +{ + public const string DefaultCollectionName = "Default"; + public const string EmptyCollectionName = "None"; + + public static readonly ModCollectionIdentity Empty = new(Guid.Empty, LocalCollectionId.Zero, EmptyCollectionName, 0); + + public string Name { get; set; } + public Guid Id { get; } = id; + public LocalCollectionId LocalId { get; } = localId; + + /// The index of the collection is set and kept up-to-date by the CollectionManager. + public int Index { get; internal set; } + + public string Identifier + => Id.ToString(); + + public string ShortIdentifier + => Id.ShortGuid(); + + /// Get the short identifier of a collection unless it is a well-known collection name. + public string AnonymizedName + => Id == Guid.Empty ? EmptyCollectionName : Name == DefaultCollectionName ? Name : ShortIdentifier; + + public override string ToString() + => Name.Length > 0 ? Name : ShortIdentifier; + + public ModCollectionIdentity(Guid id, LocalCollectionId localId, string name, int index) + : this(id, localId) + { + Name = name; + Index = index; + } + + public static ModCollectionIdentity New(string name, LocalCollectionId id, int index) + => new(Guid.NewGuid(), id, name, index); +} diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index e6bb069b..6e1b51ac 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -15,7 +15,7 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection => fileNames.CollectionFile(modCollection); public string LogName(string _) - => modCollection.AnonymizedName; + => modCollection.Identity.AnonymizedName; public string TypeName => "Collection"; @@ -28,10 +28,10 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection j.WriteStartObject(); j.WritePropertyName("Version"); j.WriteValue(ModCollection.CurrentVersion); - j.WritePropertyName(nameof(ModCollection.Id)); - j.WriteValue(modCollection.Identifier); - j.WritePropertyName(nameof(ModCollection.Name)); - j.WriteValue(modCollection.Name); + j.WritePropertyName(nameof(ModCollectionIdentity.Id)); + j.WriteValue(modCollection.Identity.Identifier); + j.WritePropertyName(nameof(ModCollectionIdentity.Name)); + j.WriteValue(modCollection.Identity.Name); j.WritePropertyName(nameof(ModCollection.Settings)); // Write all used and unused settings by mod directory name. @@ -57,7 +57,7 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection // Inherit by collection name. j.WritePropertyName("Inheritance"); - x.Serialize(j, modCollection.InheritanceByName ?? modCollection.DirectlyInheritsFrom.Select(c => c.Identifier)); + x.Serialize(j, modCollection.InheritanceByName ?? modCollection.DirectlyInheritsFrom.Select(c => c.Identity.Identifier)); j.WriteEndObject(); } @@ -79,8 +79,8 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection { var obj = JObject.Parse(File.ReadAllText(file.FullName)); version = obj["Version"]?.ToObject() ?? 0; - name = obj[nameof(ModCollection.Name)]?.ToObject() ?? string.Empty; - id = obj[nameof(ModCollection.Id)]?.ToObject() ?? (version == 1 ? Guid.NewGuid() : Guid.Empty); + name = obj[nameof(ModCollectionIdentity.Name)]?.ToObject() ?? string.Empty; + id = obj[nameof(ModCollectionIdentity.Id)]?.ToObject() ?? (version == 1 ? Guid.NewGuid() : Guid.Empty); // Custom deserialization that is converted with the constructor. settings = obj[nameof(ModCollection.Settings)]?.ToObject>() ?? settings; inheritance = obj["Inheritance"]?.ToObject>() ?? inheritance; diff --git a/Penumbra/Collections/ResolveData.cs b/Penumbra/Collections/ResolveData.cs index 8fe160b3..bda877ff 100644 --- a/Penumbra/Collections/ResolveData.cs +++ b/Penumbra/Collections/ResolveData.cs @@ -23,7 +23,7 @@ public readonly struct ResolveData(ModCollection collection, nint gameObject) { } public override string ToString() - => ModCollection.Name; + => ModCollection.Identity.Name; } public static class ResolveDataExtensions diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index aff7f16f..61946978 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -326,7 +326,7 @@ public class CommandHandler : IDisposable, IApiService { _chat.Print(collection == null ? $"The {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}" : string.Empty)} is already unassigned" - : $"{collection.Name} already is the {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); + : $"{collection.Identity.Name} already is the {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); continue; } @@ -363,13 +363,13 @@ public class CommandHandler : IDisposable, IApiService } Print( - $"Removed {oldCollection.Name} as {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); + $"Removed {oldCollection.Identity.Name} as {type.ToName()} Collection assignment {(identifier.IsValid ? $" for {identifier}." : ".")}"); anySuccess = true; continue; } _collectionManager.Active.SetCollection(collection!, type, individualIndex); - Print($"Assigned {collection!.Name} as {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); + Print($"Assigned {collection!.Identity.Name} as {type.ToName()} Collection{(identifier.IsValid ? $" for {identifier}." : ".")}"); } return anySuccess; @@ -440,7 +440,7 @@ public class CommandHandler : IDisposable, IApiService _chat.Print(new SeStringBuilder().AddText("Mod ").AddPurple(mod.Name, true) .AddText("already had the desired state in collection ") - .AddYellow(collection!.Name, true).AddText(".").BuiltString); + .AddYellow(collection!.Identity.Name, true).AddText(".").BuiltString); return false; } @@ -458,7 +458,7 @@ public class CommandHandler : IDisposable, IApiService _collectionEditor.SetModSetting(collection!, mod, groupIndex, setting); Print(() => new SeStringBuilder().AddText("Changed settings of group ").AddGreen(groupName, true).AddText(" in mod ") .AddPurple(mod.Name, true).AddText(" in collection ") - .AddYellow(collection!.Name, true).AddText(".").BuiltString); + .AddYellow(collection!.Identity.Name, true).AddText(".").BuiltString); return true; } @@ -543,7 +543,7 @@ public class CommandHandler : IDisposable, IApiService changes |= HandleModState(state, collection!, mod); if (!changes) - Print(() => new SeStringBuilder().AddText("No mod states were changed in collection ").AddYellow(collection!.Name, true) + Print(() => new SeStringBuilder().AddText("No mod states were changed in collection ").AddYellow(collection!.Identity.Name, true) .AddText(".").BuiltString); return true; @@ -558,7 +558,7 @@ public class CommandHandler : IDisposable, IApiService return true; } - collection = string.Equals(lowerName, ModCollection.Empty.Name, StringComparison.OrdinalIgnoreCase) + collection = string.Equals(lowerName, ModCollection.Empty.Identity.Name, StringComparison.OrdinalIgnoreCase) ? ModCollection.Empty : _collectionManager.Storage.ByIdentifier(lowerName, out var c) ? c @@ -614,7 +614,7 @@ public class CommandHandler : IDisposable, IApiService return false; Print(() => new SeStringBuilder().AddText("Enabled mod ").AddPurple(mod.Name, true).AddText(" in collection ") - .AddYellow(collection.Name, true) + .AddYellow(collection.Identity.Name, true) .AddText(".").BuiltString); return true; @@ -623,7 +623,7 @@ public class CommandHandler : IDisposable, IApiService return false; Print(() => new SeStringBuilder().AddText("Disabled mod ").AddPurple(mod.Name, true).AddText(" in collection ") - .AddYellow(collection.Name, true) + .AddYellow(collection.Identity.Name, true) .AddText(".").BuiltString); return true; @@ -634,7 +634,7 @@ public class CommandHandler : IDisposable, IApiService Print(() => new SeStringBuilder().AddText(setting ? "Enabled mod " : "Disabled mod ").AddPurple(mod.Name, true) .AddText(" in collection ") - .AddYellow(collection.Name, true) + .AddYellow(collection.Identity.Name, true) .AddText(".").BuiltString); return true; @@ -643,7 +643,7 @@ public class CommandHandler : IDisposable, IApiService return false; Print(() => new SeStringBuilder().AddText("Set mod ").AddPurple(mod.Name, true).AddText(" in collection ") - .AddYellow(collection.Name, true) + .AddYellow(collection.Identity.Name, true) .AddText(" to inherit.").BuiltString); return true; } diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs index dcbaedc8..c350c157 100644 --- a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs @@ -30,7 +30,7 @@ public unsafe class AtchCallerHook1 : FastHook, IDispo Task.Result.Original(data, slot, unk, playerModel); _metaState.AtchCollection.Pop(); Penumbra.Log.Excessive( - $"[AtchCaller1] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, identified to {collection.ModCollection.AnonymizedName}."); + $"[AtchCaller1] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, identified to {collection.ModCollection.Identity.AnonymizedName}."); } public void Dispose() diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs index aa2d3f31..af38ce50 100644 --- a/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook2.cs @@ -30,7 +30,7 @@ public unsafe class AtchCallerHook2 : FastHook, IDispo Task.Result.Original(data, slot, unk, playerModel, unk2); _metaState.AtchCollection.Pop(); Penumbra.Log.Excessive( - $"[AtchCaller2] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, {unk2}, identified to {collection.ModCollection.AnonymizedName}."); + $"[AtchCaller2] Invoked on 0x{(ulong)data:X} with {slot}, {unk:X}, 0x{playerModel.Address:X}, {unk2}, identified to {collection.ModCollection.Identity.AnonymizedName}."); } public void Dispose() diff --git a/Penumbra/Interop/PathResolving/MetaState.cs b/Penumbra/Interop/PathResolving/MetaState.cs index e7fc3176..eeae77cc 100644 --- a/Penumbra/Interop/PathResolving/MetaState.cs +++ b/Penumbra/Interop/PathResolving/MetaState.cs @@ -98,7 +98,7 @@ public sealed unsafe class MetaState : IDisposable, IService _lastCreatedCollection = _collectionResolver.IdentifyLastGameObjectCollection(true); if (_lastCreatedCollection.Valid && _lastCreatedCollection.AssociatedGameObject != nint.Zero) _communicator.CreatingCharacterBase.Invoke(_lastCreatedCollection.AssociatedGameObject, - _lastCreatedCollection.ModCollection.Id, (nint)modelCharaId, (nint)customize, (nint)equipData); + _lastCreatedCollection.ModCollection.Identity.Id, (nint)modelCharaId, (nint)customize, (nint)equipData); var decal = new DecalReverter(Config, _characterUtility, _resources, _lastCreatedCollection, UsesDecal(*(uint*)modelCharaId, (nint)customize)); diff --git a/Penumbra/Interop/PathResolving/PathDataHandler.cs b/Penumbra/Interop/PathResolving/PathDataHandler.cs index 25d4f7ea..e0c235a2 100644 --- a/Penumbra/Interop/PathResolving/PathDataHandler.cs +++ b/Penumbra/Interop/PathResolving/PathDataHandler.cs @@ -32,7 +32,7 @@ public static class PathDataHandler /// Create the encoding path for an IMC file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateImc(CiByteString path, ModCollection collection) - => new($"|{collection.LocalId.Id}_{collection.Counters.Imc}_{DiscriminatorString}|{path}"); + => new($"|{collection.Identity.LocalId.Id}_{collection.Counters.Imc}_{DiscriminatorString}|{path}"); /// Create the encoding path for a TMB file. [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -47,17 +47,17 @@ public static class PathDataHandler /// Create the encoding path for an ATCH file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateAtch(CiByteString path, ModCollection collection) - => new($"|{collection.LocalId.Id}_{collection.Counters.Atch}_{DiscriminatorString}|{path}"); + => new($"|{collection.Identity.LocalId.Id}_{collection.Counters.Atch}_{DiscriminatorString}|{path}"); /// Create the encoding path for a MTRL file. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static FullPath CreateMtrl(CiByteString path, ModCollection collection, Utf8GamePath originalPath) - => new($"|{collection.LocalId.Id}_{collection.Counters.Change}_{originalPath.Path.Crc32:X8}_{DiscriminatorString}|{path}"); + => new($"|{collection.Identity.LocalId.Id}_{collection.Counters.Change}_{originalPath.Path.Crc32:X8}_{DiscriminatorString}|{path}"); /// The base function shared by most file types. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static FullPath CreateBase(CiByteString path, ModCollection collection) - => new($"|{collection.LocalId.Id}_{collection.Counters.Change}_{DiscriminatorString}|{path}"); + => new($"|{collection.Identity.LocalId.Id}_{collection.Counters.Change}_{DiscriminatorString}|{path}"); /// Read an additional data blurb and parse it into usable data for all file types but Materials. [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs index a3233cfb..513877d4 100644 --- a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs +++ b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs @@ -26,6 +26,6 @@ public sealed class ImcFilePostProcessor(CollectionStorage collections) : IFileP file.Replace(resource); Penumbra.Log.Verbose( - $"[ResourceLoader] Loaded {originalGamePath} from file and replaced with IMC from collection {collection.AnonymizedName}."); + $"[ResourceLoader] Loaded {originalGamePath} from file and replaced with IMC from collection {collection.Identity.AnonymizedName}."); } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 7e378f41..f5659e7c 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -81,7 +81,7 @@ public class ResourceTreeFactory( var (name, anonymizedName, related) = GetCharacterName(character); var networked = character.EntityId != 0xE0000000; var tree = new ResourceTree(name, anonymizedName, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, - networked, collectionResolveData.ModCollection.Name, collectionResolveData.ModCollection.AnonymizedName); + networked, collectionResolveData.ModCollection.Identity.Name, collectionResolveData.ModCollection.Identity.AnonymizedName); var globalContext = new GlobalResolveContext(metaFileManager, objectIdentifier, collectionResolveData.ModCollection, cache, (flags & Flags.WithUiData) != 0); using (var _ = pathState.EnterInternalResolve()) diff --git a/Penumbra/Mods/TemporaryMod.cs b/Penumbra/Mods/TemporaryMod.cs index b5499624..8fdd09c5 100644 --- a/Penumbra/Mods/TemporaryMod.cs +++ b/Penumbra/Mods/TemporaryMod.cs @@ -63,10 +63,10 @@ public class TemporaryMod : IMod DirectoryInfo? dir = null; try { - dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Name, config.ReplaceNonAsciiOnImport, true); + dir = ModCreator.CreateModFolder(modManager.BasePath, collection.Identity.Name, config.ReplaceNonAsciiOnImport, true); var fileDir = Directory.CreateDirectory(Path.Combine(dir.FullName, "files")); - modManager.DataEditor.CreateMeta(dir, collection.Name, character ?? config.DefaultModAuthor, - $"Mod generated from temporary collection {collection.Id} for {character ?? "Unknown Character"} with name {collection.Name}.", + modManager.DataEditor.CreateMeta(dir, collection.Identity.Name, character ?? config.DefaultModAuthor, + $"Mod generated from temporary collection {collection.Identity.Id} for {character ?? "Unknown Character"} with name {collection.Identity.Name}.", null, null); var mod = new Mod(dir); var defaultMod = mod.Default; @@ -99,11 +99,11 @@ public class TemporaryMod : IMod saveService.ImmediateSaveSync(new ModSaveGroup(dir, defaultMod, config.ReplaceNonAsciiOnImport)); modManager.AddMod(dir, false); Penumbra.Log.Information( - $"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identifier}."); + $"Successfully generated mod {mod.Name} at {mod.ModPath.FullName} for collection {collection.Identity.Identifier}."); } catch (Exception e) { - Penumbra.Log.Error($"Could not save temporary collection {collection.Identifier} to permanent Mod:\n{e}"); + Penumbra.Log.Error($"Could not save temporary collection {collection.Identity.Identifier} to permanent Mod:\n{e}"); if (dir != null && Directory.Exists(dir.FullName)) { try diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 534911df..a2594145 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -245,24 +245,24 @@ public class Penumbra : IDalamudPlugin void PrintCollection(ModCollection c, CollectionCache _) => sb.Append( - $"> **`Collection {c.AnonymizedName + ':',-18}`** Inheritances: `{c.DirectlyInheritsFrom.Count,3}`, Enabled Mods: `{c.ActualSettings.Count(s => s is { Enabled: true }),4}`, Conflicts: `{c.AllConflicts.SelectMany(x => x).Sum(x => x is { HasPriority: true, Solved: true } ? x.Conflicts.Count : 0),5}/{c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority ? x.Conflicts.Count : 0),5}`\n"); + $"> **`Collection {c.Identity.AnonymizedName + ':',-18}`** Inheritances: `{c.DirectlyInheritsFrom.Count,3}`, Enabled Mods: `{c.ActualSettings.Count(s => s is { Enabled: true }),4}`, Conflicts: `{c.AllConflicts.SelectMany(x => x).Sum(x => x is { HasPriority: true, Solved: true } ? x.Conflicts.Count : 0),5}/{c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority ? x.Conflicts.Count : 0),5}`\n"); sb.AppendLine("**Collections**"); sb.Append($"> **`#Collections: `** {_collectionManager.Storage.Count - 1}\n"); sb.Append($"> **`#Temp Collections: `** {_tempCollections.Count}\n"); sb.Append($"> **`Active Collections: `** {_collectionManager.Caches.Count}\n"); - sb.Append($"> **`Base Collection: `** {_collectionManager.Active.Default.AnonymizedName}\n"); - sb.Append($"> **`Interface Collection: `** {_collectionManager.Active.Interface.AnonymizedName}\n"); - sb.Append($"> **`Selected Collection: `** {_collectionManager.Active.Current.AnonymizedName}\n"); + sb.Append($"> **`Base Collection: `** {_collectionManager.Active.Default.Identity.AnonymizedName}\n"); + sb.Append($"> **`Interface Collection: `** {_collectionManager.Active.Interface.Identity.AnonymizedName}\n"); + sb.Append($"> **`Selected Collection: `** {_collectionManager.Active.Current.Identity.AnonymizedName}\n"); foreach (var (type, name, _) in CollectionTypeExtensions.Special) { var collection = _collectionManager.Active.ByType(type); if (collection != null) - sb.Append($"> **`{name,-29}`** {collection.AnonymizedName}\n"); + sb.Append($"> **`{name,-29}`** {collection.Identity.AnonymizedName}\n"); } foreach (var (name, id, collection) in _collectionManager.Active.Individuals.Assignments) - sb.Append($"> **`{id[0].Incognito(name) + ':',-29}`** {collection.AnonymizedName}\n"); + sb.Append($"> **`{id[0].Incognito(name) + ':',-29}`** {collection.Identity.AnonymizedName}\n"); foreach (var collection in _collectionManager.Caches.Active) PrintCollection(collection, collection._cache!); diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index 5ba57cf4..f58eb891 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -27,8 +27,8 @@ public class ConfigMigrationService(SaveService saveService, BackupService backu private Configuration _config = null!; private JObject _data = null!; - public string CurrentCollection = ModCollection.DefaultCollectionName; - public string DefaultCollection = ModCollection.DefaultCollectionName; + public string CurrentCollection = ModCollectionIdentity.DefaultCollectionName; + public string DefaultCollection = ModCollectionIdentity.DefaultCollectionName; public string ForcedCollection = string.Empty; public Dictionary CharacterCollections = []; public Dictionary ModSortOrder = []; @@ -346,7 +346,7 @@ public class ConfigMigrationService(SaveService saveService, BackupService backu if (!collectionJson.Exists) return; - var defaultCollectionFile = new FileInfo(saveService.FileNames.CollectionFile(ModCollection.DefaultCollectionName)); + var defaultCollectionFile = new FileInfo(saveService.FileNames.CollectionFile(ModCollectionIdentity.DefaultCollectionName)); if (defaultCollectionFile.Exists) return; @@ -380,7 +380,7 @@ public class ConfigMigrationService(SaveService saveService, BackupService backu var emptyStorage = new ModStorage(); // Only used for saving and immediately discarded, so the local collection id here is irrelevant. - var collection = ModCollection.CreateFromData(saveService, emptyStorage, Guid.NewGuid(), ModCollection.DefaultCollectionName, LocalCollectionId.Zero, 0, 1, dict, []); + var collection = ModCollection.CreateFromData(saveService, emptyStorage, ModCollectionIdentity.New(ModCollectionIdentity.DefaultCollectionName, LocalCollectionId.Zero, 1), 0, dict, []); saveService.ImmediateSaveSync(new ModCollectionSave(emptyStorage, collection)); } catch (Exception e) diff --git a/Penumbra/Services/CrashHandlerService.cs b/Penumbra/Services/CrashHandlerService.cs index 9103b29c..4814795c 100644 --- a/Penumbra/Services/CrashHandlerService.cs +++ b/Penumbra/Services/CrashHandlerService.cs @@ -240,7 +240,7 @@ public sealed class CrashHandlerService : IDisposable, IService var name = GetActorName(character); lock (_eventWriter) { - _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Id, type); + _eventWriter?.AnimationFuncInvoked.WriteLine(character, name.Span, collection.Identity.Id, type); } } catch (Exception ex) @@ -293,7 +293,7 @@ public sealed class CrashHandlerService : IDisposable, IService var name = GetActorName(resolveData.AssociatedGameObject); lock (_eventWriter) { - _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Id, + _eventWriter!.FileLoaded.WriteLine(resolveData.AssociatedGameObject, name.Span, resolveData.ModCollection.Identity.Id, manipulatedPath.Value.InternalName.Span, originalPath.Path.Span); } } diff --git a/Penumbra/Services/FilenameService.cs b/Penumbra/Services/FilenameService.cs index 817af0d2..ee096109 100644 --- a/Penumbra/Services/FilenameService.cs +++ b/Penumbra/Services/FilenameService.cs @@ -24,7 +24,7 @@ public class FilenameService(IDalamudPluginInterface pi) : IService /// Obtain the path of a collection file given its name. public string CollectionFile(ModCollection collection) - => CollectionFile(collection.Identifier); + => CollectionFile(collection.Identity.Identifier); /// Obtain the path of a collection file given its name. public string CollectionFile(string collectionName) diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index 3972e350..0e1408c5 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -25,7 +25,7 @@ public class CollectionSelectHeader : IUiService _selection = selection; _resolver = resolver; _activeCollections = collectionManager.Active; - _collectionCombo = new CollectionCombo(collectionManager, () => collectionManager.Storage.OrderBy(c => c.Name).ToList()); + _collectionCombo = new CollectionCombo(collectionManager, () => collectionManager.Storage.OrderBy(c => c.Identity.Name).ToList()); } /// Draw the header line that can quick switch between collections. @@ -77,10 +77,10 @@ public class CollectionSelectHeader : IUiService return CheckCollection(collection) switch { CollectionState.Empty => (collection, "None", "The base collection is configured to use no mods.", true), - CollectionState.Selected => (collection, collection.Name, + CollectionState.Selected => (collection, collection.Identity.Name, "The configured base collection is already selected as the current collection.", true), - CollectionState.Available => (collection, collection.Name, - $"Select the configured base collection {collection.Name} as the current collection.", false), + CollectionState.Available => (collection, collection.Identity.Name, + $"Select the configured base collection {collection.Identity.Name} as the current collection.", false), _ => throw new Exception("Can not happen."), }; } @@ -91,10 +91,11 @@ public class CollectionSelectHeader : IUiService return CheckCollection(collection) switch { CollectionState.Empty => (collection, "None", "The loaded player character is configured to use no mods.", true), - CollectionState.Selected => (collection, collection.Name, + CollectionState.Selected => (collection, collection.Identity.Name, "The collection configured to apply to the loaded player character is already selected as the current collection.", true), - CollectionState.Available => (collection, collection.Name, - $"Select the collection {collection.Name} that applies to the loaded player character as the current collection.", false), + CollectionState.Available => (collection, collection.Identity.Name, + $"Select the collection {collection.Identity.Name} that applies to the loaded player character as the current collection.", + false), _ => throw new Exception("Can not happen."), }; } @@ -105,10 +106,10 @@ public class CollectionSelectHeader : IUiService return CheckCollection(collection) switch { CollectionState.Empty => (collection, "None", "The interface collection is configured to use no mods.", true), - CollectionState.Selected => (collection, collection.Name, + CollectionState.Selected => (collection, collection.Identity.Name, "The configured interface collection is already selected as the current collection.", true), - CollectionState.Available => (collection, collection.Name, - $"Select the configured interface collection {collection.Name} as the current collection.", false), + CollectionState.Available => (collection, collection.Identity.Name, + $"Select the configured interface collection {collection.Identity.Name} as the current collection.", false), _ => throw new Exception("Can not happen."), }; } @@ -120,8 +121,8 @@ public class CollectionSelectHeader : IUiService { CollectionState.Unavailable => (null, "Not Inherited", "The settings of the selected mod are not inherited from another collection.", true), - CollectionState.Available => (collection, collection!.Name, - $"Select the collection {collection!.Name} from which the selected mod inherits its settings as the current collection.", + CollectionState.Available => (collection, collection!.Identity.Name, + $"Select the collection {collection!.Identity.Name} from which the selected mod inherits its settings as the current collection.", false), _ => throw new Exception("Can not happen."), }; diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index 1670be5e..0259713f 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -29,13 +29,13 @@ public sealed class CollectionCombo(CollectionManager manager, Func obj.Name; + => obj.Identity.Name; protected override void DrawCombo(string label, string preview, string tooltip, int currentSelected, float previewWidth, float itemHeight, ImGuiComboFlags flags) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 914f10d9..cab34b10 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -221,16 +221,16 @@ public sealed class CollectionPanel( ImGui.SameLine(); ImGui.BeginGroup(); using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); - var name = _newName ?? collection.Name; - var identifier = collection.Identifier; + var name = _newName ?? collection.Identity.Name; + var identifier = collection.Identity.Identifier; var width = ImGui.GetContentRegionAvail().X; var fileName = saveService.FileNames.CollectionFile(collection); ImGui.SetNextItemWidth(width); if (ImGui.InputText("##name", ref name, 128)) _newName = name; - if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null && _newName != collection.Name) + if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null && _newName != collection.Identity.Name) { - collection.Name = _newName; + collection.Identity.Name = _newName; saveService.QueueSave(new ModCollectionSave(mods, collection)); selector.RestoreCollections(); _newName = null; @@ -242,7 +242,7 @@ public sealed class CollectionPanel( using (ImRaii.PushFont(UiBuilder.MonoFont)) { - if (ImGui.Button(collection.Identifier, new Vector2(width, 0))) + if (ImGui.Button(collection.Identity.Identifier, new Vector2(width, 0))) try { Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true }); @@ -289,9 +289,9 @@ public sealed class CollectionPanel( _active.SetCollection(null, type, _active.Individuals.GetGroup(identifier)); } - foreach (var coll in _collections.OrderBy(c => c.Name)) + foreach (var coll in _collections.OrderBy(c => c.Identity.Name)) { - if (coll != collection && ImGui.MenuItem($"Use {coll.Name}.")) + if (coll != collection && ImGui.MenuItem($"Use {coll.Identity.Name}.")) _active.SetCollection(coll, type, _active.Individuals.GetGroup(identifier)); } } @@ -418,7 +418,7 @@ public sealed class CollectionPanel( private string Name(ModCollection? collection) => collection == null ? "Unassigned" : collection == ModCollection.Empty ? "Use No Mods" : - incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; + incognito.IncognitoMode ? collection.Identity.AnonymizedName : collection.Identity.Name; private void DrawIndividualButton(string intro, Vector2 width, string tooltip, char suffix, params ActorIdentifier[] identifiers) { diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index 024873bf..57429531 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -69,7 +69,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl } protected override bool Filtered(int idx) - => !Items[idx].Name.Contains(Filter, StringComparison.OrdinalIgnoreCase); + => !Items[idx].Identity.Name.Contains(Filter, StringComparison.OrdinalIgnoreCase); private const string PayloadString = "Collection"; @@ -111,12 +111,12 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl } private string Name(ModCollection collection) - => _incognito.IncognitoMode || collection.Name.Length == 0 ? collection.AnonymizedName : collection.Name; + => _incognito.IncognitoMode || collection.Identity.Name.Length == 0 ? collection.Identity.AnonymizedName : collection.Identity.Name; public void RestoreCollections() { Items.Clear(); - foreach (var c in _storage.OrderBy(c => c.Name)) + foreach (var c in _storage.OrderBy(c => c.Identity.Name)) Items.Add(c); SetFilterDirty(); SetCurrent(_active.Current); diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index 418fe52c..a4d60b13 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -93,7 +93,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService /// private void DrawInheritedChildren(ModCollection collection) { - using var id = ImRaii.PushId(collection.Index); + using var id = ImRaii.PushId(collection.Identity.Index); using var indent = ImRaii.PushIndent(); // Get start point for the lines (top of the selector). @@ -114,7 +114,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService _seenInheritedCollections.Contains(inheritance)); _seenInheritedCollections.Add(inheritance); - ImRaii.TreeNode($"{Name(inheritance)}###{inheritance.Id}", + ImRaii.TreeNode($"{Name(inheritance)}###{inheritance.Identity.Id}", ImGuiTreeNodeFlags.NoTreePushOnOpen | ImGuiTreeNodeFlags.Leaf | ImGuiTreeNodeFlags.Bullet); var (minRect, maxRect) = (ImGui.GetItemRectMin(), ImGui.GetItemRectMax()); DrawInheritanceTreeClicks(inheritance, false); @@ -140,7 +140,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.HandledConflictMod.Value(), _seenInheritedCollections.Contains(collection)); _seenInheritedCollections.Add(collection); - using var tree = ImRaii.TreeNode($"{Name(collection)}###{collection.Name}", ImGuiTreeNodeFlags.NoTreePushOnOpen); + using var tree = ImRaii.TreeNode($"{Name(collection)}###{collection.Identity.Name}", ImGuiTreeNodeFlags.NoTreePushOnOpen); color.Pop(); DrawInheritanceTreeClicks(collection, true); DrawInheritanceDropSource(collection); @@ -252,7 +252,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService foreach (var collection in _collections .Where(c => InheritanceManager.CheckValidInheritance(_active.Current, c) == InheritanceManager.ValidInheritance.Valid) - .OrderBy(c => c.Name)) + .OrderBy(c => c.Identity.Name)) { if (ImGui.Selectable(Name(collection), _newInheritance == collection)) _newInheritance = collection; @@ -312,5 +312,5 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService } private string Name(ModCollection collection) - => incognito.IncognitoMode ? collection.AnonymizedName : collection.Name; + => incognito.IncognitoMode ? collection.Identity.AnonymizedName : collection.Identity.Name; } diff --git a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs index b7648428..89a7d765 100644 --- a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs @@ -56,7 +56,7 @@ public class ModPanelCollectionsTab(CollectionManager manager, ModFileSystemSele foreach (var ((collection, parent, color, state), idx) in _cache.WithIndex()) { using var id = ImUtf8.PushId(idx); - ImUtf8.DrawTableColumn(collection.Name); + ImUtf8.DrawTableColumn(collection.Identity.Name); ImGui.TableNextColumn(); ImUtf8.Text(ToText(state), color); @@ -65,7 +65,7 @@ public class ModPanelCollectionsTab(CollectionManager manager, ModFileSystemSele { if (context) { - ImUtf8.Text(collection.Name); + ImUtf8.Text(collection.Identity.Name); ImGui.Separator(); using (ImRaii.Disabled(state is ModState.Enabled && parent == collection)) { @@ -95,7 +95,7 @@ public class ModPanelCollectionsTab(CollectionManager manager, ModFileSystemSele } } - ImUtf8.DrawTableColumn(parent == collection ? string.Empty : parent.Name); + ImUtf8.DrawTableColumn(parent == collection ? string.Empty : parent.Identity.Name); } } diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 8d889c3b..261f6e92 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -67,7 +67,7 @@ public class ModPanelSettingsTab( using var color = ImRaii.PushColor(ImGuiCol.Button, Colors.PressEnterWarningBg); var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); - if (ImGui.Button($"These settings are inherited from {selection.Collection.Name}.", width)) + if (ImGui.Button($"These settings are inherited from {selection.Collection.Identity.Name}.", width)) collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, false); ImGuiUtil.HoverTooltip("You can click this button to copy the current settings to the current selection.\n" diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index d432e97e..0f72efff 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -241,7 +241,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService { var pathString = manipulatedPath != null ? $"custom file {name2} instead of {name}" : name; Penumbra.Log.Information( - $"[ResourceLoader] [LOAD] [{handle->FileType}] Loaded {pathString} to 0x{(ulong)handle:X} using collection {data.ModCollection.AnonymizedName} for {Name(data, "no associated object.")} (Refcount {handle->RefCount}) "); + $"[ResourceLoader] [LOAD] [{handle->FileType}] Loaded {pathString} to 0x{(ulong)handle:X} using collection {data.ModCollection.Identity.AnonymizedName} for {Name(data, "no associated object.")} (Refcount {handle->RefCount}) "); } } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 88b7120d..7ac3cb99 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -167,7 +167,7 @@ internal sealed class ResourceWatcherTable : Table => 80 * UiHelpers.Scale; public override string ToName(Record item) - => item.Collection?.Name ?? string.Empty; + => (item.Collection != null ? item.Collection.Identity.Name : null) ?? string.Empty; } private sealed class ObjectColumn : ColumnString diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 95afb10f..d6a9f05a 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -204,7 +204,7 @@ public class DebugTab : Window, ITab, IUiService if (collection.HasCache) { using var color = PushColor(ImGuiCol.Text, ColorId.FolderExpanded.Value()); - using var node = TreeNode($"{collection.Name} (Change Counter {collection.Counters.Change})###{collection.Name}"); + using var node = TreeNode($"{collection.Identity.Name} (Change Counter {collection.Counters.Change})###{collection.Identity.Name}"); if (!node) continue; @@ -239,7 +239,7 @@ public class DebugTab : Window, ITab, IUiService else { using var color = PushColor(ImGuiCol.Text, ColorId.UndefinedMod.Value()); - TreeNode($"{collection.AnonymizedName} (Change Counter {collection.Counters.Change})", + TreeNode($"{collection.Identity.AnonymizedName} (Change Counter {collection.Counters.Change})", ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.Leaf).Dispose(); } } @@ -265,9 +265,9 @@ public class DebugTab : Window, ITab, IUiService { PrintValue("Penumbra Version", $"{_validityChecker.Version} {DebugVersionString}"); PrintValue("Git Commit Hash", _validityChecker.CommitHash); - PrintValue(TutorialService.SelectedCollection, _collectionManager.Active.Current.Name); + PrintValue(TutorialService.SelectedCollection, _collectionManager.Active.Current.Identity.Name); PrintValue(" has Cache", _collectionManager.Active.Current.HasCache.ToString()); - PrintValue(TutorialService.DefaultCollection, _collectionManager.Active.Default.Name); + PrintValue(TutorialService.DefaultCollection, _collectionManager.Active.Default.Identity.Name); PrintValue(" has Cache", _collectionManager.Active.Default.HasCache.ToString()); PrintValue("Mod Manager BasePath", _modManager.BasePath.Name); PrintValue("Mod Manager BasePath-Full", _modManager.BasePath.FullName); @@ -518,7 +518,7 @@ public class DebugTab : Window, ITab, IUiService return; ImGui.TextUnformatted( - $"Last Game Object: 0x{_collectionResolver.IdentifyLastGameObjectCollection(true).AssociatedGameObject:X} ({_collectionResolver.IdentifyLastGameObjectCollection(true).ModCollection.Name})"); + $"Last Game Object: 0x{_collectionResolver.IdentifyLastGameObjectCollection(true).AssociatedGameObject:X} ({_collectionResolver.IdentifyLastGameObjectCollection(true).ModCollection.Identity.Name})"); using (var drawTree = TreeNode("Draw Object to Object")) { if (drawTree) @@ -545,7 +545,7 @@ public class DebugTab : Window, ITab, IUiService ImGui.TextUnformatted(name); ImGui.TableNextColumn(); var collection = _collectionResolver.IdentifyCollection(gameObject, true); - ImGui.TextUnformatted(collection.ModCollection.Name); + ImGui.TextUnformatted(collection.ModCollection.Identity.Name); } } } @@ -561,7 +561,7 @@ public class DebugTab : Window, ITab, IUiService ImGui.TableNextColumn(); ImGui.TextUnformatted($"{data.AssociatedGameObject:X}"); ImGui.TableNextColumn(); - ImGui.TextUnformatted(data.ModCollection.Name); + ImGui.TextUnformatted(data.ModCollection.Identity.Name); } } } @@ -574,12 +574,12 @@ public class DebugTab : Window, ITab, IUiService if (table) { ImGuiUtil.DrawTableColumn("Current Mtrl Data"); - ImGuiUtil.DrawTableColumn(_subfileHelper.MtrlData.ModCollection.Name); + ImGuiUtil.DrawTableColumn(_subfileHelper.MtrlData.ModCollection.Identity.Name); ImGuiUtil.DrawTableColumn($"0x{_subfileHelper.MtrlData.AssociatedGameObject:X}"); ImGui.TableNextColumn(); ImGuiUtil.DrawTableColumn("Current Avfx Data"); - ImGuiUtil.DrawTableColumn(_subfileHelper.AvfxData.ModCollection.Name); + ImGuiUtil.DrawTableColumn(_subfileHelper.AvfxData.ModCollection.Identity.Name); ImGuiUtil.DrawTableColumn($"0x{_subfileHelper.AvfxData.AssociatedGameObject:X}"); ImGui.TableNextColumn(); @@ -591,7 +591,7 @@ public class DebugTab : Window, ITab, IUiService foreach (var (resource, resolve) in _subfileHelper) { ImGuiUtil.DrawTableColumn($"0x{resource:X}"); - ImGuiUtil.DrawTableColumn(resolve.ModCollection.Name); + ImGuiUtil.DrawTableColumn(resolve.ModCollection.Identity.Name); ImGuiUtil.DrawTableColumn($"0x{resolve.AssociatedGameObject:X}"); ImGuiUtil.DrawTableColumn($"{((ResourceHandle*)resource)->FileName()}"); } @@ -611,7 +611,7 @@ public class DebugTab : Window, ITab, IUiService ImGuiUtil.DrawTableColumn($"{((GameObject*)address)->ObjectIndex}"); ImGuiUtil.DrawTableColumn($"0x{address:X}"); ImGuiUtil.DrawTableColumn(identifier.ToString()); - ImGuiUtil.DrawTableColumn(collection.Name); + ImGuiUtil.DrawTableColumn(collection.Identity.Name); } } } diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 87338bdb..c226098d 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -77,12 +77,12 @@ public class ModsTab( { Penumbra.Log.Error($"Exception thrown during ModPanel Render:\n{e}"); Penumbra.Log.Error($"{modManager.Count} Mods\n" - + $"{_activeCollections.Current.AnonymizedName} Current Collection\n" + + $"{_activeCollections.Current.Identity.AnonymizedName} Current Collection\n" + $"{_activeCollections.Current.Settings.Count} Settings\n" + $"{selector.SortMode.Name} Sort Mode\n" + $"{selector.SelectedLeaf?.Name ?? "NULL"} Selected Leaf\n" + $"{selector.Selected?.Name ?? "NULL"} Selected Mod\n" - + $"{string.Join(", ", _activeCollections.Current.DirectlyInheritsFrom.Select(c => c.AnonymizedName))} Inheritances\n"); + + $"{string.Join(", ", _activeCollections.Current.DirectlyInheritsFrom.Select(c => c.Identity.AnonymizedName))} Inheritances\n"); } } diff --git a/Penumbra/UI/TutorialService.cs b/Penumbra/UI/TutorialService.cs index 7d2a0d2a..69f2b616 100644 --- a/Penumbra/UI/TutorialService.cs +++ b/Penumbra/UI/TutorialService.cs @@ -83,14 +83,14 @@ public class TutorialService : IUiService + "Go here after setting up your root folder to continue the tutorial!") .Register("Initial Setup, Step 4: Managing Collections", "On the left, we have the collection selector. Here, we can create new collections - either empty ones or by duplicating existing ones - and delete any collections not needed anymore.\n" - + $"There will always be one collection called {ModCollection.DefaultCollectionName} that can not be deleted.") + + $"There will always be one collection called {ModCollectionIdentity.DefaultCollectionName} that can not be deleted.") .Register($"Initial Setup, Step 5: {SelectedCollection}", $"The {SelectedCollection} is the one we highlighted in the selector. It is the collection we are currently looking at and editing.\nAny changes we make in our mod settings later in the next tab will edit this collection.\n" - + $"We should already have the collection named {ModCollection.DefaultCollectionName} selected, and for our simple setup, we do not need to do anything here.\n\n") + + $"We should already have the collection named {ModCollectionIdentity.DefaultCollectionName} selected, and for our simple setup, we do not need to do anything here.\n\n") .Register("Initial Setup, Step 6: Simple Assignments", "Aside from being a collection of settings, we can also assign collections to different functions. This is used to make different mods apply to different characters.\n" + "The Simple Assignments panel shows you the possible assignments that are enough for most people along with descriptions.\n" - + $"If you are just starting, you can see that the {ModCollection.DefaultCollectionName} is currently assigned to {CollectionType.Default.ToName()} and {CollectionType.Interface.ToName()}.\n" + + $"If you are just starting, you can see that the {ModCollectionIdentity.DefaultCollectionName} is currently assigned to {CollectionType.Default.ToName()} and {CollectionType.Interface.ToName()}.\n" + "You can also assign 'Use No Mods' instead of a collection by clicking on the function buttons.") .Register("Individual Assignments", "In the Individual Assignments panel, you can manually create assignments for very specific characters or monsters, not just yourself or ones you can currently target.") From 98a89bb2b4b67a2767773ec0f18c9b346028dc07 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 16:02:50 +0100 Subject: [PATCH 1021/1381] Current state. --- Penumbra/Api/Api/ModSettingsApi.cs | 154 ++++++++++++++- Penumbra/Collections/Cache/CollectionCache.cs | 6 +- .../Cache/CollectionCacheManager.cs | 16 +- .../Collections/Manager/ActiveCollections.cs | 2 +- .../Collections/Manager/CollectionEditor.cs | 40 ++-- .../Collections/Manager/CollectionStorage.cs | 28 +-- .../Collections/Manager/InheritanceManager.cs | 46 ++--- .../Manager/ModCollectionMigration.cs | 8 +- Penumbra/Collections/ModCollection.cs | 183 +++++++----------- .../Collections/ModCollectionInheritance.cs | 92 +++++++++ Penumbra/Collections/ModCollectionSave.cs | 12 +- Penumbra/Collections/ModSettingProvider.cs | 98 ++++++++++ Penumbra/CommandHandler.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceNode.cs | 2 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 3 + Penumbra/Mods/ModSelection.cs | 21 +- Penumbra/Mods/Settings/ModSettings.cs | 2 +- Penumbra/Penumbra.cs | 2 +- Penumbra/Services/ConfigMigrationService.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 4 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 21 +- Penumbra/UI/CollectionTab/InheritanceUi.cs | 16 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 28 ++- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 37 ++-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 40 +++- Penumbra/UI/Tabs/ModsTab.cs | 2 +- 28 files changed, 606 insertions(+), 265 deletions(-) create mode 100644 Penumbra/Collections/ModCollectionInheritance.cs create mode 100644 Penumbra/Collections/ModSettingProvider.cs diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 3dc900fc..4027975b 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -1,4 +1,5 @@ using OtterGui; +using OtterGui.Log; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; @@ -24,18 +25,20 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable private readonly CollectionManager _collectionManager; private readonly CollectionEditor _collectionEditor; private readonly CommunicatorService _communicator; + private readonly ApiHelpers _helpers; public ModSettingsApi(CollectionResolver collectionResolver, ModManager modManager, CollectionManager collectionManager, CollectionEditor collectionEditor, - CommunicatorService communicator) + CommunicatorService communicator, ApiHelpers helpers) { _collectionResolver = collectionResolver; _modManager = modManager; _collectionManager = collectionManager; _collectionEditor = collectionEditor; _communicator = communicator; + _helpers = helpers; _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ApiModSettings); _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); _communicator.ModOptionChanged.Subscribe(OnModOptionEdited, ModOptionChanged.Priority.Api); @@ -63,11 +66,6 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable return new AvailableModSettings(dict); } - public Dictionary? GetAvailableModSettingsBase(string modDirectory, string modName) - => _modManager.TryGetMod(modDirectory, modName, out var mod) - ? mod.Groups.ToDictionary(g => g.Name, g => (g.Options.Select(o => o.Name).ToArray(), (int)g.Type)) - : null; - public (PenumbraApiEc, (bool, int, Dictionary>, bool)?) GetCurrentModSettings(Guid collectionId, string modDirectory, string modName, bool ignoreInheritance) { @@ -80,14 +78,14 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable var settings = collection.Identity.Id == Guid.Empty ? null : ignoreInheritance - ? collection.Settings[mod.Index] - : collection[mod.Index].Settings; + ? collection.GetOwnSettings(mod.Index) + : collection.GetInheritedSettings(mod.Index).Settings; if (settings == null) return (PenumbraApiEc.Success, null); var (enabled, priority, dict) = settings.ConvertToShareable(mod); return (PenumbraApiEc.Success, - (enabled, priority.Value, dict, collection.Settings[mod.Index] == null)); + (enabled, priority.Value, dict, collection.GetOwnSettings(mod.Index) is null)); } public PenumbraApiEc TryInheritMod(Guid collectionId, string modDirectory, string modName, bool inherit) @@ -211,11 +209,147 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable return ApiHelpers.Return(PenumbraApiEc.Success, args); } + public PenumbraApiEc SetTemporaryModSetting(Guid collectionId, string modDirectory, string modName, bool enabled, int priority, + IReadOnlyDictionary> options, string source, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Enabled", enabled, + "Priority", priority, "Options", options, "Source", source, "Key", key); + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return SetTemporaryModSetting(args, collection, modDirectory, modName, enabled, priority, options, source, key); + } + + public PenumbraApiEc TemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, bool enabled, int priority, + IReadOnlyDictionary> options, string source, int key) + { + return PenumbraApiEc.Success; + } + + private PenumbraApiEc SetTemporaryModSetting(in LazyString args, ModCollection collection, string modDirectory, string modName, + bool enabled, int priority, + IReadOnlyDictionary> options, string source, int key) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + if (collection.GetTempSettings(mod.Index) is { } settings && settings.Lock != 0 && settings.Lock != key) + return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); + + settings = new TemporaryModSettings + { + Enabled = enabled, + Priority = new ModPriority(priority), + Lock = key, + Source = source, + Settings = SettingList.Default(mod), + }; + + foreach (var (groupName, optionNames) in options) + { + var groupIdx = mod.Groups.IndexOf(g => g.Name == groupName); + if (groupIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionGroupMissing, args); + + var setting = Setting.Zero; + switch (mod.Groups[groupIdx]) + { + case { Behaviour: GroupDrawBehaviour.SingleSelection } single: + { + var optionIdx = optionNames.Count == 0 ? -1 : single.Options.IndexOf(o => o.Name == optionNames[^1]); + if (optionIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); + + setting = Setting.Single(optionIdx); + break; + } + case { Behaviour: GroupDrawBehaviour.MultiSelection } multi: + { + foreach (var name in optionNames) + { + var optionIdx = multi.Options.IndexOf(o => o.Name == name); + if (optionIdx < 0) + return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); + + setting |= Setting.Multi(optionIdx); + } + + break; + } + } + + settings.Settings[groupIdx] = setting; + } + + collection.Settings.SetTemporary(mod.Index, settings); + return ApiHelpers.Return(PenumbraApiEc.Success, args); + } + + public PenumbraApiEc RemoveTemporaryModSettings(Guid collectionId, string modDirectory, string modName, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Key", key); + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return RemoveTemporaryModSettings(args, collection, modDirectory, modName, key); + } + + private PenumbraApiEc RemoveTemporaryModSettings(in LazyString args, ModCollection collection, string modDirectory, string modName, int key) + { + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + if (collection.GetTempSettings(mod.Index) is not { } settings) + return ApiHelpers.Return(PenumbraApiEc.NothingChanged, args); + + if (settings.Lock != 0 && settings.Lock != key) + return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); + + collection.Settings.SetTemporary(mod.Index, null); + return ApiHelpers.Return(PenumbraApiEc.Success, args); + } + + public PenumbraApiEc RemoveTemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, int key) + { + return PenumbraApiEc.Success; + } + + public PenumbraApiEc RemoveAllTemporaryModSettings(Guid collectionId, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "Key", key); + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return RemoveAllTemporaryModSettings(args, collection, key); + } + + public PenumbraApiEc RemoveAllTemporaryModSettingsPlayer(int objectIndex, int key) + { + return PenumbraApiEc.Success; + } + + private PenumbraApiEc RemoveAllTemporaryModSettings(in LazyString args, ModCollection collection, int key) + { + var numRemoved = 0; + for (var i = 0; i < collection.Settings.Count; ++i) + { + if (collection.GetTempSettings(i) is { } settings && (settings.Lock == 0 || settings.Lock == key)) + { + collection.Settings.SetTemporary(i, null); + ++numRemoved; + } + } + + return ApiHelpers.Return(numRemoved > 0 ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, args); + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void TriggerSettingEdited(Mod mod) { var collection = _collectionResolver.PlayerCollection(); - var (settings, parent) = collection[mod.Index]; + var (settings, parent) = collection.GetActualSettings(mod.Index); if (settings is { Enabled: true }) ModSettingChanged?.Invoke(ModSettingChange.Edited, collection.Identity.Id, mod.Identifier, parent != collection); } diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index ad902aac..8ca9aa36 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -260,7 +260,7 @@ public sealed class CollectionCache : IDisposable if (mod.Index < 0) return mod.GetData(); - var settings = _collection[mod.Index].Settings; + var settings = _collection.GetActualSettings(mod.Index).Settings; return settings is not { Enabled: true } ? AppliedModData.Empty : mod.GetData(settings); @@ -342,8 +342,8 @@ public sealed class CollectionCache : IDisposable // Returns if the added mod takes priority before the existing mod. private bool AddConflict(object data, IMod addedMod, IMod existingMod) { - var addedPriority = addedMod.Index >= 0 ? _collection[addedMod.Index].Settings!.Priority : addedMod.Priority; - var existingPriority = existingMod.Index >= 0 ? _collection[existingMod.Index].Settings!.Priority : existingMod.Priority; + var addedPriority = addedMod.Index >= 0 ? _collection.GetActualSettings(addedMod.Index).Settings!.Priority : addedMod.Priority; + var existingPriority = existingMod.Index >= 0 ? _collection.GetActualSettings(existingMod.Index).Settings!.Priority : existingMod.Priority; if (existingPriority < addedPriority) { diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 0a851154..839c0376 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -231,11 +231,11 @@ public class CollectionCacheManager : IDisposable, IService { case ModPathChangeType.Deleted: case ModPathChangeType.StartingReload: - foreach (var collection in _storage.Where(c => c.HasCache && c[mod.Index].Settings?.Enabled == true)) + foreach (var collection in _storage.Where(c => c.HasCache && c.GetActualSettings(mod.Index).Settings?.Enabled == true)) collection._cache!.RemoveMod(mod, true); break; case ModPathChangeType.Moved: - foreach (var collection in _storage.Where(c => c.HasCache && c[mod.Index].Settings?.Enabled == true)) + foreach (var collection in _storage.Where(c => c.HasCache && c.GetActualSettings(mod.Index).Settings?.Enabled == true)) collection._cache!.ReloadMod(mod, true); break; } @@ -246,7 +246,7 @@ public class CollectionCacheManager : IDisposable, IService if (type is not (ModPathChangeType.Added or ModPathChangeType.Reloaded)) return; - foreach (var collection in _storage.Where(c => c.HasCache && c[mod.Index].Settings?.Enabled == true)) + foreach (var collection in _storage.Where(c => c.HasCache && c.GetActualSettings(mod.Index).Settings?.Enabled == true)) collection._cache!.AddMod(mod, true); } @@ -273,7 +273,7 @@ public class CollectionCacheManager : IDisposable, IService { if (type is ModOptionChangeType.PrepareChange) { - foreach (var collection in _storage.Where(collection => collection.HasCache && collection[mod.Index].Settings is { Enabled: true })) + foreach (var collection in _storage.Where(collection => collection.HasCache && collection.GetActualSettings(mod.Index).Settings is { Enabled: true })) collection._cache!.RemoveMod(mod, false); return; @@ -284,7 +284,7 @@ public class CollectionCacheManager : IDisposable, IService if (!recomputeList) return; - foreach (var collection in _storage.Where(collection => collection.HasCache && collection[mod.Index].Settings is { Enabled: true })) + foreach (var collection in _storage.Where(collection => collection.HasCache && collection.GetActualSettings(mod.Index).Settings is { Enabled: true })) { if (justAdd) collection._cache!.AddMod(mod, true); @@ -317,7 +317,7 @@ public class CollectionCacheManager : IDisposable, IService cache.AddMod(mod!, true); else if (oldValue == Setting.True) cache.RemoveMod(mod!, true); - else if (collection[mod!.Index].Settings?.Enabled == true) + else if (collection.GetActualSettings(mod!.Index).Settings?.Enabled == true) cache.ReloadMod(mod!, true); else cache.RemoveMod(mod!, true); @@ -329,8 +329,8 @@ public class CollectionCacheManager : IDisposable, IService break; case ModSettingChange.Setting: - if (collection[mod!.Index].Settings?.Enabled == true) - cache.ReloadMod(mod!, true); + if (collection.GetActualSettings(mod!.Index).Settings?.Enabled == true) + cache.ReloadMod(mod, true); break; case ModSettingChange.MultiInheritance: diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 07fcb430..2ced8ad6 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -282,7 +282,7 @@ public class ActiveCollections : ISavable, IDisposable, IService .Prepend(Interface) .Prepend(Default) .Concat(Individuals.Assignments.Select(kvp => kvp.Collection)) - .SelectMany(c => c.GetFlattenedInheritance()).Contains(Current); + .SelectMany(c => c.Inheritance.FlatHierarchy).Contains(Current); /// Save if any of the active collections is changed and set new collections to Current. private void OnCollectionChange(CollectionType collectionType, ModCollection? oldCollection, ModCollection? newCollection, string _3) diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index caff2c86..66578a95 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -26,12 +26,12 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu /// public bool SetModState(ModCollection collection, Mod mod, bool newValue) { - var oldValue = collection.Settings[mod.Index]?.Enabled ?? collection[mod.Index].Settings?.Enabled ?? false; + var oldValue = collection.GetInheritedSettings(mod.Index).Settings?.Enabled ?? false; if (newValue == oldValue) return false; var inheritance = FixInheritance(collection, mod, false); - ((List)collection.Settings)[mod.Index]!.Enabled = newValue; + collection.GetOwnSettings(mod.Index)!.Enabled = newValue; InvokeChange(collection, ModSettingChange.EnableState, mod, inheritance ? Setting.Indefinite : newValue ? Setting.False : Setting.True, 0); return true; @@ -55,13 +55,13 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu var changes = false; foreach (var mod in mods) { - var oldValue = collection.Settings[mod.Index]?.Enabled; + var oldValue = collection.GetOwnSettings(mod.Index)?.Enabled; if (newValue == oldValue) continue; FixInheritance(collection, mod, false); - ((List)collection.Settings)[mod.Index]!.Enabled = newValue; - changes = true; + collection.GetOwnSettings(mod.Index)!.Enabled = newValue; + changes = true; } if (!changes) @@ -76,12 +76,12 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu /// public bool SetModPriority(ModCollection collection, Mod mod, ModPriority newValue) { - var oldValue = collection.Settings[mod.Index]?.Priority ?? collection[mod.Index].Settings?.Priority ?? ModPriority.Default; + var oldValue = collection.GetInheritedSettings(mod.Index).Settings?.Priority ?? ModPriority.Default; if (newValue == oldValue) return false; var inheritance = FixInheritance(collection, mod, false); - ((List)collection.Settings)[mod.Index]!.Priority = newValue; + collection.GetOwnSettings(mod.Index)!.Priority = newValue; InvokeChange(collection, ModSettingChange.Priority, mod, inheritance ? Setting.Indefinite : oldValue.AsSetting, 0); return true; } @@ -92,15 +92,13 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu /// public bool SetModSetting(ModCollection collection, Mod mod, int groupIdx, Setting newValue) { - var settings = collection.Settings[mod.Index] != null - ? collection.Settings[mod.Index]!.Settings - : collection[mod.Index].Settings?.Settings; + var settings = collection.GetInheritedSettings(mod.Index).Settings?.Settings; var oldValue = settings?[groupIdx] ?? mod.Groups[groupIdx].DefaultSettings; if (oldValue == newValue) return false; var inheritance = FixInheritance(collection, mod, false); - ((List)collection.Settings)[mod.Index]!.SetValue(mod, groupIdx, newValue); + collection.GetOwnSettings(mod.Index)!.SetValue(mod, groupIdx, newValue); InvokeChange(collection, ModSettingChange.Setting, mod, inheritance ? Setting.Indefinite : oldValue, groupIdx); return true; } @@ -115,10 +113,10 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu // If it does not exist, check unused settings. // If it does not exist and has no unused settings, also use null. ModSettings.SavedSettings? savedSettings = sourceMod != null - ? collection.Settings[sourceMod.Index] != null - ? new ModSettings.SavedSettings(collection.Settings[sourceMod.Index]!, sourceMod) + ? collection.GetOwnSettings(sourceMod.Index) is { } ownSettings + ? new ModSettings.SavedSettings(ownSettings, sourceMod) : null - : collection.UnusedSettings.TryGetValue(sourceName, out var s) + : collection.Settings.Unused.TryGetValue(sourceName, out var s) ? s : null; @@ -148,10 +146,10 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu // or remove any unused settings for the target if they are inheriting. if (savedSettings != null) { - ((Dictionary)collection.UnusedSettings)[targetName] = savedSettings.Value; + ((Dictionary)collection.Settings.Unused)[targetName] = savedSettings.Value; saveService.QueueSave(new ModCollectionSave(modStorage, collection)); } - else if (((Dictionary)collection.UnusedSettings).Remove(targetName)) + else if (((Dictionary)collection.Settings.Unused).Remove(targetName)) { saveService.QueueSave(new ModCollectionSave(modStorage, collection)); } @@ -166,12 +164,12 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu /// private static bool FixInheritance(ModCollection collection, Mod mod, bool inherit) { - var settings = collection.Settings[mod.Index]; + var settings = collection.GetOwnSettings(mod.Index); if (inherit == (settings == null)) return false; - ((List)collection.Settings)[mod.Index] = - inherit ? null : collection[mod.Index].Settings?.DeepCopy() ?? ModSettings.DefaultSettings(mod); + ModSettings? settings1 = inherit ? null : collection.GetInheritedSettings(mod.Index).Settings?.DeepCopy() ?? ModSettings.DefaultSettings(mod); + collection.Settings.Set(mod.Index, settings1); return true; } @@ -188,7 +186,7 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void RecurseInheritors(ModCollection directParent, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx) { - foreach (var directInheritor in directParent.DirectParentOf) + foreach (var directInheritor in directParent.Inheritance.DirectlyInheritedBy) { switch (type) { @@ -197,7 +195,7 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu communicator.ModSettingChanged.Invoke(directInheritor, type, null, oldValue, groupIdx, true); break; default: - if (directInheritor.Settings[mod!.Index] == null) + if (directInheritor.GetOwnSettings(mod!.Index) == null) communicator.ModSettingChanged.Invoke(directInheritor, type, mod, oldValue, groupIdx, true); break; } diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index 2ed395ae..e19acd35 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -41,8 +41,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer public ModCollection CreateFromData(Guid id, string name, int version, Dictionary allSettings, IReadOnlyList inheritances) { - var newCollection = ModCollection.CreateFromData(_saveService, _modStorage, new ModCollectionIdentity(id, CurrentCollectionId, name, Count), version, allSettings, - inheritances); + var newCollection = ModCollection.CreateFromData(_saveService, _modStorage, + new ModCollectionIdentity(id, CurrentCollectionId, name, Count), version, allSettings, inheritances); _collectionsByLocal[CurrentCollectionId] = newCollection; CurrentCollectionId += 1; return newCollection; @@ -196,8 +196,8 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer /// Remove all settings for not currently-installed mods from the given collection. public void CleanUnavailableSettings(ModCollection collection) { - var any = collection.UnusedSettings.Count > 0; - ((Dictionary)collection.UnusedSettings).Clear(); + var any = collection.Settings.Unused.Count > 0; + ((Dictionary)collection.Settings.Unused).Clear(); if (any) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); } @@ -205,7 +205,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer /// Remove a specific setting for not currently-installed mods from the given collection. public void CleanUnavailableSetting(ModCollection collection, string? setting) { - if (setting != null && ((Dictionary)collection.UnusedSettings).Remove(setting)) + if (setting != null && ((Dictionary)collection.Settings.Unused).Remove(setting)) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); } @@ -307,7 +307,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer private void OnModDiscoveryStarted() { foreach (var collection in this) - collection.PrepareModDiscovery(_modStorage); + collection.Settings.PrepareModDiscovery(_modStorage); } /// Restore all settings in all collections to mods. @@ -315,7 +315,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer { // Re-apply all mod settings. foreach (var collection in this) - collection.ApplyModSettings(_saveService, _modStorage); + collection.Settings.ApplyModSettings(collection, _saveService, _modStorage); } /// Add or remove a mod from all collections, or re-save all collections where the mod has settings. @@ -326,21 +326,22 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer { case ModPathChangeType.Added: foreach (var collection in this) - collection.AddMod(mod); + collection.Settings.AddMod(mod); break; case ModPathChangeType.Deleted: foreach (var collection in this) - collection.RemoveMod(mod); + collection.Settings.RemoveMod(mod); break; case ModPathChangeType.Moved: - foreach (var collection in this.Where(collection => collection.Settings[mod.Index] != null)) + foreach (var collection in this.Where(collection => collection.GetOwnSettings(mod.Index) != null)) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); break; case ModPathChangeType.Reloaded: foreach (var collection in this) { - if (collection.Settings[mod.Index]?.Settings.FixAll(mod) ?? false) + if (collection.GetOwnSettings(mod.Index)?.Settings.FixAll(mod) ?? false) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + collection.Settings.SetTemporary(mod.Index, null); } break; @@ -357,8 +358,9 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer foreach (var collection in this) { - if (collection.Settings[mod.Index]?.HandleChanges(type, mod, group, option, movedToIdx) ?? false) + if (collection.GetOwnSettings(mod.Index)?.HandleChanges(type, mod, group, option, movedToIdx) ?? false) _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + collection.Settings.SetTemporary(mod.Index, null); } } @@ -370,7 +372,7 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer foreach (var collection in this) { - var (settings, _) = collection[mod.Index]; + var (settings, _) = collection.GetActualSettings(mod.Index); if (settings is { Enabled: true }) collection.Counters.IncrementChange(); } diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index e003ad6b..5e361bde 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -1,7 +1,6 @@ using Dalamud.Interface.ImGuiNotification; using OtterGui; using OtterGui.Classes; -using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods.Manager; @@ -63,10 +62,10 @@ public class InheritanceManager : IDisposable, IService if (ReferenceEquals(potentialParent, potentialInheritor)) return ValidInheritance.Self; - if (potentialInheritor.DirectlyInheritsFrom.Contains(potentialParent)) + if (potentialInheritor.Inheritance.DirectlyInheritsFrom.Contains(potentialParent)) return ValidInheritance.Contained; - if (ModCollection.InheritedCollections(potentialParent).Any(c => ReferenceEquals(c, potentialInheritor))) + if (potentialParent.Inheritance.FlatHierarchy.Any(c => ReferenceEquals(c, potentialInheritor))) return ValidInheritance.Circle; return ValidInheritance.Valid; @@ -83,24 +82,22 @@ public class InheritanceManager : IDisposable, IService /// Remove an existing inheritance from a collection. public void RemoveInheritance(ModCollection inheritor, int idx) { - var parent = inheritor.DirectlyInheritsFrom[idx]; - ((List)inheritor.DirectlyInheritsFrom).RemoveAt(idx); - ((List)parent.DirectParentOf).Remove(inheritor); + var parent = inheritor.Inheritance.RemoveInheritanceAt(inheritor, idx); _saveService.QueueSave(new ModCollectionSave(_modStorage, inheritor)); _communicator.CollectionInheritanceChanged.Invoke(inheritor, false); - RecurseInheritanceChanges(inheritor); + RecurseInheritanceChanges(inheritor, true); Penumbra.Log.Debug($"Removed {parent.Identity.AnonymizedName} from {inheritor.Identity.AnonymizedName} inheritances."); } /// Order in the inheritance list is relevant. public void MoveInheritance(ModCollection inheritor, int from, int to) { - if (!((List)inheritor.DirectlyInheritsFrom).Move(from, to)) + if (!inheritor.Inheritance.MoveInheritance(inheritor, from, to)) return; _saveService.QueueSave(new ModCollectionSave(_modStorage, inheritor)); _communicator.CollectionInheritanceChanged.Invoke(inheritor, false); - RecurseInheritanceChanges(inheritor); + RecurseInheritanceChanges(inheritor, true); Penumbra.Log.Debug($"Moved {inheritor.Identity.AnonymizedName}s inheritance {from} to {to}."); } @@ -110,15 +107,15 @@ public class InheritanceManager : IDisposable, IService if (CheckValidInheritance(inheritor, parent) != ValidInheritance.Valid) return false; - ((List)inheritor.DirectlyInheritsFrom).Add(parent); - ((List)parent.DirectParentOf).Add(inheritor); + inheritor.Inheritance.AddInheritance(inheritor, parent); if (invokeEvent) { _saveService.QueueSave(new ModCollectionSave(_modStorage, inheritor)); _communicator.CollectionInheritanceChanged.Invoke(inheritor, false); - RecurseInheritanceChanges(inheritor); } + RecurseInheritanceChanges(inheritor, invokeEvent); + Penumbra.Log.Debug($"Added {parent.Identity.AnonymizedName} to {inheritor.Identity.AnonymizedName} inheritances."); return true; } @@ -131,11 +128,11 @@ public class InheritanceManager : IDisposable, IService { foreach (var collection in _storage) { - if (collection.InheritanceByName == null) + if (collection.Inheritance.ConsumeNames() is not { } byName) continue; var changes = false; - foreach (var subCollectionName in collection.InheritanceByName) + foreach (var subCollectionName in byName) { if (Guid.TryParse(subCollectionName, out var guid) && _storage.ById(guid, out var subCollection)) { @@ -143,7 +140,8 @@ public class InheritanceManager : IDisposable, IService continue; changes = true; - Penumbra.Messager.NotificationMessage($"{collection.Identity.Name} can not inherit from {subCollection.Identity.Name}, removed.", + Penumbra.Messager.NotificationMessage( + $"{collection.Identity.Name} can not inherit from {subCollection.Identity.Name}, removed.", NotificationType.Warning); } else if (_storage.ByName(subCollectionName, out subCollection)) @@ -153,7 +151,8 @@ public class InheritanceManager : IDisposable, IService if (AddInheritance(collection, subCollection, false)) continue; - Penumbra.Messager.NotificationMessage($"{collection.Identity.Name} can not inherit from {subCollection.Identity.Name}, removed.", + Penumbra.Messager.NotificationMessage( + $"{collection.Identity.Name} can not inherit from {subCollection.Identity.Name}, removed.", NotificationType.Warning); } else @@ -165,7 +164,6 @@ public class InheritanceManager : IDisposable, IService } } - collection.InheritanceByName = null; if (changes) _saveService.ImmediateSave(new ModCollectionSave(_modStorage, collection)); } @@ -178,20 +176,22 @@ public class InheritanceManager : IDisposable, IService foreach (var c in _storage) { - var inheritedIdx = c.DirectlyInheritsFrom.IndexOf(old); + var inheritedIdx = c.Inheritance.DirectlyInheritsFrom.IndexOf(old); if (inheritedIdx >= 0) RemoveInheritance(c, inheritedIdx); - ((List)c.DirectParentOf).Remove(old); + c.Inheritance.RemoveChild(old); } } - private void RecurseInheritanceChanges(ModCollection newInheritor) + private void RecurseInheritanceChanges(ModCollection newInheritor, bool invokeEvent) { - foreach (var inheritor in newInheritor.DirectParentOf) + foreach (var inheritor in newInheritor.Inheritance.DirectlyInheritedBy) { - _communicator.CollectionInheritanceChanged.Invoke(inheritor, true); - RecurseInheritanceChanges(inheritor); + ModCollectionInheritance.UpdateFlattenedInheritance(inheritor); + RecurseInheritanceChanges(inheritor, invokeEvent); + if (invokeEvent) + _communicator.CollectionInheritanceChanged.Invoke(inheritor, true); } } } diff --git a/Penumbra/Collections/Manager/ModCollectionMigration.cs b/Penumbra/Collections/Manager/ModCollectionMigration.cs index fe61285d..7db375f7 100644 --- a/Penumbra/Collections/Manager/ModCollectionMigration.cs +++ b/Penumbra/Collections/Manager/ModCollectionMigration.cs @@ -26,12 +26,12 @@ internal static class ModCollectionMigration // Remove all completely defaulted settings from active and inactive mods. for (var i = 0; i < collection.Settings.Count; ++i) { - if (SettingIsDefaultV0(collection.Settings[i])) - ((List)collection.Settings)[i] = null; + if (SettingIsDefaultV0(collection.GetOwnSettings(i))) + collection.Settings.SetAll(i, FullModSettings.Empty); } - foreach (var (key, _) in collection.UnusedSettings.Where(kvp => SettingIsDefaultV0(kvp.Value)).ToList()) - ((Dictionary)collection.UnusedSettings).Remove(key); + foreach (var (key, _) in collection.Settings.Unused.Where(kvp => SettingIsDefaultV0(kvp.Value)).ToList()) + collection.Settings.RemoveUnused(key); return true; } diff --git a/Penumbra/Collections/ModCollection.cs b/Penumbra/Collections/ModCollection.cs index 9b33c1f4..69f82458 100644 --- a/Penumbra/Collections/ModCollection.cs +++ b/Penumbra/Collections/ModCollection.cs @@ -1,4 +1,3 @@ -using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Collections.Manager; using Penumbra.Mods.Settings; @@ -22,70 +21,74 @@ public partial class ModCollection /// Create the always available Empty Collection that will always sit at index 0, /// can not be deleted and does never create a cache. /// - public static readonly ModCollection Empty = new(ModCollectionIdentity.Empty, 0, CurrentVersion, [], [], []); + public static readonly ModCollection Empty = new(ModCollectionIdentity.Empty, 0, CurrentVersion, new ModSettingProvider(), + new ModCollectionInheritance()); public ModCollectionIdentity Identity; public override string ToString() => Identity.ToString(); - public CollectionCounters Counters; + public readonly ModSettingProvider Settings; + public ModCollectionInheritance Inheritance; + public CollectionCounters Counters; - /// - /// If a ModSetting is null, it can be inherited from other collections. - /// If no collection provides a setting for the mod, it is just disabled. - /// - public readonly IReadOnlyList Settings; - /// Settings for deleted mods will be kept via the mods identifier (directory name). - public readonly IReadOnlyDictionary UnusedSettings; - - /// Inheritances stored before they can be applied. - public IReadOnlyList? InheritanceByName; - - /// Contains all direct parent collections this collection inherits settings from. - public readonly IReadOnlyList DirectlyInheritsFrom; - - /// Contains all direct child collections that inherit from this collection. - public readonly IReadOnlyList DirectParentOf = new List(); - - /// All inherited collections in application order without filtering for duplicates. - public static IEnumerable InheritedCollections(ModCollection collection) - => collection.DirectlyInheritsFrom.SelectMany(InheritedCollections).Prepend(collection); - - /// - /// Iterate over all collections inherited from in depth-first order. - /// Skip already visited collections to avoid circular dependencies. - /// - public IEnumerable GetFlattenedInheritance() - => InheritedCollections(this).Distinct(); - - /// - /// Obtain the actual settings for a given mod via index. - /// Also returns the collection the settings are taken from. - /// If no collection provides settings for this mod, this collection is returned together with null. - /// - public (ModSettings? Settings, ModCollection Collection) this[Index idx] + public ModSettings? GetOwnSettings(Index idx) { - get + if (Identity.Index <= 0) + return ModSettings.Empty; + + return Settings.Settings[idx].Settings; + } + + public TemporaryModSettings? GetTempSettings(Index idx) + { + if (Identity.Index <= 0) + return null; + + return Settings.Settings[idx].TempSettings; + } + + public (ModSettings? Settings, ModCollection Collection) GetInheritedSettings(Index idx) + { + if (Identity.Index <= 0) + return (ModSettings.Empty, this); + + foreach (var collection in Inheritance.FlatHierarchy) { - if (Identity.Index <= 0) - return (ModSettings.Empty, this); - - foreach (var collection in GetFlattenedInheritance()) - { - var settings = collection.Settings[idx]; - if (settings != null) - return (settings, collection); - } - - return (null, this); + var settings = collection.Settings.Settings[idx].Settings; + if (settings != null) + return (settings, collection); } + + return (null, this); + } + + public (ModSettings? Settings, ModCollection Collection) GetActualSettings(Index idx) + { + if (Identity.Index <= 0) + return (ModSettings.Empty, this); + + // Check temp settings. + var ownTempSettings = Settings.Settings[idx].Resolve(); + if (ownTempSettings != null) + return (ownTempSettings, this); + + // Ignore temp settings for inherited collections. + foreach (var collection in Inheritance.FlatHierarchy.Skip(1)) + { + var settings = collection.Settings.Settings[idx].Settings; + if (settings != null) + return (settings, collection); + } + + return (null, this); } /// Evaluates all settings along the whole inheritance tree. public IEnumerable ActualSettings - => Enumerable.Range(0, Settings.Count).Select(i => this[i].Settings); + => Enumerable.Range(0, Settings.Count).Select(i => GetActualSettings(i).Settings); /// /// Constructor for duplication. Deep copies all settings and parent collections and adds the new collection to their children lists. @@ -93,9 +96,7 @@ public partial class ModCollection public ModCollection Duplicate(string name, LocalCollectionId localId, int index) { Debug.Assert(index > 0, "Collection duplicated with non-positive index."); - return new ModCollection(ModCollectionIdentity.New(name, localId, index), 0, CurrentVersion, - Settings.Select(s => s?.DeepCopy()).ToList(), [.. DirectlyInheritsFrom], - UnusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy())); + return new ModCollection(ModCollectionIdentity.New(name, localId, index), 0, CurrentVersion, Settings.Clone(), Inheritance.Clone()); } /// Constructor for reading from files. @@ -103,11 +104,8 @@ public partial class ModCollection Dictionary allSettings, IReadOnlyList inheritances) { Debug.Assert(identity.Index > 0, "Collection read with non-positive index."); - var ret = new ModCollection(identity, 0, version, [], [], allSettings) - { - InheritanceByName = inheritances, - }; - ret.ApplyModSettings(saver, mods); + var ret = new ModCollection(identity, 0, version, new ModSettingProvider(allSettings), new ModCollectionInheritance(inheritances)); + ret.Settings.ApplyModSettings(ret, saver, mods); ModCollectionMigration.Migrate(saver, mods, version, ret); return ret; } @@ -116,7 +114,8 @@ public partial class ModCollection public static ModCollection CreateTemporary(string name, LocalCollectionId localId, int index, int changeCounter) { Debug.Assert(index < 0, "Temporary collection created with non-negative index."); - var ret = new ModCollection(ModCollectionIdentity.New(name, localId, index), changeCounter, CurrentVersion, [], [], []); + var ret = new ModCollection(ModCollectionIdentity.New(name, localId, index), changeCounter, CurrentVersion, new ModSettingProvider(), + new ModCollectionInheritance()); return ret; } @@ -124,64 +123,18 @@ public partial class ModCollection public static ModCollection CreateEmpty(string name, LocalCollectionId localId, int index, int modCount) { Debug.Assert(index >= 0, "Empty collection created with negative index."); - return new ModCollection(ModCollectionIdentity.New(name, localId, index), 0, CurrentVersion, - Enumerable.Repeat((ModSettings?)null, modCount).ToList(), [], []); + return new ModCollection(ModCollectionIdentity.New(name, localId, index), 0, CurrentVersion, ModSettingProvider.Empty(modCount), + new ModCollectionInheritance()); } - /// Add settings for a new appended mod, by checking if the mod had settings from a previous deletion. - internal bool AddMod(Mod mod) + private ModCollection(ModCollectionIdentity identity, int changeCounter, int version, ModSettingProvider settings, + ModCollectionInheritance inheritance) { - if (UnusedSettings.TryGetValue(mod.ModPath.Name, out var save)) - { - var ret = save.ToSettings(mod, out var settings); - ((List)Settings).Add(settings); - ((Dictionary)UnusedSettings).Remove(mod.ModPath.Name); - return ret; - } - - ((List)Settings).Add(null); - return false; - } - - /// Move settings from the current mod list to the unused mod settings. - internal void RemoveMod(Mod mod) - { - var settings = Settings[mod.Index]; - if (settings != null) - ((Dictionary)UnusedSettings)[mod.ModPath.Name] = new ModSettings.SavedSettings(settings, mod); - - ((List)Settings).RemoveAt(mod.Index); - } - - /// Move all settings to unused settings for rediscovery. - internal void PrepareModDiscovery(ModStorage mods) - { - foreach (var (mod, setting) in mods.Zip(Settings).Where(s => s.Second != null)) - ((Dictionary)UnusedSettings)[mod.ModPath.Name] = new ModSettings.SavedSettings(setting!, mod); - - ((List)Settings).Clear(); - } - - /// - /// Apply all mod settings from unused settings to the current set of mods. - /// Also fixes invalid settings. - /// - internal void ApplyModSettings(SaveService saver, ModStorage mods) - { - ((List)Settings).Capacity = Math.Max(((List)Settings).Capacity, mods.Count); - if (mods.Aggregate(false, (current, mod) => current | AddMod(mod))) - saver.ImmediateSave(new ModCollectionSave(mods, this)); - } - - private ModCollection(ModCollectionIdentity identity, int changeCounter, int version, List appliedSettings, - List inheritsFrom, Dictionary settings) - { - Identity = identity; - Counters = new CollectionCounters(changeCounter); - Settings = appliedSettings; - UnusedSettings = settings; - DirectlyInheritsFrom = inheritsFrom; - foreach (var c in DirectlyInheritsFrom) - ((List)c.DirectParentOf).Add(this); + Identity = identity; + Counters = new CollectionCounters(changeCounter); + Settings = settings; + Inheritance = inheritance; + ModCollectionInheritance.UpdateChildren(this); + ModCollectionInheritance.UpdateFlattenedInheritance(this); } } diff --git a/Penumbra/Collections/ModCollectionInheritance.cs b/Penumbra/Collections/ModCollectionInheritance.cs new file mode 100644 index 00000000..151ed7db --- /dev/null +++ b/Penumbra/Collections/ModCollectionInheritance.cs @@ -0,0 +1,92 @@ +using OtterGui.Filesystem; + +namespace Penumbra.Collections; + +public struct ModCollectionInheritance +{ + public IReadOnlyList? InheritanceByName { get; private set; } + private readonly List _directlyInheritsFrom = []; + private readonly List _directlyInheritedBy = []; + private readonly List _flatHierarchy = []; + + public ModCollectionInheritance() + { } + + private ModCollectionInheritance(List inheritsFrom) + => _directlyInheritsFrom = [.. inheritsFrom]; + + public ModCollectionInheritance(IReadOnlyList byName) + => InheritanceByName = byName; + + public ModCollectionInheritance Clone() + => new(_directlyInheritsFrom); + + public IEnumerable Identifiers + => InheritanceByName ?? _directlyInheritsFrom.Select(c => c.Identity.Identifier); + + public IReadOnlyList? ConsumeNames() + { + var ret = InheritanceByName; + InheritanceByName = null; + return ret; + } + + public static void UpdateChildren(ModCollection parent) + { + foreach (var inheritance in parent.Inheritance.DirectlyInheritsFrom) + inheritance.Inheritance._directlyInheritedBy.Add(parent); + } + + public void AddInheritance(ModCollection inheritor, ModCollection newParent) + { + _directlyInheritsFrom.Add(newParent); + newParent.Inheritance._directlyInheritedBy.Add(inheritor); + UpdateFlattenedInheritance(inheritor); + } + + public ModCollection RemoveInheritanceAt(ModCollection inheritor, int idx) + { + var parent = DirectlyInheritsFrom[idx]; + _directlyInheritsFrom.RemoveAt(idx); + parent.Inheritance._directlyInheritedBy.Remove(parent); + UpdateFlattenedInheritance(inheritor); + return parent; + } + + public bool MoveInheritance(ModCollection inheritor, int from, int to) + { + if (!_directlyInheritsFrom.Move(from, to)) + return false; + + UpdateFlattenedInheritance(inheritor); + return true; + } + + public void RemoveChild(ModCollection child) + => _directlyInheritedBy.Remove(child); + + /// Contains all direct parent collections this collection inherits settings from. + public readonly IReadOnlyList DirectlyInheritsFrom + => _directlyInheritsFrom; + + /// Contains all direct child collections that inherit from this collection. + public readonly IReadOnlyList DirectlyInheritedBy + => _directlyInheritedBy; + + /// + /// Iterate over all collections inherited from in depth-first order. + /// Skip already visited collections to avoid circular dependencies. + /// + public readonly IReadOnlyList FlatHierarchy + => _flatHierarchy; + + public static void UpdateFlattenedInheritance(ModCollection parent) + { + parent.Inheritance._flatHierarchy.Clear(); + parent.Inheritance._flatHierarchy.AddRange(InheritedCollections(parent).Distinct()); + } + + /// All inherited collections in application order without filtering for duplicates. + private static IEnumerable InheritedCollections(ModCollection parent) + => parent.Inheritance.DirectlyInheritsFrom.SelectMany(InheritedCollections).Prepend(parent); +} diff --git a/Penumbra/Collections/ModCollectionSave.cs b/Penumbra/Collections/ModCollectionSave.cs index 6e1b51ac..4c41a28c 100644 --- a/Penumbra/Collections/ModCollectionSave.cs +++ b/Penumbra/Collections/ModCollectionSave.cs @@ -32,19 +32,19 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection j.WriteValue(modCollection.Identity.Identifier); j.WritePropertyName(nameof(ModCollectionIdentity.Name)); j.WriteValue(modCollection.Identity.Name); - j.WritePropertyName(nameof(ModCollection.Settings)); + j.WritePropertyName("Settings"); // Write all used and unused settings by mod directory name. j.WriteStartObject(); - var list = new List<(string, ModSettings.SavedSettings)>(modCollection.Settings.Count + modCollection.UnusedSettings.Count); + var list = new List<(string, ModSettings.SavedSettings)>(modCollection.Settings.Count + modCollection.Settings.Unused.Count); for (var i = 0; i < modCollection.Settings.Count; ++i) { - var settings = modCollection.Settings[i]; + var settings = modCollection.GetOwnSettings(i); if (settings != null) list.Add((modStorage[i].ModPath.Name, new ModSettings.SavedSettings(settings, modStorage[i]))); } - list.AddRange(modCollection.UnusedSettings.Select(kvp => (kvp.Key, kvp.Value))); + list.AddRange(modCollection.Settings.Unused.Select(kvp => (kvp.Key, kvp.Value))); list.Sort((a, b) => string.Compare(a.Item1, b.Item1, StringComparison.OrdinalIgnoreCase)); foreach (var (modDir, settings) in list) @@ -57,7 +57,7 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection // Inherit by collection name. j.WritePropertyName("Inheritance"); - x.Serialize(j, modCollection.InheritanceByName ?? modCollection.DirectlyInheritsFrom.Select(c => c.Identity.Identifier)); + x.Serialize(j, modCollection.Inheritance.Identifiers); j.WriteEndObject(); } @@ -82,7 +82,7 @@ internal readonly struct ModCollectionSave(ModStorage modStorage, ModCollection name = obj[nameof(ModCollectionIdentity.Name)]?.ToObject() ?? string.Empty; id = obj[nameof(ModCollectionIdentity.Id)]?.ToObject() ?? (version == 1 ? Guid.NewGuid() : Guid.Empty); // Custom deserialization that is converted with the constructor. - settings = obj[nameof(ModCollection.Settings)]?.ToObject>() ?? settings; + settings = obj["Settings"]?.ToObject>() ?? settings; inheritance = obj["Inheritance"]?.ToObject>() ?? inheritance; return true; } diff --git a/Penumbra/Collections/ModSettingProvider.cs b/Penumbra/Collections/ModSettingProvider.cs new file mode 100644 index 00000000..3bf2f949 --- /dev/null +++ b/Penumbra/Collections/ModSettingProvider.cs @@ -0,0 +1,98 @@ +using Penumbra.Mods; +using Penumbra.Mods.Manager; +using Penumbra.Mods.Settings; +using Penumbra.Services; + +namespace Penumbra.Collections; + +public readonly struct ModSettingProvider +{ + private ModSettingProvider(IEnumerable settings, Dictionary unusedSettings) + { + _settings = settings.Select(s => s.DeepCopy()).ToList(); + _unused = unusedSettings.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.DeepCopy()); + } + + public ModSettingProvider() + { } + + public static ModSettingProvider Empty(int count) + => new(Enumerable.Repeat(FullModSettings.Empty, count), []); + + public ModSettingProvider(Dictionary allSettings) + => _unused = allSettings; + + private readonly List _settings = []; + + /// Settings for deleted mods will be kept via the mods identifier (directory name). + private readonly Dictionary _unused = []; + + public int Count + => _settings.Count; + + public bool RemoveUnused(string key) + => _unused.Remove(key); + + internal void Set(Index index, ModSettings? settings) + => _settings[index] = _settings[index] with { Settings = settings }; + + internal void SetTemporary(Index index, TemporaryModSettings? settings) + => _settings[index] = _settings[index] with { TempSettings = settings }; + + internal void SetAll(Index index, FullModSettings settings) + => _settings[index] = settings; + + public IReadOnlyList Settings + => _settings; + + public IReadOnlyDictionary Unused + => _unused; + + public ModSettingProvider Clone() + => new(_settings, _unused); + + /// Add settings for a new appended mod, by checking if the mod had settings from a previous deletion. + internal bool AddMod(Mod mod) + { + if (_unused.Remove(mod.ModPath.Name, out var save)) + { + var ret = save.ToSettings(mod, out var settings); + _settings.Add(new FullModSettings(settings)); + return ret; + } + + _settings.Add(FullModSettings.Empty); + return false; + } + + /// Move settings from the current mod list to the unused mod settings. + internal void RemoveMod(Mod mod) + { + var settings = _settings[mod.Index]; + if (settings.Settings != null) + _unused[mod.ModPath.Name] = new ModSettings.SavedSettings(settings.Settings, mod); + + _settings.RemoveAt(mod.Index); + } + + /// Move all settings to unused settings for rediscovery. + internal void PrepareModDiscovery(ModStorage mods) + { + foreach (var (mod, setting) in mods.Zip(_settings).Where(s => s.Second.Settings != null)) + _unused[mod.ModPath.Name] = new ModSettings.SavedSettings(setting.Settings!, mod); + + _settings.Clear(); + } + + /// + /// Apply all mod settings from unused settings to the current set of mods. + /// Also fixes invalid settings. + /// + internal void ApplyModSettings(ModCollection parent, SaveService saver, ModStorage mods) + { + _settings.Capacity = Math.Max(_settings.Capacity, mods.Count); + var settings = this; + if (mods.Aggregate(false, (current, mod) => current | settings.AddMod(mod))) + saver.ImmediateSave(new ModCollectionSave(mods, parent)); + } +} diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 61946978..dee46e32 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -606,7 +606,7 @@ public class CommandHandler : IDisposable, IApiService private bool HandleModState(int settingState, ModCollection collection, Mod mod) { - var settings = collection.Settings[mod.Index]; + var settings = collection.GetOwnSettings(mod.Index); switch (settingState) { case 0: diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 088527ca..4fa13e1f 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -98,6 +98,6 @@ public class ResourceNode : ICloneable public readonly record struct UiData(string? Name, ChangedItemIconFlag IconFlag) { public UiData PrependName(string prefix) - => Name == null ? this : new UiData(prefix + Name, IconFlag); + => Name == null ? this : this with { Name = prefix + Name }; } } diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 876fe12f..c06af9c7 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -74,6 +74,9 @@ public class ModMetaEditor( dict.ClearForDefault(); var count = 0; + foreach (var value in clone.GlobalEqp) + dict.TryAdd(value); + foreach (var (key, value) in clone.Imc) { var defaultEntry = ImcChecker.GetDefaultEntry(key, false); diff --git a/Penumbra/Mods/ModSelection.cs b/Penumbra/Mods/ModSelection.cs index 73d0272b..59cd5d71 100644 --- a/Penumbra/Mods/ModSelection.cs +++ b/Penumbra/Mods/ModSelection.cs @@ -36,9 +36,16 @@ public class ModSelection : EventWrapper _communicator.ModSettingChanged.Subscribe(OnSettingChange, ModSettingChanged.Priority.ModSelection); } - public ModSettings Settings { get; private set; } = ModSettings.Empty; - public ModCollection Collection { get; private set; } = ModCollection.Empty; - public Mod? Mod { get; private set; } + public ModSettings Settings { get; private set; } = ModSettings.Empty; + public ModCollection Collection { get; private set; } = ModCollection.Empty; + public Mod? Mod { get; private set; } + public ModSettings? OwnSettings { get; private set; } + + public bool IsTemporary + => OwnSettings != Settings; + + public TemporaryModSettings? AsTemporarySettings + => Settings as TemporaryModSettings; public void SelectMod(Mod? mod) @@ -83,12 +90,14 @@ public class ModSelection : EventWrapper { if (Mod == null) { - Settings = ModSettings.Empty; - Collection = ModCollection.Empty; + Settings = ModSettings.Empty; + Collection = ModCollection.Empty; + OwnSettings = null; } else { - (var settings, Collection) = _collections.Current[Mod.Index]; + (var settings, Collection) = _collections.Current.GetActualSettings(Mod.Index); + OwnSettings = _collections.Current.GetOwnSettings(Mod.Index); Settings = settings ?? ModSettings.Empty; } } diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index 25e4805d..671fba4d 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -12,7 +12,7 @@ namespace Penumbra.Mods.Settings; public class ModSettings { public static readonly ModSettings Empty = new(); - public SettingList Settings { get; private init; } = []; + public SettingList Settings { get; internal init; } = []; public ModPriority Priority { get; set; } public bool Enabled { get; set; } diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index a2594145..69dfe3e8 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -245,7 +245,7 @@ public class Penumbra : IDalamudPlugin void PrintCollection(ModCollection c, CollectionCache _) => sb.Append( - $"> **`Collection {c.Identity.AnonymizedName + ':',-18}`** Inheritances: `{c.DirectlyInheritsFrom.Count,3}`, Enabled Mods: `{c.ActualSettings.Count(s => s is { Enabled: true }),4}`, Conflicts: `{c.AllConflicts.SelectMany(x => x).Sum(x => x is { HasPriority: true, Solved: true } ? x.Conflicts.Count : 0),5}/{c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority ? x.Conflicts.Count : 0),5}`\n"); + $"> **`Collection {c.Identity.AnonymizedName + ':',-18}`** Inheritances: `{c.Inheritance.DirectlyInheritsFrom.Count,3}`, Enabled Mods: `{c.ActualSettings.Count(s => s is { Enabled: true }),4}`, Conflicts: `{c.AllConflicts.SelectMany(x => x).Sum(x => x is { HasPriority: true, Solved: true } ? x.Conflicts.Count : 0),5}/{c.AllConflicts.SelectMany(x => x).Sum(x => x.HasPriority ? x.Conflicts.Count : 0),5}`\n"); sb.AppendLine("**Collections**"); sb.Append($"> **`#Collections: `** {_collectionManager.Storage.Count - 1}\n"); diff --git a/Penumbra/Services/ConfigMigrationService.cs b/Penumbra/Services/ConfigMigrationService.cs index f58eb891..9fe8c420 100644 --- a/Penumbra/Services/ConfigMigrationService.cs +++ b/Penumbra/Services/ConfigMigrationService.cs @@ -240,7 +240,7 @@ public class ConfigMigrationService(SaveService saveService, BackupService backu if (jObject["Name"]?.ToObject() == ForcedCollection) continue; - jObject[nameof(ModCollection.DirectlyInheritsFrom)] = JToken.FromObject(new List { ForcedCollection }); + jObject[nameof(ModCollectionInheritance.DirectlyInheritsFrom)] = JToken.FromObject(new List { ForcedCollection }); File.WriteAllText(collection.FullName, jObject.ToString()); } catch (Exception e) diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 3f7f2f6c..b0029f08 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -737,7 +737,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService if (collectionType is not CollectionType.Current || _mod == null || newCollection == null) return; - UpdateMod(_mod, _mod.Index < newCollection.Settings.Count ? newCollection[_mod.Index].Settings : null); + UpdateMod(_mod, _mod.Index < newCollection.Settings.Count ? newCollection.GetInheritedSettings(_mod.Index).Settings : null); } private void OnSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx, bool inherited) @@ -754,7 +754,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService if (collection != _collectionManager.Active.Current || _mod == null) return; - UpdateMod(_mod, collection[_mod.Index].Settings); + UpdateMod(_mod, collection.GetInheritedSettings(_mod.Index).Settings); _swapData.LoadMod(_mod, _modSettings); _dirty = true; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 1a4065bb..02e945f3 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -101,7 +101,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _modelTab.Reset(); _materialTab.Reset(); _shaderPackageTab.Reset(); - _itemSwapTab.UpdateMod(mod, _activeCollections.Current[mod.Index].Settings); + _itemSwapTab.UpdateMod(mod, _activeCollections.Current.GetInheritedSettings(mod.Index).Settings); UpdateModels(); _forceTextureStartPath = true; }); diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index cab34b10..8b41b105 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -15,6 +15,7 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; using Penumbra.Mods.Manager; +using Penumbra.Mods.Settings; using Penumbra.Services; using Penumbra.UI.Classes; @@ -497,7 +498,7 @@ public sealed class CollectionPanel( ImGui.Separator(); var buttonHeight = 2 * ImGui.GetTextLineHeightWithSpacing(); - if (_inUseCache.Count == 0 && collection.DirectParentOf.Count == 0) + if (_inUseCache.Count == 0 && collection.Inheritance.DirectlyInheritedBy.Count == 0) { ImGui.Dummy(Vector2.One); using var f = _nameFont.Push(); @@ -559,7 +560,7 @@ public sealed class CollectionPanel( private void DrawInheritanceStatistics(ModCollection collection, Vector2 buttonWidth) { - if (collection.DirectParentOf.Count <= 0) + if (collection.Inheritance.DirectlyInheritedBy.Count <= 0) return; using (var _ = ImRaii.PushStyle(ImGuiStyleVar.FramePadding, Vector2.Zero)) @@ -570,11 +571,11 @@ public sealed class CollectionPanel( using var f = _nameFont.Push(); using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); using var color = ImRaii.PushColor(ImGuiCol.Border, Colors.MetaInfoText); - ImGuiUtil.DrawTextButton(Name(collection.DirectParentOf[0]), Vector2.Zero, 0); + ImGuiUtil.DrawTextButton(Name(collection.Inheritance.DirectlyInheritedBy[0]), Vector2.Zero, 0); var constOffset = (ImGui.GetStyle().FramePadding.X + ImGuiHelpers.GlobalScale) * 2 + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X; - foreach (var parent in collection.DirectParentOf.Skip(1)) + foreach (var parent in collection.Inheritance.DirectlyInheritedBy.Skip(1)) { var name = Name(parent); var size = ImGui.CalcTextSize(name).X; @@ -602,7 +603,7 @@ public sealed class CollectionPanel( ImGui.TableSetupColumn("State", ImGuiTableColumnFlags.WidthFixed, 1.75f * ImGui.GetFrameHeight()); ImGui.TableSetupColumn("Priority", ImGuiTableColumnFlags.WidthFixed, 2.5f * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); - foreach (var (mod, (settings, parent)) in mods.Select(m => (m, collection[m.Index])) + foreach (var (mod, (settings, parent)) in mods.Select(m => (m, collection.GetInheritedSettings(m.Index))) .Where(t => t.Item2.Settings != null) .OrderBy(t => t.m.Name)) { @@ -625,12 +626,12 @@ public sealed class CollectionPanel( private void DrawInactiveSettingsList(ModCollection collection) { - if (collection.UnusedSettings.Count == 0) + if (collection.Settings.Unused.Count == 0) return; ImGui.Dummy(Vector2.One); - var text = collection.UnusedSettings.Count > 1 - ? $"Clear all {collection.UnusedSettings.Count} unused settings from deleted mods." + var text = collection.Settings.Unused.Count > 1 + ? $"Clear all {collection.Settings.Unused.Count} unused settings from deleted mods." : "Clear the currently unused setting from a deleted mods."; if (ImGui.Button(text, new Vector2(ImGui.GetContentRegionAvail().X, 0))) _collections.CleanUnavailableSettings(collection); @@ -638,7 +639,7 @@ public sealed class CollectionPanel( ImGui.Dummy(Vector2.One); var size = new Vector2(ImGui.GetContentRegionAvail().X, - Math.Min(10, collection.UnusedSettings.Count + 1) * ImGui.GetFrameHeightWithSpacing()); + Math.Min(10, collection.Settings.Unused.Count + 1) * ImGui.GetFrameHeightWithSpacing()); using var table = ImRaii.Table("##inactiveSettings", 4, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, size); if (!table) return; @@ -650,7 +651,7 @@ public sealed class CollectionPanel( ImGui.TableSetupColumn("Priority", ImGuiTableColumnFlags.WidthFixed, 2.5f * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); string? delete = null; - foreach (var (name, settings) in collection.UnusedSettings.OrderBy(n => n.Key)) + foreach (var (name, settings) in collection.Settings.Unused.OrderBy(n => n.Key)) { using var id = ImRaii.PushId(name); ImGui.TableNextColumn(); diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index a4d60b13..ce3cc3cb 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -107,7 +107,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService var lineEnd = lineStart; // Skip the collection itself. - foreach (var inheritance in collection.GetFlattenedInheritance().Skip(1)) + foreach (var inheritance in collection.Inheritance.FlatHierarchy.Skip(1)) { // Draw the child, already seen collections are colored as conflicts. using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.HandledConflictMod.Value(), @@ -150,7 +150,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService DrawInheritedChildren(collection); else // We still want to keep track of conflicts. - _seenInheritedCollections.UnionWith(collection.GetFlattenedInheritance()); + _seenInheritedCollections.UnionWith(collection.Inheritance.FlatHierarchy); } /// Draw the list box containing the current inheritance information. @@ -163,7 +163,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService _seenInheritedCollections.Clear(); _seenInheritedCollections.Add(_active.Current); - foreach (var collection in _active.Current.DirectlyInheritsFrom.ToList()) + foreach (var collection in _active.Current.Inheritance.DirectlyInheritsFrom.ToList()) DrawInheritance(collection); } @@ -180,7 +180,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService using var target = ImRaii.DragDropTarget(); if (target.Success && ImGuiUtil.IsDropping(InheritanceDragDropLabel)) - _inheritanceAction = (_active.Current.DirectlyInheritsFrom.IndexOf(_movedInheritance!), -1); + _inheritanceAction = (_active.Current.Inheritance.DirectlyInheritsFrom.IndexOf(_movedInheritance!), -1); } /// @@ -244,7 +244,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService { ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton); _newInheritance ??= _collections.FirstOrDefault(c - => c != _active.Current && !_active.Current.DirectlyInheritsFrom.Contains(c)) + => c != _active.Current && !_active.Current.Inheritance.DirectlyInheritsFrom.Contains(c)) ?? ModCollection.Empty; using var combo = ImRaii.Combo("##newInheritance", Name(_newInheritance)); if (!combo) @@ -271,8 +271,8 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService if (_movedInheritance != null) { - var idx1 = _active.Current.DirectlyInheritsFrom.IndexOf(_movedInheritance); - var idx2 = _active.Current.DirectlyInheritsFrom.IndexOf(collection); + var idx1 = _active.Current.Inheritance.DirectlyInheritsFrom.IndexOf(_movedInheritance); + var idx2 = _active.Current.Inheritance.DirectlyInheritsFrom.IndexOf(collection); if (idx1 >= 0 && idx2 >= 0) _inheritanceAction = (idx1, idx2); } @@ -302,7 +302,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService if (ImGui.GetIO().KeyCtrl && ImGui.IsItemClicked(ImGuiMouseButton.Right)) { if (withDelete && ImGui.GetIO().KeyShift) - _inheritanceAction = (_active.Current.DirectlyInheritsFrom.IndexOf(collection), -1); + _inheritanceAction = (_active.Current.Inheritance.DirectlyInheritsFrom.IndexOf(collection), -1); else _newCurrentCollection = collection; } diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 0781312c..4607434c 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -201,7 +201,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector 0) { @@ -650,14 +664,14 @@ public sealed class ModFileSystemSelector : FileSystemSelector kvp.Key)) { ImUtf8.DrawTableColumn($"{id:D6}"); ImUtf8.DrawTableColumn(name.Span); } - } } } } diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index c226098d..8b4913c8 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -82,7 +82,7 @@ public class ModsTab( + $"{selector.SortMode.Name} Sort Mode\n" + $"{selector.SelectedLeaf?.Name ?? "NULL"} Selected Leaf\n" + $"{selector.Selected?.Name ?? "NULL"} Selected Mod\n" - + $"{string.Join(", ", _activeCollections.Current.DirectlyInheritsFrom.Select(c => c.Identity.AnonymizedName))} Inheritances\n"); + + $"{string.Join(", ", _activeCollections.Current.Inheritance.DirectlyInheritsFrom.Select(c => c.Identity.AnonymizedName))} Inheritances\n"); } } From 282189ef6dc47edd8135a2f4811721b5d5ca032f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 27 Dec 2024 17:51:17 +0100 Subject: [PATCH 1022/1381] Current State. --- Penumbra.Api | 2 +- .../Cache/CollectionCacheManager.cs | 3 + .../Collections/Manager/CollectionEditor.cs | 19 ++++- Penumbra/Mods/ModSelection.cs | 17 ++-- Penumbra/Mods/Settings/ModSettings.cs | 1 + .../Mods/Settings/TemporaryModSettings.cs | 17 ++++ Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- Penumbra/UI/Classes/Colors.cs | 29 ++++--- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 81 ++++++++++++------- 9 files changed, 115 insertions(+), 56 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 97e9f427..fdda2054 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 97e9f427406f82a59ddef764b44ecea654a51623 +Subproject commit fdda2054c26a30111ac55984ed6efde7f7214b68 diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 839c0376..27b969c2 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -333,6 +333,9 @@ public class CollectionCacheManager : IDisposable, IService cache.ReloadMod(mod, true); break; + case ModSettingChange.TemporarySetting: + cache.ReloadMod(mod!, true); + break; case ModSettingChange.MultiInheritance: case ModSettingChange.MultiEnableState: FullRecalculation(collection); diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 66578a95..b456686e 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -88,7 +88,7 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu /// /// Set a given setting group settingName of mod idx to newValue if it differs from the current value and fix it if necessary. - /// /// If the mod is currently inherited, stop the inheritance. + /// If the mod is currently inherited, stop the inheritance. /// public bool SetModSetting(ModCollection collection, Mod mod, int groupIdx, Setting newValue) { @@ -103,6 +103,18 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu return true; } + public bool SetTemporarySettings(ModCollection collection, Mod mod, TemporaryModSettings? settings, int key = 0) + { + key = settings?.Lock ?? key; + var old = collection.GetTempSettings(mod.Index); + if (old != null && old.Lock != 0 && old.Lock != key) + return false; + + collection.Settings.SetTemporary(mod.Index, settings); + InvokeChange(collection, ModSettingChange.TemporarySetting, mod, Setting.Indefinite, 0); + return true; + } + /// Copy the settings of an existing (sourceMod != null) or stored (sourceName) mod to another mod, if they exist. public bool CopyModSettings(ModCollection collection, Mod? sourceMod, string sourceName, Mod? targetMod, string targetName) { @@ -168,7 +180,7 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu if (inherit == (settings == null)) return false; - ModSettings? settings1 = inherit ? null : collection.GetInheritedSettings(mod.Index).Settings?.DeepCopy() ?? ModSettings.DefaultSettings(mod); + var settings1 = inherit ? null : collection.GetInheritedSettings(mod.Index).Settings?.DeepCopy() ?? ModSettings.DefaultSettings(mod); collection.Settings.Set(mod.Index, settings1); return true; } @@ -179,7 +191,8 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu { saveService.QueueSave(new ModCollectionSave(modStorage, changedCollection)); communicator.ModSettingChanged.Invoke(changedCollection, type, mod, oldValue, groupIdx, false); - RecurseInheritors(changedCollection, type, mod, oldValue, groupIdx); + if (type is not ModSettingChange.TemporarySetting) + RecurseInheritors(changedCollection, type, mod, oldValue, groupIdx); } /// Trigger changes in all inherited collections. diff --git a/Penumbra/Mods/ModSelection.cs b/Penumbra/Mods/ModSelection.cs index 59cd5d71..b728bd00 100644 --- a/Penumbra/Mods/ModSelection.cs +++ b/Penumbra/Mods/ModSelection.cs @@ -36,17 +36,11 @@ public class ModSelection : EventWrapper _communicator.ModSettingChanged.Subscribe(OnSettingChange, ModSettingChanged.Priority.ModSelection); } - public ModSettings Settings { get; private set; } = ModSettings.Empty; - public ModCollection Collection { get; private set; } = ModCollection.Empty; - public Mod? Mod { get; private set; } - public ModSettings? OwnSettings { get; private set; } - - public bool IsTemporary - => OwnSettings != Settings; - - public TemporaryModSettings? AsTemporarySettings - => Settings as TemporaryModSettings; - + public ModSettings Settings { get; private set; } = ModSettings.Empty; + public ModCollection Collection { get; private set; } = ModCollection.Empty; + public Mod? Mod { get; private set; } + public ModSettings? OwnSettings { get; private set; } + public TemporaryModSettings? TemporarySettings { get; private set; } public void SelectMod(Mod? mod) { @@ -98,6 +92,7 @@ public class ModSelection : EventWrapper { (var settings, Collection) = _collections.Current.GetActualSettings(Mod.Index); OwnSettings = _collections.Current.GetOwnSettings(Mod.Index); + TemporarySettings = _collections.Current.GetTempSettings(Mod.Index); Settings = settings ?? ModSettings.Empty; } } diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index 671fba4d..0420ee86 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -12,6 +12,7 @@ namespace Penumbra.Mods.Settings; public class ModSettings { public static readonly ModSettings Empty = new(); + public SettingList Settings { get; internal init; } = []; public ModPriority Priority { get; set; } public bool Enabled { get; set; } diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index a0cdc2bb..27987fa6 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -5,4 +5,21 @@ public sealed class TemporaryModSettings : ModSettings public string Source = string.Empty; public int Lock = 0; public bool ForceInherit; + + // Create default settings for a given mod. + public static TemporaryModSettings DefaultSettings(Mod mod, string source, int key = 0) + => new() + { + Enabled = false, + Source = source, + Lock = key, + Priority = ModPriority.Default, + Settings = SettingList.Default(mod), + }; +} + +public static class ModSettingsExtensions +{ + public static bool IsTemporary(this ModSettings? settings) + => settings is TemporaryModSettings; } diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index b0029f08..8f1ed8d6 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -742,7 +742,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService private void OnSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx, bool inherited) { - if (collection != _collectionManager.Active.Current || mod != _mod) + if (collection != _collectionManager.Active.Current || mod != _mod || type is ModSettingChange.TemporarySetting) return; _swapData.LoadMod(_mod, _modSettings); diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 0389730d..fbead9c3 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -1,8 +1,9 @@ +using ImGuiNET; using OtterGui.Custom; namespace Penumbra.UI.Classes; -public enum ColorId +public enum ColorId : short { EnabledMod, DisabledMod, @@ -10,6 +11,7 @@ public enum ColorId InheritedMod, InheritedDisabledMod, NewMod, + NewModTint, ConflictingMod, HandledConflictMod, FolderExpanded, @@ -31,10 +33,8 @@ public enum ColorId ResTreeNonNetworked, PredefinedTagAdd, PredefinedTagRemove, - TemporaryEnabledMod, - TemporaryDisabledMod, - TemporaryInheritedMod, - TemporaryInheritedDisabledMod, + TemporaryModSettingsTint, + NoTint, } public static class Colors @@ -52,6 +52,18 @@ public static class Colors public const uint ReniColorHovered = CustomGui.ReniColorHovered; public const uint ReniColorActive = CustomGui.ReniColorActive; + public static uint Tinted(this ColorId color, ColorId tint) + { + var tintValue = ImGui.ColorConvertU32ToFloat4(tint.Value()); + var value = ImGui.ColorConvertU32ToFloat4(color.Value()); + var negAlpha = 1 - tintValue.W; + var newAlpha = negAlpha * value.W + tintValue.W; + var newR = (negAlpha * value.W * value.X + tintValue.W * tintValue.X) / newAlpha; + var newG = (negAlpha * value.W * value.Y + tintValue.W * tintValue.Y) / newAlpha; + var newB = (negAlpha * value.W * value.Z + tintValue.W * tintValue.Z) / newAlpha; + return ImGui.ColorConvertFloat4ToU32(new Vector4(newR, newG, newB, newAlpha)); + } + public static (uint DefaultColor, string Name, string Description) Data(this ColorId color) => color switch { @@ -83,10 +95,9 @@ public static class Colors ColorId.ResTreeNonNetworked => ( 0xFFC0C0FF, "On-Screen: Non-Players (Local)", "Non-player entities handled locally, in the On-Screen tab." ), ColorId.PredefinedTagAdd => ( 0xFF44AA44, "Predefined Tags: Add Tag", "A predefined tag that is not present on the current mod and can be added." ), ColorId.PredefinedTagRemove => ( 0xFF2222AA, "Predefined Tags: Remove Tag", "A predefined tag that is already present on the current mod and can be removed." ), - ColorId.TemporaryEnabledMod => ( 0xFFFFC0A0, "Mod Enabled By Temporary Settings", "A mod that is enabled by temporary settings in the currently selected collection." ), - ColorId.TemporaryDisabledMod => ( 0xFFB08070, "Mod Disabled By Temporary Settings", "A mod that is disabled by temporary settings in the currently selected collection." ), - ColorId.TemporaryInheritedMod => ( 0xFFE8FFB0, "Mod Enabled By Temporary Inheritance", "A mod that is forced to inherit by temporary settings in the currently selected collection." ), - ColorId.TemporaryInheritedDisabledMod => ( 0xFF90A080, "Mod Disabled By Temporary Inheritance", "A mod that is forced to inherit by temporary settings in the currently selected collection." ), + ColorId.TemporaryModSettingsTint => ( 0x30FF0000, "Mod with Temporary Settings", "A mod that has temporary settings. This color is used as a tint for the regular state colors." ), + ColorId.NewModTint => ( 0x8000FF00, "New Mod Tint", "A mod that was newly imported or created during this session and has not been enabled yet. This color is used as a tint for the regular state colors."), + ColorId.NoTint => ( 0x00000000, "No Tint", "The default tint for all mods."), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 4607434c..c3cb211c 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -62,6 +62,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector SetQuickMove(f, 1, _config.QuickMoveFolder2, s => { _config.QuickMoveFolder2 = s; _config.Save(); }), 120); SubscribeRightClickFolder(f => SetQuickMove(f, 2, _config.QuickMoveFolder3, s => { _config.QuickMoveFolder3 = s; _config.Save(); }), 130); SubscribeRightClickLeaf(ToggleLeafFavorite); + SubscribeRightClickLeaf(RemoveTemporarySettings); + SubscribeRightClickLeaf(DisableTemporarily); SubscribeRightClickLeaf(l => QuickMove(l, _config.QuickMoveFolder1, _config.QuickMoveFolder2, _config.QuickMoveFolder3)); SubscribeRightClickMain(ClearDefaultImportFolder, 100); SubscribeRightClickMain(() => ClearQuickMove(0, _config.QuickMoveFolder1, () => {_config.QuickMoveFolder1 = string.Empty; _config.Save();}), 110); @@ -194,7 +196,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf leaf, in ModState state, bool selected) { var flags = selected ? ImGuiTreeNodeFlags.Selected | LeafFlags : LeafFlags; - using var c = ImRaii.PushColor(ImGuiCol.Text, state.Color.Value()) + using var c = ImRaii.PushColor(ImGuiCol.Text, state.Color.Tinted(state.Tint)) .Push(ImGuiCol.HeaderHovered, 0x4000FFFF, leaf.Value.Favorite); using var id = ImRaii.PushId(leaf.Value.Index); ImRaii.TreeNode(leaf.Value.Name, flags).Dispose(); @@ -264,6 +266,23 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf mod) + { + var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); + if (tempSettings is { Lock: 0 }) + if (ImUtf8.MenuItem("Remove Temporary Settings")) + _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, null); + } + + private void DisableTemporarily(FileSystem.Leaf mod) + { + var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); + if (tempSettings == null || tempSettings.Lock == 0) + if (ImUtf8.MenuItem("Disable Temporarily")) + _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, + TemporaryModSettings.DefaultSettings(mod.Value, "User Context-Menu")); + } + private void SetDefaultImportFolder(ModFileSystem.Folder folder) { if (!ImGui.MenuItem("Set As Default Import Folder")) @@ -392,8 +411,6 @@ public sealed class ModFileSystemSelector : FileSystemSelector !_filter.IsVisible(leaf); /// Only get the text color for a mod if no filters are set. - private ColorId GetTextColor(Mod mod, ModSettings? settings, ModCollection collection) + private (ColorId Color, ColorId Tint) GetTextColor(Mod mod, ModSettings? settings, ModCollection collection) { - if (_modManager.IsNew(mod)) - return ColorId.NewMod; + var tint = settings.IsTemporary() + ? ColorId.TemporaryModSettingsTint + : _modManager.IsNew(mod) + ? ColorId.NewModTint + : ColorId.NoTint; + if (settings.IsTemporary()) + tint = ColorId.TemporaryModSettingsTint; if (settings == null) - return ColorId.UndefinedMod; + return (ColorId.UndefinedMod, tint); if (!settings.Enabled) - return collection != _collectionManager.Active.Current - ? ColorId.InheritedDisabledMod - : settings is TemporaryModSettings - ? ColorId.TemporaryDisabledMod - : ColorId.DisabledMod; - - if (settings is TemporaryModSettings) - return ColorId.TemporaryEnabledMod; + return (collection != _collectionManager.Active.Current + ? ColorId.InheritedDisabledMod + : ColorId.DisabledMod, tint); var conflicts = _collectionManager.Active.Current.Conflicts(mod); if (conflicts.Count == 0) - return collection != _collectionManager.Active.Current ? ColorId.InheritedMod : ColorId.EnabledMod; + return (collection != _collectionManager.Active.Current ? ColorId.InheritedMod : ColorId.EnabledMod, tint); - return conflicts.Any(c => !c.Solved) + return (conflicts.Any(c => !c.Solved) ? ColorId.ConflictingMod - : ColorId.HandledConflictMod; + : ColorId.HandledConflictMod, tint); } private bool CheckStateFilters(Mod mod, ModSettings? settings, ModCollection collection, ref ModState state) @@ -627,6 +645,15 @@ public sealed class ModFileSystemSelector : FileSystemSelector 0) { @@ -664,14 +686,14 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Sun, 29 Dec 2024 00:05:36 +0100 Subject: [PATCH 1023/1381] Current State. --- Penumbra.Api | 2 +- Penumbra.String | 2 +- Penumbra/Api/Api/ModSettingsApi.cs | 141 +----------------- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/Api/TemporaryApi.cs | 140 ++++++++++++++++- Penumbra/Api/IpcProviders.cs | 8 +- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 40 +++++ .../Collections/Manager/CollectionEditor.cs | 9 +- .../SchedulerResourceManagementService.cs | 2 +- .../Mods/Settings/TemporaryModSettings.cs | 16 ++ Penumbra/UI/Classes/Colors.cs | 24 ++- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 89 +++++++---- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 111 ++++++++++---- Penumbra/UI/Tabs/Debug/DebugTab.cs | 8 +- 14 files changed, 381 insertions(+), 213 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index fdda2054..882b778e 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit fdda2054c26a30111ac55984ed6efde7f7214b68 +Subproject commit 882b778e78bb0806dd7d38e8b3670ff138a84a31 diff --git a/Penumbra.String b/Penumbra.String index dd83f972..0647fbc5 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit dd83f97299ac33cfacb1064bde4f4d1f6a260936 +Subproject commit 0647fbc5017ef9ced3f3ce1c2496eefd57c5b7a8 diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 4027975b..b78523d3 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -1,5 +1,4 @@ using OtterGui; -using OtterGui.Log; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; @@ -25,20 +24,18 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable private readonly CollectionManager _collectionManager; private readonly CollectionEditor _collectionEditor; private readonly CommunicatorService _communicator; - private readonly ApiHelpers _helpers; public ModSettingsApi(CollectionResolver collectionResolver, ModManager modManager, CollectionManager collectionManager, CollectionEditor collectionEditor, - CommunicatorService communicator, ApiHelpers helpers) + CommunicatorService communicator) { _collectionResolver = collectionResolver; _modManager = modManager; _collectionManager = collectionManager; _collectionEditor = collectionEditor; _communicator = communicator; - _helpers = helpers; _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ApiModSettings); _communicator.ModSettingChanged.Subscribe(OnModSettingChange, Communication.ModSettingChanged.Priority.Api); _communicator.ModOptionChanged.Subscribe(OnModOptionEdited, ModOptionChanged.Priority.Api); @@ -209,142 +206,6 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable return ApiHelpers.Return(PenumbraApiEc.Success, args); } - public PenumbraApiEc SetTemporaryModSetting(Guid collectionId, string modDirectory, string modName, bool enabled, int priority, - IReadOnlyDictionary> options, string source, int key) - { - var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Enabled", enabled, - "Priority", priority, "Options", options, "Source", source, "Key", key); - if (!_collectionManager.Storage.ById(collectionId, out var collection)) - return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); - - return SetTemporaryModSetting(args, collection, modDirectory, modName, enabled, priority, options, source, key); - } - - public PenumbraApiEc TemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, bool enabled, int priority, - IReadOnlyDictionary> options, string source, int key) - { - return PenumbraApiEc.Success; - } - - private PenumbraApiEc SetTemporaryModSetting(in LazyString args, ModCollection collection, string modDirectory, string modName, - bool enabled, int priority, - IReadOnlyDictionary> options, string source, int key) - { - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); - - if (collection.GetTempSettings(mod.Index) is { } settings && settings.Lock != 0 && settings.Lock != key) - return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); - - settings = new TemporaryModSettings - { - Enabled = enabled, - Priority = new ModPriority(priority), - Lock = key, - Source = source, - Settings = SettingList.Default(mod), - }; - - foreach (var (groupName, optionNames) in options) - { - var groupIdx = mod.Groups.IndexOf(g => g.Name == groupName); - if (groupIdx < 0) - return ApiHelpers.Return(PenumbraApiEc.OptionGroupMissing, args); - - var setting = Setting.Zero; - switch (mod.Groups[groupIdx]) - { - case { Behaviour: GroupDrawBehaviour.SingleSelection } single: - { - var optionIdx = optionNames.Count == 0 ? -1 : single.Options.IndexOf(o => o.Name == optionNames[^1]); - if (optionIdx < 0) - return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); - - setting = Setting.Single(optionIdx); - break; - } - case { Behaviour: GroupDrawBehaviour.MultiSelection } multi: - { - foreach (var name in optionNames) - { - var optionIdx = multi.Options.IndexOf(o => o.Name == name); - if (optionIdx < 0) - return ApiHelpers.Return(PenumbraApiEc.OptionMissing, args); - - setting |= Setting.Multi(optionIdx); - } - - break; - } - } - - settings.Settings[groupIdx] = setting; - } - - collection.Settings.SetTemporary(mod.Index, settings); - return ApiHelpers.Return(PenumbraApiEc.Success, args); - } - - public PenumbraApiEc RemoveTemporaryModSettings(Guid collectionId, string modDirectory, string modName, int key) - { - var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Key", key); - if (!_collectionManager.Storage.ById(collectionId, out var collection)) - return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); - - return RemoveTemporaryModSettings(args, collection, modDirectory, modName, key); - } - - private PenumbraApiEc RemoveTemporaryModSettings(in LazyString args, ModCollection collection, string modDirectory, string modName, int key) - { - if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) - return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); - - if (collection.GetTempSettings(mod.Index) is not { } settings) - return ApiHelpers.Return(PenumbraApiEc.NothingChanged, args); - - if (settings.Lock != 0 && settings.Lock != key) - return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); - - collection.Settings.SetTemporary(mod.Index, null); - return ApiHelpers.Return(PenumbraApiEc.Success, args); - } - - public PenumbraApiEc RemoveTemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, int key) - { - return PenumbraApiEc.Success; - } - - public PenumbraApiEc RemoveAllTemporaryModSettings(Guid collectionId, int key) - { - var args = ApiHelpers.Args("CollectionId", collectionId, "Key", key); - if (!_collectionManager.Storage.ById(collectionId, out var collection)) - return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); - - return RemoveAllTemporaryModSettings(args, collection, key); - } - - public PenumbraApiEc RemoveAllTemporaryModSettingsPlayer(int objectIndex, int key) - { - return PenumbraApiEc.Success; - } - - private PenumbraApiEc RemoveAllTemporaryModSettings(in LazyString args, ModCollection collection, int key) - { - var numRemoved = 0; - for (var i = 0; i < collection.Settings.Count; ++i) - { - if (collection.GetTempSettings(i) is { } settings && (settings.Lock == 0 || settings.Lock == key)) - { - collection.Settings.SetTemporary(i, null); - ++numRemoved; - } - } - - return ApiHelpers.Return(numRemoved > 0 ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, args); - } - - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void TriggerSettingEdited(Mod mod) { diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index eaaf9f38..894b2674 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -22,7 +22,7 @@ public class PenumbraApi( } public (int Breaking, int Feature) ApiVersion - => (5, 3); + => (5, 4); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index 201839e7..afddeae8 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -1,8 +1,11 @@ +using OtterGui.Log; using OtterGui.Services; using Penumbra.Api.Enums; +using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.Interop; +using Penumbra.Mods.Manager; using Penumbra.Mods.Settings; using Penumbra.String.Classes; @@ -13,7 +16,9 @@ public class TemporaryApi( ObjectManager objects, ActorManager actors, CollectionManager collectionManager, - TempModManager tempMods) : IPenumbraApiTemporary, IApiService + TempModManager tempMods, + ApiHelpers apiHelpers, + ModManager modManager) : IPenumbraApiTemporary, IApiService { public Guid CreateTemporaryCollection(string name) => tempCollections.CreateTemporaryCollection(name); @@ -125,6 +130,139 @@ public class TemporaryApi( return ApiHelpers.Return(ret, args); } + + public PenumbraApiEc SetTemporaryModSettings(Guid collectionId, string modDirectory, string modName, bool inherit, bool enabled, int priority, + IReadOnlyDictionary> options, string source, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Inherit", inherit, "Enabled", enabled, + "Priority", priority, "Options", options, "Source", source, "Key", key); + if (!collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return SetTemporaryModSettings(args, collection, modDirectory, modName, inherit, enabled, priority, options, source, key); + } + + public PenumbraApiEc SetTemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, bool inherit, bool enabled, int priority, + IReadOnlyDictionary> options, string source, int key) + { + var args = ApiHelpers.Args("ObjectIndex", objectIndex, "ModDirectory", modDirectory, "ModName", modName, "Inherit", inherit, "Enabled", enabled, + "Priority", priority, "Options", options, "Source", source, "Key", key); + if (!apiHelpers.AssociatedCollection(objectIndex, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + return SetTemporaryModSettings(args, collection, modDirectory, modName, inherit, enabled, priority, options, source, key); + } + + private PenumbraApiEc SetTemporaryModSettings(in LazyString args, ModCollection collection, string modDirectory, string modName, + bool inherit, bool enabled, int priority, IReadOnlyDictionary> options, string source, int key) + { + if (collection.Identity.Index <= 0) + return ApiHelpers.Return(PenumbraApiEc.TemporarySettingImpossible, args); + + if (!modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + if (!collectionManager.Editor.CanSetTemporarySettings(collection, mod, key)) + if (collection.GetTempSettings(mod.Index) is { } oldSettings && oldSettings.Lock != 0 && oldSettings.Lock != key) + return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); + + var newSettings = new TemporaryModSettings() + { + ForceInherit = inherit, + Enabled = enabled, + Priority = new ModPriority(priority), + Lock = key, + Source = source, + Settings = SettingList.Default(mod), + }; + + + foreach (var (groupName, optionNames) in options) + { + var ec = ModSettingsApi.ConvertModSetting(mod, groupName, optionNames, out var groupIdx, out var setting); + if (ec != PenumbraApiEc.Success) + return ApiHelpers.Return(ec, args); + + newSettings.Settings[groupIdx] = setting; + } + + if (collectionManager.Editor.SetTemporarySettings(collection, mod, newSettings, key)) + return ApiHelpers.Return(PenumbraApiEc.Success, args); + + // This should not happen since all error cases had been checked before. + return ApiHelpers.Return(PenumbraApiEc.UnknownError, args); + } + + public PenumbraApiEc RemoveTemporaryModSettings(Guid collectionId, string modDirectory, string modName, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Key", key); + if (!collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return RemoveTemporaryModSettings(args, collection, modDirectory, modName, key); + } + + public PenumbraApiEc RemoveTemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, int key) + { + var args = ApiHelpers.Args("ObjectIndex", objectIndex, "ModDirectory", modDirectory, "ModName", modName, "Key", key); + if (!apiHelpers.AssociatedCollection(objectIndex, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + return RemoveTemporaryModSettings(args, collection, modDirectory, modName, key); + } + + private PenumbraApiEc RemoveTemporaryModSettings(in LazyString args, ModCollection collection, string modDirectory, string modName, int key) + { + if (collection.Identity.Index <= 0) + return ApiHelpers.Return(PenumbraApiEc.NothingChanged, args); + + if (!modManager.TryGetMod(modDirectory, modName, out var mod)) + return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); + + if (collection.GetTempSettings(mod.Index) is null) + return ApiHelpers.Return(PenumbraApiEc.NothingChanged, args); + + if (!collectionManager.Editor.SetTemporarySettings(collection, mod, null, key)) + return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); + + return ApiHelpers.Return(PenumbraApiEc.Success, args); + } + + public PenumbraApiEc RemoveAllTemporaryModSettings(Guid collectionId, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "Key", key); + if (!collectionManager.Storage.ById(collectionId, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); + + return RemoveAllTemporaryModSettings(args, collection, key); + } + + public PenumbraApiEc RemoveAllTemporaryModSettingsPlayer(int objectIndex, int key) + { + var args = ApiHelpers.Args("ObjectIndex", objectIndex, "Key", key); + if (!apiHelpers.AssociatedCollection(objectIndex, out var collection)) + return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); + + return RemoveAllTemporaryModSettings(args, collection, key); + } + + private PenumbraApiEc RemoveAllTemporaryModSettings(in LazyString args, ModCollection collection, int key) + { + if (collection.Identity.Index <= 0) + return ApiHelpers.Return(PenumbraApiEc.NothingChanged, args); + + var numRemoved = 0; + for (var i = 0; i < collection.Settings.Count; ++i) + { + if (collection.GetTempSettings(i) is not null + && collectionManager.Editor.SetTemporarySettings(collection, modManager[i], null, key)) + ++numRemoved; + } + + return ApiHelpers.Return(numRemoved > 0 ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, args); + } + + /// /// Convert a dictionary of strings to a dictionary of game paths to full paths. /// Only returns true if all paths can successfully be converted and added. diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 861225fa..6f3b2c38 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -63,7 +63,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ApiVersion.Provider(pi, api), new FuncProvider<(int Major, int Minor)>(pi, "Penumbra.ApiVersions", () => api.ApiVersion), // backward compatibility - new FuncProvider(pi, "Penumbra.ApiVersion", () => api.ApiVersion.Breaking), // backward compatibility + new FuncProvider(pi, "Penumbra.ApiVersion", () => api.ApiVersion.Breaking), // backward compatibility IpcSubscribers.GetModDirectory.Provider(pi, api.PluginState), IpcSubscribers.GetConfiguration.Provider(pi, api.PluginState), IpcSubscribers.ModDirectoryChanged.Provider(pi, api.PluginState), @@ -97,6 +97,12 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.AddTemporaryMod.Provider(pi, api.Temporary), IpcSubscribers.RemoveTemporaryModAll.Provider(pi, api.Temporary), IpcSubscribers.RemoveTemporaryMod.Provider(pi, api.Temporary), + IpcSubscribers.SetTemporaryModSettings.Provider(pi, api.Temporary), + IpcSubscribers.SetTemporaryModSettingsPlayer.Provider(pi, api.Temporary), + IpcSubscribers.RemoveTemporaryModSettings.Provider(pi, api.Temporary), + IpcSubscribers.RemoveTemporaryModSettingsPlayer.Provider(pi, api.Temporary), + IpcSubscribers.RemoveAllTemporaryModSettings.Provider(pi, api.Temporary), + IpcSubscribers.RemoveAllTemporaryModSettingsPlayer.Provider(pi, api.Temporary), IpcSubscribers.ChangedItemTooltip.Provider(pi, api.Ui), IpcSubscribers.ChangedItemClicked.Provider(pi, api.Ui), diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index f3c23831..2364dddf 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -33,6 +33,7 @@ public class TemporaryIpcTester( private string _tempCollectionName = string.Empty; private string _tempCollectionGuidName = string.Empty; private string _tempModName = string.Empty; + private string _modDirectory = string.Empty; private string _tempGamePath = "test/game/path.mtrl"; private string _tempFilePath = "test/success.mtrl"; private string _tempManipulation = string.Empty; @@ -50,6 +51,7 @@ public class TemporaryIpcTester( ImGuiUtil.GuidInput("##guid", "Collection GUID...", string.Empty, ref _tempGuid, ref _tempCollectionGuidName); ImGui.InputInt("##tempActorIndex", ref _tempActorIndex, 0, 0); ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); + ImGui.InputTextWithHint("##mod", "Existing Mod Name...", ref _modDirectory, 256); ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); ImUtf8.InputText("##tempManip"u8, ref _tempManipulation, "Manipulation Base64 String..."u8); @@ -121,6 +123,44 @@ public class TemporaryIpcTester( IpcTester.DrawIntro(RemoveTemporaryModAll.Label, "Remove Temporary Mod from all Collections"); if (ImGui.Button("Remove##ModAll")) _lastTempError = new RemoveTemporaryModAll(pi).Invoke(_tempModName, int.MaxValue); + + IpcTester.DrawIntro(SetTemporaryModSettings.Label, "Set Temporary Mod Settings (to default) in specific Collection"); + if (ImUtf8.Button("Set##SetTemporary"u8)) + _lastTempError = new SetTemporaryModSettings(pi).Invoke(guid, _modDirectory, string.Empty, false, true, 1337, new Dictionary>(), + "IPC Tester", 1337); + + IpcTester.DrawIntro(SetTemporaryModSettingsPlayer.Label, "Set Temporary Mod Settings (to default) in game object collection"); + if (ImUtf8.Button("Set##SetTemporaryPlayer"u8)) + _lastTempError = new SetTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, string.Empty, false, true, 1337, new Dictionary>(), + "IPC Tester", 1337); + + IpcTester.DrawIntro(RemoveTemporaryModSettings.Label, "Remove Temporary Mod Settings from specific Collection"); + if (ImUtf8.Button("Remove##RemoveTemporary"u8)) + _lastTempError = new RemoveTemporaryModSettings(pi).Invoke(guid, _modDirectory, string.Empty, 1337); + ImGui.SameLine(); + if (ImUtf8.Button("Remove (Wrong Key)##RemoveTemporary"u8)) + _lastTempError = new RemoveTemporaryModSettings(pi).Invoke(guid, _modDirectory, string.Empty, 1338); + + IpcTester.DrawIntro(RemoveTemporaryModSettingsPlayer.Label, "Remove Temporary Mod Settings from game object Collection"); + if (ImUtf8.Button("Remove##RemoveTemporaryPlayer"u8)) + _lastTempError = new RemoveTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, string.Empty, 1337); + ImGui.SameLine(); + if (ImUtf8.Button("Remove (Wrong Key)##RemoveTemporaryPlayer"u8)) + _lastTempError = new RemoveTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, string.Empty, 1338); + + IpcTester.DrawIntro(RemoveAllTemporaryModSettings.Label, "Remove All Temporary Mod Settings from specific Collection"); + if (ImUtf8.Button("Remove##RemoveAllTemporary"u8)) + _lastTempError = new RemoveAllTemporaryModSettings(pi).Invoke(guid, 1337); + ImGui.SameLine(); + if (ImUtf8.Button("Remove (Wrong Key)##RemoveAllTemporary"u8)) + _lastTempError = new RemoveAllTemporaryModSettings(pi).Invoke(guid, 1338); + + IpcTester.DrawIntro(RemoveAllTemporaryModSettingsPlayer.Label, "Remove All Temporary Mod Settings from game object Collection"); + if (ImUtf8.Button("Remove##RemoveAllTemporaryPlayer"u8)) + _lastTempError = new RemoveAllTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, 1337); + ImGui.SameLine(); + if (ImUtf8.Button("Remove (Wrong Key)##RemoveAllTemporaryPlayer"u8)) + _lastTempError = new RemoveAllTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, 1338); } public void DrawCollections() diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index b456686e..124f8cf7 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -106,8 +106,7 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu public bool SetTemporarySettings(ModCollection collection, Mod mod, TemporaryModSettings? settings, int key = 0) { key = settings?.Lock ?? key; - var old = collection.GetTempSettings(mod.Index); - if (old != null && old.Lock != 0 && old.Lock != key) + if (!CanSetTemporarySettings(collection, mod, key)) return false; collection.Settings.SetTemporary(mod.Index, settings); @@ -115,6 +114,12 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu return true; } + public bool CanSetTemporarySettings(ModCollection collection, Mod mod, int key) + { + var old = collection.GetTempSettings(mod.Index); + return old == null || old.Lock == 0 || old.Lock == key; + } + /// Copy the settings of an existing (sourceMod != null) or stored (sourceName) mod to another mod, if they exist. public bool CopyModSettings(ModCollection collection, Mod? sourceMod, string sourceName, Mod? targetMod, string targetName) { diff --git a/Penumbra/Interop/Services/SchedulerResourceManagementService.cs b/Penumbra/Interop/Services/SchedulerResourceManagementService.cs index 1d56fcdb..b7f57a44 100644 --- a/Penumbra/Interop/Services/SchedulerResourceManagementService.cs +++ b/Penumbra/Interop/Services/SchedulerResourceManagementService.cs @@ -69,7 +69,7 @@ public unsafe class SchedulerResourceManagementService : IService, IDisposable if (_actionTmbs.TryGetValue(tmb, out var rowId)) _listedTmbIds[rowId] = tmb; else - Penumbra.Log.Debug($"Action TMB {gamePath} encountered with no corresponding row ID."); + Penumbra.Log.Verbose($"Action TMB {gamePath} encountered with no corresponding row ID."); } [Signature(Sigs.SchedulerResourceManagementInstance, ScanType = ScanType.StaticAddress)] diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index 27987fa6..de4570c5 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -16,6 +16,22 @@ public sealed class TemporaryModSettings : ModSettings Priority = ModPriority.Default, Settings = SettingList.Default(mod), }; + + public TemporaryModSettings() + { } + + public TemporaryModSettings(ModSettings? clone, string source, int key = 0) + { + Source = source; + Lock = key; + ForceInherit = clone == null; + if (clone != null) + { + Enabled = clone.Enabled; + Priority = clone.Priority; + Settings = clone.Settings.Clone(); + } + } } public static class ModSettingsExtensions diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index fbead9c3..4c0d1694 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -56,12 +56,24 @@ public static class Colors { var tintValue = ImGui.ColorConvertU32ToFloat4(tint.Value()); var value = ImGui.ColorConvertU32ToFloat4(color.Value()); - var negAlpha = 1 - tintValue.W; - var newAlpha = negAlpha * value.W + tintValue.W; - var newR = (negAlpha * value.W * value.X + tintValue.W * tintValue.X) / newAlpha; - var newG = (negAlpha * value.W * value.Y + tintValue.W * tintValue.Y) / newAlpha; - var newB = (negAlpha * value.W * value.Z + tintValue.W * tintValue.Z) / newAlpha; - return ImGui.ColorConvertFloat4ToU32(new Vector4(newR, newG, newB, newAlpha)); + return ImGui.ColorConvertFloat4ToU32(TintColor(value, tintValue)); + } + + public static unsafe uint Tinted(this ImGuiCol color, ColorId tint) + { + var tintValue = ImGui.ColorConvertU32ToFloat4(tint.Value()); + ref var value = ref *ImGui.GetStyleColorVec4(color); + return ImGui.ColorConvertFloat4ToU32(TintColor(value, tintValue)); + } + + private static unsafe Vector4 TintColor(in Vector4 color, in Vector4 tint) + { + var negAlpha = 1 - tint.W; + var newAlpha = negAlpha * color.W + tint.W; + var newR = (negAlpha * color.W * color.X + tint.W * tint.X) / newAlpha; + var newG = (negAlpha * color.W * color.Y + tint.W * tint.Y) / newAlpha; + var newB = (negAlpha * color.W * color.Z + tint.W * tint.Z) / newAlpha; + return new Vector4(newR, newG, newB, newAlpha); } public static (uint DefaultColor, string Name, string Description) Data(this ColorId color) diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index dec77430..527d8bce 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections; using Penumbra.Collections.Manager; @@ -16,13 +17,19 @@ namespace Penumbra.UI.ModsTab.Groups; public sealed class ModGroupDrawer(Configuration config, CollectionManager collectionManager) : IUiService { private readonly List<(IModGroup, int)> _blockGroupCache = []; + private bool _temporary; + private bool _locked; + private TemporaryModSettings? _tempSettings; - public void Draw(Mod mod, ModSettings settings) + public void Draw(Mod mod, ModSettings settings, TemporaryModSettings? tempSettings) { if (mod.Groups.Count <= 0) return; _blockGroupCache.Clear(); + _tempSettings = tempSettings; + _temporary = tempSettings != null; + _locked = (tempSettings?.Lock ?? 0) != 0; var useDummy = true; foreach (var (group, idx) in mod.Groups.WithIndex()) { @@ -63,22 +70,23 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle /// private void DrawSingleGroupCombo(IModGroup group, int groupIdx, Setting setting) { - using var id = ImRaii.PushId(groupIdx); - var selectedOption = setting.AsIndex; + using var id = ImUtf8.PushId(groupIdx); + var selectedOption = setting.AsIndex; + using var disabled = ImRaii.Disabled(_locked); ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); var options = group.Options; - using (var combo = ImRaii.Combo(string.Empty, options[selectedOption].Name)) + using (var combo = ImUtf8.Combo(""u8, options[selectedOption].Name)) { if (combo) for (var idx2 = 0; idx2 < options.Count; ++idx2) { id.Push(idx2); var option = options[idx2]; - if (ImGui.Selectable(option.Name, idx2 == selectedOption)) + if (ImUtf8.Selectable(option.Name, idx2 == selectedOption)) SetModSetting(group, groupIdx, Setting.Single(idx2)); if (option.Description.Length > 0) - ImGuiUtil.SelectableHelpMarker(option.Description); + ImUtf8.SelectableHelpMarker(option.Description); id.Pop(); } @@ -86,9 +94,9 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle ImGui.SameLine(); if (group.Description.Length > 0) - ImGuiUtil.LabeledHelpMarker(group.Name, group.Description); + ImUtf8.LabeledHelpMarker(group.Name, group.Description); else - ImGui.TextUnformatted(group.Name); + ImUtf8.Text(group.Name); } /// @@ -97,10 +105,10 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle /// private void DrawSingleGroupRadio(IModGroup group, int groupIdx, Setting setting) { - using var id = ImRaii.PushId(groupIdx); - var selectedOption = setting.AsIndex; - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - var options = group.Options; + using var id = ImUtf8.PushId(groupIdx); + var selectedOption = setting.AsIndex; + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var options = group.Options; DrawCollapseHandling(options, minWidth, DrawOptions); Widget.EndFramedGroup(); @@ -108,11 +116,12 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle void DrawOptions() { + using var disabled = ImRaii.Disabled(_locked); for (var idx = 0; idx < group.Options.Count; ++idx) { - using var i = ImRaii.PushId(idx); - var option = options[idx]; - if (ImGui.RadioButton(option.Name, selectedOption == idx)) + using var i = ImUtf8.PushId(idx); + var option = options[idx]; + if (ImUtf8.RadioButton(option.Name, selectedOption == idx)) SetModSetting(group, groupIdx, Setting.Single(idx)); if (option.Description.Length <= 0) @@ -130,28 +139,29 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle /// private void DrawMultiGroup(IModGroup group, int groupIdx, Setting setting) { - using var id = ImRaii.PushId(groupIdx); - var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); - var options = group.Options; + using var id = ImUtf8.PushId(groupIdx); + var minWidth = Widget.BeginFramedGroup(group.Name, group.Description); + var options = group.Options; DrawCollapseHandling(options, minWidth, DrawOptions); Widget.EndFramedGroup(); var label = $"##multi{groupIdx}"; if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) - ImGui.OpenPopup($"##multi{groupIdx}"); + ImUtf8.OpenPopup($"##multi{groupIdx}"); DrawMultiPopup(group, groupIdx, label); return; void DrawOptions() { + using var disabled = ImRaii.Disabled(_locked); for (var idx = 0; idx < options.Count; ++idx) { - using var i = ImRaii.PushId(idx); - var option = options[idx]; - var enabled = setting.HasFlag(idx); + using var i = ImUtf8.PushId(idx); + var option = options[idx]; + var enabled = setting.HasFlag(idx); - if (ImGui.Checkbox(option.Name, ref enabled)) + if (ImUtf8.Checkbox(option.Name, ref enabled)) SetModSetting(group, groupIdx, setting.SetBit(idx, enabled)); if (option.Description.Length > 0) @@ -171,11 +181,12 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle return; ImGui.TextUnformatted(group.Name); + using var disabled = ImRaii.Disabled(_locked); ImGui.Separator(); - if (ImGui.Selectable("Enable All")) + if (ImUtf8.Selectable("Enable All"u8)) SetModSetting(group, groupIdx, Setting.AllBits(group.Options.Count)); - if (ImGui.Selectable("Disable All")) + if (ImUtf8.Selectable("Disable All"u8)) SetModSetting(group, groupIdx, Setting.Zero); } @@ -187,11 +198,11 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle } else { - var collapseId = ImGui.GetID("Collapse"); - var shown = ImGui.GetStateStorage().GetBool(collapseId, true); + var collapseId = ImUtf8.GetId("Collapse"); + var shown = ImGui.GetStateStorage().GetBool(collapseId, true); var buttonTextShow = $"Show {options.Count} Options"; var buttonTextHide = $"Hide {options.Count} Options"; - var buttonWidth = Math.Max(ImGui.CalcTextSize(buttonTextShow).X, ImGui.CalcTextSize(buttonTextHide).X) + var buttonWidth = Math.Max(ImUtf8.CalcTextSize(buttonTextShow).X, ImUtf8.CalcTextSize(buttonTextHide).X) + 2 * ImGui.GetStyle().FramePadding.X; minWidth = Math.Max(buttonWidth, minWidth); if (shown) @@ -204,22 +215,22 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle } - var width = Math.Max(ImGui.GetItemRectSize().X, minWidth); + var width = Math.Max(ImGui.GetItemRectSize().X, minWidth); var endPos = ImGui.GetCursorPos(); ImGui.SetCursorPos(pos); - if (ImGui.Button(buttonTextHide, new Vector2(width, 0))) + if (ImUtf8.Button(buttonTextHide, new Vector2(width, 0))) ImGui.GetStateStorage().SetBool(collapseId, !shown); ImGui.SetCursorPos(endPos); } else { - var optionWidth = options.Max(o => ImGui.CalcTextSize(o.Name).X) + var optionWidth = options.Max(o => ImUtf8.CalcTextSize(o.Name).X) + ImGui.GetStyle().ItemInnerSpacing.X + ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X; var width = Math.Max(optionWidth, minWidth); - if (ImGui.Button(buttonTextShow, new Vector2(width, 0))) + if (ImUtf8.Button(buttonTextShow, new Vector2(width, 0))) ImGui.GetStateStorage().SetBool(collapseId, !shown); } } @@ -228,6 +239,18 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle private ModCollection Current => collectionManager.Active.Current; + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void SetModSetting(IModGroup group, int groupIdx, Setting setting) - => collectionManager.Editor.SetModSetting(Current, group.Mod, groupIdx, setting); + { + if (_temporary) + { + _tempSettings!.ForceInherit = false; + _tempSettings!.Settings[groupIdx] = setting; + collectionManager.Editor.SetTemporarySettings(Current, group.Mod, _tempSettings); + } + else + { + collectionManager.Editor.SetModSetting(Current, group.Mod, groupIdx, setting); + } + } } diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 261f6e92..cf64c00a 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -1,6 +1,5 @@ using ImGuiNET; using OtterGui.Raii; -using OtterGui; using OtterGui.Services; using OtterGui.Text; using OtterGui.Widgets; @@ -24,6 +23,8 @@ public class ModPanelSettingsTab( : ITab, IUiService { private bool _inherited; + private bool _temporary; + private bool _locked; private int? _currentPriority; public ReadOnlySpan Label @@ -37,11 +38,14 @@ public class ModPanelSettingsTab( public void DrawContent() { - using var child = ImRaii.Child("##settings"); + using var child = ImUtf8.Child("##settings"u8, default); if (!child) return; - _inherited = selection.Collection != collectionManager.Active.Current; + _inherited = selection.Collection != collectionManager.Active.Current; + _temporary = selection.TemporarySettings != null; + _locked = (selection.TemporarySettings?.Lock ?? 0) != 0; + DrawTemporaryWarning(); DrawInheritedWarning(); UiHelpers.DefaultLineSpace(); communicator.PreSettingsPanelDraw.Invoke(selection.Mod!.Identifier); @@ -54,11 +58,27 @@ public class ModPanelSettingsTab( communicator.PostEnabledDraw.Invoke(selection.Mod!.Identifier); - modGroupDrawer.Draw(selection.Mod!, selection.Settings); + modGroupDrawer.Draw(selection.Mod!, selection.Settings, selection.TemporarySettings); UiHelpers.DefaultLineSpace(); communicator.PostSettingsPanelDraw.Invoke(selection.Mod!.Identifier); } + /// Draw a big tinted bar if the current setting is temporary. + private void DrawTemporaryWarning() + { + if (!_temporary) + return; + + using var color = ImRaii.PushColor(ImGuiCol.Button, ImGuiCol.Button.Tinted(ColorId.TemporaryModSettingsTint)); + var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); + if (ImUtf8.ButtonEx($"These settings are temporary from {selection.TemporarySettings!.Source}{(_locked ? " and locked." : ".")}", width, + _locked)) + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, null); + + ImUtf8.HoverTooltip("Changing settings in temporary settings will not save them across sessions.\n"u8 + + "You can click this button to remove the temporary settings and return to your normal settings."u8); + } + /// Draw a big red bar if the current setting is inherited. private void DrawInheritedWarning() { @@ -67,22 +87,42 @@ public class ModPanelSettingsTab( using var color = ImRaii.PushColor(ImGuiCol.Button, Colors.PressEnterWarningBg); var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); - if (ImGui.Button($"These settings are inherited from {selection.Collection.Identity.Name}.", width)) - collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, false); + if (ImUtf8.ButtonEx($"These settings are inherited from {selection.Collection.Identity.Name}.", width, _locked)) + { + if (_temporary) + { + selection.TemporarySettings!.ForceInherit = false; + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, selection.TemporarySettings); + } + else + { + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, false); + } + } - ImGuiUtil.HoverTooltip("You can click this button to copy the current settings to the current selection.\n" - + "You can also just change any setting, which will copy the settings with the single setting changed to the current selection."); + ImUtf8.HoverTooltip("You can click this button to copy the current settings to the current selection.\n"u8 + + "You can also just change any setting, which will copy the settings with the single setting changed to the current selection."u8); } /// Draw a checkbox for the enabled status of the mod. private void DrawEnabledInput() { - var enabled = selection.Settings.Enabled; - if (!ImGui.Checkbox("Enabled", ref enabled)) + var enabled = selection.Settings.Enabled; + using var disabled = ImRaii.Disabled(_locked); + if (!ImUtf8.Checkbox("Enabled"u8, ref enabled)) return; modManager.SetKnown(selection.Mod!); - collectionManager.Editor.SetModState(collectionManager.Active.Current, selection.Mod!, enabled); + if (_temporary) + { + selection.TemporarySettings!.ForceInherit = false; + selection.TemporarySettings!.Enabled = enabled; + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, selection.TemporarySettings); + } + else + { + collectionManager.Editor.SetModState(collectionManager.Active.Current, selection.Mod!, enabled); + } } /// @@ -91,45 +131,66 @@ public class ModPanelSettingsTab( /// private void DrawPriorityInput() { - using var group = ImRaii.Group(); + using var group = ImUtf8.Group(); var settings = selection.Settings; var priority = _currentPriority ?? settings.Priority.Value; ImGui.SetNextItemWidth(50 * UiHelpers.Scale); - if (ImGui.InputInt("##Priority", ref priority, 0, 0)) + using var disabled = ImRaii.Disabled(_locked); + if (ImUtf8.InputScalar("##Priority"u8, ref priority)) _currentPriority = priority; if (new ModPriority(priority).IsHidden) - ImUtf8.HoverTooltip($"This priority is special-cased to hide this mod in conflict tabs ({ModPriority.HiddenMin}, {ModPriority.HiddenMax})."); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + $"This priority is special-cased to hide this mod in conflict tabs ({ModPriority.HiddenMin}, {ModPriority.HiddenMax})."); if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) { if (_currentPriority != settings.Priority.Value) - collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selection.Mod!, - new ModPriority(_currentPriority.Value)); + { + if (_temporary) + { + selection.TemporarySettings!.ForceInherit = false; + selection.TemporarySettings!.Priority = new ModPriority(_currentPriority.Value); + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, + selection.TemporarySettings); + } + else + { + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selection.Mod!, + new ModPriority(_currentPriority.Value)); + } + } _currentPriority = null; } - ImGuiUtil.LabeledHelpMarker("Priority", "Mods with a higher number here take precedence before Mods with a lower number.\n" - + "That means, if Mod A should overwrite changes from Mod B, Mod A should have a higher priority number than Mod B."); + ImUtf8.LabeledHelpMarker("Priority"u8, "Mods with a higher number here take precedence before Mods with a lower number.\n"u8 + + "That means, if Mod A should overwrite changes from Mod B, Mod A should have a higher priority number than Mod B."u8); } /// /// Draw a button to remove the current settings and inherit them instead - /// on the top-right corner of the window/tab. + /// in the top-right corner of the window/tab. /// private void DrawRemoveSettings() { - const string text = "Inherit Settings"; if (_inherited || selection.Settings == ModSettings.Empty) return; var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0; - ImGui.SameLine(ImGui.GetWindowWidth() - ImGui.CalcTextSize(text).X - ImGui.GetStyle().FramePadding.X * 2 - scroll); - if (ImGui.Button(text)) - collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, true); + ImGui.SameLine(ImGui.GetWindowWidth() - ImUtf8.CalcTextSize("Inherit Settings"u8).X - ImGui.GetStyle().FramePadding.X * 2 - scroll); + if (!ImUtf8.ButtonEx("Inherit Settings"u8, "Remove current settings from this collection so that it can inherit them.\n"u8 + + "If no inherited collection has settings for this mod, it will be disabled."u8, default, _locked)) + return; - ImGuiUtil.HoverTooltip("Remove current settings from this collection so that it can inherit them.\n" - + "If no inherited collection has settings for this mod, it will be disabled."); + if (_temporary) + { + selection.TemporarySettings!.ForceInherit = true; + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, selection.TemporarySettings); + } + else + { + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, true); + } } } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 5fd38d94..c5168109 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -791,19 +791,25 @@ public class DebugTab : Window, ITab, IUiService ImGuiClip.DrawEndDummy(dummy, ImGui.GetTextLineHeightWithSpacing()); } + private string _tmbKeyFilter = string.Empty; + private CiByteString _tmbKeyFilterU8 = CiByteString.Empty; + private void DrawActionTmbs() { using var mainTree = TreeNode("Action TMBs"); if (!mainTree) return; + if (ImGui.InputText("Key", ref _tmbKeyFilter, 256)) + _tmbKeyFilterU8 = CiByteString.FromString(_tmbKeyFilter, out var r, MetaDataComputation.All) ? r : CiByteString.Empty; using var table = Table("##table", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.SizingFixedFit, new Vector2(-1, 12 * ImGui.GetTextLineHeightWithSpacing())); if (!table) return; var skips = ImGuiClip.GetNecessarySkips(ImGui.GetTextLineHeightWithSpacing()); - var dummy = ImGuiClip.ClippedDraw(_schedulerService.ActionTmbs.OrderBy(r => r.Value), skips, + var dummy = ImGuiClip.FilteredClippedDraw(_schedulerService.ActionTmbs.OrderBy(r => r.Value), skips, + kvp => kvp.Key.Contains(_tmbKeyFilterU8), p => { ImUtf8.DrawTableColumn($"{p.Value}"); From cff482a2ed1c542935b6912dc14731e50cfb14ad Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 31 Dec 2024 16:36:46 +0100 Subject: [PATCH 1024/1381] Allow non-locking, negative identifier-locks --- Penumbra/Api/Api/TemporaryApi.cs | 4 ++-- Penumbra/Collections/Manager/CollectionEditor.cs | 2 +- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 4 ++-- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index afddeae8..b12ce707 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -163,7 +163,7 @@ public class TemporaryApi( return ApiHelpers.Return(PenumbraApiEc.ModMissing, args); if (!collectionManager.Editor.CanSetTemporarySettings(collection, mod, key)) - if (collection.GetTempSettings(mod.Index) is { } oldSettings && oldSettings.Lock != 0 && oldSettings.Lock != key) + if (collection.GetTempSettings(mod.Index) is { Lock: > 0 } oldSettings && oldSettings.Lock != key) return ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args); var newSettings = new TemporaryModSettings() @@ -254,7 +254,7 @@ public class TemporaryApi( var numRemoved = 0; for (var i = 0; i < collection.Settings.Count; ++i) { - if (collection.GetTempSettings(i) is not null + if (collection.GetTempSettings(i) is {} tempSettings && tempSettings.Lock == key && collectionManager.Editor.SetTemporarySettings(collection, modManager[i], null, key)) ++numRemoved; } diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 124f8cf7..437d4e0b 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -117,7 +117,7 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu public bool CanSetTemporarySettings(ModCollection collection, Mod mod, int key) { var old = collection.GetTempSettings(mod.Index); - return old == null || old.Lock == 0 || old.Lock == key; + return old is not { Lock: > 0 } || old.Lock == key; } /// Copy the settings of an existing (sourceMod != null) or stored (sourceName) mod to another mod, if they exist. diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index 527d8bce..b723978b 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -29,7 +29,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle _blockGroupCache.Clear(); _tempSettings = tempSettings; _temporary = tempSettings != null; - _locked = (tempSettings?.Lock ?? 0) != 0; + _locked = (tempSettings?.Lock ?? 0) > 0; var useDummy = true; foreach (var (group, idx) in mod.Groups.WithIndex()) { diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index c3cb211c..091a2937 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -269,7 +269,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf mod) { var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); - if (tempSettings is { Lock: 0 }) + if (tempSettings is { Lock: <= 0 }) if (ImUtf8.MenuItem("Remove Temporary Settings")) _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, null); } @@ -277,7 +277,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf mod) { var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); - if (tempSettings == null || tempSettings.Lock == 0) + if (tempSettings is not { Lock: > 0 }) if (ImUtf8.MenuItem("Disable Temporarily")) _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, TemporaryModSettings.DefaultSettings(mod.Value, "User Context-Menu")); diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index cf64c00a..60666810 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -44,7 +44,7 @@ public class ModPanelSettingsTab( _inherited = selection.Collection != collectionManager.Active.Current; _temporary = selection.TemporarySettings != null; - _locked = (selection.TemporarySettings?.Lock ?? 0) != 0; + _locked = (selection.TemporarySettings?.Lock ?? 0) > 0; DrawTemporaryWarning(); DrawInheritedWarning(); UiHelpers.DefaultLineSpace(); From 653f6269b7b190363da723739b359b4607e764d6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 31 Dec 2024 16:38:15 +0100 Subject: [PATCH 1025/1381] Update submodule. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 882b778e..de0f281f 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 882b778e78bb0806dd7d38e8b3670ff138a84a31 +Subproject commit de0f281fbf9d8d9d3aa8463a28025d54877cde8d From dbef1cccb2b0ff89eec53ec64c814126f0a4f839 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 31 Dec 2024 17:10:09 +0100 Subject: [PATCH 1026/1381] Fix stuff after submodule update. --- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 12 ++++++------ Penumbra/Mods/Settings/TemporaryModSettings.cs | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 2364dddf..832fea82 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -126,27 +126,27 @@ public class TemporaryIpcTester( IpcTester.DrawIntro(SetTemporaryModSettings.Label, "Set Temporary Mod Settings (to default) in specific Collection"); if (ImUtf8.Button("Set##SetTemporary"u8)) - _lastTempError = new SetTemporaryModSettings(pi).Invoke(guid, _modDirectory, string.Empty, false, true, 1337, new Dictionary>(), + _lastTempError = new SetTemporaryModSettings(pi).Invoke(guid, _modDirectory, false, true, 1337, new Dictionary>(), "IPC Tester", 1337); IpcTester.DrawIntro(SetTemporaryModSettingsPlayer.Label, "Set Temporary Mod Settings (to default) in game object collection"); if (ImUtf8.Button("Set##SetTemporaryPlayer"u8)) - _lastTempError = new SetTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, string.Empty, false, true, 1337, new Dictionary>(), + _lastTempError = new SetTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, false, true, 1337, new Dictionary>(), "IPC Tester", 1337); IpcTester.DrawIntro(RemoveTemporaryModSettings.Label, "Remove Temporary Mod Settings from specific Collection"); if (ImUtf8.Button("Remove##RemoveTemporary"u8)) - _lastTempError = new RemoveTemporaryModSettings(pi).Invoke(guid, _modDirectory, string.Empty, 1337); + _lastTempError = new RemoveTemporaryModSettings(pi).Invoke(guid, _modDirectory, 1337); ImGui.SameLine(); if (ImUtf8.Button("Remove (Wrong Key)##RemoveTemporary"u8)) - _lastTempError = new RemoveTemporaryModSettings(pi).Invoke(guid, _modDirectory, string.Empty, 1338); + _lastTempError = new RemoveTemporaryModSettings(pi).Invoke(guid, _modDirectory, 1338); IpcTester.DrawIntro(RemoveTemporaryModSettingsPlayer.Label, "Remove Temporary Mod Settings from game object Collection"); if (ImUtf8.Button("Remove##RemoveTemporaryPlayer"u8)) - _lastTempError = new RemoveTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, string.Empty, 1337); + _lastTempError = new RemoveTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, 1337); ImGui.SameLine(); if (ImUtf8.Button("Remove (Wrong Key)##RemoveTemporaryPlayer"u8)) - _lastTempError = new RemoveTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, string.Empty, 1338); + _lastTempError = new RemoveTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, 1338); IpcTester.DrawIntro(RemoveAllTemporaryModSettings.Label, "Remove All Temporary Mod Settings from specific Collection"); if (ImUtf8.Button("Remove##RemoveAllTemporary"u8)) diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index de4570c5..425e0348 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -7,10 +7,10 @@ public sealed class TemporaryModSettings : ModSettings public bool ForceInherit; // Create default settings for a given mod. - public static TemporaryModSettings DefaultSettings(Mod mod, string source, int key = 0) + public static TemporaryModSettings DefaultSettings(Mod mod, string source, bool enabled = false, int key = 0) => new() { - Enabled = false, + Enabled = enabled, Source = source, Lock = key, Priority = ModPriority.Default, From a2258e61606474b9fb4d45be226918f5d498ae08 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 31 Dec 2024 17:10:18 +0100 Subject: [PATCH 1027/1381] Add some temporary context menu things. --- OtterGui | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 163 ++++++++++--------- 2 files changed, 87 insertions(+), 78 deletions(-) diff --git a/OtterGui b/OtterGui index fcc96daa..fd387218 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit fcc96daa02633f673325c14aeea6b6b568924f1e +Subproject commit fd387218d2d2d237075cb35be6ca89eeb53e14e5 diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 091a2937..280956f4 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -62,8 +62,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector SetQuickMove(f, 1, _config.QuickMoveFolder2, s => { _config.QuickMoveFolder2 = s; _config.Save(); }), 120); SubscribeRightClickFolder(f => SetQuickMove(f, 2, _config.QuickMoveFolder3, s => { _config.QuickMoveFolder3 = s; _config.Save(); }), 130); SubscribeRightClickLeaf(ToggleLeafFavorite); - SubscribeRightClickLeaf(RemoveTemporarySettings); - SubscribeRightClickLeaf(DisableTemporarily); + SubscribeRightClickLeaf(DrawTemporaryOptions); SubscribeRightClickLeaf(l => QuickMove(l, _config.QuickMoveFolder1, _config.QuickMoveFolder2, _config.QuickMoveFolder3)); SubscribeRightClickMain(ClearDefaultImportFolder, 100); SubscribeRightClickMain(() => ClearQuickMove(0, _config.QuickMoveFolder1, () => {_config.QuickMoveFolder1 = string.Empty; _config.Save();}), 110); @@ -135,7 +134,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector m.Extensions.Any(e => ValidModExtensions.Contains(e.ToLowerInvariant())), m => { - ImGui.TextUnformatted($"Dragging mods for import:\n\t{string.Join("\n\t", m.Files.Select(Path.GetFileName))}"); + ImUtf8.Text($"Dragging mods for import:\n\t{string.Join("\n\t", m.Files.Select(Path.GetFileName))}"); return true; }); base.Draw(width); @@ -198,8 +197,8 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf mod) { - if (ImGui.MenuItem(mod.Value.Favorite ? "Remove Favorite" : "Mark as Favorite")) + if (ImUtf8.MenuItem(mod.Value.Favorite ? "Remove Favorite"u8 : "Mark as Favorite"u8)) _modManager.DataEditor.ChangeModFavorite(mod.Value, !mod.Value.Favorite); } - private void RemoveTemporarySettings(FileSystem.Leaf mod) + private void DrawTemporaryOptions(FileSystem.Leaf mod) { - var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); - if (tempSettings is { Lock: <= 0 }) - if (ImUtf8.MenuItem("Remove Temporary Settings")) - _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, null); - } + const string source = "yourself"; + var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); + if (tempSettings is { Lock: > 0 }) + return; - private void DisableTemporarily(FileSystem.Leaf mod) - { - var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); - if (tempSettings is not { Lock: > 0 }) - if (ImUtf8.MenuItem("Disable Temporarily")) - _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, - TemporaryModSettings.DefaultSettings(mod.Value, "User Context-Menu")); + if (tempSettings is { Lock: <= 0 } && ImUtf8.MenuItem("Remove Temporary Settings"u8)) + _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, null); + var actual = _collectionManager.Active.Current.GetActualSettings(mod.Value.Index).Settings; + if (actual?.Enabled is true && ImUtf8.MenuItem("Disable Temporarily"u8)) + _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, + new TemporaryModSettings(actual, source) { Enabled = false }); + + if (actual is not { Enabled: true } && ImUtf8.MenuItem("Enable Temporarily"u8)) + { + var newSettings = actual is null + ? TemporaryModSettings.DefaultSettings(mod.Value, source, true) + : new TemporaryModSettings(actual, source) { Enabled = true }; + _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, newSettings); + } + + if (tempSettings is null && ImUtf8.MenuItem("Turn Temporary"u8)) + _collectionManager.Editor.SetTemporarySettings(_collectionManager.Active.Current, mod.Value, + new TemporaryModSettings(actual, source)); } private void SetDefaultImportFolder(ModFileSystem.Folder folder) { - if (!ImGui.MenuItem("Set As Default Import Folder")) + if (!ImUtf8.MenuItem("Set As Default Import Folder"u8)) return; var newName = folder.FullName(); @@ -298,7 +307,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Add an import mods button that opens a file selector. private void AddImportModButton(Vector2 size) { - var button = ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileImport.ToIconString(), size, - "Import one or multiple mods from Tex Tools Mod Pack Files or Penumbra Mod Pack Files.", !_modManager.Valid, true); + var button = ImUtf8.IconButton(FontAwesomeIcon.FileImport, + "Import one or multiple mods from Tex Tools Mod Pack Files or Penumbra Mod Pack Files."u8, size, !_modManager.Valid); _tutorial.OpenTutorial(BasicTutorialSteps.ModImport); if (!button) return; @@ -351,14 +359,14 @@ public sealed class ModFileSystemSelector : FileSystemSelector { ImGui.Dummy(Vector2.UnitY * ImGui.GetTextLineHeight()); - ImGui.TextUnformatted("Mod Management"); - ImGui.BulletText("You can create empty mods or import mods with the buttons in this row."); + ImUtf8.Text("Mod Management"u8); + ImUtf8.BulletText("You can create empty mods or import mods with the buttons in this row."u8); using var indent = ImRaii.PushIndent(); - ImGui.BulletText("Supported formats for import are: .ttmp, .ttmp2, .pmp."); - ImGui.BulletText( - "You can also support .zip, .7z or .rar archives, but only if they already contain Penumbra-styled mods with appropriate metadata."); + ImUtf8.BulletText("Supported formats for import are: .ttmp, .ttmp2, .pmp."u8); + ImUtf8.BulletText( + "You can also support .zip, .7z or .rar archives, but only if they already contain Penumbra-styled mods with appropriate metadata."u8); indent.Pop(1); - ImGui.BulletText("You can also create empty mod folders and delete mods."); - ImGui.BulletText("For further editing of mods, select them and use the Edit Mod tab in the panel or the Advanced Editing popup."); + ImUtf8.BulletText("You can also create empty mod folders and delete mods."u8); + ImUtf8.BulletText( + "For further editing of mods, select them and use the Edit Mod tab in the panel or the Advanced Editing popup."u8); ImGui.Dummy(Vector2.UnitY * ImGui.GetTextLineHeight()); - ImGui.TextUnformatted("Mod Selector"); - ImGui.BulletText("Select a mod to obtain more information or change settings."); - ImGui.BulletText("Names are colored according to your config and their current state in the collection:"); + ImUtf8.Text("Mod Selector"u8); + ImUtf8.BulletText("Select a mod to obtain more information or change settings."u8); + ImUtf8.BulletText("Names are colored according to your config and their current state in the collection:"u8); indent.Push(); - ImGuiUtil.BulletTextColored(ColorId.EnabledMod.Value(), "enabled in the current collection."); - ImGuiUtil.BulletTextColored(ColorId.DisabledMod.Value(), "disabled in the current collection."); - ImGuiUtil.BulletTextColored(ColorId.InheritedMod.Value(), "enabled due to inheritance from another collection."); - ImGuiUtil.BulletTextColored(ColorId.InheritedDisabledMod.Value(), "disabled due to inheritance from another collection."); - ImGuiUtil.BulletTextColored(ColorId.UndefinedMod.Value(), "unconfigured in all inherited collections."); - ImGuiUtil.BulletTextColored(ColorId.HandledConflictMod.Value(), - "enabled and conflicting with another enabled Mod, but on different priorities (i.e. the conflict is solved)."); - ImGuiUtil.BulletTextColored(ColorId.ConflictingMod.Value(), - "enabled and conflicting with another enabled Mod on the same priority."); - ImGuiUtil.BulletTextColored(ColorId.FolderExpanded.Value(), "expanded mod folder."); - ImGuiUtil.BulletTextColored(ColorId.FolderCollapsed.Value(), "collapsed mod folder"); + ImUtf8.BulletTextColored(ColorId.EnabledMod.Value(), "enabled in the current collection."u8); + ImUtf8.BulletTextColored(ColorId.DisabledMod.Value(), "disabled in the current collection."u8); + ImUtf8.BulletTextColored(ColorId.InheritedMod.Value(), "enabled due to inheritance from another collection."u8); + ImUtf8.BulletTextColored(ColorId.InheritedDisabledMod.Value(), "disabled due to inheritance from another collection."u8); + ImUtf8.BulletTextColored(ColorId.UndefinedMod.Value(), "unconfigured in all inherited collections."u8); + ImUtf8.BulletTextColored(ColorId.HandledConflictMod.Value(), + "enabled and conflicting with another enabled Mod, but on different priorities (i.e. the conflict is solved)."u8); + ImUtf8.BulletTextColored(ColorId.ConflictingMod.Value(), + "enabled and conflicting with another enabled Mod on the same priority."u8); + ImUtf8.BulletTextColored(ColorId.FolderExpanded.Value(), "expanded mod folder."u8); + ImUtf8.BulletTextColored(ColorId.FolderCollapsed.Value(), "collapsed mod folder"u8); indent.Pop(1); - ImGui.BulletText("Middle-click a mod to disable it if it is enabled or enable it if it is disabled."); + ImUtf8.BulletText("Middle-click a mod to disable it if it is enabled or enable it if it is disabled."u8); indent.Push(); - ImGui.BulletText( + ImUtf8.BulletText( $"Holding {_config.DeleteModModifier.ForcedModifier(new DoubleModifier(ModifierHotkey.Control, ModifierHotkey.Shift))} while middle-clicking lets it inherit, discarding settings."); indent.Pop(1); - ImGui.BulletText("Right-click a mod to enter its sort order, which is its name by default, possibly with a duplicate number."); + ImUtf8.BulletText("Right-click a mod to enter its sort order, which is its name by default, possibly with a duplicate number."u8); indent.Push(); - ImGui.BulletText("A sort order differing from the mods name will not be displayed, it will just be used for ordering."); - ImGui.BulletText( - "If the sort order string contains Forward-Slashes ('/'), the preceding substring will be turned into folders automatically."); + ImUtf8.BulletText("A sort order differing from the mods name will not be displayed, it will just be used for ordering."u8); + ImUtf8.BulletText( + "If the sort order string contains Forward-Slashes ('/'), the preceding substring will be turned into folders automatically."u8); indent.Pop(1); - ImGui.BulletText( - "You can drag and drop mods and subfolders into existing folders. Dropping them onto mods is the same as dropping them onto the parent of the mod."); + ImUtf8.BulletText( + "You can drag and drop mods and subfolders into existing folders. Dropping them onto mods is the same as dropping them onto the parent of the mod."u8); indent.Push(); - ImGui.BulletText( - "You can select multiple mods and folders by holding Control while clicking them, and then drag all of them at once."); - ImGui.BulletText( - "Selected mods inside an also selected folder will be ignored when dragging and move inside their folder instead of directly into the target."); + ImUtf8.BulletText( + "You can select multiple mods and folders by holding Control while clicking them, and then drag all of them at once."u8); + ImUtf8.BulletText( + "Selected mods inside an also selected folder will be ignored when dragging and move inside their folder instead of directly into the target."u8); indent.Pop(1); - ImGui.BulletText("Right-clicking a folder opens a context menu."); - ImGui.BulletText("Right-clicking empty space allows you to expand or collapse all folders at once."); - ImGui.BulletText("Use the Filter Mods... input at the top to filter the list for mods whose name or path contain the text."); + ImUtf8.BulletText("Right-clicking a folder opens a context menu."u8); + ImUtf8.BulletText("Right-clicking empty space allows you to expand or collapse all folders at once."u8); + ImUtf8.BulletText("Use the Filter Mods... input at the top to filter the list for mods whose name or path contain the text."u8); indent.Push(); - ImGui.BulletText("You can enter n:[string] to filter only for names, without path."); - ImGui.BulletText("You can enter c:[string] to filter for Changed Items instead."); - ImGui.BulletText("You can enter a:[string] to filter for Mod Authors instead."); + ImUtf8.BulletText("You can enter n:[string] to filter only for names, without path."u8); + ImUtf8.BulletText("You can enter c:[string] to filter for Changed Items instead."u8); + ImUtf8.BulletText("You can enter a:[string] to filter for Mod Authors instead."u8); indent.Pop(1); - ImGui.BulletText("Use the expandable menu beside the input to filter for mods fulfilling specific criteria."); + ImUtf8.BulletText("Use the expandable menu beside the input to filter for mods fulfilling specific criteria."u8); }); } @@ -729,7 +738,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Tue, 31 Dec 2024 17:56:58 +0100 Subject: [PATCH 1028/1381] Keep enabled and priority at the top of settings, add button to turn temporary. --- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 61 ++++++++++++++++------ 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 60666810..260caf26 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -38,16 +38,19 @@ public class ModPanelSettingsTab( public void DrawContent() { - using var child = ImUtf8.Child("##settings"u8, default); - if (!child) + using var table = ImUtf8.Table("##settings"u8, 1, ImGuiTableFlags.ScrollY, ImGui.GetContentRegionAvail()); + if (!table) return; _inherited = selection.Collection != collectionManager.Active.Current; _temporary = selection.TemporarySettings != null; _locked = (selection.TemporarySettings?.Lock ?? 0) > 0; + + ImGui.TableSetupScrollFreeze(0, 1); + ImGui.TableNextColumn(); DrawTemporaryWarning(); DrawInheritedWarning(); - UiHelpers.DefaultLineSpace(); + ImGui.Dummy(Vector2.Zero); communicator.PreSettingsPanelDraw.Invoke(selection.Mod!.Identifier); DrawEnabledInput(); tutorial.OpenTutorial(BasicTutorialSteps.EnablingMods); @@ -56,6 +59,7 @@ public class ModPanelSettingsTab( tutorial.OpenTutorial(BasicTutorialSteps.Priority); DrawRemoveSettings(); + ImGui.TableNextColumn(); communicator.PostEnabledDraw.Invoke(selection.Mod!.Identifier); modGroupDrawer.Draw(selection.Mod!, selection.Settings, selection.TemporarySettings); @@ -71,7 +75,8 @@ public class ModPanelSettingsTab( using var color = ImRaii.PushColor(ImGuiCol.Button, ImGuiCol.Button.Tinted(ColorId.TemporaryModSettingsTint)); var width = new Vector2(ImGui.GetContentRegionAvail().X, 0); - if (ImUtf8.ButtonEx($"These settings are temporary from {selection.TemporarySettings!.Source}{(_locked ? " and locked." : ".")}", width, + if (ImUtf8.ButtonEx($"These settings are temporarily set by {selection.TemporarySettings!.Source}{(_locked ? " and locked." : ".")}", + width, _locked)) collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, null); @@ -174,23 +179,45 @@ public class ModPanelSettingsTab( /// private void DrawRemoveSettings() { - if (_inherited || selection.Settings == ModSettings.Empty) + var drawInherited = !_inherited && selection.Settings != ModSettings.Empty; + if (!drawInherited && _temporary) return; - var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0; - ImGui.SameLine(ImGui.GetWindowWidth() - ImUtf8.CalcTextSize("Inherit Settings"u8).X - ImGui.GetStyle().FramePadding.X * 2 - scroll); - if (!ImUtf8.ButtonEx("Inherit Settings"u8, "Remove current settings from this collection so that it can inherit them.\n"u8 - + "If no inherited collection has settings for this mod, it will be disabled."u8, default, _locked)) - return; + var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X: 0; + var offset = (drawInherited, _temporary) switch + { + (true, true) => ImUtf8.CalcTextSize("Inherit Settings"u8).X + ImGui.GetStyle().FramePadding.X * 2, + (false, false) => ImUtf8.CalcTextSize("Turn Temporary"u8).X + ImGui.GetStyle().FramePadding.X * 2, + (true, false) => ImUtf8.CalcTextSize("Inherit Settings"u8).X + + ImUtf8.CalcTextSize("Turn Temporary"u8).X + + ImGui.GetStyle().FramePadding.X * 4 + + ImGui.GetStyle().ItemSpacing.X, + (false, true) => 0, // can not happen + }; - if (_temporary) + ImGui.SameLine(ImGui.GetWindowWidth() - offset - scroll); + if (!_temporary + && ImUtf8.ButtonEx("Turn Temporary"u8, "Copy the current settings over to temporary settings to experiment with them."u8)) + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, + new TemporaryModSettings(selection.Settings, "yourself")); + if (drawInherited) { - selection.TemporarySettings!.ForceInherit = true; - collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, selection.TemporarySettings); - } - else - { - collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, true); + if (!_temporary) + ImGui.SameLine(0, ImGui.GetStyle().ItemSpacing.X); + if (ImUtf8.ButtonEx("Inherit Settings"u8, "Remove current settings from this collection so that it can inherit them.\n"u8 + + "If no inherited collection has settings for this mod, it will be disabled."u8, default, _locked)) + { + if (_temporary) + { + selection.TemporarySettings!.ForceInherit = true; + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, + selection.TemporarySettings); + } + else + { + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, true); + } + } } } } From 6374362b2871a5fefe68a13a04a8da2de9171869 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 31 Dec 2024 17:05:32 +0000 Subject: [PATCH 1029/1381] [CI] Updating repo.json for testing_1.3.2.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 97e55af0..1b952d94 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.2.0", - "TestingAssemblyVersion": "1.3.2.1", + "TestingAssemblyVersion": "1.3.2.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.2.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.2.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0eed5f1707a025e376452d6b9b83f2b74d61db9a Mon Sep 17 00:00:00 2001 From: "N. Lo." Date: Sat, 21 Dec 2024 01:16:57 +0100 Subject: [PATCH 1030/1381] Add a watched plugin to Support Info --- Penumbra/Penumbra.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 69dfe3e8..33ce9f40 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -187,7 +187,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", - "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", "RoleplayingVoiceDalamud", + "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", "RoleplayingVoiceDalamud", "AQuestReborn", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) From af7a8fbddd2b9285e176a03bc720733dddbb436b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 7 Jan 2025 16:10:37 +0100 Subject: [PATCH 1031/1381] Fix bug with atch counter. --- Penumbra/Collections/CollectionCounters.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Collections/CollectionCounters.cs b/Penumbra/Collections/CollectionCounters.cs index 91d240d6..6ca0d0a0 100644 --- a/Penumbra/Collections/CollectionCounters.cs +++ b/Penumbra/Collections/CollectionCounters.cs @@ -24,5 +24,5 @@ public struct CollectionCounters(int changeCounter) /// Increment the number of ATCH-relevant changes in the effective file list. [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IncrementAtch() - => ++Imc; + => ++Atch; } From 9a457a1a953b8bf6bdce428ce62eb0bd5d027582 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 7 Jan 2025 16:11:05 +0100 Subject: [PATCH 1032/1381] Add debug panel to check changed item identification for paths. --- Penumbra/UI/Tabs/Debug/DebugTab.cs | 34 +++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index c5168109..8b2bcd77 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -36,6 +36,7 @@ using static OtterGui.Raii.ImRaii; using CharacterBase = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase; using ImGuiClip = OtterGui.ImGuiClip; using Penumbra.Api.IpcTester; +using Penumbra.GameData.Data; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.GameData.Files.StainMapStructs; @@ -102,6 +103,7 @@ public class DebugTab : Window, ITab, IUiService private readonly HookOverrideDrawer _hookOverrides; private readonly RsfService _rsfService; private readonly SchedulerResourceManagementService _schedulerService; + private readonly ObjectIdentification _objectIdentification; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -112,7 +114,7 @@ public class DebugTab : Window, ITab, IUiService TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer, - SchedulerResourceManagementService schedulerService) + SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -151,6 +153,7 @@ public class DebugTab : Window, ITab, IUiService _rsfService = rsfService; _globalVariablesDrawer = globalVariablesDrawer; _schedulerService = schedulerService; + _objectIdentification = objectIdentification; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -734,8 +737,37 @@ public class DebugTab : Window, ITab, IUiService DrawActionTmbs(); DrawStainTemplates(); DrawAtch(); + DrawChangedItemTest(); } + private string _changedItemPath = string.Empty; + private readonly Dictionary _changedItems = []; + + private void DrawChangedItemTest() + { + using var node = TreeNode("Changed Item Test"); + if (!node) + return; + + if (ImUtf8.InputText("##ChangedItemTest"u8, ref _changedItemPath, "Changed Item File Path..."u8)) + { + _changedItems.Clear(); + _objectIdentification.Identify(_changedItems, _changedItemPath); + } + + if (_changedItems.Count == 0) + return; + + using var list = ImUtf8.ListBox("##ChangedItemList"u8, + new Vector2(ImGui.GetContentRegionAvail().X, 8 * ImGui.GetTextLineHeightWithSpacing())); + if (!list) + return; + + foreach (var item in _changedItems) + ImUtf8.Selectable(item.Key); + } + + private string _emoteSearchFile = string.Empty; private string _emoteSearchName = string.Empty; From 756537c7760448176a254a8e679e7dbad0afebb1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 7 Jan 2025 16:11:26 +0100 Subject: [PATCH 1033/1381] Add Turn Permanent button for temporary settings and improve buttons, make secure. --- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 82 +++++++++++++++------- 1 file changed, 58 insertions(+), 24 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 260caf26..417c7be2 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -1,4 +1,5 @@ using ImGuiNET; +using OtterGui; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; @@ -19,7 +20,8 @@ public class ModPanelSettingsTab( ModSelection selection, TutorialService tutorial, CommunicatorService communicator, - ModGroupDrawer modGroupDrawer) + ModGroupDrawer modGroupDrawer, + Configuration config) : ITab, IUiService { private bool _inherited; @@ -180,32 +182,28 @@ public class ModPanelSettingsTab( private void DrawRemoveSettings() { var drawInherited = !_inherited && selection.Settings != ModSettings.Empty; - if (!drawInherited && _temporary) - return; - - var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X: 0; - var offset = (drawInherited, _temporary) switch - { - (true, true) => ImUtf8.CalcTextSize("Inherit Settings"u8).X + ImGui.GetStyle().FramePadding.X * 2, - (false, false) => ImUtf8.CalcTextSize("Turn Temporary"u8).X + ImGui.GetStyle().FramePadding.X * 2, - (true, false) => ImUtf8.CalcTextSize("Inherit Settings"u8).X - + ImUtf8.CalcTextSize("Turn Temporary"u8).X - + ImGui.GetStyle().FramePadding.X * 4 - + ImGui.GetStyle().ItemSpacing.X, - (false, true) => 0, // can not happen - }; - + var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X : 0; + var buttonSize = ImUtf8.CalcTextSize("Turn Permanent_"u8).X; + var offset = drawInherited + ? buttonSize + ImUtf8.CalcTextSize("Inherit Settings"u8).X + ImGui.GetStyle().FramePadding.X * 4 + ImGui.GetStyle().ItemSpacing.X + : buttonSize + ImGui.GetStyle().FramePadding.X * 2; ImGui.SameLine(ImGui.GetWindowWidth() - offset - scroll); - if (!_temporary - && ImUtf8.ButtonEx("Turn Temporary"u8, "Copy the current settings over to temporary settings to experiment with them."u8)) - collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, - new TemporaryModSettings(selection.Settings, "yourself")); + var enabled = config.DeleteModModifier.IsActive(); if (drawInherited) { - if (!_temporary) - ImGui.SameLine(0, ImGui.GetStyle().ItemSpacing.X); - if (ImUtf8.ButtonEx("Inherit Settings"u8, "Remove current settings from this collection so that it can inherit them.\n"u8 - + "If no inherited collection has settings for this mod, it will be disabled."u8, default, _locked)) + var inherit = (enabled, _locked) switch + { + (true, false) => ImUtf8.ButtonEx("Inherit Settings"u8, + "Remove current settings from this collection so that it can inherit them.\n"u8 + + "If no inherited collection has settings for this mod, it will be disabled."u8, default, false), + (false, false) => ImUtf8.ButtonEx("Inherit Settings"u8, + $"Remove current settings from this collection so that it can inherit them.\nHold {config.DeleteModModifier} to inherit.", + default, true), + (_, true) => ImUtf8.ButtonEx("Inherit Settings"u8, + "Remove current settings from this collection so that it can inherit them.\nThe settings are currently locked and can not be changed."u8, + default, true), + }; + if (inherit) { if (_temporary) { @@ -218,6 +216,42 @@ public class ModPanelSettingsTab( collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod!, true); } } + + ImGui.SameLine(); + } + + if (_temporary) + { + var overwrite = enabled + ? ImUtf8.ButtonEx("Turn Permanent"u8, + "Overwrite the actual settings for this mod in this collection with the current temporary settings."u8, + new Vector2(buttonSize, 0)) + : ImUtf8.ButtonEx("Turn Permanent"u8, + $"Overwrite the actual settings for this mod in this collection with the current temporary settings.\nHold {config.DeleteModModifier} to overwrite.", + new Vector2(buttonSize, 0), true); + if (overwrite) + { + var settings = collectionManager.Active.Current.GetTempSettings(selection.Mod!.Index)!; + if (settings.ForceInherit) + { + collectionManager.Editor.SetModInheritance(collectionManager.Active.Current, selection.Mod, true); + } + else + { + collectionManager.Editor.SetModState(collectionManager.Active.Current, selection.Mod, settings.Enabled); + collectionManager.Editor.SetModPriority(collectionManager.Active.Current, selection.Mod, settings.Priority); + foreach (var (setting, index) in settings.Settings.WithIndex()) + collectionManager.Editor.SetModSetting(collectionManager.Active.Current, selection.Mod, index, setting); + } + + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod, null); + } + } + else + { + if (ImUtf8.ButtonEx("Turn Temporary"u8, "Copy the current settings over to temporary settings to experiment with them."u8)) + collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, + new TemporaryModSettings(selection.Settings, "yourself")); } } } From 349241d0ab9cf8bd9cfb19031dfe0b12202c42a9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 7 Jan 2025 16:49:19 +0100 Subject: [PATCH 1034/1381] Better attribution of authors in item swap. --- Penumbra/Mods/ModCreator.cs | 4 +-- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 31 ++++++++++++++++++++--- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 1af9c1db..bdc16b72 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -30,12 +30,12 @@ public partial class ModCreator( public readonly Configuration Config = config; /// Creates directory and files necessary for a new mod without adding it to the manager. - public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "") + public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "", string? author = null) { try { var newDir = CreateModFolder(basePath, newName, Config.ReplaceNonAsciiOnImport, true); - dataEditor.CreateMeta(newDir, newName, Config.DefaultModAuthor, description, "1.0", string.Empty); + dataEditor.CreateMeta(newDir, newName, author ?? Config.DefaultModAuthor, description, "1.0", string.Empty); CreateDefaultFiles(newDir); return newDir; } diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index 8f1ed8d6..e590eb1e 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -12,6 +12,7 @@ using Penumbra.Communication; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; +using Penumbra.Import.Structs; using Penumbra.Meta; using Penumbra.Mods; using Penumbra.Mods.Groups; @@ -275,16 +276,38 @@ public class ItemSwapTab : IDisposable, ITab, IUiService case SwapType.Hair: case SwapType.Tail: return - $"Created by swapping {_lastTab} {_sourceId} onto {_lastTab} {_targetId} for {_currentRace.ToName()} {_currentGender.ToName()}s in {_mod!.Name}."; + $"Created by swapping {_lastTab} {_sourceId} onto {_lastTab} {_targetId} for {_currentRace.ToName()} {_currentGender.ToName()}s in {_mod!.Name}{OriginalAuthor()}"; case SwapType.BetweenSlots: return - $"Created by swapping {GetAccessorySelector(_slotFrom, true).Item3.CurrentSelection.Item.Name} onto {GetAccessorySelector(_slotTo, false).Item3.CurrentSelection.Item.Name} in {_mod!.Name}."; + $"Created by swapping {GetAccessorySelector(_slotFrom, true).Item3.CurrentSelection.Item.Name} onto {GetAccessorySelector(_slotTo, false).Item3.CurrentSelection.Item.Name} in {_mod!.Name}{OriginalAuthor()}"; default: return - $"Created by swapping {_selectors[_lastTab].Source.CurrentSelection.Item.Name} onto {_selectors[_lastTab].Target.CurrentSelection.Item.Name} in {_mod!.Name}."; + $"Created by swapping {_selectors[_lastTab].Source.CurrentSelection.Item.Name} onto {_selectors[_lastTab].Target.CurrentSelection.Item.Name} in {_mod!.Name}{OriginalAuthor()}"; } } + private string OriginalAuthor() + { + if (_mod!.Author.IsEmpty || _mod!.Author.Text is "TexTools User" or DefaultTexToolsData.Author) + return "."; + + return $" by {_mod!.Author}."; + } + + private string CreateAuthor() + { + if (_mod!.Author.IsEmpty) + return _config.DefaultModAuthor; + if (_mod!.Author.Text == _config.DefaultModAuthor) + return _config.DefaultModAuthor; + if (_mod!.Author.Text is "TexTools User" or DefaultTexToolsData.Author) + return _config.DefaultModAuthor; + if (_config.DefaultModAuthor is DefaultTexToolsData.Author) + return _mod!.Author; + + return $"{_mod!.Author} (Swap by {_config.DefaultModAuthor})"; + } + private void UpdateOption() { _selectedGroup = _mod?.Groups.FirstOrDefault(g => g.Name == _newGroupName); @@ -296,7 +319,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService private void CreateMod() { - var newDir = _modManager.Creator.CreateEmptyMod(_modManager.BasePath, _newModName, CreateDescription()); + var newDir = _modManager.Creator.CreateEmptyMod(_modManager.BasePath, _newModName, CreateDescription(), CreateAuthor()); if (newDir == null) return; From f07780cf7babb92e7421bea0df59ad8d6dc00592 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 8 Jan 2025 20:02:14 +0100 Subject: [PATCH 1035/1381] Add RenderTargetHdrEnabler --- Penumbra.GameData | 2 +- Penumbra/Configuration.cs | 1 + Penumbra/Interop/Hooks/HookSettings.cs | 1 + .../PostProcessing/RenderTargetHdrEnabler.cs | 136 ++++++++++++++++++ .../PostProcessing/ShaderReplacementFixer.cs | 9 ++ Penumbra/Penumbra.json | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 54 ++++++- Penumbra/UI/Tabs/SettingsTab.cs | 17 +++ 8 files changed, 219 insertions(+), 3 deletions(-) create mode 100644 Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 33de79bc..d5f92966 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 33de79bc62eb014298856ed5c6b6edbe819db26c +Subproject commit d5f929664c212804594fadb4e4cefe9e6a1f5d37 diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index ec5784f8..df44a51a 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -110,6 +110,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool KeepDefaultMetaChanges { get; set; } = false; public string DefaultModAuthor { get; set; } = DefaultTexToolsData.Author; public bool EditRawTileTransforms { get; set; } = false; + public bool HdrRenderTargets { get; set; } = true; public Dictionary Colors { get; set; } = Enum.GetValues().ToDictionary(c => c, c => c.Data().DefaultColor); diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 2aeeb14b..b95e5789 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -86,6 +86,7 @@ public class HookOverrides public bool ModelRendererOnRenderMaterial; public bool ModelRendererUnkFunc; public bool PrepareColorTable; + public bool RenderTargetManagerInitialize; } public struct ResourceLoadingHooks diff --git a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs new file mode 100644 index 00000000..d620935e --- /dev/null +++ b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs @@ -0,0 +1,136 @@ +using System.Collections.Immutable; +using Dalamud.Hooking; +using Dalamud.Plugin.Services; +using Dalamud.Utility.Signatures; +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks.PostProcessing; + +public unsafe class RenderTargetHdrEnabler : IService, IDisposable +{ + /// This array must be sorted by CreationOrder ascending. + private static readonly ImmutableArray ForcedTextureConfigs = + [ + new(9, TextureFormat.R16G16B16A16_FLOAT, "Main Diffuse GBuffer"), + new(10, TextureFormat.R16G16B16A16_FLOAT, "Hair Diffuse GBuffer"), + ]; + + private static readonly IComparer ForcedTextureConfigComparer + = Comparer.Create((lhs, rhs) => lhs.CreationOrder.CompareTo(rhs.CreationOrder)); + + private readonly Configuration _config; + + private readonly ThreadLocal _textureIndices = new(() => new(-1, -1)); + private readonly ThreadLocal?> _textures = new(() => null); + + public TextureReportRecord[]? TextureReport { get; private set; } + + [Signature(Sigs.RenderTargetManagerInitialize, DetourName = nameof(RenderTargetManagerInitializeDetour))] + private Hook _renderTargetManagerInitialize = null!; + + [Signature(Sigs.DeviceCreateTexture2D, DetourName = nameof(CreateTexture2DDetour))] + private Hook _createTexture2D = null!; + + public RenderTargetHdrEnabler(IGameInteropProvider interop, Configuration config) + { + _config = config; + interop.InitializeFromAttributes(this); + if (config.HdrRenderTargets && !HookOverrides.Instance.PostProcessing.RenderTargetManagerInitialize) + _renderTargetManagerInitialize.Enable(); + } + + ~RenderTargetHdrEnabler() + => Dispose(false); + + public static ForcedTextureConfig? GetForcedTextureConfig(int creationOrder) + { + var i = ForcedTextureConfigs.BinarySearch(new(creationOrder, 0, string.Empty), ForcedTextureConfigComparer); + return i >= 0 ? ForcedTextureConfigs[i] : null; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool _) + { + _renderTargetManagerInitialize.Disable(); + if (_createTexture2D.IsEnabled) + _createTexture2D.Disable(); + + _createTexture2D.Dispose(); + _renderTargetManagerInitialize.Dispose(); + } + + private nint RenderTargetManagerInitializeDetour(RenderTargetManager* @this) + { + _createTexture2D.Enable(); + _textureIndices.Value = new(0, 0); + _textures.Value = _config.DebugMode ? [] : null; + try + { + return _renderTargetManagerInitialize.Original(@this); + } + finally + { + if (_textures.Value != null) + { + TextureReport = CreateTextureReport(@this, _textures.Value); + _textures.Value = null; + } + _textureIndices.Value = new(-1, -1); + _createTexture2D.Disable(); + } + } + + private Texture* CreateTexture2DDetour( + Device* @this, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk) + { + var originalTextureFormat = textureFormat; + var indices = _textureIndices.IsValueCreated ? _textureIndices.Value : new(-1, -1); + if (indices.ConfigIndex >= 0 && indices.ConfigIndex < ForcedTextureConfigs.Length && + ForcedTextureConfigs[indices.ConfigIndex].CreationOrder == indices.CreationOrder) + { + var config = ForcedTextureConfigs[indices.ConfigIndex++]; + textureFormat = (uint)config.ForcedTextureFormat; + } + + if (indices.CreationOrder >= 0) + { + ++indices.CreationOrder; + _textureIndices.Value = indices; + } + + var texture = _createTexture2D.Original(@this, size, mipLevel, textureFormat, flags, unk); + if (_textures.IsValueCreated) + _textures.Value?.Add((nint)texture, (indices.CreationOrder - 1, originalTextureFormat)); + return texture; + } + + private static TextureReportRecord[] CreateTextureReport(RenderTargetManager* renderTargetManager, Dictionary textures) + { + var rtmTextures = new Span(renderTargetManager, sizeof(RenderTargetManager) / sizeof(nint)); + var report = new List(); + for (var i = 0; i < rtmTextures.Length; ++i) + { + if (textures.TryGetValue(rtmTextures[i], out var texture)) + report.Add(new(i * sizeof(nint), texture.TextureIndex, (TextureFormat)texture.TextureFormat)); + } + return report.ToArray(); + } + + private delegate nint RenderTargetManagerInitializeFunc(RenderTargetManager* @this); + + private delegate Texture* CreateTexture2DFunc(Device* @this, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk); + + private record struct TextureIndices(int CreationOrder, int ConfigIndex); + + public readonly record struct ForcedTextureConfig(int CreationOrder, TextureFormat ForcedTextureFormat, string Comment); + + public readonly record struct TextureReportRecord(nint Offset, int CreationOrder, TextureFormat OriginalTextureFormat); +} diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 40958eb4..3b41e752 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -7,6 +7,7 @@ using OtterGui.Classes; using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData; +using Penumbra.GameData.Files.MaterialStructs; using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.Structs; using Penumbra.Services; @@ -462,8 +463,16 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic return mtrlResource; } + private static int GetDataSetExpectedSize(uint dataFlags) + => (dataFlags & 4) != 0 + ? ColorTable.Size + ((dataFlags & 8) != 0 ? ColorDyeTable.Size : 0) + : 0; + private Texture* PrepareColorTableDetour(MaterialResourceHandle* thisPtr, byte stain0Id, byte stain1Id) { + if (thisPtr->DataSetSize < GetDataSetExpectedSize(thisPtr->DataFlags)) + Penumbra.Log.Warning($"Material at {thisPtr->FileName} has data set of size {thisPtr->DataSetSize} bytes, but should have at least {GetDataSetExpectedSize(thisPtr->DataFlags)} bytes. This may cause crashes due to access violations."); + // If we don't have any on-screen instances of modded characterlegacy.shpk, we don't need the slow path at all. if (!Enabled || GetTotalMaterialCountForColorTable() == 0) return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 4790da18..968bb750 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -10,7 +10,7 @@ "Tags": [ "modding" ], "DalamudApiLevel": 11, "LoadPriority": 69420, - "LoadState": 2, + "LoadRequiredState": 2, "LoadSync": true, "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 8b2bcd77..a759e11a 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -42,6 +42,7 @@ using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.GameData.Files.StainMapStructs; using Penumbra.String.Classes; using Penumbra.UI.AdvancedWindow.Materials; +using CSGraphics = FFXIVClientStructs.FFXIV.Client.Graphics; namespace Penumbra.UI.Tabs.Debug; @@ -104,6 +105,7 @@ public class DebugTab : Window, ITab, IUiService private readonly RsfService _rsfService; private readonly SchedulerResourceManagementService _schedulerService; private readonly ObjectIdentification _objectIdentification; + private readonly RenderTargetHdrEnabler _renderTargetHdrEnabler; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -114,7 +116,7 @@ public class DebugTab : Window, ITab, IUiService TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer, - SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification) + SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification, RenderTargetHdrEnabler renderTargetHdrEnabler) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -154,6 +156,7 @@ public class DebugTab : Window, ITab, IUiService _globalVariablesDrawer = globalVariablesDrawer; _schedulerService = schedulerService; _objectIdentification = objectIdentification; + _renderTargetHdrEnabler = renderTargetHdrEnabler; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -189,6 +192,7 @@ public class DebugTab : Window, ITab, IUiService DrawData(); DrawCrcCache(); DrawResourceProblems(); + DrawRenderTargets(); _hookOverrides.Draw(); DrawPlayerModelInfo(); _globalVariablesDrawer.Draw(); @@ -1135,6 +1139,54 @@ public class DebugTab : Window, ITab, IUiService } + /// Draw information about render targets. + private unsafe void DrawRenderTargets() + { + if (!ImGui.CollapsingHeader("Render Targets")) + return; + + var report = _renderTargetHdrEnabler.TextureReport; + if (report == null) + { + ImGui.TextUnformatted("The RenderTargetManager report has not been gathered."); + ImGui.TextUnformatted("Please restart the game with Debug Mode and Wait for Plugins on Startup enabled to fill this section."); + return; + } + + using var table = Table("##RenderTargetTable", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImUtf8.TableSetupColumn("Offset"u8, ImGuiTableColumnFlags.WidthStretch, 0.15f); + ImUtf8.TableSetupColumn("Creation Order"u8, ImGuiTableColumnFlags.WidthStretch, 0.15f); + ImUtf8.TableSetupColumn("Original Texture Format"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImUtf8.TableSetupColumn("Current Texture Format"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImUtf8.TableSetupColumn("Comment"u8, ImGuiTableColumnFlags.WidthStretch, 0.3f); + ImGui.TableHeadersRow(); + + foreach (var record in report) + { + ImGui.TableNextColumn(); + ImUtf8.Text($"0x{record.Offset:X}"); + ImGui.TableNextColumn(); + ImUtf8.Text($"{record.CreationOrder}"); + ImGui.TableNextColumn(); + ImUtf8.Text($"{record.OriginalTextureFormat}"); + ImGui.TableNextColumn(); + var texture = *(CSGraphics.Kernel.Texture**)((nint)CSGraphics.Render.RenderTargetManager.Instance() + record.Offset); + if (texture != null) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGuiUtil.HalfBlendText(0xFF), texture->TextureFormat != record.OriginalTextureFormat); + ImUtf8.Text($"{texture->TextureFormat}"); + } + ImGui.TableNextColumn(); + var forcedConfig = RenderTargetHdrEnabler.GetForcedTextureConfig(record.CreationOrder); + if (forcedConfig.HasValue) + ImGui.TextUnformatted(forcedConfig.Value.Comment); + } + } + + /// Draw information about IPC options and availability. private void DrawDebugTabIpc() { diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 46e214cf..64fa57a5 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -773,6 +773,7 @@ public class SettingsTab : ITab, IUiService DrawCrashHandler(); DrawMinimumDimensionConfig(); + DrawHdrRenderTargets(); Checkbox("Auto Deduplicate on Import", "Automatically deduplicate mod files on import. This will make mod file sizes smaller, but deletes (binary identical) files.", _config.AutoDeduplicateOnImport, v => _config.AutoDeduplicateOnImport = v); @@ -902,6 +903,22 @@ public class SettingsTab : ITab, IUiService _config.Save(); } + private void DrawHdrRenderTargets() + { + var item = _config.HdrRenderTargets ? 1 : 0; + ImGui.SetNextItemWidth(ImGui.CalcTextSize("M").X * 5.0f + ImGui.GetFrameHeight()); + var edited = ImGui.Combo("##hdrRenderTarget", ref item, "SDR\0HDR\0"); + ImGui.SameLine(); + ImGuiUtil.LabeledHelpMarker("Diffuse Dynamic Range", + "Set the dynamic range that can be used for diffuse colors in materials without causing visual artifacts.\nChanging this setting requires a game restart. It also only works if Wait for Plugins on Startup is enabled."); + + if (!edited) + return; + + _config.HdrRenderTargets = item != 0; + _config.Save(); + } + /// Draw a checkbox for the HTTP API that creates and destroys the web server when toggled. private void DrawEnableHttpApiBox() { From e8300fc5c83acc6f86dbaa5086869f721478317b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 9 Jan 2025 20:42:48 +0100 Subject: [PATCH 1036/1381] Improve RT-HDR texture comments --- .../Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs index d620935e..80106fc9 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs @@ -14,8 +14,8 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable /// This array must be sorted by CreationOrder ascending. private static readonly ImmutableArray ForcedTextureConfigs = [ - new(9, TextureFormat.R16G16B16A16_FLOAT, "Main Diffuse GBuffer"), - new(10, TextureFormat.R16G16B16A16_FLOAT, "Hair Diffuse GBuffer"), + new(9, TextureFormat.R16G16B16A16_FLOAT, "Opaque Diffuse GBuffer"), + new(10, TextureFormat.R16G16B16A16_FLOAT, "Semitransparent Diffuse GBuffer"), ]; private static readonly IComparer ForcedTextureConfigComparer From b83564bce8424daaa7b0facfb91a19dac6062850 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 10 Jan 2025 19:55:33 +0100 Subject: [PATCH 1037/1381] 1.3.3.0 --- Penumbra/UI/Changelog.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index c78ca290..f83c8989 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -56,10 +56,28 @@ public class PenumbraChangelog : IUiService Add1_3_0_0(Changelog); Add1_3_1_0(Changelog); Add1_3_2_0(Changelog); + Add1_3_3_0(Changelog); } #region Changelogs + private static void Add1_3_3_0(Changelog log) + => log.NextVersion("Version 1.3.3.0") + .RegisterHighlight("Added Temporary Settings to collections.") + .RegisterEntry("Settings can be manually turned temporary (and turned back) while editing mod settings via right-click context on the mod or buttons in the settings panel.", 1) + .RegisterEntry("This can be used to test mods or changes without saving those changes permanently or having to reinstate the old settings afterwards.", 1) + .RegisterEntry("More importantly, this can be set via IPC by other plugins, allowing Glamourer to only set and reset temporary settings when applying Mod Associations.", 1) + .RegisterEntry("As an extreme example, it would be possible to only enable the consistent mods for your character in the collection, and let Glamourer handle all outfit mods itself via temporary settings only.", 1) + .RegisterEntry("This required some pretty big changes that were in testing for a while now, but nobody talked about it much so it may still have some bugs or usability issues. Let me know!", 1) + .RegisterHighlight("Added an option to automatically select the collection assigned to the current character on login events. This is off by default.") + .RegisterEntry("Added partial copying of color tables in material editing via right-click context menu entries on the import buttons.") + .RegisterHighlight("Added handling for TMB files cached by the game that should resolve issues of leaky TMBs from animation and VFX mods.") + .RegisterEntry("The enabled checkbox, Priority and Inheriting buttons now stick at the top of the Mod Settings panel even when scrolling down for specific settings.") + .RegisterEntry("When creating new mods with Item Swap, the attributed author of the resulting mod was improved.") + .RegisterEntry("Fixed an issue with rings in the On-Screen tab and in the data sent over to other plugins via IPC.") + .RegisterEntry("Fixed some issues when writing material files that resulted in technically valid files that still caused some issues with the game for unknown reasons.") + .RegisterEntry("Fixed some ImGui assertions."); + private static void Add1_3_2_0(Changelog log) => log.NextVersion("Version 1.3.2.0") .RegisterHighlight("Added ATCH meta manipulations that allow the composite editing of attachment points across multiple mods.") From e6872cff64a8764d21bc7d37a2e11083825b3596 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 10 Jan 2025 19:00:27 +0000 Subject: [PATCH 1038/1381] [CI] Updating repo.json for 1.3.3.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 1b952d94..25dd6da4 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.2.0", - "TestingAssemblyVersion": "1.3.2.2", + "AssemblyVersion": "1.3.3.0", + "TestingAssemblyVersion": "1.3.3.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.2.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.2.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From d4e6688369961f38b365ee4611dc7d1a807ef7b4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 13:26:43 +0100 Subject: [PATCH 1039/1381] Fix issue when empty settings are turned temporary. --- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 417c7be2..2420f06b 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -249,9 +249,10 @@ public class ModPanelSettingsTab( } else { + var actual = collectionManager.Active.Current.GetActualSettings(selection.Mod!.Index).Settings; if (ImUtf8.ButtonEx("Turn Temporary"u8, "Copy the current settings over to temporary settings to experiment with them."u8)) collectionManager.Editor.SetTemporarySettings(collectionManager.Active.Current, selection.Mod!, - new TemporaryModSettings(selection.Settings, "yourself")); + new TemporaryModSettings(actual, "yourself")); } } } From 0758739666917a98304d8cdb8288924a67152084 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 13:46:08 +0100 Subject: [PATCH 1040/1381] Cleanup UI code. --- Penumbra/UI/Tabs/Debug/DebugTab.cs | 57 ++----------------- Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs | 59 ++++++++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 34 +++++++---- 3 files changed, 86 insertions(+), 64 deletions(-) create mode 100644 Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index a759e11a..77eeb3d7 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -42,7 +42,6 @@ using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.GameData.Files.StainMapStructs; using Penumbra.String.Classes; using Penumbra.UI.AdvancedWindow.Materials; -using CSGraphics = FFXIVClientStructs.FFXIV.Client.Graphics; namespace Penumbra.UI.Tabs.Debug; @@ -105,7 +104,7 @@ public class DebugTab : Window, ITab, IUiService private readonly RsfService _rsfService; private readonly SchedulerResourceManagementService _schedulerService; private readonly ObjectIdentification _objectIdentification; - private readonly RenderTargetHdrEnabler _renderTargetHdrEnabler; + private readonly RenderTargetDrawer _renderTargetDrawer; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -116,7 +115,7 @@ public class DebugTab : Window, ITab, IUiService TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer, - SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification, RenderTargetHdrEnabler renderTargetHdrEnabler) + SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification, RenderTargetDrawer renderTargetDrawer) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -156,7 +155,7 @@ public class DebugTab : Window, ITab, IUiService _globalVariablesDrawer = globalVariablesDrawer; _schedulerService = schedulerService; _objectIdentification = objectIdentification; - _renderTargetHdrEnabler = renderTargetHdrEnabler; + _renderTargetDrawer = renderTargetDrawer; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -192,7 +191,7 @@ public class DebugTab : Window, ITab, IUiService DrawData(); DrawCrcCache(); DrawResourceProblems(); - DrawRenderTargets(); + _renderTargetDrawer.Draw(); _hookOverrides.Draw(); DrawPlayerModelInfo(); _globalVariablesDrawer.Draw(); @@ -1139,54 +1138,6 @@ public class DebugTab : Window, ITab, IUiService } - /// Draw information about render targets. - private unsafe void DrawRenderTargets() - { - if (!ImGui.CollapsingHeader("Render Targets")) - return; - - var report = _renderTargetHdrEnabler.TextureReport; - if (report == null) - { - ImGui.TextUnformatted("The RenderTargetManager report has not been gathered."); - ImGui.TextUnformatted("Please restart the game with Debug Mode and Wait for Plugins on Startup enabled to fill this section."); - return; - } - - using var table = Table("##RenderTargetTable", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit); - if (!table) - return; - - ImUtf8.TableSetupColumn("Offset"u8, ImGuiTableColumnFlags.WidthStretch, 0.15f); - ImUtf8.TableSetupColumn("Creation Order"u8, ImGuiTableColumnFlags.WidthStretch, 0.15f); - ImUtf8.TableSetupColumn("Original Texture Format"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); - ImUtf8.TableSetupColumn("Current Texture Format"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); - ImUtf8.TableSetupColumn("Comment"u8, ImGuiTableColumnFlags.WidthStretch, 0.3f); - ImGui.TableHeadersRow(); - - foreach (var record in report) - { - ImGui.TableNextColumn(); - ImUtf8.Text($"0x{record.Offset:X}"); - ImGui.TableNextColumn(); - ImUtf8.Text($"{record.CreationOrder}"); - ImGui.TableNextColumn(); - ImUtf8.Text($"{record.OriginalTextureFormat}"); - ImGui.TableNextColumn(); - var texture = *(CSGraphics.Kernel.Texture**)((nint)CSGraphics.Render.RenderTargetManager.Instance() + record.Offset); - if (texture != null) - { - using var color = ImRaii.PushColor(ImGuiCol.Text, ImGuiUtil.HalfBlendText(0xFF), texture->TextureFormat != record.OriginalTextureFormat); - ImUtf8.Text($"{texture->TextureFormat}"); - } - ImGui.TableNextColumn(); - var forcedConfig = RenderTargetHdrEnabler.GetForcedTextureConfig(record.CreationOrder); - if (forcedConfig.HasValue) - ImGui.TextUnformatted(forcedConfig.Value.Comment); - } - } - - /// Draw information about IPC options and availability. private void DrawDebugTabIpc() { diff --git a/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs b/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs new file mode 100644 index 00000000..09c8b06c --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs @@ -0,0 +1,59 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; +using FFXIVClientStructs.FFXIV.Client.Graphics.Render; +using ImGuiNET; +using OtterGui; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Interop.Hooks.PostProcessing; + +namespace Penumbra.UI.Tabs.Debug; + +public class RenderTargetDrawer(RenderTargetHdrEnabler renderTargetHdrEnabler) : IUiService +{ + /// Draw information about render targets. + public unsafe void Draw() + { + if (!ImUtf8.CollapsingHeader("Render Targets"u8)) + return; + + var report = renderTargetHdrEnabler.TextureReport; + if (report == null) + { + ImUtf8.Text("The RenderTargetManager report has not been gathered."u8); + ImUtf8.Text("Please restart the game with Debug Mode and Wait for Plugins on Startup enabled to fill this section."u8); + return; + } + + using var table = ImUtf8.Table("##RenderTargetTable"u8, 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit); + if (!table) + return; + + ImUtf8.TableSetupColumn("Offset"u8, ImGuiTableColumnFlags.WidthStretch, 0.15f); + ImUtf8.TableSetupColumn("Creation Order"u8, ImGuiTableColumnFlags.WidthStretch, 0.15f); + ImUtf8.TableSetupColumn("Original Texture Format"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImUtf8.TableSetupColumn("Current Texture Format"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImUtf8.TableSetupColumn("Comment"u8, ImGuiTableColumnFlags.WidthStretch, 0.3f); + ImGui.TableHeadersRow(); + + foreach (var record in report) + { + ImUtf8.DrawTableColumn($"0x{record.Offset:X}"); + ImUtf8.DrawTableColumn($"{record.CreationOrder}"); + ImUtf8.DrawTableColumn($"{record.OriginalTextureFormat}"); + ImGui.TableNextColumn(); + var texture = *(Texture**)((nint)RenderTargetManager.Instance() + + record.Offset); + if (texture != null) + { + using var color = Dalamud.Interface.Utility.Raii.ImRaii.PushColor(ImGuiCol.Text, ImGuiUtil.HalfBlendText(0xFF), + texture->TextureFormat != record.OriginalTextureFormat); + ImUtf8.Text($"{texture->TextureFormat}"); + } + + ImGui.TableNextColumn(); + var forcedConfig = RenderTargetHdrEnabler.GetForcedTextureConfig(record.CreationOrder); + if (forcedConfig.HasValue) + ImUtf8.Text(forcedConfig.Value.Comment); + } + } +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 64fa57a5..c7f66859 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -10,6 +10,7 @@ using OtterGui.Compression; using OtterGui.Custom; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections; @@ -905,18 +906,29 @@ public class SettingsTab : ITab, IUiService private void DrawHdrRenderTargets() { - var item = _config.HdrRenderTargets ? 1 : 0; - ImGui.SetNextItemWidth(ImGui.CalcTextSize("M").X * 5.0f + ImGui.GetFrameHeight()); - var edited = ImGui.Combo("##hdrRenderTarget", ref item, "SDR\0HDR\0"); + ImGui.SetNextItemWidth(ImUtf8.CalcTextSize("M"u8).X * 5.0f + ImGui.GetFrameHeight()); + using (var combo = ImUtf8.Combo("##hdrRenderTarget"u8, _config.HdrRenderTargets ? "HDR"u8 : "SDR"u8)) + { + if (combo) + { + if (ImUtf8.Selectable("HDR"u8, _config.HdrRenderTargets) && !_config.HdrRenderTargets) + { + _config.HdrRenderTargets = true; + _config.Save(); + } + + if (ImUtf8.Selectable("SDR"u8, !_config.HdrRenderTargets) && _config.HdrRenderTargets) + { + _config.HdrRenderTargets = false; + _config.Save(); + } + } + } + ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Diffuse Dynamic Range", - "Set the dynamic range that can be used for diffuse colors in materials without causing visual artifacts.\nChanging this setting requires a game restart. It also only works if Wait for Plugins on Startup is enabled."); - - if (!edited) - return; - - _config.HdrRenderTargets = item != 0; - _config.Save(); + ImUtf8.LabeledHelpMarker("Diffuse Dynamic Range"u8, + "Set the dynamic range that can be used for diffuse colors in materials without causing visual artifacts.\n"u8 + + "Changing this setting requires a game restart. It also only works if Wait for Plugins on Startup is enabled."u8); } /// Draw a checkbox for the HTTP API that creates and destroys the web server when toggled. From e73b3e85bdd9e136761108299040433a3314e937 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 13:46:28 +0100 Subject: [PATCH 1041/1381] Autoformat and remove nagging. --- .../PostProcessing/RenderTargetHdrEnabler.cs | 41 +++++++++-------- .../PostProcessing/ShaderReplacementFixer.cs | 46 +++++++++---------- 2 files changed, 44 insertions(+), 43 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs index 80106fc9..b7ae771b 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs @@ -14,8 +14,8 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable /// This array must be sorted by CreationOrder ascending. private static readonly ImmutableArray ForcedTextureConfigs = [ - new(9, TextureFormat.R16G16B16A16_FLOAT, "Opaque Diffuse GBuffer"), - new(10, TextureFormat.R16G16B16A16_FLOAT, "Semitransparent Diffuse GBuffer"), + new ForcedTextureConfig(9, TextureFormat.R16G16B16A16_FLOAT, "Opaque Diffuse GBuffer"), + new ForcedTextureConfig(10, TextureFormat.R16G16B16A16_FLOAT, "Semitransparent Diffuse GBuffer"), ]; private static readonly IComparer ForcedTextureConfigComparer @@ -23,16 +23,17 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable private readonly Configuration _config; - private readonly ThreadLocal _textureIndices = new(() => new(-1, -1)); + private readonly ThreadLocal _textureIndices = new(() => new TextureIndices(-1, -1)); + private readonly ThreadLocal?> _textures = new(() => null); public TextureReportRecord[]? TextureReport { get; private set; } [Signature(Sigs.RenderTargetManagerInitialize, DetourName = nameof(RenderTargetManagerInitializeDetour))] - private Hook _renderTargetManagerInitialize = null!; + private readonly Hook _renderTargetManagerInitialize = null!; [Signature(Sigs.DeviceCreateTexture2D, DetourName = nameof(CreateTexture2DDetour))] - private Hook _createTexture2D = null!; + private readonly Hook _createTexture2D = null!; public RenderTargetHdrEnabler(IGameInteropProvider interop, Configuration config) { @@ -47,7 +48,7 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable public static ForcedTextureConfig? GetForcedTextureConfig(int creationOrder) { - var i = ForcedTextureConfigs.BinarySearch(new(creationOrder, 0, string.Empty), ForcedTextureConfigComparer); + var i = ForcedTextureConfigs.BinarySearch(new ForcedTextureConfig(creationOrder, 0, string.Empty), ForcedTextureConfigComparer); return i >= 0 ? ForcedTextureConfigs[i] : null; } @@ -59,10 +60,6 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable private void Dispose(bool _) { - _renderTargetManagerInitialize.Disable(); - if (_createTexture2D.IsEnabled) - _createTexture2D.Disable(); - _createTexture2D.Dispose(); _renderTargetManagerInitialize.Dispose(); } @@ -70,8 +67,8 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable private nint RenderTargetManagerInitializeDetour(RenderTargetManager* @this) { _createTexture2D.Enable(); - _textureIndices.Value = new(0, 0); - _textures.Value = _config.DebugMode ? [] : null; + _textureIndices.Value = new TextureIndices(0, 0); + _textures.Value = _config.DebugMode ? [] : null; try { return _renderTargetManagerInitialize.Original(@this); @@ -80,10 +77,11 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable { if (_textures.Value != null) { - TextureReport = CreateTextureReport(@this, _textures.Value); + TextureReport = CreateTextureReport(@this, _textures.Value); _textures.Value = null; } - _textureIndices.Value = new(-1, -1); + + _textureIndices.Value = new TextureIndices(-1, -1); _createTexture2D.Disable(); } } @@ -92,9 +90,10 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable Device* @this, int* size, byte mipLevel, uint textureFormat, uint flags, uint unk) { var originalTextureFormat = textureFormat; - var indices = _textureIndices.IsValueCreated ? _textureIndices.Value : new(-1, -1); - if (indices.ConfigIndex >= 0 && indices.ConfigIndex < ForcedTextureConfigs.Length && - ForcedTextureConfigs[indices.ConfigIndex].CreationOrder == indices.CreationOrder) + var indices = _textureIndices.IsValueCreated ? _textureIndices.Value : new TextureIndices(-1, -1); + if (indices.ConfigIndex >= 0 + && indices.ConfigIndex < ForcedTextureConfigs.Length + && ForcedTextureConfigs[indices.ConfigIndex].CreationOrder == indices.CreationOrder) { var config = ForcedTextureConfigs[indices.ConfigIndex++]; textureFormat = (uint)config.ForcedTextureFormat; @@ -112,15 +111,17 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable return texture; } - private static TextureReportRecord[] CreateTextureReport(RenderTargetManager* renderTargetManager, Dictionary textures) + private static TextureReportRecord[] CreateTextureReport(RenderTargetManager* renderTargetManager, + Dictionary textures) { var rtmTextures = new Span(renderTargetManager, sizeof(RenderTargetManager) / sizeof(nint)); - var report = new List(); + var report = new List(); for (var i = 0; i < rtmTextures.Length; ++i) { if (textures.TryGetValue(rtmTextures[i], out var texture)) - report.Add(new(i * sizeof(nint), texture.TextureIndex, (TextureFormat)texture.TextureFormat)); + report.Add(new TextureReportRecord(i * sizeof(nint), texture.TextureIndex, (TextureFormat)texture.TextureFormat)); } + return report.ToArray(); } diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 3b41e752..f70ea06e 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -64,8 +64,6 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private readonly ResourceHandleDestructor _resourceHandleDestructor; private readonly CommunicatorService _communicator; - private readonly CharacterUtility _utility; - private readonly ModelRenderer _modelRenderer; private readonly HumanSetupScalingHook _humanSetupScalingHook; private readonly ModdedShaderPackageState _skinState; @@ -111,31 +109,31 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables, HumanSetupScalingHook humanSetupScalingHook) { _resourceHandleDestructor = resourceHandleDestructor; - _utility = utility; - _modelRenderer = modelRenderer; - _communicator = communicator; - _humanSetupScalingHook = humanSetupScalingHook; + var utility1 = utility; + var modelRenderer1 = modelRenderer; + _communicator = communicator; + _humanSetupScalingHook = humanSetupScalingHook; _skinState = new ModdedShaderPackageState( - () => (ShaderPackageResourceHandle**)&_utility.Address->SkinShpkResource, - () => (ShaderPackageResourceHandle*)_utility.DefaultSkinShpkResource); + () => (ShaderPackageResourceHandle**)&utility1.Address->SkinShpkResource, + () => (ShaderPackageResourceHandle*)utility1.DefaultSkinShpkResource); _characterStockingsState = new ModdedShaderPackageState( - () => (ShaderPackageResourceHandle**)&_utility.Address->CharacterStockingsShpkResource, - () => (ShaderPackageResourceHandle*)_utility.DefaultCharacterStockingsShpkResource); + () => (ShaderPackageResourceHandle**)&utility1.Address->CharacterStockingsShpkResource, + () => (ShaderPackageResourceHandle*)utility1.DefaultCharacterStockingsShpkResource); _characterLegacyState = new ModdedShaderPackageState( - () => (ShaderPackageResourceHandle**)&_utility.Address->CharacterLegacyShpkResource, - () => (ShaderPackageResourceHandle*)_utility.DefaultCharacterLegacyShpkResource); - _irisState = new ModdedShaderPackageState(() => _modelRenderer.IrisShaderPackage, () => _modelRenderer.DefaultIrisShaderPackage); - _characterGlassState = new ModdedShaderPackageState(() => _modelRenderer.CharacterGlassShaderPackage, - () => _modelRenderer.DefaultCharacterGlassShaderPackage); - _characterTransparencyState = new ModdedShaderPackageState(() => _modelRenderer.CharacterTransparencyShaderPackage, - () => _modelRenderer.DefaultCharacterTransparencyShaderPackage); - _characterTattooState = new ModdedShaderPackageState(() => _modelRenderer.CharacterTattooShaderPackage, - () => _modelRenderer.DefaultCharacterTattooShaderPackage); - _characterOcclusionState = new ModdedShaderPackageState(() => _modelRenderer.CharacterOcclusionShaderPackage, - () => _modelRenderer.DefaultCharacterOcclusionShaderPackage); + () => (ShaderPackageResourceHandle**)&utility1.Address->CharacterLegacyShpkResource, + () => (ShaderPackageResourceHandle*)utility1.DefaultCharacterLegacyShpkResource); + _irisState = new ModdedShaderPackageState(() => modelRenderer1.IrisShaderPackage, () => modelRenderer1.DefaultIrisShaderPackage); + _characterGlassState = new ModdedShaderPackageState(() => modelRenderer1.CharacterGlassShaderPackage, + () => modelRenderer1.DefaultCharacterGlassShaderPackage); + _characterTransparencyState = new ModdedShaderPackageState(() => modelRenderer1.CharacterTransparencyShaderPackage, + () => modelRenderer1.DefaultCharacterTransparencyShaderPackage); + _characterTattooState = new ModdedShaderPackageState(() => modelRenderer1.CharacterTattooShaderPackage, + () => modelRenderer1.DefaultCharacterTattooShaderPackage); + _characterOcclusionState = new ModdedShaderPackageState(() => modelRenderer1.CharacterOcclusionShaderPackage, + () => modelRenderer1.DefaultCharacterOcclusionShaderPackage); _hairMaskState = - new ModdedShaderPackageState(() => _modelRenderer.HairMaskShaderPackage, () => _modelRenderer.DefaultHairMaskShaderPackage); + new ModdedShaderPackageState(() => modelRenderer1.HairMaskShaderPackage, () => modelRenderer1.DefaultHairMaskShaderPackage); _humanSetupScalingHook.SetupReplacements += SetupHssReplacements; _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[64], @@ -463,6 +461,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic return mtrlResource; } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private static int GetDataSetExpectedSize(uint dataFlags) => (dataFlags & 4) != 0 ? ColorTable.Size + ((dataFlags & 8) != 0 ? ColorDyeTable.Size : 0) @@ -471,7 +470,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private Texture* PrepareColorTableDetour(MaterialResourceHandle* thisPtr, byte stain0Id, byte stain1Id) { if (thisPtr->DataSetSize < GetDataSetExpectedSize(thisPtr->DataFlags)) - Penumbra.Log.Warning($"Material at {thisPtr->FileName} has data set of size {thisPtr->DataSetSize} bytes, but should have at least {GetDataSetExpectedSize(thisPtr->DataFlags)} bytes. This may cause crashes due to access violations."); + Penumbra.Log.Warning( + $"Material at {thisPtr->FileName} has data set of size {thisPtr->DataSetSize} bytes, but should have at least {GetDataSetExpectedSize(thisPtr->DataFlags)} bytes. This may cause crashes due to access violations."); // If we don't have any on-screen instances of modded characterlegacy.shpk, we don't need the slow path at all. if (!Enabled || GetTotalMaterialCountForColorTable() == 0) From c99a7884bb38d8ce2fd1d21c4b705e51b946369e Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 11 Jan 2025 12:49:05 +0000 Subject: [PATCH 1042/1381] [CI] Updating repo.json for 1.3.3.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 25dd6da4..41956dc3 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.3.0", - "TestingAssemblyVersion": "1.3.3.0", + "AssemblyVersion": "1.3.3.1", + "TestingAssemblyVersion": "1.3.3.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 7b2e82b27f1f378d82e68055df48ae758af0ad71 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 15:22:04 +0100 Subject: [PATCH 1043/1381] Add some HDR related debug data and support info. --- .../PostProcessing/RenderTargetHdrEnabler.cs | 36 ++++++++++++++-- .../PostProcessing/ShaderReplacementFixer.cs | 34 ++++++++------- Penumbra/Penumbra.cs | 13 +++--- Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs | 41 ++++++++++++++++++- 4 files changed, 96 insertions(+), 28 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs index b7ae771b..41c4dab1 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs @@ -1,11 +1,13 @@ using System.Collections.Immutable; using Dalamud.Hooking; +using Dalamud.Plugin; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using OtterGui.Services; using Penumbra.GameData; +using Penumbra.Services; namespace Penumbra.Interop.Hooks.PostProcessing; @@ -21,9 +23,9 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable private static readonly IComparer ForcedTextureConfigComparer = Comparer.Create((lhs, rhs) => lhs.CreationOrder.CompareTo(rhs.CreationOrder)); - private readonly Configuration _config; - - private readonly ThreadLocal _textureIndices = new(() => new TextureIndices(-1, -1)); + private readonly Configuration _config; + private readonly Tuple _share; + private readonly ThreadLocal _textureIndices = new(() => new TextureIndices(-1, -1)); private readonly ThreadLocal?> _textures = new(() => null); @@ -35,17 +37,42 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable [Signature(Sigs.DeviceCreateTexture2D, DetourName = nameof(CreateTexture2DDetour))] private readonly Hook _createTexture2D = null!; - public RenderTargetHdrEnabler(IGameInteropProvider interop, Configuration config) + public RenderTargetHdrEnabler(IGameInteropProvider interop, Configuration config, IDalamudPluginInterface pi, + DalamudConfigService dalamudConfig) { _config = config; interop.InitializeFromAttributes(this); if (config.HdrRenderTargets && !HookOverrides.Instance.PostProcessing.RenderTargetManagerInitialize) _renderTargetManagerInitialize.Enable(); + + _share = pi.GetOrCreateData("Penumbra.RenderTargetHDR.V1", () => + { + bool? waitForPlugins = dalamudConfig.GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool s) ? s : null; + return new Tuple(waitForPlugins, config.HdrRenderTargets, + !HookOverrides.Instance.PostProcessing.RenderTargetManagerInitialize, [0], [false]); + }); + ++_share.Item4[0]; } + public bool? FirstLaunchWaitForPluginsState + => _share.Item1; + + public bool FirstLaunchHdrState + => _share.Item2; + + public bool FirstLaunchHdrHookOverrideState + => _share.Item3; + + public int PenumbraReloadCount + => _share.Item4[0]; + + public bool HdrEnabledSuccess + => _share.Item5[0]; + ~RenderTargetHdrEnabler() => Dispose(false); + public static ForcedTextureConfig? GetForcedTextureConfig(int creationOrder) { var i = ForcedTextureConfigs.BinarySearch(new ForcedTextureConfig(creationOrder, 0, string.Empty), ForcedTextureConfigComparer); @@ -67,6 +94,7 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable private nint RenderTargetManagerInitializeDetour(RenderTargetManager* @this) { _createTexture2D.Enable(); + _share.Item5[0] = true; _textureIndices.Value = new TextureIndices(0, 0); _textures.Value = _config.DebugMode ? [] : null; try diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index f70ea06e..cae37776 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -109,31 +109,29 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables, HumanSetupScalingHook humanSetupScalingHook) { _resourceHandleDestructor = resourceHandleDestructor; - var utility1 = utility; - var modelRenderer1 = modelRenderer; _communicator = communicator; _humanSetupScalingHook = humanSetupScalingHook; _skinState = new ModdedShaderPackageState( - () => (ShaderPackageResourceHandle**)&utility1.Address->SkinShpkResource, - () => (ShaderPackageResourceHandle*)utility1.DefaultSkinShpkResource); + () => (ShaderPackageResourceHandle**)&utility.Address->SkinShpkResource, + () => (ShaderPackageResourceHandle*)utility.DefaultSkinShpkResource); _characterStockingsState = new ModdedShaderPackageState( - () => (ShaderPackageResourceHandle**)&utility1.Address->CharacterStockingsShpkResource, - () => (ShaderPackageResourceHandle*)utility1.DefaultCharacterStockingsShpkResource); + () => (ShaderPackageResourceHandle**)&utility.Address->CharacterStockingsShpkResource, + () => (ShaderPackageResourceHandle*)utility.DefaultCharacterStockingsShpkResource); _characterLegacyState = new ModdedShaderPackageState( - () => (ShaderPackageResourceHandle**)&utility1.Address->CharacterLegacyShpkResource, - () => (ShaderPackageResourceHandle*)utility1.DefaultCharacterLegacyShpkResource); - _irisState = new ModdedShaderPackageState(() => modelRenderer1.IrisShaderPackage, () => modelRenderer1.DefaultIrisShaderPackage); - _characterGlassState = new ModdedShaderPackageState(() => modelRenderer1.CharacterGlassShaderPackage, - () => modelRenderer1.DefaultCharacterGlassShaderPackage); - _characterTransparencyState = new ModdedShaderPackageState(() => modelRenderer1.CharacterTransparencyShaderPackage, - () => modelRenderer1.DefaultCharacterTransparencyShaderPackage); - _characterTattooState = new ModdedShaderPackageState(() => modelRenderer1.CharacterTattooShaderPackage, - () => modelRenderer1.DefaultCharacterTattooShaderPackage); - _characterOcclusionState = new ModdedShaderPackageState(() => modelRenderer1.CharacterOcclusionShaderPackage, - () => modelRenderer1.DefaultCharacterOcclusionShaderPackage); + () => (ShaderPackageResourceHandle**)&utility.Address->CharacterLegacyShpkResource, + () => (ShaderPackageResourceHandle*)utility.DefaultCharacterLegacyShpkResource); + _irisState = new ModdedShaderPackageState(() => modelRenderer.IrisShaderPackage, () => modelRenderer.DefaultIrisShaderPackage); + _characterGlassState = new ModdedShaderPackageState(() => modelRenderer.CharacterGlassShaderPackage, + () => modelRenderer.DefaultCharacterGlassShaderPackage); + _characterTransparencyState = new ModdedShaderPackageState(() => modelRenderer.CharacterTransparencyShaderPackage, + () => modelRenderer.DefaultCharacterTransparencyShaderPackage); + _characterTattooState = new ModdedShaderPackageState(() => modelRenderer.CharacterTattooShaderPackage, + () => modelRenderer.DefaultCharacterTattooShaderPackage); + _characterOcclusionState = new ModdedShaderPackageState(() => modelRenderer.CharacterOcclusionShaderPackage, + () => modelRenderer.DefaultCharacterOcclusionShaderPackage); _hairMaskState = - new ModdedShaderPackageState(() => modelRenderer1.HairMaskShaderPackage, () => modelRenderer1.DefaultHairMaskShaderPackage); + new ModdedShaderPackageState(() => modelRenderer.HairMaskShaderPackage, () => modelRenderer.DefaultHairMaskShaderPackage); _humanSetupScalingHook.SetupReplacements += SetupHssReplacements; _humanOnRenderMaterialHook = hooks.CreateHook("Human.OnRenderMaterial", vTables.HumanVTable[64], diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 33ce9f40..b6009627 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -23,6 +23,7 @@ using Lumina.Excel.Sheets; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.Interop.Hooks; +using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; namespace Penumbra; @@ -205,9 +206,10 @@ public class Penumbra : IDalamudPlugin public string GatherSupportInformation() { - var sb = new StringBuilder(10240); - var exists = _config.ModDirectory.Length > 0 && Directory.Exists(_config.ModDirectory); - var drive = exists ? new DriveInfo(new DirectoryInfo(_config.ModDirectory).Root.FullName) : null; + var sb = new StringBuilder(10240); + var exists = _config.ModDirectory.Length > 0 && Directory.Exists(_config.ModDirectory); + var hdrEnabler = _services.GetService(); + var drive = exists ? new DriveInfo(new DirectoryInfo(_config.ModDirectory).Root.FullName) : null; sb.AppendLine("**Settings**"); sb.Append($"> **`Plugin Version: `** {_validityChecker.Version}\n"); sb.Append($"> **`Commit Hash: `** {_validityChecker.CommitHash}\n"); @@ -223,9 +225,10 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Auto-Deduplication: `** {_config.AutoDeduplicateOnImport}\n"); sb.Append($"> **`Auto-UI-Reduplication: `** {_config.AutoReduplicateUiOnImport}\n"); sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); + sb.Append($"> **`Penumbra Reloads: `** {hdrEnabler.PenumbraReloadCount}\n"); + sb.Append($"> **`HDR Enabled (from Start): `** {_config.HdrRenderTargets} ({hdrEnabler is { FirstLaunchHdrState: true, FirstLaunchHdrHookOverrideState: true }}){(hdrEnabler.HdrEnabledSuccess ? ", Detour Called" : ", **NEVER CALLED**")}\n"); sb.Append($"> **`Hook Overrides: `** {HookOverrides.Instance.IsCustomLoaded}\n"); - sb.Append( - $"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")}\n"); + sb.Append($"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")} (first Start: {hdrEnabler.FirstLaunchWaitForPluginsState?.ToString() ?? "Unknown"})\n"); sb.Append( $"> **`Logging: `** Log: {_config.Ephemeral.EnableResourceLogging}, Watcher: {_config.Ephemeral.EnableResourceWatcher} ({_config.MaxResourceWatcherRecords})\n"); sb.Append($"> **`Use Ownership: `** {_config.UseOwnerNameForCharacterCollection}\n"); diff --git a/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs b/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs index 09c8b06c..c8c90e09 100644 --- a/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs @@ -4,18 +4,57 @@ using ImGuiNET; using OtterGui; using OtterGui.Services; using OtterGui.Text; +using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.PostProcessing; +using Penumbra.Services; namespace Penumbra.UI.Tabs.Debug; -public class RenderTargetDrawer(RenderTargetHdrEnabler renderTargetHdrEnabler) : IUiService +public class RenderTargetDrawer(RenderTargetHdrEnabler renderTargetHdrEnabler, DalamudConfigService dalamudConfig, Configuration config) : IUiService { + private void DrawStatistics() + { + using (ImUtf8.Group()) + { + ImUtf8.Text("Wait For Plugins (Now)"); + ImUtf8.Text("Wait For Plugins (First Launch)"); + + ImUtf8.Text("HDR Enabled (Now)"); + ImUtf8.Text("HDR Enabled (First Launch)"); + + ImUtf8.Text("HDR Hook Overriden (Now)"); + ImUtf8.Text("HDR Hook Overriden (First Launch)"); + + ImUtf8.Text("HDR Detour Called"); + ImUtf8.Text("Penumbra Reload Count"); + } + ImGui.SameLine(); + using (ImUtf8.Group()) + { + ImUtf8.Text($"{(dalamudConfig.GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool w) ? w.ToString() : "Unknown")}"); + ImUtf8.Text($"{renderTargetHdrEnabler.FirstLaunchWaitForPluginsState?.ToString() ?? "Unknown"}"); + + ImUtf8.Text($"{config.HdrRenderTargets}"); + ImUtf8.Text($"{renderTargetHdrEnabler.FirstLaunchHdrState}"); + + ImUtf8.Text($"{HookOverrides.Instance.PostProcessing.RenderTargetManagerInitialize}"); + ImUtf8.Text($"{!renderTargetHdrEnabler.FirstLaunchHdrHookOverrideState}"); + + ImUtf8.Text($"{renderTargetHdrEnabler.HdrEnabledSuccess}"); + ImUtf8.Text($"{renderTargetHdrEnabler.PenumbraReloadCount}"); + } + } + /// Draw information about render targets. public unsafe void Draw() { if (!ImUtf8.CollapsingHeader("Render Targets"u8)) return; + DrawStatistics(); + ImUtf8.Dummy(0); + ImGui.Separator(); + ImUtf8.Dummy(0); var report = renderTargetHdrEnabler.TextureReport; if (report == null) { From 2753c786fc938cb63a729945974d1e334e3a3934 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 15:55:14 +0100 Subject: [PATCH 1044/1381] Only put out warnings if the path is rooted. --- Penumbra.String | 2 +- .../Hooks/PostProcessing/ShaderReplacementFixer.cs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Penumbra.String b/Penumbra.String index 0647fbc5..b9003b97 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 0647fbc5017ef9ced3f3ce1c2496eefd57c5b7a8 +Subproject commit b9003b97da2d1191fa203a4d66956bc54c21db2a diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index cae37776..8e12662e 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -11,6 +11,7 @@ using Penumbra.GameData.Files.MaterialStructs; using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.Structs; using Penumbra.Services; +using Penumbra.String.Classes; using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; using CSModelRenderer = FFXIVClientStructs.FFXIV.Client.Graphics.Render.ModelRenderer; using ModelRenderer = Penumbra.Interop.Services.ModelRenderer; @@ -109,8 +110,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic CommunicatorService communicator, HookManager hooks, CharacterBaseVTables vTables, HumanSetupScalingHook humanSetupScalingHook) { _resourceHandleDestructor = resourceHandleDestructor; - _communicator = communicator; - _humanSetupScalingHook = humanSetupScalingHook; + _communicator = communicator; + _humanSetupScalingHook = humanSetupScalingHook; _skinState = new ModdedShaderPackageState( () => (ShaderPackageResourceHandle**)&utility.Address->SkinShpkResource, @@ -467,7 +468,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private Texture* PrepareColorTableDetour(MaterialResourceHandle* thisPtr, byte stain0Id, byte stain1Id) { - if (thisPtr->DataSetSize < GetDataSetExpectedSize(thisPtr->DataFlags)) + if (thisPtr->DataSetSize < GetDataSetExpectedSize(thisPtr->DataFlags) && Utf8GamePath.IsRooted(thisPtr->FileName.AsSpan())) Penumbra.Log.Warning( $"Material at {thisPtr->FileName} has data set of size {thisPtr->DataSetSize} bytes, but should have at least {GetDataSetExpectedSize(thisPtr->DataFlags)} bytes. This may cause crashes due to access violations."); @@ -507,9 +508,8 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private readonly ConcurrentSet _materials = new(); // ConcurrentDictionary.Count uses a lock in its current implementation. - private uint _materialCount = 0; - - private ulong _slowPathCallDelta = 0; + private uint _materialCount; + private ulong _slowPathCallDelta; public uint MaterialCount { From 7f52777fd48011606d6317934bcdd02f5183573e Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 11 Jan 2025 14:58:57 +0000 Subject: [PATCH 1045/1381] [CI] Updating repo.json for testing_1.3.3.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 41956dc3..ec1fc623 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.1", + "TestingAssemblyVersion": "1.3.3.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 6ea38eac0a2b050940a030423012344cc26cbb21 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 17:59:44 +0100 Subject: [PATCH 1046/1381] Share PeSigScanner and use in RenderTargetHdrEnabler because of ReShade. --- .../PostProcessing/RenderTargetHdrEnabler.cs | 33 +++++++++++-------- .../Hooks/ResourceLoading/PapHandler.cs | 4 +-- .../Hooks/ResourceLoading/PapRewriter.cs | 9 ++--- .../Hooks/ResourceLoading/PeSigScanner.cs | 3 +- .../Hooks/ResourceLoading/ResourceLoader.cs | 4 +-- 5 files changed, 28 insertions(+), 25 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs index 41c4dab1..653d9c1a 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/RenderTargetHdrEnabler.cs @@ -7,6 +7,7 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using OtterGui.Services; using Penumbra.GameData; +using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Services; namespace Penumbra.Interop.Hooks.PostProcessing; @@ -31,19 +32,23 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable public TextureReportRecord[]? TextureReport { get; private set; } - [Signature(Sigs.RenderTargetManagerInitialize, DetourName = nameof(RenderTargetManagerInitializeDetour))] - private readonly Hook _renderTargetManagerInitialize = null!; - - [Signature(Sigs.DeviceCreateTexture2D, DetourName = nameof(CreateTexture2DDetour))] - private readonly Hook _createTexture2D = null!; + private readonly Hook? _renderTargetManagerInitialize; + private readonly Hook? _createTexture2D; public RenderTargetHdrEnabler(IGameInteropProvider interop, Configuration config, IDalamudPluginInterface pi, - DalamudConfigService dalamudConfig) + DalamudConfigService dalamudConfig, PeSigScanner peScanner) { _config = config; - interop.InitializeFromAttributes(this); - if (config.HdrRenderTargets && !HookOverrides.Instance.PostProcessing.RenderTargetManagerInitialize) - _renderTargetManagerInitialize.Enable(); + if (peScanner.TryScanText(Sigs.RenderTargetManagerInitialize, out var initializeAddress) + && peScanner.TryScanText(Sigs.DeviceCreateTexture2D, out var createAddress)) + { + _renderTargetManagerInitialize = + interop.HookFromAddress(initializeAddress, RenderTargetManagerInitializeDetour); + _createTexture2D = interop.HookFromAddress(createAddress, CreateTexture2DDetour); + + if (config.HdrRenderTargets && !HookOverrides.Instance.PostProcessing.RenderTargetManagerInitialize) + _renderTargetManagerInitialize.Enable(); + } _share = pi.GetOrCreateData("Penumbra.RenderTargetHDR.V1", () => { @@ -87,19 +92,19 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable private void Dispose(bool _) { - _createTexture2D.Dispose(); - _renderTargetManagerInitialize.Dispose(); + _createTexture2D?.Dispose(); + _renderTargetManagerInitialize?.Dispose(); } private nint RenderTargetManagerInitializeDetour(RenderTargetManager* @this) { - _createTexture2D.Enable(); + _createTexture2D!.Enable(); _share.Item5[0] = true; _textureIndices.Value = new TextureIndices(0, 0); _textures.Value = _config.DebugMode ? [] : null; try { - return _renderTargetManagerInitialize.Original(@this); + return _renderTargetManagerInitialize!.Original(@this); } finally { @@ -133,7 +138,7 @@ public unsafe class RenderTargetHdrEnabler : IService, IDisposable _textureIndices.Value = indices; } - var texture = _createTexture2D.Original(@this, size, mipLevel, textureFormat, flags, unk); + var texture = _createTexture2D!.Original(@this, size, mipLevel, textureFormat, flags, unk); if (_textures.IsValueCreated) _textures.Value?.Add((nint)texture, (indices.CreationOrder - 1, originalTextureFormat)); return texture; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs index 5ba8c975..35ee86dc 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapHandler.cs @@ -2,9 +2,9 @@ namespace Penumbra.Interop.Hooks.ResourceLoading; -public sealed class PapHandler(PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable +public sealed class PapHandler(PeSigScanner sigScanner, PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable { - private readonly PapRewriter _papRewriter = new(papResourceHandler); + private readonly PapRewriter _papRewriter = new(sigScanner, papResourceHandler); public void Enable() { diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index 2fb1623d..5fdec816 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -7,21 +7,20 @@ using Swan; namespace Penumbra.Interop.Hooks.ResourceLoading; -public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable +public sealed class PapRewriter(PeSigScanner sigScanner, PapRewriter.PapResourceHandlerPrototype papResourceHandler) : IDisposable { public unsafe delegate int PapResourceHandlerPrototype(void* self, byte* path, int length); - private readonly PeSigScanner _scanner = new(); private readonly Dictionary _hooks = []; private readonly Dictionary<(nint, Register, ulong), nint> _nativeAllocPaths = []; private readonly List _nativeAllocCaves = []; public void Rewrite(string sig, string name) { - if (!_scanner.TryScanText(sig, out var address)) + if (!sigScanner.TryScanText(sig, out var address)) throw new Exception($"Signature for {name} [{sig}] could not be found."); - var funcInstructions = _scanner.GetFunctionInstructions(address).ToArray(); + var funcInstructions = sigScanner.GetFunctionInstructions(address).ToArray(); var hookPoints = ScanPapHookPoints(funcInstructions).ToList(); foreach (var hookPoint in hookPoints) @@ -165,8 +164,6 @@ public sealed class PapRewriter(PapRewriter.PapResourceHandlerPrototype papResou public void Dispose() { - _scanner.Dispose(); - foreach (var hook in _hooks.Values) { hook.Disable(); diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs index 4be0da00..620f3160 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PeSigScanner.cs @@ -1,12 +1,13 @@ using System.IO.MemoryMappedFiles; using Iced.Intel; +using OtterGui.Services; using PeNet; using Decoder = Iced.Intel.Decoder; namespace Penumbra.Interop.Hooks.ResourceLoading; // A good chunk of this was blatantly stolen from Dalamud's SigScanner 'cause Winter could not be faffed, Winter will definitely not rewrite it later -public unsafe class PeSigScanner : IDisposable +public unsafe class PeSigScanner : IDisposable, IService { private readonly MemoryMappedFile _file; private readonly MemoryMappedViewAccessor _textSection; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 47f96d98..ad9c41e6 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -22,7 +22,7 @@ public unsafe class ResourceLoader : IDisposable, IService private ResolveData _resolvedData = ResolveData.Invalid; public event Action? PapRequested; - public ResourceLoader(ResourceService resources, FileReadService fileReadService, RsfService rsfService, Configuration config) + public ResourceLoader(ResourceService resources, FileReadService fileReadService, RsfService rsfService, Configuration config, PeSigScanner sigScanner) { _resources = resources; _fileReadService = fileReadService; @@ -35,7 +35,7 @@ public unsafe class ResourceLoader : IDisposable, IService _resources.ResourceHandleDecRef += DecRefProtection; _fileReadService.ReadSqPack += ReadSqPackDetour; - _papHandler = new PapHandler(PapResourceHandler); + _papHandler = new PapHandler(sigScanner, PapResourceHandler); _papHandler.Enable(); } From 3687c99ee6d385af21e22371f6492f3bcb11c20c Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 11 Jan 2025 17:02:43 +0000 Subject: [PATCH 1047/1381] [CI] Updating repo.json for testing_1.3.3.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index ec1fc623..14c5d8ac 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.2", + "TestingAssemblyVersion": "1.3.3.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 415e15f3b150e0ee662447cbffe7340b45f50845 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Jan 2025 21:12:14 +0100 Subject: [PATCH 1048/1381] Fix another issue with temporary mod settings. --- Penumbra/Mods/Settings/TemporaryModSettings.cs | 10 ++++++++-- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 6 +++--- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index 425e0348..fa71e1b6 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -20,17 +20,23 @@ public sealed class TemporaryModSettings : ModSettings public TemporaryModSettings() { } - public TemporaryModSettings(ModSettings? clone, string source, int key = 0) + public TemporaryModSettings(Mod mod, ModSettings? clone, string source, int key = 0) { Source = source; Lock = key; ForceInherit = clone == null; - if (clone != null) + if (clone != null && clone != Empty) { Enabled = clone.Enabled; Priority = clone.Priority; Settings = clone.Settings.Clone(); } + else + { + Enabled = false; + Priority = ModPriority.Default; + Settings = SettingList.Default(mod); + } } } diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 280956f4..1a7d4e31 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -277,19 +277,19 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Sun, 12 Jan 2025 00:03:36 +0100 Subject: [PATCH 1049/1381] Add counts to multi mod selection. --- Penumbra/UI/ModsTab/MultiModPanel.cs | 90 +++++++++++++++++----------- 1 file changed, 56 insertions(+), 34 deletions(-) diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs index 4079748e..0e9b5d39 100644 --- a/Penumbra/UI/ModsTab/MultiModPanel.cs +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -4,65 +4,88 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Mods; using Penumbra.Mods.Manager; namespace Penumbra.UI.ModsTab; -public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _editor) : IUiService +public class MultiModPanel(ModFileSystemSelector selector, ModDataEditor editor) : IUiService { public void Draw() { - if (_selector.SelectedPaths.Count == 0) + if (selector.SelectedPaths.Count == 0) return; ImGui.NewLine(); - DrawModList(); + var treeNodePos = ImGui.GetCursorPos(); + var numLeaves = DrawModList(); + DrawCounts(treeNodePos, numLeaves); DrawMultiTagger(); } - private void DrawModList() + private void DrawCounts(Vector2 treeNodePos, int numLeaves) { - using var tree = ImRaii.TreeNode("Currently Selected Objects", ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.NoTreePushOnOpen); - ImGui.Separator(); - if (!tree) - return; + var startPos = ImGui.GetCursorPos(); + var numFolders = selector.SelectedPaths.Count - numLeaves; + var text = (numLeaves, numFolders) switch + { + (0, 0) => string.Empty, // should not happen + (> 0, 0) => $"{numLeaves} Mods", + (0, > 0) => $"{numFolders} Folders", + _ => $"{numLeaves} Mods, {numFolders} Folders", + }; + ImGui.SetCursorPos(treeNodePos); + ImUtf8.TextRightAligned(text); + ImGui.SetCursorPos(startPos); + } - var sizeType = ImGui.GetFrameHeight(); - var availableSizePercent = (ImGui.GetContentRegionAvail().X - sizeType - 4 * ImGui.GetStyle().CellPadding.X) / 100; + private int DrawModList() + { + using var tree = ImUtf8.TreeNode("Currently Selected Objects###Selected"u8, + ImGuiTreeNodeFlags.DefaultOpen | ImGuiTreeNodeFlags.NoTreePushOnOpen); + ImGui.Separator(); + + + if (!tree) + return selector.SelectedPaths.Count(l => l is ModFileSystem.Leaf); + + var sizeType = new Vector2(ImGui.GetFrameHeight()); + var availableSizePercent = (ImGui.GetContentRegionAvail().X - sizeType.X - 4 * ImGui.GetStyle().CellPadding.X) / 100; var sizeMods = availableSizePercent * 35; var sizeFolders = availableSizePercent * 65; - using (var table = ImRaii.Table("mods", 3, ImGuiTableFlags.RowBg)) + var leaves = 0; + using (var table = ImUtf8.Table("mods"u8, 3, ImGuiTableFlags.RowBg)) { if (!table) - return; + return selector.SelectedPaths.Count(l => l is ModFileSystem.Leaf); - ImGui.TableSetupColumn("type", ImGuiTableColumnFlags.WidthFixed, sizeType); - ImGui.TableSetupColumn("mod", ImGuiTableColumnFlags.WidthFixed, sizeMods); - ImGui.TableSetupColumn("path", ImGuiTableColumnFlags.WidthFixed, sizeFolders); + ImUtf8.TableSetupColumn("type"u8, ImGuiTableColumnFlags.WidthFixed, sizeType.X); + ImUtf8.TableSetupColumn("mod"u8, ImGuiTableColumnFlags.WidthFixed, sizeMods); + ImUtf8.TableSetupColumn("path"u8, ImGuiTableColumnFlags.WidthFixed, sizeFolders); var i = 0; - foreach (var (fullName, path) in _selector.SelectedPaths.Select(p => (p.FullName(), p)) + foreach (var (fullName, path) in selector.SelectedPaths.Select(p => (p.FullName(), p)) .OrderBy(p => p.Item1, StringComparer.OrdinalIgnoreCase)) { using var id = ImRaii.PushId(i++); + var (icon, text) = path is ModFileSystem.Leaf l + ? (FontAwesomeIcon.FileCircleMinus, l.Value.Name.Text) + : (FontAwesomeIcon.FolderMinus, string.Empty); ImGui.TableNextColumn(); - var icon = (path is ModFileSystem.Leaf ? FontAwesomeIcon.FileCircleMinus : FontAwesomeIcon.FolderMinus).ToIconString(); - if (ImGuiUtil.DrawDisabledButton(icon, new Vector2(sizeType), "Remove from selection.", false, true)) - _selector.RemovePathFromMultiSelection(path); + if (ImUtf8.IconButton(icon, "Remove from selection."u8, sizeType)) + selector.RemovePathFromMultiSelection(path); - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(path is ModFileSystem.Leaf l ? l.Value.Name : string.Empty); - - ImGui.TableNextColumn(); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(fullName); + ImUtf8.DrawFrameColumn(text); + ImUtf8.DrawFrameColumn(fullName); + if (path is ModFileSystem.Leaf) + ++leaves; } } ImGui.Separator(); + return leaves; } private string _tag = string.Empty; @@ -72,11 +95,10 @@ public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _edito private void DrawMultiTagger() { var width = ImGuiHelpers.ScaledVector2(150, 0); - ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted("Multi Tagger:"); + ImUtf8.TextFrameAligned("Multi Tagger:"u8); ImGui.SameLine(); ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - 2 * (width.X + ImGui.GetStyle().ItemSpacing.X)); - ImGui.InputTextWithHint("##tag", "Local Tag Name...", ref _tag, 128); + ImUtf8.InputText("##tag"u8, ref _tag, "Local Tag Name..."u8); UpdateTagCache(); var label = _addMods.Count > 0 @@ -88,9 +110,9 @@ public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _edito : $"All mods selected already contain the tag \"{_tag}\", either locally or as mod data." : $"Add the tag \"{_tag}\" to {_addMods.Count} mods as a local tag:\n\n\t{string.Join("\n\t", _addMods.Select(m => m.Name.Text))}"; ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton(label, width, tooltip, _addMods.Count == 0)) + if (ImUtf8.ButtonEx(label, tooltip, width, _addMods.Count == 0)) foreach (var mod in _addMods) - _editor.ChangeLocalTag(mod, mod.LocalTags.Count, _tag); + editor.ChangeLocalTag(mod, mod.LocalTags.Count, _tag); label = _removeMods.Count > 0 ? $"Remove from {_removeMods.Count} Mods" @@ -101,9 +123,9 @@ public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _edito : $"No selected mod contains the tag \"{_tag}\" locally." : $"Remove the local tag \"{_tag}\" from {_removeMods.Count} mods:\n\n\t{string.Join("\n\t", _removeMods.Select(m => m.Item1.Name.Text))}"; ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton(label, width, tooltip, _removeMods.Count == 0)) + if (ImUtf8.ButtonEx(label, tooltip, width, _removeMods.Count == 0)) foreach (var (mod, index) in _removeMods) - _editor.ChangeLocalTag(mod, index, string.Empty); + editor.ChangeLocalTag(mod, index, string.Empty); ImGui.Separator(); } @@ -114,7 +136,7 @@ public class MultiModPanel(ModFileSystemSelector _selector, ModDataEditor _edito if (_tag.Length == 0) return; - foreach (var leaf in _selector.SelectedPaths.OfType()) + foreach (var leaf in selector.SelectedPaths.OfType()) { var index = leaf.Value.LocalTags.IndexOf(_tag); if (index >= 0) From 30a4b90e843359230bbe7a127d49da16381aeb76 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 14 Jan 2025 14:34:18 +0100 Subject: [PATCH 1050/1381] Add IPC for querying temporary settings. --- Penumbra.Api | 2 +- Penumbra/Api/Api/TemporaryApi.cs | 56 ++++++++++++-- Penumbra/Api/IpcProviders.cs | 2 + Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 77 +++++++++++++++++++- 4 files changed, 128 insertions(+), 9 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index de0f281f..b4e716f8 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit de0f281fbf9d8d9d3aa8463a28025d54877cde8d +Subproject commit b4e716f86d94cd4d98d8f58e580ed5f619ea87ae diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index b12ce707..d951639c 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -130,11 +130,54 @@ public class TemporaryApi( return ApiHelpers.Return(ret, args); } + public (PenumbraApiEc, (bool, bool, int, Dictionary>)?, string) QueryTemporaryModSettings(Guid collectionId, string modDirectory, + string modName, int key) + { + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName); + if (!collectionManager.Storage.ById(collectionId, out var collection)) + return (ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args), null, string.Empty); - public PenumbraApiEc SetTemporaryModSettings(Guid collectionId, string modDirectory, string modName, bool inherit, bool enabled, int priority, + return QueryTemporaryModSettings(args, collection, modDirectory, modName, key); + } + + public (PenumbraApiEc ErrorCode, (bool, bool, int, Dictionary>)? Settings, string Source) + QueryTemporaryModSettingsPlayer(int objectIndex, + string modDirectory, string modName, int key) + { + var args = ApiHelpers.Args("ObjectIndex", objectIndex, "ModDirectory", modDirectory, "ModName", modName); + if (!apiHelpers.AssociatedCollection(objectIndex, out var collection)) + return (ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args), null, string.Empty); + + return QueryTemporaryModSettings(args, collection, modDirectory, modName, key); + } + + private (PenumbraApiEc ErrorCode, (bool, bool, int, Dictionary>)? Settings, string Source) QueryTemporaryModSettings( + in LazyString args, ModCollection collection, string modDirectory, string modName, int key) + { + if (!modManager.TryGetMod(modDirectory, modName, out var mod)) + return (ApiHelpers.Return(PenumbraApiEc.ModMissing, args), null, string.Empty); + + if (collection.Identity.Index <= 0) + return (ApiHelpers.Return(PenumbraApiEc.Success, args), null, string.Empty); + + var settings = collection.GetTempSettings(mod.Index); + if (settings == null) + return (ApiHelpers.Return(PenumbraApiEc.Success, args), null, string.Empty); + + if (settings.Lock > 0 && settings.Lock != key) + return (ApiHelpers.Return(PenumbraApiEc.TemporarySettingDisallowed, args), null, settings.Source); + + return (ApiHelpers.Return(PenumbraApiEc.Success, args), + (settings.ForceInherit, settings.Enabled, settings.Priority.Value, settings.ConvertToShareable(mod).Settings), settings.Source); + } + + + public PenumbraApiEc SetTemporaryModSettings(Guid collectionId, string modDirectory, string modName, bool inherit, bool enabled, + int priority, IReadOnlyDictionary> options, string source, int key) { - var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Inherit", inherit, "Enabled", enabled, + var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName, "Inherit", inherit, + "Enabled", enabled, "Priority", priority, "Options", options, "Source", source, "Key", key); if (!collectionManager.Storage.ById(collectionId, out var collection)) return ApiHelpers.Return(PenumbraApiEc.CollectionMissing, args); @@ -142,10 +185,12 @@ public class TemporaryApi( return SetTemporaryModSettings(args, collection, modDirectory, modName, inherit, enabled, priority, options, source, key); } - public PenumbraApiEc SetTemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, bool inherit, bool enabled, int priority, + public PenumbraApiEc SetTemporaryModSettingsPlayer(int objectIndex, string modDirectory, string modName, bool inherit, bool enabled, + int priority, IReadOnlyDictionary> options, string source, int key) { - var args = ApiHelpers.Args("ObjectIndex", objectIndex, "ModDirectory", modDirectory, "ModName", modName, "Inherit", inherit, "Enabled", enabled, + var args = ApiHelpers.Args("ObjectIndex", objectIndex, "ModDirectory", modDirectory, "ModName", modName, "Inherit", inherit, "Enabled", + enabled, "Priority", priority, "Options", options, "Source", source, "Key", key); if (!apiHelpers.AssociatedCollection(objectIndex, out var collection)) return ApiHelpers.Return(PenumbraApiEc.InvalidArgument, args); @@ -254,7 +299,8 @@ public class TemporaryApi( var numRemoved = 0; for (var i = 0; i < collection.Settings.Count; ++i) { - if (collection.GetTempSettings(i) is {} tempSettings && tempSettings.Lock == key + if (collection.GetTempSettings(i) is { } tempSettings + && tempSettings.Lock == key && collectionManager.Editor.SetTemporarySettings(collection, modManager[i], null, key)) ++numRemoved; } diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 6f3b2c38..f6948832 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -103,6 +103,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.RemoveTemporaryModSettingsPlayer.Provider(pi, api.Temporary), IpcSubscribers.RemoveAllTemporaryModSettings.Provider(pi, api.Temporary), IpcSubscribers.RemoveAllTemporaryModSettingsPlayer.Provider(pi, api.Temporary), + IpcSubscribers.QueryTemporaryModSettings.Provider(pi, api.Temporary), + IpcSubscribers.QueryTemporaryModSettingsPlayer.Provider(pi, api.Temporary), IpcSubscribers.ChangedItemTooltip.Provider(pi, api.Ui), IpcSubscribers.ChangedItemClicked.Provider(pi, api.Ui), diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 832fea82..3dc8862e 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -51,7 +51,7 @@ public class TemporaryIpcTester( ImGuiUtil.GuidInput("##guid", "Collection GUID...", string.Empty, ref _tempGuid, ref _tempCollectionGuidName); ImGui.InputInt("##tempActorIndex", ref _tempActorIndex, 0, 0); ImGui.InputTextWithHint("##tempMod", "Temporary Mod Name...", ref _tempModName, 32); - ImGui.InputTextWithHint("##mod", "Existing Mod Name...", ref _modDirectory, 256); + ImGui.InputTextWithHint("##mod", "Existing Mod Name...", ref _modDirectory, 256); ImGui.InputTextWithHint("##tempGame", "Game Path...", ref _tempGamePath, 256); ImGui.InputTextWithHint("##tempFile", "File Path...", ref _tempFilePath, 256); ImUtf8.InputText("##tempManip"u8, ref _tempManipulation, "Manipulation Base64 String..."u8); @@ -126,12 +126,14 @@ public class TemporaryIpcTester( IpcTester.DrawIntro(SetTemporaryModSettings.Label, "Set Temporary Mod Settings (to default) in specific Collection"); if (ImUtf8.Button("Set##SetTemporary"u8)) - _lastTempError = new SetTemporaryModSettings(pi).Invoke(guid, _modDirectory, false, true, 1337, new Dictionary>(), + _lastTempError = new SetTemporaryModSettings(pi).Invoke(guid, _modDirectory, false, true, 1337, + new Dictionary>(), "IPC Tester", 1337); IpcTester.DrawIntro(SetTemporaryModSettingsPlayer.Label, "Set Temporary Mod Settings (to default) in game object collection"); if (ImUtf8.Button("Set##SetTemporaryPlayer"u8)) - _lastTempError = new SetTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, false, true, 1337, new Dictionary>(), + _lastTempError = new SetTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, false, true, 1337, + new Dictionary>(), "IPC Tester", 1337); IpcTester.DrawIntro(RemoveTemporaryModSettings.Label, "Remove Temporary Mod Settings from specific Collection"); @@ -161,6 +163,75 @@ public class TemporaryIpcTester( ImGui.SameLine(); if (ImUtf8.Button("Remove (Wrong Key)##RemoveAllTemporaryPlayer"u8)) _lastTempError = new RemoveAllTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, 1338); + + IpcTester.DrawIntro(QueryTemporaryModSettings.Label, "Query Temporary Mod Settings from specific Collection"); + ImUtf8.Button("Query##QueryTemporaryModSettings"u8); + if (ImGui.IsItemHovered()) + { + _lastTempError = new QueryTemporaryModSettings(pi).Invoke(guid, _modDirectory, out var settings, out var source, 1337); + DrawTooltip(settings, source); + } + + ImGui.SameLine(); + ImUtf8.Button("Query (Wrong Key)##RemoveAllTemporary"u8); + if (ImGui.IsItemHovered()) + { + _lastTempError = new QueryTemporaryModSettings(pi).Invoke(guid, _modDirectory, out var settings, out var source, 1338); + DrawTooltip(settings, source); + } + + IpcTester.DrawIntro(QueryTemporaryModSettingsPlayer.Label, "Query Temporary Mod Settings from game object Collection"); + ImUtf8.Button("Query##QueryTemporaryModSettingsPlayer"u8); + if (ImGui.IsItemHovered()) + { + _lastTempError = + new QueryTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, out var settings, out var source, 1337); + DrawTooltip(settings, source); + } + + ImGui.SameLine(); + ImUtf8.Button("Query (Wrong Key)##RemoveAllTemporaryPlayer"u8); + if (ImGui.IsItemHovered()) + { + _lastTempError = + new QueryTemporaryModSettingsPlayer(pi).Invoke(_tempActorIndex, _modDirectory, out var settings, out var source, 1338); + DrawTooltip(settings, source); + } + + void DrawTooltip((bool ForceInherit, bool Enabled, int Priority, Dictionary> Settings)? settings, string source) + { + using var tt = ImUtf8.Tooltip(); + ImUtf8.Text($"Query returned {_lastTempError}"); + if (settings != null) + ImUtf8.Text($"Settings created by {(source.Length == 0 ? "Unknown Source" : source)}:"); + else + ImUtf8.Text(source.Length > 0 ? $"Locked by {source}." : "No settings exist."); + ImGui.Separator(); + if (settings == null) + { + + return; + } + + using (ImUtf8.Group()) + { + ImUtf8.Text("Force Inherit"u8); + ImUtf8.Text("Enabled"u8); + ImUtf8.Text("Priority"u8); + foreach (var group in settings.Value.Settings.Keys) + ImUtf8.Text(group); + } + + ImGui.SameLine(); + using (ImUtf8.Group()) + { + ImUtf8.Text($"{settings.Value.ForceInherit}"); + ImUtf8.Text($"{settings.Value.Enabled}"); + ImUtf8.Text($"{settings.Value.Priority}"); + foreach (var group in settings.Value.Settings.Values) + ImUtf8.Text(string.Join("; ", group)); + } + } } public void DrawCollections() From cc981eba156e6af19c857d1d70f43b8f1afdff72 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 14 Jan 2025 14:34:34 +0100 Subject: [PATCH 1051/1381] Fix used dye channel in material editor previews. --- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index ab93dc5f..f32a3dc9 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -603,6 +603,7 @@ public partial class MtrlTab value => dyeTable[rowIdx].Channel = (byte)(Math.Clamp(value, 1, StainService.ChannelCount) - 1)); ImGui.SameLine(subColWidth); ImGui.SetNextItemWidth(scalarSize); + _stainService.GudTemplateCombo.CurrentDyeChannel = dye.Channel; if (_stainService.GudTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, scalarSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { From 9c25fab1839473da1031382f1d54d7fe7105e5ce Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 14 Jan 2025 14:41:32 +0100 Subject: [PATCH 1052/1381] Increase API minor version. --- Penumbra/Api/Api/PenumbraApi.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 894b2674..05c47644 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -22,7 +22,7 @@ public class PenumbraApi( } public (int Breaking, int Feature) ApiVersion - => (5, 4); + => (5, 5); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; From 9559bd7358d1de390811fd331aef4bac97febcc9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 14 Jan 2025 15:20:37 +0100 Subject: [PATCH 1053/1381] Improve RSP Identifier ToString. --- Penumbra/Meta/Manipulations/Rsp.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Penumbra/Meta/Manipulations/Rsp.cs b/Penumbra/Meta/Manipulations/Rsp.cs index 2d73ec7f..9dc4fe90 100644 --- a/Penumbra/Meta/Manipulations/Rsp.cs +++ b/Penumbra/Meta/Manipulations/Rsp.cs @@ -40,6 +40,9 @@ public readonly record struct RspIdentifier(SubRace SubRace, RspAttribute Attrib public MetaManipulationType Type => MetaManipulationType.Rsp; + + public override string ToString() + => $"RSP - {SubRace.ToName()} - {Attribute.ToFullString()}"; } [JsonConverter(typeof(Converter))] From e77fa18c61f5c98a6a3e9c0ce1ff0900ee6df5a3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 10 Jan 2025 15:42:23 +0100 Subject: [PATCH 1054/1381] Start for combining groups. --- Penumbra/Mods/Groups/CombiningModGroup.cs | 235 ++++++++++++++++++ Penumbra/Mods/Groups/IModGroup.cs | 3 +- .../OptionEditor/CombiningModGroupEditor.cs | 72 ++++++ .../Manager/OptionEditor/ModGroupEditor.cs | 55 ++-- .../Mods/SubMods/CombinedDataContainer.cs | 72 ++++++ Penumbra/Mods/SubMods/CombiningSubMod.cs | 25 ++ Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 8 +- Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs | 13 + .../Groups/CombiningModGroupEditDrawer.cs | 11 + 9 files changed, 468 insertions(+), 26 deletions(-) create mode 100644 Penumbra/Mods/Groups/CombiningModGroup.cs create mode 100644 Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs create mode 100644 Penumbra/Mods/SubMods/CombinedDataContainer.cs create mode 100644 Penumbra/Mods/SubMods/CombiningSubMod.cs create mode 100644 Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs diff --git a/Penumbra/Mods/Groups/CombiningModGroup.cs b/Penumbra/Mods/Groups/CombiningModGroup.cs new file mode 100644 index 00000000..255f84aa --- /dev/null +++ b/Penumbra/Mods/Groups/CombiningModGroup.cs @@ -0,0 +1,235 @@ +using Dalamud.Interface.ImGuiNotification; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OtterGui; +using OtterGui.Classes; +using OtterGui.Filesystem; +using Penumbra.Api.Enums; +using Penumbra.GameData.Data; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.String.Classes; +using Penumbra.UI.ModsTab.Groups; +using Penumbra.Util; + +namespace Penumbra.Mods.Groups; + +/// Groups that allow all available options to be selected at once. +public sealed class CombiningModGroup : IModGroup +{ + + public GroupType Type + => GroupType.Combining; + + public GroupDrawBehaviour Behaviour + => GroupDrawBehaviour.MultiSelection; + + public Mod Mod { get; } + public string Name { get; set; } = "Group"; + public string Description { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; + public ModPriority Priority { get; set; } + public int Page { get; set; } + public Setting DefaultSettings { get; set; } + public readonly List OptionData = []; + public List Data { get; private set; } + + /// Groups that allow all available options to be selected at once. + public CombiningModGroup(Mod mod) + { + Mod = mod; + Data = [new CombinedDataContainer(this)]; + } + + IReadOnlyList IModGroup.Options + => OptionData; + + public IReadOnlyList DataContainers + => Data; + + public bool IsOption + => OptionData.Count > 0; + + public FullPath? FindBestMatch(Utf8GamePath gamePath) + { + foreach (var path in Data.SelectWhere(o + => (o.Files.TryGetValue(gamePath, out var file) || o.FileSwaps.TryGetValue(gamePath, out file), file))) + return path; + + return null; + } + + public void RemoveOption(int index) + { + if(index < 0 || index >= OptionData.Count) + return; + + OptionData.RemoveAt(index); + var list = new List(Data.Count / 2); + var optionFlag = 1 << index; + list.AddRange(Data.Where((c, i) => (i & optionFlag) == 0)); + Data = list; + } + + public void MoveOption(int from, int to) + { + if (!OptionData.Move(ref from, ref to)) + return; + + var list = new List(Data.Count); + for (var i = 0ul; i < (ulong)Data.Count; ++i) + { + var actualIndex = (int) Functions.MoveBit(i, from, to); + list.Add(Data[actualIndex]); + } + + Data = list; + } + + public IModOption? AddOption(string name, string description = "") + { + var groupIdx = Mod.Groups.IndexOf(this); + if (groupIdx < 0) + return null; + + var subMod = new CombiningSubMod(this) + { + Name = name, + Description = description, + }; + // Double available containers. + FillContainers(2 * Data.Count); + OptionData.Add(subMod); + return subMod; + } + + public static CombiningModGroup? Load(Mod mod, JObject json) + { + var ret = new CombiningModGroup(mod, true); + if (!ModSaveGroup.ReadJsonBase(json, ret)) + return null; + + var options = json["Options"]; + if (options != null) + foreach (var child in options.Children()) + { + if (ret.OptionData.Count == IModGroup.MaxCombiningOptions) + { + Penumbra.Messager.NotificationMessage( + $"Combining Group {ret.Name} in {mod.Name} has more than {IModGroup.MaxCombiningOptions} options, ignoring excessive options.", + NotificationType.Warning); + break; + } + + var subMod = new CombiningSubMod(ret, child); + ret.OptionData.Add(subMod); + } + + var requiredContainers = 1 << ret.OptionData.Count; + var containers = json["Containers"]; + if (containers != null) + foreach (var child in containers.Children()) + { + if (requiredContainers <= ret.Data.Count) + { + Penumbra.Messager.NotificationMessage( + $"Combining Group {ret.Name} in {mod.Name} has more data containers than it can support with {ret.OptionData.Count} options, ignoring excessive containers.", + NotificationType.Warning); + break; + } + + var container = new CombinedDataContainer(ret, child); + ret.Data.Add(container); + } + + if (requiredContainers > ret.Data.Count) + { + Penumbra.Messager.NotificationMessage( + $"Combining Group {ret.Name} in {mod.Name} has not enough data containers for its {ret.OptionData.Count} options, filling with empty containers.", + NotificationType.Warning); + ret.FillContainers(requiredContainers); + } + + ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); + + return ret; + } + + public int GetIndex() + => ModGroup.GetIndex(this); + + public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) + => new CombiningModGroupEditDrawer(editDrawer, this); + + public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) + => Data[setting.AsIndex].AddDataTo(redirections, manipulations); + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + foreach (var container in DataContainers) + identifier.AddChangedItems(container, changedItems); + } + + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) + { + ModSaveGroup.WriteJsonBase(jWriter, this); + jWriter.WritePropertyName("Options"); + jWriter.WriteStartArray(); + foreach (var option in OptionData) + { + jWriter.WriteStartObject(); + SubMod.WriteModOption(jWriter, option); + jWriter.WriteEndObject(); + } + + jWriter.WriteEndArray(); + + jWriter.WritePropertyName("Containers"); + jWriter.WriteStartArray(); + foreach (var container in Data) + { + jWriter.WriteStartObject(); + if (container.Name.Length > 0) + { + jWriter.WritePropertyName("Name"); + jWriter.WriteValue(container.Name); + } + + SubMod.WriteModContainer(jWriter, serializer, container, basePath ?? Mod.ModPath); + jWriter.WriteEndObject(); + } + + jWriter.WriteEndArray(); + } + + public (int Redirections, int Swaps, int Manips) GetCounts() + => ModGroup.GetCountsBase(this); + + public Setting FixSetting(Setting setting) + => new(Math.Min(setting.Value, (ulong)(Data.Count - 1))); + + /// Create a group without a mod only for saving it in the creator. + internal static CombiningModGroup WithoutMod(string name) + => new(null!) + { + Name = name, + }; + + /// For loading when no empty container should be created. + private CombiningModGroup(Mod mod, bool _) + { + Mod = mod; + Data = []; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private void FillContainers(int requiredCount) + { + if (requiredCount <= Data.Count) + return; + + Data.EnsureCapacity(requiredCount); + Data.AddRange(Enumerable.Repeat(0, requiredCount - Data.Count).Select(_ => new CombinedDataContainer(this))); + } +} diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index a6f6e20d..96422caf 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -22,7 +22,8 @@ public enum GroupDrawBehaviour public interface IModGroup { - public const int MaxMultiOptions = 32; + public const int MaxMultiOptions = 32; + public const int MaxCombiningOptions = 8; public Mod Mod { get; } public string Name { get; set; } diff --git a/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs new file mode 100644 index 00000000..46c8e3db --- /dev/null +++ b/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs @@ -0,0 +1,72 @@ +using OtterGui.Classes; +using OtterGui.Filesystem; +using OtterGui.Services; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.Services; + +namespace Penumbra.Mods.Manager.OptionEditor; + +public sealed class CombiningModGroupEditor(CommunicatorService communicator, SaveService saveService, Configuration config) + : ModOptionEditor(communicator, saveService, config), IService +{ + protected override CombiningModGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync) + => new(mod) + { + Name = newName, + Priority = priority, + }; + + protected override CombiningSubMod? CloneOption(CombiningModGroup group, IModOption option) + { + if (group.OptionData.Count >= IModGroup.MaxCombiningOptions) + { + Penumbra.Log.Error( + $"Could not add option {option.Name} to {group.Name} for mod {group.Mod.Name}, " + + $"since only up to {IModGroup.MaxCombiningOptions} options are supported in one group."); + return null; + } + + var newOption = new CombiningSubMod(group) + { + Name = option.Name, + Description = option.Description, + }; + + if (option is IModDataContainer data) + { + SubMod.Clone(data, newOption); + if (option is MultiSubMod m) + newOption.Priority = m.Priority; + else + newOption.Priority = new ModPriority(group.OptionData.Max(o => o.Priority.Value) + 1); + } + + group.OptionData.Add(newOption); + return newOption; + } + + protected override void RemoveOption(CombiningModGroup group, int optionIndex) + { + var optionFlag = 1 << optionIndex; + for (var i = group.Data.Count - 1; i >= 0; --i) + { + group.Data.RemoveAll() + if ((i & optionFlag) == optionFlag) + group.Data.RemoveAt(i); + } + + group.OptionData.RemoveAt(optionIndex); + group.DefaultSettings = group.DefaultSettings.RemoveBit(optionIndex); + } + + protected override bool MoveOption(MultiModGroup group, int optionIdxFrom, int optionIdxTo) + { + if (!group.OptionData.Move(ref optionIdxFrom, ref optionIdxTo)) + return false; + + group.DefaultSettings = group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); + return true; + } +} diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index d01297db..b66b4d8c 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -37,6 +37,7 @@ public class ModGroupEditor( SingleModGroupEditor singleEditor, MultiModGroupEditor multiEditor, ImcModGroupEditor imcEditor, + CombiningModGroupEditor combiningEditor, CommunicatorService communicator, SaveService saveService, Configuration config) : IService @@ -50,6 +51,9 @@ public class ModGroupEditor( public ImcModGroupEditor ImcEditor => imcEditor; + public CombiningModGroupEditor CombiningEditor + => combiningEditor; + /// Change the settings stored as default options in a mod. public void ChangeModGroupDefaultOption(IModGroup group, Setting defaultOption) { @@ -223,52 +227,60 @@ public class ModGroupEditor( case ImcSubMod i: ImcEditor.DeleteOption(i); return; + case CombiningModGroup c: + CombiningEditor.DeleteOption(c); + return; } } public IModOption? AddOption(IModGroup group, IModOption option) => group switch { - SingleModGroup s => SingleEditor.AddOption(s, option), - MultiModGroup m => MultiEditor.AddOption(m, option), - ImcModGroup i => ImcEditor.AddOption(i, option), - _ => null, + SingleModGroup s => SingleEditor.AddOption(s, option), + MultiModGroup m => MultiEditor.AddOption(m, option), + ImcModGroup i => ImcEditor.AddOption(i, option), + CombiningModGroup c => CombiningEditor.AddOption(c, option), + _ => null, }; public IModOption? AddOption(IModGroup group, string newName) => group switch { - SingleModGroup s => SingleEditor.AddOption(s, newName), - MultiModGroup m => MultiEditor.AddOption(m, newName), - ImcModGroup i => ImcEditor.AddOption(i, newName), - _ => null, + SingleModGroup s => SingleEditor.AddOption(s, newName), + MultiModGroup m => MultiEditor.AddOption(m, newName), + ImcModGroup i => ImcEditor.AddOption(i, newName), + CombiningModGroup c => CombiningEditor.AddOption(c, newName), + _ => null, }; public IModGroup? AddModGroup(Mod mod, GroupType type, string newName, SaveType saveType = SaveType.ImmediateSync) => type switch { - GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), - GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), - GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, default, saveType), - _ => null, + GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), + GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), + GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, default, saveType), + GroupType.Combining => CombiningEditor.AddModGroup(mod, newName, default, default, saveType), + _ => null, }; public (IModGroup?, int, bool) FindOrAddModGroup(Mod mod, GroupType type, string name, SaveType saveType = SaveType.ImmediateSync) => type switch { - GroupType.Single => SingleEditor.FindOrAddModGroup(mod, name, saveType), - GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), - GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), - _ => (null, -1, false), + GroupType.Single => SingleEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Multi => MultiEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Imc => ImcEditor.FindOrAddModGroup(mod, name, saveType), + GroupType.Combining => CombiningEditor.FindOrAddModGroup(mod, name, saveType), + _ => (null, -1, false), }; public (IModOption?, int, bool) FindOrAddOption(IModGroup group, string name, SaveType saveType = SaveType.ImmediateSync) => group switch { - SingleModGroup s => SingleEditor.FindOrAddOption(s, name, saveType), - MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), - ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), - _ => (null, -1, false), + SingleModGroup s => SingleEditor.FindOrAddOption(s, name, saveType), + MultiModGroup m => MultiEditor.FindOrAddOption(m, name, saveType), + ImcModGroup i => ImcEditor.FindOrAddOption(i, name, saveType), + CombiningModGroup c => CombiningEditor.FindOrAddOption(c, name, saveType), + _ => (null, -1, false), }; public void MoveOption(IModOption option, int toIdx) @@ -284,6 +296,9 @@ public class ModGroupEditor( case ImcSubMod i: ImcEditor.MoveOption(i, toIdx); return; + case CombiningSubMod c: + CombiningEditor.MoveOption(c, toIdx); + return; } } } diff --git a/Penumbra/Mods/SubMods/CombinedDataContainer.cs b/Penumbra/Mods/SubMods/CombinedDataContainer.cs new file mode 100644 index 00000000..3e8ec95b --- /dev/null +++ b/Penumbra/Mods/SubMods/CombinedDataContainer.cs @@ -0,0 +1,72 @@ +using Newtonsoft.Json.Linq; +using OtterGui; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.String.Classes; +using Swan.Formatters; + +namespace Penumbra.Mods.SubMods; + +public class CombinedDataContainer(IModGroup group) : IModDataContainer +{ + public IMod Mod + => Group.Mod; + + public IModGroup Group { get; } = group; + + public string Name { get; } = string.Empty; + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public MetaDictionary Manipulations { get; set; } = new(); + + public void AddDataTo(Dictionary redirections, MetaDictionary manipulations) + => SubMod.AddContainerTo(this, redirections, manipulations); + + public string GetName() + { + if (Name.Length > 0) + return Name; + + var index = GetDataIndex(); + if (index == 0) + return "None"; + + var sb = new StringBuilder(128); + for (var i = 0; i < IModGroup.MaxCombiningOptions; ++i) + { + if ((index & 1) == 0) + continue; + + sb.Append(Group.Options[i].Name); + sb.Append(' ').Append('+').Append(' '); + index >>= 1; + if (index == 0) + break; + } + + return sb.ToString(0, sb.Length - 3); + } + + public string GetFullName() + => $"{Group.Name}: {GetName()}"; + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), GetDataIndex()); + + private int GetDataIndex() + { + var dataIndex = Group.DataContainers.IndexOf(this); + if (dataIndex < 0) + throw new Exception($"Group {Group.Name} from SubMod {Name} does not contain this SubMod."); + + return dataIndex; + } + + public CombinedDataContainer(CombiningModGroup group, JToken token) + : this(group) + { + SubMod.LoadDataContainer(token, this, group.Mod.ModPath); + Name = token["Name"]?.ToObject() ?? string.Empty; + } +} diff --git a/Penumbra/Mods/SubMods/CombiningSubMod.cs b/Penumbra/Mods/SubMods/CombiningSubMod.cs new file mode 100644 index 00000000..6eb5de9d --- /dev/null +++ b/Penumbra/Mods/SubMods/CombiningSubMod.cs @@ -0,0 +1,25 @@ +using Newtonsoft.Json.Linq; +using Penumbra.Mods.Groups; + +namespace Penumbra.Mods.SubMods; + +public class CombiningSubMod(IModGroup group) : IModOption +{ + public IModGroup Group { get; } = group; + + public Mod Mod + => Group.Mod; + + public string Name { get; set; } = "Option"; + public string Description { get; set; } = string.Empty; + + public string FullName + => $"{Group.Name}: {Name}"; + + public int GetIndex() + => SubMod.GetIndex(this); + + public CombiningSubMod(CombiningModGroup group, JToken json) + : this(group) + => SubMod.LoadOptionData(json, this); +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 02e945f3..7f1a8ac5 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -452,19 +452,17 @@ public partial class ModEditWindow : Window, IDisposable, IUiService private bool DrawOptionSelectHeader() { - const string defaultOption = "Default Option"; using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero).Push(ImGuiStyleVar.FrameRounding, 0); var width = new Vector2(ImGui.GetContentRegionAvail().X / 3, 0); var ret = false; - if (ImGuiUtil.DrawDisabledButton(defaultOption, width, "Switch to the default option for the mod.\nThis resets unsaved changes.", - _editor.Option is DefaultSubMod)) + if (ImUtf8.ButtonEx("Default Option"u8, "Switch to the default option for the mod.\nThis resets unsaved changes."u8, width, _editor.Option is DefaultSubMod)) { _editor.LoadOption(-1, 0).Wait(); ret = true; } ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Refresh Data", width, "Refresh data for the current option.\nThis resets unsaved changes.", false)) + if (ImUtf8.ButtonEx("Refresh Data"u8, "Refresh data for the current option.\nThis resets unsaved changes."u8, width)) { _editor.LoadMod(_editor.Mod!, _editor.GroupIdx, _editor.DataIdx).Wait(); ret = true; @@ -474,7 +472,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService ImGui.SetNextItemWidth(width.X); style.Push(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); using var color = ImRaii.PushColor(ImGuiCol.Border, ColorId.FolderLine.Value()); - using var combo = ImRaii.Combo("##optionSelector", _editor.Option!.GetFullName()); + using var combo = ImUtf8.Combo("##optionSelector"u8, _editor.Option!.GetFullName()); if (!combo) return ret; diff --git a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index c30239bc..a3e7ce14 100644 --- a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -48,6 +48,7 @@ public class AddGroupDrawer : IUiService DrawSingleGroupButton(mod, buttonWidth); ImUtf8.SameLineInner(); DrawMultiGroupButton(mod, buttonWidth); + DrawCombiningGroupButton(mod, buttonWidth); } private void DrawSingleGroupButton(Mod mod, Vector2 width) @@ -76,6 +77,18 @@ public class AddGroupDrawer : IUiService _groupNameValid = false; } + private void DrawCombiningGroupButton(Mod mod, Vector2 width) + { + if (!ImUtf8.ButtonEx("Add Combining Group"u8, _groupNameValid + ? "Add a new combining option group to this mod."u8 + : "Can not add a new group of this name."u8, + width, !_groupNameValid)) + return; + + _modManager.OptionEditor.AddModGroup(mod, GroupType.Combining, _groupName); + _groupName = string.Empty; + _groupNameValid = false; + } private void DrawImcInput(float width) { var change = ImcMetaDrawer.DrawObjectType(ref _imcIdentifier, width); diff --git a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs new file mode 100644 index 00000000..79d2fb43 --- /dev/null +++ b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs @@ -0,0 +1,11 @@ +using Penumbra.Mods.Groups; + +namespace Penumbra.UI.ModsTab.Groups; + +public readonly struct CombiningModGroupEditDrawer(ModGroupEditDrawer editor, CombiningModGroup group) : IModGroupEditDrawer +{ + public void Draw() + { + + } +} From 795fa7336e9654ff454ce79cae9387cef8858918 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 15 Jan 2025 17:44:22 +0100 Subject: [PATCH 1055/1381] Update with workable prototype. --- OtterGui | 2 +- Penumbra/Mods/Groups/CombiningModGroup.cs | 49 +-------- .../OptionEditor/CombiningModGroupEditor.cs | 58 +++------- .../Manager/OptionEditor/ModGroupEditor.cs | 4 +- Penumbra/Mods/ModCreator.cs | 12 +-- .../Mods/SubMods/CombinedDataContainer.cs | 12 +-- Penumbra/Mods/SubMods/SubMod.cs | 41 ++++--- .../Groups/CombiningModGroupEditDrawer.cs | 102 +++++++++++++++++- .../UI/ModsTab/Groups/ModGroupEditDrawer.cs | 4 + 9 files changed, 168 insertions(+), 116 deletions(-) diff --git a/OtterGui b/OtterGui index fd387218..055f1695 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit fd387218d2d2d237075cb35be6ca89eeb53e14e5 +Subproject commit 055f169572223fd1b59389549c88b4c861c94608 diff --git a/Penumbra/Mods/Groups/CombiningModGroup.cs b/Penumbra/Mods/Groups/CombiningModGroup.cs index 255f84aa..80f3c4c0 100644 --- a/Penumbra/Mods/Groups/CombiningModGroup.cs +++ b/Penumbra/Mods/Groups/CombiningModGroup.cs @@ -3,7 +3,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; -using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; @@ -18,7 +17,6 @@ namespace Penumbra.Mods.Groups; /// Groups that allow all available options to be selected at once. public sealed class CombiningModGroup : IModGroup { - public GroupType Type => GroupType.Combining; @@ -60,33 +58,6 @@ public sealed class CombiningModGroup : IModGroup return null; } - public void RemoveOption(int index) - { - if(index < 0 || index >= OptionData.Count) - return; - - OptionData.RemoveAt(index); - var list = new List(Data.Count / 2); - var optionFlag = 1 << index; - list.AddRange(Data.Where((c, i) => (i & optionFlag) == 0)); - Data = list; - } - - public void MoveOption(int from, int to) - { - if (!OptionData.Move(ref from, ref to)) - return; - - var list = new List(Data.Count); - for (var i = 0ul; i < (ulong)Data.Count; ++i) - { - var actualIndex = (int) Functions.MoveBit(i, from, to); - list.Add(Data[actualIndex]); - } - - Data = list; - } - public IModOption? AddOption(string name, string description = "") { var groupIdx = Mod.Groups.IndexOf(this); @@ -98,10 +69,9 @@ public sealed class CombiningModGroup : IModGroup Name = name, Description = description, }; - // Double available containers. - FillContainers(2 * Data.Count); - OptionData.Add(subMod); - return subMod; + return OptionData.AddNewWithPowerSet(Data, subMod, () => new CombinedDataContainer(this), IModGroup.MaxCombiningOptions) + ? subMod + : null; } public static CombiningModGroup? Load(Mod mod, JObject json) @@ -148,7 +118,8 @@ public sealed class CombiningModGroup : IModGroup Penumbra.Messager.NotificationMessage( $"Combining Group {ret.Name} in {mod.Name} has not enough data containers for its {ret.OptionData.Count} options, filling with empty containers.", NotificationType.Warning); - ret.FillContainers(requiredContainers); + ret.Data.EnsureCapacity(requiredContainers); + ret.Data.AddRange(Enumerable.Repeat(0, requiredContainers - ret.Data.Count).Select(_ => new CombinedDataContainer(ret))); } ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); @@ -222,14 +193,4 @@ public sealed class CombiningModGroup : IModGroup Mod = mod; Data = []; } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private void FillContainers(int requiredCount) - { - if (requiredCount <= Data.Count) - return; - - Data.EnsureCapacity(requiredCount); - Data.AddRange(Enumerable.Repeat(0, requiredCount - Data.Count).Select(_ => new CombinedDataContainer(this))); - } } diff --git a/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs index 46c8e3db..ce5db454 100644 --- a/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs @@ -1,5 +1,5 @@ +using OtterGui; using OtterGui.Classes; -using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; @@ -19,54 +19,30 @@ public sealed class CombiningModGroupEditor(CommunicatorService communicator, Sa }; protected override CombiningSubMod? CloneOption(CombiningModGroup group, IModOption option) - { - if (group.OptionData.Count >= IModGroup.MaxCombiningOptions) - { - Penumbra.Log.Error( - $"Could not add option {option.Name} to {group.Name} for mod {group.Mod.Name}, " - + $"since only up to {IModGroup.MaxCombiningOptions} options are supported in one group."); - return null; - } - - var newOption = new CombiningSubMod(group) - { - Name = option.Name, - Description = option.Description, - }; - - if (option is IModDataContainer data) - { - SubMod.Clone(data, newOption); - if (option is MultiSubMod m) - newOption.Priority = m.Priority; - else - newOption.Priority = new ModPriority(group.OptionData.Max(o => o.Priority.Value) + 1); - } - - group.OptionData.Add(newOption); - return newOption; - } + => throw new NotImplementedException(); protected override void RemoveOption(CombiningModGroup group, int optionIndex) { - var optionFlag = 1 << optionIndex; - for (var i = group.Data.Count - 1; i >= 0; --i) - { - group.Data.RemoveAll() - if ((i & optionFlag) == optionFlag) - group.Data.RemoveAt(i); - } - - group.OptionData.RemoveAt(optionIndex); - group.DefaultSettings = group.DefaultSettings.RemoveBit(optionIndex); + if (group.OptionData.RemoveWithPowerSet(group.Data, optionIndex)) + group.DefaultSettings.RemoveBit(optionIndex); } - protected override bool MoveOption(MultiModGroup group, int optionIdxFrom, int optionIdxTo) + protected override bool MoveOption(CombiningModGroup group, int optionIdxFrom, int optionIdxTo) { - if (!group.OptionData.Move(ref optionIdxFrom, ref optionIdxTo)) + if (!group.OptionData.MoveWithPowerSet(group.Data, ref optionIdxFrom, ref optionIdxTo)) return false; - group.DefaultSettings = group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); + group.DefaultSettings.MoveBit(optionIdxFrom, optionIdxTo); return true; } + + public void SetDisplayName(CombinedDataContainer container, string name, SaveType saveType = SaveType.Queue) + { + if (container.Name == name) + return; + + container.Name = name; + SaveService.Save(saveType, new ModSaveGroup(container.Group, Config.ReplaceNonAsciiOnImport)); + Communicator.ModOptionChanged.Invoke(ModOptionChangeType.DisplayChange, container.Group.Mod, container.Group, null, null, -1); + } } diff --git a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs index b66b4d8c..1c077c58 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModGroupEditor.cs @@ -227,7 +227,7 @@ public class ModGroupEditor( case ImcSubMod i: ImcEditor.DeleteOption(i); return; - case CombiningModGroup c: + case CombiningSubMod c: CombiningEditor.DeleteOption(c); return; } @@ -259,7 +259,7 @@ public class ModGroupEditor( GroupType.Single => SingleEditor.AddModGroup(mod, newName, saveType), GroupType.Multi => MultiEditor.AddModGroup(mod, newName, saveType), GroupType.Imc => ImcEditor.AddModGroup(mod, newName, default, default, saveType), - GroupType.Combining => CombiningEditor.AddModGroup(mod, newName, default, default, saveType), + GroupType.Combining => CombiningEditor.AddModGroup(mod, newName, saveType), _ => null, }; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index bdc16b72..18d2bc09 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -82,13 +82,11 @@ public partial class ModCreator( if (incorporateMetaChanges) IncorporateAllMetaChanges(mod, true); if (deleteDefaultMetaChanges && !Config.KeepDefaultMetaChanges) - { foreach (var container in mod.AllDataContainers) { if (ModMetaEditor.DeleteDefaultValues(metaFileManager, container.Manipulations)) saveService.ImmediateSaveSync(new ModSaveGroup(container, Config.ReplaceNonAsciiOnImport)); } - } return true; } @@ -186,7 +184,8 @@ public partial class ModCreator( /// If .meta or .rgsp files are encountered, parse them and incorporate their meta changes into the mod. /// If delete is true, the files are deleted afterwards. /// - public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete, bool deleteDefault) + public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete, + bool deleteDefault) { var deleteList = new List(); var oldSize = option.Manipulations.Count; @@ -447,9 +446,10 @@ public partial class ModCreator( var json = JObject.Parse(File.ReadAllText(file.FullName)); switch (json[nameof(Type)]?.ToObject() ?? GroupType.Single) { - case GroupType.Multi: return MultiModGroup.Load(mod, json); - case GroupType.Single: return SingleModGroup.Load(mod, json); - case GroupType.Imc: return ImcModGroup.Load(mod, json); + case GroupType.Multi: return MultiModGroup.Load(mod, json); + case GroupType.Single: return SingleModGroup.Load(mod, json); + case GroupType.Imc: return ImcModGroup.Load(mod, json); + case GroupType.Combining: return CombiningModGroup.Load(mod, json); } } catch (Exception e) diff --git a/Penumbra/Mods/SubMods/CombinedDataContainer.cs b/Penumbra/Mods/SubMods/CombinedDataContainer.cs index 3e8ec95b..2c410c1c 100644 --- a/Penumbra/Mods/SubMods/CombinedDataContainer.cs +++ b/Penumbra/Mods/SubMods/CombinedDataContainer.cs @@ -4,7 +4,6 @@ using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.String.Classes; -using Swan.Formatters; namespace Penumbra.Mods.SubMods; @@ -15,7 +14,7 @@ public class CombinedDataContainer(IModGroup group) : IModDataContainer public IModGroup Group { get; } = group; - public string Name { get; } = string.Empty; + public string Name { get; set; } = string.Empty; public Dictionary Files { get; set; } = []; public Dictionary FileSwaps { get; set; } = []; public MetaDictionary Manipulations { get; set; } = new(); @@ -35,11 +34,12 @@ public class CombinedDataContainer(IModGroup group) : IModDataContainer var sb = new StringBuilder(128); for (var i = 0; i < IModGroup.MaxCombiningOptions; ++i) { - if ((index & 1) == 0) - continue; + if ((index & 1) != 0) + { + sb.Append(Group.Options[i].Name); + sb.Append(' ').Append('+').Append(' '); + } - sb.Append(Group.Options[i].Name); - sb.Append(' ').Append('+').Append(' '); index >>= 1; if (index == 0) break; diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index f6b1be96..7f01884d 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -81,29 +81,40 @@ public static class SubMod [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void WriteModContainer(JsonWriter j, JsonSerializer serializer, IModDataContainer data, DirectoryInfo basePath) { - j.WritePropertyName(nameof(data.Files)); - j.WriteStartObject(); - foreach (var (gamePath, file) in data.Files) + if (data.Files.Count > 0) { - if (file.ToRelPath(basePath, out var relPath)) + j.WritePropertyName(nameof(data.Files)); + j.WriteStartObject(); + foreach (var (gamePath, file) in data.Files) + { + if (file.ToRelPath(basePath, out var relPath)) + { + j.WritePropertyName(gamePath.ToString()); + j.WriteValue(relPath.ToString()); + } + } + + j.WriteEndObject(); + } + + if (data.FileSwaps.Count > 0) + { + j.WritePropertyName(nameof(data.FileSwaps)); + j.WriteStartObject(); + foreach (var (gamePath, file) in data.FileSwaps) { j.WritePropertyName(gamePath.ToString()); - j.WriteValue(relPath.ToString()); + j.WriteValue(file.ToString()); } + + j.WriteEndObject(); } - j.WriteEndObject(); - j.WritePropertyName(nameof(data.FileSwaps)); - j.WriteStartObject(); - foreach (var (gamePath, file) in data.FileSwaps) + if (data.Manipulations.Count > 0) { - j.WritePropertyName(gamePath.ToString()); - j.WriteValue(file.ToString()); + j.WritePropertyName(nameof(data.Manipulations)); + serializer.Serialize(j, data.Manipulations); } - - j.WriteEndObject(); - j.WritePropertyName(nameof(data.Manipulations)); - serializer.Serialize(j, data.Manipulations); } /// Write the data for a selectable mod option on a JsonWriter. diff --git a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs index 79d2fb43..f32e6da6 100644 --- a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs @@ -1,4 +1,10 @@ +using Dalamud.Interface; +using ImGuiNET; +using OtterGui; +using OtterGui.Raii; +using OtterGui.Text; using Penumbra.Mods.Groups; +using Penumbra.Mods.SubMods; namespace Penumbra.UI.ModsTab.Groups; @@ -6,6 +12,100 @@ public readonly struct CombiningModGroupEditDrawer(ModGroupEditDrawer editor, Co { public void Draw() { - + foreach (var (option, optionIdx) in group.OptionData.WithIndex()) + { + using var id = ImUtf8.PushId(optionIdx); + editor.DrawOptionPosition(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionDefaultMultiBehaviour(group, option, optionIdx); + + ImUtf8.SameLineInner(); + editor.DrawOptionName(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDescription(option); + + ImUtf8.SameLineInner(); + editor.DrawOptionDelete(option); + } + + DrawNewOption(); + DrawContainerNames(); + } + + private void DrawNewOption() + { + var count = group.OptionData.Count; + if (count >= IModGroup.MaxCombiningOptions) + return; + + var name = editor.DrawNewOptionBase(group, count); + + var validName = name.Length > 0; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, validName + ? "Add a new option to this group."u8 + : "Please enter a name for the new option."u8, default, !validName)) + { + editor.ModManager.OptionEditor.CombiningEditor.AddOption(group, name); + editor.NewOptionName = null; + } + } + + private unsafe void DrawContainerNames() + { + if (ImUtf8.ButtonEx("Edit Container Names"u8, + "Add optional names to separate data containers of the combining group.\nThose are just for easier identification while editing the mod, and are not generally displayed to the user."u8, + new Vector2(400 * ImUtf8.GlobalScale, 0))) + ImUtf8.OpenPopup("DataContainerNames"u8); + + var sizeX = group.OptionData.Count * (ImGui.GetStyle().ItemInnerSpacing.X + ImGui.GetFrameHeight()) + 300 * ImUtf8.GlobalScale; + ImGui.SetNextWindowSize(new Vector2(sizeX, ImGui.GetFrameHeightWithSpacing() * Math.Min(16, group.Data.Count) + 200 * ImUtf8.GlobalScale)); + using var popup = ImUtf8.Popup("DataContainerNames"u8); + if (!popup) + return; + + foreach (var option in group.OptionData) + { + ImUtf8.RotatedText(option.Name, true); + ImUtf8.SameLineInner(); + } + + ImGui.NewLine(); + ImGui.Separator(); + using var child = ImUtf8.Child("##Child"u8, ImGui.GetContentRegionAvail()); + ImGuiClip.ClippedDraw(group.Data, DrawRow, ImGui.GetFrameHeightWithSpacing()); + } + + private void DrawRow(CombinedDataContainer container, int index) + { + using var id = ImUtf8.PushId(index); + using (ImRaii.Disabled()) + { + for (var i = 0; i < group.OptionData.Count; ++i) + { + id.Push(i); + var check = (index & (1 << i)) != 0; + ImUtf8.Checkbox(""u8, ref check); + ImUtf8.SameLineInner(); + id.Pop(); + } + } + + var name = editor.CombiningDisplayIndex == index ? editor.CombiningDisplayName ?? container.Name : container.Name; + if (ImUtf8.InputText("##Nothing"u8, ref name, "Optional Display Name..."u8)) + { + editor.CombiningDisplayIndex = index; + editor.CombiningDisplayName = name; + } + + if (ImGui.IsItemDeactivatedAfterEdit()) + editor.ModManager.OptionEditor.CombiningEditor.SetDisplayName(container, name); + + if (ImGui.IsItemDeactivated()) + { + editor.CombiningDisplayIndex = -1; + editor.CombiningDisplayName = null; + } } } diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs index ec5bb920..89812346 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -58,6 +58,9 @@ public sealed class ModGroupEditDrawer( private IModOption? _dragDropOption; private bool _draggingAcross; + internal string? CombiningDisplayName; + internal int CombiningDisplayIndex; + public void Draw(Mod mod) { PrepareStyle(); @@ -275,6 +278,7 @@ public sealed class ModGroupEditDrawer( [MethodImpl(MethodImplOptions.AggressiveInlining)] internal string DrawNewOptionBase(IModGroup group, int count) { + ImGui.AlignTextToFramePadding(); ImUtf8.Selectable($"Option #{count + 1}", false, size: OptionIdxSelectable); Target(group, count); From 1462891bd36fb0e467b5a0b9181a72d97281c211 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 15 Jan 2025 17:05:31 +0000 Subject: [PATCH 1056/1381] [CI] Updating repo.json for testing_1.3.3.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 14c5d8ac..d9d597ba 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.3", + "TestingAssemblyVersion": "1.3.3.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From bdc2da95c4ece4ce36b99fba9f1b9fea11b83251 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 16 Jan 2025 17:22:25 +0100 Subject: [PATCH 1057/1381] Make mods write empty containers again for now. --- Penumbra.GameData | 2 +- Penumbra/Mods/SubMods/SubMod.cs | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index d5f92966..78ce195c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d5f929664c212804594fadb4e4cefe9e6a1f5d37 +Subproject commit 78ce195c171d7bce4ad9df105f1f95cce9bf1150 diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index 7f01884d..fcb6cc0e 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -81,8 +81,9 @@ public static class SubMod [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] public static void WriteModContainer(JsonWriter j, JsonSerializer serializer, IModDataContainer data, DirectoryInfo basePath) { - if (data.Files.Count > 0) - { + // #TODO: remove comments when TexTools updated. + //if (data.Files.Count > 0) + //{ j.WritePropertyName(nameof(data.Files)); j.WriteStartObject(); foreach (var (gamePath, file) in data.Files) @@ -95,10 +96,10 @@ public static class SubMod } j.WriteEndObject(); - } + //} - if (data.FileSwaps.Count > 0) - { + //if (data.FileSwaps.Count > 0) + //{ j.WritePropertyName(nameof(data.FileSwaps)); j.WriteStartObject(); foreach (var (gamePath, file) in data.FileSwaps) @@ -108,13 +109,13 @@ public static class SubMod } j.WriteEndObject(); - } + //} - if (data.Manipulations.Count > 0) - { + //if (data.Manipulations.Count > 0) + //{ j.WritePropertyName(nameof(data.Manipulations)); serializer.Serialize(j, data.Manipulations); - } + //} } /// Write the data for a selectable mod option on a JsonWriter. From df148b556a8a8b2f90b700a01a9ac0622ace3e31 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 16 Jan 2025 16:25:18 +0000 Subject: [PATCH 1058/1381] [CI] Updating repo.json for testing_1.3.3.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index d9d597ba..2e3dd8bc 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.4", + "TestingAssemblyVersion": "1.3.3.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a1931a93fb4bfad042b1235ec62270f4c74e3fbc Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 17 Jan 2025 01:45:37 +0100 Subject: [PATCH 1059/1381] Add drafts of JSON schemas --- schemas/container.json | 486 +++++++++++++++++++++++++++++++++++++++ schemas/default_mod.json | 25 ++ schemas/group.json | 206 +++++++++++++++++ schemas/meta-v3.json | 51 ++++ 4 files changed, 768 insertions(+) create mode 100644 schemas/container.json create mode 100644 schemas/default_mod.json create mode 100644 schemas/group.json create mode 100644 schemas/meta-v3.json diff --git a/schemas/container.json b/schemas/container.json new file mode 100644 index 00000000..5798f46c --- /dev/null +++ b/schemas/container.json @@ -0,0 +1,486 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json", + "type": "object", + "properties": { + "Name": { + "description": "Name of the container/option/sub-mod.", + "type": ["string", "null"] + }, + "Files": { + "description": "File redirections in this container. Keys are game paths, values are relative file paths.", + "type": "object", + "patternProperties": { + "^[^/\\\\][^\\\\]*$": { + "type": "string", + "pattern": "^[^/\\\\][^/]*$" + } + }, + "additionalProperties": false + }, + "FileSwaps": { + "description": "File swaps in this container. Keys are original game paths, values are actual game paths.", + "type": "object", + "patternProperties": { + "^[^/\\\\][^\\\\]*$": { + "type": "string", + "pattern": "^[^/\\\\][^/]*$" + } + }, + "additionalProperties": false + }, + "Manipulations": { + "type": "array", + "items": { + "$ref": "#/$defs/Manipulation" + } + } + }, + "$defs": { + "Manipulation": { + "type": "object", + "properties": { + "Type": { + "enum": ["Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch"] + }, + "Manipulation": { + "type": ["object", "null"] + } + }, + "required": ["Type", "Manipulation"], + "oneOf": [ + { + "properties": { + "Type": { + "const": "Unknown" + }, + "Manipulation": { + "type": "null" + } + } + }, { + "properties": { + "Type": { + "const": "Imc" + }, + "Manipulation": { + "$ref": "#/$defs/ImcManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "Eqdp" + }, + "Manipulation": { + "$ref": "#/$defs/EqdpManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "Eqp" + }, + "Manipulation": { + "$ref": "#/$defs/EqpManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "Est" + }, + "Manipulation": { + "$ref": "#/$defs/EstManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "Gmp" + }, + "Manipulation": { + "$ref": "#/$defs/GmpManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "Rsp" + }, + "Manipulation": { + "$ref": "#/$defs/RspManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "GlobalEqp" + }, + "Manipulation": { + "$ref": "#/$defs/GlobalEqpManipulation" + } + } + }, { + "properties": { + "Type": { + "const": "Atch" + }, + "Manipulation": { + "$ref": "#/$defs/AtchManipulation" + } + } + } + ], + "additionalProperties": false + }, + "ImcManipulation": { + "type": "object", + "properties": { + "Entry": { + "$ref": "#/$defs/ImcEntry" + }, + "Valid": { + "type": "boolean" + } + }, + "required": [ + "Entry" + ], + "allOf": [ + { + "$ref": "#/$defs/ImcIdentifier" + } + ], + "unevaluatedProperties": false + }, + "ImcIdentifier": { + "type": "object", + "properties": { + "PrimaryId": { + "type": "integer" + }, + "SecondaryId": { + "type": "integer" + }, + "Variant": { + "type": "integer" + }, + "ObjectType": { + "$ref": "#/$defs/ObjectType" + }, + "EquipSlot": { + "$ref": "#/$defs/EquipSlot" + }, + "BodySlot": { + "$ref": "#/$defs/BodySlot" + } + }, + "required": [ + "PrimaryId", + "SecondaryId", + "Variant", + "ObjectType", + "EquipSlot", + "BodySlot" + ] + }, + "ImcEntry": { + "type": "object", + "properties": { + "AttributeAndSound": { + "type": "integer" + }, + "MaterialId": { + "type": "integer" + }, + "DecalId": { + "type": "integer" + }, + "VfxId": { + "type": "integer" + }, + "MaterialAnimationId": { + "type": "integer" + }, + "AttributeMask": { + "type": "integer" + }, + "SoundId": { + "type": "integer" + } + }, + "required": [ + "MaterialId", + "DecalId", + "VfxId", + "MaterialAnimationId", + "AttributeMask", + "SoundId" + ], + "additionalProperties": false + }, + "EqdpManipulation": { + "type": "object", + "properties": { + "Entry": { + "type": "integer" + }, + "Gender": { + "$ref": "#/$defs/Gender" + }, + "Race": { + "$ref": "#/$defs/ModelRace" + }, + "SetId": { + "$ref": "#/$defs/LaxInteger" + }, + "Slot": { + "$ref": "#/$defs/EquipSlot" + }, + "ShiftedEntry": { + "type": "integer" + } + }, + "required": [ + "Entry", + "Gender", + "Race", + "SetId", + "Slot" + ], + "additionalProperties": false + }, + "EqpManipulation": { + "type": "object", + "properties": { + "Entry": { + "type": "integer" + }, + "SetId": { + "$ref": "#/$defs/LaxInteger" + }, + "Slot": { + "$ref": "#/$defs/EquipSlot" + } + }, + "required": [ + "Entry", + "SetId", + "Slot" + ], + "additionalProperties": false + }, + "EstManipulation": { + "type": "object", + "properties": { + "Entry": { + "type": "integer" + }, + "Gender": { + "$ref": "#/$defs/Gender" + }, + "Race": { + "$ref": "#/$defs/ModelRace" + }, + "SetId": { + "$ref": "#/$defs/LaxInteger" + }, + "Slot": { + "enum": ["Hair", "Face", "Body", "Head"] + } + }, + "required": [ + "Entry", + "Gender", + "Race", + "SetId", + "Slot" + ], + "additionalProperties": false + }, + "GmpManipulation": { + "type": "object", + "properties": { + "Entry": { + "type": "object", + "properties": { + "Enabled": { + "type": "boolean" + }, + "Animated": { + "type": "boolean" + }, + "RotationA": { + "type": "number" + }, + "RotationB": { + "type": "number" + }, + "RotationC": { + "type": "number" + }, + "UnknownA": { + "type": "number" + }, + "UnknownB": { + "type": "number" + }, + "UnknownTotal": { + "type": "number" + }, + "Value": { + "type": "number" + } + }, + "required": [ + "Enabled", + "Animated", + "RotationA", + "RotationB", + "RotationC", + "UnknownA", + "UnknownB", + "UnknownTotal", + "Value" + ], + "additionalProperties": false + }, + "SetId": { + "$ref": "#/$defs/LaxInteger" + } + }, + "required": [ + "Entry", + "SetId" + ], + "additionalProperties": false + }, + "RspManipulation": { + "type": "object", + "properties": { + "Entry": { + "type": "number" + }, + "SubRace": { + "$ref": "#/$defs/SubRace" + }, + "Attribute": { + "$ref": "#/$defs/RspAttribute" + } + }, + "additionalProperties": false + }, + "GlobalEqpManipulation": { + "type": "object", + "properties": { + "Condition": { + "type": "integer" + }, + "Type": { + "enum": ["DoNotHideEarrings", "DoNotHideNecklace", "DoNotHideBracelets", "DoNotHideRingR", "DoNotHideRingL", "DoNotHideHrothgarHats", "DoNotHideVieraHats"] + } + }, + "additionalProperties": false + }, + "AtchManipulation": { + "type": "object", + "properties": { + "Entry": { + "type": "object", + "properties": { + "Bone": { + "type": "string", + "maxLength": 34 + }, + "Scale": { + "type": "number" + }, + "OffsetX": { + "type": "number" + }, + "OffsetY": { + "type": "number" + }, + "OffsetZ": { + "type": "number" + }, + "RotationX": { + "type": "number" + }, + "RotationY": { + "type": "number" + }, + "RotationZ": { + "type": "number" + } + }, + "required": [ + "Bone", + "Scale", + "OffsetX", + "OffsetY", + "OffsetZ", + "RotationX", + "RotationY", + "RotationZ" + ], + "additionalProperties": false + }, + "Gender": { + "$ref": "#/$defs/Gender" + }, + "Race": { + "$ref": "#/$defs/ModelRace" + }, + "Type": { + "type": "string", + "minLength": 3, + "maxLength": 3 + }, + "Index": { + "type": "integer" + } + }, + "required": [ + "Entry", + "Gender", + "Race", + "Type", + "Index" + ], + "additionalProperties": false + }, + "LaxInteger": { + "oneOf": [ + { + "type": "integer" + }, { + "type": "string", + "pattern": "^\\d+$" + } + ] + }, + "EquipSlot": { + "enum": ["Unknown", "MainHand", "OffHand", "Head", "Body", "Hands", "Belt", "Legs", "Feet", "Ears", "Neck", "Wrists", "RFinger", "BothHand", "LFinger", "HeadBody", "BodyHandsLegsFeet", "SoulCrystal", "LegsFeet", "FullBody", "BodyHands", "BodyLegsFeet", "ChestHands", "Nothing", "All"] + }, + "Gender": { + "enum": ["Unknown", "Male", "Female", "MaleNpc", "FemaleNpc"] + }, + "ModelRace": { + "enum": ["Unknown", "Midlander", "Highlander", "Elezen", "Lalafell", "Miqote", "Roegadyn", "AuRa", "Hrothgar", "Viera"] + }, + "ObjectType": { + "enum": ["Unknown", "Vfx", "DemiHuman", "Accessory", "World", "Housing", "Monster", "Icon", "LoadingScreen", "Map", "Interface", "Equipment", "Character", "Weapon", "Font"] + }, + "BodySlot": { + "enum": ["Unknown", "Hair", "Face", "Tail", "Body", "Zear"] + }, + "SubRace": { + "enum": ["Unknown", "Midlander", "Highlander", "Wildwood", "Duskwight", "Plainsfolk", "Dunesfolk", "SeekerOfTheSun", "KeeperOfTheMoon", "Seawolf", "Hellsguard", "Raen", "Xaela", "Helion", "Lost", "Rava", "Veena"] + }, + "RspAttribute": { + "enum": ["MaleMinSize", "MaleMaxSize", "MaleMinTail", "MaleMaxTail", "FemaleMinSize", "FemaleMaxSize", "FemaleMinTail", "FemaleMaxTail", "BustMinX", "BustMinY", "BustMinZ", "BustMaxX", "BustMaxY", "BustMaxZ"] + } + } +} diff --git a/schemas/default_mod.json b/schemas/default_mod.json new file mode 100644 index 00000000..eecd74d0 --- /dev/null +++ b/schemas/default_mod.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json", + "allOf": [ + { + "type": "object", + "properties": { + "Version": { + "description": "???", + "type": ["integer", "null"] + }, + "Description": { + "description": "Description of the sub-mod.", + "type": ["string", "null"] + }, + "Image": { + "description": "Unused by Penumbra.", + "type": ["string", "null"] + } + } + }, { + "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" + } + ] +} diff --git a/schemas/group.json b/schemas/group.json new file mode 100644 index 00000000..0078e9f3 --- /dev/null +++ b/schemas/group.json @@ -0,0 +1,206 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/group.json", + "type": "object", + "properties": { + "Version": { + "description": "???", + "type": ["integer", "null"] + }, + "Name": { + "description": "Name of the group.", + "type": "string" + }, + "Description": { + "description": "Description of the group.", + "type": ["string", "null"] + }, + "Image": { + "description": "Relative path to a preview image for the group. Unused by Penumbra, present for round-trip import/export of TexTools-generated mods.", + "type": ["string", "null"] + }, + "Page": { + "description": "TexTools page of the group. Unused by Penumbra, present for round-trip import/export of TexTools-generated mods.", + "type": ["integer", "null"] + }, + "Priority": { + "description": "Priority of the group. If several groups define conflicting files or manipulations, the highest priority wins.", + "type": ["integer", "null"] + }, + "Type": { + "description": "Group type. Single groups have one and only one of their options active at any point. Multi groups can have zero, one or many of their options active. Combining groups have n options, 2^n containers, and will have one and only one container active depending on the selected options.", + "enum": ["Single", "Multi", "Imc", "Combining"] + }, + "DefaultSettings": { + "description": "Default configuration for the group.", + "type": "integer" + } + }, + "required": [ + "Name", + "Type" + ], + "oneOf": [ + { + "properties": { + "Type": { + "const": "Single" + }, + "Options": { + "type": "array", + "items": { + "allOf": [ + { + "type": "object", + "properties": { + "Description": { + "description": "Description of the option.", + "type": ["string", "null"] + }, + "Image": { + "description": "Unused by Penumbra.", + "type": ["string", "null"] + } + } + }, { + "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" + } + ] + } + } + } + }, { + "properties": { + "Type": { + "const": "Multi" + }, + "Options": { + "type": "array", + "items": { + "allOf": [ + { + "type": "object", + "properties": { + "Description": { + "description": "Description of the option.", + "type": ["string", "null"] + }, + "Priority": { + "description": "Priority of the option. If several enabled options within the group define conflicting files or manipulations, the highest priority wins.", + "type": ["integer", "null"] + }, + "Image": { + "description": "Unused by Penumbra.", + "type": ["string", "null"] + } + } + }, { + "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" + } + ] + } + } + } + }, { + "properties": { + "Type": { + "const": "Imc" + }, + "AllVariants": { + "type": "boolean" + }, + "OnlyAttributes": { + "type": "boolean" + }, + "Identifier": { + "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json#/$defs/ImcIdentifier" + }, + "DefaultEntry": { + "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json#/$defs/ImcEntry" + }, + "Options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "Name": { + "description": "Name of the option.", + "type": "string" + }, + "Description": { + "description": "Description of the option.", + "type": ["string", "null"] + }, + "Image": { + "description": "Unused by Penumbra.", + "type": ["string", "null"] + } + }, + "required": [ + "Name" + ], + "oneOf": [ + { + "properties": { + "AttributeMask": { + "type": "integer" + } + }, + "required": [ + "AttributeMask" + ] + }, { + "properties": { + "IsDisableSubMod": { + "const": true + } + }, + "required": [ + "IsDisableSubMod" + ] + } + ], + "unevaluatedProperties": false + } + } + } + }, { + "properties": { + "Type": { + "const": "Combining" + }, + "Options": { + "type": "array", + "items": { + "type": "object", + "properties": { + "Name": { + "description": "Name of the option.", + "type": "string" + }, + "Description": { + "description": "Description of the option.", + "type": ["string", "null"] + }, + "Image": { + "description": "Unused by Penumbra.", + "type": ["string", "null"] + } + }, + "required": [ + "Name" + ], + "additionalProperties": false + } + }, + "Containers": { + "type": "array", + "items": { + "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" + } + } + } + } + ], + "unevaluatedProperties": false +} diff --git a/schemas/meta-v3.json b/schemas/meta-v3.json new file mode 100644 index 00000000..1a132264 --- /dev/null +++ b/schemas/meta-v3.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/meta-v3.json", + "title": "Penumbra Mod Metadata", + "description": "Metadata of a Penumbra mod.", + "type": "object", + "properties": { + "FileVersion": { + "description": "Major version of the metadata schema used.", + "type": "integer", + "minimum": 3, + "maximum": 3 + }, + "Name": { + "description": "Name of the mod.", + "type": "string" + }, + "Author": { + "description": "Author of the mod.", + "type": ["string", "null"] + }, + "Description": { + "description": "Description of the mod. Can span multiple paragraphs.", + "type": ["string", "null"] + }, + "Image": { + "description": "Relative path to a preview image for the mod. Unused by Penumbra, present for round-trip import/export of TexTools-generated mods.", + "type": ["string", "null"] + }, + "Version": { + "description": "Version of the mod. Can be an arbitrary string.", + "type": ["string", "null"] + }, + "Website": { + "description": "URL of the web page of the mod.", + "type": ["string", "null"] + }, + "ModTags": { + "description": "Author-defined tags for the mod.", + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + } + }, + "required": [ + "FileVersion", + "Name" + ] +} From 3b8aac8eca94e8253b357a8b885a56bb7919e7d2 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 17 Jan 2025 18:50:00 +0100 Subject: [PATCH 1060/1381] Add schema for Material Development Kit files --- schemas/shpk_devkit.json | 500 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 500 insertions(+) create mode 100644 schemas/shpk_devkit.json diff --git a/schemas/shpk_devkit.json b/schemas/shpk_devkit.json new file mode 100644 index 00000000..cd18ab81 --- /dev/null +++ b/schemas/shpk_devkit.json @@ -0,0 +1,500 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/shpk_devkit.json", + "type": "object", + "properties": { + "ShaderKeys": { + "type": "object", + "patternProperties": { + "^\\d+$": { + "$ref": "#/$defs/ShaderKey" + } + }, + "additionalProperties": false + }, + "Comment": { + "$ref": "#/$defs/MayVary" + }, + "Samplers": { + "type": "object", + "patternProperties": { + "^\\d+$": { + "$ref": "#/$defs/MayVary" + } + }, + "additionalProperties": false + }, + "Constants": { + "type": "object", + "patternProperties": { + "^\\d+$": { + "$ref": "#/$defs/MayVary" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false, + "$defs": { + "ShaderKeyValue": { + "type": "object", + "properties": { + "Label": { + "type": "string" + }, + "Description": { + "type": "string" + } + }, + "additionalProperties": false + }, + "ShaderKey": { + "type": "object", + "properties": { + "Label": { + "type": "string" + }, + "Description": { + "type": "string" + }, + "Values": { + "type": "object", + "patternProperties": { + "^\\d+$": { + "$ref": "#/$defs/ShaderKeyValue" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "Varying": { + "type": "object", + "properties": { + "Vary": { + "type": "array", + "items": { + "$ref": "#/$defs/LaxInteger" + } + }, + "Selectors": { + "description": "Keys are Σ 31^i shaderKey(Vary[i]).", + "type": "object", + "patternProperties": { + "^\\d+$": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "Items": { + "type": "array", + "$comment": "Varying is defined by constraining this array's items to T" + } + }, + "required": [ + "Vary", + "Selectors", + "Items" + ], + "additionalProperties": false + }, + "MayVary": { + "oneOf": [ + { + "type": ["string", "null"] + }, { + "allOf": [ + { + "$ref": "#/$defs/Varying" + }, { + "type": "object", + "properties": { + "Items": { + "type": "array", + "items": { + "type": ["string", "null"] + } + } + } + } + ] + } + ] + }, + "Sampler": { + "type": ["object", "null"], + "properties": { + "Label": { + "type": "string" + }, + "Description": { + "type": "string" + }, + "DefaultTexture": { + "type": "string", + "pattern": "^[^/\\\\][^\\\\]*$" + } + }, + "additionalProperties": false + }, + "MayVary": { + "oneOf": [ + { + "$ref": "#/$defs/Sampler" + }, { + "allOf": [ + { + "$ref": "#/$defs/Varying" + }, { + "type": "object", + "properties": { + "Items": { + "type": "array", + "items": { + "$ref": "#/$defs/Sampler" + } + } + } + } + ] + } + ] + }, + "ConstantBase": { + "type": "object", + "properties": { + "Offset": { + "description": "Defaults to 0. Mutually exclusive with ByteOffset.", + "type": "integer", + "minimum": 0 + }, + "Length": { + "description": "Defaults to up to the end. Mutually exclusive with ByteLength.", + "type": "integer", + "minimum": 0 + }, + "ByteOffset": { + "description": "Defaults to 0. Mutually exclusive with Offset.", + "type": "integer", + "minimum": 0 + }, + "ByteLength": { + "description": "Defaults to up to the end. Mutually exclusive with Length.", + "type": "integer", + "minimum": 0 + }, + "Group": { + "description": "Defaults to \"Further Constants\".", + "type": "string" + }, + "Label": { + "type": "string" + }, + "Description": { + "description": "Defaults to empty.", + "type": "string" + }, + "Type": { + "description": "Defaults to Float.", + "enum": ["Hidden", "Float", "Integer", "Color", "Enum", "Int32", "Int32Enum", "Int8", "Int8Enum", "Int16", "Int16Enum", "Int64", "Int64Enum", "Half", "Double", "TileIndex", "SphereMapIndex"] + } + }, + "not": { + "anyOf": [ + { + "required": ["Offset", "ByteOffset"] + }, { + "required": ["Length", "ByteLenngth"] + } + ] + } + }, + "HiddenConstant": { + "type": "object", + "properties": { + "Type": { + "const": "Hidden" + } + }, + "required": [ + "Type" + ], + "allOf": [ + { + "$ref": "#/$defs/ConstantBase" + } + ], + "unevaluatedProperties": false + }, + "FloatConstant": { + "type": "object", + "properties": { + "Type": { + "enum": ["Float", "Half", "Double"] + }, + "Minimum": { + "description": "Defaults to -∞.", + "type": "number" + }, + "Maximum": { + "description": "Defaults to ∞.", + "type": "number" + }, + "Speed": { + "description": "Defaults to 0.1.", + "type": "number", + "minimum": 0 + }, + "RelativeSpeed": { + "description": "Defaults to 0.", + "type": "number", + "minimum": 0 + }, + "Exponent": { + "description": "Defaults to 1. Uses an odd pseudo-power function, f(x) = sgn(x) |x|^n.", + "type": "number" + }, + "Factor": { + "description": "Defaults to 1.", + "type": "number" + }, + "Bias": { + "description": "Defaults to 0.", + "type": "number" + }, + "Precision": { + "description": "Defaults to 3.", + "type": "integer", + "minimum": 0, + "maximum": 9 + }, + "Slider": { + "description": "Defaults to true. Drag has priority over this.", + "type": "boolean" + }, + "Drag": { + "description": "Defaults to true. Has priority over Slider.", + "type": "boolean" + }, + "Unit": { + "description": "Defaults to no unit.", + "type": "string" + } + }, + "required": [ + "Label" + ], + "allOf": [ + { + "$ref": "#/$defs/ConstantBase" + } + ], + "unevaluatedProperties": false + }, + "IntConstant": { + "type": "object", + "properties": { + "Type": { + "enum": ["Integer", "Int32", "Int8", "Int16", "Int64"] + }, + "Minimum": { + "description": "Defaults to -2^N, N being the explicit integer width specified in the type, or 32 for Int.", + "type": "number" + }, + "Maximum": { + "description": "Defaults to 2^N - 1, N being the explicit integer width specified in the type, or 32 for Int.", + "type": "number" + }, + "Speed": { + "description": "Defaults to 0.25.", + "type": "number", + "minimum": 0 + }, + "RelativeSpeed": { + "description": "Defaults to 0.", + "type": "number", + "minimum": 0 + }, + "Factor": { + "description": "Defaults to 1.", + "type": "number" + }, + "Bias": { + "description": "Defaults to 0.", + "type": "number" + }, + "Hex": { + "description": "Defaults to false. Has priority over Slider and Drag.", + "type": "boolean" + }, + "Slider": { + "description": "Defaults to true. Hex and Drag have priority over this.", + "type": "boolean" + }, + "Drag": { + "description": "Defaults to true. Has priority over Slider, but Hex has priority over this.", + "type": "boolean" + }, + "Unit": { + "description": "Defaults to no unit.", + "type": "string" + } + }, + "required": [ + "Label", + "Type" + ], + "allOf": [ + { + "$ref": "#/$defs/ConstantBase" + } + ], + "unevaluatedProperties": false + }, + "ColorConstant": { + "type": "object", + "properties": { + "Type": { + "const": "Color" + }, + "SquaredRgb": { + "description": "Defaults to false. Uses an odd pseudo-square function, f(x) = sgn(x) |x|².", + "type": "boolean" + }, + "Clamped": { + "description": "Defaults to false.", + "type": "boolean" + } + }, + "required": [ + "Label", + "Type" + ], + "allOf": [ + { + "$ref": "#/$defs/ConstantBase" + } + ], + "unevaluatedProperties": false + }, + "EnumValue": { + "type": "object", + "properties": { + "Label": { + "type": "string" + }, + "Description": { + "type": "string" + }, + "Value": { + "type": "number" + } + }, + "required": [ + "Label", + "Value" + ], + "additionalProperties": false + }, + "EnumConstant": { + "type": "object", + "properties": { + "Type": { + "enum": ["Enum", "Int32Enum", "Int8Enum", "Int16Enum", "Int64Enum"] + }, + "Values": { + "type": "array", + "items": { + "$ref": "#/$defs/EnumValue" + } + } + }, + "required": [ + "Label", + "Type" + ], + "allOf": [ + { + "$ref": "#/$defs/ConstantBase" + } + ], + "unevaluatedProperties": false + }, + "SpecialConstant": { + "type": "object", + "properties": { + "Type": { + "enum": ["TileIndex", "SphereMapIndex"] + } + }, + "required": [ + "Label", + "Type" + ], + "allOf": [ + { + "$ref": "#/$defs/ConstantBase" + } + ], + "unevaluatedProperties": false + }, + "Constant": { + "oneOf": [ + { + "$ref": "#/$defs/HiddenConstant" + }, { + "$ref": "#/$defs/FloatConstant" + }, { + "$ref": "#/$defs/IntConstant" + }, { + "$ref": "#/$defs/ColorConstant" + }, { + "$ref": "#/$defs/EnumConstant" + }, { + "$ref": "#/$defs/SpecialConstant" + } + ] + }, + "MayVary": { + "oneOf": [ + { + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/Constant" + } + }, { + "allOf": [ + { + "$ref": "#/$defs/Varying" + }, { + "type": "object", + "properties": { + "Items": { + "type": "array", + "items": { + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/Constant" + } + } + } + } + } + ] + } + ] + }, + "LaxInteger": { + "oneOf": [ + { + "type": "integer" + }, { + "type": "string", + "pattern": "^\\d+$" + } + ] + } + } +} From 5f8377acaaf1bc20944af85e525b09313285272c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Jan 2025 19:54:40 +0100 Subject: [PATCH 1061/1381] Update mod loading structure. --- Penumbra.GameData | 2 +- Penumbra/Mods/Manager/ModDataEditor.cs | 145 +------------------------ Penumbra/Mods/ModCreator.cs | 4 +- Penumbra/Mods/ModLocalData.cs | 57 ++++++++++ Penumbra/Mods/ModMeta.cs | 83 ++++++++++++++ 5 files changed, 146 insertions(+), 145 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 78ce195c..c5250722 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 78ce195c171d7bce4ad9df105f1f95cce9bf1150 +Subproject commit c525072299d5febd2bb638ab229060b0073ba6a6 diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 162f823d..7c48205a 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -27,6 +27,9 @@ public enum ModDataChangeType : ushort public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService) : IService { + public SaveService SaveService + => saveService; + /// Create the file containing the meta information about a mod from scratch. public void CreateMeta(DirectoryInfo directory, string? name, string? author, string? description, string? version, string? website) @@ -40,148 +43,6 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic saveService.ImmediateSaveSync(new ModMeta(mod)); } - public ModDataChangeType LoadLocalData(Mod mod) - { - var dataFile = saveService.FileNames.LocalDataFile(mod); - - var importDate = 0L; - var localTags = Enumerable.Empty(); - var favorite = false; - var note = string.Empty; - - var save = true; - if (File.Exists(dataFile)) - try - { - var text = File.ReadAllText(dataFile); - var json = JObject.Parse(text); - - importDate = json[nameof(Mod.ImportDate)]?.Value() ?? importDate; - favorite = json[nameof(Mod.Favorite)]?.Value() ?? favorite; - note = json[nameof(Mod.Note)]?.Value() ?? note; - localTags = (json[nameof(Mod.LocalTags)] as JArray)?.Values().OfType() ?? localTags; - save = false; - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not load local mod data:\n{e}"); - } - - if (importDate == 0) - importDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - - ModDataChangeType changes = 0; - if (mod.ImportDate != importDate) - { - mod.ImportDate = importDate; - changes |= ModDataChangeType.ImportDate; - } - - changes |= ModLocalData.UpdateTags(mod, null, localTags); - - if (mod.Favorite != favorite) - { - mod.Favorite = favorite; - changes |= ModDataChangeType.Favorite; - } - - if (mod.Note != note) - { - mod.Note = note; - changes |= ModDataChangeType.Note; - } - - if (save) - saveService.QueueSave(new ModLocalData(mod)); - - return changes; - } - - public ModDataChangeType LoadMeta(ModCreator creator, Mod mod) - { - var metaFile = saveService.FileNames.ModMetaPath(mod); - if (!File.Exists(metaFile)) - { - Penumbra.Log.Debug($"No mod meta found for {mod.ModPath.Name}."); - return ModDataChangeType.Deletion; - } - - try - { - var text = File.ReadAllText(metaFile); - var json = JObject.Parse(text); - - var newName = json[nameof(Mod.Name)]?.Value() ?? string.Empty; - var newAuthor = json[nameof(Mod.Author)]?.Value() ?? string.Empty; - var newDescription = json[nameof(Mod.Description)]?.Value() ?? string.Empty; - var newImage = json[nameof(Mod.Image)]?.Value() ?? string.Empty; - var newVersion = json[nameof(Mod.Version)]?.Value() ?? string.Empty; - var newWebsite = json[nameof(Mod.Website)]?.Value() ?? string.Empty; - var newFileVersion = json[nameof(ModMeta.FileVersion)]?.Value() ?? 0; - var importDate = json[nameof(Mod.ImportDate)]?.Value(); - var modTags = (json[nameof(Mod.ModTags)] as JArray)?.Values().OfType(); - - ModDataChangeType changes = 0; - if (mod.Name != newName) - { - changes |= ModDataChangeType.Name; - mod.Name = newName; - } - - if (mod.Author != newAuthor) - { - changes |= ModDataChangeType.Author; - mod.Author = newAuthor; - } - - if (mod.Description != newDescription) - { - changes |= ModDataChangeType.Description; - mod.Description = newDescription; - } - - if (mod.Image != newImage) - { - changes |= ModDataChangeType.Image; - mod.Image = newImage; - } - - if (mod.Version != newVersion) - { - changes |= ModDataChangeType.Version; - mod.Version = newVersion; - } - - if (mod.Website != newWebsite) - { - changes |= ModDataChangeType.Website; - mod.Website = newWebsite; - } - - if (newFileVersion != ModMeta.FileVersion) - if (ModMigration.Migrate(creator, saveService, mod, json, ref newFileVersion)) - { - changes |= ModDataChangeType.Migration; - saveService.ImmediateSave(new ModMeta(mod)); - } - - if (importDate != null && mod.ImportDate != importDate.Value) - { - mod.ImportDate = importDate.Value; - changes |= ModDataChangeType.ImportDate; - } - - changes |= ModLocalData.UpdateTags(mod, modTags, null); - - return changes; - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not load mod meta for {metaFile}:\n{e}"); - return ModDataChangeType.Deletion; - } - } - public void ChangeModName(Mod mod, string newName) { if (mod.Name.Text == newName) diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 18d2bc09..0db83ef9 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -72,11 +72,11 @@ public partial class ModCreator( if (!Directory.Exists(mod.ModPath.FullName)) return false; - modDataChange = dataEditor.LoadMeta(this, mod); + modDataChange = ModMeta.Load(dataEditor, this, mod); if (modDataChange.HasFlag(ModDataChangeType.Deletion) || mod.Name.Length == 0) return false; - modDataChange |= dataEditor.LoadLocalData(mod); + modDataChange |= ModLocalData.Load(dataEditor, mod); LoadDefaultOption(mod); LoadAllGroups(mod); if (incorporateMetaChanges) diff --git a/Penumbra/Mods/ModLocalData.cs b/Penumbra/Mods/ModLocalData.cs index beda0dc7..d3534391 100644 --- a/Penumbra/Mods/ModLocalData.cs +++ b/Penumbra/Mods/ModLocalData.cs @@ -27,6 +27,63 @@ public readonly struct ModLocalData(Mod mod) : ISavable jObject.WriteTo(jWriter); } + public static ModDataChangeType Load(ModDataEditor editor, Mod mod) + { + var dataFile = editor.SaveService.FileNames.LocalDataFile(mod); + + var importDate = 0L; + var localTags = Enumerable.Empty(); + var favorite = false; + var note = string.Empty; + + var save = true; + if (File.Exists(dataFile)) + try + { + var text = File.ReadAllText(dataFile); + var json = JObject.Parse(text); + + importDate = json[nameof(Mod.ImportDate)]?.Value() ?? importDate; + favorite = json[nameof(Mod.Favorite)]?.Value() ?? favorite; + note = json[nameof(Mod.Note)]?.Value() ?? note; + localTags = (json[nameof(Mod.LocalTags)] as JArray)?.Values().OfType() ?? localTags; + save = false; + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not load local mod data:\n{e}"); + } + + if (importDate == 0) + importDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + ModDataChangeType changes = 0; + if (mod.ImportDate != importDate) + { + mod.ImportDate = importDate; + changes |= ModDataChangeType.ImportDate; + } + + changes |= ModLocalData.UpdateTags(mod, null, localTags); + + if (mod.Favorite != favorite) + { + mod.Favorite = favorite; + changes |= ModDataChangeType.Favorite; + } + + if (mod.Note != note) + { + mod.Note = note; + changes |= ModDataChangeType.Note; + } + + if (save) + editor.SaveService.QueueSave(new ModLocalData(mod)); + + return changes; + } + internal static ModDataChangeType UpdateTags(Mod mod, IEnumerable? newModTags, IEnumerable? newLocalTags) { if (newModTags == null && newLocalTags == null) diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index 39dd20e4..0cebcf81 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -1,5 +1,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Manager; using Penumbra.Services; namespace Penumbra.Mods; @@ -28,4 +30,85 @@ public readonly struct ModMeta(Mod mod) : ISavable jWriter.Formatting = Formatting.Indented; jObject.WriteTo(jWriter); } + + public static ModDataChangeType Load(ModDataEditor editor, ModCreator creator, Mod mod) + { + var metaFile = editor.SaveService.FileNames.ModMetaPath(mod); + if (!File.Exists(metaFile)) + { + Penumbra.Log.Debug($"No mod meta found for {mod.ModPath.Name}."); + return ModDataChangeType.Deletion; + } + + try + { + var text = File.ReadAllText(metaFile); + var json = JObject.Parse(text); + + var newFileVersion = json[nameof(FileVersion)]?.Value() ?? 0; + + // Empty name gets checked after loading and is not allowed. + var newName = json[nameof(Mod.Name)]?.Value() ?? string.Empty; + + var newAuthor = json[nameof(Mod.Author)]?.Value() ?? string.Empty; + var newDescription = json[nameof(Mod.Description)]?.Value() ?? string.Empty; + var newImage = json[nameof(Mod.Image)]?.Value() ?? string.Empty; + var newVersion = json[nameof(Mod.Version)]?.Value() ?? string.Empty; + var newWebsite = json[nameof(Mod.Website)]?.Value() ?? string.Empty; + var modTags = (json[nameof(Mod.ModTags)] as JArray)?.Values().OfType(); + + ModDataChangeType changes = 0; + if (mod.Name != newName) + { + changes |= ModDataChangeType.Name; + mod.Name = newName; + } + + if (mod.Author != newAuthor) + { + changes |= ModDataChangeType.Author; + mod.Author = newAuthor; + } + + if (mod.Description != newDescription) + { + changes |= ModDataChangeType.Description; + mod.Description = newDescription; + } + + if (mod.Image != newImage) + { + changes |= ModDataChangeType.Image; + mod.Image = newImage; + } + + if (mod.Version != newVersion) + { + changes |= ModDataChangeType.Version; + mod.Version = newVersion; + } + + if (mod.Website != newWebsite) + { + changes |= ModDataChangeType.Website; + mod.Website = newWebsite; + } + + if (newFileVersion != FileVersion) + if (ModMigration.Migrate(creator, editor.SaveService, mod, json, ref newFileVersion)) + { + changes |= ModDataChangeType.Migration; + editor.SaveService.ImmediateSave(new ModMeta(mod)); + } + + changes |= ModLocalData.UpdateTags(mod, modTags, null); + + return changes; + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not load mod meta for {metaFile}:\n{e}"); + return ModDataChangeType.Deletion; + } + } } From ec3ec7db4e686318c9d7c2ee7a3ded8cc6357d4f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 17 Jan 2025 19:55:02 +0100 Subject: [PATCH 1062/1381] update schema organization anf change some things. --- Penumbra.sln | 32 ++ schemas/container.json | 486 --------------------- schemas/default_mod.json | 20 +- schemas/group.json | 189 +------- schemas/local_mod_data-v3.json | 32 ++ schemas/{meta-v3.json => mod_meta-v3.json} | 17 +- schemas/structs/container.json | 34 ++ schemas/structs/group_combining.json | 31 ++ schemas/structs/group_imc.json | 50 +++ schemas/structs/group_multi.json | 32 ++ schemas/structs/group_single.json | 22 + schemas/structs/manipulation.json | 95 ++++ schemas/structs/meta_atch.json | 67 +++ schemas/structs/meta_enums.json | 57 +++ schemas/structs/meta_eqdp.json | 30 ++ schemas/structs/meta_eqp.json | 20 + schemas/structs/meta_est.json | 28 ++ schemas/structs/meta_geqp.json | 40 ++ schemas/structs/meta_gmp.json | 59 +++ schemas/structs/meta_imc.json | 87 ++++ schemas/structs/meta_rsp.json | 20 + schemas/structs/option.json | 24 + 22 files changed, 796 insertions(+), 676 deletions(-) delete mode 100644 schemas/container.json create mode 100644 schemas/local_mod_data-v3.json rename schemas/{meta-v3.json => mod_meta-v3.json} (79%) create mode 100644 schemas/structs/container.json create mode 100644 schemas/structs/group_combining.json create mode 100644 schemas/structs/group_imc.json create mode 100644 schemas/structs/group_multi.json create mode 100644 schemas/structs/group_single.json create mode 100644 schemas/structs/manipulation.json create mode 100644 schemas/structs/meta_atch.json create mode 100644 schemas/structs/meta_enums.json create mode 100644 schemas/structs/meta_eqdp.json create mode 100644 schemas/structs/meta_eqp.json create mode 100644 schemas/structs/meta_est.json create mode 100644 schemas/structs/meta_geqp.json create mode 100644 schemas/structs/meta_gmp.json create mode 100644 schemas/structs/meta_imc.json create mode 100644 schemas/structs/meta_rsp.json create mode 100644 schemas/structs/option.json diff --git a/Penumbra.sln b/Penumbra.sln index 94a04ef3..c0b38118 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -24,6 +24,34 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.String", "Penumbra EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.CrashHandler", "Penumbra.CrashHandler\Penumbra.CrashHandler.csproj", "{EE834491-A98F-4395-BE0D-6861AE5AD953}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Schemas", "Schemas", "{BFEA7504-1210-4F79-A7FE-BF03B6567E33}" + ProjectSection(SolutionItems) = preProject + schemas\files\default_mod.json = schemas\files\default_mod.json + schemas\files\group.json = schemas\files\group.json + schemas\files\local_mod_data-v3.json = schemas\files\local_mod_data-v3.json + schemas\files\mod_meta-v3.json = schemas\files\mod_meta-v3.json + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "structs", "structs", "{B03F276A-0572-4F62-AF86-EF62F6B80463}" + ProjectSection(SolutionItems) = preProject + schemas\structs\container.json = schemas\structs\container.json + schemas\structs\group_combining.json = schemas\structs\group_combining.json + schemas\structs\group_imc.json = schemas\structs\group_imc.json + schemas\structs\group_multi.json = schemas\structs\group_multi.json + schemas\structs\group_single.json = schemas\structs\group_single.json + schemas\structs\manipulation.json = schemas\structs\manipulation.json + schemas\structs\meta_atch.json = schemas\structs\meta_atch.json + schemas\structs\meta_enums.json = schemas\structs\meta_enums.json + schemas\structs\meta_eqdp.json = schemas\structs\meta_eqdp.json + schemas\structs\meta_eqp.json = schemas\structs\meta_eqp.json + schemas\structs\meta_est.json = schemas\structs\meta_est.json + schemas\structs\meta_geqp.json = schemas\structs\meta_geqp.json + schemas\structs\meta_gmp.json = schemas\structs\meta_gmp.json + schemas\structs\meta_imc.json = schemas\structs\meta_imc.json + schemas\structs\meta_rsp.json = schemas\structs\meta_rsp.json + schemas\structs\option.json = schemas\structs\option.json + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -58,6 +86,10 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {BFEA7504-1210-4F79-A7FE-BF03B6567E33} = {F89C9EAE-25C8-43BE-8108-5921E5A93502} + {B03F276A-0572-4F62-AF86-EF62F6B80463} = {BFEA7504-1210-4F79-A7FE-BF03B6567E33} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B17E85B1-5F60-4440-9F9A-3DDE877E8CDF} EndGlobalSection diff --git a/schemas/container.json b/schemas/container.json deleted file mode 100644 index 5798f46c..00000000 --- a/schemas/container.json +++ /dev/null @@ -1,486 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json", - "type": "object", - "properties": { - "Name": { - "description": "Name of the container/option/sub-mod.", - "type": ["string", "null"] - }, - "Files": { - "description": "File redirections in this container. Keys are game paths, values are relative file paths.", - "type": "object", - "patternProperties": { - "^[^/\\\\][^\\\\]*$": { - "type": "string", - "pattern": "^[^/\\\\][^/]*$" - } - }, - "additionalProperties": false - }, - "FileSwaps": { - "description": "File swaps in this container. Keys are original game paths, values are actual game paths.", - "type": "object", - "patternProperties": { - "^[^/\\\\][^\\\\]*$": { - "type": "string", - "pattern": "^[^/\\\\][^/]*$" - } - }, - "additionalProperties": false - }, - "Manipulations": { - "type": "array", - "items": { - "$ref": "#/$defs/Manipulation" - } - } - }, - "$defs": { - "Manipulation": { - "type": "object", - "properties": { - "Type": { - "enum": ["Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch"] - }, - "Manipulation": { - "type": ["object", "null"] - } - }, - "required": ["Type", "Manipulation"], - "oneOf": [ - { - "properties": { - "Type": { - "const": "Unknown" - }, - "Manipulation": { - "type": "null" - } - } - }, { - "properties": { - "Type": { - "const": "Imc" - }, - "Manipulation": { - "$ref": "#/$defs/ImcManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "Eqdp" - }, - "Manipulation": { - "$ref": "#/$defs/EqdpManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "Eqp" - }, - "Manipulation": { - "$ref": "#/$defs/EqpManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "Est" - }, - "Manipulation": { - "$ref": "#/$defs/EstManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "Gmp" - }, - "Manipulation": { - "$ref": "#/$defs/GmpManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "Rsp" - }, - "Manipulation": { - "$ref": "#/$defs/RspManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "GlobalEqp" - }, - "Manipulation": { - "$ref": "#/$defs/GlobalEqpManipulation" - } - } - }, { - "properties": { - "Type": { - "const": "Atch" - }, - "Manipulation": { - "$ref": "#/$defs/AtchManipulation" - } - } - } - ], - "additionalProperties": false - }, - "ImcManipulation": { - "type": "object", - "properties": { - "Entry": { - "$ref": "#/$defs/ImcEntry" - }, - "Valid": { - "type": "boolean" - } - }, - "required": [ - "Entry" - ], - "allOf": [ - { - "$ref": "#/$defs/ImcIdentifier" - } - ], - "unevaluatedProperties": false - }, - "ImcIdentifier": { - "type": "object", - "properties": { - "PrimaryId": { - "type": "integer" - }, - "SecondaryId": { - "type": "integer" - }, - "Variant": { - "type": "integer" - }, - "ObjectType": { - "$ref": "#/$defs/ObjectType" - }, - "EquipSlot": { - "$ref": "#/$defs/EquipSlot" - }, - "BodySlot": { - "$ref": "#/$defs/BodySlot" - } - }, - "required": [ - "PrimaryId", - "SecondaryId", - "Variant", - "ObjectType", - "EquipSlot", - "BodySlot" - ] - }, - "ImcEntry": { - "type": "object", - "properties": { - "AttributeAndSound": { - "type": "integer" - }, - "MaterialId": { - "type": "integer" - }, - "DecalId": { - "type": "integer" - }, - "VfxId": { - "type": "integer" - }, - "MaterialAnimationId": { - "type": "integer" - }, - "AttributeMask": { - "type": "integer" - }, - "SoundId": { - "type": "integer" - } - }, - "required": [ - "MaterialId", - "DecalId", - "VfxId", - "MaterialAnimationId", - "AttributeMask", - "SoundId" - ], - "additionalProperties": false - }, - "EqdpManipulation": { - "type": "object", - "properties": { - "Entry": { - "type": "integer" - }, - "Gender": { - "$ref": "#/$defs/Gender" - }, - "Race": { - "$ref": "#/$defs/ModelRace" - }, - "SetId": { - "$ref": "#/$defs/LaxInteger" - }, - "Slot": { - "$ref": "#/$defs/EquipSlot" - }, - "ShiftedEntry": { - "type": "integer" - } - }, - "required": [ - "Entry", - "Gender", - "Race", - "SetId", - "Slot" - ], - "additionalProperties": false - }, - "EqpManipulation": { - "type": "object", - "properties": { - "Entry": { - "type": "integer" - }, - "SetId": { - "$ref": "#/$defs/LaxInteger" - }, - "Slot": { - "$ref": "#/$defs/EquipSlot" - } - }, - "required": [ - "Entry", - "SetId", - "Slot" - ], - "additionalProperties": false - }, - "EstManipulation": { - "type": "object", - "properties": { - "Entry": { - "type": "integer" - }, - "Gender": { - "$ref": "#/$defs/Gender" - }, - "Race": { - "$ref": "#/$defs/ModelRace" - }, - "SetId": { - "$ref": "#/$defs/LaxInteger" - }, - "Slot": { - "enum": ["Hair", "Face", "Body", "Head"] - } - }, - "required": [ - "Entry", - "Gender", - "Race", - "SetId", - "Slot" - ], - "additionalProperties": false - }, - "GmpManipulation": { - "type": "object", - "properties": { - "Entry": { - "type": "object", - "properties": { - "Enabled": { - "type": "boolean" - }, - "Animated": { - "type": "boolean" - }, - "RotationA": { - "type": "number" - }, - "RotationB": { - "type": "number" - }, - "RotationC": { - "type": "number" - }, - "UnknownA": { - "type": "number" - }, - "UnknownB": { - "type": "number" - }, - "UnknownTotal": { - "type": "number" - }, - "Value": { - "type": "number" - } - }, - "required": [ - "Enabled", - "Animated", - "RotationA", - "RotationB", - "RotationC", - "UnknownA", - "UnknownB", - "UnknownTotal", - "Value" - ], - "additionalProperties": false - }, - "SetId": { - "$ref": "#/$defs/LaxInteger" - } - }, - "required": [ - "Entry", - "SetId" - ], - "additionalProperties": false - }, - "RspManipulation": { - "type": "object", - "properties": { - "Entry": { - "type": "number" - }, - "SubRace": { - "$ref": "#/$defs/SubRace" - }, - "Attribute": { - "$ref": "#/$defs/RspAttribute" - } - }, - "additionalProperties": false - }, - "GlobalEqpManipulation": { - "type": "object", - "properties": { - "Condition": { - "type": "integer" - }, - "Type": { - "enum": ["DoNotHideEarrings", "DoNotHideNecklace", "DoNotHideBracelets", "DoNotHideRingR", "DoNotHideRingL", "DoNotHideHrothgarHats", "DoNotHideVieraHats"] - } - }, - "additionalProperties": false - }, - "AtchManipulation": { - "type": "object", - "properties": { - "Entry": { - "type": "object", - "properties": { - "Bone": { - "type": "string", - "maxLength": 34 - }, - "Scale": { - "type": "number" - }, - "OffsetX": { - "type": "number" - }, - "OffsetY": { - "type": "number" - }, - "OffsetZ": { - "type": "number" - }, - "RotationX": { - "type": "number" - }, - "RotationY": { - "type": "number" - }, - "RotationZ": { - "type": "number" - } - }, - "required": [ - "Bone", - "Scale", - "OffsetX", - "OffsetY", - "OffsetZ", - "RotationX", - "RotationY", - "RotationZ" - ], - "additionalProperties": false - }, - "Gender": { - "$ref": "#/$defs/Gender" - }, - "Race": { - "$ref": "#/$defs/ModelRace" - }, - "Type": { - "type": "string", - "minLength": 3, - "maxLength": 3 - }, - "Index": { - "type": "integer" - } - }, - "required": [ - "Entry", - "Gender", - "Race", - "Type", - "Index" - ], - "additionalProperties": false - }, - "LaxInteger": { - "oneOf": [ - { - "type": "integer" - }, { - "type": "string", - "pattern": "^\\d+$" - } - ] - }, - "EquipSlot": { - "enum": ["Unknown", "MainHand", "OffHand", "Head", "Body", "Hands", "Belt", "Legs", "Feet", "Ears", "Neck", "Wrists", "RFinger", "BothHand", "LFinger", "HeadBody", "BodyHandsLegsFeet", "SoulCrystal", "LegsFeet", "FullBody", "BodyHands", "BodyLegsFeet", "ChestHands", "Nothing", "All"] - }, - "Gender": { - "enum": ["Unknown", "Male", "Female", "MaleNpc", "FemaleNpc"] - }, - "ModelRace": { - "enum": ["Unknown", "Midlander", "Highlander", "Elezen", "Lalafell", "Miqote", "Roegadyn", "AuRa", "Hrothgar", "Viera"] - }, - "ObjectType": { - "enum": ["Unknown", "Vfx", "DemiHuman", "Accessory", "World", "Housing", "Monster", "Icon", "LoadingScreen", "Map", "Interface", "Equipment", "Character", "Weapon", "Font"] - }, - "BodySlot": { - "enum": ["Unknown", "Hair", "Face", "Tail", "Body", "Zear"] - }, - "SubRace": { - "enum": ["Unknown", "Midlander", "Highlander", "Wildwood", "Duskwight", "Plainsfolk", "Dunesfolk", "SeekerOfTheSun", "KeeperOfTheMoon", "Seawolf", "Hellsguard", "Raen", "Xaela", "Helion", "Lost", "Rava", "Veena"] - }, - "RspAttribute": { - "enum": ["MaleMinSize", "MaleMaxSize", "MaleMinTail", "MaleMaxTail", "FemaleMinSize", "FemaleMaxSize", "FemaleMinTail", "FemaleMaxTail", "BustMinX", "BustMinY", "BustMinZ", "BustMaxX", "BustMaxY", "BustMaxZ"] - } - } -} diff --git a/schemas/default_mod.json b/schemas/default_mod.json index eecd74d0..8f50c5db 100644 --- a/schemas/default_mod.json +++ b/schemas/default_mod.json @@ -1,25 +1,19 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json", "allOf": [ { "type": "object", "properties": { "Version": { - "description": "???", - "type": ["integer", "null"] - }, - "Description": { - "description": "Description of the sub-mod.", - "type": ["string", "null"] - }, - "Image": { - "description": "Unused by Penumbra.", - "type": ["string", "null"] + "description": "Mod Container version, currently unused.", + "type": "integer", + "minimum": 0, + "maximum": 0 } } - }, { - "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" + }, + { + "$ref": "structs/container.json" } ] } diff --git a/schemas/group.json b/schemas/group.json index 0078e9f3..4c37b631 100644 --- a/schemas/group.json +++ b/schemas/group.json @@ -1,35 +1,35 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/group.json", "type": "object", "properties": { "Version": { - "description": "???", - "type": ["integer", "null"] + "description": "Mod Container version, currently unused.", + "type": "integer" }, "Name": { "description": "Name of the group.", - "type": "string" + "type": "string", + "minLength": 1 }, "Description": { "description": "Description of the group.", - "type": ["string", "null"] + "type": [ "string", "null" ] }, "Image": { "description": "Relative path to a preview image for the group. Unused by Penumbra, present for round-trip import/export of TexTools-generated mods.", - "type": ["string", "null"] + "type": ["string", "null" ] }, "Page": { "description": "TexTools page of the group. Unused by Penumbra, present for round-trip import/export of TexTools-generated mods.", - "type": ["integer", "null"] + "type": "integer" }, "Priority": { "description": "Priority of the group. If several groups define conflicting files or manipulations, the highest priority wins.", - "type": ["integer", "null"] + "type": "integer" }, "Type": { "description": "Group type. Single groups have one and only one of their options active at any point. Multi groups can have zero, one or many of their options active. Combining groups have n options, 2^n containers, and will have one and only one container active depending on the selected options.", - "enum": ["Single", "Multi", "Imc", "Combining"] + "enum": [ "Single", "Multi", "Imc", "Combining" ] }, "DefaultSettings": { "description": "Default configuration for the group.", @@ -42,165 +42,16 @@ ], "oneOf": [ { - "properties": { - "Type": { - "const": "Single" - }, - "Options": { - "type": "array", - "items": { - "allOf": [ - { - "type": "object", - "properties": { - "Description": { - "description": "Description of the option.", - "type": ["string", "null"] - }, - "Image": { - "description": "Unused by Penumbra.", - "type": ["string", "null"] - } - } - }, { - "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" - } - ] - } - } - } - }, { - "properties": { - "Type": { - "const": "Multi" - }, - "Options": { - "type": "array", - "items": { - "allOf": [ - { - "type": "object", - "properties": { - "Description": { - "description": "Description of the option.", - "type": ["string", "null"] - }, - "Priority": { - "description": "Priority of the option. If several enabled options within the group define conflicting files or manipulations, the highest priority wins.", - "type": ["integer", "null"] - }, - "Image": { - "description": "Unused by Penumbra.", - "type": ["string", "null"] - } - } - }, { - "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" - } - ] - } - } - } - }, { - "properties": { - "Type": { - "const": "Imc" - }, - "AllVariants": { - "type": "boolean" - }, - "OnlyAttributes": { - "type": "boolean" - }, - "Identifier": { - "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json#/$defs/ImcIdentifier" - }, - "DefaultEntry": { - "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json#/$defs/ImcEntry" - }, - "Options": { - "type": "array", - "items": { - "type": "object", - "properties": { - "Name": { - "description": "Name of the option.", - "type": "string" - }, - "Description": { - "description": "Description of the option.", - "type": ["string", "null"] - }, - "Image": { - "description": "Unused by Penumbra.", - "type": ["string", "null"] - } - }, - "required": [ - "Name" - ], - "oneOf": [ - { - "properties": { - "AttributeMask": { - "type": "integer" - } - }, - "required": [ - "AttributeMask" - ] - }, { - "properties": { - "IsDisableSubMod": { - "const": true - } - }, - "required": [ - "IsDisableSubMod" - ] - } - ], - "unevaluatedProperties": false - } - } - } - }, { - "properties": { - "Type": { - "const": "Combining" - }, - "Options": { - "type": "array", - "items": { - "type": "object", - "properties": { - "Name": { - "description": "Name of the option.", - "type": "string" - }, - "Description": { - "description": "Description of the option.", - "type": ["string", "null"] - }, - "Image": { - "description": "Unused by Penumbra.", - "type": ["string", "null"] - } - }, - "required": [ - "Name" - ], - "additionalProperties": false - } - }, - "Containers": { - "type": "array", - "items": { - "$ref": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/container.json" - } - } - } + "$ref": "structs/group_combining.json" + }, + { + "$ref": "structs/group_imc.json" + }, + { + "$ref": "structs/group_multi.json" + }, + { + "$ref": "structs/group_single.json" } - ], - "unevaluatedProperties": false + ] } diff --git a/schemas/local_mod_data-v3.json b/schemas/local_mod_data-v3.json new file mode 100644 index 00000000..bf5d1311 --- /dev/null +++ b/schemas/local_mod_data-v3.json @@ -0,0 +1,32 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Local Penumbra Mod Data", + "description": "The locally stored data for an installed mod in Penumbra", + "type": "object", + "properties": { + "FileVersion": { + "description": "Major version of the local data schema used.", + "type": "integer", + "minimum": 3, + "maximum": 3 + }, + "ImportDate": { + "description": "The date and time of the installation of the mod as a Unix Epoch millisecond timestamp.", + "type": "integer" + }, + "LocalTags": { + "description": "User-defined local tags for the mod.", + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "uniqueItems": true + }, + "Favorite": { + "description": "Whether the mod is favourited by the user.", + "type": "boolean" + } + }, + "required": [ "FileVersion" ] +} diff --git a/schemas/meta-v3.json b/schemas/mod_meta-v3.json similarity index 79% rename from schemas/meta-v3.json rename to schemas/mod_meta-v3.json index 1a132264..a926b49e 100644 --- a/schemas/meta-v3.json +++ b/schemas/mod_meta-v3.json @@ -1,6 +1,5 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/meta-v3.json", "title": "Penumbra Mod Metadata", "description": "Metadata of a Penumbra mod.", "type": "object", @@ -13,33 +12,35 @@ }, "Name": { "description": "Name of the mod.", - "type": "string" + "type": "string", + "minLength": 1 }, "Author": { "description": "Author of the mod.", - "type": ["string", "null"] + "type": [ "string", "null" ] }, "Description": { "description": "Description of the mod. Can span multiple paragraphs.", - "type": ["string", "null"] + "type": [ "string", "null" ] }, "Image": { "description": "Relative path to a preview image for the mod. Unused by Penumbra, present for round-trip import/export of TexTools-generated mods.", - "type": ["string", "null"] + "type": [ "string", "null" ] }, "Version": { "description": "Version of the mod. Can be an arbitrary string.", - "type": ["string", "null"] + "type": [ "string", "null" ] }, "Website": { "description": "URL of the web page of the mod.", - "type": ["string", "null"] + "type": [ "string", "null" ] }, "ModTags": { "description": "Author-defined tags for the mod.", "type": "array", "items": { - "type": "string" + "type": "string", + "minLength": 1 }, "uniqueItems": true } diff --git a/schemas/structs/container.json b/schemas/structs/container.json new file mode 100644 index 00000000..74db4a23 --- /dev/null +++ b/schemas/structs/container.json @@ -0,0 +1,34 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Files": { + "description": "File redirections in this container. Keys are game paths, values are relative file paths.", + "type": [ "object", "null" ], + "patternProperties": { + "^[^/\\\\.:?][^\\\\?:]+$": { + "type": "string", + "pattern": "^[^/\\\\.:?][^?:]+$" + } + }, + "additionalProperties": false + }, + "FileSwaps": { + "description": "File swaps in this container. Keys are original game paths, values are actual game paths.", + "type": [ "object", "null" ], + "patternProperties": { + "^[^/\\\\.?:][^\\\\?:]+$": { + "type": "string", + "pattern": "^[^/\\\\.:?][^?:]+$" + } + }, + "additionalProperties": false + }, + "Manipulations": { + "type": [ "array", "null" ], + "items": { + "$ref": "manipulation.json" + } + } + } +} diff --git a/schemas/structs/group_combining.json b/schemas/structs/group_combining.json new file mode 100644 index 00000000..e42edcb8 --- /dev/null +++ b/schemas/structs/group_combining.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "Type": { + "const": "Combining" + }, + "Options": { + "type": "array", + "items": { + "$ref": "option.json" + } + }, + "Containers": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "container.json" + }, + { + "properties": { + "Name": { + "type": [ "string", "null" ] + } + } + } + ] + } + } + } +} diff --git a/schemas/structs/group_imc.json b/schemas/structs/group_imc.json new file mode 100644 index 00000000..48a04bd9 --- /dev/null +++ b/schemas/structs/group_imc.json @@ -0,0 +1,50 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "Type": { + "const": "Imc" + }, + "AllVariants": { + "type": "boolean" + }, + "OnlyAttributes": { + "type": "boolean" + }, + "Identifier": { + "$ref": "meta_imc.json#ImcIdentifier" + }, + "DefaultEntry": { + "$ref": "meta_imc.json#ImcEntry" + }, + "Options": { + "type": "array", + "items": { + "$ref": "option.json", + "oneOf": [ + { + "properties": { + "AttributeMask": { + "type": "integer", + "minimum": 0, + "maximum": 1023 + } + }, + "required": [ + "AttributeMask" + ] + }, + { + "properties": { + "IsDisableSubMod": { + "const": true + } + }, + "required": [ + "IsDisableSubMod" + ] + } + ] + } + } + } +} diff --git a/schemas/structs/group_multi.json b/schemas/structs/group_multi.json new file mode 100644 index 00000000..ca7d4dfa --- /dev/null +++ b/schemas/structs/group_multi.json @@ -0,0 +1,32 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Type": { + "const": "Multi" + }, + "Options": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "option.json" + }, + { + "$ref": "container.json" + }, + { + "properties": { + "Priority": { + "type": "integer" + } + } + } + ] + } + } + } +} + + + diff --git a/schemas/structs/group_single.json b/schemas/structs/group_single.json new file mode 100644 index 00000000..24cda88d --- /dev/null +++ b/schemas/structs/group_single.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Type": { + "const": "Single" + }, + "Options": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "option.json" + }, + { + "$ref": "container.json" + } + ] + } + } + } +} diff --git a/schemas/structs/manipulation.json b/schemas/structs/manipulation.json new file mode 100644 index 00000000..4a41dbe2 --- /dev/null +++ b/schemas/structs/manipulation.json @@ -0,0 +1,95 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Type": { + "enum": [ "Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch" ] + }, + "Manipulation": { + "type": "object" + } + }, + "required": [ "Type", "Manipulation" ], + "oneOf": [ + { + "properties": { + "Type": { + "const": "Imc" + }, + "Manipulation": { + "$ref": "meta_imc.json" + } + } + }, + { + "properties": { + "Type": { + "const": "Eqdp" + }, + "Manipulation": { + "$ref": "meta_eqdp.json" + } + } + }, + { + "properties": { + "Type": { + "const": "Eqp" + }, + "Manipulation": { + "$ref": "meta_eqp.json" + } + } + }, + { + "properties": { + "Type": { + "const": "Est" + }, + "Manipulation": { + "$ref": "meta_est.json" + } + } + }, + { + "properties": { + "Type": { + "const": "Gmp" + }, + "Manipulation": { + "$ref": "meta_gmp.json" + } + } + }, + { + "properties": { + "Type": { + "const": "Rsp" + }, + "Manipulation": { + "$ref": "meta_rsp.json" + } + } + }, + { + "properties": { + "Type": { + "const": "GlobalEqp" + }, + "Manipulation": { + "$ref": "meta_geqp.json" + } + } + }, + { + "properties": { + "Type": { + "const": "Atch" + }, + "Manipulation": { + "$ref": "meta_atch.json" + } + } + } + ] +} diff --git a/schemas/structs/meta_atch.json b/schemas/structs/meta_atch.json new file mode 100644 index 00000000..3c9cbef5 --- /dev/null +++ b/schemas/structs/meta_atch.json @@ -0,0 +1,67 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "object", + "properties": { + "Bone": { + "type": "string", + "maxLength": 34 + }, + "Scale": { + "type": "number" + }, + "OffsetX": { + "type": "number" + }, + "OffsetY": { + "type": "number" + }, + "OffsetZ": { + "type": "number" + }, + "RotationX": { + "type": "number" + }, + "RotationY": { + "type": "number" + }, + "RotationZ": { + "type": "number" + } + }, + "required": [ + "Bone", + "Scale", + "OffsetX", + "OffsetY", + "OffsetZ", + "RotationX", + "RotationY", + "RotationZ" + ] + }, + "Gender": { + "$ref": "meta_enums.json#Gender" + }, + "Race": { + "$ref": "meta_enums.json#ModelRace" + }, + "Type": { + "type": "string", + "minLength": 1, + "maxLength": 4 + }, + "Index": { + "$ref": "meta_enums.json#U16" + } + }, + "required": [ + "Entry", + "Gender", + "Race", + "Type", + "Index" + ] +} diff --git a/schemas/structs/meta_enums.json b/schemas/structs/meta_enums.json new file mode 100644 index 00000000..747da849 --- /dev/null +++ b/schemas/structs/meta_enums.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "EquipSlot": { + "$anchor": "EquipSlot", + "enum": [ "Unknown", "MainHand", "OffHand", "Head", "Body", "Hands", "Belt", "Legs", "Feet", "Ears", "Neck", "Wrists", "RFinger", "BothHand", "LFinger", "HeadBody", "BodyHandsLegsFeet", "SoulCrystal", "LegsFeet", "FullBody", "BodyHands", "BodyLegsFeet", "ChestHands", "Nothing", "All" ] + }, + "Gender": { + "$anchor": "Gender", + "enum": [ "Unknown", "Male", "Female", "MaleNpc", "FemaleNpc" ] + }, + "ModelRace": { + "$anchor": "ModelRace", + "enum": [ "Unknown", "Midlander", "Highlander", "Elezen", "Lalafell", "Miqote", "Roegadyn", "AuRa", "Hrothgar", "Viera" ] + }, + "ObjectType": { + "$anchor": "ObjectType", + "enum": [ "Unknown", "Vfx", "DemiHuman", "Accessory", "World", "Housing", "Monster", "Icon", "LoadingScreen", "Map", "Interface", "Equipment", "Character", "Weapon", "Font" ] + }, + "BodySlot": { + "$anchor": "BodySlot", + "enum": [ "Unknown", "Hair", "Face", "Tail", "Body", "Zear" ] + }, + "SubRace": { + "$anchor": "SubRace", + "enum": [ "Unknown", "Midlander", "Highlander", "Wildwood", "Duskwight", "Plainsfolk", "Dunesfolk", "SeekerOfTheSun", "KeeperOfTheMoon", "Seawolf", "Hellsguard", "Raen", "Xaela", "Helion", "Lost", "Rava", "Veena" ] + }, + "U8": { + "$anchor": "U8", + "oneOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 255 + }, + { + "type": "string", + "pattern": "^0*(1[0-9][0-9]|[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$" + } + ] + }, + "U16": { + "$anchor": "U16", + "oneOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 65535 + }, + { + "type": "string", + "pattern": "^0*([1-5][0-9]{4}|[0-9]{0,4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" + } + ] + } + } +} diff --git a/schemas/structs/meta_eqdp.json b/schemas/structs/meta_eqdp.json new file mode 100644 index 00000000..f27606b9 --- /dev/null +++ b/schemas/structs/meta_eqdp.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "integer", + "minimum": 0, + "maximum": 1023 + }, + "Gender": { + "$ref": "meta_enums.json#Gender" + }, + "Race": { + "$ref": "meta_enums.json#ModelRace" + }, + "SetId": { + "$ref": "meta_enums.json#U16" + }, + "Slot": { + "$ref": "meta_enums.json#EquipSlot" + } + }, + "required": [ + "Entry", + "Gender", + "Race", + "SetId", + "Slot" + ] +} diff --git a/schemas/structs/meta_eqp.json b/schemas/structs/meta_eqp.json new file mode 100644 index 00000000..c829d7a7 --- /dev/null +++ b/schemas/structs/meta_eqp.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "integer" + }, + "SetId": { + "$ref": "meta_enums.json#U16" + }, + "Slot": { + "$ref": "meta_enums.json#EquipSlot" + } + }, + "required": [ + "Entry", + "SetId", + "Slot" + ] +} diff --git a/schemas/structs/meta_est.json b/schemas/structs/meta_est.json new file mode 100644 index 00000000..22bce12b --- /dev/null +++ b/schemas/structs/meta_est.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "$ref": "meta_enums.json#U16" + }, + "Gender": { + "$ref": "meta_enums.json#Gender" + }, + "Race": { + "$ref": "meta_enums.json#ModelRace" + }, + "SetId": { + "$ref": "meta_enums.json#U16" + }, + "Slot": { + "enum": [ "Hair", "Face", "Body", "Head" ] + } + }, + "required": [ + "Entry", + "Gender", + "Race", + "SetId", + "Slot" + ] +} diff --git a/schemas/structs/meta_geqp.json b/schemas/structs/meta_geqp.json new file mode 100644 index 00000000..3d4908f9 --- /dev/null +++ b/schemas/structs/meta_geqp.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Condition": { + "$ref": "meta_enums.json#U16" + }, + "Type": { + "enum": [ "DoNotHideEarrings", "DoNotHideNecklace", "DoNotHideBracelets", "DoNotHideRingR", "DoNotHideRingL", "DoNotHideHrothgarHats", "DoNotHideVieraHats" ] + } + }, + "required": [ "Type" ], + "oneOf": [ + { + "properties": { + "Type": { + "const": [ "DoNotHideHrothgarHats", "DoNotHideVieraHats" ] + }, + "Condition": { + "const": 0 + } + } + }, + { + "properties": { + "Type": { + "const": [ "DoNotHideHrothgarHats", "DoNotHideVieraHats" ] + } + } + }, + { + "properties": { + "Type": { + "const": [ "DoNotHideEarrings", "DoNotHideNecklace", "DoNotHideBracelets", "DoNotHideRingR", "DoNotHideRingL" ] + }, + "Condition": {} + } + } + ] +} diff --git a/schemas/structs/meta_gmp.json b/schemas/structs/meta_gmp.json new file mode 100644 index 00000000..bf1fb1df --- /dev/null +++ b/schemas/structs/meta_gmp.json @@ -0,0 +1,59 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "object", + "properties": { + "Enabled": { + "type": "boolean" + }, + "Animated": { + "type": "boolean" + }, + "RotationA": { + "type": "integer", + "minimum": 0, + "maximum": 1023 + }, + "RotationB": { + "type": "integer", + "minimum": 0, + "maximum": 1023 + }, + "RotationC": { + "type": "integer", + "minimum": 0, + "maximum": 1023 + }, + "UnknownA": { + "type": "integer", + "minimum": 0, + "maximum": 15 + }, + "UnknownB": { + "type": "integer", + "minimum": 0, + "maximum": 15 + } + }, + "required": [ + "Enabled", + "Animated", + "RotationA", + "RotationB", + "RotationC", + "UnknownA", + "UnknownB" + ], + "additionalProperties": false + }, + "SetId": { + "$ref": "meta_enums.json#U16" + } + }, + "required": [ + "Entry", + "SetId" + ] +} diff --git a/schemas/structs/meta_imc.json b/schemas/structs/meta_imc.json new file mode 100644 index 00000000..aa9a4fca --- /dev/null +++ b/schemas/structs/meta_imc.json @@ -0,0 +1,87 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "$ref": "#ImcEntry" + } + }, + "required": [ + "Entry" + ], + "allOf": [ + { + "$ref": "#ImcIdentifier" + } + ], + "$defs": { + "ImcIdentifier": { + "type": "object", + "properties": { + "PrimaryId": { + "$ref": "meta_enums.json#U16" + }, + "SecondaryId": { + "$ref": "meta_enums.json#U16" + }, + "Variant": { + "$ref": "meta_enums.json#U8" + }, + "ObjectType": { + "$ref": "meta_enums.json#ObjectType" + }, + "EquipSlot": { + "$ref": "meta_enums.json#EquipSlot" + }, + "BodySlot": { + "$ref": "meta_enums.json#BodySlot" + } + }, + "$anchor": "ImcIdentifier", + "required": [ + "PrimaryId", + "SecondaryId", + "Variant", + "ObjectType", + "EquipSlot", + "BodySlot" + ] + }, + "ImcEntry": { + "type": "object", + "properties": { + "MaterialId": { + "$ref": "meta_enums.json#U8" + }, + "DecalId": { + "$ref": "meta_enums.json#U8" + }, + "VfxId": { + "$ref": "meta_enums.json#U8" + }, + "MaterialAnimationId": { + "$ref": "meta_enums.json#U8" + }, + "AttributeMask": { + "type": "integer", + "minimum": 0, + "maximum": 1023 + }, + "SoundId": { + "type": "integer", + "minimum": 0, + "maximum": 63 + } + }, + "$anchor": "ImcEntry", + "required": [ + "MaterialId", + "DecalId", + "VfxId", + "MaterialAnimationId", + "AttributeMask", + "SoundId" + ] + } + } +} diff --git a/schemas/structs/meta_rsp.json b/schemas/structs/meta_rsp.json new file mode 100644 index 00000000..3354281b --- /dev/null +++ b/schemas/structs/meta_rsp.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "number" + }, + "SubRace": { + "$ref": "meta_enums.json#SubRace" + }, + "Attribute": { + "enum": [ "MaleMinSize", "MaleMaxSize", "MaleMinTail", "MaleMaxTail", "FemaleMinSize", "FemaleMaxSize", "FemaleMinTail", "FemaleMaxTail", "BustMinX", "BustMinY", "BustMinZ", "BustMaxX", "BustMaxY", "BustMaxZ" ] + } + }, + "required": [ + "Entry", + "SubRace", + "Attribute" + ] +} diff --git a/schemas/structs/option.json b/schemas/structs/option.json new file mode 100644 index 00000000..c45ccfdb --- /dev/null +++ b/schemas/structs/option.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Name": { + "description": "Name of the option.", + "type": "string", + "minLength": 1 + }, + "Description": { + "description": "Description of the option.", + "type": [ "string", "null" ] + }, + "Priority": { + "description": "Priority of the option. If several enabled options within the group define conflicting files or manipulations, the highest priority wins.", + "type": "integer" + }, + "Image": { + "description": "Unused by Penumbra.", + "type": [ "string", "null" ] + } + }, + "required": [ "Name" ] +} From b62563d72131c2119370b3d25677457291c15b96 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 17 Jan 2025 20:06:21 +0100 Subject: [PATCH 1063/1381] Remove $id from shpk_devkit schema --- schemas/shpk_devkit.json | 1 - 1 file changed, 1 deletion(-) diff --git a/schemas/shpk_devkit.json b/schemas/shpk_devkit.json index cd18ab81..f03fbb05 100644 --- a/schemas/shpk_devkit.json +++ b/schemas/shpk_devkit.json @@ -1,6 +1,5 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://raw.githubusercontent.com/xivdev/Penumbra/master/schemas/shpk_devkit.json", "type": "object", "properties": { "ShaderKeys": { From 4f0428832cadfe61c4c49dd7dcbfdeacde5332bd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 20 Jan 2025 15:13:09 +0100 Subject: [PATCH 1064/1381] Fix solution file for schemas. --- Penumbra.sln | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra.sln b/Penumbra.sln index c0b38118..e864fbee 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -26,10 +26,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Penumbra.CrashHandler", "Pe EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Schemas", "Schemas", "{BFEA7504-1210-4F79-A7FE-BF03B6567E33}" ProjectSection(SolutionItems) = preProject - schemas\files\default_mod.json = schemas\files\default_mod.json - schemas\files\group.json = schemas\files\group.json - schemas\files\local_mod_data-v3.json = schemas\files\local_mod_data-v3.json - schemas\files\mod_meta-v3.json = schemas\files\mod_meta-v3.json + schemas\default_mod.json = schemas\default_mod.json + schemas\group.json = schemas\group.json + schemas\local_mod_data-v3.json = schemas\local_mod_data-v3.json + schemas\mod_meta-v3.json = schemas\mod_meta-v3.json EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "structs", "structs", "{B03F276A-0572-4F62-AF86-EF62F6B80463}" From 7b517390b6c619a27de6698ada6627b80ae21c75 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 20 Jan 2025 15:30:03 +0100 Subject: [PATCH 1065/1381] Fix temporary settings causing collection saves. --- Penumbra/Collections/Manager/CollectionEditor.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 437d4e0b..f4902fda 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -194,7 +194,8 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void InvokeChange(ModCollection changedCollection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx) { - saveService.QueueSave(new ModCollectionSave(modStorage, changedCollection)); + if (type is not ModSettingChange.TemporarySetting) + saveService.QueueSave(new ModCollectionSave(modStorage, changedCollection)); communicator.ModSettingChanged.Invoke(changedCollection, type, mod, oldValue, groupIdx, false); if (type is not ModSettingChange.TemporarySetting) RecurseInheritors(changedCollection, type, mod, oldValue, groupIdx); From 8779f4b6893b6d472c71fb63d0f31ef947140424 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 20 Jan 2025 15:36:05 +0100 Subject: [PATCH 1066/1381] Add new cutscene ENPC tracking hooks. --- Penumbra.GameData | 2 +- Penumbra/Interop/GameState.cs | 3 +- Penumbra/Interop/Hooks/HookSettings.cs | 2 + .../Objects/ConstructCutsceneCharacter.cs | 70 +++++++++++++++++++ Penumbra/Interop/Hooks/Objects/EnableDraw.cs | 2 +- .../Interop/Hooks/Objects/SetupPlayerNpc.cs | 55 +++++++++++++++ .../Interop/PathResolving/CutsceneService.cs | 29 +++++--- 7 files changed, 152 insertions(+), 11 deletions(-) create mode 100644 Penumbra/Interop/Hooks/Objects/ConstructCutsceneCharacter.cs create mode 100644 Penumbra/Interop/Hooks/Objects/SetupPlayerNpc.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index c5250722..5bac66e5 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c525072299d5febd2bb638ab229060b0073ba6a6 +Subproject commit 5bac66e5ad73e57919aff7f8b046606b75e191a2 diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs index f80ef696..497be508 100644 --- a/Penumbra/Interop/GameState.cs +++ b/Penumbra/Interop/GameState.cs @@ -11,7 +11,8 @@ public class GameState : IService { #region Last Game Object - private readonly ThreadLocal> _lastGameObject = new(() => new Queue()); + private readonly ThreadLocal> _lastGameObject = new(() => new Queue()); + public readonly ThreadLocal CharacterAssociated = new(() => false); public nint LastGameObject => _lastGameObject.IsValueCreated && _lastGameObject.Value!.Count > 0 ? _lastGameObject.Value.Peek() : nint.Zero; diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index b95e5789..5a856764 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -76,6 +76,8 @@ public class HookOverrides public bool CreateCharacterBase; public bool EnableDraw; public bool WeaponReload; + public bool SetupPlayerNpc; + public bool ConstructCutsceneCharacter; } public struct PostProcessingHooks diff --git a/Penumbra/Interop/Hooks/Objects/ConstructCutsceneCharacter.cs b/Penumbra/Interop/Hooks/Objects/ConstructCutsceneCharacter.cs new file mode 100644 index 00000000..5fa3de32 --- /dev/null +++ b/Penumbra/Interop/Hooks/Objects/ConstructCutsceneCharacter.cs @@ -0,0 +1,70 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.GameData; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; + +namespace Penumbra.Interop.Hooks.Objects; + +public sealed unsafe class ConstructCutsceneCharacter : EventWrapperPtr, IHookService +{ + private readonly GameState _gameState; + private readonly ObjectManager _objects; + + public enum Priority + { + /// + CutsceneService = 0, + } + + public ConstructCutsceneCharacter(GameState gameState, HookManager hooks, ObjectManager objects) + : base("ConstructCutsceneCharacter") + { + _gameState = gameState; + _objects = objects; + _task = hooks.CreateHook(Name, Sigs.ConstructCutsceneCharacter, Detour, !HookOverrides.Instance.Objects.ConstructCutsceneCharacter); + } + + private readonly Task> _task; + + public delegate int Delegate(SetupPlayerNpc.SchedulerStruct* scheduler); + + public int Detour(SetupPlayerNpc.SchedulerStruct* scheduler) + { + // This is the function that actually creates the new game object + // and fills it into the object table at a free index etc. + var ret = _task.Result.Original(scheduler); + // Check for the copy state from SetupPlayerNpc. + if (_gameState.CharacterAssociated.Value) + { + // If the newly created character exists, invoke the event. + var character = _objects[ret + (int)ScreenActor.CutsceneStart].AsCharacter; + if (character != null) + { + Invoke(character); + Penumbra.Log.Verbose( + $"[{Name}] Created indirect copy of player character at 0x{(nint)character}, index {character->ObjectIndex}."); + } + _gameState.CharacterAssociated.Value = false; + } + + return ret; + } + + public IntPtr Address + => _task.Result.Address; + + public void Enable() + => _task.Result.Enable(); + + public void Disable() + => _task.Result.Disable(); + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; +} diff --git a/Penumbra/Interop/Hooks/Objects/EnableDraw.cs b/Penumbra/Interop/Hooks/Objects/EnableDraw.cs index 68bb28af..979cb87c 100644 --- a/Penumbra/Interop/Hooks/Objects/EnableDraw.cs +++ b/Penumbra/Interop/Hooks/Objects/EnableDraw.cs @@ -26,7 +26,7 @@ public sealed unsafe class EnableDraw : IHookService private void Detour(GameObject* gameObject) { _state.QueueGameObject(gameObject); - Penumbra.Log.Excessive($"[Enable Draw] Invoked on 0x{(nint)gameObject:X}."); + Penumbra.Log.Excessive($"[Enable Draw] Invoked on 0x{(nint)gameObject:X} at {gameObject->ObjectIndex}."); _task.Result.Original.Invoke(gameObject); _state.DequeueGameObject(); } diff --git a/Penumbra/Interop/Hooks/Objects/SetupPlayerNpc.cs b/Penumbra/Interop/Hooks/Objects/SetupPlayerNpc.cs new file mode 100644 index 00000000..8f1226c3 --- /dev/null +++ b/Penumbra/Interop/Hooks/Objects/SetupPlayerNpc.cs @@ -0,0 +1,55 @@ +using FFXIVClientStructs.FFXIV.Client.Game.Character; +using OtterGui.Services; +using Penumbra.GameData; + +namespace Penumbra.Interop.Hooks.Objects; + +public sealed unsafe class SetupPlayerNpc : FastHook +{ + private readonly GameState _gameState; + + public SetupPlayerNpc(GameState gameState, HookManager hooks) + { + _gameState = gameState; + Task = hooks.CreateHook("SetupPlayerNPC", Sigs.SetupPlayerNpc, Detour, + !HookOverrides.Instance.Objects.SetupPlayerNpc); + } + + public delegate SchedulerStruct* Delegate(byte* npcType, nint unk, NpcSetupData* setupData); + + public SchedulerStruct* Detour(byte* npcType, nint unk, NpcSetupData* setupData) + { + // This function actually seems to generate all NPC. + + // If an ENPC is being created, check the creation parameters. + // If CopyPlayerCustomize is true, the event NPC gets a timeline that copies its customize and glasses from the local player. + // Keep track of this, so we can associate the actor to be created for this with the player character, see ConstructCutsceneCharacter. + if (setupData->CopyPlayerCustomize && npcType != null && *npcType is 8) + _gameState.CharacterAssociated.Value = true; + + var ret = Task.Result.Original.Invoke(npcType, unk, setupData); + Penumbra.Log.Excessive( + $"[Setup Player NPC] Invoked for type {*npcType} with 0x{unk:X} and Copy Player Customize: {setupData->CopyPlayerCustomize}."); + return ret; + } + + [StructLayout(LayoutKind.Explicit)] + public struct NpcSetupData + { + [FieldOffset(0x0B)] + private byte _copyPlayerCustomize; + + public bool CopyPlayerCustomize + { + get => _copyPlayerCustomize != 0; + set => _copyPlayerCustomize = value ? (byte)1 : (byte)0; + } + } + + [StructLayout(LayoutKind.Explicit)] + public struct SchedulerStruct + { + public static Character* GetCharacter(SchedulerStruct* s) + => ((delegate* unmanaged**)s)[0][19](s); + } +} diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 8e32dd76..6be19c46 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -15,10 +15,11 @@ public sealed class CutsceneService : IRequiredService, IDisposable public const int CutsceneEndIdx = (int)ScreenActor.CutsceneEnd; public const int CutsceneSlots = CutsceneEndIdx - CutsceneStartIdx; - private readonly ObjectManager _objects; - private readonly CopyCharacter _copyCharacter; - private readonly CharacterDestructor _characterDestructor; - private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); + private readonly ObjectManager _objects; + private readonly CopyCharacter _copyCharacter; + private readonly CharacterDestructor _characterDestructor; + private readonly ConstructCutsceneCharacter _constructCutsceneCharacter; + private readonly short[] _copiedCharacters = Enumerable.Repeat((short)-1, CutsceneSlots).ToArray(); public IEnumerable> Actors => Enumerable.Range(CutsceneStartIdx, CutsceneSlots) @@ -26,13 +27,15 @@ public sealed class CutsceneService : IRequiredService, IDisposable .Select(i => KeyValuePair.Create(i, this[i] ?? _objects.GetDalamudObject(i)!)); public unsafe CutsceneService(ObjectManager objects, CopyCharacter copyCharacter, CharacterDestructor characterDestructor, - IClientState clientState) + ConstructCutsceneCharacter constructCutsceneCharacter, IClientState clientState) { - _objects = objects; - _copyCharacter = copyCharacter; - _characterDestructor = characterDestructor; + _objects = objects; + _copyCharacter = copyCharacter; + _characterDestructor = characterDestructor; + _constructCutsceneCharacter = constructCutsceneCharacter; _copyCharacter.Subscribe(OnCharacterCopy, CopyCharacter.Priority.CutsceneService); _characterDestructor.Subscribe(OnCharacterDestructor, CharacterDestructor.Priority.CutsceneService); + _constructCutsceneCharacter.Subscribe(OnSetupPlayerNpc, ConstructCutsceneCharacter.Priority.CutsceneService); if (clientState.IsGPosing) RecoverGPoseActors(); } @@ -87,6 +90,7 @@ public sealed class CutsceneService : IRequiredService, IDisposable { _copyCharacter.Unsubscribe(OnCharacterCopy); _characterDestructor.Unsubscribe(OnCharacterDestructor); + _constructCutsceneCharacter.Unsubscribe(OnSetupPlayerNpc); } private unsafe void OnCharacterDestructor(Character* character) @@ -124,6 +128,15 @@ public sealed class CutsceneService : IRequiredService, IDisposable _copiedCharacters[idx] = (short)(source != null ? source->GameObject.ObjectIndex : -1); } + private unsafe void OnSetupPlayerNpc(Character* npc) + { + if (npc == null || npc->ObjectIndex is < CutsceneStartIdx or >= CutsceneEndIdx) + return; + + var idx = npc->GameObject.ObjectIndex - CutsceneStartIdx; + _copiedCharacters[idx] = 0; + } + /// Try to recover GPose actors on reloads into a running game. /// This is not 100% accurate due to world IDs, minions etc., but will be mostly sane. private void RecoverGPoseActors() From 0c8571fba92058b8281efcea0cdb2583104bf7ce Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 20 Jan 2025 17:14:13 +0100 Subject: [PATCH 1067/1381] Reduce and pad IMC allocations and log allocations. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/ImcCache.cs | 1 - Penumbra/Collections/ModCollectionIdentity.cs | 6 +++--- Penumbra/Interop/GameState.cs | 4 ++-- Penumbra/Meta/Files/ImcFile.cs | 15 ++++++++++----- Penumbra/Meta/Files/MetaBaseFile.cs | 15 +++++++++++++-- 6 files changed, 29 insertions(+), 14 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 5bac66e5..ebeea67c 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 5bac66e5ad73e57919aff7f8b046606b75e191a2 +Subproject commit ebeea67c17f6bf4ce7e635041b2138e835d31262 diff --git a/Penumbra/Collections/Cache/ImcCache.cs b/Penumbra/Collections/Cache/ImcCache.cs index 0f610d90..461ffccc 100644 --- a/Penumbra/Collections/Cache/ImcCache.cs +++ b/Penumbra/Collections/Cache/ImcCache.cs @@ -51,7 +51,6 @@ public sealed class ImcCache(MetaFileManager manager, ModCollection collection) if (!_imcFiles.TryGetValue(path, out var pair)) pair = (new ImcFile(Manager, identifier), []); - if (!Apply(pair.Item1, identifier, entry)) return; diff --git a/Penumbra/Collections/ModCollectionIdentity.cs b/Penumbra/Collections/ModCollectionIdentity.cs index c7f60005..bd2d47c4 100644 --- a/Penumbra/Collections/ModCollectionIdentity.cs +++ b/Penumbra/Collections/ModCollectionIdentity.cs @@ -10,9 +10,9 @@ public struct ModCollectionIdentity(Guid id, LocalCollectionId localId) public static readonly ModCollectionIdentity Empty = new(Guid.Empty, LocalCollectionId.Zero, EmptyCollectionName, 0); - public string Name { get; set; } - public Guid Id { get; } = id; - public LocalCollectionId LocalId { get; } = localId; + public string Name { get; set; } = string.Empty; + public Guid Id { get; } = id; + public LocalCollectionId LocalId { get; } = localId; /// The index of the collection is set and kept up-to-date by the CollectionManager. public int Index { get; internal set; } diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs index 497be508..95cef468 100644 --- a/Penumbra/Interop/GameState.cs +++ b/Penumbra/Interop/GameState.cs @@ -11,8 +11,8 @@ public class GameState : IService { #region Last Game Object - private readonly ThreadLocal> _lastGameObject = new(() => new Queue()); - public readonly ThreadLocal CharacterAssociated = new(() => false); + private readonly ThreadLocal> _lastGameObject = new(() => new Queue()); + public readonly ThreadLocal CharacterAssociated = new(() => false); public nint LastGameObject => _lastGameObject.IsValueCreated && _lastGameObject.Value!.Count > 0 ? _lastGameObject.Value.Peek() : nint.Zero; diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 01ef3f16..de022f4c 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -1,3 +1,4 @@ +using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; @@ -192,22 +193,26 @@ public unsafe class ImcFile : MetaBaseFile public void Replace(ResourceHandle* resource) { var (data, length) = resource->GetData(); - if (length == ActualLength) + var actualLength = ActualLength; + if (length >= actualLength) { - MemoryUtility.MemCpyUnchecked((byte*)data, Data, ActualLength); + MemoryUtility.MemCpyUnchecked((byte*)data, Data, actualLength); + MemoryUtility.MemSet((byte*)data + actualLength, 0, length - actualLength); return; } - var newData = Manager.XivAllocator.Allocate(ActualLength, 8); + var paddedLength = actualLength.PadToMultiple(128); + var newData = Manager.XivAllocator.Allocate(paddedLength, 8); if (newData == null) { Penumbra.Log.Error($"Could not replace loaded IMC data at 0x{(ulong)resource:X}, allocation failed."); return; } - MemoryUtility.MemCpyUnchecked(newData, Data, ActualLength); + MemoryUtility.MemCpyUnchecked(newData, Data, actualLength); + MemoryUtility.MemSet((byte*)data + actualLength, 0, paddedLength - actualLength); Manager.XivAllocator.Release((void*)data, length); - resource->SetData((nint)newData, ActualLength); + resource->SetData((nint)newData, paddedLength); } } diff --git a/Penumbra/Meta/Files/MetaBaseFile.cs b/Penumbra/Meta/Files/MetaBaseFile.cs index 5bc36068..0cb34ab3 100644 --- a/Penumbra/Meta/Files/MetaBaseFile.cs +++ b/Penumbra/Meta/Files/MetaBaseFile.cs @@ -28,11 +28,16 @@ public unsafe interface IFileAllocator public sealed class MarshalAllocator : IFileAllocator { public unsafe T* Allocate(int length, int alignment = 1) where T : unmanaged - => (T*)Marshal.AllocHGlobal(length * sizeof(T)); + { + var ret = (T*)Marshal.AllocHGlobal(length * sizeof(T)); + Penumbra.Log.Verbose($"Allocating {length * sizeof(T)} bytes via Marshal Allocator to 0x{(nint)ret:X}."); + return ret; + } public unsafe void Release(ref T* pointer, int length) where T : unmanaged { Marshal.FreeHGlobal((nint)pointer); + Penumbra.Log.Verbose($"Freeing {length * sizeof(T)} bytes from 0x{(nint)pointer:X} via Marshal Allocator."); pointer = null; } } @@ -53,11 +58,17 @@ public sealed unsafe class XivFileAllocator : IFileAllocator, IService => ((delegate* unmanaged)_getFileSpaceAddress)(); public T* Allocate(int length, int alignment = 1) where T : unmanaged - => (T*)GetFileSpace()->Malloc((ulong)(length * sizeof(T)), (ulong)alignment); + { + var ret = (T*)GetFileSpace()->Malloc((ulong)(length * sizeof(T)), (ulong)alignment); + Penumbra.Log.Verbose($"Allocating {length * sizeof(T)} bytes via FFXIV File Allocator to 0x{(nint)ret:X}."); + return ret; + } public void Release(ref T* pointer, int length) where T : unmanaged { + IMemorySpace.Free(pointer, (ulong)(length * sizeof(T))); + Penumbra.Log.Verbose($"Freeing {length * sizeof(T)} bytes from 0x{(nint)pointer:X} via FFXIV File Allocator."); pointer = null; } } From 9ca0145a7f59e002b805a1c6060e05df67d7a7ac Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 20 Jan 2025 16:48:19 +0000 Subject: [PATCH 1068/1381] [CI] Updating repo.json for testing_1.3.3.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 2e3dd8bc..7e37f77c 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.5", + "TestingAssemblyVersion": "1.3.3.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 39c73af2382228a0b5f867baf5be44979136deee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 20 Jan 2025 20:33:28 +0100 Subject: [PATCH 1069/1381] Fix stupid. --- Penumbra/Meta/Files/ImcFile.cs | 14 ++++++++------ Penumbra/Meta/Files/MetaBaseFile.cs | 18 ++++++++++++++++++ Penumbra/Meta/MetaFileManager.cs | 26 ++++++++++++++------------ 3 files changed, 40 insertions(+), 18 deletions(-) diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index de022f4c..c6e4ec94 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -197,22 +197,24 @@ public unsafe class ImcFile : MetaBaseFile if (length >= actualLength) { MemoryUtility.MemCpyUnchecked((byte*)data, Data, actualLength); - MemoryUtility.MemSet((byte*)data + actualLength, 0, length - actualLength); + if (length > actualLength) + MemoryUtility.MemSet((byte*)(data + actualLength), 0, length - actualLength); return; } var paddedLength = actualLength.PadToMultiple(128); - var newData = Manager.XivAllocator.Allocate(paddedLength, 8); + var newData = Manager.XivFileAllocator.Allocate(paddedLength, 8); if (newData == null) { Penumbra.Log.Error($"Could not replace loaded IMC data at 0x{(ulong)resource:X}, allocation failed."); return; } - + MemoryUtility.MemCpyUnchecked(newData, Data, actualLength); - MemoryUtility.MemSet((byte*)data + actualLength, 0, paddedLength - actualLength); - - Manager.XivAllocator.Release((void*)data, length); + if (paddedLength > actualLength) + MemoryUtility.MemSet(newData + actualLength, 0, paddedLength - actualLength); + + Manager.XivFileAllocator.Release((void*)data, length); resource->SetData((nint)newData, paddedLength); } } diff --git a/Penumbra/Meta/Files/MetaBaseFile.cs b/Penumbra/Meta/Files/MetaBaseFile.cs index 0cb34ab3..d04e1bdf 100644 --- a/Penumbra/Meta/Files/MetaBaseFile.cs +++ b/Penumbra/Meta/Files/MetaBaseFile.cs @@ -73,6 +73,24 @@ public sealed unsafe class XivFileAllocator : IFileAllocator, IService } } +public sealed unsafe class XivDefaultAllocator : IFileAllocator, IService +{ + public T* Allocate(int length, int alignment = 1) where T : unmanaged + { + var ret = (T*)IMemorySpace.GetDefaultSpace()->Malloc((ulong)(length * sizeof(T)), (ulong)alignment); + Penumbra.Log.Verbose($"Allocating {length * sizeof(T)} bytes via FFXIV Default Allocator to 0x{(nint)ret:X}."); + return ret; + } + + public void Release(ref T* pointer, int length) where T : unmanaged + { + + IMemorySpace.Free(pointer, (ulong)(length * sizeof(T))); + Penumbra.Log.Verbose($"Freeing {length * sizeof(T)} bytes from 0x{(nint)pointer:X} via FFXIV Default Allocator."); + pointer = null; + } +} + public unsafe class MetaBaseFile(MetaFileManager manager, IFileAllocator alloc, MetaIndex idx) : IDisposable { protected readonly MetaFileManager Manager = manager; diff --git a/Penumbra/Meta/MetaFileManager.cs b/Penumbra/Meta/MetaFileManager.cs index 5250273b..6130a48f 100644 --- a/Penumbra/Meta/MetaFileManager.cs +++ b/Penumbra/Meta/MetaFileManager.cs @@ -28,24 +28,26 @@ public class MetaFileManager : IService internal readonly ImcChecker ImcChecker; internal readonly AtchManager AtchManager; internal readonly IFileAllocator MarshalAllocator = new MarshalAllocator(); - internal readonly IFileAllocator XivAllocator; + internal readonly IFileAllocator XivFileAllocator; + internal readonly IFileAllocator XivDefaultAllocator; public MetaFileManager(CharacterUtility characterUtility, ResidentResourceManager residentResources, IDataManager gameData, ActiveCollectionData activeCollections, Configuration config, ValidityChecker validityChecker, ObjectIdentification identifier, FileCompactor compactor, IGameInteropProvider interop, AtchManager atchManager) { - CharacterUtility = characterUtility; - ResidentResources = residentResources; - GameData = gameData; - ActiveCollections = activeCollections; - Config = config; - ValidityChecker = validityChecker; - Identifier = identifier; - Compactor = compactor; - AtchManager = atchManager; - ImcChecker = new ImcChecker(this); - XivAllocator = new XivFileAllocator(interop); + CharacterUtility = characterUtility; + ResidentResources = residentResources; + GameData = gameData; + ActiveCollections = activeCollections; + Config = config; + ValidityChecker = validityChecker; + Identifier = identifier; + Compactor = compactor; + AtchManager = atchManager; + ImcChecker = new ImcChecker(this); + XivFileAllocator = new XivFileAllocator(interop); + XivDefaultAllocator = new XivDefaultAllocator(); interop.InitializeFromAttributes(this); } From 737e74582bbc2a85ebbed6dfbc771adf881392fe Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 20 Jan 2025 19:36:05 +0000 Subject: [PATCH 1070/1381] [CI] Updating repo.json for testing_1.3.3.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 7e37f77c..3e258788 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.6", + "TestingAssemblyVersion": "1.3.3.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 2afd6b966e4c79c7c11bbcd9a2b2c8c074a91495 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Jan 2025 17:36:01 +0100 Subject: [PATCH 1071/1381] Add debug logging facilities. --- OtterGui | 2 +- Penumbra.String | 2 +- Penumbra/DebugConfiguration.cs | 6 ++++ Penumbra/Meta/Files/ImcFile.cs | 29 +++++++++++++++++-- .../UI/Tabs/Debug/DebugConfigurationDrawer.cs | 14 +++++++++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 1 + 6 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 Penumbra/DebugConfiguration.cs create mode 100644 Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs diff --git a/OtterGui b/OtterGui index 055f1695..3c1260c9 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 055f169572223fd1b59389549c88b4c861c94608 +Subproject commit 3c1260c9833303c2d33d12d6f77dc2b1afea3f34 diff --git a/Penumbra.String b/Penumbra.String index b9003b97..0bc2b0f6 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit b9003b97da2d1191fa203a4d66956bc54c21db2a +Subproject commit 0bc2b0f66eee1a02c9575b2bb30f27ce166f8632 diff --git a/Penumbra/DebugConfiguration.cs b/Penumbra/DebugConfiguration.cs new file mode 100644 index 00000000..76987df8 --- /dev/null +++ b/Penumbra/DebugConfiguration.cs @@ -0,0 +1,6 @@ +namespace Penumbra; + +public class DebugConfiguration +{ + public static bool WriteImcBytesToLog = false; +} diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index c6e4ec94..23339cfc 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -1,3 +1,4 @@ +using OtterGui; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -194,11 +195,28 @@ public unsafe class ImcFile : MetaBaseFile { var (data, length) = resource->GetData(); var actualLength = ActualLength; + + if (DebugConfiguration.WriteImcBytesToLog) + { + Penumbra.Log.Information($"Default IMC file -> Modified IMC File for {Path}:"); + Penumbra.Log.Information(new Span((void*)data, length).WriteHexBytes()); + Penumbra.Log.Information(new Span(Data, actualLength).WriteHexBytes()); + Penumbra.Log.Information(new Span(Data, actualLength).WriteHexByteDiff(new Span((void*)data, length))); + } + if (length >= actualLength) { MemoryUtility.MemCpyUnchecked((byte*)data, Data, actualLength); if (length > actualLength) MemoryUtility.MemSet((byte*)(data + actualLength), 0, length - actualLength); + if (DebugConfiguration.WriteImcBytesToLog) + { + Penumbra.Log.Information( + $"Copied {actualLength} bytes from local IMC file into {length} available bytes.{(length > actualLength ? $" Filled remaining {length - actualLength} bytes with 0." : string.Empty)}"); + Penumbra.Log.Information("Result IMC Resource Data:"); + Penumbra.Log.Information(new Span((void*)data, length).WriteHexBytes()); + } + return; } @@ -209,11 +227,18 @@ public unsafe class ImcFile : MetaBaseFile Penumbra.Log.Error($"Could not replace loaded IMC data at 0x{(ulong)resource:X}, allocation failed."); return; } - + MemoryUtility.MemCpyUnchecked(newData, Data, actualLength); if (paddedLength > actualLength) MemoryUtility.MemSet(newData + actualLength, 0, paddedLength - actualLength); - + if (DebugConfiguration.WriteImcBytesToLog) + { + Penumbra.Log.Information( + $"Allocated {paddedLength} bytes for IMC file, copied {actualLength} bytes from local IMC file. {(length > actualLength ? $" Filled remaining {length - actualLength} bytes with 0." : string.Empty)}"); + Penumbra.Log.Information("Result IMC Resource Data:"); + Penumbra.Log.Information(new Span(newData, paddedLength).WriteHexBytes()); + } + Manager.XivFileAllocator.Release((void*)data, length); resource->SetData((nint)newData, paddedLength); } diff --git a/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs b/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs new file mode 100644 index 00000000..34aafbea --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs @@ -0,0 +1,14 @@ +using OtterGui.Text; + +namespace Penumbra.UI.Tabs.Debug; + +public static class DebugConfigurationDrawer +{ + public static void Draw() + { + if (!ImUtf8.CollapsingHeaderId("Debug Logging Options")) + return; + + ImUtf8.Checkbox("Log IMC File Replacements"u8, ref DebugConfiguration.WriteImcBytesToLog); + } +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 77eeb3d7..ad4824c3 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -181,6 +181,7 @@ public class DebugTab : Window, ITab, IUiService DrawDebugTabGeneral(); _crashHandlerPanel.Draw(); + DebugConfigurationDrawer.Draw(); _diagnostics.DrawDiagnostics(); DrawPerformanceTab(); DrawPathResolverDebug(); From dcc435477738d79a3c4301bf862e89ffef705bb7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Jan 2025 17:36:13 +0100 Subject: [PATCH 1072/1381] Fix clipping height in changed items tab. --- Penumbra/UI/Tabs/ChangedItemsTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index 256b0d79..5bac7d35 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -36,7 +36,7 @@ public class ChangedItemsTab( if (!child) return; - var height = ImGui.GetFrameHeight() + 2 * ImGui.GetStyle().CellPadding.Y; + var height = ImGui.GetFrameHeightWithSpacing() + 2 * ImGui.GetStyle().CellPadding.Y; var skips = ImGuiClip.GetNecessarySkips(height); using var list = ImRaii.Table("##changedItems", 3, ImGuiTableFlags.RowBg, -Vector2.One); if (!list) From dcab443b2fb221104b471c4358bdf8bc8da8bc54 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 22 Jan 2025 16:38:33 +0000 Subject: [PATCH 1073/1381] [CI] Updating repo.json for testing_1.3.3.8 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 3e258788..e0cf2a70 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.7", + "TestingAssemblyVersion": "1.3.3.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.8/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 40168d7daf418c5743558bb2906ae52456e9d7e7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Jan 2025 23:14:09 +0100 Subject: [PATCH 1074/1381] Fix issue with IPC adding mods before character utility is ready in rare cases. --- Penumbra/Api/IpcProviders.cs | 20 +++++++++++++--- .../Cache/CollectionCacheManager.cs | 6 ++--- .../Communication/CharacterUtilityFinished.cs | 23 +++++++++++++++++++ Penumbra/Interop/Services/CharacterUtility.cs | 21 +++++++++-------- Penumbra/Mods/Editor/ModMetaEditor.cs | 5 ++++ 5 files changed, 60 insertions(+), 15 deletions(-) create mode 100644 Penumbra/Communication/CharacterUtilityFinished.cs diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index f6948832..fc97290f 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -2,6 +2,8 @@ using Dalamud.Plugin; using OtterGui.Services; using Penumbra.Api.Api; using Penumbra.Api.Helpers; +using Penumbra.Communication; +using CharacterUtility = Penumbra.Interop.Services.CharacterUtility; namespace Penumbra.Api; @@ -9,11 +11,13 @@ public sealed class IpcProviders : IDisposable, IApiService { private readonly List _providers; - private readonly EventProvider _disposedProvider; - private readonly EventProvider _initializedProvider; + private readonly EventProvider _disposedProvider; + private readonly EventProvider _initializedProvider; + private readonly CharacterUtility _characterUtility; - public IpcProviders(IDalamudPluginInterface pi, IPenumbraApi api) + public IpcProviders(IDalamudPluginInterface pi, IPenumbraApi api, CharacterUtility characterUtility) { + _characterUtility = characterUtility; _disposedProvider = IpcSubscribers.Disposed.Provider(pi); _initializedProvider = IpcSubscribers.Initialized.Provider(pi); _providers = @@ -115,11 +119,21 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.OpenMainWindow.Provider(pi, api.Ui), IpcSubscribers.CloseMainWindow.Provider(pi, api.Ui), ]; + if (_characterUtility.Ready) + _initializedProvider.Invoke(); + else + _characterUtility.LoadingFinished.Subscribe(OnCharacterUtilityReady, CharacterUtilityFinished.Priority.IpcProvider); + } + + private void OnCharacterUtilityReady() + { _initializedProvider.Invoke(); + _characterUtility.LoadingFinished.Unsubscribe(OnCharacterUtilityReady); } public void Dispose() { + _characterUtility.LoadingFinished.Unsubscribe(OnCharacterUtilityReady); foreach (var provider in _providers) provider.Dispose(); _providers.Clear(); diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index 27b969c2..c46759c7 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -71,7 +71,7 @@ public class CollectionCacheManager : IDisposable, IService _communicator.ModDiscoveryFinished.Subscribe(OnModDiscoveryFinished, ModDiscoveryFinished.Priority.CollectionCacheManager); if (!MetaFileManager.CharacterUtility.Ready) - MetaFileManager.CharacterUtility.LoadingFinished += IncrementCounters; + MetaFileManager.CharacterUtility.LoadingFinished.Subscribe(IncrementCounters, CharacterUtilityFinished.Priority.CollectionCacheManager); } public void Dispose() @@ -83,7 +83,7 @@ public class CollectionCacheManager : IDisposable, IService _communicator.ModOptionChanged.Unsubscribe(OnModOptionChange); _communicator.ModSettingChanged.Unsubscribe(OnModSettingChange); _communicator.CollectionInheritanceChanged.Unsubscribe(OnCollectionInheritanceChange); - MetaFileManager.CharacterUtility.LoadingFinished -= IncrementCounters; + MetaFileManager.CharacterUtility.LoadingFinished.Unsubscribe(IncrementCounters); foreach (var collection in _storage) { @@ -298,7 +298,7 @@ public class CollectionCacheManager : IDisposable, IService { foreach (var collection in _storage.Where(c => c.HasCache)) collection.Counters.IncrementChange(); - MetaFileManager.CharacterUtility.LoadingFinished -= IncrementCounters; + MetaFileManager.CharacterUtility.LoadingFinished.Unsubscribe(IncrementCounters); } private void OnModSettingChange(ModCollection collection, ModSettingChange type, Mod? mod, Setting oldValue, int groupIdx, bool _) diff --git a/Penumbra/Communication/CharacterUtilityFinished.cs b/Penumbra/Communication/CharacterUtilityFinished.cs new file mode 100644 index 00000000..fbeeb8a7 --- /dev/null +++ b/Penumbra/Communication/CharacterUtilityFinished.cs @@ -0,0 +1,23 @@ +using OtterGui.Classes; +using Penumbra.Api; +using Penumbra.Interop.Services; + +namespace Penumbra.Communication; + +/// +/// Triggered when the Character Utility becomes ready. +/// +public sealed class CharacterUtilityFinished() : EventWrapper(nameof(CharacterUtilityFinished)) +{ + public enum Priority + { + /// + OnFinishedLoading = int.MaxValue, + + /// + IpcProvider = int.MinValue, + + /// + CollectionCacheManager = 0, + } +} diff --git a/Penumbra/Interop/Services/CharacterUtility.cs b/Penumbra/Interop/Services/CharacterUtility.cs index 1641e42d..0add9d46 100644 --- a/Penumbra/Interop/Services/CharacterUtility.cs +++ b/Penumbra/Interop/Services/CharacterUtility.cs @@ -1,6 +1,7 @@ using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using OtterGui.Services; +using Penumbra.Communication; using Penumbra.GameData; using Penumbra.Interop.Structs; @@ -26,14 +27,16 @@ public unsafe class CharacterUtility : IDisposable, IRequiredService public CharacterUtilityData* Address => *_characterUtilityAddress; - public bool Ready { get; private set; } - public event Action LoadingFinished; - public nint DefaultHumanPbdResource { get; private set; } - public nint DefaultTransparentResource { get; private set; } - public nint DefaultDecalResource { get; private set; } - public nint DefaultSkinShpkResource { get; private set; } - public nint DefaultCharacterStockingsShpkResource { get; private set; } - public nint DefaultCharacterLegacyShpkResource { get; private set; } + public bool Ready { get; private set; } + + public readonly CharacterUtilityFinished LoadingFinished = new(); + + public nint DefaultHumanPbdResource { get; private set; } + public nint DefaultTransparentResource { get; private set; } + public nint DefaultDecalResource { get; private set; } + public nint DefaultSkinShpkResource { get; private set; } + public nint DefaultCharacterStockingsShpkResource { get; private set; } + public nint DefaultCharacterLegacyShpkResource { get; private set; } /// /// The relevant indices depend on which meta manipulations we allow for. @@ -61,7 +64,7 @@ public unsafe class CharacterUtility : IDisposable, IRequiredService .Select(idx => new MetaList(new InternalIndex(idx))) .ToArray(); _framework = framework; - LoadingFinished += () => Penumbra.Log.Debug("Loading of CharacterUtility finished."); + LoadingFinished.Subscribe(() => Penumbra.Log.Debug("Loading of CharacterUtility finished."), CharacterUtilityFinished.Priority.OnFinishedLoading); LoadDefaultResources(null!); if (!Ready) _framework.Update += LoadDefaultResources; diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index c06af9c7..c5c8fb8b 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -70,6 +70,11 @@ public class ModMetaEditor( public static bool DeleteDefaultValues(MetaFileManager metaFileManager, MetaDictionary dict) { + if (!metaFileManager.CharacterUtility.Ready) + { + Penumbra.Log.Warning("Trying to delete default meta values before CharacterUtility was ready, skipped."); + return false; + } var clone = dict.Clone(); dict.ClearForDefault(); From 55ce63383255b541d3644587a10db9c765b519b1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 Jan 2025 18:11:35 +0100 Subject: [PATCH 1075/1381] Try forcing IMC files to load synchronously for now. --- Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs | 8 ++++---- Penumbra/Interop/Processing/ImcFilePostProcessor.cs | 1 - 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index ad9c41e6..a74a3712 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -176,7 +176,7 @@ public unsafe class ResourceLoader : IDisposable, IService gamePath.Path.IsAscii); fileDescriptor->ResourceHandle->FileNameData = path.Path; fileDescriptor->ResourceHandle->FileNameLength = path.Length; - MtrlForceSync(fileDescriptor, ref isSync); + ForceSync(fileDescriptor, ref isSync); returnValue = DefaultLoadResource(path, fileDescriptor, priority, isSync, data); // Return original resource handle path so that they can be loaded separately. fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; @@ -215,14 +215,14 @@ public unsafe class ResourceLoader : IDisposable, IService } } - /// Special handling for materials. - private static void MtrlForceSync(SeFileDescriptor* fileDescriptor, ref bool isSync) + /// Special handling for materials and IMCs. + private static void ForceSync(SeFileDescriptor* fileDescriptor, ref bool isSync) { // Force isSync = true for Materials. I don't really understand why, // or where the difference even comes from. // Was called with True on my client and with false on other peoples clients, // which caused problems. - isSync |= fileDescriptor->ResourceHandle->FileType is ResourceType.Mtrl; + isSync |= fileDescriptor->ResourceHandle->FileType is ResourceType.Mtrl or ResourceType.Imc; } /// diff --git a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs index 513877d4..949baaa3 100644 --- a/Penumbra/Interop/Processing/ImcFilePostProcessor.cs +++ b/Penumbra/Interop/Processing/ImcFilePostProcessor.cs @@ -1,4 +1,3 @@ -using Dalamud.Game.ClientState.JobGauge.Types; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; From 0159eb3d8348b4d01e21d542aeeb28cf06201bc6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 23 Jan 2025 17:13:52 +0000 Subject: [PATCH 1076/1381] [CI] Updating repo.json for testing_1.3.3.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e0cf2a70..0f61c85c 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.8", + "TestingAssemblyVersion": "1.3.3.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a3ddce0ef5aed4a0282039e79d46417b108c5716 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 24 Jan 2025 02:50:02 +0100 Subject: [PATCH 1077/1381] Add mechanism to handle completion of async res loads --- Penumbra.GameData | 2 +- Penumbra/Interop/Hooks/HookSettings.cs | 1 + .../Hooks/ResourceLoading/ResourceLoader.cs | 120 +++++++++++++++--- .../Hooks/ResourceLoading/ResourceService.cs | 78 ++++++++++-- .../Resources/ResourceHandleDestructor.cs | 5 +- .../Processing/FilePostProcessService.cs | 18 ++- Penumbra/Interop/Structs/ResourceHandle.cs | 15 ++- Penumbra/UI/ResourceWatcher/Record.cs | 29 ++++- .../UI/ResourceWatcher/ResourceWatcher.cs | 31 ++++- .../ResourceWatcher/ResourceWatcherTable.cs | 25 ++-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 37 +++++- 11 files changed, 303 insertions(+), 58 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ebeea67c..4a987167 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ebeea67c17f6bf4ce7e635041b2138e835d31262 +Subproject commit 4a987167b665184d4c05fc9863993981c35a1d19 diff --git a/Penumbra/Interop/Hooks/HookSettings.cs b/Penumbra/Interop/Hooks/HookSettings.cs index 5a856764..bcff25d2 100644 --- a/Penumbra/Interop/Hooks/HookSettings.cs +++ b/Penumbra/Interop/Hooks/HookSettings.cs @@ -100,6 +100,7 @@ public class HookOverrides public bool DecRef; public bool GetResourceSync; public bool GetResourceAsync; + public bool UpdateResourceState; public bool CheckFileState; public bool TexResourceHandleOnLoad; public bool LoadMdlFileExtern; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index ad9c41e6..f9b8ff60 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -1,7 +1,9 @@ +using System.IO; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; +using Penumbra.Interop.Hooks.Resources; using Penumbra.Interop.PathResolving; using Penumbra.Interop.SafeHandles; using Penumbra.Interop.Structs; @@ -13,27 +15,38 @@ namespace Penumbra.Interop.Hooks.ResourceLoading; public unsafe class ResourceLoader : IDisposable, IService { - private readonly ResourceService _resources; - private readonly FileReadService _fileReadService; - private readonly RsfService _rsfService; - private readonly PapHandler _papHandler; - private readonly Configuration _config; + private readonly ResourceService _resources; + private readonly FileReadService _fileReadService; + private readonly RsfService _rsfService; + private readonly PapHandler _papHandler; + private readonly Configuration _config; + private readonly ResourceHandleDestructor _destructor; + + private readonly ConcurrentDictionary _ongoingLoads = []; private ResolveData _resolvedData = ResolveData.Invalid; public event Action? PapRequested; - public ResourceLoader(ResourceService resources, FileReadService fileReadService, RsfService rsfService, Configuration config, PeSigScanner sigScanner) + public IReadOnlyDictionary OngoingLoads + => _ongoingLoads; + + public ResourceLoader(ResourceService resources, FileReadService fileReadService, RsfService rsfService, Configuration config, PeSigScanner sigScanner, + ResourceHandleDestructor destructor) { _resources = resources; _fileReadService = fileReadService; - _rsfService = rsfService; + _rsfService = rsfService; _config = config; + _destructor = destructor; ResetResolvePath(); - _resources.ResourceRequested += ResourceHandler; - _resources.ResourceHandleIncRef += IncRefProtection; - _resources.ResourceHandleDecRef += DecRefProtection; - _fileReadService.ReadSqPack += ReadSqPackDetour; + _resources.ResourceRequested += ResourceHandler; + _resources.ResourceStateUpdating += ResourceStateUpdatingHandler; + _resources.ResourceStateUpdated += ResourceStateUpdatedHandler; + _resources.ResourceHandleIncRef += IncRefProtection; + _resources.ResourceHandleDecRef += DecRefProtection; + _fileReadService.ReadSqPack += ReadSqPackDetour; + _destructor.Subscribe(ResourceDestructorHandler, ResourceHandleDestructor.Priority.ResourceLoader); _papHandler = new PapHandler(sigScanner, PapResourceHandler); _papHandler.Enable(); @@ -109,12 +122,32 @@ public unsafe class ResourceLoader : IDisposable, IService /// public event FileLoadedDelegate? FileLoaded; + public delegate void ResourceCompleteDelegate(ResourceHandle* resource, CiByteString path, Utf8GamePath originalPath, + ReadOnlySpan additionalData, bool isAsync); + + /// + /// Event fired just before a resource finishes loading. + /// must be checked to know whether the load was successful or not. + /// AdditionalData is either empty or the part of the path inside the leading pipes. + /// + public event ResourceCompleteDelegate? BeforeResourceComplete; + + /// + /// Event fired when a resource has finished loading. + /// must be checked to know whether the load was successful or not. + /// AdditionalData is either empty or the part of the path inside the leading pipes. + /// + public event ResourceCompleteDelegate? ResourceComplete; + public void Dispose() { - _resources.ResourceRequested -= ResourceHandler; - _resources.ResourceHandleIncRef -= IncRefProtection; - _resources.ResourceHandleDecRef -= DecRefProtection; - _fileReadService.ReadSqPack -= ReadSqPackDetour; + _resources.ResourceRequested -= ResourceHandler; + _resources.ResourceStateUpdating -= ResourceStateUpdatingHandler; + _resources.ResourceStateUpdated -= ResourceStateUpdatedHandler; + _resources.ResourceHandleIncRef -= IncRefProtection; + _resources.ResourceHandleDecRef -= DecRefProtection; + _fileReadService.ReadSqPack -= ReadSqPackDetour; + _destructor.Unsubscribe(ResourceDestructorHandler); _papHandler.Dispose(); } @@ -135,7 +168,8 @@ public unsafe class ResourceLoader : IDisposable, IService if (resolvedPath == null || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var p)) { - returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); + returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters, original: original); + TrackResourceLoad(returnValue, original); ResourceLoaded?.Invoke(returnValue, path, resolvedPath, data); return; } @@ -145,10 +179,57 @@ public unsafe class ResourceLoader : IDisposable, IService hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; path = p; - returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters); + returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters, original: original); + TrackResourceLoad(returnValue, original); ResourceLoaded?.Invoke(returnValue, oldPath, resolvedPath.Value, data); } + private void TrackResourceLoad(ResourceHandle* handle, Utf8GamePath original) + { + if (handle->UnkState == 2 && handle->LoadState >= LoadState.Success) + return; + + _ongoingLoads.TryAdd((nint)handle, original.Clone()); + } + + private void ResourceStateUpdatedHandler(ResourceHandle* handle, Utf8GamePath syncOriginal, (byte, LoadState) previousState, ref uint returnValue) + { + if (handle->UnkState != 2 || handle->LoadState < LoadState.Success || previousState.Item1 == 2 && previousState.Item2 >= LoadState.Success) + return; + + if (!_ongoingLoads.TryRemove((nint)handle, out var asyncOriginal)) + asyncOriginal = Utf8GamePath.Empty; + + var path = handle->CsHandle.FileName; + if (!syncOriginal.IsEmpty && !asyncOriginal.IsEmpty && !syncOriginal.Equals(asyncOriginal)) + Penumbra.Log.Warning($"[ResourceLoader] Resource original paths inconsistency: 0x{(nint)handle:X}, of path {path}, sync original {syncOriginal}, async original {asyncOriginal}."); + var original = !asyncOriginal.IsEmpty ? asyncOriginal : syncOriginal; + + // Penumbra.Log.Information($"[ResourceLoader] Resource is complete: 0x{(nint)handle:X}, of path {path}, original {original}, state {previousState.Item1}:{previousState.Item2} -> {handle->UnkState}:{handle->LoadState}, sync: {asyncOriginal.IsEmpty}"); + if (PathDataHandler.Split(path.AsSpan(), out var actualPath, out var additionalData)) + ResourceComplete?.Invoke(handle, new CiByteString(actualPath), original, additionalData, !asyncOriginal.IsEmpty); + else + ResourceComplete?.Invoke(handle, path.AsByteString(), original, [], !asyncOriginal.IsEmpty); + } + + private void ResourceStateUpdatingHandler(ResourceHandle* handle, Utf8GamePath syncOriginal) + { + if (handle->UnkState != 1 || handle->LoadState != LoadState.Success) + return; + + if (!_ongoingLoads.TryGetValue((nint)handle, out var asyncOriginal)) + asyncOriginal = Utf8GamePath.Empty; + + var path = handle->CsHandle.FileName; + var original = asyncOriginal.IsEmpty ? syncOriginal : asyncOriginal; + + // Penumbra.Log.Information($"[ResourceLoader] Resource is about to be complete: 0x{(nint)handle:X}, of path {path}, original {original}"); + if (PathDataHandler.Split(path.AsSpan(), out var actualPath, out var additionalData)) + BeforeResourceComplete?.Invoke(handle, new CiByteString(actualPath), original, additionalData, !asyncOriginal.IsEmpty); + else + BeforeResourceComplete?.Invoke(handle, path.AsByteString(), original, [], !asyncOriginal.IsEmpty); + } + private void ReadSqPackDetour(SeFileDescriptor* fileDescriptor, ref int priority, ref bool isSync, ref byte? returnValue) { if (fileDescriptor->ResourceHandle == null) @@ -265,6 +346,11 @@ public unsafe class ResourceLoader : IDisposable, IService returnValue = 1; } + private void ResourceDestructorHandler(ResourceHandle* handle) + { + _ongoingLoads.TryRemove((nint)handle, out _); + } + /// Compute the CRC32 hash for a given path together with potential resource parameters. private static int ComputeHash(CiByteString path, GetResourceParameters* pGetResParams) { diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index 126505d1..238ed70f 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -19,6 +19,8 @@ public unsafe class ResourceService : IDisposable, IRequiredService private readonly PerformanceTracker _performance; private readonly ResourceManagerService _resourceManager; + private readonly ThreadLocal _currentGetResourcePath = new(() => Utf8GamePath.Empty); + public ResourceService(PerformanceTracker performance, ResourceManagerService resourceManager, IGameInteropProvider interop) { _performance = performance; @@ -34,6 +36,8 @@ public unsafe class ResourceService : IDisposable, IRequiredService _getResourceSyncHook.Enable(); if (!HookOverrides.Instance.ResourceLoading.GetResourceAsync) _getResourceAsyncHook.Enable(); + if (!HookOverrides.Instance.ResourceLoading.UpdateResourceState) + _updateResourceStateHook.Enable(); if (!HookOverrides.Instance.ResourceLoading.IncRef) _incRefHook.Enable(); if (!HookOverrides.Instance.ResourceLoading.DecRef) @@ -54,8 +58,10 @@ public unsafe class ResourceService : IDisposable, IRequiredService { _getResourceSyncHook.Dispose(); _getResourceAsyncHook.Dispose(); + _updateResourceStateHook.Dispose(); _incRefHook.Dispose(); _decRefHook.Dispose(); + _currentGetResourcePath.Dispose(); } #region GetResource @@ -112,28 +118,84 @@ public unsafe class ResourceService : IDisposable, IRequiredService unk9); } + var original = gamePath; ResourceHandle* returnValue = null; - ResourceRequested?.Invoke(ref *categoryId, ref *resourceType, ref *resourceHash, ref gamePath, gamePath, pGetResParams, ref isSync, + ResourceRequested?.Invoke(ref *categoryId, ref *resourceType, ref *resourceHash, ref gamePath, original, pGetResParams, ref isSync, ref returnValue); if (returnValue != null) return returnValue; - return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk, unk8, unk9); + return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk, unk8, unk9, original); } /// Call the original GetResource function. public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, - GetResourceParameters* resourceParameters = null, byte unk = 0, nint unk8 = 0, uint unk9 = 0) - => sync - ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, - resourceParameters, unk8, unk9) - : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, - resourceParameters, unk, unk8, unk9); + GetResourceParameters* resourceParameters = null, byte unk = 0, nint unk8 = 0, uint unk9 = 0, Utf8GamePath original = default) + { + if (original.Path is null) // i. e. if original is default + Utf8GamePath.FromByteString(path, out original); + var previous = _currentGetResourcePath.Value; + try + { + _currentGetResourcePath.Value = original; + return sync + ? _getResourceSyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, + resourceParameters, unk8, unk9) + : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, + resourceParameters, unk, unk8, unk9); + } finally + { + _currentGetResourcePath.Value = previous; + } + } #endregion private delegate nint ResourceHandlePrototype(ResourceHandle* handle); + #region UpdateResourceState + + /// Invoked before a resource state is updated. + /// The resource handle. + /// The original game path of the resource, if loaded synchronously. + public delegate void ResourceStateUpdatingDelegate(ResourceHandle* handle, Utf8GamePath syncOriginal); + + /// Invoked after a resource state is updated. + /// The resource handle. + /// The original game path of the resource, if loaded synchronously. + /// The previous state of the resource. + /// The return value to use. + public delegate void ResourceStateUpdatedDelegate(ResourceHandle* handle, Utf8GamePath syncOriginal, (byte UnkState, LoadState LoadState) previousState, ref uint returnValue); + + /// + /// + /// Subscribers should be exception-safe. + /// + public event ResourceStateUpdatingDelegate? ResourceStateUpdating; + + /// + /// + /// Subscribers should be exception-safe. + /// + public event ResourceStateUpdatedDelegate? ResourceStateUpdated; + + private delegate uint UpdateResourceStatePrototype(ResourceHandle* handle, byte offFileThread); + + [Signature(Sigs.UpdateResourceState, DetourName = nameof(UpdateResourceStateDetour))] + private readonly Hook _updateResourceStateHook = null!; + + private uint UpdateResourceStateDetour(ResourceHandle* handle, byte offFileThread) + { + var previousState = (handle->UnkState, handle->LoadState); + var syncOriginal = _currentGetResourcePath.IsValueCreated ? _currentGetResourcePath.Value! : Utf8GamePath.Empty; + ResourceStateUpdating?.Invoke(handle, syncOriginal); + var ret = _updateResourceStateHook.OriginalDisposeSafe(handle, offFileThread); + ResourceStateUpdated?.Invoke(handle, syncOriginal, previousState, ref ret); + return ret; + } + + #endregion + #region IncRef /// Invoked before a resource handle reference count is incremented. diff --git a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs index bdb11752..0e04029b 100644 --- a/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs +++ b/Penumbra/Interop/Hooks/Resources/ResourceHandleDestructor.cs @@ -14,9 +14,12 @@ public sealed unsafe class ResourceHandleDestructor : EventWrapperPtr SubfileHelper, - /// + /// ShaderReplacementFixer, + /// + ResourceLoader, + /// ResourceWatcher, } diff --git a/Penumbra/Interop/Processing/FilePostProcessService.cs b/Penumbra/Interop/Processing/FilePostProcessService.cs index ecf78c69..a27f6d45 100644 --- a/Penumbra/Interop/Processing/FilePostProcessService.cs +++ b/Penumbra/Interop/Processing/FilePostProcessService.cs @@ -4,6 +4,7 @@ using Penumbra.Api.Enums; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.Interop.Structs; using Penumbra.String; +using Penumbra.String.Classes; namespace Penumbra.Interop.Processing; @@ -20,20 +21,23 @@ public unsafe class FilePostProcessService : IRequiredService, IDisposable public FilePostProcessService(ResourceLoader resourceLoader, ServiceManager services) { - _resourceLoader = resourceLoader; - _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); - _resourceLoader.FileLoaded += OnFileLoaded; + _resourceLoader = resourceLoader; + _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); + _resourceLoader.BeforeResourceComplete += OnResourceComplete; } public void Dispose() { - _resourceLoader.FileLoaded -= OnFileLoaded; + _resourceLoader.BeforeResourceComplete -= OnResourceComplete; } - private void OnFileLoaded(ResourceHandle* resource, CiByteString path, bool returnValue, bool custom, - ReadOnlySpan additionalData) + private void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, + ReadOnlySpan additionalData, bool isAsync) { + if (resource->LoadState != LoadState.Success) + return; + if (_processors.TryGetValue(resource->FileType, out var processor)) - processor.PostProcess(resource, path, additionalData); + processor.PostProcess(resource, original.Path, additionalData); } } diff --git a/Penumbra/Interop/Structs/ResourceHandle.cs b/Penumbra/Interop/Structs/ResourceHandle.cs index 65550563..1558c035 100644 --- a/Penumbra/Interop/Structs/ResourceHandle.cs +++ b/Penumbra/Interop/Structs/ResourceHandle.cs @@ -24,10 +24,20 @@ public unsafe struct TextureResourceHandle public enum LoadState : byte { + Constructing = 0x00, + Constructed = 0x01, + Async2 = 0x02, + AsyncRequested = 0x03, + Async4 = 0x04, + AsyncLoading = 0x05, + Async6 = 0x06, Success = 0x07, - Async = 0x03, + Unknown8 = 0x08, Failure = 0x09, FailedSubResource = 0x0A, + FailureB = 0x0B, + FailureC = 0x0C, + FailureD = 0x0D, None = 0xFF, } @@ -74,6 +84,9 @@ public unsafe struct ResourceHandle [FieldOffset(0x58)] public int FileNameLength; + [FieldOffset(0xA8)] + public byte UnkState; + [FieldOffset(0xA9)] public LoadState LoadState; diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index 7338e5a9..13a71656 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -10,10 +10,11 @@ namespace Penumbra.UI.ResourceWatcher; [Flags] public enum RecordType : byte { - Request = 0x01, - ResourceLoad = 0x02, - FileLoad = 0x04, - Destruction = 0x08, + Request = 0x01, + ResourceLoad = 0x02, + FileLoad = 0x04, + Destruction = 0x08, + ResourceComplete = 0x10, } internal unsafe struct Record @@ -141,4 +142,24 @@ internal unsafe struct Record LoadState = handle->LoadState, Crc64 = 0, }; + + public static Record CreateResourceComplete(CiByteString path, ResourceHandle* handle, Utf8GamePath originalPath) + => new() + { + Time = DateTime.UtcNow, + Path = path.IsOwned ? path : path.Clone(), + OriginalPath = originalPath.Path.IsOwned ? originalPath.Path : originalPath.Path.Clone(), + Collection = null, + Handle = handle, + ResourceType = handle->FileType.ToFlag(), + Category = handle->Category.ToFlag(), + RefCount = handle->RefCount, + RecordType = RecordType.ResourceComplete, + Synchronously = false, + ReturnValue = OptionalBool.Null, + CustomLoad = OptionalBool.Null, + AssociatedGameObject = string.Empty, + LoadState = handle->LoadState, + Crc64 = 0, + }; } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 0f72efff..53d7e79d 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -47,9 +47,10 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _table = new ResourceWatcherTable(config.Ephemeral, _records); _resources.ResourceRequested += OnResourceRequested; _destructor.Subscribe(OnResourceDestroyed, ResourceHandleDestructor.Priority.ResourceWatcher); - _loader.ResourceLoaded += OnResourceLoaded; - _loader.FileLoaded += OnFileLoaded; - _loader.PapRequested += OnPapRequested; + _loader.ResourceLoaded += OnResourceLoaded; + _loader.ResourceComplete += OnResourceComplete; + _loader.FileLoaded += OnFileLoaded; + _loader.PapRequested += OnPapRequested; UpdateFilter(_ephemeral.ResourceLoggingFilter, false); _newMaxEntries = _config.MaxResourceWatcherRecords; } @@ -73,9 +74,10 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _records.TrimExcess(); _resources.ResourceRequested -= OnResourceRequested; _destructor.Unsubscribe(OnResourceDestroyed); - _loader.ResourceLoaded -= OnResourceLoaded; - _loader.FileLoaded -= OnFileLoaded; - _loader.PapRequested -= OnPapRequested; + _loader.ResourceLoaded -= OnResourceLoaded; + _loader.ResourceComplete -= OnResourceComplete; + _loader.FileLoaded -= OnFileLoaded; + _loader.PapRequested -= OnPapRequested; } private void Clear() @@ -255,6 +257,23 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _newRecords.Enqueue(record); } + private unsafe void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, ReadOnlySpan _, bool isAsync) + { + if (!isAsync) + return; + + if (_ephemeral.EnableResourceLogging && FilterMatch(path, out var match)) + Penumbra.Log.Information( + $"[ResourceLoader] [DONE] [{resource->FileType}] Finished loading {match} into 0x{(ulong)resource:X}, state {resource->LoadState}."); + + if (!_ephemeral.EnableResourceWatcher) + return; + + var record = Record.CreateResourceComplete(path, resource, original); + if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) + _newRecords.Enqueue(record); + } + private unsafe void OnFileLoaded(ResourceHandle* resource, CiByteString path, bool success, bool custom, ReadOnlySpan _) { if (_ephemeral.EnableResourceLogging && FilterMatch(path, out var match)) diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 7ac3cb99..a58d74d1 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -124,11 +124,12 @@ internal sealed class ResourceWatcherTable : Table { ImGui.TextUnformatted(item.RecordType switch { - RecordType.Request => "REQ", - RecordType.ResourceLoad => "LOAD", - RecordType.FileLoad => "FILE", - RecordType.Destruction => "DEST", - _ => string.Empty, + RecordType.Request => "REQ", + RecordType.ResourceLoad => "LOAD", + RecordType.FileLoad => "FILE", + RecordType.Destruction => "DEST", + RecordType.ResourceComplete => "DONE", + _ => string.Empty, }); } } @@ -317,10 +318,10 @@ internal sealed class ResourceWatcherTable : Table { LoadState.None => FilterValue.HasFlag(LoadStateFlag.None), LoadState.Success => FilterValue.HasFlag(LoadStateFlag.Success), - LoadState.Async => FilterValue.HasFlag(LoadStateFlag.Async), - LoadState.Failure => FilterValue.HasFlag(LoadStateFlag.Failed), LoadState.FailedSubResource => FilterValue.HasFlag(LoadStateFlag.FailedSub), - _ => FilterValue.HasFlag(LoadStateFlag.Unknown), + <= LoadState.Constructed => FilterValue.HasFlag(LoadStateFlag.Unknown), + < LoadState.Success => FilterValue.HasFlag(LoadStateFlag.Async), + > LoadState.Success => FilterValue.HasFlag(LoadStateFlag.Failed), }; public override void DrawColumn(Record item, int _) @@ -332,12 +333,12 @@ internal sealed class ResourceWatcherTable : Table { LoadState.Success => (FontAwesomeIcon.CheckCircle, ColorId.IncreasedMetaValue.Value(), $"Successfully loaded ({(byte)item.LoadState})."), - LoadState.Async => (FontAwesomeIcon.Clock, ColorId.FolderLine.Value(), $"Loading asynchronously ({(byte)item.LoadState})."), - LoadState.Failure => (FontAwesomeIcon.Times, ColorId.DecreasedMetaValue.Value(), - $"Failed to load ({(byte)item.LoadState})."), LoadState.FailedSubResource => (FontAwesomeIcon.ExclamationCircle, ColorId.DecreasedMetaValue.Value(), $"Dependencies failed to load ({(byte)item.LoadState})."), - _ => (FontAwesomeIcon.QuestionCircle, ColorId.UndefinedMod.Value(), $"Unknown state ({(byte)item.LoadState})."), + <= LoadState.Constructed => (FontAwesomeIcon.QuestionCircle, ColorId.UndefinedMod.Value(), $"Not yet loaded ({(byte)item.LoadState})."), + < LoadState.Success => (FontAwesomeIcon.Clock, ColorId.FolderLine.Value(), $"Loading asynchronously ({(byte)item.LoadState})."), + > LoadState.Success => (FontAwesomeIcon.Times, ColorId.DecreasedMetaValue.Value(), + $"Failed to load ({(byte)item.LoadState})."), }; using (var font = ImRaii.PushFont(UiBuilder.IconFont)) { diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index ad4824c3..5dc203c2 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -80,6 +80,7 @@ public class DebugTab : Window, ITab, IUiService private readonly StainService _stains; private readonly GlobalVariablesDrawer _globalVariablesDrawer; private readonly ResourceManagerService _resourceManager; + private readonly ResourceLoader _resourceLoader; private readonly CollectionResolver _collectionResolver; private readonly DrawObjectState _drawObjectState; private readonly PathState _pathState; @@ -109,7 +110,7 @@ public class DebugTab : Window, ITab, IUiService public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, ValidityChecker validityChecker, ModManager modManager, HttpApi httpApi, ActorManager actors, StainService stains, - ResourceManagerService resourceManager, CollectionResolver collectionResolver, + ResourceManagerService resourceManager, ResourceLoader resourceLoader, CollectionResolver collectionResolver, DrawObjectState drawObjectState, PathState pathState, SubfileHelper subfileHelper, IdentifiedCollectionCache identifiedCollectionCache, CutsceneService cutsceneService, ModImportManager modImporter, ImportPopup importPopup, FrameworkManager framework, TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, @@ -133,6 +134,7 @@ public class DebugTab : Window, ITab, IUiService _actors = actors; _stains = stains; _resourceManager = resourceManager; + _resourceLoader = resourceLoader; _collectionResolver = collectionResolver; _drawObjectState = drawObjectState; _pathState = pathState; @@ -191,6 +193,7 @@ public class DebugTab : Window, ITab, IUiService DrawShaderReplacementFixer(); DrawData(); DrawCrcCache(); + DrawResourceLoader(); DrawResourceProblems(); _renderTargetDrawer.Draw(); _hookOverrides.Draw(); @@ -1099,6 +1102,38 @@ public class DebugTab : Window, ITab, IUiService } } + private unsafe void DrawResourceLoader() + { + if (!ImGui.CollapsingHeader("Resource Loader")) + return; + + var ongoingLoads = _resourceLoader.OngoingLoads; + var ongoingLoadCount = ongoingLoads.Count; + ImUtf8.Text($"Ongoing Loads: {ongoingLoadCount}"); + + if (ongoingLoadCount == 0) + return; + + using var table = ImUtf8.Table("ongoingLoadTable"u8, 3); + if (!table) + return; + + ImUtf8.TableSetupColumn("Resource Handle"u8, ImGuiTableColumnFlags.WidthStretch, 0.2f); + ImUtf8.TableSetupColumn("Actual Path"u8, ImGuiTableColumnFlags.WidthStretch, 0.4f); + ImUtf8.TableSetupColumn("Original Path"u8, ImGuiTableColumnFlags.WidthStretch, 0.4f); + ImGui.TableHeadersRow(); + + foreach (var (handle, original) in ongoingLoads) + { + ImGui.TableNextColumn(); + ImUtf8.Text($"0x{handle:X}"); + ImGui.TableNextColumn(); + ImUtf8.Text(((ResourceHandle*)handle)->CsHandle.FileName); + ImGui.TableNextColumn(); + ImUtf8.Text(original.Path.Span); + } + } + /// Draw resources with unusual reference count. private unsafe void DrawResourceProblems() { From 9ab8985343591de70204d16a0abe1d97ffc3955a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 25 Jan 2025 12:38:10 +0100 Subject: [PATCH 1078/1381] Debug logging. --- Penumbra/Meta/Files/ImcFile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 23339cfc..0a0faf1e 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -198,7 +198,7 @@ public unsafe class ImcFile : MetaBaseFile if (DebugConfiguration.WriteImcBytesToLog) { - Penumbra.Log.Information($"Default IMC file -> Modified IMC File for {Path}:"); + Penumbra.Log.Information($"Default IMC file -> Modified IMC File for {Path}, current handle state {resource->LoadState}:"); Penumbra.Log.Information(new Span((void*)data, length).WriteHexBytes()); Penumbra.Log.Information(new Span(Data, actualLength).WriteHexBytes()); Penumbra.Log.Information(new Span(Data, actualLength).WriteHexByteDiff(new Span((void*)data, length))); From 30a957356af4e9b959a1280a015de1a3a34672f0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 25 Jan 2025 13:54:19 +0100 Subject: [PATCH 1079/1381] Minor changes. --- .../Hooks/ResourceLoading/ResourceLoader.cs | 11 +++++------ .../Hooks/ResourceLoading/ResourceService.cs | 10 ++++------ .../Processing/FilePostProcessService.cs | 9 +++------ Penumbra/UI/ResourceWatcher/Record.cs | 17 +++++++++++++++-- Penumbra/UI/ResourceWatcher/ResourceWatcher.cs | 4 ++-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 11 ++++------- 6 files changed, 33 insertions(+), 29 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index f9b8ff60..d5e41b56 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -1,4 +1,3 @@ -using System.IO; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui.Services; using Penumbra.Api.Enums; @@ -168,7 +167,7 @@ public unsafe class ResourceLoader : IDisposable, IService if (resolvedPath == null || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var p)) { - returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters, original: original); + returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, original, parameters); TrackResourceLoad(returnValue, original); ResourceLoaded?.Invoke(returnValue, path, resolvedPath, data); return; @@ -179,7 +178,7 @@ public unsafe class ResourceLoader : IDisposable, IService hash = ComputeHash(resolvedPath.Value.InternalName, parameters); var oldPath = path; path = p; - returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, parameters, original: original); + returnValue = _resources.GetOriginalResource(sync, category, type, hash, path.Path, original, parameters); TrackResourceLoad(returnValue, original); ResourceLoaded?.Invoke(returnValue, oldPath, resolvedPath.Value, data); } @@ -194,7 +193,7 @@ public unsafe class ResourceLoader : IDisposable, IService private void ResourceStateUpdatedHandler(ResourceHandle* handle, Utf8GamePath syncOriginal, (byte, LoadState) previousState, ref uint returnValue) { - if (handle->UnkState != 2 || handle->LoadState < LoadState.Success || previousState.Item1 == 2 && previousState.Item2 >= LoadState.Success) + if (handle->UnkState != 2 || handle->LoadState < LoadState.Success || previousState is { Item1: 2, Item2: >= LoadState.Success }) return; if (!_ongoingLoads.TryRemove((nint)handle, out var asyncOriginal)) @@ -205,7 +204,7 @@ public unsafe class ResourceLoader : IDisposable, IService Penumbra.Log.Warning($"[ResourceLoader] Resource original paths inconsistency: 0x{(nint)handle:X}, of path {path}, sync original {syncOriginal}, async original {asyncOriginal}."); var original = !asyncOriginal.IsEmpty ? asyncOriginal : syncOriginal; - // Penumbra.Log.Information($"[ResourceLoader] Resource is complete: 0x{(nint)handle:X}, of path {path}, original {original}, state {previousState.Item1}:{previousState.Item2} -> {handle->UnkState}:{handle->LoadState}, sync: {asyncOriginal.IsEmpty}"); + Penumbra.Log.Excessive($"[ResourceLoader] Resource is complete: 0x{(nint)handle:X}, of path {path}, original {original}, state {previousState.Item1}:{previousState.Item2} -> {handle->UnkState}:{handle->LoadState}, sync: {asyncOriginal.IsEmpty}"); if (PathDataHandler.Split(path.AsSpan(), out var actualPath, out var additionalData)) ResourceComplete?.Invoke(handle, new CiByteString(actualPath), original, additionalData, !asyncOriginal.IsEmpty); else @@ -223,7 +222,7 @@ public unsafe class ResourceLoader : IDisposable, IService var path = handle->CsHandle.FileName; var original = asyncOriginal.IsEmpty ? syncOriginal : asyncOriginal; - // Penumbra.Log.Information($"[ResourceLoader] Resource is about to be complete: 0x{(nint)handle:X}, of path {path}, original {original}"); + Penumbra.Log.Excessive($"[ResourceLoader] Resource is about to be complete: 0x{(nint)handle:X}, of path {path}, original {original}"); if (PathDataHandler.Split(path.AsSpan(), out var actualPath, out var additionalData)) BeforeResourceComplete?.Invoke(handle, new CiByteString(actualPath), original, additionalData, !asyncOriginal.IsEmpty); else diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index 238ed70f..e90b4575 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -125,15 +125,13 @@ public unsafe class ResourceService : IDisposable, IRequiredService if (returnValue != null) return returnValue; - return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, pGetResParams, isUnk, unk8, unk9, original); + return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, original, pGetResParams, isUnk, unk8, unk9); } /// Call the original GetResource function. - public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, - GetResourceParameters* resourceParameters = null, byte unk = 0, nint unk8 = 0, uint unk9 = 0, Utf8GamePath original = default) + public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, Utf8GamePath original, + GetResourceParameters* resourceParameters = null, byte unk = 0, nint unk8 = 0, uint unk9 = 0) { - if (original.Path is null) // i. e. if original is default - Utf8GamePath.FromByteString(path, out original); var previous = _currentGetResourcePath.Value; try { @@ -187,7 +185,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService private uint UpdateResourceStateDetour(ResourceHandle* handle, byte offFileThread) { var previousState = (handle->UnkState, handle->LoadState); - var syncOriginal = _currentGetResourcePath.IsValueCreated ? _currentGetResourcePath.Value! : Utf8GamePath.Empty; + var syncOriginal = _currentGetResourcePath.IsValueCreated ? _currentGetResourcePath.Value : Utf8GamePath.Empty; ResourceStateUpdating?.Invoke(handle, syncOriginal); var ret = _updateResourceStateHook.OriginalDisposeSafe(handle, offFileThread); ResourceStateUpdated?.Invoke(handle, syncOriginal, previousState, ref ret); diff --git a/Penumbra/Interop/Processing/FilePostProcessService.cs b/Penumbra/Interop/Processing/FilePostProcessService.cs index a27f6d45..71340178 100644 --- a/Penumbra/Interop/Processing/FilePostProcessService.cs +++ b/Penumbra/Interop/Processing/FilePostProcessService.cs @@ -23,20 +23,17 @@ public unsafe class FilePostProcessService : IRequiredService, IDisposable { _resourceLoader = resourceLoader; _processors = services.GetServicesImplementing().ToFrozenDictionary(s => s.Type, s => s); - _resourceLoader.BeforeResourceComplete += OnResourceComplete; + _resourceLoader.BeforeResourceComplete += OnBeforeResourceComplete; } public void Dispose() { - _resourceLoader.BeforeResourceComplete -= OnResourceComplete; + _resourceLoader.BeforeResourceComplete -= OnBeforeResourceComplete; } - private void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, + private void OnBeforeResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, ReadOnlySpan additionalData, bool isAsync) { - if (resource->LoadState != LoadState.Success) - return; - if (_processors.TryGetValue(resource->FileType, out var processor)) processor.PostProcess(resource, original.Path, additionalData); } diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index 13a71656..8ab96f4b 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -143,11 +143,11 @@ internal unsafe struct Record Crc64 = 0, }; - public static Record CreateResourceComplete(CiByteString path, ResourceHandle* handle, Utf8GamePath originalPath) + public static Record CreateResourceComplete(CiByteString path, ResourceHandle* handle, Utf8GamePath originalPath, ReadOnlySpan additionalData) => new() { Time = DateTime.UtcNow, - Path = path.IsOwned ? path : path.Clone(), + Path = CombinedPath(path, additionalData), OriginalPath = originalPath.Path.IsOwned ? originalPath.Path : originalPath.Path.Clone(), Collection = null, Handle = handle, @@ -162,4 +162,17 @@ internal unsafe struct Record LoadState = handle->LoadState, Crc64 = 0, }; + + private static CiByteString CombinedPath(CiByteString path, ReadOnlySpan additionalData) + { + if (additionalData.Length is 0) + return path.IsOwned ? path : path.Clone(); + + fixed (byte* ptr = additionalData) + { + // If a path has additional data and is split, it is always in the form of |{additionalData}|{path}, + // so we can just read from the start of additional data - 1 and sum their length +2 for the pipes. + return new CiByteString(new ReadOnlySpan(ptr - 1, additionalData.Length + 2 + path.Length)).Clone(); + } + } } diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 53d7e79d..94bd4307 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -257,7 +257,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _newRecords.Enqueue(record); } - private unsafe void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, ReadOnlySpan _, bool isAsync) + private unsafe void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, ReadOnlySpan additionalData, bool isAsync) { if (!isAsync) return; @@ -269,7 +269,7 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService if (!_ephemeral.EnableResourceWatcher) return; - var record = Record.CreateResourceComplete(path, resource, original); + var record = Record.CreateResourceComplete(path, resource, original, additionalData); if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 5dc203c2..8f76a54a 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -1104,7 +1104,7 @@ public class DebugTab : Window, ITab, IUiService private unsafe void DrawResourceLoader() { - if (!ImGui.CollapsingHeader("Resource Loader")) + if (!ImUtf8.CollapsingHeader("Resource Loader"u8)) return; var ongoingLoads = _resourceLoader.OngoingLoads; @@ -1125,12 +1125,9 @@ public class DebugTab : Window, ITab, IUiService foreach (var (handle, original) in ongoingLoads) { - ImGui.TableNextColumn(); - ImUtf8.Text($"0x{handle:X}"); - ImGui.TableNextColumn(); - ImUtf8.Text(((ResourceHandle*)handle)->CsHandle.FileName); - ImGui.TableNextColumn(); - ImUtf8.Text(original.Path.Span); + ImUtf8.DrawTableColumn($"0x{handle:X}"); + ImUtf8.DrawTableColumn(((ResourceHandle*)handle)->CsHandle.FileName); + ImUtf8.DrawTableColumn(original.Path.Span); } } From 4d26a63944f5841198ac889dda08187d2863adbc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 25 Jan 2025 13:55:13 +0100 Subject: [PATCH 1080/1381] Test disabling MtrlForceSync. --- .../Interop/Hooks/ResourceLoading/ResourceLoader.cs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index d5e41b56..3f8cb23f 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -256,7 +256,6 @@ public unsafe class ResourceLoader : IDisposable, IService gamePath.Path.IsAscii); fileDescriptor->ResourceHandle->FileNameData = path.Path; fileDescriptor->ResourceHandle->FileNameLength = path.Length; - MtrlForceSync(fileDescriptor, ref isSync); returnValue = DefaultLoadResource(path, fileDescriptor, priority, isSync, data); // Return original resource handle path so that they can be loaded separately. fileDescriptor->ResourceHandle->FileNameData = gamePath.Path.Path; @@ -295,16 +294,6 @@ public unsafe class ResourceLoader : IDisposable, IService } } - /// Special handling for materials. - private static void MtrlForceSync(SeFileDescriptor* fileDescriptor, ref bool isSync) - { - // Force isSync = true for Materials. I don't really understand why, - // or where the difference even comes from. - // Was called with True on my client and with false on other peoples clients, - // which caused problems. - isSync |= fileDescriptor->ResourceHandle->FileType is ResourceType.Mtrl; - } - /// /// A resource with ref count 0 that gets incremented goes through GetResourceAsync again. /// This means, that if the path determined from that is different than the resources path, From ac64b4db24bcba33646dceb43e9aa304403135c8 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 25 Jan 2025 13:01:04 +0000 Subject: [PATCH 1081/1381] [CI] Updating repo.json for testing_1.3.3.10 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 0f61c85c..85ba406a 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.9", + "TestingAssemblyVersion": "1.3.3.10", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.10/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From b0a8b1baa5110d0aed944f462c7c13c7bcd2aac3 Mon Sep 17 00:00:00 2001 From: Theo <58579310+Theo-Asterio@users.noreply.github.com> Date: Mon, 16 Dec 2024 19:11:46 -0800 Subject: [PATCH 1082/1381] Bone and Material Limit updates. Fix UI in Models tab to allow for more than 4 Materials per DT spec. --- Penumbra/Import/Models/Import/ModelImporter.cs | 10 +++++----- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index a141d754..5367e892 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -208,10 +208,10 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) if (index >= 0) return (ushort)index; - // If there's already 4 materials, we can't add any more. + // If there's already 10 materials, we can't add any more. // TODO: permit, with a warning to reduce, and validation in MdlTab. var count = _materials.Count; - if (count >= 4) + if (count >= 10) return 0; _materials.Add(materialName); @@ -234,10 +234,10 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) boneIndices.Add((ushort)boneIndex); } - if (boneIndices.Count > 64) - throw notifier.Exception("XIV does not support meshes weighted to a total of more than 64 bones."); + if (boneIndices.Count > 128) + throw notifier.Exception("XIV does not support meshes weighted to a total of more than 128 bones."); - var boneIndicesArray = new ushort[64]; + var boneIndicesArray = new ushort[128]; Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); var boneTableIndex = _boneTables.Count; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index de088736..bbf3dd00 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -16,7 +16,7 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private const int MdlMaterialMaximum = 4; + private const int MdlMaterialMaximum = 10; private const string MdlImportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-9b49d296-23ab-410a-845b-a3be769b71ea"; @@ -93,7 +93,7 @@ public partial class ModEditWindow tab.Mdl.ConvertV5ToV6(); _modelTab.SaveFile(); - } + } private void DrawImportExport(MdlTab tab, bool disabled) { @@ -427,7 +427,7 @@ public partial class ModEditWindow private static void DrawInvalidMaterialMarker() { - using (ImRaii.PushFont(UiBuilder.IconFont)) + using (ImRaii.PushFont(UiBuilder.IconFont)) ImGuiUtil.TextColored(0xFF0000FF, FontAwesomeIcon.TimesCircle.ToIconString()); ImGuiUtil.HoverTooltip( From 64748790cc877f613833a3de9f366e2e21168d9d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 30 Jan 2025 14:06:39 +0100 Subject: [PATCH 1083/1381] Make limits a bit cleaner. --- Penumbra/Import/Models/Import/ModelImporter.cs | 14 ++++++++------ Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 3 ++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 5367e892..502d060a 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -8,6 +8,9 @@ namespace Penumbra.Import.Models.Import; public partial class ModelImporter(ModelRoot model, IoNotifier notifier) { + public const int BoneLimit = 128; + public const int MaterialLimit = 10; + public static MdlFile Import(ModelRoot model, IoNotifier notifier) { var importer = new ModelImporter(model, notifier); @@ -208,10 +211,9 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) if (index >= 0) return (ushort)index; - // If there's already 10 materials, we can't add any more. // TODO: permit, with a warning to reduce, and validation in MdlTab. var count = _materials.Count; - if (count >= 10) + if (count >= MaterialLimit) return 0; _materials.Add(materialName); @@ -234,11 +236,11 @@ public partial class ModelImporter(ModelRoot model, IoNotifier notifier) boneIndices.Add((ushort)boneIndex); } - if (boneIndices.Count > 128) - throw notifier.Exception("XIV does not support meshes weighted to a total of more than 128 bones."); + if (boneIndices.Count > BoneLimit) + throw notifier.Exception($"XIV does not support meshes weighted to a total of more than {BoneLimit} bones."); - var boneIndicesArray = new ushort[128]; - Array.Copy(boneIndices.ToArray(), boneIndicesArray, boneIndices.Count); + var boneIndicesArray = new ushort[BoneLimit]; + boneIndices.CopyTo(boneIndicesArray); var boneTableIndex = _boneTables.Count; _boneTables.Add(new BoneTableStruct() diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index bbf3dd00..8fbe5a68 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -9,6 +9,7 @@ using OtterGui.Widgets; using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.Import.Models; +using Penumbra.Import.Models.Import; using Penumbra.String.Classes; using Penumbra.UI.Classes; @@ -16,7 +17,7 @@ namespace Penumbra.UI.AdvancedWindow; public partial class ModEditWindow { - private const int MdlMaterialMaximum = 10; + private const int MdlMaterialMaximum = ModelImporter.MaterialLimit; private const string MdlImportDocumentation = @"https://github.com/xivdev/Penumbra/wiki/Model-IO#user-content-9b49d296-23ab-410a-845b-a3be769b71ea"; From 7022b37043c5f02d29d0078a8d086c374d30aa4a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 31 Jan 2025 15:31:05 +0100 Subject: [PATCH 1084/1381] Add some improved Mod Setting API. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ModSettingsApi.cs | 68 +++++++++++++++--- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/IpcProviders.cs | 2 + .../Api/IpcTester/ModSettingsIpcTester.cs | 72 +++++++++++++++---- 5 files changed, 120 insertions(+), 26 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index b4e716f8..35b25bef 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit b4e716f86d94cd4d98d8f58e580ed5f619ea87ae +Subproject commit 35b25bef92e9b0be96c44c150a3df89d848d2658 diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index b78523d3..fe9bf366 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -65,6 +65,16 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable public (PenumbraApiEc, (bool, int, Dictionary>, bool)?) GetCurrentModSettings(Guid collectionId, string modDirectory, string modName, bool ignoreInheritance) + { + var ret = GetCurrentModSettingsWithTemp(collectionId, modDirectory, modName, ignoreInheritance, true, 0); + if (ret.Item2 is null) + return (ret.Item1, null); + + return (ret.Item1, (ret.Item2.Value.Item1, ret.Item2.Value.Item2, ret.Item2.Value.Item3, ret.Item2.Value.Item4)); + } + + public (PenumbraApiEc, (bool, int, Dictionary>, bool, bool)?) GetCurrentModSettingsWithTemp(Guid collectionId, + string modDirectory, string modName, bool ignoreInheritance, bool ignoreTemporary, int key) { if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) return (PenumbraApiEc.ModMissing, null); @@ -72,17 +82,32 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable if (!_collectionManager.Storage.ById(collectionId, out var collection)) return (PenumbraApiEc.CollectionMissing, null); - var settings = collection.Identity.Id == Guid.Empty - ? null - : ignoreInheritance - ? collection.GetOwnSettings(mod.Index) - : collection.GetInheritedSettings(mod.Index).Settings; - if (settings == null) + if (collection.Identity.Id == Guid.Empty) return (PenumbraApiEc.Success, null); - var (enabled, priority, dict) = settings.ConvertToShareable(mod); - return (PenumbraApiEc.Success, - (enabled, priority.Value, dict, collection.GetOwnSettings(mod.Index) is null)); + if (GetCurrentSettings(collection, mod, ignoreInheritance, ignoreTemporary, key) is { } settings) + return (PenumbraApiEc.Success, settings); + + return (PenumbraApiEc.Success, null); + } + + public (PenumbraApiEc, Dictionary>, bool, bool)>?) GetAllModSettings(Guid collectionId, + bool ignoreInheritance, bool ignoreTemporary, int key) + { + if (!_collectionManager.Storage.ById(collectionId, out var collection)) + return (PenumbraApiEc.CollectionMissing, null); + + if (collection.Identity.Id == Guid.Empty) + return (PenumbraApiEc.Success, []); + + var ret = new Dictionary>, bool, bool)>(_modManager.Count); + foreach (var mod in _modManager) + { + if (GetCurrentSettings(collection, mod, ignoreInheritance, ignoreTemporary, key) is { } settings) + ret[mod.Identifier] = settings; + } + + return (PenumbraApiEc.Success, ret); } public PenumbraApiEc TryInheritMod(Guid collectionId, string modDirectory, string modName, bool inherit) @@ -206,6 +231,31 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable return ApiHelpers.Return(PenumbraApiEc.Success, args); } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private (bool, int, Dictionary>, bool, bool)? GetCurrentSettings(ModCollection collection, Mod mod, + bool ignoreInheritance, bool ignoreTemporary, int key) + { + var settings = collection.Settings.Settings[mod.Index]; + if (!ignoreTemporary && settings.TempSettings is { } tempSettings && (tempSettings.Lock <= 0 || tempSettings.Lock == key)) + { + if (!tempSettings.ForceInherit) + return (tempSettings.Enabled, tempSettings.Priority.Value, tempSettings.ConvertToShareable(mod).Settings, + false, true); + if (!ignoreInheritance && collection.GetActualSettings(mod.Index).Settings is { } actualSettingsTemp) + return (actualSettingsTemp.Enabled, actualSettingsTemp.Priority.Value, + actualSettingsTemp.ConvertToShareable(mod).Settings, true, true); + } + + if (settings.Settings is { } ownSettings) + return (ownSettings.Enabled, ownSettings.Priority.Value, ownSettings.ConvertToShareable(mod).Settings, false, + false); + if (!ignoreInheritance && collection.GetInheritedSettings(mod.Index).Settings is { } actualSettings) + return (actualSettings.Enabled, actualSettings.Priority.Value, + actualSettings.ConvertToShareable(mod).Settings, true, false); + + return null; + } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void TriggerSettingEdited(Mod mod) { diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 05c47644..cfc9d470 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -22,7 +22,7 @@ public class PenumbraApi( } public (int Breaking, int Feature) ApiVersion - => (5, 5); + => (5, 6); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index fc97290f..9733f82e 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -57,6 +57,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.GetAvailableModSettings.Provider(pi, api.ModSettings), IpcSubscribers.GetCurrentModSettings.Provider(pi, api.ModSettings), + IpcSubscribers.GetCurrentModSettingsWithTemp.Provider(pi, api.ModSettings), + IpcSubscribers.GetAllModSettings.Provider(pi, api.ModSettings), IpcSubscribers.TryInheritMod.Provider(pi, api.ModSettings), IpcSubscribers.TrySetMod.Provider(pi, api.ModSettings), IpcSubscribers.TrySetModPriority.Provider(pi, api.ModSettings), diff --git a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs index 23078576..c8eb8496 100644 --- a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs @@ -3,6 +3,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; using Penumbra.Api.IpcSubscribers; @@ -22,16 +23,20 @@ public class ModSettingsIpcTester : IUiService, IDisposable private bool _lastSettingChangeInherited; private DateTimeOffset _lastSettingChange; - private string _settingsModDirectory = string.Empty; - private string _settingsModName = string.Empty; - private Guid? _settingsCollection; - private string _settingsCollectionName = string.Empty; - private bool _settingsIgnoreInheritance; - private bool _settingsInherit; - private bool _settingsEnabled; - private int _settingsPriority; - private IReadOnlyDictionary? _availableSettings; - private Dictionary>? _currentSettings; + private string _settingsModDirectory = string.Empty; + private string _settingsModName = string.Empty; + private Guid? _settingsCollection; + private string _settingsCollectionName = string.Empty; + private bool _settingsIgnoreInheritance; + private bool _settingsIgnoreTemporary; + private int _settingsKey; + private bool _settingsInherit; + private bool _settingsTemporary; + private bool _settingsEnabled; + private int _settingsPriority; + private IReadOnlyDictionary? _availableSettings; + private Dictionary>? _currentSettings; + private Dictionary>, bool, bool)>? _allSettings; public ModSettingsIpcTester(IDalamudPluginInterface pi) { @@ -54,7 +59,9 @@ public class ModSettingsIpcTester : IUiService, IDisposable ImGui.InputTextWithHint("##settingsDir", "Mod Directory Name...", ref _settingsModDirectory, 100); ImGui.InputTextWithHint("##settingsName", "Mod Name...", ref _settingsModName, 100); ImGuiUtil.GuidInput("##settingsCollection", "Collection...", string.Empty, ref _settingsCollection, ref _settingsCollectionName); - ImGui.Checkbox("Ignore Inheritance", ref _settingsIgnoreInheritance); + ImUtf8.Checkbox("Ignore Inheritance"u8, ref _settingsIgnoreInheritance); + ImUtf8.Checkbox("Ignore Temporary"u8, ref _settingsIgnoreTemporary); + ImUtf8.InputScalar("Key"u8, ref _settingsKey); var collection = _settingsCollection.GetValueOrDefault(Guid.Empty); using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); @@ -83,10 +90,11 @@ public class ModSettingsIpcTester : IUiService, IDisposable _lastSettingsError = ret.Item1; if (ret.Item1 == PenumbraApiEc.Success) { - _settingsEnabled = ret.Item2?.Item1 ?? false; - _settingsInherit = ret.Item2?.Item4 ?? true; - _settingsPriority = ret.Item2?.Item2 ?? 0; - _currentSettings = ret.Item2?.Item3; + _settingsEnabled = ret.Item2?.Item1 ?? false; + _settingsInherit = ret.Item2?.Item4 ?? true; + _settingsTemporary = false; + _settingsPriority = ret.Item2?.Item2 ?? 0; + _currentSettings = ret.Item2?.Item3; } else { @@ -94,6 +102,40 @@ public class ModSettingsIpcTester : IUiService, IDisposable } } + IpcTester.DrawIntro(GetCurrentModSettingsWithTemp.Label, "Get Current Settings With Temp"); + if (ImGui.Button("Get##CurrentTemp")) + { + var ret = new GetCurrentModSettingsWithTemp(_pi) + .Invoke(collection, _settingsModDirectory, _settingsModName, _settingsIgnoreInheritance, _settingsIgnoreTemporary, _settingsKey); + _lastSettingsError = ret.Item1; + if (ret.Item1 == PenumbraApiEc.Success) + { + _settingsEnabled = ret.Item2?.Item1 ?? false; + _settingsInherit = ret.Item2?.Item4 ?? true; + _settingsTemporary = ret.Item2?.Item5 ?? false; + _settingsPriority = ret.Item2?.Item2 ?? 0; + _currentSettings = ret.Item2?.Item3; + } + else + { + _currentSettings = null; + } + } + + IpcTester.DrawIntro(GetAllModSettings.Label, "Get All Mod Settings"); + if (ImGui.Button("Get##All")) + { + var ret = new GetAllModSettings(_pi).Invoke(collection, _settingsIgnoreInheritance, _settingsIgnoreTemporary, _settingsKey); + _lastSettingsError = ret.Item1; + _allSettings = ret.Item2; + } + + if (_allSettings != null) + { + ImGui.SameLine(); + ImUtf8.Text($"{_allSettings.Count} Mods"); + } + IpcTester.DrawIntro(TryInheritMod.Label, "Inherit Mod"); ImGui.Checkbox("##inherit", ref _settingsInherit); ImGui.SameLine(); From ec09a7eb0ee1aafc061306c5cd4e72b1316ae83b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 31 Jan 2025 18:46:17 +0100 Subject: [PATCH 1085/1381] Add initial cleaning functions, to be improved. --- .../Collections/Manager/CollectionStorage.cs | 12 ++- Penumbra/Services/CleanupService.cs | 74 +++++++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 31 +++++++- 3 files changed, 112 insertions(+), 5 deletions(-) create mode 100644 Penumbra/Services/CleanupService.cs diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index e19acd35..de723729 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -194,12 +194,16 @@ public class CollectionStorage : IReadOnlyList, IDisposable, ISer } /// Remove all settings for not currently-installed mods from the given collection. - public void CleanUnavailableSettings(ModCollection collection) + public int CleanUnavailableSettings(ModCollection collection) { - var any = collection.Settings.Unused.Count > 0; - ((Dictionary)collection.Settings.Unused).Clear(); - if (any) + var count = collection.Settings.Unused.Count; + if (count > 0) + { + ((Dictionary)collection.Settings.Unused).Clear(); _saveService.QueueSave(new ModCollectionSave(_modStorage, collection)); + } + + return count; } /// Remove a specific setting for not currently-installed mods from the given collection. diff --git a/Penumbra/Services/CleanupService.cs b/Penumbra/Services/CleanupService.cs new file mode 100644 index 00000000..490c2407 --- /dev/null +++ b/Penumbra/Services/CleanupService.cs @@ -0,0 +1,74 @@ +using OtterGui.Services; +using Penumbra.Collections.Manager; +using Penumbra.Mods.Manager; + +namespace Penumbra.Services; + +public class CleanupService(SaveService saveService, ModManager mods, CollectionManager collections) : IService +{ + public void CleanUnusedLocalData() + { + var usedFiles = mods.Select(saveService.FileNames.LocalDataFile).ToHashSet(); + foreach (var file in saveService.FileNames.LocalDataFiles.ToList()) + { + try + { + if (!file.Exists || usedFiles.Contains(file.FullName)) + continue; + + file.Delete(); + Penumbra.Log.Information($"[CleanupService] Deleted unused local data file {file.Name}."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"[CleanupService] Failed to delete unused local data file {file.Name}:\n{ex}"); + } + } + } + + public void CleanBackupFiles() + { + foreach (var file in mods.BasePath.EnumerateFiles("group_*.json.bak", SearchOption.AllDirectories)) + { + try + { + if (!file.Exists) + continue; + + file.Delete(); + Penumbra.Log.Information($"[CleanupService] Deleted group backup file {file.FullName}."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"[CleanupService] Failed to delete group backup file {file.FullName}:\n{ex}"); + } + } + + foreach (var file in Directory.EnumerateFiles(saveService.FileNames.ConfigDirectory, "*.json.bak", SearchOption.AllDirectories)) + { + try + { + if (!File.Exists(file)) + continue; + + File.Delete(file); + Penumbra.Log.Information($"[CleanupService] Deleted config backup file {file}."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"[CleanupService] Failed to delete config backup file {file}:\n{ex}"); + } + } + } + + public void CleanupAllUnusedSettings() + { + foreach (var collection in collections.Storage) + { + var count = collections.Storage.CleanUnavailableSettings(collection); + if (count > 0) + Penumbra.Log.Information( + $"[CleanupService] Removed {count} unused settings from collection {collection.Identity.AnonymizedName}."); + } + } +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index c7f66859..e847b291 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -49,6 +49,7 @@ public class SettingsTab : ITab, IUiService private readonly CrashHandlerService _crashService; private readonly MigrationSectionDrawer _migrationDrawer; private readonly CollectionAutoSelector _autoSelector; + private readonly CleanupService _cleanupService; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -60,7 +61,7 @@ public class SettingsTab : ITab, IUiService CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, - MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector) + MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService) { _pluginInterface = pluginInterface; _config = config; @@ -84,6 +85,7 @@ public class SettingsTab : ITab, IUiService _crashService = crashService; _migrationDrawer = migrationDrawer; _autoSelector = autoSelector; + _cleanupService = cleanupService; } public void DrawHeader() @@ -789,9 +791,13 @@ public class SettingsTab : ITab, IUiService DrawWaitForPluginsReflection(); DrawEnableHttpApiBox(); DrawEnableDebugModeBox(); + ImGui.Separator(); DrawReloadResourceButton(); DrawReloadFontsButton(); + ImGui.Separator(); + DrawCleanupButtons(); ImGui.NewLine(); + } private void DrawCrashHandler() @@ -982,6 +988,29 @@ public class SettingsTab : ITab, IUiService _fontReloader.Reload(); } + private void DrawCleanupButtons() + { + var enabled = _config.DeleteModModifier.IsActive(); + if (ImUtf8.ButtonEx("Clear Unused Local Mod Data Files"u8, + "Delete all local mod data files that do not correspond to currently installed mods."u8, default, !enabled)) + _cleanupService.CleanUnusedLocalData(); + if (!enabled) + ImUtf8.HoverTooltip($"Hold {_config.DeleteModModifier} while clicking to delete files."); + + if (ImUtf8.ButtonEx("Clear Backup Files"u8, + "Delete all backups of .json configuration files in your configuration folder and all backups of mod group files in your mod directory."u8, + default, !enabled)) + _cleanupService.CleanBackupFiles(); + if (!enabled) + ImUtf8.HoverTooltip($"Hold {_config.DeleteModModifier} while clicking to delete files."); + + if (ImUtf8.ButtonEx("Clear All Unused Settings"u8, + "Remove all mod settings in all of your collections that do not correspond to currently installed mods."u8, default, !enabled)) + _cleanupService.CleanupAllUnusedSettings(); + if (!enabled) + ImUtf8.HoverTooltip($"Hold {_config.DeleteModModifier} while clicking to remove settings."); + } + /// Draw a checkbox that toggles the dalamud setting to wait for plugins on open. private void DrawWaitForPluginsReflection() { From 981c2bace4d32c404447a14c95e7129ff4212163 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 3 Feb 2025 00:20:22 +0100 Subject: [PATCH 1086/1381] Fix out-of-root path detection logic --- Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index f5659e7c..95627566 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -25,6 +25,8 @@ public class ResourceTreeFactory( PathState pathState, ModManager modManager) : IService { + private static readonly string ParentDirectoryPrefix = $"..{Path.DirectorySeparatorChar}"; + private TreeBuildCache CreateTreeBuildCache() => new(objects, gameData, actors); @@ -159,7 +161,7 @@ public class ResourceTreeFactory( if (onlyWithinPath != null) { var relPath = Path.GetRelativePath(onlyWithinPath, fullPath.FullName); - if (relPath != "." && (relPath.StartsWith('.') || Path.IsPathRooted(relPath))) + if (relPath == ".." || relPath.StartsWith(ParentDirectoryPrefix) || Path.IsPathRooted(relPath)) return false; } From f9b163e7c51a63bf01a4242f4d25cef7cef9c74c Mon Sep 17 00:00:00 2001 From: Exter-N Date: Mon, 3 Feb 2025 00:51:13 +0100 Subject: [PATCH 1087/1381] Add explanations on why paths are redacted --- Penumbra/Interop/ResourceTree/ResourceNode.cs | 9 +++++++++ .../ResourceTree/ResourceTreeFactory.cs | 13 +++++++----- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 20 +++++++++++++++++-- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 4fa13e1f..60cc48de 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -16,6 +16,7 @@ public class ResourceNode : ICloneable public readonly nint ResourceHandle; public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; + public PathStatus FullPathStatus; public string? ModName; public readonly WeakReference Mod = new(null!); public string? ModRelativePath; @@ -61,6 +62,7 @@ public class ResourceNode : ICloneable ResourceHandle = other.ResourceHandle; PossibleGamePaths = other.PossibleGamePaths; FullPath = other.FullPath; + FullPathStatus = other.FullPathStatus; ModName = other.ModName; Mod = other.Mod; ModRelativePath = other.ModRelativePath; @@ -100,4 +102,11 @@ public class ResourceNode : ICloneable public UiData PrependName(string prefix) => Name == null ? this : this with { Name = prefix + Name }; } + + public enum PathStatus : byte + { + Valid, + NonExistent, + External, + } } diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index 95627566..cb8be184 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -147,25 +147,28 @@ public class ResourceTreeFactory( { foreach (var node in tree.FlatNodes) { - if (!ShallKeepPath(node.FullPath, onlyWithinPath)) + node.FullPathStatus = GetPathStatus(node.FullPath, onlyWithinPath); + if (node.FullPathStatus != ResourceNode.PathStatus.Valid) node.FullPath = FullPath.Empty; } return; - static bool ShallKeepPath(FullPath fullPath, string? onlyWithinPath) + static ResourceNode.PathStatus GetPathStatus(FullPath fullPath, string? onlyWithinPath) { if (!fullPath.IsRooted) - return true; + return ResourceNode.PathStatus.Valid; if (onlyWithinPath != null) { var relPath = Path.GetRelativePath(onlyWithinPath, fullPath.FullName); if (relPath == ".." || relPath.StartsWith(ParentDirectoryPrefix) || Path.IsPathRooted(relPath)) - return false; + return ResourceNode.PathStatus.External; } - return fullPath.Exists; + return fullPath.Exists + ? ResourceNode.PathStatus.Valid + : ResourceNode.PathStatus.NonExistent; } } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 7bad64f9..3482f620 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -285,10 +285,10 @@ public class ResourceTreeViewer( } else { - ImGui.Selectable("(unavailable)", false, ImGuiSelectableFlags.Disabled, + ImUtf8.Selectable(GetPathStatusLabel(resourceNode.FullPathStatus), false, ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); ImGuiUtil.HoverTooltip( - $"The actual path to this file is unavailable.\nIt may be managed by another plug-in.{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); + $"{GetPathStatusDescription(resourceNode.FullPathStatus)}{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } mutedColor.Dispose(); @@ -354,6 +354,22 @@ public class ResourceTreeViewer( } } + private static ReadOnlySpan GetPathStatusLabel(ResourceNode.PathStatus status) + => status switch + { + ResourceNode.PathStatus.External => "(managed by external tools)"u8, + ResourceNode.PathStatus.NonExistent => "(not found)"u8, + _ => "(unavailable)"u8, + }; + + private static string GetPathStatusDescription(ResourceNode.PathStatus status) + => status switch + { + ResourceNode.PathStatus.External => "The actual path to this file is unavailable, because it is managed by external tools.", + ResourceNode.PathStatus.NonExistent => "The actual path to this file is unavailable, because it seems to have been moved or deleted since it was loaded.", + _ => "The actual path to this file is unavailable.", + }; + [Flags] private enum TreeCategory : uint { From 4cc5041f0a04dc1066bc00917ce003dd3569b49e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 3 Feb 2025 17:43:44 +0100 Subject: [PATCH 1088/1381] Improve cleanup. --- Penumbra/Services/CleanupService.cs | 175 +++++++++++++++++++++------- Penumbra/UI/Tabs/SettingsTab.cs | 28 +++-- 2 files changed, 154 insertions(+), 49 deletions(-) diff --git a/Penumbra/Services/CleanupService.cs b/Penumbra/Services/CleanupService.cs index 490c2407..bf76f5f0 100644 --- a/Penumbra/Services/CleanupService.cs +++ b/Penumbra/Services/CleanupService.cs @@ -6,69 +6,160 @@ namespace Penumbra.Services; public class CleanupService(SaveService saveService, ModManager mods, CollectionManager collections) : IService { + private CancellationTokenSource _cancel = new(); + private Task? _task; + + public double Progress { get; private set; } + + public bool IsRunning + => _task is { IsCompleted: false }; + + public void Cancel() + => _cancel.Cancel(); + public void CleanUnusedLocalData() { - var usedFiles = mods.Select(saveService.FileNames.LocalDataFile).ToHashSet(); - foreach (var file in saveService.FileNames.LocalDataFiles.ToList()) - { - try - { - if (!file.Exists || usedFiles.Contains(file.FullName)) - continue; + if (IsRunning) + return; - file.Delete(); - Penumbra.Log.Information($"[CleanupService] Deleted unused local data file {file.Name}."); - } - catch (Exception ex) + var usedFiles = mods.Select(saveService.FileNames.LocalDataFile).ToHashSet(); + Progress = 0; + var deleted = 0; + _cancel = new CancellationTokenSource(); + _task = Task.Run(() => + { + var localFiles = saveService.FileNames.LocalDataFiles.ToList(); + var step = 0.9 / localFiles.Count; + Progress = 0.1; + foreach (var file in localFiles) { - Penumbra.Log.Error($"[CleanupService] Failed to delete unused local data file {file.Name}:\n{ex}"); + if (_cancel.IsCancellationRequested) + break; + + try + { + if (!file.Exists || usedFiles.Contains(file.FullName)) + continue; + + file.Delete(); + Penumbra.Log.Debug($"[CleanupService] Deleted unused local data file {file.Name}."); + ++deleted; + } + catch (Exception ex) + { + Penumbra.Log.Error($"[CleanupService] Failed to delete unused local data file {file.Name}:\n{ex}"); + } + + Progress += step; } - } + + Penumbra.Log.Information($"[CleanupService] Deleted {deleted} unused local data files."); + Progress = 1; + }); } public void CleanBackupFiles() { - foreach (var file in mods.BasePath.EnumerateFiles("group_*.json.bak", SearchOption.AllDirectories)) + if (IsRunning) + return; + + Progress = 0; + var deleted = 0; + _cancel = new CancellationTokenSource(); + _task = Task.Run(() => { - try - { - if (!file.Exists) - continue; + var configFiles = Directory.EnumerateFiles(saveService.FileNames.ConfigDirectory, "*.json.bak", SearchOption.AllDirectories) + .ToList(); + Progress = 0.1; + if (_cancel.IsCancellationRequested) + return; - file.Delete(); - Penumbra.Log.Information($"[CleanupService] Deleted group backup file {file.FullName}."); - } - catch (Exception ex) + var groupFiles = mods.BasePath.EnumerateFiles("group_*.json.bak", SearchOption.AllDirectories).ToList(); + Progress = 0.5; + var step = 0.4 / (groupFiles.Count + configFiles.Count); + foreach (var file in groupFiles) { - Penumbra.Log.Error($"[CleanupService] Failed to delete group backup file {file.FullName}:\n{ex}"); - } - } + if (_cancel.IsCancellationRequested) + break; - foreach (var file in Directory.EnumerateFiles(saveService.FileNames.ConfigDirectory, "*.json.bak", SearchOption.AllDirectories)) - { - try - { - if (!File.Exists(file)) - continue; + try + { + if (!file.Exists) + continue; - File.Delete(file); - Penumbra.Log.Information($"[CleanupService] Deleted config backup file {file}."); + file.Delete(); + ++deleted; + Penumbra.Log.Debug($"[CleanupService] Deleted group backup file {file.FullName}."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"[CleanupService] Failed to delete group backup file {file.FullName}:\n{ex}"); + } + + Progress += step; } - catch (Exception ex) + + Penumbra.Log.Information($"[CleanupService] Deleted {deleted} group backup files."); + + deleted = 0; + foreach (var file in configFiles) { - Penumbra.Log.Error($"[CleanupService] Failed to delete config backup file {file}:\n{ex}"); + if (_cancel.IsCancellationRequested) + break; + + try + { + if (!File.Exists(file)) + continue; + + File.Delete(file); + ++deleted; + Penumbra.Log.Debug($"[CleanupService] Deleted config backup file {file}."); + } + catch (Exception ex) + { + Penumbra.Log.Error($"[CleanupService] Failed to delete config backup file {file}:\n{ex}"); + } + + Progress += step; } - } + + Penumbra.Log.Information($"[CleanupService] Deleted {deleted} config backup files."); + Progress = 1; + }); } public void CleanupAllUnusedSettings() { - foreach (var collection in collections.Storage) + if (IsRunning) + return; + + Progress = 0; + var totalRemoved = 0; + var diffCollections = 0; + _cancel = new CancellationTokenSource(); + _task = Task.Run(() => { - var count = collections.Storage.CleanUnavailableSettings(collection); - if (count > 0) - Penumbra.Log.Information( - $"[CleanupService] Removed {count} unused settings from collection {collection.Identity.AnonymizedName}."); - } + var step = 1.0 / collections.Storage.Count; + foreach (var collection in collections.Storage) + { + if (_cancel.IsCancellationRequested) + break; + + var count = collections.Storage.CleanUnavailableSettings(collection); + if (count > 0) + { + Penumbra.Log.Debug( + $"[CleanupService] Removed {count} unused settings from collection {collection.Identity.AnonymizedName}."); + totalRemoved += count; + ++diffCollections; + } + + Progress += step; + } + + Penumbra.Log.Information($"[CleanupService] Removed {totalRemoved} unused settings from {diffCollections} separate collections."); + Progress = 1; + }); } } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index e847b291..9637adeb 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -797,7 +797,6 @@ public class SettingsTab : ITab, IUiService ImGui.Separator(); DrawCleanupButtons(); ImGui.NewLine(); - } private void DrawCrashHandler() @@ -991,24 +990,39 @@ public class SettingsTab : ITab, IUiService private void DrawCleanupButtons() { var enabled = _config.DeleteModModifier.IsActive(); + if (_cleanupService.Progress is not 0.0 and not 1.0) + { + ImUtf8.ProgressBar((float)_cleanupService.Progress, new Vector2(200 * ImUtf8.GlobalScale, ImGui.GetFrameHeight()), + $"{_cleanupService.Progress * 100}%"); + ImGui.SameLine(); + if (ImUtf8.Button("Cancel##FileCleanup"u8)) + _cleanupService.Cancel(); + } + else + { + ImGui.NewLine(); + } + if (ImUtf8.ButtonEx("Clear Unused Local Mod Data Files"u8, - "Delete all local mod data files that do not correspond to currently installed mods."u8, default, !enabled)) + "Delete all local mod data files that do not correspond to currently installed mods."u8, default, + !enabled || _cleanupService.IsRunning)) _cleanupService.CleanUnusedLocalData(); if (!enabled) - ImUtf8.HoverTooltip($"Hold {_config.DeleteModModifier} while clicking to delete files."); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking to delete files."); if (ImUtf8.ButtonEx("Clear Backup Files"u8, "Delete all backups of .json configuration files in your configuration folder and all backups of mod group files in your mod directory."u8, - default, !enabled)) + default, !enabled || _cleanupService.IsRunning)) _cleanupService.CleanBackupFiles(); if (!enabled) - ImUtf8.HoverTooltip($"Hold {_config.DeleteModModifier} while clicking to delete files."); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking to delete files."); if (ImUtf8.ButtonEx("Clear All Unused Settings"u8, - "Remove all mod settings in all of your collections that do not correspond to currently installed mods."u8, default, !enabled)) + "Remove all mod settings in all of your collections that do not correspond to currently installed mods."u8, default, + !enabled || _cleanupService.IsRunning)) _cleanupService.CleanupAllUnusedSettings(); if (!enabled) - ImUtf8.HoverTooltip($"Hold {_config.DeleteModModifier} while clicking to remove settings."); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking to remove settings."); } /// Draw a checkbox that toggles the dalamud setting to wait for plugins on open. From f9952ada75e30a62835d4aa71c1f00e8002f11db Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 6 Feb 2025 16:19:57 +0100 Subject: [PATCH 1089/1381] 1.3.4.0 --- Penumbra/UI/Changelog.cs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index f83c8989..993ace62 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -57,10 +57,32 @@ public class PenumbraChangelog : IUiService Add1_3_1_0(Changelog); Add1_3_2_0(Changelog); Add1_3_3_0(Changelog); + Add1_3_4_0(Changelog); } #region Changelogs + private static void Add1_3_4_0(Changelog log) + => log.NextVersion("Version 1.3.4.0") + .RegisterHighlight("Added HDR functionality to diffuse buffers. This allows more accurate representation of non-standard color values for e.g. skin or hair colors when used with advanced customizations in Glamourer.") + .RegisterEntry("This option requires Wait For Plugins On Load to be enabled in Dalamud and to be enabled on start to work. It is on by default but can be turned off.", 1) + .RegisterHighlight("Added a new option group type: Combining Groups.") + .RegisterEntry("A combining group behaves similarly to a multi group for the user, but instead of enabling the different options separately, it results in exactly one option per choice of settings.", 1) + .RegisterEntry("Example: The user sees 2 checkboxes [+25%, +50%], but the 4 different selection states result in +0%, +25%, +50% or +75% if both are toggled on. Every choice of settings can be configured separately by the mod creator.", 1) + .RegisterEntry("Added new functionality to better track copies of the player character in cutscenes if they get forced to specific clothing, like in the Margrat cutscene. Might improve tracking in wedding ceremonies, too, let me know.") + .RegisterEntry("Added a display of the number of selected files and folders to the multi mod selection.") + .RegisterEntry("Added cleaning functionality to remove outdated or unused files or backups from the config and mod folders via manual action.") + .RegisterEntry("Updated the Bone and Material limits in the Model Importer.") + .RegisterEntry("Improved handling of IMC and Material files loaded asynchronously.") + .RegisterEntry("Added IPC functionality to query temporary settings.") + .RegisterEntry("Improved some mod setting IPC functions.") + .RegisterEntry("Fixed some path detection issues in the OnScreen tab.") + .RegisterEntry("Fixed some issues with temporary mod settings.") + .RegisterEntry("Fixed issues with IPC calls before the game has finished loading.") + .RegisterEntry("Fixed using the wrong dye channel in the material editor previews.") + .RegisterEntry("Added some log warnings if outdated materials are loaded by the game.") + .RegisterEntry("Added Schemas for some of the json files generated and read by Penumbra to the solution."); + private static void Add1_3_3_0(Changelog log) => log.NextVersion("Version 1.3.3.0") .RegisterHighlight("Added Temporary Settings to collections.") From 214be98662267915a5fa553b6ed2b159cdc0c597 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 6 Feb 2025 15:55:30 +0000 Subject: [PATCH 1090/1381] [CI] Updating repo.json for 1.3.4.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 85ba406a..9ee5b00d 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.3.1", - "TestingAssemblyVersion": "1.3.3.10", + "AssemblyVersion": "1.3.4.0", + "TestingAssemblyVersion": "1.3.4.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.3.10/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.3.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 9b18ffce66d26211e9af57d8afe802d6456b0aea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 6 Feb 2025 16:58:41 +0100 Subject: [PATCH 1091/1381] Updated submodule Versions. --- Penumbra.Api | 2 +- Penumbra.String | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 35b25bef..c6780905 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 35b25bef92e9b0be96c44c150a3df89d848d2658 +Subproject commit c67809057fac73a0fd407e3ad567f0aa6bc0bc37 diff --git a/Penumbra.String b/Penumbra.String index 0bc2b0f6..4eb7c118 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 0bc2b0f66eee1a02c9575b2bb30f27ce166f8632 +Subproject commit 4eb7c118cdac5873afb97cb04719602f061f03b7 From 50c42078444659cc79157df572b40189d4847913 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Feb 2025 15:12:34 +0100 Subject: [PATCH 1092/1381] Give messages for unsupported file redirection types. --- Penumbra/Collections/Cache/CollectionCache.cs | 30 ++++++++- .../Cache/CollectionCacheManager.cs | 3 +- .../Interop/PathResolving/PathResolver.cs | 66 +++++++++---------- 3 files changed, 59 insertions(+), 40 deletions(-) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 8ca9aa36..3f0ed27b 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -1,3 +1,4 @@ +using Dalamud.Interface.ImGuiNotification; using OtterGui; using OtterGui.Classes; using Penumbra.Meta.Manipulations; @@ -274,6 +275,24 @@ public sealed class CollectionCache : IDisposable _manager.ResolvedFileChanged.Invoke(collection, type, key, value, old, mod); } + private static bool IsRedirectionSupported(Utf8GamePath path, IMod mod) + { + var ext = path.Extension().AsciiToLower().ToString(); + switch (ext) + { + case ".atch" or ".eqp" or ".eqdp" or ".est" or ".gmp" or ".cmp" or ".imc": + Penumbra.Messager.NotificationMessage( + $"Redirection of {ext} files for {mod.Name} is unsupported. Please use the corresponding meta manipulations instead.", + NotificationType.Warning); + return false; + case ".lvb" or ".lgb" or ".sgb": + Penumbra.Messager.NotificationMessage($"Redirection of {ext} files for {mod.Name} is unsupported as this breaks the game.", + NotificationType.Warning); + return false; + default: return true; + } + } + // Add a specific file redirection, handling potential conflicts. // For different mods, higher mod priority takes precedence before option group priority, // which takes precedence before option priority, which takes precedence before ordering. @@ -283,6 +302,9 @@ public sealed class CollectionCache : IDisposable if (!CheckFullPath(path, file)) return; + if (!IsRedirectionSupported(path, mod)) + return; + try { if (ResolvedFiles.TryAdd(path, new ModPath(mod, file))) @@ -342,8 +364,9 @@ public sealed class CollectionCache : IDisposable // Returns if the added mod takes priority before the existing mod. private bool AddConflict(object data, IMod addedMod, IMod existingMod) { - var addedPriority = addedMod.Index >= 0 ? _collection.GetActualSettings(addedMod.Index).Settings!.Priority : addedMod.Priority; - var existingPriority = existingMod.Index >= 0 ? _collection.GetActualSettings(existingMod.Index).Settings!.Priority : existingMod.Priority; + var addedPriority = addedMod.Index >= 0 ? _collection.GetActualSettings(addedMod.Index).Settings!.Priority : addedMod.Priority; + var existingPriority = + existingMod.Index >= 0 ? _collection.GetActualSettings(existingMod.Index).Settings!.Priority : existingMod.Priority; if (existingPriority < addedPriority) { @@ -427,7 +450,8 @@ public sealed class CollectionCache : IDisposable if (!_changedItems.TryGetValue(name, out var data)) _changedItems.Add(name, (new SingleArray(mod), obj)); else if (!data.Item1.Contains(mod)) - _changedItems[name] = (data.Item1.Append(mod), obj is IdentifiedCounter x && data.Item2 is IdentifiedCounter y ? x + y : obj); + _changedItems[name] = (data.Item1.Append(mod), + obj is IdentifiedCounter x && data.Item2 is IdentifiedCounter y ? x + y : obj); else if (obj is IdentifiedCounter x && data.Item2 is IdentifiedCounter y) _changedItems[name] = (data.Item1, x + y); } diff --git a/Penumbra/Collections/Cache/CollectionCacheManager.cs b/Penumbra/Collections/Cache/CollectionCacheManager.cs index c46759c7..ec48e608 100644 --- a/Penumbra/Collections/Cache/CollectionCacheManager.cs +++ b/Penumbra/Collections/Cache/CollectionCacheManager.cs @@ -171,8 +171,7 @@ public class CollectionCacheManager : IDisposable, IService try { ResolvedFileChanged.Invoke(collection, ResolvedFileChanged.Type.FullRecomputeStart, Utf8GamePath.Empty, FullPath.Empty, - FullPath.Empty, - null); + FullPath.Empty, null); cache.ResolvedFiles.Clear(); cache.Meta.Reset(); cache.ConflictDict.Clear(); diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 0b6c8340..8e5504d5 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -49,42 +49,38 @@ public class PathResolver : IDisposable, IService if (!_config.EnableMods) return (null, ResolveData.Invalid); - // Do not allow manipulating layers to prevent very obvious cheating and softlocks. - if (resourceType is ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb) - return (null, ResolveData.Invalid); - - // Prevent .atch loading to prevent crashes on outdated .atch files. TODO: handle atch modding differently. - if (resourceType is ResourceType.Atch) - return ResolveAtch(path); - - return category switch + return resourceType switch { - // Only Interface collection. - ResourceCategory.Ui => ResolveUi(path), - // Never allow changing scripts. - ResourceCategory.UiScript => (null, ResolveData.Invalid), - ResourceCategory.GameScript => (null, ResolveData.Invalid), - // Use actual resolving. - ResourceCategory.Chara => Resolve(path, resourceType), - ResourceCategory.Shader => ResolveShader(path, resourceType), - ResourceCategory.Vfx => Resolve(path, resourceType), - ResourceCategory.Sound => Resolve(path, resourceType), - // EXD Modding in general should probably be prohibited but is currently used for fan translations. - // We prevent WebURL specifically because it technically allows launching arbitrary programs / to execute arbitrary code. - ResourceCategory.Exd => path.Path.StartsWith("exd/weburl"u8) - ? (null, ResolveData.Invalid) - : DefaultResolver(path), - // None of these files are ever associated with specific characters, - // always use the default resolver for now, - // except that common/font is conceptually more UI. - ResourceCategory.Common => path.Path.StartsWith("common/font"u8) - ? ResolveUi(path) - : DefaultResolver(path), - ResourceCategory.BgCommon => DefaultResolver(path), - ResourceCategory.Bg => DefaultResolver(path), - ResourceCategory.Cut => DefaultResolver(path), - ResourceCategory.Music => DefaultResolver(path), - _ => DefaultResolver(path), + // Do not allow manipulating layers to prevent very obvious cheating and softlocks. + ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb => (null, ResolveData.Invalid), + // Prevent .atch loading to prevent crashes on outdated .atch files. + ResourceType.Atch => ResolveAtch(path), + + _ => category switch + { + // Only Interface collection. + ResourceCategory.Ui => ResolveUi(path), + // Never allow changing scripts. + ResourceCategory.UiScript => (null, ResolveData.Invalid), + ResourceCategory.GameScript => (null, ResolveData.Invalid), + // Use actual resolving. + ResourceCategory.Chara => Resolve(path, resourceType), + ResourceCategory.Shader => ResolveShader(path, resourceType), + ResourceCategory.Vfx => Resolve(path, resourceType), + ResourceCategory.Sound => Resolve(path, resourceType), + // EXD Modding in general should probably be prohibited but is currently used for fan translations. + // We prevent WebURL specifically because it technically allows launching arbitrary programs / to execute arbitrary code. + ResourceCategory.Exd => path.Path.StartsWith("exd/weburl"u8) ? (null, ResolveData.Invalid) : DefaultResolver(path), + // None of these files are ever associated with specific characters, + // always use the default resolver for now, + // except that common/font is conceptually more UI. + ResourceCategory.Common => path.Path.StartsWith("common/font"u8) ? ResolveUi(path) : DefaultResolver(path), + ResourceCategory.BgCommon => DefaultResolver(path), + ResourceCategory.Bg => DefaultResolver(path), + ResourceCategory.Cut => DefaultResolver(path), + ResourceCategory.Music => DefaultResolver(path), + _ => DefaultResolver(path), + } }; } From 60b9facea31c871d5951791ae8bffbc9ee9337fb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Feb 2025 15:27:32 +0100 Subject: [PATCH 1093/1381] Cont. --- Penumbra/Interop/PathResolving/PathResolver.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/PathResolving/PathResolver.cs b/Penumbra/Interop/PathResolving/PathResolver.cs index 8e5504d5..ec421304 100644 --- a/Penumbra/Interop/PathResolving/PathResolver.cs +++ b/Penumbra/Interop/PathResolving/PathResolver.cs @@ -1,4 +1,3 @@ -using System.Linq; using FFXIVClientStructs.FFXIV.Client.System.Resource; using OtterGui.Services; using Penumbra.Api.Enums; @@ -55,6 +54,8 @@ public class PathResolver : IDisposable, IService ResourceType.Lvb or ResourceType.Lgb or ResourceType.Sgb => (null, ResolveData.Invalid), // Prevent .atch loading to prevent crashes on outdated .atch files. ResourceType.Atch => ResolveAtch(path), + // These are manipulated through Meta Edits instead. + ResourceType.Eqp or ResourceType.Eqdp or ResourceType.Est or ResourceType.Gmp or ResourceType.Cmp => (null, ResolveData.Invalid), _ => category switch { From 0af9667789d763a6c3a512a605d41b77925e2b1f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 12 Feb 2025 16:44:22 +0100 Subject: [PATCH 1094/1381] Add changed item adapters. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ModsApi.cs | 6 ++ Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/IpcProviders.cs | 2 + Penumbra/Mods/Manager/ModCacheManager.cs | 2 +- .../Mods/Manager/ModChangedItemAdapter.cs | 102 ++++++++++++++++++ 6 files changed, 113 insertions(+), 3 deletions(-) create mode 100644 Penumbra/Mods/Manager/ModChangedItemAdapter.cs diff --git a/Penumbra.Api b/Penumbra.Api index c6780905..7ae46f0d 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit c67809057fac73a0fd407e3ad567f0aa6bc0bc37 +Subproject commit 7ae46f0d09f40b36a5b2d10382db46fbfb729117 diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 64e201be..ace98f83 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -145,4 +145,10 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable => _modManager.TryGetMod(modDirectory, modName, out var mod) ? mod.ChangedItems.ToDictionary(kvp => kvp.Key, kvp => kvp.Value?.ToInternalObject()) : []; + + public IReadOnlyDictionary> GetChangedItemAdapterDictionary() + => new ModChangedItemAdapter(new WeakReference(_modManager)); + + public IReadOnlyList<(string ModDirectory, IReadOnlyDictionary ChangedItems)> GetChangedItemAdapterList() + => new ModChangedItemAdapter(new WeakReference(_modManager)); } diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index cfc9d470..36f799a0 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -22,7 +22,7 @@ public class PenumbraApi( } public (int Breaking, int Feature) ApiVersion - => (5, 6); + => (5, 7); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 9733f82e..085e57ca 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -54,6 +54,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.GetModPath.Provider(pi, api.Mods), IpcSubscribers.SetModPath.Provider(pi, api.Mods), IpcSubscribers.GetChangedItems.Provider(pi, api.Mods), + IpcSubscribers.GetChangedItemAdapterDictionary.Provider(pi, api.Mods), + IpcSubscribers.GetChangedItemAdapterList.Provider(pi, api.Mods), IpcSubscribers.GetAvailableModSettings.Provider(pi, api.ModSettings), IpcSubscribers.GetCurrentModSettings.Provider(pi, api.ModSettings), diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 38d98d7c..4bf22272 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -15,7 +15,7 @@ public class ModCacheManager : IDisposable, IService private readonly CommunicatorService _communicator; private readonly ObjectIdentification _identifier; private readonly ModStorage _modManager; - private bool _updatingItems = false; + private bool _updatingItems; public ModCacheManager(CommunicatorService communicator, ObjectIdentification identifier, ModStorage modStorage, Configuration config) { diff --git a/Penumbra/Mods/Manager/ModChangedItemAdapter.cs b/Penumbra/Mods/Manager/ModChangedItemAdapter.cs new file mode 100644 index 00000000..8b99cdf2 --- /dev/null +++ b/Penumbra/Mods/Manager/ModChangedItemAdapter.cs @@ -0,0 +1,102 @@ +using Penumbra.GameData.Data; + +namespace Penumbra.Mods.Manager; + +public sealed class ModChangedItemAdapter(WeakReference storage) + : IReadOnlyDictionary>, + IReadOnlyList<(string ModDirectory, IReadOnlyDictionary ChangedItems)> +{ + IEnumerator<(string ModDirectory, IReadOnlyDictionary ChangedItems)> + IEnumerable<(string ModDirectory, IReadOnlyDictionary ChangedItems)>.GetEnumerator() + => Storage.Select(m => (m.Identifier, (IReadOnlyDictionary)new ChangedItemDictionaryAdapter(m.ChangedItems))) + .GetEnumerator(); + + public IEnumerator>> GetEnumerator() + => Storage.Select(m => new KeyValuePair>(m.Identifier, + new ChangedItemDictionaryAdapter(m.ChangedItems))) + .GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); + + public int Count + => Storage.Count; + + public bool ContainsKey(string key) + => Storage.TryGetMod(key, string.Empty, out _); + + public bool TryGetValue(string key, [NotNullWhen(true)] out IReadOnlyDictionary? value) + { + if (Storage.TryGetMod(key, string.Empty, out var mod)) + { + value = new ChangedItemDictionaryAdapter(mod.ChangedItems); + return true; + } + + value = null; + return false; + } + + public IReadOnlyDictionary this[string key] + => TryGetValue(key, out var v) ? v : throw new KeyNotFoundException(); + + (string ModDirectory, IReadOnlyDictionary ChangedItems) + IReadOnlyList<(string ModDirectory, IReadOnlyDictionary ChangedItems)>.this[int index] + { + get + { + var m = Storage[index]; + return (m.Identifier, new ChangedItemDictionaryAdapter(m.ChangedItems)); + } + } + + public IEnumerable Keys + => Storage.Select(m => m.Identifier); + + public IEnumerable> Values + => Storage.Select(m => new ChangedItemDictionaryAdapter(m.ChangedItems)); + + private ModStorage Storage + { + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + get => storage.TryGetTarget(out var t) + ? t + : throw new ObjectDisposedException("The underlying mod storage of this IPC container was disposed."); + } + + private sealed class ChangedItemDictionaryAdapter(SortedList data) : IReadOnlyDictionary + { + public IEnumerator> GetEnumerator() + => data.Select(d => new KeyValuePair(d.Key, d.Value?.ToInternalObject())).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => GetEnumerator(); + + public int Count + => data.Count; + + public bool ContainsKey(string key) + => data.ContainsKey(key); + + public bool TryGetValue(string key, out object? value) + { + if (data.TryGetValue(key, out var v)) + { + value = v?.ToInternalObject(); + return true; + } + + value = null; + return false; + } + + public object? this[string key] + => data[key]?.ToInternalObject(); + + public IEnumerable Keys + => data.Keys; + + public IEnumerable Values + => data.Values.Select(v => v?.ToInternalObject()); + } +} From a9a556eb55a2ed6c93899eb47926663301da2066 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 12 Feb 2025 17:56:01 +0100 Subject: [PATCH 1095/1381] Add CheckCurrentChangedItemFunc, --- Penumbra.Api | 2 +- Penumbra/Api/Api/CollectionApi.cs | 22 +++++++++++++++++-- Penumbra/Api/IpcProviders.cs | 1 + .../Manager => Api}/ModChangedItemAdapter.cs | 3 ++- 4 files changed, 24 insertions(+), 4 deletions(-) rename Penumbra/{Mods/Manager => Api}/ModChangedItemAdapter.cs (95%) diff --git a/Penumbra.Api b/Penumbra.Api index 7ae46f0d..70f04683 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 7ae46f0d09f40b36a5b2d10382db46fbfb729117 +Subproject commit 70f046830cc7cd35b3480b12b7efe94182477fbb diff --git a/Penumbra/Api/Api/CollectionApi.cs b/Penumbra/Api/Api/CollectionApi.cs index 964da1a5..c40feb12 100644 --- a/Penumbra/Api/Api/CollectionApi.cs +++ b/Penumbra/Api/Api/CollectionApi.cs @@ -2,6 +2,7 @@ using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; +using Penumbra.Mods; namespace Penumbra.Api.Api; @@ -23,11 +24,27 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : .Select(c => (c.Identity.Id, c.Identity.Name))); list.AddRange(collections.Storage - .Where(c => string.Equals(c.Identity.Name, identifier, StringComparison.OrdinalIgnoreCase) && !list.Contains((c.Identity.Id, c.Identity.Name))) + .Where(c => string.Equals(c.Identity.Name, identifier, StringComparison.OrdinalIgnoreCase) + && !list.Contains((c.Identity.Id, c.Identity.Name))) .Select(c => (c.Identity.Id, c.Identity.Name))); return list; } + public Func CheckCurrentChangedItemFunc() + { + var weakRef = new WeakReference(collections); + return s => + { + if (!weakRef.TryGetTarget(out var c)) + throw new ObjectDisposedException("The underlying collection storage of this IPC container was disposed."); + + if (!c.Active.Current.ChangedItems.TryGetValue(s, out var d)) + return []; + + return d.Item1.Select(m => (m is Mod mod ? mod.Identifier : string.Empty, m.Name.Text)).ToArray(); + }; + } + public Dictionary GetChangedItemsForCollection(Guid collectionId) { try @@ -74,7 +91,8 @@ public class CollectionApi(CollectionManager collections, ApiHelpers helpers) : } public Guid[] GetCollectionByName(string name) - => collections.Storage.Where(c => string.Equals(name, c.Identity.Name, StringComparison.OrdinalIgnoreCase)).Select(c => c.Identity.Id).ToArray(); + => collections.Storage.Where(c => string.Equals(name, c.Identity.Name, StringComparison.OrdinalIgnoreCase)).Select(c => c.Identity.Id) + .ToArray(); public (PenumbraApiEc, (Guid Id, string Name)? OldCollection) SetCollection(ApiCollectionType type, Guid? collectionId, bool allowCreateNew, bool allowDelete) diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 085e57ca..d54faa6c 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -29,6 +29,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.GetCollectionForObject.Provider(pi, api.Collection), IpcSubscribers.SetCollection.Provider(pi, api.Collection), IpcSubscribers.SetCollectionForObject.Provider(pi, api.Collection), + IpcSubscribers.CheckCurrentChangedItemFunc.Provider(pi, api.Collection), IpcSubscribers.ConvertTextureFile.Provider(pi, api.Editing), IpcSubscribers.ConvertTextureData.Provider(pi, api.Editing), diff --git a/Penumbra/Mods/Manager/ModChangedItemAdapter.cs b/Penumbra/Api/ModChangedItemAdapter.cs similarity index 95% rename from Penumbra/Mods/Manager/ModChangedItemAdapter.cs rename to Penumbra/Api/ModChangedItemAdapter.cs index 8b99cdf2..8842f20a 100644 --- a/Penumbra/Mods/Manager/ModChangedItemAdapter.cs +++ b/Penumbra/Api/ModChangedItemAdapter.cs @@ -1,6 +1,7 @@ using Penumbra.GameData.Data; +using Penumbra.Mods.Manager; -namespace Penumbra.Mods.Manager; +namespace Penumbra.Api; public sealed class ModChangedItemAdapter(WeakReference storage) : IReadOnlyDictionary>, From f89eab8b2bd2b08c48b6608b2b62e042d610f3cc Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 13 Feb 2025 15:42:58 +0000 Subject: [PATCH 1096/1381] [CI] Updating repo.json for testing_1.3.4.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 9ee5b00d..c5402b49 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.0", + "TestingAssemblyVersion": "1.3.4.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 2be5bd06117caa208c51c27a68550a773075abf6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Feb 2025 16:45:46 +0100 Subject: [PATCH 1097/1381] Make EQP swaps also swap multi-slot items correctly. --- Penumbra.GameData | 2 +- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 134 +++++++++++++------- Penumbra/Mods/ItemSwap/ItemSwapContainer.cs | 4 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 10 +- 4 files changed, 93 insertions(+), 57 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 4a987167..f6dff467 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 4a987167b665184d4c05fc9863993981c35a1d19 +Subproject commit f6dff467c7dad6b1213a7d7b65d40a56450f0672 diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index c7e43a26..8c80c91c 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -27,31 +27,31 @@ public static class EquipmentSwap : []; } - public static EquipItem[] CreateTypeSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, + public static HashSet CreateTypeSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, Func redirections, MetaDictionary manips, EquipSlot slotFrom, EquipItem itemFrom, EquipSlot slotTo, EquipItem itemTo) { LookupItem(itemFrom, out var actualSlotFrom, out var idFrom, out var variantFrom); - LookupItem(itemTo, out var actualSlotTo, out var idTo, out var variantTo); + LookupItem(itemTo, out var actualSlotTo, out var idTo, out var variantTo); if (actualSlotFrom != slotFrom.ToSlot() || actualSlotTo != slotTo.ToSlot()) throw new ItemSwap.InvalidItemTypeException(); var (imcFileFrom, variants, affectedItems) = GetVariants(manager, identifier, slotFrom, idFrom, idTo, variantFrom); var imcIdentifierTo = new ImcIdentifier(slotTo, idTo, variantTo); - var imcFileTo = new ImcFile(manager, imcIdentifierTo); + var imcFileTo = new ImcFile(manager, imcIdentifierTo); var imcEntry = manips.TryGetValue(imcIdentifierTo, out var entry) ? entry : imcFileTo.GetEntry(imcIdentifierTo.EquipSlot, imcIdentifierTo.Variant); var mtrlVariantTo = imcEntry.MaterialId; - var skipFemale = false; - var skipMale = false; + var skipFemale = false; + var skipMale = false; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) { - case Gender.Male when skipMale: continue; - case Gender.Female when skipFemale: continue; - case Gender.MaleNpc when skipMale: continue; + case Gender.Male when skipMale: continue; + case Gender.Female when skipFemale: continue; + case Gender.MaleNpc when skipMale: continue; case Gender.FemaleNpc when skipFemale: continue; } @@ -88,30 +88,40 @@ public static class EquipmentSwap return affectedItems; } - public static EquipItem[] CreateItemSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, + public static HashSet CreateItemSwap(MetaFileManager manager, ObjectIdentification identifier, List swaps, Func redirections, MetaDictionary manips, EquipItem itemFrom, EquipItem itemTo, bool rFinger = true, bool lFinger = true) { // Check actual ids, variants and slots. We only support using the same slot. LookupItem(itemFrom, out var slotFrom, out var idFrom, out var variantFrom); - LookupItem(itemTo, out var slotTo, out var idTo, out var variantTo); + LookupItem(itemTo, out var slotTo, out var idTo, out var variantTo); if (slotFrom != slotTo) throw new ItemSwap.InvalidItemTypeException(); - var eqp = CreateEqp(manager, manips, slotFrom, idFrom, idTo); + HashSet affectedItems = []; + var eqp = CreateEqp(manager, manips, slotFrom, idFrom, idTo); if (eqp != null) + { swaps.Add(eqp); + // Add items affected through multi-slot EQP edits. + foreach (var child in eqp.ChildSwaps.SelectMany(c => c.WithChildren()).OfType>()) + { + affectedItems.UnionWith(identifier + .Identify(GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, child.SwapFromIdentifier.Slot)) + .Select(kvp => kvp.Value).OfType().Select(i => i.Item)); + } + } var gmp = CreateGmp(manager, manips, slotFrom, idFrom, idTo); if (gmp != null) swaps.Add(gmp); - var affectedItems = Array.Empty(); foreach (var slot in ConvertSlots(slotFrom, rFinger, lFinger)) { - (var imcFileFrom, var variants, affectedItems) = GetVariants(manager, identifier, slot, idFrom, idTo, variantFrom); + var (imcFileFrom, variants, affectedItemsLocal) = GetVariants(manager, identifier, slot, idFrom, idTo, variantFrom); + affectedItems.UnionWith(affectedItemsLocal); var imcIdentifierTo = new ImcIdentifier(slotTo, idTo, variantTo); - var imcFileTo = new ImcFile(manager, imcIdentifierTo); + var imcFileTo = new ImcFile(manager, imcIdentifierTo); var imcEntry = manips.TryGetValue(imcIdentifierTo, out var entry) ? entry : imcFileTo.GetEntry(imcIdentifierTo.EquipSlot, imcIdentifierTo.Variant); @@ -122,18 +132,18 @@ public static class EquipmentSwap { EquipSlot.Head => EstType.Head, EquipSlot.Body => EstType.Body, - _ => (EstType)0, + _ => (EstType)0, }; var skipFemale = false; - var skipMale = false; + var skipMale = false; foreach (var gr in Enum.GetValues()) { switch (gr.Split().Item1) { - case Gender.Male when skipMale: continue; - case Gender.Female when skipFemale: continue; - case Gender.MaleNpc when skipMale: continue; + case Gender.Male when skipMale: continue; + case Gender.Female when skipFemale: continue; + case Gender.MaleNpc when skipMale: continue; case Gender.FemaleNpc when skipFemale: continue; } @@ -148,7 +158,7 @@ public static class EquipmentSwap swaps.Add(eqdp); var ownMdl = eqdp?.SwapToModdedEntry.Model ?? false; - var est = ItemSwap.CreateEst(manager, redirections, manips, estType, gr, idFrom, idTo, ownMdl); + var est = ItemSwap.CreateEst(manager, redirections, manips, estType, gr, idFrom, idTo, ownMdl); if (est != null) swaps.Add(est); } @@ -176,6 +186,7 @@ public static class EquipmentSwap return affectedItems; } + public static MetaSwap? CreateEqdp(MetaFileManager manager, Func redirections, MetaDictionary manips, EquipSlot slot, GenderRace gr, PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) => CreateEqdp(manager, redirections, manips, slot, slot, gr, idFrom, idTo, mtrlTo); @@ -185,9 +196,9 @@ public static class EquipmentSwap PrimaryId idTo, byte mtrlTo) { var eqdpFromIdentifier = new EqdpIdentifier(idFrom, slotFrom, gr); - var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); - var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); - var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); + var eqdpToIdentifier = new EqdpIdentifier(idTo, slotTo, gr); + var eqdpFromDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpFromIdentifier), slotFrom); + var eqdpToDefault = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(manager, eqdpToIdentifier), slotTo); var meta = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, eqdpFromIdentifier, eqdpFromDefault, eqdpToIdentifier, eqdpToDefault); @@ -216,7 +227,7 @@ public static class EquipmentSwap ? GamePaths.Accessory.Mdl.Path(idFrom, gr, slotFrom) : GamePaths.Equipment.Mdl.Path(idFrom, gr, slotFrom); var mdlPathTo = slotTo.IsAccessory() ? GamePaths.Accessory.Mdl.Path(idTo, gr, slotTo) : GamePaths.Equipment.Mdl.Path(idTo, gr, slotTo); - var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); + var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); foreach (ref var fileName in mdl.AsMdl()!.Materials.AsSpan()) { @@ -238,16 +249,17 @@ public static class EquipmentSwap variant = i.Variant; } - private static (ImcFile, Variant[], EquipItem[]) GetVariants(MetaFileManager manager, ObjectIdentification identifier, EquipSlot slotFrom, + private static (ImcFile, Variant[], HashSet) GetVariants(MetaFileManager manager, ObjectIdentification identifier, + EquipSlot slotFrom, PrimaryId idFrom, PrimaryId idTo, Variant variantFrom) { - var ident = new ImcIdentifier(slotFrom, idFrom, variantFrom); - var imc = new ImcFile(manager, ident); - EquipItem[] items; - Variant[] variants; + var ident = new ImcIdentifier(slotFrom, idFrom, variantFrom); + var imc = new ImcFile(manager, ident); + HashSet items; + Variant[] variants; if (idFrom == idTo) { - items = identifier.Identify(idFrom, 0, variantFrom, slotFrom).ToArray(); + items = identifier.Identify(idFrom, 0, variantFrom, slotFrom).ToHashSet(); variants = [variantFrom]; } else @@ -256,7 +268,7 @@ public static class EquipmentSwap ? GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom) : GamePaths.Accessory.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom)) .Select(kvp => kvp.Value).OfType().Select(i => i.Item) - .ToArray(); + .ToHashSet(); variants = Enumerable.Range(0, imc.Count + 1).Select(i => (Variant)i).ToArray(); } @@ -270,9 +282,9 @@ public static class EquipmentSwap return null; var manipFromIdentifier = new GmpIdentifier(idFrom); - var manipToIdentifier = new GmpIdentifier(idTo); - var manipFromDefault = ExpandedGmpFile.GetDefault(manager, manipFromIdentifier); - var manipToDefault = ExpandedGmpFile.GetDefault(manager, manipToIdentifier); + var manipToIdentifier = new GmpIdentifier(idTo); + var manipFromDefault = ExpandedGmpFile.GetDefault(manager, manipFromIdentifier); + var manipToDefault = ExpandedGmpFile.GetDefault(manager, manipToIdentifier); return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); } @@ -287,9 +299,9 @@ public static class EquipmentSwap Variant variantFrom, Variant variantTo, ImcFile imcFileFrom, ImcFile imcFileTo) { var manipFromIdentifier = new ImcIdentifier(slotFrom, idFrom, variantFrom); - var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); - var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); - var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); + var manipToIdentifier = new ImcIdentifier(slotTo, idTo, variantTo); + var manipFromDefault = imcFileFrom.GetEntry(ImcFile.PartIndex(slotFrom), variantFrom); + var manipToDefault = imcFileTo.GetEntry(ImcFile.PartIndex(slotTo), variantTo); var imc = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); @@ -328,7 +340,7 @@ public static class EquipmentSwap var vfxPathFrom = GamePaths.Equipment.Avfx.Path(idFrom, vfxId); vfxPathFrom = ItemSwap.ReplaceType(vfxPathFrom, slotFrom, slotTo, idFrom); var vfxPathTo = GamePaths.Equipment.Avfx.Path(idTo, vfxId); - var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); + var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); foreach (ref var filePath in avfx.AsAvfx()!.Textures.AsSpan()) { @@ -339,18 +351,42 @@ public static class EquipmentSwap return avfx; } - public static MetaSwap? CreateEqp(MetaFileManager manager, MetaDictionary manips, - EquipSlot slot, PrimaryId idFrom, PrimaryId idTo) + public static MetaSwap? CreateEqp(MetaFileManager manager, MetaDictionary manips, EquipSlot slot, + PrimaryId idFrom, PrimaryId idTo) { if (slot.IsAccessory()) return null; var manipFromIdentifier = new EqpIdentifier(idFrom, slot); - var manipToIdentifier = new EqpIdentifier(idTo, slot); - var manipFromDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idFrom), slot); - var manipToDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idTo), slot); - return new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, + var manipToIdentifier = new EqpIdentifier(idTo, slot); + var manipFromDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idFrom), slot); + var manipToDefault = new EqpEntryInternal(ExpandedEqpFile.GetDefault(manager, idTo), slot); + var swap = new MetaSwap(i => manips.TryGetValue(i, out var e) ? e : null, manipFromIdentifier, manipFromDefault, manipToIdentifier, manipToDefault); + var entry = swap.SwapToModdedEntry.ToEntry(slot); + // Add additional EQP entries if the swapped item is a multi-slot item, + // because those take the EQP entries of their other model-set slots when used. + switch (slot) + { + case EquipSlot.Body: + if (!entry.HasFlag(EqpEntry.BodyShowLeg) + && CreateEqp(manager, manips, EquipSlot.Legs, idFrom, idTo) is { } legChild) + swap.ChildSwaps.Add(legChild); + if (!entry.HasFlag(EqpEntry.BodyShowHead) + && CreateEqp(manager, manips, EquipSlot.Head, idFrom, idTo) is { } headChild) + swap.ChildSwaps.Add(headChild); + if (!entry.HasFlag(EqpEntry.BodyShowHand) + && CreateEqp(manager, manips, EquipSlot.Hands, idFrom, idTo) is { } handChild) + swap.ChildSwaps.Add(handChild); + break; + case EquipSlot.Legs: + if (!entry.HasFlag(EqpEntry.LegsShowFoot) + && CreateEqp(manager, manips, EquipSlot.Feet, idFrom, idTo) is { } footChild) + swap.ChildSwaps.Add(footChild); + break; + } + + return swap; } public static FileSwap? CreateMtrl(MetaFileManager manager, Func redirections, EquipSlot slot, PrimaryId idFrom, @@ -380,7 +416,7 @@ public static class EquipmentSwap if (newFileName != fileName) { - fileName = newFileName; + fileName = newFileName; dataWasChanged = true; } @@ -405,13 +441,13 @@ public static class EquipmentSwap EquipSlot slotTo, PrimaryId idFrom, PrimaryId idTo, ref MtrlFile.Texture texture, ref bool dataWasChanged) { var addedDashes = GamePaths.Tex.HandleDx11Path(texture, out var path); - var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); + var newPath = ItemSwap.ReplaceAnyId(path, prefix, idFrom); newPath = ItemSwap.ReplaceSlot(newPath, slotTo, slotFrom, slotTo != slotFrom); newPath = ItemSwap.ReplaceType(newPath, slotFrom, slotTo, idFrom); newPath = ItemSwap.AddSuffix(newPath, ".tex", $"_{Path.GetFileName(texture.Path).GetStableHashCode():x8}"); if (newPath != path) { - texture.Path = addedDashes ? newPath.Replace("--", string.Empty) : newPath; + texture.Path = addedDashes ? newPath.Replace("--", string.Empty) : newPath; dataWasChanged = true; } @@ -429,8 +465,8 @@ public static class EquipmentSwap PrimaryId idFrom, ref string filePath, ref bool dataWasChanged) { var oldPath = filePath; - filePath = ItemSwap.AddSuffix(filePath, ".atex", $"_{Path.GetFileName(filePath).GetStableHashCode():x8}"); - filePath = ItemSwap.ReplaceType(filePath, slotFrom, slotTo, idFrom); + filePath = ItemSwap.AddSuffix(filePath, ".atex", $"_{Path.GetFileName(filePath).GetStableHashCode():x8}"); + filePath = ItemSwap.ReplaceType(filePath, slotFrom, slotTo, idFrom); dataWasChanged = true; return FileSwap.CreateSwap(manager, ResourceType.Atex, redirections, filePath, oldPath, oldPath); diff --git a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs index d2deb9ef..a9d5e0d6 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwapContainer.cs @@ -127,7 +127,7 @@ public class ItemSwapContainer ? new MetaDictionary(cache) : _appliedModData.Manipulations; - public EquipItem[] LoadEquipment(EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, + public HashSet LoadEquipment(EquipItem from, EquipItem to, ModCollection? collection = null, bool useRightRing = true, bool useLeftRing = true) { Swaps.Clear(); @@ -138,7 +138,7 @@ public class ItemSwapContainer return ret; } - public EquipItem[] LoadTypeSwap(EquipSlot slotFrom, EquipItem from, EquipSlot slotTo, EquipItem to, ModCollection? collection = null) + public HashSet LoadTypeSwap(EquipSlot slotFrom, EquipItem from, EquipSlot slotTo, EquipItem to, ModCollection? collection = null) { Swaps.Clear(); Loaded = false; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index e590eb1e..cb56de08 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -180,7 +180,7 @@ public class ItemSwapTab : IDisposable, ITab, IUiService private bool _useLeftRing = true; private bool _useRightRing = true; - private EquipItem[]? _affectedItems; + private HashSet? _affectedItems; private void UpdateState() { @@ -541,11 +541,11 @@ public class ItemSwapTab : IDisposable, ITab, IUiService _dirty |= selector.Draw("##itemTarget", selector.CurrentSelection.Item.Name, string.Empty, InputWidth * 2 * UiHelpers.Scale, ImGui.GetTextLineHeightWithSpacing()); - if (_affectedItems is not { Length: > 1 }) + if (_affectedItems is not { Count: > 1 }) return; ImGui.SameLine(); - ImGuiUtil.DrawTextButton($"which will also affect {_affectedItems.Length - 1} other Items.", Vector2.Zero, + ImGuiUtil.DrawTextButton($"which will also affect {_affectedItems.Count - 1} other Items.", Vector2.Zero, Colors.PressEnterWarningBg); if (ImGui.IsItemHovered()) ImGui.SetTooltip(string.Join('\n', _affectedItems.Where(i => !ReferenceEquals(i.Name, selector.CurrentSelection.Item.Name)) @@ -602,11 +602,11 @@ public class ItemSwapTab : IDisposable, ITab, IUiService _dirty |= ImGui.Checkbox("Swap Left Ring", ref _useLeftRing); } - if (_affectedItems is not { Length: > 1 }) + if (_affectedItems is not { Count: > 1 }) return; ImGui.SameLine(); - ImGuiUtil.DrawTextButton($"which will also affect {_affectedItems.Length - 1} other Items.", Vector2.Zero, + ImGuiUtil.DrawTextButton($"which will also affect {_affectedItems.Count - 1} other Items.", Vector2.Zero, Colors.PressEnterWarningBg); if (ImGui.IsItemHovered()) ImGui.SetTooltip(string.Join('\n', _affectedItems.Where(i => !ReferenceEquals(i.Name, targetSelector.CurrentSelection.Item.Name)) From 93e184c9a564302dde5434369028033dae037eb3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Feb 2025 16:46:03 +0100 Subject: [PATCH 1098/1381] Add import of .atch files into metadata. --- .../UI/AdvancedWindow/Meta/AtchMetaDrawer.cs | 45 +++++++++++++++++-- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 25 ++++++++++- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs index 4cf01faa..66db0932 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs @@ -1,11 +1,14 @@ using Dalamud.Interface; +using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using Newtonsoft.Json.Linq; +using OtterGui; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Collections.Cache; +using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; using Penumbra.GameData.Files.AtchStructs; @@ -13,6 +16,7 @@ using Penumbra.Meta; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.UI.Classes; +using Notification = OtterGui.Classes.Notification; namespace Penumbra.UI.AdvancedWindow.Meta; @@ -27,9 +31,9 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer public override float ColumnHeight => 2 * ImUtf8.FrameHeightSpacing; - private AtchFile? _currentBaseAtchFile; - private AtchPoint? _currentBaseAtchPoint; - private AtchPointCombo _combo; + private AtchFile? _currentBaseAtchFile; + private AtchPoint? _currentBaseAtchPoint; + private readonly AtchPointCombo _combo; public AtchMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) : base(editor, metaFiles) @@ -44,6 +48,41 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer => obj.ToName(); } + public void ImportFile(string filePath) + { + try + { + if (filePath.Length == 0 || !File.Exists(filePath)) + throw new FileNotFoundException(); + + var gr = GamePaths.ParseRaceCode(filePath); + if (gr is GenderRace.Unknown) + throw new Exception($"Could not identify race code from path {filePath}."); + var text = File.ReadAllBytes(filePath); + var file = new AtchFile(text); + foreach (var point in file.Points) + { + foreach (var (entry, index) in point.Entries.WithIndex()) + { + var identifier = new AtchIdentifier(point.Type, gr, (ushort) index); + var defaultValue = AtchCache.GetDefault(MetaFiles, identifier); + if (defaultValue == null) + continue; + + if (defaultValue.Value.Equals(entry)) + Editor.Changes |= Editor.Remove(identifier); + else + Editor.Changes |= Editor.TryAdd(identifier, entry) || Editor.Update(identifier, entry); + } + } + } + catch (Exception ex) + { + Penumbra.Messager.AddMessage(new Notification(ex, "Unable to import .atch file.", "Could not import .atch file:", + NotificationType.Warning)); + } + } + protected override void DrawNew() { diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 7d688df9..1356340c 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -4,6 +4,8 @@ using OtterGui; using OtterGui.Raii; using OtterGui.Text; using Penumbra.Api.Api; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; using Penumbra.Meta.Manipulations; using Penumbra.UI.AdvancedWindow.Meta; using Penumbra.UI.Classes; @@ -43,8 +45,10 @@ public partial class ModEditWindow if (ImUtf8.Button("Write as TexTools Files"u8)) _metaFileManager.WriteAllTexToolsMeta(Mod!); ImGui.SameLine(); - if (ImUtf8.ButtonEx("Remove All Default-Values", "Delete any entries from all lists that set the value to its default value."u8)) + if (ImUtf8.ButtonEx("Remove All Default-Values"u8, "Delete any entries from all lists that set the value to its default value."u8)) _editor.MetaEditor.DeleteDefaultValues(); + ImGui.SameLine(); + DrawAtchDragDrop(); using var child = ImRaii.Child("##meta", -Vector2.One, true); if (!child) @@ -60,6 +64,25 @@ public partial class ModEditWindow DrawEditHeader(MetaManipulationType.GlobalEqp); } + private void DrawAtchDragDrop() + { + _dragDropManager.CreateImGuiSource("atchDrag", f => f.Extensions.Contains(".atch"), f => + { + var gr = GamePaths.ParseRaceCode(f.Files.FirstOrDefault() ?? string.Empty); + if (gr is GenderRace.Unknown) + return false; + + ImUtf8.Text($"Dragging .atch for {gr.ToName()}..."); + return true; + }); + ImUtf8.ButtonEx("Import .atch"u8, + _dragDropManager.IsDragging ? ""u8 : "Drag a .atch file containinig its race code in the path here to import its values."u8, + default, + !_dragDropManager.IsDragging); + if (_dragDropManager.CreateImGuiTarget("atchDrag", out var files, out _) && files.FirstOrDefault() is { } file) + _metaDrawers.Atch.ImportFile(file); + } + private void DrawEditHeader(MetaManipulationType type) { var drawer = _metaDrawers.Get(type); From 40f24344af122eb4bb8bc3e0d5afdcd9c3395477 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 15 Feb 2025 16:46:31 +0100 Subject: [PATCH 1099/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 3c1260c9..0b6085ce 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3c1260c9833303c2d33d12d6f77dc2b1afea3f34 +Subproject commit 0b6085ce720ffb7c78cf42d4e51861f34db27744 From 79938b6dd01a914cb13dcd833c3f2d97de0372da Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 15 Feb 2025 15:50:18 +0000 Subject: [PATCH 1100/1381] [CI] Updating repo.json for testing_1.3.4.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index c5402b49..fdb0b638 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.1", + "TestingAssemblyVersion": "1.3.4.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From b7b9defaa6f8d861841cb134dfbb3ef161c24bda Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 17 Feb 2025 17:38:42 +0100 Subject: [PATCH 1101/1381] Add context menu to clear temporary settings. --- Penumbra/Api/Api/TemporaryApi.cs | 14 +++----------- Penumbra/Collections/Manager/CollectionEditor.cs | 14 ++++++++++++++ Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 9 ++++++++- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index d951639c..a997ded8 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -130,8 +130,8 @@ public class TemporaryApi( return ApiHelpers.Return(ret, args); } - public (PenumbraApiEc, (bool, bool, int, Dictionary>)?, string) QueryTemporaryModSettings(Guid collectionId, string modDirectory, - string modName, int key) + public (PenumbraApiEc, (bool, bool, int, Dictionary>)?, string) QueryTemporaryModSettings(Guid collectionId, + string modDirectory, string modName, int key) { var args = ApiHelpers.Args("CollectionId", collectionId, "ModDirectory", modDirectory, "ModName", modName); if (!collectionManager.Storage.ById(collectionId, out var collection)) @@ -296,15 +296,7 @@ public class TemporaryApi( if (collection.Identity.Index <= 0) return ApiHelpers.Return(PenumbraApiEc.NothingChanged, args); - var numRemoved = 0; - for (var i = 0; i < collection.Settings.Count; ++i) - { - if (collection.GetTempSettings(i) is { } tempSettings - && tempSettings.Lock == key - && collectionManager.Editor.SetTemporarySettings(collection, modManager[i], null, key)) - ++numRemoved; - } - + var numRemoved = collectionManager.Editor.ClearTemporarySettings(collection, key); return ApiHelpers.Return(numRemoved > 0 ? PenumbraApiEc.Success : PenumbraApiEc.NothingChanged, args); } diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index f4902fda..5ccc38e2 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -114,6 +114,20 @@ public class CollectionEditor(SaveService saveService, CommunicatorService commu return true; } + public int ClearTemporarySettings(ModCollection collection, int key = 0) + { + var numRemoved = 0; + for (var i = 0; i < collection.Settings.Count; ++i) + { + if (collection.GetTempSettings(i) is { } tempSettings + && tempSettings.Lock == key + && SetTemporarySettings(collection, modStorage[i], null, key)) + ++numRemoved; + } + + return numRemoved; + } + public bool CanSetTemporarySettings(ModCollection collection, Mod mod, int key) { var old = collection.GetTempSettings(mod.Index); diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 1a7d4e31..0a68c077 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -64,6 +64,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector QuickMove(l, _config.QuickMoveFolder1, _config.QuickMoveFolder2, _config.QuickMoveFolder3)); + SubscribeRightClickMain(ClearTemporarySettings, 105); SubscribeRightClickMain(ClearDefaultImportFolder, 100); SubscribeRightClickMain(() => ClearQuickMove(0, _config.QuickMoveFolder1, () => {_config.QuickMoveFolder1 = string.Empty; _config.Save();}), 110); SubscribeRightClickMain(() => ClearQuickMove(1, _config.QuickMoveFolder2, () => {_config.QuickMoveFolder2 = string.Empty; _config.Save();}), 120); @@ -237,10 +238,16 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Mon, 17 Feb 2025 17:39:41 +0100 Subject: [PATCH 1102/1381] Add option to always work in temporary settings. --- Penumbra/Configuration.cs | 1 + .../Mods/Settings/TemporaryModSettings.cs | 9 ++-- Penumbra/UI/Classes/CollectionSelectHeader.cs | 43 ++++++++++++++++--- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 9 ++-- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 11 +++-- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 27 ++++++------ Penumbra/UI/Tabs/SettingsTab.cs | 4 +- 7 files changed, 72 insertions(+), 32 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index df44a51a..ce86dd4a 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -70,6 +70,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HidePrioritiesInSelector { get; set; } = false; public bool HideRedrawBar { get; set; } = false; public bool HideMachinistOffhandFromChangedItems { get; set; } = true; + public bool DefaultTemporaryMode { get; set; } = false; public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; public int OptionGroupCollapsibleMin { get; set; } = 5; diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index fa71e1b6..a16a9feb 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -2,9 +2,10 @@ namespace Penumbra.Mods.Settings; public sealed class TemporaryModSettings : ModSettings { - public string Source = string.Empty; - public int Lock = 0; - public bool ForceInherit; + public const string OwnSource = "yourself"; + public string Source = string.Empty; + public int Lock = 0; + public bool ForceInherit; // Create default settings for a given mod. public static TemporaryModSettings DefaultSettings(Mod mod, string source, bool enabled = false, int key = 0) @@ -20,7 +21,7 @@ public sealed class TemporaryModSettings : ModSettings public TemporaryModSettings() { } - public TemporaryModSettings(Mod mod, ModSettings? clone, string source, int key = 0) + public TemporaryModSettings(Mod mod, ModSettings? clone, string source = OwnSource, int key = 0) { Source = source; Lock = key; diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index 0e1408c5..54fcf279 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -1,7 +1,10 @@ +using Dalamud.Interface; using ImGuiNET; using OtterGui.Raii; using OtterGui; using OtterGui.Services; +using OtterGui.Text; +using OtterGui.Text.Widget; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; @@ -12,18 +15,21 @@ namespace Penumbra.UI.Classes; public class CollectionSelectHeader : IUiService { - private readonly CollectionCombo _collectionCombo; - private readonly ActiveCollections _activeCollections; - private readonly TutorialService _tutorial; - private readonly ModSelection _selection; - private readonly CollectionResolver _resolver; + private readonly CollectionCombo _collectionCombo; + private readonly ActiveCollections _activeCollections; + private readonly TutorialService _tutorial; + private readonly ModSelection _selection; + private readonly CollectionResolver _resolver; + private readonly FontAwesomeCheckbox _temporaryCheckbox = new(FontAwesomeIcon.Stopwatch); + private readonly Configuration _config; public CollectionSelectHeader(CollectionManager collectionManager, TutorialService tutorial, ModSelection selection, - CollectionResolver resolver) + CollectionResolver resolver, Configuration config) { _tutorial = tutorial; _selection = selection; _resolver = resolver; + _config = config; _activeCollections = collectionManager.Active; _collectionCombo = new CollectionCombo(collectionManager, () => collectionManager.Storage.OrderBy(c => c.Identity.Name).ToList()); } @@ -33,6 +39,8 @@ public class CollectionSelectHeader : IUiService { using var style = ImRaii.PushStyle(ImGuiStyleVar.FrameRounding, 0) .Push(ImGuiStyleVar.ItemSpacing, new Vector2(0, spacing ? ImGui.GetStyle().ItemSpacing.Y : 0)); + DrawTemporaryCheckbox(); + ImGui.SameLine(); var comboWidth = ImGui.GetContentRegionAvail().X / 4f; var buttonSize = new Vector2(comboWidth * 3f / 4f, 0f); using (var _ = ImRaii.Group()) @@ -51,6 +59,29 @@ public class CollectionSelectHeader : IUiService ImGuiUtil.DrawTextButton("The currently selected collection is not used in any way.", -Vector2.UnitX, Colors.PressEnterWarningBg); } + private void DrawTemporaryCheckbox() + { + var hold = _config.DeleteModModifier.IsActive(); + using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImUtf8.GlobalScale)) + { + var tint = ImGuiCol.Text.Tinted(ColorId.TemporaryModSettingsTint); + using var color = ImRaii.PushColor(ImGuiCol.FrameBgHovered, ImGui.GetColorU32(ImGuiCol.FrameBg), !hold) + .Push(ImGuiCol.FrameBgActive, ImGui.GetColorU32(ImGuiCol.FrameBg), !hold) + .Push(ImGuiCol.CheckMark, tint) + .Push(ImGuiCol.Border, tint, _config.DefaultTemporaryMode); + if (_temporaryCheckbox.Draw("##tempCheck"u8, _config.DefaultTemporaryMode, out var newValue) && hold) + { + _config.DefaultTemporaryMode = newValue; + _config.Save(); + } + } + + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, + "Toggle the temporary settings mode, where all changes you do create temporary settings first and need to be made permanent if desired.\n"u8); + if (!hold) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking to toggle."); + } + private enum CollectionState { Empty, diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index b723978b..8dee13bf 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -20,6 +20,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle private bool _temporary; private bool _locked; private TemporaryModSettings? _tempSettings; + private ModSettings? _settings; public void Draw(Mod mod, ModSettings settings, TemporaryModSettings? tempSettings) { @@ -27,6 +28,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle return; _blockGroupCache.Clear(); + _settings = settings; _tempSettings = tempSettings; _temporary = tempSettings != null; _locked = (tempSettings?.Lock ?? 0) > 0; @@ -242,10 +244,11 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void SetModSetting(IModGroup group, int groupIdx, Setting setting) { - if (_temporary) + if (_temporary || config.DefaultTemporaryMode) { - _tempSettings!.ForceInherit = false; - _tempSettings!.Settings[groupIdx] = setting; + _tempSettings ??= new TemporaryModSettings(group.Mod, _settings); + _tempSettings!.ForceInherit = false; + _tempSettings!.Settings[groupIdx] = setting; collectionManager.Editor.SetTemporarySettings(Current, group.Mod, _tempSettings); } else diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 0a68c077..a0383329 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -274,8 +274,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector.Leaf mod) { - const string source = "yourself"; - var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); + var tempSettings = _collectionManager.Active.Current.GetTempSettings(mod.Value.Index); if (tempSettings is { Lock: > 0 }) return; @@ -284,19 +283,19 @@ public sealed class ModFileSystemSelector : FileSystemSelector _config.PrintSuccessfulCommandsToChat = v); @@ -618,6 +617,9 @@ public class SettingsTab : ITab, IUiService /// Draw all settings pertaining to import and export of mods. private void DrawModHandlingSettings() { + Checkbox("Use Temporary Settings Per Default", + "When you make any changes to your collection, apply them as temporary changes first and require a click to 'turn permanent' if you want to keep them.", + _config.DefaultTemporaryMode, v => _config.DefaultTemporaryMode = v); Checkbox("Replace Non-Standard Symbols On Import", "Replace all non-ASCII symbols in mod and option names with underscores when importing mods.", _config.ReplaceNonAsciiOnImport, v => _config.ReplaceNonAsciiOnImport = v); From 41672c31ce0e63f07c3c46e9c903ae05442dc0a1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 18 Feb 2025 15:10:16 +0100 Subject: [PATCH 1103/1381] Update message slightly. --- Penumbra/Collections/Cache/CollectionCache.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 3f0ed27b..a80928d0 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -282,11 +282,11 @@ public sealed class CollectionCache : IDisposable { case ".atch" or ".eqp" or ".eqdp" or ".est" or ".gmp" or ".cmp" or ".imc": Penumbra.Messager.NotificationMessage( - $"Redirection of {ext} files for {mod.Name} is unsupported. Please use the corresponding meta manipulations instead.", + $"Redirection of {ext} files for {mod.Name} is unsupported. This probably means that the mod is outdated and may not work correctly.\n\nPlease tell the mod creator to use the corresponding meta manipulations instead.", NotificationType.Warning); return false; case ".lvb" or ".lgb" or ".sgb": - Penumbra.Messager.NotificationMessage($"Redirection of {ext} files for {mod.Name} is unsupported as this breaks the game.", + Penumbra.Messager.NotificationMessage($"Redirection of {ext} files for {mod.Name} is unsupported as this breaks the game.\n\nThis mod will probably not work correctly.", NotificationType.Warning); return false; default: return true; From a73dee83b309104600f326d45e46f6fd9ab2180c Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 18 Feb 2025 14:12:54 +0000 Subject: [PATCH 1104/1381] [CI] Updating repo.json for testing_1.3.4.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index fdb0b638..c46f3d27 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.2", + "TestingAssemblyVersion": "1.3.4.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From ef26049c53d57cb5625f9dab476d5c61ae1c904b Mon Sep 17 00:00:00 2001 From: Adam Moy Date: Wed, 5 Feb 2025 11:25:09 -0600 Subject: [PATCH 1105/1381] Consider VertexElement's UsageIndex Allows VertexDeclarations to have multiple VertexElements of the same Type but different UsageIndex --- Penumbra/Import/Models/Export/MeshExporter.cs | 117 ++++++++++++------ .../Import/Models/Export/VertexFragment.cs | 109 ++++++++++++++++ 2 files changed, 187 insertions(+), 39 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 73160615..0dc8a9ac 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -82,13 +82,16 @@ public class MeshExporter if (skeleton != null) _boneIndexMap = BuildBoneIndexMap(skeleton.Value); + var usages = new Dictionary>(); - var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements - .ToImmutableDictionary( - element => (MdlFile.VertexUsage)element.Usage, - element => (MdlFile.VertexType)element.Type - ); - + foreach (var element in _mdl.VertexDeclarations[_meshIndex].VertexElements) + { + if (!usages.ContainsKey((MdlFile.VertexUsage)element.Usage)) + { + usages.Add((MdlFile.VertexUsage)element.Usage, new Dictionary()); + } + usages[(MdlFile.VertexUsage)element.Usage][element.UsageIndex] = (MdlFile.VertexType)element.Type; + } _geometryType = GetGeometryType(usages); _materialType = GetMaterialType(usages); _skinningType = GetSkinningType(usages); @@ -104,14 +107,20 @@ public class MeshExporter /// Build a mapping between indices in this mesh's bone table (if any), and the glTF joint indices provided. private Dictionary? BuildBoneIndexMap(GltfSkeleton skeleton) { + Penumbra.Log.Debug("Building Bone Index Map"); // A BoneTableIndex of 255 means that this mesh is not skinned. if (XivMesh.BoneTableIndex == 255) + { + Penumbra.Log.Debug("BoneTableIndex was 255"); return null; + } var xivBoneTable = _mdl.BoneTables[XivMesh.BoneTableIndex]; var indexMap = new Dictionary(); // #TODO @ackwell maybe fix for V6 Models, I think this works fine. + Penumbra.Log.Debug($"Version is 5 {_mdl.Version == MdlFile.V5}"); + foreach (var (xivBoneIndex, tableIndex) in xivBoneTable.BoneIndex.Take((int)xivBoneTable.BoneCount).WithIndex()) { var boneName = _mdl.Bones[xivBoneIndex]; @@ -283,13 +292,20 @@ public class MeshExporter var vertices = new List(); - var attributes = new Dictionary(); + var attributes = new Dictionary>(); for (var vertexIndex = 0; vertexIndex < XivMesh.VertexCount; vertexIndex++) { attributes.Clear(); - foreach (var (usage, element) in sortedElements) - attributes[usage] = ReadVertexAttribute((MdlFile.VertexType)element.Type, streams[element.Stream]); + { + if (!attributes.TryGetValue(usage, out var value)) + { + value = new Dictionary(); + attributes[usage] = value; + } + + value[element.UsageIndex] = ReadVertexAttribute((MdlFile.VertexType)element.Type, streams[element.Stream]); + } var vertexGeometry = BuildVertexGeometry(attributes); var vertexMaterial = BuildVertexMaterial(attributes); @@ -320,7 +336,7 @@ public class MeshExporter } /// Get the vertex geometry type for this mesh's vertex usages. - private Type GetGeometryType(IReadOnlyDictionary usages) + private Type GetGeometryType(IReadOnlyDictionary> usages) { if (!usages.ContainsKey(MdlFile.VertexUsage.Position)) throw _notifier.Exception("Mesh does not contain position vertex elements."); @@ -335,28 +351,28 @@ public class MeshExporter } /// Build a geometry vertex from a vertex's attributes. - private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary attributes) + private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary> attributes) { if (_geometryType == typeof(VertexPosition)) return new VertexPosition( - ToVector3(attributes[MdlFile.VertexUsage.Position]) + ToVector3(attributes[MdlFile.VertexUsage.Position][0]) ); if (_geometryType == typeof(VertexPositionNormal)) return new VertexPositionNormal( - ToVector3(attributes[MdlFile.VertexUsage.Position]), - ToVector3(attributes[MdlFile.VertexUsage.Normal]) + ToVector3(attributes[MdlFile.VertexUsage.Position][0]), + ToVector3(attributes[MdlFile.VertexUsage.Normal][0]) ); if (_geometryType == typeof(VertexPositionNormalTangent)) { // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. // TODO: While this assumption is safe, it would be sensible to actually check. - var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1]) * 2 - Vector4.One; + var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1][0]) * 2 - Vector4.One; return new VertexPositionNormalTangent( - ToVector3(attributes[MdlFile.VertexUsage.Position]), - ToVector3(attributes[MdlFile.VertexUsage.Normal]), + ToVector3(attributes[MdlFile.VertexUsage.Position][0]), + ToVector3(attributes[MdlFile.VertexUsage.Normal][0]), bitangent ); } @@ -365,18 +381,23 @@ public class MeshExporter } /// Get the vertex material type for this mesh's vertex usages. - private Type GetMaterialType(IReadOnlyDictionary usages) + private Type GetMaterialType(IReadOnlyDictionary> usages) { var uvCount = 0; - if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var type)) - uvCount = type switch + if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var dict)) + { + foreach (var type in dict.Values) { - MdlFile.VertexType.Half2 => 1, - MdlFile.VertexType.Half4 => 2, - MdlFile.VertexType.Single2 => 1, - MdlFile.VertexType.Single4 => 2, - _ => throw _notifier.Exception($"Unexpected UV vertex type {type}."), - }; + uvCount += type switch + { + MdlFile.VertexType.Half2 => 1, + MdlFile.VertexType.Half4 => 2, + MdlFile.VertexType.Single2 => 1, + MdlFile.VertexType.Single4 => 2, + _ => throw _notifier.Exception($"Unexpected UV vertex type {type}."), + }; + } + } var materialUsages = ( uvCount, @@ -385,6 +406,8 @@ public class MeshExporter return materialUsages switch { + (3, true) => typeof(VertexTexture3ColorFfxiv), + (3, false) => typeof(VertexTexture3), (2, true) => typeof(VertexTexture2ColorFfxiv), (2, false) => typeof(VertexTexture2), (1, true) => typeof(VertexTexture1ColorFfxiv), @@ -397,28 +420,28 @@ public class MeshExporter } /// Build a material vertex from a vertex's attributes. - private IVertexMaterial BuildVertexMaterial(IReadOnlyDictionary attributes) + private IVertexMaterial BuildVertexMaterial(IReadOnlyDictionary> attributes) { if (_materialType == typeof(VertexEmpty)) return new VertexEmpty(); if (_materialType == typeof(VertexColorFfxiv)) - return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color])); + return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color][0])); if (_materialType == typeof(VertexTexture1)) - return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV])); + return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV][0])); if (_materialType == typeof(VertexTexture1ColorFfxiv)) return new VertexTexture1ColorFfxiv( - ToVector2(attributes[MdlFile.VertexUsage.UV]), - ToVector4(attributes[MdlFile.VertexUsage.Color]) + ToVector2(attributes[MdlFile.VertexUsage.UV][0]), + ToVector4(attributes[MdlFile.VertexUsage.Color][0]) ); // XIV packs two UVs into a single vec4 attribute. if (_materialType == typeof(VertexTexture2)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV]); + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); return new VertexTexture2( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W) @@ -427,11 +450,27 @@ public class MeshExporter if (_materialType == typeof(VertexTexture2ColorFfxiv)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV]); + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); return new VertexTexture2ColorFfxiv( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W), - ToVector4(attributes[MdlFile.VertexUsage.Color]) + ToVector4(attributes[MdlFile.VertexUsage.Color][0]) + ); + } + if (_materialType == typeof(VertexTexture3)) + { + throw _notifier.Exception("Unimplemented: Material Type is VertexTexture3"); + } + + if (_materialType == typeof(VertexTexture3ColorFfxiv)) + { + var uv0 = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); + var uv1 = ToVector4(attributes[MdlFile.VertexUsage.UV][1]); + return new VertexTexture3ColorFfxiv( + new Vector2(uv0.X, uv0.Y), + new Vector2(uv0.Z, uv0.W), + new Vector2(uv1.X, uv1.Y), + ToVector4(attributes[MdlFile.VertexUsage.Color][0]) ); } @@ -439,11 +478,11 @@ public class MeshExporter } /// Get the vertex skinning type for this mesh's vertex usages. - private static Type GetSkinningType(IReadOnlyDictionary usages) + private static Type GetSkinningType(IReadOnlyDictionary> usages) { if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) { - if (usages[MdlFile.VertexUsage.BlendWeights] == MdlFile.VertexType.UShort4) + if (usages[MdlFile.VertexUsage.BlendWeights][0] == MdlFile.VertexType.UShort4) { return typeof(VertexJoints8); } @@ -457,7 +496,7 @@ public class MeshExporter } /// Build a skinning vertex from a vertex's attributes. - private IVertexSkinning BuildVertexSkinning(IReadOnlyDictionary attributes) + private IVertexSkinning BuildVertexSkinning(IReadOnlyDictionary> attributes) { if (_skinningType == typeof(VertexEmpty)) return new VertexEmpty(); @@ -467,8 +506,8 @@ public class MeshExporter if (_boneIndexMap == null) throw _notifier.Exception("Tried to build skinned vertex but no bone mappings are available."); - var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices]; - var weightsData = attributes[MdlFile.VertexUsage.BlendWeights]; + var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices][0]; + var weightsData = attributes[MdlFile.VertexUsage.BlendWeights][0]; var indices = ToByteArray(indiciesData); var weights = ToFloatArray(weightsData); diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index eff34d54..c9b97997 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -282,3 +282,112 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom throw new ArgumentOutOfRangeException(nameof(FfxivColor)); } } + +public struct VertexTexture3ColorFfxiv : IVertexCustom +{ + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("TEXCOORD_0", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("TEXCOORD_1", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("TEXCOORD_2", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("_FFXIV_COLOR", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + + public Vector2 TexCoord0; + public Vector2 TexCoord1; + public Vector2 TexCoord2; + public Vector4 FfxivColor; + + public int MaxColors + => 0; + + public int MaxTextCoords + => 3; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR"]; + + public IEnumerable CustomAttributes + => CustomNames; + + public VertexTexture3ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector2 texCoord2, Vector4 ffxivColor) + { + TexCoord0 = texCoord0; + TexCoord1 = texCoord1; + TexCoord2 = texCoord2; + FfxivColor = ffxivColor; + } + + public void Add(in VertexMaterialDelta delta) + { + TexCoord0 += delta.TexCoord0Delta; + TexCoord1 += delta.TexCoord1Delta; + TexCoord2 += delta.TexCoord2Delta; + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + => new(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), TexCoord1 - baseValue.GetTexCoord(1)); + + public Vector2 GetTexCoord(int index) + => index switch + { + 0 => TexCoord0, + 1 => TexCoord1, + 2 => TexCoord2, + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + public void SetTexCoord(int setIndex, Vector2 coord) + { + if (setIndex == 0) + TexCoord0 = coord; + if (setIndex == 1) + TexCoord1 = coord; + if (setIndex == 2) + TexCoord2 = coord; + if (setIndex >= 3) + throw new ArgumentOutOfRangeException(nameof(setIndex)); + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR": + value = FfxivColor; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + if (attributeName == "_FFXIV_COLOR" && value is Vector4 valueVector4) + FfxivColor = valueVector4; + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { } + + public void Validate() + { + var components = new[] + { + FfxivColor.X, + FfxivColor.Y, + FfxivColor.Z, + FfxivColor.W, + }; + if (components.Any(component => component < 0 || component > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor)); + } +} From 2f0bf19d00f9047817fb8bbfba38e5471f14bb20 Mon Sep 17 00:00:00 2001 From: Adam Moy Date: Wed, 12 Feb 2025 09:48:22 -0600 Subject: [PATCH 1106/1381] Use First().Value --- Penumbra/Import/Models/Export/MeshExporter.cs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 0dc8a9ac..48f66177 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -355,24 +355,24 @@ public class MeshExporter { if (_geometryType == typeof(VertexPosition)) return new VertexPosition( - ToVector3(attributes[MdlFile.VertexUsage.Position][0]) + ToVector3(attributes[MdlFile.VertexUsage.Position].First().Value) ); if (_geometryType == typeof(VertexPositionNormal)) return new VertexPositionNormal( - ToVector3(attributes[MdlFile.VertexUsage.Position][0]), - ToVector3(attributes[MdlFile.VertexUsage.Normal][0]) + ToVector3(attributes[MdlFile.VertexUsage.Position].First().Value), + ToVector3(attributes[MdlFile.VertexUsage.Normal].First().Value) ); if (_geometryType == typeof(VertexPositionNormalTangent)) { // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. // TODO: While this assumption is safe, it would be sensible to actually check. - var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1][0]) * 2 - Vector4.One; + var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1].First().Value) * 2 - Vector4.One; return new VertexPositionNormalTangent( - ToVector3(attributes[MdlFile.VertexUsage.Position][0]), - ToVector3(attributes[MdlFile.VertexUsage.Normal][0]), + ToVector3(attributes[MdlFile.VertexUsage.Position].First().Value), + ToVector3(attributes[MdlFile.VertexUsage.Normal].First().Value), bitangent ); } @@ -426,22 +426,22 @@ public class MeshExporter return new VertexEmpty(); if (_materialType == typeof(VertexColorFfxiv)) - return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color][0])); + return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value)); if (_materialType == typeof(VertexTexture1)) - return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV][0])); + return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV].First().Value)); if (_materialType == typeof(VertexTexture1ColorFfxiv)) return new VertexTexture1ColorFfxiv( - ToVector2(attributes[MdlFile.VertexUsage.UV][0]), - ToVector4(attributes[MdlFile.VertexUsage.Color][0]) + ToVector2(attributes[MdlFile.VertexUsage.UV].First().Value), + ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value) ); // XIV packs two UVs into a single vec4 attribute. if (_materialType == typeof(VertexTexture2)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First().Value); return new VertexTexture2( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W) @@ -450,11 +450,11 @@ public class MeshExporter if (_materialType == typeof(VertexTexture2ColorFfxiv)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First().Value); return new VertexTexture2ColorFfxiv( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W), - ToVector4(attributes[MdlFile.VertexUsage.Color][0]) + ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value) ); } if (_materialType == typeof(VertexTexture3)) @@ -470,7 +470,7 @@ public class MeshExporter new Vector2(uv0.X, uv0.Y), new Vector2(uv0.Z, uv0.W), new Vector2(uv1.X, uv1.Y), - ToVector4(attributes[MdlFile.VertexUsage.Color][0]) + ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value) ); } @@ -482,7 +482,7 @@ public class MeshExporter { if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) { - if (usages[MdlFile.VertexUsage.BlendWeights][0] == MdlFile.VertexType.UShort4) + if (usages[MdlFile.VertexUsage.BlendWeights].First().Value == MdlFile.VertexType.UShort4) { return typeof(VertexJoints8); } @@ -506,8 +506,8 @@ public class MeshExporter if (_boneIndexMap == null) throw _notifier.Exception("Tried to build skinned vertex but no bone mappings are available."); - var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices][0]; - var weightsData = attributes[MdlFile.VertexUsage.BlendWeights][0]; + var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices].First().Value; + var weightsData = attributes[MdlFile.VertexUsage.BlendWeights].First().Value; var indices = ToByteArray(indiciesData); var weights = ToFloatArray(weightsData); From 579969a9e107e9a7b4b7adfef5f419cbed648899 Mon Sep 17 00:00:00 2001 From: Adam Moy Date: Wed, 12 Feb 2025 12:45:15 -0600 Subject: [PATCH 1107/1381] Using LINQ And also change types from using LINQ --- Penumbra/Import/Models/Export/MeshExporter.cs | 91 +++++++++---------- 1 file changed, 44 insertions(+), 47 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 48f66177..fb88dfc3 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -82,16 +82,16 @@ public class MeshExporter if (skeleton != null) _boneIndexMap = BuildBoneIndexMap(skeleton.Value); - var usages = new Dictionary>(); - foreach (var element in _mdl.VertexDeclarations[_meshIndex].VertexElements) - { - if (!usages.ContainsKey((MdlFile.VertexUsage)element.Usage)) - { - usages.Add((MdlFile.VertexUsage)element.Usage, new Dictionary()); - } - usages[(MdlFile.VertexUsage)element.Usage][element.UsageIndex] = (MdlFile.VertexType)element.Type; - } + var usages = _mdl.VertexDeclarations[_meshIndex].VertexElements + .GroupBy(ele => (MdlFile.VertexUsage)ele.Usage, ele => ele) + .ToImmutableDictionary( + g => g.Key, + g => g.OrderBy(ele => ele.UsageIndex) // OrderBy UsageIndex is probably unnecessary as they're probably already be in order + .Select(ele => (MdlFile.VertexType)ele.Type) + .ToList() + ); + _geometryType = GetGeometryType(usages); _materialType = GetMaterialType(usages); _skinningType = GetSkinningType(usages); @@ -287,25 +287,22 @@ public class MeshExporter var sortedElements = _mdl.VertexDeclarations[_meshIndex].VertexElements .OrderBy(element => element.Offset) - .Select(element => ((MdlFile.VertexUsage)element.Usage, element)) .ToList(); - var vertices = new List(); - var attributes = new Dictionary>(); + var attributes = new Dictionary>(); for (var vertexIndex = 0; vertexIndex < XivMesh.VertexCount; vertexIndex++) { attributes.Clear(); - foreach (var (usage, element) in sortedElements) - { - if (!attributes.TryGetValue(usage, out var value)) - { - value = new Dictionary(); - attributes[usage] = value; - } - - value[element.UsageIndex] = ReadVertexAttribute((MdlFile.VertexType)element.Type, streams[element.Stream]); - } + attributes = sortedElements + .GroupBy(element => element.Usage) + .ToDictionary( + x => (MdlFile.VertexUsage)x.Key, + x => x.OrderBy(ele => ele.UsageIndex) // Once again, OrderBy UsageIndex is probably unnecessary + .Select(ele => ReadVertexAttribute((MdlFile.VertexType)ele.Type, streams[ele.Stream])) + .ToList() + ); + var vertexGeometry = BuildVertexGeometry(attributes); var vertexMaterial = BuildVertexMaterial(attributes); @@ -336,7 +333,7 @@ public class MeshExporter } /// Get the vertex geometry type for this mesh's vertex usages. - private Type GetGeometryType(IReadOnlyDictionary> usages) + private Type GetGeometryType(IReadOnlyDictionary> usages) { if (!usages.ContainsKey(MdlFile.VertexUsage.Position)) throw _notifier.Exception("Mesh does not contain position vertex elements."); @@ -351,28 +348,28 @@ public class MeshExporter } /// Build a geometry vertex from a vertex's attributes. - private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary> attributes) + private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary> attributes) { if (_geometryType == typeof(VertexPosition)) return new VertexPosition( - ToVector3(attributes[MdlFile.VertexUsage.Position].First().Value) + ToVector3(attributes[MdlFile.VertexUsage.Position].First()) ); if (_geometryType == typeof(VertexPositionNormal)) return new VertexPositionNormal( - ToVector3(attributes[MdlFile.VertexUsage.Position].First().Value), - ToVector3(attributes[MdlFile.VertexUsage.Normal].First().Value) + ToVector3(attributes[MdlFile.VertexUsage.Position].First()), + ToVector3(attributes[MdlFile.VertexUsage.Normal].First()) ); if (_geometryType == typeof(VertexPositionNormalTangent)) { // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. // TODO: While this assumption is safe, it would be sensible to actually check. - var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1].First().Value) * 2 - Vector4.One; + var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1].First()) * 2 - Vector4.One; return new VertexPositionNormalTangent( - ToVector3(attributes[MdlFile.VertexUsage.Position].First().Value), - ToVector3(attributes[MdlFile.VertexUsage.Normal].First().Value), + ToVector3(attributes[MdlFile.VertexUsage.Position].First()), + ToVector3(attributes[MdlFile.VertexUsage.Normal].First()), bitangent ); } @@ -381,12 +378,12 @@ public class MeshExporter } /// Get the vertex material type for this mesh's vertex usages. - private Type GetMaterialType(IReadOnlyDictionary> usages) + private Type GetMaterialType(IReadOnlyDictionary> usages) { var uvCount = 0; - if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var dict)) + if (usages.TryGetValue(MdlFile.VertexUsage.UV, out var list)) { - foreach (var type in dict.Values) + foreach (var type in list) { uvCount += type switch { @@ -420,28 +417,28 @@ public class MeshExporter } /// Build a material vertex from a vertex's attributes. - private IVertexMaterial BuildVertexMaterial(IReadOnlyDictionary> attributes) + private IVertexMaterial BuildVertexMaterial(IReadOnlyDictionary> attributes) { if (_materialType == typeof(VertexEmpty)) return new VertexEmpty(); if (_materialType == typeof(VertexColorFfxiv)) - return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value)); + return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color].First())); if (_materialType == typeof(VertexTexture1)) - return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV].First().Value)); + return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV].First())); if (_materialType == typeof(VertexTexture1ColorFfxiv)) return new VertexTexture1ColorFfxiv( - ToVector2(attributes[MdlFile.VertexUsage.UV].First().Value), - ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value) + ToVector2(attributes[MdlFile.VertexUsage.UV].First()), + ToVector4(attributes[MdlFile.VertexUsage.Color].First()) ); // XIV packs two UVs into a single vec4 attribute. if (_materialType == typeof(VertexTexture2)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First().Value); + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First()); return new VertexTexture2( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W) @@ -450,11 +447,11 @@ public class MeshExporter if (_materialType == typeof(VertexTexture2ColorFfxiv)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First().Value); + var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First()); return new VertexTexture2ColorFfxiv( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W), - ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value) + ToVector4(attributes[MdlFile.VertexUsage.Color].First()) ); } if (_materialType == typeof(VertexTexture3)) @@ -470,7 +467,7 @@ public class MeshExporter new Vector2(uv0.X, uv0.Y), new Vector2(uv0.Z, uv0.W), new Vector2(uv1.X, uv1.Y), - ToVector4(attributes[MdlFile.VertexUsage.Color].First().Value) + ToVector4(attributes[MdlFile.VertexUsage.Color].First()) ); } @@ -478,11 +475,11 @@ public class MeshExporter } /// Get the vertex skinning type for this mesh's vertex usages. - private static Type GetSkinningType(IReadOnlyDictionary> usages) + private static Type GetSkinningType(IReadOnlyDictionary> usages) { if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) { - if (usages[MdlFile.VertexUsage.BlendWeights].First().Value == MdlFile.VertexType.UShort4) + if (usages[MdlFile.VertexUsage.BlendWeights].First() == MdlFile.VertexType.UShort4) { return typeof(VertexJoints8); } @@ -496,7 +493,7 @@ public class MeshExporter } /// Build a skinning vertex from a vertex's attributes. - private IVertexSkinning BuildVertexSkinning(IReadOnlyDictionary> attributes) + private IVertexSkinning BuildVertexSkinning(IReadOnlyDictionary> attributes) { if (_skinningType == typeof(VertexEmpty)) return new VertexEmpty(); @@ -506,8 +503,8 @@ public class MeshExporter if (_boneIndexMap == null) throw _notifier.Exception("Tried to build skinned vertex but no bone mappings are available."); - var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices].First().Value; - var weightsData = attributes[MdlFile.VertexUsage.BlendWeights].First().Value; + var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices].First(); + var weightsData = attributes[MdlFile.VertexUsage.BlendWeights].First(); var indices = ToByteArray(indiciesData); var weights = ToFloatArray(weightsData); From b76626ac8dbe9e4595be5e87a8f221415314ed18 Mon Sep 17 00:00:00 2001 From: Adam Moy Date: Wed, 12 Feb 2025 13:18:30 -0600 Subject: [PATCH 1108/1381] Added VertexTexture3 Not sure of accuracy but followed existing pattern --- Penumbra/Import/Models/Export/MeshExporter.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index fb88dfc3..a3cc2f04 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -456,7 +456,14 @@ public class MeshExporter } if (_materialType == typeof(VertexTexture3)) { - throw _notifier.Exception("Unimplemented: Material Type is VertexTexture3"); + // Not 100% sure about this + var uv0 = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); + var uv1 = ToVector4(attributes[MdlFile.VertexUsage.UV][1]); + return new VertexTexture3( + new Vector2(uv0.X, uv0.Y), + new Vector2(uv0.Z, uv0.W), + new Vector2(uv1.X, uv1.Y) + ); } if (_materialType == typeof(VertexTexture3ColorFfxiv)) From 6d2b72e0798ac6cad82d54d9d0996ae666ff4c1e Mon Sep 17 00:00:00 2001 From: Adam Moy Date: Wed, 12 Feb 2025 13:30:06 -0600 Subject: [PATCH 1109/1381] Removed irrelevant comments --- Penumbra/Import/Models/Export/MeshExporter.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index a3cc2f04..6d65e152 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -107,19 +107,14 @@ public class MeshExporter /// Build a mapping between indices in this mesh's bone table (if any), and the glTF joint indices provided. private Dictionary? BuildBoneIndexMap(GltfSkeleton skeleton) { - Penumbra.Log.Debug("Building Bone Index Map"); // A BoneTableIndex of 255 means that this mesh is not skinned. if (XivMesh.BoneTableIndex == 255) - { - Penumbra.Log.Debug("BoneTableIndex was 255"); return null; - } var xivBoneTable = _mdl.BoneTables[XivMesh.BoneTableIndex]; var indexMap = new Dictionary(); // #TODO @ackwell maybe fix for V6 Models, I think this works fine. - Penumbra.Log.Debug($"Version is 5 {_mdl.Version == MdlFile.V5}"); foreach (var (xivBoneIndex, tableIndex) in xivBoneTable.BoneIndex.Take((int)xivBoneTable.BoneCount).WithIndex()) { From 31f23024a45b0663b87c97a1a8c0fe56b4b891b7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Feb 2025 18:36:08 +0100 Subject: [PATCH 1110/1381] Notify and fail when a list of vertex usages has more than one entry where this is not expected. --- Penumbra/Import/Models/Export/MeshExporter.cs | 57 ++++++++++--------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 6d65e152..aa0811d7 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -7,7 +7,6 @@ using Penumbra.GameData.Files; using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Geometry; using SharpGLTF.Geometry.VertexTypes; -using SharpGLTF.IO; using SharpGLTF.Materials; using SharpGLTF.Scenes; @@ -347,24 +346,24 @@ public class MeshExporter { if (_geometryType == typeof(VertexPosition)) return new VertexPosition( - ToVector3(attributes[MdlFile.VertexUsage.Position].First()) + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)) ); if (_geometryType == typeof(VertexPositionNormal)) return new VertexPositionNormal( - ToVector3(attributes[MdlFile.VertexUsage.Position].First()), - ToVector3(attributes[MdlFile.VertexUsage.Normal].First()) + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)), + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal)) ); if (_geometryType == typeof(VertexPositionNormalTangent)) { // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. // TODO: While this assumption is safe, it would be sensible to actually check. - var bitangent = ToVector4(attributes[MdlFile.VertexUsage.Tangent1].First()) * 2 - Vector4.One; + var bitangent = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)) * 2 - Vector4.One; return new VertexPositionNormalTangent( - ToVector3(attributes[MdlFile.VertexUsage.Position].First()), - ToVector3(attributes[MdlFile.VertexUsage.Normal].First()), + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)), + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal)), bitangent ); } @@ -418,22 +417,22 @@ public class MeshExporter return new VertexEmpty(); if (_materialType == typeof(VertexColorFfxiv)) - return new VertexColorFfxiv(ToVector4(attributes[MdlFile.VertexUsage.Color].First())); + return new VertexColorFfxiv(ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color))); if (_materialType == typeof(VertexTexture1)) - return new VertexTexture1(ToVector2(attributes[MdlFile.VertexUsage.UV].First())); + return new VertexTexture1(ToVector2(GetFirstSafe(attributes, MdlFile.VertexUsage.UV))); if (_materialType == typeof(VertexTexture1ColorFfxiv)) return new VertexTexture1ColorFfxiv( - ToVector2(attributes[MdlFile.VertexUsage.UV].First()), - ToVector4(attributes[MdlFile.VertexUsage.Color].First()) + ToVector2(GetFirstSafe(attributes, MdlFile.VertexUsage.UV)), + ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color)) ); // XIV packs two UVs into a single vec4 attribute. if (_materialType == typeof(VertexTexture2)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First()); + var uv = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.UV)); return new VertexTexture2( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W) @@ -442,11 +441,11 @@ public class MeshExporter if (_materialType == typeof(VertexTexture2ColorFfxiv)) { - var uv = ToVector4(attributes[MdlFile.VertexUsage.UV].First()); + var uv = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.UV)); return new VertexTexture2ColorFfxiv( new Vector2(uv.X, uv.Y), new Vector2(uv.Z, uv.W), - ToVector4(attributes[MdlFile.VertexUsage.Color].First()) + ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color)) ); } if (_materialType == typeof(VertexTexture3)) @@ -469,7 +468,7 @@ public class MeshExporter new Vector2(uv0.X, uv0.Y), new Vector2(uv0.Z, uv0.W), new Vector2(uv1.X, uv1.Y), - ToVector4(attributes[MdlFile.VertexUsage.Color].First()) + ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color)) ); } @@ -477,18 +476,13 @@ public class MeshExporter } /// Get the vertex skinning type for this mesh's vertex usages. - private static Type GetSkinningType(IReadOnlyDictionary> usages) + private Type GetSkinningType(IReadOnlyDictionary> usages) { if (usages.ContainsKey(MdlFile.VertexUsage.BlendWeights) && usages.ContainsKey(MdlFile.VertexUsage.BlendIndices)) { - if (usages[MdlFile.VertexUsage.BlendWeights].First() == MdlFile.VertexType.UShort4) - { - return typeof(VertexJoints8); - } - else - { - return typeof(VertexJoints4); - } + return GetFirstSafe(usages, MdlFile.VertexUsage.BlendWeights) == MdlFile.VertexType.UShort4 + ? typeof(VertexJoints8) + : typeof(VertexJoints4); } return typeof(VertexEmpty); @@ -505,8 +499,8 @@ public class MeshExporter if (_boneIndexMap == null) throw _notifier.Exception("Tried to build skinned vertex but no bone mappings are available."); - var indiciesData = attributes[MdlFile.VertexUsage.BlendIndices].First(); - var weightsData = attributes[MdlFile.VertexUsage.BlendWeights].First(); + var indiciesData = GetFirstSafe(attributes, MdlFile.VertexUsage.BlendIndices); + var weightsData = GetFirstSafe(attributes, MdlFile.VertexUsage.BlendWeights); var indices = ToByteArray(indiciesData); var weights = ToFloatArray(weightsData); @@ -533,6 +527,17 @@ public class MeshExporter throw _notifier.Exception($"Unknown skinning type {_skinningType}"); } + /// Check that the list has length 1 for any case where this is expected and return the one entry. + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private T GetFirstSafe(IReadOnlyDictionary> attributes, MdlFile.VertexUsage usage) + { + var list = attributes[usage]; + if (list.Count != 1) + throw _notifier.Exception($"Multiple usage indices encountered for {usage}."); + + return list[0]; + } + /// Convert a vertex attribute value to a Vector2. Supported inputs are Vector2, Vector3, and Vector4. private static Vector2 ToVector2(object data) => data switch From f8d0616acd835eefc394b7303b6e4ee55f1e923d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Feb 2025 18:36:33 +0100 Subject: [PATCH 1111/1381] Notify when an unhandled UV count is reached. --- Penumbra/Import/Models/Export/MeshExporter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index aa0811d7..32b9b323 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -406,7 +406,7 @@ public class MeshExporter (0, true) => typeof(VertexColorFfxiv), (0, false) => typeof(VertexEmpty), - _ => throw new Exception("Unreachable."), + _ => throw _notifier.Exception($"Unhandled UV count of {uvCount} encountered."), }; } From d40c59eee98bcd2f20ac0ce701e181bf6eb7bf70 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Feb 2025 18:36:46 +0100 Subject: [PATCH 1112/1381] Slight cleanup. --- .../Import/Models/Export/VertexFragment.cs | 56 ++++++------------- 1 file changed, 16 insertions(+), 40 deletions(-) diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index c9b97997..56495f2f 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -1,4 +1,3 @@ -using System; using SharpGLTF.Geometry.VertexTypes; using SharpGLTF.Memory; using SharpGLTF.Schema2; @@ -11,7 +10,7 @@ Realistically, it will need to stick around until transforms/mutations are built and there's reason to overhaul the export pipeline. */ -public struct VertexColorFfxiv : IVertexCustom +public struct VertexColorFfxiv(Vector4 ffxivColor) : IVertexCustom { public IEnumerable> GetEncodingAttributes() { @@ -20,7 +19,7 @@ public struct VertexColorFfxiv : IVertexCustom new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); } - public Vector4 FfxivColor; + public Vector4 FfxivColor = ffxivColor; public int MaxColors => 0; @@ -33,9 +32,6 @@ public struct VertexColorFfxiv : IVertexCustom public IEnumerable CustomAttributes => CustomNames; - public VertexColorFfxiv(Vector4 ffxivColor) - => FfxivColor = ffxivColor; - public void Add(in VertexMaterialDelta delta) { } @@ -88,7 +84,7 @@ public struct VertexColorFfxiv : IVertexCustom } } -public struct VertexTexture1ColorFfxiv : IVertexCustom +public struct VertexTexture1ColorFfxiv(Vector2 texCoord0, Vector4 ffxivColor) : IVertexCustom { public IEnumerable> GetEncodingAttributes() { @@ -98,9 +94,9 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); } - public Vector2 TexCoord0; + public Vector2 TexCoord0 = texCoord0; - public Vector4 FfxivColor; + public Vector4 FfxivColor = ffxivColor; public int MaxColors => 0; @@ -113,12 +109,6 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom public IEnumerable CustomAttributes => CustomNames; - public VertexTexture1ColorFfxiv(Vector2 texCoord0, Vector4 ffxivColor) - { - TexCoord0 = texCoord0; - FfxivColor = ffxivColor; - } - public void Add(in VertexMaterialDelta delta) { TexCoord0 += delta.TexCoord0Delta; @@ -182,7 +172,7 @@ public struct VertexTexture1ColorFfxiv : IVertexCustom } } -public struct VertexTexture2ColorFfxiv : IVertexCustom +public struct VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor) : IVertexCustom { public IEnumerable> GetEncodingAttributes() { @@ -194,9 +184,9 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); } - public Vector2 TexCoord0; - public Vector2 TexCoord1; - public Vector4 FfxivColor; + public Vector2 TexCoord0 = texCoord0; + public Vector2 TexCoord1 = texCoord1; + public Vector4 FfxivColor = ffxivColor; public int MaxColors => 0; @@ -209,13 +199,6 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom public IEnumerable CustomAttributes => CustomNames; - public VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor) - { - TexCoord0 = texCoord0; - TexCoord1 = texCoord1; - FfxivColor = ffxivColor; - } - public void Add(in VertexMaterialDelta delta) { TexCoord0 += delta.TexCoord0Delta; @@ -283,7 +266,8 @@ public struct VertexTexture2ColorFfxiv : IVertexCustom } } -public struct VertexTexture3ColorFfxiv : IVertexCustom +public struct VertexTexture3ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector2 texCoord2, Vector4 ffxivColor) + : IVertexCustom { public IEnumerable> GetEncodingAttributes() { @@ -297,10 +281,10 @@ public struct VertexTexture3ColorFfxiv : IVertexCustom new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); } - public Vector2 TexCoord0; - public Vector2 TexCoord1; - public Vector2 TexCoord2; - public Vector4 FfxivColor; + public Vector2 TexCoord0 = texCoord0; + public Vector2 TexCoord1 = texCoord1; + public Vector2 TexCoord2 = texCoord2; + public Vector4 FfxivColor = ffxivColor; public int MaxColors => 0; @@ -313,14 +297,6 @@ public struct VertexTexture3ColorFfxiv : IVertexCustom public IEnumerable CustomAttributes => CustomNames; - public VertexTexture3ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector2 texCoord2, Vector4 ffxivColor) - { - TexCoord0 = texCoord0; - TexCoord1 = texCoord1; - TexCoord2 = texCoord2; - FfxivColor = ffxivColor; - } - public void Add(in VertexMaterialDelta delta) { TexCoord0 += delta.TexCoord0Delta; @@ -387,7 +363,7 @@ public struct VertexTexture3ColorFfxiv : IVertexCustom FfxivColor.Z, FfxivColor.W, }; - if (components.Any(component => component < 0 || component > 1)) + if (components.Any(component => component is < 0f or > 1f)) throw new ArgumentOutOfRangeException(nameof(FfxivColor)); } } From 1f172b463206bc41b5769f0d6148d551aefdda50 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Feb 2025 18:37:15 +0100 Subject: [PATCH 1113/1381] Make default constructed models use V6 instead of V5. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index f6dff467..b4a0806e 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f6dff467c7dad6b1213a7d7b65d40a56450f0672 +Subproject commit b4a0806e00be4ce8cf3103fd526e4a412b4770b7 From fdd75e2866a10aa380eddf46d615af6ad373f11a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 20 Feb 2025 19:17:55 +0100 Subject: [PATCH 1114/1381] Use Meta Compression V1. --- Penumbra/Api/Api/MetaApi.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index ff88ae4e..7c0cd5fc 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -51,7 +51,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver } internal static string CompressMetaManipulations(ModCollection collection) - => CompressMetaManipulationsV0(collection); + => CompressMetaManipulationsV1(collection); private static string CompressMetaManipulationsV0(ModCollection collection) { From 4a00d82921468397ed7262ff8aef470090d9d398 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 20 Feb 2025 18:20:23 +0000 Subject: [PATCH 1115/1381] [CI] Updating repo.json for testing_1.3.4.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index c46f3d27..afb2c32d 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.3", + "TestingAssemblyVersion": "1.3.4.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 514b0e7f30f4a792726a1bca9c811bdf0a373ee2 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 27 Feb 2025 00:10:24 +0100 Subject: [PATCH 1116/1381] Add file types to Resource Tree and require Ctrl+Shift for some quick imports --- Penumbra.GameData | 2 +- .../ResolveContext.PathResolution.cs | 84 ++++++++++++----- .../Interop/ResourceTree/ResolveContext.cs | 93 ++++++++++++++++++- Penumbra/Interop/ResourceTree/ResourceNode.cs | 11 ++- Penumbra/Interop/ResourceTree/ResourceTree.cs | 50 ++++++++-- Penumbra/Interop/Structs/StructExtensions.cs | 12 +++ .../ModEditWindow.QuickImport.cs | 5 +- 7 files changed, 224 insertions(+), 33 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index b4a0806e..c59b1da6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b4a0806e00be4ce8cf3103fd526e4a412b4770b7 +Subproject commit c59b1da61610e656b3e89f9c33113d08f97ae6c7 diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index bdf66a16..cd6b8568 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -22,6 +22,13 @@ internal partial record ResolveContext private static bool IsEquipmentSlot(uint slotIndex) => slotIndex is < 5 or 16 or 17; + private unsafe Variant Variant + => ModelType switch + { + ModelType.Monster => (byte)((Monster*)CharacterBase)->Variant, + _ => Equipment.Variant, + }; + private Utf8GamePath ResolveModelPath() { // Correctness: @@ -92,7 +99,7 @@ internal partial record ResolveContext => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), ModelType.DemiHuman => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), ModelType.Weapon => ResolveWeaponMaterialPath(modelPath, imc, mtrlFileName), - ModelType.Monster => ResolveMonsterMaterialPath(modelPath, imc, mtrlFileName), + ModelType.Monster => ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName), _ => ResolveMaterialPathNative(mtrlFileName), }; } @@ -100,7 +107,7 @@ internal partial record ResolveContext [SkipLocalsInit] private unsafe Utf8GamePath ResolveEquipmentMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) { - var variant = ResolveMaterialVariant(imc, Equipment.Variant); + var variant = ResolveImcData(imc).MaterialId; var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; @@ -118,9 +125,9 @@ internal partial record ResolveContext return Utf8GamePath.FromString(GamePaths.Weapon.Mtrl.Path(2001, 1, 1, "c"), out var path) ? path : Utf8GamePath.Empty; // Some offhands share materials with the corresponding mainhand - if (ItemData.AdaptOffhandImc(Equipment.Set.Id, out var mirroredSetId)) + if (ItemData.AdaptOffhandImc(Equipment.Set, out var mirroredSetId)) { - var variant = ResolveMaterialVariant(imc, Equipment.Variant); + var variant = ResolveImcData(imc).MaterialId; var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); Span mirroredFileName = stackalloc byte[32]; @@ -141,31 +148,16 @@ internal partial record ResolveContext return ResolveEquipmentMaterialPath(modelPath, imc, mtrlFileName); } - private unsafe Utf8GamePath ResolveMonsterMaterialPath(Utf8GamePath modelPath, ResourceHandle* imc, byte* mtrlFileName) - { - var variant = ResolveMaterialVariant(imc, (byte)((Monster*)CharacterBase)->Variant); - var fileName = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(mtrlFileName); - - Span pathBuffer = stackalloc byte[CharaBase.PathBufferSize]; - pathBuffer = AssembleMaterialPath(pathBuffer, modelPath.Path.Span, variant, fileName); - - return Utf8GamePath.FromSpan(pathBuffer, MetaDataComputation.None, out var path) ? path.Clone() : Utf8GamePath.Empty; - } - - private unsafe byte ResolveMaterialVariant(ResourceHandle* imc, Variant variant) + private unsafe ImcEntry ResolveImcData(ResourceHandle* imc) { var imcFileData = imc->GetDataSpan(); if (imcFileData.IsEmpty) { Penumbra.Log.Warning($"IMC resource handle with path {imc->FileName.AsByteString()} doesn't have a valid data span"); - return variant.Id; + return default; } - var entry = ImcFile.GetEntry(imcFileData, SlotIndex.ToEquipSlot(), variant, out var exists); - if (!exists) - return variant.Id; - - return entry.MaterialId; + return ImcFile.GetEntry(imcFileData, SlotIndex.ToEquipSlot(), Variant, out _); } private static Span AssembleMaterialPath(Span materialPathBuffer, ReadOnlySpan modelPath, byte variant, @@ -317,4 +309,52 @@ internal partial record ResolveContext var path = CharacterBase->ResolveSkpPathAsByteString(partialSkeletonIndex); return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } + + private Utf8GamePath ResolvePhysicsModulePath(uint partialSkeletonIndex) + { + // Correctness and Safety: + // Resolving a physics module path through the game's code can use EST metadata for human skeletons. + // Additionally, it can dereference null pointers for human equipment skeletons. + return ModelType switch + { + ModelType.Human => ResolveHumanPhysicsModulePath(partialSkeletonIndex), + _ => ResolvePhysicsModulePathNative(partialSkeletonIndex), + }; + } + + private Utf8GamePath ResolveHumanPhysicsModulePath(uint partialSkeletonIndex) + { + var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); + if (set == 0) + return Utf8GamePath.Empty; + + var path = GamePaths.Skeleton.Phyb.Path(raceCode, slot, set); + return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolvePhysicsModulePathNative(uint partialSkeletonIndex) + { + var path = CharacterBase->ResolvePhybPathAsByteString(partialSkeletonIndex); + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolveMaterialAnimationPath(ResourceHandle* imc) + { + var animation = ResolveImcData(imc).MaterialAnimationId; + if (animation == 0) + return Utf8GamePath.Empty; + + var path = CharacterBase->ResolveMaterialPapPathAsByteString(SlotIndex, animation); + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolveDecalPath(ResourceHandle* imc) + { + var decal = ResolveImcData(imc).DecalId; + if (decal == 0) + return Utf8GamePath.Empty; + + var path = GamePaths.Equipment.Decal.Path(decal); + return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 54612070..f33bf041 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -180,7 +180,15 @@ internal unsafe partial record ResolveContext( return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, path); } - public ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc) + public ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, Utf8GamePath gamePath) + { + if (tex == null) + return null; + + return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, gamePath); + } + + public ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc, TextureResourceHandle* decalHandle, ResourceHandle* mpapHandle) { if (mdl == null || mdl->ModelResourceHandle == null) return null; @@ -210,6 +218,14 @@ internal unsafe partial record ResolveContext( } } + var decalNode = CreateNodeFromDecal(decalHandle, imc); + if (null != decalNode) + node.Children.Add(decalNode); + + var mpapNode = CreateNodeFromMaterialPap(mpapHandle, imc); + if (null != mpapNode) + node.Children.Add(mpapNode); + Global.Nodes.Add((path, (nint)mdl->ModelResourceHandle), node); return node; @@ -301,7 +317,59 @@ internal unsafe partial record ResolveContext( } } - public ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) + public ResourceNode? CreateNodeFromDecal(TextureResourceHandle* decalHandle, ResourceHandle* imc) + { + if (decalHandle == null) + return null; + + var path = ResolveDecalPath(imc); + if (path.IsEmpty) + return null; + + var node = CreateNodeFromTex(decalHandle, path)!; + if (Global.WithUiData) + node.FallbackName = "Decal"; + + return node; + } + + public ResourceNode? CreateNodeFromMaterialPap(ResourceHandle* mpapHandle, ResourceHandle* imc) + { + if (mpapHandle == null) + return null; + + var path = ResolveMaterialAnimationPath(imc); + if (path.IsEmpty) + return null; + + if (Global.Nodes.TryGetValue((path, (nint)mpapHandle), out var cached)) + return cached; + + var node = CreateNode(ResourceType.Pap, 0, mpapHandle, path); + if (Global.WithUiData) + node.FallbackName = "Material Animation"; + + return node; + } + + public ResourceNode? CreateNodeFromMaterialSklb(SkeletonResourceHandle* sklbHandle) + { + if (sklbHandle == null) + return null; + + if (!Utf8GamePath.FromString(GamePaths.Skeleton.Sklb.MaterialAnimationSkeletonPath, out var path)) + return null; + + if (Global.Nodes.TryGetValue((path, (nint)sklbHandle), out var cached)) + return cached; + + var node = CreateNode(ResourceType.Sklb, 0, (ResourceHandle*)sklbHandle, path); + node.ForceInternal = true; + + return node; + } + + public ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, ResourceHandle* phybHandle, uint partialSkeletonIndex) { if (sklb == null || sklb->SkeletonResourceHandle == null) return null; @@ -315,6 +383,9 @@ internal unsafe partial record ResolveContext( var skpNode = CreateParameterNodeFromPartialSkeleton(sklb, partialSkeletonIndex); if (skpNode != null) node.Children.Add(skpNode); + var phybNode = CreateNodeFromPhyb(phybHandle, partialSkeletonIndex); + if (phybNode != null) + node.Children.Add(phybNode); Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); return node; @@ -338,6 +409,24 @@ internal unsafe partial record ResolveContext( return node; } + private ResourceNode? CreateNodeFromPhyb(ResourceHandle* phybHandle, uint partialSkeletonIndex) + { + if (phybHandle == null) + return null; + + var path = ResolvePhysicsModulePath(partialSkeletonIndex); + + if (Global.Nodes.TryGetValue((path, (nint)phybHandle), out var cached)) + return cached; + + var node = CreateNode(ResourceType.Phyb, 0, phybHandle, path, false); + if (Global.WithUiData) + node.FallbackName = "Physics Module"; + Global.Nodes.Add((path, (nint)phybHandle), node); + + return node; + } + internal ResourceNode.UiData GuessModelUiData(Utf8GamePath gamePath) { var path = gamePath.Path.Split((byte)'/'); diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 60cc48de..24cb8f02 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -21,6 +21,8 @@ public class ResourceNode : ICloneable public readonly WeakReference Mod = new(null!); public string? ModRelativePath; public CiByteString AdditionalData; + public bool ForceInternal; + public bool ForceProtected; public readonly ulong Length; public readonly List Children; internal ResolveContext? ResolveContext; @@ -37,8 +39,13 @@ public class ResourceNode : ICloneable } } + /// Whether to treat the file as internal (hide from user unless debug mode is on). public bool Internal - => Type is ResourceType.Eid or ResourceType.Imc; + => ForceInternal || Type is ResourceType.Eid or ResourceType.Imc; + + /// Whether to treat the file as protected (require holding the Mod Deletion Modifier to make a quick import). + public bool Protected + => ForceProtected || Internal || Type is ResourceType.Shpk or ResourceType.Sklb or ResourceType.Pbd; internal ResourceNode(ResourceType type, nint objectAddress, nint resourceHandle, ulong length, ResolveContext? resolveContext) { @@ -67,6 +74,8 @@ public class ResourceNode : ICloneable Mod = other.Mod; ModRelativePath = other.ModRelativePath; AdditionalData = other.AdditionalData; + ForceInternal = other.ForceInternal; + ForceProtected = other.ForceProtected; Length = other.Length; Children = other.Children; ResolveContext = other.ResolveContext; diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index b50fc695..ac1f889c 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -1,7 +1,9 @@ using FFXIVClientStructs.FFXIV.Client.Game.Character; +using FFXIVClientStructs.FFXIV.Client.Graphics.Physics; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; +using FFXIVClientStructs.Interop; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -10,6 +12,7 @@ using Penumbra.UI; using CustomizeData = FFXIVClientStructs.FFXIV.Client.Game.Character.CustomizeData; using CustomizeIndex = Dalamud.Game.ClientState.Objects.Enums.CustomizeIndex; using ModelType = FFXIVClientStructs.FFXIV.Client.Graphics.Scene.CharacterBase.ModelType; +using ResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.ResourceHandle; namespace Penumbra.Interop.ResourceTree; @@ -74,6 +77,18 @@ public class ResourceTree var genericContext = globalContext.CreateContext(model); + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) + var mpapArrayPtr = *(ResourceHandle***)((nint)model + 0x948); + var mpapArray = null != mpapArrayPtr ? new ReadOnlySpan>(mpapArrayPtr, model->SlotCount) : []; + var decalArray = modelType switch + { + ModelType.Human => human->SlotDecalsSpan, + ModelType.DemiHuman => ((Demihuman*)model)->SlotDecals, + ModelType.Weapon => [((Weapon*)model)->Decal], + ModelType.Monster => [((Monster*)model)->Decal], + _ => [], + }; + for (var i = 0u; i < model->SlotCount; ++i) { var slotContext = modelType switch @@ -100,7 +115,8 @@ public class ResourceTree } var mdl = model->Models[i]; - var mdlNode = slotContext.CreateNodeFromModel(mdl, imc); + var mdlNode = slotContext.CreateNodeFromModel(mdl, imc, i < decalArray.Length ? decalArray[(int)i].Value : null, + i < mpapArray.Length ? mpapArray[(int)i].Value : null); if (mdlNode != null) { if (globalContext.WithUiData) @@ -109,7 +125,9 @@ public class ResourceTree } } - AddSkeleton(Nodes, genericContext, model->EID, model->Skeleton); + AddSkeleton(Nodes, genericContext, model->EID, model->Skeleton, model->BonePhysicsModule); + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) + AddMaterialAnimationSkeleton(Nodes, genericContext, *(SkeletonResourceHandle**)((nint)model + 0x940)); AddWeapons(globalContext, model); @@ -140,6 +158,10 @@ public class ResourceTree var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment, weaponType); + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) + var mpapArrayPtr = *(ResourceHandle***)((nint)subObject + 0x948); + var mpapArray = null != mpapArrayPtr ? new ReadOnlySpan>(mpapArrayPtr, subObject->SlotCount) : []; + for (var i = 0; i < subObject->SlotCount; ++i) { var slotContext = globalContext.CreateContext(subObject, (uint)i, slot, equipment, weaponType); @@ -154,7 +176,7 @@ public class ResourceTree } var mdl = subObject->Models[i]; - var mdlNode = slotContext.CreateNodeFromModel(mdl, imc); + var mdlNode = slotContext.CreateNodeFromModel(mdl, imc, weapon->Decal, i < mpapArray.Length ? mpapArray[i].Value : null); if (mdlNode != null) { if (globalContext.WithUiData) @@ -163,7 +185,9 @@ public class ResourceTree } } - AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, $"Weapon #{weaponIndex}, "); + AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, subObject->BonePhysicsModule, $"Weapon #{weaponIndex}, "); + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) + AddMaterialAnimationSkeleton(weaponNodes, genericContext, *(SkeletonResourceHandle**)((nint)subObject + 0x940), $"Weapon #{weaponIndex}, "); ++weaponIndex; } @@ -216,6 +240,7 @@ public class ResourceTree var legacyDecalNode = genericContext.CreateNodeFromTex(human->LegacyBodyDecal, legacyDecalPath); if (legacyDecalNode != null) { + legacyDecalNode.ForceProtected = !hasLegacyDecal; if (globalContext.WithUiData) { legacyDecalNode = legacyDecalNode.Clone(); @@ -227,7 +252,7 @@ public class ResourceTree } } - private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, string prefix = "") + private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, BonePhysicsModule* physics, string prefix = "") { var eidNode = context.CreateNodeFromEid((ResourceHandle*)eid); if (eidNode != null) @@ -242,7 +267,9 @@ public class ResourceTree for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) { - var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], (uint)i); + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) + var phybHandle = physics != null ? ((ResourceHandle**)((nint)physics + 0x190))[i] : null; + var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, (uint)i); if (sklbNode != null) { if (context.Global.WithUiData) @@ -251,4 +278,15 @@ public class ResourceTree } } } + + private unsafe void AddMaterialAnimationSkeleton(List nodes, ResolveContext context, SkeletonResourceHandle* sklbHandle, string prefix = "") + { + var sklbNode = context.CreateNodeFromMaterialSklb(sklbHandle); + if (sklbNode == null) + return; + + if (context.Global.WithUiData) + sklbNode.FallbackName = $"{prefix}Material Animation Skeleton"; + nodes.Add(sklbNode); + } } diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 9dd9a96d..8b5974f0 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -33,6 +33,12 @@ internal static class StructExtensions return ToOwnedByteString(character.ResolveMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex, mtrlFileName)); } + public static CiByteString ResolveMaterialPapPathAsByteString(ref this CharacterBase character, uint slotIndex, uint unkSId) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveMaterialPapPath(pathBuffer, slotIndex, unkSId)); + } + public static CiByteString ResolveSklbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) { Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; @@ -45,6 +51,12 @@ internal static class StructExtensions return ToOwnedByteString(character.ResolveSkpPath(pathBuffer, partialSkeletonIndex)); } + public static CiByteString ResolvePhybPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolvePhybPath(pathBuffer, partialSkeletonIndex)); + } + private static unsafe CiByteString ToOwnedByteString(byte* str) => str == null ? CiByteString.Empty : new CiByteString(str).Clone(); diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 6fb223df..a49d2933 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -110,8 +110,11 @@ public partial class ModEditWindow _quickImportActions.Add((resourceNode.GamePath, writable), quickImport); } + var canQuickImport = quickImport.CanExecute; + var quickImportEnabled = canQuickImport && (!resourceNode.Protected || _config.DeleteModModifier.IsActive()); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileImport.ToIconString(), buttonSize, - $"Add a copy of this file to {quickImport.OptionName}.", !quickImport.CanExecute, true)) + $"Add a copy of this file to {quickImport.OptionName}.{(canQuickImport && !quickImportEnabled ? $"\nHold {_config.DeleteModModifier} while clicking to add." : string.Empty)}", + !quickImportEnabled, true)) { quickImport.Execute(); _quickImportActions.Remove((resourceNode.GamePath, writable)); From 776a93dc73b03f87dbcea4165f4ab571f4f21b0c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 05:38:42 +0100 Subject: [PATCH 1117/1381] Some null-check cleanup. --- .../ResolveContext.PathResolution.cs | 10 +-- .../Interop/ResourceTree/ResolveContext.cs | 81 ++++++++----------- 2 files changed, 39 insertions(+), 52 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index cd6b8568..b1ca24b0 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -248,7 +248,7 @@ internal partial record ResolveContext if (faceId < 201) faceId -= tribe switch { - 0xB when modelType == 4 => 100, + 0xB when modelType is 4 => 100, 0xE | 0xF => 100, _ => 0, }; @@ -297,7 +297,7 @@ internal partial record ResolveContext private Utf8GamePath ResolveHumanSkeletonParameterPath(uint partialSkeletonIndex) { var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); - if (set == 0) + if (set.Id is 0) return Utf8GamePath.Empty; var path = GamePaths.Skeleton.Skp.Path(raceCode, slot, set); @@ -325,7 +325,7 @@ internal partial record ResolveContext private Utf8GamePath ResolveHumanPhysicsModulePath(uint partialSkeletonIndex) { var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); - if (set == 0) + if (set.Id is 0) return Utf8GamePath.Empty; var path = GamePaths.Skeleton.Phyb.Path(raceCode, slot, set); @@ -341,7 +341,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveMaterialAnimationPath(ResourceHandle* imc) { var animation = ResolveImcData(imc).MaterialAnimationId; - if (animation == 0) + if (animation is 0) return Utf8GamePath.Empty; var path = CharacterBase->ResolveMaterialPapPathAsByteString(SlotIndex, animation); @@ -351,7 +351,7 @@ internal partial record ResolveContext private unsafe Utf8GamePath ResolveDecalPath(ResourceHandle* imc) { var decal = ResolveImcData(imc).DecalId; - if (decal == 0) + if (decal is 0) return Utf8GamePath.Empty; var path = GamePaths.Equipment.Decal.Path(decal); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index f33bf041..81904819 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -52,7 +52,7 @@ internal unsafe partial record ResolveContext( private ResourceNode? CreateNodeFromShpk(ShaderPackageResourceHandle* resourceHandle, CiByteString gamePath) { - if (resourceHandle == null) + if (resourceHandle is null) return null; if (gamePath.IsEmpty) return null; @@ -65,7 +65,7 @@ internal unsafe partial record ResolveContext( [SkipLocalsInit] private ResourceNode? CreateNodeFromTex(TextureResourceHandle* resourceHandle, CiByteString gamePath, bool dx11) { - if (resourceHandle == null) + if (resourceHandle is null) return null; Utf8GamePath path; @@ -105,7 +105,7 @@ internal unsafe partial record ResolveContext( private ResourceNode GetOrCreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, Utf8GamePath gamePath) { - if (resourceHandle == null) + if (resourceHandle is null) throw new ArgumentNullException(nameof(resourceHandle)); if (Global.Nodes.TryGetValue((gamePath, (nint)resourceHandle), out var cached)) @@ -117,7 +117,7 @@ internal unsafe partial record ResolveContext( private ResourceNode CreateNode(ResourceType type, nint objectAddress, ResourceHandle* resourceHandle, Utf8GamePath gamePath, bool autoAdd = true) { - if (resourceHandle == null) + if (resourceHandle is null) throw new ArgumentNullException(nameof(resourceHandle)); var fileName = (ReadOnlySpan)resourceHandle->FileName.AsSpan(); @@ -141,7 +141,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromEid(ResourceHandle* eid) { - if (eid == null) + if (eid is null) return null; if (!Utf8GamePath.FromByteString(CharacterBase->ResolveEidPathAsByteString(), out var path)) @@ -152,7 +152,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromImc(ResourceHandle* imc) { - if (imc == null) + if (imc is null) return null; if (!Utf8GamePath.FromByteString(CharacterBase->ResolveImcPathAsByteString(SlotIndex), out var path)) @@ -163,7 +163,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromPbd(ResourceHandle* pbd) { - if (pbd == null) + if (pbd is null) return null; return GetOrCreateNode(ResourceType.Pbd, 0, pbd, PreBoneDeformerReplacer.PreBoneDeformerPath); @@ -171,7 +171,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, string gamePath) { - if (tex == null) + if (tex is null) return null; if (!Utf8GamePath.FromString(gamePath, out var path)) @@ -182,7 +182,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromTex(TextureResourceHandle* tex, Utf8GamePath gamePath) { - if (tex == null) + if (tex is null) return null; return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, gamePath); @@ -190,7 +190,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc, TextureResourceHandle* decalHandle, ResourceHandle* mpapHandle) { - if (mdl == null || mdl->ModelResourceHandle == null) + if (mdl is null || mdl->ModelResourceHandle is null) return null; var mdlResource = mdl->ModelResourceHandle; @@ -205,12 +205,12 @@ internal unsafe partial record ResolveContext( for (var i = 0; i < mdl->MaterialCount; i++) { var mtrl = mdl->Materials[i]; - if (mtrl == null) + if (mtrl is null) continue; var mtrlFileName = mdlResource->GetMaterialFileNameBySlot((uint)i); var mtrlNode = CreateNodeFromMaterial(mtrl, ResolveMaterialPath(path, imc, mtrlFileName)); - if (mtrlNode != null) + if (mtrlNode is not null) { if (Global.WithUiData) mtrlNode.FallbackName = $"Material #{i}"; @@ -218,12 +218,10 @@ internal unsafe partial record ResolveContext( } } - var decalNode = CreateNodeFromDecal(decalHandle, imc); - if (null != decalNode) + if (CreateNodeFromDecal(decalHandle, imc) is { } decalNode) node.Children.Add(decalNode); - var mpapNode = CreateNodeFromMaterialPap(mpapHandle, imc); - if (null != mpapNode) + if (CreateNodeFromMaterialPap(mpapHandle, imc) is { } mpapNode) node.Children.Add(mpapNode); Global.Nodes.Add((path, (nint)mdl->ModelResourceHandle), node); @@ -233,7 +231,7 @@ internal unsafe partial record ResolveContext( private ResourceNode? CreateNodeFromMaterial(Material* mtrl, Utf8GamePath path) { - if (mtrl == null || mtrl->MaterialResourceHandle == null) + if (mtrl is null || mtrl->MaterialResourceHandle is null) return null; var resource = mtrl->MaterialResourceHandle; @@ -242,15 +240,15 @@ internal unsafe partial record ResolveContext( var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new CiByteString(resource->ShpkName)); - if (shpkNode != null) + if (shpkNode is not null) { if (Global.WithUiData) shpkNode.Name = "Shader Package"; node.Children.Add(shpkNode); } - var shpkNames = Global.WithUiData && shpkNode != null ? Global.TreeBuildCache.ReadShaderPackageNames(shpkNode.FullPath) : null; - var shpk = Global.WithUiData && shpkNode != null ? (ShaderPackage*)shpkNode.ObjectAddress : null; + var shpkNames = Global.WithUiData && shpkNode is not null ? Global.TreeBuildCache.ReadShaderPackageNames(shpkNode.FullPath) : null; + var shpk = Global.WithUiData && shpkNode is not null ? (ShaderPackage*)shpkNode.ObjectAddress : null; var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->TextureCount; i++) @@ -263,7 +261,7 @@ internal unsafe partial record ResolveContext( if (Global.WithUiData) { string? name = null; - if (shpk != null) + if (shpk is not null) { var index = GetTextureIndex(mtrl, resource->Textures[i].Flags, alreadyProcessedSamplerIds); var samplerId = index != 0x001F @@ -319,7 +317,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromDecal(TextureResourceHandle* decalHandle, ResourceHandle* imc) { - if (decalHandle == null) + if (decalHandle is null) return null; var path = ResolveDecalPath(imc); @@ -335,7 +333,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromMaterialPap(ResourceHandle* mpapHandle, ResourceHandle* imc) { - if (mpapHandle == null) + if (mpapHandle is null) return null; var path = ResolveMaterialAnimationPath(imc); @@ -354,7 +352,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromMaterialSklb(SkeletonResourceHandle* sklbHandle) { - if (sklbHandle == null) + if (sklbHandle is null) return null; if (!Utf8GamePath.FromString(GamePaths.Skeleton.Sklb.MaterialAnimationSkeletonPath, out var path)) @@ -371,7 +369,7 @@ internal unsafe partial record ResolveContext( public ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, ResourceHandle* phybHandle, uint partialSkeletonIndex) { - if (sklb == null || sklb->SkeletonResourceHandle == null) + if (sklb is null || sklb->SkeletonResourceHandle is null) return null; var path = ResolveSkeletonPath(partialSkeletonIndex); @@ -379,12 +377,10 @@ internal unsafe partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)sklb->SkeletonResourceHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); - var skpNode = CreateParameterNodeFromPartialSkeleton(sklb, partialSkeletonIndex); - if (skpNode != null) + var node = CreateNode(ResourceType.Sklb, (nint)sklb, (ResourceHandle*)sklb->SkeletonResourceHandle, path, false); + if (CreateParameterNodeFromPartialSkeleton(sklb, partialSkeletonIndex) is { } skpNode) node.Children.Add(skpNode); - var phybNode = CreateNodeFromPhyb(phybHandle, partialSkeletonIndex); - if (phybNode != null) + if (CreateNodeFromPhyb(phybHandle, partialSkeletonIndex) is { } phybNode) node.Children.Add(phybNode); Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); @@ -393,7 +389,7 @@ internal unsafe partial record ResolveContext( private ResourceNode? CreateParameterNodeFromPartialSkeleton(PartialSkeleton* sklb, uint partialSkeletonIndex) { - if (sklb == null || sklb->SkeletonParameterResourceHandle == null) + if (sklb is null || sklb->SkeletonParameterResourceHandle is null) return null; var path = ResolveSkeletonParameterPath(partialSkeletonIndex); @@ -411,7 +407,7 @@ internal unsafe partial record ResolveContext( private ResourceNode? CreateNodeFromPhyb(ResourceHandle* phybHandle, uint partialSkeletonIndex) { - if (phybHandle == null) + if (phybHandle is null) return null; var path = ResolvePhysicsModulePath(partialSkeletonIndex); @@ -431,7 +427,9 @@ internal unsafe partial record ResolveContext( { var path = gamePath.Path.Split((byte)'/'); // Weapons intentionally left out. - var isEquipment = path.Count >= 2 && path[0].Span.SequenceEqual("chara"u8) && (path[1].Span.SequenceEqual("accessory"u8) || path[1].Span.SequenceEqual("equipment"u8)); + var isEquipment = path.Count >= 2 + && path[0].Span.SequenceEqual("chara"u8) + && (path[1].Span.SequenceEqual("accessory"u8) || path[1].Span.SequenceEqual("equipment"u8)); if (isEquipment) foreach (var item in Global.Identifier.Identify(Equipment.Set, 0, Equipment.Variant, Slot.ToSlot())) { @@ -447,7 +445,7 @@ internal unsafe partial record ResolveContext( } var dataFromPath = GuessUiDataFromPath(gamePath); - if (dataFromPath.Name != null) + if (dataFromPath.Name is not null) return dataFromPath; return isEquipment @@ -462,24 +460,13 @@ internal unsafe partial record ResolveContext( var name = obj.Key; if (obj.Value is IdentifiedCustomization) name = name[14..].Trim(); - if (name != "Unknown") + if (name is not "Unknown") return new ResourceNode.UiData(name, obj.Value.GetIcon().ToFlag()); } return new ResourceNode.UiData(null, ChangedItemIconFlag.Unknown); } - private static string? SafeGet(ReadOnlySpan array, Index index) - { - var i = index.GetOffset(array.Length); - return i >= 0 && i < array.Length ? array[i] : null; - } - private static ulong GetResourceHandleLength(ResourceHandle* handle) - { - if (handle == null) - return 0; - - return handle->GetLength(); - } + => handle is null ? 0ul : handle->GetLength(); } From e4cfd674ee1443f876574fa5f8e351413d739d7d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 05:39:19 +0100 Subject: [PATCH 1118/1381] Probably unnecessary size optimization. --- Penumbra/Interop/ResourceTree/ResourceNode.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 24cb8f02..3699ae0b 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -17,12 +17,12 @@ public class ResourceNode : ICloneable public Utf8GamePath[] PossibleGamePaths; public FullPath FullPath; public PathStatus FullPathStatus; + public bool ForceInternal; + public bool ForceProtected; public string? ModName; public readonly WeakReference Mod = new(null!); public string? ModRelativePath; public CiByteString AdditionalData; - public bool ForceInternal; - public bool ForceProtected; public readonly ulong Length; public readonly List Children; internal ResolveContext? ResolveContext; From 70844610d8a913ffd915d0348882cb14bd50a89f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 05:45:06 +0100 Subject: [PATCH 1119/1381] Primary constructor and some null-check cleanup. --- Penumbra/Interop/ResourceTree/ResourceTree.cs | 132 ++++++++---------- 1 file changed, 60 insertions(+), 72 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index ac1f889c..5e3f52d4 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -16,42 +16,35 @@ using ResourceHandle = FFXIVClientStructs.FFXIV.Client.System.Resource.Handle.Re namespace Penumbra.Interop.ResourceTree; -public class ResourceTree +public class ResourceTree( + string name, + string anonymizedName, + int gameObjectIndex, + nint gameObjectAddress, + nint drawObjectAddress, + bool localPlayerRelated, + bool playerRelated, + bool networked, + string collectionName, + string anonymizedCollectionName) { - public readonly string Name; - public readonly string AnonymizedName; - public readonly int GameObjectIndex; - public readonly nint GameObjectAddress; - public readonly nint DrawObjectAddress; - public readonly bool LocalPlayerRelated; - public readonly bool PlayerRelated; - public readonly bool Networked; - public readonly string CollectionName; - public readonly string AnonymizedCollectionName; - public readonly List Nodes; - public readonly HashSet FlatNodes; + public readonly string Name = name; + public readonly string AnonymizedName = anonymizedName; + public readonly int GameObjectIndex = gameObjectIndex; + public readonly nint GameObjectAddress = gameObjectAddress; + public readonly nint DrawObjectAddress = drawObjectAddress; + public readonly bool LocalPlayerRelated = localPlayerRelated; + public readonly bool PlayerRelated = playerRelated; + public readonly bool Networked = networked; + public readonly string CollectionName = collectionName; + public readonly string AnonymizedCollectionName = anonymizedCollectionName; + public readonly List Nodes = []; + public readonly HashSet FlatNodes = []; public int ModelId; public CustomizeData CustomizeData; public GenderRace RaceCode; - public ResourceTree(string name, string anonymizedName, int gameObjectIndex, nint gameObjectAddress, nint drawObjectAddress, - bool localPlayerRelated, bool playerRelated, bool networked, string collectionName, string anonymizedCollectionName) - { - Name = name; - AnonymizedName = anonymizedName; - GameObjectIndex = gameObjectIndex; - GameObjectAddress = gameObjectAddress; - DrawObjectAddress = drawObjectAddress; - LocalPlayerRelated = localPlayerRelated; - Networked = networked; - PlayerRelated = playerRelated; - CollectionName = collectionName; - AnonymizedCollectionName = anonymizedCollectionName; - Nodes = []; - FlatNodes = []; - } - public void ProcessPostfix(Action action) { foreach (var node in Nodes) @@ -73,13 +66,13 @@ public class ResourceTree }; ModelId = character->ModelContainer.ModelCharaId; CustomizeData = character->DrawData.CustomizeData; - RaceCode = human != null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; + RaceCode = human is not null ? (GenderRace)human->RaceSexId : GenderRace.Unknown; var genericContext = globalContext.CreateContext(model); // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) var mpapArrayPtr = *(ResourceHandle***)((nint)model + 0x948); - var mpapArray = null != mpapArrayPtr ? new ReadOnlySpan>(mpapArrayPtr, model->SlotCount) : []; + var mpapArray = mpapArrayPtr is not null ? new ReadOnlySpan>(mpapArrayPtr, model->SlotCount) : []; var decalArray = modelType switch { ModelType.Human => human->SlotDecalsSpan, @@ -105,19 +98,17 @@ public class ResourceTree : globalContext.CreateContext(model, i), }; - var imc = (ResourceHandle*)model->IMCArray[i]; - var imcNode = slotContext.CreateNodeFromImc(imc); - if (imcNode != null) + var imc = (ResourceHandle*)model->IMCArray[i]; + if (slotContext.CreateNodeFromImc(imc) is { } imcNode) { if (globalContext.WithUiData) imcNode.FallbackName = $"IMC #{i}"; Nodes.Add(imcNode); } - var mdl = model->Models[i]; - var mdlNode = slotContext.CreateNodeFromModel(mdl, imc, i < decalArray.Length ? decalArray[(int)i].Value : null, - i < mpapArray.Length ? mpapArray[(int)i].Value : null); - if (mdlNode != null) + var mdl = model->Models[i]; + if (slotContext.CreateNodeFromModel(mdl, imc, i < decalArray.Length ? decalArray[(int)i].Value : null, + i < mpapArray.Length ? mpapArray[(int)i].Value : null) is { } mdlNode) { if (globalContext.WithUiData) mdlNode.FallbackName = $"Model #{i}"; @@ -131,7 +122,7 @@ public class ResourceTree AddWeapons(globalContext, model); - if (human != null) + if (human is not null) AddHumanResources(globalContext, human); } @@ -141,12 +132,12 @@ public class ResourceTree var weaponNodes = new List(); foreach (var baseSubObject in model->DrawObject.Object.ChildObjects) { - if (baseSubObject->GetObjectType() != FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType.CharacterBase) + if (baseSubObject->GetObjectType() is not FFXIVClientStructs.FFXIV.Client.Graphics.Scene.ObjectType.CharacterBase) continue; var subObject = (CharacterBase*)baseSubObject; - if (subObject->GetModelType() != ModelType.Weapon) + if (subObject->GetModelType() is not ModelType.Weapon) continue; var weapon = (Weapon*)subObject; @@ -160,24 +151,22 @@ public class ResourceTree // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) var mpapArrayPtr = *(ResourceHandle***)((nint)subObject + 0x948); - var mpapArray = null != mpapArrayPtr ? new ReadOnlySpan>(mpapArrayPtr, subObject->SlotCount) : []; + var mpapArray = mpapArrayPtr is not null ? new ReadOnlySpan>(mpapArrayPtr, subObject->SlotCount) : []; for (var i = 0; i < subObject->SlotCount; ++i) { var slotContext = globalContext.CreateContext(subObject, (uint)i, slot, equipment, weaponType); - var imc = (ResourceHandle*)subObject->IMCArray[i]; - var imcNode = slotContext.CreateNodeFromImc(imc); - if (imcNode != null) + var imc = (ResourceHandle*)subObject->IMCArray[i]; + if (slotContext.CreateNodeFromImc(imc) is { } imcNode) { if (globalContext.WithUiData) imcNode.FallbackName = $"Weapon #{weaponIndex}, IMC #{i}"; weaponNodes.Add(imcNode); } - var mdl = subObject->Models[i]; - var mdlNode = slotContext.CreateNodeFromModel(mdl, imc, weapon->Decal, i < mpapArray.Length ? mpapArray[i].Value : null); - if (mdlNode != null) + var mdl = subObject->Models[i]; + if (slotContext.CreateNodeFromModel(mdl, imc, weapon->Decal, i < mpapArray.Length ? mpapArray[i].Value : null) is { } mdlNode) { if (globalContext.WithUiData) mdlNode.FallbackName = $"Weapon #{weaponIndex}, Model #{i}"; @@ -185,9 +174,11 @@ public class ResourceTree } } - AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, subObject->BonePhysicsModule, $"Weapon #{weaponIndex}, "); + AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, subObject->BonePhysicsModule, + $"Weapon #{weaponIndex}, "); // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) - AddMaterialAnimationSkeleton(weaponNodes, genericContext, *(SkeletonResourceHandle**)((nint)subObject + 0x940), $"Weapon #{weaponIndex}, "); + AddMaterialAnimationSkeleton(weaponNodes, genericContext, *(SkeletonResourceHandle**)((nint)subObject + 0x940), + $"Weapon #{weaponIndex}, "); ++weaponIndex; } @@ -200,28 +191,25 @@ public class ResourceTree var genericContext = globalContext.CreateContext(&human->CharacterBase); var cache = globalContext.Collection._cache; - if (cache != null && cache.CustomResources.TryGetValue(PreBoneDeformerReplacer.PreBoneDeformerPath, out var pbdHandle)) + if (cache is not null + && cache.CustomResources.TryGetValue(PreBoneDeformerReplacer.PreBoneDeformerPath, out var pbdHandle) + && genericContext.CreateNodeFromPbd(pbdHandle.ResourceHandle) is { } pbdNode) { - var pbdNode = genericContext.CreateNodeFromPbd(pbdHandle.ResourceHandle); - if (pbdNode != null) + if (globalContext.WithUiData) { - if (globalContext.WithUiData) - { - pbdNode = pbdNode.Clone(); - pbdNode.FallbackName = "Racial Deformer"; - pbdNode.IconFlag = ChangedItemIconFlag.Customization; - } - - Nodes.Add(pbdNode); + pbdNode = pbdNode.Clone(); + pbdNode.FallbackName = "Racial Deformer"; + pbdNode.IconFlag = ChangedItemIconFlag.Customization; } + + Nodes.Add(pbdNode); } var decalId = (byte)(human->Customize[(int)CustomizeIndex.Facepaint] & 0x7F); - var decalPath = decalId != 0 + var decalPath = decalId is not 0 ? GamePaths.Human.Decal.FaceDecalPath(decalId) : GamePaths.Tex.TransparentPath; - var decalNode = genericContext.CreateNodeFromTex(human->Decal, decalPath); - if (decalNode != null) + if (genericContext.CreateNodeFromTex(human->Decal, decalPath) is { } decalNode) { if (globalContext.WithUiData) { @@ -237,8 +225,7 @@ public class ResourceTree var legacyDecalPath = hasLegacyDecal ? GamePaths.Human.Decal.LegacyDecalPath : GamePaths.Tex.TransparentPath; - var legacyDecalNode = genericContext.CreateNodeFromTex(human->LegacyBodyDecal, legacyDecalPath); - if (legacyDecalNode != null) + if (genericContext.CreateNodeFromTex(human->LegacyBodyDecal, legacyDecalPath) is { } legacyDecalNode) { legacyDecalNode.ForceProtected = !hasLegacyDecal; if (globalContext.WithUiData) @@ -252,7 +239,8 @@ public class ResourceTree } } - private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, BonePhysicsModule* physics, string prefix = "") + private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, BonePhysicsModule* physics, + string prefix = "") { var eidNode = context.CreateNodeFromEid((ResourceHandle*)eid); if (eidNode != null) @@ -269,8 +257,7 @@ public class ResourceTree { // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) var phybHandle = physics != null ? ((ResourceHandle**)((nint)physics + 0x190))[i] : null; - var sklbNode = context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, (uint)i); - if (sklbNode != null) + if (context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, (uint)i) is { } sklbNode) { if (context.Global.WithUiData) sklbNode.FallbackName = $"{prefix}Skeleton #{i}"; @@ -279,10 +266,11 @@ public class ResourceTree } } - private unsafe void AddMaterialAnimationSkeleton(List nodes, ResolveContext context, SkeletonResourceHandle* sklbHandle, string prefix = "") + private unsafe void AddMaterialAnimationSkeleton(List nodes, ResolveContext context, SkeletonResourceHandle* sklbHandle, + string prefix = "") { var sklbNode = context.CreateNodeFromMaterialSklb(sklbHandle); - if (sklbNode == null) + if (sklbNode is null) return; if (context.Global.WithUiData) From 9b25193d4e6feb39136b69a522b84b395b35fce2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 05:51:25 +0100 Subject: [PATCH 1120/1381] ImUtf8 and null-check cleanup. --- .../ModEditWindow.QuickImport.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index a49d2933..00caaabc 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -1,8 +1,7 @@ using Dalamud.Interface; using ImGuiNET; using Lumina.Data; -using OtterGui; -using OtterGui.Raii; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; @@ -43,7 +42,7 @@ public partial class ModEditWindow private void DrawQuickImportTab() { - using var tab = ImRaii.TabItem("Import from Screen"); + using var tab = ImUtf8.TabItem("Import from Screen"u8); if (!tab) { _quickImportActions.Clear(); @@ -73,14 +72,14 @@ public partial class ModEditWindow else { var file = _gameData.GetFile(path); - writable = file == null ? null : new RawGameFileWritable(file); + writable = file is null ? null : new RawGameFileWritable(file); } _quickImportWritables.Add(resourceNode.FullPath, writable); } - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Save.ToIconString(), buttonSize, "Export this file.", - resourceNode.FullPath.FullName.Length == 0 || writable == null, true)) + if (ImUtf8.IconButton(FontAwesomeIcon.Save, "Export this file."u8, buttonSize, + resourceNode.FullPath.FullName.Length is 0 || writable is null)) { var fullPathStr = resourceNode.FullPath.FullName; var ext = resourceNode.PossibleGamePaths.Length == 1 @@ -112,16 +111,17 @@ public partial class ModEditWindow var canQuickImport = quickImport.CanExecute; var quickImportEnabled = canQuickImport && (!resourceNode.Protected || _config.DeleteModModifier.IsActive()); - if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.FileImport.ToIconString(), buttonSize, + if (ImUtf8.IconButton(FontAwesomeIcon.FileImport, $"Add a copy of this file to {quickImport.OptionName}.{(canQuickImport && !quickImportEnabled ? $"\nHold {_config.DeleteModModifier} while clicking to add." : string.Empty)}", - !quickImportEnabled, true)) + buttonSize, + !quickImportEnabled)) { quickImport.Execute(); _quickImportActions.Remove((resourceNode.GamePath, writable)); } } - private record class RawFileWritable(string Path) : IWritable + private record RawFileWritable(string Path) : IWritable { public bool Valid => true; @@ -130,7 +130,7 @@ public partial class ModEditWindow => File.ReadAllBytes(Path); } - private record class RawGameFileWritable(FileResource FileResource) : IWritable + private record RawGameFileWritable(FileResource FileResource) : IWritable { public bool Valid => true; @@ -188,19 +188,19 @@ public partial class ModEditWindow public static QuickImportAction Prepare(ModEditWindow owner, Utf8GamePath gamePath, IWritable? file) { var editor = owner._editor; - if (editor == null) + if (editor is null) return new QuickImportAction(owner._editor, FallbackOptionName, gamePath); var subMod = editor.Option!; var optionName = subMod is IModOption o ? o.FullName : FallbackOptionName; - if (gamePath.IsEmpty || file == null || editor.FileEditor.Changes) + if (gamePath.IsEmpty || file is null || editor.FileEditor.Changes) return new QuickImportAction(editor, optionName, gamePath); if (subMod.Files.ContainsKey(gamePath) || subMod.FileSwaps.ContainsKey(gamePath)) return new QuickImportAction(editor, optionName, gamePath); var mod = owner.Mod; - if (mod == null) + if (mod is null) return new QuickImportAction(editor, optionName, gamePath); var (preferredPath, subDirs) = GetPreferredPath(mod, subMod as IModOption, owner._config.ReplaceNonAsciiOnImport); @@ -235,7 +235,7 @@ public partial class ModEditWindow { var path = mod.ModPath; var subDirs = 0; - if (subMod == null) + if (subMod is null) return (path, subDirs); var name = subMod.Name; From 8860d1e39afd872eabb140f4dd955896c61d9db7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 06:01:08 +0100 Subject: [PATCH 1121/1381] Fix an exception in incognito names in weird cutscene cases. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c59b1da6..f42c7fc9 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c59b1da61610e656b3e89f9c33113d08f97ae6c7 +Subproject commit f42c7fc9de98e9fc72680dee7805251fd938af26 From c6de7ddebd7af3b52ecb5ebebe86efef07597b1e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 13:08:41 +0100 Subject: [PATCH 1122/1381] Improve GamePaths and parsing, add support for identifying skeletons and phybs. --- Penumbra.GameData | 2 +- Penumbra/Import/Models/ModelManager.cs | 12 ++++---- .../ResolveContext.PathResolution.cs | 14 ++++----- .../Interop/ResourceTree/ResolveContext.cs | 12 ++++---- Penumbra/Interop/ResourceTree/ResourceTree.cs | 8 ++--- Penumbra/Meta/Manipulations/Eqdp.cs | 2 +- Penumbra/Meta/Manipulations/Eqp.cs | 2 +- Penumbra/Meta/Manipulations/Est.cs | 8 ++--- .../Manipulations/GlobalEqpManipulation.cs | 10 +++---- Penumbra/Meta/Manipulations/Gmp.cs | 2 +- Penumbra/Meta/Manipulations/Imc.cs | 24 +++++---------- Penumbra/Mods/ItemSwap/CustomizationSwap.cs | 10 +++---- Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 30 +++++++------------ Penumbra/Mods/ItemSwap/ItemSwap.cs | 4 +-- .../Materials/MtrlTab.ShaderPackage.cs | 2 +- .../UI/AdvancedWindow/Meta/AtchMetaDrawer.cs | 4 +-- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 2 +- 17 files changed, 65 insertions(+), 83 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index f42c7fc9..bc339208 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit f42c7fc9de98e9fc72680dee7805251fd938af26 +Subproject commit bc339208d1d453582eb146533c572823146a4592 diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 0c19bc0a..19d06a52 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -63,7 +63,7 @@ public sealed class ModelManager(IFramework framework, MetaFileManager metaFileM if (info.FileType is not FileType.Model) return []; - var baseSkeleton = GamePaths.Skeleton.Sklb.Path(info.GenderRace, "base", 1); + var baseSkeleton = GamePaths.Sklb.Customization(info.GenderRace, "base", 1); return info.ObjectType switch { @@ -79,9 +79,9 @@ public sealed class ModelManager(IFramework framework, MetaFileManager metaFileM ObjectType.Character when info.BodySlot is BodySlot.Face or BodySlot.Ear => [baseSkeleton, ..ResolveEstSkeleton(EstType.Face, info, estManipulations)], ObjectType.Character => throw new Exception($"Currently unsupported human model type \"{info.BodySlot}\"."), - ObjectType.DemiHuman => [GamePaths.DemiHuman.Sklb.Path(info.PrimaryId)], - ObjectType.Monster => [GamePaths.Monster.Sklb.Path(info.PrimaryId)], - ObjectType.Weapon => [GamePaths.Weapon.Sklb.Path(info.PrimaryId)], + ObjectType.DemiHuman => [GamePaths.Sklb.DemiHuman(info.PrimaryId)], + ObjectType.Monster => [GamePaths.Sklb.Monster(info.PrimaryId)], + ObjectType.Weapon => [GamePaths.Sklb.Weapon(info.PrimaryId)], _ => [], }; } @@ -105,7 +105,7 @@ public sealed class ModelManager(IFramework framework, MetaFileManager metaFileM if (targetId == EstEntry.Zero) return []; - return [GamePaths.Skeleton.Sklb.Path(info.GenderRace, type.ToName(), targetId.AsId)]; + return [GamePaths.Sklb.Customization(info.GenderRace, type.ToName(), targetId.AsId)]; } /// Try to resolve the absolute path to a .mtrl from the potentially-partial path provided by a model. @@ -137,7 +137,7 @@ public sealed class ModelManager(IFramework framework, MetaFileManager metaFileM var resolvedPath = info.ObjectType switch { - ObjectType.Character => GamePaths.Character.Mtrl.Path( + ObjectType.Character => GamePaths.Mtrl.Customization( info.GenderRace, info.BodySlot, info.PrimaryId, relativePath, out _, out _, info.Variant), _ => absolutePath, }; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index b1ca24b0..b6d04769 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -43,8 +43,8 @@ internal partial record ResolveContext private Utf8GamePath ResolveEquipmentModelPath() { var path = IsEquipmentSlot(SlotIndex) - ? GamePaths.Equipment.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()) - : GamePaths.Accessory.Mdl.Path(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()); + ? GamePaths.Mdl.Equipment(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()) + : GamePaths.Mdl.Accessory(Equipment.Set, ResolveModelRaceCode(), SlotIndex.ToEquipSlot()); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -122,7 +122,7 @@ internal partial record ResolveContext var setIdHigh = Equipment.Set.Id / 100; // All MCH (20??) weapons' materials C are one and the same if (setIdHigh is 20 && mtrlFileName[14] == (byte)'c') - return Utf8GamePath.FromString(GamePaths.Weapon.Mtrl.Path(2001, 1, 1, "c"), out var path) ? path : Utf8GamePath.Empty; + return Utf8GamePath.FromString(GamePaths.Mtrl.Weapon(2001, 1, 1, "c"), out var path) ? path : Utf8GamePath.Empty; // Some offhands share materials with the corresponding mainhand if (ItemData.AdaptOffhandImc(Equipment.Set, out var mirroredSetId)) @@ -230,7 +230,7 @@ internal partial record ResolveContext if (set == 0) return Utf8GamePath.Empty; - var path = GamePaths.Skeleton.Sklb.Path(raceCode, slot, set); + var path = GamePaths.Sklb.Customization(raceCode, slot, set); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -300,7 +300,7 @@ internal partial record ResolveContext if (set.Id is 0) return Utf8GamePath.Empty; - var path = GamePaths.Skeleton.Skp.Path(raceCode, slot, set); + var path = GamePaths.Skp.Customization(raceCode, slot, set); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -328,7 +328,7 @@ internal partial record ResolveContext if (set.Id is 0) return Utf8GamePath.Empty; - var path = GamePaths.Skeleton.Phyb.Path(raceCode, slot, set); + var path = GamePaths.Phyb.Customization(raceCode, slot, set); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } @@ -354,7 +354,7 @@ internal partial record ResolveContext if (decal is 0) return Utf8GamePath.Empty; - var path = GamePaths.Equipment.Decal.Path(decal); + var path = GamePaths.Tex.EquipDecal(decal); return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } } diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 81904819..ea4506c7 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -355,13 +355,10 @@ internal unsafe partial record ResolveContext( if (sklbHandle is null) return null; - if (!Utf8GamePath.FromString(GamePaths.Skeleton.Sklb.MaterialAnimationSkeletonPath, out var path)) - return null; - - if (Global.Nodes.TryGetValue((path, (nint)sklbHandle), out var cached)) + if (Global.Nodes.TryGetValue((GamePaths.Sklb.MaterialAnimationSkeletonUtf8, (nint)sklbHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Sklb, 0, (ResourceHandle*)sklbHandle, path); + var node = CreateNode(ResourceType.Sklb, 0, (ResourceHandle*)sklbHandle, GamePaths.Sklb.MaterialAnimationSkeletonUtf8); node.ForceInternal = true; return node; @@ -455,11 +452,12 @@ internal unsafe partial record ResolveContext( internal ResourceNode.UiData GuessUiDataFromPath(Utf8GamePath gamePath) { + const string customization = "Customization: "; foreach (var obj in Global.Identifier.Identify(gamePath.ToString())) { var name = obj.Key; - if (obj.Value is IdentifiedCustomization) - name = name[14..].Trim(); + if (name.StartsWith(customization)) + name = name.AsSpan(14).Trim().ToString(); if (name is not "Unknown") return new ResourceNode.UiData(name, obj.Value.GetIcon().ToFlag()); } diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 5e3f52d4..7be8694a 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -207,8 +207,8 @@ public class ResourceTree( var decalId = (byte)(human->Customize[(int)CustomizeIndex.Facepaint] & 0x7F); var decalPath = decalId is not 0 - ? GamePaths.Human.Decal.FaceDecalPath(decalId) - : GamePaths.Tex.TransparentPath; + ? GamePaths.Tex.FaceDecal(decalId) + : GamePaths.Tex.Transparent; if (genericContext.CreateNodeFromTex(human->Decal, decalPath) is { } decalNode) { if (globalContext.WithUiData) @@ -223,8 +223,8 @@ public class ResourceTree( var hasLegacyDecal = (human->Customize[(int)CustomizeIndex.FaceFeatures] & 0x80) != 0; var legacyDecalPath = hasLegacyDecal - ? GamePaths.Human.Decal.LegacyDecalPath - : GamePaths.Tex.TransparentPath; + ? GamePaths.Tex.LegacyDecal + : GamePaths.Tex.Transparent; if (genericContext.CreateNodeFromTex(human->LegacyBodyDecal, legacyDecalPath) is { } legacyDecalNode) { legacyDecalNode.ForceProtected = !hasLegacyDecal; diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs index 3a804d0c..285f2309 100644 --- a/Penumbra/Meta/Manipulations/Eqdp.cs +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -16,7 +16,7 @@ public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, Ge => GenderRace.Split().Item1; public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, Slot)); + => identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, Slot)); public MetaIndex FileIndex() => CharacterUtilityData.EqdpIdx(GenderRace, Slot.IsAccessory()); diff --git a/Penumbra/Meta/Manipulations/Eqp.cs b/Penumbra/Meta/Manipulations/Eqp.cs index f758126c..c71f2f4d 100644 --- a/Penumbra/Meta/Manipulations/Eqp.cs +++ b/Penumbra/Meta/Manipulations/Eqp.cs @@ -9,7 +9,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct EqpIdentifier(PrimaryId SetId, EquipSlot Slot) : IMetaIdentifier, IComparable { public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace.MidlanderMale, Slot)); + => identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace.MidlanderMale, Slot)); public MetaIndex FileIndex() => MetaIndex.Eqp; diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs index cfe9b7d4..007cd02f 100644 --- a/Penumbra/Meta/Manipulations/Est.cs +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -30,17 +30,17 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende { case EstType.Hair: changedItems.TryAdd( - $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Hair (Hair) {SetId}", null); + $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Hair {SetId}", null); break; case EstType.Face: changedItems.TryAdd( - $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Face (Face) {SetId}", null); + $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Face {SetId}", null); break; case EstType.Body: - identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, EquipSlot.Body)); + identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Body)); break; case EstType.Head: - identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace, EquipSlot.Head)); + identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Head)); break; } } diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs index ec59762b..6a1ceaea 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -74,11 +74,11 @@ public readonly struct GlobalEqpManipulation : IMetaIdentifier { var path = Type switch { - GlobalEqpType.DoNotHideEarrings => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.Ears), - GlobalEqpType.DoNotHideNecklace => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.Neck), - GlobalEqpType.DoNotHideBracelets => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.Wrists), - GlobalEqpType.DoNotHideRingR => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.RFinger), - GlobalEqpType.DoNotHideRingL => GamePaths.Accessory.Mdl.Path(Condition, GenderRace.MidlanderMale, EquipSlot.LFinger), + GlobalEqpType.DoNotHideEarrings => GamePaths.Mdl.Accessory(Condition, GenderRace.MidlanderMale, EquipSlot.Ears), + GlobalEqpType.DoNotHideNecklace => GamePaths.Mdl.Accessory(Condition, GenderRace.MidlanderMale, EquipSlot.Neck), + GlobalEqpType.DoNotHideBracelets => GamePaths.Mdl.Accessory(Condition, GenderRace.MidlanderMale, EquipSlot.Wrists), + GlobalEqpType.DoNotHideRingR => GamePaths.Mdl.Accessory(Condition, GenderRace.MidlanderMale, EquipSlot.RFinger), + GlobalEqpType.DoNotHideRingL => GamePaths.Mdl.Accessory(Condition, GenderRace.MidlanderMale, EquipSlot.LFinger), GlobalEqpType.DoNotHideHrothgarHats => string.Empty, GlobalEqpType.DoNotHideVieraHats => string.Empty, _ => string.Empty, diff --git a/Penumbra/Meta/Manipulations/Gmp.cs b/Penumbra/Meta/Manipulations/Gmp.cs index 1f41adfb..8cd07bfd 100644 --- a/Penumbra/Meta/Manipulations/Gmp.cs +++ b/Penumbra/Meta/Manipulations/Gmp.cs @@ -9,7 +9,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct GmpIdentifier(PrimaryId SetId) : IMetaIdentifier, IComparable { public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - => identifier.Identify(changedItems, GamePaths.Equipment.Mdl.Path(SetId, GenderRace.MidlanderMale, EquipSlot.Head)); + => identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace.MidlanderMale, EquipSlot.Head)); public MetaIndex FileIndex() => MetaIndex.Gmp; diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index cba6c379..6e893043 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -34,14 +34,14 @@ public readonly record struct ImcIdentifier( { var path = ObjectType switch { - ObjectType.Equipment when allVariants => GamePaths.Equipment.Mdl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot), - ObjectType.Equipment => GamePaths.Equipment.Mtrl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot, Variant, "a"), - ObjectType.Accessory when allVariants => GamePaths.Accessory.Mdl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot), - ObjectType.Accessory => GamePaths.Accessory.Mtrl.Path(PrimaryId, GenderRace.MidlanderMale, EquipSlot, Variant, "a"), - ObjectType.Weapon => GamePaths.Weapon.Mtrl.Path(PrimaryId, SecondaryId.Id, Variant, "a"), - ObjectType.DemiHuman => GamePaths.DemiHuman.Mtrl.Path(PrimaryId, SecondaryId.Id, EquipSlot, Variant, + ObjectType.Equipment when allVariants => GamePaths.Mdl.Equipment(PrimaryId, GenderRace.MidlanderMale, EquipSlot), + ObjectType.Equipment => GamePaths.Mtrl.Equipment(PrimaryId, GenderRace.MidlanderMale, EquipSlot, Variant, "a"), + ObjectType.Accessory when allVariants => GamePaths.Mdl.Accessory(PrimaryId, GenderRace.MidlanderMale, EquipSlot), + ObjectType.Accessory => GamePaths.Mtrl.Accessory(PrimaryId, GenderRace.MidlanderMale, EquipSlot, Variant, "a"), + ObjectType.Weapon => GamePaths.Mtrl.Weapon(PrimaryId, SecondaryId.Id, Variant, "a"), + ObjectType.DemiHuman => GamePaths.Mtrl.DemiHuman(PrimaryId, SecondaryId.Id, EquipSlot, Variant, "a"), - ObjectType.Monster => GamePaths.Monster.Mtrl.Path(PrimaryId, SecondaryId.Id, Variant, "a"), + ObjectType.Monster => GamePaths.Mtrl.Monster(PrimaryId, SecondaryId.Id, Variant, "a"), _ => string.Empty, }; if (path.Length == 0) @@ -51,15 +51,7 @@ public readonly record struct ImcIdentifier( } public string GamePathString() - => ObjectType switch - { - ObjectType.Accessory => GamePaths.Accessory.Imc.Path(PrimaryId), - ObjectType.Equipment => GamePaths.Equipment.Imc.Path(PrimaryId), - ObjectType.DemiHuman => GamePaths.DemiHuman.Imc.Path(PrimaryId, SecondaryId.Id), - ObjectType.Monster => GamePaths.Monster.Imc.Path(PrimaryId, SecondaryId.Id), - ObjectType.Weapon => GamePaths.Weapon.Imc.Path(PrimaryId, SecondaryId.Id), - _ => string.Empty, - }; + => GamePaths.Imc.Path(ObjectType, PrimaryId, SecondaryId); public Utf8GamePath GamePath() => Utf8GamePath.FromString(GamePathString(), out var p) ? p : Utf8GamePath.Empty; diff --git a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs index cd36de93..c5406f66 100644 --- a/Penumbra/Mods/ItemSwap/CustomizationSwap.cs +++ b/Penumbra/Mods/ItemSwap/CustomizationSwap.cs @@ -17,8 +17,8 @@ public static class CustomizationSwap if (idFrom.Id > byte.MaxValue) throw new Exception($"The Customization ID {idFrom} is too large for {slot}."); - var mdlPathFrom = GamePaths.Character.Mdl.Path(race, slot, idFrom, slot.ToCustomizationType()); - var mdlPathTo = GamePaths.Character.Mdl.Path(race, slot, idTo, slot.ToCustomizationType()); + var mdlPathFrom = GamePaths.Mdl.Customization(race, slot, idFrom, slot.ToCustomizationType()); + var mdlPathTo = GamePaths.Mdl.Customization(race, slot, idTo, slot.ToCustomizationType()); var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); var range = slot == BodySlot.Tail @@ -47,8 +47,8 @@ public static class CustomizationSwap ref string fileName, ref bool dataWasChanged) { variant = slot is BodySlot.Face or BodySlot.Ear ? Variant.None.Id : variant; - var mtrlFromPath = GamePaths.Character.Mtrl.Path(race, slot, idFrom, fileName, out var gameRaceFrom, out var gameSetIdFrom, variant); - var mtrlToPath = GamePaths.Character.Mtrl.Path(race, slot, idTo, fileName, out var gameRaceTo, out var gameSetIdTo, variant); + var mtrlFromPath = GamePaths.Mtrl.Customization(race, slot, idFrom, fileName, out var gameRaceFrom, out var gameSetIdFrom, variant); + var mtrlToPath = GamePaths.Mtrl.Customization(race, slot, idTo, fileName, out var gameRaceTo, out var gameSetIdTo, variant); var newFileName = fileName; newFileName = ItemSwap.ReplaceRace(newFileName, gameRaceTo, race, gameRaceTo != race); @@ -60,7 +60,7 @@ public static class CustomizationSwap var actualMtrlFromPath = mtrlFromPath; if (newFileName != fileName) { - actualMtrlFromPath = GamePaths.Character.Mtrl.Path(race, slot, idFrom, newFileName, out _, out _, variant); + actualMtrlFromPath = GamePaths.Mtrl.Customization(race, slot, idFrom, newFileName, out _, out _, variant); fileName = newFileName; dataWasChanged = true; } diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 8c80c91c..5c67df52 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -107,7 +107,7 @@ public static class EquipmentSwap foreach (var child in eqp.ChildSwaps.SelectMany(c => c.WithChildren()).OfType>()) { affectedItems.UnionWith(identifier - .Identify(GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, child.SwapFromIdentifier.Slot)) + .Identify(GamePaths.Mdl.Equipment(idFrom, GenderRace.MidlanderMale, child.SwapFromIdentifier.Slot)) .Select(kvp => kvp.Value).OfType().Select(i => i.Item)); } } @@ -223,11 +223,9 @@ public static class EquipmentSwap public static FileSwap CreateMdl(MetaFileManager manager, Func redirections, EquipSlot slotFrom, EquipSlot slotTo, GenderRace gr, PrimaryId idFrom, PrimaryId idTo, byte mtrlTo) { - var mdlPathFrom = slotFrom.IsAccessory() - ? GamePaths.Accessory.Mdl.Path(idFrom, gr, slotFrom) - : GamePaths.Equipment.Mdl.Path(idFrom, gr, slotFrom); - var mdlPathTo = slotTo.IsAccessory() ? GamePaths.Accessory.Mdl.Path(idTo, gr, slotTo) : GamePaths.Equipment.Mdl.Path(idTo, gr, slotTo); - var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); + var mdlPathFrom = GamePaths.Mdl.Gear(idFrom, gr, slotFrom); + var mdlPathTo = GamePaths.Mdl.Gear(idTo, gr, slotTo); + var mdl = FileSwap.CreateSwap(manager, ResourceType.Mdl, redirections, mdlPathFrom, mdlPathTo); foreach (ref var fileName in mdl.AsMdl()!.Materials.AsSpan()) { @@ -264,9 +262,7 @@ public static class EquipmentSwap } else { - items = identifier.Identify(slotFrom.IsEquipment() - ? GamePaths.Equipment.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom) - : GamePaths.Accessory.Mdl.Path(idFrom, GenderRace.MidlanderMale, slotFrom)) + items = identifier.Identify(GamePaths.Mdl.Gear(idFrom, GenderRace.MidlanderMale, slotFrom)) .Select(kvp => kvp.Value).OfType().Select(i => i.Item) .ToHashSet(); variants = Enumerable.Range(0, imc.Count + 1).Select(i => (Variant)i).ToArray(); @@ -324,7 +320,7 @@ public static class EquipmentSwap if (decalId == 0) return null; - var decalPath = GamePaths.Equipment.Decal.Path(decalId); + var decalPath = GamePaths.Tex.EquipDecal(decalId); return FileSwap.CreateSwap(manager, ResourceType.Tex, redirections, decalPath, decalPath); } @@ -337,9 +333,9 @@ public static class EquipmentSwap if (vfxId == 0) return null; - var vfxPathFrom = GamePaths.Equipment.Avfx.Path(idFrom, vfxId); + var vfxPathFrom = GamePaths.Avfx.Path(slotFrom, idFrom, vfxId); vfxPathFrom = ItemSwap.ReplaceType(vfxPathFrom, slotFrom, slotTo, idFrom); - var vfxPathTo = GamePaths.Equipment.Avfx.Path(idTo, vfxId); + var vfxPathTo = GamePaths.Avfx.Path(slotTo, idTo, vfxId); var avfx = FileSwap.CreateSwap(manager, ResourceType.Avfx, redirections, vfxPathFrom, vfxPathTo); foreach (ref var filePath in avfx.AsAvfx()!.Textures.AsSpan()) @@ -402,14 +398,10 @@ public static class EquipmentSwap if (!fileName.Contains($"{prefix}{idTo.Id:D4}")) return null; - var folderTo = slotTo.IsAccessory() - ? GamePaths.Accessory.Mtrl.FolderPath(idTo, variantTo) - : GamePaths.Equipment.Mtrl.FolderPath(idTo, variantTo); + var folderTo = GamePaths.Mtrl.GearFolder(slotTo, idTo, variantTo); var pathTo = $"{folderTo}{fileName}"; - var folderFrom = slotFrom.IsAccessory() - ? GamePaths.Accessory.Mtrl.FolderPath(idFrom, variantTo) - : GamePaths.Equipment.Mtrl.FolderPath(idFrom, variantTo); + var folderFrom = GamePaths.Mtrl.GearFolder(slotFrom, idFrom, variantTo); var newFileName = ItemSwap.ReplaceId(fileName, prefix, idTo, idFrom); newFileName = ItemSwap.ReplaceSlot(newFileName, slotTo, slotFrom, slotTo != slotFrom); var pathFrom = $"{folderFrom}{newFileName}"; @@ -457,7 +449,7 @@ public static class EquipmentSwap public static FileSwap CreateShader(MetaFileManager manager, Func redirections, ref string shaderName, ref bool dataWasChanged) { - var path = $"shader/sm5/shpk/{shaderName}"; + var path = GamePaths.Shader(shaderName); return FileSwap.CreateSwap(manager, ResourceType.Shpk, redirections, path, path); } diff --git a/Penumbra/Mods/ItemSwap/ItemSwap.cs b/Penumbra/Mods/ItemSwap/ItemSwap.cs index 03abfc45..0049fa12 100644 --- a/Penumbra/Mods/ItemSwap/ItemSwap.cs +++ b/Penumbra/Mods/ItemSwap/ItemSwap.cs @@ -132,14 +132,14 @@ public static class ItemSwap public static FileSwap CreatePhyb(MetaFileManager manager, Func redirections, EstType type, GenderRace race, EstEntry estEntry) { - var phybPath = GamePaths.Skeleton.Phyb.Path(race, type.ToName(), estEntry.AsId); + var phybPath = GamePaths.Phyb.Customization(race, type.ToName(), estEntry.AsId); return FileSwap.CreateSwap(manager, ResourceType.Phyb, redirections, phybPath, phybPath); } public static FileSwap CreateSklb(MetaFileManager manager, Func redirections, EstType type, GenderRace race, EstEntry estEntry) { - var sklbPath = GamePaths.Skeleton.Sklb.Path(race, type.ToName(), estEntry.AsId); + var sklbPath = GamePaths.Sklb.Customization(race, type.ToName(), estEntry.AsId); return FileSwap.CreateSwap(manager, ResourceType.Sklb, redirections, sklbPath, sklbPath); } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs index ae57a122..a13dd96b 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -124,7 +124,7 @@ public partial class MtrlTab private FullPath FindAssociatedShpk(out string defaultPath, out Utf8GamePath defaultGamePath) { - defaultPath = GamePaths.Shader.ShpkPath(Mtrl.ShaderPackage.Name); + defaultPath = GamePaths.Shader(Mtrl.ShaderPackage.Name); if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) return FullPath.Empty; diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs index 66db0932..80b10607 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs @@ -55,7 +55,7 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer if (filePath.Length == 0 || !File.Exists(filePath)) throw new FileNotFoundException(); - var gr = GamePaths.ParseRaceCode(filePath); + var gr = Parser.ParseRaceCode(filePath); if (gr is GenderRace.Unknown) throw new Exception($"Could not identify race code from path {filePath}."); var text = File.ReadAllBytes(filePath); @@ -277,7 +277,7 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer if (!ret) return false; - index = Math.Clamp(index, (ushort)0, (ushort)(currentAtchPoint!.Entries.Length - 1)); + index = Math.Clamp(index, (ushort)0, (ushort)(currentAtchPoint.Entries.Length - 1)); identifier = identifier with { EntryIndex = index }; return true; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 1356340c..c9a1d059 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -68,7 +68,7 @@ public partial class ModEditWindow { _dragDropManager.CreateImGuiSource("atchDrag", f => f.Extensions.Contains(".atch"), f => { - var gr = GamePaths.ParseRaceCode(f.Files.FirstOrDefault() ?? string.Empty); + var gr = Parser.ParseRaceCode(f.Files.FirstOrDefault() ?? string.Empty); if (gr is GenderRace.Unknown) return false; From 1ebe4099d6782c60ab3769be2b1801d42bb07480 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Feb 2025 17:51:27 +0100 Subject: [PATCH 1123/1381] Add ImGuiCacheService. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 0b6085ce..3bf047bf 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 0b6085ce720ffb7c78cf42d4e51861f34db27744 +Subproject commit 3bf047bfa293817a691b7f06032bae7aeb2e4dc7 From deba8ac9101572d3f7245e6a2fe4c8b33a34e0dc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Mar 2025 00:33:56 +0100 Subject: [PATCH 1124/1381] Heavily improve changed item display. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/Api/UiApi.cs | 8 +- Penumbra/Api/ModChangedItemAdapter.cs | 2 +- Penumbra/Collections/Cache/CollectionCache.cs | 6 +- .../Collections/ModCollection.Cache.Access.cs | 4 +- Penumbra/Communication/ChangedItemClick.cs | 2 +- Penumbra/Communication/ChangedItemHover.cs | 2 +- Penumbra/Meta/Manipulations/AtchIdentifier.cs | 2 +- Penumbra/Meta/Manipulations/Eqdp.cs | 2 +- Penumbra/Meta/Manipulations/Eqp.cs | 2 +- Penumbra/Meta/Manipulations/Est.cs | 10 +- .../Manipulations/GlobalEqpManipulation.cs | 6 +- Penumbra/Meta/Manipulations/Gmp.cs | 2 +- .../Meta/Manipulations/IMetaIdentifier.cs | 2 +- Penumbra/Meta/Manipulations/Imc.cs | 4 +- Penumbra/Meta/Manipulations/Rsp.cs | 4 +- Penumbra/Mods/Groups/CombiningModGroup.cs | 2 +- Penumbra/Mods/Groups/IModGroup.cs | 2 +- Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 2 +- Penumbra/Mods/Groups/SingleModGroup.cs | 2 +- Penumbra/Mods/Manager/ModCacheManager.cs | 1 + Penumbra/Mods/Mod.cs | 9 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 3 +- Penumbra/UI/ChangedItemDrawer.cs | 83 +++--- .../UI/ModsTab/ModPanelChangedItemsTab.cs | 253 ++++++++++++++++-- Penumbra/UI/Tabs/ChangedItemsTab.cs | 57 ++-- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 +- Penumbra/Util/IdentifierExtensions.cs | 6 +- 30 files changed, 360 insertions(+), 126 deletions(-) diff --git a/OtterGui b/OtterGui index 3bf047bf..c347d29d 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3bf047bfa293817a691b7f06032bae7aeb2e4dc7 +Subproject commit c347d29d980b0191d1d071170cf2ec229e3efdcf diff --git a/Penumbra.GameData b/Penumbra.GameData index bc339208..955c4e6b 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit bc339208d1d453582eb146533c572823146a4592 +Subproject commit 955c4e6b281bf0781689b15c01a868b0de5881b4 diff --git a/Penumbra/Api/Api/UiApi.cs b/Penumbra/Api/Api/UiApi.cs index 515874c0..b14f67ae 100644 --- a/Penumbra/Api/Api/UiApi.cs +++ b/Penumbra/Api/Api/UiApi.cs @@ -81,21 +81,21 @@ public class UiApi : IPenumbraApiUi, IApiService, IDisposable public void CloseMainWindow() => _configWindow.IsOpen = false; - private void OnChangedItemClick(MouseButton button, IIdentifiedObjectData? data) + private void OnChangedItemClick(MouseButton button, IIdentifiedObjectData data) { if (ChangedItemClicked == null) return; - var (type, id) = data?.ToApiObject() ?? (ChangedItemType.None, 0); + var (type, id) = data.ToApiObject(); ChangedItemClicked.Invoke(button, type, id); } - private void OnChangedItemHover(IIdentifiedObjectData? data) + private void OnChangedItemHover(IIdentifiedObjectData data) { if (ChangedItemTooltip == null) return; - var (type, id) = data?.ToApiObject() ?? (ChangedItemType.None, 0); + var (type, id) = data.ToApiObject(); ChangedItemTooltip.Invoke(type, id); } } diff --git a/Penumbra/Api/ModChangedItemAdapter.cs b/Penumbra/Api/ModChangedItemAdapter.cs index 8842f20a..8d2d473c 100644 --- a/Penumbra/Api/ModChangedItemAdapter.cs +++ b/Penumbra/Api/ModChangedItemAdapter.cs @@ -65,7 +65,7 @@ public sealed class ModChangedItemAdapter(WeakReference storage) : throw new ObjectDisposedException("The underlying mod storage of this IPC container was disposed."); } - private sealed class ChangedItemDictionaryAdapter(SortedList data) : IReadOnlyDictionary + private sealed class ChangedItemDictionaryAdapter(SortedList data) : IReadOnlyDictionary { public IEnumerator> GetEnumerator() => data.Select(d => new KeyValuePair(d.Key, d.Value?.ToInternalObject())).GetEnumerator(); diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index a80928d0..42c8b27d 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -23,7 +23,7 @@ public sealed class CollectionCache : IDisposable private readonly CollectionCacheManager _manager; private readonly ModCollection _collection; public readonly CollectionModData ModData = new(); - private readonly SortedList, IIdentifiedObjectData?)> _changedItems = []; + private readonly SortedList, IIdentifiedObjectData)> _changedItems = []; public readonly ConcurrentDictionary ResolvedFiles = new(); public readonly CustomResourceCache CustomResources; public readonly MetaCache Meta; @@ -43,7 +43,7 @@ public sealed class CollectionCache : IDisposable private int _changedItemsSaveCounter = -1; // Obtain currently changed items. Computes them if they haven't been computed before. - public IReadOnlyDictionary, IIdentifiedObjectData?)> ChangedItems + public IReadOnlyDictionary, IIdentifiedObjectData)> ChangedItems { get { @@ -441,7 +441,7 @@ public sealed class CollectionCache : IDisposable // Skip IMCs because they would result in far too many false-positive items, // since they are per set instead of per item-slot/item/variant. var identifier = _manager.MetaFileManager.Identifier; - var items = new SortedList(512); + var items = new SortedList(512); void AddItems(IMod mod) { diff --git a/Penumbra/Collections/ModCollection.Cache.Access.cs b/Penumbra/Collections/ModCollection.Cache.Access.cs index 0b38dde8..716b153e 100644 --- a/Penumbra/Collections/ModCollection.Cache.Access.cs +++ b/Penumbra/Collections/ModCollection.Cache.Access.cs @@ -46,8 +46,8 @@ public partial class ModCollection internal IReadOnlyDictionary ResolvedFiles => _cache?.ResolvedFiles ?? new ConcurrentDictionary(); - internal IReadOnlyDictionary, IIdentifiedObjectData?)> ChangedItems - => _cache?.ChangedItems ?? new Dictionary, IIdentifiedObjectData?)>(); + internal IReadOnlyDictionary, IIdentifiedObjectData)> ChangedItems + => _cache?.ChangedItems ?? new Dictionary, IIdentifiedObjectData)>(); internal IEnumerable> AllConflicts => _cache?.AllConflicts ?? Array.Empty>(); diff --git a/Penumbra/Communication/ChangedItemClick.cs b/Penumbra/Communication/ChangedItemClick.cs index 1aac4454..2d27f36a 100644 --- a/Penumbra/Communication/ChangedItemClick.cs +++ b/Penumbra/Communication/ChangedItemClick.cs @@ -12,7 +12,7 @@ namespace Penumbra.Communication; /// Parameter is the clicked object data if any. /// /// -public sealed class ChangedItemClick() : EventWrapper(nameof(ChangedItemClick)) +public sealed class ChangedItemClick() : EventWrapper(nameof(ChangedItemClick)) { public enum Priority { diff --git a/Penumbra/Communication/ChangedItemHover.cs b/Penumbra/Communication/ChangedItemHover.cs index 4e72b558..92d770f7 100644 --- a/Penumbra/Communication/ChangedItemHover.cs +++ b/Penumbra/Communication/ChangedItemHover.cs @@ -10,7 +10,7 @@ namespace Penumbra.Communication; /// Parameter is the hovered object data if any. /// /// -public sealed class ChangedItemHover() : EventWrapper(nameof(ChangedItemHover)) +public sealed class ChangedItemHover() : EventWrapper(nameof(ChangedItemHover)) { public enum Priority { diff --git a/Penumbra/Meta/Manipulations/AtchIdentifier.cs b/Penumbra/Meta/Manipulations/AtchIdentifier.cs index bce37620..c248c48b 100644 --- a/Penumbra/Meta/Manipulations/AtchIdentifier.cs +++ b/Penumbra/Meta/Manipulations/AtchIdentifier.cs @@ -31,7 +31,7 @@ public readonly record struct AtchIdentifier(AtchType Type, GenderRace GenderRac public override string ToString() => $"Atch - {Type.ToAbbreviation()} - {GenderRace.ToName()} - {EntryIndex}"; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { // Nothing specific } diff --git a/Penumbra/Meta/Manipulations/Eqdp.cs b/Penumbra/Meta/Manipulations/Eqdp.cs index 285f2309..c8423b92 100644 --- a/Penumbra/Meta/Manipulations/Eqdp.cs +++ b/Penumbra/Meta/Manipulations/Eqdp.cs @@ -15,7 +15,7 @@ public readonly record struct EqdpIdentifier(PrimaryId SetId, EquipSlot Slot, Ge public Gender Gender => GenderRace.Split().Item1; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, Slot)); public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/Eqp.cs b/Penumbra/Meta/Manipulations/Eqp.cs index c71f2f4d..154aca40 100644 --- a/Penumbra/Meta/Manipulations/Eqp.cs +++ b/Penumbra/Meta/Manipulations/Eqp.cs @@ -8,7 +8,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct EqpIdentifier(PrimaryId SetId, EquipSlot Slot) : IMetaIdentifier, IComparable { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace.MidlanderMale, Slot)); public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs index 007cd02f..8a450eee 100644 --- a/Penumbra/Meta/Manipulations/Est.cs +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -24,17 +24,17 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende public Gender Gender => GenderRace.Split().Item1; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { switch (Slot) { case EstType.Hair: - changedItems.TryAdd( - $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Hair {SetId}", null); + changedItems.UpdateCountOrSet( + $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Hair {SetId}", () => new IdentifiedName()); break; case EstType.Face: - changedItems.TryAdd( - $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Face {SetId}", null); + changedItems.UpdateCountOrSet( + $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Face {SetId}", () => new IdentifiedName()); break; case EstType.Body: identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Body)); diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs index 6a1ceaea..1365d9d3 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -70,7 +70,7 @@ public readonly struct GlobalEqpManipulation : IMetaIdentifier public override string ToString() => $"Global EQP - {Type}{(Condition != 0 ? $" - {Condition.Id}" : string.Empty)}"; - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { var path = Type switch { @@ -86,9 +86,9 @@ public readonly struct GlobalEqpManipulation : IMetaIdentifier if (path.Length > 0) identifier.Identify(changedItems, path); else if (Type is GlobalEqpType.DoNotHideVieraHats) - changedItems["All Hats for Viera"] = null; + changedItems.UpdateCountOrSet("All Hats for Viera", () => new IdentifiedName()); else if (Type is GlobalEqpType.DoNotHideHrothgarHats) - changedItems["All Hats for Hrothgar"] = null; + changedItems.UpdateCountOrSet("All Hats for Hrothgar", () => new IdentifiedName()); } public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/Gmp.cs b/Penumbra/Meta/Manipulations/Gmp.cs index 8cd07bfd..5bc81f26 100644 --- a/Penumbra/Meta/Manipulations/Gmp.cs +++ b/Penumbra/Meta/Manipulations/Gmp.cs @@ -8,7 +8,7 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct GmpIdentifier(PrimaryId SetId) : IMetaIdentifier, IComparable { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace.MidlanderMale, EquipSlot.Head)); public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs index 999fd906..c897bb2a 100644 --- a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -19,7 +19,7 @@ public enum MetaManipulationType : byte public interface IMetaIdentifier { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); public MetaIndex FileIndex(); diff --git a/Penumbra/Meta/Manipulations/Imc.cs b/Penumbra/Meta/Manipulations/Imc.cs index 6e893043..fa726708 100644 --- a/Penumbra/Meta/Manipulations/Imc.cs +++ b/Penumbra/Meta/Manipulations/Imc.cs @@ -27,10 +27,10 @@ public readonly record struct ImcIdentifier( : this(primaryId, variant, slot.IsAccessory() ? ObjectType.Accessory : ObjectType.Equipment, 0, slot, BodySlot.Unknown) { } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => AddChangedItems(identifier, changedItems, false); - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems, bool allVariants) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems, bool allVariants) { var path = ObjectType switch { diff --git a/Penumbra/Meta/Manipulations/Rsp.cs b/Penumbra/Meta/Manipulations/Rsp.cs index 9dc4fe90..5f91a37c 100644 --- a/Penumbra/Meta/Manipulations/Rsp.cs +++ b/Penumbra/Meta/Manipulations/Rsp.cs @@ -8,8 +8,8 @@ namespace Penumbra.Meta.Manipulations; public readonly record struct RspIdentifier(SubRace SubRace, RspAttribute Attribute) : IMetaIdentifier { - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) - => changedItems.TryAdd($"{SubRace.ToName()} {Attribute.ToFullString()}", null); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + => changedItems.UpdateCountOrSet($"{SubRace.ToName()} {Attribute.ToFullString()}", () => new IdentifiedName()); public MetaIndex FileIndex() => MetaIndex.HumanCmp; diff --git a/Penumbra/Mods/Groups/CombiningModGroup.cs b/Penumbra/Mods/Groups/CombiningModGroup.cs index 80f3c4c0..90a962b7 100644 --- a/Penumbra/Mods/Groups/CombiningModGroup.cs +++ b/Penumbra/Mods/Groups/CombiningModGroup.cs @@ -136,7 +136,7 @@ public sealed class CombiningModGroup : IModGroup public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) => Data[setting.AsIndex].AddDataTo(redirections, manipulations); - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { foreach (var container in DataContainers) identifier.AddChangedItems(container, changedItems); diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index 96422caf..cc961b0f 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -53,7 +53,7 @@ public interface IModGroup public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer); public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations); - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems); /// Ensure that a value is valid for a group. public Setting FixSetting(Setting setting); diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 2a1854ed..5ec32274 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -131,7 +131,7 @@ public class ImcModGroup(Mod mod) : IModGroup } } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) => Identifier.AddChangedItems(identifier, changedItems, AllVariants); public Setting FixSetting(Setting setting) diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 0c9aa805..82555314 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -122,7 +122,7 @@ public sealed class MultiModGroup(Mod mod) : IModGroup, ITexToolsGroup } } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { foreach (var container in DataContainers) identifier.AddChangedItems(container, changedItems); diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index ab0c2d4f..c250182a 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -107,7 +107,7 @@ public sealed class SingleModGroup(Mod mod) : IModGroup, ITexToolsGroup OptionData[setting.AsIndex].AddDataTo(redirections, manipulations); } - public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { foreach (var container in DataContainers) identifier.AddChangedItems(container, changedItems); diff --git a/Penumbra/Mods/Manager/ModCacheManager.cs b/Penumbra/Mods/Manager/ModCacheManager.cs index 4bf22272..130c8fcb 100644 --- a/Penumbra/Mods/Manager/ModCacheManager.cs +++ b/Penumbra/Mods/Manager/ModCacheManager.cs @@ -139,6 +139,7 @@ public class ModCacheManager : IDisposable, IService mod.ChangedItems.RemoveMachinistOffhands(); mod.LowerChangedItemsString = string.Join("\0", mod.ChangedItems.Keys.Select(k => k.ToLowerInvariant())); + ++mod.LastChangedItemsUpdate; } private static void UpdateCounts(Mod mod) diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 488e3dc1..9829d5a0 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -101,13 +101,14 @@ public sealed class Mod : IMod } // Cache - public readonly SortedList ChangedItems = new(); + public readonly SortedList ChangedItems = new(); public string LowerChangedItemsString { get; internal set; } = string.Empty; public string AllTagsLower { get; internal set; } = string.Empty; - public int TotalFileCount { get; internal set; } - public int TotalSwapCount { get; internal set; } - public int TotalManipulations { get; internal set; } + public int TotalFileCount { get; internal set; } + public int TotalSwapCount { get; internal set; } + public int TotalManipulations { get; internal set; } + public ushort LastChangedItemsUpdate { get; internal set; } public bool HasOptions { get; internal set; } } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 3482f620..eb9aa93d 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -25,7 +25,6 @@ public class ResourceTreeViewer( private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; - private readonly CommunicatorService _communicator = communicator; private readonly HashSet _unfolded = []; private readonly Dictionary _filterCache = []; @@ -278,7 +277,7 @@ public class ResourceTreeViewer( if (ImGui.IsItemClicked()) ImGui.SetClipboardText(resourceNode.FullPath.ToPath()); if (hasMod && ImGui.IsItemClicked(ImGuiMouseButton.Right) && ImGui.GetIO().KeyCtrl) - _communicator.SelectTab.Invoke(TabType.Mods, mod); + communicator.SelectTab.Invoke(TabType.Mods, mod); ImGuiUtil.HoverTooltip( $"{resourceNode.FullPath.ToPath()}\n\nClick to copy to clipboard.{(hasMod ? "\nControl + Right-Click to jump to mod." : string.Empty)}{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index af9782d5..a9070360 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -9,6 +9,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.Services; @@ -86,18 +87,20 @@ public class ChangedItemDrawer : IDisposable, IUiService } /// Check if a changed item should be drawn based on its category. - public bool FilterChangedItem(string name, IIdentifiedObjectData? data, LowerString filter) + public bool FilterChangedItem(string name, IIdentifiedObjectData data, LowerString filter) => (_config.Ephemeral.ChangedItemFilter == ChangedItemFlagExtensions.AllFlags || _config.Ephemeral.ChangedItemFilter.HasFlag(data.GetIcon().ToFlag())) && (filter.IsEmpty || !data.IsFilteredOut(name, filter)); /// Draw the icon corresponding to the category of a changed item. - public void DrawCategoryIcon(IIdentifiedObjectData? data) - => DrawCategoryIcon(data.GetIcon().ToFlag()); + public void DrawCategoryIcon(IIdentifiedObjectData data, float height) + => DrawCategoryIcon(data.GetIcon().ToFlag(), height); public void DrawCategoryIcon(ChangedItemIconFlag iconFlagType) + => DrawCategoryIcon(iconFlagType, ImGui.GetFrameHeight()); + + public void DrawCategoryIcon(ChangedItemIconFlag iconFlagType, float height) { - var height = ImGui.GetFrameHeight(); if (!_icons.TryGetValue(iconFlagType, out var icon)) { ImGui.Dummy(new Vector2(height)); @@ -114,50 +117,50 @@ public class ChangedItemDrawer : IDisposable, IUiService } } - /// - /// Draw a changed item, invoking the Api-Events for clicks and tooltips. - /// Also draw the item ID in grey if requested. - /// - public void DrawChangedItem(string name, IIdentifiedObjectData? data) + public void ChangedItemHandling(IIdentifiedObjectData data, bool leftClicked) { - name = data?.ToName(name) ?? name; - using (ImRaii.PushStyle(ImGuiStyleVar.SelectableTextAlign, new Vector2(0, 0.5f)) - .Push(ImGuiStyleVar.ItemSpacing, new Vector2(ImGui.GetStyle().ItemSpacing.X, ImGui.GetStyle().CellPadding.Y * 2))) - { - var ret = ImGui.Selectable(name, false, ImGuiSelectableFlags.None, new Vector2(0, ImGui.GetFrameHeight())) - ? MouseButton.Left - : MouseButton.None; - ret = ImGui.IsItemClicked(ImGuiMouseButton.Right) ? MouseButton.Right : ret; - ret = ImGui.IsItemClicked(ImGuiMouseButton.Middle) ? MouseButton.Middle : ret; - if (ret != MouseButton.None) - _communicator.ChangedItemClick.Invoke(ret, data); - } + var ret = leftClicked ? MouseButton.Left : MouseButton.None; + ret = ImGui.IsItemClicked(ImGuiMouseButton.Right) ? MouseButton.Right : ret; + ret = ImGui.IsItemClicked(ImGuiMouseButton.Middle) ? MouseButton.Middle : ret; + if (ret != MouseButton.None) + _communicator.ChangedItemClick.Invoke(ret, data); + if (!ImGui.IsItemHovered()) + return; - if (_communicator.ChangedItemHover.HasTooltip && ImGui.IsItemHovered()) - { - // We can not be sure that any subscriber actually prints something in any case. - // Circumvent ugly blank tooltip with less-ugly useless tooltip. - using var tt = ImRaii.Tooltip(); - using (ImRaii.Group()) - { - _communicator.ChangedItemHover.Invoke(data); - } - - if (ImGui.GetItemRectSize() == Vector2.Zero) - ImGui.TextUnformatted("No actions available."); - } + using var tt = ImUtf8.Tooltip(); + if (data.Count == 1) + ImUtf8.Text("This item is changed through a single effective change.\n"); + else + ImUtf8.Text($"This item is changed through {data.Count} distinct effective changes.\n"); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 3 * ImUtf8.GlobalScale); + ImGui.Separator(); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + 3 * ImUtf8.GlobalScale); + _communicator.ChangedItemHover.Invoke(data); } /// Draw the model information, right-justified. - public static void DrawModelData(IIdentifiedObjectData? data) + public static void DrawModelData(IIdentifiedObjectData data, float height) { - var additionalData = data?.AdditionalData ?? string.Empty; + var additionalData = data.AdditionalData; if (additionalData.Length == 0) return; - ImGui.SameLine(ImGui.GetContentRegionAvail().X); - ImGui.AlignTextToFramePadding(); - ImGuiUtil.RightJustify(additionalData, ColorId.ItemId.Value()); + ImGui.SameLine(); + using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ItemId.Value()); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + (height - ImGui.GetTextLineHeight()) / 2); + ImUtf8.TextRightAligned(additionalData, ImGui.GetStyle().ItemInnerSpacing.X); + } + + /// Draw the model information, right-justified. + public static void DrawModelData(ReadOnlySpan text, float height) + { + if (text.Length == 0) + return; + + ImGui.SameLine(); + using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ItemId.Value()); + ImGui.SetCursorPosY(ImGui.GetCursorPosY() + (height - ImGui.GetTextLineHeight()) / 2); + ImUtf8.TextRightAligned(text, ImGui.GetStyle().ItemInnerSpacing.X); } /// Draw a header line with the different icon types to filter them. @@ -276,7 +279,7 @@ public class ChangedItemDrawer : IDisposable, IUiService return true; } - private static unsafe IDalamudTextureWrap? LoadUnknownTexture(IDataManager gameData, ITextureProvider textureProvider) + private static IDalamudTextureWrap? LoadUnknownTexture(IDataManager gameData, ITextureProvider textureProvider) { var unk = gameData.GetFile("ui/uld/levelup2_hr1.tex"); if (unk == null) diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index a7bdadd3..ac4fd167 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -1,47 +1,268 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; using ImGuiNET; using OtterGui; using OtterGui.Classes; -using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Mods; +using Penumbra.String; namespace Penumbra.UI.ModsTab; -public class ModPanelChangedItemsTab(ModFileSystemSelector selector, ChangedItemDrawer drawer) : ITab, IUiService +public class ModPanelChangedItemsTab( + ModFileSystemSelector selector, + ChangedItemDrawer drawer, + ImGuiCacheService cacheService, + EphemeralConfig config) + : ITab, IUiService { + private readonly ImGuiCacheService.CacheId _cacheId = cacheService.GetNewId(); + + private class ChangedItemsCache + { + private Mod? _lastSelected; + private ushort _lastUpdate; + private ChangedItemIconFlag _filter = ChangedItemFlagExtensions.DefaultFlags; + private bool _reset; + public readonly List Data = []; + public bool AnyExpandable { get; private set; } + + public record struct Container + { + public IIdentifiedObjectData Data; + public ByteString Text; + public ByteString ModelData; + public uint Id; + public int Children; + public ChangedItemIconFlag Icon; + public bool Expandable; + public bool Expanded; + public bool Child; + + public static Container Single(string text, IIdentifiedObjectData data) + => new() + { + Child = false, + Text = ByteString.FromStringUnsafe(data.ToName(text), false), + ModelData = ByteString.FromStringUnsafe(data.AdditionalData, false), + Icon = data.GetIcon().ToFlag(), + Expandable = false, + Expanded = false, + Data = data, + Id = 0, + Children = 0, + }; + + public static Container Parent(string text, IIdentifiedObjectData data, uint id, int children, bool expanded) + => new() + { + Child = false, + Text = ByteString.FromStringUnsafe(data.ToName(text), false), + ModelData = ByteString.FromStringUnsafe(data.AdditionalData, false), + Icon = data.GetIcon().ToFlag(), + Expandable = true, + Expanded = expanded, + Data = data, + Id = id, + Children = children, + }; + + public static Container Indent(string text, IIdentifiedObjectData data) + => new() + { + Child = true, + Text = ByteString.FromStringUnsafe(data.ToName(text), false), + ModelData = ByteString.FromStringUnsafe(data.AdditionalData, false), + Icon = data.GetIcon().ToFlag(), + Expandable = false, + Expanded = false, + Data = data, + Id = 0, + Children = 0, + }; + } + + public void Reset() + => _reset = true; + + public void Update(Mod? mod, ChangedItemDrawer drawer, ChangedItemIconFlag filter) + { + if (mod == _lastSelected && _lastSelected!.LastChangedItemsUpdate == _lastUpdate && _filter == filter && !_reset) + return; + + _reset = false; + Data.Clear(); + AnyExpandable = false; + _lastSelected = mod; + _filter = filter; + if (_lastSelected == null) + return; + + _lastUpdate = _lastSelected.LastChangedItemsUpdate; + var tmp = new Dictionary<(PrimaryId, FullEquipType), List>(); + + foreach (var (s, i) in _lastSelected.ChangedItems) + { + if (i is not IdentifiedItem item) + continue; + + if (!drawer.FilterChangedItem(s, item, LowerString.Empty)) + continue; + + if (tmp.TryGetValue((item.Item.PrimaryId, item.Item.Type), out var p)) + p.Add(item); + else + tmp[(item.Item.PrimaryId, item.Item.Type)] = [item]; + } + + foreach (var list in tmp.Values) + { + list.Sort((i1, i2) => + { + // reversed + var count = i2.Count.CompareTo(i1.Count); + if (count != 0) + return count; + + return string.Compare(i1.Item.Name, i2.Item.Name, StringComparison.Ordinal); + }); + } + + var sortedTmp = tmp.Values.OrderBy(s => s[0].Item.Name).ToArray(); + + var sortedTmpIdx = 0; + foreach (var (s, i) in _lastSelected.ChangedItems) + { + if (i is IdentifiedItem) + continue; + + if (!drawer.FilterChangedItem(s, i, LowerString.Empty)) + continue; + + while (sortedTmpIdx < sortedTmp.Length + && string.Compare(sortedTmp[sortedTmpIdx][0].Item.Name, s, StringComparison.Ordinal) <= 0) + AddList(sortedTmp[sortedTmpIdx++]); + + Data.Add(Container.Single(s, i)); + } + + for (; sortedTmpIdx < sortedTmp.Length; ++sortedTmpIdx) + AddList(sortedTmp[sortedTmpIdx]); + return; + + void AddList(List list) + { + var mainItem = list[0]; + if (list.Count == 1) + { + Data.Add(Container.Single(mainItem.Item.Name, mainItem)); + } + else + { + var id = ImUtf8.GetId($"{mainItem.Item.PrimaryId}{(int)mainItem.Item.Type}"); + var expanded = ImGui.GetStateStorage().GetBool(id, false); + Data.Add(Container.Parent(mainItem.Item.Name, mainItem, id, list.Count - 1, expanded)); + AnyExpandable = true; + if (!expanded) + return; + + foreach (var item in list.Skip(1)) + Data.Add(Container.Indent(item.Item.Name, item)); + } + } + } + } + public ReadOnlySpan Label => "Changed Items"u8; public bool IsVisible => selector.Selected!.ChangedItems.Count > 0; + private ImGuiStoragePtr _stateStorage; + + private Vector2 _buttonSize; + public void DrawContent() { + if (cacheService.Cache(_cacheId, () => (new ChangedItemsCache(), "ModPanelChangedItemsCache")) is not { } cache) + return; + drawer.DrawTypeFilter(); + + _stateStorage = ImGui.GetStateStorage(); + cache.Update(selector.Selected, drawer, config.ChangedItemFilter); ImGui.Separator(); - using var table = ImRaii.Table("##changedItems", 1, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, + _buttonSize = new Vector2(ImGui.GetStyle().ItemSpacing.Y + ImGui.GetFrameHeight()); + using var style = ImRaii.PushStyle(ImGuiStyleVar.CellPadding, Vector2.Zero) + .Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero) + .Push(ImGuiStyleVar.FramePadding, Vector2.Zero) + .Push(ImGuiStyleVar.SelectableTextAlign, new Vector2(0.01f, 0.5f)); + + using var table = ImUtf8.Table("##changedItems"u8, cache.AnyExpandable ? 2 : 1, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(ImGui.GetContentRegionAvail().X, -1)); if (!table) return; - var zipList = ZipList.FromSortedList(selector.Selected!.ChangedItems); - var height = ImGui.GetFrameHeightWithSpacing(); - ImGui.TableNextColumn(); - var skips = ImGuiClip.GetNecessarySkips(height); - var remainder = ImGuiClip.FilteredClippedDraw(zipList, skips, CheckFilter, DrawChangedItem); - ImGuiClip.DrawEndDummy(remainder, height); + if (cache.AnyExpandable) + { + ImUtf8.TableSetupColumn("##exp"u8, ImGuiTableColumnFlags.WidthFixed, _buttonSize.Y); + ImUtf8.TableSetupColumn("##text"u8, ImGuiTableColumnFlags.WidthStretch); + ImGuiClip.ClippedDraw(cache.Data, DrawContainerExpandable, _buttonSize.Y); + } + else + { + ImGuiClip.ClippedDraw(cache.Data, DrawContainer, ImGui.GetFrameHeightWithSpacing()); + } } - private bool CheckFilter((string Name, IIdentifiedObjectData? Data) kvp) - => drawer.FilterChangedItem(kvp.Name, kvp.Data, LowerString.Empty); + private void DrawContainerExpandable(ChangedItemsCache.Container obj, int idx) + { + using var id = ImUtf8.PushId(idx); + ImGui.TableNextColumn(); + if (obj.Expandable) + { + using var color = ImRaii.PushColor(ImGuiCol.Button, 0); + if (ImUtf8.IconButton(obj.Expanded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight, + obj.Expanded ? "Hide the other items using the same model." : + obj.Children > 1 ? $"Show {obj.Children} other items using the same model." : + "Show one other item using the same model.", + _buttonSize)) + { + _stateStorage.SetBool(obj.Id, !obj.Expanded); + if (cacheService.TryGetCache(_cacheId, out var cache)) + cache.Reset(); + } + } + else + { + ImGui.Dummy(_buttonSize); + } - private void DrawChangedItem((string Name, IIdentifiedObjectData? Data) kvp) + DrawBaseContainer(obj, idx); + } + + private void DrawContainer(ChangedItemsCache.Container obj, int idx) + { + using var id = ImUtf8.PushId(idx); + DrawBaseContainer(obj, idx); + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void DrawBaseContainer(in ChangedItemsCache.Container obj, int idx) { ImGui.TableNextColumn(); - drawer.DrawCategoryIcon(kvp.Data); - ImGui.SameLine(); - drawer.DrawChangedItem(kvp.Name, kvp.Data); - ChangedItemDrawer.DrawModelData(kvp.Data); + using var indent = ImRaii.PushIndent(1, obj.Child); + drawer.DrawCategoryIcon(obj.Icon, _buttonSize.Y); + ImGui.SameLine(0, 0); + var clicked = ImUtf8.Selectable(obj.Text.Span, false, ImGuiSelectableFlags.None, _buttonSize with { X = 0 }); + drawer.ChangedItemHandling(obj.Data, clicked); + ChangedItemDrawer.DrawModelData(obj.ModelData.Span, _buttonSize.Y); } } diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index 5bac7d35..6cee22d6 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -3,6 +3,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; @@ -26,30 +27,36 @@ public class ChangedItemsTab( private LowerString _changedItemFilter = LowerString.Empty; private LowerString _changedItemModFilter = LowerString.Empty; + private Vector2 _buttonSize; public void DrawContent() { collectionHeader.Draw(true); drawer.DrawTypeFilter(); var varWidth = DrawFilters(); - using var child = ImRaii.Child("##changedItemsChild", -Vector2.One); + using var child = ImUtf8.Child("##changedItemsChild"u8, -Vector2.One); if (!child) return; - var height = ImGui.GetFrameHeightWithSpacing() + 2 * ImGui.GetStyle().CellPadding.Y; - var skips = ImGuiClip.GetNecessarySkips(height); - using var list = ImRaii.Table("##changedItems", 3, ImGuiTableFlags.RowBg, -Vector2.One); + _buttonSize = new Vector2(ImGui.GetStyle().ItemSpacing.Y + ImGui.GetFrameHeight()); + using var style = ImRaii.PushStyle(ImGuiStyleVar.CellPadding, Vector2.Zero) + .Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero) + .Push(ImGuiStyleVar.FramePadding, Vector2.Zero) + .Push(ImGuiStyleVar.SelectableTextAlign, new Vector2(0.01f, 0.5f)); + + var skips = ImGuiClip.GetNecessarySkips(_buttonSize.Y); + using var list = ImUtf8.Table("##changedItems"u8, 3, ImGuiTableFlags.RowBg, -Vector2.One); if (!list) return; const ImGuiTableColumnFlags flags = ImGuiTableColumnFlags.NoResize | ImGuiTableColumnFlags.WidthFixed; - ImGui.TableSetupColumn("items", flags, 450 * UiHelpers.Scale); - ImGui.TableSetupColumn("mods", flags, varWidth - 130 * UiHelpers.Scale); - ImGui.TableSetupColumn("id", flags, 130 * UiHelpers.Scale); + ImUtf8.TableSetupColumn("items"u8, flags, 450 * UiHelpers.Scale); + ImUtf8.TableSetupColumn("mods"u8, flags, varWidth - 140 * UiHelpers.Scale); + ImUtf8.TableSetupColumn("id"u8, flags, 140 * UiHelpers.Scale); var items = collectionManager.Active.Current.ChangedItems; var rest = ImGuiClip.FilteredClippedDraw(items, skips, FilterChangedItem, DrawChangedItemColumn); - ImGuiClip.DrawEndDummy(rest, height); + ImGuiClip.DrawEndDummy(rest, _buttonSize.Y); } /// Draw a pair of filters and return the variable width of the flexible column. @@ -67,22 +74,25 @@ public class ChangedItemsTab( } /// Apply the current filters. - private bool FilterChangedItem(KeyValuePair, IIdentifiedObjectData?)> item) + private bool FilterChangedItem(KeyValuePair, IIdentifiedObjectData)> item) => drawer.FilterChangedItem(item.Key, item.Value.Item2, _changedItemFilter) && (_changedItemModFilter.IsEmpty || item.Value.Item1.Any(m => m.Name.Contains(_changedItemModFilter))); /// Draw a full column for a changed item. - private void DrawChangedItemColumn(KeyValuePair, IIdentifiedObjectData?)> item) + private void DrawChangedItemColumn(KeyValuePair, IIdentifiedObjectData)> item) { ImGui.TableNextColumn(); - drawer.DrawCategoryIcon(item.Value.Item2); - ImGui.SameLine(); - drawer.DrawChangedItem(item.Key, item.Value.Item2); + drawer.DrawCategoryIcon(item.Value.Item2, _buttonSize.Y); + ImGui.SameLine(0, 0); + var name = item.Value.Item2.ToName(item.Key); + var clicked = ImUtf8.Selectable(name, false, ImGuiSelectableFlags.None, _buttonSize with { X = 0 }); + drawer.ChangedItemHandling(item.Value.Item2, clicked); + ImGui.TableNextColumn(); DrawModColumn(item.Value.Item1); ImGui.TableNextColumn(); - ChangedItemDrawer.DrawModelData(item.Value.Item2); + ChangedItemDrawer.DrawModelData(item.Value.Item2, _buttonSize.Y); } private void DrawModColumn(SingleArray mods) @@ -90,19 +100,18 @@ public class ChangedItemsTab( if (mods.Count <= 0) return; - var first = mods[0]; - using var style = ImRaii.PushStyle(ImGuiStyleVar.SelectableTextAlign, new Vector2(0, 0.5f)); - if (ImGui.Selectable(first.Name, false, ImGuiSelectableFlags.None, new Vector2(0, ImGui.GetFrameHeight())) + var first = mods[0]; + if (ImUtf8.Selectable(first.Name.Text, false, ImGuiSelectableFlags.None, _buttonSize with { X = 0 }) && ImGui.GetIO().KeyCtrl && first is Mod mod) communicator.SelectTab.Invoke(TabType.Mods, mod); - if (ImGui.IsItemHovered()) - { - using var _ = ImRaii.Tooltip(); - ImGui.TextUnformatted("Hold Control and click to jump to mod.\n"); - if (mods.Count > 1) - ImGui.TextUnformatted("Other mods affecting this item:\n" + string.Join("\n", mods.Skip(1).Select(m => m.Name))); - } + if (!ImGui.IsItemHovered()) + return; + + using var _ = ImRaii.Tooltip(); + ImUtf8.Text("Hold Control and click to jump to mod.\n"u8); + if (mods.Count > 1) + ImUtf8.Text("Other mods affecting this item:\n" + string.Join("\n", mods.Skip(1).Select(m => m.Name))); } } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 8f76a54a..42502290 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -748,7 +748,7 @@ public class DebugTab : Window, ITab, IUiService } private string _changedItemPath = string.Empty; - private readonly Dictionary _changedItems = []; + private readonly Dictionary _changedItems = []; private void DrawChangedItemTest() { diff --git a/Penumbra/Util/IdentifierExtensions.cs b/Penumbra/Util/IdentifierExtensions.cs index 5bd3f77c..f744e940 100644 --- a/Penumbra/Util/IdentifierExtensions.cs +++ b/Penumbra/Util/IdentifierExtensions.cs @@ -10,7 +10,7 @@ namespace Penumbra.Util; public static class IdentifierExtensions { public static void AddChangedItems(this ObjectIdentification identifier, IModDataContainer container, - IDictionary changedItems) + IDictionary changedItems) { foreach (var gamePath in container.Files.Keys.Concat(container.FileSwaps.Keys)) identifier.Identify(changedItems, gamePath.ToString()); @@ -19,7 +19,7 @@ public static class IdentifierExtensions manip.AddChangedItems(identifier, changedItems); } - public static void RemoveMachinistOffhands(this SortedList changedItems) + public static void RemoveMachinistOffhands(this SortedList changedItems) { for (var i = 0; i < changedItems.Count; i++) { @@ -31,7 +31,7 @@ public static class IdentifierExtensions } } - public static void RemoveMachinistOffhands(this SortedList, IIdentifiedObjectData?)> changedItems) + public static void RemoveMachinistOffhands(this SortedList, IIdentifiedObjectData)> changedItems) { for (var i = 0; i < changedItems.Count; i++) { From 26985e01a20c83c46c00a1107bda7fe9292132b3 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 28 Feb 2025 23:37:03 +0000 Subject: [PATCH 1125/1381] [CI] Updating repo.json for testing_1.3.4.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index afb2c32d..0b8d89cf 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.4", + "TestingAssemblyVersion": "1.3.4.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 13adbd54667e4eff64812d7e281c7d26dfb9689c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Mar 2025 16:55:50 +0100 Subject: [PATCH 1126/1381] Allow configuration of the changed item display. --- Penumbra/ChangedItemMode.cs | 57 ++++++++++++++ Penumbra/Configuration.cs | 78 ++++++++++++++----- .../UI/ModsTab/ModPanelChangedItemsTab.cs | 26 +++++-- Penumbra/UI/Tabs/SettingsTab.cs | 9 +++ 4 files changed, 144 insertions(+), 26 deletions(-) create mode 100644 Penumbra/ChangedItemMode.cs diff --git a/Penumbra/ChangedItemMode.cs b/Penumbra/ChangedItemMode.cs new file mode 100644 index 00000000..dccffded --- /dev/null +++ b/Penumbra/ChangedItemMode.cs @@ -0,0 +1,57 @@ +using ImGuiNET; +using OtterGui.Text; + +namespace Penumbra; + +public enum ChangedItemMode +{ + GroupedCollapsed, + GroupedExpanded, + Alphabetical, +} + +public static class ChangedItemModeExtensions +{ + public static ReadOnlySpan ToName(this ChangedItemMode mode) + => mode switch + { + ChangedItemMode.GroupedCollapsed => "Grouped (Collapsed)"u8, + ChangedItemMode.GroupedExpanded => "Grouped (Expanded)"u8, + ChangedItemMode.Alphabetical => "Alphabetical"u8, + _ => "Error"u8, + }; + + public static ReadOnlySpan ToTooltip(this ChangedItemMode mode) + => mode switch + { + ChangedItemMode.GroupedCollapsed => + "Display items as groups by their model and slot. Collapse those groups to a single item by default. Prefers items with more changes affecting them or configured items as the main item."u8, + ChangedItemMode.GroupedExpanded => + "Display items as groups by their model and slot. Expand those groups showing all items by default. Prefers items with more changes affecting them or configured items as the main item."u8, + ChangedItemMode.Alphabetical => "Display all changed items in a single list sorted alphabetically."u8, + _ => ""u8, + }; + + public static bool DrawCombo(ReadOnlySpan label, ChangedItemMode value, float width, Action setter) + { + ImGui.SetNextItemWidth(width); + using var combo = ImUtf8.Combo(label, value.ToName()); + if (!combo) + return false; + + var ret = false; + foreach (var newValue in Enum.GetValues()) + { + var selected = ImUtf8.Selectable(newValue.ToName(), newValue == value); + if (selected) + { + ret = true; + setter(newValue); + } + + ImUtf8.HoverTooltip(newValue.ToTooltip()); + } + + return ret; + } +} diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index ce86dd4a..939eb122 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -39,11 +39,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool EnableMods { get => _enableMods; - set - { - _enableMods = value; - ModsEnabled?.Invoke(value); - } + set => SetField(ref _enableMods, value, ModsEnabled); } public string ModDirectory { get; set; } = string.Empty; @@ -58,21 +54,22 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool AutoSelectCollection { get; set; } = false; - public bool ShowModsInLobby { get; set; } = true; - public bool UseCharacterCollectionInMainWindow { get; set; } = true; - public bool UseCharacterCollectionsInCards { get; set; } = true; - public bool UseCharacterCollectionInInspect { get; set; } = true; - public bool UseCharacterCollectionInTryOn { get; set; } = true; - public bool UseOwnerNameForCharacterCollection { get; set; } = true; - public bool UseNoModsInInspect { get; set; } = false; - public bool HideChangedItemFilters { get; set; } = false; - public bool ReplaceNonAsciiOnImport { get; set; } = false; - public bool HidePrioritiesInSelector { get; set; } = false; - public bool HideRedrawBar { get; set; } = false; - public bool HideMachinistOffhandFromChangedItems { get; set; } = true; - public bool DefaultTemporaryMode { get; set; } = false; - public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; - public int OptionGroupCollapsibleMin { get; set; } = 5; + public bool ShowModsInLobby { get; set; } = true; + public bool UseCharacterCollectionInMainWindow { get; set; } = true; + public bool UseCharacterCollectionsInCards { get; set; } = true; + public bool UseCharacterCollectionInInspect { get; set; } = true; + public bool UseCharacterCollectionInTryOn { get; set; } = true; + public bool UseOwnerNameForCharacterCollection { get; set; } = true; + public bool UseNoModsInInspect { get; set; } = false; + public bool HideChangedItemFilters { get; set; } = false; + public bool ReplaceNonAsciiOnImport { get; set; } = false; + public bool HidePrioritiesInSelector { get; set; } = false; + public bool HideRedrawBar { get; set; } = false; + public bool HideMachinistOffhandFromChangedItems { get; set; } = true; + public bool DefaultTemporaryMode { get; set; } = false; + public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; + public ChangedItemMode ChangedItemDisplay { get; set; } = ChangedItemMode.GroupedCollapsed; + public int OptionGroupCollapsibleMin { get; set; } = 5; public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); @@ -217,4 +214,45 @@ public class Configuration : IPluginConfiguration, ISavable, IService var serializer = new JsonSerializer { Formatting = Formatting.Indented }; serializer.Serialize(jWriter, this); } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool SetField(ref T field, T value, Action? @event, [CallerMemberName] string? propertyName = null) + { + if (EqualityComparer.Default.Equals(value)) + return false; + + var oldValue = field; + field = value; + try + { + @event?.Invoke(oldValue, field); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Error in subscribers updating configuration field {propertyName} from {oldValue} to {field}:\n{ex}"); + throw; + } + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool SetField(ref T field, T value, Action? @event, [CallerMemberName] string? propertyName = null) + { + if (EqualityComparer.Default.Equals(value)) + return false; + + field = value; + try + { + @event?.Invoke(field); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Error in subscribers updating configuration field {propertyName} to {field}:\n{ex}"); + throw; + } + + return true; + } } diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index ac4fd167..f97e4d51 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -18,7 +18,7 @@ public class ModPanelChangedItemsTab( ModFileSystemSelector selector, ChangedItemDrawer drawer, ImGuiCacheService cacheService, - EphemeralConfig config) + Configuration config) : ITab, IUiService { private readonly ImGuiCacheService.CacheId _cacheId = cacheService.GetNewId(); @@ -28,6 +28,7 @@ public class ModPanelChangedItemsTab( private Mod? _lastSelected; private ushort _lastUpdate; private ChangedItemIconFlag _filter = ChangedItemFlagExtensions.DefaultFlags; + private ChangedItemMode _lastMode; private bool _reset; public readonly List Data = []; public bool AnyExpandable { get; private set; } @@ -90,9 +91,9 @@ public class ModPanelChangedItemsTab( public void Reset() => _reset = true; - public void Update(Mod? mod, ChangedItemDrawer drawer, ChangedItemIconFlag filter) + public void Update(Mod? mod, ChangedItemDrawer drawer, ChangedItemIconFlag filter, ChangedItemMode mode) { - if (mod == _lastSelected && _lastSelected!.LastChangedItemsUpdate == _lastUpdate && _filter == filter && !_reset) + if (mod == _lastSelected && _lastSelected!.LastChangedItemsUpdate == _lastUpdate && _filter == filter && !_reset && _lastMode == mode) return; _reset = false; @@ -100,12 +101,25 @@ public class ModPanelChangedItemsTab( AnyExpandable = false; _lastSelected = mod; _filter = filter; + _lastMode = mode; if (_lastSelected == null) return; _lastUpdate = _lastSelected.LastChangedItemsUpdate; - var tmp = new Dictionary<(PrimaryId, FullEquipType), List>(); + if (mode is ChangedItemMode.Alphabetical) + { + foreach (var (s, i) in _lastSelected.ChangedItems) + { + if (drawer.FilterChangedItem(s, i, LowerString.Empty)) + Data.Add(Container.Single(s, i)); + } + + return; + } + + var tmp = new Dictionary<(PrimaryId, FullEquipType), List>(); + var defaultExpansion = _lastMode is ChangedItemMode.GroupedExpanded; foreach (var (s, i) in _lastSelected.ChangedItems) { if (i is not IdentifiedItem item) @@ -165,7 +179,7 @@ public class ModPanelChangedItemsTab( else { var id = ImUtf8.GetId($"{mainItem.Item.PrimaryId}{(int)mainItem.Item.Type}"); - var expanded = ImGui.GetStateStorage().GetBool(id, false); + var expanded = ImGui.GetStateStorage().GetBool(id, defaultExpansion); Data.Add(Container.Parent(mainItem.Item.Name, mainItem, id, list.Count - 1, expanded)); AnyExpandable = true; if (!expanded) @@ -196,7 +210,7 @@ public class ModPanelChangedItemsTab( drawer.DrawTypeFilter(); _stateStorage = ImGui.GetStateStorage(); - cache.Update(selector.Selected, drawer, config.ChangedItemFilter); + cache.Update(selector.Selected, drawer, config.Ephemeral.ChangedItemFilter, config.ChangedItemDisplay); ImGui.Separator(); _buttonSize = new Vector2(ImGui.GetStyle().ItemSpacing.Y + ImGui.GetFrameHeight()); using var style = ImRaii.PushStyle(ImGuiStyleVar.CellPadding, Vector2.Zero) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 4ff0cd42..ba226aa8 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -445,6 +445,15 @@ public class SettingsTab : ITab, IUiService _config.Ephemeral.Save(); } }); + + ChangedItemModeExtensions.DrawCombo("##ChangedItemMode"u8, _config.ChangedItemDisplay, UiHelpers.InputTextWidth.X, v => + { + _config.ChangedItemDisplay = v; + _config.Save(); + }); + ImUtf8.LabeledHelpMarker("Mod Changed Item Display"u8, + "Configure how to display the changed items of a single mod in the mods info panel."u8); + Checkbox("Omit Machinist Offhands in Changed Items", "Omits all Aetherotransformers (machinist offhands) in the changed items tabs because any change on them changes all of them at the moment.\n\n" + "Changing this triggers a rediscovery of your mods so all changed items can be updated.", From 509f11561aee52acd23a56f7c35d6f4494572384 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Mar 2025 22:21:36 +0100 Subject: [PATCH 1127/1381] Add preferred changed items to mods. --- Penumbra/Mods/Manager/ModDataEditor.cs | 158 ++++++++++++++++-- Penumbra/Mods/Mod.cs | 28 ++-- Penumbra/Mods/ModLocalData.cs | 27 ++- Penumbra/Mods/ModMeta.cs | 12 +- .../UI/ModsTab/ModPanelChangedItemsTab.cs | 71 +++++++- schemas/local_mod_data-v3.json | 9 + schemas/mod_meta-v3.json | 9 + 7 files changed, 273 insertions(+), 41 deletions(-) diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 7c48205a..1349b525 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -1,7 +1,8 @@ using Dalamud.Utility; -using Newtonsoft.Json.Linq; using OtterGui.Classes; using OtterGui.Services; +using Penumbra.GameData.Data; +using Penumbra.GameData.Structs; using Penumbra.Services; namespace Penumbra.Mods.Manager; @@ -9,23 +10,25 @@ namespace Penumbra.Mods.Manager; [Flags] public enum ModDataChangeType : ushort { - None = 0x0000, - Name = 0x0001, - Author = 0x0002, - Description = 0x0004, - Version = 0x0008, - Website = 0x0010, - Deletion = 0x0020, - Migration = 0x0040, - ModTags = 0x0080, - ImportDate = 0x0100, - Favorite = 0x0200, - LocalTags = 0x0400, - Note = 0x0800, - Image = 0x1000, + None = 0x0000, + Name = 0x0001, + Author = 0x0002, + Description = 0x0004, + Version = 0x0008, + Website = 0x0010, + Deletion = 0x0020, + Migration = 0x0040, + ModTags = 0x0080, + ImportDate = 0x0100, + Favorite = 0x0200, + LocalTags = 0x0400, + Note = 0x0800, + Image = 0x1000, + DefaultChangedItems = 0x2000, + PreferredChangedItems = 0x4000, } -public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService) : IService +public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService, ItemData itemData) : IService { public SaveService SaveService => saveService; @@ -35,7 +38,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic string? website) { var mod = new Mod(directory); - mod.Name = name.IsNullOrEmpty() ? mod.Name : new LowerString(name!); + mod.Name = name.IsNullOrEmpty() ? mod.Name : new LowerString(name); mod.Author = author != null ? new LowerString(author) : mod.Author; mod.Description = description ?? mod.Description; mod.Version = version ?? mod.Version; @@ -175,4 +178,125 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic Penumbra.Log.Error($"Could not move local data file {oldFile} to {newFile}:\n{e}"); } } + + public void AddPreferredItem(Mod mod, CustomItemId id, bool toDefault, bool cleanExisting) + { + if (CleanExisting(mod.PreferredChangedItems)) + { + ++mod.LastChangedItemsUpdate; + saveService.QueueSave(new ModLocalData(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.PreferredChangedItems, mod, null); + } + + if (toDefault && CleanExisting(mod.DefaultPreferredItems)) + { + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.DefaultChangedItems, mod, null); + } + + bool CleanExisting(HashSet items) + { + if (!items.Add(id)) + return false; + + if (!cleanExisting) + return true; + + var it1Exists = itemData.Primary.TryGetValue(id, out var it1); + var it2Exists = itemData.Secondary.TryGetValue(id, out var it2); + var it3Exists = itemData.Tertiary.TryGetValue(id, out var it3); + + foreach (var item in items.ToArray()) + { + if (item == id) + continue; + + if (it1Exists + && itemData.Primary.TryGetValue(item, out var oldItem1) + && oldItem1.PrimaryId == it1.PrimaryId + && oldItem1.Type == it1.Type) + items.Remove(item); + + else if (it2Exists + && itemData.Primary.TryGetValue(item, out var oldItem2) + && oldItem2.PrimaryId == it2.PrimaryId + && oldItem2.Type == it2.Type) + items.Remove(item); + + else if (it3Exists + && itemData.Primary.TryGetValue(item, out var oldItem3) + && oldItem3.PrimaryId == it3.PrimaryId + && oldItem3.Type == it3.Type) + items.Remove(item); + } + + return true; + } + } + + public void RemovePreferredItem(Mod mod, CustomItemId id, bool fromDefault) + { + if (!fromDefault && mod.PreferredChangedItems.Remove(id)) + { + ++mod.LastChangedItemsUpdate; + saveService.QueueSave(new ModLocalData(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.PreferredChangedItems, mod, null); + } + + if (fromDefault && mod.DefaultPreferredItems.Remove(id)) + { + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.DefaultChangedItems, mod, null); + } + } + + public void ClearInvalidPreferredItems(Mod mod) + { + var currentChangedItems = mod.ChangedItems.Values.OfType().Select(i => i.Item.Id).Distinct().ToHashSet(); + var newSet = new HashSet(mod.PreferredChangedItems.Count); + + if (CheckItems(mod.PreferredChangedItems)) + { + mod.PreferredChangedItems = newSet; + ++mod.LastChangedItemsUpdate; + saveService.QueueSave(new ModLocalData(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.PreferredChangedItems, mod, null); + } + + newSet = new HashSet(mod.DefaultPreferredItems.Count); + if (CheckItems(mod.DefaultPreferredItems)) + { + mod.DefaultPreferredItems = newSet; + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.DefaultChangedItems, mod, null); + } + + return; + + bool CheckItems(HashSet set) + { + var changes = false; + foreach (var item in set) + { + if (currentChangedItems.Contains(item)) + newSet.Add(item); + else + changes = true; + } + + return changes; + } + } + + public void ResetPreferredItems(Mod mod) + { + if (mod.PreferredChangedItems.SetEquals(mod.DefaultPreferredItems)) + return; + + mod.PreferredChangedItems.Clear(); + mod.PreferredChangedItems.UnionWith(mod.DefaultPreferredItems); + ++mod.LastChangedItemsUpdate; + saveService.QueueSave(new ModLocalData(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.PreferredChangedItems, mod, null); + } } diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 9829d5a0..efd92631 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,6 +1,7 @@ using OtterGui; using OtterGui.Classes; using Penumbra.GameData.Data; +using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; @@ -47,21 +48,22 @@ public sealed class Mod : IMod => Name.Text; // Meta Data - public LowerString Name { get; internal set; } = "New Mod"; - public LowerString Author { get; internal set; } = LowerString.Empty; - public string Description { get; internal set; } = string.Empty; - public string Version { get; internal set; } = string.Empty; - public string Website { get; internal set; } = string.Empty; - public string Image { get; internal set; } = string.Empty; - public IReadOnlyList ModTags { get; internal set; } = []; + public LowerString Name { get; internal set; } = "New Mod"; + public LowerString Author { get; internal set; } = LowerString.Empty; + public string Description { get; internal set; } = string.Empty; + public string Version { get; internal set; } = string.Empty; + public string Website { get; internal set; } = string.Empty; + public string Image { get; internal set; } = string.Empty; + public IReadOnlyList ModTags { get; internal set; } = []; + public HashSet DefaultPreferredItems { get; internal set; } = []; // Local Data - public long ImportDate { get; internal set; } = DateTimeOffset.UnixEpoch.ToUnixTimeMilliseconds(); - public IReadOnlyList LocalTags { get; internal set; } = []; - public string Note { get; internal set; } = string.Empty; - public bool Favorite { get; internal set; } = false; - + public long ImportDate { get; internal set; } = DateTimeOffset.UnixEpoch.ToUnixTimeMilliseconds(); + public IReadOnlyList LocalTags { get; internal set; } = []; + public string Note { get; internal set; } = string.Empty; + public HashSet PreferredChangedItems { get; internal set; } = []; + public bool Favorite { get; internal set; } = false; // Options public readonly DefaultSubMod Default; @@ -110,5 +112,5 @@ public sealed class Mod : IMod public int TotalSwapCount { get; internal set; } public int TotalManipulations { get; internal set; } public ushort LastChangedItemsUpdate { get; internal set; } - public bool HasOptions { get; internal set; } + public bool HasOptions { get; internal set; } } diff --git a/Penumbra/Mods/ModLocalData.cs b/Penumbra/Mods/ModLocalData.cs index d3534391..cc20fad6 100644 --- a/Penumbra/Mods/ModLocalData.cs +++ b/Penumbra/Mods/ModLocalData.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using Penumbra.GameData.Structs; using Penumbra.Mods.Manager; using Penumbra.Services; @@ -21,6 +22,7 @@ public readonly struct ModLocalData(Mod mod) : ISavable { nameof(Mod.LocalTags), JToken.FromObject(mod.LocalTags) }, { nameof(Mod.Note), JToken.FromObject(mod.Note) }, { nameof(Mod.Favorite), JToken.FromObject(mod.Favorite) }, + { nameof(Mod.PreferredChangedItems), JToken.FromObject(mod.PreferredChangedItems) }, }; using var jWriter = new JsonTextWriter(writer); jWriter.Formatting = Formatting.Indented; @@ -36,6 +38,8 @@ public readonly struct ModLocalData(Mod mod) : ISavable var favorite = false; var note = string.Empty; + HashSet preferredChangedItems = []; + var save = true; if (File.Exists(dataFile)) try @@ -43,16 +47,21 @@ public readonly struct ModLocalData(Mod mod) : ISavable var text = File.ReadAllText(dataFile); var json = JObject.Parse(text); - importDate = json[nameof(Mod.ImportDate)]?.Value() ?? importDate; - favorite = json[nameof(Mod.Favorite)]?.Value() ?? favorite; - note = json[nameof(Mod.Note)]?.Value() ?? note; - localTags = (json[nameof(Mod.LocalTags)] as JArray)?.Values().OfType() ?? localTags; - save = false; + importDate = json[nameof(Mod.ImportDate)]?.Value() ?? importDate; + favorite = json[nameof(Mod.Favorite)]?.Value() ?? favorite; + note = json[nameof(Mod.Note)]?.Value() ?? note; + localTags = (json[nameof(Mod.LocalTags)] as JArray)?.Values().OfType() ?? localTags; + preferredChangedItems = (json[nameof(Mod.PreferredChangedItems)] as JArray)?.Values().Select(i => (CustomItemId) i).ToHashSet() ?? mod.DefaultPreferredItems; + save = false; } catch (Exception e) { Penumbra.Log.Error($"Could not load local mod data:\n{e}"); } + else + { + preferredChangedItems = mod.DefaultPreferredItems; + } if (importDate == 0) importDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); @@ -64,7 +73,7 @@ public readonly struct ModLocalData(Mod mod) : ISavable changes |= ModDataChangeType.ImportDate; } - changes |= ModLocalData.UpdateTags(mod, null, localTags); + changes |= UpdateTags(mod, null, localTags); if (mod.Favorite != favorite) { @@ -78,6 +87,12 @@ public readonly struct ModLocalData(Mod mod) : ISavable changes |= ModDataChangeType.Note; } + if (!preferredChangedItems.SetEquals(mod.PreferredChangedItems)) + { + mod.PreferredChangedItems = preferredChangedItems; + changes |= ModDataChangeType.PreferredChangedItems; + } + if (save) editor.SaveService.QueueSave(new ModLocalData(mod)); diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index 0cebcf81..1b104af4 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using Penumbra.GameData.Structs; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Services; @@ -25,6 +26,7 @@ public readonly struct ModMeta(Mod mod) : ISavable { nameof(Mod.Version), JToken.FromObject(mod.Version) }, { nameof(Mod.Website), JToken.FromObject(mod.Website) }, { nameof(Mod.ModTags), JToken.FromObject(mod.ModTags) }, + { nameof(Mod.DefaultPreferredItems), JToken.FromObject(mod.DefaultPreferredItems) }, }; using var jWriter = new JsonTextWriter(writer); jWriter.Formatting = Formatting.Indented; @@ -48,7 +50,7 @@ public readonly struct ModMeta(Mod mod) : ISavable var newFileVersion = json[nameof(FileVersion)]?.Value() ?? 0; // Empty name gets checked after loading and is not allowed. - var newName = json[nameof(Mod.Name)]?.Value() ?? string.Empty; + var newName = json[nameof(Mod.Name)]?.Value() ?? string.Empty; var newAuthor = json[nameof(Mod.Author)]?.Value() ?? string.Empty; var newDescription = json[nameof(Mod.Description)]?.Value() ?? string.Empty; @@ -56,6 +58,8 @@ public readonly struct ModMeta(Mod mod) : ISavable var newVersion = json[nameof(Mod.Version)]?.Value() ?? string.Empty; var newWebsite = json[nameof(Mod.Website)]?.Value() ?? string.Empty; var modTags = (json[nameof(Mod.ModTags)] as JArray)?.Values().OfType(); + var defaultItems = (json[nameof(Mod.DefaultPreferredItems)] as JArray)?.Values().Select(i => (CustomItemId)i).ToHashSet() + ?? []; ModDataChangeType changes = 0; if (mod.Name != newName) @@ -94,6 +98,12 @@ public readonly struct ModMeta(Mod mod) : ISavable mod.Website = newWebsite; } + if (!mod.DefaultPreferredItems.SetEquals(defaultItems)) + { + changes |= ModDataChangeType.DefaultChangedItems; + mod.DefaultPreferredItems = defaultItems; + } + if (newFileVersion != FileVersion) if (ModMigration.Migrate(creator, editor.SaveService, mod, json, ref newFileVersion)) { diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index f97e4d51..700f1d66 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -10,6 +10,7 @@ using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Mods; +using Penumbra.Mods.Manager; using Penumbra.String; namespace Penumbra.UI.ModsTab; @@ -18,7 +19,8 @@ public class ModPanelChangedItemsTab( ModFileSystemSelector selector, ChangedItemDrawer drawer, ImGuiCacheService cacheService, - Configuration config) + Configuration config, + ModDataEditor dataEditor) : ITab, IUiService { private readonly ImGuiCacheService.CacheId _cacheId = cacheService.GetNewId(); @@ -77,7 +79,7 @@ public class ModPanelChangedItemsTab( => new() { Child = true, - Text = ByteString.FromStringUnsafe(data.ToName(text), false), + Text = ByteString.FromStringUnsafe(data.ToName(text), false), ModelData = ByteString.FromStringUnsafe(data.AdditionalData, false), Icon = data.GetIcon().ToFlag(), Expandable = false, @@ -93,7 +95,11 @@ public class ModPanelChangedItemsTab( public void Update(Mod? mod, ChangedItemDrawer drawer, ChangedItemIconFlag filter, ChangedItemMode mode) { - if (mod == _lastSelected && _lastSelected!.LastChangedItemsUpdate == _lastUpdate && _filter == filter && !_reset && _lastMode == mode) + if (mod == _lastSelected + && _lastSelected!.LastChangedItemsUpdate == _lastUpdate + && _filter == filter + && !_reset + && _lastMode == mode) return; _reset = false; @@ -138,6 +144,12 @@ public class ModPanelChangedItemsTab( { list.Sort((i1, i2) => { + // reversed + var preferred = _lastSelected.PreferredChangedItems.Contains(i2.Item.Id) + .CompareTo(_lastSelected.PreferredChangedItems.Contains(i1.Item.Id)); + if (preferred != 0) + return preferred; + // reversed var count = i2.Count.CompareTo(i1.Count); if (count != 0) @@ -217,6 +229,7 @@ public class ModPanelChangedItemsTab( .Push(ImGuiStyleVar.ItemSpacing, Vector2.Zero) .Push(ImGuiStyleVar.FramePadding, Vector2.Zero) .Push(ImGuiStyleVar.SelectableTextAlign, new Vector2(0.01f, 0.5f)); + using var color = ImRaii.PushColor(ImGuiCol.Button, 0); using var table = ImUtf8.Table("##changedItems"u8, cache.AnyExpandable ? 2 : 1, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY, new Vector2(ImGui.GetContentRegionAvail().X, -1)); @@ -241,7 +254,6 @@ public class ModPanelChangedItemsTab( ImGui.TableNextColumn(); if (obj.Expandable) { - using var color = ImRaii.PushColor(ImGuiCol.Button, 0); if (ImUtf8.IconButton(obj.Expanded ? FontAwesomeIcon.CaretDown : FontAwesomeIcon.CaretRight, obj.Expanded ? "Hide the other items using the same model." : obj.Children > 1 ? $"Show {obj.Children} other items using the same model." : @@ -253,6 +265,10 @@ public class ModPanelChangedItemsTab( cache.Reset(); } } + else if (obj is { Child: true, Data: IdentifiedItem item }) + { + DrawPreferredButton(item, idx); + } else { ImGui.Dummy(_buttonSize); @@ -267,6 +283,53 @@ public class ModPanelChangedItemsTab( DrawBaseContainer(obj, idx); } + private void DrawPreferredButton(IdentifiedItem item, int idx) + { + if (ImUtf8.IconButton(FontAwesomeIcon.Star, "Prefer displaying this item instead of the current primary item.\n\nRight-click for more options."u8, _buttonSize, + false, ImGui.GetColorU32(ImGuiCol.TextDisabled, 0.1f))) + dataEditor.AddPreferredItem(selector.Selected!, item.Item.Id, false, true); + using var context = ImUtf8.PopupContextItem("StarContext"u8, ImGuiPopupFlags.MouseButtonRight); + if (!context) + return; + + if (cacheService.TryGetCache(_cacheId, out var cache)) + for (--idx; idx >= 0; --idx) + { + if (!cache.Data[idx].Expanded) + continue; + + if (cache.Data[idx].Data is IdentifiedItem it) + { + if (selector.Selected!.PreferredChangedItems.Contains(it.Item.Id) + && ImUtf8.MenuItem("Remove Parent from Local Preferred Items"u8)) + dataEditor.RemovePreferredItem(selector.Selected!, it.Item.Id, false); + if (selector.Selected!.DefaultPreferredItems.Contains(it.Item.Id) + && ImUtf8.MenuItem("Remove Parent from Default Preferred Items"u8)) + dataEditor.RemovePreferredItem(selector.Selected!, it.Item.Id, true); + } + + break; + } + + var enabled = !selector.Selected!.DefaultPreferredItems.Contains(item.Item.Id); + if (enabled) + { + if (ImUtf8.MenuItem("Add to Local and Default Preferred Changed Items"u8)) + dataEditor.AddPreferredItem(selector.Selected!, item.Item.Id, true, true); + } + else + { + if (ImUtf8.MenuItem("Remove from Default Preferred Changed Items"u8)) + dataEditor.RemovePreferredItem(selector.Selected!, item.Item.Id, true); + } + + if (ImUtf8.MenuItem("Reset Local Preferred Items to Default"u8)) + dataEditor.ResetPreferredItems(selector.Selected!); + + if (ImUtf8.MenuItem("Clear Local and Default Preferred Items not Changed by the Mod"u8)) + dataEditor.ClearInvalidPreferredItems(selector.Selected!); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void DrawBaseContainer(in ChangedItemsCache.Container obj, int idx) diff --git a/schemas/local_mod_data-v3.json b/schemas/local_mod_data-v3.json index bf5d1311..c50e130e 100644 --- a/schemas/local_mod_data-v3.json +++ b/schemas/local_mod_data-v3.json @@ -26,6 +26,15 @@ "Favorite": { "description": "Whether the mod is favourited by the user.", "type": "boolean" + }, + "PreferredChangedItems": { + "description": "Preferred items to list as the main item of a group.", + "type": "array", + "items": { + "minimum": 0, + "type": "integer" + }, + "uniqueItems": true } }, "required": [ "FileVersion" ] diff --git a/schemas/mod_meta-v3.json b/schemas/mod_meta-v3.json index a926b49e..ed63a228 100644 --- a/schemas/mod_meta-v3.json +++ b/schemas/mod_meta-v3.json @@ -43,6 +43,15 @@ "minLength": 1 }, "uniqueItems": true + }, + "DefaultPreferredItems": { + "description": "Default preferred items to list as the main item of a group managed by the mod creator.", + "type": "array", + "items": { + "minimum": 0, + "type": "integer" + }, + "uniqueItems": true } }, "required": [ From cda9b1df655bb4aceed78f47a1a459b35cdc3692 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 1 Mar 2025 22:34:50 +0100 Subject: [PATCH 1128/1381] Fix weapon identification bug. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 955c4e6b..a21c1467 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 955c4e6b281bf0781689b15c01a868b0de5881b4 +Subproject commit a21c146790b370bd58b0f752385ae153f7e769c0 From 34d51b66aa53d3245e1c37960878e0492f9fdbcf Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 1 Mar 2025 21:37:03 +0000 Subject: [PATCH 1129/1381] [CI] Updating repo.json for testing_1.3.4.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 0b8d89cf..b098593a 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.5", + "TestingAssemblyVersion": "1.3.4.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0b0c92eb098b50d4631fb0ba2d65db5f01273247 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 2 Mar 2025 14:27:40 +0100 Subject: [PATCH 1130/1381] Some cleanup. --- Penumbra/Import/Structs/TexToolsStructs.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra/Import/Structs/TexToolsStructs.cs b/Penumbra/Import/Structs/TexToolsStructs.cs index bf3bccd8..f5b5ef4a 100644 --- a/Penumbra/Import/Structs/TexToolsStructs.cs +++ b/Penumbra/Import/Structs/TexToolsStructs.cs @@ -26,7 +26,7 @@ public class SimpleMod public class ModPackPage { public int PageIndex = 0; - public ModGroup[] ModGroups = Array.Empty(); + public ModGroup[] ModGroups = []; } [Serializable] @@ -34,7 +34,7 @@ public class ModGroup { public string GroupName = string.Empty; public GroupType SelectionType = GroupType.Single; - public OptionList[] OptionList = Array.Empty(); + public OptionList[] OptionList = []; public string Description = string.Empty; } @@ -44,7 +44,7 @@ public class OptionList public string Name = string.Empty; public string Description = string.Empty; public string ImagePath = string.Empty; - public SimpleMod[] ModsJsons = Array.Empty(); + public SimpleMod[] ModsJsons = []; public string GroupName = string.Empty; public GroupType SelectionType = GroupType.Single; public bool IsChecked = false; @@ -59,8 +59,8 @@ public class ExtendedModPack public string Version = string.Empty; public string Description = DefaultTexToolsData.Description; public string Url = string.Empty; - public ModPackPage[] ModPackPages = Array.Empty(); - public SimpleMod[] SimpleModsList = Array.Empty(); + public ModPackPage[] ModPackPages = []; + public SimpleMod[] SimpleModsList = []; } [Serializable] @@ -72,5 +72,5 @@ public class SimpleModPack public string Version = string.Empty; public string Description = DefaultTexToolsData.Description; public string Url = string.Empty; - public SimpleMod[] SimpleModsList = Array.Empty(); + public SimpleMod[] SimpleModsList = []; } From 7cf0367361934ae063c8b5c6d826235a554a39e1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Mar 2025 13:39:25 +0100 Subject: [PATCH 1131/1381] Try moving extracted folders 3 times for unknown issues. --- Penumbra/Import/TexToolsImporter.Archives.cs | 39 +++++++++++++++----- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index febbe179..8166dea7 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -96,17 +96,36 @@ public partial class TexToolsImporter _token.ThrowIfCancellationRequested(); var oldName = _currentModDirectory.FullName; - // Use either the top-level directory as the mods base name, or the (fixed for path) name in the json. - if (leadDir) + + // Try renaming the folder three times because sometimes we get AccessDenied here for some unknown reason. + const int numTries = 3; + for (var i = 1;; ++i) { - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, baseName, _config.ReplaceNonAsciiOnImport, false); - Directory.Move(Path.Combine(oldName, baseName), _currentModDirectory.FullName); - Directory.Delete(oldName); - } - else - { - _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, name, _config.ReplaceNonAsciiOnImport, false); - Directory.Move(oldName, _currentModDirectory.FullName); + // Use either the top-level directory as the mods base name, or the (fixed for path) name in the json. + try + { + if (leadDir) + { + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, baseName, _config.ReplaceNonAsciiOnImport, false); + Directory.Move(Path.Combine(oldName, baseName), _currentModDirectory.FullName); + Directory.Delete(oldName); + } + else + { + _currentModDirectory = ModCreator.CreateModFolder(_baseDirectory, name, _config.ReplaceNonAsciiOnImport, false); + Directory.Move(oldName, _currentModDirectory.FullName); + } + } + catch (IOException io) + { + if (i == numTries) + throw; + + Penumbra.Log.Warning($"Error when renaming the extracted mod, try {i}/{numTries}: {io.Message}."); + continue; + } + + break; } _currentModDirectory.Refresh(); From 1afbbfef78f7ec295bc5ccb7cfd15b6a23b74eae Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Mar 2025 13:39:41 +0100 Subject: [PATCH 1132/1381] Update NuGet packages. --- Penumbra/packages.lock.json | 87 +++++++++++++++++++------------------ 1 file changed, 45 insertions(+), 42 deletions(-) diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 5b868212..9aa1ebd5 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -13,67 +13,68 @@ }, "PeNet": { "type": "Direct", - "requested": "[4.0.5, )", - "resolved": "4.0.5", - "contentHash": "/OUfRnMG8STVuK8kTpdfm+WQGTDoUiJnI845kFw4QrDmv2gYourmSnH84pqVjHT1YHBSuRfCzfioIpHGjFJrGA==", + "requested": "[4.1.1, )", + "resolved": "4.1.1", + "contentHash": "TiRyOVcg1Bh2FyP6Dm2NEiYzemSlQderhaxuH3XWNyTYsnHrm1n/xvoTftgMwsWD4C/3kTqJw93oZOvHojJfKg==", "dependencies": { "PeNet.Asn1": "2.0.1", - "System.Security.Cryptography.Pkcs": "8.0.0" + "System.Security.Cryptography.Pkcs": "8.0.1" } }, "SharpCompress": { "type": "Direct", - "requested": "[0.37.2, )", - "resolved": "0.37.2", - "contentHash": "cFBpTct57aubLQXkdqMmgP8GGTFRh7fnRWP53lgE/EYUpDZJ27SSvTkdjB4OYQRZ20SJFpzczUquKLbt/9xkhw==", + "requested": "[0.39.0, )", + "resolved": "0.39.0", + "contentHash": "0esqIUDlg68Z7+Weuge4QzEvNtawUO4obTJFL7xuf4DBHMxVRr+wbNgiX9arMrj3kGXQSvLe0zbZG3oxpkwJOA==", "dependencies": { - "ZstdSharp.Port": "0.8.0" + "System.Buffers": "4.6.0", + "ZstdSharp.Port": "0.8.4" } }, "SharpGLTF.Core": { "type": "Direct", - "requested": "[1.0.1, )", - "resolved": "1.0.1", - "contentHash": "ykeV1oNHcJrEJE7s0pGAsf/nYGYY7wqF9nxCMxJUjp/WdW+UUgR1cGdbAa2lVZPkiXEwLzWenZ5wPz7yS0Gj9w==" + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "su+Flcg2g6GgOIgulRGBDMHA6zY5NBx6NYH1Ayd6iBbSbwspHsN2VQgZfANgJy92cBf7qtpjC0uMiShbO+TEEg==" }, "SharpGLTF.Toolkit": { "type": "Direct", - "requested": "[1.0.1, )", - "resolved": "1.0.1", - "contentHash": "LYBjHdHW5Z8R1oT1iI04si3559tWdZ3jTdHfDEu0jqhuyU8w3oJRLFUoDfVeCOI5zWXlVQPtlpjhH9XTfFFAcA==", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vkEuf8ch76NNgZXU/3zoXTIXRO0o14H3aRoSFzcuUQb0PTxvV6jEfmWkUVO6JtLDuFCIimqZaf3hdxr32ltpfQ==", "dependencies": { - "SharpGLTF.Runtime": "1.0.1" + "SharpGLTF.Runtime": "1.0.3" } }, "SixLabors.ImageSharp": { "type": "Direct", - "requested": "[3.1.5, )", - "resolved": "3.1.5", - "contentHash": "lNtlq7dSI/QEbYey+A0xn48z5w4XHSffF8222cC4F4YwTXfEImuiBavQcWjr49LThT/pRmtWJRcqA/PlL+eJ6g==" + "requested": "[3.1.7, )", + "resolved": "3.1.7", + "contentHash": "9fIOOAsyLFid6qKypM2Iy0Z3Q9yoanV8VoYAHtI2sYGMNKzhvRTjgFDHonIiVe+ANtxIxM6SuqUzj0r91nItpA==" }, "System.Formats.Asn1": { "type": "Direct", - "requested": "[8.0.1, )", - "resolved": "8.0.1", - "contentHash": "XqKba7Mm/koKSjKMfW82olQdmfbI5yqeoLV/tidRp7fbh5rmHAQ5raDI/7SU0swTzv+jgqtUGkzmFxuUg0it1A==" + "requested": "[9.0.2, )", + "resolved": "9.0.2", + "contentHash": "OKWHCPYQr/+cIoO8EVjFn7yFyiT8Mnf1wif/5bYGsqxQV6PrwlX2HQ9brZNx57ViOvRe4ing1xgHCKl/5Ko8xg==" }, "JetBrains.Annotations": { "type": "Transitive", - "resolved": "2024.2.0", - "contentHash": "GNnqCFW/163p1fOehKx0CnAqjmpPrUSqrgfHM6qca+P+RN39C9rhlfZHQpJhxmQG/dkOYe/b3Z0P8b6Kv5m1qw==" + "resolved": "2024.3.0", + "contentHash": "ox5pkeLQXjvJdyAB4b2sBYAlqZGLh3PjSnP1bQNVx72ONuTJ9+34/+Rq91Fc0dG29XG9RgZur9+NcP4riihTug==" }, "Microsoft.Extensions.DependencyInjection": { "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "V8S3bsm50ig6JSyrbcJJ8bW2b9QLGouz+G1miK3UTaOWmMtFwNNNzUf4AleyDWUmTrWMLNnFSLEQtxmxgNQnNQ==", + "resolved": "9.0.2", + "contentHash": "ZffbJrskOZ40JTzcTyKwFHS5eACSWp2bUQBBApIgGV+es8RaTD4OxUG7XxFr3RIPLXtYQ1jQzF2DjKB5fZn7Qg==", "dependencies": { - "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0" + "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.2" } }, "Microsoft.Extensions.DependencyInjection.Abstractions": { "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "cjWrLkJXK0rs4zofsK4bSdg+jhDLTaxrkXu4gS6Y7MAlCvRyNNgwY/lJi5RDlQOnSZweHqoyvgvbdvQsRIW+hg==" + "resolved": "9.0.2", + "contentHash": "MNe7GSTBf3jQx5vYrXF0NZvn6l7hUKF6J54ENfAgCO8y6xjN1XUmKKWG464LP2ye6QqDiA1dkaWEZBYnhoZzjg==" }, "PeNet.Asn1": { "type": "Transitive", @@ -82,19 +83,21 @@ }, "SharpGLTF.Runtime": { "type": "Transitive", - "resolved": "1.0.1", - "contentHash": "KsgEBKLfsEnu2IPeKaWp4Ih97+kby17IohrAB6Ev8gET18iS80nKMW/APytQWpenMmcWU06utInpANqyrwRlDg==", + "resolved": "1.0.3", + "contentHash": "W0bg2WyXlcSAJVu153hNUNm+BU4RP46yLwGD4099hSm8dsXG/H+J95PBoLJbIq8KGVkUWvfM0+XWHoEkCyd50A==", "dependencies": { - "SharpGLTF.Core": "1.0.1" + "SharpGLTF.Core": "1.0.3" } }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.0", + "contentHash": "lN6tZi7Q46zFzAbRYXTIvfXcyvQQgxnY7Xm6C6xQ9784dEL1amjM6S6Iw4ZpsvesAKnRVsM4scrDQaDqSClkjA==" + }, "System.Security.Cryptography.Pkcs": { "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "ULmp3xoOwNYjOYp4JZ2NK/6NdTgiN1GQXzVVN1njQ7LOZ0d0B9vyMnhyqbIi9Qw4JXj1JgCsitkTShboHRx7Eg==", - "dependencies": { - "System.Formats.Asn1": "8.0.0" - } + "resolved": "8.0.1", + "contentHash": "CoCRHFym33aUSf/NtWSVSZa99dkd0Hm7OCZUxORBjRB16LNhIEOf8THPqzIYlvKM0nNDAPTRBa1FxEECrgaxxA==" }, "System.ValueTuple": { "type": "Transitive", @@ -111,14 +114,14 @@ }, "ZstdSharp.Port": { "type": "Transitive", - "resolved": "0.8.0", - "contentHash": "Z62eNBIu8E8YtbqlMy57tK3dV1+m2b9NhPeaYovB5exmLKvrGCqOhJTzrEUH5VyUWU6vwX3c1XHJGhW5HVs8dA==" + "resolved": "0.8.4", + "contentHash": "eieSXq3kakCUXbgdxkKaRqWS6hF0KBJcqok9LlDCs60GOyrynLvPOcQ0pRw7shdPF7lh/VepJ9cP9n9HHc759g==" }, "ottergui": { "type": "Project", "dependencies": { - "JetBrains.Annotations": "[2024.2.0, )", - "Microsoft.Extensions.DependencyInjection": "[8.0.0, )" + "JetBrains.Annotations": "[2024.3.0, )", + "Microsoft.Extensions.DependencyInjection": "[9.0.2, )" } }, "penumbra.api": { @@ -131,8 +134,8 @@ "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[5.3.0, )", - "Penumbra.String": "[1.0.4, )" + "Penumbra.Api": "[5.6.0, )", + "Penumbra.String": "[1.0.5, )" } }, "penumbra.string": { From 6eacc82dcdb5bb26f54421de239ea0be4eec9750 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Mar 2025 13:48:41 +0100 Subject: [PATCH 1133/1381] Update references. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Penumbra.csproj | 12 ++++++------ 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/OtterGui b/OtterGui index c347d29d..13f1a90b 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit c347d29d980b0191d1d071170cf2ec229e3efdcf +Subproject commit 13f1a90b88d2b8572480748a209f957b70d6a46f diff --git a/Penumbra.Api b/Penumbra.Api index 70f04683..404c8aaa 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 70f046830cc7cd35b3480b12b7efe94182477fbb +Subproject commit 404c8aaa5115925006963baa118bf710c7953380 diff --git a/Penumbra.GameData b/Penumbra.GameData index a21c1467..96163f79 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit a21c146790b370bd58b0f752385ae153f7e769c0 +Subproject commit 96163f79e13c7d52cc36cdd82ab4e823763f4f31 diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 9b613729..b4266aeb 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -87,13 +87,13 @@ - + - - - - - + + + + + From eab98ec0e4cefaeff12fccb55a6fdc5c36cbfde3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 9 Mar 2025 14:41:45 +0100 Subject: [PATCH 1134/1381] 1.3.5.0 --- Penumbra/UI/Changelog.cs | 135 ++++++++++++++++++++++++++++++--------- 1 file changed, 105 insertions(+), 30 deletions(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 993ace62..87dd101d 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -58,20 +58,65 @@ public class PenumbraChangelog : IUiService Add1_3_2_0(Changelog); Add1_3_3_0(Changelog); Add1_3_4_0(Changelog); - } - + Add1_3_5_0(Changelog); + } + #region Changelogs + private static void Add1_3_5_0(Changelog log) + => log.NextVersion("Version 1.3.5.0") + .RegisterImportant( + "Redirections of unsupported file types like .atch will now produce warnings when they are enabled. Please update mods still containing them or request updates from their creators.") + .RegisterEntry("You can now import .atch in the Meta section of advanced editing to add their non-default changes to the mod.") + .RegisterHighlight("Added an option in settings and in the collection bar in the mod tab to always use temporary settings.") + .RegisterEntry( + "While this option is enabled, all changes you make in the current collection will be applied as temporary changes, and you have to use Turn Permanent to make them permanent.", + 1) + .RegisterEntry( + "This should be useful for trying out new mods without needing to reset their settings later, or for creating mod associations in Glamourer from them.", + 1) + .RegisterEntry( + "Added a context menu entry on the mod selector blank-space context menu to clear all temporary settings made manually.") + .RegisterHighlight( + "Resource Trees now consider some additional files like decals, and improved the quick-import behaviour for some files that should not generally be modded.") + .RegisterHighlight("The Changed Item display for single mods has been heavily improved.") + .RegisterEntry("Any changed item will now show how many individual edits are affecting it in the mod in its tooltip.", 1) + .RegisterEntry("Equipment pieces are now grouped by their model id, reducing clutter.", 1) + .RegisterEntry( + "The primary equipment piece displayed is the one with the most changes affecting it, but can be configured to a specific item by the mod creator and locally.", + 1) + .RegisterEntry( + "Preferred changed items stored in the mod will be shared when exporting the mod, and used as the default for local preferences, which will not be shared.", + 2) + .RegisterEntry( + "You can configure whether groups are automatically collapsed or expanded, or remove grouping entirely in the settings.", 1) + .RegisterHighlight("Fixed support for model import/export with more than one UV.") + .RegisterEntry("Added some IPC relating to changed items.") + .RegisterEntry("Skeleton and Physics changes should now be identified in Changed Items.") + .RegisterEntry("Item Swaps will now also correctly swap EQP entries of multi-slot pieces.") + .RegisterEntry("Meta edit transmission through IPC should be a lot more efficient than before.") + .RegisterEntry("Fixed an issue with incognito names in some cutscenes.") + .RegisterEntry("Newly extracted mod folders will now try to rename themselves three times before being considered a failure."); + private static void Add1_3_4_0(Changelog log) => log.NextVersion("Version 1.3.4.0") - .RegisterHighlight("Added HDR functionality to diffuse buffers. This allows more accurate representation of non-standard color values for e.g. skin or hair colors when used with advanced customizations in Glamourer.") - .RegisterEntry("This option requires Wait For Plugins On Load to be enabled in Dalamud and to be enabled on start to work. It is on by default but can be turned off.", 1) + .RegisterHighlight( + "Added HDR functionality to diffuse buffers. This allows more accurate representation of non-standard color values for e.g. skin or hair colors when used with advanced customizations in Glamourer.") + .RegisterEntry( + "This option requires Wait For Plugins On Load to be enabled in Dalamud and to be enabled on start to work. It is on by default but can be turned off.", + 1) .RegisterHighlight("Added a new option group type: Combining Groups.") - .RegisterEntry("A combining group behaves similarly to a multi group for the user, but instead of enabling the different options separately, it results in exactly one option per choice of settings.", 1) - .RegisterEntry("Example: The user sees 2 checkboxes [+25%, +50%], but the 4 different selection states result in +0%, +25%, +50% or +75% if both are toggled on. Every choice of settings can be configured separately by the mod creator.", 1) - .RegisterEntry("Added new functionality to better track copies of the player character in cutscenes if they get forced to specific clothing, like in the Margrat cutscene. Might improve tracking in wedding ceremonies, too, let me know.") + .RegisterEntry( + "A combining group behaves similarly to a multi group for the user, but instead of enabling the different options separately, it results in exactly one option per choice of settings.", + 1) + .RegisterEntry( + "Example: The user sees 2 checkboxes [+25%, +50%], but the 4 different selection states result in +0%, +25%, +50% or +75% if both are toggled on. Every choice of settings can be configured separately by the mod creator.", + 1) + .RegisterEntry( + "Added new functionality to better track copies of the player character in cutscenes if they get forced to specific clothing, like in the Margrat cutscene. Might improve tracking in wedding ceremonies, too, let me know.") .RegisterEntry("Added a display of the number of selected files and folders to the multi mod selection.") - .RegisterEntry("Added cleaning functionality to remove outdated or unused files or backups from the config and mod folders via manual action.") + .RegisterEntry( + "Added cleaning functionality to remove outdated or unused files or backups from the config and mod folders via manual action.") .RegisterEntry("Updated the Bone and Material limits in the Model Importer.") .RegisterEntry("Improved handling of IMC and Material files loaded asynchronously.") .RegisterEntry("Added IPC functionality to query temporary settings.") @@ -86,49 +131,75 @@ public class PenumbraChangelog : IUiService private static void Add1_3_3_0(Changelog log) => log.NextVersion("Version 1.3.3.0") .RegisterHighlight("Added Temporary Settings to collections.") - .RegisterEntry("Settings can be manually turned temporary (and turned back) while editing mod settings via right-click context on the mod or buttons in the settings panel.", 1) - .RegisterEntry("This can be used to test mods or changes without saving those changes permanently or having to reinstate the old settings afterwards.", 1) - .RegisterEntry("More importantly, this can be set via IPC by other plugins, allowing Glamourer to only set and reset temporary settings when applying Mod Associations.", 1) - .RegisterEntry("As an extreme example, it would be possible to only enable the consistent mods for your character in the collection, and let Glamourer handle all outfit mods itself via temporary settings only.", 1) - .RegisterEntry("This required some pretty big changes that were in testing for a while now, but nobody talked about it much so it may still have some bugs or usability issues. Let me know!", 1) - .RegisterHighlight("Added an option to automatically select the collection assigned to the current character on login events. This is off by default.") - .RegisterEntry("Added partial copying of color tables in material editing via right-click context menu entries on the import buttons.") - .RegisterHighlight("Added handling for TMB files cached by the game that should resolve issues of leaky TMBs from animation and VFX mods.") - .RegisterEntry("The enabled checkbox, Priority and Inheriting buttons now stick at the top of the Mod Settings panel even when scrolling down for specific settings.") + .RegisterEntry( + "Settings can be manually turned temporary (and turned back) while editing mod settings via right-click context on the mod or buttons in the settings panel.", + 1) + .RegisterEntry( + "This can be used to test mods or changes without saving those changes permanently or having to reinstate the old settings afterwards.", + 1) + .RegisterEntry( + "More importantly, this can be set via IPC by other plugins, allowing Glamourer to only set and reset temporary settings when applying Mod Associations.", + 1) + .RegisterEntry( + "As an extreme example, it would be possible to only enable the consistent mods for your character in the collection, and let Glamourer handle all outfit mods itself via temporary settings only.", + 1) + .RegisterEntry( + "This required some pretty big changes that were in testing for a while now, but nobody talked about it much so it may still have some bugs or usability issues. Let me know!", + 1) + .RegisterHighlight( + "Added an option to automatically select the collection assigned to the current character on login events. This is off by default.") + .RegisterEntry( + "Added partial copying of color tables in material editing via right-click context menu entries on the import buttons.") + .RegisterHighlight( + "Added handling for TMB files cached by the game that should resolve issues of leaky TMBs from animation and VFX mods.") + .RegisterEntry( + "The enabled checkbox, Priority and Inheriting buttons now stick at the top of the Mod Settings panel even when scrolling down for specific settings.") .RegisterEntry("When creating new mods with Item Swap, the attributed author of the resulting mod was improved.") .RegisterEntry("Fixed an issue with rings in the On-Screen tab and in the data sent over to other plugins via IPC.") - .RegisterEntry("Fixed some issues when writing material files that resulted in technically valid files that still caused some issues with the game for unknown reasons.") + .RegisterEntry( + "Fixed some issues when writing material files that resulted in technically valid files that still caused some issues with the game for unknown reasons.") .RegisterEntry("Fixed some ImGui assertions."); private static void Add1_3_2_0(Changelog log) => log.NextVersion("Version 1.3.2.0") .RegisterHighlight("Added ATCH meta manipulations that allow the composite editing of attachment points across multiple mods.") .RegisterEntry("Those ATCH manipulations should be shared via Mare Synchronos.", 1) - .RegisterEntry("This is an early implementation and might be bug-prone. Let me know of any issues. It was in testing for quite a while without reports.", 1) - .RegisterEntry("Added jumping to identified mods in the On-Screen tab via Control + Right-Click and improved their display slightly.") + .RegisterEntry( + "This is an early implementation and might be bug-prone. Let me know of any issues. It was in testing for quite a while without reports.", + 1) + .RegisterEntry( + "Added jumping to identified mods in the On-Screen tab via Control + Right-Click and improved their display slightly.") .RegisterEntry("Added some right-click context menu copy options in the File Redirections editor for paths.") .RegisterHighlight("Added the option to change a specific mod's settings via chat commands by using '/penumbra mod settings'.") .RegisterEntry("Fixed issues with the copy-pasting of meta manipulations.") .RegisterEntry("Fixed some other issues related to meta manipulations.") - .RegisterEntry("Updated available NPC names and fixed an issue with some supposedly invisible characters in names showing in ImGui."); + .RegisterEntry( + "Updated available NPC names and fixed an issue with some supposedly invisible characters in names showing in ImGui."); private static void Add1_3_1_0(Changelog log) => log.NextVersion("Version 1.3.1.0") .RegisterEntry("Penumbra has been updated for Dalamud API 11 and patch 7.1.") - .RegisterImportant("There are some known issues with potential crashes using certain VFX/SFX mods, probably related to sound files.") - .RegisterEntry("If you encounter those issues, please report them in the discord and potentially disable the corresponding mods for the time being.", 1) - .RegisterImportant("The modding of .atch files has been disabled. Outdated modded versions of these files cause crashes when loaded.") + .RegisterImportant( + "There are some known issues with potential crashes using certain VFX/SFX mods, probably related to sound files.") + .RegisterEntry( + "If you encounter those issues, please report them in the discord and potentially disable the corresponding mods for the time being.", + 1) + .RegisterImportant( + "The modding of .atch files has been disabled. Outdated modded versions of these files cause crashes when loaded.") .RegisterEntry("A better way for modular modding of .atch files via meta changes will release to the testing branch soonish.", 1) .RegisterHighlight("Temporary collections (as created by Mare) will now always respect ownership.") - .RegisterEntry("This means that you can toggle this setting off if you do not want it, and Mare will still work for minions and mounts of other players.", 1) - .RegisterEntry("The new physics and animation engine files (.kdb and .bnmb) should now be correctly redirected and respect EST changes.") + .RegisterEntry( + "This means that you can toggle this setting off if you do not want it, and Mare will still work for minions and mounts of other players.", + 1) + .RegisterEntry( + "The new physics and animation engine files (.kdb and .bnmb) should now be correctly redirected and respect EST changes.") .RegisterEntry("Fixed issues with EQP entries being labeled wrongly and global EQP not changing all required values for earrings.") .RegisterEntry("Fixed an issue with global EQP changes of a mod being reset upon reloading the mod.") .RegisterEntry("Fixed another issue with left rings and mare synchronization / the on-screen tab.") .RegisterEntry("Maybe fixed some issues with characters appearing in the login screen being misidentified.") .RegisterEntry("Some improvements for debug visualization have been made."); - + private static void Add1_3_0_0(Changelog log) => log.NextVersion("Version 1.3.0.0") @@ -138,16 +209,20 @@ public class PenumbraChangelog : IUiService .RegisterEntry("Reworked quite a bit of things around face wear / bonus items. Please let me know if anything broke.", 1) .RegisterEntry("The import date of a mod is now shown in the Edit Mod tab, and can be reset via button.") .RegisterEntry("A button to open the file containing local mod data for a mod was also added.", 1) - .RegisterHighlight("IMC groups can now be configured to only apply the attribute flags for their entry, and take the other values from the default value.") + .RegisterHighlight( + "IMC groups can now be configured to only apply the attribute flags for their entry, and take the other values from the default value.") .RegisterEntry("This allows keeping the material index of every IMC entry of a group, while setting the attributes.", 1) .RegisterHighlight("Model Import/Export was fixed and re-enabled (thanks ackwell and ramen).") .RegisterHighlight("Added a hack to allow bonus items (face wear, glasses) to have VFX.") .RegisterEntry("Also fixed the hack that allowed accessories to have VFX not working anymore.", 1) .RegisterHighlight("Added rudimentary options to edit PBD files in the advanced editing window.") .RegisterEntry("Preparing the advanced editing window for a mod now does not freeze the game until it is ready.") - .RegisterEntry("Meta Manipulations in the advanced editing window are now ordered and do not eat into performance as much when drawn.") + .RegisterEntry( + "Meta Manipulations in the advanced editing window are now ordered and do not eat into performance as much when drawn.") .RegisterEntry("Added a button to the advanced editing window to remove all default-valued meta manipulations from a mod") - .RegisterEntry("Default-valued manipulations will now also be removed on import from archives and .pmps, not just .ttmps, if not configured otherwise.", 1) + .RegisterEntry( + "Default-valued manipulations will now also be removed on import from archives and .pmps, not just .ttmps, if not configured otherwise.", + 1) .RegisterEntry("Checkbox-based mod filters are now tri-state checkboxes instead of two disjoint checkboxes.") .RegisterEntry("Paths from the resource logger can now be copied.") .RegisterEntry("Silenced some redundant error logs when updating mods via Heliosphere.") From 1d70be8060f92e3c7ad9fdfd671a42b7437774bf Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 9 Mar 2025 22:16:58 +0000 Subject: [PATCH 1135/1381] [CI] Updating repo.json for 1.3.5.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index b098593a..8de11f0e 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.4.0", - "TestingAssemblyVersion": "1.3.4.6", + "AssemblyVersion": "1.3.5.0", + "TestingAssemblyVersion": "1.3.5.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.4.6/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.4.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 93b0996794ea68104cc0f93bfb9ab826a91ec318 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 11 Mar 2025 18:12:54 +0100 Subject: [PATCH 1136/1381] Add chat command to clear temporary settings. --- Penumbra/CommandHandler.cs | 47 ++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index dee46e32..9f681da2 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -75,20 +75,21 @@ public class CommandHandler : IDisposable, IApiService _ = argumentList[0].ToLowerInvariant() switch { - "window" => ToggleWindow(arguments), - "enable" => SetPenumbraState(arguments, true), - "disable" => SetPenumbraState(arguments, false), - "toggle" => SetPenumbraState(arguments, null), - "reload" => Reload(arguments), - "redraw" => Redraw(arguments), - "lockui" => SetUiLockState(arguments), - "size" => SetUiMinimumSize(arguments), - "debug" => SetDebug(arguments), - "collection" => SetCollection(arguments), - "mod" => SetMod(arguments), - "bulktag" => SetTag(arguments), - "knowledge" => HandleKnowledge(arguments), - _ => PrintHelp(argumentList[0]), + "window" => ToggleWindow(arguments), + "enable" => SetPenumbraState(arguments, true), + "disable" => SetPenumbraState(arguments, false), + "toggle" => SetPenumbraState(arguments, null), + "reload" => Reload(arguments), + "redraw" => Redraw(arguments), + "lockui" => SetUiLockState(arguments), + "size" => SetUiMinimumSize(arguments), + "debug" => SetDebug(arguments), + "collection" => SetCollection(arguments), + "mod" => SetMod(arguments), + "bulktag" => SetTag(arguments), + "clearsettings" => ClearSettings(arguments), + "knowledge" => HandleKnowledge(arguments), + _ => PrintHelp(argumentList[0]), }; } @@ -126,6 +127,21 @@ public class CommandHandler : IDisposable, IApiService _chat.Print(new SeStringBuilder() .AddCommand("bulktag", "Change multiple mods settings based on their tags. Use without further parameters for more detailed help.") .BuiltString); + _chat.Print(new SeStringBuilder() + .AddCommand("clearsettings", + "Clear all temporary settings applied manually through Penumbra in the current or all collections. Use with 'all' parameter for all.") + .BuiltString); + return true; + } + + private bool ClearSettings(string arguments) + { + if (arguments.Trim().ToLowerInvariant() is "all") + foreach (var collection in _collectionManager.Storage) + _collectionEditor.ClearTemporarySettings(collection); + else + _collectionEditor.ClearTemporarySettings(_collectionManager.Active.Current); + return true; } @@ -416,7 +432,8 @@ public class CommandHandler : IDisposable, IApiService var split2 = nameSplit[1].Split('|', 3, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); if (split2.Length < 2) { - _chat.Print("Not enough arguments for changing settings provided. Please add a group name and a list of setting names - which can be empty for multi options."); + _chat.Print( + "Not enough arguments for changing settings provided. Please add a group name and a list of setting names - which can be empty for multi options."); return false; } From e5620e17e0f468ab6331e9dbf347e881c592cb5b Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 12 Mar 2025 01:20:36 +0100 Subject: [PATCH 1137/1381] Improve texture saving --- Penumbra/Import/Textures/TextureManager.cs | 43 ++++++++++++------ Penumbra/Penumbra.csproj | 4 ++ .../Materials/MtrlTab.LivePreview.cs | 2 +- .../AdvancedWindow/ModEditWindow.Textures.cs | 21 +++++++-- Penumbra/lib/OtterTex.dll | Bin 41984 -> 42496 bytes 5 files changed, 50 insertions(+), 20 deletions(-) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 7118f8af..6adf5861 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -1,3 +1,4 @@ +using Dalamud.Interface; using Dalamud.Interface.Textures; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Services; @@ -6,15 +7,17 @@ using OtterGui.Log; using OtterGui.Services; using OtterGui.Tasks; using OtterTex; +using SharpDX.Direct3D11; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.Formats.Tga; using SixLabors.ImageSharp.PixelFormats; +using DxgiDevice = SharpDX.DXGI.Device; using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; -public sealed class TextureManager(IDataManager gameData, Logger logger, ITextureProvider textureProvider) +public sealed class TextureManager(IDataManager gameData, Logger logger, ITextureProvider textureProvider, IUiBuilder uiBuilder) : SingleTaskQueue, IDisposable, IService { private readonly Logger _logger = logger; @@ -47,11 +50,11 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, string output) - => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, input, output)); + => Enqueue(new SaveAsAction(this, type, uiBuilder.Device, mipMaps, asTex, input, output)); public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) - => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, image, path, rgba, width, height)); + => Enqueue(new SaveAsAction(this, type, uiBuilder.Device, mipMaps, asTex, image, path, rgba, width, height)); private Task Enqueue(IAction action) { @@ -156,27 +159,30 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur private readonly string _outputPath; private readonly ImageInputData _input; private readonly CombinedTexture.TextureSaveType _type; + private readonly Device? _device; private readonly bool _mipMaps; private readonly bool _asTex; - public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, - string output) + public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, Device? device, bool mipMaps, bool asTex, + string input, string output) { _textures = textures; _input = new ImageInputData(input); _outputPath = output; _type = type; + _device = device; _mipMaps = mipMaps; _asTex = asTex; } - public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, - string path, byte[]? rgba = null, int width = 0, int height = 0) + public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, Device? device, bool mipMaps, bool asTex, + BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) { _textures = textures; _input = new ImageInputData(image, rgba, width, height); _outputPath = path; _type = type; + _device = device; _mipMaps = mipMaps; _asTex = asTex; } @@ -201,8 +207,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur rgba, width, height), CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC7 => ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, _device, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC7 => ConvertToCompressedDds(image, _mipMaps, true, _device, cancel, rgba, width, height), _ => throw new Exception("Wrong save type."), }; @@ -320,8 +326,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Convert an existing image to a block compressed .dds. Does not create a deep copy of an existing dds of the correct format and just returns the existing one. - public static BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, CancellationToken cancel, byte[]? rgba = null, - int width = 0, int height = 0) + public static BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, Device? device, CancellationToken cancel, + byte[]? rgba = null, int width = 0, int height = 0) { switch (input.Type.ReduceToBehaviour()) { @@ -331,12 +337,12 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur cancel.ThrowIfCancellationRequested(); var dds = ConvertToDds(rgba, width, height).AsDds!; cancel.ThrowIfCancellationRequested(); - return CreateCompressed(dds, mipMaps, bc7, cancel); + return CreateCompressed(dds, mipMaps, bc7, device, cancel); } case TextureType.Dds: { var scratch = input.AsDds!; - return CreateCompressed(scratch, mipMaps, bc7, cancel); + return CreateCompressed(scratch, mipMaps, bc7, device, cancel); } default: return new BaseImage(); } @@ -384,7 +390,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Create a BC3 or BC7 block-compressed .dds from the input (optionally with mipmaps). Returns input (+ mipmaps) if it is already the correct format. - public static ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, bool bc7, CancellationToken cancel) + public static ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, bool bc7, Device? device, CancellationToken cancel) { var format = bc7 ? DXGIFormat.BC7UNorm : DXGIFormat.BC3UNorm; if (input.Meta.Format == format) @@ -398,6 +404,15 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur input = AddMipMaps(input, mipMaps); cancel.ThrowIfCancellationRequested(); + // See https://github.com/microsoft/DirectXTex/wiki/Compress#parameters for the format condition. + if (device is not null && format is DXGIFormat.BC6HUF16 or DXGIFormat.BC6HSF16 or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB) + { + var dxgiDevice = device.QueryInterface(); + + using var deviceClone = new Device(dxgiDevice.Adapter, device.CreationFlags, device.FeatureLevel); + return input.Compress(deviceClone.NativePointer, format, CompressFlags.Parallel); + } + return input.Compress(format, CompressFlags.BC7Quick | CompressFlags.Parallel); } diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index b4266aeb..870865da 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -80,6 +80,10 @@ $(DalamudLibPath)SharpDX.Direct3D11.dll False + + $(DalamudLibPath)SharpDX.DXGI.dll + False + lib\OtterTex.dll diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs index 01a40980..5025bafd 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs @@ -138,7 +138,7 @@ public partial class MtrlTab foreach (var constant in Mtrl.ShaderPackage.Constants) { var values = Mtrl.GetConstantValue(constant); - if (values != null) + if (values != []) SetMaterialParameter(constant.Id, 0, values); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index c08e8a8e..d0764808 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -134,7 +134,7 @@ public partial class ModEditWindow tt, !isActive || !canSaveInPlace || _center.IsLeftCopy && _currentSaveAs == (int)CombinedTexture.TextureSaveType.AsIs)) { _center.SaveAs(_left.Type, _textures, _left.Path, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); - InvokeChange(Mod, _left.Path); + AddChangeTask(_left.Path); AddReloadTask(_left.Path, false); } @@ -159,7 +159,7 @@ public partial class ModEditWindow !canConvertInPlace || _left.Format is DXGIFormat.BC7Typeless or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC7, _left.MipMaps > 1); - InvokeChange(Mod, _left.Path); + AddChangeTask(_left.Path); AddReloadTask(_left.Path, false); } @@ -169,7 +169,7 @@ public partial class ModEditWindow !canConvertInPlace || _left.Format is DXGIFormat.BC3Typeless or DXGIFormat.BC3UNorm or DXGIFormat.BC3UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.BC3, _left.MipMaps > 1); - InvokeChange(Mod, _left.Path); + AddChangeTask(_left.Path); AddReloadTask(_left.Path, false); } @@ -180,7 +180,7 @@ public partial class ModEditWindow || _left.Format is DXGIFormat.B8G8R8A8UNorm or DXGIFormat.B8G8R8A8Typeless or DXGIFormat.B8G8R8A8UNormSRGB)) { _center.SaveAsTex(_textures, _left.Path, CombinedTexture.TextureSaveType.Bitmap, _left.MipMaps > 1); - InvokeChange(Mod, _left.Path); + AddChangeTask(_left.Path); AddReloadTask(_left.Path, false); } } @@ -235,7 +235,7 @@ public partial class ModEditWindow if (a) { _center.SaveAs(null, _textures, b, (CombinedTexture.TextureSaveType)_currentSaveAs, _addMipMaps); - InvokeChange(Mod, b); + AddChangeTask(b); if (b == _left.Path) AddReloadTask(_left.Path, false); else if (b == _right.Path) @@ -245,6 +245,17 @@ public partial class ModEditWindow _forceTextureStartPath = false; } + private void AddChangeTask(string path) + { + _center.SaveTask.ContinueWith(t => + { + if (!t.IsCompletedSuccessfully) + return; + + _framework.RunOnFrameworkThread(() => InvokeChange(Mod, path)); + }, TaskScheduler.Default); + } + private void AddReloadTask(string path, bool right) { _center.SaveTask.ContinueWith(t => diff --git a/Penumbra/lib/OtterTex.dll b/Penumbra/lib/OtterTex.dll index 29912e6215ff28a7959b73aa1e00cc9ebb919d76..c137aee184d789102648a05ecc24c0437df54ba1 100644 GIT binary patch delta 16738 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 delta 16281 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 Date: Wed, 12 Mar 2025 15:18:20 +0100 Subject: [PATCH 1138/1381] Simplify passing of the device (suggested by @rootdarkarchon) --- Penumbra/Import/Textures/TextureManager.cs | 32 ++++++++++------------ 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 6adf5861..8fab097e 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -50,11 +50,11 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, string output) - => Enqueue(new SaveAsAction(this, type, uiBuilder.Device, mipMaps, asTex, input, output)); + => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, input, output)); public Task SaveAs(CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) - => Enqueue(new SaveAsAction(this, type, uiBuilder.Device, mipMaps, asTex, image, path, rgba, width, height)); + => Enqueue(new SaveAsAction(this, type, mipMaps, asTex, image, path, rgba, width, height)); private Task Enqueue(IAction action) { @@ -159,30 +159,27 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur private readonly string _outputPath; private readonly ImageInputData _input; private readonly CombinedTexture.TextureSaveType _type; - private readonly Device? _device; private readonly bool _mipMaps; private readonly bool _asTex; - public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, Device? device, bool mipMaps, bool asTex, - string input, string output) + public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, string input, + string output) { _textures = textures; _input = new ImageInputData(input); _outputPath = output; _type = type; - _device = device; _mipMaps = mipMaps; _asTex = asTex; } - public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, Device? device, bool mipMaps, bool asTex, - BaseImage image, string path, byte[]? rgba = null, int width = 0, int height = 0) + public SaveAsAction(TextureManager textures, CombinedTexture.TextureSaveType type, bool mipMaps, bool asTex, BaseImage image, + string path, byte[]? rgba = null, int width = 0, int height = 0) { _textures = textures; _input = new ImageInputData(image, rgba, width, height); _outputPath = path; _type = type; - _device = device; _mipMaps = mipMaps; _asTex = asTex; } @@ -207,8 +204,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur rgba, width, height), CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC3 => ConvertToCompressedDds(image, _mipMaps, false, _device, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC7 => ConvertToCompressedDds(image, _mipMaps, true, _device, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC3 => _textures.ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC7 => _textures.ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), _ => throw new Exception("Wrong save type."), }; @@ -326,8 +323,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Convert an existing image to a block compressed .dds. Does not create a deep copy of an existing dds of the correct format and just returns the existing one. - public static BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, Device? device, CancellationToken cancel, - byte[]? rgba = null, int width = 0, int height = 0) + public BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, CancellationToken cancel, byte[]? rgba = null, + int width = 0, int height = 0) { switch (input.Type.ReduceToBehaviour()) { @@ -337,12 +334,12 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur cancel.ThrowIfCancellationRequested(); var dds = ConvertToDds(rgba, width, height).AsDds!; cancel.ThrowIfCancellationRequested(); - return CreateCompressed(dds, mipMaps, bc7, device, cancel); + return CreateCompressed(dds, mipMaps, bc7, cancel); } case TextureType.Dds: { var scratch = input.AsDds!; - return CreateCompressed(scratch, mipMaps, bc7, device, cancel); + return CreateCompressed(scratch, mipMaps, bc7, cancel); } default: return new BaseImage(); } @@ -390,7 +387,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Create a BC3 or BC7 block-compressed .dds from the input (optionally with mipmaps). Returns input (+ mipmaps) if it is already the correct format. - public static ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, bool bc7, Device? device, CancellationToken cancel) + public ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, bool bc7, CancellationToken cancel) { var format = bc7 ? DXGIFormat.BC7UNorm : DXGIFormat.BC3UNorm; if (input.Meta.Format == format) @@ -405,8 +402,9 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur input = AddMipMaps(input, mipMaps); cancel.ThrowIfCancellationRequested(); // See https://github.com/microsoft/DirectXTex/wiki/Compress#parameters for the format condition. - if (device is not null && format is DXGIFormat.BC6HUF16 or DXGIFormat.BC6HSF16 or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB) + if (format is DXGIFormat.BC6HUF16 or DXGIFormat.BC6HSF16 or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB) { + var device = uiBuilder.Device; var dxgiDevice = device.QueryInterface(); using var deviceClone = new Device(dxgiDevice.Adapter, device.CreationFlags, device.FeatureLevel); From 442ae960cf429ddf9703252615916acf3fa0d679 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 12 Mar 2025 20:03:53 +0100 Subject: [PATCH 1139/1381] Add encoding support for BC1, BC4 and BC5 --- Penumbra/Import/Textures/CombinedTexture.cs | 3 +++ Penumbra/Import/Textures/TextureManager.cs | 16 +++++++++------- .../UI/AdvancedWindow/ModEditWindow.Textures.cs | 12 +++++++++--- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/Penumbra/Import/Textures/CombinedTexture.cs b/Penumbra/Import/Textures/CombinedTexture.cs index c1a22088..f5f921be 100644 --- a/Penumbra/Import/Textures/CombinedTexture.cs +++ b/Penumbra/Import/Textures/CombinedTexture.cs @@ -6,7 +6,10 @@ public partial class CombinedTexture : IDisposable { AsIs, Bitmap, + BC1, BC3, + BC4, + BC5, BC7, } diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 8fab097e..0c85f5be 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -204,8 +204,11 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur rgba, width, height), CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC3 => _textures.ConvertToCompressedDds(image, _mipMaps, false, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC7 => _textures.ConvertToCompressedDds(image, _mipMaps, true, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC1 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC1UNorm, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC3 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC3UNorm, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC4 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC4UNorm, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC5 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC5UNorm, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC7 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC7UNorm, cancel, rgba, width, height), _ => throw new Exception("Wrong save type."), }; @@ -323,7 +326,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Convert an existing image to a block compressed .dds. Does not create a deep copy of an existing dds of the correct format and just returns the existing one. - public BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, bool bc7, CancellationToken cancel, byte[]? rgba = null, + public BaseImage ConvertToCompressedDds(BaseImage input, bool mipMaps, DXGIFormat format, CancellationToken cancel, byte[]? rgba = null, int width = 0, int height = 0) { switch (input.Type.ReduceToBehaviour()) @@ -334,12 +337,12 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur cancel.ThrowIfCancellationRequested(); var dds = ConvertToDds(rgba, width, height).AsDds!; cancel.ThrowIfCancellationRequested(); - return CreateCompressed(dds, mipMaps, bc7, cancel); + return CreateCompressed(dds, mipMaps, format, cancel); } case TextureType.Dds: { var scratch = input.AsDds!; - return CreateCompressed(scratch, mipMaps, bc7, cancel); + return CreateCompressed(scratch, mipMaps, format, cancel); } default: return new BaseImage(); } @@ -387,9 +390,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Create a BC3 or BC7 block-compressed .dds from the input (optionally with mipmaps). Returns input (+ mipmaps) if it is already the correct format. - public ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, bool bc7, CancellationToken cancel) + public ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, DXGIFormat format, CancellationToken cancel) { - var format = bc7 ? DXGIFormat.BC7UNorm : DXGIFormat.BC3UNorm; if (input.Meta.Format == format) return input; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index d0764808..274c216b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -26,9 +26,15 @@ public partial class ModEditWindow ("As Is", "Save the current texture with its own format without additional conversion or compression, if possible."), ("RGBA (Uncompressed)", "Save the current texture as an uncompressed BGRA bitmap. This requires the most space but technically offers the best quality."), - ("BC3 (Simple Compression)", - "Save the current texture compressed via BC3/DXT5 compression. This offers a 4:1 compression ratio and is quick with acceptable quality."), - ("BC7 (Complex Compression)", + ("BC1 (Simple Compression for Opaque RGB)", + "Save the current texture compressed via BC1/DXT1 compression. This offers a 8:1 compression ratio and is quick with acceptable quality, but only supports RGB, without Alpha."), + ("BC3 (Simple Compression for RGBA)", + "Save the current texture compressed via BC3/DXT5 compression. This offers a 4:1 compression ratio and is quick with acceptable quality, and fully supports RGBA."), + ("BC4 (Simple Compression for Opaque Grayscale)", + "Save the current texture compressed via BC4 compression. This offers a 8:1 compression ratio and has almost indistinguishable quality, but only supports Grayscale, without Alpha."), + ("BC5 (Simple Compression for Opaque RG)", + "Save the current texture compressed via BC5 compression. This offers a 4:1 compression ratio and has almost indistinguishable quality, but only supports RG, without B or Alpha."), + ("BC7 (Complex Compression for RGBA)", "Save the current texture compressed via BC7 compression. This offers a 4:1 compression ratio and has almost indistinguishable quality, but may take a while."), }; From 4093228e6150c87cc3968ff0371f6a8f64cfcf36 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Wed, 12 Mar 2025 23:04:57 +0100 Subject: [PATCH 1140/1381] Improve wording of block compressions (suggested by @Theo-Asterio) --- Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 274c216b..4664372e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -25,17 +25,17 @@ public partial class ModEditWindow { ("As Is", "Save the current texture with its own format without additional conversion or compression, if possible."), ("RGBA (Uncompressed)", - "Save the current texture as an uncompressed BGRA bitmap. This requires the most space but technically offers the best quality."), + "Save the current texture as an uncompressed BGRA bitmap.\nThis requires the most space but technically offers the best quality."), ("BC1 (Simple Compression for Opaque RGB)", - "Save the current texture compressed via BC1/DXT1 compression. This offers a 8:1 compression ratio and is quick with acceptable quality, but only supports RGB, without Alpha."), + "Save the current texture compressed via BC1/DXT1 compression.\nThis offers a 8:1 compression ratio and is quick with acceptable quality, but only supports RGB, without Alpha.\n\nCan be used for diffuse maps and equipment textures to save extra space."), ("BC3 (Simple Compression for RGBA)", - "Save the current texture compressed via BC3/DXT5 compression. This offers a 4:1 compression ratio and is quick with acceptable quality, and fully supports RGBA."), + "Save the current texture compressed via BC3/DXT5 compression.\nThis offers a 4:1 compression ratio and is quick with acceptable quality, and fully supports RGBA.\n\nGeneric format that can be used for most textures."), ("BC4 (Simple Compression for Opaque Grayscale)", - "Save the current texture compressed via BC4 compression. This offers a 8:1 compression ratio and has almost indistinguishable quality, but only supports Grayscale, without Alpha."), + "Save the current texture compressed via BC4 compression.\nThis offers a 8:1 compression ratio and has almost indistinguishable quality, but only supports Grayscale, without Alpha.\n\nCan be used for face paints and legacy marks."), ("BC5 (Simple Compression for Opaque RG)", - "Save the current texture compressed via BC5 compression. This offers a 4:1 compression ratio and has almost indistinguishable quality, but only supports RG, without B or Alpha."), + "Save the current texture compressed via BC5 compression.\nThis offers a 4:1 compression ratio and has almost indistinguishable quality, but only supports RG, without B or Alpha.\n\nRecommended for index maps, unrecommended for normal maps."), ("BC7 (Complex Compression for RGBA)", - "Save the current texture compressed via BC7 compression. This offers a 4:1 compression ratio and has almost indistinguishable quality, but may take a while."), + "Save the current texture compressed via BC7 compression.\nThis offers a 4:1 compression ratio and has almost indistinguishable quality, but may take a while.\n\nGeneric format that can be used for most textures."), }; private void DrawInputChild(string label, Texture tex, Vector2 size, Vector2 imageSize) From cda6a4c4202866deb8d26fff7726d4c2e99f450a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Mar 2025 00:13:01 +0100 Subject: [PATCH 1141/1381] Make preferred changed item star more noticeable, and make the color configurable. --- Penumbra/UI/Classes/Colors.cs | 2 ++ Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 4c0d1694..9c15ceb8 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -34,6 +34,7 @@ public enum ColorId : short PredefinedTagAdd, PredefinedTagRemove, TemporaryModSettingsTint, + ChangedItemPreferenceStar, NoTint, } @@ -110,6 +111,7 @@ public static class Colors ColorId.TemporaryModSettingsTint => ( 0x30FF0000, "Mod with Temporary Settings", "A mod that has temporary settings. This color is used as a tint for the regular state colors." ), ColorId.NewModTint => ( 0x8000FF00, "New Mod Tint", "A mod that was newly imported or created during this session and has not been enabled yet. This color is used as a tint for the regular state colors."), ColorId.NoTint => ( 0x00000000, "No Tint", "The default tint for all mods."), + ColorId.ChangedItemPreferenceStar => ( 0x30FFFFFF, "Preferred Changed Item Star", "The color of the star button in the mod panel's changed items tab to prioritize specific items."), _ => throw new ArgumentOutOfRangeException( nameof( color ), color, null ), // @formatter:on }; diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index 700f1d66..f70d63d2 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -12,6 +12,7 @@ using Penumbra.GameData.Structs; using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.String; +using Penumbra.UI.Classes; namespace Penumbra.UI.ModsTab; @@ -213,6 +214,7 @@ public class ModPanelChangedItemsTab( private ImGuiStoragePtr _stateStorage; private Vector2 _buttonSize; + private uint _starColor; public void DrawContent() { @@ -236,6 +238,7 @@ public class ModPanelChangedItemsTab( if (!table) return; + _starColor = ColorId.ChangedItemPreferenceStar.Value(); if (cache.AnyExpandable) { ImUtf8.TableSetupColumn("##exp"u8, ImGuiTableColumnFlags.WidthFixed, _buttonSize.Y); @@ -286,7 +289,7 @@ public class ModPanelChangedItemsTab( private void DrawPreferredButton(IdentifiedItem item, int idx) { if (ImUtf8.IconButton(FontAwesomeIcon.Star, "Prefer displaying this item instead of the current primary item.\n\nRight-click for more options."u8, _buttonSize, - false, ImGui.GetColorU32(ImGuiCol.TextDisabled, 0.1f))) + false, _starColor)) dataEditor.AddPreferredItem(selector.Selected!, item.Item.Id, false, true); using var context = ImUtf8.PopupContextItem("StarContext"u8, ImGuiPopupFlags.MouseButtonRight); if (!context) From 87f44d7a880203ee40a03c4a7e660e68ac6444e9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 14 Mar 2025 00:13:57 +0100 Subject: [PATCH 1142/1381] Some minor parser fixes thanks to Anna. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 96163f79..c59dd2e6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 96163f79e13c7d52cc36cdd82ab4e823763f4f31 +Subproject commit c59dd2e6724be71dfe6ade11dacf405f29634fde From dc47a08988d81844738051072a9e96607f5da9c7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 13 Mar 2025 23:20:54 +0000 Subject: [PATCH 1143/1381] [CI] Updating repo.json for testing_1.3.5.1 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 8de11f0e..1617a879 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.5.0", - "TestingAssemblyVersion": "1.3.5.0", + "TestingAssemblyVersion": "1.3.5.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.5.1/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0213096c58e0f3a232f1b1602b88970c37c8a624 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Mar 2025 15:45:42 +0100 Subject: [PATCH 1144/1381] Add BodyHideGloveCuffs name to eqp entries. --- Penumbra.GameData | 2 +- Penumbra/Collections/Cache/EqpCache.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index c59dd2e6..1c1b3d1b 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit c59dd2e6724be71dfe6ade11dacf405f29634fde +Subproject commit 1c1b3d1b2f050ae0424cb299d30b2bbb65514aa6 diff --git a/Penumbra/Collections/Cache/EqpCache.cs b/Penumbra/Collections/Cache/EqpCache.cs index c681b230..da1a1d44 100644 --- a/Penumbra/Collections/Cache/EqpCache.cs +++ b/Penumbra/Collections/Cache/EqpCache.cs @@ -48,8 +48,8 @@ public sealed class EqpCache(MetaFileManager manager, ModCollection collection) ? entry.HasFlag(EqpEntry.BodyHideGlovesL) : entry.HasFlag(EqpEntry.BodyHideGlovesM); return testFlag - ? (entry | EqpEntry._4) & ~EqpEntry.BodyHideGlovesS - : entry & ~(EqpEntry._4 | EqpEntry.BodyHideGlovesS); + ? (entry | EqpEntry.BodyHideGloveCuffs) & ~EqpEntry.BodyHideGlovesS + : entry & ~(EqpEntry.BodyHideGloveCuffs | EqpEntry.BodyHideGlovesS); } [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] From 61d70f7b4e994de1674bdfdcec883c54524b7dcd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Mar 2025 15:45:56 +0100 Subject: [PATCH 1145/1381] Fix identification of EST changes. --- Penumbra/Meta/Manipulations/Est.cs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs index 8a450eee..05d4c014 100644 --- a/Penumbra/Meta/Manipulations/Est.cs +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -29,19 +29,24 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende switch (Slot) { case EstType.Hair: + { + var (gender, race) = GenderRace.Split(); + var id = (CustomizeValue)SetId.Id; changedItems.UpdateCountOrSet( - $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Hair {SetId}", () => new IdentifiedName()); + $"Customization: {gender.ToName()} {race.ToName()} Hair {SetId}", () => IdentifiedCustomization.Hair(race, gender, id)); break; + } case EstType.Face: + { + var (gender, race) = GenderRace.Split(); + var id = (CustomizeValue)SetId.Id; changedItems.UpdateCountOrSet( - $"Customization: {GenderRace.Split().Item2.ToName()} {GenderRace.Split().Item1.ToName()} Face {SetId}", () => new IdentifiedName()); - break; - case EstType.Body: - identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Body)); - break; - case EstType.Head: - identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Head)); + $"Customization: {gender.ToName()} {race.ToName()} Face {SetId}", + () => IdentifiedCustomization.Face(race, gender, id)); break; + } + case EstType.Body: identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Body)); break; + case EstType.Head: identifier.Identify(changedItems, GamePaths.Mdl.Equipment(SetId, GenderRace, EquipSlot.Head)); break; } } From 26a6cc473502952c704465432e97f7a9684a6a06 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Mar 2025 15:46:16 +0100 Subject: [PATCH 1146/1381] Fix clipping in changed items panel without grouping. --- Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index f70d63d2..b12df97d 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -247,7 +247,7 @@ public class ModPanelChangedItemsTab( } else { - ImGuiClip.ClippedDraw(cache.Data, DrawContainer, ImGui.GetFrameHeightWithSpacing()); + ImGuiClip.ClippedDraw(cache.Data, DrawContainer, _buttonSize.Y); } } From 82a1271281509e1158f4c5d3e421f603e0333fc6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Mar 2025 15:46:44 +0100 Subject: [PATCH 1147/1381] Add option to import atch files from the mod itself via context. --- Penumbra/Mods/Editor/ModFileCollection.cs | 16 +++++++--- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 30 ++++++++++++++++--- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 20423493..7667910f 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -13,6 +13,7 @@ public class ModFileCollection : IDisposable, IService private readonly List _tex = []; private readonly List _shpk = []; private readonly List _pbd = []; + private readonly List _atch = []; private readonly SortedSet _missing = []; private readonly HashSet _usedPaths = []; @@ -41,21 +42,24 @@ public class ModFileCollection : IDisposable, IService public IReadOnlyList Pbd => Ready ? _pbd : []; + public IReadOnlyList Atch + => Ready ? _atch : []; + public bool Ready { get; private set; } = true; public void UpdateAll(Mod mod, IModDataContainer option) { - UpdateFiles(mod, new CancellationToken()); - UpdatePaths(mod, option, false, new CancellationToken()); + UpdateFiles(mod, CancellationToken.None); + UpdatePaths(mod, option, false, CancellationToken.None); } public void UpdatePaths(Mod mod, IModDataContainer option) - => UpdatePaths(mod, option, true, new CancellationToken()); + => UpdatePaths(mod, option, true, CancellationToken.None); public void Clear() { ClearFiles(); - ClearPaths(false, new CancellationToken()); + ClearPaths(false, CancellationToken.None); } public void Dispose() @@ -135,6 +139,9 @@ public class ModFileCollection : IDisposable, IService case ".pbd": _pbd.Add(registry); break; + case ".atch": + _atch.Add(registry); + break; } } } @@ -147,6 +154,7 @@ public class ModFileCollection : IDisposable, IService _tex.Clear(); _shpk.Clear(); _pbd.Clear(); + _atch.Clear(); } private void ClearPaths(bool clearRegistries, CancellationToken tok) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index c9a1d059..68424ae9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -75,12 +75,34 @@ public partial class ModEditWindow ImUtf8.Text($"Dragging .atch for {gr.ToName()}..."); return true; }); - ImUtf8.ButtonEx("Import .atch"u8, - _dragDropManager.IsDragging ? ""u8 : "Drag a .atch file containinig its race code in the path here to import its values."u8, - default, - !_dragDropManager.IsDragging); + var hasAtch = _editor.Files.Atch.Count > 0; + if (ImUtf8.ButtonEx("Import .atch"u8, + _dragDropManager.IsDragging + ? ""u8 + : hasAtch + ? "Drag a .atch file containing its race code in the path here to import its values.\n\nClick to select an .atch file from the mod."u8 + : "Drag a .atch file containing its race code in the path here to import its values."u8, default, + !_dragDropManager.IsDragging && !hasAtch) + && hasAtch) + ImUtf8.OpenPopup("##atchPopup"u8); if (_dragDropManager.CreateImGuiTarget("atchDrag", out var files, out _) && files.FirstOrDefault() is { } file) _metaDrawers.Atch.ImportFile(file); + + using var popup = ImUtf8.Popup("##atchPopup"u8); + if (!popup) + return; + + if (!hasAtch) + { + ImGui.CloseCurrentPopup(); + return; + } + + foreach (var atchFile in _editor.Files.Atch) + { + if (ImUtf8.Selectable(atchFile.RelPath.Path.Span) && atchFile.File.Exists) + _metaDrawers.Atch.ImportFile(atchFile.File.FullName); + } } private void DrawEditHeader(MetaManipulationType type) From 279a861582c7168604e6e995d801ff5add94c2fb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 16 Mar 2025 22:17:37 +0100 Subject: [PATCH 1148/1381] Fix error in parser. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 1c1b3d1b..757aaa39 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1c1b3d1b2f050ae0424cb299d30b2bbb65514aa6 +Subproject commit 757aaa39ac4aa988d0b8597ff088641a0f4f49fd From 03bb07a9c08f7fd867aa5344f62ce6070e97c1d0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Mar 2025 12:04:38 +0100 Subject: [PATCH 1149/1381] Update for SDK. --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/test_release.yml | 2 +- OtterGui | 2 +- Penumbra.Api | 2 +- .../Buffers/AnimationInvocationBuffer.cs | 4 +- .../Buffers/CharacterBaseBuffer.cs | 4 +- .../Buffers/MemoryMappedBuffer.cs | 3 + .../Buffers/ModdedFileBuffer.cs | 4 +- Penumbra.CrashHandler/CrashData.cs | 2 + Penumbra.CrashHandler/GameEventLogReader.cs | 5 +- Penumbra.CrashHandler/GameEventLogWriter.cs | 3 +- .../Penumbra.CrashHandler.csproj | 20 ++---- Penumbra.CrashHandler/Program.cs | 4 +- Penumbra.CrashHandler/packages.lock.json | 13 ++++ Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra.sln | 52 +++++++-------- .../PostProcessing/ShaderReplacementFixer.cs | 12 ++-- .../LiveColorTablePreviewer.cs | 4 +- .../Interop/ResourceTree/ResolveContext.cs | 4 +- Penumbra/Interop/Structs/StructExtensions.cs | 5 +- Penumbra/Penumbra.csproj | 64 +------------------ Penumbra/Penumbra.json | 2 +- Penumbra/Services/MigrationManager.cs | 64 +++++++++++++++++++ Penumbra/UI/LaunchButton.cs | 9 +-- .../UI/Tabs/Debug/GlobalVariablesDrawer.cs | 9 +-- Penumbra/packages.lock.json | 24 ++++--- 28 files changed, 178 insertions(+), 147 deletions(-) create mode 100644 Penumbra.CrashHandler/packages.lock.json diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1783c9a4..7901a653 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,7 +16,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '8.x.x' + dotnet-version: '9.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4799cbed..c87c0244 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '8.x.x' + dotnet-version: '9.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 549c967a..2bece720 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -15,7 +15,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '8.x.x' + dotnet-version: '9.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/OtterGui b/OtterGui index 13f1a90b..3396ee17 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 13f1a90b88d2b8572480748a209f957b70d6a46f +Subproject commit 3396ee176fa72ad2dfb2de3294f7125ebce4dae5 diff --git a/Penumbra.Api b/Penumbra.Api index 404c8aaa..6d262cd3 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 404c8aaa5115925006963baa118bf710c7953380 +Subproject commit 6d262cd3181d44c29891c9473f7c423300320f15 diff --git a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs index 11dc52db..292be2ff 100644 --- a/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/AnimationInvocationBuffer.cs @@ -1,4 +1,6 @@ -using System.Text.Json.Nodes; +using System; +using System.Collections.Generic; +using System.Text.Json.Nodes; namespace Penumbra.CrashHandler.Buffers; diff --git a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs index a48fe846..89fea29d 100644 --- a/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/CharacterBaseBuffer.cs @@ -1,4 +1,6 @@ -using System.Text.Json.Nodes; +using System; +using System.Collections.Generic; +using System.Text.Json.Nodes; namespace Penumbra.CrashHandler.Buffers; diff --git a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs index a1b3de52..e2ffcebe 100644 --- a/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/MemoryMappedBuffer.cs @@ -1,5 +1,8 @@ +using System; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.IO.MemoryMappedFiles; +using System.Linq; using System.Numerics; using System.Text; diff --git a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs index ac507e7f..e4ee66d0 100644 --- a/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs +++ b/Penumbra.CrashHandler/Buffers/ModdedFileBuffer.cs @@ -1,4 +1,6 @@ -using System.Text.Json.Nodes; +using System; +using System.Collections.Generic; +using System.Text.Json.Nodes; namespace Penumbra.CrashHandler.Buffers; diff --git a/Penumbra.CrashHandler/CrashData.cs b/Penumbra.CrashHandler/CrashData.cs index dd75f46e..55460548 100644 --- a/Penumbra.CrashHandler/CrashData.cs +++ b/Penumbra.CrashHandler/CrashData.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using Penumbra.CrashHandler.Buffers; namespace Penumbra.CrashHandler; diff --git a/Penumbra.CrashHandler/GameEventLogReader.cs b/Penumbra.CrashHandler/GameEventLogReader.cs index 1813a671..8a7f53f8 100644 --- a/Penumbra.CrashHandler/GameEventLogReader.cs +++ b/Penumbra.CrashHandler/GameEventLogReader.cs @@ -1,4 +1,7 @@ -using System.Text.Json.Nodes; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json.Nodes; using Penumbra.CrashHandler.Buffers; namespace Penumbra.CrashHandler; diff --git a/Penumbra.CrashHandler/GameEventLogWriter.cs b/Penumbra.CrashHandler/GameEventLogWriter.cs index e2c461f4..915c59a2 100644 --- a/Penumbra.CrashHandler/GameEventLogWriter.cs +++ b/Penumbra.CrashHandler/GameEventLogWriter.cs @@ -1,4 +1,5 @@ -using Penumbra.CrashHandler.Buffers; +using System; +using Penumbra.CrashHandler.Buffers; namespace Penumbra.CrashHandler; diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj index c9f97fde..4cb53c8b 100644 --- a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -1,20 +1,6 @@ - - + Exe - net8.0-windows - preview - enable - x64 - enable - true - false - - - - $(appdata)\XIVLauncher\addon\Hooks\dev\ - $(HOME)/.xlcore/dalamud/Hooks/dev/ - $(DALAMUD_HOME)/ @@ -25,4 +11,8 @@ embedded + + false + + diff --git a/Penumbra.CrashHandler/Program.cs b/Penumbra.CrashHandler/Program.cs index 3bc461f7..38c176a6 100644 --- a/Penumbra.CrashHandler/Program.cs +++ b/Penumbra.CrashHandler/Program.cs @@ -1,4 +1,6 @@ -using System.Diagnostics; +using System; +using System.Diagnostics; +using System.IO; using System.Text.Json; namespace Penumbra.CrashHandler; diff --git a/Penumbra.CrashHandler/packages.lock.json b/Penumbra.CrashHandler/packages.lock.json new file mode 100644 index 00000000..1d395083 --- /dev/null +++ b/Penumbra.CrashHandler/packages.lock.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "dependencies": { + "net9.0-windows7.0": { + "DotNet.ReproducibleBuilds": { + "type": "Direct", + "requested": "[1.2.25, )", + "resolved": "1.2.25", + "contentHash": "xCXiw7BCxHJ8pF6wPepRUddlh2dlQlbr81gXA72hdk4FLHkKXas7EH/n+fk5UCA/YfMqG1Z6XaPiUjDbUNBUzg==" + } + } + } +} \ No newline at end of file diff --git a/Penumbra.GameData b/Penumbra.GameData index 757aaa39..ab3ee0ee 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 757aaa39ac4aa988d0b8597ff088641a0f4f49fd +Subproject commit ab3ee0ee814e170b59e0c13b023bbb8bc9314c74 diff --git a/Penumbra.String b/Penumbra.String index 4eb7c118..2896c056 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 4eb7c118cdac5873afb97cb04719602f061f03b7 +Subproject commit 2896c0561f60827f97408650d52a15c38f4d9d10 diff --git a/Penumbra.sln b/Penumbra.sln index e864fbee..0293df63 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -54,34 +54,34 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "structs", "structs", "{B03F EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU + Debug|x64 = Debug|x64 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {13C812E9-0D42-4B95-8646-40EEBF30636F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {13C812E9-0D42-4B95-8646-40EEBF30636F}.Release|Any CPU.Build.0 = Release|Any CPU - {EE551E87-FDB3-4612-B500-DC870C07C605}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE551E87-FDB3-4612-B500-DC870C07C605}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE551E87-FDB3-4612-B500-DC870C07C605}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE551E87-FDB3-4612-B500-DC870C07C605}.Release|Any CPU.Build.0 = Release|Any CPU - {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|Any CPU.Build.0 = Debug|Any CPU - {87750518-1A20-40B4-9FC1-22F906EFB290}.Release|Any CPU.ActiveCfg = Release|Any CPU - {87750518-1A20-40B4-9FC1-22F906EFB290}.Release|Any CPU.Build.0 = Release|Any CPU - {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Release|Any CPU.Build.0 = Release|Any CPU - {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Release|Any CPU.Build.0 = Release|Any CPU - {EE834491-A98F-4395-BE0D-6861AE5AD953}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EE834491-A98F-4395-BE0D-6861AE5AD953}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EE834491-A98F-4395-BE0D-6861AE5AD953}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EE834491-A98F-4395-BE0D-6861AE5AD953}.Release|Any CPU.Build.0 = Release|Any CPU + {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|x64.ActiveCfg = Debug|Any CPU + {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|x64.Build.0 = Debug|Any CPU + {13C812E9-0D42-4B95-8646-40EEBF30636F}.Release|x64.ActiveCfg = Release|x64 + {13C812E9-0D42-4B95-8646-40EEBF30636F}.Release|x64.Build.0 = Release|x64 + {EE551E87-FDB3-4612-B500-DC870C07C605}.Debug|x64.ActiveCfg = Debug|x64 + {EE551E87-FDB3-4612-B500-DC870C07C605}.Debug|x64.Build.0 = Debug|x64 + {EE551E87-FDB3-4612-B500-DC870C07C605}.Release|x64.ActiveCfg = Release|x64 + {EE551E87-FDB3-4612-B500-DC870C07C605}.Release|x64.Build.0 = Release|x64 + {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|x64.ActiveCfg = Debug|Any CPU + {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|x64.Build.0 = Debug|Any CPU + {87750518-1A20-40B4-9FC1-22F906EFB290}.Release|x64.ActiveCfg = Release|x64 + {87750518-1A20-40B4-9FC1-22F906EFB290}.Release|x64.Build.0 = Release|x64 + {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Debug|x64.ActiveCfg = Debug|x64 + {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Debug|x64.Build.0 = Debug|x64 + {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Release|x64.ActiveCfg = Release|x64 + {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Release|x64.Build.0 = Release|x64 + {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Debug|x64.ActiveCfg = Debug|x64 + {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Debug|x64.Build.0 = Debug|x64 + {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Release|x64.ActiveCfg = Release|x64 + {5549BAFD-6357-4B1A-800C-75AC36E5B76D}.Release|x64.Build.0 = Release|x64 + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Debug|x64.ActiveCfg = Debug|x64 + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Debug|x64.Build.0 = Debug|x64 + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Release|x64.ActiveCfg = Release|x64 + {EE834491-A98F-4395-BE0D-6861AE5AD953}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index 8e12662e..b9c21556 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -193,7 +193,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (shpk == null) return; - var shpkName = mtrl->ShpkNameSpan; + var shpkName = mtrl->ShpkName.AsSpan(); var shpkState = GetStateForHumanSetup(shpkName) ?? GetStateForHumanRender(shpkName) ?? GetStateForModelRendererRender(shpkName) @@ -217,7 +217,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic } private ModdedShaderPackageState? GetStateForHumanSetup(MaterialResourceHandle* mtrlResource) - => mtrlResource == null ? null : GetStateForHumanSetup(mtrlResource->ShpkNameSpan); + => mtrlResource == null ? null : GetStateForHumanSetup(mtrlResource->ShpkName.AsSpan()); private ModdedShaderPackageState? GetStateForHumanSetup(ReadOnlySpan shpkName) => CharacterStockingsShpkName.SequenceEqual(shpkName) ? _characterStockingsState : null; @@ -227,7 +227,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic => _characterStockingsState.MaterialCount; private ModdedShaderPackageState? GetStateForHumanRender(MaterialResourceHandle* mtrlResource) - => mtrlResource == null ? null : GetStateForHumanRender(mtrlResource->ShpkNameSpan); + => mtrlResource == null ? null : GetStateForHumanRender(mtrlResource->ShpkName.AsSpan()); private ModdedShaderPackageState? GetStateForHumanRender(ReadOnlySpan shpkName) => SkinShpkName.SequenceEqual(shpkName) ? _skinState : null; @@ -237,7 +237,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic => _skinState.MaterialCount; private ModdedShaderPackageState? GetStateForModelRendererRender(MaterialResourceHandle* mtrlResource) - => mtrlResource == null ? null : GetStateForModelRendererRender(mtrlResource->ShpkNameSpan); + => mtrlResource == null ? null : GetStateForModelRendererRender(mtrlResource->ShpkName.AsSpan()); private ModdedShaderPackageState? GetStateForModelRendererRender(ReadOnlySpan shpkName) { @@ -264,7 +264,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic + _hairMaskState.MaterialCount; private ModdedShaderPackageState? GetStateForModelRendererUnk(MaterialResourceHandle* mtrlResource) - => mtrlResource == null ? null : GetStateForModelRendererUnk(mtrlResource->ShpkNameSpan); + => mtrlResource == null ? null : GetStateForModelRendererUnk(mtrlResource->ShpkName.AsSpan()); private ModdedShaderPackageState? GetStateForModelRendererUnk(ReadOnlySpan shpkName) { @@ -480,7 +480,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic if (material == null) return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); - var shpkState = GetStateForColorTable(thisPtr->ShpkNameSpan); + var shpkState = GetStateForColorTable(thisPtr->ShpkName.AsSpan()); if (shpkState == null || shpkState.MaterialCount == 0) return _prepareColorTableHook.Original(thisPtr, stain0Id, stain1Id); diff --git a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs index c459a67a..0415fc9d 100644 --- a/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs +++ b/Penumbra/Interop/MaterialPreview/LiveColorTablePreviewer.cs @@ -84,7 +84,9 @@ public sealed unsafe class LiveColorTablePreviewer : LiveMaterialPreviewerBase textureSize[1] = Height; using var texture = - new SafeTextureHandle(Device.Instance()->CreateTexture2D(textureSize, 1, 0x2460, 0x80000804, 7), false); + new SafeTextureHandle( + Device.Instance()->CreateTexture2D(textureSize, 1, TextureFormat.R16G16B16A16_FLOAT, + TextureFlags.TextureNoSwizzle | TextureFlags.Immutable | TextureFlags.Managed, 7), false); if (texture.IsInvalid) return; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index ea4506c7..41a27ed5 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -239,7 +239,7 @@ internal unsafe partial record ResolveContext( return cached; var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); - var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new CiByteString(resource->ShpkName)); + var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new CiByteString(resource->ShpkName.Value)); if (shpkNode is not null) { if (Global.WithUiData) @@ -253,7 +253,7 @@ internal unsafe partial record ResolveContext( var alreadyProcessedSamplerIds = new HashSet(); for (var i = 0; i < resource->TextureCount; i++) { - var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new CiByteString(resource->TexturePath(i)), + var texNode = CreateNodeFromTex(resource->Textures[i].TextureResourceHandle, new CiByteString(resource->TexturePath(i).Value), resource->Textures[i].IsDX11); if (texNode == null) continue; diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 8b5974f0..03b4cf36 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -1,5 +1,6 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.STD; +using InteropGenerator.Runtime; using Penumbra.String; namespace Penumbra.Interop.Structs; @@ -57,8 +58,8 @@ internal static class StructExtensions return ToOwnedByteString(character.ResolvePhybPath(pathBuffer, partialSkeletonIndex)); } - private static unsafe CiByteString ToOwnedByteString(byte* str) - => str == null ? CiByteString.Empty : new CiByteString(str).Clone(); + private static unsafe CiByteString ToOwnedByteString(CStringPointer str) + => str.HasValue ? new CiByteString(str.Value).Clone() : CiByteString.Empty; private static CiByteString ToOwnedByteString(ReadOnlySpan str) => str.Length == 0 ? CiByteString.Empty : CiByteString.FromSpanUnsafe(str, true).Clone(); diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 870865da..a09abcaa 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,25 +1,15 @@ - + - net8.0-windows - preview - x64 Penumbra absolute gangstas Penumbra - Copyright © 2022 + Copyright © 2025 9.0.0.1 9.0.0.1 bin\$(Configuration)\ - true - enable - true - false - false - true - $(MSBuildWarningsAsMessages);MSB3277 PROFILING; @@ -35,63 +25,13 @@ - - $(AppData)\XIVLauncher\addon\Hooks\dev\ - - - - $(DalamudLibPath)Dalamud.dll - False - - - $(DalamudLibPath)ImGui.NET.dll - False - - - $(DalamudLibPath)ImGuiScene.dll - False - - - $(DalamudLibPath)Lumina.dll - False - - - $(DalamudLibPath)Lumina.Excel.dll - False - - - $(DalamudLibPath)FFXIVClientStructs.dll - False - - - $(DalamudLibPath)Newtonsoft.Json.dll - False - - - $(DalamudLibPath)Iced.dll - False - - - $(DalamudLibPath)SharpDX.dll - False - - - $(DalamudLibPath)SharpDX.Direct3D11.dll - False - - - $(DalamudLibPath)SharpDX.DXGI.dll - False - lib\OtterTex.dll - - diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 968bb750..924d7bd3 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -8,7 +8,7 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], - "DalamudApiLevel": 11, + "DalamudApiLevel": 12, "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index aa2d445e..abc059e9 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -1,12 +1,76 @@ using Dalamud.Interface.ImGuiNotification; using OtterGui.Classes; using OtterGui.Services; +using Penumbra.Api.Enums; using Penumbra.GameData.Files; +using Penumbra.Mods; +using Penumbra.String.Classes; using SharpCompress.Common; using SharpCompress.Readers; namespace Penumbra.Services; +public class ModMigrator +{ + private class FileData(string path) + { + public readonly string Path = path; + public readonly List<(string GamePath, int Option)> GamePaths = []; + } + + private sealed class FileDataDict : Dictionary + { + public void Add(string path, string gamePath, int option) + { + if (!TryGetValue(path, out var data)) + { + data = new FileData(path); + data.GamePaths.Add((gamePath, option)); + Add(path, data); + } + else + { + data.GamePaths.Add((gamePath, option)); + } + } + } + + private readonly FileDataDict Textures = []; + private readonly FileDataDict Models = []; + private readonly FileDataDict Materials = []; + + public void Update(IEnumerable mods) + { + CollectFiles(mods); + } + + private void CollectFiles(IEnumerable mods) + { + var option = 0; + foreach (var mod in mods) + { + AddDict(mod.Default.Files, option++); + foreach (var container in mod.Groups.SelectMany(group => group.DataContainers)) + AddDict(container.Files, option++); + } + + return; + + void AddDict(Dictionary dict, int currentOption) + { + foreach (var (gamePath, file) in dict) + { + switch (ResourceTypeExtensions.FromExtension(gamePath.Extension().Span)) + { + case ResourceType.Tex: Textures.Add(file.FullName, gamePath.ToString(), currentOption); break; + case ResourceType.Mdl: Models.Add(file.FullName, gamePath.ToString(), currentOption); break; + case ResourceType.Mtrl: Materials.Add(file.FullName, gamePath.ToString(), currentOption); break; + } + } + } + } +} + public class MigrationManager(Configuration config) : IService { public enum TaskType : byte diff --git a/Penumbra/UI/LaunchButton.cs b/Penumbra/UI/LaunchButton.cs index cb533a00..49161c31 100644 --- a/Penumbra/UI/LaunchButton.cs +++ b/Penumbra/UI/LaunchButton.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using Dalamud.Interface.Textures; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin; using Dalamud.Plugin.Services; @@ -18,7 +19,6 @@ public class LaunchButton : IDisposable, IUiService private readonly string _fileName; private readonly ITextureProvider _textureProvider; - private IDalamudTextureWrap? _icon; private IReadOnlyTitleScreenMenuEntry? _entry; /// @@ -30,7 +30,6 @@ public class LaunchButton : IDisposable, IUiService _configWindow = ui; _textureProvider = textureProvider; _title = title; - _icon = null; _entry = null; _fileName = Path.Combine(pi.AssemblyLocation.DirectoryName!, "tsmLogo.png"); @@ -39,7 +38,6 @@ public class LaunchButton : IDisposable, IUiService public void Dispose() { - _icon?.Dispose(); if (_entry != null) _title.RemoveEntry(_entry); } @@ -52,9 +50,8 @@ public class LaunchButton : IDisposable, IUiService try { // TODO: update when API updated. - _icon = _textureProvider.GetFromFile(_fileName).RentAsync().Result; - if (_icon != null) - _entry = _title.AddEntry("Manage Penumbra", _icon, OnTriggered); + var icon = _textureProvider.GetFromFile(_fileName); + _entry = _title.AddEntry("Manage Penumbra", icon, OnTriggered); _uiBuilder.Draw -= CreateEntry; } diff --git a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs index 4e6cf62c..bfe89768 100644 --- a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs @@ -164,13 +164,14 @@ public unsafe class GlobalVariablesDrawer( _schedulerFilterMapU8 = CiByteString.FromString(_schedulerFilterMap, out var t, MetaDataComputation.All, false) ? t : CiByteString.Empty; - ImUtf8.Text($"{_shownResourcesMap} / {scheduler.Scheduler->NumResources}"); + ImUtf8.Text($"{_shownResourcesMap} / {scheduler.Scheduler->Resources.LongCount}"); using var table = ImUtf8.Table("##SchedulerMapResources"u8, 10, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) return; - var map = (StdMap>*)&scheduler.Scheduler->Unknown; + // TODO Remove cast when it'll have the right type in CS. + var map = (StdMap>*)&scheduler.Scheduler->Resources; var total = 0; _shownResourcesMap = 0; foreach (var (key, resourcePtr) in *map) @@ -214,7 +215,7 @@ public unsafe class GlobalVariablesDrawer( _schedulerFilterListU8 = CiByteString.FromString(_schedulerFilterList, out var t, MetaDataComputation.All, false) ? t : CiByteString.Empty; - ImUtf8.Text($"{_shownResourcesList} / {scheduler.Scheduler->NumResources}"); + ImUtf8.Text($"{_shownResourcesList} / {scheduler.Scheduler->Resources.LongCount}"); using var table = ImUtf8.Table("##SchedulerListResources"u8, 10, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) @@ -223,7 +224,7 @@ public unsafe class GlobalVariablesDrawer( var resource = scheduler.Scheduler->Begin; var total = 0; _shownResourcesList = 0; - while (resource != null && total < (int)scheduler.Scheduler->NumResources) + while (resource != null && total < scheduler.Scheduler->Resources.Count) { if (_schedulerFilterList.Length is 0 || resource->Name.Buffer.IndexOf(_schedulerFilterListU8.Span) >= 0) { diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 9aa1ebd5..dda6b305 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -1,7 +1,19 @@ { "version": 1, "dependencies": { - "net8.0-windows7.0": { + "net9.0-windows7.0": { + "DalamudPackager": { + "type": "Direct", + "requested": "[12.0.0, )", + "resolved": "12.0.0", + "contentHash": "J5TJLV3f16T/E2H2P17ClWjtfEBPpq3yxvqW46eN36JCm6wR+EaoaYkqG9Rm5sHqs3/nK/vKjWWyvEs/jhKoXw==" + }, + "DotNet.ReproducibleBuilds": { + "type": "Direct", + "requested": "[1.2.25, )", + "resolved": "1.2.25", + "contentHash": "xCXiw7BCxHJ8pF6wPepRUddlh2dlQlbr81gXA72hdk4FLHkKXas7EH/n+fk5UCA/YfMqG1Z6XaPiUjDbUNBUzg==" + }, "EmbedIO": { "type": "Direct", "requested": "[3.5.2, )", @@ -52,12 +64,6 @@ "resolved": "3.1.7", "contentHash": "9fIOOAsyLFid6qKypM2Iy0Z3Q9yoanV8VoYAHtI2sYGMNKzhvRTjgFDHonIiVe+ANtxIxM6SuqUzj0r91nItpA==" }, - "System.Formats.Asn1": { - "type": "Direct", - "requested": "[9.0.2, )", - "resolved": "9.0.2", - "contentHash": "OKWHCPYQr/+cIoO8EVjFn7yFyiT8Mnf1wif/5bYGsqxQV6PrwlX2HQ9brZNx57ViOvRe4ing1xgHCKl/5Ko8xg==" - }, "JetBrains.Annotations": { "type": "Transitive", "resolved": "2024.3.0", @@ -134,8 +140,8 @@ "type": "Project", "dependencies": { "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[5.6.0, )", - "Penumbra.String": "[1.0.5, )" + "Penumbra.Api": "[5.6.1, )", + "Penumbra.String": "[1.0.6, )" } }, "penumbra.string": { From 586bd9d0cc6e3ff308a69fa3ce6e65ff3fc41f2f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Mar 2025 12:07:45 +0100 Subject: [PATCH 1150/1381] Re-add wrong dependencies. --- Penumbra.sln | 8 ++++---- Penumbra/Penumbra.csproj | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/Penumbra.sln b/Penumbra.sln index 0293df63..ac1c9566 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -58,16 +58,16 @@ Global Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|x64.ActiveCfg = Debug|Any CPU - {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|x64.Build.0 = Debug|Any CPU + {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|x64.ActiveCfg = Debug|x64 + {13C812E9-0D42-4B95-8646-40EEBF30636F}.Debug|x64.Build.0 = Debug|x64 {13C812E9-0D42-4B95-8646-40EEBF30636F}.Release|x64.ActiveCfg = Release|x64 {13C812E9-0D42-4B95-8646-40EEBF30636F}.Release|x64.Build.0 = Release|x64 {EE551E87-FDB3-4612-B500-DC870C07C605}.Debug|x64.ActiveCfg = Debug|x64 {EE551E87-FDB3-4612-B500-DC870C07C605}.Debug|x64.Build.0 = Debug|x64 {EE551E87-FDB3-4612-B500-DC870C07C605}.Release|x64.ActiveCfg = Release|x64 {EE551E87-FDB3-4612-B500-DC870C07C605}.Release|x64.Build.0 = Release|x64 - {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|x64.ActiveCfg = Debug|Any CPU - {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|x64.Build.0 = Debug|Any CPU + {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|x64.ActiveCfg = Debug|x64 + {87750518-1A20-40B4-9FC1-22F906EFB290}.Debug|x64.Build.0 = Debug|x64 {87750518-1A20-40B4-9FC1-22F906EFB290}.Release|x64.ActiveCfg = Release|x64 {87750518-1A20-40B4-9FC1-22F906EFB290}.Release|x64.Build.0 = Release|x64 {1FE4D8DF-B56A-464F-B39E-CDC0ED4167D4}.Debug|x64.ActiveCfg = Debug|x64 diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index a09abcaa..cc892fa8 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -26,6 +26,22 @@ + + $(DalamudLibPath)Iced.dll + False + + + $(DalamudLibPath)SharpDX.dll + False + + + $(DalamudLibPath)SharpDX.Direct3D11.dll + False + + + $(DalamudLibPath)SharpDX.DXGI.dll + False + lib\OtterTex.dll From b8b2127a5d63b3368ca047d206073a288b42166f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Mar 2025 15:53:59 +0100 Subject: [PATCH 1151/1381] Update STM and signatures. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Services/StainService.cs | 4 ++-- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs | 2 +- .../UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 6d262cd3..2cbf4bac 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 6d262cd3181d44c29891c9473f7c423300320f15 +Subproject commit 2cbf4bace53a5749d3eab1ff03025a6e6bd9fc37 diff --git a/Penumbra.GameData b/Penumbra.GameData index ab3ee0ee..9442f1d6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ab3ee0ee814e170b59e0c13b023bbb8bc9314c74 +Subproject commit 9442f1d60578dae7598cbb0a1ff545d24905bdfd diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index 0a437da0..b16d4dcd 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -16,7 +16,7 @@ namespace Penumbra.Services; public class StainService : IService { public sealed class StainTemplateCombo(FilterComboColors[] stainCombos, StmFile stmFile) - : FilterComboCache(stmFile.Entries.Keys.Prepend((ushort)0), MouseWheelType.None, Penumbra.Log) + : FilterComboCache(stmFile.Entries.Keys.Prepend(0), MouseWheelType.None, Penumbra.Log) where TDyePack : unmanaged, IDyePack { // FIXME There might be a better way to handle that. @@ -31,7 +31,7 @@ public class StainService : IService return baseSize + ImGui.GetTextLineHeight() * 3 + ImGui.GetStyle().ItemInnerSpacing.X * 3; } - protected override string ToString(ushort obj) + protected override string ToString(StmKeyType obj) => $"{obj,4}"; protected override void DrawFilter(int currentSelected, float width) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index f32a3dc9..0c987972 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -607,7 +607,7 @@ public partial class MtrlTab if (_stainService.GudTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, scalarSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { - dye.Template = _stainService.GudTemplateCombo.CurrentSelection; + dye.Template = _stainService.GudTemplateCombo.CurrentSelection.UShort; ret = true; } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs index f21d86a9..0ffdd1cc 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -184,7 +184,7 @@ public partial class MtrlTab if (_stainService.LegacyTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { - dyeTable[rowIdx].Template = _stainService.LegacyTemplateCombo.CurrentSelection; + dyeTable[rowIdx].Template = _stainService.LegacyTemplateCombo.CurrentSelection.UShort; ret = true; } @@ -299,7 +299,7 @@ public partial class MtrlTab if (_stainService.LegacyTemplateCombo.Draw("##dyeTemplate", dye.Template.ToString(), string.Empty, intSize + ImGui.GetStyle().ScrollbarSize / 2, ImGui.GetTextLineHeightWithSpacing(), ImGuiComboFlags.NoArrowButton)) { - dyeTable[rowIdx].Template = _stainService.LegacyTemplateCombo.CurrentSelection; + dyeTable[rowIdx].Template = _stainService.LegacyTemplateCombo.CurrentSelection.UShort; ret = true; } From 124b54ab046888f49df8d28120d1d3990dc30c69 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Mar 2025 16:00:30 +0100 Subject: [PATCH 1152/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 9442f1d6..64823f2e 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 9442f1d60578dae7598cbb0a1ff545d24905bdfd +Subproject commit 64823f2e29fdc65033d1891debe1ea18dadce1c8 From 525d1c6bf96ee2965e541d17a160a961f0ed85cd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 27 Mar 2025 18:18:04 +0100 Subject: [PATCH 1153/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 64823f2e..9ae4a971 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 64823f2e29fdc65033d1891debe1ea18dadce1c8 +Subproject commit 9ae4a97110fff005a54213815086ce950d4d8b2d From 49f077aca0eb850f3814af29d157911489e4967d Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 27 Mar 2025 22:32:07 +0100 Subject: [PATCH 1154/1381] Fixes for 7.2 (ResourceTree + ShPk 13.1) --- Penumbra.GameData | 2 +- .../ResourceTree/ResourceTreeFactory.cs | 54 +++++++++++-------- .../Interop/ResourceTree/TreeBuildCache.cs | 22 ++++---- 3 files changed, 45 insertions(+), 33 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 9ae4a971..1158cf40 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 9ae4a97110fff005a54213815086ce950d4d8b2d +Subproject commit 1158cf404a16979d0b7e12f7bbcbbc651da16add diff --git a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs index cb8be184..49194c3a 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTreeFactory.cs @@ -23,24 +23,35 @@ public class ResourceTreeFactory( Configuration config, ActorManager actors, PathState pathState, + IFramework framework, ModManager modManager) : IService { private static readonly string ParentDirectoryPrefix = $"..{Path.DirectorySeparatorChar}"; private TreeBuildCache CreateTreeBuildCache() - => new(objects, gameData, actors); + => new(framework.IsInFrameworkUpdateThread ? objects : null, gameData, actors); + + private TreeBuildCache CreateTreeBuildCache(Flags flags) + => !framework.IsInFrameworkUpdateThread && flags.HasFlag(Flags.PopulateObjectTableData) + ? framework.RunOnFrameworkThread(CreateTreeBuildCache).Result + : CreateTreeBuildCache(); public IEnumerable GetLocalPlayerRelatedCharacters() - { - var cache = CreateTreeBuildCache(); - return cache.GetLocalPlayerRelatedCharacters(); - } + => framework.RunOnFrameworkThread(() => + { + var cache = CreateTreeBuildCache(); + return cache.GetLocalPlayerRelatedCharacters(); + }).Result; public IEnumerable<(ICharacter Character, ResourceTree ResourceTree)> FromObjectTable( Flags flags) { - var cache = CreateTreeBuildCache(); - var characters = (flags & Flags.LocalPlayerRelatedOnly) != 0 ? cache.GetLocalPlayerRelatedCharacters() : cache.GetCharacters(); + var (cache, characters) = framework.RunOnFrameworkThread(() => + { + var cache = CreateTreeBuildCache(); + var characters = ((flags & Flags.LocalPlayerRelatedOnly) != 0 ? cache.GetLocalPlayerRelatedCharacters() : cache.GetCharacters()).ToArray(); + return (cache, characters); + }).Result; foreach (var character in characters) { @@ -53,7 +64,7 @@ public class ResourceTreeFactory( public IEnumerable<(ICharacter Character, ResourceTree ResourceTree)> FromCharacters( IEnumerable characters, Flags flags) { - var cache = CreateTreeBuildCache(); + var cache = CreateTreeBuildCache(flags); foreach (var character in characters) { var tree = FromCharacter(character, cache, flags); @@ -63,7 +74,7 @@ public class ResourceTreeFactory( } public ResourceTree? FromCharacter(ICharacter character, Flags flags) - => FromCharacter(character, CreateTreeBuildCache(), flags); + => FromCharacter(character, CreateTreeBuildCache(flags), flags); private unsafe ResourceTree? FromCharacter(ICharacter character, TreeBuildCache cache, Flags flags) { @@ -80,7 +91,7 @@ public class ResourceTreeFactory( return null; var localPlayerRelated = cache.IsLocalPlayerRelated(character); - var (name, anonymizedName, related) = GetCharacterName(character); + var (name, anonymizedName, related) = GetCharacterName((GameObject*)character.Address); var networked = character.EntityId != 0xE0000000; var tree = new ResourceTree(name, anonymizedName, character.ObjectIndex, (nint)gameObjStruct, (nint)drawObjStruct, localPlayerRelated, related, networked, collectionResolveData.ModCollection.Identity.Name, collectionResolveData.ModCollection.Identity.AnonymizedName); @@ -183,36 +194,37 @@ public class ResourceTreeFactory( } } - private unsafe (string Name, string AnonymizedName, bool PlayerRelated) GetCharacterName(ICharacter character) + private unsafe (string Name, string AnonymizedName, bool PlayerRelated) GetCharacterName(GameObject* character) { - var identifier = actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); + var identifier = actors.FromObject(character, out var owner, true, false, false); var identifierStr = identifier.ToString(); return (identifierStr, identifier.Incognito(identifierStr), IsPlayerRelated(identifier, owner)); } - private unsafe bool IsPlayerRelated(ICharacter? character) + private unsafe bool IsPlayerRelated(GameObject* character) { - if (character == null) + if (character is null) return false; - var identifier = actors.FromObject((GameObject*)character.Address, out var owner, true, false, false); + var identifier = actors.FromObject(character, out var owner, true, false, false); return IsPlayerRelated(identifier, owner); } - private bool IsPlayerRelated(ActorIdentifier identifier, Actor owner) + private unsafe bool IsPlayerRelated(ActorIdentifier identifier, Actor owner) => identifier.Type switch { IdentifierType.Player => true, - IdentifierType.Owned => IsPlayerRelated(objects.Objects.CreateObjectReference(owner) as ICharacter), + IdentifierType.Owned => IsPlayerRelated(owner.AsObject), _ => false, }; [Flags] public enum Flags { - RedactExternalPaths = 1, - WithUiData = 2, - LocalPlayerRelatedOnly = 4, - WithOwnership = 8, + RedactExternalPaths = 1, + WithUiData = 2, + LocalPlayerRelatedOnly = 4, + WithOwnership = 8, + PopulateObjectTableData = 16, } } diff --git a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs index 49e00547..c0114412 100644 --- a/Penumbra/Interop/ResourceTree/TreeBuildCache.cs +++ b/Penumbra/Interop/ResourceTree/TreeBuildCache.cs @@ -12,14 +12,15 @@ using Penumbra.String.Classes; namespace Penumbra.Interop.ResourceTree; -internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager dataManager, ActorManager actors) +internal readonly struct TreeBuildCache(ObjectManager? objects, IDataManager dataManager, ActorManager actors) { private readonly Dictionary?> _shaderPackageNames = []; + private readonly IGameObject? _player = objects?.GetDalamudObject(0); + public unsafe bool IsLocalPlayerRelated(ICharacter character) { - var player = objects.GetDalamudObject(0); - if (player == null) + if (_player is null) return false; var gameObject = (FFXIVClientStructs.FFXIV.Client.Game.Object.GameObject*)character.Address; @@ -28,27 +29,26 @@ internal readonly struct TreeBuildCache(ObjectManager objects, IDataManager data return actualIndex switch { < 2 => true, - < (int)ScreenActor.CutsceneStart => gameObject->OwnerId == player.EntityId, + < (int)ScreenActor.CutsceneStart => gameObject->OwnerId == _player.EntityId, _ => false, }; } public IEnumerable GetCharacters() - => objects.Objects.OfType(); + => objects is not null ? objects.Objects.OfType() : []; public IEnumerable GetLocalPlayerRelatedCharacters() { - var player = objects.GetDalamudObject(0); - if (player == null) + if (_player is null) yield break; - yield return (ICharacter)player; + yield return (ICharacter)_player; - var minion = objects.GetDalamudObject(1); - if (minion != null) + var minion = objects!.GetDalamudObject(1); + if (minion is not null) yield return (ICharacter)minion; - var playerId = player.EntityId; + var playerId = _player.EntityId; for (var i = 2; i < ObjectIndex.CutsceneStart.Index; i += 2) { if (objects.GetDalamudObject(i) is ICharacter owned && owned.OwnerId == playerId) From b189ac027baa29fdeee79401985bd9968027d83b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 02:29:49 +0100 Subject: [PATCH 1155/1381] Fix imgui assert. --- Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs b/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs index 34aafbea..97761091 100644 --- a/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs @@ -6,7 +6,8 @@ public static class DebugConfigurationDrawer { public static void Draw() { - if (!ImUtf8.CollapsingHeaderId("Debug Logging Options")) + using var id = ImUtf8.CollapsingHeaderId("Debug Logging Options"u8); + if (!id) return; ImUtf8.Checkbox("Log IMC File Replacements"u8, ref DebugConfiguration.WriteImcBytesToLog); From 8e191ae07525e6f05398a0bbbfa6ac5435232ae7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 13:33:43 +0100 Subject: [PATCH 1156/1381] Fix offsets. --- Penumbra/Interop/VolatileOffsets.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/VolatileOffsets.cs b/Penumbra/Interop/VolatileOffsets.cs index 2c6e3180..85008aae 100644 --- a/Penumbra/Interop/VolatileOffsets.cs +++ b/Penumbra/Interop/VolatileOffsets.cs @@ -6,7 +6,7 @@ public static class VolatileOffsets { public const int PlayTimeOffset = 0x254; public const int SomeIntermediate = 0x1F8; - public const int Flags = 0x4A4; + public const int Flags = 0x4A8; public const int IInstanceListenner = 0x270; public const int BitShift = 13; public const int CasterVFunc = 1; @@ -19,7 +19,7 @@ public static class VolatileOffsets public static class UpdateModel { - public const int ShortCircuit = 0xA2C; + public const int ShortCircuit = 0xA3C; } public static class FontReloader From 974b21561002c46461b1b81eb26aa32333b47060 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 13:58:11 +0100 Subject: [PATCH 1157/1381] 1.3.6.0 --- Penumbra.sln | 1 + Penumbra/UI/Changelog.cs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/Penumbra.sln b/Penumbra.sln index ac1c9566..e52045b0 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -9,6 +9,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig .github\workflows\build.yml = .github\workflows\build.yml + Penumbra\Penumbra.json = Penumbra\Penumbra.json .github\workflows\release.yml = .github\workflows\release.yml repo.json = repo.json .github\workflows\test_release.yml = .github\workflows\test_release.yml diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 87dd101d..1b0225ed 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -59,10 +59,36 @@ public class PenumbraChangelog : IUiService Add1_3_3_0(Changelog); Add1_3_4_0(Changelog); Add1_3_5_0(Changelog); + Add1_3_6_0(Changelog); } #region Changelogs + private static void Add1_3_6_0(Changelog log) + => log.NextVersion("Version 1.3.6.0") + .RegisterImportant("Updated Penumbra for update 7.20 and Dalamud API 12.") + .RegisterEntry( + "This is not thoroughly tested, but I decided to push to stable instead of testing because otherwise a lot of people would just go to testing just for early access again despite having no business doing so.", + 1) + .RegisterEntry( + "I also do not use most of the functionality of Penumbra myself, so I am unable to even encounter most issues myself.", 1) + .RegisterEntry("If you encounter any issues, please report them quickly on the discord.", 1) + .RegisterImportant("There is a known issue with the Material Editor due to the shader changes, please do not author materials for the moment, they will be broken!", 1) + .RegisterHighlight( + "The texture editor now has encoding support for Block Compression 1, 4 and 5 and tooltips explaining when to use which format.") + .RegisterEntry("It also is able to use GPU compression and thus has become much faster for BC7 in particular. (Thanks Ny!)", 1) + .RegisterEntry( + "Added the option to import .atch files found in the particular mod via right-click context menu on the import drag & drop button.") + .RegisterEntry("Added a chat command to clear temporary settings done manually in Penumbra.") + .RegisterEntry( + "The changed item star to select the preferred changed item is a bit more noticeable by default, and its color can be configured.") + .RegisterEntry("Some minor fixes for computing changed items. (Thanks Anna!)") + .RegisterEntry("The EQP entry previously named Unknown 4 was renamed to 'Hide Glove Cuffs'.") + .RegisterEntry("Fixed the changed item identification for EST changes.") + .RegisterEntry("Fixed clipping issues in the changed items panel when no grouping was active."); + + + private static void Add1_3_5_0(Changelog log) => log.NextVersion("Version 1.3.5.0") .RegisterImportant( From 60becf0a090fa2a999cda123adaadac369ee13ec Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 14:06:21 +0100 Subject: [PATCH 1158/1381] Use staging build for release for now. --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c87c0244..377919b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | From b019da2a8c370595a9f9190c961cd18592a0cabb Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 28 Mar 2025 13:09:26 +0000 Subject: [PATCH 1159/1381] [CI] Updating repo.json for 1.3.6.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 1617a879..69db2f84 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.5.0", - "TestingAssemblyVersion": "1.3.5.1", + "AssemblyVersion": "1.3.6.0", + "TestingAssemblyVersion": "1.3.6.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 11, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.5.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.5.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 1a1d1c184026f363ddae1632d5c089b34c82cc0a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 14:10:52 +0100 Subject: [PATCH 1160/1381] Revert Dalamud staging on release, and update api level. --- .github/workflows/release.yml | 2 +- repo.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 377919b2..c87c0244 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | diff --git a/repo.json b/repo.json index 69db2f84..e4fd5abc 100644 --- a/repo.json +++ b/repo.json @@ -9,8 +9,8 @@ "TestingAssemblyVersion": "1.3.6.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 11, - "TestingDalamudApiLevel": 11, + "DalamudApiLevel": 12, + "TestingDalamudApiLevel": 12, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 23ba77c107516a9f373d8f88cb71f421184f75f2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 15:52:40 +0100 Subject: [PATCH 1161/1381] Update build step and check for pre 7.2 shps. --- Penumbra.GameData | 2 +- .../Interop/Processing/ShpkPathPreProcessor.cs | 8 ++++---- Penumbra/Penumbra.csproj | 17 +++++++---------- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 1158cf40..85921598 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 1158cf404a16979d0b7e12f7bbcbbc651da16add +Subproject commit 859215989da41a4ccb59a5ce390223570a69c94e diff --git a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs index 2fb35ae0..826771dd 100644 --- a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs @@ -56,8 +56,8 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, using var file = MmioMemoryManager.CreateFromFile(path, access: MemoryMappedFileAccess.Read); var bytes = file.GetSpan(); - return ShpkFile.FastIsLegacy(bytes) - ? SanityCheckResult.Legacy + return ShpkFile.FastIsObsolete(bytes) + ? SanityCheckResult.Obsolete : SanityCheckResult.Success; } catch (FileNotFoundException) @@ -75,7 +75,7 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, { SanityCheckResult.IoError => "Cannot read the modded file.", SanityCheckResult.NotFound => "The modded file does not exist.", - SanityCheckResult.Legacy => "This mod is not compatible with Dawntrail. Get an updated version, if possible, or disable it.", + SanityCheckResult.Obsolete => "This mod is not compatible with Dawntrail post patch 7.2. Get an updated version, if possible, or disable it.", _ => string.Empty, }; @@ -84,6 +84,6 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, Success, IoError, NotFound, - Legacy, + Obsolete, } } diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index cc892fa8..f93b1815 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -23,6 +23,13 @@ PreserveNewest + + PreserveNewest + DirectXTexC.dll + + + PreserveNewest + @@ -64,16 +71,6 @@ - - - PreserveNewest - DirectXTexC.dll - - - PreserveNewest - - - From 7498bc469f413dbe4d4230cb7ae64b98df4037b3 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 28 Mar 2025 14:55:12 +0000 Subject: [PATCH 1162/1381] [CI] Updating repo.json for 1.3.6.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index e4fd5abc..94200e61 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.0", - "TestingAssemblyVersion": "1.3.6.0", + "AssemblyVersion": "1.3.6.1", + "TestingAssemblyVersion": "1.3.6.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 01e6f5846335d3741395c741c3f244e71ef36446 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 16:53:43 +0100 Subject: [PATCH 1163/1381] Add Launching IPC Event. API 5.8 --- Penumbra.Api | 2 +- Penumbra/Api/Api/PenumbraApi.cs | 5 ++++- Penumbra/Api/IpcLaunchingProvider.cs | 28 ++++++++++++++++++++++++++++ Penumbra/Penumbra.cs | 2 ++ 4 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 Penumbra/Api/IpcLaunchingProvider.cs diff --git a/Penumbra.Api b/Penumbra.Api index 2cbf4bac..bd56d828 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 2cbf4bace53a5749d3eab1ff03025a6e6bd9fc37 +Subproject commit bd56d82816b8366e19dddfb2dc7fd7f167e264ee diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 36f799a0..47d44cfc 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -16,13 +16,16 @@ public class PenumbraApi( TemporaryApi temporary, UiApi ui) : IDisposable, IApiService, IPenumbraApi { + public const int BreakingVersion = 5; + public const int FeatureVersion = 8; + public void Dispose() { Valid = false; } public (int Breaking, int Feature) ApiVersion - => (5, 7); + => (BreakingVersion, FeatureVersion); public bool Valid { get; private set; } = true; public IPenumbraApiCollection Collection { get; } = collection; diff --git a/Penumbra/Api/IpcLaunchingProvider.cs b/Penumbra/Api/IpcLaunchingProvider.cs new file mode 100644 index 00000000..ff851003 --- /dev/null +++ b/Penumbra/Api/IpcLaunchingProvider.cs @@ -0,0 +1,28 @@ +using Dalamud.Plugin; +using OtterGui.Log; +using OtterGui.Services; +using Penumbra.Api.Api; +using Serilog.Events; + +namespace Penumbra.Api; + +public sealed class IpcLaunchingProvider : IApiService +{ + public IpcLaunchingProvider(IDalamudPluginInterface pi, Logger log) + { + try + { + using var subscriber = log.MainLogger.IsEnabled(LogEventLevel.Debug) + ? IpcSubscribers.Launching.Subscriber(pi, + (major, minor) => log.Debug($"[IPC] Invoked Penumbra.Launching IPC with API Version {major}.{minor}.")) + : null; + + using var provider = IpcSubscribers.Launching.Provider(pi); + provider.Invoke(PenumbraApi.BreakingVersion, PenumbraApi.FeatureVersion); + } + catch (Exception ex) + { + log.Error($"[IPC] Could not invoke Penumbra.Launching IPC:\n{ex}"); + } + } +} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b6009627..79c7f2db 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -58,6 +58,8 @@ public class Penumbra : IDalamudPlugin { HookOverrides.Instance = HookOverrides.LoadFile(pluginInterface); _services = StaticServiceManager.CreateProvider(this, pluginInterface, Log); + // Invoke the IPC Penumbra.Launching method before any hooks or other services are created. + _services.GetService(); Messager = _services.GetService(); _validityChecker = _services.GetService(); _services.EnsureRequiredServices(); From 8a68a1bff52bb80a79f2041a54efb5b03905d1cd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 17:25:03 +0100 Subject: [PATCH 1164/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 85921598..e717a66f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 859215989da41a4ccb59a5ce390223570a69c94e +Subproject commit e717a66f33b0656a7c5c971ffa2f63fd96477d94 From 3bb7db10fba29088a83a0c0adf71b248de38552c Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 28 Mar 2025 16:29:20 +0000 Subject: [PATCH 1165/1381] [CI] Updating repo.json for 1.3.6.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 94200e61..4fac86da 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.1", - "TestingAssemblyVersion": "1.3.6.1", + "AssemblyVersion": "1.3.6.2", + "TestingAssemblyVersion": "1.3.6.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a1bf26e7e8a00deafea2b09e41df8437a69641ae Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 28 Mar 2025 18:30:18 +0100 Subject: [PATCH 1166/1381] Run HTTP redraws on framework thread. --- Penumbra/Api/HttpApi.cs | 51 +++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index 859c46b4..b6e1d799 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using EmbedIO; using EmbedIO.Routing; using EmbedIO.WebApi; @@ -14,7 +15,7 @@ public class HttpApi : IDisposable, IApiService // @formatter:off [Route( HttpVerbs.Get, "/mods" )] public partial object? GetMods(); [Route( HttpVerbs.Post, "/redraw" )] public partial Task Redraw(); - [Route( HttpVerbs.Post, "/redrawAll" )] public partial void RedrawAll(); + [Route( HttpVerbs.Post, "/redrawAll" )] public partial Task RedrawAll(); [Route( HttpVerbs.Post, "/reloadmod" )] public partial Task ReloadMod(); [Route( HttpVerbs.Post, "/installmod" )] public partial Task InstallMod(); [Route( HttpVerbs.Post, "/openwindow" )] public partial void OpenWindow(); @@ -24,11 +25,13 @@ public class HttpApi : IDisposable, IApiService public const string Prefix = "http://localhost:42069/"; private readonly IPenumbraApi _api; + private readonly IFramework _framework; private WebServer? _server; - public HttpApi(Configuration config, IPenumbraApi api) + public HttpApi(Configuration config, IPenumbraApi api, IFramework framework) { - _api = api; + _api = api; + _framework = framework; if (config.EnableHttpApi) CreateWebServer(); } @@ -44,7 +47,7 @@ public class HttpApi : IDisposable, IApiService .WithUrlPrefix(Prefix) .WithMode(HttpListenerMode.EmbedIO)) .WithCors(Prefix) - .WithWebApi("/api", m => m.WithController(() => new Controller(_api))); + .WithWebApi("/api", m => m.WithController(() => new Controller(_api, _framework))); _server.StateChanged += (_, e) => Penumbra.Log.Information($"WebServer New State - {e.NewState}"); _server.RunAsync(); @@ -59,60 +62,58 @@ public class HttpApi : IDisposable, IApiService public void Dispose() => ShutdownWebServer(); - private partial class Controller + private partial class Controller(IPenumbraApi api, IFramework framework) { - private readonly IPenumbraApi _api; - - public Controller(IPenumbraApi api) - => _api = api; - public partial object? GetMods() { Penumbra.Log.Debug($"[HTTP] {nameof(GetMods)} triggered."); - return _api.Mods.GetModList(); + return api.Mods.GetModList(); } public async partial Task Redraw() { - var data = await HttpContext.GetRequestDataAsync(); - Penumbra.Log.Debug($"[HTTP] {nameof(Redraw)} triggered with {data}."); - if (data.ObjectTableIndex >= 0) - _api.Redraw.RedrawObject(data.ObjectTableIndex, data.Type); - else - _api.Redraw.RedrawAll(data.Type); + var data = await HttpContext.GetRequestDataAsync().ConfigureAwait(false); + Penumbra.Log.Debug($"[HTTP] [{Environment.CurrentManagedThreadId}] {nameof(Redraw)} triggered with {data}."); + await framework.RunOnFrameworkThread(() => + { + if (data.ObjectTableIndex >= 0) + api.Redraw.RedrawObject(data.ObjectTableIndex, data.Type); + else + api.Redraw.RedrawAll(data.Type); + }).ConfigureAwait(false); } - public partial void RedrawAll() + public async partial Task RedrawAll() { Penumbra.Log.Debug($"[HTTP] {nameof(RedrawAll)} triggered."); - _api.Redraw.RedrawAll(RedrawType.Redraw); + await framework.RunOnFrameworkThread(() => { api.Redraw.RedrawAll(RedrawType.Redraw); }).ConfigureAwait(false); } public async partial Task ReloadMod() { - var data = await HttpContext.GetRequestDataAsync(); + var data = await HttpContext.GetRequestDataAsync().ConfigureAwait(false); Penumbra.Log.Debug($"[HTTP] {nameof(ReloadMod)} triggered with {data}."); // Add the mod if it is not already loaded and if the directory name is given. // AddMod returns Success if the mod is already loaded. if (data.Path.Length != 0) - _api.Mods.AddMod(data.Path); + api.Mods.AddMod(data.Path); // Reload the mod by path or name, which will also remove no-longer existing mods. - _api.Mods.ReloadMod(data.Path, data.Name); + api.Mods.ReloadMod(data.Path, data.Name); } public async partial Task InstallMod() { - var data = await HttpContext.GetRequestDataAsync(); + var data = await HttpContext.GetRequestDataAsync().ConfigureAwait(false); Penumbra.Log.Debug($"[HTTP] {nameof(InstallMod)} triggered with {data}."); if (data.Path.Length != 0) - _api.Mods.InstallMod(data.Path); + api.Mods.InstallMod(data.Path); } public partial void OpenWindow() { Penumbra.Log.Debug($"[HTTP] {nameof(OpenWindow)} triggered."); - _api.Ui.OpenMainWindow(TabType.Mods, string.Empty, string.Empty); + api.Ui.OpenMainWindow(TabType.Mods, string.Empty, string.Empty); } private record ModReloadData(string Path, string Name) From de408e4d58328686084a4f06e7e0924abb344011 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 28 Mar 2025 17:33:26 +0000 Subject: [PATCH 1167/1381] [CI] Updating repo.json for 1.3.6.3 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 4fac86da..7a09af2e 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.2", - "TestingAssemblyVersion": "1.3.6.2", + "AssemblyVersion": "1.3.6.3", + "TestingAssemblyVersion": "1.3.6.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.3/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 5a5a1487a31ceed61ef98160d7eca6e2645a2f2c Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 28 Mar 2025 20:24:22 +0100 Subject: [PATCH 1168/1381] Fix texture naming in Resource Trees --- Penumbra/Interop/ResourceTree/ResolveContext.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 41a27ed5..99360077 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -270,13 +270,13 @@ internal unsafe partial record ResolveContext( if (samplerId.HasValue) { alreadyProcessedSamplerIds.Add(samplerId.Value); - var samplerCrc = GetSamplerCrcById(shpk, samplerId.Value); - if (samplerCrc.HasValue) + var textureCrc = GetTextureCrcById(shpk, samplerId.Value); + if (textureCrc.HasValue) { - if (shpkNames != null && shpkNames.TryGetValue(samplerCrc.Value, out var samplerName)) + if (shpkNames != null && shpkNames.TryGetValue(textureCrc.Value, out var samplerName)) name = samplerName.Value; else - name = $"Texture 0x{samplerCrc.Value:X8}"; + name = $"Texture 0x{textureCrc.Value:X8}"; } } } @@ -292,9 +292,9 @@ internal unsafe partial record ResolveContext( return node; - static uint? GetSamplerCrcById(ShaderPackage* shpk, uint id) - => shpk->SamplersSpan.FindFirst(s => s.Id == id, out var s) - ? s.CRC + static uint? GetTextureCrcById(ShaderPackage* shpk, uint id) + => shpk->TexturesSpan.FindFirst(t => t.Id == id, out var t) + ? t.CRC : null; static uint? GetTextureSamplerId(Material* mtrl, TextureResourceHandle* handle, HashSet alreadyVisitedSamplerIds) From cb0214ca2ff22c3d7ad8445aef685415e3d66088 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 29 Mar 2025 16:52:08 +0100 Subject: [PATCH 1169/1381] Fix material editor and improve pinning logic --- Penumbra.GameData | 2 +- .../Import/Models/Export/MaterialExporter.cs | 4 +- .../Materials/MtrlTab.CommonColorTable.cs | 2 +- .../Materials/MtrlTab.ShaderPackage.cs | 8 +- .../Materials/MtrlTab.Textures.cs | 146 ++++++++++-------- .../UI/AdvancedWindow/Materials/MtrlTab.cs | 19 ++- 6 files changed, 110 insertions(+), 71 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index e717a66f..b6b91f84 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e717a66f33b0656a7c5c971ffa2f63fd96477d94 +Subproject commit b6b91f846096d15276b728ba2078f27b95317d15 diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 121e6eed..6be2ccbd 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -288,7 +288,7 @@ public class MaterialExporter const uint valueFace = 0x6E5B8F10; var isFace = material.Mtrl.ShaderPackage.ShaderKeys - .Any(key => key is { Category: categoryHairType, Value: valueFace }); + .Any(key => key is { Key: categoryHairType, Value: valueFace }); var normal = material.Textures[TextureUsage.SamplerNormal]; var mask = material.Textures[TextureUsage.SamplerMask]; @@ -363,7 +363,7 @@ public class MaterialExporter // Face is the default for the skin shader, so a lack of skin type category is also correct. var isFace = !material.Mtrl.ShaderPackage.ShaderKeys - .Any(key => key.Category == categorySkinType && key.Value != valueFace); + .Any(key => key.Key == categorySkinType && key.Value != valueFace); // TODO: There's more nuance to skin than this, but this should be enough for a baseline reference. // TODO: Specular? diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index 236a66c3..d70a4b50 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -22,7 +22,7 @@ public partial class MtrlTab private bool DrawColorTableSection(bool disabled) { - if (!_shpkLoading && !SamplerIds.Contains(ShpkFile.TableSamplerId) || Mtrl.Table == null) + if (!_shpkLoading && !TextureIds.Contains(ShpkFile.TableSamplerId) || Mtrl.Table == null) return false; ImGui.Dummy(new Vector2(ImGui.GetTextLineHeight() / 2)); diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs index a13dd96b..202047e4 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -216,7 +216,7 @@ public partial class MtrlTab else foreach (var (key, index) in Mtrl.ShaderPackage.ShaderKeys.WithIndex()) { - var keyName = Names.KnownNames.TryResolve(key.Category); + var keyName = Names.KnownNames.TryResolve(key.Key); var valueName = keyName.WithKnownSuffixes().TryResolve(Names.KnownNames, key.Value); _shaderKeys.Add((keyName.ToString(), index, string.Empty, true, [(valueName.ToString(), key.Value, string.Empty)])); } @@ -366,6 +366,7 @@ public partial class MtrlTab ret = true; _associatedShpk = null; _loadedShpkPath = FullPath.Empty; + UnpinResources(true); LoadShpk(FindAssociatedShpk(out _, out _)); } @@ -442,8 +443,8 @@ public partial class MtrlTab { using var font = ImRaii.PushFont(UiBuilder.MonoFont, monoFont); ref var key = ref Mtrl.ShaderPackage.ShaderKeys[index]; - using var id = ImUtf8.PushId((int)key.Category); - var shpkKey = _associatedShpk?.GetMaterialKeyById(key.Category); + using var id = ImUtf8.PushId((int)key.Key); + var shpkKey = _associatedShpk?.GetMaterialKeyById(key.Key); var currentValue = key.Value; var (currentLabel, _, currentDescription) = values.FirstOrNull(v => v.Value == currentValue) ?? ($"0x{currentValue:X8}", currentValue, string.Empty); @@ -459,6 +460,7 @@ public partial class MtrlTab { key.Value = value; ret = true; + UnpinResources(false); Update(); } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs index 7ab2900d..dfa07d52 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs @@ -3,7 +3,6 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Text; -using Penumbra.GameData; using Penumbra.GameData.Files.MaterialStructs; using Penumbra.String.Classes; using static Penumbra.GameData.Files.MaterialStructs.SamplerFlags; @@ -16,18 +15,22 @@ public partial class MtrlTab public readonly List<(string Label, int TextureIndex, int SamplerIndex, string Description, bool MonoFont)> Textures = new(4); public readonly HashSet UnfoldedTextures = new(4); + public readonly HashSet TextureIds = new(16); public readonly HashSet SamplerIds = new(16); public float TextureLabelWidth; + private bool _samplersPinned; private void UpdateTextures() { Textures.Clear(); + TextureIds.Clear(); SamplerIds.Clear(); if (_associatedShpk == null) { + TextureIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); if (Mtrl.Table != null) - SamplerIds.Add(TableSamplerId); + TextureIds.Add(TableSamplerId); foreach (var (sampler, index) in Mtrl.ShaderPackage.Samplers.WithIndex()) Textures.Add(($"0x{sampler.SamplerId:X8}", sampler.TextureIndex, index, string.Empty, true)); @@ -35,31 +38,39 @@ public partial class MtrlTab else { foreach (var index in _vertexShaders) - SamplerIds.UnionWith(_associatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); - foreach (var index in _pixelShaders) - SamplerIds.UnionWith(_associatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); - if (!_shadersKnown) { - SamplerIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); - if (Mtrl.Table != null) - SamplerIds.Add(TableSamplerId); + TextureIds.UnionWith(_associatedShpk.VertexShaders[index].Textures.Select(texture => texture.Id)); + SamplerIds.UnionWith(_associatedShpk.VertexShaders[index].Samplers.Select(sampler => sampler.Id)); } - foreach (var samplerId in SamplerIds) + foreach (var index in _pixelShaders) { - var shpkSampler = _associatedShpk.GetSamplerById(samplerId); - if (shpkSampler is not { Slot: 2 }) + TextureIds.UnionWith(_associatedShpk.PixelShaders[index].Textures.Select(texture => texture.Id)); + SamplerIds.UnionWith(_associatedShpk.PixelShaders[index].Samplers.Select(sampler => sampler.Id)); + } + + if (_samplersPinned || !_shadersKnown) + { + TextureIds.UnionWith(Mtrl.ShaderPackage.Samplers.Select(sampler => sampler.SamplerId)); + if (Mtrl.Table != null) + TextureIds.Add(TableSamplerId); + } + + foreach (var textureId in TextureIds) + { + var shpkTexture = _associatedShpk.GetTextureById(textureId); + if (shpkTexture is not { Slot: 2 }) continue; - var dkData = TryGetShpkDevkitData("Samplers", samplerId, true); + var dkData = TryGetShpkDevkitData("Samplers", textureId, true); var hasDkLabel = !string.IsNullOrEmpty(dkData?.Label); - var sampler = Mtrl.GetOrAddSampler(samplerId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); - Textures.Add((hasDkLabel ? dkData!.Label : shpkSampler.Value.Name, sampler.TextureIndex, samplerIndex, + var sampler = Mtrl.GetOrAddSampler(textureId, dkData?.DefaultTexture ?? string.Empty, out var samplerIndex); + Textures.Add((hasDkLabel ? dkData!.Label : shpkTexture.Value.Name, sampler.TextureIndex, samplerIndex, dkData?.Description ?? string.Empty, !hasDkLabel)); } - if (SamplerIds.Contains(TableSamplerId)) + if (TextureIds.Contains(TableSamplerId)) Mtrl.Table ??= new ColorTable(); } @@ -205,58 +216,67 @@ public partial class MtrlTab ret = true; } - ref var samplerFlags = ref Wrap(ref sampler.Flags); - - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - var addressMode = samplerFlags.UAddressMode; - if (ComboTextureAddressMode("##UAddressMode"u8, ref addressMode)) + if (SamplerIds.Contains(sampler.SamplerId)) { - samplerFlags.UAddressMode = addressMode; - ret = true; - SetSamplerFlags(sampler.SamplerId, sampler.Flags); + ref var samplerFlags = ref Wrap(ref sampler.Flags); + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + var addressMode = samplerFlags.UAddressMode; + if (ComboTextureAddressMode("##UAddressMode"u8, ref addressMode)) + { + samplerFlags.UAddressMode = addressMode; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("U Address Mode"u8, + "Method to use for resolving a U texture coordinate that is outside the 0 to 1 range."); + + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + addressMode = samplerFlags.VAddressMode; + if (ComboTextureAddressMode("##VAddressMode"u8, ref addressMode)) + { + samplerFlags.VAddressMode = addressMode; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("V Address Mode"u8, + "Method to use for resolving a V texture coordinate that is outside the 0 to 1 range."); + + var lodBias = samplerFlags.LodBias; + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImUtf8.DragScalar("##LoDBias"u8, ref lodBias, -8.0f, 7.984375f, 0.1f)) + { + samplerFlags.LodBias = lodBias; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("Level of Detail Bias"u8, + "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); + + var minLod = samplerFlags.MinLod; + ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); + if (ImUtf8.DragScalar("##MinLoD"u8, ref minLod, 0, 15, 0.1f)) + { + samplerFlags.MinLod = minLod; + ret = true; + SetSamplerFlags(sampler.SamplerId, sampler.Flags); + } + + ImGui.SameLine(); + ImUtf8.LabeledHelpMarker("Minimum Level of Detail"u8, + "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); } - - ImGui.SameLine(); - ImUtf8.LabeledHelpMarker("U Address Mode"u8, "Method to use for resolving a U texture coordinate that is outside the 0 to 1 range."); - - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - addressMode = samplerFlags.VAddressMode; - if (ComboTextureAddressMode("##VAddressMode"u8, ref addressMode)) + else { - samplerFlags.VAddressMode = addressMode; - ret = true; - SetSamplerFlags(sampler.SamplerId, sampler.Flags); + ImUtf8.Text("This texture does not have a dedicated sampler."u8); } - ImGui.SameLine(); - ImUtf8.LabeledHelpMarker("V Address Mode"u8, "Method to use for resolving a V texture coordinate that is outside the 0 to 1 range."); - - var lodBias = samplerFlags.LodBias; - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ImUtf8.DragScalar("##LoDBias"u8, ref lodBias, -8.0f, 7.984375f, 0.1f)) - { - samplerFlags.LodBias = lodBias; - ret = true; - SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - ImGui.SameLine(); - ImUtf8.LabeledHelpMarker("Level of Detail Bias"u8, - "Offset from the calculated mipmap level.\n\nHigher means that the texture will start to lose detail nearer.\nLower means that the texture will keep its detail until farther."); - - var minLod = samplerFlags.MinLod; - ImGui.SetNextItemWidth(UiHelpers.Scale * 100.0f); - if (ImUtf8.DragScalar("##MinLoD"u8, ref minLod, 0, 15, 0.1f)) - { - samplerFlags.MinLod = minLod; - ret = true; - SetSamplerFlags(sampler.SamplerId, sampler.Flags); - } - - ImGui.SameLine(); - ImUtf8.LabeledHelpMarker("Minimum Level of Detail"u8, - "Most detailed mipmap level to use.\n\n0 is the full-sized texture, 1 is the half-sized texture, 2 is the quarter-sized texture, and so on.\n15 will forcibly reduce the texture to its smallest mipmap."); - using var t = ImUtf8.TreeNode("Advanced Settings"u8); if (!t) return ret; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs index 6e16de99..97acf130 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs @@ -57,6 +57,7 @@ public sealed partial class MtrlTab : IWritable, IDisposable Mtrl = file; FilePath = filePath; Writable = writable; + _samplersPinned = true; _associatedBaseDevkit = TryLoadShpkDevkit("_base", out _loadedBaseDevkitPathName); Update(); LoadShpk(FindAssociatedShpk(out _, out _)); @@ -172,6 +173,22 @@ public sealed partial class MtrlTab : IWritable, IDisposable Widget.DrawHexViewer(Mtrl.AdditionalData); } + private void UnpinResources(bool all) + { + _samplersPinned = false; + + if (!all) + return; + + var keys = Mtrl.ShaderPackage.ShaderKeys; + for (var i = 0; i < keys.Length; i++) + keys[i].Pinned = false; + + var constants = Mtrl.ShaderPackage.Constants; + for (var i = 0; i < constants.Length; i++) + constants[i].Pinned = false; + } + private void Update() { UpdateShaders(); @@ -192,7 +209,7 @@ public sealed partial class MtrlTab : IWritable, IDisposable public byte[] Write() { var output = Mtrl.Clone(); - output.GarbageCollect(_associatedShpk, SamplerIds); + output.GarbageCollect(_associatedShpk, TextureIds); return output.Write(); } From 2dd6dd201c61f80a1ce3a01088120b3c5adc7aff Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 29 Mar 2025 18:03:50 +0100 Subject: [PATCH 1170/1381] Update PAP records. --- Penumbra/UI/ResourceWatcher/Record.cs | 20 +++++++++++++++++++ .../UI/ResourceWatcher/ResourceWatcher.cs | 12 +++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index 8ab96f4b..b8730750 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -56,6 +56,26 @@ internal unsafe struct Record Crc64 = 0, }; + public static Record CreateRequest(CiByteString path, bool sync, FullPath fullPath, ResolveData resolve) + => new() + { + Time = DateTime.UtcNow, + Path = fullPath.InternalName.IsOwned ? fullPath.InternalName : fullPath.InternalName.Clone(), + OriginalPath = path.IsOwned ? path : path.Clone(), + Collection = resolve.Valid ? resolve.ModCollection : null, + Handle = null, + ResourceType = ResourceExtensions.Type(path).ToFlag(), + Category = ResourceExtensions.Category(path).ToFlag(), + RefCount = 0, + RecordType = RecordType.Request, + Synchronously = sync, + ReturnValue = OptionalBool.Null, + CustomLoad = fullPath.InternalName != path, + AssociatedGameObject = string.Empty, + LoadState = LoadState.None, + Crc64 = fullPath.Crc64, + }; + public static Record CreateDefaultLoad(CiByteString path, ResourceHandle* handle, ModCollection collection, string associatedGameObject) { path = path.IsOwned ? path : path.Clone(); diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index 94bd4307..d134cfe5 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -58,12 +58,19 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService private void OnPapRequested(Utf8GamePath original, FullPath? _1, ResolveData _2) { if (_ephemeral.EnableResourceLogging && FilterMatch(original.Path, out var match)) + { Penumbra.Log.Information($"[ResourceLoader] [REQ] {match} was requested asynchronously."); + if (_1.HasValue) + Penumbra.Log.Information( + $"[ResourceLoader] [LOAD] Resolved {_1.Value.FullName} for {match} from collection {_2.ModCollection} for object 0x{_2.AssociatedGameObject:X}."); + } if (!_ephemeral.EnableResourceWatcher) return; - var record = Record.CreateRequest(original.Path, false); + var record = _1.HasValue + ? Record.CreateRequest(original.Path, false, _1.Value, _2) + : Record.CreateRequest(original.Path, false); if (!_ephemeral.OnlyAddMatchingResources || _table.WouldBeVisible(record)) _newRecords.Enqueue(record); } @@ -257,7 +264,8 @@ public sealed class ResourceWatcher : IDisposable, ITab, IUiService _newRecords.Enqueue(record); } - private unsafe void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, ReadOnlySpan additionalData, bool isAsync) + private unsafe void OnResourceComplete(ResourceHandle* resource, CiByteString path, Utf8GamePath original, + ReadOnlySpan additionalData, bool isAsync) { if (!isAsync) return; From f3bcc4d55492f422384099c1dadac50968ce3ba0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 29 Mar 2025 18:05:47 +0100 Subject: [PATCH 1171/1381] Update changelog. --- Penumbra/UI/Changelog.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 1b0225ed..32abeb41 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -60,10 +60,15 @@ public class PenumbraChangelog : IUiService Add1_3_4_0(Changelog); Add1_3_5_0(Changelog); Add1_3_6_0(Changelog); + Add1_3_6_4(Changelog); } #region Changelogs + private static void Add1_3_6_4(Changelog log) + => log.NextVersion("Version 1.3.6.4") + .RegisterEntry("The material editor should be functional again."); + private static void Add1_3_6_0(Changelog log) => log.NextVersion("Version 1.3.6.0") .RegisterImportant("Updated Penumbra for update 7.20 and Dalamud API 12.") @@ -73,7 +78,6 @@ public class PenumbraChangelog : IUiService .RegisterEntry( "I also do not use most of the functionality of Penumbra myself, so I am unable to even encounter most issues myself.", 1) .RegisterEntry("If you encounter any issues, please report them quickly on the discord.", 1) - .RegisterImportant("There is a known issue with the Material Editor due to the shader changes, please do not author materials for the moment, they will be broken!", 1) .RegisterHighlight( "The texture editor now has encoding support for Block Compression 1, 4 and 5 and tooltips explaining when to use which format.") .RegisterEntry("It also is able to use GPU compression and thus has become much faster for BC7 in particular. (Thanks Ny!)", 1) From cc76125b1c3f5c1e60e3fd3e0b344e01add3a8d9 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 29 Mar 2025 17:07:46 +0000 Subject: [PATCH 1172/1381] [CI] Updating repo.json for 1.3.6.4 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 7a09af2e..17fe95b3 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.3", - "TestingAssemblyVersion": "1.3.6.3", + "AssemblyVersion": "1.3.6.4", + "TestingAssemblyVersion": "1.3.6.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.3/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.4/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.4/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From b589103b05d19122c6a9f01d9e8ceb9f33a7510f Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 30 Mar 2025 13:44:04 +0200 Subject: [PATCH 1173/1381] Make resolvedData thread-local --- .../Hooks/ResourceLoading/ResourceLoader.cs | 40 +++++++++++++------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs index 3f8cb23f..6ddcbfda 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceLoader.cs @@ -23,7 +23,7 @@ public unsafe class ResourceLoader : IDisposable, IService private readonly ConcurrentDictionary _ongoingLoads = []; - private ResolveData _resolvedData = ResolveData.Invalid; + private readonly ThreadLocal _resolvedData = new(() => ResolveData.Invalid); public event Action? PapRequested; public IReadOnlyDictionary OngoingLoads @@ -56,10 +56,11 @@ public unsafe class ResourceLoader : IDisposable, IService if (!_config.EnableMods || !Utf8GamePath.FromPointer(path, MetaDataComputation.CiCrc32, out var gamePath)) return length; + var resolvedData = _resolvedData.Value; var (resolvedPath, data) = _incMode.Value ? (null, ResolveData.Invalid) - : _resolvedData.Valid - ? (_resolvedData.ModCollection.ResolvePath(gamePath), _resolvedData) + : resolvedData.Valid + ? (resolvedData.ModCollection.ResolvePath(gamePath), resolvedData) : ResolvePath(gamePath, ResourceCategory.Chara, ResourceType.Pap); @@ -78,19 +79,31 @@ public unsafe class ResourceLoader : IDisposable, IService /// Load a resource for a given path and a specific collection. public ResourceHandle* LoadResolvedResource(ResourceCategory category, ResourceType type, CiByteString path, ResolveData resolveData) { - _resolvedData = resolveData; - var ret = _resources.GetResource(category, type, path); - _resolvedData = ResolveData.Invalid; - return ret; + var previous = _resolvedData.Value; + _resolvedData.Value = resolveData; + try + { + return _resources.GetResource(category, type, path); + } + finally + { + _resolvedData.Value = previous; + } } /// Load a resource for a given path and a specific collection. public SafeResourceHandle LoadResolvedSafeResource(ResourceCategory category, ResourceType type, CiByteString path, ResolveData resolveData) { - _resolvedData = resolveData; - var ret = _resources.GetSafeResource(category, type, path); - _resolvedData = ResolveData.Invalid; - return ret; + var previous = _resolvedData.Value; + _resolvedData.Value = resolveData; + try + { + return _resources.GetSafeResource(category, type, path); + } + finally + { + _resolvedData.Value = previous; + } } /// The function to use to resolve a given path. @@ -159,10 +172,11 @@ public unsafe class ResourceLoader : IDisposable, IService CompareHash(ComputeHash(path.Path, parameters), hash, path); // If no replacements are being made, we still want to be able to trigger the event. + var resolvedData = _resolvedData.Value; var (resolvedPath, data) = _incMode.Value ? (null, ResolveData.Invalid) - : _resolvedData.Valid - ? (_resolvedData.ModCollection.ResolvePath(path), _resolvedData) + : resolvedData.Valid + ? (resolvedData.ModCollection.ResolvePath(path), resolvedData) : ResolvePath(path, category, type); if (resolvedPath == null || !Utf8GamePath.FromByteString(resolvedPath.Value.InternalName, out var p)) From fe5d1bc36ee05017fde0bf9cdad71772fd1ad109 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 30 Mar 2025 16:08:59 +0000 Subject: [PATCH 1174/1381] [CI] Updating repo.json for 1.3.6.5 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 17fe95b3..2c2088c3 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.4", - "TestingAssemblyVersion": "1.3.6.4", + "AssemblyVersion": "1.3.6.5", + "TestingAssemblyVersion": "1.3.6.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.4/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.4/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.4/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.5/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.5/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 1d517103b3d52758afbd47648352d793446eb5c6 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 30 Mar 2025 19:55:43 +0200 Subject: [PATCH 1175/1381] Mtrl editor: Fix texture pinning --- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs index dfa07d52..dd01ec2b 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs @@ -59,7 +59,7 @@ public partial class MtrlTab foreach (var textureId in TextureIds) { var shpkTexture = _associatedShpk.GetTextureById(textureId); - if (shpkTexture is not { Slot: 2 }) + if (shpkTexture is not { Slot: 2 } && (shpkTexture is not null || textureId == TableSamplerId)) continue; var dkData = TryGetShpkDevkitData("Samplers", textureId, true); From abb47751c821b86eb8f7a3e88a9e12939a611d3a Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 30 Mar 2025 20:29:25 +0200 Subject: [PATCH 1176/1381] Mtrl editor: Disregard obsolete modded ShPks --- Penumbra/Interop/Processing/ShpkPathPreProcessor.cs | 4 ++-- .../UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs index 826771dd..ddd59121 100644 --- a/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs +++ b/Penumbra/Interop/Processing/ShpkPathPreProcessor.cs @@ -49,7 +49,7 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, return null; } - private static SanityCheckResult SanityCheck(string path) + internal static SanityCheckResult SanityCheck(string path) { try { @@ -79,7 +79,7 @@ public sealed class ShpkPathPreProcessor(ResourceManagerService resourceManager, _ => string.Empty, }; - private enum SanityCheckResult + internal enum SanityCheckResult { Success, IoError, diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs index 202047e4..b76cffc2 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -10,6 +10,7 @@ using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.GameData.Files.ShaderStructs; +using Penumbra.Interop.Processing; using Penumbra.String.Classes; using static Penumbra.GameData.Files.ShpkFile; @@ -128,7 +129,11 @@ public partial class MtrlTab if (!Utf8GamePath.FromString(defaultPath, out defaultGamePath)) return FullPath.Empty; - return _edit.FindBestMatch(defaultGamePath); + var path = _edit.FindBestMatch(defaultGamePath); + if (!path.IsRooted || ShpkPathPreProcessor.SanityCheck(path.FullName) == ShpkPathPreProcessor.SanityCheckResult.Success) + return path; + + return new FullPath(defaultPath); } private void LoadShpk(FullPath path) From c3be151d4023d6b4edc5985c259bfef8645cb4b7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 2 Apr 2025 23:36:56 +0200 Subject: [PATCH 1177/1381] Maybe fix crash issue in AtchHook1 / issue with kept draw object links. --- .../Hooks/Objects/CharacterDestructor.cs | 3 ++ .../Interop/PathResolving/DrawObjectState.cs | 36 ++++++++++++++++++- Penumbra/UI/Changelog.cs | 1 - 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs index ffe2f72d..55b392ba 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterDestructor.cs @@ -15,6 +15,9 @@ public sealed unsafe class CharacterDestructor : EventWrapperPtr IdentifiedCollectionCache = 0, + + /// + DrawObjectState = 0, } public CharacterDestructor(HookManager hooks) diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 5e413fe2..28a0dd8d 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -15,6 +15,7 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _drawObjectToGameObject = []; @@ -23,21 +24,24 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _gameState.LastGameObject; public unsafe DrawObjectState(ObjectManager objects, CreateCharacterBase createCharacterBase, WeaponReload weaponReload, - CharacterBaseDestructor characterBaseDestructor, GameState gameState, IFramework framework) + CharacterBaseDestructor characterBaseDestructor, GameState gameState, IFramework framework, CharacterDestructor characterDestructor) { _objects = objects; _createCharacterBase = createCharacterBase; _weaponReload = weaponReload; _characterBaseDestructor = characterBaseDestructor; _gameState = gameState; + _characterDestructor = characterDestructor; framework.RunOnFrameworkThread(InitializeDrawObjects); _weaponReload.Subscribe(OnWeaponReloading, WeaponReload.Priority.DrawObjectState); _weaponReload.Subscribe(OnWeaponReloaded, WeaponReload.PostEvent.Priority.DrawObjectState); _createCharacterBase.Subscribe(OnCharacterBaseCreated, CreateCharacterBase.PostEvent.Priority.DrawObjectState); _characterBaseDestructor.Subscribe(OnCharacterBaseDestructor, CharacterBaseDestructor.Priority.DrawObjectState); + _characterDestructor.Subscribe(OnCharacterDestructor, CharacterDestructor.Priority.DrawObjectState); } + public bool ContainsKey(nint key) => _drawObjectToGameObject.ContainsKey(key); @@ -68,6 +72,36 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary + /// Seems like sometimes the draw object of a game object is destroyed in frames after the original game object is already destroyed. + /// So protect against outdated game object pointers in the dictionary. + /// + private unsafe void OnCharacterDestructor(Character* a) + { + if (a is null) + return; + + var character = (nint)a; + var delete = stackalloc nint[5]; + var current = 0; + foreach (var (drawObject, (gameObject, _)) in _drawObjectToGameObject) + { + if (gameObject != character) + continue; + + delete[current++] = drawObject; + if (current is 4) + break; + } + + for (var ptr = delete; *ptr != nint.Zero; ++ptr) + { + _drawObjectToGameObject.Remove(*ptr, out var pair); + Penumbra.Log.Excessive($"[DrawObjectState] Removed draw object 0x{*ptr:X} -> 0x{(nint)a:X} (actual: 0x{pair.GameObject:X}, {pair.IsChild})."); + } } private unsafe void OnWeaponReloading(DrawDataContainer* _, Character* character, CharacterWeapon* _2) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 32abeb41..5e1612eb 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -90,7 +90,6 @@ public class PenumbraChangelog : IUiService .RegisterEntry("The EQP entry previously named Unknown 4 was renamed to 'Hide Glove Cuffs'.") .RegisterEntry("Fixed the changed item identification for EST changes.") .RegisterEntry("Fixed clipping issues in the changed items panel when no grouping was active."); - private static void Add1_3_5_0(Changelog log) From 09c2264de4bd93eec422fc4e69e9e40e0b8023f6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 2 Apr 2025 23:41:08 +0200 Subject: [PATCH 1178/1381] Revert overeager BNPC Name update. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index b6b91f84..ab63da80 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b6b91f846096d15276b728ba2078f27b95317d15 +Subproject commit ab63da8047f3d99240159bb1b17dbcb61d77326a From 2fdafc5c8581792acdd09c4a6e93bf8442b8edfa Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 2 Apr 2025 21:45:19 +0000 Subject: [PATCH 1179/1381] [CI] Updating repo.json for 1.3.6.6 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 2c2088c3..f471e95e 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.5", - "TestingAssemblyVersion": "1.3.6.5", + "AssemblyVersion": "1.3.6.6", + "TestingAssemblyVersion": "1.3.6.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.5/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.5/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.5/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.6/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From c3b2443ab52231658bfa73e36d0d42e671cc2c79 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 4 Apr 2025 22:35:23 +0200 Subject: [PATCH 1180/1381] Add Incognito modifier. --- Penumbra/Configuration.cs | 1 + Penumbra/EphemeralConfig.cs | 1 + .../Hooks/Objects/CharacterBaseDestructor.cs | 5 ++--- .../Hooks/Objects/CharacterDestructor.cs | 2 +- .../Materials/MtrlTab.Textures.cs | 16 ++++++++-------- Penumbra/UI/Classes/CollectionSelectHeader.cs | 6 +++--- Penumbra/UI/IncognitoService.cs | 17 +++++++++++++---- Penumbra/UI/Tabs/SettingsTab.cs | 8 ++++++++ 8 files changed, 37 insertions(+), 19 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 939eb122..3a9bcdc4 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -94,6 +94,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public string QuickMoveFolder2 { get; set; } = string.Empty; public string QuickMoveFolder3 { get; set; } = string.Empty; public DoubleModifier DeleteModModifier { get; set; } = new(ModifierHotkey.Control, ModifierHotkey.Shift); + public DoubleModifier IncognitoModifier { get; set; } = new(ModifierHotkey.Control); public bool PrintSuccessfulCommandsToChat { get; set; } = true; public bool AutoDeduplicateOnImport { get; set; } = true; public bool AutoReduplicateUiOnImport { get; set; } = true; diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 24ab466b..678e53ad 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -41,6 +41,7 @@ public class EphemeralConfig : ISavable, IDisposable, IService public string LastModPath { get; set; } = string.Empty; public bool AdvancedEditingOpen { get; set; } = false; public bool ForceRedrawOnFileChange { get; set; } = false; + public bool IncognitoMode { get; set; } = false; /// /// Load the current configuration. diff --git a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs index 7636718e..2d8e60b2 100644 --- a/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs +++ b/Penumbra/Interop/Hooks/Objects/CharacterBaseDestructor.cs @@ -2,7 +2,6 @@ using Dalamud.Hooking; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using OtterGui.Classes; using OtterGui.Services; -using Penumbra.UI.AdvancedWindow; namespace Penumbra.Interop.Hooks.Objects; @@ -13,7 +12,7 @@ public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr DrawObjectState = 0, - /// + /// MtrlTab = -1000, } @@ -42,7 +41,7 @@ public sealed unsafe class CharacterBaseDestructor : EventWrapperPtr 0) - ImGuiUtil.LabeledHelpMarker(label, description); - else - ImGui.TextUnformatted(label); + using (ImRaii.PushFont(UiBuilder.MonoFont, monoFont)) + { + ImGui.AlignTextToFramePadding(); + if (description.Length > 0) + ImGuiUtil.LabeledHelpMarker(label, description); + else + ImGui.TextUnformatted(label); } if (unfolded) diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index 54fcf279..d7a81876 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -61,7 +61,7 @@ public class CollectionSelectHeader : IUiService private void DrawTemporaryCheckbox() { - var hold = _config.DeleteModModifier.IsActive(); + var hold = _config.IncognitoModifier.IsActive(); using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImUtf8.GlobalScale)) { var tint = ImGuiCol.Text.Tinted(ColorId.TemporaryModSettingsTint); @@ -77,9 +77,9 @@ public class CollectionSelectHeader : IUiService } ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, - "Toggle the temporary settings mode, where all changes you do create temporary settings first and need to be made permanent if desired.\n"u8); + "Toggle the temporary settings mode, where all changes you do create temporary settings first and need to be made permanent if desired."u8); if (!hold) - ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking to toggle."); + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"\nHold {_config.IncognitoModifier} while clicking to toggle."); } private enum CollectionState diff --git a/Penumbra/UI/IncognitoService.cs b/Penumbra/UI/IncognitoService.cs index d58ea1ec..29358618 100644 --- a/Penumbra/UI/IncognitoService.cs +++ b/Penumbra/UI/IncognitoService.cs @@ -1,4 +1,5 @@ using Dalamud.Interface; +using ImGuiNET; using Penumbra.UI.Classes; using OtterGui.Raii; using OtterGui.Services; @@ -6,19 +7,27 @@ using OtterGui.Text; namespace Penumbra.UI; -public class IncognitoService(TutorialService tutorial) : IService +public class IncognitoService(TutorialService tutorial, Configuration config) : IService { - public bool IncognitoMode; + public bool IncognitoMode + => config.Ephemeral.IncognitoMode; public void DrawToggle(float width) { + var hold = config.IncognitoModifier.IsActive(); var color = ColorId.FolderExpanded.Value(); using (ImRaii.PushFrameBorder(ImUtf8.GlobalScale, color)) { var tt = IncognitoMode ? "Toggle incognito mode off."u8 : "Toggle incognito mode on."u8; var icon = IncognitoMode ? FontAwesomeIcon.EyeSlash : FontAwesomeIcon.Eye; - if (ImUtf8.IconButton(icon, tt, new Vector2(width, ImUtf8.FrameHeight), false, color)) - IncognitoMode = !IncognitoMode; + if (ImUtf8.IconButton(icon, tt, new Vector2(width, ImUtf8.FrameHeight), false, color) && hold) + { + config.Ephemeral.IncognitoMode = !IncognitoMode; + config.Ephemeral.Save(); + } + + if (!hold) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"\nHold {config.IncognitoModifier} while clicking to toggle."); } tutorial.OpenTutorial(BasicTutorialSteps.Incognito); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index ba226aa8..b1f82a91 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -621,6 +621,14 @@ public class SettingsTab : ITab, IUiService _config.DeleteModModifier = v; _config.Save(); }); + Widget.DoubleModifierSelector("Incognito Modifier", + "A modifier you need to hold while clicking the Incognito or Temporary Settings Mode button for it to take effect.", UiHelpers.InputTextWidth.X, + _config.IncognitoModifier, + v => + { + _config.IncognitoModifier = v; + _config.Save(); + }); } /// Draw all settings pertaining to import and export of mods. From 3b54485127dcbee68733d9eb5a5027c90e552619 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 5 Apr 2025 14:42:25 +0200 Subject: [PATCH 1181/1381] Maybe fix AtchCaller crashes. --- Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs | 2 +- Penumbra/Interop/PathResolving/CollectionResolver.cs | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs index c350c157..2a3d7468 100644 --- a/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs +++ b/Penumbra/Interop/Hooks/Meta/AtchCallerHook1.cs @@ -25,7 +25,7 @@ public unsafe class AtchCallerHook1 : FastHook, IDispo private void Detour(DrawObjectData* data, uint slot, nint unk, Model playerModel) { - var collection = _collectionResolver.IdentifyCollection(playerModel.AsDrawObject, true); + var collection = playerModel.Valid ? _collectionResolver.IdentifyCollection(playerModel.AsDrawObject, true) : _collectionResolver.DefaultCollection; _metaState.AtchCollection.Push(collection); Task.Result.Original(data, slot, unk, playerModel); _metaState.AtchCollection.Pop(); diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 576b61bb..f14abbff 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -95,6 +95,10 @@ public sealed unsafe class CollectionResolver( return IdentifyCollection(obj, useCache); } + /// Get the default collection. + public ResolveData DefaultCollection + => collectionManager.Active.Default.ToResolveData(); + /// Return whether the given ModelChara id refers to a human-type model. public bool IsModelHuman(uint modelCharaId) => humanModels.IsHuman(modelCharaId); From 5437ab477f349682edb09781340f6db34fbc9be2 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 5 Apr 2025 12:44:47 +0000 Subject: [PATCH 1182/1381] [CI] Updating repo.json for 1.3.6.7 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index f471e95e..5163bb7d 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.6", - "TestingAssemblyVersion": "1.3.6.6", + "AssemblyVersion": "1.3.6.7", + "TestingAssemblyVersion": "1.3.6.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.6/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.6/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.7/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.7/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 93e60471de1b68cfc828fba0819b4d7ab06072cc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 5 Apr 2025 18:49:18 +0200 Subject: [PATCH 1183/1381] Update for new objectmanager. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 3396ee17..f53fd227 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3396ee176fa72ad2dfb2de3294f7125ebce4dae5 +Subproject commit f53fd227a242435ce44a9fe9c5e847d0ca788869 diff --git a/Penumbra.GameData b/Penumbra.GameData index ab63da80..4769bbcd 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ab63da8047f3d99240159bb1b17dbcb61d77326a +Subproject commit 4769bbcdfce9e1d5a461c6b552b5b30ad6bc478e diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 42502290..6629c126 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -503,6 +503,8 @@ public class DebugTab : Window, ITab, IUiService if (!ImGui.CollapsingHeader("Actors")) return; + _objects.DrawDebug(); + using var table = Table("##actors", 8, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, -Vector2.UnitX); if (!table) From 0afcae45046c5e4b25b59757296500aa92d4aae2 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 5 Apr 2025 18:49:30 +0200 Subject: [PATCH 1184/1381] Run API redraws on framework. --- Penumbra/Api/Api/RedrawApi.cs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Penumbra/Api/Api/RedrawApi.cs b/Penumbra/Api/Api/RedrawApi.cs index 82d14f7b..ec4de892 100644 --- a/Penumbra/Api/Api/RedrawApi.cs +++ b/Penumbra/Api/Api/RedrawApi.cs @@ -1,23 +1,32 @@ using Dalamud.Game.ClientState.Objects.Types; +using Dalamud.Plugin.Services; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Interop.Services; namespace Penumbra.Api.Api; -public class RedrawApi(RedrawService redrawService) : IPenumbraApiRedraw, IApiService +public class RedrawApi(RedrawService redrawService, IFramework framework) : IPenumbraApiRedraw, IApiService { public void RedrawObject(int gameObjectIndex, RedrawType setting) - => redrawService.RedrawObject(gameObjectIndex, setting); + { + framework.RunOnFrameworkThread(() => redrawService.RedrawObject(gameObjectIndex, setting)); + } public void RedrawObject(string name, RedrawType setting) - => redrawService.RedrawObject(name, setting); + { + framework.RunOnFrameworkThread(() => redrawService.RedrawObject(name, setting)); + } public void RedrawObject(IGameObject? gameObject, RedrawType setting) - => redrawService.RedrawObject(gameObject, setting); + { + framework.RunOnFrameworkThread(() => redrawService.RedrawObject(gameObject, setting)); + } public void RedrawAll(RedrawType setting) - => redrawService.RedrawAll(setting); + { + framework.RunOnFrameworkThread(() => redrawService.RedrawAll(setting)); + } public event GameObjectRedrawnDelegate? GameObjectRedrawn { From 33ada1d9949b6b68315e0e6f96f6714973250128 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 8 Apr 2025 16:56:23 +0200 Subject: [PATCH 1185/1381] Remove meta-default-value checking from TT imports, move it entirely to mod loads, and keep default-valued entries if other options actually edit the same entry. --- .editorconfig | 12 ++ OtterGui | 2 +- .../Import/TexToolsMeta.Deserialization.cs | 31 +--- Penumbra/Import/TexToolsMeta.Rgsp.cs | 7 +- Penumbra/Import/TexToolsMeta.cs | 9 +- Penumbra/Mods/Editor/ModMetaEditor.cs | 162 ++++++++++++++++-- Penumbra/Mods/Manager/ModMigration.cs | 10 +- Penumbra/Mods/ModCreator.cs | 36 ++-- 8 files changed, 194 insertions(+), 75 deletions(-) diff --git a/.editorconfig b/.editorconfig index c645b573..f0328fd7 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3576,6 +3576,18 @@ resharper_xaml_xaml_xamarin_forms_data_type_and_binding_context_type_mismatched_ resharper_xaml_x_key_attribute_disallowed_highlighting=error resharper_xml_doc_comment_syntax_problem_highlighting=warning resharper_xunit_xunit_test_with_console_output_highlighting=warning +csharp_style_prefer_implicitly_typed_lambda_expression = true:suggestion +csharp_style_expression_bodied_methods = true:silent +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_unbound_generic_type_in_nameof = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_expression_bodied_constructors = true:silent +csharp_style_expression_bodied_operators = true:silent +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent +csharp_style_expression_bodied_properties = true:silent [*.{cshtml,htm,html,proto,razor}] indent_style=tab diff --git a/OtterGui b/OtterGui index f53fd227..21ddfccb 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit f53fd227a242435ce44a9fe9c5e847d0ca788869 +Subproject commit 21ddfccb91ba3fa56e1c191e706ff91bffaa9515 diff --git a/Penumbra/Import/TexToolsMeta.Deserialization.cs b/Penumbra/Import/TexToolsMeta.Deserialization.cs index 1f970dfe..7861a95b 100644 --- a/Penumbra/Import/TexToolsMeta.Deserialization.cs +++ b/Penumbra/Import/TexToolsMeta.Deserialization.cs @@ -2,7 +2,6 @@ using Lumina.Extensions; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Import.Structs; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Import; @@ -19,9 +18,7 @@ public partial class TexToolsMeta var identifier = new EqpIdentifier(metaFileInfo.PrimaryId, metaFileInfo.EquipSlot); var value = Eqp.FromSlotAndBytes(metaFileInfo.EquipSlot, data) & mask; - var def = ExpandedEqpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId) & mask; - if (_keepDefault || def != value) - MetaManipulations.TryAdd(identifier, value); + MetaManipulations.TryAdd(identifier, value); } // Deserialize and check Eqdp Entries and add them to the list if they are non-default. @@ -41,11 +38,9 @@ public partial class TexToolsMeta continue; var identifier = new EqdpIdentifier(metaFileInfo.PrimaryId, metaFileInfo.EquipSlot, gr); - var mask = Eqdp.Mask(metaFileInfo.EquipSlot); - var value = Eqdp.FromSlotAndBits(metaFileInfo.EquipSlot, (byteValue & 1) == 1, (byteValue & 2) == 2) & mask; - var def = ExpandedEqdpFile.GetDefault(_metaFileManager, gr, metaFileInfo.EquipSlot.IsAccessory(), metaFileInfo.PrimaryId) & mask; - if (_keepDefault || def != value) - MetaManipulations.TryAdd(identifier, value); + var mask = Eqdp.Mask(metaFileInfo.EquipSlot); + var value = Eqdp.FromSlotAndBits(metaFileInfo.EquipSlot, (byteValue & 1) == 1, (byteValue & 2) == 2) & mask; + MetaManipulations.TryAdd(identifier, value); } } @@ -55,10 +50,9 @@ public partial class TexToolsMeta if (data == null) return; - var value = GmpEntry.FromTexToolsMeta(data.AsSpan(0, 5)); - var def = ExpandedGmpFile.GetDefault(_metaFileManager, metaFileInfo.PrimaryId); - if (_keepDefault || value != def) - MetaManipulations.TryAdd(new GmpIdentifier(metaFileInfo.PrimaryId), value); + var value = GmpEntry.FromTexToolsMeta(data.AsSpan(0, 5)); + var identifier = new GmpIdentifier(metaFileInfo.PrimaryId); + MetaManipulations.TryAdd(identifier, value); } // Deserialize and check Est Entries and add them to the list if they are non-default. @@ -86,9 +80,7 @@ public partial class TexToolsMeta continue; var identifier = new EstIdentifier(id, type, gr); - var def = EstFile.GetDefault(_metaFileManager, type, gr, id); - if (_keepDefault || def != value) - MetaManipulations.TryAdd(identifier, value); + MetaManipulations.TryAdd(identifier, value); } } @@ -108,15 +100,10 @@ public partial class TexToolsMeta { var identifier = new ImcIdentifier(metaFileInfo.PrimaryId, 0, metaFileInfo.PrimaryType, metaFileInfo.SecondaryId, metaFileInfo.EquipSlot, metaFileInfo.SecondaryType); - var file = new ImcFile(_metaFileManager, identifier); - var partIdx = ImcFile.PartIndex(identifier.EquipSlot); // Gets turned to unknown for things without equip, and unknown turns to 0. foreach (var value in values) { identifier = identifier with { Variant = (Variant)i }; - var def = file.GetEntry(partIdx, (Variant)i); - if (_keepDefault || def != value && identifier.Validate()) - MetaManipulations.TryAdd(identifier, value); - + MetaManipulations.TryAdd(identifier, value); ++i; } } diff --git a/Penumbra/Import/TexToolsMeta.Rgsp.cs b/Penumbra/Import/TexToolsMeta.Rgsp.cs index 7b0bb5a8..77c70e6c 100644 --- a/Penumbra/Import/TexToolsMeta.Rgsp.cs +++ b/Penumbra/Import/TexToolsMeta.Rgsp.cs @@ -1,6 +1,5 @@ using Penumbra.GameData.Enums; using Penumbra.Meta; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Import; @@ -8,7 +7,7 @@ namespace Penumbra.Import; public partial class TexToolsMeta { // Parse a single rgsp file. - public static TexToolsMeta FromRgspFile(MetaFileManager manager, string filePath, byte[] data, bool keepDefault) + public static TexToolsMeta FromRgspFile(MetaFileManager manager, string filePath, byte[] data) { if (data.Length != 45 && data.Length != 42) { @@ -70,9 +69,7 @@ public partial class TexToolsMeta void Add(RspAttribute attribute, float value) { var identifier = new RspIdentifier(subRace, attribute); - var def = CmpFile.GetDefault(manager, subRace, attribute); - if (keepDefault || value != def.Value) - ret.MetaManipulations.TryAdd(identifier, new RspEntry(value)); + ret.MetaManipulations.TryAdd(identifier, new RspEntry(value)); } } } diff --git a/Penumbra/Import/TexToolsMeta.cs b/Penumbra/Import/TexToolsMeta.cs index c4a8e81f..f98eddbe 100644 --- a/Penumbra/Import/TexToolsMeta.cs +++ b/Penumbra/Import/TexToolsMeta.cs @@ -23,15 +23,11 @@ public partial class TexToolsMeta // The info class determines the files or table locations the changes need to apply to from the filename. public readonly uint Version; public readonly string FilePath; - public readonly MetaDictionary MetaManipulations = new(); - private readonly bool _keepDefault; + public readonly MetaDictionary MetaManipulations = new(); - private readonly MetaFileManager _metaFileManager; - public TexToolsMeta(MetaFileManager metaFileManager, GamePathParser parser, byte[] data, bool keepDefault) + public TexToolsMeta(GamePathParser parser, byte[] data) { - _metaFileManager = metaFileManager; - _keepDefault = keepDefault; try { using var reader = new BinaryReader(new MemoryStream(data)); @@ -79,7 +75,6 @@ public partial class TexToolsMeta private TexToolsMeta(MetaFileManager metaFileManager, string filePath, uint version) { - _metaFileManager = metaFileManager; FilePath = filePath; Version = version; } diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index c5c8fb8b..050dab51 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -1,11 +1,15 @@ using System.Collections.Frozen; +using OtterGui.Classes; using OtterGui.Services; using Penumbra.Collections.Cache; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; +using Penumbra.Services; +using static Penumbra.GameData.Files.ShpkFile; namespace Penumbra.Mods.Editor; @@ -68,13 +72,157 @@ public class ModMetaEditor( Changes = false; } - public static bool DeleteDefaultValues(MetaFileManager metaFileManager, MetaDictionary dict) + public static bool DeleteDefaultValues(Mod mod, MetaFileManager metaFileManager, SaveService? saveService, bool deleteAll = false) + { + if (deleteAll) + { + var changes = false; + foreach (var container in mod.AllDataContainers) + { + if (!DeleteDefaultValues(metaFileManager, container.Manipulations)) + continue; + + saveService?.ImmediateSaveSync(new ModSaveGroup(container, metaFileManager.Config.ReplaceNonAsciiOnImport)); + changes = true; + } + + return changes; + } + + var defaultEntries = new MultiDictionary(); + var actualEntries = new HashSet(); + if (!FilterDefaultValues(mod.AllDataContainers, metaFileManager, defaultEntries, actualEntries)) + return false; + + var groups = new HashSet(); + DefaultSubMod? defaultMod = null; + foreach (var (defaultIdentifier, containers) in defaultEntries.Grouped) + { + if (!deleteAll && actualEntries.Contains(defaultIdentifier)) + continue; + + foreach (var container in containers) + { + if (!container.Manipulations.Remove(defaultIdentifier)) + continue; + + Penumbra.Log.Verbose($"Deleted default-valued meta-entry {defaultIdentifier}."); + if (container.Group is { } group) + groups.Add(group); + else if (container is DefaultSubMod d) + defaultMod = d; + } + } + + if (saveService is not null) + { + if (defaultMod is not null) + saveService.ImmediateSaveSync(new ModSaveGroup(defaultMod, metaFileManager.Config.ReplaceNonAsciiOnImport)); + foreach (var group in groups) + saveService.ImmediateSaveSync(new ModSaveGroup(group, metaFileManager.Config.ReplaceNonAsciiOnImport)); + } + + return defaultMod is not null || groups.Count > 0; + } + + public void DeleteDefaultValues() + => Changes = DeleteDefaultValues(metaFileManager, this); + + public void Apply(IModDataContainer container) + { + if (!Changes) + return; + + groupEditor.SetManipulations(container, this); + Changes = false; + } + + private static bool FilterDefaultValues(IEnumerable containers, MetaFileManager metaFileManager, + MultiDictionary defaultEntries, HashSet actualEntries) + { + if (!metaFileManager.CharacterUtility.Ready) + { + Penumbra.Log.Warning("Trying to filter default meta values before CharacterUtility was ready, skipped."); + return false; + } + + foreach (var container in containers) + { + foreach (var (key, value) in container.Manipulations.Imc) + { + var defaultEntry = ImcChecker.GetDefaultEntry(key, false); + if (defaultEntry.Entry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + + foreach (var (key, value) in container.Manipulations.Eqp) + { + var defaultEntry = new EqpEntryInternal(ExpandedEqpFile.GetDefault(metaFileManager, key.SetId), key.Slot); + if (defaultEntry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + + foreach (var (key, value) in container.Manipulations.Eqdp) + { + var defaultEntry = new EqdpEntryInternal(ExpandedEqdpFile.GetDefault(metaFileManager, key), key.Slot); + if (defaultEntry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + + foreach (var (key, value) in container.Manipulations.Est) + { + var defaultEntry = EstFile.GetDefault(metaFileManager, key); + if (defaultEntry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + + foreach (var (key, value) in container.Manipulations.Gmp) + { + var defaultEntry = ExpandedGmpFile.GetDefault(metaFileManager, key); + if (defaultEntry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + + foreach (var (key, value) in container.Manipulations.Rsp) + { + var defaultEntry = CmpFile.GetDefault(metaFileManager, key.SubRace, key.Attribute); + if (defaultEntry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + + foreach (var (key, value) in container.Manipulations.Atch) + { + var defaultEntry = AtchCache.GetDefault(metaFileManager, key); + if (defaultEntry.Equals(value)) + defaultEntries.TryAdd(key, container); + else + actualEntries.Add(key); + } + } + + return true; + } + + private static bool DeleteDefaultValues(MetaFileManager metaFileManager, MetaDictionary dict) { if (!metaFileManager.CharacterUtility.Ready) { Penumbra.Log.Warning("Trying to delete default meta values before CharacterUtility was ready, skipped."); return false; } + var clone = dict.Clone(); dict.ClearForDefault(); @@ -189,16 +337,4 @@ public class ModMetaEditor( Penumbra.Log.Debug($"Deleted {count} default-valued meta-entries from a mod option."); return true; } - - public void DeleteDefaultValues() - => Changes = DeleteDefaultValues(metaFileManager, this); - - public void Apply(IModDataContainer container) - { - if (!Changes) - return; - - groupEditor.SetManipulations(container, this); - Changes = false; - } } diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 3e58c515..8b5b80d0 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -2,6 +2,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using Penumbra.Api.Enums; +using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; @@ -82,9 +83,8 @@ public static partial class ModMigration foreach (var (gamePath, swapPath) in swaps) mod.Default.FileSwaps.Add(gamePath, swapPath); - creator.IncorporateMetaChanges(mod.Default, mod.ModPath, true, true); - foreach (var group in mod.Groups) - saveService.ImmediateSave(new ModSaveGroup(group, creator.Config.ReplaceNonAsciiOnImport)); + creator.IncorporateAllMetaChanges(mod, true, true); + saveService.SaveAllOptionGroups(mod, false, creator.Config.ReplaceNonAsciiOnImport); // Delete meta files. foreach (var file in seenMetaFiles.Where(f => f.Exists)) @@ -182,7 +182,7 @@ public static partial class ModMigration Description = option.OptionDesc, }; AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); - creator.IncorporateMetaChanges(subMod, mod.ModPath, false, true); + creator.IncorporateMetaChanges(subMod, mod.ModPath, false); return subMod; } @@ -196,7 +196,7 @@ public static partial class ModMigration Priority = priority, }; AddFilesToSubMod(subMod, mod.ModPath, option, seenMetaFiles); - creator.IncorporateMetaChanges(subMod, mod.ModPath, false, true); + creator.IncorporateMetaChanges(subMod, mod.ModPath, false); return subMod; } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 0db83ef9..f4f182eb 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -80,14 +80,10 @@ public partial class ModCreator( LoadDefaultOption(mod); LoadAllGroups(mod); if (incorporateMetaChanges) - IncorporateAllMetaChanges(mod, true); - if (deleteDefaultMetaChanges && !Config.KeepDefaultMetaChanges) - foreach (var container in mod.AllDataContainers) - { - if (ModMetaEditor.DeleteDefaultValues(metaFileManager, container.Manipulations)) - saveService.ImmediateSaveSync(new ModSaveGroup(container, Config.ReplaceNonAsciiOnImport)); - } - + IncorporateAllMetaChanges(mod, true, deleteDefaultMetaChanges); + else if (deleteDefaultMetaChanges) + ModMetaEditor.DeleteDefaultValues(mod, metaFileManager, saveService, false); + return true; } @@ -158,19 +154,21 @@ public partial class ModCreator( /// Convert all .meta and .rgsp files to their respective meta changes and add them to their options. /// Deletes the source files if delete is true. /// - public void IncorporateAllMetaChanges(Mod mod, bool delete) + public void IncorporateAllMetaChanges(Mod mod, bool delete, bool removeDefaultValues) { var changes = false; - List deleteList = new(); + List deleteList = []; foreach (var subMod in mod.AllDataContainers) { - var (localChanges, localDeleteList) = IncorporateMetaChanges(subMod, mod.ModPath, false, true); + var (localChanges, localDeleteList) = IncorporateMetaChanges(subMod, mod.ModPath, false); changes |= localChanges; if (delete) deleteList.AddRange(localDeleteList); } DeleteDeleteList(deleteList, delete); + if (removeDefaultValues && !Config.KeepDefaultMetaChanges) + changes |= ModMetaEditor.DeleteDefaultValues(mod, metaFileManager, null, false); if (!changes) return; @@ -184,8 +182,7 @@ public partial class ModCreator( /// If .meta or .rgsp files are encountered, parse them and incorporate their meta changes into the mod. /// If delete is true, the files are deleted afterwards. /// - public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete, - bool deleteDefault) + public (bool Changes, List DeleteList) IncorporateMetaChanges(IModDataContainer option, DirectoryInfo basePath, bool delete) { var deleteList = new List(); var oldSize = option.Manipulations.Count; @@ -202,8 +199,7 @@ public partial class ModCreator( if (!file.Exists) continue; - var meta = new TexToolsMeta(metaFileManager, gamePathParser, File.ReadAllBytes(file.FullName), - Config.KeepDefaultMetaChanges); + var meta = new TexToolsMeta(gamePathParser, File.ReadAllBytes(file.FullName)); Penumbra.Log.Verbose( $"Incorporating {file} as Metadata file of {meta.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); @@ -215,8 +211,7 @@ public partial class ModCreator( if (!file.Exists) continue; - var rgsp = TexToolsMeta.FromRgspFile(metaFileManager, file.FullName, File.ReadAllBytes(file.FullName), - Config.KeepDefaultMetaChanges); + var rgsp = TexToolsMeta.FromRgspFile(metaFileManager, file.FullName, File.ReadAllBytes(file.FullName)); Penumbra.Log.Verbose( $"Incorporating {file} as racial scaling file of {rgsp.MetaManipulations.Count} manipulations {deleteString}"); deleteList.Add(file.FullName); @@ -232,9 +227,6 @@ public partial class ModCreator( DeleteDeleteList(deleteList, delete); var changes = oldSize < option.Manipulations.Count; - if (deleteDefault && !Config.KeepDefaultMetaChanges) - changes |= ModMetaEditor.DeleteDefaultValues(metaFileManager, option.Manipulations); - return (changes, deleteList); } @@ -289,7 +281,7 @@ public partial class ModCreator( foreach (var (_, gamePath, file) in list) mod.Files.TryAdd(gamePath, file); - IncorporateMetaChanges(mod, baseFolder, true, true); + IncorporateMetaChanges(mod, baseFolder, true); return mod; } @@ -308,7 +300,7 @@ public partial class ModCreator( mod.Default.Files.TryAdd(gamePath, file); } - IncorporateMetaChanges(mod.Default, directory, true, true); + IncorporateMetaChanges(mod.Default, directory, true); saveService.ImmediateSaveSync(new ModSaveGroup(mod.ModPath, mod.Default, Config.ReplaceNonAsciiOnImport)); } From 129156a1c195f0cbce0c5bc464b4d6c8402d0ea1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 9 Apr 2025 15:04:47 +0200 Subject: [PATCH 1186/1381] Add some more safety and better IPC for draw object storage. --- Penumbra.Api | 2 +- Penumbra/Api/Api/GameStateApi.cs | 28 ++++++++++- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/IpcProviders.cs | 2 + .../PathResolving/CollectionResolver.cs | 9 ++-- .../Interop/PathResolving/DrawObjectState.cs | 50 ++++++++++++------- Penumbra/Penumbra.cs | 3 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 38 +++++++------- 8 files changed, 89 insertions(+), 45 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index bd56d828..47bd5424 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit bd56d82816b8366e19dddfb2dc7fd7f167e264ee +Subproject commit 47bd5424d04c667d0df1ac1dd1eeb3e50b476c2c diff --git a/Penumbra/Api/Api/GameStateApi.cs b/Penumbra/Api/Api/GameStateApi.cs index 7f70c6bf..74cde3a0 100644 --- a/Penumbra/Api/Api/GameStateApi.cs +++ b/Penumbra/Api/Api/GameStateApi.cs @@ -14,16 +14,18 @@ public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable { private readonly CommunicatorService _communicator; private readonly CollectionResolver _collectionResolver; + private readonly DrawObjectState _drawObjectState; private readonly CutsceneService _cutsceneService; private readonly ResourceLoader _resourceLoader; public unsafe GameStateApi(CommunicatorService communicator, CollectionResolver collectionResolver, CutsceneService cutsceneService, - ResourceLoader resourceLoader) + ResourceLoader resourceLoader, DrawObjectState drawObjectState) { _communicator = communicator; _collectionResolver = collectionResolver; _cutsceneService = cutsceneService; _resourceLoader = resourceLoader; + _drawObjectState = drawObjectState; _resourceLoader.ResourceLoaded += OnResourceLoaded; _resourceLoader.PapRequested += OnPapRequested; _communicator.CreatedCharacterBase.Subscribe(OnCreatedCharacterBase, Communication.CreatedCharacterBase.Priority.Api); @@ -67,6 +69,30 @@ public class GameStateApi : IPenumbraApiGameState, IApiService, IDisposable public int GetCutsceneParentIndex(int actorIdx) => _cutsceneService.GetParentIndex(actorIdx); + public Func GetCutsceneParentIndexFunc() + { + var weakRef = new WeakReference(_cutsceneService); + return idx => + { + if (!weakRef.TryGetTarget(out var c)) + throw new ObjectDisposedException("The underlying cutscene state storage of this IPC container was disposed."); + + return c.GetParentIndex(idx); + }; + } + + public Func GetGameObjectFromDrawObjectFunc() + { + var weakRef = new WeakReference(_drawObjectState); + return model => + { + if (!weakRef.TryGetTarget(out var c)) + throw new ObjectDisposedException("The underlying draw object state storage of this IPC container was disposed."); + + return c.TryGetValue(model, out var data) ? data.Item1.Address : nint.Zero; + }; + } + public PenumbraApiEc SetCutsceneParentIndex(int copyIdx, int newParentIdx) => _cutsceneService.SetParentIndex(copyIdx, newParentIdx) ? PenumbraApiEc.Success diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 47d44cfc..38125627 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -17,7 +17,7 @@ public class PenumbraApi( UiApi ui) : IDisposable, IApiService, IPenumbraApi { public const int BreakingVersion = 5; - public const int FeatureVersion = 8; + public const int FeatureVersion = 9; public void Dispose() { diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index d54faa6c..f5a6c16d 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -40,6 +40,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.CreatingCharacterBase.Provider(pi, api.GameState), IpcSubscribers.CreatedCharacterBase.Provider(pi, api.GameState), IpcSubscribers.GameObjectResourcePathResolved.Provider(pi, api.GameState), + IpcSubscribers.GetCutsceneParentIndexFunc.Provider(pi, api.GameState), + IpcSubscribers.GetGameObjectFromDrawObjectFunc.Provider(pi, api.GameState), IpcSubscribers.GetPlayerMetaManipulations.Provider(pi, api.Meta), IpcSubscribers.GetMetaManipulations.Provider(pi, api.Meta), diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index f14abbff..02e1be54 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -89,10 +89,13 @@ public sealed unsafe class CollectionResolver( /// Identify the correct collection for a draw object. public ResolveData IdentifyCollection(DrawObject* drawObject, bool useCache) { - var obj = (GameObject*)(drawObjectState.TryGetValue((nint)drawObject, out var gameObject) + if (drawObject is null) + return DefaultCollection; + + Actor obj = drawObjectState.TryGetValue(drawObject, out var gameObject) ? gameObject.Item1 - : drawObjectState.LastGameObject); - return IdentifyCollection(obj, useCache); + : drawObjectState.LastGameObject; + return IdentifyCollection(obj.AsObject, useCache); } /// Get the default collection. diff --git a/Penumbra/Interop/PathResolving/DrawObjectState.cs b/Penumbra/Interop/PathResolving/DrawObjectState.cs index 28a0dd8d..6f3e457c 100644 --- a/Penumbra/Interop/PathResolving/DrawObjectState.cs +++ b/Penumbra/Interop/PathResolving/DrawObjectState.cs @@ -9,7 +9,7 @@ using Penumbra.Interop.Hooks.Objects; namespace Penumbra.Interop.PathResolving; -public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary, IService +public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary, IService { private readonly ObjectManager _objects; private readonly CreateCharacterBase _createCharacterBase; @@ -18,7 +18,7 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _drawObjectToGameObject = []; + private readonly Dictionary _drawObjectToGameObject = []; public nint LastGameObject => _gameState.LastGameObject; @@ -41,11 +41,10 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _drawObjectToGameObject.ContainsKey(key); - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() => _drawObjectToGameObject.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() @@ -54,16 +53,28 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary _drawObjectToGameObject.Count; - public bool TryGetValue(nint drawObject, out (nint, bool) gameObject) - => _drawObjectToGameObject.TryGetValue(drawObject, out gameObject); + public bool TryGetValue(Model drawObject, out (Actor, ObjectIndex, bool) gameObject) + { + if (!_drawObjectToGameObject.TryGetValue(drawObject, out gameObject)) + return false; - public (nint, bool) this[nint key] + var currentObject = _objects[gameObject.Item2]; + if (currentObject != gameObject.Item1) + { + Penumbra.Log.Warning($"[DrawObjectState] Stored association {drawObject} -> {gameObject.Item1} has index {gameObject.Item2}, which resolves to {currentObject}."); + return false; + } + + return true; + } + + public (Actor, ObjectIndex, bool) this[Model key] => _drawObjectToGameObject[key]; - public IEnumerable Keys + public IEnumerable Keys => _drawObjectToGameObject.Keys; - public IEnumerable<(nint, bool)> Values + public IEnumerable<(Actor, ObjectIndex, bool)> Values => _drawObjectToGameObject.Values; public unsafe void Dispose() @@ -87,20 +98,21 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary 0x{(nint)a:X} (actual: 0x{pair.GameObject:X}, {pair.IsChild})."); + Penumbra.Log.Excessive( + $"[DrawObjectState] Removed draw object 0x{*ptr:X} -> 0x{(nint)a:X} (actual: 0x{pair.GameObject.Address:X}, {pair.IsChild})."); } } @@ -119,9 +131,9 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionary @@ -137,12 +149,12 @@ public sealed class DrawObjectState : IDisposable, IReadOnlyDictionaryChildObject, gameObject, true, true); if (!iterate) return; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 79c7f2db..7f4c1b23 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -21,7 +21,6 @@ using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManage using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; using Penumbra.GameData.Data; -using Penumbra.GameData.Files; using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; @@ -190,7 +189,7 @@ public class Penumbra : IDalamudPlugin ReadOnlySpan relevantPlugins = [ "Glamourer", "MareSynchronos", "CustomizePlus", "SimpleHeels", "VfxEditor", "heliosphere-plugin", "Ktisis", "Brio", "DynamicBridge", - "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", "RoleplayingVoiceDalamud", "AQuestReborn", + "IllusioVitae", "Aetherment", "LoporritSync", "GagSpeak", "ProjectGagSpeak", "RoleplayingVoiceDalamud", "AQuestReborn", ]; var plugins = _services.GetService().InstalledPlugins .GroupBy(p => p.InternalName) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 6629c126..9dd18ddd 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -569,29 +569,31 @@ public class DebugTab : Window, ITab, IUiService { if (drawTree) { - using var table = Table("###DrawObjectResolverTable", 6, ImGuiTableFlags.SizingFixedFit); + using var table = Table("###DrawObjectResolverTable", 8, ImGuiTableFlags.SizingFixedFit); if (table) - foreach (var (drawObject, (gameObjectPtr, child)) in _drawObjectState - .OrderBy(kvp => ((GameObject*)kvp.Value.Item1)->ObjectIndex) - .ThenBy(kvp => kvp.Value.Item2) - .ThenBy(kvp => kvp.Key)) + foreach (var (drawObject, (gameObjectPtr, idx, child)) in _drawObjectState + .OrderBy(kvp => kvp.Value.Item2.Index) + .ThenBy(kvp => kvp.Value.Item3) + .ThenBy(kvp => kvp.Key.Address)) { - var gameObject = (GameObject*)gameObjectPtr; ImGui.TableNextColumn(); + ImUtf8.CopyOnClickSelectable($"{drawObject}"); + ImUtf8.DrawTableColumn($"{gameObjectPtr.Index}"); + using (ImRaii.PushColor(ImGuiCol.Text, 0xFF0000FF, gameObjectPtr.Index != idx)) + { + ImUtf8.DrawTableColumn($"{idx}"); + } - ImGuiUtil.CopyOnClickSelectable($"0x{drawObject:X}"); + ImUtf8.DrawTableColumn(child ? "Child"u8 : "Main"u8); ImGui.TableNextColumn(); - ImGui.TextUnformatted(gameObject->ObjectIndex.ToString()); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(child ? "Child" : "Main"); - ImGui.TableNextColumn(); - var (address, name) = ($"0x{gameObjectPtr:X}", new ByteString(gameObject->Name).ToString()); - ImGuiUtil.CopyOnClickSelectable(address); - ImGui.TableNextColumn(); - ImGui.TextUnformatted(name); - ImGui.TableNextColumn(); - var collection = _collectionResolver.IdentifyCollection(gameObject, true); - ImGui.TextUnformatted(collection.ModCollection.Identity.Name); + ImUtf8.CopyOnClickSelectable($"{gameObjectPtr}"); + using (ImRaii.PushColor(ImGuiCol.Text, 0xFF0000FF, _objects[idx] != gameObjectPtr)) + { + ImUtf8.DrawTableColumn($"{_objects[idx]}"); + } + ImUtf8.DrawTableColumn(gameObjectPtr.Utf8Name.Span); + var collection = _collectionResolver.IdentifyCollection(gameObjectPtr.AsObject, true); + ImUtf8.DrawTableColumn(collection.ModCollection.Identity.Name); } } } From 0ec6a17ac7c83c350f90fb6856c548f091b67f34 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Apr 2025 00:02:21 +0200 Subject: [PATCH 1187/1381] Add context to open backup directory. --- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 1ccee2cb..1e6afa09 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -121,32 +121,42 @@ public class ModPanelEditTab( : backup.Exists ? $"Overwrite current exported mod \"{backup.Name}\" with current mod." : $"Create exported archive of current mod at \"{backup.Name}\"."; - if (ImGuiUtil.DrawDisabledButton("Export Mod", buttonSize, tt, ModBackup.CreatingBackup)) + if (ImUtf8.ButtonEx("Export Mod"u8, tt, buttonSize, ModBackup.CreatingBackup)) backup.CreateAsync(); + if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) + ImUtf8.OpenPopup("context"u8); + ImGui.SameLine(); tt = backup.Exists ? $"Delete existing mod export \"{backup.Name}\" (hold {config.DeleteModModifier} while clicking)." : $"Exported mod \"{backup.Name}\" does not exist."; - if (ImGuiUtil.DrawDisabledButton("Delete Export", buttonSize, tt, !backup.Exists || !config.DeleteModModifier.IsActive())) + if (ImUtf8.ButtonEx("Delete Export"u8, tt, buttonSize, !backup.Exists || !config.DeleteModModifier.IsActive())) backup.Delete(); tt = backup.Exists ? $"Restore mod from exported file \"{backup.Name}\" (hold {config.DeleteModModifier} while clicking)." : $"Exported mod \"{backup.Name}\" does not exist."; ImGui.SameLine(); - if (ImGuiUtil.DrawDisabledButton("Restore From Export", buttonSize, tt, !backup.Exists || !config.DeleteModModifier.IsActive())) + if (ImUtf8.ButtonEx("Restore From Export"u8, tt, buttonSize, !backup.Exists || !config.DeleteModModifier.IsActive())) backup.Restore(modManager); if (backup.Exists) { ImGui.SameLine(); - using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + using (ImRaii.PushFont(UiBuilder.IconFont)) { - ImGui.TextUnformatted(FontAwesomeIcon.CheckCircle.ToIconString()); + ImUtf8.Text(FontAwesomeIcon.CheckCircle.ToIconString()); } - ImGuiUtil.HoverTooltip($"Export exists in \"{backup.Name}\"."); + ImUtf8.HoverTooltip($"Export exists in \"{backup.Name}\"."); } + + using var context = ImUtf8.Popup("context"u8); + if (!context) + return; + + if (ImUtf8.Selectable("Open Backup Directory"u8)) + Process.Start(new ProcessStartInfo(modExportManager.ExportDirectory.FullName) { UseShellExecute = true }); } /// Anything about editing the regular meta information about the mod. From dc336569ff6d79a9ab08cbf40670c74aed3065a5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Apr 2025 00:02:36 +0200 Subject: [PATCH 1188/1381] Add context to copy the full file path from redirections. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 6792c359..071b0551 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -210,6 +210,9 @@ public partial class ModEditWindow if (!context) return; + if (ImUtf8.Selectable("Copy Full File Path")) + ImUtf8.SetClipboardText(registry.File.FullName); + using (ImRaii.Disabled(registry.CurrentUsage == 0)) { if (ImUtf8.Selectable("Copy Game Paths"u8)) @@ -244,10 +247,8 @@ public partial class ModEditWindow using (ImRaii.Disabled(_cutPaths.Count == 0)) { if (ImUtf8.Selectable("Paste Game Paths"u8)) - { foreach (var path in _cutPaths) _editor.FileEditor.SetGamePath(_editor.Option!, i, -1, path); - } } } From f9b5a626cfa2da3b245cc5d982662a3fec76795a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Apr 2025 00:02:49 +0200 Subject: [PATCH 1189/1381] Add some migration stuff. --- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Services/MigrationManager.cs | 67 +---- Penumbra/Services/ModMigrator.cs | 331 +++++++++++++++++++++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 9 +- Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs | 55 ++++ 6 files changed, 397 insertions(+), 69 deletions(-) create mode 100644 Penumbra/Services/ModMigrator.cs create mode 100644 Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs diff --git a/Penumbra.Api b/Penumbra.Api index 47bd5424..14652039 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 47bd5424d04c667d0df1ac1dd1eeb3e50b476c2c +Subproject commit 1465203967d08519c6716292bc5e5094c7fbcacc diff --git a/Penumbra.GameData b/Penumbra.GameData index 4769bbcd..e10d8f33 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 4769bbcdfce9e1d5a461c6b552b5b30ad6bc478e +Subproject commit e10d8f33a676ff4544d7ca05a93d555416f41222 diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index abc059e9..2438c0ad 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -1,76 +1,13 @@ using Dalamud.Interface.ImGuiNotification; using OtterGui.Classes; using OtterGui.Services; -using Penumbra.Api.Enums; -using Penumbra.GameData.Files; -using Penumbra.Mods; -using Penumbra.String.Classes; using SharpCompress.Common; using SharpCompress.Readers; +using MdlFile = Penumbra.GameData.Files.MdlFile; +using MtrlFile = Penumbra.GameData.Files.MtrlFile; namespace Penumbra.Services; -public class ModMigrator -{ - private class FileData(string path) - { - public readonly string Path = path; - public readonly List<(string GamePath, int Option)> GamePaths = []; - } - - private sealed class FileDataDict : Dictionary - { - public void Add(string path, string gamePath, int option) - { - if (!TryGetValue(path, out var data)) - { - data = new FileData(path); - data.GamePaths.Add((gamePath, option)); - Add(path, data); - } - else - { - data.GamePaths.Add((gamePath, option)); - } - } - } - - private readonly FileDataDict Textures = []; - private readonly FileDataDict Models = []; - private readonly FileDataDict Materials = []; - - public void Update(IEnumerable mods) - { - CollectFiles(mods); - } - - private void CollectFiles(IEnumerable mods) - { - var option = 0; - foreach (var mod in mods) - { - AddDict(mod.Default.Files, option++); - foreach (var container in mod.Groups.SelectMany(group => group.DataContainers)) - AddDict(container.Files, option++); - } - - return; - - void AddDict(Dictionary dict, int currentOption) - { - foreach (var (gamePath, file) in dict) - { - switch (ResourceTypeExtensions.FromExtension(gamePath.Extension().Span)) - { - case ResourceType.Tex: Textures.Add(file.FullName, gamePath.ToString(), currentOption); break; - case ResourceType.Mdl: Models.Add(file.FullName, gamePath.ToString(), currentOption); break; - case ResourceType.Mtrl: Materials.Add(file.FullName, gamePath.ToString(), currentOption); break; - } - } - } - } -} - public class MigrationManager(Configuration config) : IService { public enum TaskType : byte diff --git a/Penumbra/Services/ModMigrator.cs b/Penumbra/Services/ModMigrator.cs new file mode 100644 index 00000000..20005c8f --- /dev/null +++ b/Penumbra/Services/ModMigrator.cs @@ -0,0 +1,331 @@ +using Dalamud.Plugin.Services; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.GameData.Data; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Structs; +using Penumbra.Import.Textures; +using Penumbra.Mods; +using Penumbra.Mods.SubMods; + +namespace Penumbra.Services; + +public class ModMigrator(IDataManager gameData, TextureManager textures) : IService +{ + private sealed class FileDataDict : MultiDictionary; + + private readonly Lazy _glassReferenceMaterial = new(() => + { + var bytes = gameData.GetFile("chara/equipment/e5001/material/v0001/mt_c0101e5001_met_b.mtrl"); + return new MtrlFile(bytes!.Data); + }); + + private readonly HashSet _changedMods = []; + private readonly HashSet _failedMods = []; + + private readonly FileDataDict Textures = []; + private readonly FileDataDict Models = []; + private readonly FileDataDict Materials = []; + private readonly FileDataDict FileSwaps = []; + + private readonly ConcurrentBag _messages = []; + + public void Update(IEnumerable mods) + { + CollectFiles(mods); + foreach (var (from, (to, container)) in FileSwaps) + MigrateFileSwaps(from, to, container); + foreach (var (model, list) in Models.Grouped) + MigrateModel(model, (Mod)list[0].Container.Mod); + } + + private void CollectFiles(IEnumerable mods) + { + foreach (var mod in mods) + { + foreach (var container in mod.AllDataContainers) + { + foreach (var (gamePath, file) in container.Files) + { + switch (ResourceTypeExtensions.FromExtension(gamePath.Extension().Span)) + { + case ResourceType.Tex: Textures.TryAdd(file.FullName, (gamePath.ToString(), container)); break; + case ResourceType.Mdl: Models.TryAdd(file.FullName, (gamePath.ToString(), container)); break; + case ResourceType.Mtrl: Materials.TryAdd(file.FullName, (gamePath.ToString(), container)); break; + } + } + + foreach (var (swapFrom, swapTo) in container.FileSwaps) + FileSwaps.TryAdd(swapTo.FullName, (swapFrom.ToString(), container)); + } + } + } + + public Task CreateIndexFile(string normalPath, string targetPath) + { + const int rowBlend = 17; + + return Task.Run(async () => + { + var tex = textures.LoadTex(normalPath); + var data = tex.GetPixelData(); + var rgbaData = new RgbaPixelData(data.Width, data.Height, data.Rgba); + if (!BitOperations.IsPow2(rgbaData.Height) || !BitOperations.IsPow2(rgbaData.Width)) + { + var requiredHeight = (int)BitOperations.RoundUpToPowerOf2((uint)rgbaData.Height); + var requiredWidth = (int)BitOperations.RoundUpToPowerOf2((uint)rgbaData.Width); + rgbaData = rgbaData.Resize((requiredWidth, requiredHeight)); + } + + Parallel.ForEach(Enumerable.Range(0, rgbaData.PixelData.Length / 4), idx => + { + var pixelIdx = 4 * idx; + var normal = rgbaData.PixelData[pixelIdx + 3]; + + // Copied from TT + var blendRem = normal % (2 * rowBlend); + var originalRow = normal / rowBlend; + switch (blendRem) + { + // Goes to next row, clamped to the closer row. + case > 25: + blendRem = 0; + ++originalRow; + break; + // Stays in this row, clamped to the closer row. + case > 17: blendRem = 17; break; + } + + var newBlend = (byte)(255 - MathF.Round(blendRem / 17f * 255f)); + + // Slight add here to push the color deeper into the row to ensure BC5 compression doesn't + // cause any artifacting. + var newRow = (byte)(originalRow / 2 * 17 + 4); + + rgbaData.PixelData[pixelIdx] = newRow; + rgbaData.PixelData[pixelIdx] = newBlend; + rgbaData.PixelData[pixelIdx] = 0; + rgbaData.PixelData[pixelIdx] = 255; + }); + await textures.SaveAs(CombinedTexture.TextureSaveType.BC5, true, true, new BaseImage(), targetPath, rgbaData.PixelData, + rgbaData.Width, rgbaData.Height); + }); + } + + private void MigrateModel(string filePath, Mod mod) + { + if (MigrationManager.TryMigrateSingleModel(filePath, true)) + { + _messages.Add($"Migrated model {filePath} in {mod.Name}."); + } + else + { + _messages.Add($"Failed to migrate model {filePath} in {mod.Name}"); + _failedMods.Add(mod); + } + } + + private void SetGlassReferenceValues(MtrlFile mtrl) + { + var reference = _glassReferenceMaterial.Value; + mtrl.ShaderPackage.ShaderKeys = reference.ShaderPackage.ShaderKeys.ToArray(); + mtrl.ShaderPackage.Constants = reference.ShaderPackage.Constants.ToArray(); + mtrl.AdditionalData = reference.AdditionalData.ToArray(); + mtrl.ShaderPackage.Flags &= ~(0x04u | 0x08u); + // From TT. + if (mtrl.Table is ColorTable t) + foreach (ref var row in t.AsRows()) + row.SpecularColor = new HalfColor((Half)0.8100586, (Half)0.8100586, (Half)0.8100586); + } + + private ref struct MaterialPack + { + public readonly MtrlFile File; + public readonly bool UsesMaskAsSpecular; + + private readonly Dictionary Samplers = []; + + public MaterialPack(MtrlFile file) + { + File = file; + UsesMaskAsSpecular = File.ShaderPackage.ShaderKeys.Any(x => x.Key is 0xC8BD1DEF && x.Value is 0xA02F4828 or 0x198D11CD); + Add(Samplers, TextureUsage.Normal, ShpkFile.NormalSamplerId); + Add(Samplers, TextureUsage.Index, ShpkFile.IndexSamplerId); + Add(Samplers, TextureUsage.Mask, ShpkFile.MaskSamplerId); + Add(Samplers, TextureUsage.Diffuse, ShpkFile.DiffuseSamplerId); + Add(Samplers, TextureUsage.Specular, ShpkFile.SpecularSamplerId); + return; + + void Add(Dictionary dict, TextureUsage usage, uint samplerId) + { + var idx = new SamplerIndex(file, samplerId); + if (idx.Texture >= 0) + dict.Add(usage, idx); + } + } + + public readonly record struct SamplerIndex(int Sampler, int Texture) + { + public SamplerIndex(MtrlFile file, uint samplerId) + : this(file.FindSampler(samplerId), -1) + => Texture = Sampler < 0 ? -1 : file.ShaderPackage.Samplers[Sampler].TextureIndex; + } + + public enum TextureUsage + { + Normal, + Index, + Mask, + Diffuse, + Specular, + } + + public static bool AdaptPath(IDataManager data, string path, TextureUsage usage, out string newPath) + { + newPath = path; + if (Path.GetExtension(newPath) is not ".tex") + return false; + + if (data.FileExists(newPath)) + return true; + + switch (usage) + { + case TextureUsage.Normal: + newPath = path.Replace("_n.tex", "_norm.tex"); + if (data.FileExists(newPath)) + return true; + + newPath = path.Replace("_n_", "_norm_"); + if (data.FileExists(newPath)) + return true; + + return false; + case TextureUsage.Index: return false; + case TextureUsage.Mask: + newPath = path.Replace("_m.tex", "_mult.tex"); + if (data.FileExists(newPath)) + return true; + + newPath = path.Replace("_m.tex", "_mask.tex"); + if (data.FileExists(newPath)) + return true; + + newPath = path.Replace("_m_", "_mult_"); + if (data.FileExists(newPath)) + return true; + + newPath = path.Replace("_m_", "_mask_"); + if (data.FileExists(newPath)) + return true; + + return false; + case TextureUsage.Diffuse: + newPath = path.Replace("_d.tex", "_base.tex"); + if (data.FileExists(newPath)) + return true; + + newPath = path.Replace("_d_", "_base_"); + if (data.FileExists(newPath)) + return true; + + return false; + case TextureUsage.Specular: + return false; + default: throw new ArgumentOutOfRangeException(nameof(usage), usage, null); + } + } + } + + private void MigrateMaterial(string filePath, IReadOnlyList<(string GamePath, IModDataContainer Container)> redirections) + { + try + { + var bytes = File.ReadAllBytes(filePath); + var mtrl = new MtrlFile(bytes); + if (!CheckUpdateNeeded(mtrl)) + return; + + // Update colorsets, flags and character shader package. + var changes = mtrl.MigrateToDawntrail(); + + if (!changes) + switch (mtrl.ShaderPackage.Name) + { + case "hair.shpk": break; + case "characterglass.shpk": + SetGlassReferenceValues(mtrl); + changes = true; + break; + } + + // Remove DX11 flags and update paths if necessary. + foreach (ref var tex in mtrl.Textures.AsSpan()) + { + if (tex.DX11) + { + changes = true; + if (GamePaths.Tex.HandleDx11Path(tex, out var newPath)) + tex.Path = newPath; + tex.DX11 = false; + } + + if (gameData.FileExists(tex.Path)) + continue; + } + + // Dyeing, from TT. + if (mtrl.DyeTable is ColorDyeTable dye) + foreach (ref var row in dye.AsRows()) + row.Template += 1000; + } + catch + { + // ignored + } + + static bool CheckUpdateNeeded(MtrlFile mtrl) + { + if (!mtrl.IsDawntrail) + return true; + + if (mtrl.ShaderPackage.Name is not "hair.shpk") + return false; + + var foundOld = 0; + foreach (var c in mtrl.ShaderPackage.Constants) + { + switch (c.Id) + { + case 0x36080AD0: foundOld |= 1; break; // == 1, from TT + case 0x992869AB: foundOld |= 2; break; // == 3 (skin) or 4 (hair) from TT + } + + if (foundOld is 3) + return true; + } + + return false; + } + } + + private void MigrateFileSwaps(string swapFrom, string swapTo, IModDataContainer container) + { + var fromExists = gameData.FileExists(swapFrom); + var toExists = gameData.FileExists(swapTo); + if (fromExists && toExists) + return; + + if (ResourceTypeExtensions.FromExtension(Path.GetExtension(swapFrom.AsSpan())) is not ResourceType.Tex + || ResourceTypeExtensions.FromExtension(Path.GetExtension(swapTo.AsSpan())) is not ResourceType.Tex) + { + _messages.Add( + $"Could not migrate file swap {swapFrom} -> {swapTo} in {container.Mod.Name}: {container.GetFullName()}. Only textures may be migrated.{(fromExists ? "\n\tSource File does not exist." : "")}{(toExists ? "\n\tTarget File does not exist." : "")}"); + return; + } + + // try to migrate texture swaps + } +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 9dd18ddd..6d6222ec 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -106,6 +106,7 @@ public class DebugTab : Window, ITab, IUiService private readonly SchedulerResourceManagementService _schedulerService; private readonly ObjectIdentification _objectIdentification; private readonly RenderTargetDrawer _renderTargetDrawer; + private readonly ModMigratorDebug _modMigratorDebug; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -116,7 +117,8 @@ public class DebugTab : Window, ITab, IUiService TextureManager textureManager, ShaderReplacementFixer shaderReplacementFixer, RedrawService redraws, DictEmote emotes, Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer, - SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification, RenderTargetDrawer renderTargetDrawer) + SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification, RenderTargetDrawer renderTargetDrawer, + ModMigratorDebug modMigratorDebug) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -158,6 +160,7 @@ public class DebugTab : Window, ITab, IUiService _schedulerService = schedulerService; _objectIdentification = objectIdentification; _renderTargetDrawer = renderTargetDrawer; + _modMigratorDebug = modMigratorDebug; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -190,6 +193,7 @@ public class DebugTab : Window, ITab, IUiService DrawActorsDebug(); DrawCollectionCaches(); _texHeaderDrawer.Draw(); + _modMigratorDebug.Draw(); DrawShaderReplacementFixer(); DrawData(); DrawCrcCache(); @@ -591,6 +595,7 @@ public class DebugTab : Window, ITab, IUiService { ImUtf8.DrawTableColumn($"{_objects[idx]}"); } + ImUtf8.DrawTableColumn(gameObjectPtr.Utf8Name.Span); var collection = _collectionResolver.IdentifyCollection(gameObjectPtr.AsObject, true); ImUtf8.DrawTableColumn(collection.ModCollection.Identity.Name); @@ -751,7 +756,7 @@ public class DebugTab : Window, ITab, IUiService DrawChangedItemTest(); } - private string _changedItemPath = string.Empty; + private string _changedItemPath = string.Empty; private readonly Dictionary _changedItems = []; private void DrawChangedItemTest() diff --git a/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs b/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs new file mode 100644 index 00000000..c8518315 --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs @@ -0,0 +1,55 @@ +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Services; + +namespace Penumbra.UI.Tabs.Debug; + +public class ModMigratorDebug(ModMigrator migrator) : IUiService +{ + private string _inputPath = string.Empty; + private string _outputPath = string.Empty; + private Task? _indexTask; + private Task? _mdlTask; + + public void Draw() + { + if (!ImUtf8.CollapsingHeaderId("Mod Migrator"u8)) + return; + + ImUtf8.InputText("##input"u8, ref _inputPath, "Input Path..."u8); + ImUtf8.InputText("##output"u8, ref _outputPath, "Output Path..."u8); + + if (ImUtf8.ButtonEx("Create Index Texture"u8, "Requires input to be a path to a normal texture."u8, default, _inputPath.Length == 0 + || _outputPath.Length == 0 + || _indexTask is + { + IsCompleted: false, + })) + _indexTask = migrator.CreateIndexFile(_inputPath, _outputPath); + + if (_indexTask is not null) + { + ImGui.SameLine(); + ImUtf8.TextFrameAligned($"{_indexTask.Status}"); + } + + if (ImUtf8.ButtonEx("Update Model File"u8, "Requires input to be a path to a mdl."u8, default, _inputPath.Length == 0 + || _outputPath.Length == 0 + || _mdlTask is + { + IsCompleted: false, + })) + _mdlTask = Task.Run(() => + { + File.Copy(_inputPath, _outputPath, true); + MigrationManager.TryMigrateSingleModel(_outputPath, false); + }); + + if (_mdlTask is not null) + { + ImGui.SameLine(); + ImUtf8.TextFrameAligned($"{_mdlTask.Status}"); + } + } +} From f03a139e0e32acf0e35fff61cecd078f0ef72335 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Apr 2025 00:17:23 +0200 Subject: [PATCH 1190/1381] blech --- Penumbra/Services/ModMigrator.cs | 136 +++++++++++++++++-------------- 1 file changed, 77 insertions(+), 59 deletions(-) diff --git a/Penumbra/Services/ModMigrator.cs b/Penumbra/Services/ModMigrator.cs index 20005c8f..043d9631 100644 --- a/Penumbra/Services/ModMigrator.cs +++ b/Penumbra/Services/ModMigrator.cs @@ -1,17 +1,18 @@ -using Dalamud.Plugin.Services; -using OtterGui.Classes; -using OtterGui.Services; -using Penumbra.Api.Enums; -using Penumbra.GameData.Data; -using Penumbra.GameData.Files; -using Penumbra.GameData.Files.MaterialStructs; -using Penumbra.GameData.Structs; -using Penumbra.Import.Textures; -using Penumbra.Mods; -using Penumbra.Mods.SubMods; - -namespace Penumbra.Services; - +using Dalamud.Plugin.Services; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.Api.Enums; +using Penumbra.GameData.Data; +using Penumbra.GameData.Files; +using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.GameData.Structs; +using Penumbra.Import.Textures; +using Penumbra.Mods; +using Penumbra.Mods.SubMods; +using Penumbra.String.Classes; + +namespace Penumbra.Services; + public class ModMigrator(IDataManager gameData, TextureManager textures) : IService { private sealed class FileDataDict : MultiDictionary; @@ -175,6 +176,7 @@ public class ModMigrator(IDataManager gameData, TextureManager textures) : IServ public enum TextureUsage { + Unknown, Normal, Index, Mask, @@ -191,51 +193,44 @@ public class ModMigrator(IDataManager gameData, TextureManager textures) : IServ if (data.FileExists(newPath)) return true; - switch (usage) + ReadOnlySpan<(string, string)> pairs = usage switch { - case TextureUsage.Normal: - newPath = path.Replace("_n.tex", "_norm.tex"); - if (data.FileExists(newPath)) - return true; - - newPath = path.Replace("_n_", "_norm_"); - if (data.FileExists(newPath)) - return true; - - return false; - case TextureUsage.Index: return false; - case TextureUsage.Mask: - newPath = path.Replace("_m.tex", "_mult.tex"); - if (data.FileExists(newPath)) - return true; - - newPath = path.Replace("_m.tex", "_mask.tex"); - if (data.FileExists(newPath)) - return true; - - newPath = path.Replace("_m_", "_mult_"); - if (data.FileExists(newPath)) - return true; - - newPath = path.Replace("_m_", "_mask_"); - if (data.FileExists(newPath)) - return true; - - return false; - case TextureUsage.Diffuse: - newPath = path.Replace("_d.tex", "_base.tex"); - if (data.FileExists(newPath)) - return true; - - newPath = path.Replace("_d_", "_base_"); - if (data.FileExists(newPath)) - return true; - - return false; - case TextureUsage.Specular: - return false; - default: throw new ArgumentOutOfRangeException(nameof(usage), usage, null); + TextureUsage.Unknown => + [ + ("_n.tex", "_norm.tex"), + ("_m.tex", "_mult.tex"), + ("_m.tex", "_mask.tex"), + ("_d.tex", "_base.tex"), + ], + TextureUsage.Normal => + [ + ("_n_", "_norm_"), + ("_n.tex", "_norm.tex"), + ], + TextureUsage.Mask => + [ + ("_m_", "_mult_"), + ("_m_", "_mask_"), + ("_m.tex", "_mult.tex"), + ("_m.tex", "_mask.tex"), + ], + TextureUsage.Diffuse => + [ + ("_d_", "_base_"), + ("_d.tex", "_base.tex"), + ], + TextureUsage.Index => [], + TextureUsage.Specular => [], + _ => [], + }; + foreach (var (from, to) in pairs) + { + newPath = path.Replace(from, to); + if (data.FileExists(newPath)) + return true; } + + return false; } } @@ -326,6 +321,29 @@ public class ModMigrator(IDataManager gameData, TextureManager textures) : IServ return; } - // try to migrate texture swaps + var newSwapFrom = swapFrom; + if (!fromExists && !MaterialPack.AdaptPath(gameData, swapFrom, MaterialPack.TextureUsage.Unknown, out newSwapFrom)) + { + _messages.Add($"Could not migrate file swap {swapFrom} -> {swapTo} in {container.Mod.Name}: {container.GetFullName()}."); + return; + } + + var newSwapTo = swapTo; + if (!toExists && !MaterialPack.AdaptPath(gameData, swapTo, MaterialPack.TextureUsage.Unknown, out newSwapTo)) + { + _messages.Add($"Could not migrate file swap {swapFrom} -> {swapTo} in {container.Mod.Name}: {container.GetFullName()}."); + return; + } + + if (!Utf8GamePath.FromString(swapFrom, out var path) || !Utf8GamePath.FromString(newSwapFrom, out var newPath)) + { + _messages.Add( + $"Could not migrate file swap {swapFrom} -> {swapTo} in {container.Mod.Name}: {container.GetFullName()}. Unknown Error."); + return; + } + + container.FileSwaps.Remove(path); + container.FileSwaps.Add(newPath, new FullPath(newSwapTo)); + _changedMods.Add((Mod)container.Mod); } -} +} From 2bd0c895887a33c6161a743e40a0f063b5a9183f Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 10 Apr 2025 16:04:49 +0200 Subject: [PATCH 1191/1381] Better item sort for item swap selectors. --- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 52 ++++++++++++++--------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index cb56de08..f5d2a8c7 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -4,6 +4,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections; @@ -15,6 +16,7 @@ using Penumbra.GameData.Structs; using Penumbra.Import.Structs; using Penumbra.Meta; using Penumbra.Mods; +using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; using Penumbra.Mods.ItemSwap; using Penumbra.Mods.Manager; @@ -46,19 +48,20 @@ public class ItemSwapTab : IDisposable, ITab, IUiService _config = config; _swapData = new ItemSwapContainer(metaFileManager, identifier); + var a = collectionManager.Active; _selectors = new Dictionary { // @formatter:off - [SwapType.Hat] = (new ItemSelector(itemService, selector, FullEquipType.Head), new ItemSelector(itemService, null, FullEquipType.Head), "Take this Hat", "and put it on this one" ), - [SwapType.Top] = (new ItemSelector(itemService, selector, FullEquipType.Body), new ItemSelector(itemService, null, FullEquipType.Body), "Take this Top", "and put it on this one" ), - [SwapType.Gloves] = (new ItemSelector(itemService, selector, FullEquipType.Hands), new ItemSelector(itemService, null, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), - [SwapType.Pants] = (new ItemSelector(itemService, selector, FullEquipType.Legs), new ItemSelector(itemService, null, FullEquipType.Legs), "Take these Pants", "and put them on these" ), - [SwapType.Shoes] = (new ItemSelector(itemService, selector, FullEquipType.Feet), new ItemSelector(itemService, null, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), - [SwapType.Earrings] = (new ItemSelector(itemService, selector, FullEquipType.Ears), new ItemSelector(itemService, null, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), - [SwapType.Necklace] = (new ItemSelector(itemService, selector, FullEquipType.Neck), new ItemSelector(itemService, null, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), - [SwapType.Bracelet] = (new ItemSelector(itemService, selector, FullEquipType.Wrists), new ItemSelector(itemService, null, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), - [SwapType.Ring] = (new ItemSelector(itemService, selector, FullEquipType.Finger), new ItemSelector(itemService, null, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), - [SwapType.Glasses] = (new ItemSelector(itemService, selector, FullEquipType.Glasses), new ItemSelector(itemService, null, FullEquipType.Glasses), "Take these Glasses", "and put them on these" ), + [SwapType.Hat] = (new ItemSelector(a, itemService, selector, FullEquipType.Head), new ItemSelector(a, itemService, null, FullEquipType.Head), "Take this Hat", "and put it on this one" ), + [SwapType.Top] = (new ItemSelector(a, itemService, selector, FullEquipType.Body), new ItemSelector(a, itemService, null, FullEquipType.Body), "Take this Top", "and put it on this one" ), + [SwapType.Gloves] = (new ItemSelector(a, itemService, selector, FullEquipType.Hands), new ItemSelector(a, itemService, null, FullEquipType.Hands), "Take these Gloves", "and put them on these" ), + [SwapType.Pants] = (new ItemSelector(a, itemService, selector, FullEquipType.Legs), new ItemSelector(a, itemService, null, FullEquipType.Legs), "Take these Pants", "and put them on these" ), + [SwapType.Shoes] = (new ItemSelector(a, itemService, selector, FullEquipType.Feet), new ItemSelector(a, itemService, null, FullEquipType.Feet), "Take these Shoes", "and put them on these" ), + [SwapType.Earrings] = (new ItemSelector(a, itemService, selector, FullEquipType.Ears), new ItemSelector(a, itemService, null, FullEquipType.Ears), "Take these Earrings", "and put them on these" ), + [SwapType.Necklace] = (new ItemSelector(a, itemService, selector, FullEquipType.Neck), new ItemSelector(a, itemService, null, FullEquipType.Neck), "Take this Necklace", "and put it on this one" ), + [SwapType.Bracelet] = (new ItemSelector(a, itemService, selector, FullEquipType.Wrists), new ItemSelector(a, itemService, null, FullEquipType.Wrists), "Take these Bracelets", "and put them on these" ), + [SwapType.Ring] = (new ItemSelector(a, itemService, selector, FullEquipType.Finger), new ItemSelector(a, itemService, null, FullEquipType.Finger), "Take this Ring", "and put it on this one" ), + [SwapType.Glasses] = (new ItemSelector(a, itemService, selector, FullEquipType.Glasses), new ItemSelector(a, itemService, null, FullEquipType.Glasses), "Take these Glasses", "and put them on these" ), // @formatter:on }; @@ -134,23 +137,34 @@ public class ItemSwapTab : IDisposable, ITab, IUiService Glasses, } - private class ItemSelector(ItemData data, ModFileSystemSelector? selector, FullEquipType type) - : FilterComboCache<(EquipItem Item, bool InMod)>(() => + private class ItemSelector(ActiveCollections collections, ItemData data, ModFileSystemSelector? selector, FullEquipType type) + : FilterComboCache<(EquipItem Item, bool InMod, SingleArray InCollection)>(() => { var list = data.ByType[type]; - if (selector?.Selected is { } mod && mod.ChangedItems.Values.Any(o => o is IdentifiedItem i && i.Item.Type == type)) - return list.Select(i => (i, mod.ChangedItems.ContainsKey(i.Name))).OrderByDescending(p => p.Item2).ToList(); - - return list.Select(i => (i, false)).ToList(); + var enumerable = selector?.Selected is { } mod && mod.ChangedItems.Values.Any(o => o is IdentifiedItem i && i.Item.Type == type) + ? list.Select(i => (i, mod.ChangedItems.ContainsKey(i.Name), collections.Current.ChangedItems.TryGetValue(i.Name, out var m) ? m.Item1 : new SingleArray())) + .OrderByDescending(p => p.Item2).ThenByDescending(p => p.Item3.Count) + : selector is null + ? list.Select(i => (i, false, collections.Current.ChangedItems.TryGetValue(i.Name, out var m) ? m.Item1 : new SingleArray())).OrderBy(p => p.Item3.Count) + : list.Select(i => (i, false, collections.Current.ChangedItems.TryGetValue(i.Name, out var m) ? m.Item1 : new SingleArray())).OrderByDescending(p => p.Item3.Count); + return enumerable.ToList(); }, MouseWheelType.None, Penumbra.Log) { protected override bool DrawSelectable(int globalIdx, bool selected) { - using var color = ImRaii.PushColor(ImGuiCol.Text, ColorId.ResTreeLocalPlayer.Value(), Items[globalIdx].InMod); - return base.DrawSelectable(globalIdx, selected); + var (_, inMod, inCollection) = Items[globalIdx]; + using var color = inMod + ? ImRaii.PushColor(ImGuiCol.Text, ColorId.ResTreeLocalPlayer.Value()) + : inCollection.Count > 0 + ? ImRaii.PushColor(ImGuiCol.Text, ColorId.ResTreeNonNetworked.Value()) + : null; + var ret = base.DrawSelectable(globalIdx, selected); + if (inCollection.Count > 0) + ImUtf8.HoverTooltip(string.Join('\n', inCollection.Select(m => m.Name.Text))); + return ret; } - protected override string ToString((EquipItem Item, bool InMod) obj) + protected override string ToString((EquipItem Item, bool InMod, SingleArray InCollection) obj) => obj.Item.Name; } From 5d5fc673b1ff703aec294cde7a557f7513de454c Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 10 Apr 2025 14:42:26 +0000 Subject: [PATCH 1192/1381] [CI] Updating repo.json for 1.3.6.8 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 5163bb7d..8e88ad52 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.7", - "TestingAssemblyVersion": "1.3.6.7", + "AssemblyVersion": "1.3.6.8", + "TestingAssemblyVersion": "1.3.6.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.7/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.7/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.7/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 0954f509127736e266dfc26d19593b42bb51c05a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 17 Apr 2025 01:05:56 +0200 Subject: [PATCH 1193/1381] Update OtterGui, GameData, Namespaces. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra/Api/Api/ModSettingsApi.cs | 2 +- Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs | 1 + Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 1 + Penumbra/Collections/Cache/CollectionCache.cs | 2 +- Penumbra/Collections/Manager/ActiveCollections.cs | 2 +- Penumbra/Collections/Manager/CollectionEditor.cs | 2 +- Penumbra/Collections/Manager/CollectionStorage.cs | 2 +- Penumbra/Collections/Manager/InheritanceManager.cs | 2 +- Penumbra/Collections/Manager/TempCollectionManager.cs | 2 +- Penumbra/Collections/ModCollectionIdentity.cs | 1 + Penumbra/Configuration.cs | 2 +- Penumbra/Import/Models/Export/MeshExporter.cs | 2 +- Penumbra/Import/Models/Import/MeshImporter.cs | 2 +- Penumbra/Import/Models/Import/ModelImporter.cs | 2 +- Penumbra/Import/Models/Import/PrimitiveImporter.cs | 2 +- Penumbra/Import/Models/Import/SubMeshImporter.cs | 2 +- Penumbra/Import/Models/ModelManager.cs | 2 +- Penumbra/Import/Models/SkeletonConverter.cs | 2 +- Penumbra/Import/TexToolsImporter.ModPack.cs | 2 +- Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs | 2 +- Penumbra/Interop/PathResolving/CollectionResolver.cs | 2 +- Penumbra/Interop/ResourceTree/ResolveContext.cs | 2 +- Penumbra/Meta/Files/ImcFile.cs | 2 +- Penumbra/Mods/Editor/MdlMaterialEditor.cs | 2 +- Penumbra/Mods/Editor/ModFileCollection.cs | 1 + Penumbra/Mods/Editor/ModMerger.cs | 1 + Penumbra/Mods/Editor/ModNormalizer.cs | 2 +- Penumbra/Mods/Editor/ModelMaterialInfo.cs | 2 +- Penumbra/Mods/Groups/CombiningModGroup.cs | 1 + Penumbra/Mods/Groups/ImcModGroup.cs | 2 +- Penumbra/Mods/Groups/MultiModGroup.cs | 2 +- Penumbra/Mods/Groups/SingleModGroup.cs | 2 +- Penumbra/Mods/Manager/ModMigration.cs | 2 +- Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs | 1 + Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs | 2 +- Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs | 2 +- Penumbra/Mods/Mod.cs | 1 + Penumbra/Mods/ModCreator.cs | 1 + Penumbra/Mods/Settings/ModSettings.cs | 2 +- Penumbra/Mods/SubMods/CombinedDataContainer.cs | 2 +- Penumbra/Mods/SubMods/OptionSubMod.cs | 2 +- Penumbra/Mods/SubMods/SubMod.cs | 2 +- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs | 1 + Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs | 1 + Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs | 1 + Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs | 1 + Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 1 + Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 1 + Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 1 + Penumbra/UI/CollectionTab/CollectionCombo.cs | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 1 + Penumbra/UI/CollectionTab/InheritanceUi.cs | 1 + Penumbra/UI/FileDialogService.cs | 1 + Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs | 1 + Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 1 + Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs | 1 + Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 1 + Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 2 +- Penumbra/UI/ModsTab/MultiModPanel.cs | 2 +- Penumbra/UI/PredefinedTagManager.cs | 1 + Penumbra/UI/Tabs/Debug/AtchDrawer.cs | 2 +- 75 files changed, 75 insertions(+), 47 deletions(-) diff --git a/OtterGui b/OtterGui index 21ddfccb..5704b215 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 21ddfccb91ba3fa56e1c191e706ff91bffaa9515 +Subproject commit 5704b2151bcdbf18b04dff1b199ca2f35765504f diff --git a/Penumbra.GameData b/Penumbra.GameData index e10d8f33..62bbce59 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit e10d8f33a676ff4544d7ca05a93d555416f41222 +Subproject commit 62bbce5981e961a91322ca1a7d3bb5be25f67185 diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index fe9bf366..3ba17cf4 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Api.Helpers; diff --git a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs index 088a77bd..48f3b4a8 100644 --- a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs +++ b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs @@ -4,6 +4,7 @@ using Dalamud.Interface.Utility; using Dalamud.Plugin; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Api.Enums; diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 3dc8862e..c106a867 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using Dalamud.Plugin; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index 42c8b27d..f6f038a1 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -1,5 +1,4 @@ using Dalamud.Interface.ImGuiNotification; -using OtterGui; using OtterGui.Classes; using Penumbra.Meta.Manipulations; using Penumbra.Mods; @@ -8,6 +7,7 @@ using Penumbra.Mods.Editor; using Penumbra.String.Classes; using Penumbra.Util; using Penumbra.GameData.Data; +using OtterGui.Extensions; namespace Penumbra.Collections.Cache; diff --git a/Penumbra/Collections/Manager/ActiveCollections.cs b/Penumbra/Collections/Manager/ActiveCollections.cs index 2ced8ad6..ffec7fd2 100644 --- a/Penumbra/Collections/Manager/ActiveCollections.cs +++ b/Penumbra/Collections/Manager/ActiveCollections.cs @@ -1,8 +1,8 @@ using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Communication; using Penumbra.GameData.Actors; diff --git a/Penumbra/Collections/Manager/CollectionEditor.cs b/Penumbra/Collections/Manager/CollectionEditor.cs index 5ccc38e2..f62eea3f 100644 --- a/Penumbra/Collections/Manager/CollectionEditor.cs +++ b/Penumbra/Collections/Manager/CollectionEditor.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Mods; diff --git a/Penumbra/Collections/Manager/CollectionStorage.cs b/Penumbra/Collections/Manager/CollectionStorage.cs index de723729..531b6333 100644 --- a/Penumbra/Collections/Manager/CollectionStorage.cs +++ b/Penumbra/Collections/Manager/CollectionStorage.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.ImGuiNotification; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods; diff --git a/Penumbra/Collections/Manager/InheritanceManager.cs b/Penumbra/Collections/Manager/InheritanceManager.cs index 5e361bde..34582677 100644 --- a/Penumbra/Collections/Manager/InheritanceManager.cs +++ b/Penumbra/Collections/Manager/InheritanceManager.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.ImGuiNotification; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Communication; using Penumbra.Mods.Manager; diff --git a/Penumbra/Collections/Manager/TempCollectionManager.cs b/Penumbra/Collections/Manager/TempCollectionManager.cs index 8aab5297..9476e38c 100644 --- a/Penumbra/Collections/Manager/TempCollectionManager.cs +++ b/Penumbra/Collections/Manager/TempCollectionManager.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Api; using Penumbra.Communication; diff --git a/Penumbra/Collections/ModCollectionIdentity.cs b/Penumbra/Collections/ModCollectionIdentity.cs index bd2d47c4..7050450c 100644 --- a/Penumbra/Collections/ModCollectionIdentity.cs +++ b/Penumbra/Collections/ModCollectionIdentity.cs @@ -1,4 +1,5 @@ using OtterGui; +using OtterGui.Extensions; using Penumbra.Collections.Manager; namespace Penumbra.Collections; diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 3a9bcdc4..bd6ccfb1 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -1,8 +1,8 @@ using Dalamud.Configuration; using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Filesystem; using OtterGui.Services; using OtterGui.Widgets; diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 32b9b323..0070a808 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -2,7 +2,7 @@ using System.Collections.Immutable; using System.Text.Json; using System.Text.Json.Nodes; using Lumina.Extensions; -using OtterGui; +using OtterGui.Extensions; using Penumbra.GameData.Files; using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Geometry; diff --git a/Penumbra/Import/Models/Import/MeshImporter.cs b/Penumbra/Import/Models/Import/MeshImporter.cs index 6a46fb9f..16fe2ca0 100644 --- a/Penumbra/Import/Models/Import/MeshImporter.cs +++ b/Penumbra/Import/Models/Import/MeshImporter.cs @@ -1,5 +1,5 @@ using Lumina.Data.Parsing; -using OtterGui; +using OtterGui.Extensions; using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Schema2; diff --git a/Penumbra/Import/Models/Import/ModelImporter.cs b/Penumbra/Import/Models/Import/ModelImporter.cs index 502d060a..f4eefccc 100644 --- a/Penumbra/Import/Models/Import/ModelImporter.cs +++ b/Penumbra/Import/Models/Import/ModelImporter.cs @@ -1,5 +1,5 @@ using Lumina.Data.Parsing; -using OtterGui; +using OtterGui.Extensions; using Penumbra.GameData.Files; using Penumbra.GameData.Files.ModelStructs; using SharpGLTF.Schema2; diff --git a/Penumbra/Import/Models/Import/PrimitiveImporter.cs b/Penumbra/Import/Models/Import/PrimitiveImporter.cs index 5df7597e..57c7929f 100644 --- a/Penumbra/Import/Models/Import/PrimitiveImporter.cs +++ b/Penumbra/Import/Models/Import/PrimitiveImporter.cs @@ -1,5 +1,5 @@ using Lumina.Data.Parsing; -using OtterGui; +using OtterGui.Extensions; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; diff --git a/Penumbra/Import/Models/Import/SubMeshImporter.cs b/Penumbra/Import/Models/Import/SubMeshImporter.cs index df08eea3..6aa46fb6 100644 --- a/Penumbra/Import/Models/Import/SubMeshImporter.cs +++ b/Penumbra/Import/Models/Import/SubMeshImporter.cs @@ -1,6 +1,6 @@ using System.Text.Json; using Lumina.Data.Parsing; -using OtterGui; +using OtterGui.Extensions; using SharpGLTF.Schema2; namespace Penumbra.Import.Models.Import; diff --git a/Penumbra/Import/Models/ModelManager.cs b/Penumbra/Import/Models/ModelManager.cs index 19d06a52..6818ad64 100644 --- a/Penumbra/Import/Models/ModelManager.cs +++ b/Penumbra/Import/Models/ModelManager.cs @@ -1,6 +1,6 @@ using Dalamud.Plugin.Services; using Lumina.Data.Parsing; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using OtterGui.Tasks; using Penumbra.Collections.Manager; diff --git a/Penumbra/Import/Models/SkeletonConverter.cs b/Penumbra/Import/Models/SkeletonConverter.cs index 25e74332..e180662d 100644 --- a/Penumbra/Import/Models/SkeletonConverter.cs +++ b/Penumbra/Import/Models/SkeletonConverter.cs @@ -1,5 +1,5 @@ using System.Xml; -using OtterGui; +using OtterGui.Extensions; using Penumbra.Import.Models.Export; namespace Penumbra.Import.Models; diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 7bbb762e..1c28aef2 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -1,5 +1,5 @@ using Newtonsoft.Json; -using OtterGui; +using OtterGui.Extensions; using Penumbra.Api.Enums; using Penumbra.Import.Structs; using Penumbra.Mods; diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index 5fdec816..caf43d08 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -1,7 +1,7 @@ using System.Text.Unicode; using Dalamud.Hooking; using Iced.Intel; -using OtterGui; +using OtterGui.Extensions; using Penumbra.String.Classes; using Swan; diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 02e1be54..10795e6d 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -1,7 +1,7 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; using FFXIVClientStructs.FFXIV.Client.UI.Agent; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 99360077..013d7db7 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -2,7 +2,7 @@ using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Text.HelperObjects; using Penumbra.Api.Enums; using Penumbra.Collections; diff --git a/Penumbra/Meta/Files/ImcFile.cs b/Penumbra/Meta/Files/ImcFile.cs index 0a0faf1e..b8db66dd 100644 --- a/Penumbra/Meta/Files/ImcFile.cs +++ b/Penumbra/Meta/Files/ImcFile.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; diff --git a/Penumbra/Mods/Editor/MdlMaterialEditor.cs b/Penumbra/Mods/Editor/MdlMaterialEditor.cs index 2a23ffad..da580794 100644 --- a/Penumbra/Mods/Editor/MdlMaterialEditor.cs +++ b/Penumbra/Mods/Editor/MdlMaterialEditor.cs @@ -1,5 +1,5 @@ -using OtterGui; using OtterGui.Compression; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.GameData.Enums; using Penumbra.GameData.Files; diff --git a/Penumbra/Mods/Editor/ModFileCollection.cs b/Penumbra/Mods/Editor/ModFileCollection.cs index 7667910f..15bd179e 100644 --- a/Penumbra/Mods/Editor/ModFileCollection.cs +++ b/Penumbra/Mods/Editor/ModFileCollection.cs @@ -1,4 +1,5 @@ using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Mods.SubMods; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index e3eb5f54..88941edf 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -2,6 +2,7 @@ using Dalamud.Interface.ImGuiNotification; using Dalamud.Utility; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Communication; diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 3e367a3b..527dbf7c 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.ImGuiNotification; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using OtterGui.Tasks; using Penumbra.Mods.Groups; diff --git a/Penumbra/Mods/Editor/ModelMaterialInfo.cs b/Penumbra/Mods/Editor/ModelMaterialInfo.cs index 741c2388..fe46048f 100644 --- a/Penumbra/Mods/Editor/ModelMaterialInfo.cs +++ b/Penumbra/Mods/Editor/ModelMaterialInfo.cs @@ -1,5 +1,5 @@ -using OtterGui; using OtterGui.Compression; +using OtterGui.Extensions; using Penumbra.GameData.Files; using Penumbra.String.Classes; diff --git a/Penumbra/Mods/Groups/CombiningModGroup.cs b/Penumbra/Mods/Groups/CombiningModGroup.cs index 90a962b7..d3f14101 100644 --- a/Penumbra/Mods/Groups/CombiningModGroup.cs +++ b/Penumbra/Mods/Groups/CombiningModGroup.cs @@ -3,6 +3,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Mods/Groups/ImcModGroup.cs b/Penumbra/Mods/Groups/ImcModGroup.cs index 5ec32274..34174f7f 100644 --- a/Penumbra/Mods/Groups/ImcModGroup.cs +++ b/Penumbra/Mods/Groups/ImcModGroup.cs @@ -1,8 +1,8 @@ using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.GameData.Structs; diff --git a/Penumbra/Mods/Groups/MultiModGroup.cs b/Penumbra/Mods/Groups/MultiModGroup.cs index 82555314..558ee6be 100644 --- a/Penumbra/Mods/Groups/MultiModGroup.cs +++ b/Penumbra/Mods/Groups/MultiModGroup.cs @@ -1,8 +1,8 @@ using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Mods/Groups/SingleModGroup.cs b/Penumbra/Mods/Groups/SingleModGroup.cs index c250182a..f376c1c9 100644 --- a/Penumbra/Mods/Groups/SingleModGroup.cs +++ b/Penumbra/Mods/Groups/SingleModGroup.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui; +using OtterGui.Extensions; using Penumbra.Api.Enums; using Penumbra.GameData.Data; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Mods/Manager/ModMigration.cs b/Penumbra/Mods/Manager/ModMigration.cs index 8b5b80d0..f3b25f1a 100644 --- a/Penumbra/Mods/Manager/ModMigration.cs +++ b/Penumbra/Mods/Manager/ModMigration.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui; +using OtterGui.Extensions; using Penumbra.Api.Enums; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; diff --git a/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs b/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs index ce5db454..5acf5eb5 100644 --- a/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/CombiningModGroupEditor.cs @@ -1,5 +1,6 @@ using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; diff --git a/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs b/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs index a7b73ac9..12ed4c60 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ImcAttributeCache.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using Penumbra.GameData.Structs; using Penumbra.Mods.Groups; using Penumbra.Mods.SubMods; diff --git a/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs index c067102e..5c5ed4f1 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs @@ -1,5 +1,5 @@ -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using Penumbra.Mods.Groups; using Penumbra.Mods.Settings; using Penumbra.Mods.SubMods; diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index efd92631..99f86517 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,5 +1,6 @@ using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using Penumbra.GameData.Data; using Penumbra.GameData.Structs; using Penumbra.Meta.Manipulations; diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index f4f182eb..df476a6f 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -3,6 +3,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Filesystem; using OtterGui.Services; using Penumbra.Api.Enums; diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index 0420ee86..07217d4d 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using OtterGui.Filesystem; using Penumbra.Api.Enums; using Penumbra.Mods.Editor; diff --git a/Penumbra/Mods/SubMods/CombinedDataContainer.cs b/Penumbra/Mods/SubMods/CombinedDataContainer.cs index 2c410c1c..b467c360 100644 --- a/Penumbra/Mods/SubMods/CombinedDataContainer.cs +++ b/Penumbra/Mods/SubMods/CombinedDataContainer.cs @@ -1,5 +1,5 @@ using Newtonsoft.Json.Linq; -using OtterGui; +using OtterGui.Extensions; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs index 8fac52d8..9044350d 100644 --- a/Penumbra/Mods/SubMods/OptionSubMod.cs +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using Penumbra.Meta.Manipulations; using Penumbra.Mods.Editor; using Penumbra.Mods.Groups; diff --git a/Penumbra/Mods/SubMods/SubMod.cs b/Penumbra/Mods/SubMods/SubMod.cs index fcb6cc0e..a7a2ee61 100644 --- a/Penumbra/Mods/SubMods/SubMod.cs +++ b/Penumbra/Mods/SubMods/SubMod.cs @@ -1,6 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using OtterGui; +using OtterGui.Extensions; using Penumbra.Meta.Manipulations; using Penumbra.String.Classes; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs index 176ec3f4..f413a6a2 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Text.Widget.Editors; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs index b76cffc2..ee5341b2 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -4,6 +4,7 @@ using ImGuiNET; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.GameData; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs index 7ecd97e0..ac88f77c 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.GameData.Files.MaterialStructs; diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs index 80b10607..5bc70fc3 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs @@ -2,7 +2,7 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using Newtonsoft.Json.Linq; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs index 258e51ff..36154105 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility.Raii; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Text; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 071b0551..3f63967e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.Mods.Editor; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 59b38465..4c946fe7 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.UI.AdvancedWindow.Materials; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs index b436448f..fc197bc0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.MdlTab.cs @@ -1,4 +1,4 @@ -using OtterGui; +using OtterGui.Extensions; using Penumbra.GameData; using Penumbra.GameData.Files; using Penumbra.Import.Models; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 8fbe5a68..0c8c496f 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -3,6 +3,7 @@ using ImGuiNET; using Lumina.Data.Parsing; using OtterGui; using OtterGui.Custom; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Widgets; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index 41f1da26..a6a75e0d 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -12,6 +12,7 @@ using static Penumbra.GameData.Files.ShpkFile; using OtterGui.Widgets; using OtterGui.Text; using Penumbra.GameData.Structs; +using OtterGui.Extensions; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs index b5b39e90..6c2953e0 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShpkTab.cs @@ -1,7 +1,7 @@ using Dalamud.Utility; using Newtonsoft.Json.Linq; -using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using Penumbra.GameData.Files; using Penumbra.GameData.Files.ShaderStructs; using Penumbra.GameData.Interop; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index 4664372e..ee4e1eda 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -1,5 +1,6 @@ using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterTex; using Penumbra.Import.Textures; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 7f1a8ac5..ccbbf0db 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -6,6 +6,7 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index bd62089f..3c110fab 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -1,6 +1,7 @@ using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index eb9aa93d..4d33a3fc 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -9,6 +9,7 @@ using Penumbra.Interop.ResourceTree; using Penumbra.Services; using Penumbra.UI.Classes; using Penumbra.String; +using OtterGui.Extensions; namespace Penumbra.UI.AdvancedWindow; diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index 0259713f..98dc924f 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -1,5 +1,5 @@ using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Widgets; diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 8b41b105..dc0e71b5 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -9,6 +9,7 @@ using Dalamud.Plugin; using ImGuiNET; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Raii; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index ce3cc3cb..cdc1e83e 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Collections; diff --git a/Penumbra/UI/FileDialogService.cs b/Penumbra/UI/FileDialogService.cs index cc2a7f6a..6773bc88 100644 --- a/Penumbra/UI/FileDialogService.cs +++ b/Penumbra/UI/FileDialogService.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.ImGuiFileDialog; using Dalamud.Utility; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Communication; using Penumbra.Services; diff --git a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs index f32e6da6..5bd5dfdf 100644 --- a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.Mods.Groups; diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 786bb8ff..3d330093 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Text.Widget; diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index 8dee13bf..666fce61 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -1,6 +1,7 @@ using Dalamud.Interface.Components; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs index 89812346..e9ab72ae 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.ImGuiNotification; using ImGuiNET; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs index f0275853..04ca6c82 100644 --- a/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/MultiModGroupEditDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.Mods.Groups; diff --git a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs index be2dbd73..492a8fb7 100644 --- a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.Mods.Groups; diff --git a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs index 2b4b665b..ec020c86 100644 --- a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.Utility; using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index f7b6b42d..c750b8b0 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -2,6 +2,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; using ImGuiNET; using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 38340a2d..3988de35 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -1,5 +1,4 @@ using ImGuiNET; -using OtterGui; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; @@ -11,6 +10,7 @@ using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.Mods.Settings; using Penumbra.UI.ModsTab.Groups; +using OtterGui.Extensions; namespace Penumbra.UI.ModsTab; diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs index 0e9b5d39..ff5f636d 100644 --- a/Penumbra/UI/ModsTab/MultiModPanel.cs +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index 8de613d4..12355672 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -5,6 +5,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Mods.Manager; diff --git a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs index d9058083..eb9f05d9 100644 --- a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs @@ -1,5 +1,5 @@ using ImGuiNET; -using OtterGui; +using OtterGui.Extensions; using OtterGui.Text; using Penumbra.GameData.Files; using Penumbra.GameData.Files.AtchStructs; From 53ef42adfa109cd073783acd328d096e01634453 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 17 Apr 2025 01:06:09 +0200 Subject: [PATCH 1194/1381] Update EST Customization identification. --- Penumbra/Meta/Manipulations/Est.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Meta/Manipulations/Est.cs b/Penumbra/Meta/Manipulations/Est.cs index 05d4c014..46a275a5 100644 --- a/Penumbra/Meta/Manipulations/Est.cs +++ b/Penumbra/Meta/Manipulations/Est.cs @@ -33,7 +33,7 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende var (gender, race) = GenderRace.Split(); var id = (CustomizeValue)SetId.Id; changedItems.UpdateCountOrSet( - $"Customization: {gender.ToName()} {race.ToName()} Hair {SetId}", () => IdentifiedCustomization.Hair(race, gender, id)); + $"Customization: {race.ToName()} {gender.ToName()} Hair {SetId}", () => IdentifiedCustomization.Hair(race, gender, id)); break; } case EstType.Face: @@ -41,7 +41,7 @@ public readonly record struct EstIdentifier(PrimaryId SetId, EstType Slot, Gende var (gender, race) = GenderRace.Split(); var id = (CustomizeValue)SetId.Id; changedItems.UpdateCountOrSet( - $"Customization: {gender.ToName()} {race.ToName()} Face {SetId}", + $"Customization: {race.ToName()} {gender.ToName()} Face {SetId}", () => IdentifiedCustomization.Face(race, gender, id)); break; } From 0c768979d4e34969aabbb4cf1dd4dc90cc1ed8e4 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 17 Apr 2025 01:06:22 +0200 Subject: [PATCH 1195/1381] Don't use DalamudPackager for no reason. --- Penumbra/Penumbra.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index f93b1815..f668f775 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -11,6 +11,7 @@ PROFILING; + false From cbebfe5e99709b7babc3de2245eaadb2dd48c763 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 17 Apr 2025 01:06:58 +0200 Subject: [PATCH 1196/1381] Fix sizing of mod panel. --- Penumbra/UI/Tabs/ModsTab.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 8b4913c8..b77240ec 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -55,12 +55,12 @@ public class ModsTab( { selector.Draw(GetModSelectorSize(config)); ImGui.SameLine(); + ImGui.SetCursorPosX(MathF.Round(ImGui.GetCursorPosX())); using var group = ImRaii.Group(); collectionHeader.Draw(false); using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero); - - using (var child = ImRaii.Child("##ModsTabMod", new Vector2(-1, config.HideRedrawBar ? 0 : -ImGui.GetFrameHeight()), + using (var child = ImRaii.Child("##ModsTabMod", new Vector2(ImGui.GetContentRegionAvail().X, config.HideRedrawBar ? 0 : -ImGui.GetFrameHeight()), true, ImGuiWindowFlags.HorizontalScrollbar)) { style.Pop(); @@ -94,9 +94,9 @@ public class ModsTab( var relativeSize = config.ScaleModSelector ? Math.Clamp(config.ModSelectorScaledSize, Configuration.Constants.MinScaledSize, Configuration.Constants.MaxScaledSize) : 0; - return !config.ScaleModSelector - ? absoluteSize - : Math.Max(absoluteSize, relativeSize * ImGui.GetContentRegionAvail().X / 100); + return MathF.Round(config.ScaleModSelector + ? Math.Max(absoluteSize, relativeSize * ImGui.GetContentRegionAvail().X / 100) + : absoluteSize); } private void DrawRedrawLine() From a5d221dc1359281e68614f5fb9a3db060a839278 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 18 Apr 2025 00:14:11 +0200 Subject: [PATCH 1197/1381] Make temporary mode checkbox more visible. --- OtterGui | 2 +- Penumbra/UI/Classes/CollectionSelectHeader.cs | 31 +++++++++---------- Penumbra/UI/Tabs/Debug/DebugTab.cs | 1 + 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/OtterGui b/OtterGui index 5704b215..ac32553b 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5704b2151bcdbf18b04dff1b199ca2f35765504f +Subproject commit ac32553b1e2e9feca7b9cd0c1b16eae81d5fcc31 diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index d7a81876..aa492362 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -1,10 +1,9 @@ using Dalamud.Interface; using ImGuiNET; -using OtterGui.Raii; using OtterGui; +using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; -using OtterGui.Text.Widget; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; @@ -15,13 +14,12 @@ namespace Penumbra.UI.Classes; public class CollectionSelectHeader : IUiService { - private readonly CollectionCombo _collectionCombo; - private readonly ActiveCollections _activeCollections; - private readonly TutorialService _tutorial; - private readonly ModSelection _selection; - private readonly CollectionResolver _resolver; - private readonly FontAwesomeCheckbox _temporaryCheckbox = new(FontAwesomeIcon.Stopwatch); - private readonly Configuration _config; + private readonly CollectionCombo _collectionCombo; + private readonly ActiveCollections _activeCollections; + private readonly TutorialService _tutorial; + private readonly ModSelection _selection; + private readonly CollectionResolver _resolver; + private readonly Configuration _config; public CollectionSelectHeader(CollectionManager collectionManager, TutorialService tutorial, ModSelection selection, CollectionResolver resolver, Configuration config) @@ -64,14 +62,15 @@ public class CollectionSelectHeader : IUiService var hold = _config.IncognitoModifier.IsActive(); using (ImRaii.PushStyle(ImGuiStyleVar.FrameBorderSize, ImUtf8.GlobalScale)) { - var tint = ImGuiCol.Text.Tinted(ColorId.TemporaryModSettingsTint); - using var color = ImRaii.PushColor(ImGuiCol.FrameBgHovered, ImGui.GetColorU32(ImGuiCol.FrameBg), !hold) - .Push(ImGuiCol.FrameBgActive, ImGui.GetColorU32(ImGuiCol.FrameBg), !hold) - .Push(ImGuiCol.CheckMark, tint) - .Push(ImGuiCol.Border, tint, _config.DefaultTemporaryMode); - if (_temporaryCheckbox.Draw("##tempCheck"u8, _config.DefaultTemporaryMode, out var newValue) && hold) + var tint = _config.DefaultTemporaryMode + ? ImGuiCol.Text.Tinted(ColorId.TemporaryModSettingsTint) + : ImGui.GetColorU32(ImGuiCol.TextDisabled); + using var color = ImRaii.PushColor(ImGuiCol.ButtonHovered, ImGui.GetColorU32(ImGuiCol.FrameBg), !hold) + .Push(ImGuiCol.ButtonActive, ImGui.GetColorU32(ImGuiCol.FrameBg), !hold) + .Push(ImGuiCol.Border, tint, _config.DefaultTemporaryMode); + if (ImUtf8.IconButton(FontAwesomeIcon.Stopwatch, ""u8, default, false, tint, ImGui.GetColorU32(ImGuiCol.FrameBg)) && hold) { - _config.DefaultTemporaryMode = newValue; + _config.DefaultTemporaryMode = !_config.DefaultTemporaryMode; _config.Save(); } } diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 6d6222ec..b7bc8edf 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -12,6 +12,7 @@ using ImGuiNET; using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; +using OtterGui.Extensions; using OtterGui.Services; using OtterGui.Text; using OtterGui.Widgets; From 117724b0aebc0b063a5edb81342b28cca44a4fc7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 19 Apr 2025 23:11:45 +0200 Subject: [PATCH 1198/1381] Update npc names. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Services/StaticServiceManager.cs | 5 ++++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/OtterGui b/OtterGui index ac32553b..089ed82a 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit ac32553b1e2e9feca7b9cd0c1b16eae81d5fcc31 +Subproject commit 089ed82a53dc75b0d3be469d2a005e6096c4b2d2 diff --git a/Penumbra.GameData b/Penumbra.GameData index 62bbce59..002260d9 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 62bbce5981e961a91322ca1a7d3bb5be25f67185 +Subproject commit 002260d9815e571f1496c50374f5b712818e9880 diff --git a/Penumbra.String b/Penumbra.String index 2896c056..0e5dcd1a 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 2896c0561f60827f97408650d52a15c38f4d9d10 +Subproject commit 0e5dcd1a5687ec5f8fa2ef2526b94b9a0ea1b5b5 diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index c0dc9314..27582395 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -17,6 +17,8 @@ using IPenumbraApi = Penumbra.Api.Api.IPenumbraApi; namespace Penumbra.Services; +#pragma warning disable SeStringEvaluator + public static class StaticServiceManager { public static ServiceManager CreateProvider(Penumbra penumbra, IDalamudPluginInterface pi, Logger log) @@ -60,5 +62,6 @@ public static class StaticServiceManager .AddDalamudService(pi) .AddDalamudService(pi) .AddDalamudService(pi) - .AddDalamudService(pi); + .AddDalamudService(pi) + .AddDalamudService(pi); } From 363d115be8980009db8bccc87204b12ce1d24e14 Mon Sep 17 00:00:00 2001 From: Caraxi Date: Sun, 20 Apr 2025 00:35:36 +0930 Subject: [PATCH 1199/1381] Add filter for temporary mods --- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 14 ++++++++++++++ Penumbra/UI/ModsTab/ModFilter.cs | 7 +++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index a0383329..6586747c 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -647,6 +647,20 @@ public sealed class ModFileSystemSelector : FileSystemSelector TriStatePairs = [ @@ -38,6 +40,7 @@ public static class ModFilterExtensions (ModFilter.HasFiles, ModFilter.HasNoFiles, "Has Redirections"), (ModFilter.HasMetaManipulations, ModFilter.HasNoMetaManipulations, "Has Meta Manipulations"), (ModFilter.HasFileSwaps, ModFilter.HasNoFileSwaps, "Has File Swaps"), + (ModFilter.Temporary, ModFilter.NotTemporary, "Temporary"), ]; public static IReadOnlyList> Groups = From 0fe4a3671ab6e577ca39a2d94bd714df1a2c3a06 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 8 May 2025 23:46:25 +0200 Subject: [PATCH 1200/1381] Improve small issue with redraw service. --- Penumbra/Interop/Services/RedrawService.cs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 8f20ca5e..08e9ddf5 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -10,7 +10,6 @@ using OtterGui.Services; using Penumbra.Api; using Penumbra.Api.Enums; using Penumbra.Communication; -using Penumbra.GameData; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.Interop.Structs; @@ -354,21 +353,14 @@ public sealed unsafe partial class RedrawService : IDisposable { switch (settings) { - case RedrawType.Redraw: - ReloadActor(actor); - break; - case RedrawType.AfterGPose: - ReloadActorAfterGPose(actor); - break; - default: throw new ArgumentOutOfRangeException(nameof(settings), settings, null); + case RedrawType.Redraw: ReloadActor(actor); break; + case RedrawType.AfterGPose: ReloadActorAfterGPose(actor); break; + default: throw new ArgumentOutOfRangeException(nameof(settings), settings, null); } } private IGameObject? GetLocalPlayer() - { - var gPosePlayer = _objects.GetDalamudObject(GPosePlayerIdx); - return gPosePlayer ?? _objects.GetDalamudObject(0); - } + => InGPose ? _objects.GetDalamudObject(GPosePlayerIdx) ?? _objects.GetDalamudObject(0) : _objects.GetDalamudObject(0); public bool GetName(string lowerName, out IGameObject? actor) { From 0adec35848f8e02838d7d43e755cf6e0f8444980 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 15 May 2025 00:26:59 +0200 Subject: [PATCH 1201/1381] Add initial support for custom shapes. --- OtterGui | 2 +- Penumbra.GameData | 2 +- .../Communication/ModelAttributeComputed.cs | 24 ++++ Penumbra/Configuration.cs | 4 +- .../Hooks/PostProcessing/AttributeHooks.cs | 110 +++++++++++++++ .../Hooks/Resources/ResolvePathHooksBase.cs | 22 --- Penumbra/Meta/ShapeManager.cs | 127 ++++++++++++++++++ Penumbra/Meta/ShapeString.cs | 89 ++++++++++++ Penumbra/Penumbra.cs | 7 +- Penumbra/Services/CommunicatorService.cs | 4 + Penumbra/UI/Tabs/Debug/AtchDrawer.cs | 12 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 89 +++++++----- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 71 ++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 8 +- Penumbra/packages.lock.json | 6 - 15 files changed, 502 insertions(+), 75 deletions(-) create mode 100644 Penumbra/Communication/ModelAttributeComputed.cs create mode 100644 Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs create mode 100644 Penumbra/Meta/ShapeManager.cs create mode 100644 Penumbra/Meta/ShapeString.cs create mode 100644 Penumbra/UI/Tabs/Debug/ShapeInspector.cs diff --git a/OtterGui b/OtterGui index 089ed82a..86b49242 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 089ed82a53dc75b0d3be469d2a005e6096c4b2d2 +Subproject commit 86b492422565abde2e8ad17c0295896a21c3439c diff --git a/Penumbra.GameData b/Penumbra.GameData index 002260d9..0ca50105 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 002260d9815e571f1496c50374f5b712818e9880 +Subproject commit 0ca501050de72ee1cc7382dfae894f984ce241b6 diff --git a/Penumbra/Communication/ModelAttributeComputed.cs b/Penumbra/Communication/ModelAttributeComputed.cs new file mode 100644 index 00000000..389f56b6 --- /dev/null +++ b/Penumbra/Communication/ModelAttributeComputed.cs @@ -0,0 +1,24 @@ +using OtterGui.Classes; +using Penumbra.Collections; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; + +namespace Penumbra.Communication; + +/// +/// Triggered whenever a model recomputes its attribute masks. +/// +/// Parameter is the game object that recomputed its attributes. +/// Parameter is the draw object on which the recomputation was called. +/// Parameter is the collection associated with the game object. +/// Parameter is the slot that was recomputed. If this is Unknown, it is a general new update call. +/// +public sealed class ModelAttributeComputed() + : EventWrapper(nameof(ModelAttributeComputed)) +{ + public enum Priority + { + /// + ShapeManager = 0, + } +} diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index bd6ccfb1..8c50dad7 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -67,6 +67,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HideRedrawBar { get; set; } = false; public bool HideMachinistOffhandFromChangedItems { get; set; } = true; public bool DefaultTemporaryMode { get; set; } = false; + public bool EnableCustomShapes { get; set; } = true; public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; public ChangedItemMode ChangedItemDisplay { get; set; } = ChangedItemMode.GroupedCollapsed; public int OptionGroupCollapsibleMin { get; set; } = 5; @@ -84,9 +85,6 @@ public class Configuration : IPluginConfiguration, ISavable, IService [JsonProperty(Order = int.MaxValue)] public ISortMode SortMode = ISortMode.FoldersFirst; - public bool ScaleModSelector { get; set; } = false; - public float ModSelectorAbsoluteSize { get; set; } = Constants.DefaultAbsoluteSize; - public int ModSelectorScaledSize { get; set; } = Constants.DefaultScaledSize; public bool OpenFoldersByDefault { get; set; } = false; public int SingleGroupRadioMax { get; set; } = 2; public string DefaultImportFolder { get; set; } = string.Empty; diff --git a/Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs b/Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs new file mode 100644 index 00000000..861962ee --- /dev/null +++ b/Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs @@ -0,0 +1,110 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Communication; +using Penumbra.GameData; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; +using Penumbra.Services; + +namespace Penumbra.Interop.Hooks.PostProcessing; + +public sealed unsafe class AttributeHooks : IRequiredService, IDisposable +{ + private delegate void SetupAttributes(Human* human, byte* data); + private delegate void AttributeUpdate(Human* human); + + private readonly Configuration _config; + private readonly ModelAttributeComputed _event; + private readonly CollectionResolver _resolver; + + private readonly AttributeHook[] _hooks; + private readonly Task> _updateHook; + private ModCollection _identifiedCollection = ModCollection.Empty; + private Actor _identifiedActor = Actor.Null; + private bool _inUpdate; + + public AttributeHooks(Configuration config, CommunicatorService communication, CollectionResolver resolver, HookManager hooks) + { + _config = config; + _event = communication.ModelAttributeComputed; + _resolver = resolver; + _hooks = + [ + new AttributeHook(this, hooks, Sigs.SetupTopModelAttributes, _config.EnableCustomShapes, HumanSlot.Body), + new AttributeHook(this, hooks, Sigs.SetupHandModelAttributes, _config.EnableCustomShapes, HumanSlot.Hands), + new AttributeHook(this, hooks, Sigs.SetupLegModelAttributes, _config.EnableCustomShapes, HumanSlot.Legs), + new AttributeHook(this, hooks, Sigs.SetupFootModelAttributes, _config.EnableCustomShapes, HumanSlot.Feet), + ]; + _updateHook = hooks.CreateHook("UpdateAttributes", Sigs.UpdateAttributes, UpdateAttributesDetour, + _config.EnableCustomShapes); + } + + private class AttributeHook + { + private readonly AttributeHooks _parent; + public readonly string Name; + public readonly Task> Hook; + public readonly uint ModelIndex; + public readonly HumanSlot Slot; + + public AttributeHook(AttributeHooks parent, HookManager hooks, string signature, bool enabled, HumanSlot slot) + { + _parent = parent; + Name = $"Setup{slot}Attributes"; + Slot = slot; + ModelIndex = slot.ToIndex(); + Hook = hooks.CreateHook(Name, signature, Detour, enabled); + } + + private void Detour(Human* human, byte* data) + { + Penumbra.Log.Excessive($"[{Name}] Invoked on 0x{(ulong)human:X} (0x{_parent._identifiedActor.Address:X})."); + Hook.Result.Original(human, data); + if (_parent is { _inUpdate: true, _identifiedActor.Valid: true }) + _parent._event.Invoke(_parent._identifiedActor, human, _parent._identifiedCollection, Slot); + } + } + + private void UpdateAttributesDetour(Human* human) + { + var resolveData = _resolver.IdentifyCollection((DrawObject*)human, true); + _identifiedActor = resolveData.AssociatedGameObject; + _identifiedCollection = resolveData.ModCollection; + _inUpdate = true; + Penumbra.Log.Excessive($"[UpdateAttributes] Invoked on 0x{(ulong)human:X} (0x{_identifiedActor.Address:X})."); + _event.Invoke(_identifiedActor, human, _identifiedCollection, HumanSlot.Unknown); + _updateHook.Result.Original(human); + _inUpdate = false; + } + + public void SetState(bool enabled) + { + if (_config.EnableCustomShapes == enabled) + return; + + _config.EnableCustomShapes = enabled; + _config.Save(); + if (enabled) + { + foreach (var hook in _hooks) + hook.Hook.Result.Enable(); + _updateHook.Result.Enable(); + } + else + { + foreach (var hook in _hooks) + hook.Hook.Result.Disable(); + _updateHook.Result.Disable(); + } + } + + public void Dispose() + { + foreach (var hook in _hooks) + hook.Hook.Result.Dispose(); + _updateHook.Result.Dispose(); + } +} diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 54066782..8a45ec2c 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -246,28 +246,6 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable return ret; } - [StructLayout(LayoutKind.Explicit)] - private struct ChangedEquipData - { - [FieldOffset(0)] - public PrimaryId Model; - - [FieldOffset(2)] - public Variant Variant; - - [FieldOffset(8)] - public PrimaryId BonusModel; - - [FieldOffset(10)] - public Variant BonusVariant; - - [FieldOffset(20)] - public ushort VfxId; - - [FieldOffset(22)] - public GenderRace GenderRace; - } - private nint ResolveVfxHuman(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint unkOutParam) { switch (slotIndex) diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs new file mode 100644 index 00000000..4356086a --- /dev/null +++ b/Penumbra/Meta/ShapeManager.cs @@ -0,0 +1,127 @@ +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Communication; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; +using Penumbra.Services; + +namespace Penumbra.Meta; + +public class ShapeManager : IRequiredService, IDisposable +{ + public const int NumSlots = 4; + private readonly CommunicatorService _communicator; + + private static ReadOnlySpan UsedModels + => [1, 2, 3, 4]; + + public ShapeManager(CommunicatorService communicator) + { + _communicator = communicator; + _communicator.ModelAttributeComputed.Subscribe(OnAttributeComputed, ModelAttributeComputed.Priority.ShapeManager); + } + + private readonly Dictionary[] _temporaryIndices = + Enumerable.Range(0, NumSlots).Select(_ => new Dictionary()).ToArray(); + + private readonly uint[] _temporaryMasks = new uint[NumSlots]; + private readonly uint[] _temporaryValues = new uint[NumSlots]; + + private unsafe void OnAttributeComputed(Actor actor, Model model, ModCollection collection, HumanSlot slot) + { + int index; + switch (slot) + { + case HumanSlot.Unknown: + ResetCache(model); + return; + case HumanSlot.Body: index = 0; break; + case HumanSlot.Hands: index = 1; break; + case HumanSlot.Legs: index = 2; break; + case HumanSlot.Feet: index = 3; break; + default: return; + } + + if (_temporaryMasks[index] is 0) + return; + + var modelIndex = UsedModels[index]; + var currentMask = model.AsHuman->Models[modelIndex]->EnabledShapeKeyIndexMask; + var newMask = (currentMask & ~_temporaryMasks[index]) | _temporaryValues[index]; + Penumbra.Log.Excessive($"Changed Model Mask from {currentMask:X} to {newMask:X}."); + model.AsHuman->Models[modelIndex]->EnabledShapeKeyIndexMask = newMask; + } + + public void Dispose() + { + _communicator.ModelAttributeComputed.Unsubscribe(OnAttributeComputed); + } + + private unsafe void ResetCache(Model human) + { + for (var i = 0; i < NumSlots; ++i) + { + _temporaryMasks[i] = 0; + _temporaryValues[i] = 0; + _temporaryIndices[i].Clear(); + + var modelIndex = UsedModels[i]; + var model = human.AsHuman->Models[modelIndex]; + if (model is null || model->ModelResourceHandle is null) + continue; + + ref var shapes = ref model->ModelResourceHandle->Shapes; + foreach (var (shape, index) in shapes.Where(kvp => CheckShapes(kvp.Key.AsSpan(), modelIndex))) + { + if (ShapeString.TryRead(shape.Value, out var shapeString)) + { + _temporaryIndices[i].TryAdd(shapeString, index); + _temporaryMasks[i] |= (ushort)(1 << index); + } + else + { + Penumbra.Log.Warning($"Trying to read a shape string that is too long: {shape}."); + } + } + } + + UpdateMasks(); + } + + private static bool CheckShapes(ReadOnlySpan shape, byte index) + => index switch + { + 1 => shape.StartsWith("shp_wa_"u8) || shape.StartsWith("shp_wr_"u8), + 2 => shape.StartsWith("shp_wr_"u8), + 3 => shape.StartsWith("shp_wa_"u8) || shape.StartsWith("shp_an"u8), + 4 => shape.StartsWith("shp_an"u8), + _ => false, + }; + + private void UpdateMasks() + { + foreach (var (shape, topIndex) in _temporaryIndices[0]) + { + if (_temporaryIndices[1].TryGetValue(shape, out var handIndex)) + { + _temporaryValues[0] |= 1u << topIndex; + _temporaryValues[1] |= 1u << handIndex; + } + + if (_temporaryIndices[2].TryGetValue(shape, out var legIndex)) + { + _temporaryValues[0] |= 1u << topIndex; + _temporaryValues[2] |= 1u << legIndex; + } + } + + foreach (var (shape, bottomIndex) in _temporaryIndices[2]) + { + if (_temporaryIndices[3].TryGetValue(shape, out var footIndex)) + { + _temporaryValues[2] |= 1u << bottomIndex; + _temporaryValues[3] |= 1u << footIndex; + } + } + } +} diff --git a/Penumbra/Meta/ShapeString.cs b/Penumbra/Meta/ShapeString.cs new file mode 100644 index 00000000..987ed474 --- /dev/null +++ b/Penumbra/Meta/ShapeString.cs @@ -0,0 +1,89 @@ +using Lumina.Misc; +using Newtonsoft.Json; +using Penumbra.GameData.Files.PhybStructs; + +namespace Penumbra.Meta; + +[JsonConverter(typeof(Converter))] +public struct ShapeString : IEquatable +{ + public const int MaxLength = 30; + + public static readonly ShapeString Empty = new(); + + private FixedString32 _buffer; + + public int Count + => _buffer[31]; + + public int Length + => _buffer[31]; + + public override string ToString() + => Encoding.UTF8.GetString(_buffer[..Length]); + + public bool Equals(ShapeString other) + => Length == other.Length && _buffer[..Length].SequenceEqual(other._buffer[..Length]); + + public override bool Equals(object? obj) + => obj is ShapeString other && Equals(other); + + public override int GetHashCode() + => (int)Crc32.Get(_buffer[..Length]); + + public static bool operator ==(ShapeString left, ShapeString right) + => left.Equals(right); + + public static bool operator !=(ShapeString left, ShapeString right) + => !left.Equals(right); + + public static unsafe bool TryRead(byte* pointer, out ShapeString ret) + { + var span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(pointer); + return TryRead(span, out ret); + } + + public static bool TryRead(ReadOnlySpan utf8, out ShapeString ret) + { + if (utf8.Length is 0 or > MaxLength) + { + ret = Empty; + return false; + } + + ret = Empty; + utf8.CopyTo(ret._buffer); + ret._buffer[utf8.Length] = 0; + ret._buffer[31] = (byte)utf8.Length; + return true; + } + + public static bool TryRead(ReadOnlySpan utf16, out ShapeString ret) + { + ret = Empty; + if (!Encoding.UTF8.TryGetBytes(utf16, ret._buffer[..MaxLength], out var written)) + return false; + + ret._buffer[written] = 0; + ret._buffer[31] = (byte)written; + return true; + } + + private sealed class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, ShapeString value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString()); + } + + public override ShapeString ReadJson(JsonReader reader, Type objectType, ShapeString existingValue, bool hasExistingValue, + JsonSerializer serializer) + { + var value = serializer.Deserialize(reader); + if (!TryRead(value, out existingValue)) + throw new JsonReaderException($"Could not parse {value} into ShapeString."); + + return existingValue; + } + } +} diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 7f4c1b23..70636bbf 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -34,6 +34,7 @@ public class Penumbra : IDalamudPlugin public static readonly Logger Log = new(); public static MessageService Messager { get; private set; } = null!; + public static DynamisIpc Dynamis { get; private set; } = null!; private readonly ValidityChecker _validityChecker; private readonly ResidentResourceManager _residentResources; @@ -59,8 +60,9 @@ public class Penumbra : IDalamudPlugin _services = StaticServiceManager.CreateProvider(this, pluginInterface, Log); // Invoke the IPC Penumbra.Launching method before any hooks or other services are created. _services.GetService(); - Messager = _services.GetService(); - _validityChecker = _services.GetService(); + Messager = _services.GetService(); + Dynamis = _services.GetService(); + _validityChecker = _services.GetService(); _services.EnsureRequiredServices(); var startup = _services.GetService() @@ -228,6 +230,7 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); sb.Append($"> **`Penumbra Reloads: `** {hdrEnabler.PenumbraReloadCount}\n"); sb.Append($"> **`HDR Enabled (from Start): `** {_config.HdrRenderTargets} ({hdrEnabler is { FirstLaunchHdrState: true, FirstLaunchHdrHookOverrideState: true }}){(hdrEnabler.HdrEnabledSuccess ? ", Detour Called" : ", **NEVER CALLED**")}\n"); + sb.Append($"> **`Custom Shapes Enabled: `** {_config.EnableCustomShapes}\n"); sb.Append($"> **`Hook Overrides: `** {HookOverrides.Instance.IsCustomLoaded}\n"); sb.Append($"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")} (first Start: {hdrEnabler.FirstLaunchWaitForPluginsState?.ToString() ?? "Unknown"})\n"); sb.Append( diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index 5d745419..e008752f 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -81,6 +81,9 @@ public class CommunicatorService : IDisposable, IService /// public readonly ResolvedFileChanged ResolvedFileChanged = new(); + /// + public readonly ModelAttributeComputed ModelAttributeComputed = new(); + public void Dispose() { CollectionChange.Dispose(); @@ -105,5 +108,6 @@ public class CommunicatorService : IDisposable, IService ChangedItemClick.Dispose(); SelectTab.Dispose(); ResolvedFileChanged.Dispose(); + ModelAttributeComputed.Dispose(); } } diff --git a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs index eb9f05d9..3b25c1a9 100644 --- a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs @@ -1,11 +1,11 @@ using ImGuiNET; -using OtterGui.Extensions; -using OtterGui.Text; +using OtterGui.Extensions; +using OtterGui.Text; using Penumbra.GameData.Files; -using Penumbra.GameData.Files.AtchStructs; - -namespace Penumbra.UI.Tabs.Debug; - +using Penumbra.GameData.Files.AtchStructs; + +namespace Penumbra.UI.Tabs.Debug; + public static class AtchDrawer { public static void Draw(AtchFile file) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index b7bc8edf..b4fa3b9f 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -108,6 +108,7 @@ public class DebugTab : Window, ITab, IUiService private readonly ObjectIdentification _objectIdentification; private readonly RenderTargetDrawer _renderTargetDrawer; private readonly ModMigratorDebug _modMigratorDebug; + private readonly ShapeInspector _shapeInspector; public DebugTab(PerformanceTracker performance, Configuration config, CollectionManager collectionManager, ObjectManager objects, IClientState clientState, IDataManager dataManager, @@ -119,7 +120,7 @@ public class DebugTab : Window, ITab, IUiService Diagnostics diagnostics, IpcTester ipcTester, CrashHandlerPanel crashHandlerPanel, TexHeaderDrawer texHeaderDrawer, HookOverrideDrawer hookOverrides, RsfService rsfService, GlobalVariablesDrawer globalVariablesDrawer, SchedulerResourceManagementService schedulerService, ObjectIdentification objectIdentification, RenderTargetDrawer renderTargetDrawer, - ModMigratorDebug modMigratorDebug) + ModMigratorDebug modMigratorDebug, ShapeInspector shapeInspector) : base("Penumbra Debug Window", ImGuiWindowFlags.NoCollapse) { IsOpen = true; @@ -162,6 +163,7 @@ public class DebugTab : Window, ITab, IUiService _objectIdentification = objectIdentification; _renderTargetDrawer = renderTargetDrawer; _modMigratorDebug = modMigratorDebug; + _shapeInspector = shapeInspector; _objects = objects; _clientState = clientState; _dataManager = dataManager; @@ -508,37 +510,50 @@ public class DebugTab : Window, ITab, IUiService if (!ImGui.CollapsingHeader("Actors")) return; - _objects.DrawDebug(); - - using var table = Table("##actors", 8, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, - -Vector2.UnitX); - if (!table) - return; - - DrawSpecial("Current Player", _actors.GetCurrentPlayer()); - DrawSpecial("Current Inspect", _actors.GetInspectPlayer()); - DrawSpecial("Current Card", _actors.GetCardPlayer()); - DrawSpecial("Current Glamour", _actors.GetGlamourPlayer()); - - foreach (var obj in _objects) + using (var objectTree = ImUtf8.TreeNode("Object Manager"u8)) { - ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"{((GameObject*)obj.Address)->ObjectIndex}" : "NULL"); - ImGui.TableNextColumn(); - ImGuiUtil.CopyOnClickSelectable($"0x{obj.Address:X}"); - ImGui.TableNextColumn(); - if (obj.Address != nint.Zero) - ImGuiUtil.CopyOnClickSelectable($"0x{(nint)((Character*)obj.Address)->GameObject.GetDrawObject():X}"); - var identifier = _actors.FromObject(obj, out _, false, true, false); - ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); - var id = obj.AsObject->ObjectKind is ObjectKind.BattleNpc - ? $"{identifier.DataId} | {obj.AsObject->BaseId}" - : identifier.DataId.ToString(); - ImGuiUtil.DrawTableColumn(id); - ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{*(nint*)obj.Address:X}" : "NULL"); - ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{obj.AsObject->EntityId:X}" : "NULL"); - ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero - ? obj.AsObject->IsCharacter() ? $"Character: {obj.AsCharacter->ObjectKind}" : "No Character" - : "NULL"); + if (objectTree) + { + _objects.DrawDebug(); + + using var table = Table("##actors", 8, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingFixedFit, + -Vector2.UnitX); + if (!table) + return; + + DrawSpecial("Current Player", _actors.GetCurrentPlayer()); + DrawSpecial("Current Inspect", _actors.GetInspectPlayer()); + DrawSpecial("Current Card", _actors.GetCardPlayer()); + DrawSpecial("Current Glamour", _actors.GetGlamourPlayer()); + + foreach (var obj in _objects) + { + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"{((GameObject*)obj.Address)->ObjectIndex}" : "NULL"); + ImGui.TableNextColumn(); + Penumbra.Dynamis.DrawPointer(obj.Address); + ImGui.TableNextColumn(); + if (obj.Address != nint.Zero) + Penumbra.Dynamis.DrawPointer((nint)((Character*)obj.Address)->GameObject.GetDrawObject()); + var identifier = _actors.FromObject(obj, out _, false, true, false); + ImGuiUtil.DrawTableColumn(_actors.ToString(identifier)); + var id = obj.AsObject->ObjectKind is ObjectKind.BattleNpc + ? $"{identifier.DataId} | {obj.AsObject->BaseId}" + : identifier.DataId.ToString(); + ImGuiUtil.DrawTableColumn(id); + ImGui.TableNextColumn(); + Penumbra.Dynamis.DrawPointer(obj.Address != nint.Zero ? *(nint*)obj.Address : nint.Zero); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero ? $"0x{obj.AsObject->EntityId:X}" : "NULL"); + ImGuiUtil.DrawTableColumn(obj.Address != nint.Zero + ? obj.AsObject->IsCharacter() ? $"Character: {obj.AsCharacter->ObjectKind}" : "No Character" + : "NULL"); + } + } + } + + using (var shapeTree = ImUtf8.TreeNode("Shape Inspector"u8)) + { + if (shapeTree) + _shapeInspector.Draw(); } return; @@ -1184,8 +1199,16 @@ public class DebugTab : Window, ITab, IUiService /// Draw information about IPC options and availability. private void DrawDebugTabIpc() { - if (ImGui.CollapsingHeader("IPC")) - _ipcTester.Draw(); + if (!ImUtf8.CollapsingHeader("IPC"u8)) + return; + + using (var tree = ImUtf8.TreeNode("Dynamis"u8)) + { + if (tree) + Penumbra.Dynamis.DrawDebugInfo(); + } + + _ipcTester.Draw(); } /// Helper to print a property and its value in a 2-column table. diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs new file mode 100644 index 00000000..968bc484 --- /dev/null +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -0,0 +1,71 @@ +using Dalamud.Interface; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; + +namespace Penumbra.UI.Tabs.Debug; + +public class ShapeInspector(ObjectManager objects) : IUiService +{ + private int _objectIndex = 0; + + public unsafe void Draw() + { + ImUtf8.InputScalar("Object Index"u8, ref _objectIndex); + var actor = objects[0]; + if (!actor.IsCharacter) + { + ImUtf8.Text("No valid character."u8); + return; + } + + var human = actor.Model; + if (!human.IsHuman) + { + ImUtf8.Text("No valid character."u8); + return; + } + + using var table = ImUtf8.Table("##table"u8, 4, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("idx"u8, ImGuiTableColumnFlags.WidthFixed, 25 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("ptr"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); + ImUtf8.TableSetupColumn("mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("shapes"u8, ImGuiTableColumnFlags.WidthStretch); + + var disabledColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); + foreach (var slot in Enum.GetValues()) + { + ImUtf8.DrawTableColumn($"{(uint)slot:D2}"); + ImGui.TableNextColumn(); + var model = human.AsHuman->Models[(int)slot]; + Penumbra.Dynamis.DrawPointer((nint)model); + if (model is not null) + { + var mask = model->EnabledShapeKeyIndexMask; + ImUtf8.DrawTableColumn($"{mask:X8}"); + ImGui.TableNextColumn(); + foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) + { + var disabled = (mask & (1u << idx)) is 0; + using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); + ImUtf8.Text(shape.AsSpan()); + ImGui.SameLine(0, 0); + ImUtf8.Text(", "u8); + if ((idx % 8) < 7) + ImGui.SameLine(0, 0); + } + } + else + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + } + } + } +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index b1f82a91..7b3a3c8b 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -14,6 +14,7 @@ using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections; +using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Services; using Penumbra.Mods.Manager; using Penumbra.Services; @@ -50,6 +51,7 @@ public class SettingsTab : ITab, IUiService private readonly MigrationSectionDrawer _migrationDrawer; private readonly CollectionAutoSelector _autoSelector; private readonly CleanupService _cleanupService; + private readonly AttributeHooks _attributeHooks; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -61,7 +63,8 @@ public class SettingsTab : ITab, IUiService CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, - MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService) + MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, + AttributeHooks attributeHooks) { _pluginInterface = pluginInterface; _config = config; @@ -86,6 +89,7 @@ public class SettingsTab : ITab, IUiService _migrationDrawer = migrationDrawer; _autoSelector = autoSelector; _cleanupService = cleanupService; + _attributeHooks = attributeHooks; } public void DrawHeader() @@ -807,6 +811,8 @@ public class SettingsTab : ITab, IUiService "Normally, metadata changes that equal their default values, which are sometimes exported by TexTools, are discarded. " + "Toggle this to keep them, for example if an option in a mod is supposed to disable a metadata change from a prior option.", _config.KeepDefaultMetaChanges, v => _config.KeepDefaultMetaChanges = v); + Checkbox("Enable Advanced Shape Support", "Penumbra will allow for custom shape keys for modded models to be considered and combined.", + _config.EnableAttributeHooks, _attributeHooks.SetState); DrawWaitForPluginsReflection(); DrawEnableHttpApiBox(); DrawEnableDebugModeBox(); diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index dda6b305..4a162f8f 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -2,12 +2,6 @@ "version": 1, "dependencies": { "net9.0-windows7.0": { - "DalamudPackager": { - "type": "Direct", - "requested": "[12.0.0, )", - "resolved": "12.0.0", - "contentHash": "J5TJLV3f16T/E2H2P17ClWjtfEBPpq3yxvqW46eN36JCm6wR+EaoaYkqG9Rm5sHqs3/nK/vKjWWyvEs/jhKoXw==" - }, "DotNet.ReproducibleBuilds": { "type": "Direct", "requested": "[1.2.25, )", From 6ad0b4299a29486af69a02d96bbf71cbbb77e939 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 15 May 2025 17:46:53 +0200 Subject: [PATCH 1202/1381] Add shape meta manipulations and rework attribute hook. --- OtterGui | 2 +- Penumbra.GameData | 2 +- Penumbra.sln | 1 + Penumbra/Collections/Cache/CollectionCache.cs | 2 + Penumbra/Collections/Cache/MetaCache.cs | 9 +- Penumbra/Collections/Cache/ShpCache.cs | 109 ++++++++ .../Communication/ModelAttributeComputed.cs | 24 -- .../Hooks/PostProcessing/AttributeHook.cs | 85 ++++++ .../Hooks/PostProcessing/AttributeHooks.cs | 110 -------- .../Meta/Manipulations/IMetaIdentifier.cs | 1 + Penumbra/Meta/Manipulations/MetaDictionary.cs | 72 ++++- Penumbra/Meta/Manipulations/ShpIdentifier.cs | 157 +++++++++++ Penumbra/Meta/ShapeManager.cs | 117 ++++----- Penumbra/Meta/ShapeString.cs | 33 ++- Penumbra/Services/CommunicatorService.cs | 4 - .../UI/AdvancedWindow/Meta/MetaDrawers.cs | 5 +- .../UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 247 ++++++++++++++++++ .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 1 + Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 114 +++++--- Penumbra/UI/Tabs/SettingsTab.cs | 64 +---- schemas/structs/manipulation.json | 12 +- schemas/structs/meta_enums.json | 4 + schemas/structs/meta_shp.json | 23 ++ 23 files changed, 900 insertions(+), 298 deletions(-) create mode 100644 Penumbra/Collections/Cache/ShpCache.cs delete mode 100644 Penumbra/Communication/ModelAttributeComputed.cs create mode 100644 Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs delete mode 100644 Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs create mode 100644 Penumbra/Meta/Manipulations/ShpIdentifier.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs create mode 100644 schemas/structs/meta_shp.json diff --git a/OtterGui b/OtterGui index 86b49242..f130c928 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 86b492422565abde2e8ad17c0295896a21c3439c +Subproject commit f130c928928cb0d48d3c807b7df5874c2460fe98 diff --git a/Penumbra.GameData b/Penumbra.GameData index 0ca50105..8e57c2e1 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 0ca501050de72ee1cc7382dfae894f984ce241b6 +Subproject commit 8e57c2e12570bb1795efb9e5c6e38617aa8dd5e3 diff --git a/Penumbra.sln b/Penumbra.sln index e52045b0..642876ef 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -50,6 +50,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "structs", "structs", "{B03F schemas\structs\meta_gmp.json = schemas\structs\meta_gmp.json schemas\structs\meta_imc.json = schemas\structs\meta_imc.json schemas\structs\meta_rsp.json = schemas\structs\meta_rsp.json + schemas\structs\meta_shp.json = schemas\structs\meta_shp.json schemas\structs\option.json = schemas\structs\option.json EndProjectSection EndProject diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index f6f038a1..c48a487c 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -245,6 +245,8 @@ public sealed class CollectionCache : IDisposable AddManipulation(mod, identifier, entry); foreach (var (identifier, entry) in files.Manipulations.Atch) AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Shp) + AddManipulation(mod, identifier, entry); foreach (var identifier in files.Manipulations.GlobalEqp) AddManipulation(mod, identifier, null!); } diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 7d8586c3..790dd3af 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -16,11 +16,12 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public readonly RspCache Rsp = new(manager, collection); public readonly ImcCache Imc = new(manager, collection); public readonly AtchCache Atch = new(manager, collection); + public readonly ShpCache Shp = new(manager, collection); public readonly GlobalEqpCache GlobalEqp = new(); public bool IsDisposed { get; private set; } public int Count - => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + Atch.Count + GlobalEqp.Count; + => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + Atch.Count + Shp.Count + GlobalEqp.Count; public IEnumerable<(IMetaIdentifier, IMod)> IdentifierSources => Eqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source)) @@ -30,6 +31,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) .Concat(Rsp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(Imc.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(Atch.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Shp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(GlobalEqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value))); public void Reset() @@ -41,6 +43,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Rsp.Reset(); Imc.Reset(); Atch.Reset(); + Shp.Reset(); GlobalEqp.Clear(); } @@ -57,6 +60,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Rsp.Dispose(); Imc.Dispose(); Atch.Dispose(); + Shp.Dispose(); } public bool TryGetMod(IMetaIdentifier identifier, [NotNullWhen(true)] out IMod? mod) @@ -71,6 +75,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) ImcIdentifier i => Imc.TryGetValue(i, out var p) && Convert(p, out mod), RspIdentifier i => Rsp.TryGetValue(i, out var p) && Convert(p, out mod), AtchIdentifier i => Atch.TryGetValue(i, out var p) && Convert(p, out mod), + ShpIdentifier i => Shp.TryGetValue(i, out var p) && Convert(p, out mod), GlobalEqpManipulation i => GlobalEqp.TryGetValue(i, out mod), _ => false, }; @@ -92,6 +97,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) ImcIdentifier i => Imc.RevertMod(i, out mod), RspIdentifier i => Rsp.RevertMod(i, out mod), AtchIdentifier i => Atch.RevertMod(i, out mod), + ShpIdentifier i => Shp.RevertMod(i, out mod), GlobalEqpManipulation i => GlobalEqp.RevertMod(i, out mod), _ => (mod = null) != null, }; @@ -108,6 +114,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) ImcIdentifier i when entry is ImcEntry e => Imc.ApplyMod(mod, i, e), RspIdentifier i when entry is RspEntry e => Rsp.ApplyMod(mod, i, e), AtchIdentifier i when entry is AtchEntry e => Atch.ApplyMod(mod, i, e), + ShpIdentifier i when entry is ShpEntry e => Shp.ApplyMod(mod, i, e), GlobalEqpManipulation i => GlobalEqp.ApplyMod(mod, i), _ => false, }; diff --git a/Penumbra/Collections/Cache/ShpCache.cs b/Penumbra/Collections/Cache/ShpCache.cs new file mode 100644 index 00000000..2e90052d --- /dev/null +++ b/Penumbra/Collections/Cache/ShpCache.cs @@ -0,0 +1,109 @@ +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Collections.Cache; + +public sealed class ShpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) +{ + public bool ShouldBeEnabled(in ShapeString shape, HumanSlot slot, PrimaryId id) + => _shpData.TryGetValue(shape, out var value) && value.Contains(slot, id); + + internal IReadOnlyDictionary State + => _shpData; + + internal sealed class ShpHashSet : HashSet<(HumanSlot Slot, PrimaryId Id)> + { + private readonly BitArray _allIds = new(ShapeManager.ModelSlotSize); + + public bool All + { + get => _allIds[^1]; + set => _allIds[^1] = value; + } + + public bool this[HumanSlot slot] + { + get + { + if (slot is HumanSlot.Unknown) + return All; + + return _allIds[(int)slot]; + } + set + { + if (slot is HumanSlot.Unknown) + _allIds[^1] = value; + else + _allIds[(int)slot] = value; + } + } + + public bool Contains(HumanSlot slot, PrimaryId id) + => All || this[slot] || Contains((slot, id)); + + public bool TrySet(HumanSlot slot, PrimaryId? id, ShpEntry value) + { + if (slot is HumanSlot.Unknown) + { + var old = All; + All = value.Value; + return old != value.Value; + } + + if (!id.HasValue) + { + var old = this[slot]; + this[slot] = value.Value; + return old != value.Value; + } + + if (value.Value) + return Add((slot, id.Value)); + + return Remove((slot, id.Value)); + } + + public new void Clear() + { + base.Clear(); + _allIds.SetAll(false); + } + + public bool IsEmpty + => !_allIds.HasAnySet() && Count is 0; + } + + private readonly Dictionary _shpData = []; + + public void Reset() + { + Clear(); + _shpData.Clear(); + } + + protected override void Dispose(bool _) + => Clear(); + + protected override void ApplyModInternal(ShpIdentifier identifier, ShpEntry entry) + { + if (!_shpData.TryGetValue(identifier.Shape, out var value)) + { + value = []; + _shpData.Add(identifier.Shape, value); + } + + value.TrySet(identifier.Slot, identifier.Id, entry); + } + + protected override void RevertModInternal(ShpIdentifier identifier) + { + if (!_shpData.TryGetValue(identifier.Shape, out var value)) + return; + + if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False) && value.IsEmpty) + _shpData.Remove(identifier.Shape); + } +} diff --git a/Penumbra/Communication/ModelAttributeComputed.cs b/Penumbra/Communication/ModelAttributeComputed.cs deleted file mode 100644 index 389f56b6..00000000 --- a/Penumbra/Communication/ModelAttributeComputed.cs +++ /dev/null @@ -1,24 +0,0 @@ -using OtterGui.Classes; -using Penumbra.Collections; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Interop; - -namespace Penumbra.Communication; - -/// -/// Triggered whenever a model recomputes its attribute masks. -/// -/// Parameter is the game object that recomputed its attributes. -/// Parameter is the draw object on which the recomputation was called. -/// Parameter is the collection associated with the game object. -/// Parameter is the slot that was recomputed. If this is Unknown, it is a general new update call. -/// -public sealed class ModelAttributeComputed() - : EventWrapper(nameof(ModelAttributeComputed)) -{ - public enum Priority - { - /// - ShapeManager = 0, - } -} diff --git a/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs b/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs new file mode 100644 index 00000000..cad049ad --- /dev/null +++ b/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs @@ -0,0 +1,85 @@ +using Dalamud.Hooking; +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.GameData; +using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta; + +namespace Penumbra.Interop.Hooks.PostProcessing; + +/// +/// Triggered whenever a model recomputes its attribute masks. +/// +/// Parameter is the game object that recomputed its attributes. +/// Parameter is the draw object on which the recomputation was called. +/// Parameter is the collection associated with the game object. +/// Parameter is the slot that was recomputed. If this is Unknown, it is a general new update call. +/// +public sealed unsafe class AttributeHook : EventWrapper, IHookService +{ + public enum Priority + { + /// + ShapeManager = 0, + } + + private readonly CollectionResolver _resolver; + private readonly Configuration _config; + + public AttributeHook(HookManager hooks, Configuration config, CollectionResolver resolver) + : base("Update Model Attributes") + { + _config = config; + _resolver = resolver; + _task = hooks.CreateHook(Name, Sigs.UpdateAttributes, Detour, config.EnableCustomShapes); + } + + private readonly Task> _task; + + public nint Address + => _task.Result.Address; + + public void Enable() + => SetState(true); + + public void Disable() + => SetState(false); + + public void SetState(bool enabled) + { + if (_config.EnableCustomShapes == enabled) + return; + + _config.EnableCustomShapes = enabled; + _config.Save(); + if (enabled) + _task.Result.Enable(); + else + _task.Result.Disable(); + } + + + public Task Awaiter + => _task; + + public bool Finished + => _task.IsCompletedSuccessfully; + + private delegate void Delegate(Human* human); + + private void Detour(Human* human) + { + _task.Result.Original(human); + var resolveData = _resolver.IdentifyCollection((DrawObject*)human, true); + var identifiedActor = resolveData.AssociatedGameObject; + var identifiedCollection = resolveData.ModCollection; + Penumbra.Log.Excessive($"[{Name}] Invoked on 0x{(ulong)human:X} (0x{identifiedActor:X})."); + Invoke(identifiedActor, human, identifiedCollection); + } + + protected override void Dispose(bool disposing) + => _task.Result.Dispose(); +} diff --git a/Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs b/Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs deleted file mode 100644 index 861962ee..00000000 --- a/Penumbra/Interop/Hooks/PostProcessing/AttributeHooks.cs +++ /dev/null @@ -1,110 +0,0 @@ -using Dalamud.Hooking; -using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using OtterGui.Services; -using Penumbra.Collections; -using Penumbra.Communication; -using Penumbra.GameData; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Interop; -using Penumbra.Interop.PathResolving; -using Penumbra.Services; - -namespace Penumbra.Interop.Hooks.PostProcessing; - -public sealed unsafe class AttributeHooks : IRequiredService, IDisposable -{ - private delegate void SetupAttributes(Human* human, byte* data); - private delegate void AttributeUpdate(Human* human); - - private readonly Configuration _config; - private readonly ModelAttributeComputed _event; - private readonly CollectionResolver _resolver; - - private readonly AttributeHook[] _hooks; - private readonly Task> _updateHook; - private ModCollection _identifiedCollection = ModCollection.Empty; - private Actor _identifiedActor = Actor.Null; - private bool _inUpdate; - - public AttributeHooks(Configuration config, CommunicatorService communication, CollectionResolver resolver, HookManager hooks) - { - _config = config; - _event = communication.ModelAttributeComputed; - _resolver = resolver; - _hooks = - [ - new AttributeHook(this, hooks, Sigs.SetupTopModelAttributes, _config.EnableCustomShapes, HumanSlot.Body), - new AttributeHook(this, hooks, Sigs.SetupHandModelAttributes, _config.EnableCustomShapes, HumanSlot.Hands), - new AttributeHook(this, hooks, Sigs.SetupLegModelAttributes, _config.EnableCustomShapes, HumanSlot.Legs), - new AttributeHook(this, hooks, Sigs.SetupFootModelAttributes, _config.EnableCustomShapes, HumanSlot.Feet), - ]; - _updateHook = hooks.CreateHook("UpdateAttributes", Sigs.UpdateAttributes, UpdateAttributesDetour, - _config.EnableCustomShapes); - } - - private class AttributeHook - { - private readonly AttributeHooks _parent; - public readonly string Name; - public readonly Task> Hook; - public readonly uint ModelIndex; - public readonly HumanSlot Slot; - - public AttributeHook(AttributeHooks parent, HookManager hooks, string signature, bool enabled, HumanSlot slot) - { - _parent = parent; - Name = $"Setup{slot}Attributes"; - Slot = slot; - ModelIndex = slot.ToIndex(); - Hook = hooks.CreateHook(Name, signature, Detour, enabled); - } - - private void Detour(Human* human, byte* data) - { - Penumbra.Log.Excessive($"[{Name}] Invoked on 0x{(ulong)human:X} (0x{_parent._identifiedActor.Address:X})."); - Hook.Result.Original(human, data); - if (_parent is { _inUpdate: true, _identifiedActor.Valid: true }) - _parent._event.Invoke(_parent._identifiedActor, human, _parent._identifiedCollection, Slot); - } - } - - private void UpdateAttributesDetour(Human* human) - { - var resolveData = _resolver.IdentifyCollection((DrawObject*)human, true); - _identifiedActor = resolveData.AssociatedGameObject; - _identifiedCollection = resolveData.ModCollection; - _inUpdate = true; - Penumbra.Log.Excessive($"[UpdateAttributes] Invoked on 0x{(ulong)human:X} (0x{_identifiedActor.Address:X})."); - _event.Invoke(_identifiedActor, human, _identifiedCollection, HumanSlot.Unknown); - _updateHook.Result.Original(human); - _inUpdate = false; - } - - public void SetState(bool enabled) - { - if (_config.EnableCustomShapes == enabled) - return; - - _config.EnableCustomShapes = enabled; - _config.Save(); - if (enabled) - { - foreach (var hook in _hooks) - hook.Hook.Result.Enable(); - _updateHook.Result.Enable(); - } - else - { - foreach (var hook in _hooks) - hook.Hook.Result.Disable(); - _updateHook.Result.Disable(); - } - } - - public void Dispose() - { - foreach (var hook in _hooks) - hook.Hook.Result.Dispose(); - _updateHook.Result.Dispose(); - } -} diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs index c897bb2a..13feba51 100644 --- a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -15,6 +15,7 @@ public enum MetaManipulationType : byte Rsp = 6, GlobalEqp = 7, Atch = 8, + Shp = 9, } public interface IMetaIdentifier diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index ca45c777..a7225067 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -18,6 +18,7 @@ public class MetaDictionary private readonly Dictionary _rsp = []; private readonly Dictionary _gmp = []; private readonly Dictionary _atch = []; + private readonly Dictionary _shp = []; private readonly HashSet _globalEqp = []; public IReadOnlyDictionary Imc @@ -41,6 +42,9 @@ public class MetaDictionary public IReadOnlyDictionary Atch => _atch; + public IReadOnlyDictionary Shp + => _shp; + public IReadOnlySet GlobalEqp => _globalEqp; @@ -56,6 +60,7 @@ public class MetaDictionary MetaManipulationType.Gmp => _gmp.Count, MetaManipulationType.Rsp => _rsp.Count, MetaManipulationType.Atch => _atch.Count, + MetaManipulationType.Shp => _shp.Count, MetaManipulationType.GlobalEqp => _globalEqp.Count, _ => 0, }; @@ -70,6 +75,7 @@ public class MetaDictionary GmpIdentifier i => _gmp.ContainsKey(i), ImcIdentifier i => _imc.ContainsKey(i), AtchIdentifier i => _atch.ContainsKey(i), + ShpIdentifier i => _shp.ContainsKey(i), RspIdentifier i => _rsp.ContainsKey(i), _ => false, }; @@ -84,6 +90,7 @@ public class MetaDictionary _rsp.Clear(); _gmp.Clear(); _atch.Clear(); + _shp.Clear(); _globalEqp.Clear(); } @@ -108,6 +115,7 @@ public class MetaDictionary && _rsp.SetEquals(other._rsp) && _gmp.SetEquals(other._gmp) && _atch.SetEquals(other._atch) + && _shp.SetEquals(other._shp) && _globalEqp.SetEquals(other._globalEqp); public IEnumerable Identifiers @@ -118,6 +126,7 @@ public class MetaDictionary .Concat(_gmp.Keys.Cast()) .Concat(_rsp.Keys.Cast()) .Concat(_atch.Keys.Cast()) + .Concat(_shp.Keys.Cast()) .Concat(_globalEqp.Cast()); #region TryAdd @@ -191,6 +200,15 @@ public class MetaDictionary return true; } + public bool TryAdd(ShpIdentifier identifier, in ShpEntry entry) + { + if (!_shp.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + public bool TryAdd(GlobalEqpManipulation identifier) { if (!_globalEqp.Add(identifier)) @@ -273,6 +291,15 @@ public class MetaDictionary return true; } + public bool Update(ShpIdentifier identifier, in ShpEntry entry) + { + if (!_shp.ContainsKey(identifier)) + return false; + + _shp[identifier] = entry; + return true; + } + #endregion #region TryGetValue @@ -298,6 +325,9 @@ public class MetaDictionary public bool TryGetValue(AtchIdentifier identifier, out AtchEntry value) => _atch.TryGetValue(identifier, out value); + public bool TryGetValue(ShpIdentifier identifier, out ShpEntry value) + => _shp.TryGetValue(identifier, out value); + #endregion public bool Remove(IMetaIdentifier identifier) @@ -312,6 +342,7 @@ public class MetaDictionary ImcIdentifier i => _imc.Remove(i), RspIdentifier i => _rsp.Remove(i), AtchIdentifier i => _atch.Remove(i), + ShpIdentifier i => _shp.Remove(i), _ => false, }; if (ret) @@ -344,6 +375,9 @@ public class MetaDictionary foreach (var (identifier, entry) in manips._atch) TryAdd(identifier, entry); + foreach (var (identifier, entry) in manips._shp) + TryAdd(identifier, entry); + foreach (var identifier in manips._globalEqp) TryAdd(identifier); } @@ -393,13 +427,19 @@ public class MetaDictionary return false; } + foreach (var (identifier, _) in manips._shp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + { + failedIdentifier = identifier; + return false; + } + foreach (var identifier in manips._globalEqp.Where(identifier => !TryAdd(identifier))) { failedIdentifier = identifier; return false; } - failedIdentifier = default; + failedIdentifier = null; return true; } @@ -412,8 +452,9 @@ public class MetaDictionary _rsp.SetTo(other._rsp); _gmp.SetTo(other._gmp); _atch.SetTo(other._atch); + _shp.SetTo(other._shp); _globalEqp.SetTo(other._globalEqp); - Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _globalEqp.Count; + Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _shp.Count + _globalEqp.Count; } public void UpdateTo(MetaDictionary other) @@ -425,8 +466,9 @@ public class MetaDictionary _rsp.UpdateTo(other._rsp); _gmp.UpdateTo(other._gmp); _atch.UpdateTo(other._atch); + _shp.UpdateTo(other._shp); _globalEqp.UnionWith(other._globalEqp); - Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _globalEqp.Count; + Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _shp.Count + _globalEqp.Count; } #endregion @@ -514,6 +556,16 @@ public class MetaDictionary }), }; + public static JObject Serialize(ShpIdentifier identifier, ShpEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Shp.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = entry.Value, + }), + }; + public static JObject Serialize(GlobalEqpManipulation identifier) => new() { @@ -543,6 +595,8 @@ public class MetaDictionary return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); if (typeof(TIdentifier) == typeof(AtchIdentifier) && typeof(TEntry) == typeof(AtchEntry)) return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(ShpIdentifier) && typeof(TEntry) == typeof(ShpEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); if (typeof(TIdentifier) == typeof(GlobalEqpManipulation)) return Serialize(Unsafe.As(ref identifier)); @@ -588,6 +642,7 @@ public class MetaDictionary SerializeTo(array, value._rsp); SerializeTo(array, value._gmp); SerializeTo(array, value._atch); + SerializeTo(array, value._shp); SerializeTo(array, value._globalEqp); array.WriteTo(writer); } @@ -685,6 +740,16 @@ public class MetaDictionary Penumbra.Log.Warning("Invalid ATCH Manipulation encountered."); break; } + case MetaManipulationType.Shp: + { + var identifier = ShpIdentifier.FromJson(manip); + var entry = new ShpEntry(manip["Entry"]?.Value() ?? true); + if (identifier.HasValue) + dict.TryAdd(identifier.Value, entry); + else + Penumbra.Log.Warning("Invalid SHP Manipulation encountered."); + break; + } case MetaManipulationType.GlobalEqp: { var identifier = GlobalEqpManipulation.FromJson(manip); @@ -716,6 +781,7 @@ public class MetaDictionary _gmp = cache.Gmp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); _rsp = cache.Rsp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); _atch = cache.Atch.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + _shp = cache.Shp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); _globalEqp = cache.GlobalEqp.Select(kvp => kvp.Key).ToHashSet(); Count = cache.Count; } diff --git a/Penumbra/Meta/Manipulations/ShpIdentifier.cs b/Penumbra/Meta/Manipulations/ShpIdentifier.cs new file mode 100644 index 00000000..fffa51ba --- /dev/null +++ b/Penumbra/Meta/Manipulations/ShpIdentifier.cs @@ -0,0 +1,157 @@ +using Lumina.Models.Models; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeString Shape) + : IComparable, IMetaIdentifier +{ + public int CompareTo(ShpIdentifier other) + { + var slotComparison = Slot.CompareTo(other.Slot); + if (slotComparison is not 0) + return slotComparison; + + if (Id.HasValue) + { + if (other.Id.HasValue) + { + var idComparison = Id.Value.Id.CompareTo(other.Id.Value.Id); + if (idComparison is not 0) + return idComparison; + } + else + { + return -1; + } + } + else if (other.Id.HasValue) + { + return 1; + } + + + return Shape.CompareTo(other.Shape); + } + + public override string ToString() + => $"Shp - {Shape}{(Slot is HumanSlot.Unknown ? " - All Slots & IDs" : $" - {Slot.ToName()}{(Id.HasValue ? $" - {Id.Value.Id}" : " - All IDs")}")}"; + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + // Nothing for now since it depends entirely on the shape key. + } + + public MetaIndex FileIndex() + => (MetaIndex)(-1); + + public bool Validate() + { + if (!Enum.IsDefined(Slot) || Slot is HumanSlot.UnkBonus) + return false; + + if (Slot is HumanSlot.Unknown && Id is not null) + return false; + + return ValidateCustomShapeString(Shape); + } + + public static bool ValidateCustomShapeString(ReadOnlySpan shape) + { + // "shp_xx_y" + if (shape.Length < 8) + return false; + + if (shape[0] is not (byte)'s' + || shape[1] is not (byte)'h' + || shape[2] is not (byte)'p' + || shape[3] is not (byte)'_' + || shape[6] is not (byte)'_') + return false; + + return true; + } + + public static unsafe bool ValidateCustomShapeString(byte* shape) + { + // "shp_xx_y" + if (shape is null) + return false; + + if (*shape++ is not (byte)'s' + || *shape++ is not (byte)'h' + || *shape++ is not (byte)'p' + || *shape++ is not (byte)'_' + || *shape++ is 0 + || *shape++ is 0 + || *shape++ is not (byte)'_' + || *shape is 0) + return false; + + return true; + } + + public static bool ValidateCustomShapeString(in ShapeString shape) + { + // "shp_xx_y" + if (shape.Length < 8) + return false; + + var span = shape.AsSpan; + if (span[0] is not (byte)'s' + || span[1] is not (byte)'h' + || span[2] is not (byte)'p' + || span[3] is not (byte)'_' + || span[6] is not (byte)'_') + return false; + + return true; + } + + public JObject AddToJson(JObject jObj) + { + if (Slot is not HumanSlot.Unknown) + jObj["Slot"] = Slot.ToString(); + if (Id.HasValue) + jObj["Id"] = Id.Value.Id.ToString(); + jObj["Shape"] = Shape.ToString(); + return jObj; + } + + public static ShpIdentifier? FromJson(JObject jObj) + { + var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; + var id = jObj["Id"]?.ToObject(); + var shape = jObj["Shape"]?.ToObject(); + if (shape is null || !ShapeString.TryRead(shape, out var shapeString)) + return null; + + var identifier = new ShpIdentifier(slot, id, shapeString); + return identifier.Validate() ? identifier : null; + } + + public MetaManipulationType Type + => MetaManipulationType.Shp; +} + +[JsonConverter(typeof(Converter))] +public readonly record struct ShpEntry(bool Value) +{ + public static readonly ShpEntry True = new(true); + public static readonly ShpEntry False = new(false); + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, ShpEntry value, JsonSerializer serializer) + => serializer.Serialize(writer, value.Value); + + public override ShpEntry ReadJson(JsonReader reader, Type objectType, ShpEntry existingValue, bool hasExistingValue, + JsonSerializer serializer) + => new(serializer.Deserialize(reader)); + } +} diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs index 4356086a..ec8ddb50 100644 --- a/Penumbra/Meta/ShapeManager.cs +++ b/Penumbra/Meta/ShapeManager.cs @@ -1,24 +1,30 @@ +using System.Reflection.Metadata.Ecma335; using OtterGui.Services; using Penumbra.Collections; -using Penumbra.Communication; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; -using Penumbra.Services; +using Penumbra.Interop.Hooks.PostProcessing; +using Penumbra.Meta.Manipulations; namespace Penumbra.Meta; public class ShapeManager : IRequiredService, IDisposable { - public const int NumSlots = 4; - private readonly CommunicatorService _communicator; + public const int NumSlots = 14; + public const int ModelSlotSize = 18; + private readonly AttributeHook _attributeHook; - private static ReadOnlySpan UsedModels - => [1, 2, 3, 4]; + public static ReadOnlySpan UsedModels + => + [ + HumanSlot.Head, HumanSlot.Body, HumanSlot.Hands, HumanSlot.Legs, HumanSlot.Feet, HumanSlot.Ears, HumanSlot.Neck, HumanSlot.Wrists, + HumanSlot.RFinger, HumanSlot.LFinger, HumanSlot.Glasses, HumanSlot.Hair, HumanSlot.Face, HumanSlot.Ear, + ]; - public ShapeManager(CommunicatorService communicator) + public ShapeManager(AttributeHook attributeHook) { - _communicator = communicator; - _communicator.ModelAttributeComputed.Subscribe(OnAttributeComputed, ModelAttributeComputed.Priority.ShapeManager); + _attributeHook = attributeHook; + _attributeHook.Subscribe(OnAttributeComputed, AttributeHook.Priority.ShapeManager); } private readonly Dictionary[] _temporaryIndices = @@ -27,38 +33,30 @@ public class ShapeManager : IRequiredService, IDisposable private readonly uint[] _temporaryMasks = new uint[NumSlots]; private readonly uint[] _temporaryValues = new uint[NumSlots]; - private unsafe void OnAttributeComputed(Actor actor, Model model, ModCollection collection, HumanSlot slot) - { - int index; - switch (slot) - { - case HumanSlot.Unknown: - ResetCache(model); - return; - case HumanSlot.Body: index = 0; break; - case HumanSlot.Hands: index = 1; break; - case HumanSlot.Legs: index = 2; break; - case HumanSlot.Feet: index = 3; break; - default: return; - } + public void Dispose() + => _attributeHook.Unsubscribe(OnAttributeComputed); - if (_temporaryMasks[index] is 0) + private unsafe void OnAttributeComputed(Actor actor, Model model, ModCollection collection) + { + ComputeCache(model, collection); + for (var i = 0; i < NumSlots; ++i) + { + if (_temporaryMasks[i] is 0) + continue; + + var modelIndex = UsedModels[i]; + var currentMask = model.AsHuman->Models[modelIndex.ToIndex()]->EnabledShapeKeyIndexMask; + var newMask = (currentMask & ~_temporaryMasks[i]) | _temporaryValues[i]; + Penumbra.Log.Excessive($"Changed Model Mask from {currentMask:X} to {newMask:X}."); + model.AsHuman->Models[modelIndex.ToIndex()]->EnabledShapeKeyIndexMask = newMask; + } + } + + private unsafe void ComputeCache(Model human, ModCollection collection) + { + if (!collection.HasCache) return; - var modelIndex = UsedModels[index]; - var currentMask = model.AsHuman->Models[modelIndex]->EnabledShapeKeyIndexMask; - var newMask = (currentMask & ~_temporaryMasks[index]) | _temporaryValues[index]; - Penumbra.Log.Excessive($"Changed Model Mask from {currentMask:X} to {newMask:X}."); - model.AsHuman->Models[modelIndex]->EnabledShapeKeyIndexMask = newMask; - } - - public void Dispose() - { - _communicator.ModelAttributeComputed.Unsubscribe(OnAttributeComputed); - } - - private unsafe void ResetCache(Model human) - { for (var i = 0; i < NumSlots; ++i) { _temporaryMasks[i] = 0; @@ -66,17 +64,20 @@ public class ShapeManager : IRequiredService, IDisposable _temporaryIndices[i].Clear(); var modelIndex = UsedModels[i]; - var model = human.AsHuman->Models[modelIndex]; + var model = human.AsHuman->Models[modelIndex.ToIndex()]; if (model is null || model->ModelResourceHandle is null) continue; ref var shapes = ref model->ModelResourceHandle->Shapes; - foreach (var (shape, index) in shapes.Where(kvp => CheckShapes(kvp.Key.AsSpan(), modelIndex))) + foreach (var (shape, index) in shapes.Where(kvp => ShpIdentifier.ValidateCustomShapeString(kvp.Key.Value))) { if (ShapeString.TryRead(shape.Value, out var shapeString)) { _temporaryIndices[i].TryAdd(shapeString, index); _temporaryMasks[i] |= (ushort)(1 << index); + if (collection.MetaCache!.Shp.State.Count > 0 + && collection.MetaCache!.Shp.ShouldBeEnabled(shapeString, modelIndex, human.GetArmorChanged(modelIndex).Set)) + _temporaryValues[i] |= (ushort)(1 << index); } else { @@ -85,42 +86,32 @@ public class ShapeManager : IRequiredService, IDisposable } } - UpdateMasks(); + UpdateDefaultMasks(); } - private static bool CheckShapes(ReadOnlySpan shape, byte index) - => index switch - { - 1 => shape.StartsWith("shp_wa_"u8) || shape.StartsWith("shp_wr_"u8), - 2 => shape.StartsWith("shp_wr_"u8), - 3 => shape.StartsWith("shp_wa_"u8) || shape.StartsWith("shp_an"u8), - 4 => shape.StartsWith("shp_an"u8), - _ => false, - }; - - private void UpdateMasks() + private void UpdateDefaultMasks() { - foreach (var (shape, topIndex) in _temporaryIndices[0]) + foreach (var (shape, topIndex) in _temporaryIndices[1]) { - if (_temporaryIndices[1].TryGetValue(shape, out var handIndex)) + if (shape[4] is (byte)'w' && shape[5] is (byte)'r' && _temporaryIndices[2].TryGetValue(shape, out var handIndex)) { - _temporaryValues[0] |= 1u << topIndex; - _temporaryValues[1] |= 1u << handIndex; + _temporaryValues[1] |= 1u << topIndex; + _temporaryValues[2] |= 1u << handIndex; } - if (_temporaryIndices[2].TryGetValue(shape, out var legIndex)) + if (shape[4] is (byte)'w' && shape[5] is (byte)'a' && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) { - _temporaryValues[0] |= 1u << topIndex; - _temporaryValues[2] |= 1u << legIndex; + _temporaryValues[1] |= 1u << topIndex; + _temporaryValues[3] |= 1u << legIndex; } } - foreach (var (shape, bottomIndex) in _temporaryIndices[2]) + foreach (var (shape, bottomIndex) in _temporaryIndices[3]) { - if (_temporaryIndices[3].TryGetValue(shape, out var footIndex)) + if (shape[4] is (byte)'a' && shape[5] is (byte)'n' && _temporaryIndices[4].TryGetValue(shape, out var footIndex)) { - _temporaryValues[2] |= 1u << bottomIndex; - _temporaryValues[3] |= 1u << footIndex; + _temporaryValues[3] |= 1u << bottomIndex; + _temporaryValues[4] |= 1u << footIndex; } } } diff --git a/Penumbra/Meta/ShapeString.cs b/Penumbra/Meta/ShapeString.cs index 987ed474..5b6f9c52 100644 --- a/Penumbra/Meta/ShapeString.cs +++ b/Penumbra/Meta/ShapeString.cs @@ -1,11 +1,12 @@ using Lumina.Misc; using Newtonsoft.Json; using Penumbra.GameData.Files.PhybStructs; +using Penumbra.String.Functions; namespace Penumbra.Meta; [JsonConverter(typeof(Converter))] -public struct ShapeString : IEquatable +public struct ShapeString : IEquatable, IComparable { public const int MaxLength = 30; @@ -22,6 +23,20 @@ public struct ShapeString : IEquatable public override string ToString() => Encoding.UTF8.GetString(_buffer[..Length]); + public byte this[int index] + => _buffer[index]; + + public unsafe ReadOnlySpan AsSpan + { + get + { + fixed (void* ptr = &this) + { + return new ReadOnlySpan(ptr, Length); + } + } + } + public bool Equals(ShapeString other) => Length == other.Length && _buffer[..Length].SequenceEqual(other._buffer[..Length]); @@ -43,6 +58,14 @@ public struct ShapeString : IEquatable return TryRead(span, out ret); } + public unsafe int CompareTo(ShapeString other) + { + fixed (void* lhs = &this) + { + return ByteStringFunctions.Compare((byte*)lhs, Length, (byte*)&other, other.Length); + } + } + public static bool TryRead(ReadOnlySpan utf8, out ShapeString ret) { if (utf8.Length is 0 or > MaxLength) @@ -69,6 +92,14 @@ public struct ShapeString : IEquatable return true; } + public void ForceLength(byte length) + { + if (length > MaxLength) + length = MaxLength; + _buffer[length] = 0; + _buffer[31] = length; + } + private sealed class Converter : JsonConverter { public override void WriteJson(JsonWriter writer, ShapeString value, JsonSerializer serializer) diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index e008752f..5d745419 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -81,9 +81,6 @@ public class CommunicatorService : IDisposable, IService /// public readonly ResolvedFileChanged ResolvedFileChanged = new(); - /// - public readonly ModelAttributeComputed ModelAttributeComputed = new(); - public void Dispose() { CollectionChange.Dispose(); @@ -108,6 +105,5 @@ public class CommunicatorService : IDisposable, IService ChangedItemClick.Dispose(); SelectTab.Dispose(); ResolvedFileChanged.Dispose(); - ModelAttributeComputed.Dispose(); } } diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs index d1c7cd52..70b5f83b 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs @@ -11,7 +11,8 @@ public class MetaDrawers( GmpMetaDrawer gmp, ImcMetaDrawer imc, RspMetaDrawer rsp, - AtchMetaDrawer atch) : IService + AtchMetaDrawer atch, + ShpMetaDrawer shp) : IService { public readonly EqdpMetaDrawer Eqdp = eqdp; public readonly EqpMetaDrawer Eqp = eqp; @@ -21,6 +22,7 @@ public class MetaDrawers( public readonly ImcMetaDrawer Imc = imc; public readonly GlobalEqpMetaDrawer GlobalEqp = globalEqp; public readonly AtchMetaDrawer Atch = atch; + public readonly ShpMetaDrawer Shp = shp; public IMetaDrawer? Get(MetaManipulationType type) => type switch @@ -32,6 +34,7 @@ public class MetaDrawers( MetaManipulationType.Gmp => Gmp, MetaManipulationType.Rsp => Rsp, MetaManipulationType.Atch => Atch, + MetaManipulationType.Shp => Shp, MetaManipulationType.GlobalEqp => GlobalEqp, _ => null, }; diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs new file mode 100644 index 00000000..4be6e6aa --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -0,0 +1,247 @@ +using Dalamud.Interface; +using ImGuiNET; +using Newtonsoft.Json.Linq; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.GameData.Enums; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Shape Keys (SHP)###SHP"u8; + + private ShapeString _buffer = ShapeString.TryRead("shp_"u8, out var s) ? s : ShapeString.Empty; + private bool _identifierValid; + + public override int NumColumns + => 6; + + public override float ColumnHeight + => ImUtf8.FrameHeightSpacing; + + protected override void Initialize() + { + Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeString.Empty); + } + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current SHP manipulations to clipboard."u8, + new Lazy(() => MetaDictionary.SerializeTo([], Editor.Shp))); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier) && _identifierValid; + var tt = canAdd + ? "Stage this edit."u8 + : _identifierValid + ? "This entry does not contain a valid shape key."u8 + : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, ShpEntry.True); + + DrawIdentifierInput(ref Identifier); + DrawEntry(ref Entry, true); + } + + protected override void DrawEntry(ShpIdentifier identifier, ShpEntry entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + if (DrawEntry(ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(ShpIdentifier, ShpEntry)> Enumerate() + => Editor.Shp + .OrderBy(kvp => kvp.Key.Shape) + .ThenBy(kvp => kvp.Key.Slot) + .ThenBy(kvp => kvp.Key.Id) + .Select(kvp => (kvp.Key, kvp.Value)); + + protected override int Count + => Editor.Shp.Count; + + private bool DrawIdentifierInput(ref ShpIdentifier identifier) + { + ImGui.TableNextColumn(); + var changes = DrawHumanSlot(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawPrimaryId(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawShapeKeyInput(ref identifier, ref _buffer, ref _identifierValid); + return changes; + } + + private static void DrawIdentifier(ShpIdentifier identifier) + { + ImGui.TableNextColumn(); + + ImUtf8.TextFramed(SlotName(identifier.Slot), FrameColor); + ImUtf8.HoverTooltip("Model Slot"u8); + + ImGui.TableNextColumn(); + if (identifier.Id.HasValue) + ImUtf8.TextFramed($"{identifier.Id.Value.Id}", FrameColor); + else + ImUtf8.TextFramed("All IDs"u8, FrameColor); + ImUtf8.HoverTooltip("Primary ID"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Shape.AsSpan, FrameColor); + } + + private static bool DrawEntry(ref ShpEntry entry, bool disabled) + { + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + var value = entry.Value; + var changes = ImUtf8.Checkbox("##shpEntry"u8, ref value); + if (changes) + entry = new ShpEntry(value); + ImUtf8.HoverTooltip("Whether to enable or disable this shape key for the selected items."); + return changes; + } + + public static bool DrawPrimaryId(ref ShpIdentifier identifier, float unscaledWidth = 100) + { + var allSlots = identifier.Slot is HumanSlot.Unknown; + var all = !identifier.Id.HasValue; + var ret = false; + using (ImRaii.Disabled(allSlots)) + { + if (ImUtf8.Checkbox("##shpAll"u8, ref all)) + { + identifier = identifier with { Id = all ? null : 0 }; + ret = true; + } + } + + ImUtf8.HoverTooltip(allSlots ? "When using all slots, you also need to use all IDs."u8 : "Enable this shape key for all model IDs."u8); + + ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.X); + if (all) + { + using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0.05f, 0.5f)); + ImUtf8.TextFramed("All IDs"u8, ImGui.GetColorU32(ImGuiCol.FrameBg, all || allSlots ? ImGui.GetStyle().DisabledAlpha : 1f), + new Vector2(unscaledWidth, 0), ImGui.GetColorU32(ImGuiCol.TextDisabled)); + } + else + { + if (IdInput("##shpPrimaryId"u8, unscaledWidth, identifier.Id.GetValueOrDefault(0).Id, out var setId, 0, + ExpandedEqpGmpBase.Count - 1, + false)) + { + identifier = identifier with { Id = setId }; + ret = true; + } + } + + ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'e####' part of an item path or similar for customizations."u8); + + return ret; + } + + public static bool DrawHumanSlot(ref ShpIdentifier identifier, float unscaledWidth = 150) + { + var ret = false; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using (var combo = ImUtf8.Combo("##shpSlot"u8, SlotName(identifier.Slot))) + { + if (combo) + foreach (var slot in AvailableSlots) + { + if (!ImUtf8.Selectable(SlotName(slot), slot == identifier.Slot) || slot == identifier.Slot) + continue; + + ret = true; + if (slot is HumanSlot.Unknown) + identifier = identifier with + { + Id = null, + Slot = slot, + }; + else + identifier = identifier with { Slot = slot }; + } + } + + ImUtf8.HoverTooltip("Model Slot"u8); + return ret; + } + + public static unsafe bool DrawShapeKeyInput(ref ShpIdentifier identifier, ref ShapeString buffer, ref bool valid, float unscaledWidth = 150) + { + var ret = false; + var ptr = Unsafe.AsPointer(ref buffer); + var span = new Span(ptr, ShapeString.MaxLength + 1); + using (new ImRaii.ColorStyle().Push(ImGuiCol.Border, Colors.RegexWarningBorder, !valid).Push(ImGuiStyleVar.FrameBorderSize, 1f, !valid)) + { + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + if (ImUtf8.InputText("##shpShape"u8, span, out int newLength, "Shape Key..."u8)) + { + buffer.ForceLength((byte)newLength); + valid = ShpIdentifier.ValidateCustomShapeString(buffer); + if (valid) + identifier = identifier with { Shape = buffer }; + ret = true; + } + } + + ImUtf8.HoverTooltip("Supported shape keys need to have the format `shp_xx_*` and a maximum length of 30 characters."u8); + return ret; + } + + private static ReadOnlySpan AvailableSlots + => + [ + HumanSlot.Unknown, + HumanSlot.Head, + HumanSlot.Body, + HumanSlot.Hands, + HumanSlot.Legs, + HumanSlot.Feet, + HumanSlot.Ears, + HumanSlot.Neck, + HumanSlot.Wrists, + HumanSlot.RFinger, + HumanSlot.LFinger, + HumanSlot.Glasses, + HumanSlot.Hair, + HumanSlot.Face, + HumanSlot.Ear, + ]; + + private static ReadOnlySpan SlotName(HumanSlot slot) + => slot switch + { + HumanSlot.Unknown => "All Slots"u8, + HumanSlot.Head => "Equipment: Head"u8, + HumanSlot.Body => "Equipment: Body"u8, + HumanSlot.Hands => "Equipment: Hands"u8, + HumanSlot.Legs => "Equipment: Legs"u8, + HumanSlot.Feet => "Equipment: Feet"u8, + HumanSlot.Ears => "Equipment: Ears"u8, + HumanSlot.Neck => "Equipment: Neck"u8, + HumanSlot.Wrists => "Equipment: Wrists"u8, + HumanSlot.RFinger => "Equipment: Right Finger"u8, + HumanSlot.LFinger => "Equipment: Left Finger"u8, + HumanSlot.Glasses => "Equipment: Glasses"u8, + HumanSlot.Hair => "Customization: Hair"u8, + HumanSlot.Face => "Customization: Face"u8, + HumanSlot.Ear => "Customization: Ears"u8, + _ => "Unknown"u8, + }; +} diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 68424ae9..70a15373 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -61,6 +61,7 @@ public partial class ModEditWindow DrawEditHeader(MetaManipulationType.Gmp); DrawEditHeader(MetaManipulationType.Rsp); DrawEditHeader(MetaManipulationType.Atch); + DrawEditHeader(MetaManipulationType.Shp); DrawEditHeader(MetaManipulationType.GlobalEqp); } diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 968bc484..5292bd17 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -5,10 +5,12 @@ using OtterGui.Services; using OtterGui.Text; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; +using Penumbra.Interop.PathResolving; +using Penumbra.Meta; namespace Penumbra.UI.Tabs.Debug; -public class ShapeInspector(ObjectManager objects) : IUiService +public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) : IUiService { private int _objectIndex = 0; @@ -29,42 +31,92 @@ public class ShapeInspector(ObjectManager objects) : IUiService return; } - using var table = ImUtf8.Table("##table"u8, 4, ImGuiTableFlags.RowBg); - if (!table) - return; - - ImUtf8.TableSetupColumn("idx"u8, ImGuiTableColumnFlags.WidthFixed, 25 * ImUtf8.GlobalScale); - ImUtf8.TableSetupColumn("ptr"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); - ImUtf8.TableSetupColumn("mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); - ImUtf8.TableSetupColumn("shapes"u8, ImGuiTableColumnFlags.WidthStretch); - - var disabledColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); - foreach (var slot in Enum.GetValues()) + var data = resolver.IdentifyCollection(actor.AsObject, true); + using (var treeNode1 = ImUtf8.TreeNode($"Collection Shape Cache ({data.ModCollection})")) { - ImUtf8.DrawTableColumn($"{(uint)slot:D2}"); - ImGui.TableNextColumn(); - var model = human.AsHuman->Models[(int)slot]; - Penumbra.Dynamis.DrawPointer((nint)model); - if (model is not null) + if (treeNode1.Success && data.ModCollection.HasCache) { - var mask = model->EnabledShapeKeyIndexMask; - ImUtf8.DrawTableColumn($"{mask:X8}"); - ImGui.TableNextColumn(); - foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) + using var table = ImUtf8.Table("##cacheTable"u8, 2, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("shape"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("enabled"u8, ImGuiTableColumnFlags.WidthStretch); + + foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State) { - var disabled = (mask & (1u << idx)) is 0; - using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); - ImUtf8.Text(shape.AsSpan()); - ImGui.SameLine(0, 0); - ImUtf8.Text(", "u8); - if ((idx % 8) < 7) - ImGui.SameLine(0, 0); + ImUtf8.DrawTableColumn(shape.AsSpan); + if (set.All) + { + ImUtf8.DrawTableColumn("All"u8); + } + else + { + ImGui.TableNextColumn(); + foreach (var slot in ShapeManager.UsedModels) + { + if (!set[slot]) + continue; + + ImUtf8.Text($"All {slot.ToName()}, "); + ImGui.SameLine(0, 0); + } + + foreach (var item in set.Where(i => !set[i.Slot])) + { + ImUtf8.Text($"{item.Slot.ToName()} {item.Id.Id:D4}, "); + ImGui.SameLine(0, 0); + } + } } } - else + } + + using (var treeNode2 = ImUtf8.TreeNode("Character Model Shapes"u8)) + { + if (treeNode2) { - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); + using var table = ImUtf8.Table("##table"u8, 5, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("idx"u8, ImGuiTableColumnFlags.WidthFixed, 25 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("name"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("ptr"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); + ImUtf8.TableSetupColumn("mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("shapes"u8, ImGuiTableColumnFlags.WidthStretch); + + var disabledColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); + for (var i = 0; i < human.AsHuman->SlotCount; ++i) + { + ImUtf8.DrawTableColumn($"{(uint)i:D2}"); + ImUtf8.DrawTableColumn(((HumanSlot)i).ToName()); + + ImGui.TableNextColumn(); + var model = human.AsHuman->Models[i]; + Penumbra.Dynamis.DrawPointer((nint)model); + if (model is not null) + { + var mask = model->EnabledShapeKeyIndexMask; + ImUtf8.DrawTableColumn($"{mask:X8}"); + ImGui.TableNextColumn(); + foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) + { + var disabled = (mask & (1u << idx)) is 0; + using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); + ImUtf8.Text(shape.AsSpan()); + ImGui.SameLine(0, 0); + ImUtf8.Text(", "u8); + if (idx % 8 < 7) + ImGui.SameLine(0, 0); + } + } + else + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + } + } } } } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 7b3a3c8b..cb22b54a 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -51,7 +51,7 @@ public class SettingsTab : ITab, IUiService private readonly MigrationSectionDrawer _migrationDrawer; private readonly CollectionAutoSelector _autoSelector; private readonly CleanupService _cleanupService; - private readonly AttributeHooks _attributeHooks; + private readonly AttributeHook _attributeHook; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -64,7 +64,7 @@ public class SettingsTab : ITab, IUiService DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, - AttributeHooks attributeHooks) + AttributeHook attributeHook) { _pluginInterface = pluginInterface; _config = config; @@ -89,7 +89,7 @@ public class SettingsTab : ITab, IUiService _migrationDrawer = migrationDrawer; _autoSelector = autoSelector; _cleanupService = cleanupService; - _attributeHooks = attributeHooks; + _attributeHook = attributeHook; } public void DrawHeader() @@ -525,55 +525,6 @@ public class SettingsTab : ITab, IUiService ImGuiUtil.LabeledHelpMarker("Sort Mode", "Choose the sort mode for the mod selector in the mods tab."); } - private float _absoluteSelectorSize = float.NaN; - - /// Draw a selector for the absolute size of the mod selector in pixels. - private void DrawAbsoluteSizeSelector() - { - if (float.IsNaN(_absoluteSelectorSize)) - _absoluteSelectorSize = _config.ModSelectorAbsoluteSize; - - if (ImGuiUtil.DragFloat("##absoluteSize", ref _absoluteSelectorSize, UiHelpers.InputTextWidth.X, 1, - Configuration.Constants.MinAbsoluteSize, Configuration.Constants.MaxAbsoluteSize, "%.0f") - && _absoluteSelectorSize != _config.ModSelectorAbsoluteSize) - { - _config.ModSelectorAbsoluteSize = _absoluteSelectorSize; - _config.Save(); - } - - ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Mod Selector Absolute Size", - "The minimal absolute size of the mod selector in the mod tab in pixels."); - } - - private int _relativeSelectorSize = int.MaxValue; - - /// Draw a selector for the relative size of the mod selector as a percentage and a toggle to enable relative sizing. - private void DrawRelativeSizeSelector() - { - var scaleModSelector = _config.ScaleModSelector; - if (ImGui.Checkbox("Scale Mod Selector With Window Size", ref scaleModSelector)) - { - _config.ScaleModSelector = scaleModSelector; - _config.Save(); - } - - ImGui.SameLine(); - if (_relativeSelectorSize == int.MaxValue) - _relativeSelectorSize = _config.ModSelectorScaledSize; - if (ImGuiUtil.DragInt("##relativeSize", ref _relativeSelectorSize, UiHelpers.InputTextWidth.X - ImGui.GetCursorPosX(), 0.1f, - Configuration.Constants.MinScaledSize, Configuration.Constants.MaxScaledSize, "%i%%") - && _relativeSelectorSize != _config.ModSelectorScaledSize) - { - _config.ModSelectorScaledSize = _relativeSelectorSize; - _config.Save(); - } - - ImGui.SameLine(); - ImGuiUtil.LabeledHelpMarker("Mod Selector Relative Size", - "Instead of keeping the mod-selector in the Installed Mods tab a fixed width, this will let it scale with the total size of the Penumbra window."); - } - private void DrawRenameSettings() { ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X); @@ -607,8 +558,6 @@ public class SettingsTab : ITab, IUiService private void DrawModSelectorSettings() { DrawFolderSortType(); - DrawAbsoluteSizeSelector(); - DrawRelativeSizeSelector(); DrawRenameSettings(); Checkbox("Open Folders by Default", "Whether to start with all folders collapsed or expanded in the mod selector.", _config.OpenFoldersByDefault, v => @@ -626,7 +575,8 @@ public class SettingsTab : ITab, IUiService _config.Save(); }); Widget.DoubleModifierSelector("Incognito Modifier", - "A modifier you need to hold while clicking the Incognito or Temporary Settings Mode button for it to take effect.", UiHelpers.InputTextWidth.X, + "A modifier you need to hold while clicking the Incognito or Temporary Settings Mode button for it to take effect.", + UiHelpers.InputTextWidth.X, _config.IncognitoModifier, v => { @@ -811,8 +761,8 @@ public class SettingsTab : ITab, IUiService "Normally, metadata changes that equal their default values, which are sometimes exported by TexTools, are discarded. " + "Toggle this to keep them, for example if an option in a mod is supposed to disable a metadata change from a prior option.", _config.KeepDefaultMetaChanges, v => _config.KeepDefaultMetaChanges = v); - Checkbox("Enable Advanced Shape Support", "Penumbra will allow for custom shape keys for modded models to be considered and combined.", - _config.EnableAttributeHooks, _attributeHooks.SetState); + Checkbox("Enable Custom Shape Support", "Penumbra will allow for custom shape keys for modded models to be considered and combined.", + _config.EnableCustomShapes, _attributeHook.SetState); DrawWaitForPluginsReflection(); DrawEnableHttpApiBox(); DrawEnableDebugModeBox(); diff --git a/schemas/structs/manipulation.json b/schemas/structs/manipulation.json index 4a41dbe2..55fc5cad 100644 --- a/schemas/structs/manipulation.json +++ b/schemas/structs/manipulation.json @@ -3,7 +3,7 @@ "type": "object", "properties": { "Type": { - "enum": [ "Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch" ] + "enum": [ "Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch", "Shp" ] }, "Manipulation": { "type": "object" @@ -90,6 +90,16 @@ "$ref": "meta_atch.json" } } + }, + { + "properties": { + "Type": { + "const": "Shp" + }, + "Manipulation": { + "$ref": "meta_shp.json" + } + } } ] } diff --git a/schemas/structs/meta_enums.json b/schemas/structs/meta_enums.json index 747da849..2fc65a0d 100644 --- a/schemas/structs/meta_enums.json +++ b/schemas/structs/meta_enums.json @@ -5,6 +5,10 @@ "$anchor": "EquipSlot", "enum": [ "Unknown", "MainHand", "OffHand", "Head", "Body", "Hands", "Belt", "Legs", "Feet", "Ears", "Neck", "Wrists", "RFinger", "BothHand", "LFinger", "HeadBody", "BodyHandsLegsFeet", "SoulCrystal", "LegsFeet", "FullBody", "BodyHands", "BodyLegsFeet", "ChestHands", "Nothing", "All" ] }, + "HumanSlot": { + "$anchor": "HumanSlot", + "enum": [ "Head", "Body", "Hands", "Legs", "Feet", "Ears", "Neck", "Wrists", "RFinger", "LFinger", "Hair", "Face", "Ear", "Glasses", "Unknown" ] + }, "Gender": { "$anchor": "Gender", "enum": [ "Unknown", "Male", "Female", "MaleNpc", "FemaleNpc" ] diff --git a/schemas/structs/meta_shp.json b/schemas/structs/meta_shp.json new file mode 100644 index 00000000..e6b66420 --- /dev/null +++ b/schemas/structs/meta_shp.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "boolean" + }, + "Slot": { + "$ref": "meta_enums.json#HumanSlot" + }, + "Id": { + "$ref": "meta_enums.json#U16" + }, + "Shape": { + "type": "string", + "minLength": 8, + "maxLength": 30 + } + }, + "required": [ + "Shape" + ] +} From 480942339f4bff0d30e7afcb84852d3f318eb47a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 15 May 2025 17:47:32 +0200 Subject: [PATCH 1203/1381] Add draggable mod selector width. --- Penumbra/EphemeralConfig.cs | 5 +++ Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 33 +++++++++++++++----- Penumbra/UI/Tabs/ModsTab.cs | 15 +-------- 3 files changed, 32 insertions(+), 21 deletions(-) diff --git a/Penumbra/EphemeralConfig.cs b/Penumbra/EphemeralConfig.cs index 678e53ad..ecb0218f 100644 --- a/Penumbra/EphemeralConfig.cs +++ b/Penumbra/EphemeralConfig.cs @@ -1,6 +1,7 @@ using Dalamud.Interface.ImGuiNotification; using Newtonsoft.Json; using OtterGui.Classes; +using OtterGui.FileSystem.Selector; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Communication; @@ -23,6 +24,10 @@ public class EphemeralConfig : ISavable, IDisposable, IService [JsonIgnore] private readonly ModPathChanged _modPathChanged; + public float CurrentModSelectorWidth { get; set; } = 200f; + public float ModSelectorMinimumScale { get; set; } = 0.1f; + public float ModSelectorMaximumScale { get; set; } = 0.5f; + public int Version { get; set; } = Configuration.Constants.CurrentVersion; public int LastSeenVersion { get; set; } = PenumbraChangelog.LastChangelogVersion; public bool DebugSeparateWindow { get; set; } = false; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 6586747c..2dff19ab 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -131,18 +131,41 @@ public sealed class ModFileSystemSelector : FileSystemSelector m.Extensions.Any(e => ValidModExtensions.Contains(e.ToLowerInvariant())), m => { ImUtf8.Text($"Dragging mods for import:\n\t{string.Join("\n\t", m.Files.Select(Path.GetFileName))}"); return true; }); - base.Draw(width); + base.Draw(); if (_dragDrop.CreateImGuiTarget("ModDragDrop", out var files, out _)) _modImportManager.AddUnpack(files.Where(f => ValidModExtensions.Contains(Path.GetExtension(f.ToLowerInvariant())))); } + protected override float CurrentWidth + => _config.Ephemeral.CurrentModSelectorWidth * ImUtf8.GlobalScale; + + protected override float MinimumAbsoluteRemainder + => 550 * ImUtf8.GlobalScale; + + protected override float MinimumScaling + => _config.Ephemeral.ModSelectorMinimumScale; + + protected override float MaximumScaling + => _config.Ephemeral.ModSelectorMaximumScale; + + protected override void SetSize(Vector2 size) + { + base.SetSize(size); + var adaptedSize = MathF.Round(size.X / ImUtf8.GlobalScale); + if (adaptedSize == _config.Ephemeral.CurrentModSelectorWidth) + return; + + _config.Ephemeral.CurrentModSelectorWidth = adaptedSize; + _config.Ephemeral.Save(); + } + public override void Dispose() { base.Dispose(); @@ -651,14 +674,10 @@ public sealed class ModFileSystemSelector : FileSystemSelector Get the correct size for the mod selector based on current config. - public static float GetModSelectorSize(Configuration config) - { - var absoluteSize = Math.Clamp(config.ModSelectorAbsoluteSize, Configuration.Constants.MinAbsoluteSize, - Math.Min(Configuration.Constants.MaxAbsoluteSize, ImGui.GetContentRegionAvail().X - 100)); - var relativeSize = config.ScaleModSelector - ? Math.Clamp(config.ModSelectorScaledSize, Configuration.Constants.MinScaledSize, Configuration.Constants.MaxScaledSize) - : 0; - return MathF.Round(config.ScaleModSelector - ? Math.Max(absoluteSize, relativeSize * ImGui.GetContentRegionAvail().X / 100) - : absoluteSize); - } - private void DrawRedrawLine() { if (config.HideRedrawBar) From 70295b7a6bca0c5fb1358cf5f396dee4173a5e23 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 15 May 2025 15:50:16 +0000 Subject: [PATCH 1204/1381] [CI] Updating repo.json for testing_1.3.6.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 8e88ad52..13d91e5c 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.8", + "TestingAssemblyVersion": "1.3.6.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From c0dcfdd83587a5c27bcb707f391ad9e53ed752fb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 15 May 2025 22:23:33 +0200 Subject: [PATCH 1205/1381] Update shape string format. --- Penumbra/Meta/Manipulations/ShpIdentifier.cs | 31 ++++--------------- Penumbra/Meta/ShapeManager.cs | 10 ++++-- .../UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 4 +-- schemas/structs/meta_shp.json | 5 +-- 4 files changed, 18 insertions(+), 32 deletions(-) diff --git a/Penumbra/Meta/Manipulations/ShpIdentifier.cs b/Penumbra/Meta/Manipulations/ShpIdentifier.cs index fffa51ba..c642167f 100644 --- a/Penumbra/Meta/Manipulations/ShpIdentifier.cs +++ b/Penumbra/Meta/Manipulations/ShpIdentifier.cs @@ -1,4 +1,3 @@ -using Lumina.Models.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.GameData.Data; @@ -61,34 +60,16 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape return ValidateCustomShapeString(Shape); } - public static bool ValidateCustomShapeString(ReadOnlySpan shape) - { - // "shp_xx_y" - if (shape.Length < 8) - return false; - - if (shape[0] is not (byte)'s' - || shape[1] is not (byte)'h' - || shape[2] is not (byte)'p' - || shape[3] is not (byte)'_' - || shape[6] is not (byte)'_') - return false; - - return true; - } - public static unsafe bool ValidateCustomShapeString(byte* shape) { - // "shp_xx_y" + // "shpx_*" if (shape is null) return false; if (*shape++ is not (byte)'s' || *shape++ is not (byte)'h' || *shape++ is not (byte)'p' - || *shape++ is not (byte)'_' - || *shape++ is 0 - || *shape++ is 0 + || *shape++ is not (byte)'x' || *shape++ is not (byte)'_' || *shape is 0) return false; @@ -98,16 +79,16 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape public static bool ValidateCustomShapeString(in ShapeString shape) { - // "shp_xx_y" - if (shape.Length < 8) + // "shpx_*" + if (shape.Length < 6) return false; var span = shape.AsSpan; if (span[0] is not (byte)'s' || span[1] is not (byte)'h' || span[2] is not (byte)'p' - || span[3] is not (byte)'_' - || span[6] is not (byte)'_') + || span[3] is not (byte)'x' + || span[4] is not (byte)'_') return false; return true; diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs index ec8ddb50..dc3e1a1c 100644 --- a/Penumbra/Meta/ShapeManager.cs +++ b/Penumbra/Meta/ShapeManager.cs @@ -93,13 +93,13 @@ public class ShapeManager : IRequiredService, IDisposable { foreach (var (shape, topIndex) in _temporaryIndices[1]) { - if (shape[4] is (byte)'w' && shape[5] is (byte)'r' && _temporaryIndices[2].TryGetValue(shape, out var handIndex)) + if (CheckCenter(shape, 'w', 'r') && _temporaryIndices[2].TryGetValue(shape, out var handIndex)) { _temporaryValues[1] |= 1u << topIndex; _temporaryValues[2] |= 1u << handIndex; } - if (shape[4] is (byte)'w' && shape[5] is (byte)'a' && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) + if (CheckCenter(shape, 'w', 'a') && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) { _temporaryValues[1] |= 1u << topIndex; _temporaryValues[3] |= 1u << legIndex; @@ -108,11 +108,15 @@ public class ShapeManager : IRequiredService, IDisposable foreach (var (shape, bottomIndex) in _temporaryIndices[3]) { - if (shape[4] is (byte)'a' && shape[5] is (byte)'n' && _temporaryIndices[4].TryGetValue(shape, out var footIndex)) + if (CheckCenter(shape, 'a', 'n') && _temporaryIndices[4].TryGetValue(shape, out var footIndex)) { _temporaryValues[3] |= 1u << bottomIndex; _temporaryValues[4] |= 1u << footIndex; } } } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool CheckCenter(in ShapeString shape, char first, char second) + => shape.Length > 8 && shape[4] == first && shape[5] == second && shape[6] is (byte)'_'; } diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs index 4be6e6aa..2c99af02 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -19,7 +19,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile public override ReadOnlySpan Label => "Shape Keys (SHP)###SHP"u8; - private ShapeString _buffer = ShapeString.TryRead("shp_"u8, out var s) ? s : ShapeString.Empty; + private ShapeString _buffer = ShapeString.TryRead("shpx_"u8, out var s) ? s : ShapeString.Empty; private bool _identifierValid; public override int NumColumns @@ -200,7 +200,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } } - ImUtf8.HoverTooltip("Supported shape keys need to have the format `shp_xx_*` and a maximum length of 30 characters."u8); + ImUtf8.HoverTooltip("Supported shape keys need to have the format `shpx_*` and a maximum length of 30 characters."u8); return ret; } diff --git a/schemas/structs/meta_shp.json b/schemas/structs/meta_shp.json index e6b66420..197f3104 100644 --- a/schemas/structs/meta_shp.json +++ b/schemas/structs/meta_shp.json @@ -13,8 +13,9 @@ }, "Shape": { "type": "string", - "minLength": 8, - "maxLength": 30 + "minLength": 5, + "maxLength": 30, + "pattern": "^shpx_" } }, "required": [ From f1448ed947039cc9a9e235e6da4745cdcde483cd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 16 May 2025 00:25:13 +0200 Subject: [PATCH 1206/1381] Add conditional connector shapes. --- Penumbra/Collections/Cache/ShpCache.cs | 79 +++++++- Penumbra/Meta/Manipulations/ShpIdentifier.cs | 62 +++++- Penumbra/Meta/ShapeManager.cs | 58 ++++-- Penumbra/Meta/ShapeString.cs | 16 ++ .../UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 76 +++++++- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 183 ++++++++++-------- schemas/structs/meta_shp.json | 6 + 7 files changed, 360 insertions(+), 120 deletions(-) diff --git a/Penumbra/Collections/Cache/ShpCache.cs b/Penumbra/Collections/Cache/ShpCache.cs index 2e90052d..eaf949d9 100644 --- a/Penumbra/Collections/Cache/ShpCache.cs +++ b/Penumbra/Collections/Cache/ShpCache.cs @@ -13,7 +13,23 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) internal IReadOnlyDictionary State => _shpData; - internal sealed class ShpHashSet : HashSet<(HumanSlot Slot, PrimaryId Id)> + internal IEnumerable<(ShapeString, IReadOnlyDictionary)> ConditionState + => _conditionalSet.Select(kvp => (kvp.Key, (IReadOnlyDictionary)kvp.Value)); + + public bool CheckConditionState(ShapeString condition, [NotNullWhen(true)] out IReadOnlyDictionary? dict) + { + if (_conditionalSet.TryGetValue(condition, out var d)) + { + dict = d; + return true; + } + + dict = null; + return false; + } + + + public sealed class ShpHashSet : HashSet<(HumanSlot Slot, PrimaryId Id)> { private readonly BitArray _allIds = new(ShapeManager.ModelSlotSize); @@ -76,12 +92,14 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) => !_allIds.HasAnySet() && Count is 0; } - private readonly Dictionary _shpData = []; + private readonly Dictionary _shpData = []; + private readonly Dictionary> _conditionalSet = []; public void Reset() { Clear(); _shpData.Clear(); + _conditionalSet.Clear(); } protected override void Dispose(bool _) @@ -89,21 +107,62 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) protected override void ApplyModInternal(ShpIdentifier identifier, ShpEntry entry) { - if (!_shpData.TryGetValue(identifier.Shape, out var value)) + if (identifier.ShapeCondition.Length > 0) { - value = []; - _shpData.Add(identifier.Shape, value); + if (!_conditionalSet.TryGetValue(identifier.ShapeCondition, out var shapes)) + { + if (!entry.Value) + return; + + shapes = new Dictionary(); + _conditionalSet.Add(identifier.ShapeCondition, shapes); + } + + Func(shapes); + } + else + { + Func(_shpData); } - value.TrySet(identifier.Slot, identifier.Id, entry); + void Func(Dictionary dict) + { + if (!dict.TryGetValue(identifier.Shape, out var value)) + { + if (!entry.Value) + return; + + value = []; + dict.Add(identifier.Shape, value); + } + + value.TrySet(identifier.Slot, identifier.Id, entry); + } } protected override void RevertModInternal(ShpIdentifier identifier) { - if (!_shpData.TryGetValue(identifier.Shape, out var value)) - return; + if (identifier.ShapeCondition.Length > 0) + { + if (!_conditionalSet.TryGetValue(identifier.ShapeCondition, out var shapes)) + return; - if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False) && value.IsEmpty) - _shpData.Remove(identifier.Shape); + Func(shapes); + } + else + { + Func(_shpData); + } + + return; + + void Func(Dictionary dict) + { + if (!_shpData.TryGetValue(identifier.Shape, out var value)) + return; + + if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False) && value.IsEmpty) + _shpData.Remove(identifier.Shape); + } } } diff --git a/Penumbra/Meta/Manipulations/ShpIdentifier.cs b/Penumbra/Meta/Manipulations/ShpIdentifier.cs index c642167f..777be512 100644 --- a/Penumbra/Meta/Manipulations/ShpIdentifier.cs +++ b/Penumbra/Meta/Manipulations/ShpIdentifier.cs @@ -7,7 +7,7 @@ using Penumbra.Interop.Structs; namespace Penumbra.Meta.Manipulations; -public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeString Shape) +public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeString Shape, ShapeString ShapeCondition) : IComparable, IMetaIdentifier { public int CompareTo(ShpIdentifier other) @@ -34,12 +34,39 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape return 1; } + var shapeComparison = Shape.CompareTo(other.Shape); + if (shapeComparison is not 0) + return shapeComparison; - return Shape.CompareTo(other.Shape); + return ShapeCondition.CompareTo(other.ShapeCondition); } + public override string ToString() - => $"Shp - {Shape}{(Slot is HumanSlot.Unknown ? " - All Slots & IDs" : $" - {Slot.ToName()}{(Id.HasValue ? $" - {Id.Value.Id}" : " - All IDs")}")}"; + { + var sb = new StringBuilder(64); + sb.Append("Shp - ") + .Append(Shape); + if (Slot is HumanSlot.Unknown) + { + sb.Append(" - All Slots & IDs"); + } + else + { + sb.Append(" - ") + .Append(Slot.ToName()) + .Append(" - "); + if (Id.HasValue) + sb.Append(Id.Value.Id); + else + sb.Append("All IDs"); + } + + if (ShapeCondition.Length > 0) + sb.Append(" - ") + .Append(ShapeCondition); + return sb.ToString(); + } public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) { @@ -57,7 +84,24 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (Slot is HumanSlot.Unknown && Id is not null) return false; - return ValidateCustomShapeString(Shape); + if (!ValidateCustomShapeString(Shape)) + return false; + + if (ShapeCondition.Length is 0) + return true; + + if (!ValidateCustomShapeString(ShapeCondition)) + return false; + + return Slot switch + { + HumanSlot.Hands when ShapeCondition.IsWrist() => true, + HumanSlot.Body when ShapeCondition.IsWrist() || ShapeCondition.IsWaist() => true, + HumanSlot.Legs when ShapeCondition.IsWaist() || ShapeCondition.IsAnkle() => true, + HumanSlot.Feet when ShapeCondition.IsAnkle() => true, + HumanSlot.Unknown when ShapeCondition.IsWrist() || ShapeCondition.IsWaist() || ShapeCondition.IsAnkle() => true, + _ => false, + }; } public static unsafe bool ValidateCustomShapeString(byte* shape) @@ -101,18 +145,22 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (Id.HasValue) jObj["Id"] = Id.Value.Id.ToString(); jObj["Shape"] = Shape.ToString(); + if (ShapeCondition.Length > 0) + jObj["ShapeCondition"] = ShapeCondition.ToString(); return jObj; } public static ShpIdentifier? FromJson(JObject jObj) { - var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; - var id = jObj["Id"]?.ToObject(); var shape = jObj["Shape"]?.ToObject(); if (shape is null || !ShapeString.TryRead(shape, out var shapeString)) return null; - var identifier = new ShpIdentifier(slot, id, shapeString); + var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; + var id = jObj["Id"]?.ToObject(); + var shapeCondition = jObj["ShapeCondition"]?.ToObject(); + var shapeConditionString = shapeCondition is null || !ShapeString.TryRead(shapeCondition, out var s) ? ShapeString.Empty : s; + var identifier = new ShpIdentifier(slot, id, shapeString, shapeConditionString); return identifier.Validate() ? identifier : null; } diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs index dc3e1a1c..57f6f23f 100644 --- a/Penumbra/Meta/ShapeManager.cs +++ b/Penumbra/Meta/ShapeManager.cs @@ -1,8 +1,10 @@ using System.Reflection.Metadata.Ecma335; using OtterGui.Services; using Penumbra.Collections; +using Penumbra.Collections.Cache; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; +using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Meta.Manipulations; @@ -30,15 +32,19 @@ public class ShapeManager : IRequiredService, IDisposable private readonly Dictionary[] _temporaryIndices = Enumerable.Range(0, NumSlots).Select(_ => new Dictionary()).ToArray(); - private readonly uint[] _temporaryMasks = new uint[NumSlots]; - private readonly uint[] _temporaryValues = new uint[NumSlots]; + private readonly uint[] _temporaryMasks = new uint[NumSlots]; + private readonly uint[] _temporaryValues = new uint[NumSlots]; + private readonly PrimaryId[] _ids = new PrimaryId[ModelSlotSize]; public void Dispose() => _attributeHook.Unsubscribe(OnAttributeComputed); private unsafe void OnAttributeComputed(Actor actor, Model model, ModCollection collection) { - ComputeCache(model, collection); + if (!collection.HasCache) + return; + + ComputeCache(model, collection.MetaCache!.Shp); for (var i = 0; i < NumSlots; ++i) { if (_temporaryMasks[i] is 0) @@ -52,11 +58,8 @@ public class ShapeManager : IRequiredService, IDisposable } } - private unsafe void ComputeCache(Model human, ModCollection collection) + private unsafe void ComputeCache(Model human, ShpCache cache) { - if (!collection.HasCache) - return; - for (var i = 0; i < NumSlots; ++i) { _temporaryMasks[i] = 0; @@ -68,6 +71,8 @@ public class ShapeManager : IRequiredService, IDisposable if (model is null || model->ModelResourceHandle is null) continue; + _ids[(int)modelIndex] = human.GetArmorChanged(modelIndex).Set; + ref var shapes = ref model->ModelResourceHandle->Shapes; foreach (var (shape, index) in shapes.Where(kvp => ShpIdentifier.ValidateCustomShapeString(kvp.Key.Value))) { @@ -75,8 +80,8 @@ public class ShapeManager : IRequiredService, IDisposable { _temporaryIndices[i].TryAdd(shapeString, index); _temporaryMasks[i] |= (ushort)(1 << index); - if (collection.MetaCache!.Shp.State.Count > 0 - && collection.MetaCache!.Shp.ShouldBeEnabled(shapeString, modelIndex, human.GetArmorChanged(modelIndex).Set)) + if (cache.State.Count > 0 + && cache.ShouldBeEnabled(shapeString, modelIndex, _ids[(int)modelIndex])) _temporaryValues[i] |= (ushort)(1 << index); } else @@ -86,37 +91,54 @@ public class ShapeManager : IRequiredService, IDisposable } } - UpdateDefaultMasks(); + UpdateDefaultMasks(cache); } - private void UpdateDefaultMasks() + private void UpdateDefaultMasks(ShpCache cache) { foreach (var (shape, topIndex) in _temporaryIndices[1]) { - if (CheckCenter(shape, 'w', 'r') && _temporaryIndices[2].TryGetValue(shape, out var handIndex)) + if (shape.IsWrist() && _temporaryIndices[2].TryGetValue(shape, out var handIndex)) { _temporaryValues[1] |= 1u << topIndex; _temporaryValues[2] |= 1u << handIndex; + CheckCondition(shape, HumanSlot.Body, HumanSlot.Hands, 1, 2); } - if (CheckCenter(shape, 'w', 'a') && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) + if (shape.IsWaist() && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) { _temporaryValues[1] |= 1u << topIndex; _temporaryValues[3] |= 1u << legIndex; + CheckCondition(shape, HumanSlot.Body, HumanSlot.Legs, 1, 3); } } foreach (var (shape, bottomIndex) in _temporaryIndices[3]) { - if (CheckCenter(shape, 'a', 'n') && _temporaryIndices[4].TryGetValue(shape, out var footIndex)) + if (shape.IsAnkle() && _temporaryIndices[4].TryGetValue(shape, out var footIndex)) { _temporaryValues[3] |= 1u << bottomIndex; _temporaryValues[4] |= 1u << footIndex; + CheckCondition(shape, HumanSlot.Legs, HumanSlot.Feet, 3, 4); + } + } + + return; + + void CheckCondition(in ShapeString shape, HumanSlot slot1, HumanSlot slot2, int idx1, int idx2) + { + if (!cache.CheckConditionState(shape, out var dict)) + return; + + foreach (var (subShape, set) in dict) + { + if (set.Contains(slot1, _ids[idx1])) + if (_temporaryIndices[idx1].TryGetValue(subShape, out var subIndex)) + _temporaryValues[idx1] |= 1u << subIndex; + if (set.Contains(slot2, _ids[idx2])) + if (_temporaryIndices[idx2].TryGetValue(subShape, out var subIndex)) + _temporaryValues[idx2] |= 1u << subIndex; } } } - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private static bool CheckCenter(in ShapeString shape, char first, char second) - => shape.Length > 8 && shape[4] == first && shape[5] == second && shape[6] is (byte)'_'; } diff --git a/Penumbra/Meta/ShapeString.cs b/Penumbra/Meta/ShapeString.cs index 5b6f9c52..95ca0933 100644 --- a/Penumbra/Meta/ShapeString.cs +++ b/Penumbra/Meta/ShapeString.cs @@ -37,6 +37,22 @@ public struct ShapeString : IEquatable, IComparable } } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public bool IsAnkle() + => CheckCenter('a', 'n'); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public bool IsWaist() + => CheckCenter('w', 'a'); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + public bool IsWrist() + => CheckCenter('w', 'r'); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private bool CheckCenter(char first, char second) + => Length > 8 && _buffer[5] == first && _buffer[6] == second && _buffer[7] is (byte)'_'; + public bool Equals(ShapeString other) => Length == other.Length && _buffer[..Length].SequenceEqual(other._buffer[..Length]); diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs index 2c99af02..fe7e743c 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -19,18 +19,20 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile public override ReadOnlySpan Label => "Shape Keys (SHP)###SHP"u8; - private ShapeString _buffer = ShapeString.TryRead("shpx_"u8, out var s) ? s : ShapeString.Empty; + private ShapeString _buffer = ShapeString.TryRead("shpx_"u8, out var s) ? s : ShapeString.Empty; + private ShapeString _conditionBuffer = ShapeString.Empty; private bool _identifierValid; + private bool _conditionValid = true; public override int NumColumns - => 6; + => 7; public override float ColumnHeight => ImUtf8.FrameHeightSpacing; protected override void Initialize() { - Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeString.Empty); + Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeString.Empty, ShapeString.Empty); } protected override void DrawNew() @@ -40,7 +42,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile new Lazy(() => MetaDictionary.SerializeTo([], Editor.Shp))); ImGui.TableNextColumn(); - var canAdd = !Editor.Contains(Identifier) && _identifierValid; + var canAdd = !Editor.Contains(Identifier) && _identifierValid && _conditionValid; var tt = canAdd ? "Stage this edit."u8 : _identifierValid @@ -67,6 +69,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile .OrderBy(kvp => kvp.Key.Shape) .ThenBy(kvp => kvp.Key.Slot) .ThenBy(kvp => kvp.Key.Id) + .ThenBy(kvp => kvp.Key.ShapeCondition) .Select(kvp => (kvp.Key, kvp.Value)); protected override int Count @@ -82,6 +85,9 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ImGui.TableNextColumn(); changes |= DrawShapeKeyInput(ref identifier, ref _buffer, ref _identifierValid); + + ImGui.TableNextColumn(); + changes |= DrawShapeConditionInput(ref identifier, ref _conditionBuffer, ref _conditionValid); return changes; } @@ -101,6 +107,13 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ImGui.TableNextColumn(); ImUtf8.TextFramed(identifier.Shape.AsSpan, FrameColor); + + ImGui.TableNextColumn(); + if (identifier.ShapeCondition.Length > 0) + { + ImUtf8.TextFramed(identifier.ShapeCondition.AsSpan, FrameColor); + ImUtf8.HoverTooltip("Connector condition for this shape to be activated."); + } } private static bool DrawEntry(ref ShpEntry entry, bool disabled) @@ -154,7 +167,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } - public static bool DrawHumanSlot(ref ShpIdentifier identifier, float unscaledWidth = 150) + public bool DrawHumanSlot(ref ShpIdentifier identifier, float unscaledWidth = 150) { var ret = false; ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); @@ -168,13 +181,37 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ret = true; if (slot is HumanSlot.Unknown) + { identifier = identifier with { Id = null, Slot = slot, }; + } else - identifier = identifier with { Slot = slot }; + { + if (_conditionBuffer.Length > 0 + && (_conditionBuffer.IsAnkle() && slot is not HumanSlot.Feet and not HumanSlot.Legs + || _conditionBuffer.IsWrist() && slot is not HumanSlot.Hands and not HumanSlot.Body + || _conditionBuffer.IsWaist() && slot is not HumanSlot.Body and not HumanSlot.Legs)) + { + identifier = identifier with + { + Slot = slot, + ShapeCondition = ShapeString.Empty, + }; + _conditionValid = false; + } + else + { + identifier = identifier with + { + Slot = slot, + ShapeCondition = _conditionBuffer, + }; + _conditionValid = true; + } + } } } @@ -204,6 +241,33 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } + public static unsafe bool DrawShapeConditionInput(ref ShpIdentifier identifier, ref ShapeString buffer, ref bool valid, + float unscaledWidth = 150) + { + var ret = false; + var ptr = Unsafe.AsPointer(ref buffer); + var span = new Span(ptr, ShapeString.MaxLength + 1); + using (new ImRaii.ColorStyle().Push(ImGuiCol.Border, Colors.RegexWarningBorder, !valid).Push(ImGuiStyleVar.FrameBorderSize, 1f, !valid)) + { + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + if (ImUtf8.InputText("##shpCondition"u8, span, out int newLength, "Shape Condition..."u8)) + { + buffer.ForceLength((byte)newLength); + valid = ShpIdentifier.ValidateCustomShapeString(buffer) + && (buffer.IsAnkle() && identifier.Slot is HumanSlot.Unknown or HumanSlot.Feet or HumanSlot.Legs + || buffer.IsWaist() && identifier.Slot is HumanSlot.Unknown or HumanSlot.Body or HumanSlot.Legs + || buffer.IsWrist() && identifier.Slot is HumanSlot.Unknown or HumanSlot.Body or HumanSlot.Hands); + if (valid) + identifier = identifier with { ShapeCondition = buffer }; + ret = true; + } + } + + ImUtf8.HoverTooltip( + "Supported conditional shape keys need to have the format `shpx_an_*` (Legs or Feet), `shpx_wr_*` (Body or Hands), or `shpx_wa_*` (Body or Legs) and a maximum length of 30 characters."u8); + return ret; + } + private static ReadOnlySpan AvailableSlots => [ diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 5292bd17..8439587c 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -3,6 +3,7 @@ using Dalamud.Interface.Utility.Raii; using ImGuiNET; using OtterGui.Services; using OtterGui.Text; +using Penumbra.Collections.Cache; using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; @@ -12,9 +13,9 @@ namespace Penumbra.UI.Tabs.Debug; public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) : IUiService { - private int _objectIndex = 0; + private int _objectIndex; - public unsafe void Draw() + public void Draw() { ImUtf8.InputScalar("Object Index"u8, ref _objectIndex); var actor = objects[0]; @@ -31,93 +32,117 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) return; } - var data = resolver.IdentifyCollection(actor.AsObject, true); - using (var treeNode1 = ImUtf8.TreeNode($"Collection Shape Cache ({data.ModCollection})")) + DrawCollectionShapeCache(actor); + DrawCharacterShapes(human); + } + + private unsafe void DrawCollectionShapeCache(Actor actor) + { + var data = resolver.IdentifyCollection(actor.AsObject, true); + using var treeNode1 = ImUtf8.TreeNode($"Collection Shape Cache ({data.ModCollection})"); + if (!treeNode1.Success || !data.ModCollection.HasCache) + return; + + using var table = ImUtf8.Table("##cacheTable"u8, 3, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("Condition"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Shape"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Enabled"u8, ImGuiTableColumnFlags.WidthStretch); + + ImGui.TableHeadersRow(); + foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State) { - if (treeNode1.Success && data.ModCollection.HasCache) - { - using var table = ImUtf8.Table("##cacheTable"u8, 2, ImGuiTableFlags.RowBg); - if (!table) - return; - - ImUtf8.TableSetupColumn("shape"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); - ImUtf8.TableSetupColumn("enabled"u8, ImGuiTableColumnFlags.WidthStretch); - - foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State) - { - ImUtf8.DrawTableColumn(shape.AsSpan); - if (set.All) - { - ImUtf8.DrawTableColumn("All"u8); - } - else - { - ImGui.TableNextColumn(); - foreach (var slot in ShapeManager.UsedModels) - { - if (!set[slot]) - continue; - - ImUtf8.Text($"All {slot.ToName()}, "); - ImGui.SameLine(0, 0); - } - - foreach (var item in set.Where(i => !set[i.Slot])) - { - ImUtf8.Text($"{item.Slot.ToName()} {item.Id.Id:D4}, "); - ImGui.SameLine(0, 0); - } - } - } - } + ImGui.TableNextColumn(); + DrawShape(shape, set); } - using (var treeNode2 = ImUtf8.TreeNode("Character Model Shapes"u8)) + foreach (var (condition, dict) in data.ModCollection.MetaCache!.Shp.ConditionState) { - if (treeNode2) + foreach (var (shape, set) in dict) { - using var table = ImUtf8.Table("##table"u8, 5, ImGuiTableFlags.RowBg); - if (!table) - return; + ImUtf8.DrawTableColumn(condition.AsSpan); + DrawShape(shape, set); + } + } + } - ImUtf8.TableSetupColumn("idx"u8, ImGuiTableColumnFlags.WidthFixed, 25 * ImUtf8.GlobalScale); - ImUtf8.TableSetupColumn("name"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); - ImUtf8.TableSetupColumn("ptr"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); - ImUtf8.TableSetupColumn("mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); - ImUtf8.TableSetupColumn("shapes"u8, ImGuiTableColumnFlags.WidthStretch); + private static void DrawShape(in ShapeString shape, ShpCache.ShpHashSet set) + { + ImUtf8.DrawTableColumn(shape.AsSpan); + if (set.All) + { + ImUtf8.DrawTableColumn("All"u8); + } + else + { + ImGui.TableNextColumn(); + foreach (var slot in ShapeManager.UsedModels) + { + if (!set[slot]) + continue; - var disabledColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); - for (var i = 0; i < human.AsHuman->SlotCount; ++i) + ImUtf8.Text($"All {slot.ToName()}, "); + ImGui.SameLine(0, 0); + } + + foreach (var item in set.Where(i => !set[i.Slot])) + { + ImUtf8.Text($"{item.Slot.ToName()} {item.Id.Id:D4}, "); + ImGui.SameLine(0, 0); + } + } + } + + private unsafe void DrawCharacterShapes(Model human) + { + using var treeNode2 = ImUtf8.TreeNode("Character Model Shapes"u8); + if (!treeNode2) + return; + + using var table = ImUtf8.Table("##table"u8, 5, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("#"u8, ImGuiTableColumnFlags.WidthFixed, 25 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); + ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("Shapes"u8, ImGuiTableColumnFlags.WidthStretch); + + ImGui.TableHeadersRow(); + + var disabledColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); + for (var i = 0; i < human.AsHuman->SlotCount; ++i) + { + ImUtf8.DrawTableColumn($"{(uint)i:D2}"); + ImUtf8.DrawTableColumn(((HumanSlot)i).ToName()); + + ImGui.TableNextColumn(); + var model = human.AsHuman->Models[i]; + Penumbra.Dynamis.DrawPointer((nint)model); + if (model is not null) + { + var mask = model->EnabledShapeKeyIndexMask; + ImUtf8.DrawTableColumn($"{mask:X8}"); + ImGui.TableNextColumn(); + foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) { - ImUtf8.DrawTableColumn($"{(uint)i:D2}"); - ImUtf8.DrawTableColumn(((HumanSlot)i).ToName()); - - ImGui.TableNextColumn(); - var model = human.AsHuman->Models[i]; - Penumbra.Dynamis.DrawPointer((nint)model); - if (model is not null) - { - var mask = model->EnabledShapeKeyIndexMask; - ImUtf8.DrawTableColumn($"{mask:X8}"); - ImGui.TableNextColumn(); - foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) - { - var disabled = (mask & (1u << idx)) is 0; - using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); - ImUtf8.Text(shape.AsSpan()); - ImGui.SameLine(0, 0); - ImUtf8.Text(", "u8); - if (idx % 8 < 7) - ImGui.SameLine(0, 0); - } - } - else - { - ImGui.TableNextColumn(); - ImGui.TableNextColumn(); - } + var disabled = (mask & (1u << idx)) is 0; + using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); + ImUtf8.Text(shape.AsSpan()); + ImGui.SameLine(0, 0); + ImUtf8.Text(", "u8); + if (idx % 8 < 7) + ImGui.SameLine(0, 0); } } + else + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + } } } } diff --git a/schemas/structs/meta_shp.json b/schemas/structs/meta_shp.json index 197f3104..4f868a0a 100644 --- a/schemas/structs/meta_shp.json +++ b/schemas/structs/meta_shp.json @@ -16,6 +16,12 @@ "minLength": 5, "maxLength": 30, "pattern": "^shpx_" + }, + "ShapeCondition": { + "type": "string", + "minLength": 8, + "maxLength": 30, + "pattern": "^shpx_(wa|an|wr)_" } }, "required": [ From 08e8b9d2a460ad7245ddcf6006e10d23cfc3f267 Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 15 May 2025 22:28:36 +0000 Subject: [PATCH 1207/1381] [CI] Updating repo.json for testing_1.3.6.10 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 13d91e5c..137ba00c 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.9", + "TestingAssemblyVersion": "1.3.6.10", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.10/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 52927ff06bbc7c159a237876e4cf50ea328dbddd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 May 2025 12:31:13 +0200 Subject: [PATCH 1208/1381] Fix clipping in meta edits. --- OtterGui | 2 +- Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/OtterGui b/OtterGui index f130c928..9aeda9a8 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit f130c928928cb0d48d3c807b7df5874c2460fe98 +Subproject commit 9aeda9a892d9b971e32b10db21a8daf9c0b9ee53 diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs index a6f042b7..7e788462 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -44,9 +44,13 @@ public abstract class MetaDrawer(ModMetaEditor editor, Meta DrawNew(); var height = ColumnHeight; - var skips = ImGuiClip.GetNecessarySkipsAtPos(height, ImGui.GetCursorPosY()); - var remainder = ImGuiClip.ClippedTableDraw(Enumerate(), skips, DrawLine, Count); - ImGuiClip.DrawEndDummy(remainder, height); + var skips = ImGuiClip.GetNecessarySkipsAtPos(height, ImGui.GetCursorPosY(), Count); + if (skips < Count) + { + var remainder = ImGuiClip.ClippedTableDraw(Enumerate(), skips, DrawLine, Count); + if (remainder > 0) + ImGuiClip.DrawEndDummy(remainder, height); + } void DrawLine((TIdentifier Identifier, TEntry Value) pair) => DrawEntry(pair.Identifier, pair.Value); From 3078c467d0666e28ab25dd31d515648300f946da Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 May 2025 12:31:34 +0200 Subject: [PATCH 1209/1381] Fix issue with empty and temporary settings. --- Penumbra/Mods/Settings/ModSettings.cs | 15 +++++++++++---- Penumbra/Mods/Settings/TemporaryModSettings.cs | 11 +++++++++-- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 4 ++-- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 2 +- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/Penumbra/Mods/Settings/ModSettings.cs b/Penumbra/Mods/Settings/ModSettings.cs index 07217d4d..bbdd6bfa 100644 --- a/Penumbra/Mods/Settings/ModSettings.cs +++ b/Penumbra/Mods/Settings/ModSettings.cs @@ -11,11 +11,18 @@ namespace Penumbra.Mods.Settings; /// Contains the settings for a given mod. public class ModSettings { - public static readonly ModSettings Empty = new(); + public static readonly ModSettings Empty = new(true); - public SettingList Settings { get; internal init; } = []; - public ModPriority Priority { get; set; } - public bool Enabled { get; set; } + public SettingList Settings { get; internal init; } = []; + public ModPriority Priority { get; set; } + public bool Enabled { get; set; } + public bool IsEmpty { get; protected init; } + + public ModSettings() + { } + + protected ModSettings(bool empty) + => IsEmpty = empty; // Create an independent copy of the current settings. public ModSettings DeepCopy() diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index a16a9feb..ce438aac 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -2,9 +2,11 @@ namespace Penumbra.Mods.Settings; public sealed class TemporaryModSettings : ModSettings { + public new static readonly TemporaryModSettings Empty = new(true); + public const string OwnSource = "yourself"; public string Source = string.Empty; - public int Lock = 0; + public int Lock; public bool ForceInherit; // Create default settings for a given mod. @@ -21,12 +23,16 @@ public sealed class TemporaryModSettings : ModSettings public TemporaryModSettings() { } + private TemporaryModSettings(bool empty) + : base(empty) + { } + public TemporaryModSettings(Mod mod, ModSettings? clone, string source = OwnSource, int key = 0) { Source = source; Lock = key; ForceInherit = clone == null; - if (clone != null && clone != Empty) + if (clone is { IsEmpty: false }) { Enabled = clone.Enabled; Priority = clone.Priority; @@ -34,6 +40,7 @@ public sealed class TemporaryModSettings : ModSettings } else { + IsEmpty = true; Enabled = false; Priority = ModPriority.Default; Settings = SettingList.Default(mod); diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index 666fce61..3e165cb5 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -49,7 +49,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle case GroupDrawBehaviour.SingleSelection: ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); useDummy = false; - DrawSingleGroupCombo(group, idx, settings == ModSettings.Empty ? group.DefaultSettings : settings.Settings[idx]); + DrawSingleGroupCombo(group, idx, settings.IsEmpty ? group.DefaultSettings : settings.Settings[idx]); break; } } @@ -59,7 +59,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle { ImGuiUtil.Dummy(UiHelpers.DefaultSpace, useDummy); useDummy = false; - var option = settings == ModSettings.Empty ? group.DefaultSettings : settings.Settings[idx]; + var option = settings.IsEmpty ? group.DefaultSettings : settings.Settings[idx]; if (group.Behaviour is GroupDrawBehaviour.MultiSelection) DrawMultiGroup(group, idx, option); else diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 3988de35..7c6ebf74 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -183,7 +183,7 @@ public class ModPanelSettingsTab( /// private void DrawRemoveSettings() { - var drawInherited = !_inherited && selection.Settings != ModSettings.Empty; + var drawInherited = !_inherited && !selection.Settings.IsEmpty; var scroll = ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize + ImGui.GetStyle().ItemInnerSpacing.X : 0; var buttonSize = ImUtf8.CalcTextSize("Turn Permanent_"u8).X; var offset = drawInherited From fbc4c2d054dd37575d495736d01fa6cd97b7ec07 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 May 2025 12:54:09 +0200 Subject: [PATCH 1210/1381] Improve option select combo. --- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 75 +++++++++++++------ .../UI/AdvancedWindow/OptionSelectCombo.cs | 43 +++++++++++ 2 files changed, 95 insertions(+), 23 deletions(-) create mode 100644 Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index ccbbf0db..0b9fcde9 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -7,9 +7,11 @@ using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; using OtterGui.Extensions; +using OtterGui.Log; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; +using OtterGui.Widgets; using Penumbra.Api.Enums; using Penumbra.Collections.Manager; using Penumbra.Communication; @@ -34,6 +36,41 @@ using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; namespace Penumbra.UI.AdvancedWindow; +public sealed class OptionSelectCombo(ModEditor editor, ModEditWindow window) + : FilterComboCache<(string FullName, (int Group, int Data) Index)>( + () => window.Mod!.AllDataContainers.Select(c => (c.GetFullName(), c.GetDataIndices())).ToList(), MouseWheelType.Control, Penumbra.Log) +{ + private ImRaii.ColorStyle _border; + + protected override void DrawCombo(string label, string preview, string tooltip, int currentSelected, float previewWidth, float itemHeight, + ImGuiComboFlags flags) + { + _border = ImRaii.PushFrameBorder(ImUtf8.GlobalScale, ColorId.FolderLine.Value()); + base.DrawCombo(label, preview, tooltip, currentSelected, previewWidth, itemHeight, flags); + _border.Dispose(); + } + + protected override void DrawFilter(int currentSelected, float width) + { + _border.Dispose(); + base.DrawFilter(currentSelected, width); + } + + public bool Draw(float width) + { + var flags = window.Mod!.AllDataContainers.Count() switch + { + 0 => ImGuiComboFlags.NoArrowButton, + > 8 => ImGuiComboFlags.HeightLargest, + _ => ImGuiComboFlags.None, + }; + return Draw("##optionSelector", editor.Option!.GetFullName(), string.Empty, width, ImGui.GetTextLineHeight(), flags); + } + + protected override bool DrawSelectable(int globalIdx, bool selected) + => ImUtf8.Selectable(Items[globalIdx].FullName, selected); +} + public partial class ModEditWindow : Window, IDisposable, IUiService { private const string WindowBaseLabel = "###SubModEdit"; @@ -49,11 +86,12 @@ public partial class ModEditWindow : Window, IDisposable, IUiService private readonly IDragDropManager _dragDropManager; private readonly IDataManager _gameData; private readonly IFramework _framework; + private readonly OptionSelectCombo _optionSelect; private Vector2 _iconSize = Vector2.Zero; private bool _allowReduplicate; - public Mod? Mod { get; private set; } + public Mod? Mod { get; private set; } public bool IsLoading @@ -208,7 +246,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService if (IsLoading) { var radius = 100 * ImUtf8.GlobalScale; - var thickness = (int) (20 * ImUtf8.GlobalScale); + var thickness = (int)(20 * ImUtf8.GlobalScale); var offsetX = ImGui.GetContentRegionAvail().X / 2 - radius; var offsetY = ImGui.GetContentRegionAvail().Y / 2 - radius; ImGui.SetCursorPos(ImGui.GetCursorPos() + new Vector2(offsetX, offsetY)); @@ -216,7 +254,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService return; } - using var tabBar = ImRaii.TabBar("##tabs"); + using var tabBar = ImUtf8.TabBar("##tabs"u8); if (!tabBar) return; @@ -231,7 +269,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _materialTab.Draw(); DrawTextureTab(); _shaderPackageTab.Draw(); - using (var tab = ImRaii.TabItem("Item Swap")) + using (var tab = ImUtf8.TabItem("Item Swap"u8)) { if (tab) _itemSwapTab.DrawContent(); @@ -453,10 +491,11 @@ public partial class ModEditWindow : Window, IDisposable, IUiService private bool DrawOptionSelectHeader() { - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero).Push(ImGuiStyleVar.FrameRounding, 0); - var width = new Vector2(ImGui.GetContentRegionAvail().X / 3, 0); - var ret = false; - if (ImUtf8.ButtonEx("Default Option"u8, "Switch to the default option for the mod.\nThis resets unsaved changes."u8, width, _editor.Option is DefaultSubMod)) + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero).Push(ImGuiStyleVar.FrameRounding, 0); + var width = new Vector2(ImGui.GetContentRegionAvail().X / 3, 0); + var ret = false; + if (ImUtf8.ButtonEx("Default Option"u8, "Switch to the default option for the mod.\nThis resets unsaved changes."u8, width, + _editor.Option is DefaultSubMod)) { _editor.LoadOption(-1, 0).Wait(); ret = true; @@ -470,22 +509,11 @@ public partial class ModEditWindow : Window, IDisposable, IUiService } ImGui.SameLine(); - ImGui.SetNextItemWidth(width.X); - style.Push(ImGuiStyleVar.FrameBorderSize, ImGuiHelpers.GlobalScale); - using var color = ImRaii.PushColor(ImGuiCol.Border, ColorId.FolderLine.Value()); - using var combo = ImUtf8.Combo("##optionSelector"u8, _editor.Option!.GetFullName()); - if (!combo) - return ret; - - foreach (var (option, idx) in Mod!.AllDataContainers.WithIndex()) + if (_optionSelect.Draw(width.X)) { - using var id = ImRaii.PushId(idx); - if (ImGui.Selectable(option.GetFullName(), option == _editor.Option)) - { - var (groupIdx, dataIdx) = option.GetDataIndices(); - _editor.LoadOption(groupIdx, dataIdx).Wait(); - ret = true; - } + var (groupIdx, dataIdx) = _optionSelect.CurrentSelection.Index; + _editor.LoadOption(groupIdx, dataIdx).Wait(); + ret = true; } return ret; @@ -656,6 +684,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _fileDialog = fileDialog; _framework = framework; _metaDrawers = metaDrawers; + _optionSelect = new OptionSelectCombo(editor, this); _materialTab = new FileEditor(this, _communicator, gameData, config, _editor.Compactor, _fileDialog, "Materials", ".mtrl", () => PopulateIsOnPlayer(_editor.Files.Mtrl, ResourceType.Mtrl), DrawMaterialPanel, () => Mod?.ModPath.FullName ?? string.Empty, (bytes, path, writable) => mtrlTabFactory.Create(this, new MtrlFile(bytes), path, writable)); diff --git a/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs b/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs new file mode 100644 index 00000000..1fa12b6d --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs @@ -0,0 +1,43 @@ +using ImGuiNET; +using OtterGui.Raii; +using OtterGui.Text; +using OtterGui.Widgets; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow; + +public sealed class OptionSelectCombo(ModEditor editor, ModEditWindow window) + : FilterComboCache<(string FullName, (int Group, int Data) Index)>( + () => window.Mod!.AllDataContainers.Select(c => (c.GetFullName(), c.GetDataIndices())).ToList(), MouseWheelType.Control, Penumbra.Log) +{ + private ImRaii.ColorStyle _border; + + protected override void DrawCombo(string label, string preview, string tooltip, int currentSelected, float previewWidth, float itemHeight, + ImGuiComboFlags flags) + { + _border = ImRaii.PushFrameBorder(ImUtf8.GlobalScale, ColorId.FolderLine.Value()); + base.DrawCombo(label, preview, tooltip, currentSelected, previewWidth, itemHeight, flags); + _border.Dispose(); + } + + protected override void DrawFilter(int currentSelected, float width) + { + _border.Dispose(); + base.DrawFilter(currentSelected, width); + } + + public bool Draw(float width) + { + var flags = window.Mod!.AllDataContainers.Count() switch + { + 0 => ImGuiComboFlags.NoArrowButton, + > 8 => ImGuiComboFlags.HeightLargest, + _ => ImGuiComboFlags.None, + }; + return Draw("##optionSelector", editor.Option!.GetFullName(), string.Empty, width, ImGui.GetTextLineHeight(), flags); + } + + protected override bool DrawSelectable(int globalIdx, bool selected) + => ImUtf8.Selectable(Items[globalIdx].FullName, selected); +} From e326e3d809b0cfa7a71f9290e6e449f8e05e0f46 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 May 2025 15:52:47 +0200 Subject: [PATCH 1211/1381] Update shp conditions. --- Penumbra/Collections/Cache/ShpCache.cs | 81 ++++++++--------- Penumbra/Meta/Manipulations/ShpIdentifier.cs | 61 +++++++------ Penumbra/Meta/ShapeManager.cs | 26 +++--- .../UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 89 +++++++++---------- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 35 -------- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 13 +-- schemas/structs/meta_enums.json | 4 + schemas/structs/meta_shp.json | 7 +- 8 files changed, 137 insertions(+), 179 deletions(-) diff --git a/Penumbra/Collections/Cache/ShpCache.cs b/Penumbra/Collections/Cache/ShpCache.cs index eaf949d9..ee6a4e65 100644 --- a/Penumbra/Collections/Cache/ShpCache.cs +++ b/Penumbra/Collections/Cache/ShpCache.cs @@ -8,27 +8,24 @@ namespace Penumbra.Collections.Cache; public sealed class ShpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { public bool ShouldBeEnabled(in ShapeString shape, HumanSlot slot, PrimaryId id) - => _shpData.TryGetValue(shape, out var value) && value.Contains(slot, id); + => EnabledCount > 0 && _shpData.TryGetValue(shape, out var value) && value.Contains(slot, id); - internal IReadOnlyDictionary State - => _shpData; - - internal IEnumerable<(ShapeString, IReadOnlyDictionary)> ConditionState - => _conditionalSet.Select(kvp => (kvp.Key, (IReadOnlyDictionary)kvp.Value)); - - public bool CheckConditionState(ShapeString condition, [NotNullWhen(true)] out IReadOnlyDictionary? dict) - { - if (_conditionalSet.TryGetValue(condition, out var d)) + internal IReadOnlyDictionary State(ShapeConnectorCondition connector) + => connector switch { - dict = d; - return true; - } + ShapeConnectorCondition.None => _shpData, + ShapeConnectorCondition.Wrists => _wristConnectors, + ShapeConnectorCondition.Waist => _waistConnectors, + ShapeConnectorCondition.Ankles => _ankleConnectors, + _ => [], + }; - dict = null; - return false; - } + public int EnabledCount { get; private set; } + public bool ShouldBeEnabled(ShapeConnectorCondition connector, in ShapeString shape, HumanSlot slot, PrimaryId id) + => State(connector).TryGetValue(shape, out var value) && value.Contains(slot, id); + public sealed class ShpHashSet : HashSet<(HumanSlot Slot, PrimaryId Id)> { private readonly BitArray _allIds = new(ShapeManager.ModelSlotSize); @@ -92,14 +89,18 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) => !_allIds.HasAnySet() && Count is 0; } - private readonly Dictionary _shpData = []; - private readonly Dictionary> _conditionalSet = []; + private readonly Dictionary _shpData = []; + private readonly Dictionary _wristConnectors = []; + private readonly Dictionary _waistConnectors = []; + private readonly Dictionary _ankleConnectors = []; public void Reset() { Clear(); _shpData.Clear(); - _conditionalSet.Clear(); + _wristConnectors.Clear(); + _waistConnectors.Clear(); + _ankleConnectors.Clear(); } protected override void Dispose(bool _) @@ -107,24 +108,16 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) protected override void ApplyModInternal(ShpIdentifier identifier, ShpEntry entry) { - if (identifier.ShapeCondition.Length > 0) + switch (identifier.ConnectorCondition) { - if (!_conditionalSet.TryGetValue(identifier.ShapeCondition, out var shapes)) - { - if (!entry.Value) - return; - - shapes = new Dictionary(); - _conditionalSet.Add(identifier.ShapeCondition, shapes); - } - - Func(shapes); - } - else - { - Func(_shpData); + case ShapeConnectorCondition.None: Func(_shpData); break; + case ShapeConnectorCondition.Wrists: Func(_wristConnectors); break; + case ShapeConnectorCondition.Waist: Func(_waistConnectors); break; + case ShapeConnectorCondition.Ankles: Func(_ankleConnectors); break; } + return; + void Func(Dictionary dict) { if (!dict.TryGetValue(identifier.Shape, out var value)) @@ -136,22 +129,19 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) dict.Add(identifier.Shape, value); } - value.TrySet(identifier.Slot, identifier.Id, entry); + if (value.TrySet(identifier.Slot, identifier.Id, entry)) + ++EnabledCount; } } protected override void RevertModInternal(ShpIdentifier identifier) { - if (identifier.ShapeCondition.Length > 0) + switch (identifier.ConnectorCondition) { - if (!_conditionalSet.TryGetValue(identifier.ShapeCondition, out var shapes)) - return; - - Func(shapes); - } - else - { - Func(_shpData); + case ShapeConnectorCondition.None: Func(_shpData); break; + case ShapeConnectorCondition.Wrists: Func(_wristConnectors); break; + case ShapeConnectorCondition.Waist: Func(_waistConnectors); break; + case ShapeConnectorCondition.Ankles: Func(_ankleConnectors); break; } return; @@ -162,7 +152,10 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) return; if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False) && value.IsEmpty) + { + --EnabledCount; _shpData.Remove(identifier.Shape); + } } } } diff --git a/Penumbra/Meta/Manipulations/ShpIdentifier.cs b/Penumbra/Meta/Manipulations/ShpIdentifier.cs index 777be512..b3fdb0cb 100644 --- a/Penumbra/Meta/Manipulations/ShpIdentifier.cs +++ b/Penumbra/Meta/Manipulations/ShpIdentifier.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; @@ -7,7 +8,16 @@ using Penumbra.Interop.Structs; namespace Penumbra.Meta.Manipulations; -public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeString Shape, ShapeString ShapeCondition) +[JsonConverter(typeof(StringEnumConverter))] +public enum ShapeConnectorCondition : byte +{ + None = 0, + Wrists = 1, + Waist = 2, + Ankles = 3, +} + +public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeString Shape, ShapeConnectorCondition ConnectorCondition) : IComparable, IMetaIdentifier { public int CompareTo(ShpIdentifier other) @@ -34,11 +44,11 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape return 1; } - var shapeComparison = Shape.CompareTo(other.Shape); - if (shapeComparison is not 0) - return shapeComparison; + var conditionComparison = ConnectorCondition.CompareTo(other.ConnectorCondition); + if (conditionComparison is not 0) + return conditionComparison; - return ShapeCondition.CompareTo(other.ShapeCondition); + return Shape.CompareTo(other.Shape); } @@ -62,9 +72,13 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape sb.Append("All IDs"); } - if (ShapeCondition.Length > 0) - sb.Append(" - ") - .Append(ShapeCondition); + switch (ConnectorCondition) + { + case ShapeConnectorCondition.Wrists: sb.Append(" - Wrist Connector"); break; + case ShapeConnectorCondition.Waist: sb.Append(" - Waist Connector"); break; + case ShapeConnectorCondition.Ankles: sb.Append(" - Ankle Connector"); break; + } + return sb.ToString(); } @@ -87,20 +101,16 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (!ValidateCustomShapeString(Shape)) return false; - if (ShapeCondition.Length is 0) - return true; - - if (!ValidateCustomShapeString(ShapeCondition)) + if (!Enum.IsDefined(ConnectorCondition)) return false; - return Slot switch + return ConnectorCondition switch { - HumanSlot.Hands when ShapeCondition.IsWrist() => true, - HumanSlot.Body when ShapeCondition.IsWrist() || ShapeCondition.IsWaist() => true, - HumanSlot.Legs when ShapeCondition.IsWaist() || ShapeCondition.IsAnkle() => true, - HumanSlot.Feet when ShapeCondition.IsAnkle() => true, - HumanSlot.Unknown when ShapeCondition.IsWrist() || ShapeCondition.IsWaist() || ShapeCondition.IsAnkle() => true, - _ => false, + ShapeConnectorCondition.None => true, + ShapeConnectorCondition.Wrists => Slot is HumanSlot.Body or HumanSlot.Hands or HumanSlot.Unknown, + ShapeConnectorCondition.Waist => Slot is HumanSlot.Body or HumanSlot.Legs or HumanSlot.Unknown, + ShapeConnectorCondition.Ankles => Slot is HumanSlot.Legs or HumanSlot.Feet or HumanSlot.Unknown, + _ => false, }; } @@ -145,8 +155,8 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (Id.HasValue) jObj["Id"] = Id.Value.Id.ToString(); jObj["Shape"] = Shape.ToString(); - if (ShapeCondition.Length > 0) - jObj["ShapeCondition"] = ShapeCondition.ToString(); + if (ConnectorCondition is not ShapeConnectorCondition.None) + jObj["ConnectorCondition"] = ConnectorCondition.ToString(); return jObj; } @@ -156,11 +166,10 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (shape is null || !ShapeString.TryRead(shape, out var shapeString)) return null; - var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; - var id = jObj["Id"]?.ToObject(); - var shapeCondition = jObj["ShapeCondition"]?.ToObject(); - var shapeConditionString = shapeCondition is null || !ShapeString.TryRead(shapeCondition, out var s) ? ShapeString.Empty : s; - var identifier = new ShpIdentifier(slot, id, shapeString, shapeConditionString); + var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; + var id = jObj["Id"]?.ToObject(); + var connectorCondition = jObj["ConnectorCondition"]?.ToObject() ?? ShapeConnectorCondition.None; + var identifier = new ShpIdentifier(slot, id, shapeString, connectorCondition); return identifier.Validate() ? identifier : null; } diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs index 57f6f23f..7431b1c2 100644 --- a/Penumbra/Meta/ShapeManager.cs +++ b/Penumbra/Meta/ShapeManager.cs @@ -1,4 +1,3 @@ -using System.Reflection.Metadata.Ecma335; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Cache; @@ -80,8 +79,7 @@ public class ShapeManager : IRequiredService, IDisposable { _temporaryIndices[i].TryAdd(shapeString, index); _temporaryMasks[i] |= (ushort)(1 << index); - if (cache.State.Count > 0 - && cache.ShouldBeEnabled(shapeString, modelIndex, _ids[(int)modelIndex])) + if (cache.ShouldBeEnabled(shapeString, modelIndex, _ids[(int)modelIndex])) _temporaryValues[i] |= (ushort)(1 << index); } else @@ -102,14 +100,14 @@ public class ShapeManager : IRequiredService, IDisposable { _temporaryValues[1] |= 1u << topIndex; _temporaryValues[2] |= 1u << handIndex; - CheckCondition(shape, HumanSlot.Body, HumanSlot.Hands, 1, 2); + CheckCondition(cache.State(ShapeConnectorCondition.Wrists), HumanSlot.Body, HumanSlot.Hands, 1, 2); } if (shape.IsWaist() && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) { _temporaryValues[1] |= 1u << topIndex; _temporaryValues[3] |= 1u << legIndex; - CheckCondition(shape, HumanSlot.Body, HumanSlot.Legs, 1, 3); + CheckCondition(cache.State(ShapeConnectorCondition.Waist), HumanSlot.Body, HumanSlot.Legs, 1, 3); } } @@ -119,25 +117,23 @@ public class ShapeManager : IRequiredService, IDisposable { _temporaryValues[3] |= 1u << bottomIndex; _temporaryValues[4] |= 1u << footIndex; - CheckCondition(shape, HumanSlot.Legs, HumanSlot.Feet, 3, 4); + CheckCondition(cache.State(ShapeConnectorCondition.Ankles), HumanSlot.Legs, HumanSlot.Feet, 3, 4); } } return; - void CheckCondition(in ShapeString shape, HumanSlot slot1, HumanSlot slot2, int idx1, int idx2) + void CheckCondition(IReadOnlyDictionary dict, HumanSlot slot1, HumanSlot slot2, int idx1, int idx2) { - if (!cache.CheckConditionState(shape, out var dict)) + if (dict.Count is 0) return; - foreach (var (subShape, set) in dict) + foreach (var (shape, set) in dict) { - if (set.Contains(slot1, _ids[idx1])) - if (_temporaryIndices[idx1].TryGetValue(subShape, out var subIndex)) - _temporaryValues[idx1] |= 1u << subIndex; - if (set.Contains(slot2, _ids[idx2])) - if (_temporaryIndices[idx2].TryGetValue(subShape, out var subIndex)) - _temporaryValues[idx2] |= 1u << subIndex; + if (set.Contains(slot1, _ids[idx1]) && _temporaryIndices[idx1].TryGetValue(shape, out var index1)) + _temporaryValues[idx1] |= 1u << index1; + if (set.Contains(slot2, _ids[idx2]) && _temporaryIndices[idx2].TryGetValue(shape, out var index2)) + _temporaryValues[idx2] |= 1u << index2; } } } diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs index fe7e743c..c40726f8 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -19,10 +19,8 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile public override ReadOnlySpan Label => "Shape Keys (SHP)###SHP"u8; - private ShapeString _buffer = ShapeString.TryRead("shpx_"u8, out var s) ? s : ShapeString.Empty; - private ShapeString _conditionBuffer = ShapeString.Empty; + private ShapeString _buffer = ShapeString.TryRead("shpx_"u8, out var s) ? s : ShapeString.Empty; private bool _identifierValid; - private bool _conditionValid = true; public override int NumColumns => 7; @@ -32,7 +30,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile protected override void Initialize() { - Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeString.Empty, ShapeString.Empty); + Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeString.Empty, ShapeConnectorCondition.None); } protected override void DrawNew() @@ -42,7 +40,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile new Lazy(() => MetaDictionary.SerializeTo([], Editor.Shp))); ImGui.TableNextColumn(); - var canAdd = !Editor.Contains(Identifier) && _identifierValid && _conditionValid; + var canAdd = !Editor.Contains(Identifier) && _identifierValid; var tt = canAdd ? "Stage this edit."u8 : _identifierValid @@ -69,7 +67,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile .OrderBy(kvp => kvp.Key.Shape) .ThenBy(kvp => kvp.Key.Slot) .ThenBy(kvp => kvp.Key.Id) - .ThenBy(kvp => kvp.Key.ShapeCondition) + .ThenBy(kvp => kvp.Key.ConnectorCondition) .Select(kvp => (kvp.Key, kvp.Value)); protected override int Count @@ -87,7 +85,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile changes |= DrawShapeKeyInput(ref identifier, ref _buffer, ref _identifierValid); ImGui.TableNextColumn(); - changes |= DrawShapeConditionInput(ref identifier, ref _conditionBuffer, ref _conditionValid); + changes |= DrawConnectorConditionInput(ref identifier); return changes; } @@ -109,9 +107,9 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ImUtf8.TextFramed(identifier.Shape.AsSpan, FrameColor); ImGui.TableNextColumn(); - if (identifier.ShapeCondition.Length > 0) + if (identifier.ConnectorCondition is not ShapeConnectorCondition.None) { - ImUtf8.TextFramed(identifier.ShapeCondition.AsSpan, FrameColor); + ImUtf8.TextFramed($"{identifier.ConnectorCondition}", FrameColor); ImUtf8.HoverTooltip("Connector condition for this shape to be activated."); } } @@ -190,27 +188,18 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } else { - if (_conditionBuffer.Length > 0 - && (_conditionBuffer.IsAnkle() && slot is not HumanSlot.Feet and not HumanSlot.Legs - || _conditionBuffer.IsWrist() && slot is not HumanSlot.Hands and not HumanSlot.Body - || _conditionBuffer.IsWaist() && slot is not HumanSlot.Body and not HumanSlot.Legs)) + identifier = identifier with { - identifier = identifier with + Slot = slot, + ConnectorCondition = Identifier.ConnectorCondition switch { - Slot = slot, - ShapeCondition = ShapeString.Empty, - }; - _conditionValid = false; - } - else - { - identifier = identifier with - { - Slot = slot, - ShapeCondition = _conditionBuffer, - }; - _conditionValid = true; - } + ShapeConnectorCondition.Wrists when slot is HumanSlot.Body or HumanSlot.Hands => ShapeConnectorCondition.Wrists, + ShapeConnectorCondition.Waist when slot is HumanSlot.Body or HumanSlot.Legs => ShapeConnectorCondition.Waist, + ShapeConnectorCondition.Ankles when slot is HumanSlot.Legs or HumanSlot.Feet => ShapeConnectorCondition.Ankles, + _ => ShapeConnectorCondition.None, + }, + }; + ret = true; } } } @@ -241,30 +230,40 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } - public static unsafe bool DrawShapeConditionInput(ref ShpIdentifier identifier, ref ShapeString buffer, ref bool valid, - float unscaledWidth = 150) + public static unsafe bool DrawConnectorConditionInput(ref ShpIdentifier identifier, float unscaledWidth = 150) { - var ret = false; - var ptr = Unsafe.AsPointer(ref buffer); - var span = new Span(ptr, ShapeString.MaxLength + 1); - using (new ImRaii.ColorStyle().Push(ImGuiCol.Border, Colors.RegexWarningBorder, !valid).Push(ImGuiStyleVar.FrameBorderSize, 1f, !valid)) + var ret = false; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + var (showWrists, showWaist, showAnkles, disable) = identifier.Slot switch { - ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); - if (ImUtf8.InputText("##shpCondition"u8, span, out int newLength, "Shape Condition..."u8)) + HumanSlot.Unknown => (true, true, true, false), + HumanSlot.Body => (true, true, false, false), + HumanSlot.Legs => (false, true, true, false), + HumanSlot.Hands => (true, false, false, false), + HumanSlot.Feet => (false, false, true, false), + _ => (false, false, false, true), + }; + using var disabled = ImRaii.Disabled(disable); + using (var combo = ImUtf8.Combo("##shpCondition"u8, $"{identifier.ConnectorCondition}")) + { + if (combo) { - buffer.ForceLength((byte)newLength); - valid = ShpIdentifier.ValidateCustomShapeString(buffer) - && (buffer.IsAnkle() && identifier.Slot is HumanSlot.Unknown or HumanSlot.Feet or HumanSlot.Legs - || buffer.IsWaist() && identifier.Slot is HumanSlot.Unknown or HumanSlot.Body or HumanSlot.Legs - || buffer.IsWrist() && identifier.Slot is HumanSlot.Unknown or HumanSlot.Body or HumanSlot.Hands); - if (valid) - identifier = identifier with { ShapeCondition = buffer }; - ret = true; + if (ImUtf8.Selectable("None"u8, identifier.ConnectorCondition is ShapeConnectorCondition.None)) + identifier = identifier with { ConnectorCondition = ShapeConnectorCondition.None }; + + if (showWrists && ImUtf8.Selectable("Wrists"u8, identifier.ConnectorCondition is ShapeConnectorCondition.Wrists)) + identifier = identifier with { ConnectorCondition = ShapeConnectorCondition.Wrists }; + + if (showWaist && ImUtf8.Selectable("Waist"u8, identifier.ConnectorCondition is ShapeConnectorCondition.Waist)) + identifier = identifier with { ConnectorCondition = ShapeConnectorCondition.Waist }; + + if (showAnkles && ImUtf8.Selectable("Ankles"u8, identifier.ConnectorCondition is ShapeConnectorCondition.Ankles)) + identifier = identifier with { ConnectorCondition = ShapeConnectorCondition.Ankles }; } } ImUtf8.HoverTooltip( - "Supported conditional shape keys need to have the format `shpx_an_*` (Legs or Feet), `shpx_wr_*` (Body or Hands), or `shpx_wa_*` (Body or Legs) and a maximum length of 30 characters."u8); + "Only activate this shape key if any custom connector shape keys (shpx_[wr|wa|an]_*) are also enabled through matching attributes."u8); return ret; } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 0b9fcde9..e148167b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -36,41 +36,6 @@ using MdlMaterialEditor = Penumbra.Mods.Editor.MdlMaterialEditor; namespace Penumbra.UI.AdvancedWindow; -public sealed class OptionSelectCombo(ModEditor editor, ModEditWindow window) - : FilterComboCache<(string FullName, (int Group, int Data) Index)>( - () => window.Mod!.AllDataContainers.Select(c => (c.GetFullName(), c.GetDataIndices())).ToList(), MouseWheelType.Control, Penumbra.Log) -{ - private ImRaii.ColorStyle _border; - - protected override void DrawCombo(string label, string preview, string tooltip, int currentSelected, float previewWidth, float itemHeight, - ImGuiComboFlags flags) - { - _border = ImRaii.PushFrameBorder(ImUtf8.GlobalScale, ColorId.FolderLine.Value()); - base.DrawCombo(label, preview, tooltip, currentSelected, previewWidth, itemHeight, flags); - _border.Dispose(); - } - - protected override void DrawFilter(int currentSelected, float width) - { - _border.Dispose(); - base.DrawFilter(currentSelected, width); - } - - public bool Draw(float width) - { - var flags = window.Mod!.AllDataContainers.Count() switch - { - 0 => ImGuiComboFlags.NoArrowButton, - > 8 => ImGuiComboFlags.HeightLargest, - _ => ImGuiComboFlags.None, - }; - return Draw("##optionSelector", editor.Option!.GetFullName(), string.Empty, width, ImGui.GetTextLineHeight(), flags); - } - - protected override bool DrawSelectable(int globalIdx, bool selected) - => ImUtf8.Selectable(Items[globalIdx].FullName, selected); -} - public partial class ModEditWindow : Window, IDisposable, IUiService { private const string WindowBaseLabel = "###SubModEdit"; diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 8439587c..109cb5c4 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -8,6 +8,7 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.Interop.PathResolving; using Penumbra.Meta; +using Penumbra.Meta.Manipulations; namespace Penumbra.UI.Tabs.Debug; @@ -52,17 +53,11 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Enabled"u8, ImGuiTableColumnFlags.WidthStretch); ImGui.TableHeadersRow(); - foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State) + foreach (var condition in Enum.GetValues()) { - ImGui.TableNextColumn(); - DrawShape(shape, set); - } - - foreach (var (condition, dict) in data.ModCollection.MetaCache!.Shp.ConditionState) - { - foreach (var (shape, set) in dict) + foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State(condition)) { - ImUtf8.DrawTableColumn(condition.AsSpan); + ImUtf8.DrawTableColumn(condition.ToString()); DrawShape(shape, set); } } diff --git a/schemas/structs/meta_enums.json b/schemas/structs/meta_enums.json index 2fc65a0d..bad184e0 100644 --- a/schemas/structs/meta_enums.json +++ b/schemas/structs/meta_enums.json @@ -29,6 +29,10 @@ "$anchor": "SubRace", "enum": [ "Unknown", "Midlander", "Highlander", "Wildwood", "Duskwight", "Plainsfolk", "Dunesfolk", "SeekerOfTheSun", "KeeperOfTheMoon", "Seawolf", "Hellsguard", "Raen", "Xaela", "Helion", "Lost", "Rava", "Veena" ] }, + "ShapeConnectorCondition": { + "$anchor": "ShapeConnectorCondition", + "enum": [ "None", "Wrists", "Waist", "Ankles" ] + }, "U8": { "$anchor": "U8", "oneOf": [ diff --git a/schemas/structs/meta_shp.json b/schemas/structs/meta_shp.json index 4f868a0a..851842a4 100644 --- a/schemas/structs/meta_shp.json +++ b/schemas/structs/meta_shp.json @@ -17,11 +17,8 @@ "maxLength": 30, "pattern": "^shpx_" }, - "ShapeCondition": { - "type": "string", - "minLength": 8, - "maxLength": 30, - "pattern": "^shpx_(wa|an|wr)_" + "ConnectorCondition": { + "$ref": "meta_enums.json#ShapeConnectorCondition" } }, "required": [ From 6e4e28fa00f73d5c937e8cd12553917af79bf798 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 May 2025 16:00:09 +0200 Subject: [PATCH 1212/1381] Fix disabling conditional shapes. --- Penumbra/Collections/Cache/ShpCache.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Penumbra/Collections/Cache/ShpCache.cs b/Penumbra/Collections/Cache/ShpCache.cs index ee6a4e65..2fe7f933 100644 --- a/Penumbra/Collections/Cache/ShpCache.cs +++ b/Penumbra/Collections/Cache/ShpCache.cs @@ -22,10 +22,6 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) public int EnabledCount { get; private set; } - - public bool ShouldBeEnabled(ShapeConnectorCondition connector, in ShapeString shape, HumanSlot slot, PrimaryId id) - => State(connector).TryGetValue(shape, out var value) && value.Contains(slot, id); - public sealed class ShpHashSet : HashSet<(HumanSlot Slot, PrimaryId Id)> { private readonly BitArray _allIds = new(ShapeManager.ModelSlotSize); @@ -148,13 +144,14 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) void Func(Dictionary dict) { - if (!_shpData.TryGetValue(identifier.Shape, out var value)) + if (!dict.TryGetValue(identifier.Shape, out var value)) return; - if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False) && value.IsEmpty) + if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False)) { --EnabledCount; - _shpData.Remove(identifier.Shape); + if (value.IsEmpty) + dict.Remove(identifier.Shape); } } } From e18e4bb0e1fb0dcc450736c100cd3f2867d811aa Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 18 May 2025 14:02:16 +0000 Subject: [PATCH 1213/1381] [CI] Updating repo.json for testing_1.3.6.11 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 137ba00c..c077c355 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.10", + "TestingAssemblyVersion": "1.3.6.11", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.10/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.11/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 47b589540435c8f81826887de33c9827897b7f3d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 18 May 2025 22:00:10 +0200 Subject: [PATCH 1214/1381] Fix issue with temp settings again. --- Penumbra/Mods/Settings/TemporaryModSettings.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Penumbra/Mods/Settings/TemporaryModSettings.cs b/Penumbra/Mods/Settings/TemporaryModSettings.cs index ce438aac..d3e36ef6 100644 --- a/Penumbra/Mods/Settings/TemporaryModSettings.cs +++ b/Penumbra/Mods/Settings/TemporaryModSettings.cs @@ -40,7 +40,6 @@ public sealed class TemporaryModSettings : ModSettings } else { - IsEmpty = true; Enabled = false; Priority = ModPriority.Default; Settings = SettingList.Default(mod); From 68b68d6ce7657d32466ad8a8622f203a43936887 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 19 May 2025 17:15:29 +0200 Subject: [PATCH 1215/1381] Fix some issues with customization IDs and supported counts. --- Penumbra.GameData | 2 +- Penumbra/Meta/Manipulations/ShpIdentifier.cs | 7 +++++++ Penumbra/Meta/ShapeManager.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 10 +++++++--- 4 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 8e57c2e1..b15c0f07 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 8e57c2e12570bb1795efb9e5c6e38617aa8dd5e3 +Subproject commit b15c0f07ba270a7b6a350411006e003da9818d1b diff --git a/Penumbra/Meta/Manipulations/ShpIdentifier.cs b/Penumbra/Meta/Manipulations/ShpIdentifier.cs index b3fdb0cb..3be46d32 100644 --- a/Penumbra/Meta/Manipulations/ShpIdentifier.cs +++ b/Penumbra/Meta/Manipulations/ShpIdentifier.cs @@ -5,6 +5,7 @@ using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.Structs; +using Penumbra.Meta.Files; namespace Penumbra.Meta.Manipulations; @@ -98,6 +99,12 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (Slot is HumanSlot.Unknown && Id is not null) return false; + if (Slot.ToSpecificEnum() is BodySlot && Id is { Id: > byte.MaxValue }) + return false; + + if (Id is { Id: > ExpandedEqpGmpBase.Count - 1 }) + return false; + if (!ValidateCustomShapeString(Shape)) return false; diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs index 7431b1c2..abd4c3b8 100644 --- a/Penumbra/Meta/ShapeManager.cs +++ b/Penumbra/Meta/ShapeManager.cs @@ -70,7 +70,7 @@ public class ShapeManager : IRequiredService, IDisposable if (model is null || model->ModelResourceHandle is null) continue; - _ids[(int)modelIndex] = human.GetArmorChanged(modelIndex).Set; + _ids[(int)modelIndex] = human.GetModelId(modelIndex); ref var shapes = ref model->ModelResourceHandle->Shapes; foreach (var (shape, index) in shapes.Where(kvp => ShpIdentifier.ValidateCustomShapeString(kvp.Key.Value))) diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs index c40726f8..6505ecc0 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -5,6 +5,7 @@ using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; using Penumbra.Meta; using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; @@ -151,9 +152,8 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile } else { - if (IdInput("##shpPrimaryId"u8, unscaledWidth, identifier.Id.GetValueOrDefault(0).Id, out var setId, 0, - ExpandedEqpGmpBase.Count - 1, - false)) + var max = identifier.Slot.ToSpecificEnum() is BodySlot ? byte.MaxValue : ExpandedEqpGmpBase.Count - 1; + if (IdInput("##shpPrimaryId"u8, unscaledWidth, identifier.Id.GetValueOrDefault(0).Id, out var setId, 0, max, false)) { identifier = identifier with { Id = setId }; ret = true; @@ -190,6 +190,10 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile { identifier = identifier with { + Id = identifier.Id.HasValue + ? (PrimaryId)Math.Clamp(identifier.Id.Value.Id, 0, + slot.ToSpecificEnum() is BodySlot ? byte.MaxValue : ExpandedEqpGmpBase.Count - 1) + : null, Slot = slot, ConnectorCondition = Identifier.ConnectorCondition switch { From fefa3852f7755e42e63957d9e5a244af9dc8001a Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 19 May 2025 15:17:54 +0000 Subject: [PATCH 1216/1381] [CI] Updating repo.json for testing_1.3.6.12 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index c077c355..0413b876 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.11", + "TestingAssemblyVersion": "1.3.6.12", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.11/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.12/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 861cbc77590e196a3c1f9fb828aebb3432696ec1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 20 May 2025 17:05:49 +0200 Subject: [PATCH 1217/1381] Add global EQP edits to always hide horns or ears. --- Penumbra/Collections/Cache/GlobalEqpCache.cs | 27 ++++++++++++++++++- .../Manipulations/GlobalEqpManipulation.cs | 12 ++++++--- Penumbra/Meta/Manipulations/GlobalEqpType.cs | 14 +++++++++- schemas/structs/meta_geqp.json | 6 ++--- 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/Penumbra/Collections/Cache/GlobalEqpCache.cs b/Penumbra/Collections/Cache/GlobalEqpCache.cs index 60e782b5..7d2fbf64 100644 --- a/Penumbra/Collections/Cache/GlobalEqpCache.cs +++ b/Penumbra/Collections/Cache/GlobalEqpCache.cs @@ -15,6 +15,9 @@ public class GlobalEqpCache : ReadWriteDictionary, private readonly HashSet _doNotHideRingR = []; private bool _doNotHideVieraHats; private bool _doNotHideHrothgarHats; + private bool _hideAuRaHorns; + private bool _hideVieraEars; + private bool _hideMiqoteEars; public new void Clear() { @@ -26,6 +29,9 @@ public class GlobalEqpCache : ReadWriteDictionary, _doNotHideRingR.Clear(); _doNotHideHrothgarHats = false; _doNotHideVieraHats = false; + _hideAuRaHorns = false; + _hideVieraEars = false; + _hideMiqoteEars = false; } public unsafe EqpEntry Apply(EqpEntry original, CharacterArmor* armor) @@ -39,8 +45,20 @@ public class GlobalEqpCache : ReadWriteDictionary, if (_doNotHideHrothgarHats) original |= EqpEntry.HeadShowHrothgarHat; + if (_hideAuRaHorns) + original &= ~EqpEntry.HeadShowEarAuRa; + + if (_hideVieraEars) + original &= ~EqpEntry.HeadShowEarViera; + + if (_hideMiqoteEars) + original &= ~EqpEntry.HeadShowEarMiqote; + if (_doNotHideEarrings.Contains(armor[5].Set)) - original |= EqpEntry.HeadShowEarringsHyurRoe | EqpEntry.HeadShowEarringsLalaElezen | EqpEntry.HeadShowEarringsMiqoHrothViera | EqpEntry.HeadShowEarringsAura; + original |= EqpEntry.HeadShowEarringsHyurRoe + | EqpEntry.HeadShowEarringsLalaElezen + | EqpEntry.HeadShowEarringsMiqoHrothViera + | EqpEntry.HeadShowEarringsAura; if (_doNotHideNecklace.Contains(armor[6].Set)) original |= EqpEntry.BodyShowNecklace | EqpEntry.HeadShowNecklace; @@ -53,6 +71,7 @@ public class GlobalEqpCache : ReadWriteDictionary, if (_doNotHideRingL.Contains(armor[9].Set)) original |= EqpEntry.HandShowRingL; + return original; } @@ -71,6 +90,9 @@ public class GlobalEqpCache : ReadWriteDictionary, GlobalEqpType.DoNotHideRingL => _doNotHideRingL.Add(manipulation.Condition), GlobalEqpType.DoNotHideHrothgarHats => !_doNotHideHrothgarHats && (_doNotHideHrothgarHats = true), GlobalEqpType.DoNotHideVieraHats => !_doNotHideVieraHats && (_doNotHideVieraHats = true), + GlobalEqpType.HideHorns => !_hideAuRaHorns && (_hideAuRaHorns = true), + GlobalEqpType.HideMiqoteEars => !_hideMiqoteEars && (_hideMiqoteEars = true), + GlobalEqpType.HideVieraEars => !_hideVieraEars && (_hideVieraEars = true), _ => false, }; return true; @@ -90,6 +112,9 @@ public class GlobalEqpCache : ReadWriteDictionary, GlobalEqpType.DoNotHideRingL => _doNotHideRingL.Remove(manipulation.Condition), GlobalEqpType.DoNotHideHrothgarHats => _doNotHideHrothgarHats && !(_doNotHideHrothgarHats = false), GlobalEqpType.DoNotHideVieraHats => _doNotHideVieraHats && !(_doNotHideVieraHats = false), + GlobalEqpType.HideHorns => _hideAuRaHorns && (_hideAuRaHorns = false), + GlobalEqpType.HideMiqoteEars => _hideMiqoteEars && (_hideMiqoteEars = false), + GlobalEqpType.HideVieraEars => _hideVieraEars && (_hideVieraEars = false), _ => false, }; return true; diff --git a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs index 1365d9d3..33399a36 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpManipulation.cs @@ -16,10 +16,10 @@ public readonly struct GlobalEqpManipulation : IMetaIdentifier if (!Enum.IsDefined(Type)) return false; - if (Type is GlobalEqpType.DoNotHideVieraHats or GlobalEqpType.DoNotHideHrothgarHats) - return Condition == 0; + if (Type.HasCondition()) + return Condition.Id is not 0; - return Condition != 0; + return Condition.Id is 0; } public JObject AddToJson(JObject jObj) @@ -89,6 +89,12 @@ public readonly struct GlobalEqpManipulation : IMetaIdentifier changedItems.UpdateCountOrSet("All Hats for Viera", () => new IdentifiedName()); else if (Type is GlobalEqpType.DoNotHideHrothgarHats) changedItems.UpdateCountOrSet("All Hats for Hrothgar", () => new IdentifiedName()); + else if (Type is GlobalEqpType.HideHorns) + changedItems.UpdateCountOrSet("All Au Ra Horns", () => new IdentifiedName()); + else if (Type is GlobalEqpType.HideVieraEars) + changedItems.UpdateCountOrSet("All Viera Ears", () => new IdentifiedName()); + else if (Type is GlobalEqpType.HideMiqoteEars) + changedItems.UpdateCountOrSet("All Miqo'te Ears", () => new IdentifiedName()); } public MetaIndex FileIndex() diff --git a/Penumbra/Meta/Manipulations/GlobalEqpType.cs b/Penumbra/Meta/Manipulations/GlobalEqpType.cs index 1a7396f9..29bfe825 100644 --- a/Penumbra/Meta/Manipulations/GlobalEqpType.cs +++ b/Penumbra/Meta/Manipulations/GlobalEqpType.cs @@ -13,6 +13,9 @@ public enum GlobalEqpType DoNotHideRingL, DoNotHideHrothgarHats, DoNotHideVieraHats, + HideHorns, + HideVieraEars, + HideMiqoteEars, } public static class GlobalEqpExtensions @@ -27,6 +30,9 @@ public static class GlobalEqpExtensions GlobalEqpType.DoNotHideRingL => true, GlobalEqpType.DoNotHideHrothgarHats => false, GlobalEqpType.DoNotHideVieraHats => false, + GlobalEqpType.HideHorns => false, + GlobalEqpType.HideVieraEars => false, + GlobalEqpType.HideMiqoteEars => false, _ => false, }; @@ -41,6 +47,9 @@ public static class GlobalEqpExtensions GlobalEqpType.DoNotHideRingL => "Always Show Rings (Left Finger)"u8, GlobalEqpType.DoNotHideHrothgarHats => "Always Show Hats for Hrothgar"u8, GlobalEqpType.DoNotHideVieraHats => "Always Show Hats for Viera"u8, + GlobalEqpType.HideHorns => "Always Hide Horns (Au Ra)"u8, + GlobalEqpType.HideVieraEars => "Always Hide Ears (Viera)"u8, + GlobalEqpType.HideMiqoteEars => "Always Hide Ears (Miqo'te)"u8, _ => "\0"u8, }; @@ -60,6 +69,9 @@ public static class GlobalEqpExtensions "Prevents the game from hiding any hats for Hrothgar that are normally flagged to not display on them."u8, GlobalEqpType.DoNotHideVieraHats => "Prevents the game from hiding any hats for Viera that are normally flagged to not display on them."u8, - _ => "\0"u8, + GlobalEqpType.HideHorns => "Forces the game to hide Au Ra horns regardless of headwear."u8, + GlobalEqpType.HideVieraEars => "Forces the game to hide Viera ears regardless of headwear."u8, + GlobalEqpType.HideMiqoteEars => "Forces the game to hide Miqo'te ears regardless of headwear."u8, + _ => "\0"u8, }; } diff --git a/schemas/structs/meta_geqp.json b/schemas/structs/meta_geqp.json index 3d4908f9..e38fbb86 100644 --- a/schemas/structs/meta_geqp.json +++ b/schemas/structs/meta_geqp.json @@ -6,7 +6,7 @@ "$ref": "meta_enums.json#U16" }, "Type": { - "enum": [ "DoNotHideEarrings", "DoNotHideNecklace", "DoNotHideBracelets", "DoNotHideRingR", "DoNotHideRingL", "DoNotHideHrothgarHats", "DoNotHideVieraHats" ] + "enum": [ "DoNotHideEarrings", "DoNotHideNecklace", "DoNotHideBracelets", "DoNotHideRingR", "DoNotHideRingL", "DoNotHideHrothgarHats", "DoNotHideVieraHats", "HideHorns", "HideVieraEars", "HideMiqoteEars" ] } }, "required": [ "Type" ], @@ -14,7 +14,7 @@ { "properties": { "Type": { - "const": [ "DoNotHideHrothgarHats", "DoNotHideVieraHats" ] + "const": [ "DoNotHideHrothgarHats", "DoNotHideVieraHats", "HideHorns", "HideVieraEars", "HideMiqoteEars" ] }, "Condition": { "const": 0 @@ -24,7 +24,7 @@ { "properties": { "Type": { - "const": [ "DoNotHideHrothgarHats", "DoNotHideVieraHats" ] + "const": [ "DoNotHideHrothgarHats", "DoNotHideVieraHats", "HideHorns", "HideVieraEars", "HideMiqoteEars" ] } } }, From 3412786282f1aa52fab12c1328faa3bcfec51408 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 21 May 2025 12:03:04 +0200 Subject: [PATCH 1218/1381] Optimize used memory by metadictionarys a bit. --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 445 +++++++++++------- 1 file changed, 263 insertions(+), 182 deletions(-) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index a7225067..51ca09ab 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -11,129 +11,164 @@ namespace Penumbra.Meta.Manipulations; [JsonConverter(typeof(Converter))] public class MetaDictionary { - private readonly Dictionary _imc = []; - private readonly Dictionary _eqp = []; - private readonly Dictionary _eqdp = []; - private readonly Dictionary _est = []; - private readonly Dictionary _rsp = []; - private readonly Dictionary _gmp = []; - private readonly Dictionary _atch = []; - private readonly Dictionary _shp = []; - private readonly HashSet _globalEqp = []; + private class Wrapper : HashSet + { + public readonly Dictionary Imc = []; + public readonly Dictionary Eqp = []; + public readonly Dictionary Eqdp = []; + public readonly Dictionary Est = []; + public readonly Dictionary Rsp = []; + public readonly Dictionary Gmp = []; + public readonly Dictionary Atch = []; + public readonly Dictionary Shp = []; + + public Wrapper() + { } + + public Wrapper(MetaCache cache) + { + Imc = cache.Imc.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + Eqp = cache.Eqp.ToDictionary(kvp => kvp.Key, kvp => new EqpEntryInternal(kvp.Value.Entry, kvp.Key.Slot)); + Eqdp = cache.Eqdp.ToDictionary(kvp => kvp.Key, kvp => new EqdpEntryInternal(kvp.Value.Entry, kvp.Key.Slot)); + Est = cache.Est.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + Gmp = cache.Gmp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + Rsp = cache.Rsp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + Atch = cache.Atch.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + Shp = cache.Shp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + foreach (var geqp in cache.GlobalEqp.Keys) + Add(geqp); + } + } + + private Wrapper? _data; public IReadOnlyDictionary Imc - => _imc; + => _data?.Imc ?? []; public IReadOnlyDictionary Eqp - => _eqp; + => _data?.Eqp ?? []; public IReadOnlyDictionary Eqdp - => _eqdp; + => _data?.Eqdp ?? []; public IReadOnlyDictionary Est - => _est; + => _data?.Est ?? []; public IReadOnlyDictionary Gmp - => _gmp; + => _data?.Gmp ?? []; public IReadOnlyDictionary Rsp - => _rsp; + => _data?.Rsp ?? []; public IReadOnlyDictionary Atch - => _atch; + => _data?.Atch ?? []; public IReadOnlyDictionary Shp - => _shp; + => _data?.Shp ?? []; public IReadOnlySet GlobalEqp - => _globalEqp; + => _data ?? []; public int Count { get; private set; } public int GetCount(MetaManipulationType type) - => type switch - { - MetaManipulationType.Imc => _imc.Count, - MetaManipulationType.Eqdp => _eqdp.Count, - MetaManipulationType.Eqp => _eqp.Count, - MetaManipulationType.Est => _est.Count, - MetaManipulationType.Gmp => _gmp.Count, - MetaManipulationType.Rsp => _rsp.Count, - MetaManipulationType.Atch => _atch.Count, - MetaManipulationType.Shp => _shp.Count, - MetaManipulationType.GlobalEqp => _globalEqp.Count, - _ => 0, - }; + => _data is null + ? 0 + : type switch + { + MetaManipulationType.Imc => _data.Imc.Count, + MetaManipulationType.Eqdp => _data.Eqdp.Count, + MetaManipulationType.Eqp => _data.Eqp.Count, + MetaManipulationType.Est => _data.Est.Count, + MetaManipulationType.Gmp => _data.Gmp.Count, + MetaManipulationType.Rsp => _data.Rsp.Count, + MetaManipulationType.Atch => _data.Atch.Count, + MetaManipulationType.Shp => _data.Shp.Count, + MetaManipulationType.GlobalEqp => _data.Count, + _ => 0, + }; public bool Contains(IMetaIdentifier identifier) - => identifier switch - { - EqdpIdentifier i => _eqdp.ContainsKey(i), - EqpIdentifier i => _eqp.ContainsKey(i), - EstIdentifier i => _est.ContainsKey(i), - GlobalEqpManipulation i => _globalEqp.Contains(i), - GmpIdentifier i => _gmp.ContainsKey(i), - ImcIdentifier i => _imc.ContainsKey(i), - AtchIdentifier i => _atch.ContainsKey(i), - ShpIdentifier i => _shp.ContainsKey(i), - RspIdentifier i => _rsp.ContainsKey(i), - _ => false, - }; + => _data is not null + && identifier switch + { + EqdpIdentifier i => _data.Eqdp.ContainsKey(i), + EqpIdentifier i => _data.Eqp.ContainsKey(i), + EstIdentifier i => _data.Est.ContainsKey(i), + GlobalEqpManipulation i => _data.Contains(i), + GmpIdentifier i => _data.Gmp.ContainsKey(i), + ImcIdentifier i => _data.Imc.ContainsKey(i), + AtchIdentifier i => _data.Atch.ContainsKey(i), + ShpIdentifier i => _data.Shp.ContainsKey(i), + RspIdentifier i => _data.Rsp.ContainsKey(i), + _ => false, + }; public void Clear() { + _data = null; Count = 0; - _imc.Clear(); - _eqp.Clear(); - _eqdp.Clear(); - _est.Clear(); - _rsp.Clear(); - _gmp.Clear(); - _atch.Clear(); - _shp.Clear(); - _globalEqp.Clear(); } public void ClearForDefault() { - Count = _globalEqp.Count; - _imc.Clear(); - _eqp.Clear(); - _eqdp.Clear(); - _est.Clear(); - _rsp.Clear(); - _gmp.Clear(); - _atch.Clear(); + if (_data is null) + return; + + if (_data.Count is 0 && Shp.Count is 0) + { + _data = null; + Count = 0; + } + + Count = GlobalEqp.Count + Shp.Count; + _data!.Imc.Clear(); + _data!.Eqp.Clear(); + _data!.Eqdp.Clear(); + _data!.Est.Clear(); + _data!.Rsp.Clear(); + _data!.Gmp.Clear(); + _data!.Atch.Clear(); } public bool Equals(MetaDictionary other) - => Count == other.Count - && _imc.SetEquals(other._imc) - && _eqp.SetEquals(other._eqp) - && _eqdp.SetEquals(other._eqdp) - && _est.SetEquals(other._est) - && _rsp.SetEquals(other._rsp) - && _gmp.SetEquals(other._gmp) - && _atch.SetEquals(other._atch) - && _shp.SetEquals(other._shp) - && _globalEqp.SetEquals(other._globalEqp); + { + if (Count != other.Count) + return false; + + if (_data is null) + return true; + + return _data.Imc.SetEquals(other._data!.Imc) + && _data.Eqp.SetEquals(other._data!.Eqp) + && _data.Eqdp.SetEquals(other._data!.Eqdp) + && _data.Est.SetEquals(other._data!.Est) + && _data.Rsp.SetEquals(other._data!.Rsp) + && _data.Gmp.SetEquals(other._data!.Gmp) + && _data.Atch.SetEquals(other._data!.Atch) + && _data.Shp.SetEquals(other._data!.Shp) + && _data.SetEquals(other._data!); + } public IEnumerable Identifiers - => _imc.Keys.Cast() - .Concat(_eqdp.Keys.Cast()) - .Concat(_eqp.Keys.Cast()) - .Concat(_est.Keys.Cast()) - .Concat(_gmp.Keys.Cast()) - .Concat(_rsp.Keys.Cast()) - .Concat(_atch.Keys.Cast()) - .Concat(_shp.Keys.Cast()) - .Concat(_globalEqp.Cast()); + => _data is null + ? [] + : _data.Imc.Keys.Cast() + .Concat(_data!.Eqdp.Keys.Cast()) + .Concat(_data!.Eqp.Keys.Cast()) + .Concat(_data!.Est.Keys.Cast()) + .Concat(_data!.Gmp.Keys.Cast()) + .Concat(_data!.Rsp.Keys.Cast()) + .Concat(_data!.Atch.Keys.Cast()) + .Concat(_data!.Shp.Keys.Cast()) + .Concat(_data!.Cast()); #region TryAdd public bool TryAdd(ImcIdentifier identifier, ImcEntry entry) { - if (!_imc.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Imc.TryAdd(identifier, entry)) return false; ++Count; @@ -142,7 +177,8 @@ public class MetaDictionary public bool TryAdd(EqpIdentifier identifier, EqpEntryInternal entry) { - if (!_eqp.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Eqp.TryAdd(identifier, entry)) return false; ++Count; @@ -154,7 +190,8 @@ public class MetaDictionary public bool TryAdd(EqdpIdentifier identifier, EqdpEntryInternal entry) { - if (!_eqdp.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Eqdp.TryAdd(identifier, entry)) return false; ++Count; @@ -166,7 +203,8 @@ public class MetaDictionary public bool TryAdd(EstIdentifier identifier, EstEntry entry) { - if (!_est.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Est.TryAdd(identifier, entry)) return false; ++Count; @@ -175,7 +213,8 @@ public class MetaDictionary public bool TryAdd(GmpIdentifier identifier, GmpEntry entry) { - if (!_gmp.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Gmp.TryAdd(identifier, entry)) return false; ++Count; @@ -184,7 +223,8 @@ public class MetaDictionary public bool TryAdd(RspIdentifier identifier, RspEntry entry) { - if (!_rsp.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Rsp.TryAdd(identifier, entry)) return false; ++Count; @@ -193,7 +233,8 @@ public class MetaDictionary public bool TryAdd(AtchIdentifier identifier, in AtchEntry entry) { - if (!_atch.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Atch.TryAdd(identifier, entry)) return false; ++Count; @@ -202,7 +243,8 @@ public class MetaDictionary public bool TryAdd(ShpIdentifier identifier, in ShpEntry entry) { - if (!_shp.TryAdd(identifier, entry)) + _data ??= []; + if (!_data!.Shp.TryAdd(identifier, entry)) return false; ++Count; @@ -211,7 +253,8 @@ public class MetaDictionary public bool TryAdd(GlobalEqpManipulation identifier) { - if (!_globalEqp.Add(identifier)) + _data ??= []; + if (!_data.Add(identifier)) return false; ++Count; @@ -224,19 +267,19 @@ public class MetaDictionary public bool Update(ImcIdentifier identifier, ImcEntry entry) { - if (!_imc.ContainsKey(identifier)) + if (_data is null || !_data.Imc.ContainsKey(identifier)) return false; - _imc[identifier] = entry; + _data.Imc[identifier] = entry; return true; } public bool Update(EqpIdentifier identifier, EqpEntryInternal entry) { - if (!_eqp.ContainsKey(identifier)) + if (_data is null || !_data.Eqp.ContainsKey(identifier)) return false; - _eqp[identifier] = entry; + _data.Eqp[identifier] = entry; return true; } @@ -245,10 +288,10 @@ public class MetaDictionary public bool Update(EqdpIdentifier identifier, EqdpEntryInternal entry) { - if (!_eqdp.ContainsKey(identifier)) + if (_data is null || !_data.Eqdp.ContainsKey(identifier)) return false; - _eqdp[identifier] = entry; + _data.Eqdp[identifier] = entry; return true; } @@ -257,46 +300,46 @@ public class MetaDictionary public bool Update(EstIdentifier identifier, EstEntry entry) { - if (!_est.ContainsKey(identifier)) + if (_data is null || !_data.Est.ContainsKey(identifier)) return false; - _est[identifier] = entry; + _data.Est[identifier] = entry; return true; } public bool Update(GmpIdentifier identifier, GmpEntry entry) { - if (!_gmp.ContainsKey(identifier)) + if (_data is null || !_data.Gmp.ContainsKey(identifier)) return false; - _gmp[identifier] = entry; + _data.Gmp[identifier] = entry; return true; } public bool Update(RspIdentifier identifier, RspEntry entry) { - if (!_rsp.ContainsKey(identifier)) + if (_data is null || !_data.Rsp.ContainsKey(identifier)) return false; - _rsp[identifier] = entry; + _data.Rsp[identifier] = entry; return true; } public bool Update(AtchIdentifier identifier, in AtchEntry entry) { - if (!_atch.ContainsKey(identifier)) + if (_data is null || !_data.Atch.ContainsKey(identifier)) return false; - _atch[identifier] = entry; + _data.Atch[identifier] = entry; return true; } public bool Update(ShpIdentifier identifier, in ShpEntry entry) { - if (!_shp.ContainsKey(identifier)) + if (_data is null || !_data.Shp.ContainsKey(identifier)) return false; - _shp[identifier] = entry; + _data.Shp[identifier] = entry; return true; } @@ -305,48 +348,59 @@ public class MetaDictionary #region TryGetValue public bool TryGetValue(EstIdentifier identifier, out EstEntry value) - => _est.TryGetValue(identifier, out value); + => _data?.Est.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(EqpIdentifier identifier, out EqpEntryInternal value) - => _eqp.TryGetValue(identifier, out value); + => _data?.Eqp.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(EqdpIdentifier identifier, out EqdpEntryInternal value) - => _eqdp.TryGetValue(identifier, out value); + => _data?.Eqdp.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(GmpIdentifier identifier, out GmpEntry value) - => _gmp.TryGetValue(identifier, out value); + => _data?.Gmp.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(RspIdentifier identifier, out RspEntry value) - => _rsp.TryGetValue(identifier, out value); + => _data?.Rsp.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(ImcIdentifier identifier, out ImcEntry value) - => _imc.TryGetValue(identifier, out value); + => _data?.Imc.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(AtchIdentifier identifier, out AtchEntry value) - => _atch.TryGetValue(identifier, out value); + => _data?.Atch.TryGetValue(identifier, out value) ?? SetDefault(out value); public bool TryGetValue(ShpIdentifier identifier, out ShpEntry value) - => _shp.TryGetValue(identifier, out value); + => _data?.Shp.TryGetValue(identifier, out value) ?? SetDefault(out value); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool SetDefault(out T? value) + { + value = default; + return false; + } #endregion public bool Remove(IMetaIdentifier identifier) { + if (_data is null) + return false; + var ret = identifier switch { - EqdpIdentifier i => _eqdp.Remove(i), - EqpIdentifier i => _eqp.Remove(i), - EstIdentifier i => _est.Remove(i), - GlobalEqpManipulation i => _globalEqp.Remove(i), - GmpIdentifier i => _gmp.Remove(i), - ImcIdentifier i => _imc.Remove(i), - RspIdentifier i => _rsp.Remove(i), - AtchIdentifier i => _atch.Remove(i), - ShpIdentifier i => _shp.Remove(i), + EqdpIdentifier i => _data.Eqdp.Remove(i), + EqpIdentifier i => _data.Eqp.Remove(i), + EstIdentifier i => _data.Est.Remove(i), + GlobalEqpManipulation i => _data.Remove(i), + GmpIdentifier i => _data.Gmp.Remove(i), + ImcIdentifier i => _data.Imc.Remove(i), + RspIdentifier i => _data.Rsp.Remove(i), + AtchIdentifier i => _data.Atch.Remove(i), + ShpIdentifier i => _data.Shp.Remove(i), _ => false, }; - if (ret) - --Count; + if (ret && --Count is 0) + _data = null; + return ret; } @@ -354,86 +408,97 @@ public class MetaDictionary public void UnionWith(MetaDictionary manips) { - foreach (var (identifier, entry) in manips._imc) + if (manips.Count is 0) + return; + + _data ??= []; + foreach (var (identifier, entry) in manips._data!.Imc) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._eqp) + foreach (var (identifier, entry) in manips._data!.Eqp) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._eqdp) + foreach (var (identifier, entry) in manips._data!.Eqdp) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._gmp) + foreach (var (identifier, entry) in manips._data!.Gmp) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._rsp) + foreach (var (identifier, entry) in manips._data!.Rsp) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._est) + foreach (var (identifier, entry) in manips._data!.Est) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._atch) + foreach (var (identifier, entry) in manips._data!.Atch) TryAdd(identifier, entry); - foreach (var (identifier, entry) in manips._shp) + foreach (var (identifier, entry) in manips._data!.Shp) TryAdd(identifier, entry); - foreach (var identifier in manips._globalEqp) + foreach (var identifier in manips._data!) TryAdd(identifier); } /// Try to merge all manipulations from manips into this, and return the first failure, if any. public bool MergeForced(MetaDictionary manips, out IMetaIdentifier? failedIdentifier) { - foreach (var (identifier, _) in manips._imc.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + if (manips.Count is 0) + { + failedIdentifier = null; + return true; + } + + _data ??= []; + foreach (var (identifier, _) in manips._data!.Imc.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._eqp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Eqp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._eqdp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Eqdp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._gmp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Gmp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._rsp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Rsp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._est.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Est.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._atch.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Atch.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var (identifier, _) in manips._shp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + foreach (var (identifier, _) in manips._data!.Shp.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) { failedIdentifier = identifier; return false; } - foreach (var identifier in manips._globalEqp.Where(identifier => !TryAdd(identifier))) + foreach (var identifier in manips._data!.Where(identifier => !TryAdd(identifier))) { failedIdentifier = identifier; return false; @@ -445,30 +510,50 @@ public class MetaDictionary public void SetTo(MetaDictionary other) { - _imc.SetTo(other._imc); - _eqp.SetTo(other._eqp); - _eqdp.SetTo(other._eqdp); - _est.SetTo(other._est); - _rsp.SetTo(other._rsp); - _gmp.SetTo(other._gmp); - _atch.SetTo(other._atch); - _shp.SetTo(other._shp); - _globalEqp.SetTo(other._globalEqp); - Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _shp.Count + _globalEqp.Count; + if (other.Count is 0) + { + _data = null; + Count = 0; + return; + } + + _data ??= []; + _data!.Imc.SetTo(other._data!.Imc); + _data!.Eqp.SetTo(other._data!.Eqp); + _data!.Eqdp.SetTo(other._data!.Eqdp); + _data!.Est.SetTo(other._data!.Est); + _data!.Rsp.SetTo(other._data!.Rsp); + _data!.Gmp.SetTo(other._data!.Gmp); + _data!.Atch.SetTo(other._data!.Atch); + _data!.Shp.SetTo(other._data!.Shp); + _data!.SetTo(other._data!); + Count = other.Count; } public void UpdateTo(MetaDictionary other) { - _imc.UpdateTo(other._imc); - _eqp.UpdateTo(other._eqp); - _eqdp.UpdateTo(other._eqdp); - _est.UpdateTo(other._est); - _rsp.UpdateTo(other._rsp); - _gmp.UpdateTo(other._gmp); - _atch.UpdateTo(other._atch); - _shp.UpdateTo(other._shp); - _globalEqp.UnionWith(other._globalEqp); - Count = _imc.Count + _eqp.Count + _eqdp.Count + _est.Count + _rsp.Count + _gmp.Count + _atch.Count + _shp.Count + _globalEqp.Count; + if (other.Count is 0) + return; + + _data ??= []; + _data!.Imc.UpdateTo(other._data!.Imc); + _data!.Eqp.UpdateTo(other._data!.Eqp); + _data!.Eqdp.UpdateTo(other._data!.Eqdp); + _data!.Est.UpdateTo(other._data!.Est); + _data!.Rsp.UpdateTo(other._data!.Rsp); + _data!.Gmp.UpdateTo(other._data!.Gmp); + _data!.Atch.UpdateTo(other._data!.Atch); + _data!.Shp.UpdateTo(other._data!.Shp); + _data!.UnionWith(other._data!); + Count = _data!.Imc.Count + + _data!.Eqp.Count + + _data!.Eqdp.Count + + _data!.Est.Count + + _data!.Rsp.Count + + _data!.Gmp.Count + + _data!.Atch.Count + + _data!.Shp.Count + + _data!.Count; } #endregion @@ -635,15 +720,19 @@ public class MetaDictionary } var array = new JArray(); - SerializeTo(array, value._imc); - SerializeTo(array, value._eqp); - SerializeTo(array, value._eqdp); - SerializeTo(array, value._est); - SerializeTo(array, value._rsp); - SerializeTo(array, value._gmp); - SerializeTo(array, value._atch); - SerializeTo(array, value._shp); - SerializeTo(array, value._globalEqp); + if (value._data is not null) + { + SerializeTo(array, value._data!.Imc); + SerializeTo(array, value._data!.Eqp); + SerializeTo(array, value._data!.Eqdp); + SerializeTo(array, value._data!.Est); + SerializeTo(array, value._data!.Rsp); + SerializeTo(array, value._data!.Gmp); + SerializeTo(array, value._data!.Atch); + SerializeTo(array, value._data!.Shp); + SerializeTo(array, value._data!); + } + array.WriteTo(writer); } @@ -771,18 +860,10 @@ public class MetaDictionary public MetaDictionary(MetaCache? cache) { - if (cache == null) + if (cache is null) return; - _imc = cache.Imc.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); - _eqp = cache.Eqp.ToDictionary(kvp => kvp.Key, kvp => new EqpEntryInternal(kvp.Value.Entry, kvp.Key.Slot)); - _eqdp = cache.Eqdp.ToDictionary(kvp => kvp.Key, kvp => new EqdpEntryInternal(kvp.Value.Entry, kvp.Key.Slot)); - _est = cache.Est.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); - _gmp = cache.Gmp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); - _rsp = cache.Rsp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); - _atch = cache.Atch.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); - _shp = cache.Shp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); - _globalEqp = cache.GlobalEqp.Select(kvp => kvp.Key).ToHashSet(); - Count = cache.Count; + _data = new Wrapper(cache); + Count = cache.Count; } } From d7dee39fab37fcedf047b4fb2829f034526bf63d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 21 May 2025 15:44:26 +0200 Subject: [PATCH 1219/1381] Add attribute handling, rework atr and shape caches. --- Penumbra.GameData | 2 +- Penumbra.sln | 1 + Penumbra/Collections/Cache/AtrCache.cs | 56 ++++ Penumbra/Collections/Cache/CollectionCache.cs | 2 + Penumbra/Collections/Cache/MetaCache.cs | 9 +- .../Cache/ShapeAttributeHashSet.cs | 123 ++++++++ Penumbra/Collections/Cache/ShpCache.cs | 85 +----- .../Hooks/PostProcessing/AttributeHook.cs | 4 +- Penumbra/Meta/Manipulations/AtrIdentifier.cs | 145 +++++++++ .../Meta/Manipulations/IMetaIdentifier.cs | 1 + Penumbra/Meta/Manipulations/MetaDictionary.cs | 70 ++++- Penumbra/Meta/Manipulations/ShpIdentifier.cs | 73 ++--- Penumbra/Meta/ShapeAttributeManager.cs | 153 ++++++++++ ...ShapeString.cs => ShapeAttributeString.cs} | 95 +++++- Penumbra/Meta/ShapeManager.cs | 140 --------- .../UI/AdvancedWindow/Meta/AtrMetaDrawer.cs | 274 ++++++++++++++++++ .../UI/AdvancedWindow/Meta/MetaDrawers.cs | 5 +- .../UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 74 ++++- .../UI/AdvancedWindow/ModEditWindow.Meta.cs | 1 + Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 132 ++++++++- schemas/structs/manipulation.json | 12 +- schemas/structs/meta_atr.json | 27 ++ schemas/structs/meta_shp.json | 3 + 23 files changed, 1187 insertions(+), 300 deletions(-) create mode 100644 Penumbra/Collections/Cache/AtrCache.cs create mode 100644 Penumbra/Collections/Cache/ShapeAttributeHashSet.cs create mode 100644 Penumbra/Meta/Manipulations/AtrIdentifier.cs create mode 100644 Penumbra/Meta/ShapeAttributeManager.cs rename Penumbra/Meta/{ShapeString.cs => ShapeAttributeString.cs} (55%) delete mode 100644 Penumbra/Meta/ShapeManager.cs create mode 100644 Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs create mode 100644 schemas/structs/meta_atr.json diff --git a/Penumbra.GameData b/Penumbra.GameData index b15c0f07..bb3b462b 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit b15c0f07ba270a7b6a350411006e003da9818d1b +Subproject commit bb3b462bbc5bc2a598c1ad8c372b0cb255551fe1 diff --git a/Penumbra.sln b/Penumbra.sln index 642876ef..fbcd6080 100644 --- a/Penumbra.sln +++ b/Penumbra.sln @@ -42,6 +42,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "structs", "structs", "{B03F schemas\structs\group_single.json = schemas\structs\group_single.json schemas\structs\manipulation.json = schemas\structs\manipulation.json schemas\structs\meta_atch.json = schemas\structs\meta_atch.json + schemas\structs\meta_atr.json = schemas\structs\meta_atr.json schemas\structs\meta_enums.json = schemas\structs\meta_enums.json schemas\structs\meta_eqdp.json = schemas\structs\meta_eqdp.json schemas\structs\meta_eqp.json = schemas\structs\meta_eqp.json diff --git a/Penumbra/Collections/Cache/AtrCache.cs b/Penumbra/Collections/Cache/AtrCache.cs new file mode 100644 index 00000000..757ddaa2 --- /dev/null +++ b/Penumbra/Collections/Cache/AtrCache.cs @@ -0,0 +1,56 @@ +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Collections.Cache; + +public sealed class AtrCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) +{ + public bool ShouldBeDisabled(in ShapeAttributeString attribute, HumanSlot slot, PrimaryId id, GenderRace genderRace) + => DisabledCount > 0 && _atrData.TryGetValue(attribute, out var value) && value.Contains(slot, id, genderRace); + + public int DisabledCount { get; private set; } + + internal IReadOnlyDictionary Data + => _atrData; + + private readonly Dictionary _atrData = []; + + public void Reset() + { + Clear(); + _atrData.Clear(); + } + + protected override void Dispose(bool _) + => Clear(); + + protected override void ApplyModInternal(AtrIdentifier identifier, AtrEntry entry) + { + if (!_atrData.TryGetValue(identifier.Attribute, out var value)) + { + if (entry.Value) + return; + + value = []; + _atrData.Add(identifier.Attribute, value); + } + + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, !entry.Value)) + ++DisabledCount; + } + + protected override void RevertModInternal(AtrIdentifier identifier) + { + if (!_atrData.TryGetValue(identifier.Attribute, out var value)) + return; + + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, false)) + { + --DisabledCount; + if (value.IsEmpty) + _atrData.Remove(identifier.Attribute); + } + } +} diff --git a/Penumbra/Collections/Cache/CollectionCache.cs b/Penumbra/Collections/Cache/CollectionCache.cs index c48a487c..8294624b 100644 --- a/Penumbra/Collections/Cache/CollectionCache.cs +++ b/Penumbra/Collections/Cache/CollectionCache.cs @@ -247,6 +247,8 @@ public sealed class CollectionCache : IDisposable AddManipulation(mod, identifier, entry); foreach (var (identifier, entry) in files.Manipulations.Shp) AddManipulation(mod, identifier, entry); + foreach (var (identifier, entry) in files.Manipulations.Atr) + AddManipulation(mod, identifier, entry); foreach (var identifier in files.Manipulations.GlobalEqp) AddManipulation(mod, identifier, null!); } diff --git a/Penumbra/Collections/Cache/MetaCache.cs b/Penumbra/Collections/Cache/MetaCache.cs index 790dd3af..011cdd23 100644 --- a/Penumbra/Collections/Cache/MetaCache.cs +++ b/Penumbra/Collections/Cache/MetaCache.cs @@ -17,11 +17,12 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) public readonly ImcCache Imc = new(manager, collection); public readonly AtchCache Atch = new(manager, collection); public readonly ShpCache Shp = new(manager, collection); + public readonly AtrCache Atr = new(manager, collection); public readonly GlobalEqpCache GlobalEqp = new(); public bool IsDisposed { get; private set; } public int Count - => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + Atch.Count + Shp.Count + GlobalEqp.Count; + => Eqp.Count + Eqdp.Count + Est.Count + Gmp.Count + Rsp.Count + Imc.Count + Atch.Count + Shp.Count + Atr.Count + GlobalEqp.Count; public IEnumerable<(IMetaIdentifier, IMod)> IdentifierSources => Eqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source)) @@ -32,6 +33,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) .Concat(Imc.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(Atch.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(Shp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) + .Concat(Atr.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value.Source))) .Concat(GlobalEqp.Select(kvp => ((IMetaIdentifier)kvp.Key, kvp.Value))); public void Reset() @@ -44,6 +46,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Imc.Reset(); Atch.Reset(); Shp.Reset(); + Atr.Reset(); GlobalEqp.Clear(); } @@ -61,6 +64,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) Imc.Dispose(); Atch.Dispose(); Shp.Dispose(); + Atr.Dispose(); } public bool TryGetMod(IMetaIdentifier identifier, [NotNullWhen(true)] out IMod? mod) @@ -76,6 +80,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) RspIdentifier i => Rsp.TryGetValue(i, out var p) && Convert(p, out mod), AtchIdentifier i => Atch.TryGetValue(i, out var p) && Convert(p, out mod), ShpIdentifier i => Shp.TryGetValue(i, out var p) && Convert(p, out mod), + AtrIdentifier i => Atr.TryGetValue(i, out var p) && Convert(p, out mod), GlobalEqpManipulation i => GlobalEqp.TryGetValue(i, out mod), _ => false, }; @@ -98,6 +103,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) RspIdentifier i => Rsp.RevertMod(i, out mod), AtchIdentifier i => Atch.RevertMod(i, out mod), ShpIdentifier i => Shp.RevertMod(i, out mod), + AtrIdentifier i => Atr.RevertMod(i, out mod), GlobalEqpManipulation i => GlobalEqp.RevertMod(i, out mod), _ => (mod = null) != null, }; @@ -115,6 +121,7 @@ public class MetaCache(MetaFileManager manager, ModCollection collection) RspIdentifier i when entry is RspEntry e => Rsp.ApplyMod(mod, i, e), AtchIdentifier i when entry is AtchEntry e => Atch.ApplyMod(mod, i, e), ShpIdentifier i when entry is ShpEntry e => Shp.ApplyMod(mod, i, e), + AtrIdentifier i when entry is AtrEntry e => Atr.ApplyMod(mod, i, e), GlobalEqpManipulation i => GlobalEqp.ApplyMod(mod, i), _ => false, }; diff --git a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs new file mode 100644 index 00000000..f1fc7127 --- /dev/null +++ b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs @@ -0,0 +1,123 @@ +using System.Collections.Frozen; +using OtterGui.Extensions; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; + +namespace Penumbra.Collections.Cache; + +public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryId Id), ulong> +{ + public static readonly IReadOnlyList GenderRaceValues = + [ + GenderRace.Unknown, GenderRace.MidlanderMale, GenderRace.MidlanderFemale, GenderRace.HighlanderMale, GenderRace.HighlanderFemale, + GenderRace.ElezenMale, GenderRace.ElezenFemale, GenderRace.MiqoteMale, GenderRace.MiqoteFemale, GenderRace.RoegadynMale, + GenderRace.RoegadynFemale, GenderRace.LalafellMale, GenderRace.LalafellFemale, GenderRace.AuRaMale, GenderRace.AuRaFemale, + GenderRace.HrothgarMale, GenderRace.HrothgarFemale, GenderRace.VieraMale, GenderRace.VieraFemale, + ]; + + public static readonly FrozenDictionary GenderRaceIndices = + GenderRaceValues.WithIndex().ToFrozenDictionary(p => p.Value, p => p.Index); + + private readonly BitArray _allIds = new((ShapeAttributeManager.ModelSlotSize + 1) * GenderRaceValues.Count); + + public bool this[HumanSlot slot] + => slot is HumanSlot.Unknown ? All : _allIds[(int)slot * GenderRaceIndices.Count]; + + public bool this[GenderRace genderRace] + => GenderRaceIndices.TryGetValue(genderRace, out var index) + && _allIds[ShapeAttributeManager.ModelSlotSize * GenderRaceIndices.Count + index]; + + public bool this[HumanSlot slot, GenderRace genderRace] + { + get + { + if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) + return false; + + if (_allIds[ShapeAttributeManager.ModelSlotSize * GenderRaceIndices.Count + index]) + return true; + + return _allIds[(int)slot * GenderRaceIndices.Count + index]; + } + set + { + if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) + return; + + var genderRaceCount = GenderRaceValues.Count; + if (slot is HumanSlot.Unknown) + _allIds[ShapeAttributeManager.ModelSlotSize * genderRaceCount + index] = value; + else + _allIds[(int)slot * genderRaceCount + index] = value; + } + } + + public bool All + => _allIds[ShapeAttributeManager.ModelSlotSize * GenderRaceIndices.Count]; + + public bool Contains(HumanSlot slot, PrimaryId id, GenderRace genderRace) + => All || this[slot, genderRace] || ContainsEntry(slot, id, genderRace); + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private bool ContainsEntry(HumanSlot slot, PrimaryId id, GenderRace genderRace) + => GenderRaceIndices.TryGetValue(genderRace, out var index) + && TryGetValue((slot, id), out var flags) + && (flags & (1ul << index)) is not 0; + + public bool TrySet(HumanSlot slot, PrimaryId? id, GenderRace genderRace, bool value) + { + if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) + return false; + + if (!id.HasValue) + { + var slotIndex = slot is HumanSlot.Unknown ? ShapeAttributeManager.ModelSlotSize : (int)slot; + var old = _allIds[slotIndex * GenderRaceIndices.Count + index]; + _allIds[slotIndex * GenderRaceIndices.Count + index] = value; + return old != value; + } + + if (value) + { + if (TryGetValue((slot, id.Value), out var flags)) + { + var newFlags = flags | (1ul << index); + if (newFlags == flags) + return false; + + this[(slot, id.Value)] = newFlags; + return true; + } + + this[(slot, id.Value)] = 1ul << index; + return true; + } + else if (TryGetValue((slot, id.Value), out var flags)) + { + var newFlags = flags & ~(1ul << index); + if (newFlags == flags) + return false; + + if (newFlags is 0) + { + Remove((slot, id.Value)); + return true; + } + + this[(slot, id.Value)] = newFlags; + return true; + } + + return false; + } + + public new void Clear() + { + base.Clear(); + _allIds.SetAll(false); + } + + public bool IsEmpty + => !_allIds.HasAnySet() && Count is 0; +} diff --git a/Penumbra/Collections/Cache/ShpCache.cs b/Penumbra/Collections/Cache/ShpCache.cs index 2fe7f933..22547d25 100644 --- a/Penumbra/Collections/Cache/ShpCache.cs +++ b/Penumbra/Collections/Cache/ShpCache.cs @@ -7,10 +7,10 @@ namespace Penumbra.Collections.Cache; public sealed class ShpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { - public bool ShouldBeEnabled(in ShapeString shape, HumanSlot slot, PrimaryId id) - => EnabledCount > 0 && _shpData.TryGetValue(shape, out var value) && value.Contains(slot, id); + public bool ShouldBeEnabled(in ShapeAttributeString shape, HumanSlot slot, PrimaryId id, GenderRace genderRace) + => EnabledCount > 0 && _shpData.TryGetValue(shape, out var value) && value.Contains(slot, id, genderRace); - internal IReadOnlyDictionary State(ShapeConnectorCondition connector) + internal IReadOnlyDictionary State(ShapeConnectorCondition connector) => connector switch { ShapeConnectorCondition.None => _shpData, @@ -22,73 +22,10 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) public int EnabledCount { get; private set; } - public sealed class ShpHashSet : HashSet<(HumanSlot Slot, PrimaryId Id)> - { - private readonly BitArray _allIds = new(ShapeManager.ModelSlotSize); - - public bool All - { - get => _allIds[^1]; - set => _allIds[^1] = value; - } - - public bool this[HumanSlot slot] - { - get - { - if (slot is HumanSlot.Unknown) - return All; - - return _allIds[(int)slot]; - } - set - { - if (slot is HumanSlot.Unknown) - _allIds[^1] = value; - else - _allIds[(int)slot] = value; - } - } - - public bool Contains(HumanSlot slot, PrimaryId id) - => All || this[slot] || Contains((slot, id)); - - public bool TrySet(HumanSlot slot, PrimaryId? id, ShpEntry value) - { - if (slot is HumanSlot.Unknown) - { - var old = All; - All = value.Value; - return old != value.Value; - } - - if (!id.HasValue) - { - var old = this[slot]; - this[slot] = value.Value; - return old != value.Value; - } - - if (value.Value) - return Add((slot, id.Value)); - - return Remove((slot, id.Value)); - } - - public new void Clear() - { - base.Clear(); - _allIds.SetAll(false); - } - - public bool IsEmpty - => !_allIds.HasAnySet() && Count is 0; - } - - private readonly Dictionary _shpData = []; - private readonly Dictionary _wristConnectors = []; - private readonly Dictionary _waistConnectors = []; - private readonly Dictionary _ankleConnectors = []; + private readonly Dictionary _shpData = []; + private readonly Dictionary _wristConnectors = []; + private readonly Dictionary _waistConnectors = []; + private readonly Dictionary _ankleConnectors = []; public void Reset() { @@ -114,7 +51,7 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) return; - void Func(Dictionary dict) + void Func(Dictionary dict) { if (!dict.TryGetValue(identifier.Shape, out var value)) { @@ -125,7 +62,7 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) dict.Add(identifier.Shape, value); } - if (value.TrySet(identifier.Slot, identifier.Id, entry)) + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, entry.Value)) ++EnabledCount; } } @@ -142,12 +79,12 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) return; - void Func(Dictionary dict) + void Func(Dictionary dict) { if (!dict.TryGetValue(identifier.Shape, out var value)) return; - if (value.TrySet(identifier.Slot, identifier.Id, ShpEntry.False)) + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, false)) { --EnabledCount; if (value.IsEmpty) diff --git a/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs b/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs index cad049ad..00e5851f 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/AttributeHook.cs @@ -22,8 +22,8 @@ public sealed unsafe class AttributeHook : EventWrapper - ShapeManager = 0, + /// + ShapeAttributeManager = 0, } private readonly CollectionResolver _resolver; diff --git a/Penumbra/Meta/Manipulations/AtrIdentifier.cs b/Penumbra/Meta/Manipulations/AtrIdentifier.cs new file mode 100644 index 00000000..ca65f6aa --- /dev/null +++ b/Penumbra/Meta/Manipulations/AtrIdentifier.cs @@ -0,0 +1,145 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Penumbra.Collections.Cache; +using Penumbra.GameData.Data; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Structs; +using Penumbra.Meta.Files; + +namespace Penumbra.Meta.Manipulations; + +public readonly record struct AtrIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeAttributeString Attribute, GenderRace GenderRaceCondition) + : IComparable, IMetaIdentifier +{ + public int CompareTo(AtrIdentifier other) + { + var slotComparison = Slot.CompareTo(other.Slot); + if (slotComparison is not 0) + return slotComparison; + + if (Id.HasValue) + { + if (other.Id.HasValue) + { + var idComparison = Id.Value.Id.CompareTo(other.Id.Value.Id); + if (idComparison is not 0) + return idComparison; + } + else + { + return -1; + } + } + else if (other.Id.HasValue) + { + return 1; + } + + var genderRaceComparison = GenderRaceCondition.CompareTo(other.GenderRaceCondition); + if (genderRaceComparison is not 0) + return genderRaceComparison; + + return Attribute.CompareTo(other.Attribute); + } + + + public override string ToString() + { + var sb = new StringBuilder(64); + sb.Append("Shp - ") + .Append(Attribute); + if (Slot is HumanSlot.Unknown) + { + sb.Append(" - All Slots & IDs"); + } + else + { + sb.Append(" - ") + .Append(Slot.ToName()) + .Append(" - "); + if (Id.HasValue) + sb.Append(Id.Value.Id); + else + sb.Append("All IDs"); + } + + if (GenderRaceCondition is not GenderRace.Unknown) + sb.Append(" - ").Append(GenderRaceCondition.ToRaceCode()); + + return sb.ToString(); + } + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + // Nothing for now since it depends entirely on the shape key. + } + + public MetaIndex FileIndex() + => (MetaIndex)(-1); + + public bool Validate() + { + if (!Enum.IsDefined(Slot) || Slot is HumanSlot.UnkBonus) + return false; + + if (!ShapeAttributeHashSet.GenderRaceIndices.ContainsKey(GenderRaceCondition)) + return false; + + if (Slot is HumanSlot.Unknown && Id is not null) + return false; + + if (Slot.ToSpecificEnum() is BodySlot && Id is { Id: > byte.MaxValue }) + return false; + + if (Id is { Id: > ExpandedEqpGmpBase.Count - 1 }) + return false; + + return Attribute.ValidateCustomAttributeString(); + } + + public JObject AddToJson(JObject jObj) + { + if (Slot is not HumanSlot.Unknown) + jObj["Slot"] = Slot.ToString(); + if (Id.HasValue) + jObj["Id"] = Id.Value.Id.ToString(); + jObj["Attribute"] = Attribute.ToString(); + if (GenderRaceCondition is not GenderRace.Unknown) + jObj["GenderRaceCondition"] = (uint)GenderRaceCondition; + return jObj; + } + + public static AtrIdentifier? FromJson(JObject jObj) + { + var attribute = jObj["Attribute"]?.ToObject(); + if (attribute is null || !ShapeAttributeString.TryRead(attribute, out var attributeString)) + return null; + + var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; + var id = jObj["Id"]?.ToObject(); + var genderRaceCondition = jObj["GenderRaceCondition"]?.ToObject() ?? 0; + var identifier = new AtrIdentifier(slot, id, attributeString, genderRaceCondition); + return identifier.Validate() ? identifier : null; + } + + public MetaManipulationType Type + => MetaManipulationType.Atr; +} + +[JsonConverter(typeof(Converter))] +public readonly record struct AtrEntry(bool Value) +{ + public static readonly AtrEntry True = new(true); + public static readonly AtrEntry False = new(false); + + private class Converter : JsonConverter + { + public override void WriteJson(JsonWriter writer, AtrEntry value, JsonSerializer serializer) + => serializer.Serialize(writer, value.Value); + + public override AtrEntry ReadJson(JsonReader reader, Type objectType, AtrEntry existingValue, bool hasExistingValue, + JsonSerializer serializer) + => new(serializer.Deserialize(reader)); + } +} diff --git a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs index 13feba51..922825c3 100644 --- a/Penumbra/Meta/Manipulations/IMetaIdentifier.cs +++ b/Penumbra/Meta/Manipulations/IMetaIdentifier.cs @@ -16,6 +16,7 @@ public enum MetaManipulationType : byte GlobalEqp = 7, Atch = 8, Shp = 9, + Atr = 10, } public interface IMetaIdentifier diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 51ca09ab..23eaec76 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -21,6 +21,7 @@ public class MetaDictionary public readonly Dictionary Gmp = []; public readonly Dictionary Atch = []; public readonly Dictionary Shp = []; + public readonly Dictionary Atr = []; public Wrapper() { } @@ -35,6 +36,7 @@ public class MetaDictionary Rsp = cache.Rsp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); Atch = cache.Atch.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); Shp = cache.Shp.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); + Atr = cache.Atr.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Entry); foreach (var geqp in cache.GlobalEqp.Keys) Add(geqp); } @@ -66,6 +68,9 @@ public class MetaDictionary public IReadOnlyDictionary Shp => _data?.Shp ?? []; + public IReadOnlyDictionary Atr + => _data?.Atr ?? []; + public IReadOnlySet GlobalEqp => _data ?? []; @@ -84,6 +89,7 @@ public class MetaDictionary MetaManipulationType.Rsp => _data.Rsp.Count, MetaManipulationType.Atch => _data.Atch.Count, MetaManipulationType.Shp => _data.Shp.Count, + MetaManipulationType.Atr => _data.Atr.Count, MetaManipulationType.GlobalEqp => _data.Count, _ => 0, }; @@ -100,6 +106,7 @@ public class MetaDictionary ImcIdentifier i => _data.Imc.ContainsKey(i), AtchIdentifier i => _data.Atch.ContainsKey(i), ShpIdentifier i => _data.Shp.ContainsKey(i), + AtrIdentifier i => _data.Atr.ContainsKey(i), RspIdentifier i => _data.Rsp.ContainsKey(i), _ => false, }; @@ -115,13 +122,13 @@ public class MetaDictionary if (_data is null) return; - if (_data.Count is 0 && Shp.Count is 0) + if (_data.Count is 0 && Shp.Count is 0 && Atr.Count is 0) { _data = null; Count = 0; } - Count = GlobalEqp.Count + Shp.Count; + Count = GlobalEqp.Count + Shp.Count + Atr.Count; _data!.Imc.Clear(); _data!.Eqp.Clear(); _data!.Eqdp.Clear(); @@ -147,6 +154,7 @@ public class MetaDictionary && _data.Gmp.SetEquals(other._data!.Gmp) && _data.Atch.SetEquals(other._data!.Atch) && _data.Shp.SetEquals(other._data!.Shp) + && _data.Atr.SetEquals(other._data!.Atr) && _data.SetEquals(other._data!); } @@ -161,6 +169,7 @@ public class MetaDictionary .Concat(_data!.Rsp.Keys.Cast()) .Concat(_data!.Atch.Keys.Cast()) .Concat(_data!.Shp.Keys.Cast()) + .Concat(_data!.Atr.Keys.Cast()) .Concat(_data!.Cast()); #region TryAdd @@ -251,6 +260,16 @@ public class MetaDictionary return true; } + public bool TryAdd(AtrIdentifier identifier, in AtrEntry entry) + { + _data ??= []; + if (!_data!.Atr.TryAdd(identifier, entry)) + return false; + + ++Count; + return true; + } + public bool TryAdd(GlobalEqpManipulation identifier) { _data ??= []; @@ -343,6 +362,15 @@ public class MetaDictionary return true; } + public bool Update(AtrIdentifier identifier, in AtrEntry entry) + { + if (_data is null || !_data.Atr.ContainsKey(identifier)) + return false; + + _data.Atr[identifier] = entry; + return true; + } + #endregion #region TryGetValue @@ -371,6 +399,9 @@ public class MetaDictionary public bool TryGetValue(ShpIdentifier identifier, out ShpEntry value) => _data?.Shp.TryGetValue(identifier, out value) ?? SetDefault(out value); + public bool TryGetValue(AtrIdentifier identifier, out AtrEntry value) + => _data?.Atr.TryGetValue(identifier, out value) ?? SetDefault(out value); + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private static bool SetDefault(out T? value) { @@ -396,6 +427,7 @@ public class MetaDictionary RspIdentifier i => _data.Rsp.Remove(i), AtchIdentifier i => _data.Atch.Remove(i), ShpIdentifier i => _data.Shp.Remove(i), + AtrIdentifier i => _data.Atr.Remove(i), _ => false, }; if (ret && --Count is 0) @@ -436,6 +468,9 @@ public class MetaDictionary foreach (var (identifier, entry) in manips._data!.Shp) TryAdd(identifier, entry); + foreach (var (identifier, entry) in manips._data!.Atr) + TryAdd(identifier, entry); + foreach (var identifier in manips._data!) TryAdd(identifier); } @@ -498,6 +533,12 @@ public class MetaDictionary return false; } + foreach (var (identifier, _) in manips._data!.Atr.Where(kvp => !TryAdd(kvp.Key, kvp.Value))) + { + failedIdentifier = identifier; + return false; + } + foreach (var identifier in manips._data!.Where(identifier => !TryAdd(identifier))) { failedIdentifier = identifier; @@ -526,6 +567,7 @@ public class MetaDictionary _data!.Gmp.SetTo(other._data!.Gmp); _data!.Atch.SetTo(other._data!.Atch); _data!.Shp.SetTo(other._data!.Shp); + _data!.Atr.SetTo(other._data!.Atr); _data!.SetTo(other._data!); Count = other.Count; } @@ -544,6 +586,7 @@ public class MetaDictionary _data!.Gmp.UpdateTo(other._data!.Gmp); _data!.Atch.UpdateTo(other._data!.Atch); _data!.Shp.UpdateTo(other._data!.Shp); + _data!.Atr.UpdateTo(other._data!.Atr); _data!.UnionWith(other._data!); Count = _data!.Imc.Count + _data!.Eqp.Count @@ -651,6 +694,16 @@ public class MetaDictionary }), }; + public static JObject Serialize(AtrIdentifier identifier, AtrEntry entry) + => new() + { + ["Type"] = MetaManipulationType.Atr.ToString(), + ["Manipulation"] = identifier.AddToJson(new JObject + { + ["Entry"] = entry.Value, + }), + }; + public static JObject Serialize(GlobalEqpManipulation identifier) => new() { @@ -682,6 +735,8 @@ public class MetaDictionary return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); if (typeof(TIdentifier) == typeof(ShpIdentifier) && typeof(TEntry) == typeof(ShpEntry)) return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); + if (typeof(TIdentifier) == typeof(AtrIdentifier) && typeof(TEntry) == typeof(AtrEntry)) + return Serialize(Unsafe.As(ref identifier), Unsafe.As(ref entry)); if (typeof(TIdentifier) == typeof(GlobalEqpManipulation)) return Serialize(Unsafe.As(ref identifier)); @@ -730,6 +785,7 @@ public class MetaDictionary SerializeTo(array, value._data!.Gmp); SerializeTo(array, value._data!.Atch); SerializeTo(array, value._data!.Shp); + SerializeTo(array, value._data!.Atr); SerializeTo(array, value._data!); } @@ -839,6 +895,16 @@ public class MetaDictionary Penumbra.Log.Warning("Invalid SHP Manipulation encountered."); break; } + case MetaManipulationType.Atr: + { + var identifier = AtrIdentifier.FromJson(manip); + var entry = new AtrEntry(manip["Entry"]?.Value() ?? true); + if (identifier.HasValue) + dict.TryAdd(identifier.Value, entry); + else + Penumbra.Log.Warning("Invalid ATR Manipulation encountered."); + break; + } case MetaManipulationType.GlobalEqp: { var identifier = GlobalEqpManipulation.FromJson(manip); diff --git a/Penumbra/Meta/Manipulations/ShpIdentifier.cs b/Penumbra/Meta/Manipulations/ShpIdentifier.cs index 3be46d32..0a5b71b7 100644 --- a/Penumbra/Meta/Manipulations/ShpIdentifier.cs +++ b/Penumbra/Meta/Manipulations/ShpIdentifier.cs @@ -1,6 +1,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; +using Penumbra.Collections.Cache; using Penumbra.GameData.Data; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; @@ -18,7 +19,12 @@ public enum ShapeConnectorCondition : byte Ankles = 3, } -public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, ShapeString Shape, ShapeConnectorCondition ConnectorCondition) +public readonly record struct ShpIdentifier( + HumanSlot Slot, + PrimaryId? Id, + ShapeAttributeString Shape, + ShapeConnectorCondition ConnectorCondition, + GenderRace GenderRaceCondition) : IComparable, IMetaIdentifier { public int CompareTo(ShpIdentifier other) @@ -49,6 +55,10 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (conditionComparison is not 0) return conditionComparison; + var genderRaceComparison = GenderRaceCondition.CompareTo(other.GenderRaceCondition); + if (genderRaceComparison is not 0) + return genderRaceComparison; + return Shape.CompareTo(other.Shape); } @@ -80,6 +90,9 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape case ShapeConnectorCondition.Ankles: sb.Append(" - Ankle Connector"); break; } + if (GenderRaceCondition is not GenderRace.Unknown) + sb.Append(" - ").Append(GenderRaceCondition.ToRaceCode()); + return sb.ToString(); } @@ -96,6 +109,12 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (!Enum.IsDefined(Slot) || Slot is HumanSlot.UnkBonus) return false; + if (!ShapeAttributeHashSet.GenderRaceIndices.ContainsKey(GenderRaceCondition)) + return false; + + if (!Enum.IsDefined(ConnectorCondition)) + return false; + if (Slot is HumanSlot.Unknown && Id is not null) return false; @@ -105,10 +124,7 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape if (Id is { Id: > ExpandedEqpGmpBase.Count - 1 }) return false; - if (!ValidateCustomShapeString(Shape)) - return false; - - if (!Enum.IsDefined(ConnectorCondition)) + if (!Shape.ValidateCustomShapeString()) return false; return ConnectorCondition switch @@ -121,40 +137,6 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape }; } - public static unsafe bool ValidateCustomShapeString(byte* shape) - { - // "shpx_*" - if (shape is null) - return false; - - if (*shape++ is not (byte)'s' - || *shape++ is not (byte)'h' - || *shape++ is not (byte)'p' - || *shape++ is not (byte)'x' - || *shape++ is not (byte)'_' - || *shape is 0) - return false; - - return true; - } - - public static bool ValidateCustomShapeString(in ShapeString shape) - { - // "shpx_*" - if (shape.Length < 6) - return false; - - var span = shape.AsSpan; - if (span[0] is not (byte)'s' - || span[1] is not (byte)'h' - || span[2] is not (byte)'p' - || span[3] is not (byte)'x' - || span[4] is not (byte)'_') - return false; - - return true; - } - public JObject AddToJson(JObject jObj) { if (Slot is not HumanSlot.Unknown) @@ -164,19 +146,22 @@ public readonly record struct ShpIdentifier(HumanSlot Slot, PrimaryId? Id, Shape jObj["Shape"] = Shape.ToString(); if (ConnectorCondition is not ShapeConnectorCondition.None) jObj["ConnectorCondition"] = ConnectorCondition.ToString(); + if (GenderRaceCondition is not GenderRace.Unknown) + jObj["GenderRaceCondition"] = (uint)GenderRaceCondition; return jObj; } public static ShpIdentifier? FromJson(JObject jObj) { var shape = jObj["Shape"]?.ToObject(); - if (shape is null || !ShapeString.TryRead(shape, out var shapeString)) + if (shape is null || !ShapeAttributeString.TryRead(shape, out var shapeString)) return null; - var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; - var id = jObj["Id"]?.ToObject(); - var connectorCondition = jObj["ConnectorCondition"]?.ToObject() ?? ShapeConnectorCondition.None; - var identifier = new ShpIdentifier(slot, id, shapeString, connectorCondition); + var slot = jObj["Slot"]?.ToObject() ?? HumanSlot.Unknown; + var id = jObj["Id"]?.ToObject(); + var connectorCondition = jObj["ConnectorCondition"]?.ToObject() ?? ShapeConnectorCondition.None; + var genderRaceCondition = jObj["GenderRaceCondition"]?.ToObject() ?? 0; + var identifier = new ShpIdentifier(slot, id, shapeString, connectorCondition, genderRaceCondition); return identifier.Validate() ? identifier : null; } diff --git a/Penumbra/Meta/ShapeAttributeManager.cs b/Penumbra/Meta/ShapeAttributeManager.cs new file mode 100644 index 00000000..c6800141 --- /dev/null +++ b/Penumbra/Meta/ShapeAttributeManager.cs @@ -0,0 +1,153 @@ +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Collections.Cache; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Interop; +using Penumbra.GameData.Structs; +using Penumbra.Interop.Hooks.PostProcessing; +using Penumbra.Meta.Manipulations; + +namespace Penumbra.Meta; + +public unsafe class ShapeAttributeManager : IRequiredService, IDisposable +{ + public const int NumSlots = 14; + public const int ModelSlotSize = 18; + private readonly AttributeHook _attributeHook; + + public static ReadOnlySpan UsedModels + => + [ + HumanSlot.Head, HumanSlot.Body, HumanSlot.Hands, HumanSlot.Legs, HumanSlot.Feet, HumanSlot.Ears, HumanSlot.Neck, HumanSlot.Wrists, + HumanSlot.RFinger, HumanSlot.LFinger, HumanSlot.Glasses, HumanSlot.Hair, HumanSlot.Face, HumanSlot.Ear, + ]; + + public ShapeAttributeManager(AttributeHook attributeHook) + { + _attributeHook = attributeHook; + _attributeHook.Subscribe(OnAttributeComputed, AttributeHook.Priority.ShapeAttributeManager); + } + + private readonly Dictionary[] _temporaryShapes = + Enumerable.Range(0, NumSlots).Select(_ => new Dictionary()).ToArray(); + + private readonly PrimaryId[] _ids = new PrimaryId[ModelSlotSize]; + + private HumanSlot _modelIndex; + private int _slotIndex; + private GenderRace _genderRace; + + private FFXIVClientStructs.FFXIV.Client.Graphics.Render.Model* _model; + + public void Dispose() + => _attributeHook.Unsubscribe(OnAttributeComputed); + + private void OnAttributeComputed(Actor actor, Model model, ModCollection collection) + { + if (!collection.HasCache) + return; + + _genderRace = (GenderRace)model.AsHuman->RaceSexId; + for (_slotIndex = 0; _slotIndex < NumSlots; ++_slotIndex) + { + _modelIndex = UsedModels[_slotIndex]; + _model = model.AsHuman->Models[_modelIndex.ToIndex()]; + if (_model is null || _model->ModelResourceHandle is null) + continue; + + _ids[(int)_modelIndex] = model.GetModelId(_modelIndex); + CheckShapes(collection.MetaCache!.Shp); + CheckAttributes(collection.MetaCache!.Atr); + } + + UpdateDefaultMasks(model, collection.MetaCache!.Shp); + } + + private void CheckAttributes(AtrCache attributeCache) + { + if (attributeCache.DisabledCount is 0) + return; + + ref var attributes = ref _model->ModelResourceHandle->Attributes; + foreach (var (attribute, index) in attributes.Where(kvp => ShapeAttributeString.ValidateCustomAttributeString(kvp.Key.Value))) + { + if (ShapeAttributeString.TryRead(attribute.Value, out var attributeString)) + { + // Mask out custom attributes if they are disabled. Attributes are enabled by default. + if (attributeCache.ShouldBeDisabled(attributeString, _modelIndex, _ids[_modelIndex.ToIndex()], _genderRace)) + _model->EnabledAttributeIndexMask &= (ushort)~(1 << index); + } + else + { + Penumbra.Log.Warning($"Trying to read a attribute string that is too long: {attribute}."); + } + } + } + + private void CheckShapes(ShpCache shapeCache) + { + _temporaryShapes[_slotIndex].Clear(); + ref var shapes = ref _model->ModelResourceHandle->Shapes; + foreach (var (shape, index) in shapes.Where(kvp => ShapeAttributeString.ValidateCustomShapeString(kvp.Key.Value))) + { + if (ShapeAttributeString.TryRead(shape.Value, out var shapeString)) + { + _temporaryShapes[_slotIndex].TryAdd(shapeString, index); + // Add custom shapes if they are enabled. Shapes are disabled by default. + if (shapeCache.ShouldBeEnabled(shapeString, _modelIndex, _ids[_modelIndex.ToIndex()], _genderRace)) + _model->EnabledShapeKeyIndexMask |= (ushort)(1 << index); + } + else + { + Penumbra.Log.Warning($"Trying to read a shape string that is too long: {shape}."); + } + } + } + + private void UpdateDefaultMasks(Model human, ShpCache cache) + { + foreach (var (shape, topIndex) in _temporaryShapes[1]) + { + if (shape.IsWrist() && _temporaryShapes[2].TryGetValue(shape, out var handIndex)) + { + human.AsHuman->Models[1]->EnabledShapeKeyIndexMask |= 1u << topIndex; + human.AsHuman->Models[2]->EnabledShapeKeyIndexMask |= 1u << handIndex; + CheckCondition(cache.State(ShapeConnectorCondition.Wrists), HumanSlot.Body, HumanSlot.Hands, 1, 2); + } + + if (shape.IsWaist() && _temporaryShapes[3].TryGetValue(shape, out var legIndex)) + { + human.AsHuman->Models[1]->EnabledShapeKeyIndexMask |= 1u << topIndex; + human.AsHuman->Models[3]->EnabledShapeKeyIndexMask |= 1u << legIndex; + CheckCondition(cache.State(ShapeConnectorCondition.Waist), HumanSlot.Body, HumanSlot.Legs, 1, 3); + } + } + + foreach (var (shape, bottomIndex) in _temporaryShapes[3]) + { + if (shape.IsAnkle() && _temporaryShapes[4].TryGetValue(shape, out var footIndex)) + { + human.AsHuman->Models[3]->EnabledShapeKeyIndexMask |= 1u << bottomIndex; + human.AsHuman->Models[4]->EnabledShapeKeyIndexMask |= 1u << footIndex; + CheckCondition(cache.State(ShapeConnectorCondition.Ankles), HumanSlot.Legs, HumanSlot.Feet, 3, 4); + } + } + + return; + + void CheckCondition(IReadOnlyDictionary dict, HumanSlot slot1, + HumanSlot slot2, int idx1, int idx2) + { + if (dict.Count is 0) + return; + + foreach (var (shape, set) in dict) + { + if (set.Contains(slot1, _ids[idx1], GenderRace.Unknown) && _temporaryShapes[idx1].TryGetValue(shape, out var index1)) + human.AsHuman->Models[idx1]->EnabledShapeKeyIndexMask |= 1u << index1; + if (set.Contains(slot2, _ids[idx2], GenderRace.Unknown) && _temporaryShapes[idx2].TryGetValue(shape, out var index2)) + human.AsHuman->Models[idx2]->EnabledShapeKeyIndexMask |= 1u << index2; + } + } + } +} diff --git a/Penumbra/Meta/ShapeString.cs b/Penumbra/Meta/ShapeAttributeString.cs similarity index 55% rename from Penumbra/Meta/ShapeString.cs rename to Penumbra/Meta/ShapeAttributeString.cs index 95ca0933..55e3f021 100644 --- a/Penumbra/Meta/ShapeString.cs +++ b/Penumbra/Meta/ShapeAttributeString.cs @@ -6,11 +6,11 @@ using Penumbra.String.Functions; namespace Penumbra.Meta; [JsonConverter(typeof(Converter))] -public struct ShapeString : IEquatable, IComparable +public struct ShapeAttributeString : IEquatable, IComparable { public const int MaxLength = 30; - public static readonly ShapeString Empty = new(); + public static readonly ShapeAttributeString Empty = new(); private FixedString32 _buffer; @@ -37,6 +37,72 @@ public struct ShapeString : IEquatable, IComparable } } + public static unsafe bool ValidateCustomShapeString(byte* shape) + { + // "shpx_*" + if (shape is null) + return false; + + if (*shape++ is not (byte)'s' + || *shape++ is not (byte)'h' + || *shape++ is not (byte)'p' + || *shape++ is not (byte)'x' + || *shape++ is not (byte)'_' + || *shape is 0) + return false; + + return true; + } + + public bool ValidateCustomShapeString() + { + // "shpx_*" + if (Length < 6) + return false; + + if (_buffer[0] is not (byte)'s' + || _buffer[1] is not (byte)'h' + || _buffer[2] is not (byte)'p' + || _buffer[3] is not (byte)'x' + || _buffer[4] is not (byte)'_') + return false; + + return true; + } + + public static unsafe bool ValidateCustomAttributeString(byte* shape) + { + // "atrx_*" + if (shape is null) + return false; + + if (*shape++ is not (byte)'a' + || *shape++ is not (byte)'t' + || *shape++ is not (byte)'r' + || *shape++ is not (byte)'x' + || *shape++ is not (byte)'_' + || *shape is 0) + return false; + + return true; + } + + public bool ValidateCustomAttributeString() + { + // "atrx_*" + if (Length < 6) + return false; + + if (_buffer[0] is not (byte)'a' + || _buffer[1] is not (byte)'t' + || _buffer[2] is not (byte)'r' + || _buffer[3] is not (byte)'x' + || _buffer[4] is not (byte)'_') + return false; + + return true; + } + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] public bool IsAnkle() => CheckCenter('a', 'n'); @@ -53,28 +119,28 @@ public struct ShapeString : IEquatable, IComparable private bool CheckCenter(char first, char second) => Length > 8 && _buffer[5] == first && _buffer[6] == second && _buffer[7] is (byte)'_'; - public bool Equals(ShapeString other) + public bool Equals(ShapeAttributeString other) => Length == other.Length && _buffer[..Length].SequenceEqual(other._buffer[..Length]); public override bool Equals(object? obj) - => obj is ShapeString other && Equals(other); + => obj is ShapeAttributeString other && Equals(other); public override int GetHashCode() => (int)Crc32.Get(_buffer[..Length]); - public static bool operator ==(ShapeString left, ShapeString right) + public static bool operator ==(ShapeAttributeString left, ShapeAttributeString right) => left.Equals(right); - public static bool operator !=(ShapeString left, ShapeString right) + public static bool operator !=(ShapeAttributeString left, ShapeAttributeString right) => !left.Equals(right); - public static unsafe bool TryRead(byte* pointer, out ShapeString ret) + public static unsafe bool TryRead(byte* pointer, out ShapeAttributeString ret) { var span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(pointer); return TryRead(span, out ret); } - public unsafe int CompareTo(ShapeString other) + public unsafe int CompareTo(ShapeAttributeString other) { fixed (void* lhs = &this) { @@ -82,7 +148,7 @@ public struct ShapeString : IEquatable, IComparable } } - public static bool TryRead(ReadOnlySpan utf8, out ShapeString ret) + public static bool TryRead(ReadOnlySpan utf8, out ShapeAttributeString ret) { if (utf8.Length is 0 or > MaxLength) { @@ -97,7 +163,7 @@ public struct ShapeString : IEquatable, IComparable return true; } - public static bool TryRead(ReadOnlySpan utf16, out ShapeString ret) + public static bool TryRead(ReadOnlySpan utf16, out ShapeAttributeString ret) { ret = Empty; if (!Encoding.UTF8.TryGetBytes(utf16, ret._buffer[..MaxLength], out var written)) @@ -116,19 +182,20 @@ public struct ShapeString : IEquatable, IComparable _buffer[31] = length; } - private sealed class Converter : JsonConverter + private sealed class Converter : JsonConverter { - public override void WriteJson(JsonWriter writer, ShapeString value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, ShapeAttributeString value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } - public override ShapeString ReadJson(JsonReader reader, Type objectType, ShapeString existingValue, bool hasExistingValue, + public override ShapeAttributeString ReadJson(JsonReader reader, Type objectType, ShapeAttributeString existingValue, + bool hasExistingValue, JsonSerializer serializer) { var value = serializer.Deserialize(reader); if (!TryRead(value, out existingValue)) - throw new JsonReaderException($"Could not parse {value} into ShapeString."); + throw new JsonReaderException($"Could not parse {value} into ShapeAttributeString."); return existingValue; } diff --git a/Penumbra/Meta/ShapeManager.cs b/Penumbra/Meta/ShapeManager.cs deleted file mode 100644 index abd4c3b8..00000000 --- a/Penumbra/Meta/ShapeManager.cs +++ /dev/null @@ -1,140 +0,0 @@ -using OtterGui.Services; -using Penumbra.Collections; -using Penumbra.Collections.Cache; -using Penumbra.GameData.Enums; -using Penumbra.GameData.Interop; -using Penumbra.GameData.Structs; -using Penumbra.Interop.Hooks.PostProcessing; -using Penumbra.Meta.Manipulations; - -namespace Penumbra.Meta; - -public class ShapeManager : IRequiredService, IDisposable -{ - public const int NumSlots = 14; - public const int ModelSlotSize = 18; - private readonly AttributeHook _attributeHook; - - public static ReadOnlySpan UsedModels - => - [ - HumanSlot.Head, HumanSlot.Body, HumanSlot.Hands, HumanSlot.Legs, HumanSlot.Feet, HumanSlot.Ears, HumanSlot.Neck, HumanSlot.Wrists, - HumanSlot.RFinger, HumanSlot.LFinger, HumanSlot.Glasses, HumanSlot.Hair, HumanSlot.Face, HumanSlot.Ear, - ]; - - public ShapeManager(AttributeHook attributeHook) - { - _attributeHook = attributeHook; - _attributeHook.Subscribe(OnAttributeComputed, AttributeHook.Priority.ShapeManager); - } - - private readonly Dictionary[] _temporaryIndices = - Enumerable.Range(0, NumSlots).Select(_ => new Dictionary()).ToArray(); - - private readonly uint[] _temporaryMasks = new uint[NumSlots]; - private readonly uint[] _temporaryValues = new uint[NumSlots]; - private readonly PrimaryId[] _ids = new PrimaryId[ModelSlotSize]; - - public void Dispose() - => _attributeHook.Unsubscribe(OnAttributeComputed); - - private unsafe void OnAttributeComputed(Actor actor, Model model, ModCollection collection) - { - if (!collection.HasCache) - return; - - ComputeCache(model, collection.MetaCache!.Shp); - for (var i = 0; i < NumSlots; ++i) - { - if (_temporaryMasks[i] is 0) - continue; - - var modelIndex = UsedModels[i]; - var currentMask = model.AsHuman->Models[modelIndex.ToIndex()]->EnabledShapeKeyIndexMask; - var newMask = (currentMask & ~_temporaryMasks[i]) | _temporaryValues[i]; - Penumbra.Log.Excessive($"Changed Model Mask from {currentMask:X} to {newMask:X}."); - model.AsHuman->Models[modelIndex.ToIndex()]->EnabledShapeKeyIndexMask = newMask; - } - } - - private unsafe void ComputeCache(Model human, ShpCache cache) - { - for (var i = 0; i < NumSlots; ++i) - { - _temporaryMasks[i] = 0; - _temporaryValues[i] = 0; - _temporaryIndices[i].Clear(); - - var modelIndex = UsedModels[i]; - var model = human.AsHuman->Models[modelIndex.ToIndex()]; - if (model is null || model->ModelResourceHandle is null) - continue; - - _ids[(int)modelIndex] = human.GetModelId(modelIndex); - - ref var shapes = ref model->ModelResourceHandle->Shapes; - foreach (var (shape, index) in shapes.Where(kvp => ShpIdentifier.ValidateCustomShapeString(kvp.Key.Value))) - { - if (ShapeString.TryRead(shape.Value, out var shapeString)) - { - _temporaryIndices[i].TryAdd(shapeString, index); - _temporaryMasks[i] |= (ushort)(1 << index); - if (cache.ShouldBeEnabled(shapeString, modelIndex, _ids[(int)modelIndex])) - _temporaryValues[i] |= (ushort)(1 << index); - } - else - { - Penumbra.Log.Warning($"Trying to read a shape string that is too long: {shape}."); - } - } - } - - UpdateDefaultMasks(cache); - } - - private void UpdateDefaultMasks(ShpCache cache) - { - foreach (var (shape, topIndex) in _temporaryIndices[1]) - { - if (shape.IsWrist() && _temporaryIndices[2].TryGetValue(shape, out var handIndex)) - { - _temporaryValues[1] |= 1u << topIndex; - _temporaryValues[2] |= 1u << handIndex; - CheckCondition(cache.State(ShapeConnectorCondition.Wrists), HumanSlot.Body, HumanSlot.Hands, 1, 2); - } - - if (shape.IsWaist() && _temporaryIndices[3].TryGetValue(shape, out var legIndex)) - { - _temporaryValues[1] |= 1u << topIndex; - _temporaryValues[3] |= 1u << legIndex; - CheckCondition(cache.State(ShapeConnectorCondition.Waist), HumanSlot.Body, HumanSlot.Legs, 1, 3); - } - } - - foreach (var (shape, bottomIndex) in _temporaryIndices[3]) - { - if (shape.IsAnkle() && _temporaryIndices[4].TryGetValue(shape, out var footIndex)) - { - _temporaryValues[3] |= 1u << bottomIndex; - _temporaryValues[4] |= 1u << footIndex; - CheckCondition(cache.State(ShapeConnectorCondition.Ankles), HumanSlot.Legs, HumanSlot.Feet, 3, 4); - } - } - - return; - - void CheckCondition(IReadOnlyDictionary dict, HumanSlot slot1, HumanSlot slot2, int idx1, int idx2) - { - if (dict.Count is 0) - return; - - foreach (var (shape, set) in dict) - { - if (set.Contains(slot1, _ids[idx1]) && _temporaryIndices[idx1].TryGetValue(shape, out var index1)) - _temporaryValues[idx1] |= 1u << index1; - if (set.Contains(slot2, _ids[idx2]) && _temporaryIndices[idx2].TryGetValue(shape, out var index2)) - _temporaryValues[idx2] |= 1u << index2; - } - } - } -} diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs new file mode 100644 index 00000000..89fadfa8 --- /dev/null +++ b/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs @@ -0,0 +1,274 @@ +using Dalamud.Interface; +using ImGuiNET; +using Newtonsoft.Json.Linq; +using OtterGui.Raii; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Collections.Cache; +using Penumbra.GameData.Enums; +using Penumbra.GameData.Structs; +using Penumbra.Meta; +using Penumbra.Meta.Files; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.UI.Classes; + +namespace Penumbra.UI.AdvancedWindow.Meta; + +public sealed class AtrMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) + : MetaDrawer(editor, metaFiles), IService +{ + public override ReadOnlySpan Label + => "Attributes(ATR)###ATR"u8; + + private ShapeAttributeString _buffer = ShapeAttributeString.TryRead("atrx_"u8, out var s) ? s : ShapeAttributeString.Empty; + private bool _identifierValid; + + public override int NumColumns + => 7; + + public override float ColumnHeight + => ImUtf8.FrameHeightSpacing; + + protected override void Initialize() + { + Identifier = new AtrIdentifier(HumanSlot.Unknown, null, ShapeAttributeString.Empty, GenderRace.Unknown); + Entry = AtrEntry.True; + } + + protected override void DrawNew() + { + ImGui.TableNextColumn(); + CopyToClipboardButton("Copy all current ATR manipulations to clipboard."u8, + new Lazy(() => MetaDictionary.SerializeTo([], Editor.Atr))); + + ImGui.TableNextColumn(); + var canAdd = !Editor.Contains(Identifier) && _identifierValid; + var tt = canAdd + ? "Stage this edit."u8 + : _identifierValid + ? "This entry does not contain a valid attribute."u8 + : "This entry is already edited."u8; + if (ImUtf8.IconButton(FontAwesomeIcon.Plus, tt, disabled: !canAdd)) + Editor.Changes |= Editor.TryAdd(Identifier, AtrEntry.False); + + DrawIdentifierInput(ref Identifier); + DrawEntry(ref Entry, true); + } + + protected override void DrawEntry(AtrIdentifier identifier, AtrEntry entry) + { + DrawMetaButtons(identifier, entry); + DrawIdentifier(identifier); + + if (DrawEntry(ref entry, false)) + Editor.Changes |= Editor.Update(identifier, entry); + } + + protected override IEnumerable<(AtrIdentifier, AtrEntry)> Enumerate() + => Editor.Atr + .OrderBy(kvp => kvp.Key.Attribute) + .ThenBy(kvp => kvp.Key.Slot) + .ThenBy(kvp => kvp.Key.Id) + .Select(kvp => (kvp.Key, kvp.Value)); + + protected override int Count + => Editor.Atr.Count; + + private bool DrawIdentifierInput(ref AtrIdentifier identifier) + { + ImGui.TableNextColumn(); + var changes = DrawHumanSlot(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawGenderRaceConditionInput(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawPrimaryId(ref identifier); + + ImGui.TableNextColumn(); + changes |= DrawAttributeKeyInput(ref identifier, ref _buffer, ref _identifierValid); + return changes; + } + + private static void DrawIdentifier(AtrIdentifier identifier) + { + ImGui.TableNextColumn(); + + ImUtf8.TextFramed(ShpMetaDrawer.SlotName(identifier.Slot), FrameColor); + ImUtf8.HoverTooltip("Model Slot"u8); + + ImGui.TableNextColumn(); + if (identifier.GenderRaceCondition is not GenderRace.Unknown) + { + ImUtf8.TextFramed($"{identifier.GenderRaceCondition.ToName()} ({identifier.GenderRaceCondition.ToRaceCode()})", FrameColor); + ImUtf8.HoverTooltip("Gender & Race Code for this attribute to be set."); + } + else + { + ImUtf8.TextFramed("Any Gender & Race"u8, FrameColor); + } + + ImGui.TableNextColumn(); + if (identifier.Id.HasValue) + ImUtf8.TextFramed($"{identifier.Id.Value.Id}", FrameColor); + else + ImUtf8.TextFramed("All IDs"u8, FrameColor); + ImUtf8.HoverTooltip("Primary ID"u8); + + ImGui.TableNextColumn(); + ImUtf8.TextFramed(identifier.Attribute.AsSpan, FrameColor); + } + + private static bool DrawEntry(ref AtrEntry entry, bool disabled) + { + using var dis = ImRaii.Disabled(disabled); + ImGui.TableNextColumn(); + var value = entry.Value; + var changes = ImUtf8.Checkbox("##atrEntry"u8, ref value); + if (changes) + entry = new AtrEntry(value); + ImUtf8.HoverTooltip("Whether to enable or disable this attribute for the selected items."); + return changes; + } + + public static bool DrawPrimaryId(ref AtrIdentifier identifier, float unscaledWidth = 100) + { + var allSlots = identifier.Slot is HumanSlot.Unknown; + var all = !identifier.Id.HasValue; + var ret = false; + using (ImRaii.Disabled(allSlots)) + { + if (ImUtf8.Checkbox("##atrAll"u8, ref all)) + { + identifier = identifier with { Id = all ? null : 0 }; + ret = true; + } + } + + ImUtf8.HoverTooltip(allSlots + ? "When using all slots, you also need to use all IDs."u8 + : "Enable this attribute for all model IDs."u8); + + ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.X); + if (all) + { + using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0.05f, 0.5f)); + ImUtf8.TextFramed("All IDs"u8, ImGui.GetColorU32(ImGuiCol.FrameBg, all || allSlots ? ImGui.GetStyle().DisabledAlpha : 1f), + new Vector2(unscaledWidth, 0), ImGui.GetColorU32(ImGuiCol.TextDisabled)); + } + else + { + var max = identifier.Slot.ToSpecificEnum() is BodySlot ? byte.MaxValue : ExpandedEqpGmpBase.Count - 1; + if (IdInput("##atrPrimaryId"u8, unscaledWidth, identifier.Id.GetValueOrDefault(0).Id, out var setId, 0, max, false)) + { + identifier = identifier with { Id = setId }; + ret = true; + } + } + + ImUtf8.HoverTooltip("Primary ID - You can usually find this as the 'e####' part of an item path or similar for customizations."u8); + + return ret; + } + + public bool DrawHumanSlot(ref AtrIdentifier identifier, float unscaledWidth = 150) + { + var ret = false; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + using (var combo = ImUtf8.Combo("##atrSlot"u8, ShpMetaDrawer.SlotName(identifier.Slot))) + { + if (combo) + foreach (var slot in ShpMetaDrawer.AvailableSlots) + { + if (!ImUtf8.Selectable(ShpMetaDrawer.SlotName(slot), slot == identifier.Slot) || slot == identifier.Slot) + continue; + + ret = true; + if (slot is HumanSlot.Unknown) + { + identifier = identifier with + { + Id = null, + Slot = slot, + }; + } + else + { + identifier = identifier with + { + Id = identifier.Id.HasValue + ? (PrimaryId)Math.Clamp(identifier.Id.Value.Id, 0, + slot.ToSpecificEnum() is BodySlot ? byte.MaxValue : ExpandedEqpGmpBase.Count - 1) + : null, + Slot = slot, + }; + ret = true; + } + } + } + + ImUtf8.HoverTooltip("Model Slot"u8); + return ret; + } + + private static bool DrawGenderRaceConditionInput(ref AtrIdentifier identifier, float unscaledWidth = 250) + { + var ret = false; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + + using (var combo = ImUtf8.Combo("##shpGenderRace"u8, + identifier.GenderRaceCondition is GenderRace.Unknown + ? "Any Gender & Race" + : $"{identifier.GenderRaceCondition.ToName()} ({identifier.GenderRaceCondition.ToRaceCode()})")) + { + if (combo) + { + if (ImUtf8.Selectable("Any Gender & Race"u8, identifier.GenderRaceCondition is GenderRace.Unknown) + && identifier.GenderRaceCondition is not GenderRace.Unknown) + { + identifier = identifier with { GenderRaceCondition = GenderRace.Unknown }; + ret = true; + } + + foreach (var gr in ShapeAttributeHashSet.GenderRaceValues.Skip(1)) + { + if (ImUtf8.Selectable($"{gr.ToName()} ({gr.ToRaceCode()})", identifier.GenderRaceCondition == gr) + && identifier.GenderRaceCondition != gr) + { + identifier = identifier with { GenderRaceCondition = gr }; + ret = true; + } + } + } + } + + ImUtf8.HoverTooltip( + "Only activate this attribute for this gender & race code."u8); + + return ret; + } + + public static unsafe bool DrawAttributeKeyInput(ref AtrIdentifier identifier, ref ShapeAttributeString buffer, ref bool valid, + float unscaledWidth = 150) + { + var ret = false; + var ptr = Unsafe.AsPointer(ref buffer); + var span = new Span(ptr, ShapeAttributeString.MaxLength + 1); + using (new ImRaii.ColorStyle().Push(ImGuiCol.Border, Colors.RegexWarningBorder, !valid).Push(ImGuiStyleVar.FrameBorderSize, 1f, !valid)) + { + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + if (ImUtf8.InputText("##atrAttribute"u8, span, out int newLength, "Attribute..."u8)) + { + buffer.ForceLength((byte)newLength); + valid = buffer.ValidateCustomAttributeString(); + if (valid) + identifier = identifier with { Attribute = buffer }; + ret = true; + } + } + + ImUtf8.HoverTooltip("Supported attribute need to have the format `atrx_*` and a maximum length of 30 characters."u8); + return ret; + } +} diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs index 70b5f83b..792611e2 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawers.cs @@ -12,7 +12,8 @@ public class MetaDrawers( ImcMetaDrawer imc, RspMetaDrawer rsp, AtchMetaDrawer atch, - ShpMetaDrawer shp) : IService + ShpMetaDrawer shp, + AtrMetaDrawer atr) : IService { public readonly EqdpMetaDrawer Eqdp = eqdp; public readonly EqpMetaDrawer Eqp = eqp; @@ -23,6 +24,7 @@ public class MetaDrawers( public readonly GlobalEqpMetaDrawer GlobalEqp = globalEqp; public readonly AtchMetaDrawer Atch = atch; public readonly ShpMetaDrawer Shp = shp; + public readonly AtrMetaDrawer Atr = atr; public IMetaDrawer? Get(MetaManipulationType type) => type switch @@ -35,6 +37,7 @@ public class MetaDrawers( MetaManipulationType.Rsp => Rsp, MetaManipulationType.Atch => Atch, MetaManipulationType.Shp => Shp, + MetaManipulationType.Atr => Atr, MetaManipulationType.GlobalEqp => GlobalEqp, _ => null, }; diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs index 6505ecc0..35c8ccec 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; +using Penumbra.Collections.Cache; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Meta; @@ -20,18 +21,18 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile public override ReadOnlySpan Label => "Shape Keys (SHP)###SHP"u8; - private ShapeString _buffer = ShapeString.TryRead("shpx_"u8, out var s) ? s : ShapeString.Empty; - private bool _identifierValid; + private ShapeAttributeString _buffer = ShapeAttributeString.TryRead("shpx_"u8, out var s) ? s : ShapeAttributeString.Empty; + private bool _identifierValid; public override int NumColumns - => 7; + => 8; public override float ColumnHeight => ImUtf8.FrameHeightSpacing; protected override void Initialize() { - Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeString.Empty, ShapeConnectorCondition.None); + Identifier = new ShpIdentifier(HumanSlot.Unknown, null, ShapeAttributeString.Empty, ShapeConnectorCondition.None, GenderRace.Unknown); } protected override void DrawNew() @@ -79,6 +80,9 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ImGui.TableNextColumn(); var changes = DrawHumanSlot(ref identifier); + ImGui.TableNextColumn(); + changes |= DrawGenderRaceConditionInput(ref identifier); + ImGui.TableNextColumn(); changes |= DrawPrimaryId(ref identifier); @@ -97,6 +101,17 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile ImUtf8.TextFramed(SlotName(identifier.Slot), FrameColor); ImUtf8.HoverTooltip("Model Slot"u8); + ImGui.TableNextColumn(); + if (identifier.GenderRaceCondition is not GenderRace.Unknown) + { + ImUtf8.TextFramed($"{identifier.GenderRaceCondition.ToName()} ({identifier.GenderRaceCondition.ToRaceCode()})", FrameColor); + ImUtf8.HoverTooltip("Gender & Race Code for this shape key to be set."); + } + else + { + ImUtf8.TextFramed("Any Gender & Race"u8, FrameColor); + } + ImGui.TableNextColumn(); if (identifier.Id.HasValue) ImUtf8.TextFramed($"{identifier.Id.Value.Id}", FrameColor); @@ -165,7 +180,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } - public bool DrawHumanSlot(ref ShpIdentifier identifier, float unscaledWidth = 150) + public bool DrawHumanSlot(ref ShpIdentifier identifier, float unscaledWidth = 170) { var ret = false; ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); @@ -212,18 +227,19 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } - public static unsafe bool DrawShapeKeyInput(ref ShpIdentifier identifier, ref ShapeString buffer, ref bool valid, float unscaledWidth = 150) + public static unsafe bool DrawShapeKeyInput(ref ShpIdentifier identifier, ref ShapeAttributeString buffer, ref bool valid, + float unscaledWidth = 200) { var ret = false; var ptr = Unsafe.AsPointer(ref buffer); - var span = new Span(ptr, ShapeString.MaxLength + 1); + var span = new Span(ptr, ShapeAttributeString.MaxLength + 1); using (new ImRaii.ColorStyle().Push(ImGuiCol.Border, Colors.RegexWarningBorder, !valid).Push(ImGuiStyleVar.FrameBorderSize, 1f, !valid)) { ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); if (ImUtf8.InputText("##shpShape"u8, span, out int newLength, "Shape Key..."u8)) { buffer.ForceLength((byte)newLength); - valid = ShpIdentifier.ValidateCustomShapeString(buffer); + valid = buffer.ValidateCustomShapeString(); if (valid) identifier = identifier with { Shape = buffer }; ret = true; @@ -234,7 +250,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } - public static unsafe bool DrawConnectorConditionInput(ref ShpIdentifier identifier, float unscaledWidth = 150) + private static bool DrawConnectorConditionInput(ref ShpIdentifier identifier, float unscaledWidth = 80) { var ret = false; ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); @@ -271,7 +287,43 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile return ret; } - private static ReadOnlySpan AvailableSlots + private static bool DrawGenderRaceConditionInput(ref ShpIdentifier identifier, float unscaledWidth = 250) + { + var ret = false; + ImGui.SetNextItemWidth(unscaledWidth * ImUtf8.GlobalScale); + + using (var combo = ImUtf8.Combo("##shpGenderRace"u8, identifier.GenderRaceCondition is GenderRace.Unknown + ? "Any Gender & Race" + : $"{identifier.GenderRaceCondition.ToName()} ({identifier.GenderRaceCondition.ToRaceCode()})")) + { + if (combo) + { + if (ImUtf8.Selectable("Any Gender & Race"u8, identifier.GenderRaceCondition is GenderRace.Unknown) + && identifier.GenderRaceCondition is not GenderRace.Unknown) + { + identifier = identifier with { GenderRaceCondition = GenderRace.Unknown }; + ret = true; + } + + foreach (var gr in ShapeAttributeHashSet.GenderRaceValues.Skip(1)) + { + if (ImUtf8.Selectable($"{gr.ToName()} ({gr.ToRaceCode()})", identifier.GenderRaceCondition == gr) + && identifier.GenderRaceCondition != gr) + { + identifier = identifier with { GenderRaceCondition = gr }; + ret = true; + } + } + } + } + + ImUtf8.HoverTooltip( + "Only activate this shape key for this gender & race code."u8); + + return ret; + } + + public static ReadOnlySpan AvailableSlots => [ HumanSlot.Unknown, @@ -291,7 +343,7 @@ public sealed class ShpMetaDrawer(ModMetaEditor editor, MetaFileManager metaFile HumanSlot.Ear, ]; - private static ReadOnlySpan SlotName(HumanSlot slot) + public static ReadOnlySpan SlotName(HumanSlot slot) => slot switch { HumanSlot.Unknown => "All Slots"u8, diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 70a15373..3f19da5e 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -62,6 +62,7 @@ public partial class ModEditWindow DrawEditHeader(MetaManipulationType.Rsp); DrawEditHeader(MetaManipulationType.Atch); DrawEditHeader(MetaManipulationType.Shp); + DrawEditHeader(MetaManipulationType.Atr); DrawEditHeader(MetaManipulationType.GlobalEqp); } diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 109cb5c4..9290e52d 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -35,6 +35,27 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) DrawCollectionShapeCache(actor); DrawCharacterShapes(human); + DrawCollectionAttributeCache(actor); + DrawCharacterAttributes(human); + } + + private unsafe void DrawCollectionAttributeCache(Actor actor) + { + var data = resolver.IdentifyCollection(actor.AsObject, true); + using var treeNode1 = ImUtf8.TreeNode($"Collection Attribute Cache ({data.ModCollection})"); + if (!treeNode1.Success || !data.ModCollection.HasCache) + return; + + using var table = ImUtf8.Table("##aCache"u8, 2, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("Attribute"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Disabled"u8, ImGuiTableColumnFlags.WidthStretch); + + ImGui.TableHeadersRow(); + foreach (var (attribute, set) in data.ModCollection.MetaCache!.Atr.Data) + DrawShapeAttribute(attribute, set); } private unsafe void DrawCollectionShapeCache(Actor actor) @@ -44,7 +65,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (!treeNode1.Success || !data.ModCollection.HasCache) return; - using var table = ImUtf8.Table("##cacheTable"u8, 3, ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##sCache"u8, 3, ImGuiTableFlags.RowBg); if (!table) return; @@ -58,14 +79,14 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State(condition)) { ImUtf8.DrawTableColumn(condition.ToString()); - DrawShape(shape, set); + DrawShapeAttribute(shape, set); } } } - private static void DrawShape(in ShapeString shape, ShpCache.ShpHashSet set) + private static void DrawShapeAttribute(in ShapeAttributeString shapeAttribute, ShapeAttributeHashSet set) { - ImUtf8.DrawTableColumn(shape.AsSpan); + ImUtf8.DrawTableColumn(shapeAttribute.AsSpan); if (set.All) { ImUtf8.DrawTableColumn("All"u8); @@ -73,7 +94,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) else { ImGui.TableNextColumn(); - foreach (var slot in ShapeManager.UsedModels) + foreach (var slot in ShapeAttributeManager.UsedModels) { if (!set[slot]) continue; @@ -82,10 +103,52 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImGui.SameLine(0, 0); } - foreach (var item in set.Where(i => !set[i.Slot])) + foreach (var gr in ShapeAttributeHashSet.GenderRaceValues.Skip(1)) { - ImUtf8.Text($"{item.Slot.ToName()} {item.Id.Id:D4}, "); - ImGui.SameLine(0, 0); + if (set[gr]) + { + ImUtf8.Text($"All {gr.ToName()}, "); + ImGui.SameLine(0, 0); + } + else + { + foreach (var slot in ShapeAttributeManager.UsedModels) + { + if (!set[slot, gr]) + continue; + + ImUtf8.Text($"All {gr.ToName()} {slot.ToName()}, "); + ImGui.SameLine(0, 0); + } + } + } + + + foreach (var ((slot, id), flags) in set) + { + if ((flags & 1ul) is not 0) + { + if (set[slot]) + continue; + + ImUtf8.Text($"{slot.ToName()} {id.Id:D4}, "); + ImGui.SameLine(0, 0); + } + else + { + var currentFlags = flags >> 1; + var currentIndex = BitOperations.TrailingZeroCount(currentFlags); + while (currentIndex < ShapeAttributeHashSet.GenderRaceValues.Count) + { + var gr = ShapeAttributeHashSet.GenderRaceValues[currentIndex]; + if (set[slot, gr]) + continue; + + ImUtf8.Text($"{gr.ToName()} {slot.ToName()} {id.Id:D4}, "); + currentFlags >>= currentIndex; + currentIndex = BitOperations.TrailingZeroCount(currentFlags); + } + } } } } @@ -96,7 +159,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (!treeNode2) return; - using var table = ImUtf8.Table("##table"u8, 5, ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##shapes"u8, 5, ImGuiTableFlags.RowBg); if (!table) return; @@ -140,4 +203,55 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) } } } + + private unsafe void DrawCharacterAttributes(Model human) + { + using var treeNode2 = ImUtf8.TreeNode("Character Model Attributes"u8); + if (!treeNode2) + return; + + using var table = ImUtf8.Table("##attributes"u8, 5, ImGuiTableFlags.RowBg); + if (!table) + return; + + ImUtf8.TableSetupColumn("#"u8, ImGuiTableColumnFlags.WidthFixed, 25 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); + ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("Attributes"u8, ImGuiTableColumnFlags.WidthStretch); + + ImGui.TableHeadersRow(); + + var disabledColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); + for (var i = 0; i < human.AsHuman->SlotCount; ++i) + { + ImUtf8.DrawTableColumn($"{(uint)i:D2}"); + ImUtf8.DrawTableColumn(((HumanSlot)i).ToName()); + + ImGui.TableNextColumn(); + var model = human.AsHuman->Models[i]; + Penumbra.Dynamis.DrawPointer((nint)model); + if (model is not null) + { + var mask = model->EnabledAttributeIndexMask; + ImUtf8.DrawTableColumn($"{mask:X8}"); + ImGui.TableNextColumn(); + foreach (var (attribute, idx) in model->ModelResourceHandle->Attributes) + { + var disabled = (mask & (1u << idx)) is 0; + using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); + ImUtf8.Text(attribute.AsSpan()); + ImGui.SameLine(0, 0); + ImUtf8.Text(", "u8); + if (idx % 8 < 7) + ImGui.SameLine(0, 0); + } + } + else + { + ImGui.TableNextColumn(); + ImGui.TableNextColumn(); + } + } + } } diff --git a/schemas/structs/manipulation.json b/schemas/structs/manipulation.json index 55fc5cad..81f2cef3 100644 --- a/schemas/structs/manipulation.json +++ b/schemas/structs/manipulation.json @@ -3,7 +3,7 @@ "type": "object", "properties": { "Type": { - "enum": [ "Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch", "Shp" ] + "enum": [ "Unknown", "Imc", "Eqdp", "Eqp", "Est", "Gmp", "Rsp", "GlobalEqp", "Atch", "Shp", "Atr" ] }, "Manipulation": { "type": "object" @@ -100,6 +100,16 @@ "$ref": "meta_shp.json" } } + }, + { + "properties": { + "Type": { + "const": "Atr" + }, + "Manipulation": { + "$ref": "meta_atr.json" + } + } } ] } diff --git a/schemas/structs/meta_atr.json b/schemas/structs/meta_atr.json new file mode 100644 index 00000000..479d4127 --- /dev/null +++ b/schemas/structs/meta_atr.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "Entry": { + "type": "boolean" + }, + "Slot": { + "$ref": "meta_enums.json#HumanSlot" + }, + "Id": { + "$ref": "meta_enums.json#U16" + }, + "Attribute": { + "type": "string", + "minLength": 5, + "maxLength": 30, + "pattern": "^atrx_" + }, + "GenderRaceCondition": { + "enum": [ 0, 101, 201, 301, 401, 501, 601, 701, 801, 901, 1001, 1101, 1201, 1301, 1401, 1501, 1601, 1701, 1801 ] + } + }, + "required": [ + "Attribute" + ] +} diff --git a/schemas/structs/meta_shp.json b/schemas/structs/meta_shp.json index 851842a4..cb7fd0ec 100644 --- a/schemas/structs/meta_shp.json +++ b/schemas/structs/meta_shp.json @@ -19,6 +19,9 @@ }, "ConnectorCondition": { "$ref": "meta_enums.json#ShapeConnectorCondition" + }, + "GenderRaceCondition": { + "enum": [ 0, 101, 201, 301, 401, 501, 601, 701, 801, 901, 1001, 1101, 1201, 1301, 1401, 1501, 1601, 1701, 1801 ] } }, "required": [ From f5db888bbdb1e5193086027daf3f99da95636c33 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 21 May 2025 13:49:29 +0000 Subject: [PATCH 1220/1381] [CI] Updating repo.json for testing_1.3.6.13 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 0413b876..3e2a9d2c 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.12", + "TestingAssemblyVersion": "1.3.6.13", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.12/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.13/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 507b0a5aee46b0c7a62e2a3a8ba997a0dbc4944e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 21 May 2025 18:07:12 +0200 Subject: [PATCH 1221/1381] Slight description update. --- Penumbra/UI/Tabs/SettingsTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index cb22b54a..4bbdf2a9 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -761,7 +761,7 @@ public class SettingsTab : ITab, IUiService "Normally, metadata changes that equal their default values, which are sometimes exported by TexTools, are discarded. " + "Toggle this to keep them, for example if an option in a mod is supposed to disable a metadata change from a prior option.", _config.KeepDefaultMetaChanges, v => _config.KeepDefaultMetaChanges = v); - Checkbox("Enable Custom Shape Support", "Penumbra will allow for custom shape keys for modded models to be considered and combined.", + Checkbox("Enable Custom Shape and Attribute Support", "Penumbra will allow for custom shape keys and attributes for modded models to be considered and combined.", _config.EnableCustomShapes, _attributeHook.SetState); DrawWaitForPluginsReflection(); DrawEnableHttpApiBox(); From ac4c75d3c36f658c054d2ef508d909f94f975e39 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 22 May 2025 11:13:42 +0200 Subject: [PATCH 1222/1381] Fix not updating meta count correctly. --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index 23eaec76..ede062ae 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -596,6 +596,7 @@ public class MetaDictionary + _data!.Gmp.Count + _data!.Atch.Count + _data!.Shp.Count + + _data!.Atr.Count + _data!.Count; } From 400d7d0bea0a611be2071d56236ba3745828f4ab Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 22 May 2025 11:13:58 +0200 Subject: [PATCH 1223/1381] Slight improvements. --- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 12 ++++++------ Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 10 ++++++++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index 3f19da5e..aa3d9172 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -165,7 +165,7 @@ public partial class ModEditWindow private void AddFromClipboardButton() { - if (ImGui.Button("Add from Clipboard")) + if (ImUtf8.Button("Add from Clipboard"u8)) { var clipboard = ImGuiUtil.GetClipboardText(); @@ -176,13 +176,13 @@ public partial class ModEditWindow } } - ImGuiUtil.HoverTooltip( - "Try to add meta manipulations currently stored in the clipboard to the current manipulations.\nOverwrites already existing manipulations."); + ImUtf8.HoverTooltip( + "Try to add meta manipulations currently stored in the clipboard to the current manipulations.\nOverwrites already existing manipulations."u8); } private void SetFromClipboardButton() { - if (ImGui.Button("Set from Clipboard")) + if (ImUtf8.Button("Set from Clipboard"u8)) { var clipboard = ImGuiUtil.GetClipboardText(); if (MetaApi.ConvertManips(clipboard, out var manips, out _)) @@ -192,7 +192,7 @@ public partial class ModEditWindow } } - ImGuiUtil.HoverTooltip( - "Try to set the current meta manipulations to the set currently stored in the clipboard.\nRemoves all other manipulations."); + ImUtf8.HoverTooltip( + "Try to set the current meta manipulations to the set currently stored in the clipboard.\nRemoves all other manipulations."u8); } } diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 9290e52d..3180a212 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -159,7 +159,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (!treeNode2) return; - using var table = ImUtf8.Table("##shapes"u8, 5, ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##shapes"u8, 6, ImGuiTableFlags.RowBg); if (!table) return; @@ -167,6 +167,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("Count"u8, ImGuiTableColumnFlags.WidthFixed, 30 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Shapes"u8, ImGuiTableColumnFlags.WidthStretch); ImGui.TableHeadersRow(); @@ -184,6 +185,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { var mask = model->EnabledShapeKeyIndexMask; ImUtf8.DrawTableColumn($"{mask:X8}"); + ImUtf8.DrawTableColumn($"{model->ModelResourceHandle->Shapes.Count}"); ImGui.TableNextColumn(); foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) { @@ -200,6 +202,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { ImGui.TableNextColumn(); ImGui.TableNextColumn(); + ImGui.TableNextColumn(); } } } @@ -210,7 +213,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (!treeNode2) return; - using var table = ImUtf8.Table("##attributes"u8, 5, ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##attributes"u8, 6, ImGuiTableFlags.RowBg); if (!table) return; @@ -218,6 +221,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("Count"u8, ImGuiTableColumnFlags.WidthFixed, 30 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Attributes"u8, ImGuiTableColumnFlags.WidthStretch); ImGui.TableHeadersRow(); @@ -235,6 +239,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { var mask = model->EnabledAttributeIndexMask; ImUtf8.DrawTableColumn($"{mask:X8}"); + ImUtf8.DrawTableColumn($"{model->ModelResourceHandle->Attributes.Count}"); ImGui.TableNextColumn(); foreach (var (attribute, idx) in model->ModelResourceHandle->Attributes) { @@ -251,6 +256,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { ImGui.TableNextColumn(); ImGui.TableNextColumn(); + ImGui.TableNextColumn(); } } } From bc4f88aee9e91b299a828e18b1196c6562df13e8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 22 May 2025 11:14:17 +0200 Subject: [PATCH 1224/1381] Fix shape/attribute mask stupidity. --- Penumbra/Meta/ShapeAttributeManager.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Meta/ShapeAttributeManager.cs b/Penumbra/Meta/ShapeAttributeManager.cs index c6800141..e9c9c169 100644 --- a/Penumbra/Meta/ShapeAttributeManager.cs +++ b/Penumbra/Meta/ShapeAttributeManager.cs @@ -75,7 +75,7 @@ public unsafe class ShapeAttributeManager : IRequiredService, IDisposable { // Mask out custom attributes if they are disabled. Attributes are enabled by default. if (attributeCache.ShouldBeDisabled(attributeString, _modelIndex, _ids[_modelIndex.ToIndex()], _genderRace)) - _model->EnabledAttributeIndexMask &= (ushort)~(1 << index); + _model->EnabledAttributeIndexMask &= ~(1u << index); } else { @@ -95,7 +95,7 @@ public unsafe class ShapeAttributeManager : IRequiredService, IDisposable _temporaryShapes[_slotIndex].TryAdd(shapeString, index); // Add custom shapes if they are enabled. Shapes are disabled by default. if (shapeCache.ShouldBeEnabled(shapeString, _modelIndex, _ids[_modelIndex.ToIndex()], _genderRace)) - _model->EnabledShapeKeyIndexMask |= (ushort)(1 << index); + _model->EnabledShapeKeyIndexMask |= 1u << index; } else { From 9e7c30455625e9296702f461a7bf644a10af934a Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 22 May 2025 09:16:22 +0000 Subject: [PATCH 1225/1381] [CI] Updating repo.json for testing_1.3.6.14 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 3e2a9d2c..8b262136 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.13", + "TestingAssemblyVersion": "1.3.6.14", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.13/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.14/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 1bdbfe22c1f7b576cdb25bd775fa437ded0db559 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 23 May 2025 10:50:04 +0200 Subject: [PATCH 1226/1381] Update Libraries. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 9aeda9a8..421874a1 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9aeda9a892d9b971e32b10db21a8daf9c0b9ee53 +Subproject commit 421874a12540b7f8c1279dcc6a92e895a94d2fbc diff --git a/Penumbra.GameData b/Penumbra.GameData index bb3b462b..14b3641f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit bb3b462bbc5bc2a598c1ad8c372b0cb255551fe1 +Subproject commit 14b3641f0fb520cb829ceb50fa7cb31255a1da4e From 08c91248583bdd07f98968f66de0a57bc1a58dea Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 23 May 2025 11:29:52 +0200 Subject: [PATCH 1227/1381] Fix issue with shapes/attributes not checking the groups correctly. --- .../Cache/ShapeAttributeHashSet.cs | 70 +++++++++++-------- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 11 +-- 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs index f1fc7127..74691e41 100644 --- a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs +++ b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs @@ -21,43 +21,39 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI private readonly BitArray _allIds = new((ShapeAttributeManager.ModelSlotSize + 1) * GenderRaceValues.Count); - public bool this[HumanSlot slot] - => slot is HumanSlot.Unknown ? All : _allIds[(int)slot * GenderRaceIndices.Count]; - - public bool this[GenderRace genderRace] - => GenderRaceIndices.TryGetValue(genderRace, out var index) - && _allIds[ShapeAttributeManager.ModelSlotSize * GenderRaceIndices.Count + index]; - - public bool this[HumanSlot slot, GenderRace genderRace] + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private bool CheckGroups(HumanSlot slot, GenderRace genderRace) { - get - { - if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) - return false; + if (All || this[slot]) + return true; - if (_allIds[ShapeAttributeManager.ModelSlotSize * GenderRaceIndices.Count + index]) - return true; + if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) + return false; - return _allIds[(int)slot * GenderRaceIndices.Count + index]; - } - set - { - if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) - return; + if (_allIds[ToIndex(HumanSlot.Unknown, index)]) + return true; - var genderRaceCount = GenderRaceValues.Count; - if (slot is HumanSlot.Unknown) - _allIds[ShapeAttributeManager.ModelSlotSize * genderRaceCount + index] = value; - else - _allIds[(int)slot * genderRaceCount + index] = value; - } + return _allIds[ToIndex(slot, index)]; } + public bool this[HumanSlot slot] + => _allIds[ToIndex(slot, 0)]; + + public bool this[GenderRace genderRace] + => ToIndex(HumanSlot.Unknown, genderRace, out var index) && _allIds[index]; + + public bool this[HumanSlot slot, GenderRace genderRace] + => ToIndex(slot, genderRace, out var index) && _allIds[index]; + public bool All - => _allIds[ShapeAttributeManager.ModelSlotSize * GenderRaceIndices.Count]; + => _allIds[AllIndex]; + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static int ToIndex(HumanSlot slot, int genderRaceIndex) + => slot is HumanSlot.Unknown ? genderRaceIndex + AllIndex : genderRaceIndex + (int)slot * GenderRaceValues.Count; public bool Contains(HumanSlot slot, PrimaryId id, GenderRace genderRace) - => All || this[slot, genderRace] || ContainsEntry(slot, id, genderRace); + => CheckGroups(slot, genderRace) || ContainsEntry(slot, id, genderRace); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private bool ContainsEntry(HumanSlot slot, PrimaryId id, GenderRace genderRace) @@ -72,9 +68,9 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI if (!id.HasValue) { - var slotIndex = slot is HumanSlot.Unknown ? ShapeAttributeManager.ModelSlotSize : (int)slot; - var old = _allIds[slotIndex * GenderRaceIndices.Count + index]; - _allIds[slotIndex * GenderRaceIndices.Count + index] = value; + var slotIndex = ToIndex(slot, index); + var old = _allIds[slotIndex]; + _allIds[slotIndex] = value; return old != value; } @@ -120,4 +116,16 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI public bool IsEmpty => !_allIds.HasAnySet() && Count is 0; + + private static readonly int AllIndex = ShapeAttributeManager.ModelSlotSize * GenderRaceValues.Count; + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool ToIndex(HumanSlot slot, GenderRace genderRace, out int index) + { + if (!GenderRaceIndices.TryGetValue(genderRace, out index)) + return false; + + index = ToIndex(slot, index); + return true; + } } diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 3180a212..fd37bf35 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -1,6 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; using ImGuiNET; +using OtterGui.Extensions; using OtterGui.Services; using OtterGui.Text; using Penumbra.Collections.Cache; @@ -167,7 +168,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); - ImUtf8.TableSetupColumn("Count"u8, ImGuiTableColumnFlags.WidthFixed, 30 * ImUtf8.GlobalScale); + ImUtf8.TableSetupColumn("Count"u8, ImGuiTableColumnFlags.WidthFixed, 30 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Shapes"u8, ImGuiTableColumnFlags.WidthStretch); ImGui.TableHeadersRow(); @@ -187,9 +188,9 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.DrawTableColumn($"{mask:X8}"); ImUtf8.DrawTableColumn($"{model->ModelResourceHandle->Shapes.Count}"); ImGui.TableNextColumn(); - foreach (var (shape, idx) in model->ModelResourceHandle->Shapes) + foreach (var ((shape, flag), idx) in model->ModelResourceHandle->Shapes.WithIndex()) { - var disabled = (mask & (1u << idx)) is 0; + var disabled = (mask & (1u << flag)) is 0; using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); ImUtf8.Text(shape.AsSpan()); ImGui.SameLine(0, 0); @@ -241,9 +242,9 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.DrawTableColumn($"{mask:X8}"); ImUtf8.DrawTableColumn($"{model->ModelResourceHandle->Attributes.Count}"); ImGui.TableNextColumn(); - foreach (var (attribute, idx) in model->ModelResourceHandle->Attributes) + foreach (var ((attribute, flag), idx) in model->ModelResourceHandle->Attributes.WithIndex()) { - var disabled = (mask & (1u << idx)) is 0; + var disabled = (mask & (1u << flag)) is 0; using var color = ImRaii.PushColor(ImGuiCol.Text, disabledColor, disabled); ImUtf8.Text(attribute.AsSpan()); ImGui.SameLine(0, 0); From ccc2c1fd4c9a226758dbb65d1330ae844fe21a80 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 23 May 2025 11:30:10 +0200 Subject: [PATCH 1228/1381] Fix missing other option notifications for shp/atr. --- Penumbra/Mods/Editor/ModMetaEditor.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Penumbra/Mods/Editor/ModMetaEditor.cs b/Penumbra/Mods/Editor/ModMetaEditor.cs index 050dab51..b4db457d 100644 --- a/Penumbra/Mods/Editor/ModMetaEditor.cs +++ b/Penumbra/Mods/Editor/ModMetaEditor.cs @@ -64,6 +64,8 @@ public class ModMetaEditor( OtherData[MetaManipulationType.Est].Add(name, option.Manipulations.GetCount(MetaManipulationType.Est)); OtherData[MetaManipulationType.Rsp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Rsp)); OtherData[MetaManipulationType.Atch].Add(name, option.Manipulations.GetCount(MetaManipulationType.Atch)); + OtherData[MetaManipulationType.Shp].Add(name, option.Manipulations.GetCount(MetaManipulationType.Shp)); + OtherData[MetaManipulationType.Atr].Add(name, option.Manipulations.GetCount(MetaManipulationType.Atr)); OtherData[MetaManipulationType.GlobalEqp].Add(name, option.Manipulations.GetCount(MetaManipulationType.GlobalEqp)); } From cd56163b1b75132b8892e462e1d36225a4a7d79c Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 23 May 2025 09:32:11 +0000 Subject: [PATCH 1229/1381] [CI] Updating repo.json for testing_1.3.6.15 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 8b262136..9a41e09b 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.14", + "TestingAssemblyVersion": "1.3.6.15", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.14/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.15/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 82fc334be7c45921102d621a0dfee6ac8b93bc39 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 23 May 2025 15:17:13 +0200 Subject: [PATCH 1230/1381] Use dynamis for some pointers. --- Penumbra/UI/Tabs/Debug/DebugTab.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index b4fa3b9f..76df5acc 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -1075,14 +1075,14 @@ public class DebugTab : Window, ITab, IUiService ImGui.TableNextColumn(); ImGui.TextUnformatted($"Slot {i}"); ImGui.TableNextColumn(); - ImGui.TextUnformatted(imc == null ? "NULL" : $"0x{(ulong)imc:X}"); + Penumbra.Dynamis.DrawPointer((nint)imc); ImGui.TableNextColumn(); if (imc != null) UiHelpers.Text(imc); var mdl = (RenderModel*)model->Models[i]; ImGui.TableNextColumn(); - ImGui.TextUnformatted(mdl == null ? "NULL" : $"0x{(ulong)mdl:X}"); + Penumbra.Dynamis.DrawPointer((nint)mdl); if (mdl == null || mdl->ResourceHandle == null || mdl->ResourceHandle->Category != ResourceCategory.Chara) continue; From ebe45c6a47eeea7cab7e7db38d2da90bb875304b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 27 May 2025 11:33:10 +0200 Subject: [PATCH 1231/1381] Update Lib. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 421874a1..cee50c3f 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 421874a12540b7f8c1279dcc6a92e895a94d2fbc +Subproject commit cee50c3fe97a03ca7445c81de651b609620da526 From 2c115eda9426e53ffbcd06b494077b5863b17f3d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 May 2025 13:54:23 +0200 Subject: [PATCH 1232/1381] Slightly improve error message when importing wrongly named atch files. --- .../UI/AdvancedWindow/Meta/AtchMetaDrawer.cs | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs index 5bc70fc3..5b6d585a 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs @@ -34,6 +34,7 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer private AtchFile? _currentBaseAtchFile; private AtchPoint? _currentBaseAtchPoint; private readonly AtchPointCombo _combo; + private string _fileImport = string.Empty; public AtchMetaDrawer(ModMetaEditor editor, MetaFileManager metaFiles) : base(editor, metaFiles) @@ -48,6 +49,8 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer => obj.ToName(); } + private sealed class RaceCodeException(string filePath) : Exception($"Could not identify race code from path {filePath}."); + public void ImportFile(string filePath) { try @@ -57,14 +60,15 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer var gr = Parser.ParseRaceCode(filePath); if (gr is GenderRace.Unknown) - throw new Exception($"Could not identify race code from path {filePath}."); - var text = File.ReadAllBytes(filePath); - var file = new AtchFile(text); + throw new RaceCodeException(filePath); + + var text = File.ReadAllBytes(filePath); + var file = new AtchFile(text); foreach (var point in file.Points) { foreach (var (entry, index) in point.Entries.WithIndex()) { - var identifier = new AtchIdentifier(point.Type, gr, (ushort) index); + var identifier = new AtchIdentifier(point.Type, gr, (ushort)index); var defaultValue = AtchCache.GetDefault(MetaFiles, identifier); if (defaultValue == null) continue; @@ -76,6 +80,12 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer } } } + catch (RaceCodeException ex) + { + Penumbra.Messager.AddMessage(new Notification(ex, "The imported .atch file does not contain a race code (cXXXX) in its name.", + "Could not import .atch file:", + NotificationType.Warning)); + } catch (Exception ex) { Penumbra.Messager.AddMessage(new Notification(ex, "Unable to import .atch file.", "Could not import .atch file:", @@ -157,12 +167,12 @@ public sealed class AtchMetaDrawer : MetaDrawer, ISer private void UpdateFile() { - _currentBaseAtchFile = MetaFiles.AtchManager.AtchFileBase[Identifier.GenderRace]; + _currentBaseAtchFile = MetaFiles.AtchManager.AtchFileBase[Identifier.GenderRace]; _currentBaseAtchPoint = _currentBaseAtchFile.GetPoint(Identifier.Type); if (_currentBaseAtchPoint == null) { _currentBaseAtchPoint = _currentBaseAtchFile.Points.First(); - Identifier = Identifier with { Type = _currentBaseAtchPoint.Type }; + Identifier = Identifier with { Type = _currentBaseAtchPoint.Type }; } if (Identifier.EntryIndex >= _currentBaseAtchPoint.Entries.Length) From 5e985f4a84b45706373db655bcc4472917d4d10a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 28 May 2025 13:54:42 +0200 Subject: [PATCH 1233/1381] 1.4.0.0 --- Penumbra/UI/Changelog.cs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 5e1612eb..c1f7a1e6 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -61,10 +61,49 @@ public class PenumbraChangelog : IUiService Add1_3_5_0(Changelog); Add1_3_6_0(Changelog); Add1_3_6_4(Changelog); + Add1_4_0_0(Changelog); } #region Changelogs + private static void Add1_4_0_0(Changelog log) + => log.NextVersion("Version 1.4.0.0") + .RegisterHighlight("Added two types of new Meta Changes, SHP and ATR (Thanks Karou!).") + .RegisterEntry("Those allow mod creators to toggle custom shape keys and attributes for models on and off, respectively.", 1) + .RegisterEntry("Custom shape keys need to have the format 'shpx_*' and custom attributes need 'atrx_*'.", 1) + .RegisterHighlight( + "Shapes of the following formats will automatically be toggled on if both relevant slots contain the same shape key:", 1) + .RegisterEntry("'shpx_wa_*', for the waist seam between the body and leg slot,", 2) + .RegisterEntry("'shpx_wr_*', for the wrist seams between the body and hands slot,", 2) + .RegisterEntry("'shpx_an_*', for the ankle seams between the leg and feet slot.", 2) + .RegisterEntry( + "Custom shape key and attributes can be turned off in the advanced settings section for the moment, but this is not recommended.", + 1) + .RegisterHighlight("The mod selector width is now draggable within certain restrictions that depend on the total window width.") + .RegisterEntry("The current behavior may not be final, let me know if you have any comments.", 1) + .RegisterEntry("Improved the naming of NPCs for identifiers by using Haselnussbombers new naming functionality (Thanks Hasel!).") + .RegisterEntry("Added global EQP entries to always hide Au Ra horns, Viera ears, or Miqo'te ears, respectively.") + .RegisterEntry("This will leave holes in the heads of the respective race if not modded in some way.", 1) + .RegisterEntry("Added a filter for mods that have temporary settings in the mod selector panel (Thanks Caraxi).") + .RegisterEntry("Made the checkbox for toggling Temporary Settings Mode in the mod tab more visible.") + .RegisterEntry("Improved the option select combo in advanced editing.") + .RegisterEntry("Fixed some issues with item identification for EST changes.") + .RegisterEntry("Fixed the sizing of the mod panel being off by 1 pixel sometimes.") + .RegisterEntry("Fixed an issue with redrawing while in GPose when other plugins broke some assumptions about the game state.") + .RegisterEntry("Fixed a clipping issue within the Meta Manipulations tab in advanced editing.") + .RegisterEntry("Fixed an issue with empty and temporary settings.") + .RegisterHighlight( + "In the Item Swap tab, items changed by this mod are now sorted and highlighted before items changed in the current collection before other items for the source, and inversely for the target. (1.3.6.8)") + .RegisterHighlight( + "Default-valued meta edits should now be kept on import and only removed when the option to keep them is not set AND no other options in the mod edit the same entry. (1.3.6.8)") + .RegisterEntry("Added a right-click context menu on file redirections to copy the full file path. (1.3.6.8)") + .RegisterEntry( + "Added a right-click context menu on the mod export button to open the backup directory in your file explorer. (1.3.6.8)") + .RegisterEntry("Fixed some issues when redrawing characters from other plugins. (1.3.6.8)") + .RegisterEntry( + "Added a modifier key separate from the delete modifier key that is used for less important key-checks, specifically toggling incognito mode. (1.3.6.7)") + .RegisterEntry("Fixed some issues with the Material Editor (Thanks Ny). (1.3.6.6)"); + private static void Add1_3_6_4(Changelog log) => log.NextVersion("Version 1.3.6.4") .RegisterEntry("The material editor should be functional again."); From 1551d9b6f3fa35ffde863e5442eab23ea52c6e35 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 28 May 2025 11:56:49 +0000 Subject: [PATCH 1234/1381] [CI] Updating repo.json for 1.4.0.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 9a41e09b..94020c96 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.3.6.8", - "TestingAssemblyVersion": "1.3.6.15", + "AssemblyVersion": "1.4.0.0", + "TestingAssemblyVersion": "1.4.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.3.6.15/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.3.6.8/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From f2927290f52ceebde1a60edd2f5b8b25cf56e186 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 30 May 2025 14:35:13 +0200 Subject: [PATCH 1235/1381] Fix exceptions when unsubscribing during event invocation. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index cee50c3f..17a3ee57 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit cee50c3fe97a03ca7445c81de651b609620da526 +Subproject commit 17a3ee5711ca30eb7f5b393dfb8136f0bce49b2b From ff2a9f95c46a7500528127aaca0c413653df706e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 30 May 2025 14:36:07 +0200 Subject: [PATCH 1236/1381] Fix Atr and Shp not being transmitted via Mare, add improved compression but don't use it yet. --- Penumbra/Api/Api/MetaApi.cs | 232 ++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) diff --git a/Penumbra/Api/Api/MetaApi.cs b/Penumbra/Api/Api/MetaApi.cs index 7c0cd5fc..5cffc811 100644 --- a/Penumbra/Api/Api/MetaApi.cs +++ b/Penumbra/Api/Api/MetaApi.cs @@ -66,6 +66,8 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver MetaDictionary.SerializeTo(array, cache.Rsp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); MetaDictionary.SerializeTo(array, cache.Gmp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); MetaDictionary.SerializeTo(array, cache.Atch.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Shp.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); + MetaDictionary.SerializeTo(array, cache.Atr.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.Entry))); } return Functions.ToCompressedBase64(array, 0); @@ -111,6 +113,8 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver } WriteCache(zipStream, cache.Atch); + WriteCache(zipStream, cache.Shp); + WriteCache(zipStream, cache.Atr); } } @@ -140,6 +144,86 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver } } + public const uint ImcKey = ((uint)'I' << 24) | ((uint)'M' << 16) | ((uint)'C' << 8); + public const uint EqpKey = ((uint)'E' << 24) | ((uint)'Q' << 16) | ((uint)'P' << 8); + public const uint EqdpKey = ((uint)'E' << 24) | ((uint)'Q' << 16) | ((uint)'D' << 8) | 'P'; + public const uint EstKey = ((uint)'E' << 24) | ((uint)'S' << 16) | ((uint)'T' << 8); + public const uint RspKey = ((uint)'R' << 24) | ((uint)'S' << 16) | ((uint)'P' << 8); + public const uint GmpKey = ((uint)'G' << 24) | ((uint)'M' << 16) | ((uint)'P' << 8); + public const uint GeqpKey = ((uint)'G' << 24) | ((uint)'E' << 16) | ((uint)'Q' << 8) | 'P'; + public const uint AtchKey = ((uint)'A' << 24) | ((uint)'T' << 16) | ((uint)'C' << 8) | 'H'; + public const uint ShpKey = ((uint)'S' << 24) | ((uint)'H' << 16) | ((uint)'P' << 8); + public const uint AtrKey = ((uint)'A' << 24) | ((uint)'T' << 16) | ((uint)'R' << 8); + + private static unsafe string CompressMetaManipulationsV2(ModCollection? collection) + { + using var ms = new MemoryStream(); + ms.Capacity = 1024; + using (var zipStream = new GZipStream(ms, CompressionMode.Compress, true)) + { + zipStream.Write((byte)2); + zipStream.Write("META0002"u8); + if (collection?.MetaCache is { } cache) + { + WriteCache(zipStream, cache.Imc, ImcKey); + WriteCache(zipStream, cache.Eqp, EqpKey); + WriteCache(zipStream, cache.Eqdp, EqdpKey); + WriteCache(zipStream, cache.Est, EstKey); + WriteCache(zipStream, cache.Rsp, RspKey); + WriteCache(zipStream, cache.Gmp, GmpKey); + cache.GlobalEqp.EnterReadLock(); + + try + { + if (cache.GlobalEqp.Count > 0) + { + zipStream.Write(GeqpKey); + zipStream.Write(cache.GlobalEqp.Count); + foreach (var (globalEqp, _) in cache.GlobalEqp) + zipStream.Write(new ReadOnlySpan(&globalEqp, sizeof(GlobalEqpManipulation))); + } + } + finally + { + cache.GlobalEqp.ExitReadLock(); + } + + WriteCache(zipStream, cache.Atch, AtchKey); + WriteCache(zipStream, cache.Shp, ShpKey); + WriteCache(zipStream, cache.Atr, AtrKey); + } + } + + ms.Flush(); + ms.Position = 0; + var data = ms.GetBuffer().AsSpan(0, (int)ms.Length); + return Convert.ToBase64String(data); + + void WriteCache(Stream stream, MetaCacheBase metaCache, uint label) + where TKey : unmanaged, IMetaIdentifier + where TValue : unmanaged + { + metaCache.EnterReadLock(); + try + { + if (metaCache.Count <= 0) + return; + + stream.Write(label); + stream.Write(metaCache.Count); + foreach (var (identifier, (_, value)) in metaCache) + { + stream.Write(identifier); + stream.Write(value); + } + } + finally + { + metaCache.ExitReadLock(); + } + } + } + /// /// Convert manipulations from a transmitted base64 string to actual manipulations. /// The empty string is treated as an empty set. @@ -170,6 +254,7 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver { case 0: return ConvertManipsV0(data, out manips); case 1: return ConvertManipsV1(data, out manips); + case 2: return ConvertManipsV2(data, out manips); default: Penumbra.Log.Debug($"Invalid version for manipulations: {version}."); manips = null; @@ -185,6 +270,131 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver } } + private static bool ConvertManipsV2(ReadOnlySpan data, [NotNullWhen(true)] out MetaDictionary? manips) + { + if (!data.StartsWith("META0002"u8)) + { + Penumbra.Log.Debug("Invalid manipulations of version 2, does not start with valid prefix."); + manips = null; + return false; + } + + manips = new MetaDictionary(); + var r = new SpanBinaryReader(data[8..]); + while (r.Remaining > 4) + { + var prefix = r.ReadUInt32(); + var count = r.Remaining > 4 ? r.ReadInt32() : 0; + if (count is 0) + continue; + + switch (prefix) + { + case ImcKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case EqpKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case EqdpKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case EstKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case RspKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case GmpKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case GeqpKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier)) + return false; + } + + break; + case AtchKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case ShpKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + case AtrKey: + for (var i = 0; i < count; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + break; + } + } + + return true; + } + private static bool ConvertManipsV1(ReadOnlySpan data, [NotNullWhen(true)] out MetaDictionary? manips) { if (!data.StartsWith("META0001"u8)) @@ -269,6 +479,28 @@ public class MetaApi(IFramework framework, CollectionResolver collectionResolver if (!identifier.Validate() || !manips.TryAdd(identifier, value)) return false; } + + // Shp and Atr was added later + if (r.Position < r.Count) + { + var shpCount = r.ReadInt32(); + for (var i = 0; i < shpCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + + var atrCount = r.ReadInt32(); + for (var i = 0; i < atrCount; ++i) + { + var identifier = r.Read(); + var value = r.Read(); + if (!identifier.Validate() || !manips.TryAdd(identifier, value)) + return false; + } + } } return true; From 74bd1cf911fdd906b16c3bce1acc38716bf14efe Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 30 May 2025 14:36:33 +0200 Subject: [PATCH 1237/1381] Fix checking the flags for all races and genders for specific IDs in shapes/attributes. --- Penumbra/Collections/Cache/ShapeAttributeHashSet.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs index 74691e41..9670928f 100644 --- a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs +++ b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs @@ -59,7 +59,7 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI private bool ContainsEntry(HumanSlot slot, PrimaryId id, GenderRace genderRace) => GenderRaceIndices.TryGetValue(genderRace, out var index) && TryGetValue((slot, id), out var flags) - && (flags & (1ul << index)) is not 0; + && ((flags & 1ul) is not 0 || (flags & (1ul << index)) is not 0); public bool TrySet(HumanSlot slot, PrimaryId? id, GenderRace genderRace, bool value) { From 75f4e66dbf5da8984e2cbe825fb8ba8d8a7e0652 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 30 May 2025 12:38:32 +0000 Subject: [PATCH 1238/1381] [CI] Updating repo.json for 1.4.0.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 94020c96..7cdc7bbb 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.4.0.0", - "TestingAssemblyVersion": "1.4.0.0", + "AssemblyVersion": "1.4.0.1", + "TestingAssemblyVersion": "1.4.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From b48c4f440acdc02a32c9518023269e1524a8e191 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 1 Jun 2025 13:04:01 +0200 Subject: [PATCH 1239/1381] Make attributes and shapes completely toggleable. --- Penumbra/Collections/Cache/AtrCache.cs | 27 ++- .../Cache/ShapeAttributeHashSet.cs | 171 +++++++++++------- Penumbra/Collections/Cache/ShpCache.cs | 31 +++- Penumbra/Meta/ShapeAttributeManager.cs | 37 ++-- Penumbra/UI/ConfigWindow.cs | 12 +- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 123 +++++++------ 6 files changed, 245 insertions(+), 156 deletions(-) diff --git a/Penumbra/Collections/Cache/AtrCache.cs b/Penumbra/Collections/Cache/AtrCache.cs index 757ddaa2..b017da32 100644 --- a/Penumbra/Collections/Cache/AtrCache.cs +++ b/Penumbra/Collections/Cache/AtrCache.cs @@ -8,10 +8,12 @@ namespace Penumbra.Collections.Cache; public sealed class AtrCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { public bool ShouldBeDisabled(in ShapeAttributeString attribute, HumanSlot slot, PrimaryId id, GenderRace genderRace) - => DisabledCount > 0 && _atrData.TryGetValue(attribute, out var value) && value.Contains(slot, id, genderRace); + => DisabledCount > 0 && _atrData.TryGetValue(attribute, out var value) && value.CheckEntry(slot, id, genderRace) is false; + public int EnabledCount { get; private set; } public int DisabledCount { get; private set; } + internal IReadOnlyDictionary Data => _atrData; @@ -21,24 +23,28 @@ public sealed class AtrCache(MetaFileManager manager, ModCollection collection) { Clear(); _atrData.Clear(); + DisabledCount = 0; + EnabledCount = 0; } protected override void Dispose(bool _) - => Clear(); + => Reset(); protected override void ApplyModInternal(AtrIdentifier identifier, AtrEntry entry) { if (!_atrData.TryGetValue(identifier.Attribute, out var value)) { - if (entry.Value) - return; - value = []; _atrData.Add(identifier.Attribute, value); } - if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, !entry.Value)) - ++DisabledCount; + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, entry.Value, out _)) + { + if (entry.Value) + ++EnabledCount; + else + ++DisabledCount; + } } protected override void RevertModInternal(AtrIdentifier identifier) @@ -46,9 +52,12 @@ public sealed class AtrCache(MetaFileManager manager, ModCollection collection) if (!_atrData.TryGetValue(identifier.Attribute, out var value)) return; - if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, false)) + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, null, out var which)) { - --DisabledCount; + if (which) + --EnabledCount; + else + --DisabledCount; if (value.IsEmpty) _atrData.Remove(identifier.Attribute); } diff --git a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs index 9670928f..e50ceaa2 100644 --- a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs +++ b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs @@ -19,93 +19,126 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI public static readonly FrozenDictionary GenderRaceIndices = GenderRaceValues.WithIndex().ToFrozenDictionary(p => p.Value, p => p.Index); - private readonly BitArray _allIds = new((ShapeAttributeManager.ModelSlotSize + 1) * GenderRaceValues.Count); + private readonly BitArray _allIds = new(2 * (ShapeAttributeManager.ModelSlotSize + 1) * GenderRaceValues.Count); + + public bool? this[HumanSlot slot] + => AllCheck(ToIndex(slot, 0)); + + public bool? this[GenderRace genderRace] + => ToIndex(HumanSlot.Unknown, genderRace, out var index) ? AllCheck(index) : null; + + public bool? this[HumanSlot slot, GenderRace genderRace] + => ToIndex(slot, genderRace, out var index) ? AllCheck(index) : null; + + public bool? All + => Convert(_allIds[2 * AllIndex], _allIds[2 * AllIndex + 1]); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private bool CheckGroups(HumanSlot slot, GenderRace genderRace) - { - if (All || this[slot]) - return true; - - if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) - return false; - - if (_allIds[ToIndex(HumanSlot.Unknown, index)]) - return true; - - return _allIds[ToIndex(slot, index)]; - } - - public bool this[HumanSlot slot] - => _allIds[ToIndex(slot, 0)]; - - public bool this[GenderRace genderRace] - => ToIndex(HumanSlot.Unknown, genderRace, out var index) && _allIds[index]; - - public bool this[HumanSlot slot, GenderRace genderRace] - => ToIndex(slot, genderRace, out var index) && _allIds[index]; - - public bool All - => _allIds[AllIndex]; + private bool? AllCheck(int idx) + => Convert(_allIds[idx], _allIds[idx + 1]); [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private static int ToIndex(HumanSlot slot, int genderRaceIndex) - => slot is HumanSlot.Unknown ? genderRaceIndex + AllIndex : genderRaceIndex + (int)slot * GenderRaceValues.Count; + => 2 * (slot is HumanSlot.Unknown ? genderRaceIndex + AllIndex : genderRaceIndex + (int)slot * GenderRaceValues.Count); - public bool Contains(HumanSlot slot, PrimaryId id, GenderRace genderRace) - => CheckGroups(slot, genderRace) || ContainsEntry(slot, id, genderRace); - - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] - private bool ContainsEntry(HumanSlot slot, PrimaryId id, GenderRace genderRace) - => GenderRaceIndices.TryGetValue(genderRace, out var index) - && TryGetValue((slot, id), out var flags) - && ((flags & 1ul) is not 0 || (flags & (1ul << index)) is not 0); - - public bool TrySet(HumanSlot slot, PrimaryId? id, GenderRace genderRace, bool value) + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + public bool? CheckEntry(HumanSlot slot, PrimaryId id, GenderRace genderRace) { + if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) + return null; + + // Check for specific ID. + if (TryGetValue((slot, id), out var flags)) + { + // Check completely specified entry. + if (Convert(flags, 2 * index) is { } specified) + return specified; + + // Check any gender / race. + if (Convert(flags, 0) is { } anyGr) + return anyGr; + } + + // Check for specified gender / race and slot, but no ID. + if (AllCheck(ToIndex(slot, index)) is { } noIdButGr) + return noIdButGr; + + // Check for specified gender / race but no slot or ID. + if (AllCheck(ToIndex(HumanSlot.Unknown, index)) is { } noSlotButGr) + return noSlotButGr; + + // Check for specified slot but no gender / race or ID. + if (AllCheck(ToIndex(slot, 0)) is { } noGrButSlot) + return noGrButSlot; + + return All; + } + + public bool TrySet(HumanSlot slot, PrimaryId? id, GenderRace genderRace, bool? value, out bool which) + { + which = false; if (!GenderRaceIndices.TryGetValue(genderRace, out var index)) return false; if (!id.HasValue) { var slotIndex = ToIndex(slot, index); - var old = _allIds[slotIndex]; - _allIds[slotIndex] = value; - return old != value; - } - - if (value) - { - if (TryGetValue((slot, id.Value), out var flags)) + var ret = false; + if (value is true) { - var newFlags = flags | (1ul << index); - if (newFlags == flags) - return false; + if (!_allIds[slotIndex]) + ret = true; + _allIds[slotIndex] = true; + _allIds[slotIndex + 1] = false; + } + else if (value is false) + { + if (!_allIds[slotIndex + 1]) + ret = true; + _allIds[slotIndex] = false; + _allIds[slotIndex + 1] = true; + } + else + { + if (_allIds[slotIndex]) + { + which = true; + ret = true; + } + else if (_allIds[slotIndex + 1]) + { + which = false; + ret = true; + } - this[(slot, id.Value)] = newFlags; - return true; + _allIds[slotIndex] = false; + _allIds[slotIndex + 1] = false; } - this[(slot, id.Value)] = 1ul << index; - return true; + return ret; } - else if (TryGetValue((slot, id.Value), out var flags)) + + if (TryGetValue((slot, id.Value), out var flags)) { - var newFlags = flags & ~(1ul << index); + var newFlags = value switch + { + true => (flags | (1ul << index)) & ~(1ul << (index + 1)), + false => (flags & ~(1ul << index)) | (1ul << (index + 1)), + _ => flags & ~(1ul << index) & ~(1ul << (index + 1)), + }; if (newFlags == flags) return false; - if (newFlags is 0) - { - Remove((slot, id.Value)); - return true; - } - this[(slot, id.Value)] = newFlags; + which = (flags & (1ul << index)) is not 0; return true; } - return false; + if (value is null) + return false; + + this[(slot, id.Value)] = 1ul << (index + (value.Value ? 0 : 1)); + return true; } public new void Clear() @@ -128,4 +161,20 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI index = ToIndex(slot, index); return true; } + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool? Convert(bool trueValue, bool falseValue) + => trueValue ? true : falseValue ? false : null; + + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private static bool? Convert(ulong mask, int idx) + { + mask >>= idx; + return (mask & 3) switch + { + 1 => true, + 2 => false, + _ => null, + }; + } } diff --git a/Penumbra/Collections/Cache/ShpCache.cs b/Penumbra/Collections/Cache/ShpCache.cs index 22547d25..d8c3a036 100644 --- a/Penumbra/Collections/Cache/ShpCache.cs +++ b/Penumbra/Collections/Cache/ShpCache.cs @@ -8,7 +8,10 @@ namespace Penumbra.Collections.Cache; public sealed class ShpCache(MetaFileManager manager, ModCollection collection) : MetaCacheBase(manager, collection) { public bool ShouldBeEnabled(in ShapeAttributeString shape, HumanSlot slot, PrimaryId id, GenderRace genderRace) - => EnabledCount > 0 && _shpData.TryGetValue(shape, out var value) && value.Contains(slot, id, genderRace); + => EnabledCount > 0 && _shpData.TryGetValue(shape, out var value) && value.CheckEntry(slot, id, genderRace) is true; + + public bool ShouldBeDisabled(in ShapeAttributeString shape, HumanSlot slot, PrimaryId id, GenderRace genderRace) + => DisabledCount > 0 && _shpData.TryGetValue(shape, out var value) && value.CheckEntry(slot, id, genderRace) is false; internal IReadOnlyDictionary State(ShapeConnectorCondition connector) => connector switch @@ -20,7 +23,8 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) _ => [], }; - public int EnabledCount { get; private set; } + public int EnabledCount { get; private set; } + public int DisabledCount { get; private set; } private readonly Dictionary _shpData = []; private readonly Dictionary _wristConnectors = []; @@ -34,10 +38,12 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) _wristConnectors.Clear(); _waistConnectors.Clear(); _ankleConnectors.Clear(); + EnabledCount = 0; + DisabledCount = 0; } protected override void Dispose(bool _) - => Clear(); + => Reset(); protected override void ApplyModInternal(ShpIdentifier identifier, ShpEntry entry) { @@ -55,15 +61,17 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) { if (!dict.TryGetValue(identifier.Shape, out var value)) { - if (!entry.Value) - return; - value = []; dict.Add(identifier.Shape, value); } - if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, entry.Value)) - ++EnabledCount; + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, entry.Value, out _)) + { + if (entry.Value) + ++EnabledCount; + else + ++DisabledCount; + } } } @@ -84,9 +92,12 @@ public sealed class ShpCache(MetaFileManager manager, ModCollection collection) if (!dict.TryGetValue(identifier.Shape, out var value)) return; - if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, false)) + if (value.TrySet(identifier.Slot, identifier.Id, identifier.GenderRaceCondition, null, out var which)) { - --EnabledCount; + if (which) + --EnabledCount; + else + --DisabledCount; if (value.IsEmpty) dict.Remove(identifier.Shape); } diff --git a/Penumbra/Meta/ShapeAttributeManager.cs b/Penumbra/Meta/ShapeAttributeManager.cs index e9c9c169..a742806f 100644 --- a/Penumbra/Meta/ShapeAttributeManager.cs +++ b/Penumbra/Meta/ShapeAttributeManager.cs @@ -106,46 +106,59 @@ public unsafe class ShapeAttributeManager : IRequiredService, IDisposable private void UpdateDefaultMasks(Model human, ShpCache cache) { + var genderRace = (GenderRace)human.AsHuman->RaceSexId; foreach (var (shape, topIndex) in _temporaryShapes[1]) { - if (shape.IsWrist() && _temporaryShapes[2].TryGetValue(shape, out var handIndex)) + if (shape.IsWrist() + && _temporaryShapes[2].TryGetValue(shape, out var handIndex) + && !cache.ShouldBeDisabled(shape, HumanSlot.Body, _ids[1], genderRace) + && !cache.ShouldBeDisabled(shape, HumanSlot.Hands, _ids[2], genderRace) + && human.AsHuman->Models[1] is not null + && human.AsHuman->Models[2] is not null) { human.AsHuman->Models[1]->EnabledShapeKeyIndexMask |= 1u << topIndex; human.AsHuman->Models[2]->EnabledShapeKeyIndexMask |= 1u << handIndex; - CheckCondition(cache.State(ShapeConnectorCondition.Wrists), HumanSlot.Body, HumanSlot.Hands, 1, 2); + CheckCondition(cache.State(ShapeConnectorCondition.Wrists), genderRace, HumanSlot.Body, HumanSlot.Hands, 1, 2); } - if (shape.IsWaist() && _temporaryShapes[3].TryGetValue(shape, out var legIndex)) + if (shape.IsWaist() + && _temporaryShapes[3].TryGetValue(shape, out var legIndex) + && !cache.ShouldBeDisabled(shape, HumanSlot.Body, _ids[1], genderRace) + && !cache.ShouldBeDisabled(shape, HumanSlot.Legs, _ids[3], genderRace) + && human.AsHuman->Models[1] is not null + && human.AsHuman->Models[3] is not null) { human.AsHuman->Models[1]->EnabledShapeKeyIndexMask |= 1u << topIndex; human.AsHuman->Models[3]->EnabledShapeKeyIndexMask |= 1u << legIndex; - CheckCondition(cache.State(ShapeConnectorCondition.Waist), HumanSlot.Body, HumanSlot.Legs, 1, 3); + CheckCondition(cache.State(ShapeConnectorCondition.Waist), genderRace, HumanSlot.Body, HumanSlot.Legs, 1, 3); } } foreach (var (shape, bottomIndex) in _temporaryShapes[3]) { - if (shape.IsAnkle() && _temporaryShapes[4].TryGetValue(shape, out var footIndex)) + if (shape.IsAnkle() + && _temporaryShapes[4].TryGetValue(shape, out var footIndex) + && !cache.ShouldBeDisabled(shape, HumanSlot.Legs, _ids[3], genderRace) + && !cache.ShouldBeDisabled(shape, HumanSlot.Feet, _ids[4], genderRace) + && human.AsHuman->Models[3] is not null + && human.AsHuman->Models[4] is not null) { human.AsHuman->Models[3]->EnabledShapeKeyIndexMask |= 1u << bottomIndex; human.AsHuman->Models[4]->EnabledShapeKeyIndexMask |= 1u << footIndex; - CheckCondition(cache.State(ShapeConnectorCondition.Ankles), HumanSlot.Legs, HumanSlot.Feet, 3, 4); + CheckCondition(cache.State(ShapeConnectorCondition.Ankles), genderRace, HumanSlot.Legs, HumanSlot.Feet, 3, 4); } } return; - void CheckCondition(IReadOnlyDictionary dict, HumanSlot slot1, + void CheckCondition(IReadOnlyDictionary dict, GenderRace genderRace, HumanSlot slot1, HumanSlot slot2, int idx1, int idx2) { - if (dict.Count is 0) - return; - foreach (var (shape, set) in dict) { - if (set.Contains(slot1, _ids[idx1], GenderRace.Unknown) && _temporaryShapes[idx1].TryGetValue(shape, out var index1)) + if (set.CheckEntry(slot1, _ids[idx1], genderRace) is true && _temporaryShapes[idx1].TryGetValue(shape, out var index1)) human.AsHuman->Models[idx1]->EnabledShapeKeyIndexMask |= 1u << index1; - if (set.Contains(slot2, _ids[idx2], GenderRace.Unknown) && _temporaryShapes[idx2].TryGetValue(shape, out var index2)) + if (set.CheckEntry(slot2, _ids[idx2], genderRace) is true && _temporaryShapes[idx2].TryGetValue(shape, out var index2)) human.AsHuman->Models[idx2]->EnabledShapeKeyIndexMask |= 1u << index2; } } diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 53fa0b33..64d370b5 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -17,12 +17,12 @@ namespace Penumbra.UI; public sealed class ConfigWindow : Window, IUiService { private readonly IDalamudPluginInterface _pluginInterface; - private readonly Configuration _config; - private readonly PerformanceTracker _tracker; - private readonly ValidityChecker _validityChecker; - private Penumbra? _penumbra; - private ConfigTabBar _configTabs = null!; - private string? _lastException; + private readonly Configuration _config; + private readonly PerformanceTracker _tracker; + private readonly ValidityChecker _validityChecker; + private Penumbra? _penumbra; + private ConfigTabBar _configTabs = null!; + private string? _lastException; public ConfigWindow(PerformanceTracker tracker, IDalamudPluginInterface pi, Configuration config, ValidityChecker checker, TutorialService tutorial) diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index fd37bf35..2de78c66 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -52,11 +52,14 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) return; ImUtf8.TableSetupColumn("Attribute"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); - ImUtf8.TableSetupColumn("Disabled"u8, ImGuiTableColumnFlags.WidthStretch); + ImUtf8.TableSetupColumn("State"u8, ImGuiTableColumnFlags.WidthStretch); ImGui.TableHeadersRow(); - foreach (var (attribute, set) in data.ModCollection.MetaCache!.Atr.Data) - DrawShapeAttribute(attribute, set); + foreach (var (attribute, set) in data.ModCollection.MetaCache!.Atr.Data.OrderBy(a => a.Key)) + { + ImUtf8.DrawTableColumn(attribute.AsSpan); + DrawValues(attribute, set); + } } private unsafe void DrawCollectionShapeCache(Actor actor) @@ -72,83 +75,87 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Condition"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Shape"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); - ImUtf8.TableSetupColumn("Enabled"u8, ImGuiTableColumnFlags.WidthStretch); + ImUtf8.TableSetupColumn("State"u8, ImGuiTableColumnFlags.WidthStretch); ImGui.TableHeadersRow(); foreach (var condition in Enum.GetValues()) { - foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State(condition)) + foreach (var (shape, set) in data.ModCollection.MetaCache!.Shp.State(condition).OrderBy(shp => shp.Key)) { ImUtf8.DrawTableColumn(condition.ToString()); - DrawShapeAttribute(shape, set); + ImUtf8.DrawTableColumn(shape.AsSpan); + DrawValues(shape, set); } } } - private static void DrawShapeAttribute(in ShapeAttributeString shapeAttribute, ShapeAttributeHashSet set) + private static void DrawValues(in ShapeAttributeString shapeAttribute, ShapeAttributeHashSet set) { - ImUtf8.DrawTableColumn(shapeAttribute.AsSpan); - if (set.All) - { - ImUtf8.DrawTableColumn("All"u8); - } - else - { - ImGui.TableNextColumn(); - foreach (var slot in ShapeAttributeManager.UsedModels) - { - if (!set[slot]) - continue; + ImGui.TableNextColumn(); - ImUtf8.Text($"All {slot.ToName()}, "); + if (set.All is { } value) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value); + ImUtf8.Text("All"u8); + ImGui.SameLine(0, 0); + } + + foreach (var slot in ShapeAttributeManager.UsedModels) + { + if (set[slot] is not { } value2) + continue; + + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value2); + ImUtf8.Text($"All {slot.ToName()}, "); + ImGui.SameLine(0, 0); + } + + foreach (var gr in ShapeAttributeHashSet.GenderRaceValues.Skip(1)) + { + if (set[gr] is { } value3) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value3); + ImUtf8.Text($"All {gr.ToName()}, "); ImGui.SameLine(0, 0); } - - foreach (var gr in ShapeAttributeHashSet.GenderRaceValues.Skip(1)) + else { - if (set[gr]) + foreach (var slot in ShapeAttributeManager.UsedModels) { - ImUtf8.Text($"All {gr.ToName()}, "); - ImGui.SameLine(0, 0); - } - else - { - foreach (var slot in ShapeAttributeManager.UsedModels) - { - if (!set[slot, gr]) - continue; - - ImUtf8.Text($"All {gr.ToName()} {slot.ToName()}, "); - ImGui.SameLine(0, 0); - } - } - } - - - foreach (var ((slot, id), flags) in set) - { - if ((flags & 1ul) is not 0) - { - if (set[slot]) + if (set[slot, gr] is not { } value4) continue; - ImUtf8.Text($"{slot.ToName()} {id.Id:D4}, "); + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value4); + ImUtf8.Text($"All {gr.ToName()} {slot.ToName()}, "); ImGui.SameLine(0, 0); } - else - { - var currentFlags = flags >> 1; - var currentIndex = BitOperations.TrailingZeroCount(currentFlags); - while (currentIndex < ShapeAttributeHashSet.GenderRaceValues.Count) - { - var gr = ShapeAttributeHashSet.GenderRaceValues[currentIndex]; - if (set[slot, gr]) - continue; + } + } - ImUtf8.Text($"{gr.ToName()} {slot.ToName()} {id.Id:D4}, "); - currentFlags >>= currentIndex; - currentIndex = BitOperations.TrailingZeroCount(currentFlags); + foreach (var ((slot, id), flags) in set) + { + if ((flags & 3) is not 0) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), (flags & 2) is not 0); + ImUtf8.Text($"{slot.ToName()} {id.Id:D4}, "); + ImGui.SameLine(0, 0); + } + else + { + var currentFlags = flags >> 2; + var currentIndex = BitOperations.TrailingZeroCount(currentFlags) / 2; + while (currentIndex < ShapeAttributeHashSet.GenderRaceValues.Count) + { + var value5 = (currentFlags & 1) is 1; + var gr = ShapeAttributeHashSet.GenderRaceValues[currentIndex]; + if (set[slot, gr] != value5) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value5); + ImUtf8.Text($"{gr.ToName()} {slot.ToName()} #{id.Id:D4}, "); } + + currentFlags >>= currentIndex * 2; + currentIndex = BitOperations.TrailingZeroCount(currentFlags) / 2; } } } From 6cba63ac9807b4797166c02b903b872b11890db8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 1 Jun 2025 13:04:20 +0200 Subject: [PATCH 1240/1381] Make shape names editable in models. --- .../UI/AdvancedWindow/ModEditWindow.Models.cs | 77 +++++++++++++------ 1 file changed, 54 insertions(+), 23 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index 0c8c496f..cc592296 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -31,19 +31,18 @@ public partial class ModEditWindow private class LoadedData { - public MdlFile LastFile = null!; + public MdlFile LastFile = null!; public readonly List SubMeshAttributeTags = []; public long[] LodTriCount = []; } - private string _modelNewMaterial = string.Empty; + private string _modelNewMaterial = string.Empty; private readonly LoadedData _main = new(); private readonly LoadedData _preview = new(); - private string _customPath = string.Empty; - private Utf8GamePath _customGamePath = Utf8GamePath.Empty; - + private string _customPath = string.Empty; + private Utf8GamePath _customGamePath = Utf8GamePath.Empty; private LoadedData UpdateFile(MdlFile file, bool force, bool disabled) @@ -68,7 +67,7 @@ public partial class ModEditWindow private bool DrawModelPanel(MdlTab tab, bool disabled) { - var ret = tab.Dirty; + var ret = tab.Dirty; var data = UpdateFile(tab.Mdl, ret, disabled); DrawVersionUpdate(tab, disabled); DrawImportExport(tab, disabled); @@ -89,7 +88,8 @@ public partial class ModEditWindow if (disabled || tab.Mdl.Version is not MdlFile.V5) return; - if (!ImUtf8.ButtonEx("Update MDL Version from V5 to V6"u8, "Try using this if the bone weights of a pre-Dawntrail model seem wrong.\n\nThis is not revertible."u8, + if (!ImUtf8.ButtonEx("Update MDL Version from V5 to V6"u8, + "Try using this if the bone weights of a pre-Dawntrail model seem wrong.\n\nThis is not revertible."u8, new Vector2(-0.1f, 0), false, 0, Colors.PressEnterWarningBg)) return; @@ -350,7 +350,7 @@ public partial class ModEditWindow if (!disabled) { ImGui.TableSetupColumn("actions", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); - ImGui.TableSetupColumn("help", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); + ImGui.TableSetupColumn("help", ImGuiTableColumnFlags.WidthFixed, UiHelpers.IconButtonSize.X); } var inputFlags = disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None; @@ -369,10 +369,11 @@ public partial class ModEditWindow ImGui.TableNextColumn(); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Plus.ToIconString(), UiHelpers.IconButtonSize, string.Empty, !validName, true)) { - ret |= true; - tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); - _modelNewMaterial = string.Empty; + ret |= true; + tab.Mdl.Materials = materials.AddItem(_modelNewMaterial); + _modelNewMaterial = string.Empty; } + ImGui.TableNextColumn(); if (!validName && _modelNewMaterial.Length > 0) DrawInvalidMaterialMarker(); @@ -423,14 +424,16 @@ public partial class ModEditWindow // Add markers to invalid materials. if (!tab.ValidateMaterial(temp)) DrawInvalidMaterialMarker(); - + return ret; } private static void DrawInvalidMaterialMarker() { using (ImRaii.PushFont(UiBuilder.IconFont)) + { ImGuiUtil.TextColored(0xFF0000FF, FontAwesomeIcon.TimesCircle.ToIconString()); + } ImGuiUtil.HoverTooltip( "Materials must be either relative (e.g. \"/filename.mtrl\")\n" @@ -498,11 +501,11 @@ public partial class ModEditWindow using var node = ImRaii.TreeNode($"Click to expand"); if (!node) return; - + var flags = ImGuiTableFlags.SizingFixedFit - | ImGuiTableFlags.RowBg - | ImGuiTableFlags.Borders - | ImGuiTableFlags.NoHostExtendX; + | ImGuiTableFlags.RowBg + | ImGuiTableFlags.Borders + | ImGuiTableFlags.NoHostExtendX; using var table = ImRaii.Table(string.Empty, 4, flags); if (!table) return; @@ -590,6 +593,7 @@ public partial class ModEditWindow if (!header) return false; + var ret = false; using (var table = ImRaii.Table("##data", 2, ImGuiTableFlags.SizingFixedFit)) { if (table) @@ -650,22 +654,49 @@ public partial class ModEditWindow using (var attributes = ImRaii.TreeNode("Attributes", ImGuiTreeNodeFlags.DefaultOpen)) { if (attributes) - foreach (var attribute in data.LastFile.Attributes) - ImRaii.TreeNode(attribute, ImGuiTreeNodeFlags.Leaf).Dispose(); + for (var i = 0; i < data.LastFile.Attributes.Length; ++i) + { + using var id = ImUtf8.PushId(i); + ref var attribute = ref data.LastFile.Attributes[i]; + var name = attribute; + if (ImUtf8.InputText("##attribute"u8, ref name, "Attribute Name..."u8) && name.Length > 0 && name != attribute) + { + attribute = name; + ret = true; + } + } } using (var bones = ImRaii.TreeNode("Bones", ImGuiTreeNodeFlags.DefaultOpen)) { if (bones) - foreach (var bone in data.LastFile.Bones) - ImRaii.TreeNode(bone, ImGuiTreeNodeFlags.Leaf).Dispose(); + for (var i = 0; i < data.LastFile.Bones.Length; ++i) + { + using var id = ImUtf8.PushId(i); + ref var bone = ref data.LastFile.Bones[i]; + var name = bone; + if (ImUtf8.InputText("##bone"u8, ref name, "Bone Name..."u8) && name.Length > 0 && name != bone) + { + bone = name; + ret = true; + } + } } using (var shapes = ImRaii.TreeNode("Shapes", ImGuiTreeNodeFlags.DefaultOpen)) { if (shapes) - foreach (var shape in data.LastFile.Shapes) - ImRaii.TreeNode(shape.ShapeName, ImGuiTreeNodeFlags.Leaf).Dispose(); + for (var i = 0; i < data.LastFile.Shapes.Length; ++i) + { + using var id = ImUtf8.PushId(i); + ref var shape = ref data.LastFile.Shapes[i]; + var name = shape.ShapeName; + if (ImUtf8.InputText("##shape"u8, ref name, "Shape Name..."u8) && name.Length > 0 && name != shape.ShapeName) + { + shape.ShapeName = name; + ret = true; + } + } } if (data.LastFile.RemainingData.Length > 0) @@ -675,7 +706,7 @@ public partial class ModEditWindow Widget.DrawHexViewer(data.LastFile.RemainingData); } - return false; + return ret; } private static bool GetFirstModel(IEnumerable files, [NotNullWhen(true)] out string? file) From 98203e4e8a6a7bd660d0df4dabebc6c48776450d Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 1 Jun 2025 11:06:37 +0000 Subject: [PATCH 1241/1381] [CI] Updating repo.json for testing_1.4.0.2 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 7cdc7bbb..e36176d5 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.4.0.1", - "TestingAssemblyVersion": "1.4.0.1", + "TestingAssemblyVersion": "1.4.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.2/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 318a41fe52ad00ce120d08b2c812e11a6a9b014a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 3 Jun 2025 18:39:46 +0200 Subject: [PATCH 1242/1381] Add checking for supported features with the currently new supported features 'Atch', 'Shp' and 'Atr'. --- Penumbra.Api | 2 +- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/Api/PluginStateApi.cs | 33 ++++--- Penumbra/Api/IpcProviders.cs | 2 + .../Api/IpcTester/PluginStateIpcTester.cs | 15 ++- Penumbra/Mods/FeatureChecker.cs | 95 +++++++++++++++++++ Penumbra/Mods/Manager/ModDataEditor.cs | 11 +++ Penumbra/Mods/Manager/ModManager.cs | 15 ++- Penumbra/Mods/Mod.cs | 29 +++++- Penumbra/Mods/ModCreator.cs | 11 ++- Penumbra/Mods/ModMeta.cs | 23 ++++- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 5 + Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 2 +- schemas/mod_meta-v3.json | 8 ++ 14 files changed, 216 insertions(+), 37 deletions(-) create mode 100644 Penumbra/Mods/FeatureChecker.cs diff --git a/Penumbra.Api b/Penumbra.Api index 14652039..ff7b3b40 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 1465203967d08519c6716292bc5e5094c7fbcacc +Subproject commit ff7b3b4014a97455f823380c78b8a7c5107f8e2f diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 38125627..7ca41324 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -17,7 +17,7 @@ public class PenumbraApi( UiApi ui) : IDisposable, IApiService, IPenumbraApi { public const int BreakingVersion = 5; - public const int FeatureVersion = 9; + public const int FeatureVersion = 10; public void Dispose() { diff --git a/Penumbra/Api/Api/PluginStateApi.cs b/Penumbra/Api/Api/PluginStateApi.cs index d69df448..f74553d1 100644 --- a/Penumbra/Api/Api/PluginStateApi.cs +++ b/Penumbra/Api/Api/PluginStateApi.cs @@ -1,39 +1,38 @@ +using System.Collections.Frozen; using Newtonsoft.Json; using OtterGui.Services; using Penumbra.Communication; +using Penumbra.Mods; using Penumbra.Services; namespace Penumbra.Api.Api; -public class PluginStateApi : IPenumbraApiPluginState, IApiService +public class PluginStateApi(Configuration config, CommunicatorService communicator) : IPenumbraApiPluginState, IApiService { - private readonly Configuration _config; - private readonly CommunicatorService _communicator; - - public PluginStateApi(Configuration config, CommunicatorService communicator) - { - _config = config; - _communicator = communicator; - } - public string GetModDirectory() - => _config.ModDirectory; + => config.ModDirectory; public string GetConfiguration() - => JsonConvert.SerializeObject(_config, Formatting.Indented); + => JsonConvert.SerializeObject(config, Formatting.Indented); public event Action? ModDirectoryChanged { - add => _communicator.ModDirectoryChanged.Subscribe(value!, Communication.ModDirectoryChanged.Priority.Api); - remove => _communicator.ModDirectoryChanged.Unsubscribe(value!); + add => communicator.ModDirectoryChanged.Subscribe(value!, Communication.ModDirectoryChanged.Priority.Api); + remove => communicator.ModDirectoryChanged.Unsubscribe(value!); } public bool GetEnabledState() - => _config.EnableMods; + => config.EnableMods; public event Action? EnabledChange { - add => _communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); - remove => _communicator.EnabledChanged.Unsubscribe(value!); + add => communicator.EnabledChanged.Subscribe(value!, EnabledChanged.Priority.Api); + remove => communicator.EnabledChanged.Unsubscribe(value!); } + + public FrozenSet SupportedFeatures + => FeatureChecker.SupportedFeatures.ToFrozenSet(); + + public string[] CheckSupportedFeatures(IEnumerable requiredFeatures) + => requiredFeatures.Where(f => !FeatureChecker.Supported(f)).ToArray(); } diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index f5a6c16d..7dcee375 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -80,6 +80,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ModDirectoryChanged.Provider(pi, api.PluginState), IpcSubscribers.GetEnabledState.Provider(pi, api.PluginState), IpcSubscribers.EnabledChange.Provider(pi, api.PluginState), + IpcSubscribers.SupportedFeatures.Provider(pi, api.PluginState), + IpcSubscribers.CheckSupportedFeatures.Provider(pi, api.PluginState), IpcSubscribers.RedrawObject.Provider(pi, api.Redraw), IpcSubscribers.RedrawAll.Provider(pi, api.Redraw), diff --git a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs index df82033d..a1bf4fc4 100644 --- a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs @@ -5,6 +5,7 @@ using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; using Penumbra.Api.Helpers; using Penumbra.Api.IpcSubscribers; @@ -12,7 +13,7 @@ namespace Penumbra.Api.IpcTester; public class PluginStateIpcTester : IUiService, IDisposable { - private readonly IDalamudPluginInterface _pi; + private readonly IDalamudPluginInterface _pi; public readonly EventSubscriber ModDirectoryChanged; public readonly EventSubscriber Initialized; public readonly EventSubscriber Disposed; @@ -26,6 +27,9 @@ public class PluginStateIpcTester : IUiService, IDisposable private readonly List _initializedList = []; private readonly List _disposedList = []; + private string _requiredFeatureString = string.Empty; + private string[] _requiredFeatures = []; + private DateTimeOffset _lastEnabledChange = DateTimeOffset.UnixEpoch; private bool? _lastEnabledValue; @@ -48,12 +52,15 @@ public class PluginStateIpcTester : IUiService, IDisposable EnabledChange.Dispose(); } + public void Draw() { using var _ = ImRaii.TreeNode("Plugin State"); if (!_) return; + if (ImUtf8.InputText("Required Features"u8, ref _requiredFeatureString)) + _requiredFeatures = _requiredFeatureString.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); using var table = ImRaii.Table(string.Empty, 3, ImGuiTableFlags.SizingFixedFit); if (!table) return; @@ -71,6 +78,12 @@ public class PluginStateIpcTester : IUiService, IDisposable IpcTester.DrawIntro(IpcSubscribers.EnabledChange.Label, "Last Change"); ImGui.TextUnformatted(_lastEnabledValue is { } v ? $"{_lastEnabledChange} (to {v})" : "Never"); + IpcTester.DrawIntro(SupportedFeatures.Label, "Supported Features"); + ImUtf8.Text(string.Join(", ", new SupportedFeatures(_pi).Invoke())); + + IpcTester.DrawIntro(CheckSupportedFeatures.Label, "Missing Features"); + ImUtf8.Text(string.Join(", ", new CheckSupportedFeatures(_pi).Invoke(_requiredFeatures))); + DrawConfigPopup(); IpcTester.DrawIntro(GetConfiguration.Label, "Configuration"); if (ImGui.Button("Get")) diff --git a/Penumbra/Mods/FeatureChecker.cs b/Penumbra/Mods/FeatureChecker.cs new file mode 100644 index 00000000..5800ef07 --- /dev/null +++ b/Penumbra/Mods/FeatureChecker.cs @@ -0,0 +1,95 @@ +using System.Collections.Frozen; +using Dalamud.Interface.ImGuiNotification; +using Dalamud.Interface.Utility.Raii; +using ImGuiNET; +using OtterGui.Text; +using Penumbra.Mods.Manager; +using Penumbra.UI.Classes; +using Notification = OtterGui.Classes.Notification; + +namespace Penumbra.Mods; + +public static class FeatureChecker +{ + /// Manually setup supported features to exclude None and Invalid and not make something supported too early. + private static readonly FrozenDictionary SupportedFlags = new[] + { + FeatureFlags.Atch, + FeatureFlags.Shp, + FeatureFlags.Atr, + }.ToFrozenDictionary(f => f.ToString(), f => f); + + public static IReadOnlyCollection SupportedFeatures + => SupportedFlags.Keys; + + public static FeatureFlags ParseFlags(string modDirectory, string modName, IEnumerable features) + { + var featureFlags = FeatureFlags.None; + HashSet missingFeatures = []; + foreach (var feature in features) + { + if (SupportedFlags.TryGetValue(feature, out var featureFlag)) + featureFlags |= featureFlag; + else + missingFeatures.Add(feature); + } + + if (missingFeatures.Count > 0) + { + Penumbra.Messager.AddMessage(new Notification( + $"Please update Penumbra to use the mod {modName}{(modDirectory != modName ? $" at {modDirectory}" : string.Empty)}!\n\nLoading failed because it requires the unsupported feature{(missingFeatures.Count > 1 ? $"s\n\n\t[{string.Join("], [", missingFeatures)}]." : $" [{missingFeatures.First()}].")}", + NotificationType.Warning)); + return FeatureFlags.Invalid; + } + + return featureFlags; + } + + public static bool Supported(string features) + => SupportedFlags.ContainsKey(features); + + public static void DrawFeatureFlagInput(ModDataEditor editor, Mod mod, float width) + { + const int numButtons = 5; + var innerSpacing = ImGui.GetStyle().ItemInnerSpacing; + var size = new Vector2((width - (numButtons - 1) * innerSpacing.X) / numButtons, 0); + var buttonColor = ImGui.GetColorU32(ImGuiCol.FrameBg); + var textColor = ImGui.GetColorU32(ImGuiCol.TextDisabled); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, innerSpacing) + .Push(ImGuiStyleVar.FrameBorderSize, 0); + using (var color = ImRaii.PushColor(ImGuiCol.Border, ColorId.FolderLine.Value()) + .Push(ImGuiCol.Button, buttonColor) + .Push(ImGuiCol.Text, textColor)) + { + foreach (var flag in SupportedFlags.Values) + { + if (mod.RequiredFeatures.HasFlag(flag)) + { + style.Push(ImGuiStyleVar.FrameBorderSize, ImUtf8.GlobalScale); + color.Pop(2); + if (ImUtf8.Button($"{flag}", size)) + editor.ChangeRequiredFeatures(mod, mod.RequiredFeatures & ~flag); + color.Push(ImGuiCol.Button, buttonColor) + .Push(ImGuiCol.Text, textColor); + style.Pop(); + } + else if (ImUtf8.Button($"{flag}", size)) + { + editor.ChangeRequiredFeatures(mod, mod.RequiredFeatures | flag); + } + + ImGui.SameLine(); + } + } + + if (ImUtf8.ButtonEx("Compute"u8, "Compute the required features automatically from the used features."u8, size)) + editor.ChangeRequiredFeatures(mod, mod.ComputeRequiredFeatures()); + + ImGui.SameLine(); + if (ImUtf8.ButtonEx("Clear"u8, "Clear all required features."u8, size)) + editor.ChangeRequiredFeatures(mod, FeatureFlags.None); + + ImGui.SameLine(); + ImUtf8.Text("Required Features"u8); + } +} diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index 1349b525..fc4fdadc 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -26,6 +26,7 @@ public enum ModDataChangeType : ushort Image = 0x1000, DefaultChangedItems = 0x2000, PreferredChangedItems = 0x4000, + RequiredFeatures = 0x8000, } public class ModDataEditor(SaveService saveService, CommunicatorService communicatorService, ItemData itemData) : IService @@ -95,6 +96,16 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic mod.Website = newWebsite; saveService.QueueSave(new ModMeta(mod)); communicatorService.ModDataChanged.Invoke(ModDataChangeType.Website, mod, null); + } + + public void ChangeRequiredFeatures(Mod mod, FeatureFlags flags) + { + if (mod.RequiredFeatures == flags) + return; + + mod.RequiredFeatures = flags; + saveService.QueueSave(new ModMeta(mod)); + communicatorService.ModDataChanged.Invoke(ModDataChangeType.RequiredFeatures, mod, null); } public void ChangeModTag(Mod mod, int tagIdx, string newTag) diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index bf1b6637..32dac049 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -143,9 +143,10 @@ public sealed class ModManager : ModStorage, IDisposable, IService _communicator.ModPathChanged.Invoke(ModPathChangeType.StartingReload, mod, mod.ModPath, mod.ModPath); if (!Creator.ReloadMod(mod, true, false, out var metaChange)) { - Penumbra.Log.Warning(mod.Name.Length == 0 - ? $"Reloading mod {oldName} has failed, new name is empty. Removing from loaded mods instead." - : $"Reloading mod {oldName} failed, {mod.ModPath.FullName} does not exist anymore or it has invalid data. Removing from loaded mods instead."); + if (mod.RequiredFeatures is not FeatureFlags.Invalid) + Penumbra.Log.Warning(mod.Name.Length == 0 + ? $"Reloading mod {oldName} has failed, new name is empty. Removing from loaded mods instead." + : $"Reloading mod {oldName} failed, {mod.ModPath.FullName} does not exist anymore or it has invalid data. Removing from loaded mods instead."); RemoveMod(mod); return; } @@ -251,12 +252,8 @@ public sealed class ModManager : ModStorage, IDisposable, IService { switch (type) { - case ModPathChangeType.Added: - SetNew(mod); - break; - case ModPathChangeType.Deleted: - SetKnown(mod); - break; + case ModPathChangeType.Added: SetNew(mod); break; + case ModPathChangeType.Deleted: SetKnown(mod); break; case ModPathChangeType.Moved: if (oldDirectory != null && newDirectory != null) DataEditor.MoveDataFile(oldDirectory, newDirectory); diff --git a/Penumbra/Mods/Mod.cs b/Penumbra/Mods/Mod.cs index 99f86517..e262e8f1 100644 --- a/Penumbra/Mods/Mod.cs +++ b/Penumbra/Mods/Mod.cs @@ -1,4 +1,3 @@ -using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; using Penumbra.GameData.Data; @@ -12,6 +11,16 @@ using Penumbra.String.Classes; namespace Penumbra.Mods; +[Flags] +public enum FeatureFlags : ulong +{ + None = 0, + Atch = 1ul << 0, + Shp = 1ul << 1, + Atr = 1ul << 2, + Invalid = 1ul << 62, +} + public sealed class Mod : IMod { public static readonly TemporaryMod ForcedFiles = new() @@ -57,6 +66,7 @@ public sealed class Mod : IMod public string Image { get; internal set; } = string.Empty; public IReadOnlyList ModTags { get; internal set; } = []; public HashSet DefaultPreferredItems { get; internal set; } = []; + public FeatureFlags RequiredFeatures { get; internal set; } = 0; // Local Data @@ -70,6 +80,23 @@ public sealed class Mod : IMod public readonly DefaultSubMod Default; public readonly List Groups = []; + /// Compute the required feature flags for this mod. + public FeatureFlags ComputeRequiredFeatures() + { + var flags = FeatureFlags.None; + foreach (var option in AllDataContainers) + { + if (option.Manipulations.Atch.Count > 0) + flags |= FeatureFlags.Atch; + if (option.Manipulations.Atr.Count > 0) + flags |= FeatureFlags.Atr; + if (option.Manipulations.Shp.Count > 0) + flags |= FeatureFlags.Shp; + } + + return flags; + } + public AppliedModData GetData(ModSettings? settings = null) { if (settings is not { Enabled: true }) diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index df476a6f..1bb2a073 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -28,7 +28,8 @@ public partial class ModCreator( MetaFileManager metaFileManager, GamePathParser gamePathParser) : IService { - public readonly Configuration Config = config; + public const FeatureFlags SupportedFeatures = FeatureFlags.Atch | FeatureFlags.Shp | FeatureFlags.Atr; + public readonly Configuration Config = config; /// Creates directory and files necessary for a new mod without adding it to the manager. public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "", string? author = null) @@ -74,7 +75,7 @@ public partial class ModCreator( return false; modDataChange = ModMeta.Load(dataEditor, this, mod); - if (modDataChange.HasFlag(ModDataChangeType.Deletion) || mod.Name.Length == 0) + if (modDataChange.HasFlag(ModDataChangeType.Deletion) || mod.Name.Length == 0 || mod.RequiredFeatures is FeatureFlags.Invalid) return false; modDataChange |= ModLocalData.Load(dataEditor, mod); @@ -82,9 +83,9 @@ public partial class ModCreator( LoadAllGroups(mod); if (incorporateMetaChanges) IncorporateAllMetaChanges(mod, true, deleteDefaultMetaChanges); - else if (deleteDefaultMetaChanges) - ModMetaEditor.DeleteDefaultValues(mod, metaFileManager, saveService, false); - + else if (deleteDefaultMetaChanges) + ModMetaEditor.DeleteDefaultValues(mod, metaFileManager, saveService, false); + return true; } diff --git a/Penumbra/Mods/ModMeta.cs b/Penumbra/Mods/ModMeta.cs index 1b104af4..b52eecf4 100644 --- a/Penumbra/Mods/ModMeta.cs +++ b/Penumbra/Mods/ModMeta.cs @@ -1,7 +1,6 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.GameData.Structs; -using Penumbra.Mods.Editor; using Penumbra.Mods.Manager; using Penumbra.Services; @@ -28,6 +27,19 @@ public readonly struct ModMeta(Mod mod) : ISavable { nameof(Mod.ModTags), JToken.FromObject(mod.ModTags) }, { nameof(Mod.DefaultPreferredItems), JToken.FromObject(mod.DefaultPreferredItems) }, }; + if (mod.RequiredFeatures is not FeatureFlags.None) + { + var features = mod.RequiredFeatures; + var array = new JArray(); + foreach (var flag in Enum.GetValues()) + { + if ((features & flag) is not FeatureFlags.None) + array.Add(flag.ToString()); + } + + jObject[nameof(Mod.RequiredFeatures)] = array; + } + using var jWriter = new JsonTextWriter(writer); jWriter.Formatting = Formatting.Indented; jObject.WriteTo(jWriter); @@ -60,6 +72,8 @@ public readonly struct ModMeta(Mod mod) : ISavable var modTags = (json[nameof(Mod.ModTags)] as JArray)?.Values().OfType(); var defaultItems = (json[nameof(Mod.DefaultPreferredItems)] as JArray)?.Values().Select(i => (CustomItemId)i).ToHashSet() ?? []; + var requiredFeatureArray = (json[nameof(Mod.RequiredFeatures)] as JArray)?.Values() ?? []; + var requiredFeatures = FeatureChecker.ParseFlags(mod.ModPath.Name, newName.Length > 0 ? newName : mod.Name.Length > 0 ? mod.Name : "Unknown", requiredFeatureArray!); ModDataChangeType changes = 0; if (mod.Name != newName) @@ -111,6 +125,13 @@ public readonly struct ModMeta(Mod mod) : ISavable editor.SaveService.ImmediateSave(new ModMeta(mod)); } + // Required features get checked during parsing, in which case the new required features signal invalid. + if (requiredFeatures != mod.RequiredFeatures) + { + changes |= ModDataChangeType.RequiredFeatures; + mod.RequiredFeatures = requiredFeatures; + } + changes |= ModLocalData.UpdateTags(mod, modTags, null); return changes; diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 1e6afa09..478ab892 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -64,6 +64,10 @@ public class ModPanelEditTab( messager.NotificationMessage(e.Message, NotificationType.Warning, false); } + UiHelpers.DefaultLineSpace(); + + FeatureChecker.DrawFeatureFlagInput(modManager.DataEditor, _mod, UiHelpers.InputTextWidth.X); + UiHelpers.DefaultLineSpace(); var sharedTagsEnabled = predefinedTagManager.Count > 0; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; @@ -76,6 +80,7 @@ public class ModPanelEditTab( predefinedTagManager.DrawAddFromSharedTagsAndUpdateTags(selector.Selected!.LocalTags, selector.Selected!.ModTags, false, selector.Selected!); + UiHelpers.DefaultLineSpace(); addGroupDrawer.Draw(_mod, UiHelpers.InputTextWidth.X); UiHelpers.DefaultLineSpace(); diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 2de78c66..a7bfd49c 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -96,7 +96,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (set.All is { } value) { using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value); - ImUtf8.Text("All"u8); + ImUtf8.Text("All, "u8); ImGui.SameLine(0, 0); } diff --git a/schemas/mod_meta-v3.json b/schemas/mod_meta-v3.json index ed63a228..6fc68714 100644 --- a/schemas/mod_meta-v3.json +++ b/schemas/mod_meta-v3.json @@ -52,6 +52,14 @@ "type": "integer" }, "uniqueItems": true + }, + "RequiredFeatures": { + "description": "A list of required features by name.", + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true } }, "required": [ From 535694e9c8fd5377abcfbf32b5149d1111d4f18a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 7 Jun 2025 22:10:17 +0200 Subject: [PATCH 1243/1381] Update some BNPC Names. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 14b3641f..94076bf6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 14b3641f0fb520cb829ceb50fa7cb31255a1da4e +Subproject commit 94076bf6bba27c02e0adbafa1c5cc9c279a0b5df From 4c0e6d2a67d5964717c9057cbcec7c73eb9651bf Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 7 Jun 2025 22:10:59 +0200 Subject: [PATCH 1244/1381] Update Mod Merger for other group types. --- Penumbra/Mods/Editor/ModMerger.cs | 139 +++++++++++++++--- .../Manager/OptionEditor/ModOptionEditor.cs | 48 +++--- 2 files changed, 139 insertions(+), 48 deletions(-) diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index 88941edf..bb84173a 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -6,6 +6,7 @@ using OtterGui.Extensions; using OtterGui.Services; using Penumbra.Api.Enums; using Penumbra.Communication; +using Penumbra.Mods.Groups; using Penumbra.Mods.Manager; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Mods.SubMods; @@ -44,13 +45,13 @@ public class ModMerger : IDisposable, IService public ModMerger(ModManager mods, ModGroupEditor editor, ModSelection selection, DuplicateManager duplicates, CommunicatorService communicator, ModCreator creator, Configuration config) { - _editor = editor; - _selection = selection; - _duplicates = duplicates; - _communicator = communicator; - _creator = creator; - _config = config; - _mods = mods; + _editor = editor; + _selection = selection; + _duplicates = duplicates; + _communicator = communicator; + _creator = creator; + _config = config; + _mods = mods; _selection.Subscribe(OnSelectionChange, ModSelection.Priority.ModMerger); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModMerger); } @@ -99,26 +100,117 @@ public class ModMerger : IDisposable, IService foreach (var originalGroup in MergeFromMod!.Groups) { - var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, originalGroup.Type, originalGroup.Name); - if (groupCreated) - _createdGroups.Add(groupIdx); - if (group == null) - throw new Exception( - $"The merged group {originalGroup.Name} already existed, but had a different type than the original group of type {originalGroup.Type}."); - - foreach (var originalOption in originalGroup.DataContainers) + switch (originalGroup.Type) { - var (option, _, optionCreated) = _editor.FindOrAddOption(group, originalOption.GetName()); - if (optionCreated) + case GroupType.Single: + case GroupType.Multi: { - _createdOptions.Add(option!); - // #TODO DataContainer <> Option. - MergeIntoOption([originalOption], (IModDataContainer)option!, false); + var (group, groupIdx, groupCreated) = _editor.FindOrAddModGroup(MergeToMod!, originalGroup.Type, originalGroup.Name); + if (group is null) + throw new Exception( + $"The merged group {originalGroup.Name} already existed, but had a different type than the original group of type {originalGroup.Type}."); + + if (groupCreated) + { + _createdGroups.Add(groupIdx); + group.Description = originalGroup.Description; + group.Image = originalGroup.Image; + group.DefaultSettings = originalGroup.DefaultSettings; + group.Page = originalGroup.Page; + group.Priority = originalGroup.Priority; + } + + foreach (var originalOption in originalGroup.Options) + { + var (option, _, optionCreated) = _editor.FindOrAddOption(group, originalOption.Name); + if (optionCreated) + { + _createdOptions.Add(option!); + MergeIntoOption([(IModDataContainer)originalOption], (IModDataContainer)option!, false); + option!.Description = originalOption.Description; + if (option is MultiSubMod multiOption) + multiOption.Priority = ((MultiSubMod)originalOption).Priority; + } + else + { + throw new Exception( + $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: The option {option!.FullName} already existed."); + } + } + + break; } - else + + case GroupType.Imc when originalGroup is ImcModGroup imc: { - throw new Exception( - $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: The option {option!.FullName} already existed."); + var group = _editor.ImcEditor.AddModGroup(MergeToMod!, imc.Name, imc.Identifier, imc.DefaultEntry); + if (group is null) + throw new Exception( + $"The merged group {originalGroup.Name} already existed, but groups of type {originalGroup.Type} can not be merged."); + + group.AllVariants = imc.AllVariants; + group.OnlyAttributes = imc.OnlyAttributes; + group.Description = imc.Description; + group.Image = imc.Image; + group.DefaultSettings = imc.DefaultSettings; + group.Page = imc.Page; + group.Priority = imc.Priority; + foreach (var originalOption in imc.OptionData) + { + if (originalOption.IsDisableSubMod) + { + _editor.ImcEditor.ChangeCanBeDisabled(group, true); + var disable = group.OptionData.First(s => s.IsDisableSubMod); + disable.Description = originalOption.Description; + disable.Name = originalOption.Name; + continue; + } + + var newOption = _editor.ImcEditor.AddOption(group, originalOption.Name); + if (newOption is null) + throw new Exception( + $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: Unknown error when creating IMC option {originalOption.FullName}."); + + newOption.Description = originalOption.Description; + newOption.AttributeMask = originalOption.AttributeMask; + } + + break; + } + case GroupType.Combining when originalGroup is CombiningModGroup combining: + { + var group = _editor.CombiningEditor.AddModGroup(MergeToMod!, combining.Name); + if (group is null) + throw new Exception( + $"The merged group {originalGroup.Name} already existed, but groups of type {originalGroup.Type} can not be merged."); + + group.Description = combining.Description; + group.Image = combining.Image; + group.DefaultSettings = combining.DefaultSettings; + group.Page = combining.Page; + group.Priority = combining.Priority; + foreach (var originalOption in combining.OptionData) + { + var option = _editor.CombiningEditor.AddOption(group, originalOption.Name); + if (option is null) + throw new Exception( + $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: Unknown error when creating combining option {originalOption.FullName}."); + + option.Description = originalOption.Description; + } + + if (group.Data.Count != combining.Data.Count) + throw new Exception( + $"Could not merge {MergeFromMod!.Name} into {MergeToMod!.Name}: Unknown error caused data container counts in combining group {originalGroup.Name} to differ."); + + foreach (var (originalContainer, container) in combining.Data.Zip(group.Data)) + { + container.Name = originalContainer.Name; + MergeIntoOption([originalContainer], container, false); + } + + + break; } } } @@ -151,7 +243,6 @@ public class ModMerger : IDisposable, IService if (!dir.Exists) _createdDirectories.Add(dir.FullName); CopyFiles(dir); - // #TODO DataContainer <> Option. MergeIntoOption(MergeFromMod!.AllDataContainers.Reverse(), (IModDataContainer)option!, true); } diff --git a/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs b/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs index 5c5ed4f1..d9d672e3 100644 --- a/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs +++ b/Penumbra/Mods/Manager/OptionEditor/ModOptionEditor.cs @@ -15,8 +15,8 @@ public abstract class ModOptionEditor( where TOption : class, IModOption { protected readonly CommunicatorService Communicator = communicator; - protected readonly SaveService SaveService = saveService; - protected readonly Configuration Config = config; + protected readonly SaveService SaveService = saveService; + protected readonly Configuration Config = config; /// Add a new, empty option group of the given type and name. public TGroup? AddModGroup(Mod mod, string newName, SaveType saveType = SaveType.ImmediateSync) @@ -25,7 +25,7 @@ public abstract class ModOptionEditor( return null; var maxPriority = mod.Groups.Count == 0 ? ModPriority.Default : mod.Groups.Max(o => o.Priority) + 1; - var group = CreateGroup(mod, newName, maxPriority); + var group = CreateGroup(mod, newName, maxPriority); mod.Groups.Add(group); SaveService.Save(saveType, new ModSaveGroup(group, Config.ReplaceNonAsciiOnImport)); Communicator.ModOptionChanged.Invoke(ModOptionChangeType.GroupAdded, mod, group, null, null, -1); @@ -92,8 +92,8 @@ public abstract class ModOptionEditor( /// Delete the given option from the given group. public void DeleteOption(TOption option) { - var mod = option.Mod; - var group = option.Group; + var mod = option.Mod; + var group = option.Group; var optionIdx = option.GetIndex(); Communicator.ModOptionChanged.Invoke(ModOptionChangeType.PrepareChange, mod, group, option, null, -1); RemoveOption((TGroup)group, optionIdx); @@ -104,7 +104,7 @@ public abstract class ModOptionEditor( /// Move an option inside the given option group. public void MoveOption(TOption option, int optionIdxTo) { - var idx = option.GetIndex(); + var idx = option.GetIndex(); var group = (TGroup)option.Group; if (!MoveOption(group, idx, optionIdxTo)) return; @@ -113,10 +113,10 @@ public abstract class ModOptionEditor( Communicator.ModOptionChanged.Invoke(ModOptionChangeType.OptionMoved, group.Mod, group, option, null, idx); } - protected abstract TGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync); + protected abstract TGroup CreateGroup(Mod mod, string newName, ModPriority priority, SaveType saveType = SaveType.ImmediateSync); protected abstract TOption? CloneOption(TGroup group, IModOption option); - protected abstract void RemoveOption(TGroup group, int optionIndex); - protected abstract bool MoveOption(TGroup group, int optionIdxFrom, int optionIdxTo); + protected abstract void RemoveOption(TGroup group, int optionIndex); + protected abstract bool MoveOption(TGroup group, int optionIdxFrom, int optionIdxTo); } public static class ModOptionChangeTypeExtension @@ -132,22 +132,22 @@ public static class ModOptionChangeTypeExtension { (requiresSaving, requiresReloading, wasPrepared) = type switch { - ModOptionChangeType.GroupRenamed => (true, false, false), - ModOptionChangeType.GroupAdded => (true, false, false), - ModOptionChangeType.GroupDeleted => (true, true, false), - ModOptionChangeType.GroupMoved => (true, false, false), - ModOptionChangeType.GroupTypeChanged => (true, true, true), - ModOptionChangeType.PriorityChanged => (true, true, true), - ModOptionChangeType.OptionAdded => (true, true, true), - ModOptionChangeType.OptionDeleted => (true, true, false), - ModOptionChangeType.OptionMoved => (true, false, false), - ModOptionChangeType.OptionFilesChanged => (false, true, false), - ModOptionChangeType.OptionFilesAdded => (false, true, true), - ModOptionChangeType.OptionSwapsChanged => (false, true, false), - ModOptionChangeType.OptionMetaChanged => (false, true, false), - ModOptionChangeType.DisplayChange => (false, false, false), + ModOptionChangeType.GroupRenamed => (true, false, false), + ModOptionChangeType.GroupAdded => (true, false, false), + ModOptionChangeType.GroupDeleted => (true, true, false), + ModOptionChangeType.GroupMoved => (true, false, false), + ModOptionChangeType.GroupTypeChanged => (true, true, true), + ModOptionChangeType.PriorityChanged => (true, true, true), + ModOptionChangeType.OptionAdded => (true, true, true), + ModOptionChangeType.OptionDeleted => (true, true, false), + ModOptionChangeType.OptionMoved => (true, false, false), + ModOptionChangeType.OptionFilesChanged => (false, true, false), + ModOptionChangeType.OptionFilesAdded => (false, true, true), + ModOptionChangeType.OptionSwapsChanged => (false, true, false), + ModOptionChangeType.OptionMetaChanged => (false, true, false), + ModOptionChangeType.DisplayChange => (false, false, false), ModOptionChangeType.DefaultOptionChanged => (true, false, false), - _ => (false, false, false), + _ => (false, false, false), }; } } From a16fd85a7ea1fb6d6190b5c264f70c78a2b13c63 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 8 Jun 2025 11:28:12 +0200 Subject: [PATCH 1245/1381] Handle .tex files with broken mip map offsets on import, also remove unnecessary mipmaps (any after reaching minimum size once). --- Penumbra/Import/TexToolsImporter.Archives.cs | 4 ++ Penumbra/Import/TexToolsImporter.ModPack.cs | 1 + Penumbra/Import/Textures/TexFileParser.cs | 69 ++++++++++++++++++++ Penumbra/Mods/Manager/ModImportManager.cs | 1 - Penumbra/Services/MigrationManager.cs | 43 ++++++++++++ 5 files changed, 117 insertions(+), 1 deletion(-) diff --git a/Penumbra/Import/TexToolsImporter.Archives.cs b/Penumbra/Import/TexToolsImporter.Archives.cs index 8166dea7..a80730bf 100644 --- a/Penumbra/Import/TexToolsImporter.Archives.cs +++ b/Penumbra/Import/TexToolsImporter.Archives.cs @@ -4,6 +4,7 @@ using Newtonsoft.Json.Linq; using OtterGui.Filesystem; using Penumbra.Import.Structs; using Penumbra.Mods; +using Penumbra.Services; using SharpCompress.Archives; using SharpCompress.Archives.Rar; using SharpCompress.Archives.SevenZip; @@ -146,6 +147,9 @@ public partial class TexToolsImporter case ".mtrl": _migrationManager.MigrateMtrlDuringExtraction(reader, _currentModDirectory!.FullName, _extractionOptions); break; + case ".tex": + _migrationManager.FixMipMaps(reader, _currentModDirectory!.FullName, _extractionOptions); + break; default: reader.WriteEntryToDirectory(_currentModDirectory!.FullName, _extractionOptions); break; diff --git a/Penumbra/Import/TexToolsImporter.ModPack.cs b/Penumbra/Import/TexToolsImporter.ModPack.cs index 1c28aef2..fd9e50c0 100644 --- a/Penumbra/Import/TexToolsImporter.ModPack.cs +++ b/Penumbra/Import/TexToolsImporter.ModPack.cs @@ -259,6 +259,7 @@ public partial class TexToolsImporter { ".mdl" => _migrationManager.MigrateTtmpModel(extractedFile.FullName, data.Data), ".mtrl" => _migrationManager.MigrateTtmpMaterial(extractedFile.FullName, data.Data), + ".tex" => _migrationManager.FixTtmpMipMaps(extractedFile.FullName, data.Data), _ => data.Data, }; diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 220095c1..6a12a0dd 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -61,6 +61,75 @@ public static class TexFileParser return 13; } + public static unsafe void FixMipOffsets(long size, ref TexFile.TexHeader header, out long newSize) + { + var width = (uint)header.Width; + var height = (uint)header.Height; + var format = header.Format.ToDXGI(); + var bits = format.BitsPerPixel(); + var totalSize = 80u; + size -= totalSize; + var minSize = format.IsCompressed() ? 4u : 1u; + for (var i = 0; i < 13; ++i) + { + var requiredSize = (uint)((long)width * height * bits / 8); + if (requiredSize > size) + { + newSize = totalSize; + if (header.MipCount != i) + { + Penumbra.Log.Debug( + $"-- Mip Map Count in TEX header was {header.MipCount}, but file only contains data for {i} Mip Maps, fixed."); + FixLodOffsets(ref header, i); + } + + return; + } + + if (header.OffsetToSurface[i] != totalSize) + { + Penumbra.Log.Debug( + $"-- Mip Map Offset {i + 1} in TEX header was {header.OffsetToSurface[i]} but should be {totalSize}, fixed."); + header.OffsetToSurface[i] = totalSize; + } + + if (width == minSize && height == minSize) + { + newSize = totalSize; + if (header.MipCount != i) + { + Penumbra.Log.Debug($"-- Reduced number of Mip Maps from {header.MipCount} to {i} due to minimum size constraints."); + FixLodOffsets(ref header, i); + } + + return; + } + + totalSize += requiredSize; + size -= requiredSize; + width = Math.Max(width / 2, minSize); + height = Math.Max(height / 2, minSize); + } + + newSize = totalSize; + if (header.MipCount != 13) + { + Penumbra.Log.Debug($"-- Mip Map Count in TEX header was {header.MipCount}, but maximum is 13, fixed."); + FixLodOffsets(ref header, 13); + } + + void FixLodOffsets(ref TexFile.TexHeader header, int index) + { + header.MipCount = index; + if (header.LodOffset[2] >= header.MipCount) + header.LodOffset[2] = (byte)(header.MipCount - 1); + if (header.LodOffset[1] >= header.MipCount) + header.LodOffset[1] = header.MipCount > 2 ? (byte)(header.MipCount - 2) : (byte)(header.MipCount - 1); + for (++index; index < 13; ++index) + header.OffsetToSurface[index] = 0; + } + } + private static unsafe void CopyData(ScratchImage image, BinaryReader r) { fixed (byte* ptr = image.Pixels) diff --git a/Penumbra/Mods/Manager/ModImportManager.cs b/Penumbra/Mods/Manager/ModImportManager.cs index 22cc0c86..bb282262 100644 --- a/Penumbra/Mods/Manager/ModImportManager.cs +++ b/Penumbra/Mods/Manager/ModImportManager.cs @@ -70,7 +70,6 @@ public class ModImportManager(ModManager modManager, Configuration config, ModEd _import = null; } - public bool AddUnpackedMod([NotNullWhen(true)] out Mod? mod) { if (!_modsToAdd.TryDequeue(out var directory)) diff --git a/Penumbra/Services/MigrationManager.cs b/Penumbra/Services/MigrationManager.cs index 2438c0ad..8db62e48 100644 --- a/Penumbra/Services/MigrationManager.cs +++ b/Penumbra/Services/MigrationManager.cs @@ -1,6 +1,10 @@ using Dalamud.Interface.ImGuiNotification; +using Lumina.Data.Files; using OtterGui.Classes; using OtterGui.Services; +using Lumina.Extensions; +using Penumbra.GameData.Files.Utility; +using Penumbra.Import.Textures; using SharpCompress.Common; using SharpCompress.Readers; using MdlFile = Penumbra.GameData.Files.MdlFile; @@ -296,6 +300,26 @@ public class MigrationManager(Configuration config) : IService } } + public void FixMipMaps(IReader reader, string directory, ExtractionOptions options) + { + var path = Path.Combine(directory, reader.Entry.Key!); + using var s = new MemoryStream(); + using var e = reader.OpenEntryStream(); + e.CopyTo(s); + var length = s.Position; + s.Seek(0, SeekOrigin.Begin); + var br = new BinaryReader(s, Encoding.UTF8, true); + var header = br.ReadStructure(); + br.Dispose(); + TexFileParser.FixMipOffsets(length, ref header, out var actualSize); + + s.Seek(0, SeekOrigin.Begin); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + using var f = File.Open(path, FileMode.Create, FileAccess.Write); + f.Write(header); + f.Write(s.GetBuffer().AsSpan(80, (int)actualSize - 80)); + } + /// Update the data of a .mdl file during TTMP extraction. Returns either the existing array or a new one. public byte[] MigrateTtmpModel(string path, byte[] data) { @@ -348,6 +372,25 @@ public class MigrationManager(Configuration config) : IService } } + public byte[] FixTtmpMipMaps(string path, byte[] data) + { + using var m = new MemoryStream(data); + var br = new BinaryReader(m, Encoding.UTF8, true); + var header = br.ReadStructure(); + br.Dispose(); + TexFileParser.FixMipOffsets(data.Length, ref header, out var actualSize); + if (actualSize == data.Length) + return data; + + var ret = new byte[actualSize]; + using var m2 = new MemoryStream(ret); + using var bw = new BinaryWriter(m2); + bw.Write(header); + bw.Write(data.AsSpan(80, (int)actualSize - 80)); + + return ret; + } + private static bool MigrateModel(string path, MdlFile mdl, bool createBackup) { From 973814b31b88c8c6176f1b12dc6a75a5d9439696 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 8 Jun 2025 11:36:32 +0200 Subject: [PATCH 1246/1381] Some more BNPCs. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 94076bf6..a1252cdc 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 94076bf6bba27c02e0adbafa1c5cc9c279a0b5df +Subproject commit a1252cdcab09cbf4c9694971f29523f7485c90bc From 3d056623840592ffa8504577169270dac00bdad7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 8 Jun 2025 09:38:30 +0000 Subject: [PATCH 1247/1381] [CI] Updating repo.json for testing_1.4.0.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e36176d5..a6cec268 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.4.0.1", - "TestingAssemblyVersion": "1.4.0.2", + "TestingAssemblyVersion": "1.4.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a8c05fc6eea82e5beae224a1467a7f8255eda37d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 13 Jun 2025 17:19:33 +0200 Subject: [PATCH 1248/1381] Make middle-mouse button handle temporary settings. --- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 23 +++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 2dff19ab..8a383791 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -229,14 +229,27 @@ public sealed class ModFileSystemSelector : FileSystemSelector Date: Fri, 13 Jun 2025 17:26:18 +0200 Subject: [PATCH 1249/1381] BNPCs. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index a1252cdc..10fdb025 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit a1252cdcab09cbf4c9694971f29523f7485c90bc +Subproject commit 10fdb025436f7ea9f1f5e97635c19eee0578de7b From 1f4ec984b348c66f962899721f3f97d34e6c098c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 13 Jun 2025 17:27:49 +0200 Subject: [PATCH 1250/1381] Use improved filesystem. --- OtterGui | 2 +- Penumbra/Api/Api/ModsApi.cs | 4 ++-- Penumbra/Mods/Manager/ModFileSystem.cs | 14 ++------------ 3 files changed, 5 insertions(+), 15 deletions(-) diff --git a/OtterGui b/OtterGui index 17a3ee57..78528f93 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 17a3ee5711ca30eb7f5b393dfb8136f0bce49b2b +Subproject commit 78528f93ac253db0061d9a8244cfa0cee5c2f873 diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index ace98f83..78c62953 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -112,7 +112,7 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable public (PenumbraApiEc, string, bool, bool) GetModPath(string modDirectory, string modName) { if (!_modManager.TryGetMod(modDirectory, modName, out var mod) - || !_modFileSystem.FindLeaf(mod, out var leaf)) + || !_modFileSystem.TryGetValue(mod, out var leaf)) return (PenumbraApiEc.ModMissing, string.Empty, false, false); var fullPath = leaf.FullName(); @@ -127,7 +127,7 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable return PenumbraApiEc.InvalidArgument; if (!_modManager.TryGetMod(modDirectory, modName, out var mod) - || !_modFileSystem.FindLeaf(mod, out var leaf)) + || !_modFileSystem.TryGetValue(mod, out var leaf)) return PenumbraApiEc.ModMissing; try diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index 693db944..a5c46972 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -80,7 +80,7 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer // Update sort order when defaulted mod names change. private void OnModDataChange(ModDataChangeType type, Mod mod, string? oldName) { - if (!type.HasFlag(ModDataChangeType.Name) || oldName == null || !FindLeaf(mod, out var leaf)) + if (!type.HasFlag(ModDataChangeType.Name) || oldName == null || !TryGetValue(mod, out var leaf)) return; var old = oldName.FixName(); @@ -111,7 +111,7 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer CreateDuplicateLeaf(parent, mod.Name.Text, mod); break; case ModPathChangeType.Deleted: - if (FindLeaf(mod, out var leaf)) + if (TryGetValue(mod, out var leaf)) Delete(leaf); break; @@ -124,16 +124,6 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer } } - // Search the entire filesystem for the leaf corresponding to a mod. - public bool FindLeaf(Mod mod, [NotNullWhen(true)] out Leaf? leaf) - { - leaf = Root.GetAllDescendants(ISortMode.Lexicographical) - .OfType() - .FirstOrDefault(l => l.Value == mod); - return leaf != null; - } - - // Used for saving and loading. private static string ModToIdentifier(Mod mod) => mod.ModPath.Name; From 1961b03d37f651a54a9746f245d6e0e4614188d5 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 15 Jun 2025 23:18:46 +0200 Subject: [PATCH 1251/1381] Fix issues with shapes and attributes with ID. --- .../Cache/ShapeAttributeHashSet.cs | 3 +- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 39 ++++++++++++------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs index e50ceaa2..4c61bdd2 100644 --- a/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs +++ b/Penumbra/Collections/Cache/ShapeAttributeHashSet.cs @@ -120,6 +120,7 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI if (TryGetValue((slot, id.Value), out var flags)) { + index *= 2; var newFlags = value switch { true => (flags | (1ul << index)) & ~(1ul << (index + 1)), @@ -137,7 +138,7 @@ public sealed class ShapeAttributeHashSet : Dictionary<(HumanSlot Slot, PrimaryI if (value is null) return false; - this[(slot, id.Value)] = 1ul << (index + (value.Value ? 0 : 1)); + this[(slot, id.Value)] = 1ul << (2 * index + (value.Value ? 0 : 1)); return true; } diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index a7bfd49c..7b940cd0 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -136,26 +136,33 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { if ((flags & 3) is not 0) { - using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), (flags & 2) is not 0); - ImUtf8.Text($"{slot.ToName()} {id.Id:D4}, "); - ImGui.SameLine(0, 0); + var enabled = (flags & 1) is 1; + + if (set[slot, GenderRace.Unknown] != enabled) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !enabled); + ImUtf8.Text($"{slot.ToName()} {id.Id:D4}, "); + ImGui.SameLine(0, 0); + } } else { - var currentFlags = flags >> 2; - var currentIndex = BitOperations.TrailingZeroCount(currentFlags) / 2; + var currentIndex = BitOperations.TrailingZeroCount(flags) / 2; + var currentFlags = flags >> (2 * currentIndex); while (currentIndex < ShapeAttributeHashSet.GenderRaceValues.Count) { - var value5 = (currentFlags & 1) is 1; - var gr = ShapeAttributeHashSet.GenderRaceValues[currentIndex]; - if (set[slot, gr] != value5) + var enabled = (currentFlags & 1) is 1; + var gr = ShapeAttributeHashSet.GenderRaceValues[currentIndex]; + if (set[slot, gr] != enabled) { - using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !value5); + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGui.GetColorU32(ImGuiCol.TextDisabled), !enabled); ImUtf8.Text($"{gr.ToName()} {slot.ToName()} #{id.Id:D4}, "); + ImGui.SameLine(0, 0); } - currentFlags >>= currentIndex * 2; - currentIndex = BitOperations.TrailingZeroCount(currentFlags) / 2; + currentFlags &= ~0x3u; + currentIndex += BitOperations.TrailingZeroCount(currentFlags) / 2; + currentFlags = flags >> (2 * currentIndex); } } } @@ -167,7 +174,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (!treeNode2) return; - using var table = ImUtf8.Table("##shapes"u8, 6, ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##shapes"u8, 7, ImGuiTableFlags.RowBg); if (!table) return; @@ -175,6 +182,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("ID"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 4); ImUtf8.TableSetupColumn("Count"u8, ImGuiTableColumnFlags.WidthFixed, 30 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Shapes"u8, ImGuiTableColumnFlags.WidthStretch); @@ -193,6 +201,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { var mask = model->EnabledShapeKeyIndexMask; ImUtf8.DrawTableColumn($"{mask:X8}"); + ImUtf8.DrawTableColumn($"{human.GetModelId((HumanSlot)i):D4}"); ImUtf8.DrawTableColumn($"{model->ModelResourceHandle->Shapes.Count}"); ImGui.TableNextColumn(); foreach (var ((shape, flag), idx) in model->ModelResourceHandle->Shapes.WithIndex()) @@ -211,6 +220,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.TableNextColumn(); + ImGui.TableNextColumn(); } } } @@ -221,7 +231,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) if (!treeNode2) return; - using var table = ImUtf8.Table("##attributes"u8, 6, ImGuiTableFlags.RowBg); + using var table = ImUtf8.Table("##attributes"u8, 7, ImGuiTableFlags.RowBg); if (!table) return; @@ -229,6 +239,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImUtf8.TableSetupColumn("Slot"u8, ImGuiTableColumnFlags.WidthFixed, 150 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Address"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 14); ImUtf8.TableSetupColumn("Mask"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 8); + ImUtf8.TableSetupColumn("ID"u8, ImGuiTableColumnFlags.WidthFixed, UiBuilder.MonoFont.GetCharAdvance('0') * 4); ImUtf8.TableSetupColumn("Count"u8, ImGuiTableColumnFlags.WidthFixed, 30 * ImUtf8.GlobalScale); ImUtf8.TableSetupColumn("Attributes"u8, ImGuiTableColumnFlags.WidthStretch); @@ -247,6 +258,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) { var mask = model->EnabledAttributeIndexMask; ImUtf8.DrawTableColumn($"{mask:X8}"); + ImUtf8.DrawTableColumn($"{human.GetModelId((HumanSlot)i):D4}"); ImUtf8.DrawTableColumn($"{model->ModelResourceHandle->Attributes.Count}"); ImGui.TableNextColumn(); foreach (var ((attribute, flag), idx) in model->ModelResourceHandle->Attributes.WithIndex()) @@ -265,6 +277,7 @@ public class ShapeInspector(ObjectManager objects, CollectionResolver resolver) ImGui.TableNextColumn(); ImGui.TableNextColumn(); ImGui.TableNextColumn(); + ImGui.TableNextColumn(); } } } From 3c20b541ce5f5cd93ef5b1038407badb6ea4680c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 15 Jun 2025 23:20:13 +0200 Subject: [PATCH 1252/1381] Make mousewheel-scrolling work for setting combos, also filters. --- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 76 +++++++++++++------- 1 file changed, 50 insertions(+), 26 deletions(-) diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index 3e165cb5..566ec02c 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -15,13 +15,55 @@ using Penumbra.Mods.SubMods; namespace Penumbra.UI.ModsTab.Groups; -public sealed class ModGroupDrawer(Configuration config, CollectionManager collectionManager) : IUiService +public sealed class ModGroupDrawer : IUiService { private readonly List<(IModGroup, int)> _blockGroupCache = []; private bool _temporary; private bool _locked; private TemporaryModSettings? _tempSettings; private ModSettings? _settings; + private readonly SingleGroupCombo _combo; + private readonly Configuration _config; + private readonly CollectionManager _collectionManager; + + public ModGroupDrawer(Configuration config, CollectionManager collectionManager) + { + _config = config; + _collectionManager = collectionManager; + _combo = new SingleGroupCombo(this); + } + + private sealed class SingleGroupCombo(ModGroupDrawer parent) + : FilterComboCache(() => _group!.Options, MouseWheelType.Control, Penumbra.Log) + { + private static IModGroup? _group; + private static int _groupIdx; + + protected override bool DrawSelectable(int globalIdx, bool selected) + { + var option = _group!.Options[globalIdx]; + var ret = ImUtf8.Selectable(option.Name, globalIdx == CurrentSelectionIdx); + + if (option.Description.Length > 0) + ImUtf8.SelectableHelpMarker(option.Description); + + return ret; + } + + protected override string ToString(IModOption obj) + => obj.Name; + + public void Draw(IModGroup group, int groupIndex, int currentOption) + { + _group = group; + _groupIdx = groupIndex; + CurrentSelectionIdx = currentOption; + CurrentSelection = _group.Options[CurrentSelectionIdx]; + if (Draw(string.Empty, CurrentSelection.Name, string.Empty, ref CurrentSelectionIdx, UiHelpers.InputTextWidth.X * 3 / 4, + ImGui.GetTextLineHeightWithSpacing())) + parent.SetModSetting(_group, _groupIdx, Setting.Single(CurrentSelectionIdx)); + } + } public void Draw(Mod mod, ModSettings settings, TemporaryModSettings? tempSettings) { @@ -41,7 +83,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle switch (group.Behaviour) { - case GroupDrawBehaviour.SingleSelection when group.Options.Count <= config.SingleGroupRadioMax: + case GroupDrawBehaviour.SingleSelection when group.Options.Count <= _config.SingleGroupRadioMax: case GroupDrawBehaviour.MultiSelection: _blockGroupCache.Add((group, idx)); break; @@ -76,25 +118,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle using var id = ImUtf8.PushId(groupIdx); var selectedOption = setting.AsIndex; using var disabled = ImRaii.Disabled(_locked); - ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X * 3 / 4); - var options = group.Options; - using (var combo = ImUtf8.Combo(""u8, options[selectedOption].Name)) - { - if (combo) - for (var idx2 = 0; idx2 < options.Count; ++idx2) - { - id.Push(idx2); - var option = options[idx2]; - if (ImUtf8.Selectable(option.Name, idx2 == selectedOption)) - SetModSetting(group, groupIdx, Setting.Single(idx2)); - - if (option.Description.Length > 0) - ImUtf8.SelectableHelpMarker(option.Description); - - id.Pop(); - } - } - + _combo.Draw(group, groupIdx, selectedOption); ImGui.SameLine(); if (group.Description.Length > 0) ImUtf8.LabeledHelpMarker(group.Name, group.Description); @@ -195,7 +219,7 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle private void DrawCollapseHandling(IReadOnlyList options, float minWidth, Action draw) { - if (options.Count <= config.OptionGroupCollapsibleMin) + if (options.Count <= _config.OptionGroupCollapsibleMin) { draw(); } @@ -240,21 +264,21 @@ public sealed class ModGroupDrawer(Configuration config, CollectionManager colle } private ModCollection Current - => collectionManager.Active.Current; + => _collectionManager.Active.Current; [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] private void SetModSetting(IModGroup group, int groupIdx, Setting setting) { - if (_temporary || config.DefaultTemporaryMode) + if (_temporary || _config.DefaultTemporaryMode) { _tempSettings ??= new TemporaryModSettings(group.Mod, _settings); _tempSettings!.ForceInherit = false; _tempSettings!.Settings[groupIdx] = setting; - collectionManager.Editor.SetTemporarySettings(Current, group.Mod, _tempSettings); + _collectionManager.Editor.SetTemporarySettings(Current, group.Mod, _tempSettings); } else { - collectionManager.Editor.SetModSetting(Current, group.Mod, groupIdx, setting); + _collectionManager.Editor.SetModSetting(Current, group.Mod, groupIdx, setting); } } } From 9fc572ba0cb198a3acbf0bd98a696e243c2bc433 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 15 Jun 2025 21:47:41 +0000 Subject: [PATCH 1253/1381] [CI] Updating repo.json for testing_1.4.0.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a6cec268..e12c3c9d 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.4.0.1", - "TestingAssemblyVersion": "1.4.0.3", + "TestingAssemblyVersion": "1.4.0.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 62e9dc164d624c13ef13d023e4501ee1e4f755eb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 26 Jun 2025 14:49:12 +0200 Subject: [PATCH 1254/1381] Add support button. --- OtterGui | 2 +- Penumbra/Penumbra.cs | 6 ++++-- Penumbra/UI/Tabs/SettingsTab.cs | 11 +++++++++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/OtterGui b/OtterGui index 78528f93..2c3c32bf 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 78528f93ac253db0061d9a8244cfa0cee5c2f873 +Subproject commit 2c3c32bfb7057d7be7678f413122c2b1453050d5 diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 70636bbf..cf96c7f6 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -229,10 +229,12 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Auto-UI-Reduplication: `** {_config.AutoReduplicateUiOnImport}\n"); sb.Append($"> **`Debug Mode: `** {_config.DebugMode}\n"); sb.Append($"> **`Penumbra Reloads: `** {hdrEnabler.PenumbraReloadCount}\n"); - sb.Append($"> **`HDR Enabled (from Start): `** {_config.HdrRenderTargets} ({hdrEnabler is { FirstLaunchHdrState: true, FirstLaunchHdrHookOverrideState: true }}){(hdrEnabler.HdrEnabledSuccess ? ", Detour Called" : ", **NEVER CALLED**")}\n"); + sb.Append( + $"> **`HDR Enabled (from Start): `** {_config.HdrRenderTargets} ({hdrEnabler is { FirstLaunchHdrState: true, FirstLaunchHdrHookOverrideState: true }}){(hdrEnabler.HdrEnabledSuccess ? ", Detour Called" : ", **NEVER CALLED**")}\n"); sb.Append($"> **`Custom Shapes Enabled: `** {_config.EnableCustomShapes}\n"); sb.Append($"> **`Hook Overrides: `** {HookOverrides.Instance.IsCustomLoaded}\n"); - sb.Append($"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")} (first Start: {hdrEnabler.FirstLaunchWaitForPluginsState?.ToString() ?? "Unknown"})\n"); + sb.Append( + $"> **`Synchronous Load (Dalamud): `** {(_services.GetService().GetDalamudConfig(DalamudConfigService.WaitingForPluginsOption, out bool v) ? v.ToString() : "Unknown")} (first Start: {hdrEnabler.FirstLaunchWaitForPluginsState?.ToString() ?? "Unknown"})\n"); sb.Append( $"> **`Logging: `** Log: {_config.Ephemeral.EnableResourceLogging}, Watcher: {_config.Ephemeral.EnableResourceWatcher} ({_config.MaxResourceWatcherRecords})\n"); sb.Append($"> **`Use Ownership: `** {_config.UseOwnerNameForCharacterCollection}\n"); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 4bbdf2a9..c1aea97c 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -12,6 +12,7 @@ using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; using OtterGui.Widgets; +using OtterGuiInternal.Enums; using Penumbra.Api; using Penumbra.Collections; using Penumbra.Interop.Hooks.PostProcessing; @@ -20,6 +21,7 @@ using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.Classes; using Penumbra.UI.ModsTab; +using ImGuiId = OtterGuiInternal.Enums.ImGuiId; namespace Penumbra.UI.Tabs; @@ -113,6 +115,7 @@ public class SettingsTab : ITab, IUiService DrawRootFolder(); DrawDirectoryButtons(); ImGui.NewLine(); + ImGui.NewLine(); DrawGeneralSettings(); _migrationDrawer.Draw(); @@ -761,8 +764,9 @@ public class SettingsTab : ITab, IUiService "Normally, metadata changes that equal their default values, which are sometimes exported by TexTools, are discarded. " + "Toggle this to keep them, for example if an option in a mod is supposed to disable a metadata change from a prior option.", _config.KeepDefaultMetaChanges, v => _config.KeepDefaultMetaChanges = v); - Checkbox("Enable Custom Shape and Attribute Support", "Penumbra will allow for custom shape keys and attributes for modded models to be considered and combined.", - _config.EnableCustomShapes, _attributeHook.SetState); + Checkbox("Enable Custom Shape and Attribute Support", + "Penumbra will allow for custom shape keys and attributes for modded models to be considered and combined.", + _config.EnableCustomShapes, _attributeHook.SetState); DrawWaitForPluginsReflection(); DrawEnableHttpApiBox(); DrawEnableDebugModeBox(); @@ -1050,6 +1054,9 @@ public class SettingsTab : ITab, IUiService ImGui.SetCursorPos(new Vector2(xPos, 4 * ImGui.GetFrameHeightWithSpacing())); if (ImGui.Button("Show Changelogs", new Vector2(width, 0))) _penumbra.ForceChangelogOpen(); + + ImGui.SetCursorPos(new Vector2(xPos, 5 * ImGui.GetFrameHeightWithSpacing())); + CustomGui.DrawKofiPatreonButton(Penumbra.Messager, new Vector2(width, 0)); } private void DrawPredefinedTagsSection() From 30e3cd1f383ce9c9c2a1e2927518993d9be9ad1c Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 4 Jul 2025 19:41:31 +0200 Subject: [PATCH 1255/1381] Add OS thread ID info to the Resource Logger --- Penumbra/Interop/ProcessThreadApi.cs | 7 +++++++ Penumbra/UI/ResourceWatcher/Record.cs | 9 +++++++++ .../UI/ResourceWatcher/ResourceWatcherTable.cs | 18 +++++++++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 Penumbra/Interop/ProcessThreadApi.cs diff --git a/Penumbra/Interop/ProcessThreadApi.cs b/Penumbra/Interop/ProcessThreadApi.cs new file mode 100644 index 00000000..5ee213d9 --- /dev/null +++ b/Penumbra/Interop/ProcessThreadApi.cs @@ -0,0 +1,7 @@ +namespace Penumbra.Interop; + +public static partial class ProcessThreadApi +{ + [LibraryImport("kernel32.dll")] + public static partial uint GetCurrentThreadId(); +} diff --git a/Penumbra/UI/ResourceWatcher/Record.cs b/Penumbra/UI/ResourceWatcher/Record.cs index b8730750..ba718bc9 100644 --- a/Penumbra/UI/ResourceWatcher/Record.cs +++ b/Penumbra/UI/ResourceWatcher/Record.cs @@ -1,6 +1,7 @@ using OtterGui.Classes; using Penumbra.Collections; using Penumbra.Enums; +using Penumbra.Interop; using Penumbra.Interop.Structs; using Penumbra.String; using Penumbra.String.Classes; @@ -34,6 +35,7 @@ internal unsafe struct Record public OptionalBool ReturnValue; public OptionalBool CustomLoad; public LoadState LoadState; + public uint OsThreadId; public static Record CreateRequest(CiByteString path, bool sync) @@ -54,6 +56,7 @@ internal unsafe struct Record AssociatedGameObject = string.Empty, LoadState = LoadState.None, Crc64 = 0, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; public static Record CreateRequest(CiByteString path, bool sync, FullPath fullPath, ResolveData resolve) @@ -74,6 +77,7 @@ internal unsafe struct Record AssociatedGameObject = string.Empty, LoadState = LoadState.None, Crc64 = fullPath.Crc64, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; public static Record CreateDefaultLoad(CiByteString path, ResourceHandle* handle, ModCollection collection, string associatedGameObject) @@ -96,6 +100,7 @@ internal unsafe struct Record AssociatedGameObject = associatedGameObject, LoadState = handle->LoadState, Crc64 = 0, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; } @@ -118,6 +123,7 @@ internal unsafe struct Record AssociatedGameObject = associatedGameObject, LoadState = handle->LoadState, Crc64 = path.Crc64, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; public static Record CreateDestruction(ResourceHandle* handle) @@ -140,6 +146,7 @@ internal unsafe struct Record AssociatedGameObject = string.Empty, LoadState = handle->LoadState, Crc64 = 0, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; } @@ -161,6 +168,7 @@ internal unsafe struct Record AssociatedGameObject = string.Empty, LoadState = handle->LoadState, Crc64 = 0, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; public static Record CreateResourceComplete(CiByteString path, ResourceHandle* handle, Utf8GamePath originalPath, ReadOnlySpan additionalData) @@ -181,6 +189,7 @@ internal unsafe struct Record AssociatedGameObject = string.Empty, LoadState = handle->LoadState, Crc64 = 0, + OsThreadId = ProcessThreadApi.GetCurrentThreadId(), }; private static CiByteString CombinedPath(CiByteString path, ReadOnlySpan additionalData) diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index a58d74d1..009da842 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -30,7 +30,8 @@ internal sealed class ResourceWatcherTable : Table new LoadStateColumn { Label = "State" }, new RefCountColumn { Label = "#Ref" }, new DateColumn { Label = "Time" }, - new Crc64Column { Label = "Crc64" } + new Crc64Column { Label = "Crc64" }, + new OsThreadColumn { Label = "TID" } ) { } @@ -453,4 +454,19 @@ internal sealed class ResourceWatcherTable : Table public override int Compare(Record lhs, Record rhs) => lhs.RefCount.CompareTo(rhs.RefCount); } + + private sealed class OsThreadColumn : ColumnString + { + public override float Width + => 60 * UiHelpers.Scale; + + public override string ToName(Record item) + => item.OsThreadId.ToString(); + + public override void DrawColumn(Record item, int _) + => ImGuiUtil.RightAlign(ToName(item)); + + public override int Compare(Record lhs, Record rhs) + => lhs.OsThreadId.CompareTo(rhs.OsThreadId); + } } From a97d9e49531ace985eeef1c305bdd123b11dfa38 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 5 Jul 2025 04:37:37 +0200 Subject: [PATCH 1256/1381] Add Human skin material handling --- .../Hooks/Resources/ResolvePathHooksBase.cs | 40 ++++++++----- .../Interop/ResourceTree/ResolveContext.cs | 9 ++- Penumbra/Interop/ResourceTree/ResourceTree.cs | 12 +++- Penumbra/Interop/Structs/StructExtensions.cs | 60 +++++++++++-------- 4 files changed, 76 insertions(+), 45 deletions(-) diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 8a45ec2c..85fb1098 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -35,6 +35,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private readonly Hook _resolveMPapPathHook; private readonly Hook _resolveMdlPathHook; private readonly Hook _resolveMtrlPathHook; + private readonly Hook _resolveSkinMtrlPathHook; private readonly Hook _resolvePapPathHook; private readonly Hook _resolveKdbPathHook; private readonly Hook _resolvePhybPathHook; @@ -52,22 +53,23 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable { _parent = parent; // @formatter:off - _resolveSklbPathHook = Create($"{name}.{nameof(ResolveSklb)}", hooks, vTable[76], type, ResolveSklb, ResolveSklbHuman); - _resolveMdlPathHook = Create($"{name}.{nameof(ResolveMdl)}", hooks, vTable[77], type, ResolveMdl, ResolveMdlHuman); - _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[78], type, ResolveSkp, ResolveSkpHuman); - _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[79], type, ResolvePhyb, ResolvePhybHuman); - _resolveKdbPathHook = Create($"{name}.{nameof(ResolveKdb)}", hooks, vTable[80], type, ResolveKdb, ResolveKdbHuman); - _vFunc81Hook = Create( $"{name}.{nameof(VFunc81)}", hooks, vTable[81], type, null, VFunc81); - _resolveBnmbPathHook = Create($"{name}.{nameof(ResolveBnmb)}", hooks, vTable[82], type, ResolveBnmb, ResolveBnmbHuman); - _vFunc83Hook = Create( $"{name}.{nameof(VFunc83)}", hooks, vTable[83], type, null, VFunc83); - _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[84], type, ResolvePap, ResolvePapHuman); - _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[85], ResolveTmb); - _resolveMPapPathHook = Create( $"{name}.{nameof(ResolveMPap)}", hooks, vTable[87], ResolveMPap); - _resolveImcPathHook = Create($"{name}.{nameof(ResolveImc)}", hooks, vTable[89], ResolveImc); - _resolveMtrlPathHook = Create( $"{name}.{nameof(ResolveMtrl)}", hooks, vTable[90], ResolveMtrl); - _resolveDecalPathHook = Create($"{name}.{nameof(ResolveDecal)}", hooks, vTable[92], ResolveDecal); - _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[93], type, ResolveVfx, ResolveVfxHuman); - _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[94], ResolveEid); + _resolveSklbPathHook = Create($"{name}.{nameof(ResolveSklb)}", hooks, vTable[76], type, ResolveSklb, ResolveSklbHuman); + _resolveMdlPathHook = Create($"{name}.{nameof(ResolveMdl)}", hooks, vTable[77], type, ResolveMdl, ResolveMdlHuman); + _resolveSkpPathHook = Create($"{name}.{nameof(ResolveSkp)}", hooks, vTable[78], type, ResolveSkp, ResolveSkpHuman); + _resolvePhybPathHook = Create($"{name}.{nameof(ResolvePhyb)}", hooks, vTable[79], type, ResolvePhyb, ResolvePhybHuman); + _resolveKdbPathHook = Create($"{name}.{nameof(ResolveKdb)}", hooks, vTable[80], type, ResolveKdb, ResolveKdbHuman); + _vFunc81Hook = Create( $"{name}.{nameof(VFunc81)}", hooks, vTable[81], type, null, VFunc81); + _resolveBnmbPathHook = Create($"{name}.{nameof(ResolveBnmb)}", hooks, vTable[82], type, ResolveBnmb, ResolveBnmbHuman); + _vFunc83Hook = Create( $"{name}.{nameof(VFunc83)}", hooks, vTable[83], type, null, VFunc83); + _resolvePapPathHook = Create( $"{name}.{nameof(ResolvePap)}", hooks, vTable[84], type, ResolvePap, ResolvePapHuman); + _resolveTmbPathHook = Create( $"{name}.{nameof(ResolveTmb)}", hooks, vTable[85], ResolveTmb); + _resolveMPapPathHook = Create( $"{name}.{nameof(ResolveMPap)}", hooks, vTable[87], ResolveMPap); + _resolveImcPathHook = Create($"{name}.{nameof(ResolveImc)}", hooks, vTable[89], ResolveImc); + _resolveMtrlPathHook = Create( $"{name}.{nameof(ResolveMtrl)}", hooks, vTable[90], ResolveMtrl); + _resolveSkinMtrlPathHook = Create($"{name}.{nameof(ResolveSkinMtrl)}", hooks, vTable[91], ResolveSkinMtrl); + _resolveDecalPathHook = Create($"{name}.{nameof(ResolveDecal)}", hooks, vTable[92], ResolveDecal); + _resolveVfxPathHook = Create( $"{name}.{nameof(ResolveVfx)}", hooks, vTable[93], type, ResolveVfx, ResolveVfxHuman); + _resolveEidPathHook = Create( $"{name}.{nameof(ResolveEid)}", hooks, vTable[94], ResolveEid); // @formatter:on @@ -83,6 +85,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMPapPathHook.Enable(); _resolveMdlPathHook.Enable(); _resolveMtrlPathHook.Enable(); + _resolveSkinMtrlPathHook.Enable(); _resolvePapPathHook.Enable(); _resolveKdbPathHook.Enable(); _resolvePhybPathHook.Enable(); @@ -103,6 +106,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMPapPathHook.Disable(); _resolveMdlPathHook.Disable(); _resolveMtrlPathHook.Disable(); + _resolveSkinMtrlPathHook.Disable(); _resolvePapPathHook.Disable(); _resolveKdbPathHook.Disable(); _resolvePhybPathHook.Disable(); @@ -123,6 +127,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable _resolveMPapPathHook.Dispose(); _resolveMdlPathHook.Dispose(); _resolveMtrlPathHook.Dispose(); + _resolveSkinMtrlPathHook.Dispose(); _resolvePapPathHook.Dispose(); _resolveKdbPathHook.Dispose(); _resolvePhybPathHook.Dispose(); @@ -153,6 +158,9 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolveMtrl(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex, nint mtrlFileName) => ResolvePath(drawObject, _resolveMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex, mtrlFileName)); + private nint ResolveSkinMtrl(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) + => ResolvePath(drawObject, _resolveSkinMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); + private nint ResolvePap(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) => ResolvePath(drawObject, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 013d7db7..64a91302 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -188,7 +188,8 @@ internal unsafe partial record ResolveContext( return GetOrCreateNode(ResourceType.Tex, (nint)tex->Texture, &tex->ResourceHandle, gamePath); } - public ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc, TextureResourceHandle* decalHandle, ResourceHandle* mpapHandle) + public ResourceNode? CreateNodeFromModel(Model* mdl, ResourceHandle* imc, TextureResourceHandle* decalHandle, + MaterialResourceHandle* skinMtrlHandle, ResourceHandle* mpapHandle) { if (mdl is null || mdl->ModelResourceHandle is null) return null; @@ -218,6 +219,12 @@ internal unsafe partial record ResolveContext( } } + if (skinMtrlHandle is not null + && Utf8GamePath.FromByteString(CharacterBase->ResolveSkinMtrlPathAsByteString(SlotIndex), out var skinMtrlPath) + && CreateNodeFromMaterial(skinMtrlHandle->Material, skinMtrlPath) is + { } skinMaaterialNode) + node.Children.Add(skinMaaterialNode); + if (CreateNodeFromDecal(decalHandle, imc) is { } decalNode) node.Children.Add(decalNode); diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 7be8694a..97a926ad 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -73,6 +73,12 @@ public class ResourceTree( // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) var mpapArrayPtr = *(ResourceHandle***)((nint)model + 0x948); var mpapArray = mpapArrayPtr is not null ? new ReadOnlySpan>(mpapArrayPtr, model->SlotCount) : []; + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1474) + var skinMtrlArray = modelType switch + { + ModelType.Human => new ReadOnlySpan>((MaterialResourceHandle**)((nint)model + 0xB48), 5), + _ => [], + }; var decalArray = modelType switch { ModelType.Human => human->SlotDecalsSpan, @@ -108,7 +114,8 @@ public class ResourceTree( var mdl = model->Models[i]; if (slotContext.CreateNodeFromModel(mdl, imc, i < decalArray.Length ? decalArray[(int)i].Value : null, - i < mpapArray.Length ? mpapArray[(int)i].Value : null) is { } mdlNode) + i < skinMtrlArray.Length ? skinMtrlArray[(int)i].Value : null, i < mpapArray.Length ? mpapArray[(int)i].Value : null) is + { } mdlNode) { if (globalContext.WithUiData) mdlNode.FallbackName = $"Model #{i}"; @@ -166,7 +173,8 @@ public class ResourceTree( } var mdl = subObject->Models[i]; - if (slotContext.CreateNodeFromModel(mdl, imc, weapon->Decal, i < mpapArray.Length ? mpapArray[i].Value : null) is { } mdlNode) + if (slotContext.CreateNodeFromModel(mdl, imc, weapon->Decal, null, i < mpapArray.Length ? mpapArray[i].Value : null) is + { } mdlNode) { if (globalContext.WithUiData) mdlNode.FallbackName = $"Weapon #{weaponIndex}, Model #{i}"; diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 03b4cf36..62dca02e 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -10,28 +10,36 @@ internal static class StructExtensions public static CiByteString AsByteString(in this StdString str) => CiByteString.FromSpanUnsafe(str.AsSpan(), true); - public static CiByteString ResolveEidPathAsByteString(ref this CharacterBase character) - { - Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(character.ResolveEidPath(pathBuffer)); - } - - public static CiByteString ResolveImcPathAsByteString(ref this CharacterBase character, uint slotIndex) - { - Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(character.ResolveImcPath(pathBuffer, slotIndex)); + public static CiByteString ResolveEidPathAsByteString(ref this CharacterBase character) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveEidPath(pathBuffer)); } - public static CiByteString ResolveMdlPathAsByteString(ref this CharacterBase character, uint slotIndex) - { - Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(character.ResolveMdlPath(pathBuffer, slotIndex)); + public static CiByteString ResolveImcPathAsByteString(ref this CharacterBase character, uint slotIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveImcPath(pathBuffer, slotIndex)); } - public static unsafe CiByteString ResolveMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex, byte* mtrlFileName) - { - var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(character.ResolveMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex, mtrlFileName)); + public static CiByteString ResolveMdlPathAsByteString(ref this CharacterBase character, uint slotIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveMdlPath(pathBuffer, slotIndex)); + } + + public static unsafe CiByteString ResolveMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex, byte* mtrlFileName) + { + var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex, mtrlFileName)); + } + + public static unsafe CiByteString ResolveSkinMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex) + { + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1474) + var vf91 = (delegate* unmanaged)((nint*)character.VirtualTable)[91]; + var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(vf91((CharacterBase*)Unsafe.AsPointer(ref character), pathBuffer, CharacterBase.PathBufferSize, slotIndex)); } public static CiByteString ResolveMaterialPapPathAsByteString(ref this CharacterBase character, uint slotIndex, uint unkSId) @@ -40,16 +48,16 @@ internal static class StructExtensions return ToOwnedByteString(character.ResolveMaterialPapPath(pathBuffer, slotIndex, unkSId)); } - public static CiByteString ResolveSklbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) - { - Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(character.ResolveSklbPath(pathBuffer, partialSkeletonIndex)); + public static CiByteString ResolveSklbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveSklbPath(pathBuffer, partialSkeletonIndex)); } - public static CiByteString ResolveSkpPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) - { - Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(character.ResolveSkpPath(pathBuffer, partialSkeletonIndex)); + public static CiByteString ResolveSkpPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) + { + Span pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(character.ResolveSkpPath(pathBuffer, partialSkeletonIndex)); } public static CiByteString ResolvePhybPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) From 278bf43b29809ff4c0657921311f8581c820b9b8 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 5 Jul 2025 05:20:24 +0200 Subject: [PATCH 1257/1381] ClientStructs-ify ResourceTree stuff --- Penumbra/Interop/ResourceTree/ResourceTree.cs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 97a926ad..e7c4b11b 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -70,8 +70,7 @@ public class ResourceTree( var genericContext = globalContext.CreateContext(model); - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) - var mpapArrayPtr = *(ResourceHandle***)((nint)model + 0x948); + var mpapArrayPtr = model->MaterialAnimationPacks; var mpapArray = mpapArrayPtr is not null ? new ReadOnlySpan>(mpapArrayPtr, model->SlotCount) : []; // TODO ClientStructs-ify (aers/FFXIVClientStructs#1474) var skinMtrlArray = modelType switch @@ -124,8 +123,7 @@ public class ResourceTree( } AddSkeleton(Nodes, genericContext, model->EID, model->Skeleton, model->BonePhysicsModule); - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) - AddMaterialAnimationSkeleton(Nodes, genericContext, *(SkeletonResourceHandle**)((nint)model + 0x940)); + AddMaterialAnimationSkeleton(Nodes, genericContext, model->MaterialAnimationSkeleton); AddWeapons(globalContext, model); @@ -156,8 +154,7 @@ public class ResourceTree( var genericContext = globalContext.CreateContext(subObject, 0xFFFFFFFFu, slot, equipment, weaponType); - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) - var mpapArrayPtr = *(ResourceHandle***)((nint)subObject + 0x948); + var mpapArrayPtr = subObject->MaterialAnimationPacks; var mpapArray = mpapArrayPtr is not null ? new ReadOnlySpan>(mpapArrayPtr, subObject->SlotCount) : []; for (var i = 0; i < subObject->SlotCount; ++i) @@ -184,8 +181,7 @@ public class ResourceTree( AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, subObject->BonePhysicsModule, $"Weapon #{weaponIndex}, "); - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) - AddMaterialAnimationSkeleton(weaponNodes, genericContext, *(SkeletonResourceHandle**)((nint)subObject + 0x940), + AddMaterialAnimationSkeleton(weaponNodes, genericContext, subObject->MaterialAnimationSkeleton, $"Weapon #{weaponIndex}, "); ++weaponIndex; @@ -263,7 +259,7 @@ public class ResourceTree( for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) { - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1312) + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1475) var phybHandle = physics != null ? ((ResourceHandle**)((nint)physics + 0x190))[i] : null; if (context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, (uint)i) is { } sklbNode) { From a953febfba522579b338d2c8015e3dcfd6315168 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 5 Jul 2025 21:59:20 +0200 Subject: [PATCH 1258/1381] Add support for imc-toggle attributes to accessories, and fix up attributes when item swapping models. --- Penumbra/Meta/ShapeAttributeManager.cs | 64 +++++++++++++++++++++++++ Penumbra/Mods/ItemSwap/EquipmentSwap.cs | 49 ++++++++++++++++++- 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/Penumbra/Meta/ShapeAttributeManager.cs b/Penumbra/Meta/ShapeAttributeManager.cs index a742806f..16901741 100644 --- a/Penumbra/Meta/ShapeAttributeManager.cs +++ b/Penumbra/Meta/ShapeAttributeManager.cs @@ -1,3 +1,4 @@ +using System.Collections.Frozen; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Cache; @@ -5,6 +6,8 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.PostProcessing; +using Penumbra.Interop.Structs; +using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Meta; @@ -58,11 +61,72 @@ public unsafe class ShapeAttributeManager : IRequiredService, IDisposable _ids[(int)_modelIndex] = model.GetModelId(_modelIndex); CheckShapes(collection.MetaCache!.Shp); CheckAttributes(collection.MetaCache!.Atr); + if (_modelIndex is <= HumanSlot.LFinger and >= HumanSlot.Ears) + AccessoryImcCheck(model); } UpdateDefaultMasks(model, collection.MetaCache!.Shp); } + private void AccessoryImcCheck(Model model) + { + var imcMask = (ushort)(0x03FF & *(ushort*)(model.Address + 0xAAC + 6 * (int)_modelIndex)); + + Span attr = + [ + (byte)'a', + (byte)'t', + (byte)'r', + (byte)'_', + AccessoryByte(_modelIndex), + (byte)'v', + (byte)'_', + (byte)'a', + 0, + ]; + for (var i = 1; i < 10; ++i) + { + var flag = (ushort)(1 << i); + if ((imcMask & flag) is not 0) + continue; + + attr[^2] = (byte)('a' + i); + + foreach (var (attribute, index) in _model->ModelResourceHandle->Attributes) + { + if (!EqualAttribute(attr, attribute.Value)) + continue; + + _model->EnabledAttributeIndexMask &= ~(1u << index); + break; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] + private static bool EqualAttribute(Span needle, byte* haystack) + { + foreach (var character in needle) + { + if (*haystack++ != character) + return false; + } + + return true; + } + + private static byte AccessoryByte(HumanSlot slot) + => slot switch + { + HumanSlot.Head => (byte)'m', + HumanSlot.Ears => (byte)'e', + HumanSlot.Neck => (byte)'n', + HumanSlot.Wrists => (byte)'w', + HumanSlot.RFinger => (byte)'r', + HumanSlot.LFinger => (byte)'r', + _ => 0, + }; + private void CheckAttributes(AtrCache attributeCache) { if (attributeCache.DisabledCount is 0) diff --git a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs index 5c67df52..216b5841 100644 --- a/Penumbra/Mods/ItemSwap/EquipmentSwap.cs +++ b/Penumbra/Mods/ItemSwap/EquipmentSwap.cs @@ -234,9 +234,56 @@ public static class EquipmentSwap mdl.ChildSwaps.Add(mtrl); } + FixAttributes(mdl, slotFrom, slotTo); + return mdl; } + private static void FixAttributes(FileSwap swap, EquipSlot slotFrom, EquipSlot slotTo) + { + if (slotFrom == slotTo) + return; + + var needle = slotTo switch + { + EquipSlot.Head => "atr_mv_", + EquipSlot.Ears => "atr_ev_", + EquipSlot.Neck => "atr_nv_", + EquipSlot.Wrists => "atr_wv_", + EquipSlot.RFinger or EquipSlot.LFinger => "atr_rv_", + _ => string.Empty, + }; + + var replacement = slotFrom switch + { + EquipSlot.Head => 'm', + EquipSlot.Ears => 'e', + EquipSlot.Neck => 'n', + EquipSlot.Wrists => 'w', + EquipSlot.RFinger or EquipSlot.LFinger => 'r', + _ => 'm', + }; + + var attributes = swap.AsMdl()!.Attributes; + for (var i = 0; i < attributes.Length; ++i) + { + if (FixAttribute(ref attributes[i], needle, replacement)) + swap.DataWasChanged = true; + } + } + + private static unsafe bool FixAttribute(ref string attribute, string from, char to) + { + if (!attribute.StartsWith(from) || attribute.Length != from.Length + 1 || attribute[^1] is < 'a' or > 'j') + return false; + + Span stack = stackalloc char[attribute.Length]; + attribute.CopyTo(stack); + stack[4] = to; + attribute = new string(stack); + return true; + } + private static void LookupItem(EquipItem i, out EquipSlot slot, out PrimaryId modelId, out Variant variant) { slot = i.Type.ToSlot(); @@ -399,7 +446,7 @@ public static class EquipmentSwap return null; var folderTo = GamePaths.Mtrl.GearFolder(slotTo, idTo, variantTo); - var pathTo = $"{folderTo}{fileName}"; + var pathTo = $"{folderTo}{fileName}"; var folderFrom = GamePaths.Mtrl.GearFolder(slotFrom, idFrom, variantTo); var newFileName = ItemSwap.ReplaceId(fileName, prefix, idTo, idFrom); From 49a6d935f3d0bd149442003f727f0f8a85b07019 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 5 Jul 2025 20:11:28 +0000 Subject: [PATCH 1259/1381] [CI] Updating repo.json for testing_1.4.0.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index e12c3c9d..f0bf9a4a 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.4.0.1", - "TestingAssemblyVersion": "1.4.0.4", + "TestingAssemblyVersion": "1.4.0.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 140d150bb4b1c64051673811aa8cf349b2c56c80 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 14 Jul 2025 17:08:46 +0200 Subject: [PATCH 1260/1381] Fix character sound data. --- Penumbra/Interop/GameState.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs index 95cef468..32b45b7e 100644 --- a/Penumbra/Interop/GameState.cs +++ b/Penumbra/Interop/GameState.cs @@ -60,7 +60,7 @@ public class GameState : IService private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); public ResolveData SoundData - => _animationLoadData.Value; + => _characterSoundData.Value; [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] public ResolveData SetSoundData(ResolveData data) From 00c02fd16e641eb40933010c48ea1e32602213b0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 14 Jul 2025 17:09:07 +0200 Subject: [PATCH 1261/1381] Fix tex file migration for small textures. --- Penumbra/Import/Textures/TexFileParser.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Penumbra/Import/Textures/TexFileParser.cs b/Penumbra/Import/Textures/TexFileParser.cs index 6a12a0dd..04bbf5d8 100644 --- a/Penumbra/Import/Textures/TexFileParser.cs +++ b/Penumbra/Import/Textures/TexFileParser.cs @@ -95,7 +95,8 @@ public static class TexFileParser if (width == minSize && height == minSize) { - newSize = totalSize; + ++i; + newSize = totalSize + requiredSize; if (header.MipCount != i) { Penumbra.Log.Debug($"-- Reduced number of Mip Maps from {header.MipCount} to {i} due to minimum size constraints."); From a4a6283e7b007a5d4f019ee12565887eabc235ad Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 14 Jul 2025 15:12:06 +0000 Subject: [PATCH 1262/1381] [CI] Updating repo.json for testing_1.4.0.6 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index f0bf9a4a..af368d75 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.4.0.1", - "TestingAssemblyVersion": "1.4.0.5", + "TestingAssemblyVersion": "1.4.0.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.6/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a9546e31eed28555f00bd724f9c00106a40e9da3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Aug 2025 00:05:27 +0200 Subject: [PATCH 1263/1381] Update packages. --- .../Import/Models/Import/VertexAttribute.cs | 2 +- Penumbra/Penumbra.csproj | 10 ++--- Penumbra/packages.lock.json | 44 +++++++++---------- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Penumbra/Import/Models/Import/VertexAttribute.cs b/Penumbra/Import/Models/Import/VertexAttribute.cs index a1c3246b..155fa833 100644 --- a/Penumbra/Import/Models/Import/VertexAttribute.cs +++ b/Penumbra/Import/Models/Import/VertexAttribute.cs @@ -319,7 +319,7 @@ public class VertexAttribute var normals = normalAccessor.AsVector3Array(); var tangents = accessors.TryGetValue("TANGENT", out var accessor) - ? accessor.AsVector4Array() + ? accessor.AsVector4Array().ToArray() : CalculateTangents(accessors, indices, normals, notifier); if (tangents == null) diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index f668f775..c61692f4 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -57,11 +57,11 @@ - - - - - + + + + + diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 4a162f8f..778f776e 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -19,9 +19,9 @@ }, "PeNet": { "type": "Direct", - "requested": "[4.1.1, )", - "resolved": "4.1.1", - "contentHash": "TiRyOVcg1Bh2FyP6Dm2NEiYzemSlQderhaxuH3XWNyTYsnHrm1n/xvoTftgMwsWD4C/3kTqJw93oZOvHojJfKg==", + "requested": "[5.1.0, )", + "resolved": "5.1.0", + "contentHash": "XSd1PUwWo5uI8iqVHk7Mm02RT1bjndtAYsaRwLmdYZoHOAmb4ohkvRcZiqxJ7iLfBfdiwm+PHKQIMqDmOavBtw==", "dependencies": { "PeNet.Asn1": "2.0.1", "System.Security.Cryptography.Pkcs": "8.0.1" @@ -29,34 +29,34 @@ }, "SharpCompress": { "type": "Direct", - "requested": "[0.39.0, )", - "resolved": "0.39.0", - "contentHash": "0esqIUDlg68Z7+Weuge4QzEvNtawUO4obTJFL7xuf4DBHMxVRr+wbNgiX9arMrj3kGXQSvLe0zbZG3oxpkwJOA==", + "requested": "[0.40.0, )", + "resolved": "0.40.0", + "contentHash": "yP/aFX1jqGikVF7u2f05VEaWN4aCaKNLxSas82UgA2GGVECxq/BcqZx3STHCJ78qilo1azEOk1XpBglIuGMb7w==", "dependencies": { "System.Buffers": "4.6.0", - "ZstdSharp.Port": "0.8.4" + "ZstdSharp.Port": "0.8.5" } }, "SharpGLTF.Core": { "type": "Direct", - "requested": "[1.0.3, )", - "resolved": "1.0.3", - "contentHash": "su+Flcg2g6GgOIgulRGBDMHA6zY5NBx6NYH1Ayd6iBbSbwspHsN2VQgZfANgJy92cBf7qtpjC0uMiShbO+TEEg==" + "requested": "[1.0.5, )", + "resolved": "1.0.5", + "contentHash": "HNHKPqaHXm7R1nlXZ764K5UI02IeDOQ5DQKLjwYUVNTsSW27jJpw+wLGQx6ZFoiFYqUlyZjmsu+WfEak2GmJAg==" }, "SharpGLTF.Toolkit": { "type": "Direct", - "requested": "[1.0.3, )", - "resolved": "1.0.3", - "contentHash": "vkEuf8ch76NNgZXU/3zoXTIXRO0o14H3aRoSFzcuUQb0PTxvV6jEfmWkUVO6JtLDuFCIimqZaf3hdxr32ltpfQ==", + "requested": "[1.0.5, )", + "resolved": "1.0.5", + "contentHash": "piQKk7PH2pSWQSQmCSd8cYPaDtAy/ppAD+Mrh2RUhhHI8awl81HqqLyAauwQhJwea3LNaiJ6f4ehZuOGk89TlA==", "dependencies": { - "SharpGLTF.Runtime": "1.0.3" + "SharpGLTF.Runtime": "1.0.5" } }, "SixLabors.ImageSharp": { "type": "Direct", - "requested": "[3.1.7, )", - "resolved": "3.1.7", - "contentHash": "9fIOOAsyLFid6qKypM2Iy0Z3Q9yoanV8VoYAHtI2sYGMNKzhvRTjgFDHonIiVe+ANtxIxM6SuqUzj0r91nItpA==" + "requested": "[3.1.11, )", + "resolved": "3.1.11", + "contentHash": "JfPLyigLthuE50yi6tMt7Amrenr/fA31t2CvJyhy/kQmfulIBAqo5T/YFUSRHtuYPXRSaUHygFeh6Qd933EoSw==" }, "JetBrains.Annotations": { "type": "Transitive", @@ -83,10 +83,10 @@ }, "SharpGLTF.Runtime": { "type": "Transitive", - "resolved": "1.0.3", - "contentHash": "W0bg2WyXlcSAJVu153hNUNm+BU4RP46yLwGD4099hSm8dsXG/H+J95PBoLJbIq8KGVkUWvfM0+XWHoEkCyd50A==", + "resolved": "1.0.5", + "contentHash": "EVP32k4LqERxSVICiupT8xQvhHSHJCiXajBjNpqdfdajtREHayuVhH0Jmk6uSjTLX8/IIH9XfT34sw3TwvCziw==", "dependencies": { - "SharpGLTF.Core": "1.0.3" + "SharpGLTF.Core": "1.0.5" } }, "System.Buffers": { @@ -114,8 +114,8 @@ }, "ZstdSharp.Port": { "type": "Transitive", - "resolved": "0.8.4", - "contentHash": "eieSXq3kakCUXbgdxkKaRqWS6hF0KBJcqok9LlDCs60GOyrynLvPOcQ0pRw7shdPF7lh/VepJ9cP9n9HHc759g==" + "resolved": "0.8.5", + "contentHash": "TR4j17WeVSEb3ncgL2NqlXEqcy04I+Kk9CaebNDplUeL8XOgjkZ7fP4Wg4grBdPLIqsV86p2QaXTkZoRMVOsew==" }, "ottergui": { "type": "Project", From 012052daa0c5cf81e11c32bb27ee220533000577 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Aug 2025 00:06:03 +0200 Subject: [PATCH 1264/1381] Change behavior for directory names. --- Penumbra/Mods/Editor/ModNormalizer.cs | 4 ++-- .../Mods/SubMods/CombinedDataContainer.cs | 19 +++++++++++++++++++ Penumbra/Mods/SubMods/DefaultSubMod.cs | 3 +++ Penumbra/Mods/SubMods/IModDataContainer.cs | 1 + Penumbra/Mods/SubMods/OptionSubMod.cs | 3 +++ 5 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Penumbra/Mods/Editor/ModNormalizer.cs b/Penumbra/Mods/Editor/ModNormalizer.cs index 527dbf7c..df1528f6 100644 --- a/Penumbra/Mods/Editor/ModNormalizer.cs +++ b/Penumbra/Mods/Editor/ModNormalizer.cs @@ -76,7 +76,7 @@ public class ModNormalizer(ModManager modManager, Configuration config, SaveServ else { var groupDir = ModCreator.NewOptionDirectory(mod.ModPath, container.Group.Name, config.ReplaceNonAsciiOnImport); - var optionDir = ModCreator.NewOptionDirectory(groupDir, container.GetName(), config.ReplaceNonAsciiOnImport); + var optionDir = ModCreator.NewOptionDirectory(groupDir, container.GetDirectoryName(), config.ReplaceNonAsciiOnImport); containers[container] = optionDir.FullName; } } @@ -286,7 +286,7 @@ public class ModNormalizer(ModManager modManager, Configuration config, SaveServ void HandleSubMod(DirectoryInfo groupDir, IModDataContainer option, Dictionary newDict) { - var name = option.GetName(); + var name = option.GetDirectoryName(); var optionDir = ModCreator.CreateModFolder(groupDir, name, config.ReplaceNonAsciiOnImport, true); newDict.Clear(); diff --git a/Penumbra/Mods/SubMods/CombinedDataContainer.cs b/Penumbra/Mods/SubMods/CombinedDataContainer.cs index b467c360..bfca2afd 100644 --- a/Penumbra/Mods/SubMods/CombinedDataContainer.cs +++ b/Penumbra/Mods/SubMods/CombinedDataContainer.cs @@ -48,6 +48,25 @@ public class CombinedDataContainer(IModGroup group) : IModDataContainer return sb.ToString(0, sb.Length - 3); } + public unsafe string GetDirectoryName() + { + if (Name.Length > 0) + return Name; + + var index = GetDataIndex(); + if (index == 0) + return "None"; + + var text = stackalloc char[IModGroup.MaxCombiningOptions].Slice(0, Group.Options.Count); + for (var i = 0; i < Group.Options.Count; ++i) + { + text[Group.Options.Count - 1 - i] = (index & 1) is 0 ? '0' : '1'; + index >>= 1; + } + + return new string(text); + } + public string GetFullName() => $"{Group.Name}: {GetName()}"; diff --git a/Penumbra/Mods/SubMods/DefaultSubMod.cs b/Penumbra/Mods/SubMods/DefaultSubMod.cs index 3840468f..3282f518 100644 --- a/Penumbra/Mods/SubMods/DefaultSubMod.cs +++ b/Penumbra/Mods/SubMods/DefaultSubMod.cs @@ -27,6 +27,9 @@ public class DefaultSubMod(IMod mod) : IModDataContainer public string GetName() => FullName; + public string GetDirectoryName() + => GetName(); + public string GetFullName() => FullName; diff --git a/Penumbra/Mods/SubMods/IModDataContainer.cs b/Penumbra/Mods/SubMods/IModDataContainer.cs index 1a89ec17..92ccf7e1 100644 --- a/Penumbra/Mods/SubMods/IModDataContainer.cs +++ b/Penumbra/Mods/SubMods/IModDataContainer.cs @@ -15,6 +15,7 @@ public interface IModDataContainer public MetaDictionary Manipulations { get; set; } public string GetName(); + public string GetDirectoryName(); public string GetFullName(); public (int GroupIndex, int DataIndex) GetDataIndices(); } diff --git a/Penumbra/Mods/SubMods/OptionSubMod.cs b/Penumbra/Mods/SubMods/OptionSubMod.cs index 9044350d..aa3fed8f 100644 --- a/Penumbra/Mods/SubMods/OptionSubMod.cs +++ b/Penumbra/Mods/SubMods/OptionSubMod.cs @@ -41,6 +41,9 @@ public abstract class OptionSubMod(IModGroup group) : IModOption, IModDataContai public string GetName() => Name; + public string GetDirectoryName() + => GetName(); + public string GetFullName() => FullName; From dc93eba34c322b20dcbbc0164ad2f2379f0909e6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Aug 2025 00:06:25 +0200 Subject: [PATCH 1265/1381] Add initial complex group things. --- Penumbra/Mods/Groups/ComplexModGroup.cs | 180 ++++++++++++++++++ Penumbra/Mods/Groups/IModGroup.cs | 2 + Penumbra/Mods/SubMods/ComplexDataContainer.cs | 46 +++++ Penumbra/Mods/SubMods/ComplexSubMod.cs | 39 ++++ Penumbra/Mods/SubMods/MaskedSetting.cs | 27 +++ 5 files changed, 294 insertions(+) create mode 100644 Penumbra/Mods/Groups/ComplexModGroup.cs create mode 100644 Penumbra/Mods/SubMods/ComplexDataContainer.cs create mode 100644 Penumbra/Mods/SubMods/ComplexSubMod.cs create mode 100644 Penumbra/Mods/SubMods/MaskedSetting.cs diff --git a/Penumbra/Mods/Groups/ComplexModGroup.cs b/Penumbra/Mods/Groups/ComplexModGroup.cs new file mode 100644 index 00000000..435bc253 --- /dev/null +++ b/Penumbra/Mods/Groups/ComplexModGroup.cs @@ -0,0 +1,180 @@ +using Dalamud.Interface.ImGuiNotification; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OtterGui.Classes; +using OtterGui.Extensions; +using Penumbra.Api.Enums; +using Penumbra.GameData.Data; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Settings; +using Penumbra.Mods.SubMods; +using Penumbra.String.Classes; +using Penumbra.UI.ModsTab.Groups; +using Penumbra.Util; + +namespace Penumbra.Mods.Groups; + +public sealed class ComplexModGroup(Mod mod) : IModGroup +{ + public Mod Mod { get; } = mod; + public string Name { get; set; } = "Option"; + public string Description { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; + + public GroupType Type + => GroupType.Complex; + + public GroupDrawBehaviour Behaviour + => GroupDrawBehaviour.Complex; + + public ModPriority Priority { get; set; } + public int Page { get; set; } + public Setting DefaultSettings { get; set; } + + public readonly List Options = []; + public readonly List Containers = []; + + + public FullPath? FindBestMatch(Utf8GamePath gamePath) + => throw new NotImplementedException(); + + public IModOption? AddOption(string name, string description = "") + => throw new NotImplementedException(); + + IReadOnlyList IModGroup.Options + => Options; + + IReadOnlyList IModGroup.DataContainers + => Containers; + + public bool IsOption + => Options.Count > 0; + + public int GetIndex() + => ModGroup.GetIndex(this); + + public IModGroupEditDrawer EditDrawer(ModGroupEditDrawer editDrawer) + => throw new NotImplementedException(); + + public void AddData(Setting setting, Dictionary redirections, MetaDictionary manipulations) + { + foreach (var container in Containers.Where(c => c.Association.IsEnabled(setting))) + SubMod.AddContainerTo(container, redirections, manipulations); + } + + public void AddChangedItems(ObjectIdentification identifier, IDictionary changedItems) + { + foreach (var container in Containers) + identifier.AddChangedItems(container, changedItems); + } + + public Setting FixSetting(Setting setting) + => new(setting.Value & ((1ul << Options.Count) - 1)); + + public void WriteJson(JsonTextWriter jWriter, JsonSerializer serializer, DirectoryInfo? basePath = null) + { + ModSaveGroup.WriteJsonBase(jWriter, this); + jWriter.WritePropertyName("Options"); + jWriter.WriteStartArray(); + foreach (var option in Options) + { + jWriter.WriteStartObject(); + SubMod.WriteModOption(jWriter, option); + if (!option.Conditions.IsZero) + { + jWriter.WritePropertyName("ConditionMask"); + jWriter.WriteValue(option.Conditions.Mask.Value); + jWriter.WritePropertyName("ConditionValue"); + jWriter.WriteValue(option.Conditions.Value.Value); + } + + if (option.Indentation > 0) + { + jWriter.WritePropertyName("Indentation"); + jWriter.WriteValue(option.Indentation); + } + + if (option.SubGroupLabel.Length > 0) + { + jWriter.WritePropertyName("SubGroup"); + jWriter.WriteValue(option.SubGroupLabel); + } + + jWriter.WriteEndObject(); + } + + jWriter.WriteEndArray(); + + jWriter.WritePropertyName("Containers"); + jWriter.WriteStartArray(); + foreach (var container in Containers) + { + jWriter.WriteStartObject(); + if (container.Name.Length > 0) + { + jWriter.WritePropertyName("Name"); + jWriter.WriteValue(container.Name); + } + + if (!container.Association.IsZero) + { + jWriter.WritePropertyName("AssociationMask"); + jWriter.WriteValue(container.Association.Mask.Value); + + jWriter.WritePropertyName("AssociationValue"); + jWriter.WriteValue(container.Association.Value.Value); + } + + SubMod.WriteModContainer(jWriter, serializer, container, basePath ?? Mod.ModPath); + jWriter.WriteEndObject(); + } + + jWriter.WriteEndArray(); + } + + public (int Redirections, int Swaps, int Manips) GetCounts() + => ModGroup.GetCountsBase(this); + + public static ComplexModGroup? Load(Mod mod, JObject json) + { + var ret = new ComplexModGroup(mod); + if (!ModSaveGroup.ReadJsonBase(json, ret)) + return null; + + var options = json["Options"]; + if (options != null) + foreach (var child in options.Children()) + { + if (ret.Options.Count == IModGroup.MaxComplexOptions) + { + Penumbra.Messager.NotificationMessage( + $"Complex Group {ret.Name} in {mod.Name} has more than {IModGroup.MaxComplexOptions} options, ignoring excessive options.", + NotificationType.Warning); + break; + } + + var subMod = new ComplexSubMod(ret, child); + ret.Options.Add(subMod); + } + + // Fix up conditions: No condition on itself. + foreach (var (option, index) in ret.Options.WithIndex()) + { + option.Conditions = option.Conditions.Limit(ret.Options.Count); + option.Conditions = new MaskedSetting(option.Conditions.Mask.SetBit(index, false), option.Conditions.Value); + } + + var containers = json["Containers"]; + if (containers != null) + foreach (var child in containers.Children()) + { + var container = new ComplexDataContainer(ret, child); + container.Association = container.Association.Limit(ret.Options.Count); + ret.Containers.Add(container); + } + + ret.DefaultSettings = ret.FixSetting(ret.DefaultSettings); + + return ret; + } +} diff --git a/Penumbra/Mods/Groups/IModGroup.cs b/Penumbra/Mods/Groups/IModGroup.cs index cc961b0f..98f62862 100644 --- a/Penumbra/Mods/Groups/IModGroup.cs +++ b/Penumbra/Mods/Groups/IModGroup.cs @@ -18,11 +18,13 @@ public enum GroupDrawBehaviour { SingleSelection, MultiSelection, + Complex, } public interface IModGroup { public const int MaxMultiOptions = 32; + public const int MaxComplexOptions = MaxMultiOptions; public const int MaxCombiningOptions = 8; public Mod Mod { get; } diff --git a/Penumbra/Mods/SubMods/ComplexDataContainer.cs b/Penumbra/Mods/SubMods/ComplexDataContainer.cs new file mode 100644 index 00000000..0f0fdef8 --- /dev/null +++ b/Penumbra/Mods/SubMods/ComplexDataContainer.cs @@ -0,0 +1,46 @@ +using Newtonsoft.Json.Linq; +using OtterGui.Extensions; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods.Editor; +using Penumbra.Mods.Groups; +using Penumbra.String.Classes; + +namespace Penumbra.Mods.SubMods; + +public sealed class ComplexDataContainer(ComplexModGroup group) : IModDataContainer +{ + public IMod Mod + => Group.Mod; + + public IModGroup Group { get; } = group; + + public Dictionary Files { get; set; } = []; + public Dictionary FileSwaps { get; set; } = []; + public MetaDictionary Manipulations { get; set; } = new(); + + public MaskedSetting Association = MaskedSetting.Zero; + + public string Name { get; set; } = string.Empty; + + public string GetName() + => Name.Length > 0 ? Name : $"Container {Group.DataContainers.IndexOf(this)}"; + + public string GetDirectoryName() + => Name.Length > 0 ? Name : $"{Group.DataContainers.IndexOf(this)}"; + + public string GetFullName() + => $"{Group.Name}: {GetName()}"; + + public (int GroupIndex, int DataIndex) GetDataIndices() + => (Group.GetIndex(), Group.DataContainers.IndexOf(this)); + + public ComplexDataContainer(ComplexModGroup group, JToken json) + : this(group) + { + SubMod.LoadDataContainer(json, this, group.Mod.ModPath); + var mask = json["AssociationMask"]?.ToObject() ?? 0; + var value = json["AssociationMask"]?.ToObject() ?? 0; + Association = new MaskedSetting(mask, value); + Name = json["Name"]?.ToObject() ?? string.Empty; + } +} diff --git a/Penumbra/Mods/SubMods/ComplexSubMod.cs b/Penumbra/Mods/SubMods/ComplexSubMod.cs new file mode 100644 index 00000000..3eea6f15 --- /dev/null +++ b/Penumbra/Mods/SubMods/ComplexSubMod.cs @@ -0,0 +1,39 @@ +using ImSharp; +using Newtonsoft.Json.Linq; +using OtterGui.Extensions; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; + +namespace Penumbra.Mods.SubMods; + +public sealed class ComplexSubMod(ComplexModGroup group) : IModOption +{ + public Mod Mod + => group.Mod; + + public IModGroup Group { get; } = group; + public string Name { get; set; } = "Option"; + + public string FullName + => $"{Group.Name}: {Name}"; + + public MaskedSetting Conditions = MaskedSetting.Zero; + public int Indentation = 0; + public string SubGroupLabel = string.Empty; + + public string Description { get; set; } = string.Empty; + + public int GetIndex() + => Group.Options.IndexOf(this); + + public ComplexSubMod(ComplexModGroup group, JToken json) + : this(group) + { + SubMod.LoadOptionData(json, this); + var mask = json["ConditionMask"]?.ToObject() ?? 0; + var value = json["ConditionMask"]?.ToObject() ?? 0; + Conditions = new MaskedSetting(mask, value); + Indentation = json["Indentation"]?.ToObject() ?? 0; + SubGroupLabel = json["SubGroup"]?.ToObject() ?? string.Empty; + } +} diff --git a/Penumbra/Mods/SubMods/MaskedSetting.cs b/Penumbra/Mods/SubMods/MaskedSetting.cs new file mode 100644 index 00000000..75bb46c2 --- /dev/null +++ b/Penumbra/Mods/SubMods/MaskedSetting.cs @@ -0,0 +1,27 @@ +using Penumbra.Mods.Groups; +using Penumbra.Mods.Settings; + +namespace Penumbra.Mods.SubMods; + +public readonly struct MaskedSetting(Setting mask, Setting value) +{ + public const int MaxSettings = IModGroup.MaxMultiOptions; + public static readonly MaskedSetting Zero = new(Setting.Zero, Setting.Zero); + public static readonly MaskedSetting FullMask = new(Setting.AllBits(IModGroup.MaxComplexOptions), Setting.Zero); + + public readonly Setting Mask = mask; + public readonly Setting Value = new(value.Value & mask.Value); + + public MaskedSetting(ulong mask, ulong value) + : this(new Setting(mask), new Setting(value)) + { } + + public MaskedSetting Limit(int numOptions) + => new(Mask.Value & Setting.AllBits(numOptions).Value, Value.Value); + + public bool IsZero + => Mask.Value is 0; + + public bool IsEnabled(Setting input) + => (input.Value & Mask.Value) == Value.Value; +} From baca3cdec21a705f231d7d45edfcea8c17735602 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Aug 2025 00:08:09 +0200 Subject: [PATCH 1266/1381] Update Libs. --- OtterGui | 2 +- Penumbra.GameData | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 2c3c32bf..ad3bafa4 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 2c3c32bfb7057d7be7678f413122c2b1453050d5 +Subproject commit ad3bafa4f0af5b69833347f8c8ff2e178645e2f0 diff --git a/Penumbra.GameData b/Penumbra.GameData index 10fdb025..82b44672 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 10fdb025436f7ea9f1f5e97635c19eee0578de7b +Subproject commit 82b446721a9b9c99d2470c54ad49fe19ff4987e3 From 8527bfa29c6bc722d9dad579a1bf719700b9ccac Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 2 Aug 2025 00:13:35 +0200 Subject: [PATCH 1267/1381] Fix missing updates for OtterGui. --- Penumbra/Mods/Manager/ModFileSystem.cs | 16 ++++++++-------- Penumbra/Mods/SubMods/ComplexSubMod.cs | 2 -- Penumbra/UI/Tabs/SettingsTab.cs | 6 +++--- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/Penumbra/Mods/Manager/ModFileSystem.cs b/Penumbra/Mods/Manager/ModFileSystem.cs index a5c46972..20a78995 100644 --- a/Penumbra/Mods/Manager/ModFileSystem.cs +++ b/Penumbra/Mods/Manager/ModFileSystem.cs @@ -37,11 +37,11 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer public struct ImportDate : ISortMode { - public string Name - => "Import Date (Older First)"; + public ReadOnlySpan Name + => "Import Date (Older First)"u8; - public string Description - => "In each folder, sort all subfolders lexicographically, then sort all leaves using their import date."; + public ReadOnlySpan Description + => "In each folder, sort all subfolders lexicographically, then sort all leaves using their import date."u8; public IEnumerable GetChildren(Folder f) => f.GetSubFolders().Cast().Concat(f.GetLeaves().OrderBy(l => l.Value.ImportDate)); @@ -49,11 +49,11 @@ public sealed class ModFileSystem : FileSystem, IDisposable, ISavable, ISer public struct InverseImportDate : ISortMode { - public string Name - => "Import Date (Newer First)"; + public ReadOnlySpan Name + => "Import Date (Newer First)"u8; - public string Description - => "In each folder, sort all subfolders lexicographically, then sort all leaves using their inverse import date."; + public ReadOnlySpan Description + => "In each folder, sort all subfolders lexicographically, then sort all leaves using their inverse import date."u8; public IEnumerable GetChildren(Folder f) => f.GetSubFolders().Cast().Concat(f.GetLeaves().OrderByDescending(l => l.Value.ImportDate)); diff --git a/Penumbra/Mods/SubMods/ComplexSubMod.cs b/Penumbra/Mods/SubMods/ComplexSubMod.cs index 3eea6f15..7c189170 100644 --- a/Penumbra/Mods/SubMods/ComplexSubMod.cs +++ b/Penumbra/Mods/SubMods/ComplexSubMod.cs @@ -1,8 +1,6 @@ -using ImSharp; using Newtonsoft.Json.Linq; using OtterGui.Extensions; using Penumbra.Mods.Groups; -using Penumbra.Mods.Settings; namespace Penumbra.Mods.SubMods; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index c1aea97c..2abf90ef 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -509,19 +509,19 @@ public class SettingsTab : ITab, IUiService { var sortMode = _config.SortMode; ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X); - using (var combo = ImRaii.Combo("##sortMode", sortMode.Name)) + using (var combo = ImUtf8.Combo("##sortMode", sortMode.Name)) { if (combo) foreach (var val in Configuration.Constants.ValidSortModes) { - if (ImGui.Selectable(val.Name, val.GetType() == sortMode.GetType()) && val.GetType() != sortMode.GetType()) + if (ImUtf8.Selectable(val.Name, val.GetType() == sortMode.GetType()) && val.GetType() != sortMode.GetType()) { _config.SortMode = val; _selector.SetFilterDirty(); _config.Save(); } - ImGuiUtil.HoverTooltip(val.Description); + ImUtf8.HoverTooltip(val.Description); } } From 898963fea530a04799eeb84675354c520b19ecf5 Mon Sep 17 00:00:00 2001 From: Sebastina Date: Tue, 22 Jul 2025 14:08:30 -0500 Subject: [PATCH 1268/1381] Allow focusing a specified mod via HTTP API under the mods tab. --- Penumbra/Api/HttpApi.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index b6e1d799..8f8b44f4 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -19,6 +19,7 @@ public class HttpApi : IDisposable, IApiService [Route( HttpVerbs.Post, "/reloadmod" )] public partial Task ReloadMod(); [Route( HttpVerbs.Post, "/installmod" )] public partial Task InstallMod(); [Route( HttpVerbs.Post, "/openwindow" )] public partial void OpenWindow(); + [Route( HttpVerbs.Post, "/focusmod" )] public partial Task FocusMod(); // @formatter:on } @@ -115,6 +116,13 @@ public class HttpApi : IDisposable, IApiService Penumbra.Log.Debug($"[HTTP] {nameof(OpenWindow)} triggered."); api.Ui.OpenMainWindow(TabType.Mods, string.Empty, string.Empty); } + public async partial Task FocusMod() + { + var data = await HttpContext.GetRequestDataAsync().ConfigureAwait(false); + Penumbra.Log.Debug($"[HTTP] {nameof(FocusMod)} triggered."); + if (data.Path.Length != 0) + api.Ui.OpenMainWindow(TabType.Mods, data.Path, data.Name); + } private record ModReloadData(string Path, string Name) { @@ -123,6 +131,13 @@ public class HttpApi : IDisposable, IApiService { } } + private record ModFocusData(string Path, string Name) + { + public ModFocusData() + : this(string.Empty, string.Empty) + { } + } + private record ModInstallData(string Path) { public ModInstallData() From f5f4fe7259cb8aeec36cad45e2bc342eda3f109f Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Thu, 31 Jul 2025 23:07:22 +1000 Subject: [PATCH 1269/1381] Invalid tangent fix example --- Penumbra/Import/Models/Export/MeshExporter.cs | 45 ++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 0070a808..11c84677 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -340,6 +340,39 @@ public class MeshExporter return typeof(VertexPositionNormalTangent); } + + private const float UnitLengthThresholdVec3 = 0.00674f; + internal static bool _IsFinite(float value) + { + return float.IsFinite(value); + } + + internal static bool _IsFinite(Vector2 v) + { + return _IsFinite(v.X) && _IsFinite(v.Y); + } + + internal static bool _IsFinite(Vector3 v) + { + return _IsFinite(v.X) && _IsFinite(v.Y) && _IsFinite(v.Z); + } + internal static Boolean IsNormalized(Vector3 normal) + { + if (!_IsFinite(normal)) return false; + + return Math.Abs(normal.Length() - 1) <= UnitLengthThresholdVec3; + } + internal static Vector3 SanitizeNormal(Vector3 normal) + { + if (normal == Vector3.Zero) return Vector3.UnitX; + return IsNormalized(normal) ? normal : Vector3.Normalize(normal); + } + internal static Vector4 SanitizeTangent(Vector4 tangent) + { + var n = SanitizeNormal(new Vector3(tangent.X, tangent.Y, tangent.Z)); + var s = float.IsNaN(tangent.W) ? 1 : tangent.W; + return new Vector4(n, s > 0 ? 1 : -1); + } /// Build a geometry vertex from a vertex's attributes. private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary> attributes) @@ -352,19 +385,21 @@ public class MeshExporter if (_geometryType == typeof(VertexPositionNormal)) return new VertexPositionNormal( ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)), - ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal)) + SanitizeNormal(ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal))) ); if (_geometryType == typeof(VertexPositionNormalTangent)) { // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. // TODO: While this assumption is safe, it would be sensible to actually check. - var bitangent = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)) * 2 - Vector4.One; - + // var bitangent = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)) * 2 - Vector4.One; + var vec4 = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)); + var bitangent = vec4 with { W = vec4.W == 1 ? 1 : -1 }; + return new VertexPositionNormalTangent( ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)), - ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal)), - bitangent + SanitizeNormal(ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal))), + SanitizeTangent(bitangent) ); } From bdcab22a5528758d5f2d54505f3ecb5b866efb7d Mon Sep 17 00:00:00 2001 From: Passive <20432486+PassiveModding@users.noreply.github.com> Date: Fri, 1 Aug 2025 22:03:27 +1000 Subject: [PATCH 1270/1381] Cleanup methods to extension class --- Penumbra/Import/Models/Export/MeshExporter.cs | 43 ++---------- Penumbra/Import/Models/ModelExtensions.cs | 69 +++++++++++++++++++ 2 files changed, 73 insertions(+), 39 deletions(-) create mode 100644 Penumbra/Import/Models/ModelExtensions.cs diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 11c84677..2e41f65a 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -340,39 +340,6 @@ public class MeshExporter return typeof(VertexPositionNormalTangent); } - - private const float UnitLengthThresholdVec3 = 0.00674f; - internal static bool _IsFinite(float value) - { - return float.IsFinite(value); - } - - internal static bool _IsFinite(Vector2 v) - { - return _IsFinite(v.X) && _IsFinite(v.Y); - } - - internal static bool _IsFinite(Vector3 v) - { - return _IsFinite(v.X) && _IsFinite(v.Y) && _IsFinite(v.Z); - } - internal static Boolean IsNormalized(Vector3 normal) - { - if (!_IsFinite(normal)) return false; - - return Math.Abs(normal.Length() - 1) <= UnitLengthThresholdVec3; - } - internal static Vector3 SanitizeNormal(Vector3 normal) - { - if (normal == Vector3.Zero) return Vector3.UnitX; - return IsNormalized(normal) ? normal : Vector3.Normalize(normal); - } - internal static Vector4 SanitizeTangent(Vector4 tangent) - { - var n = SanitizeNormal(new Vector3(tangent.X, tangent.Y, tangent.Z)); - var s = float.IsNaN(tangent.W) ? 1 : tangent.W; - return new Vector4(n, s > 0 ? 1 : -1); - } /// Build a geometry vertex from a vertex's attributes. private IVertexGeometry BuildVertexGeometry(IReadOnlyDictionary> attributes) @@ -385,21 +352,19 @@ public class MeshExporter if (_geometryType == typeof(VertexPositionNormal)) return new VertexPositionNormal( ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)), - SanitizeNormal(ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal))) + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal)) ); if (_geometryType == typeof(VertexPositionNormalTangent)) { // (Bi)tangents are universally stored as ByteFloat4, which uses 0..1 to represent the full -1..1 range. // TODO: While this assumption is safe, it would be sensible to actually check. - // var bitangent = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)) * 2 - Vector4.One; - var vec4 = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)); - var bitangent = vec4 with { W = vec4.W == 1 ? 1 : -1 }; + var bitangent = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Tangent1)) * 2 - Vector4.One; return new VertexPositionNormalTangent( ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Position)), - SanitizeNormal(ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal))), - SanitizeTangent(bitangent) + ToVector3(GetFirstSafe(attributes, MdlFile.VertexUsage.Normal)), + bitangent.SanitizeTangent() ); } diff --git a/Penumbra/Import/Models/ModelExtensions.cs b/Penumbra/Import/Models/ModelExtensions.cs new file mode 100644 index 00000000..2edb3ca4 --- /dev/null +++ b/Penumbra/Import/Models/ModelExtensions.cs @@ -0,0 +1,69 @@ +namespace Penumbra.Import.Models; + +public static class ModelExtensions +{ + // https://github.com/vpenades/SharpGLTF/blob/2073cf3cd671f8ecca9667f9a8c7f04ed865d3ac/src/Shared/_Extensions.cs#L158 + private const float UnitLengthThresholdVec3 = 0.00674f; + private const float UnitLengthThresholdVec4 = 0.00769f; + + internal static bool _IsFinite(this float value) + { + return float.IsFinite(value); + } + + internal static bool _IsFinite(this Vector2 v) + { + return v.X._IsFinite() && v.Y._IsFinite(); + } + + internal static bool _IsFinite(this Vector3 v) + { + return v.X._IsFinite() && v.Y._IsFinite() && v.Z._IsFinite(); + } + + internal static bool _IsFinite(this in Vector4 v) + { + return v.X._IsFinite() && v.Y._IsFinite() && v.Z._IsFinite() && v.W._IsFinite(); + } + + internal static Boolean IsNormalized(this Vector3 normal) + { + if (!normal._IsFinite()) return false; + + return Math.Abs(normal.Length() - 1) <= UnitLengthThresholdVec3; + } + + internal static void ValidateNormal(this Vector3 normal, string msg) + { + if (!normal._IsFinite()) throw new NotFiniteNumberException($"{msg} is invalid."); + + if (!normal.IsNormalized()) throw new ArithmeticException($"{msg} is not unit length."); + } + + internal static void ValidateTangent(this Vector4 tangent, string msg) + { + if (tangent.W != 1 && tangent.W != -1) throw new ArithmeticException(msg); + + new Vector3(tangent.X, tangent.Y, tangent.Z).ValidateNormal(msg); + } + + internal static Vector3 SanitizeNormal(this Vector3 normal) + { + if (normal == Vector3.Zero) return Vector3.UnitX; + return normal.IsNormalized() ? normal : Vector3.Normalize(normal); + } + + internal static bool IsValidTangent(this Vector4 tangent) + { + if (tangent.W != 1 && tangent.W != -1) return false; + + return new Vector3(tangent.X, tangent.Y, tangent.Z).IsNormalized(); + } + + internal static Vector4 SanitizeTangent(this Vector4 tangent) + { + var n = new Vector3(tangent.X, tangent.Y, tangent.Z).SanitizeNormal(); + var s = float.IsNaN(tangent.W) ? 1 : tangent.W; + return new Vector4(n, s > 0 ? 1 : -1); + } +} From 6689e326ee00d9dfddca4f813cb7232388cc0654 Mon Sep 17 00:00:00 2001 From: Ridan Vandenbergh Date: Sat, 2 Aug 2025 00:27:21 +0200 Subject: [PATCH 1271/1381] Material tab: disallow "Enable Transparency" for stockings shader --- .../UI/AdvancedWindow/Materials/MtrlTab.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs index 97acf130..77bfb795 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs @@ -1,3 +1,4 @@ +using Dalamud.Interface.Components; using Dalamud.Plugin.Services; using ImGuiNET; using OtterGui; @@ -119,11 +120,22 @@ public sealed partial class MtrlTab : IWritable, IDisposable using var dis = ImRaii.Disabled(disabled); var tmp = shaderFlags.EnableTransparency; - if (ImUtf8.Checkbox("Enable Transparency"u8, ref tmp)) + + // guardrail: the game crashes if transparency is enabled on characterstockings.shpk + var disallowTransparency = Mtrl.ShaderPackage.Name == "characterstockings.shpk"; + using (ImRaii.Disabled(disallowTransparency)) { - shaderFlags.EnableTransparency = tmp; - ret = true; - SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); + if (ImUtf8.Checkbox("Enable Transparency"u8, ref tmp)) + { + shaderFlags.EnableTransparency = tmp; + ret = true; + SetShaderPackageFlags(Mtrl.ShaderPackage.Flags); + } + } + + if (disallowTransparency) + { + ImGuiComponents.HelpMarker("Enabling transparency for shader package characterstockings.shpk will crash the game."); } ImGui.SameLine(200 * UiHelpers.Scale + ImGui.GetStyle().ItemSpacing.X + ImGui.GetStyle().WindowPadding.X); From 3f18ad50de0d3f360771fd472ef98a05008e5bd3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 00:45:24 +0200 Subject: [PATCH 1272/1381] Initial API13 / 7.3 update. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.CrashHandler/Penumbra.CrashHandler.csproj | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Api/IpcTester/CollectionsIpcTester.cs | 2 +- Penumbra/Api/IpcTester/EditingIpcTester.cs | 2 +- Penumbra/Api/IpcTester/GameStateIpcTester.cs | 2 +- Penumbra/Api/IpcTester/IpcTester.cs | 2 +- Penumbra/Api/IpcTester/MetaIpcTester.cs | 2 +- Penumbra/Api/IpcTester/ModSettingsIpcTester.cs | 2 +- Penumbra/Api/IpcTester/ModsIpcTester.cs | 2 +- Penumbra/Api/IpcTester/PluginStateIpcTester.cs | 2 +- Penumbra/Api/IpcTester/RedrawingIpcTester.cs | 2 +- Penumbra/Api/IpcTester/ResolveIpcTester.cs | 2 +- Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs | 2 +- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 4 ++-- Penumbra/Api/IpcTester/UiIpcTester.cs | 2 +- Penumbra/ChangedItemMode.cs | 2 +- Penumbra/CommandHandler.cs | 2 +- Penumbra/Import/TexToolsImporter.Gui.cs | 2 +- .../Textures/CombinedTexture.Manipulation.cs | 2 +- Penumbra/Import/Textures/TextureDrawer.cs | 4 ++-- Penumbra/Import/Textures/TextureManager.cs | 2 +- Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs | 2 +- Penumbra/Interop/MaterialPreview/MaterialInfo.cs | 2 +- Penumbra/Interop/ResourceTree/ResolveContext.cs | 4 ++-- Penumbra/Interop/ResourceTree/ResourceTree.cs | 5 ++--- Penumbra/Interop/Services/TextureArraySlicer.cs | 7 ++++--- Penumbra/Meta/ShapeAttributeManager.cs | 3 --- Penumbra/Mods/FeatureChecker.cs | 2 +- Penumbra/Penumbra.cs | 4 +++- Penumbra/Penumbra.csproj | 2 +- Penumbra/Penumbra.json | 2 +- Penumbra/Services/StainService.cs | 2 +- Penumbra/UI/AdvancedWindow/FileEditor.cs | 2 +- Penumbra/UI/AdvancedWindow/ItemSwapTab.cs | 2 +- .../Materials/MaterialTemplatePickers.cs | 2 +- .../AdvancedWindow/Materials/MtrlTab.ColorTable.cs | 2 +- .../Materials/MtrlTab.CommonColorTable.cs | 14 +++++++------- .../AdvancedWindow/Materials/MtrlTab.Constants.cs | 2 +- .../Materials/MtrlTab.LegacyColorTable.cs | 2 +- .../Materials/MtrlTab.LivePreview.cs | 2 +- .../Materials/MtrlTab.ShaderPackage.cs | 4 ++-- .../AdvancedWindow/Materials/MtrlTab.Textures.cs | 2 +- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs | 2 +- .../UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs | 2 +- Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.Deformers.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.Materials.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs | 2 +- .../UI/AdvancedWindow/ModEditWindow.QuickImport.cs | 2 +- .../AdvancedWindow/ModEditWindow.ShaderPackages.cs | 4 ++-- .../UI/AdvancedWindow/ModEditWindow.Textures.cs | 2 +- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- Penumbra/UI/AdvancedWindow/ModMergeTab.cs | 2 +- Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs | 2 +- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 2 +- Penumbra/UI/ChangedItemDrawer.cs | 12 ++++++------ Penumbra/UI/Classes/CollectionSelectHeader.cs | 2 +- Penumbra/UI/Classes/Colors.cs | 2 +- Penumbra/UI/Classes/MigrationSectionDrawer.cs | 2 +- Penumbra/UI/CollectionTab/CollectionCombo.cs | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 4 ++-- Penumbra/UI/CollectionTab/CollectionSelector.cs | 4 ++-- .../UI/CollectionTab/IndividualAssignmentUi.cs | 2 +- Penumbra/UI/CollectionTab/InheritanceUi.cs | 4 ++-- Penumbra/UI/ConfigWindow.cs | 2 +- Penumbra/UI/FileDialogService.cs | 2 +- Penumbra/UI/ImportPopup.cs | 2 +- Penumbra/UI/IncognitoService.cs | 2 +- Penumbra/UI/Knowledge/KnowledgeWindow.cs | 2 +- Penumbra/UI/Knowledge/RaceCodeTab.cs | 2 +- Penumbra/UI/ModsTab/DescriptionEditPopup.cs | 2 +- Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs | 2 +- .../ModsTab/Groups/CombiningModGroupEditDrawer.cs | 2 +- .../UI/ModsTab/Groups/ImcModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs | 2 +- Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs | 2 +- .../UI/ModsTab/Groups/SingleModGroupEditDrawer.cs | 2 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 2 +- Penumbra/UI/ModsTab/ModPanel.cs | 2 +- Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelConflictsTab.cs | 10 +++++----- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 4 ++-- Penumbra/UI/ModsTab/ModPanelHeader.cs | 2 +- Penumbra/UI/ModsTab/ModPanelSettingsTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelTabBar.cs | 2 +- Penumbra/UI/ModsTab/MultiModPanel.cs | 2 +- Penumbra/UI/PredefinedTagManager.cs | 4 ++-- Penumbra/UI/ResourceWatcher/ResourceWatcher.cs | 2 +- .../UI/ResourceWatcher/ResourceWatcherTable.cs | 2 +- Penumbra/UI/Tabs/ChangedItemsTab.cs | 2 +- Penumbra/UI/Tabs/CollectionsTab.cs | 2 +- Penumbra/UI/Tabs/ConfigTabBar.cs | 2 +- Penumbra/UI/Tabs/Debug/AtchDrawer.cs | 2 +- Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs | 2 +- Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 +- Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs | 3 +-- Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs | 2 +- Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs | 2 +- Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs | 2 +- Penumbra/UI/Tabs/Debug/ShapeInspector.cs | 2 +- Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs | 2 +- Penumbra/UI/Tabs/EffectiveTab.cs | 2 +- Penumbra/UI/Tabs/ModsTab.cs | 2 +- Penumbra/UI/Tabs/ResourceTab.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 2 +- Penumbra/UI/UiHelpers.cs | 12 ++++++------ 123 files changed, 158 insertions(+), 160 deletions(-) diff --git a/OtterGui b/OtterGui index ad3bafa4..9523b7ac 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit ad3bafa4f0af5b69833347f8c8ff2e178645e2f0 +Subproject commit 9523b7ac725656b21fa98faef96962652e86e64f diff --git a/Penumbra.Api b/Penumbra.Api index ff7b3b40..c27a0600 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit ff7b3b4014a97455f823380c78b8a7c5107f8e2f +Subproject commit c27a06004138f2ec80ccdb494bb6ddf6d39d2165 diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj index 4cb53c8b..abcb8e3d 100644 --- a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/Penumbra.GameData b/Penumbra.GameData index 82b44672..65c5bf3f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 82b446721a9b9c99d2470c54ad49fe19ff4987e3 +Subproject commit 65c5bf3f46569a54b0057c9015ab839b4e2a4350 diff --git a/Penumbra.String b/Penumbra.String index 0e5dcd1a..878acce4 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 0e5dcd1a5687ec5f8fa2ef2526b94b9a0ea1b5b5 +Subproject commit 878acce46e286867d6ef1f8ecedb390f7bac34fd diff --git a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs index 1d516eba..c06bdeb4 100644 --- a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs +++ b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs @@ -1,7 +1,7 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility; using Dalamud.Plugin; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/Api/IpcTester/EditingIpcTester.cs b/Penumbra/Api/IpcTester/EditingIpcTester.cs index a1001630..d754cf90 100644 --- a/Penumbra/Api/IpcTester/EditingIpcTester.cs +++ b/Penumbra/Api/IpcTester/EditingIpcTester.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Plugin; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/Api/IpcTester/GameStateIpcTester.cs b/Penumbra/Api/IpcTester/GameStateIpcTester.cs index 04541a57..38a09714 100644 --- a/Penumbra/Api/IpcTester/GameStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/GameStateIpcTester.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Plugin; -using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Api.Enums; diff --git a/Penumbra/Api/IpcTester/IpcTester.cs b/Penumbra/Api/IpcTester/IpcTester.cs index 201e7068..b03d7e03 100644 --- a/Penumbra/Api/IpcTester/IpcTester.cs +++ b/Penumbra/Api/IpcTester/IpcTester.cs @@ -1,6 +1,6 @@ using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.System.Framework; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using Penumbra.Api.Api; diff --git a/Penumbra/Api/IpcTester/MetaIpcTester.cs b/Penumbra/Api/IpcTester/MetaIpcTester.cs index 9cf20cd7..bee1981c 100644 --- a/Penumbra/Api/IpcTester/MetaIpcTester.cs +++ b/Penumbra/Api/IpcTester/MetaIpcTester.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Plugin; -using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs index c8eb8496..152efa45 100644 --- a/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModSettingsIpcTester.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Plugin; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/Api/IpcTester/ModsIpcTester.cs b/Penumbra/Api/IpcTester/ModsIpcTester.cs index a24861a3..9ea53366 100644 --- a/Penumbra/Api/IpcTester/ModsIpcTester.cs +++ b/Penumbra/Api/IpcTester/ModsIpcTester.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; using Dalamud.Plugin; -using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs index a1bf4fc4..073305d0 100644 --- a/Penumbra/Api/IpcTester/PluginStateIpcTester.cs +++ b/Penumbra/Api/IpcTester/PluginStateIpcTester.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs index b862dde5..6b853ed2 100644 --- a/Penumbra/Api/IpcTester/RedrawingIpcTester.cs +++ b/Penumbra/Api/IpcTester/RedrawingIpcTester.cs @@ -1,6 +1,6 @@ using Dalamud.Plugin; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Api.Enums; diff --git a/Penumbra/Api/IpcTester/ResolveIpcTester.cs b/Penumbra/Api/IpcTester/ResolveIpcTester.cs index a79b099d..9fc5bfc7 100644 --- a/Penumbra/Api/IpcTester/ResolveIpcTester.cs +++ b/Penumbra/Api/IpcTester/ResolveIpcTester.cs @@ -1,5 +1,5 @@ using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Api.IpcSubscribers; diff --git a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs index 48f3b4a8..e6c8d52e 100644 --- a/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs +++ b/Penumbra/Api/IpcTester/ResourceTreeIpcTester.cs @@ -1,8 +1,8 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Objects.Enums; using Dalamud.Interface; using Dalamud.Interface.Utility; using Dalamud.Plugin; -using ImGuiNET; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index c106a867..64adf256 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; @@ -282,7 +282,7 @@ public class TemporaryIpcTester( foreach (var mod in list) { ImGui.TableNextColumn(); - ImGui.TextUnformatted(mod.Name); + ImGui.TextUnformatted(mod.Name.Text); ImGui.TableNextColumn(); ImGui.TextUnformatted(mod.Priority.ToString()); ImGui.TableNextColumn(); diff --git a/Penumbra/Api/IpcTester/UiIpcTester.cs b/Penumbra/Api/IpcTester/UiIpcTester.cs index 647a4dda..852339c9 100644 --- a/Penumbra/Api/IpcTester/UiIpcTester.cs +++ b/Penumbra/Api/IpcTester/UiIpcTester.cs @@ -1,5 +1,5 @@ using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Api.Enums; diff --git a/Penumbra/ChangedItemMode.cs b/Penumbra/ChangedItemMode.cs index dccffded..ddb79ee0 100644 --- a/Penumbra/ChangedItemMode.cs +++ b/Penumbra/ChangedItemMode.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Text; namespace Penumbra; diff --git a/Penumbra/CommandHandler.cs b/Penumbra/CommandHandler.cs index 9f681da2..b5d307ef 100644 --- a/Penumbra/CommandHandler.cs +++ b/Penumbra/CommandHandler.cs @@ -1,7 +1,7 @@ using Dalamud.Game.Command; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Classes; using OtterGui.Services; using Penumbra.Api.Api; diff --git a/Penumbra/Import/TexToolsImporter.Gui.cs b/Penumbra/Import/TexToolsImporter.Gui.cs index f145f560..5cb99d72 100644 --- a/Penumbra/Import/TexToolsImporter.Gui.cs +++ b/Penumbra/Import/TexToolsImporter.Gui.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using Penumbra.Import.Structs; diff --git a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs index 2d131d71..7a7e5888 100644 --- a/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs +++ b/Penumbra/Import/Textures/CombinedTexture.Manipulation.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui; using SixLabors.ImageSharp.PixelFormats; diff --git a/Penumbra/Import/Textures/TextureDrawer.cs b/Penumbra/Import/Textures/TextureDrawer.cs index b0a65ac0..14203dff 100644 --- a/Penumbra/Import/Textures/TextureDrawer.cs +++ b/Penumbra/Import/Textures/TextureDrawer.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; -using ImGuiNET; using Lumina.Data.Files; using OtterGui; using OtterGui.Raii; @@ -20,7 +20,7 @@ public static class TextureDrawer { size = texture.TextureWrap.Size.Contain(size); - ImGui.Image(texture.TextureWrap.ImGuiHandle, size); + ImGui.Image(texture.TextureWrap.Handle, size); DrawData(texture); } else if (texture.LoadError != null) diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 0c85f5be..073fef2f 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -406,7 +406,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur // See https://github.com/microsoft/DirectXTex/wiki/Compress#parameters for the format condition. if (format is DXGIFormat.BC6HUF16 or DXGIFormat.BC6HSF16 or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB) { - var device = uiBuilder.Device; + var device = new Device(uiBuilder.DeviceHandle); var dxgiDevice = device.QueryInterface(); using var deviceClone = new Device(dxgiDevice.Adapter, device.CreationFlags, device.FeatureLevel); diff --git a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs index 368845b4..523ae610 100644 --- a/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs +++ b/Penumbra/Interop/Hooks/Meta/ChangeCustomize.cs @@ -16,7 +16,7 @@ public sealed unsafe class ChangeCustomize : FastHook { _collectionResolver = collectionResolver; _metaState = metaState; - Task = hooks.CreateHook("Change Customize", Sigs.ChangeCustomize, Detour, !HookOverrides.Instance.Meta.ChangeCustomize); + Task = hooks.CreateHook("Change Customize", Sigs.UpdateDrawData, Detour, !HookOverrides.Instance.Meta.ChangeCustomize); } public delegate bool Delegate(Human* human, CustomizeArray* data, byte skipEquipment); diff --git a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs index f2ea2d6c..a9fb46ff 100644 --- a/Penumbra/Interop/MaterialPreview/MaterialInfo.cs +++ b/Penumbra/Interop/MaterialPreview/MaterialInfo.cs @@ -85,7 +85,7 @@ public readonly record struct MaterialInfo(ObjectIndex ObjectIndex, DrawObjectTy if (mtrlHandle == null) continue; - PathDataHandler.Split(mtrlHandle->ResourceHandle.FileName.AsSpan(), out var path, out _); + PathDataHandler.Split(mtrlHandle->FileName.AsSpan(), out var path, out _); var fileName = CiByteString.FromSpanUnsafe(path, true); if (fileName == needle) result.Add(new MaterialInfo(index, type, i, j)); diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index 64a91302..b2364e33 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -59,7 +59,7 @@ internal unsafe partial record ResolveContext( if (!Utf8GamePath.FromByteString(CiByteString.Join((byte)'/', ShpkPrefix, gamePath), out var path)) return null; - return GetOrCreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, &resourceHandle->ResourceHandle, path); + return GetOrCreateNode(ResourceType.Shpk, (nint)resourceHandle->ShaderPackage, (ResourceHandle*)resourceHandle, path); } [SkipLocalsInit] @@ -245,7 +245,7 @@ internal unsafe partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)resource), out var cached)) return cached; - var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, &resource->ResourceHandle, path, false); + var node = CreateNode(ResourceType.Mtrl, (nint)mtrl, (ResourceHandle*)resource, path, false); var shpkNode = CreateNodeFromShpk(resource->ShaderPackageResourceHandle, new CiByteString(resource->ShpkName.Value)); if (shpkNode is not null) { diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index e7c4b11b..49649e13 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -72,15 +72,14 @@ public class ResourceTree( var mpapArrayPtr = model->MaterialAnimationPacks; var mpapArray = mpapArrayPtr is not null ? new ReadOnlySpan>(mpapArrayPtr, model->SlotCount) : []; - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1474) var skinMtrlArray = modelType switch { - ModelType.Human => new ReadOnlySpan>((MaterialResourceHandle**)((nint)model + 0xB48), 5), + ModelType.Human => ((Human*) model)->SlotSkinMaterials, _ => [], }; var decalArray = modelType switch { - ModelType.Human => human->SlotDecalsSpan, + ModelType.Human => human->SlotDecals, ModelType.DemiHuman => ((Demihuman*)model)->SlotDecals, ModelType.Weapon => [((Weapon*)model)->Decal], ModelType.Monster => [((Monster*)model)->Decal], diff --git a/Penumbra/Interop/Services/TextureArraySlicer.cs b/Penumbra/Interop/Services/TextureArraySlicer.cs index c934ac2b..11498878 100644 --- a/Penumbra/Interop/Services/TextureArraySlicer.cs +++ b/Penumbra/Interop/Services/TextureArraySlicer.cs @@ -1,3 +1,4 @@ +using Dalamud.Bindings.ImGui; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using OtterGui.Services; using SharpDX.Direct3D; @@ -16,7 +17,7 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable private readonly HashSet<(nint XivTexture, byte SliceIndex)> _expiredKeys = []; /// Caching this across frames will cause a crash to desktop. - public nint GetImGuiHandle(Texture* texture, byte sliceIndex) + public ImTextureID GetImGuiHandle(Texture* texture, byte sliceIndex) { if (texture == null) throw new ArgumentNullException(nameof(texture)); @@ -25,7 +26,7 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable if (_activeSlices.TryGetValue(((nint)texture, sliceIndex), out var state)) { state.Refresh(); - return (nint)state.ShaderResourceView; + return new ImTextureID((nint)state.ShaderResourceView); } var srv = (ShaderResourceView)(nint)texture->D3D11ShaderResourceView; var description = srv.Description; @@ -60,7 +61,7 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable } state = new SliceState(new ShaderResourceView(srv.Device, srv.Resource, description)); _activeSlices.Add(((nint)texture, sliceIndex), state); - return (nint)state.ShaderResourceView; + return new ImTextureID((nint)state.ShaderResourceView); } public void Tick() diff --git a/Penumbra/Meta/ShapeAttributeManager.cs b/Penumbra/Meta/ShapeAttributeManager.cs index 16901741..a7f71ac7 100644 --- a/Penumbra/Meta/ShapeAttributeManager.cs +++ b/Penumbra/Meta/ShapeAttributeManager.cs @@ -1,4 +1,3 @@ -using System.Collections.Frozen; using OtterGui.Services; using Penumbra.Collections; using Penumbra.Collections.Cache; @@ -6,8 +5,6 @@ using Penumbra.GameData.Enums; using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; using Penumbra.Interop.Hooks.PostProcessing; -using Penumbra.Interop.Structs; -using Penumbra.Meta.Files; using Penumbra.Meta.Manipulations; namespace Penumbra.Meta; diff --git a/Penumbra/Mods/FeatureChecker.cs b/Penumbra/Mods/FeatureChecker.cs index 5800ef07..10874fc9 100644 --- a/Penumbra/Mods/FeatureChecker.cs +++ b/Penumbra/Mods/FeatureChecker.cs @@ -1,7 +1,7 @@ using System.Collections.Frozen; using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Text; using Penumbra.Mods.Manager; using Penumbra.UI.Classes; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index cf96c7f6..b22d049d 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; +using Dalamud.Game; using OtterGui; using OtterGui.Log; using OtterGui.Services; @@ -20,6 +21,7 @@ using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; +using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.PostProcessing; diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index c61692f4..3159b736 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,4 +1,4 @@ - + Penumbra absolute gangstas diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 924d7bd3..bd9a2479 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -8,7 +8,7 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], - "DalamudApiLevel": 12, + "DalamudApiLevel": 13, "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, diff --git a/Penumbra/Services/StainService.cs b/Penumbra/Services/StainService.cs index b16d4dcd..17294aa8 100644 --- a/Penumbra/Services/StainService.cs +++ b/Penumbra/Services/StainService.cs @@ -1,7 +1,7 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin.Services; -using ImGuiNET; using OtterGui.Services; using OtterGui.Widgets; using Penumbra.GameData.DataContainers; diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index c783e17f..a0305619 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Compression; diff --git a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs index f5d2a8c7..e9d76990 100644 --- a/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs +++ b/Penumbra/UI/AdvancedWindow/ItemSwapTab.cs @@ -1,5 +1,5 @@ using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs index 5c636b1d..241c3a91 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using FFXIVClientStructs.Interop; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs index 0c987972..fad9adeb 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ColorTable.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index d70a4b50..39ff0a15 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility; -using ImGuiNET; using Penumbra.GameData.Files.MaterialStructs; using Penumbra.GameData.Files; using OtterGui.Text; @@ -338,10 +338,10 @@ public partial class MtrlTab var tmp = inputSqrt; if (ImUtf8.ColorEdit(label, ref tmp, ImGuiColorEditFlags.NoInputs - | ImGuiColorEditFlags.DisplayRGB - | ImGuiColorEditFlags.InputRGB + | ImGuiColorEditFlags.DisplayRgb + | ImGuiColorEditFlags.InputRgb | ImGuiColorEditFlags.NoTooltip - | ImGuiColorEditFlags.HDR) + | ImGuiColorEditFlags.Hdr) && tmp != inputSqrt) { setter((HalfColor)PseudoSquareRgb(tmp)); @@ -373,10 +373,10 @@ public partial class MtrlTab var tmp = Vector4.Zero; ImUtf8.ColorEdit(label, ref tmp, ImGuiColorEditFlags.NoInputs - | ImGuiColorEditFlags.DisplayRGB - | ImGuiColorEditFlags.InputRGB + | ImGuiColorEditFlags.DisplayRgb + | ImGuiColorEditFlags.InputRgb | ImGuiColorEditFlags.NoTooltip - | ImGuiColorEditFlags.HDR + | ImGuiColorEditFlags.Hdr | ImGuiColorEditFlags.AlphaPreview); if (letter.Length > 0 && ImGui.IsItemVisible()) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs index f413a6a2..4ad6968b 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Constants.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs index 0ffdd1cc..bebacc94 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Text; using Penumbra.GameData.Files.MaterialStructs; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs index 5025bafd..dfa3a963 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LivePreview.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; -using ImGuiNET; using OtterGui.Raii; using OtterGui.Text; using Penumbra.GameData.Files.MaterialStructs; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs index ee5341b2..43040ca3 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.ShaderPackage.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Classes; @@ -384,7 +384,7 @@ public partial class MtrlTab var shpkFlags = (int)Mtrl.ShaderPackage.Flags; ImGui.SetNextItemWidth(UiHelpers.Scale * 250.0f); if (!ImGui.InputInt("Shader Flags", ref shpkFlags, 0, 0, - ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) + flags: ImGuiInputTextFlags.CharsHexadecimal | (disabled ? ImGuiInputTextFlags.ReadOnly : ImGuiInputTextFlags.None))) return false; Mtrl.ShaderPackage.Flags = (uint)shpkFlags; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs index ac88f77c..82ba7be4 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.Textures.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs index 77bfb795..e15d1c90 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.Components; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs index 5b6d585a..4a74cda5 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/AtchMetaDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs index 89fadfa8..4b375c26 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/AtrMetaDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs index 348a0d4c..16af5217 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqdpMetaDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs index d6df95cb..77c2915a 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EqpMetaDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs index e5e28a3d..84e09be5 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/EstMetaDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs index 929feadd..b03f4aa5 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GlobalEqpMetaDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs index 3691a4f7..4053560b 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/GmpMetaDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Text; using Penumbra.GameData.Structs; diff --git a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs index 34488a87..bb87cd47 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ImcMetaDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs index 7e788462..f608a194 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/MetaDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs index d60f877b..88abe0cb 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/RspMetaDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs index 35c8ccec..59692195 100644 --- a/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs +++ b/Penumbra/UI/AdvancedWindow/Meta/ShpMetaDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Newtonsoft.Json.Linq; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs index 36154105..4f7ae8da 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Deformers.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 3f63967e..87d7487b 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs index 4c946fe7..3caff226 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Materials.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs index aa3d9172..06cd0763 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Meta.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs index cc592296..a7db7f25 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Models.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; -using ImGuiNET; using Lumina.Data.Parsing; using OtterGui; using OtterGui.Custom; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 00caaabc..72350857 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Lumina.Data; using OtterGui.Text; using Penumbra.Api.Enums; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs index a6a75e0d..baaf4a82 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.ShaderPackages.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui; using OtterGui.Classes; @@ -147,7 +147,7 @@ public partial class ModEditWindow using var font = ImRaii.PushFont(UiBuilder.MonoFont); var size = new Vector2(ImGui.GetContentRegionAvail().X, ImGui.GetTextLineHeight() * 20); - ImGuiNative.igInputTextMultiline(DisassemblyLabel.Path, shader.Disassembly!.RawDisassembly.Path, + ImGuiNative.InputTextMultiline(DisassemblyLabel.Path, shader.Disassembly!.RawDisassembly.Path, (uint)shader.Disassembly!.RawDisassembly.Length + 1, size, ImGuiInputTextFlags.ReadOnly, null, null); } diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs index ee4e1eda..34e1e0d4 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Textures.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index e148167b..952d8489 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -4,7 +4,7 @@ using Dalamud.Interface.DragDrop; using Dalamud.Interface.Utility; using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Log; diff --git a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs index 3c110fab..bf16fa37 100644 --- a/Penumbra/UI/AdvancedWindow/ModMergeTab.cs +++ b/Penumbra/UI/AdvancedWindow/ModMergeTab.cs @@ -1,5 +1,5 @@ using Dalamud.Interface.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs b/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs index 1fa12b6d..c9996a1e 100644 --- a/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs +++ b/Penumbra/UI/AdvancedWindow/OptionSelectCombo.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Widgets; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 4d33a3fc..440baa2f 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui; using OtterGui.Text; diff --git a/Penumbra/UI/ChangedItemDrawer.cs b/Penumbra/UI/ChangedItemDrawer.cs index a9070360..db54a8e5 100644 --- a/Penumbra/UI/ChangedItemDrawer.cs +++ b/Penumbra/UI/ChangedItemDrawer.cs @@ -3,7 +3,7 @@ using Dalamud.Interface.Textures; using Dalamud.Interface.Textures.TextureWraps; using Dalamud.Plugin.Services; using Dalamud.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Lumina.Data.Files; using OtterGui; using OtterGui.Classes; @@ -107,11 +107,11 @@ public class ChangedItemDrawer : IDisposable, IUiService return; } - ImGui.Image(icon.ImGuiHandle, new Vector2(height)); + ImGui.Image(icon.Handle, new Vector2(height)); if (ImGui.IsItemHovered()) { using var tt = ImRaii.Tooltip(); - ImGui.Image(icon.ImGuiHandle, new Vector2(_smallestIconWidth)); + ImGui.Image(icon.Handle, new Vector2(_smallestIconWidth)); ImGui.SameLine(); ImGuiUtil.DrawTextButton(iconFlagType.ToDescription(), new Vector2(0, _smallestIconWidth), 0); } @@ -193,7 +193,7 @@ public class ChangedItemDrawer : IDisposable, IUiService } ImGui.SetCursorPosX(ImGui.GetContentRegionMax().X - size.X); - ImGui.Image(_icons[ChangedItemFlagExtensions.AllFlags].ImGuiHandle, size, Vector2.Zero, Vector2.One, + ImGui.Image(_icons[ChangedItemFlagExtensions.AllFlags].Handle, size, Vector2.Zero, Vector2.One, typeFilter switch { 0 => new Vector4(0.6f, 0.3f, 0.3f, 1f), @@ -213,7 +213,7 @@ public class ChangedItemDrawer : IDisposable, IUiService var localRet = false; var icon = _icons[type]; var flag = typeFilter.HasFlag(type); - ImGui.Image(icon.ImGuiHandle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); + ImGui.Image(icon.Handle, size, Vector2.Zero, Vector2.One, flag ? Vector4.One : new Vector4(0.6f, 0.3f, 0.3f, 1f)); if (ImGui.IsItemClicked(ImGuiMouseButton.Left)) { typeFilter = flag ? typeFilter & ~type : typeFilter | type; @@ -232,7 +232,7 @@ public class ChangedItemDrawer : IDisposable, IUiService if (ImGui.IsItemHovered()) { using var tt = ImRaii.Tooltip(); - ImGui.Image(icon.ImGuiHandle, new Vector2(_smallestIconWidth)); + ImGui.Image(icon.Handle, new Vector2(_smallestIconWidth)); ImGui.SameLine(); ImGuiUtil.DrawTextButton(type.ToDescription(), new Vector2(0, _smallestIconWidth), 0); } diff --git a/Penumbra/UI/Classes/CollectionSelectHeader.cs b/Penumbra/UI/Classes/CollectionSelectHeader.cs index aa492362..355a6106 100644 --- a/Penumbra/UI/Classes/CollectionSelectHeader.cs +++ b/Penumbra/UI/Classes/CollectionSelectHeader.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/Classes/Colors.cs b/Penumbra/UI/Classes/Colors.cs index 9c15ceb8..90ef0591 100644 --- a/Penumbra/UI/Classes/Colors.cs +++ b/Penumbra/UI/Classes/Colors.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Custom; namespace Penumbra.UI.Classes; diff --git a/Penumbra/UI/Classes/MigrationSectionDrawer.cs b/Penumbra/UI/Classes/MigrationSectionDrawer.cs index a3dcd23a..98a59a5b 100644 --- a/Penumbra/UI/Classes/MigrationSectionDrawer.cs +++ b/Penumbra/UI/Classes/MigrationSectionDrawer.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Text; using Penumbra.Services; diff --git a/Penumbra/UI/CollectionTab/CollectionCombo.cs b/Penumbra/UI/CollectionTab/CollectionCombo.cs index 98dc924f..bf97f178 100644 --- a/Penumbra/UI/CollectionTab/CollectionCombo.cs +++ b/Penumbra/UI/CollectionTab/CollectionCombo.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index dc0e71b5..26fa2b14 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -6,7 +6,7 @@ using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Utility; using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; @@ -346,7 +346,7 @@ public sealed class CollectionPanel( if (!source) return; - ImGui.SetDragDropPayload("DragIndividual", nint.Zero, 0); + ImGui.SetDragDropPayload("DragIndividual", null, 0); ImGui.TextUnformatted($"Re-ordering {text}..."); _draggedIndividualAssignment = _active.Individuals.Index(id); } diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index 57429531..e54f994e 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using Penumbra.Collections; @@ -85,7 +85,7 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl if (source) { _dragging = Items[idx]; - ImGui.SetDragDropPayload(PayloadString, nint.Zero, 0); + ImGui.SetDragDropPayload(PayloadString, null, 0); ImGui.TextUnformatted($"Assigning {Name(_dragging)} to..."); } diff --git a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs index fd8f9b25..f472e346 100644 --- a/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs +++ b/Penumbra/UI/CollectionTab/IndividualAssignmentUi.cs @@ -1,5 +1,5 @@ using Dalamud.Game.ClientState.Objects.Enums; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Custom; using Penumbra.Collections; using Penumbra.Collections.Manager; diff --git a/Penumbra/UI/CollectionTab/InheritanceUi.cs b/Penumbra/UI/CollectionTab/InheritanceUi.cs index cdc1e83e..2053f269 100644 --- a/Penumbra/UI/CollectionTab/InheritanceUi.cs +++ b/Penumbra/UI/CollectionTab/InheritanceUi.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; @@ -288,7 +288,7 @@ public class InheritanceUi(CollectionManager collectionManager, IncognitoService if (!source) return; - ImGui.SetDragDropPayload(InheritanceDragDropLabel, nint.Zero, 0); + ImGui.SetDragDropPayload(InheritanceDragDropLabel, null, 0); _movedInheritance = collection; ImGui.TextUnformatted($"Moving {(_movedInheritance != null ? Name(_movedInheritance) : "Unknown")}..."); } diff --git a/Penumbra/UI/ConfigWindow.cs b/Penumbra/UI/ConfigWindow.cs index 64d370b5..55d0bc19 100644 --- a/Penumbra/UI/ConfigWindow.cs +++ b/Penumbra/UI/ConfigWindow.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.Windowing; using Dalamud.Plugin; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Custom; using OtterGui.Raii; diff --git a/Penumbra/UI/FileDialogService.cs b/Penumbra/UI/FileDialogService.cs index 6773bc88..3bbc4ba8 100644 --- a/Penumbra/UI/FileDialogService.cs +++ b/Penumbra/UI/FileDialogService.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiFileDialog; using Dalamud.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Services; diff --git a/Penumbra/UI/ImportPopup.cs b/Penumbra/UI/ImportPopup.cs index 28767edc..59ed0308 100644 --- a/Penumbra/UI/ImportPopup.cs +++ b/Penumbra/UI/ImportPopup.cs @@ -1,7 +1,7 @@ using Dalamud.Game.ClientState.Keys; using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui.Services; using Penumbra.Import.Structs; diff --git a/Penumbra/UI/IncognitoService.cs b/Penumbra/UI/IncognitoService.cs index 29358618..678e072e 100644 --- a/Penumbra/UI/IncognitoService.cs +++ b/Penumbra/UI/IncognitoService.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Penumbra.UI.Classes; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/Knowledge/KnowledgeWindow.cs b/Penumbra/UI/Knowledge/KnowledgeWindow.cs index f831975b..118ed479 100644 --- a/Penumbra/UI/Knowledge/KnowledgeWindow.cs +++ b/Penumbra/UI/Knowledge/KnowledgeWindow.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.Utility.Raii; using Dalamud.Interface.Windowing; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Text; using Penumbra.String; diff --git a/Penumbra/UI/Knowledge/RaceCodeTab.cs b/Penumbra/UI/Knowledge/RaceCodeTab.cs index 36b048aa..44b544eb 100644 --- a/Penumbra/UI/Knowledge/RaceCodeTab.cs +++ b/Penumbra/UI/Knowledge/RaceCodeTab.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Text; using Penumbra.GameData.Enums; diff --git a/Penumbra/UI/ModsTab/DescriptionEditPopup.cs b/Penumbra/UI/ModsTab/DescriptionEditPopup.cs index c284afc3..7d7a6967 100644 --- a/Penumbra/UI/ModsTab/DescriptionEditPopup.cs +++ b/Penumbra/UI/ModsTab/DescriptionEditPopup.cs @@ -1,5 +1,5 @@ using Dalamud.Interface.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Text; using Penumbra.Mods; diff --git a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs index a3e7ce14..1430f17b 100644 --- a/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/AddGroupDrawer.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Text; using Penumbra.Api.Enums; diff --git a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs index 5bd5dfdf..e9840e6c 100644 --- a/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/CombiningModGroupEditDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs index 3d330093..fa5b0ef6 100644 --- a/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ImcModGroupEditDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs index 566ec02c..3d8409ad 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface.Components; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; diff --git a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs index e9ab72ae..9610f173 100644 --- a/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/ModGroupEditDrawer.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; diff --git a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs index 492a8fb7..8fa6a377 100644 --- a/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs +++ b/Penumbra/UI/ModsTab/Groups/SingleModGroupEditDrawer.cs @@ -1,5 +1,5 @@ using Dalamud.Interface; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 8a383791..16ff7b41 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -2,7 +2,7 @@ using Dalamud.Interface; using Dalamud.Interface.DragDrop; using Dalamud.Interface.ImGuiNotification; using Dalamud.Plugin.Services; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Filesystem; diff --git a/Penumbra/UI/ModsTab/ModPanel.cs b/Penumbra/UI/ModsTab/ModPanel.cs index 9d6ead62..b7546699 100644 --- a/Penumbra/UI/ModsTab/ModPanel.cs +++ b/Penumbra/UI/ModsTab/ModPanel.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility.Raii; using Dalamud.Plugin; -using ImGuiNET; using OtterGui.Services; using Penumbra.Mods; using Penumbra.Services; diff --git a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs index b12df97d..332b64f0 100644 --- a/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelChangedItemsTab.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Services; diff --git a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs index ec020c86..70cad148 100644 --- a/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelCollectionsTab.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; -using ImGuiNET; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs index c750b8b0..1002d8ca 100644 --- a/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelConflictsTab.cs @@ -1,6 +1,6 @@ using Dalamud.Interface; using Dalamud.Interface.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Extensions; using OtterGui.Raii; @@ -73,7 +73,7 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy ImGui.TableNextColumn(); using var c = ImRaii.PushColor(ImGuiCol.Text, ColorId.FolderLine.Value()); ImGui.AlignTextToFramePadding(); - ImGui.TextUnformatted(selector.Selected!.Name); + ImGui.TextUnformatted(selector.Selected!.Name.Text); ImGui.TableNextColumn(); var actualSettings = collectionManager.Active.Current.GetActualSettings(selector.Selected!.Index).Settings!; var priority = actualSettings.Priority.Value; @@ -81,7 +81,7 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy using (ImRaii.Disabled(actualSettings is TemporaryModSettings)) { ImGui.SetNextItemWidth(priorityWidth); - if (ImGui.InputInt("##priority", ref priority, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue)) + if (ImGui.InputInt("##priority", ref priority, 0, 0, flags: ImGuiInputTextFlags.EnterReturnsTrue)) _currentPriority = priority; if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) @@ -104,7 +104,7 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy private void DrawConflictSelectable(ModConflicts conflict) { ImGui.AlignTextToFramePadding(); - if (ImGui.Selectable(conflict.Mod2.Name) && conflict.Mod2 is Mod otherMod) + if (ImGui.Selectable(conflict.Mod2.Name.Text) && conflict.Mod2 is Mod otherMod) selector.SelectByValue(otherMod); var hovered = ImGui.IsItemHovered(); var rightClicked = ImGui.IsItemClicked(ImGuiMouseButton.Right); @@ -172,7 +172,7 @@ public class ModPanelConflictsTab(CollectionManager collectionManager, ModFileSy var priority = _currentPriority ?? GetPriority(conflict).Value; ImGui.SetNextItemWidth(priorityWidth); - if (ImGui.InputInt("##priority", ref priority, 0, 0, ImGuiInputTextFlags.EnterReturnsTrue)) + if (ImGui.InputInt("##priority", ref priority, 0, 0, flags: ImGuiInputTextFlags.EnterReturnsTrue)) _currentPriority = priority; if (ImGui.IsItemDeactivatedAfterEdit() && _currentPriority.HasValue) diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 6fe3e4c6..71c1a225 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface.Utility; -using ImGuiNET; using OtterGui.Raii; using OtterGui; using OtterGui.Services; diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 478ab892..5b831a66 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -1,7 +1,7 @@ using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using OtterGui.Widgets; @@ -325,7 +325,7 @@ public class ModPanelEditTab( var tmp = field == _currentField && option == _optionIndex ? _currentEdit ?? oldValue : oldValue; ImGui.SetNextItemWidth(width); - if (ImGui.InputText(label, ref tmp, maxLength)) + if (ImGui.InputText(label, ref tmp)) { _currentEdit = tmp; _optionIndex = option; diff --git a/Penumbra/UI/ModsTab/ModPanelHeader.cs b/Penumbra/UI/ModsTab/ModPanelHeader.cs index aafbffa6..b42ac680 100644 --- a/Penumbra/UI/ModsTab/ModPanelHeader.cs +++ b/Penumbra/UI/ModsTab/ModPanelHeader.cs @@ -1,7 +1,7 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface.GameFonts; using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Plugin; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.Communication; diff --git a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs index 7c6ebf74..84f69bcb 100644 --- a/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelSettingsTab.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/ModsTab/ModPanelTabBar.cs b/Penumbra/UI/ModsTab/ModPanelTabBar.cs index 639118f5..5981d979 100644 --- a/Penumbra/UI/ModsTab/ModPanelTabBar.cs +++ b/Penumbra/UI/ModsTab/ModPanelTabBar.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs index ff5f636d..3eac972c 100644 --- a/Penumbra/UI/ModsTab/MultiModPanel.cs +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility; -using ImGuiNET; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index 12355672..7e268e8c 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -1,6 +1,6 @@ -using Dalamud.Interface; +using Dalamud.Bindings.ImGui; +using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; -using ImGuiNET; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OtterGui; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs index d134cfe5..ee3613fc 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcher.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; -using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Widgets; diff --git a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs index 009da842..97df095e 100644 --- a/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs +++ b/Penumbra/UI/ResourceWatcher/ResourceWatcherTable.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; -using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; diff --git a/Penumbra/UI/Tabs/ChangedItemsTab.cs b/Penumbra/UI/Tabs/ChangedItemsTab.cs index 6cee22d6..4dc9474f 100644 --- a/Penumbra/UI/Tabs/ChangedItemsTab.cs +++ b/Penumbra/UI/Tabs/ChangedItemsTab.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index 05a1f33b..f2a041eb 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Objects; using Dalamud.Plugin; -using ImGuiNET; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Widgets; diff --git a/Penumbra/UI/Tabs/ConfigTabBar.cs b/Penumbra/UI/Tabs/ConfigTabBar.cs index 28827ad9..43ae2488 100644 --- a/Penumbra/UI/Tabs/ConfigTabBar.cs +++ b/Penumbra/UI/Tabs/ConfigTabBar.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Widgets; using Penumbra.Api.Enums; diff --git a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs index 3b25c1a9..f136bacd 100644 --- a/Penumbra/UI/Tabs/Debug/AtchDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/AtchDrawer.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Extensions; using OtterGui.Text; using Penumbra.GameData.Files; diff --git a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs index 94c6cbd6..471d770a 100644 --- a/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs +++ b/Penumbra/UI/Tabs/Debug/CrashDataExtensions.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Raii; using Penumbra.CrashHandler; diff --git a/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs b/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs index c8e7f001..672b8c79 100644 --- a/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs +++ b/Penumbra/UI/Tabs/Debug/CrashHandlerPanel.cs @@ -1,6 +1,6 @@ using System.Text.Json; +using Dalamud.Bindings.ImGui; using Dalamud.Interface.DragDrop; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 76df5acc..eadee2d5 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -8,7 +8,7 @@ using FFXIVClientStructs.FFXIV.Client.Game.Group; using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.UI.Agent; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; diff --git a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs index bfe89768..7af33a36 100644 --- a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs @@ -1,10 +1,9 @@ -using Dalamud.Hooking; +using Dalamud.Bindings.ImGui; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.System.Scheduler; using FFXIVClientStructs.FFXIV.Client.System.Scheduler.Resource; using FFXIVClientStructs.Interop; using FFXIVClientStructs.STD; -using ImGuiNET; using OtterGui.Services; using OtterGui.Text; using Penumbra.Interop.Services; diff --git a/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs b/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs index e8ff9b9c..f1024950 100644 --- a/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/HookOverrideDrawer.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Plugin; -using ImGuiNET; using OtterGui.Services; using OtterGui.Text; using Penumbra.Interop.Hooks; diff --git a/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs b/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs index c8518315..e6e01107 100644 --- a/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs +++ b/Penumbra/UI/Tabs/Debug/ModMigratorDebug.cs @@ -1,4 +1,4 @@ -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui.Services; using OtterGui.Text; using Penumbra.Services; diff --git a/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs b/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs index c8c90e09..d497f90a 100644 --- a/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/RenderTargetDrawer.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using FFXIVClientStructs.FFXIV.Client.Graphics.Render; -using ImGuiNET; using OtterGui; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs index 7b940cd0..4c3b43bf 100644 --- a/Penumbra/UI/Tabs/Debug/ShapeInspector.cs +++ b/Penumbra/UI/Tabs/Debug/ShapeInspector.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; using OtterGui.Extensions; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs b/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs index 08d51184..4244e455 100644 --- a/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/TexHeaderDrawer.cs @@ -1,6 +1,6 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface.DragDrop; using Dalamud.Interface.Utility.Raii; -using ImGuiNET; using Lumina.Data.Files; using OtterGui.Services; using OtterGui.Text; diff --git a/Penumbra/UI/Tabs/EffectiveTab.cs b/Penumbra/UI/Tabs/EffectiveTab.cs index ecf9a886..5691f821 100644 --- a/Penumbra/UI/Tabs/EffectiveTab.cs +++ b/Penumbra/UI/Tabs/EffectiveTab.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; -using ImGuiNET; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 613a3532..79dcbb9e 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -1,5 +1,5 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Game.ClientState.Objects; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index c54e3433..593adde1 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -1,9 +1,9 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Game; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; using FFXIVClientStructs.STD; -using ImGuiNET; using OtterGui; using OtterGui.Raii; using OtterGui.Services; diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 2abf90ef..96d11baa 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -1,10 +1,10 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Components; using Dalamud.Interface.Utility; using Dalamud.Plugin; using Dalamud.Plugin.Services; using Dalamud.Utility; -using ImGuiNET; using OtterGui; using OtterGui.Compression; using OtterGui.Custom; diff --git a/Penumbra/UI/UiHelpers.cs b/Penumbra/UI/UiHelpers.cs index deba7023..9fe90ee8 100644 --- a/Penumbra/UI/UiHelpers.cs +++ b/Penumbra/UI/UiHelpers.cs @@ -1,6 +1,6 @@ using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility; -using ImGuiNET; +using Dalamud.Bindings.ImGui; using OtterGui; using OtterGui.Classes; using OtterGui.Raii; @@ -13,11 +13,11 @@ public static class UiHelpers { /// Draw text given by a ByteString. public static unsafe void Text(ByteString s) - => ImGuiNative.igTextUnformatted(s.Path, s.Path + s.Length); + => ImGuiNative.TextUnformatted(s.Path, s.Path + s.Length); /// Draw text given by a byte pointer and length. public static unsafe void Text(byte* s, int length) - => ImGuiNative.igTextUnformatted(s, s + length); + => ImGuiNative.TextUnformatted(s, s + length); /// Draw text given by a byte span. public static unsafe void Text(ReadOnlySpan s) @@ -36,7 +36,7 @@ public static class UiHelpers public static unsafe bool Selectable(ByteString s, bool selected) { var tmp = (byte)(selected ? 1 : 0); - return ImGuiNative.igSelectable_Bool(s.Path, tmp, ImGuiSelectableFlags.None, Vector2.Zero) != 0; + return ImGuiNative.Selectable(s.Path, tmp, ImGuiSelectableFlags.None, Vector2.Zero) != 0; } /// @@ -45,8 +45,8 @@ public static class UiHelpers /// public static unsafe void CopyOnClickSelectable(ByteString text) { - if (ImGuiNative.igSelectable_Bool(text.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) != 0) - ImGuiNative.igSetClipboardText(text.Path); + if (ImGuiNative.Selectable(text.Path, 0, ImGuiSelectableFlags.None, Vector2.Zero) != 0) + ImGuiNative.SetClipboardText(text.Path); if (ImGui.IsItemHovered()) ImGui.SetTooltip("Click to copy to clipboard."); From a69811800d7203642f75b900bd56368199264283 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 15:56:25 +0200 Subject: [PATCH 1273/1381] Update GameData --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 65c5bf3f..ea49bc09 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 65c5bf3f46569a54b0057c9015ab839b4e2a4350 +Subproject commit ea49bc099e783ecafdf78f0bd0bc41fb8c60ad19 From 2b36f3984860a4db41cf2832c93f3e7220cd23f0 Mon Sep 17 00:00:00 2001 From: Ridan Vandenbergh Date: Mon, 4 Aug 2025 18:37:36 +0200 Subject: [PATCH 1274/1381] Fix basecolor texture in material export --- Penumbra/Import/Models/Export/MaterialExporter.cs | 7 ++++--- .../AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Penumbra/Import/Models/Export/MaterialExporter.cs b/Penumbra/Import/Models/Export/MaterialExporter.cs index 6be2ccbd..0d91534e 100644 --- a/Penumbra/Import/Models/Export/MaterialExporter.cs +++ b/Penumbra/Import/Models/Export/MaterialExporter.cs @@ -1,6 +1,7 @@ using Lumina.Data.Parsing; using Penumbra.GameData.Files; using Penumbra.GameData.Files.MaterialStructs; +using Penumbra.UI.AdvancedWindow.Materials; using SharpGLTF.Materials; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; @@ -140,13 +141,13 @@ public class MaterialExporter // Lerp between table row values to fetch final pixel values for each subtexture. var lerpedDiffuse = Vector3.Lerp((Vector3)prevRow.DiffuseColor, (Vector3)nextRow.DiffuseColor, rowBlend); - baseColorSpan[x].FromVector4(new Vector4(lerpedDiffuse, 1)); + baseColorSpan[x].FromVector4(new Vector4(MtrlTab.PseudoSqrtRgb(lerpedDiffuse), 1)); var lerpedSpecularColor = Vector3.Lerp((Vector3)prevRow.SpecularColor, (Vector3)nextRow.SpecularColor, rowBlend); - specularSpan[x].FromVector4(new Vector4(lerpedSpecularColor, 1)); + specularSpan[x].FromVector4(new Vector4(MtrlTab.PseudoSqrtRgb(lerpedSpecularColor), 1)); var lerpedEmissive = Vector3.Lerp((Vector3)prevRow.EmissiveColor, (Vector3)nextRow.EmissiveColor, rowBlend); - emissiveSpan[x].FromVector4(new Vector4(lerpedEmissive, 1)); + emissiveSpan[x].FromVector4(new Vector4(MtrlTab.PseudoSqrtRgb(lerpedEmissive), 1)); } } } diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs index 39ff0a15..9ea9c2e0 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.CommonColorTable.cs @@ -594,7 +594,7 @@ public partial class MtrlTab internal static float PseudoSqrtRgb(float x) => x < 0.0f ? -MathF.Sqrt(-x) : MathF.Sqrt(x); - internal static Vector3 PseudoSqrtRgb(Vector3 vec) + public static Vector3 PseudoSqrtRgb(Vector3 vec) => new(PseudoSqrtRgb(vec.X), PseudoSqrtRgb(vec.Y), PseudoSqrtRgb(vec.Z)); internal static Vector4 PseudoSqrtRgb(Vector4 vec) From 8140d085575aab238d5d844561afd8926d413d2d Mon Sep 17 00:00:00 2001 From: Ridan Vandenbergh Date: Mon, 4 Aug 2025 20:19:19 +0200 Subject: [PATCH 1275/1381] Add vertex material types for usages of 2 colour attributes --- Penumbra/Import/Models/Export/MeshExporter.cs | 83 +++- .../Import/Models/Export/VertexFragment.cs | 450 ++++++++++++++++++ 2 files changed, 523 insertions(+), 10 deletions(-) diff --git a/Penumbra/Import/Models/Export/MeshExporter.cs b/Penumbra/Import/Models/Export/MeshExporter.cs index 2e41f65a..6ea2b284 100644 --- a/Penumbra/Import/Models/Export/MeshExporter.cs +++ b/Penumbra/Import/Models/Export/MeshExporter.cs @@ -390,23 +390,30 @@ public class MeshExporter } } + usages.TryGetValue(MdlFile.VertexUsage.Color, out var colours); + var nColors = colours?.Count ?? 0; + var materialUsages = ( uvCount, - usages.ContainsKey(MdlFile.VertexUsage.Color) + nColors ); return materialUsages switch { - (3, true) => typeof(VertexTexture3ColorFfxiv), - (3, false) => typeof(VertexTexture3), - (2, true) => typeof(VertexTexture2ColorFfxiv), - (2, false) => typeof(VertexTexture2), - (1, true) => typeof(VertexTexture1ColorFfxiv), - (1, false) => typeof(VertexTexture1), - (0, true) => typeof(VertexColorFfxiv), - (0, false) => typeof(VertexEmpty), + (3, 2) => typeof(VertexTexture3Color2Ffxiv), + (3, 1) => typeof(VertexTexture3ColorFfxiv), + (3, 0) => typeof(VertexTexture3), + (2, 2) => typeof(VertexTexture2Color2Ffxiv), + (2, 1) => typeof(VertexTexture2ColorFfxiv), + (2, 0) => typeof(VertexTexture2), + (1, 2) => typeof(VertexTexture1Color2Ffxiv), + (1, 1) => typeof(VertexTexture1ColorFfxiv), + (1, 0) => typeof(VertexTexture1), + (0, 2) => typeof(VertexColor2Ffxiv), + (0, 1) => typeof(VertexColorFfxiv), + (0, 0) => typeof(VertexEmpty), - _ => throw _notifier.Exception($"Unhandled UV count of {uvCount} encountered."), + _ => throw _notifier.Exception($"Unhandled UV/color count of {uvCount}/{nColors} encountered."), }; } @@ -419,6 +426,12 @@ public class MeshExporter if (_materialType == typeof(VertexColorFfxiv)) return new VertexColorFfxiv(ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color))); + if (_materialType == typeof(VertexColor2Ffxiv)) + { + var (color0, color1) = GetBothSafe(attributes, MdlFile.VertexUsage.Color); + return new VertexColor2Ffxiv(ToVector4(color0), ToVector4(color1)); + } + if (_materialType == typeof(VertexTexture1)) return new VertexTexture1(ToVector2(GetFirstSafe(attributes, MdlFile.VertexUsage.UV))); @@ -428,6 +441,16 @@ public class MeshExporter ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color)) ); + if (_materialType == typeof(VertexTexture1Color2Ffxiv)) + { + var (color0, color1) = GetBothSafe(attributes, MdlFile.VertexUsage.Color); + return new VertexTexture1Color2Ffxiv( + ToVector2(GetFirstSafe(attributes, MdlFile.VertexUsage.UV)), + ToVector4(color0), + ToVector4(color1) + ); + } + // XIV packs two UVs into a single vec4 attribute. if (_materialType == typeof(VertexTexture2)) @@ -448,6 +471,20 @@ public class MeshExporter ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.Color)) ); } + + if (_materialType == typeof(VertexTexture2Color2Ffxiv)) + { + var uv = ToVector4(GetFirstSafe(attributes, MdlFile.VertexUsage.UV)); + var (color0, color1) = GetBothSafe(attributes, MdlFile.VertexUsage.Color); + + return new VertexTexture2Color2Ffxiv( + new Vector2(uv.X, uv.Y), + new Vector2(uv.Z, uv.W), + ToVector4(color0), + ToVector4(color1) + ); + } + if (_materialType == typeof(VertexTexture3)) { // Not 100% sure about this @@ -472,6 +509,21 @@ public class MeshExporter ); } + if (_materialType == typeof(VertexTexture3Color2Ffxiv)) + { + var uv0 = ToVector4(attributes[MdlFile.VertexUsage.UV][0]); + var uv1 = ToVector4(attributes[MdlFile.VertexUsage.UV][1]); + var (color0, color1) = GetBothSafe(attributes, MdlFile.VertexUsage.Color); + + return new VertexTexture3Color2Ffxiv( + new Vector2(uv0.X, uv0.Y), + new Vector2(uv0.Z, uv0.W), + new Vector2(uv1.X, uv1.Y), + ToVector4(color0), + ToVector4(color1) + ); + } + throw _notifier.Exception($"Unknown material type {_skinningType}"); } @@ -537,6 +589,17 @@ public class MeshExporter return list[0]; } + + /// Check that the list has length 2 for any case where this is expected and return both entries. + [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] + private (T First, T Second) GetBothSafe(IReadOnlyDictionary> attributes, MdlFile.VertexUsage usage) + { + var list = attributes[usage]; + if (list.Count != 2) + throw _notifier.Exception($"{list.Count} usage indices encountered for {usage}, but expected 2."); + + return (list[0], list[1]); + } /// Convert a vertex attribute value to a Vector2. Supported inputs are Vector2, Vector3, and Vector4. private static Vector2 ToVector2(object data) diff --git a/Penumbra/Import/Models/Export/VertexFragment.cs b/Penumbra/Import/Models/Export/VertexFragment.cs index 56495f2f..463c59fc 100644 --- a/Penumbra/Import/Models/Export/VertexFragment.cs +++ b/Penumbra/Import/Models/Export/VertexFragment.cs @@ -84,6 +84,103 @@ public struct VertexColorFfxiv(Vector4 ffxivColor) : IVertexCustom } } +public struct VertexColor2Ffxiv(Vector4 ffxivColor0, Vector4 ffxivColor1) : IVertexCustom +{ + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("_FFXIV_COLOR_0", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + yield return new KeyValuePair("_FFXIV_COLOR_1", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + + public Vector4 FfxivColor0 = ffxivColor0; + public Vector4 FfxivColor1 = ffxivColor1; + + public int MaxColors + => 0; + + public int MaxTextCoords + => 0; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR_0", "_FFXIV_COLOR_1"]; + + public IEnumerable CustomAttributes + => CustomNames; + + public void Add(in VertexMaterialDelta delta) + { } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + => new(Vector4.Zero, Vector4.Zero, Vector2.Zero, Vector2.Zero); + + public Vector2 GetTexCoord(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetTexCoord(int setIndex, Vector2 coord) + { } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0": + value = FfxivColor0; + return true; + + case "_FFXIV_COLOR_1": + value = FfxivColor1; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0" when value is Vector4 valueVector4: + FfxivColor0 = valueVector4; + break; + case "_FFXIV_COLOR_1" when value is Vector4 valueVector4: + FfxivColor1 = valueVector4; + break; + } + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { } + + public void Validate() + { + var components = new[] + { + FfxivColor0.X, + FfxivColor0.Y, + FfxivColor0.Z, + FfxivColor0.W, + }; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor0)); + components = + [ + FfxivColor1.X, + FfxivColor1.Y, + FfxivColor1.Z, + FfxivColor1.W, + ]; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor1)); + } +} + + public struct VertexTexture1ColorFfxiv(Vector2 texCoord0, Vector4 ffxivColor) : IVertexCustom { public IEnumerable> GetEncodingAttributes() @@ -172,6 +269,118 @@ public struct VertexTexture1ColorFfxiv(Vector2 texCoord0, Vector4 ffxivColor) : } } +public struct VertexTexture1Color2Ffxiv(Vector2 texCoord0, Vector4 ffxivColor0, Vector4 ffxivColor1) : IVertexCustom +{ + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("TEXCOORD_0", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("_FFXIV_COLOR_0", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + yield return new KeyValuePair("_FFXIV_COLOR_1", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + + public Vector2 TexCoord0 = texCoord0; + + public Vector4 FfxivColor0 = ffxivColor0; + public Vector4 FfxivColor1 = ffxivColor1; + + public int MaxColors + => 0; + + public int MaxTextCoords + => 1; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR_0", "_FFXIV_COLOR_1"]; + + public IEnumerable CustomAttributes + => CustomNames; + + public void Add(in VertexMaterialDelta delta) + { + TexCoord0 += delta.TexCoord0Delta; + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + => new(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), Vector2.Zero); + + public Vector2 GetTexCoord(int index) + => index switch + { + 0 => TexCoord0, + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + public void SetTexCoord(int setIndex, Vector2 coord) + { + if (setIndex == 0) + TexCoord0 = coord; + if (setIndex >= 1) + throw new ArgumentOutOfRangeException(nameof(setIndex)); + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0": + value = FfxivColor0; + return true; + + case "_FFXIV_COLOR_1": + value = FfxivColor1; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0" when value is Vector4 valueVector4: + FfxivColor0 = valueVector4; + break; + case "_FFXIV_COLOR_1" when value is Vector4 valueVector4: + FfxivColor1 = valueVector4; + break; + } + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { } + + public void Validate() + { + var components = new[] + { + FfxivColor0.X, + FfxivColor0.Y, + FfxivColor0.Z, + FfxivColor0.W, + }; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor0)); + components = + [ + FfxivColor1.X, + FfxivColor1.Y, + FfxivColor1.Z, + FfxivColor1.W, + ]; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor1)); + } +} + + public struct VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor) : IVertexCustom { public IEnumerable> GetEncodingAttributes() @@ -266,6 +475,124 @@ public struct VertexTexture2ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vec } } +public struct VertexTexture2Color2Ffxiv(Vector2 texCoord0, Vector2 texCoord1, Vector4 ffxivColor0, Vector4 ffxivColor1) : IVertexCustom +{ + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("TEXCOORD_0", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("TEXCOORD_1", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("_FFXIV_COLOR_0", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + yield return new KeyValuePair("_FFXIV_COLOR_1", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + + public Vector2 TexCoord0 = texCoord0; + public Vector2 TexCoord1 = texCoord1; + public Vector4 FfxivColor0 = ffxivColor0; + public Vector4 FfxivColor1 = ffxivColor1; + + public int MaxColors + => 0; + + public int MaxTextCoords + => 2; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR_0", "_FFXIV_COLOR_1"]; + + public IEnumerable CustomAttributes + => CustomNames; + + public void Add(in VertexMaterialDelta delta) + { + TexCoord0 += delta.TexCoord0Delta; + TexCoord1 += delta.TexCoord1Delta; + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + => new(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), TexCoord1 - baseValue.GetTexCoord(1)); + + public Vector2 GetTexCoord(int index) + => index switch + { + 0 => TexCoord0, + 1 => TexCoord1, + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + public void SetTexCoord(int setIndex, Vector2 coord) + { + if (setIndex == 0) + TexCoord0 = coord; + if (setIndex == 1) + TexCoord1 = coord; + if (setIndex >= 2) + throw new ArgumentOutOfRangeException(nameof(setIndex)); + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0": + value = FfxivColor0; + return true; + + case "_FFXIV_COLOR_1": + value = FfxivColor1; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0" when value is Vector4 valueVector4: + FfxivColor0 = valueVector4; + break; + case "_FFXIV_COLOR_1" when value is Vector4 valueVector4: + FfxivColor1 = valueVector4; + break; + } + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { } + + public void Validate() + { + var components = new[] + { + FfxivColor0.X, + FfxivColor0.Y, + FfxivColor0.Z, + FfxivColor0.W, + }; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor0)); + components = + [ + FfxivColor1.X, + FfxivColor1.Y, + FfxivColor1.Z, + FfxivColor1.W, + ]; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor1)); + } + +} + public struct VertexTexture3ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vector2 texCoord2, Vector4 ffxivColor) : IVertexCustom { @@ -367,3 +694,126 @@ public struct VertexTexture3ColorFfxiv(Vector2 texCoord0, Vector2 texCoord1, Vec throw new ArgumentOutOfRangeException(nameof(FfxivColor)); } } + +public struct VertexTexture3Color2Ffxiv(Vector2 texCoord0, Vector2 texCoord1, Vector2 texCoord2, Vector4 ffxivColor0, Vector4 ffxivColor1) + : IVertexCustom +{ + public IEnumerable> GetEncodingAttributes() + { + yield return new KeyValuePair("TEXCOORD_0", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("TEXCOORD_1", + new AttributeFormat(DimensionType.VEC2, EncodingType.FLOAT, false)); + yield return new KeyValuePair("_FFXIV_COLOR_0", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + yield return new KeyValuePair("_FFXIV_COLOR_1", + new AttributeFormat(DimensionType.VEC4, EncodingType.UNSIGNED_SHORT, true)); + } + + public Vector2 TexCoord0 = texCoord0; + public Vector2 TexCoord1 = texCoord1; + public Vector2 TexCoord2 = texCoord2; + public Vector4 FfxivColor0 = ffxivColor0; + public Vector4 FfxivColor1 = ffxivColor1; + + public int MaxColors + => 0; + + public int MaxTextCoords + => 3; + + private static readonly string[] CustomNames = ["_FFXIV_COLOR_0", "_FFXIV_COLOR_1"]; + + public IEnumerable CustomAttributes + => CustomNames; + + public void Add(in VertexMaterialDelta delta) + { + TexCoord0 += delta.TexCoord0Delta; + TexCoord1 += delta.TexCoord1Delta; + TexCoord2 += delta.TexCoord2Delta; + } + + public VertexMaterialDelta Subtract(IVertexMaterial baseValue) + => new(Vector4.Zero, Vector4.Zero, TexCoord0 - baseValue.GetTexCoord(0), TexCoord1 - baseValue.GetTexCoord(1)); + + public Vector2 GetTexCoord(int index) + => index switch + { + 0 => TexCoord0, + 1 => TexCoord1, + 2 => TexCoord2, + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + public void SetTexCoord(int setIndex, Vector2 coord) + { + if (setIndex == 0) + TexCoord0 = coord; + if (setIndex == 1) + TexCoord1 = coord; + if (setIndex == 2) + TexCoord2 = coord; + if (setIndex >= 3) + throw new ArgumentOutOfRangeException(nameof(setIndex)); + } + + public bool TryGetCustomAttribute(string attributeName, out object? value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0": + value = FfxivColor0; + return true; + + case "_FFXIV_COLOR_1": + value = FfxivColor1; + return true; + + default: + value = null; + return false; + } + } + + public void SetCustomAttribute(string attributeName, object value) + { + switch (attributeName) + { + case "_FFXIV_COLOR_0" when value is Vector4 valueVector4: + FfxivColor0 = valueVector4; + break; + case "_FFXIV_COLOR_1" when value is Vector4 valueVector4: + FfxivColor1 = valueVector4; + break; + } + } + + public Vector4 GetColor(int index) + => throw new ArgumentOutOfRangeException(nameof(index)); + + public void SetColor(int setIndex, Vector4 color) + { } + + public void Validate() + { + var components = new[] + { + FfxivColor0.X, + FfxivColor0.Y, + FfxivColor0.Z, + FfxivColor0.W, + }; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor0)); + components = + [ + FfxivColor1.X, + FfxivColor1.Y, + FfxivColor1.Z, + FfxivColor1.W, + ]; + if (components.Any(component => component is < 0 or > 1)) + throw new ArgumentOutOfRangeException(nameof(FfxivColor1)); + } +} From 93406e4d4e50e84b12292d74aeb5c1f0f697b8af Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 16:17:59 +0200 Subject: [PATCH 1276/1381] 1.5.0.0 --- Penumbra/UI/Changelog.cs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index c1f7a1e6..4b487104 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -62,10 +62,37 @@ public class PenumbraChangelog : IUiService Add1_3_6_0(Changelog); Add1_3_6_4(Changelog); Add1_4_0_0(Changelog); + Add1_5_0_0(Changelog); } #region Changelogs + private static void Add1_5_0_0(Changelog log) + => log.NextVersion("Version 1.5.0.0") + .RegisterImportant("Updated for game version 7.30 and Dalamud API13, which uses a new GUI backend. Some things may not work as expected. Please let me know any issues you encounter.") + .RegisterEntry("Added support for exporting models using two vertex color schemes (thanks zeroeightysix!).") + .RegisterEntry("Possibly improved the color accuracy of the basecolor texture created when exporting models (thanks zeroeightysix!).") + .RegisterEntry("Disabled enabling transparency for materials that use the characterstockings shader due to crashes (thanks zeroeightysix!).") + .RegisterEntry("Fixed some issues with model i/o and invalid tangents (thanks PassiveModding!)") + .RegisterEntry("Changed the behavior for default directory names when using the mod normalizer with combining groups.") + .RegisterEntry("Added jumping to specific mods to the HTTP API.") + .RegisterEntry("Fixed an issue with character sound modding (1.4.0.6).") + .RegisterHighlight("Added support for IMC-toggle attributes to accessories beyond the first toggle (1.4.0.5).") + .RegisterEntry("Fixed up some slot-specific attributes and shapes in models when swapping items between slots (1.4.0.5).") + .RegisterEntry("Added handling for human skin materials to the OnScreen tab and similar functionality (thanks Ny!) (1.4.0.5).") + .RegisterEntry("The OS thread ID a resource was loaded from was added to the resource logger (1.4.0.5).") + .RegisterEntry("A button linking to my (Ottermandias') Ko-Fi and Patreon was added in the settings tab. Feel free, but not pressured, to use it! :D ") + .RegisterHighlight("Mod setting combos now support mouse-wheel scrolling with Control and have filters (1.4.0.4).") + .RegisterEntry("Using the middle mouse button to toggle designs now works correctly with temporary settings (1.4.0.4).") + .RegisterEntry("Updated some BNPC associations (1.4.0.3).") + .RegisterEntry("Fixed further issues with shapes and attributes (1.4.0.4).") + .RegisterEntry("Penumbra now handles textures with MipMap offsets broken by TexTools on import and removes unnecessary MipMaps (1.4.0.3).") + .RegisterEntry("Updated the Mod Merger for the new group types (1.4.0.3).") + .RegisterEntry("Added querying Penumbra for supported features via IPC (1.4.0.3).") + .RegisterEntry("Shape names can now be edited in Penumbras model editor (1.4.0.2).") + .RegisterEntry("Attributes and Shapes can be fully toggled (1.4.0.2).") + .RegisterEntry("Fixed several issues with attributes and shapes (1.4.0.1)."); + private static void Add1_4_0_0(Changelog log) => log.NextVersion("Version 1.4.0.0") .RegisterHighlight("Added two types of new Meta Changes, SHP and ATR (Thanks Karou!).") From 13df8b2248010554342a4081ac27ad4fd6d67471 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 23:02:22 +0200 Subject: [PATCH 1277/1381] Update gamedata. --- Penumbra.GameData | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index ea49bc09..fd875c43 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit ea49bc099e783ecafdf78f0bd0bc41fb8c60ad19 +Subproject commit fd875c43ee910350107b2609809335285bd4ac0f diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index eadee2d5..9356ff5e 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -726,6 +726,9 @@ public class DebugTab : Window, ITab, IUiService if (agent->Data == null) agent = &AgentBannerMIP.Instance()->AgentBannerInterface; + ImUtf8.Text("Agent: "); + ImGui.SameLine(0, 0); + Penumbra.Dynamis.DrawPointer((nint)agent); if (agent->Data != null) { using var table = Table("###PBannerTable", 2, ImGuiTableFlags.SizingFixedFit); From bedfb22466801e3a9bf8503a6fe0745ce1766a30 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 23:04:50 +0200 Subject: [PATCH 1278/1381] Use staging for release. --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c87c0244..377919b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | From 13283c969015d8e1d89a37721e6f5bc54da32664 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 23:08:26 +0200 Subject: [PATCH 1279/1381] Fix dumb. --- Penumbra/UI/Tabs/Debug/DebugTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 9356ff5e..b9e36d80 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -1048,7 +1048,7 @@ public class DebugTab : Window, ITab, IUiService if (t1) { ImGuiUtil.DrawTableColumn("Flags"); - ImGuiUtil.DrawTableColumn($"{model->UnkFlags_01:X2}"); + ImGuiUtil.DrawTableColumn($"{model->StateFlags}"); ImGuiUtil.DrawTableColumn("Has Model In Slot Loaded"); ImGuiUtil.DrawTableColumn($"{model->HasModelInSlotLoaded:X8}"); ImGuiUtil.DrawTableColumn("Has Model Files In Slot Loaded"); From 66543cc671f77d14d21dc3b0c5a1df644799e638 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 8 Aug 2025 21:12:00 +0000 Subject: [PATCH 1280/1381] [CI] Updating repo.json for 1.5.0.0 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index af368d75..16206811 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.4.0.1", - "TestingAssemblyVersion": "1.4.0.6", + "AssemblyVersion": "1.5.0.0", + "TestingAssemblyVersion": "1.5.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 12, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.4.0.6/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.4.0.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.0/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 46cfbcb115f34d4e5d5e2203b41e0379223e679b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 8 Aug 2025 23:13:23 +0200 Subject: [PATCH 1281/1381] Set Repo API level to 13 and remove stg from future releases. --- .github/workflows/release.yml | 2 +- repo.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 377919b2..c87c0244 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | diff --git a/repo.json b/repo.json index 16206811..8cc42d45 100644 --- a/repo.json +++ b/repo.json @@ -9,8 +9,8 @@ "TestingAssemblyVersion": "1.5.0.0", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 12, - "TestingDalamudApiLevel": 12, + "DalamudApiLevel": 13, + "TestingDalamudApiLevel": 13, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From 11cd08a9dec41d90b1e40f70e2c60d7508a4c7bf Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 9 Aug 2025 03:31:17 +0200 Subject: [PATCH 1282/1381] ClientStructs-ify stuff --- Penumbra/Interop/ResourceTree/ResourceTree.cs | 3 +-- Penumbra/Interop/Structs/StructExtensions.cs | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 49649e13..ddef347d 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -258,8 +258,7 @@ public class ResourceTree( for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) { - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1475) - var phybHandle = physics != null ? ((ResourceHandle**)((nint)physics + 0x190))[i] : null; + var phybHandle = physics != null ? physics->BonePhysicsResourceHandles[i] : null; if (context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, (uint)i) is { } sklbNode) { if (context.Global.WithUiData) diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 62dca02e..031d24b1 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -36,10 +36,8 @@ internal static class StructExtensions public static unsafe CiByteString ResolveSkinMtrlPathAsByteString(ref this CharacterBase character, uint slotIndex) { - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1474) - var vf91 = (delegate* unmanaged)((nint*)character.VirtualTable)[91]; var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(vf91((CharacterBase*)Unsafe.AsPointer(ref character), pathBuffer, CharacterBase.PathBufferSize, slotIndex)); + return ToOwnedByteString(character.ResolveSkinMtrlPath(pathBuffer, CharacterBase.PathBufferSize, slotIndex)); } public static CiByteString ResolveMaterialPapPathAsByteString(ref this CharacterBase character, uint slotIndex, uint unkSId) From 6242b30f93b1992b2639c3180a77aa333a365472 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 9 Aug 2025 11:58:28 +0200 Subject: [PATCH 1283/1381] Fix resizable child. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 9523b7ac..539ce9e5 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9523b7ac725656b21fa98faef96962652e86e64f +Subproject commit 539ce9e504fdc8bb0c2ca229905f4d236c376f6a From ff2b2be95352191c50701d5634c28fb75b53c000 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 9 Aug 2025 12:11:29 +0200 Subject: [PATCH 1284/1381] Fix popups not working early. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 539ce9e5..5224ac53 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 539ce9e504fdc8bb0c2ca229905f4d236c376f6a +Subproject commit 5224ac538b1a7c0e86e7d2ceaf652d8d807888ae From 391c9d727e2946e1a55bbda60cb238e2adde733a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 9 Aug 2025 12:51:39 +0200 Subject: [PATCH 1285/1381] Fix shifted timeline vfunc offset. --- Penumbra/Interop/GameState.cs | 3 --- Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs | 3 ++- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/GameState.cs b/Penumbra/Interop/GameState.cs index 32b45b7e..b5171244 100644 --- a/Penumbra/Interop/GameState.cs +++ b/Penumbra/Interop/GameState.cs @@ -59,9 +59,6 @@ public class GameState : IService private readonly ThreadLocal _characterSoundData = new(() => ResolveData.Invalid, true); - public ResolveData SoundData - => _characterSoundData.Value; - [MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)] public ResolveData SetSoundData(ResolveData data) { diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index cdd82b95..e0eb7ec5 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -63,7 +63,8 @@ public sealed unsafe class LoadTimelineResources : FastHookGetOwningGameObjectIndex(); + // TODO: Clientstructify + var idx = ((delegate* unmanaged**)timeline)[0][29](timeline); if (idx >= 0 && idx < objects.TotalCount) { var obj = objects[idx]; From 02af52671f0f5ce8ff8293bbcfe1fc2f0419a277 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 9 Aug 2025 13:00:40 +0200 Subject: [PATCH 1286/1381] Need staging again ... --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c87c0244..377919b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: run: dotnet restore - name: Download Dalamud run: | - Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/latest.zip -OutFile latest.zip + Invoke-WebRequest -Uri https://goatcorp.github.io/dalamud-distrib/stg/latest.zip -OutFile latest.zip Expand-Archive -Force latest.zip "$env:AppData\XIVLauncher\addon\Hooks\dev" - name: Build run: | From 3785a629ce42c500f604d85b78cd67ea03e7e6d6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 9 Aug 2025 11:03:24 +0000 Subject: [PATCH 1287/1381] [CI] Updating repo.json for 1.5.0.1 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 8cc42d45..9a970ea7 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.0", - "TestingAssemblyVersion": "1.5.0.0", + "AssemblyVersion": "1.5.0.1", + "TestingAssemblyVersion": "1.5.0.1", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.1/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.1/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.1/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 9aae2210a2f7194a61da4844f7c8df5812fbfa73 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 9 Aug 2025 14:54:56 +0200 Subject: [PATCH 1288/1381] Fix nullptr crashes --- OtterGui | 2 +- .../UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/OtterGui b/OtterGui index 5224ac53..0eaf7655 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 5224ac538b1a7c0e86e7d2ceaf652d8d807888ae +Subproject commit 0eaf7655123bd6502456e93d6ae9593249d3f792 diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs index bebacc94..e75cd633 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.LegacyColorTable.cs @@ -67,7 +67,7 @@ public partial class MtrlTab private static void DrawLegacyColorTableHeader(bool hasDyeTable) { ImGui.TableNextColumn(); - ImUtf8.TableHeader(default(ReadOnlySpan)); + ImUtf8.TableHeader(""u8); ImGui.TableNextColumn(); ImUtf8.TableHeader("Row"u8); ImGui.TableNextColumn(); From 155d3d49aa640da456794d9756097e82de158417 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 9 Aug 2025 16:40:42 +0000 Subject: [PATCH 1289/1381] [CI] Updating repo.json for 1.5.0.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 9a970ea7..cd2a8018 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.1", - "TestingAssemblyVersion": "1.5.0.1", + "AssemblyVersion": "1.5.0.2", + "TestingAssemblyVersion": "1.5.0.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.1/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.1/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.1/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From f6bac93db78f1dc42ea48774a37c38c07b2460dd Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 11 Aug 2025 19:58:24 +0200 Subject: [PATCH 1290/1381] Update ChangedEquipData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index fd875c43..2f5e9013 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit fd875c43ee910350107b2609809335285bd4ac0f +Subproject commit 2f5e901314444238ab3aa6c5043368622bca815a From 12a218bb2b4cee341d31fa3d2887b76ec67b816c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 12 Aug 2025 12:28:56 +0200 Subject: [PATCH 1291/1381] Protect against empty requested paths. --- .../Hooks/ResourceLoading/ResourceService.cs | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs index e90b4575..1a40accc 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/ResourceService.cs @@ -1,4 +1,5 @@ using Dalamud.Hooking; +using Dalamud.Interface.Windowing; using Dalamud.Plugin.Services; using Dalamud.Utility.Signatures; using FFXIVClientStructs.FFXIV.Client.System.Resource; @@ -85,7 +86,8 @@ public unsafe class ResourceService : IDisposable, IRequiredService ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams, nint unk7, uint unk8); private delegate ResourceHandle* GetResourceAsyncPrototype(ResourceManager* resourceManager, ResourceCategory* pCategoryId, - ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams, byte isUnknown, nint unk8, uint unk9); + ResourceType* pResourceType, int* pResourceHash, byte* pPath, GetResourceParameters* pGetResParams, byte isUnknown, nint unk8, + uint unk9); [Signature(Sigs.GetResourceSync, DetourName = nameof(GetResourceSyncDetour))] private readonly Hook _getResourceSyncHook = null!; @@ -118,18 +120,26 @@ public unsafe class ResourceService : IDisposable, IRequiredService unk9); } - var original = gamePath; + if (gamePath.IsEmpty) + { + Penumbra.Log.Error($"[ResourceService] Empty resource path requested with category {*categoryId}, type {*resourceType}, hash {*resourceHash}."); + return null; + } + + var original = gamePath; ResourceHandle* returnValue = null; ResourceRequested?.Invoke(ref *categoryId, ref *resourceType, ref *resourceHash, ref gamePath, original, pGetResParams, ref isSync, ref returnValue); if (returnValue != null) return returnValue; - return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, original, pGetResParams, isUnk, unk8, unk9); + return GetOriginalResource(isSync, *categoryId, *resourceType, *resourceHash, gamePath.Path, original, pGetResParams, isUnk, unk8, + unk9); } /// Call the original GetResource function. - public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, Utf8GamePath original, + public ResourceHandle* GetOriginalResource(bool sync, ResourceCategory categoryId, ResourceType type, int hash, CiByteString path, + Utf8GamePath original, GetResourceParameters* resourceParameters = null, byte unk = 0, nint unk8 = 0, uint unk9 = 0) { var previous = _currentGetResourcePath.Value; @@ -141,7 +151,8 @@ public unsafe class ResourceService : IDisposable, IRequiredService resourceParameters, unk8, unk9) : _getResourceAsyncHook.OriginalDisposeSafe(_resourceManager.ResourceManager, &categoryId, &type, &hash, path.Path, resourceParameters, unk, unk8, unk9); - } finally + } + finally { _currentGetResourcePath.Value = previous; } @@ -163,7 +174,8 @@ public unsafe class ResourceService : IDisposable, IRequiredService /// The original game path of the resource, if loaded synchronously. /// The previous state of the resource. /// The return value to use. - public delegate void ResourceStateUpdatedDelegate(ResourceHandle* handle, Utf8GamePath syncOriginal, (byte UnkState, LoadState LoadState) previousState, ref uint returnValue); + public delegate void ResourceStateUpdatedDelegate(ResourceHandle* handle, Utf8GamePath syncOriginal, + (byte UnkState, LoadState LoadState) previousState, ref uint returnValue); /// /// @@ -185,7 +197,7 @@ public unsafe class ResourceService : IDisposable, IRequiredService private uint UpdateResourceStateDetour(ResourceHandle* handle, byte offFileThread) { var previousState = (handle->UnkState, handle->LoadState); - var syncOriginal = _currentGetResourcePath.IsValueCreated ? _currentGetResourcePath.Value : Utf8GamePath.Empty; + var syncOriginal = _currentGetResourcePath.IsValueCreated ? _currentGetResourcePath.Value : Utf8GamePath.Empty; ResourceStateUpdating?.Invoke(handle, syncOriginal); var ret = _updateResourceStateHook.OriginalDisposeSafe(handle, offFileThread); ResourceStateUpdated?.Invoke(handle, syncOriginal, previousState, ref ret); From 7af81a6c18f382cd2b2cf806134060fed421dbd9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 12 Aug 2025 12:29:09 +0200 Subject: [PATCH 1292/1381] Fix issue with removing default metadata. --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index ede062ae..c2c9e777 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -126,6 +126,7 @@ public class MetaDictionary { _data = null; Count = 0; + return; } Count = GlobalEqp.Count + Shp.Count + Atr.Count; From b112d75a27baac5ea02e60c353fcb32e6f46e609 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 12 Aug 2025 10:31:13 +0000 Subject: [PATCH 1293/1381] [CI] Updating repo.json for 1.5.0.3 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index cd2a8018..305912c0 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.2", - "TestingAssemblyVersion": "1.5.0.2", + "AssemblyVersion": "1.5.0.3", + "TestingAssemblyVersion": "1.5.0.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.2/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.3/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.3/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 9f8185f67baf18ee552bf68fa3556fa4509d3acb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 12 Aug 2025 14:47:35 +0200 Subject: [PATCH 1294/1381] Add new parameter to LoadWeapon hook. --- Penumbra/Interop/Hooks/Objects/WeaponReload.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs index b09103f6..4231b027 100644 --- a/Penumbra/Interop/Hooks/Objects/WeaponReload.cs +++ b/Penumbra/Interop/Hooks/Objects/WeaponReload.cs @@ -35,14 +35,14 @@ public sealed unsafe class WeaponReload : EventWrapperPtr _task.IsCompletedSuccessfully; - private delegate void Delegate(DrawDataContainer* drawData, uint slot, ulong weapon, byte d, byte e, byte f, byte g); + private delegate void Delegate(DrawDataContainer* drawData, uint slot, ulong weapon, byte d, byte e, byte f, byte g, byte h); - private void Detour(DrawDataContainer* drawData, uint slot, ulong weapon, byte d, byte e, byte f, byte g) + private void Detour(DrawDataContainer* drawData, uint slot, ulong weapon, byte d, byte e, byte f, byte g, byte h) { var gameObject = drawData->OwnerObject; - Penumbra.Log.Verbose($"[{Name}] Triggered with drawData: 0x{(nint)drawData:X}, {slot}, {weapon}, {d}, {e}, {f}, {g}."); + Penumbra.Log.Verbose($"[{Name}] Triggered with drawData: 0x{(nint)drawData:X}, {slot}, {weapon}, {d}, {e}, {f}, {g}, {h}."); Invoke(drawData, gameObject, (CharacterWeapon*)(&weapon)); - _task.Result.Original(drawData, slot, weapon, d, e, f, g); + _task.Result.Original(drawData, slot, weapon, d, e, f, g, h); _postEvent.Invoke(drawData, gameObject); } From 9aff388e21a6e0d688157123ec5b3d2d061b90dd Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 12 Aug 2025 12:53:33 +0000 Subject: [PATCH 1295/1381] [CI] Updating repo.json for 1.5.0.4 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 305912c0..6045e266 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.3", - "TestingAssemblyVersion": "1.5.0.3", + "AssemblyVersion": "1.5.0.4", + "TestingAssemblyVersion": "1.5.0.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.3/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.3/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.3/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.4/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.4/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From a7246b9d98392db549ec6fd408d430843664e48b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 13 Aug 2025 16:50:26 +0200 Subject: [PATCH 1296/1381] Add PBD Post-Processor that appends EPBD data if the loaded PBD does not contain it. --- OtterGui | 2 +- Penumbra.GameData | 2 +- .../PostProcessing/PreBoneDeformerReplacer.cs | 2 +- .../Processing/PbdFilePostProcessor.cs | 119 ++++++++++++++++++ Penumbra/UI/AdvancedWindow/FileEditor.cs | 3 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 16 +-- .../UI/Tabs/Debug/GlobalVariablesDrawer.cs | 73 ++++++----- Penumbra/packages.lock.json | 22 +++- 8 files changed, 187 insertions(+), 52 deletions(-) create mode 100644 Penumbra/Interop/Processing/PbdFilePostProcessor.cs diff --git a/OtterGui b/OtterGui index 0eaf7655..3ea61642 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 0eaf7655123bd6502456e93d6ae9593249d3f792 +Subproject commit 3ea61642a05403fb2b64032112ff674b387825b3 diff --git a/Penumbra.GameData b/Penumbra.GameData index 2f5e9013..2cf59c61 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2f5e901314444238ab3aa6c5043368622bca815a +Subproject commit 2cf59c61494a01fd14aecf925e7dc6325a7374ac diff --git a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs index 30e643c7..51af5813 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/PreBoneDeformerReplacer.cs @@ -63,7 +63,7 @@ public sealed unsafe class PreBoneDeformerReplacer : IDisposable, IRequiredServi if (!_framework.IsInFrameworkUpdateThread) Penumbra.Log.Warning( $"{nameof(PreBoneDeformerReplacer)}.{nameof(SetupHssReplacements)}(0x{(nint)drawObject:X}, {slotIndex}) called out of framework thread"); - + var preBoneDeformer = GetPreBoneDeformerForCharacter(drawObject); try { diff --git a/Penumbra/Interop/Processing/PbdFilePostProcessor.cs b/Penumbra/Interop/Processing/PbdFilePostProcessor.cs new file mode 100644 index 00000000..69f2ecd5 --- /dev/null +++ b/Penumbra/Interop/Processing/PbdFilePostProcessor.cs @@ -0,0 +1,119 @@ +using Dalamud.Game; +using Dalamud.Plugin.Services; +using Penumbra.Api.Enums; +using Penumbra.GameData; +using Penumbra.GameData.Data; +using Penumbra.Interop.Structs; +using Penumbra.Meta.Files; +using Penumbra.String; + +namespace Penumbra.Interop.Processing; + +public sealed class PbdFilePostProcessor : IFilePostProcessor +{ + private readonly IFileAllocator _allocator; + private byte[] _epbdData; + private unsafe delegate* unmanaged _loadEpbdData; + + public ResourceType Type + => ResourceType.Pbd; + + public unsafe PbdFilePostProcessor(IDataManager dataManager, XivFileAllocator allocator, ISigScanner scanner) + { + _allocator = allocator; + _epbdData = SetEpbdData(dataManager); + _loadEpbdData = (delegate* unmanaged)scanner.ScanText(Sigs.LoadEpbdData); + } + + public unsafe void PostProcess(ResourceHandle* resource, CiByteString originalGamePath, ReadOnlySpan additionalData) + { + if (_epbdData.Length is 0) + return; + + if (resource->LoadState is not LoadState.Success) + { + Penumbra.Log.Warning($"[ResourceLoader] Requested PBD at {originalGamePath} failed load ({resource->LoadState})."); + return; + } + + var (data, length) = resource->GetData(); + if (length is 0 || data == nint.Zero) + { + Penumbra.Log.Warning($"[ResourceLoader] Requested PBD at {originalGamePath} succeeded load but has no data."); + return; + } + + var span = new ReadOnlySpan((void*)data, (int)resource->FileSize); + var reader = new PackReader(span); + if (reader.HasData) + { + Penumbra.Log.Excessive($"[ResourceLoader] Successfully loaded PBD at {originalGamePath} with EPBD data."); + return; + } + + var newData = AppendData(span); + fixed (byte* ptr = newData) + { + // Set the appended data and the actual file size, then re-load the EPBD data via game function call. + if (resource->SetData((nint)ptr, newData.Length)) + { + resource->FileSize = (uint)newData.Length; + resource->CsHandle.FileSize2 = (uint)newData.Length; + resource->CsHandle.FileSize3 = (uint)newData.Length; + _loadEpbdData(resource); + // Free original data. + _allocator.Release((void*)data, length); + Penumbra.Log.Verbose($"[ResourceLoader] Loaded {originalGamePath} from file and appended default EPBD data."); + } + else + { + Penumbra.Log.Warning( + $"[ResourceLoader] Failed to append EPBD data to custom PBD at {originalGamePath}."); + } + } + } + + /// Combine the given data with the default PBD data using the game's file allocator. + private unsafe ReadOnlySpan AppendData(ReadOnlySpan data) + { + // offset has to be set, otherwise not called. + var newLength = data.Length + _epbdData.Length; + var memory = _allocator.Allocate(newLength); + var span = new Span(memory, newLength); + data.CopyTo(span); + _epbdData.CopyTo(span[data.Length..]); + return span; + } + + /// Fetch the default EPBD data from the .pbd file of the game's installation. + private static byte[] SetEpbdData(IDataManager dataManager) + { + try + { + var file = dataManager.GetFile(GamePaths.Pbd.Path); + if (file is null || file.Data.Length is 0) + { + Penumbra.Log.Warning("Default PBD file has no data."); + return []; + } + + ReadOnlySpan span = file.Data; + var reader = new PackReader(span); + if (!reader.HasData) + { + Penumbra.Log.Warning("Default PBD file has no EPBD section."); + return []; + } + + var offset = span.Length - (int)reader.PackLength; + var ret = span[offset..]; + Penumbra.Log.Verbose($"Default PBD file has EPBD section of length {ret.Length} at offset {offset}."); + return ret.ToArray(); + } + catch (Exception ex) + { + Penumbra.Log.Error($"Unknown error getting default EPBD data:\n{ex}"); + return []; + } + } +} diff --git a/Penumbra/UI/AdvancedWindow/FileEditor.cs b/Penumbra/UI/AdvancedWindow/FileEditor.cs index a0305619..424bc56f 100644 --- a/Penumbra/UI/AdvancedWindow/FileEditor.cs +++ b/Penumbra/UI/AdvancedWindow/FileEditor.cs @@ -8,6 +8,7 @@ using OtterGui.Compression; using OtterGui.Raii; using OtterGui.Text; using OtterGui.Widgets; +using Penumbra.GameData.Data; using Penumbra.GameData.Files; using Penumbra.Mods.Editor; using Penumbra.Services; @@ -80,7 +81,7 @@ public class FileEditor( private Exception? _currentException; private bool _changed; - private string _defaultPath = string.Empty; + private string _defaultPath = typeof(T) == typeof(ModEditWindow.PbdTab) ? GamePaths.Pbd.Path : string.Empty; private bool _inInput; private Utf8GamePath _defaultPathUtf8; private bool _isDefaultPathUtf8Valid; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index b9e36d80..d41dd25a 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -1236,16 +1236,12 @@ public class DebugTab : Window, ITab, IUiService } public static unsafe void DrawCopyableAddress(ReadOnlySpan label, void* address) - { - using (var _ = ImRaii.PushFont(UiBuilder.MonoFont)) - { - if (ImUtf8.Selectable($"0x{(nint)address:X16} {label}")) - ImUtf8.SetClipboardText($"0x{(nint)address:X16}"); - } - - ImUtf8.HoverTooltip("Click to copy address to clipboard."u8); - } + => DrawCopyableAddress(label, (nint)address); public static unsafe void DrawCopyableAddress(ReadOnlySpan label, nint address) - => DrawCopyableAddress(label, (void*)address); + { + Penumbra.Dynamis.DrawPointer(address); + ImUtf8.SameLineInner(); + ImUtf8.Text(label); + } } diff --git a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs index 7af33a36..f0ab1125 100644 --- a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs @@ -27,14 +27,31 @@ public unsafe class GlobalVariablesDrawer( return; var actionManager = (ActionTimelineManager**)ActionTimelineManager.Instance(); - DebugTab.DrawCopyableAddress("CharacterUtility"u8, characterUtility.Address); - DebugTab.DrawCopyableAddress("ResidentResourceManager"u8, residentResources.Address); - DebugTab.DrawCopyableAddress("ScheduleManagement"u8, ScheduleManagement.Instance()); - DebugTab.DrawCopyableAddress("ActionTimelineManager*"u8, actionManager); - DebugTab.DrawCopyableAddress("ActionTimelineManager"u8, actionManager != null ? *actionManager : null); - DebugTab.DrawCopyableAddress("SchedulerResourceManagement*"u8, scheduler.Address); - DebugTab.DrawCopyableAddress("SchedulerResourceManagement"u8, scheduler.Address != null ? *scheduler.Address : null); - DebugTab.DrawCopyableAddress("Device"u8, Device.Instance()); + using (ImUtf8.Group()) + { + Penumbra.Dynamis.DrawPointer(characterUtility.Address); + Penumbra.Dynamis.DrawPointer(residentResources.Address); + Penumbra.Dynamis.DrawPointer(ScheduleManagement.Instance()); + Penumbra.Dynamis.DrawPointer(actionManager); + Penumbra.Dynamis.DrawPointer(actionManager != null ? *actionManager : null); + Penumbra.Dynamis.DrawPointer(scheduler.Address); + Penumbra.Dynamis.DrawPointer(scheduler.Address != null ? *scheduler.Address : null); + Penumbra.Dynamis.DrawPointer(Device.Instance()); + } + + ImGui.SameLine(); + using (ImUtf8.Group()) + { + ImUtf8.Text("CharacterUtility"u8); + ImUtf8.Text("ResidentResourceManager"u8); + ImUtf8.Text("ScheduleManagement"u8); + ImUtf8.Text("ActionTimelineManager*"u8); + ImUtf8.Text("ActionTimelineManager"u8); + ImUtf8.Text("SchedulerResourceManagement*"u8); + ImUtf8.Text("SchedulerResourceManagement"u8); + ImUtf8.Text("Device"u8); + } + DrawCharacterUtility(); DrawResidentResources(); DrawSchedulerResourcesMap(); @@ -63,7 +80,7 @@ public unsafe class GlobalVariablesDrawer( var resource = characterUtility.Address->Resource(idx); ImUtf8.DrawTableColumn($"[{idx}]"); ImGui.TableNextColumn(); - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + Penumbra.Dynamis.DrawPointer(resource); if (resource == null) { ImGui.TableNextRow(); @@ -74,25 +91,12 @@ public unsafe class GlobalVariablesDrawer( ImGui.TableNextColumn(); var data = (nint)resource->CsHandle.GetData(); var length = resource->CsHandle.GetLength(); - if (ImUtf8.Selectable($"0x{data:X}")) - if (data != nint.Zero && length > 0) - ImUtf8.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); - - ImUtf8.HoverTooltip("Click to copy bytes to clipboard."u8); + Penumbra.Dynamis.DrawPointer(data); ImUtf8.DrawTableColumn(length.ToString()); - ImGui.TableNextColumn(); if (intern.Value != -1) { - ImUtf8.Selectable($"0x{characterUtility.DefaultResource(intern).Address:X}"); - if (ImGui.IsItemClicked()) - ImUtf8.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)characterUtility.DefaultResource(intern).Address, - characterUtility.DefaultResource(intern).Size).ToArray().Select(b => b.ToString("X2")))); - - ImUtf8.HoverTooltip("Click to copy bytes to clipboard."u8); - + Penumbra.Dynamis.DrawPointer(characterUtility.DefaultResource(intern).Address); ImUtf8.DrawTableColumn($"{characterUtility.DefaultResource(intern).Size}"); } else @@ -122,7 +126,7 @@ public unsafe class GlobalVariablesDrawer( var resource = residentResources.Address->ResourceList[idx]; ImUtf8.DrawTableColumn($"[{idx}]"); ImGui.TableNextColumn(); - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + Penumbra.Dynamis.DrawPointer(resource); if (resource == null) { ImGui.TableNextRow(); @@ -133,12 +137,7 @@ public unsafe class GlobalVariablesDrawer( ImGui.TableNextColumn(); var data = (nint)resource->CsHandle.GetData(); var length = resource->CsHandle.GetLength(); - if (ImUtf8.Selectable($"0x{data:X}")) - if (data != nint.Zero && length > 0) - ImUtf8.SetClipboardText(string.Join("\n", - new ReadOnlySpan((byte*)data, (int)length).ToArray().Select(b => b.ToString("X2")))); - - ImUtf8.HoverTooltip("Click to copy bytes to clipboard."u8); + Penumbra.Dynamis.DrawPointer(data); ImUtf8.DrawTableColumn(length.ToString()); } } @@ -184,15 +183,15 @@ public unsafe class GlobalVariablesDrawer( ImUtf8.DrawTableColumn($"{resource->Consumers}"); ImUtf8.DrawTableColumn($"{resource->Unk1}"); // key ImGui.TableNextColumn(); - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + Penumbra.Dynamis.DrawPointer(resource); ImGui.TableNextColumn(); var resourceHandle = *((ResourceHandle**)resource + 3); - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resourceHandle:X}"); + Penumbra.Dynamis.DrawPointer(resourceHandle); ImGui.TableNextColumn(); ImUtf8.CopyOnClickSelectable(resourceHandle->FileName().Span); ImGui.TableNextColumn(); uint dataLength = 0; - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource->GetResourceData(&dataLength):X}"); + Penumbra.Dynamis.DrawPointer(resource->GetResourceData(&dataLength)); ImUtf8.DrawTableColumn($"{dataLength}"); ++_shownResourcesMap; } @@ -233,15 +232,15 @@ public unsafe class GlobalVariablesDrawer( ImUtf8.DrawTableColumn($"{resource->Consumers}"); ImUtf8.DrawTableColumn($"{resource->Unk1}"); // key ImGui.TableNextColumn(); - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource:X}"); + Penumbra.Dynamis.DrawPointer(resource); ImGui.TableNextColumn(); var resourceHandle = *((ResourceHandle**)resource + 3); - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resourceHandle:X}"); + Penumbra.Dynamis.DrawPointer(resourceHandle); ImGui.TableNextColumn(); ImUtf8.CopyOnClickSelectable(resourceHandle->FileName().Span); ImGui.TableNextColumn(); uint dataLength = 0; - ImUtf8.CopyOnClickSelectable($"0x{(ulong)resource->GetResourceData(&dataLength):X}"); + Penumbra.Dynamis.DrawPointer(resource->GetResourceData(&dataLength)); ImUtf8.DrawTableColumn($"{dataLength}"); ++_shownResourcesList; } diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 778f776e..7499bffa 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -58,6 +58,19 @@ "resolved": "3.1.11", "contentHash": "JfPLyigLthuE50yi6tMt7Amrenr/fA31t2CvJyhy/kQmfulIBAqo5T/YFUSRHtuYPXRSaUHygFeh6Qd933EoSw==" }, + "FlatSharp.Compiler": { + "type": "Transitive", + "resolved": "7.9.0", + "contentHash": "MU6808xvdbWJ3Ev+5PKalqQuzvVbn1DzzQH8txRDHGFUNDvHjd+ejqpvnYc9BSJ8Qp8VjkkpJD8OzRYilbPp3A==" + }, + "FlatSharp.Runtime": { + "type": "Transitive", + "resolved": "7.9.0", + "contentHash": "Bm8+WqzEsWNpxqrD5x4x+zQ8dyINlToCreM5FI2oNSfUVc9U9ZB+qztX/jd8rlJb3r0vBSlPwVLpw0xBtPa3Vw==", + "dependencies": { + "System.Memory": "4.5.5" + } + }, "JetBrains.Annotations": { "type": "Transitive", "resolved": "2024.3.0", @@ -94,6 +107,11 @@ "resolved": "4.6.0", "contentHash": "lN6tZi7Q46zFzAbRYXTIvfXcyvQQgxnY7Xm6C6xQ9784dEL1amjM6S6Iw4ZpsvesAKnRVsM4scrDQaDqSClkjA==" }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.5.5", + "contentHash": "XIWiDvKPXaTveaB7HVganDlOCRoj03l+jrwNvcge/t8vhGYKvqV+dMv6G4SAX2NoNmN0wZfVPTAlFwZcZvVOUw==" + }, "System.Security.Cryptography.Pkcs": { "type": "Transitive", "resolved": "8.0.1", @@ -133,8 +151,10 @@ "penumbra.gamedata": { "type": "Project", "dependencies": { + "FlatSharp.Compiler": "[7.9.0, )", + "FlatSharp.Runtime": "[7.9.0, )", "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[5.6.1, )", + "Penumbra.Api": "[5.10.0, )", "Penumbra.String": "[1.0.6, )" } }, From f69c2643176b2c2b08eb92e08facc945f96b3ce3 Mon Sep 17 00:00:00 2001 From: Actions User Date: Wed, 13 Aug 2025 14:53:11 +0000 Subject: [PATCH 1297/1381] [CI] Updating repo.json for 1.5.0.5 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 6045e266..f6d69c8b 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.4", - "TestingAssemblyVersion": "1.5.0.4", + "AssemblyVersion": "1.5.0.5", + "TestingAssemblyVersion": "1.5.0.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.4/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.4/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.4/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.5/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.5/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.5/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 5917f5fad12125339d4cb52182dfc57bdbdbbf80 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 13 Aug 2025 17:42:40 +0200 Subject: [PATCH 1298/1381] Small fixes. --- Penumbra/Interop/Processing/PbdFilePostProcessor.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/Processing/PbdFilePostProcessor.cs b/Penumbra/Interop/Processing/PbdFilePostProcessor.cs index 69f2ecd5..674500cd 100644 --- a/Penumbra/Interop/Processing/PbdFilePostProcessor.cs +++ b/Penumbra/Interop/Processing/PbdFilePostProcessor.cs @@ -32,14 +32,14 @@ public sealed class PbdFilePostProcessor : IFilePostProcessor if (resource->LoadState is not LoadState.Success) { - Penumbra.Log.Warning($"[ResourceLoader] Requested PBD at {originalGamePath} failed load ({resource->LoadState})."); + Penumbra.Log.Warning($"[ResourceLoader] Requested PBD at {resource->FileName()} failed load ({resource->LoadState})."); return; } var (data, length) = resource->GetData(); if (length is 0 || data == nint.Zero) { - Penumbra.Log.Warning($"[ResourceLoader] Requested PBD at {originalGamePath} succeeded load but has no data."); + Penumbra.Log.Warning($"[ResourceLoader] Requested PBD at {resource->FileName()} succeeded load but has no data."); return; } @@ -47,7 +47,7 @@ public sealed class PbdFilePostProcessor : IFilePostProcessor var reader = new PackReader(span); if (reader.HasData) { - Penumbra.Log.Excessive($"[ResourceLoader] Successfully loaded PBD at {originalGamePath} with EPBD data."); + Penumbra.Log.Excessive($"[ResourceLoader] Successfully loaded PBD at {resource->FileName()} with EPBD data."); return; } @@ -63,12 +63,12 @@ public sealed class PbdFilePostProcessor : IFilePostProcessor _loadEpbdData(resource); // Free original data. _allocator.Release((void*)data, length); - Penumbra.Log.Verbose($"[ResourceLoader] Loaded {originalGamePath} from file and appended default EPBD data."); + Penumbra.Log.Debug($"[ResourceLoader] Loaded {resource->FileName()} from file and appended default EPBD data."); } else { Penumbra.Log.Warning( - $"[ResourceLoader] Failed to append EPBD data to custom PBD at {originalGamePath}."); + $"[ResourceLoader] Failed to append EPBD data to custom PBD at {resource->FileName()}."); } } } From 87ace28bcfea13d8a50c8f8c1e3822a2f0302353 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 16 Aug 2025 11:56:24 +0200 Subject: [PATCH 1299/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index 3ea61642..4a9b71a9 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 3ea61642a05403fb2b64032112ff674b387825b3 +Subproject commit 4a9b71a93e76aa5eed818542288329e34ec0dd89 From aa920b5e9b46f7139decfea27d248478212012fa Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 17 Aug 2025 01:41:49 +0200 Subject: [PATCH 1300/1381] Fix ImGui texture usage issue --- Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs index 241c3a91..24a5f9c2 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MaterialTemplatePickers.cs @@ -131,7 +131,7 @@ public sealed unsafe class MaterialTemplatePickers : IUiService if (texture == null) continue; var handle = _textureArraySlicer.GetImGuiHandle(texture, sliceIndex); - if (handle == 0) + if (handle.IsNull) continue; var position = regionStart with { X = regionStart.X + (itemSize.X + itemSpacing) * j }; From 41edc2382005e3ff2600872aefb276fabd741c30 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 17 Aug 2025 03:10:35 +0200 Subject: [PATCH 1301/1381] Allow changing the skin mtrl suffix --- .../Hooks/Resources/ResolvePathHooksBase.cs | 9 ++- .../Processing/SkinMtrlPathEarlyProcessing.cs | 61 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index 85fb1098..eecb98c5 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -6,6 +6,7 @@ using Penumbra.Collections; using Penumbra.GameData.Enums; using Penumbra.GameData.Structs; using Penumbra.Interop.PathResolving; +using Penumbra.Interop.Processing; using static FFXIVClientStructs.FFXIV.Client.Game.Character.ActionEffectHandler; namespace Penumbra.Interop.Hooks.Resources; @@ -159,7 +160,13 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable => ResolvePath(drawObject, _resolveMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex, mtrlFileName)); private nint ResolveSkinMtrl(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) - => ResolvePath(drawObject, _resolveSkinMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex)); + { + var finalPathBuffer = _resolveSkinMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex); + if (finalPathBuffer != 0 && finalPathBuffer == pathBuffer) + SkinMtrlPathEarlyProcessing.Process(new Span((void*)pathBuffer, (int)pathBufferSize), (CharacterBase*)drawObject, slotIndex); + + return ResolvePath(drawObject, finalPathBuffer); + } private nint ResolvePap(nint drawObject, nint pathBuffer, nint pathBufferSize, uint unkAnimationIndex, nint animationName) => ResolvePath(drawObject, _resolvePapPathHook.Original(drawObject, pathBuffer, pathBufferSize, unkAnimationIndex, animationName)); diff --git a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs new file mode 100644 index 00000000..d35845e1 --- /dev/null +++ b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs @@ -0,0 +1,61 @@ +using FFXIVClientStructs.FFXIV.Client.Graphics.Scene; +using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; + +namespace Penumbra.Interop.Processing; + +public static unsafe class SkinMtrlPathEarlyProcessing +{ + public static void Process(Span path, CharacterBase* character, uint slotIndex) + { + var end = path.IndexOf(".mtrl\0"u8); + if (end < 0) + return; + + var suffixPos = path[..end].LastIndexOf((byte)'_'); + if (suffixPos < 0) + return; + + var handle = GetModelResourceHandle(character, slotIndex); + if (handle == null) + return; + + var skinSuffix = GetSkinSuffix(handle); + if (skinSuffix.IsEmpty || skinSuffix.Length > path.Length - suffixPos - 7) + return; + + skinSuffix.CopyTo(path[(suffixPos + 1)..]); + ".mtrl\0"u8.CopyTo(path[(suffixPos + 1 + skinSuffix.Length)..]); + } + + private static ModelResourceHandle* GetModelResourceHandle(CharacterBase* character, uint slotIndex) + { + if (character == null) + return null; + + if (character->TempSlotData != null) + { + // TODO ClientStructs-ify + var handle = *(ModelResourceHandle**)((nint)character->TempSlotData + 0xE0 * slotIndex + 0x8); + if (handle != null) + return handle; + } + + var model = character->Models[slotIndex]; + if (model == null) + return null; + + return model->ModelResourceHandle; + } + + private static ReadOnlySpan GetSkinSuffix(ModelResourceHandle* handle) + { + foreach (var (attribute, _) in handle->Attributes) + { + var attributeSpan = attribute.AsSpan(); + if (attributeSpan.Length > 12 && attributeSpan[..11].SequenceEqual("skin_suffix"u8) && attributeSpan[11] is (byte)'=' or (byte)'_') + return attributeSpan[12..]; + } + + return []; + } +} From 24cbc6c5e141aacddda897dc3e0a2eb637847f99 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 17 Aug 2025 08:46:26 +0000 Subject: [PATCH 1302/1381] [CI] Updating repo.json for 1.5.0.6 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index f6d69c8b..a452dc94 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.5", - "TestingAssemblyVersion": "1.5.0.5", + "AssemblyVersion": "1.5.0.6", + "TestingAssemblyVersion": "1.5.0.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.5/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.5/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.5/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 8304579d29788d4bb41b7af043516e3912561d86 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 17 Aug 2025 13:54:31 +0200 Subject: [PATCH 1303/1381] Add predefined tags to the multi mod selector. --- Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs | 2 +- Penumbra/UI/ModsTab/ModPanelEditTab.cs | 2 +- Penumbra/UI/ModsTab/MultiModPanel.cs | 22 +++- Penumbra/UI/PredefinedTagManager.cs | 119 ++++++++++++++++-- 4 files changed, 132 insertions(+), 13 deletions(-) diff --git a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs index 71c1a225..b8710707 100644 --- a/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelDescriptionTab.cs @@ -30,7 +30,7 @@ public class ModPanelDescriptionTab( ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); ImGui.Dummy(ImGuiHelpers.ScaledVector2(2)); - var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.Count > 0 + var (predefinedTagsEnabled, predefinedTagButtonOffset) = predefinedTagsConfig.Enabled ? (true, ImGui.GetFrameHeight() + ImGui.GetStyle().WindowPadding.X + (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ScrollbarSize : 0)) : (false, 0); var tagIdx = _localTags.Draw("Local Tags: ", diff --git a/Penumbra/UI/ModsTab/ModPanelEditTab.cs b/Penumbra/UI/ModsTab/ModPanelEditTab.cs index 5b831a66..c3737b40 100644 --- a/Penumbra/UI/ModsTab/ModPanelEditTab.cs +++ b/Penumbra/UI/ModsTab/ModPanelEditTab.cs @@ -69,7 +69,7 @@ public class ModPanelEditTab( FeatureChecker.DrawFeatureFlagInput(modManager.DataEditor, _mod, UiHelpers.InputTextWidth.X); UiHelpers.DefaultLineSpace(); - var sharedTagsEnabled = predefinedTagManager.Count > 0; + var sharedTagsEnabled = predefinedTagManager.Enabled; var sharedTagButtonOffset = sharedTagsEnabled ? ImGui.GetFrameHeight() + ImGui.GetStyle().FramePadding.X : 0; var tagIdx = _modTags.Draw("Mod Tags: ", "Edit tags by clicking them, or add new tags. Empty tags are removed.", _mod.ModTags, out var editedTag, rightEndOffset: sharedTagButtonOffset); diff --git a/Penumbra/UI/ModsTab/MultiModPanel.cs b/Penumbra/UI/ModsTab/MultiModPanel.cs index 3eac972c..947ede14 100644 --- a/Penumbra/UI/ModsTab/MultiModPanel.cs +++ b/Penumbra/UI/ModsTab/MultiModPanel.cs @@ -2,6 +2,7 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface; using Dalamud.Interface.Utility; using OtterGui.Extensions; +using OtterGui.Filesystem; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Text; @@ -10,7 +11,7 @@ using Penumbra.Mods.Manager; namespace Penumbra.UI.ModsTab; -public class MultiModPanel(ModFileSystemSelector selector, ModDataEditor editor) : IUiService +public class MultiModPanel(ModFileSystemSelector selector, ModDataEditor editor, PredefinedTagManager tagManager) : IUiService { public void Draw() { @@ -97,7 +98,12 @@ public class MultiModPanel(ModFileSystemSelector selector, ModDataEditor editor) var width = ImGuiHelpers.ScaledVector2(150, 0); ImUtf8.TextFrameAligned("Multi Tagger:"u8); ImGui.SameLine(); - ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X - 2 * (width.X + ImGui.GetStyle().ItemSpacing.X)); + + var predefinedTagsEnabled = tagManager.Enabled; + var inputWidth = predefinedTagsEnabled + ? ImGui.GetContentRegionAvail().X - 2 * width.X - 3 * ImGui.GetStyle().ItemInnerSpacing.X - ImGui.GetFrameHeight() + : ImGui.GetContentRegionAvail().X - 2 * (width.X + ImGui.GetStyle().ItemInnerSpacing.X); + ImGui.SetNextItemWidth(inputWidth); ImUtf8.InputText("##tag"u8, ref _tag, "Local Tag Name..."u8); UpdateTagCache(); @@ -109,7 +115,7 @@ public class MultiModPanel(ModFileSystemSelector selector, ModDataEditor editor) ? "No tag specified." : $"All mods selected already contain the tag \"{_tag}\", either locally or as mod data." : $"Add the tag \"{_tag}\" to {_addMods.Count} mods as a local tag:\n\n\t{string.Join("\n\t", _addMods.Select(m => m.Name.Text))}"; - ImGui.SameLine(); + ImUtf8.SameLineInner(); if (ImUtf8.ButtonEx(label, tooltip, width, _addMods.Count == 0)) foreach (var mod in _addMods) editor.ChangeLocalTag(mod, mod.LocalTags.Count, _tag); @@ -122,10 +128,18 @@ public class MultiModPanel(ModFileSystemSelector selector, ModDataEditor editor) ? "No tag specified." : $"No selected mod contains the tag \"{_tag}\" locally." : $"Remove the local tag \"{_tag}\" from {_removeMods.Count} mods:\n\n\t{string.Join("\n\t", _removeMods.Select(m => m.Item1.Name.Text))}"; - ImGui.SameLine(); + ImUtf8.SameLineInner(); if (ImUtf8.ButtonEx(label, tooltip, width, _removeMods.Count == 0)) foreach (var (mod, index) in _removeMods) editor.ChangeLocalTag(mod, index, string.Empty); + + if (predefinedTagsEnabled) + { + ImUtf8.SameLineInner(); + tagManager.DrawToggleButton(); + tagManager.DrawListMulti(selector.SelectedPaths.OfType().Select(l => l.Value)); + } + ImGui.Separator(); } diff --git a/Penumbra/UI/PredefinedTagManager.cs b/Penumbra/UI/PredefinedTagManager.cs index 7e268e8c..5a3a4b62 100644 --- a/Penumbra/UI/PredefinedTagManager.cs +++ b/Penumbra/UI/PredefinedTagManager.cs @@ -8,6 +8,8 @@ using OtterGui.Classes; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Mods; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.Classes; @@ -52,6 +54,9 @@ public sealed class PredefinedTagManager : ISavable, IReadOnlyList, ISer jObj.WriteTo(jWriter); } + public bool Enabled + => Count > 0; + public void Save() => _saveService.DelaySave(this, TimeSpan.FromSeconds(5)); @@ -98,9 +103,9 @@ public sealed class PredefinedTagManager : ISavable, IReadOnlyList, ISer } public void DrawAddFromSharedTagsAndUpdateTags(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, - Mods.Mod mod) + Mod mod) { - DrawToggleButton(); + DrawToggleButtonTopRight(); if (!DrawList(localTags, modTags, editLocal, out var changedTag, out var index)) return; @@ -110,17 +115,22 @@ public sealed class PredefinedTagManager : ISavable, IReadOnlyList, ISer _modManager.DataEditor.ChangeModTag(mod, index, changedTag); } - private void DrawToggleButton() + public void DrawToggleButton() { - ImGui.SameLine(ImGui.GetContentRegionMax().X - - ImGui.GetFrameHeight() - - (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ItemInnerSpacing.X : 0)); using var color = ImRaii.PushColor(ImGuiCol.Button, ImGui.GetColorU32(ImGuiCol.ButtonActive), _isListOpen); if (ImGuiUtil.DrawDisabledButton(FontAwesomeIcon.Tags.ToIconString(), new Vector2(ImGui.GetFrameHeight()), "Add Predefined Tags...", false, true)) _isListOpen = !_isListOpen; } + private void DrawToggleButtonTopRight() + { + ImGui.SameLine(ImGui.GetContentRegionMax().X + - ImGui.GetFrameHeight() + - (ImGui.GetScrollMaxY() > 0 ? ImGui.GetStyle().ItemInnerSpacing.X : 0)); + DrawToggleButton(); + } + private bool DrawList(IReadOnlyCollection localTags, IReadOnlyCollection modTags, bool editLocal, out string changedTag, out int changedIndex) { @@ -130,7 +140,7 @@ public sealed class PredefinedTagManager : ISavable, IReadOnlyList, ISer if (!_isListOpen) return false; - ImGui.TextUnformatted("Predefined Tags"); + ImUtf8.Text("Predefined Tags"u8); ImGui.Separator(); var ret = false; @@ -155,6 +165,101 @@ public sealed class PredefinedTagManager : ISavable, IReadOnlyList, ISer return ret; } + private readonly List _selectedMods = []; + private readonly List<(int Index, int DataIndex)> _countedMods = []; + + private void PrepareLists(IEnumerable selection) + { + _selectedMods.Clear(); + _selectedMods.AddRange(selection); + _countedMods.EnsureCapacity(_selectedMods.Count); + while (_countedMods.Count < _selectedMods.Count) + _countedMods.Add((-1, -1)); + } + + public void DrawListMulti(IEnumerable selection) + { + if (!_isListOpen) + return; + + ImUtf8.Text("Predefined Tags"u8); + PrepareLists(selection); + + _enabledColor = ColorId.PredefinedTagAdd.Value(); + _disabledColor = ColorId.PredefinedTagRemove.Value(); + using var color = new ImRaii.Color(); + foreach (var (tag, idx) in _predefinedTags.Keys.WithIndex()) + { + var alreadyContained = 0; + var inModData = 0; + var missing = 0; + + foreach (var (modIndex, mod) in _selectedMods.Index()) + { + var tagIdx = mod.LocalTags.IndexOf(tag); + if (tagIdx >= 0) + { + ++alreadyContained; + _countedMods[modIndex] = (tagIdx, -1); + } + else + { + var dataIdx = mod.ModTags.IndexOf(tag); + if (dataIdx >= 0) + { + ++inModData; + _countedMods[modIndex] = (-1, dataIdx); + } + else + { + ++missing; + _countedMods[modIndex] = (-1, -1); + } + } + } + + using var id = ImRaii.PushId(idx); + var buttonWidth = CalcTextButtonWidth(tag); + // Prevent adding a new tag past the right edge of the popup + if (buttonWidth + ImGui.GetStyle().ItemSpacing.X >= ImGui.GetContentRegionAvail().X) + ImGui.NewLine(); + + var (usedColor, disabled, tt) = (missing, alreadyContained) switch + { + (> 0, _) => (_enabledColor, false, + $"Add this tag to {missing} mods.{(inModData > 0 ? $" {inModData} mods contain it in their mod tags and are untouched." : string.Empty)}"), + (_, > 0) => (_disabledColor, false, + $"Remove this tag from {alreadyContained} mods.{(inModData > 0 ? $" {inModData} mods contain it in their mod tags and are untouched." : string.Empty)}"), + _ => (_disabledColor, true, "This tag is already present in the mod tags of all selected mods."), + }; + color.Push(ImGuiCol.Button, usedColor); + if (ImUtf8.ButtonEx(tag, tt, new Vector2(buttonWidth, 0), disabled)) + { + if (missing > 0) + foreach (var (mod, (localIdx, _)) in _selectedMods.Zip(_countedMods)) + { + if (localIdx >= 0) + continue; + + _modManager.DataEditor.ChangeLocalTag(mod, mod.LocalTags.Count, tag); + } + else + foreach (var (mod, (localIdx, _)) in _selectedMods.Zip(_countedMods)) + { + if (localIdx < 0) + continue; + + _modManager.DataEditor.ChangeLocalTag(mod, localIdx, string.Empty); + } + } + ImGui.SameLine(); + + color.Pop(); + } + + ImGui.NewLine(); + } + private bool DrawColoredButton(string buttonLabel, int index, int tagIdx, bool inOther) { using var id = ImRaii.PushId(index); From 23257f94a4ad4db3b25bed01f9774a3e1512b3f1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 18 Aug 2025 15:41:10 +0200 Subject: [PATCH 1304/1381] Some cleanup and add option to disable skin material attribute scanning. --- Penumbra/DebugConfiguration.cs | 3 ++- .../Hooks/Resources/ResolvePathHooksBase.cs | 2 +- .../Processing/SkinMtrlPathEarlyProcessing.cs | 21 +++++++++++-------- .../UI/Tabs/Debug/DebugConfigurationDrawer.cs | 15 ++++++------- 4 files changed, 23 insertions(+), 18 deletions(-) diff --git a/Penumbra/DebugConfiguration.cs b/Penumbra/DebugConfiguration.cs index 76987df8..3f9e8207 100644 --- a/Penumbra/DebugConfiguration.cs +++ b/Penumbra/DebugConfiguration.cs @@ -2,5 +2,6 @@ namespace Penumbra; public class DebugConfiguration { - public static bool WriteImcBytesToLog = false; + public static bool WriteImcBytesToLog = false; + public static bool UseSkinMaterialProcessing = true; } diff --git a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs index eecb98c5..db39889e 100644 --- a/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs +++ b/Penumbra/Interop/Hooks/Resources/ResolvePathHooksBase.cs @@ -162,7 +162,7 @@ public sealed unsafe class ResolvePathHooksBase : IDisposable private nint ResolveSkinMtrl(nint drawObject, nint pathBuffer, nint pathBufferSize, uint slotIndex) { var finalPathBuffer = _resolveSkinMtrlPathHook.Original(drawObject, pathBuffer, pathBufferSize, slotIndex); - if (finalPathBuffer != 0 && finalPathBuffer == pathBuffer) + if (DebugConfiguration.UseSkinMaterialProcessing && finalPathBuffer != nint.Zero && finalPathBuffer == pathBuffer) SkinMtrlPathEarlyProcessing.Process(new Span((void*)pathBuffer, (int)pathBufferSize), (CharacterBase*)drawObject, slotIndex); return ResolvePath(drawObject, finalPathBuffer); diff --git a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs index d35845e1..4487eb7f 100644 --- a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs +++ b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs @@ -7,7 +7,7 @@ public static unsafe class SkinMtrlPathEarlyProcessing { public static void Process(Span path, CharacterBase* character, uint slotIndex) { - var end = path.IndexOf(".mtrl\0"u8); + var end = path.IndexOf(MaterialExtension()); if (end < 0) return; @@ -23,16 +23,22 @@ public static unsafe class SkinMtrlPathEarlyProcessing if (skinSuffix.IsEmpty || skinSuffix.Length > path.Length - suffixPos - 7) return; - skinSuffix.CopyTo(path[(suffixPos + 1)..]); - ".mtrl\0"u8.CopyTo(path[(suffixPos + 1 + skinSuffix.Length)..]); + ++suffixPos; + skinSuffix.CopyTo(path[suffixPos..]); + suffixPos += skinSuffix.Length; + MaterialExtension().CopyTo(path[suffixPos..]); + return; + + static ReadOnlySpan MaterialExtension() + => ".mtrl\0"u8; } private static ModelResourceHandle* GetModelResourceHandle(CharacterBase* character, uint slotIndex) { - if (character == null) + if (character is null) return null; - if (character->TempSlotData != null) + if (character->TempSlotData is not null) { // TODO ClientStructs-ify var handle = *(ModelResourceHandle**)((nint)character->TempSlotData + 0xE0 * slotIndex + 0x8); @@ -41,10 +47,7 @@ public static unsafe class SkinMtrlPathEarlyProcessing } var model = character->Models[slotIndex]; - if (model == null) - return null; - - return model->ModelResourceHandle; + return model is null ? null : model->ModelResourceHandle; } private static ReadOnlySpan GetSkinSuffix(ModelResourceHandle* handle) diff --git a/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs b/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs index 97761091..087670c1 100644 --- a/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/DebugConfigurationDrawer.cs @@ -1,15 +1,16 @@ -using OtterGui.Text; - -namespace Penumbra.UI.Tabs.Debug; - +using OtterGui.Text; + +namespace Penumbra.UI.Tabs.Debug; + public static class DebugConfigurationDrawer { public static void Draw() { - using var id = ImUtf8.CollapsingHeaderId("Debug Logging Options"u8); + using var id = ImUtf8.CollapsingHeaderId("Debugging Options"u8); if (!id) return; - ImUtf8.Checkbox("Log IMC File Replacements"u8, ref DebugConfiguration.WriteImcBytesToLog); + ImUtf8.Checkbox("Log IMC File Replacements"u8, ref DebugConfiguration.WriteImcBytesToLog); + ImUtf8.Checkbox("Scan for Skin Material Attributes"u8, ref DebugConfiguration.UseSkinMaterialProcessing); } -} +} From dad01e1af8c52ab3ddc46851b3f885bd5c3e2cf0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 20 Aug 2025 15:24:00 +0200 Subject: [PATCH 1305/1381] Update GameData. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2cf59c61..15e7c8eb 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2cf59c61494a01fd14aecf925e7dc6325a7374ac +Subproject commit 15e7c8eb41867e6bbd3fe6a8885404df087bc7e7 From b7f326e29c87c31dc1a790a8feb7608a08bacfca Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Aug 2025 15:43:55 +0200 Subject: [PATCH 1306/1381] Fix bug with collection setting and empty collection. --- Penumbra/Collections/CollectionAutoSelector.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Penumbra/Collections/CollectionAutoSelector.cs b/Penumbra/Collections/CollectionAutoSelector.cs index 68dac914..f6e6bf72 100644 --- a/Penumbra/Collections/CollectionAutoSelector.cs +++ b/Penumbra/Collections/CollectionAutoSelector.cs @@ -59,8 +59,15 @@ public sealed class CollectionAutoSelector : IService, IDisposable return; var collection = _resolver.PlayerCollection(); - Penumbra.Log.Debug($"Setting current collection to {collection.Identity.Identifier} through automatic collection selection."); - _collections.SetCollection(collection, CollectionType.Current); + if (collection.Identity.Id == Guid.Empty) + { + Penumbra.Log.Debug($"Not setting current collection because character has no mods assigned."); + } + else + { + Penumbra.Log.Debug($"Setting current collection to {collection.Identity.Identifier} through automatic collection selection."); + _collections.SetCollection(collection, CollectionType.Current); + } } From e3b7f728932da3402f5e479319e459b23d018d74 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Aug 2025 15:44:33 +0200 Subject: [PATCH 1307/1381] Add initial PCP. --- Penumbra.Api | 2 +- Penumbra/Communication/ModPathChanged.cs | 8 +- Penumbra/Configuration.cs | 1 + Penumbra/Import/TexToolsImport.cs | 2 +- Penumbra/Mods/Manager/ModDataEditor.cs | 3 +- Penumbra/Mods/ModCreator.cs | 4 +- Penumbra/Services/PcpService.cs | 259 ++++++++++++++++++ .../UI/AdvancedWindow/ResourceTreeViewer.cs | 56 +++- .../ResourceTreeViewerFactory.cs | 5 +- Penumbra/UI/ModsTab/ModFileSystemSelector.cs | 5 +- Penumbra/UI/Tabs/SettingsTab.cs | 20 +- 11 files changed, 338 insertions(+), 27 deletions(-) create mode 100644 Penumbra/Services/PcpService.cs diff --git a/Penumbra.Api b/Penumbra.Api index c27a0600..2e26d911 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit c27a06004138f2ec80ccdb494bb6ddf6d39d2165 +Subproject commit 2e26d9119249e67f03f415f8ebe1dcb7c28d5cf2 diff --git a/Penumbra/Communication/ModPathChanged.cs b/Penumbra/Communication/ModPathChanged.cs index 1e4f8d36..efe59482 100644 --- a/Penumbra/Communication/ModPathChanged.cs +++ b/Penumbra/Communication/ModPathChanged.cs @@ -3,6 +3,7 @@ using Penumbra.Api; using Penumbra.Api.Api; using Penumbra.Mods; using Penumbra.Mods.Manager; +using Penumbra.Services; namespace Penumbra.Communication; @@ -20,11 +21,14 @@ public sealed class ModPathChanged() { public enum Priority { + /// + PcpService = int.MinValue, + /// - ApiMods = int.MinValue, + ApiMods = int.MinValue + 1, /// - ApiModSettings = int.MinValue, + ApiModSettings = int.MinValue + 1, /// EphemeralConfig = -500, diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 8c50dad7..e8f1d5ef 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -88,6 +88,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool OpenFoldersByDefault { get; set; } = false; public int SingleGroupRadioMax { get; set; } = 2; public string DefaultImportFolder { get; set; } = string.Empty; + public string PcpFolderName { get; set; } = "PCP"; public string QuickMoveFolder1 { get; set; } = string.Empty; public string QuickMoveFolder2 { get; set; } = string.Empty; public string QuickMoveFolder3 { get; set; } = string.Empty; diff --git a/Penumbra/Import/TexToolsImport.cs b/Penumbra/Import/TexToolsImport.cs index fed06573..8e4fea41 100644 --- a/Penumbra/Import/TexToolsImport.cs +++ b/Penumbra/Import/TexToolsImport.cs @@ -119,7 +119,7 @@ public partial class TexToolsImporter : IDisposable // Puts out warnings if extension does not correspond to data. private DirectoryInfo VerifyVersionAndImport(FileInfo modPackFile) { - if (modPackFile.Extension.ToLowerInvariant() is ".pmp" or ".zip" or ".7z" or ".rar") + if (modPackFile.Extension.ToLowerInvariant() is ".pmp" or ".pcp" or ".zip" or ".7z" or ".rar") return HandleRegularArchive(modPackFile); using var zfs = modPackFile.OpenRead(); diff --git a/Penumbra/Mods/Manager/ModDataEditor.cs b/Penumbra/Mods/Manager/ModDataEditor.cs index fc4fdadc..ffa73b76 100644 --- a/Penumbra/Mods/Manager/ModDataEditor.cs +++ b/Penumbra/Mods/Manager/ModDataEditor.cs @@ -36,7 +36,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic /// Create the file containing the meta information about a mod from scratch. public void CreateMeta(DirectoryInfo directory, string? name, string? author, string? description, string? version, - string? website) + string? website, params string[] tags) { var mod = new Mod(directory); mod.Name = name.IsNullOrEmpty() ? mod.Name : new LowerString(name); @@ -44,6 +44,7 @@ public class ModDataEditor(SaveService saveService, CommunicatorService communic mod.Description = description ?? mod.Description; mod.Version = version ?? mod.Version; mod.Website = website ?? mod.Website; + mod.ModTags = tags; saveService.ImmediateSaveSync(new ModMeta(mod)); } diff --git a/Penumbra/Mods/ModCreator.cs b/Penumbra/Mods/ModCreator.cs index 1bb2a073..3a7bd105 100644 --- a/Penumbra/Mods/ModCreator.cs +++ b/Penumbra/Mods/ModCreator.cs @@ -32,12 +32,12 @@ public partial class ModCreator( public readonly Configuration Config = config; /// Creates directory and files necessary for a new mod without adding it to the manager. - public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "", string? author = null) + public DirectoryInfo? CreateEmptyMod(DirectoryInfo basePath, string newName, string description = "", string? author = null, params string[] tags) { try { var newDir = CreateModFolder(basePath, newName, Config.ReplaceNonAsciiOnImport, true); - dataEditor.CreateMeta(newDir, newName, author ?? Config.DefaultModAuthor, description, "1.0", string.Empty); + dataEditor.CreateMeta(newDir, newName, author ?? Config.DefaultModAuthor, description, "1.0", string.Empty, tags); CreateDefaultFiles(newDir); return newDir; } diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs new file mode 100644 index 00000000..461045ba --- /dev/null +++ b/Penumbra/Services/PcpService.cs @@ -0,0 +1,259 @@ +using System.Buffers.Text; +using Dalamud.Game.ClientState.Objects.Types; +using FFXIVClientStructs.FFXIV.Client.Game.Object; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using OtterGui.Classes; +using OtterGui.Services; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.Communication; +using Penumbra.GameData.Actors; +using Penumbra.GameData.Interop; +using Penumbra.GameData.Structs; +using Penumbra.Interop.PathResolving; +using Penumbra.Interop.ResourceTree; +using Penumbra.Meta.Manipulations; +using Penumbra.Mods; +using Penumbra.Mods.Groups; +using Penumbra.Mods.Manager; +using Penumbra.Mods.SubMods; +using Penumbra.String.Classes; + +namespace Penumbra.Services; + +public class PcpService : IApiService, IDisposable +{ + public const string Extension = ".pcp"; + + private readonly Configuration _config; + private readonly SaveService _files; + private readonly ResourceTreeFactory _treeFactory; + private readonly ObjectManager _objectManager; + private readonly ActorManager _actors; + private readonly FrameworkManager _framework; + private readonly CollectionResolver _collectionResolver; + private readonly CollectionManager _collections; + private readonly ModCreator _modCreator; + private readonly ModExportManager _modExport; + private readonly CommunicatorService _communicator; + private readonly SHA1 _sha1 = SHA1.Create(); + private readonly ModFileSystem _fileSystem; + + public PcpService(Configuration config, + SaveService files, + ResourceTreeFactory treeFactory, + ObjectManager objectManager, + ActorManager actors, + FrameworkManager framework, + CollectionManager collections, + CollectionResolver collectionResolver, + ModCreator modCreator, + ModExportManager modExport, + CommunicatorService communicator, + ModFileSystem fileSystem) + { + _config = config; + _files = files; + _treeFactory = treeFactory; + _objectManager = objectManager; + _actors = actors; + _framework = framework; + _collectionResolver = collectionResolver; + _collections = collections; + _modCreator = modCreator; + _modExport = modExport; + _communicator = communicator; + _fileSystem = fileSystem; + + _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.PcpService); + } + + private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) + { + if (type is not ModPathChangeType.Added || newDirectory is null) + return; + + try + { + var file = Path.Combine(newDirectory.FullName, "collection.json"); + if (!File.Exists(file)) + return; + + var text = File.ReadAllText(file); + var jObj = JObject.Parse(text); + var identifier = _actors.FromJson(jObj["Actor"] as JObject); + if (!identifier.IsValid) + return; + + if (jObj["Collection"]?.ToObject() is not { } collectionName) + return; + + var name = $"PCP/{collectionName}"; + if (!_collections.Storage.AddCollection(name, null)) + return; + + var collection = _collections.Storage[^1]; + _collections.Editor.SetModState(collection, mod, true); + + var identifierGroup = _collections.Active.Individuals.GetGroup(identifier); + _collections.Active.SetCollection(collection, CollectionType.Individual, identifierGroup); + if (_fileSystem.TryGetValue(mod, out var leaf)) + { + try + { + var folder = _fileSystem.FindOrCreateAllFolders(_config.PcpFolderName); + _fileSystem.Move(leaf, folder); + } + catch + { + // ignored. + } + } + } + catch (Exception ex) + { + Penumbra.Log.Error($"Error reading the collection.json file from {mod.Identifier}:\n{ex}"); + } + } + + public void Dispose() + => _communicator.ModPathChanged.Unsubscribe(OnModPathChange); + + public async Task<(bool, string)> CreatePcp(ObjectIndex objectIndex, string note = "", CancellationToken cancel = default) + { + try + { + var (identifier, tree, collection) = await _framework.Framework.RunOnFrameworkThread(() => + { + var (actor, identifier) = CheckActor(objectIndex); + cancel.ThrowIfCancellationRequested(); + unsafe + { + var collection = _collectionResolver.IdentifyCollection((GameObject*)actor.Address, true); + if (!collection.Valid || !collection.ModCollection.HasCache) + throw new Exception($"Actor {identifier} has no mods applying, nothing to do."); + + cancel.ThrowIfCancellationRequested(); + if (_treeFactory.FromCharacter(actor, 0) is not { } tree) + throw new Exception($"Unable to fetch modded resources for {identifier}."); + + return (identifier.CreatePermanent(), tree, collection); + } + }); + cancel.ThrowIfCancellationRequested(); + var time = DateTime.Now; + var modDirectory = CreateMod(identifier, note, time); + await CreateDefaultMod(modDirectory, collection.ModCollection, tree, cancel); + await CreateCollectionInfo(modDirectory, identifier, note, time, cancel); + var file = ZipUp(modDirectory); + return (true, file); + } + catch (Exception ex) + { + return (false, ex.Message); + } + } + + private static string ZipUp(DirectoryInfo directory) + { + var fileName = directory.FullName + Extension; + ZipFile.CreateFromDirectory(directory.FullName, fileName, CompressionLevel.Optimal, false); + directory.Delete(true); + return fileName; + } + + private static async Task CreateCollectionInfo(DirectoryInfo directory, ActorIdentifier actor, string note, DateTime time, + CancellationToken cancel = default) + { + var jObj = new JObject + { + ["Version"] = 1, + ["Actor"] = actor.ToJson(), + ["Collection"] = note.Length > 0 ? $"{actor.ToName()}: {note}" : actor.ToName(), + ["Time"] = time, + ["Note"] = note, + }; + if (note.Length > 0) + cancel.ThrowIfCancellationRequested(); + var filePath = Path.Combine(directory.FullName, "collection.json"); + await using var file = File.Open(filePath, File.Exists(filePath) ? FileMode.Truncate : FileMode.CreateNew); + await using var stream = new StreamWriter(file); + await using var json = new JsonTextWriter(stream); + json.Formatting = Formatting.Indented; + await jObj.WriteToAsync(json, cancel); + } + + private DirectoryInfo CreateMod(ActorIdentifier actor, string note, DateTime time) + { + var directory = _modExport.ExportDirectory; + directory.Create(); + var actorName = actor.ToName(); + var authorName = _actors.GetCurrentPlayer().ToName(); + var suffix = note.Length > 0 + ? note + : time.ToString("yyyy-MM-ddTHH\\:mm", CultureInfo.InvariantCulture); + var modName = $"{actorName} - {suffix}"; + var description = $"On-Screen Data for {actorName} as snapshotted on {time}."; + return _modCreator.CreateEmptyMod(directory, modName, description, authorName, "PCP") + ?? throw new Exception($"Unable to create mod {modName} in {directory.FullName}."); + } + + private async Task CreateDefaultMod(DirectoryInfo modDirectory, ModCollection collection, ResourceTree tree, + CancellationToken cancel = default) + { + var subDirectory = modDirectory.CreateSubdirectory("files"); + var subMod = new DefaultSubMod(null!); + foreach (var node in tree.FlatNodes) + { + cancel.ThrowIfCancellationRequested(); + var gamePath = node.GamePath; + var fullPath = node.FullPath; + if (fullPath.IsRooted) + { + var hash = await _sha1.ComputeHashAsync(File.OpenRead(fullPath.FullName), cancel).ConfigureAwait(false); + cancel.ThrowIfCancellationRequested(); + var name = Convert.ToHexString(hash) + fullPath.Extension; + var newFile = Path.Combine(subDirectory.FullName, name); + if (!File.Exists(newFile)) + File.Copy(fullPath.FullName, newFile); + subMod.Files.TryAdd(gamePath, new FullPath(newFile)); + } + else if (gamePath.Path != fullPath.InternalName) + { + subMod.FileSwaps.TryAdd(gamePath, fullPath); + } + } + + cancel.ThrowIfCancellationRequested(); + subMod.Manipulations = new MetaDictionary(collection.MetaCache); + + var saveGroup = new ModSaveGroup(modDirectory, subMod, _config.ReplaceNonAsciiOnImport); + var filePath = _files.FileNames.OptionGroupFile(modDirectory.FullName, -1, string.Empty, _config.ReplaceNonAsciiOnImport); + cancel.ThrowIfCancellationRequested(); + await using var fileStream = File.Open(filePath, File.Exists(filePath) ? FileMode.Truncate : FileMode.CreateNew); + await using var writer = new StreamWriter(fileStream); + saveGroup.Save(writer); + } + + private (ICharacter Actor, ActorIdentifier Identifier) CheckActor(ObjectIndex objectIndex) + { + var actor = _objectManager[objectIndex]; + if (!actor.Valid) + throw new Exception($"No Actor at index {objectIndex} found."); + + if (!actor.Identifier(_actors, out var identifier)) + throw new Exception($"Could not create valid identifier for actor at index {objectIndex}."); + + if (!actor.IsCharacter) + throw new Exception($"Actor {identifier} at index {objectIndex} is not a valid character."); + + if (!actor.Model.Valid) + throw new Exception($"Actor {identifier} at index {objectIndex} has no model."); + + if (_objectManager.Objects.CreateObjectReference(actor.Address) is not ICharacter character) + throw new Exception($"Actor {identifier} at index {objectIndex} could not be converted to ICharacter"); + + return (character, identifier); + } +} diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 440baa2f..a2309343 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -1,15 +1,19 @@ -using Dalamud.Interface; -using Dalamud.Interface.Utility; using Dalamud.Bindings.ImGui; -using OtterGui.Raii; +using Dalamud.Interface; +using Dalamud.Interface.ImGuiNotification; +using Dalamud.Interface.Utility; using OtterGui; +using OtterGui.Classes; +using OtterGui.Extensions; +using OtterGui.Raii; using OtterGui.Text; using Penumbra.Api.Enums; +using Penumbra.GameData.Structs; using Penumbra.Interop.ResourceTree; using Penumbra.Services; -using Penumbra.UI.Classes; using Penumbra.String; -using OtterGui.Extensions; +using Penumbra.UI.Classes; +using static System.Net.Mime.MediaTypeNames; namespace Penumbra.UI.AdvancedWindow; @@ -21,12 +25,13 @@ public class ResourceTreeViewer( int actionCapacity, Action onRefresh, Action drawActions, - CommunicatorService communicator) + CommunicatorService communicator, + PcpService pcpService) { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; - private readonly HashSet _unfolded = []; + private readonly HashSet _unfolded = []; private readonly Dictionary _filterCache = []; @@ -34,6 +39,7 @@ public class ResourceTreeViewer( private ChangedItemIconFlag _typeFilter = ChangedItemFlagExtensions.AllFlags; private string _nameFilter = string.Empty; private string _nodeFilter = string.Empty; + private string _note = string.Empty; private Task? _task; @@ -83,7 +89,28 @@ public class ResourceTreeViewer( using var id = ImRaii.PushId(index); - ImGui.TextUnformatted($"Collection: {(incognito.IncognitoMode ? tree.AnonymizedCollectionName : tree.CollectionName)}"); + ImUtf8.TextFrameAligned($"Collection: {(incognito.IncognitoMode ? tree.AnonymizedCollectionName : tree.CollectionName)}"); + ImGui.SameLine(); + if (ImUtf8.ButtonEx("Export Character Pack"u8, + "Note that this recomputes the current data of the actor if it still exists, and does not use the cached data."u8)) + { + pcpService.CreatePcp((ObjectIndex)tree.GameObjectIndex, _note).ContinueWith(t => + { + + var (success, text) = t.Result; + + if (success) + Penumbra.Messager.NotificationMessage($"Created {text}.", NotificationType.Success, false); + else + Penumbra.Messager.NotificationMessage(text, NotificationType.Error, false); + }); + _note = string.Empty; + } + + ImUtf8.SameLineInner(); + ImGui.SetNextItemWidth(ImGui.GetContentRegionAvail().X); + ImUtf8.InputText("##note"u8, ref _note, "Export note..."u8); + using var table = ImRaii.Table("##ResourceTree", actionCapacity > 0 ? 4 : 3, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); @@ -263,7 +290,8 @@ public class ResourceTreeViewer( using var group = ImUtf8.Group(); using (var color = ImRaii.PushColor(ImGuiCol.Text, (hasMod ? ColorId.NewMod : ColorId.DisabledMod).Value())) { - ImUtf8.Selectable(modName, false, ImGuiSelectableFlags.AllowItemOverlap, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + ImUtf8.Selectable(modName, false, ImGuiSelectableFlags.AllowItemOverlap, + new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); } ImGui.SameLine(); @@ -272,7 +300,8 @@ public class ResourceTreeViewer( } else { - ImGui.Selectable(resourceNode.FullPath.ToPath(), false, ImGuiSelectableFlags.AllowItemOverlap, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + ImGui.Selectable(resourceNode.FullPath.ToPath(), false, ImGuiSelectableFlags.AllowItemOverlap, + new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); } if (ImGui.IsItemClicked()) @@ -365,9 +394,10 @@ public class ResourceTreeViewer( private static string GetPathStatusDescription(ResourceNode.PathStatus status) => status switch { - ResourceNode.PathStatus.External => "The actual path to this file is unavailable, because it is managed by external tools.", - ResourceNode.PathStatus.NonExistent => "The actual path to this file is unavailable, because it seems to have been moved or deleted since it was loaded.", - _ => "The actual path to this file is unavailable.", + ResourceNode.PathStatus.External => "The actual path to this file is unavailable, because it is managed by external tools.", + ResourceNode.PathStatus.NonExistent => + "The actual path to this file is unavailable, because it seems to have been moved or deleted since it was loaded.", + _ => "The actual path to this file is unavailable.", }; [Flags] diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs index 10a4aea2..ac06fe1a 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs @@ -9,8 +9,9 @@ public class ResourceTreeViewerFactory( ResourceTreeFactory treeFactory, ChangedItemDrawer changedItemDrawer, IncognitoService incognito, - CommunicatorService communicator) : IService + CommunicatorService communicator, + PcpService pcpService) : IService { public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) - => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator); + => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator, pcpService); } diff --git a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs index 16ff7b41..3f3c82aa 100644 --- a/Penumbra/UI/ModsTab/ModFileSystemSelector.cs +++ b/Penumbra/UI/ModsTab/ModFileSystemSelector.cs @@ -126,6 +126,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector + "Mod Packs{.ttmp,.ttmp2,.pmp,.pcp},TexTools Mod Packs{.ttmp,.ttmp2},Penumbra Mod Packs{.pmp,.pcp},Archives{.zip,.7z,.rar},Penumbra Character Packs{.pcp}", (s, f) => { if (!s) return; @@ -445,7 +446,7 @@ public sealed class ModFileSystemSelector : FileSystemSelector Draw input for the default folder to sort put newly imported mods into. + private void DrawPcpFolder() + { + var tmp = _config.PcpFolderName; + ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X); + if (ImUtf8.InputText("##pcpFolder"u8, ref tmp)) + _config.PcpFolderName = tmp; + + if (ImGui.IsItemDeactivatedAfterEdit()) + _config.Save(); + + ImGuiUtil.LabeledHelpMarker("Default PCP Organizational Folder", + "The folder any penumbra character packs are moved to on import.\nLeave blank to import into Root."); + } + /// Draw all settings pertaining to advanced editing of mods. private void DrawModEditorSettings() @@ -1055,7 +1069,7 @@ public class SettingsTab : ITab, IUiService if (ImGui.Button("Show Changelogs", new Vector2(width, 0))) _penumbra.ForceChangelogOpen(); - ImGui.SetCursorPos(new Vector2(xPos, 5 * ImGui.GetFrameHeightWithSpacing())); + ImGui.SetCursorPos(new Vector2(xPos, 5 * ImGui.GetFrameHeightWithSpacing())); CustomGui.DrawKofiPatreonButton(Penumbra.Messager, new Vector2(width, 0)); } From 8043e6fb6be5751deb5a33657638a73542728c35 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Aug 2025 15:49:15 +0200 Subject: [PATCH 1308/1381] Add option to disable PCP. --- Penumbra/Configuration.cs | 1 + Penumbra/Services/PcpService.cs | 2 +- Penumbra/UI/Tabs/SettingsTab.cs | 3 +++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index e8f1d5ef..b9a0d9ce 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -68,6 +68,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HideMachinistOffhandFromChangedItems { get; set; } = true; public bool DefaultTemporaryMode { get; set; } = false; public bool EnableCustomShapes { get; set; } = true; + public bool DisablePcpHandling { get; set; } = false; public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; public ChangedItemMode ChangedItemDisplay { get; set; } = ChangedItemMode.GroupedCollapsed; public int OptionGroupCollapsibleMin { get; set; } = 5; diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index 461045ba..5f4a844d 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -71,7 +71,7 @@ public class PcpService : IApiService, IDisposable private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) { - if (type is not ModPathChangeType.Added || newDirectory is null) + if (type is not ModPathChangeType.Added || _config.DisablePcpHandling || newDirectory is null) return; try diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 4bed1ef2..143709f4 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -598,6 +598,9 @@ public class SettingsTab : ITab, IUiService Checkbox("Always Open Import at Default Directory", "Open the import window at the location specified here every time, forgetting your previous path.", _config.AlwaysOpenDefaultImport, v => _config.AlwaysOpenDefaultImport = v); + Checkbox("Handle PCP Files", + "When encountering specific mods, usually but not necessarily denoted by a .pcp file ending, Penumbra will automatically try to create an associated collection and assign it to a specific character for this mod package. This can turn this behaviour off if unwanted.", + !_config.DisablePcpHandling, v => _config.DisablePcpHandling = !v); DrawDefaultModImportPath(); DrawDefaultModAuthor(); DrawDefaultModImportFolder(); From fb34238530f08918fdc18c63e553ca134f4f8fee Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Aug 2025 13:51:50 +0000 Subject: [PATCH 1309/1381] [CI] Updating repo.json for testing_1.5.0.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index a452dc94..cf4fe6cb 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.0.6", - "TestingAssemblyVersion": "1.5.0.6", + "TestingAssemblyVersion": "1.5.0.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 10894d451a525e504422c4b16a3d3022601e8dfe Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Aug 2025 18:08:22 +0200 Subject: [PATCH 1310/1381] Add Pcp Events. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ModsApi.cs | 25 +++++++++++++++++------- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/IpcProviders.cs | 2 ++ Penumbra/Communication/PcpCreation.cs | 20 +++++++++++++++++++ Penumbra/Communication/PcpParsing.cs | 21 ++++++++++++++++++++ Penumbra/Configuration.cs | 1 + Penumbra/Services/CommunicatorService.cs | 8 ++++++++ Penumbra/Services/PcpService.cs | 24 ++++++++++++++++------- 9 files changed, 89 insertions(+), 16 deletions(-) create mode 100644 Penumbra/Communication/PcpCreation.cs create mode 100644 Penumbra/Communication/PcpParsing.cs diff --git a/Penumbra.Api b/Penumbra.Api index 2e26d911..0a970295 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 2e26d9119249e67f03f415f8ebe1dcb7c28d5cf2 +Subproject commit 0a970295b2398683b1e49c46fd613541e2486210 diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 78c62953..55f1e259 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -1,3 +1,4 @@ +using Newtonsoft.Json.Linq; using OtterGui.Compression; using OtterGui.Services; using Penumbra.Api.Enums; @@ -33,12 +34,8 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable { switch (type) { - case ModPathChangeType.Deleted when oldDirectory != null: - ModDeleted?.Invoke(oldDirectory.Name); - break; - case ModPathChangeType.Added when newDirectory != null: - ModAdded?.Invoke(newDirectory.Name); - break; + case ModPathChangeType.Deleted when oldDirectory != null: ModDeleted?.Invoke(oldDirectory.Name); break; + case ModPathChangeType.Added when newDirectory != null: ModAdded?.Invoke(newDirectory.Name); break; case ModPathChangeType.Moved when newDirectory != null && oldDirectory != null: ModMoved?.Invoke(oldDirectory.Name, newDirectory.Name); break; @@ -46,7 +43,9 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable } public void Dispose() - => _communicator.ModPathChanged.Unsubscribe(OnModPathChanged); + { + _communicator.ModPathChanged.Unsubscribe(OnModPathChanged); + } public Dictionary GetModList() => _modManager.ToDictionary(m => m.ModPath.Name, m => m.Name.Text); @@ -109,6 +108,18 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable public event Action? ModAdded; public event Action? ModMoved; + public event Action? CreatingPcp + { + add => _communicator.PcpCreation.Subscribe(value!, PcpCreation.Priority.ModsApi); + remove => _communicator.PcpCreation.Unsubscribe(value!); + } + + public event Action? ParsingPcp + { + add => _communicator.PcpParsing.Subscribe(value!, PcpParsing.Priority.ModsApi); + remove => _communicator.PcpParsing.Unsubscribe(value!); + } + public (PenumbraApiEc, string, bool, bool) GetModPath(string modDirectory, string modName) { if (!_modManager.TryGetMod(modDirectory, modName, out var mod) diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 7ca41324..9e7eb964 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -17,7 +17,7 @@ public class PenumbraApi( UiApi ui) : IDisposable, IApiService, IPenumbraApi { public const int BreakingVersion = 5; - public const int FeatureVersion = 10; + public const int FeatureVersion = 11; public void Dispose() { diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 7dcee375..0c80626f 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -54,6 +54,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ModDeleted.Provider(pi, api.Mods), IpcSubscribers.ModAdded.Provider(pi, api.Mods), IpcSubscribers.ModMoved.Provider(pi, api.Mods), + IpcSubscribers.CreatingPcp.Provider(pi, api.Mods), + IpcSubscribers.ParsingPcp.Provider(pi, api.Mods), IpcSubscribers.GetModPath.Provider(pi, api.Mods), IpcSubscribers.SetModPath.Provider(pi, api.Mods), IpcSubscribers.GetChangedItems.Provider(pi, api.Mods), diff --git a/Penumbra/Communication/PcpCreation.cs b/Penumbra/Communication/PcpCreation.cs new file mode 100644 index 00000000..cb11b3c3 --- /dev/null +++ b/Penumbra/Communication/PcpCreation.cs @@ -0,0 +1,20 @@ +using Newtonsoft.Json.Linq; +using OtterGui.Classes; + +namespace Penumbra.Communication; + +/// +/// Triggered when the character.json file for a .pcp file is written. +/// +/// Parameter is the JObject that gets written to file. +/// Parameter is the object index of the game object this is written for. +/// +/// +public sealed class PcpCreation() : EventWrapper(nameof(PcpCreation)) +{ + public enum Priority + { + /// + ModsApi = int.MinValue, + } +} diff --git a/Penumbra/Communication/PcpParsing.cs b/Penumbra/Communication/PcpParsing.cs new file mode 100644 index 00000000..95b78951 --- /dev/null +++ b/Penumbra/Communication/PcpParsing.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json.Linq; +using OtterGui.Classes; + +namespace Penumbra.Communication; + +/// +/// Triggered when the character.json file for a .pcp file is parsed and applied. +/// +/// Parameter is parsed JObject that contains the data. +/// Parameter is the identifier of the created mod. +/// Parameter is the GUID of the created collection. +/// +/// +public sealed class PcpParsing() : EventWrapper(nameof(PcpParsing)) +{ + public enum Priority + { + /// + ModsApi = int.MinValue, + } +} diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index b9a0d9ce..d9a9f5fe 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -69,6 +69,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool DefaultTemporaryMode { get; set; } = false; public bool EnableCustomShapes { get; set; } = true; public bool DisablePcpHandling { get; set; } = false; + public bool AllowPcpIpc { get; set; } = true; public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; public ChangedItemMode ChangedItemDisplay { get; set; } = ChangedItemMode.GroupedCollapsed; public int OptionGroupCollapsibleMin { get; set; } = 5; diff --git a/Penumbra/Services/CommunicatorService.cs b/Penumbra/Services/CommunicatorService.cs index 5d745419..35f15e9e 100644 --- a/Penumbra/Services/CommunicatorService.cs +++ b/Penumbra/Services/CommunicatorService.cs @@ -81,6 +81,12 @@ public class CommunicatorService : IDisposable, IService /// public readonly ResolvedFileChanged ResolvedFileChanged = new(); + /// + public readonly PcpCreation PcpCreation = new(); + + /// + public readonly PcpParsing PcpParsing = new(); + public void Dispose() { CollectionChange.Dispose(); @@ -105,5 +111,7 @@ public class CommunicatorService : IDisposable, IService ChangedItemClick.Dispose(); SelectTab.Dispose(); ResolvedFileChanged.Dispose(); + PcpCreation.Dispose(); + PcpParsing.Dispose(); } } diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index 5f4a844d..32eca652 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -1,4 +1,3 @@ -using System.Buffers.Text; using Dalamud.Game.ClientState.Objects.Types; using FFXIVClientStructs.FFXIV.Client.Game.Object; using Newtonsoft.Json; @@ -76,9 +75,16 @@ public class PcpService : IApiService, IDisposable try { - var file = Path.Combine(newDirectory.FullName, "collection.json"); + var file = Path.Combine(newDirectory.FullName, "character.json"); if (!File.Exists(file)) - return; + { + // First version had collection.json, changed. + var oldFile = Path.Combine(newDirectory.FullName, "collection.json"); + if (File.Exists(oldFile)) + File.Move(oldFile, file, true); + else + return; + } var text = File.ReadAllText(file); var jObj = JObject.Parse(text); @@ -110,10 +116,12 @@ public class PcpService : IApiService, IDisposable // ignored. } } + if (_config.AllowPcpIpc) + _communicator.PcpParsing.Invoke(jObj, mod.Identifier, collection.Identity.Id); } catch (Exception ex) { - Penumbra.Log.Error($"Error reading the collection.json file from {mod.Identifier}:\n{ex}"); + Penumbra.Log.Error($"Error reading the character.json file from {mod.Identifier}:\n{ex}"); } } @@ -145,7 +153,7 @@ public class PcpService : IApiService, IDisposable var time = DateTime.Now; var modDirectory = CreateMod(identifier, note, time); await CreateDefaultMod(modDirectory, collection.ModCollection, tree, cancel); - await CreateCollectionInfo(modDirectory, identifier, note, time, cancel); + await CreateCollectionInfo(modDirectory, objectIndex, identifier, note, time, cancel); var file = ZipUp(modDirectory); return (true, file); } @@ -163,7 +171,7 @@ public class PcpService : IApiService, IDisposable return fileName; } - private static async Task CreateCollectionInfo(DirectoryInfo directory, ActorIdentifier actor, string note, DateTime time, + private async Task CreateCollectionInfo(DirectoryInfo directory, ObjectIndex index, ActorIdentifier actor, string note, DateTime time, CancellationToken cancel = default) { var jObj = new JObject @@ -176,7 +184,9 @@ public class PcpService : IApiService, IDisposable }; if (note.Length > 0) cancel.ThrowIfCancellationRequested(); - var filePath = Path.Combine(directory.FullName, "collection.json"); + if (_config.AllowPcpIpc) + await _framework.Framework.RunOnFrameworkThread(() => _communicator.PcpCreation.Invoke(jObj, index.Index)); + var filePath = Path.Combine(directory.FullName, "character.json"); await using var file = File.Open(filePath, File.Exists(filePath) ? FileMode.Truncate : FileMode.CreateNew); await using var stream = new StreamWriter(file); await using var json = new JsonTextWriter(stream); From 0d643840592bac17b67a09dc66f971fed8dc35a1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 22 Aug 2025 20:31:40 +0200 Subject: [PATCH 1311/1381] Add cleanup buttons to PCP, add option to turn off PCP IPC. --- Penumbra/Services/PcpService.cs | 26 +++++++++++++++++++++++++- Penumbra/UI/Tabs/SettingsTab.cs | 21 ++++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index 32eca652..73c61cdb 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -38,6 +38,7 @@ public class PcpService : IApiService, IDisposable private readonly CommunicatorService _communicator; private readonly SHA1 _sha1 = SHA1.Create(); private readonly ModFileSystem _fileSystem; + private readonly ModManager _mods; public PcpService(Configuration config, SaveService files, @@ -50,7 +51,8 @@ public class PcpService : IApiService, IDisposable ModCreator modCreator, ModExportManager modExport, CommunicatorService communicator, - ModFileSystem fileSystem) + ModFileSystem fileSystem, + ModManager mods) { _config = config; _files = files; @@ -64,10 +66,27 @@ public class PcpService : IApiService, IDisposable _modExport = modExport; _communicator = communicator; _fileSystem = fileSystem; + _mods = mods; _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.PcpService); } + public void CleanPcpMods() + { + var mods = _mods.Where(m => m.ModTags.Contains("PCP")).ToList(); + Penumbra.Log.Information($"[PCPService] Deleting {mods.Count} mods containing the tag PCP."); + foreach (var mod in mods) + _mods.DeleteMod(mod); + } + + public void CleanPcpCollections() + { + var collections = _collections.Storage.Where(c => c.Identity.Name.StartsWith("PCP/")).ToList(); + Penumbra.Log.Information($"[PCPService] Deleting {collections.Count} mods containing the tag PCP."); + foreach (var collection in collections) + _collections.Storage.Delete(collection); + } + private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) { if (type is not ModPathChangeType.Added || _config.DisablePcpHandling || newDirectory is null) @@ -80,12 +99,14 @@ public class PcpService : IApiService, IDisposable { // First version had collection.json, changed. var oldFile = Path.Combine(newDirectory.FullName, "collection.json"); + Penumbra.Log.Information("[PCPService] Renaming old PCP file from collection.json to character.json."); if (File.Exists(oldFile)) File.Move(oldFile, file, true); else return; } + Penumbra.Log.Information($"[PCPService] Found a PCP file for {mod.Name}, applying."); var text = File.ReadAllText(file); var jObj = JObject.Parse(text); var identifier = _actors.FromJson(jObj["Actor"] as JObject); @@ -116,6 +137,7 @@ public class PcpService : IApiService, IDisposable // ignored. } } + if (_config.AllowPcpIpc) _communicator.PcpParsing.Invoke(jObj, mod.Identifier, collection.Identity.Id); } @@ -132,6 +154,7 @@ public class PcpService : IApiService, IDisposable { try { + Penumbra.Log.Information($"[PCPService] Creating PCP file for game object {objectIndex.Index}."); var (identifier, tree, collection) = await _framework.Framework.RunOnFrameworkThread(() => { var (actor, identifier) = CheckActor(objectIndex); @@ -178,6 +201,7 @@ public class PcpService : IApiService, IDisposable { ["Version"] = 1, ["Actor"] = actor.ToJson(), + ["Mod"] = directory.Name, ["Collection"] = note.Length > 0 ? $"{actor.ToName()}: {note}" : actor.ToName(), ["Time"] = time, ["Note"] = note, diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 143709f4..a6d03593 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -52,6 +52,7 @@ public class SettingsTab : ITab, IUiService private readonly CollectionAutoSelector _autoSelector; private readonly CleanupService _cleanupService; private readonly AttributeHook _attributeHook; + private readonly PcpService _pcpService; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -64,7 +65,7 @@ public class SettingsTab : ITab, IUiService DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, - AttributeHook attributeHook) + AttributeHook attributeHook, PcpService pcpService) { _pluginInterface = pluginInterface; _config = config; @@ -90,6 +91,7 @@ public class SettingsTab : ITab, IUiService _autoSelector = autoSelector; _cleanupService = cleanupService; _attributeHook = attributeHook; + _pcpService = pcpService; } public void DrawHeader() @@ -601,6 +603,23 @@ public class SettingsTab : ITab, IUiService Checkbox("Handle PCP Files", "When encountering specific mods, usually but not necessarily denoted by a .pcp file ending, Penumbra will automatically try to create an associated collection and assign it to a specific character for this mod package. This can turn this behaviour off if unwanted.", !_config.DisablePcpHandling, v => _config.DisablePcpHandling = !v); + + var active = _config.DeleteModModifier.IsActive(); + ImGui.SameLine(); + if (ImUtf8.ButtonEx("Delete all PCP Mods"u8, "Deletes all mods tagged with 'PCP' from the mod list."u8, disabled: !active)) + _pcpService.CleanPcpMods(); + if (!active) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking."); + + ImGui.SameLine(); + if (ImUtf8.ButtonEx("Delete all PCP Collections"u8, "Deletes all collections whose name starts with 'PCP/' from the collection list."u8, disabled: !active)) + _pcpService.CleanPcpCollections(); + if (!active) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking."); + + Checkbox("Allow Other Plugins Access to PCP Handling", + "When creating or importing PCP files, other plugins can add and interpret their own data to the character.json file.", + _config.AllowPcpIpc, v => _config.AllowPcpIpc = v); DrawDefaultModImportPath(); DrawDefaultModAuthor(); DrawDefaultModImportFolder(); From d302a17f1f2ca2f792acc8f28cf4722f3ded9be6 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 22 Aug 2025 18:33:43 +0000 Subject: [PATCH 1312/1381] [CI] Updating repo.json for testing_1.5.0.8 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index cf4fe6cb..48d5b97f 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.0.6", - "TestingAssemblyVersion": "1.5.0.7", + "TestingAssemblyVersion": "1.5.0.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.7/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.8/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 6079103505c3b0b99c26e041f59c26c41b13a543 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 23 Aug 2025 14:46:19 +0200 Subject: [PATCH 1313/1381] Add collection PCP settings. --- Penumbra.Api | 2 +- Penumbra/Api/Api/ModsApi.cs | 2 +- Penumbra/Communication/PcpCreation.cs | 3 +- Penumbra/Configuration.cs | 19 ++++++---- Penumbra/Services/PcpService.cs | 51 ++++++++++++++++----------- Penumbra/UI/Tabs/SettingsTab.cs | 19 +++++++--- 6 files changed, 61 insertions(+), 35 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 0a970295..297941bc 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 0a970295b2398683b1e49c46fd613541e2486210 +Subproject commit 297941bc22300f4a8368f4d0177f62943eb69727 diff --git a/Penumbra/Api/Api/ModsApi.cs b/Penumbra/Api/Api/ModsApi.cs index 55f1e259..1f4f1cf4 100644 --- a/Penumbra/Api/Api/ModsApi.cs +++ b/Penumbra/Api/Api/ModsApi.cs @@ -108,7 +108,7 @@ public class ModsApi : IPenumbraApiMods, IApiService, IDisposable public event Action? ModAdded; public event Action? ModMoved; - public event Action? CreatingPcp + public event Action? CreatingPcp { add => _communicator.PcpCreation.Subscribe(value!, PcpCreation.Priority.ModsApi); remove => _communicator.PcpCreation.Unsubscribe(value!); diff --git a/Penumbra/Communication/PcpCreation.cs b/Penumbra/Communication/PcpCreation.cs index cb11b3c3..ca0cfcf6 100644 --- a/Penumbra/Communication/PcpCreation.cs +++ b/Penumbra/Communication/PcpCreation.cs @@ -8,9 +8,10 @@ namespace Penumbra.Communication; /// /// Parameter is the JObject that gets written to file. /// Parameter is the object index of the game object this is written for. +/// Parameter is the full path to the directory being set up for the PCP creation. /// /// -public sealed class PcpCreation() : EventWrapper(nameof(PcpCreation)) +public sealed class PcpCreation() : EventWrapper(nameof(PcpCreation)) { public enum Priority { diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index d9a9f5fe..f9cad217 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -18,6 +18,15 @@ using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Penumbra; +public record PcpSettings +{ + public bool CreateCollection { get; set; } = true; + public bool AssignCollection { get; set; } = true; + public bool AllowIpc { get; set; } = true; + public bool DisableHandling { get; set; } = false; + public string FolderName { get; set; } = "PCP"; +} + [Serializable] public class Configuration : IPluginConfiguration, ISavable, IService { @@ -68,11 +77,10 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HideMachinistOffhandFromChangedItems { get; set; } = true; public bool DefaultTemporaryMode { get; set; } = false; public bool EnableCustomShapes { get; set; } = true; - public bool DisablePcpHandling { get; set; } = false; - public bool AllowPcpIpc { get; set; } = true; - public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; - public ChangedItemMode ChangedItemDisplay { get; set; } = ChangedItemMode.GroupedCollapsed; - public int OptionGroupCollapsibleMin { get; set; } = 5; + public PcpSettings PcpSettings = new(); + public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; + public ChangedItemMode ChangedItemDisplay { get; set; } = ChangedItemMode.GroupedCollapsed; + public int OptionGroupCollapsibleMin { get; set; } = 5; public Vector2 MinimumSize = new(Constants.MinimumSizeX, Constants.MinimumSizeY); @@ -90,7 +98,6 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool OpenFoldersByDefault { get; set; } = false; public int SingleGroupRadioMax { get; set; } = 2; public string DefaultImportFolder { get; set; } = string.Empty; - public string PcpFolderName { get; set; } = "PCP"; public string QuickMoveFolder1 { get; set; } = string.Empty; public string QuickMoveFolder2 { get; set; } = string.Empty; public string QuickMoveFolder3 { get; set; } = string.Empty; diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index 73c61cdb..b9d472aa 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -89,7 +89,7 @@ public class PcpService : IApiService, IDisposable private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) { - if (type is not ModPathChangeType.Added || _config.DisablePcpHandling || newDirectory is null) + if (type is not ModPathChangeType.Added || _config.PcpSettings.DisableHandling || newDirectory is null) return; try @@ -107,29 +107,37 @@ public class PcpService : IApiService, IDisposable } Penumbra.Log.Information($"[PCPService] Found a PCP file for {mod.Name}, applying."); - var text = File.ReadAllText(file); - var jObj = JObject.Parse(text); - var identifier = _actors.FromJson(jObj["Actor"] as JObject); - if (!identifier.IsValid) - return; + var text = File.ReadAllText(file); + var jObj = JObject.Parse(text); + var collection = ModCollection.Empty; + // Create collection. + if (_config.PcpSettings.CreateCollection) + { + var identifier = _actors.FromJson(jObj["Actor"] as JObject); + if (identifier.IsValid && jObj["Collection"]?.ToObject() is { } collectionName) + { + var name = $"PCP/{collectionName}"; + if (_collections.Storage.AddCollection(name, null)) + { + collection = _collections.Storage[^1]; + _collections.Editor.SetModState(collection, mod, true); - if (jObj["Collection"]?.ToObject() is not { } collectionName) - return; + // Assign collection. + if (_config.PcpSettings.AssignCollection) + { + var identifierGroup = _collections.Active.Individuals.GetGroup(identifier); + _collections.Active.SetCollection(collection, CollectionType.Individual, identifierGroup); + } + } + } + } - var name = $"PCP/{collectionName}"; - if (!_collections.Storage.AddCollection(name, null)) - return; - - var collection = _collections.Storage[^1]; - _collections.Editor.SetModState(collection, mod, true); - - var identifierGroup = _collections.Active.Individuals.GetGroup(identifier); - _collections.Active.SetCollection(collection, CollectionType.Individual, identifierGroup); + // Move to folder. if (_fileSystem.TryGetValue(mod, out var leaf)) { try { - var folder = _fileSystem.FindOrCreateAllFolders(_config.PcpFolderName); + var folder = _fileSystem.FindOrCreateAllFolders(_config.PcpSettings.FolderName); _fileSystem.Move(leaf, folder); } catch @@ -138,7 +146,8 @@ public class PcpService : IApiService, IDisposable } } - if (_config.AllowPcpIpc) + // Invoke IPC. + if (_config.PcpSettings.AllowIpc) _communicator.PcpParsing.Invoke(jObj, mod.Identifier, collection.Identity.Id); } catch (Exception ex) @@ -208,8 +217,8 @@ public class PcpService : IApiService, IDisposable }; if (note.Length > 0) cancel.ThrowIfCancellationRequested(); - if (_config.AllowPcpIpc) - await _framework.Framework.RunOnFrameworkThread(() => _communicator.PcpCreation.Invoke(jObj, index.Index)); + if (_config.PcpSettings.AllowIpc) + await _framework.Framework.RunOnFrameworkThread(() => _communicator.PcpCreation.Invoke(jObj, index.Index, directory.FullName)); var filePath = Path.Combine(directory.FullName, "character.json"); await using var file = File.Open(filePath, File.Exists(filePath) ? FileMode.Truncate : FileMode.CreateNew); await using var stream = new StreamWriter(file); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index a6d03593..ded56bb1 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -602,7 +602,7 @@ public class SettingsTab : ITab, IUiService _config.AlwaysOpenDefaultImport, v => _config.AlwaysOpenDefaultImport = v); Checkbox("Handle PCP Files", "When encountering specific mods, usually but not necessarily denoted by a .pcp file ending, Penumbra will automatically try to create an associated collection and assign it to a specific character for this mod package. This can turn this behaviour off if unwanted.", - !_config.DisablePcpHandling, v => _config.DisablePcpHandling = !v); + !_config.PcpSettings.DisableHandling, v => _config.PcpSettings.DisableHandling = !v); var active = _config.DeleteModModifier.IsActive(); ImGui.SameLine(); @@ -612,14 +612,23 @@ public class SettingsTab : ITab, IUiService ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking."); ImGui.SameLine(); - if (ImUtf8.ButtonEx("Delete all PCP Collections"u8, "Deletes all collections whose name starts with 'PCP/' from the collection list."u8, disabled: !active)) + if (ImUtf8.ButtonEx("Delete all PCP Collections"u8, "Deletes all collections whose name starts with 'PCP/' from the collection list."u8, + disabled: !active)) _pcpService.CleanPcpCollections(); if (!active) ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, $"Hold {_config.DeleteModModifier} while clicking."); Checkbox("Allow Other Plugins Access to PCP Handling", "When creating or importing PCP files, other plugins can add and interpret their own data to the character.json file.", - _config.AllowPcpIpc, v => _config.AllowPcpIpc = v); + _config.PcpSettings.AllowIpc, v => _config.PcpSettings.AllowIpc = v); + + Checkbox("Create PCP Collections", + "When importing PCP files, create the associated collection.", + _config.PcpSettings.CreateCollection, v => _config.PcpSettings.CreateCollection = v); + + Checkbox("Assign PCP Collections", + "When importing PCP files and creating the associated collection, assign it to the associated character.", + _config.PcpSettings.AssignCollection, v => _config.PcpSettings.AssignCollection = v); DrawDefaultModImportPath(); DrawDefaultModAuthor(); DrawDefaultModImportFolder(); @@ -736,10 +745,10 @@ public class SettingsTab : ITab, IUiService /// Draw input for the default folder to sort put newly imported mods into. private void DrawPcpFolder() { - var tmp = _config.PcpFolderName; + var tmp = _config.PcpSettings.FolderName; ImGui.SetNextItemWidth(UiHelpers.InputTextWidth.X); if (ImUtf8.InputText("##pcpFolder"u8, ref tmp)) - _config.PcpFolderName = tmp; + _config.PcpSettings.FolderName = tmp; if (ImGui.IsItemDeactivatedAfterEdit()) _config.Save(); From c8b6325a8733cfdbae82cb90b4eb2d903c6c1ca6 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 24 Aug 2025 08:34:54 +0200 Subject: [PATCH 1314/1381] Add game integrity message to On-Screen --- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 25 +++++++++++++++++-- .../ResourceTreeViewerFactory.cs | 6 +++-- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index a2309343..617ba30f 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -1,7 +1,9 @@ using Dalamud.Bindings.ImGui; using Dalamud.Interface; +using Dalamud.Interface.Colors; using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility; +using Dalamud.Plugin.Services; using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; @@ -13,7 +15,6 @@ using Penumbra.Interop.ResourceTree; using Penumbra.Services; using Penumbra.String; using Penumbra.UI.Classes; -using static System.Net.Mime.MediaTypeNames; namespace Penumbra.UI.AdvancedWindow; @@ -26,7 +27,8 @@ public class ResourceTreeViewer( Action onRefresh, Action drawActions, CommunicatorService communicator, - PcpService pcpService) + PcpService pcpService, + IDataManager gameData) { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; @@ -45,6 +47,7 @@ public class ResourceTreeViewer( public void Draw() { + DrawModifiedGameFilesWarning(); DrawControls(); _task ??= RefreshCharacterList(); @@ -130,6 +133,24 @@ public class ResourceTreeViewer( } } + private void DrawModifiedGameFilesWarning() + { + if (!gameData.HasModifiedGameDataFiles) + return; + + using var style = ImRaii.PushColor(ImGuiCol.Text, ImGuiColors.DalamudOrange); + + ImUtf8.TextWrapped( + "Dalamud is reporting your FFXIV installation has modified game files. Any mods installed through TexTools will produce this message."u8); + ImUtf8.TextWrapped("Penumbra and some other plugins assume your FFXIV installation is unmodified in order to work."u8); + ImUtf8.TextWrapped( + "Data displayed here may be inaccurate because of this, which, in turn, can break functionality relying on it, such as Character Pack exports/imports, or mod synchronization functions provided by other plugins."u8); + ImUtf8.TextWrapped( + "Exit the game, open XIVLauncher, click the arrow next to Log In and select \"repair game files\" to resolve this issue. Afterwards, do not install any mods with TexTools. Your plugin configurations will remain, as will mods enabled in Penumbra."u8); + + ImGui.Separator(); + } + private void DrawControls() { var yOffset = (ChangedItemDrawer.TypeFilterIconSize.Y - ImGui.GetFrameHeight()) / 2f; diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs index ac06fe1a..43b60716 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs @@ -1,3 +1,4 @@ +using Dalamud.Plugin.Services; using OtterGui.Services; using Penumbra.Interop.ResourceTree; using Penumbra.Services; @@ -10,8 +11,9 @@ public class ResourceTreeViewerFactory( ChangedItemDrawer changedItemDrawer, IncognitoService incognito, CommunicatorService communicator, - PcpService pcpService) : IService + PcpService pcpService, + IDataManager gameData) : IService { public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) - => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator, pcpService); + => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator, pcpService, gameData); } From 1fca78fa71239882dc7f88df72c31440a8660cb4 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 24 Aug 2025 06:39:38 +0200 Subject: [PATCH 1315/1381] Add Kdb files to ResourceTree --- Penumbra.GameData | 2 +- .../Processing/SkinMtrlPathEarlyProcessing.cs | 2 +- .../ResolveContext.PathResolution.cs | 28 +++++++++++++++++++ .../Interop/ResourceTree/ResolveContext.cs | 23 ++++++++++++++- Penumbra/Interop/ResourceTree/ResourceNode.cs | 4 ++- Penumbra/Interop/ResourceTree/ResourceTree.cs | 14 ++++++---- Penumbra/Interop/Structs/StructExtensions.cs | 9 ++++++ 7 files changed, 73 insertions(+), 9 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 15e7c8eb..73010350 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 15e7c8eb41867e6bbd3fe6a8885404df087bc7e7 +Subproject commit 73010350338ecd7b98ad85d127bed08d7d8718d4 diff --git a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs index 4487eb7f..6be1b959 100644 --- a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs +++ b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs @@ -40,7 +40,7 @@ public static unsafe class SkinMtrlPathEarlyProcessing if (character->TempSlotData is not null) { - // TODO ClientStructs-ify + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1564) var handle = *(ModelResourceHandle**)((nint)character->TempSlotData + 0xE0 * slotIndex + 0x8); if (handle != null) return handle; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs index b6d04769..c204f141 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.PathResolution.cs @@ -338,6 +338,34 @@ internal partial record ResolveContext return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; } + private Utf8GamePath ResolveKineDriverModulePath(uint partialSkeletonIndex) + { + // Correctness and Safety: + // Resolving a KineDriver module path through the game's code can use EST metadata for human skeletons. + // Additionally, it can dereference null pointers for human equipment skeletons. + return ModelType switch + { + ModelType.Human => ResolveHumanKineDriverModulePath(partialSkeletonIndex), + _ => ResolveKineDriverModulePathNative(partialSkeletonIndex), + }; + } + + private Utf8GamePath ResolveHumanKineDriverModulePath(uint partialSkeletonIndex) + { + var (raceCode, slot, set) = ResolveHumanSkeletonData(partialSkeletonIndex); + if (set.Id is 0) + return Utf8GamePath.Empty; + + var path = GamePaths.Kdb.Customization(raceCode, slot, set); + return Utf8GamePath.FromString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + + private unsafe Utf8GamePath ResolveKineDriverModulePathNative(uint partialSkeletonIndex) + { + var path = CharacterBase->ResolveKdbPathAsByteString(partialSkeletonIndex); + return Utf8GamePath.FromByteString(path, out var gamePath) ? gamePath : Utf8GamePath.Empty; + } + private unsafe Utf8GamePath ResolveMaterialAnimationPath(ResourceHandle* imc) { var animation = ResolveImcData(imc).MaterialAnimationId; diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index b2364e33..bbe9b8ce 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -371,7 +371,8 @@ internal unsafe partial record ResolveContext( return node; } - public ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, ResourceHandle* phybHandle, uint partialSkeletonIndex) + public ResourceNode? CreateNodeFromPartialSkeleton(PartialSkeleton* sklb, ResourceHandle* phybHandle, ResourceHandle* kdbHandle, + uint partialSkeletonIndex) { if (sklb is null || sklb->SkeletonResourceHandle is null) return null; @@ -386,6 +387,8 @@ internal unsafe partial record ResolveContext( node.Children.Add(skpNode); if (CreateNodeFromPhyb(phybHandle, partialSkeletonIndex) is { } phybNode) node.Children.Add(phybNode); + if (CreateNodeFromKdb(kdbHandle, partialSkeletonIndex) is { } kdbNode) + node.Children.Add(kdbNode); Global.Nodes.Add((path, (nint)sklb->SkeletonResourceHandle), node); return node; @@ -427,6 +430,24 @@ internal unsafe partial record ResolveContext( return node; } + private ResourceNode? CreateNodeFromKdb(ResourceHandle* kdbHandle, uint partialSkeletonIndex) + { + if (kdbHandle is null) + return null; + + var path = ResolveKineDriverModulePath(partialSkeletonIndex); + + if (Global.Nodes.TryGetValue((path, (nint)kdbHandle), out var cached)) + return cached; + + var node = CreateNode(ResourceType.Phyb, 0, kdbHandle, path, false); + if (Global.WithUiData) + node.FallbackName = "KineDriver Module"; + Global.Nodes.Add((path, (nint)kdbHandle), node); + + return node; + } + internal ResourceNode.UiData GuessModelUiData(Utf8GamePath gamePath) { var path = gamePath.Path.Split((byte)'/'); diff --git a/Penumbra/Interop/ResourceTree/ResourceNode.cs b/Penumbra/Interop/ResourceTree/ResourceNode.cs index 3699ae0b..08dee818 100644 --- a/Penumbra/Interop/ResourceTree/ResourceNode.cs +++ b/Penumbra/Interop/ResourceTree/ResourceNode.cs @@ -45,7 +45,9 @@ public class ResourceNode : ICloneable /// Whether to treat the file as protected (require holding the Mod Deletion Modifier to make a quick import). public bool Protected - => ForceProtected || Internal || Type is ResourceType.Shpk or ResourceType.Sklb or ResourceType.Pbd; + => ForceProtected + || Internal + || Type is ResourceType.Shpk or ResourceType.Sklb or ResourceType.Skp or ResourceType.Phyb or ResourceType.Kdb or ResourceType.Pbd; internal ResourceNode(ResourceType type, nint objectAddress, nint resourceHandle, ulong length, ResolveContext? resolveContext) { diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index ddef347d..23fe26b8 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -121,7 +121,7 @@ public class ResourceTree( } } - AddSkeleton(Nodes, genericContext, model->EID, model->Skeleton, model->BonePhysicsModule); + AddSkeleton(Nodes, genericContext, model); AddMaterialAnimationSkeleton(Nodes, genericContext, model->MaterialAnimationSkeleton); AddWeapons(globalContext, model); @@ -178,8 +178,7 @@ public class ResourceTree( } } - AddSkeleton(weaponNodes, genericContext, subObject->EID, subObject->Skeleton, subObject->BonePhysicsModule, - $"Weapon #{weaponIndex}, "); + AddSkeleton(weaponNodes, genericContext, subObject, $"Weapon #{weaponIndex}, "); AddMaterialAnimationSkeleton(weaponNodes, genericContext, subObject->MaterialAnimationSkeleton, $"Weapon #{weaponIndex}, "); @@ -242,8 +241,11 @@ public class ResourceTree( } } + private unsafe void AddSkeleton(List nodes, ResolveContext context, CharacterBase* model, string prefix = "") + => AddSkeleton(nodes, context, model->EID, model->Skeleton, model->BonePhysicsModule, *(void**)((nint)model + 0x160), prefix); + private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, BonePhysicsModule* physics, - string prefix = "") + void* kineDriver, string prefix = "") { var eidNode = context.CreateNodeFromEid((ResourceHandle*)eid); if (eidNode != null) @@ -259,7 +261,9 @@ public class ResourceTree( for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) { var phybHandle = physics != null ? physics->BonePhysicsResourceHandles[i] : null; - if (context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, (uint)i) is { } sklbNode) + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1562) + var kdbHandle = kineDriver != null ? *(ResourceHandle**)((nint)kineDriver + 0x20 + 0x18 * i) : null; + if (context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, kdbHandle, (uint)i) is { } sklbNode) { if (context.Global.WithUiData) sklbNode.FallbackName = $"{prefix}Skeleton #{i}"; diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 031d24b1..5a29bb6f 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -64,6 +64,15 @@ internal static class StructExtensions return ToOwnedByteString(character.ResolvePhybPath(pathBuffer, partialSkeletonIndex)); } + public static unsafe CiByteString ResolveKdbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) + { + // TODO ClientStructs-ify (aers/FFXIVClientStructs#1561) + var vf80 = (delegate* unmanaged)((nint*)character.VirtualTable)[80]; + var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; + return ToOwnedByteString(vf80((CharacterBase*)Unsafe.AsPointer(ref character), pathBuffer, CharacterBase.PathBufferSize, + partialSkeletonIndex)); + } + private static unsafe CiByteString ToOwnedByteString(CStringPointer str) => str.HasValue ? new CiByteString(str.Value).Clone() : CiByteString.Empty; From f51f8a7bf80f5560c9a88251cad8766a71e17692 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 24 Aug 2025 15:24:50 +0200 Subject: [PATCH 1316/1381] Try to filter meta entries for relevance. --- Penumbra/Meta/Manipulations/MetaDictionary.cs | 182 ++++++++++++++++++ Penumbra/Services/PcpService.cs | 20 +- 2 files changed, 194 insertions(+), 8 deletions(-) diff --git a/Penumbra/Meta/Manipulations/MetaDictionary.cs b/Penumbra/Meta/Manipulations/MetaDictionary.cs index c2c9e777..8b448ec6 100644 --- a/Penumbra/Meta/Manipulations/MetaDictionary.cs +++ b/Penumbra/Meta/Manipulations/MetaDictionary.cs @@ -1,7 +1,10 @@ +using System.Collections.Frozen; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Penumbra.Collections.Cache; +using Penumbra.GameData.Enums; using Penumbra.GameData.Files.AtchStructs; +using Penumbra.GameData.Interop; using Penumbra.GameData.Structs; using Penumbra.Util; using ImcEntry = Penumbra.GameData.Structs.ImcEntry; @@ -40,6 +43,165 @@ public class MetaDictionary foreach (var geqp in cache.GlobalEqp.Keys) Add(geqp); } + + public static unsafe Wrapper Filtered(MetaCache cache, Actor actor) + { + if (!actor.IsCharacter) + return new Wrapper(cache); + + var model = actor.Model; + if (!model.IsHuman) + return new Wrapper(cache); + + var headId = model.GetModelId(HumanSlot.Head); + var bodyId = model.GetModelId(HumanSlot.Body); + var equipIdSet = ((IEnumerable) + [ + headId, + bodyId, + model.GetModelId(HumanSlot.Hands), + model.GetModelId(HumanSlot.Legs), + model.GetModelId(HumanSlot.Feet), + ]).ToFrozenSet(); + var earsId = model.GetModelId(HumanSlot.Ears); + var neckId = model.GetModelId(HumanSlot.Neck); + var wristId = model.GetModelId(HumanSlot.Wrists); + var rFingerId = model.GetModelId(HumanSlot.RFinger); + var lFingerId = model.GetModelId(HumanSlot.LFinger); + + var wrapper = new Wrapper(); + // Check for all relevant primary IDs due to slot overlap. + foreach (var (eqp, value) in cache.Eqp) + { + if (eqp.Slot.IsEquipment()) + { + if (equipIdSet.Contains(eqp.SetId)) + wrapper.Eqp.Add(eqp, new EqpEntryInternal(value.Entry, eqp.Slot)); + } + else + { + switch (eqp.Slot) + { + case EquipSlot.Ears when eqp.SetId == earsId: + case EquipSlot.Neck when eqp.SetId == neckId: + case EquipSlot.Wrists when eqp.SetId == wristId: + case EquipSlot.RFinger when eqp.SetId == rFingerId: + case EquipSlot.LFinger when eqp.SetId == lFingerId: + wrapper.Eqp.Add(eqp, new EqpEntryInternal(value.Entry, eqp.Slot)); + break; + } + } + } + + // Check also for body IDs due to body occupying head. + foreach (var (gmp, value) in cache.Gmp) + { + if (gmp.SetId == headId || gmp.SetId == bodyId) + wrapper.Gmp.Add(gmp, value.Entry); + } + + // Check for all races due to inheritance and all slots due to overlap. + foreach (var (eqdp, value) in cache.Eqdp) + { + if (eqdp.Slot.IsEquipment()) + { + if (equipIdSet.Contains(eqdp.SetId)) + wrapper.Eqdp.Add(eqdp, new EqdpEntryInternal(value.Entry, eqdp.Slot)); + } + else + { + switch (eqdp.Slot) + { + case EquipSlot.Ears when eqdp.SetId == earsId: + case EquipSlot.Neck when eqdp.SetId == neckId: + case EquipSlot.Wrists when eqdp.SetId == wristId: + case EquipSlot.RFinger when eqdp.SetId == rFingerId: + case EquipSlot.LFinger when eqdp.SetId == lFingerId: + wrapper.Eqdp.Add(eqdp, new EqdpEntryInternal(value.Entry, eqdp.Slot)); + break; + } + } + } + + var genderRace = (GenderRace)model.AsHuman->RaceSexId; + var hairId = model.GetModelId(HumanSlot.Hair); + var faceId = model.GetModelId(HumanSlot.Face); + // We do not need to care for racial inheritance for ESTs. + foreach (var (est, value) in cache.Est) + { + switch (est.Slot) + { + case EstType.Hair when est.SetId == hairId && est.GenderRace == genderRace: + case EstType.Face when est.SetId == faceId && est.GenderRace == genderRace: + case EstType.Body when est.SetId == bodyId && est.GenderRace == genderRace: + case EstType.Head when (est.SetId == headId || est.SetId == bodyId) && est.GenderRace == genderRace: + wrapper.Est.Add(est, value.Entry); + break; + } + } + + foreach (var (geqp, _) in cache.GlobalEqp) + { + switch (geqp.Type) + { + case GlobalEqpType.DoNotHideEarrings when geqp.Condition != earsId: + case GlobalEqpType.DoNotHideNecklace when geqp.Condition != neckId: + case GlobalEqpType.DoNotHideBracelets when geqp.Condition != wristId: + case GlobalEqpType.DoNotHideRingR when geqp.Condition != rFingerId: + case GlobalEqpType.DoNotHideRingL when geqp.Condition != lFingerId: + continue; + default: wrapper.Add(geqp); break; + } + } + + var (_, _, main, off) = model.GetWeapons(actor); + foreach (var (imc, value) in cache.Imc) + { + switch (imc.ObjectType) + { + case ObjectType.Equipment when equipIdSet.Contains(imc.PrimaryId): wrapper.Imc.Add(imc, value.Entry); break; + + case ObjectType.Weapon: + if (imc.PrimaryId == main.Skeleton && imc.SecondaryId == main.Weapon) + wrapper.Imc.Add(imc, value.Entry); + else if (imc.PrimaryId == off.Skeleton && imc.SecondaryId == off.Weapon) + wrapper.Imc.Add(imc, value.Entry); + break; + case ObjectType.Accessory: + switch (imc.EquipSlot) + { + case EquipSlot.Ears when imc.PrimaryId == earsId: + case EquipSlot.Neck when imc.PrimaryId == neckId: + case EquipSlot.Wrists when imc.PrimaryId == wristId: + case EquipSlot.RFinger when imc.PrimaryId == rFingerId: + case EquipSlot.LFinger when imc.PrimaryId == lFingerId: + wrapper.Imc.Add(imc, value.Entry); + break; + } + + break; + } + } + + var subRace = (SubRace)model.AsHuman->Customize[4]; + foreach (var (rsp, value) in cache.Rsp) + { + if (rsp.SubRace == subRace) + wrapper.Rsp.Add(rsp, value.Entry); + } + + // Keep all atch, atr and shp. + wrapper.Atch.EnsureCapacity(cache.Atch.Count); + wrapper.Shp.EnsureCapacity(cache.Shp.Count); + wrapper.Atr.EnsureCapacity(cache.Atr.Count); + foreach (var (atch, value) in cache.Atch) + wrapper.Atch.Add(atch, value.Entry); + foreach (var (shp, value) in cache.Shp) + wrapper.Shp.Add(shp, value.Entry); + foreach (var (atr, value) in cache.Atr) + wrapper.Atr.Add(atr, value.Entry); + return wrapper; + } } private Wrapper? _data; @@ -934,4 +1096,24 @@ public class MetaDictionary _data = new Wrapper(cache); Count = cache.Count; } + + public MetaDictionary(MetaCache? cache, Actor actor) + { + if (cache is null) + return; + + _data = Wrapper.Filtered(cache, actor); + Count = _data.Count + + _data.Eqp.Count + + _data.Eqdp.Count + + _data.Est.Count + + _data.Gmp.Count + + _data.Imc.Count + + _data.Rsp.Count + + _data.Atch.Count + + _data.Atr.Count + + _data.Shp.Count; + if (Count is 0) + _data = null; + } } diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index b9d472aa..f75d3b5e 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -107,8 +107,8 @@ public class PcpService : IApiService, IDisposable } Penumbra.Log.Information($"[PCPService] Found a PCP file for {mod.Name}, applying."); - var text = File.ReadAllText(file); - var jObj = JObject.Parse(text); + var text = File.ReadAllText(file); + var jObj = JObject.Parse(text); var collection = ModCollection.Empty; // Create collection. if (_config.PcpSettings.CreateCollection) @@ -164,7 +164,7 @@ public class PcpService : IApiService, IDisposable try { Penumbra.Log.Information($"[PCPService] Creating PCP file for game object {objectIndex.Index}."); - var (identifier, tree, collection) = await _framework.Framework.RunOnFrameworkThread(() => + var (identifier, tree, meta) = await _framework.Framework.RunOnFrameworkThread(() => { var (actor, identifier) = CheckActor(objectIndex); cancel.ThrowIfCancellationRequested(); @@ -178,13 +178,14 @@ public class PcpService : IApiService, IDisposable if (_treeFactory.FromCharacter(actor, 0) is not { } tree) throw new Exception($"Unable to fetch modded resources for {identifier}."); - return (identifier.CreatePermanent(), tree, collection); + var meta = new MetaDictionary(collection.ModCollection.MetaCache, actor.Address); + return (identifier.CreatePermanent(), tree, meta); } }); cancel.ThrowIfCancellationRequested(); var time = DateTime.Now; var modDirectory = CreateMod(identifier, note, time); - await CreateDefaultMod(modDirectory, collection.ModCollection, tree, cancel); + await CreateDefaultMod(modDirectory, meta, tree, cancel); await CreateCollectionInfo(modDirectory, objectIndex, identifier, note, time, cancel); var file = ZipUp(modDirectory); return (true, file); @@ -242,11 +243,15 @@ public class PcpService : IApiService, IDisposable ?? throw new Exception($"Unable to create mod {modName} in {directory.FullName}."); } - private async Task CreateDefaultMod(DirectoryInfo modDirectory, ModCollection collection, ResourceTree tree, + private async Task CreateDefaultMod(DirectoryInfo modDirectory, MetaDictionary meta, ResourceTree tree, CancellationToken cancel = default) { var subDirectory = modDirectory.CreateSubdirectory("files"); - var subMod = new DefaultSubMod(null!); + var subMod = new DefaultSubMod(null!) + { + Manipulations = meta, + }; + foreach (var node in tree.FlatNodes) { cancel.ThrowIfCancellationRequested(); @@ -269,7 +274,6 @@ public class PcpService : IApiService, IDisposable } cancel.ThrowIfCancellationRequested(); - subMod.Manipulations = new MetaDictionary(collection.MetaCache); var saveGroup = new ModSaveGroup(modDirectory, subMod, _config.ReplaceNonAsciiOnImport); var filePath = _files.FileNames.OptionGroupFile(modDirectory.FullName, -1, string.Empty, _config.ReplaceNonAsciiOnImport); From 1e07e434985ce55cd47d783d1e6dc7f48e29c7b9 Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 24 Aug 2025 13:51:43 +0000 Subject: [PATCH 1317/1381] [CI] Updating repo.json for testing_1.5.0.9 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 48d5b97f..446932b5 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.0.6", - "TestingAssemblyVersion": "1.5.0.8", + "TestingAssemblyVersion": "1.5.0.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.9/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From a14347f73a39ae0579d721f9b77b05f3e989c8b0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Aug 2025 10:13:31 +0200 Subject: [PATCH 1318/1381] Update temporary collection creation. --- Penumbra.Api | 2 +- Penumbra/Api/Api/IdentityChecker.cs | 7 +++++++ Penumbra/Api/Api/TemporaryApi.cs | 12 ++++++++++-- Penumbra/Api/IpcTester/TemporaryIpcTester.cs | 4 +++- 4 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 Penumbra/Api/Api/IdentityChecker.cs diff --git a/Penumbra.Api b/Penumbra.Api index 297941bc..af41b178 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 297941bc22300f4a8368f4d0177f62943eb69727 +Subproject commit af41b1787acef9df7dc83619fe81e63a36443ee5 diff --git a/Penumbra/Api/Api/IdentityChecker.cs b/Penumbra/Api/Api/IdentityChecker.cs new file mode 100644 index 00000000..e090053e --- /dev/null +++ b/Penumbra/Api/Api/IdentityChecker.cs @@ -0,0 +1,7 @@ +namespace Penumbra.Api.Api; + +public static class IdentityChecker +{ + public static bool Check(string identity) + => true; +} diff --git a/Penumbra/Api/Api/TemporaryApi.cs b/Penumbra/Api/Api/TemporaryApi.cs index a997ded8..7567acd3 100644 --- a/Penumbra/Api/Api/TemporaryApi.cs +++ b/Penumbra/Api/Api/TemporaryApi.cs @@ -20,8 +20,16 @@ public class TemporaryApi( ApiHelpers apiHelpers, ModManager modManager) : IPenumbraApiTemporary, IApiService { - public Guid CreateTemporaryCollection(string name) - => tempCollections.CreateTemporaryCollection(name); + public (PenumbraApiEc, Guid) CreateTemporaryCollection(string identity, string name) + { + if (!IdentityChecker.Check(identity)) + return (PenumbraApiEc.InvalidCredentials, Guid.Empty); + + var collection = tempCollections.CreateTemporaryCollection(name); + if (collection == Guid.Empty) + return (PenumbraApiEc.UnknownError, collection); + return (PenumbraApiEc.Success, collection); + } public PenumbraApiEc DeleteTemporaryCollection(Guid collectionId) => tempCollections.RemoveTemporaryCollection(collectionId) diff --git a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs index 64adf256..d46c5728 100644 --- a/Penumbra/Api/IpcTester/TemporaryIpcTester.cs +++ b/Penumbra/Api/IpcTester/TemporaryIpcTester.cs @@ -38,6 +38,7 @@ public class TemporaryIpcTester( private string _tempGamePath = "test/game/path.mtrl"; private string _tempFilePath = "test/success.mtrl"; private string _tempManipulation = string.Empty; + private string _identity = string.Empty; private PenumbraApiEc _lastTempError; private int _tempActorIndex; private bool _forceOverwrite; @@ -48,6 +49,7 @@ public class TemporaryIpcTester( if (!_) return; + ImGui.InputTextWithHint("##identity", "Identity...", ref _identity, 128); ImGui.InputTextWithHint("##tempCollection", "Collection Name...", ref _tempCollectionName, 128); ImGuiUtil.GuidInput("##guid", "Collection GUID...", string.Empty, ref _tempGuid, ref _tempCollectionGuidName); ImGui.InputInt("##tempActorIndex", ref _tempActorIndex, 0, 0); @@ -73,7 +75,7 @@ public class TemporaryIpcTester( IpcTester.DrawIntro(CreateTemporaryCollection.Label, "Create Temporary Collection"); if (ImGui.Button("Create##Collection")) { - LastCreatedCollectionId = new CreateTemporaryCollection(pi).Invoke(_tempCollectionName); + _lastTempError = new CreateTemporaryCollection(pi).Invoke(_identity, _tempCollectionName, out LastCreatedCollectionId); if (_tempGuid == null) { _tempGuid = LastCreatedCollectionId; From bf90725dd2db6b300577fa0c64d309b5277eedee Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Aug 2025 10:13:39 +0200 Subject: [PATCH 1319/1381] Fix resolvecontext issue. --- Penumbra/Interop/ResourceTree/ResolveContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/ResourceTree/ResolveContext.cs b/Penumbra/Interop/ResourceTree/ResolveContext.cs index bbe9b8ce..501bbc56 100644 --- a/Penumbra/Interop/ResourceTree/ResolveContext.cs +++ b/Penumbra/Interop/ResourceTree/ResolveContext.cs @@ -440,7 +440,7 @@ internal unsafe partial record ResolveContext( if (Global.Nodes.TryGetValue((path, (nint)kdbHandle), out var cached)) return cached; - var node = CreateNode(ResourceType.Phyb, 0, kdbHandle, path, false); + var node = CreateNode(ResourceType.Kdb, 0, kdbHandle, path, false); if (Global.WithUiData) node.FallbackName = "KineDriver Module"; Global.Nodes.Add((path, (nint)kdbHandle), node); From 79a4fc5904501fb30dd879ec37d8513c328ea120 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Aug 2025 10:13:48 +0200 Subject: [PATCH 1320/1381] Fix wrong logging. --- Penumbra/Services/PcpService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index f75d3b5e..63b8eab3 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -99,9 +99,11 @@ public class PcpService : IApiService, IDisposable { // First version had collection.json, changed. var oldFile = Path.Combine(newDirectory.FullName, "collection.json"); - Penumbra.Log.Information("[PCPService] Renaming old PCP file from collection.json to character.json."); if (File.Exists(oldFile)) + { + Penumbra.Log.Information("[PCPService] Renaming old PCP file from collection.json to character.json."); File.Move(oldFile, file, true); + } else return; } From e16800f21649447cc316fa9ce8c7d88518ad19dd Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 25 Aug 2025 08:16:04 +0000 Subject: [PATCH 1321/1381] [CI] Updating repo.json for testing_1.5.0.10 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 446932b5..dea56357 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.0.6", - "TestingAssemblyVersion": "1.5.0.9", + "TestingAssemblyVersion": "1.5.0.10", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.10/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From da47c19aeb30fcc293308652503b5cf1985a390d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Aug 2025 10:25:05 +0200 Subject: [PATCH 1322/1381] Woops, increment version. --- Penumbra/Api/Api/PenumbraApi.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 9e7eb964..7304c9c7 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -17,7 +17,7 @@ public class PenumbraApi( UiApi ui) : IDisposable, IApiService, IPenumbraApi { public const int BreakingVersion = 5; - public const int FeatureVersion = 11; + public const int FeatureVersion = 12; public void Dispose() { From c0120f81af3a713f861f275ad379a18ed14c0091 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Mon, 25 Aug 2025 10:37:38 +0200 Subject: [PATCH 1323/1381] 1.5.1.0 --- Penumbra/Penumbra.json | 2 +- Penumbra/UI/Changelog.cs | 22 ++++++++++++++++-- repo.json | 48 ++++++++++++++++++++-------------------- 3 files changed, 45 insertions(+), 27 deletions(-) diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index bd9a2479..32032282 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -1,5 +1,5 @@ { - "Author": "Ottermandias, Adam, Wintermute", + "Author": "Ottermandias, Nylfae, Adam, Wintermute", "Name": "Penumbra", "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", diff --git a/Penumbra/UI/Changelog.cs b/Penumbra/UI/Changelog.cs index 4b487104..306dcc79 100644 --- a/Penumbra/UI/Changelog.cs +++ b/Penumbra/UI/Changelog.cs @@ -63,10 +63,28 @@ public class PenumbraChangelog : IUiService Add1_3_6_4(Changelog); Add1_4_0_0(Changelog); Add1_5_0_0(Changelog); - } - + Add1_5_1_0(Changelog); + } + #region Changelogs + private static void Add1_5_1_0(Changelog log) + => log.NextVersion("Version 1.5.1.0") + .RegisterHighlight("Added the option to export a characters current data as a .pcp modpack in the On-Screen tab.") + .RegisterEntry("Other plugins can attach to this functionality and package and interpret their own data.", 1) + .RegisterEntry("When a .pcp modpack is installed, it can create and assign collections for the corresponding character it was created for.", 1) + .RegisterEntry("This basically provides an easier way to manually synchronize other players, but does not contain any automation.", 1) + .RegisterEntry("The settings provide some fine control about what happens when a PCP is installed, as well as buttons to cleanup any PCP-created data.", 1) + .RegisterEntry("Added a warning message when the game's integrity is corrupted to the On-Screen tab.") + .RegisterEntry("Added .kdb files to the On-Screen tab and associated functionality (thanks Ny!).") + .RegisterEntry("Updated the creation of temporary collections to require a passed identity.") + .RegisterEntry("Added the option to change the skin material suffix in models using the stockings shader by adding specific attributes (thanks Ny!).") + .RegisterEntry("Added predefined tag utility to the multi-mod selection.") + .RegisterEntry("Fixed an issue with the automatic collection selection on character login when no mods are assigned.") + .RegisterImportant( + "Fixed issue with new deformer data that makes modded deformers not containing this data work implicitly. Updates are still recommended (1.5.0.5).") + .RegisterEntry("Fixed various issues after patch (1.5.0.1 - 1.5.0.4)."); + private static void Add1_5_0_0(Changelog log) => log.NextVersion("Version 1.5.0.0") .RegisterImportant("Updated for game version 7.30 and Dalamud API13, which uses a new GUI backend. Some things may not work as expected. Please let me know any issues you encounter.") diff --git a/repo.json b/repo.json index dea56357..4675bccf 100644 --- a/repo.json +++ b/repo.json @@ -1,26 +1,26 @@ [ - { - "Author": "Ottermandias, Adam, Wintermute", - "Name": "Penumbra", - "Punchline": "Runtime mod loader and manager.", - "Description": "Runtime mod loader and manager.", - "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.6", - "TestingAssemblyVersion": "1.5.0.10", - "RepoUrl": "https://github.com/xivdev/Penumbra", - "ApplicableVersion": "any", - "DalamudApiLevel": 13, - "TestingDalamudApiLevel": 13, - "IsHide": "False", - "IsTestingExclusive": "False", - "DownloadCount": 0, - "LastUpdate": 0, - "LoadPriority": 69420, - "LoadRequiredState": 2, - "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.10/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" - } + { + "Author": "Ottermandias, Nylfae, Adam, Wintermute", + "Name": "Penumbra", + "Punchline": "Runtime mod loader and manager.", + "Description": "Runtime mod loader and manager.", + "InternalName": "Penumbra", + "AssemblyVersion": "1.5.0.6", + "TestingAssemblyVersion": "1.5.0.10", + "RepoUrl": "https://github.com/xivdev/Penumbra", + "ApplicableVersion": "any", + "DalamudApiLevel": 13, + "TestingDalamudApiLevel": 13, + "IsHide": "False", + "IsTestingExclusive": "False", + "DownloadCount": 0, + "LastUpdate": 0, + "LoadPriority": 69420, + "LoadRequiredState": 2, + "LoadSync": true, + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.10/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", + "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" + } ] From 71e24c13c7915e4741fe20fa86cc6dbebf1d2355 Mon Sep 17 00:00:00 2001 From: Actions User Date: Mon, 25 Aug 2025 08:39:42 +0000 Subject: [PATCH 1324/1381] [CI] Updating repo.json for 1.5.1.0 --- repo.json | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/repo.json b/repo.json index 4675bccf..e9a52799 100644 --- a/repo.json +++ b/repo.json @@ -1,26 +1,26 @@ [ - { - "Author": "Ottermandias, Nylfae, Adam, Wintermute", - "Name": "Penumbra", - "Punchline": "Runtime mod loader and manager.", - "Description": "Runtime mod loader and manager.", - "InternalName": "Penumbra", - "AssemblyVersion": "1.5.0.6", - "TestingAssemblyVersion": "1.5.0.10", - "RepoUrl": "https://github.com/xivdev/Penumbra", - "ApplicableVersion": "any", - "DalamudApiLevel": 13, - "TestingDalamudApiLevel": 13, - "IsHide": "False", - "IsTestingExclusive": "False", - "DownloadCount": 0, - "LastUpdate": 0, - "LoadPriority": 69420, - "LoadRequiredState": 2, - "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.0.10/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.0.6/Penumbra.zip", - "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" - } + { + "Author": "Ottermandias, Nylfae, Adam, Wintermute", + "Name": "Penumbra", + "Punchline": "Runtime mod loader and manager.", + "Description": "Runtime mod loader and manager.", + "InternalName": "Penumbra", + "AssemblyVersion": "1.5.1.0", + "TestingAssemblyVersion": "1.5.1.0", + "RepoUrl": "https://github.com/xivdev/Penumbra", + "ApplicableVersion": "any", + "DalamudApiLevel": 13, + "TestingDalamudApiLevel": 13, + "IsHide": "False", + "IsTestingExclusive": "False", + "DownloadCount": 0, + "LastUpdate": 0, + "LoadPriority": 69420, + "LoadRequiredState": 2, + "LoadSync": true, + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.0/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.0/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.0/Penumbra.zip", + "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" + } ] From a04a5a071c99585f4d4bd749fc6b4f8b9d4dce99 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Aug 2025 18:51:57 +0200 Subject: [PATCH 1325/1381] Add warning in file redirections if extension doesn't match. --- Penumbra.Api | 2 +- .../UI/AdvancedWindow/ModEditWindow.Files.cs | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index af41b178..953dd227 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit af41b1787acef9df7dc83619fe81e63a36443ee5 +Subproject commit 953dd227afda6b3943b0b88cc965d8aee8a879b5 diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs index 87d7487b..63c99b8a 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.Files.cs @@ -287,6 +287,17 @@ public partial class ModEditWindow using var font = ImRaii.PushFont(UiBuilder.IconFont); ImGuiUtil.TextColored(0xFF0000FF, FontAwesomeIcon.TimesCircle.ToIconString()); } + else if (tmp.Length > 0 && Path.GetExtension(tmp) != registry.File.Extension) + { + ImGui.SameLine(); + ImGui.SetCursorPosX(pos); + using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + { + ImGuiUtil.TextColored(0xFF00B0B0, FontAwesomeIcon.ExclamationCircle.ToIconString()); + } + + ImUtf8.HoverTooltip("The game path and the file do not have the same extension."u8); + } } private void PrintNewGamePath(int i, FileRegistry registry, IModDataContainer subMod) @@ -319,6 +330,17 @@ public partial class ModEditWindow using var font = ImRaii.PushFont(UiBuilder.IconFont); ImGuiUtil.TextColored(0xFF0000FF, FontAwesomeIcon.TimesCircle.ToIconString()); } + else if (tmp.Length > 0 && Path.GetExtension(tmp) != registry.File.Extension) + { + ImGui.SameLine(); + ImGui.SetCursorPosX(pos); + using (var font = ImRaii.PushFont(UiBuilder.IconFont)) + { + ImGuiUtil.TextColored(0xFF00B0B0, FontAwesomeIcon.ExclamationCircle.ToIconString()); + } + + ImUtf8.HoverTooltip("The game path and the file do not have the same extension."u8); + } } private void DrawButtonHeader() From f7cf5503bbd4c31b59c081f91b966afbc291b1f3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 28 Aug 2025 18:52:06 +0200 Subject: [PATCH 1326/1381] Fix deleting PCP collections. --- Penumbra/Services/PcpService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index 63b8eab3..bdf1adc5 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -84,7 +84,7 @@ public class PcpService : IApiService, IDisposable var collections = _collections.Storage.Where(c => c.Identity.Name.StartsWith("PCP/")).ToList(); Penumbra.Log.Information($"[PCPService] Deleting {collections.Count} mods containing the tag PCP."); foreach (var collection in collections) - _collections.Storage.Delete(collection); + _collections.Storage.RemoveCollection(collection); } private void OnModPathChange(ModPathChangeType type, Mod mod, DirectoryInfo? oldDirectory, DirectoryInfo? newDirectory) From 912020cc3f9a08324bb2515b0a35f22b720051cc Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 29 Aug 2025 16:36:42 +0200 Subject: [PATCH 1327/1381] Update for staging and wrong tooltip. --- Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs | 5 ++--- Penumbra/Services/PcpService.cs | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs index 6be1b959..bd066d83 100644 --- a/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs +++ b/Penumbra/Interop/Processing/SkinMtrlPathEarlyProcessing.cs @@ -38,10 +38,9 @@ public static unsafe class SkinMtrlPathEarlyProcessing if (character is null) return null; - if (character->TempSlotData is not null) + if (character->PerSlotStagingArea is not null) { - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1564) - var handle = *(ModelResourceHandle**)((nint)character->TempSlotData + 0xE0 * slotIndex + 0x8); + var handle = character->PerSlotStagingArea[slotIndex].ModelResourceHandle; if (handle != null) return handle; } diff --git a/Penumbra/Services/PcpService.cs b/Penumbra/Services/PcpService.cs index bdf1adc5..17646564 100644 --- a/Penumbra/Services/PcpService.cs +++ b/Penumbra/Services/PcpService.cs @@ -82,7 +82,7 @@ public class PcpService : IApiService, IDisposable public void CleanPcpCollections() { var collections = _collections.Storage.Where(c => c.Identity.Name.StartsWith("PCP/")).ToList(); - Penumbra.Log.Information($"[PCPService] Deleting {collections.Count} mods containing the tag PCP."); + Penumbra.Log.Information($"[PCPService] Deleting {collections.Count} collections starting with PCP/."); foreach (var collection in collections) _collections.Storage.RemoveCollection(collection); } From 8c25ef4b47486df7b79c63d66c78fcf7710f2112 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 30 Aug 2025 16:53:12 +0200 Subject: [PATCH 1328/1381] Make the save button ResourceTreeViewer baseline --- .../ModEditWindow.QuickImport.cs | 62 +---------- Penumbra/UI/AdvancedWindow/ModEditWindow.cs | 2 +- .../UI/AdvancedWindow/ResourceTreeViewer.cs | 104 ++++++++++++++---- .../ResourceTreeViewerFactory.cs | 11 +- 4 files changed, 95 insertions(+), 84 deletions(-) diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs index 72350857..f55ae576 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.QuickImport.cs @@ -17,7 +17,6 @@ public partial class ModEditWindow private readonly FileDialogService _fileDialog; private readonly ResourceTreeFactory _resourceTreeFactory; private readonly ResourceTreeViewer _quickImportViewer; - private readonly Dictionary _quickImportWritables = new(); private readonly Dictionary<(Utf8GamePath, IWritable?), QuickImportAction> _quickImportActions = new(); private HashSet GetPlayerResourcesOfType(ResourceType type) @@ -56,52 +55,11 @@ public partial class ModEditWindow private void OnQuickImportRefresh() { - _quickImportWritables.Clear(); _quickImportActions.Clear(); } - private void DrawQuickImportActions(ResourceNode resourceNode, Vector2 buttonSize) + private void DrawQuickImportActions(ResourceNode resourceNode, IWritable? writable, Vector2 buttonSize) { - if (!_quickImportWritables!.TryGetValue(resourceNode.FullPath, out var writable)) - { - var path = resourceNode.FullPath.ToPath(); - if (resourceNode.FullPath.IsRooted) - { - writable = new RawFileWritable(path); - } - else - { - var file = _gameData.GetFile(path); - writable = file is null ? null : new RawGameFileWritable(file); - } - - _quickImportWritables.Add(resourceNode.FullPath, writable); - } - - if (ImUtf8.IconButton(FontAwesomeIcon.Save, "Export this file."u8, buttonSize, - resourceNode.FullPath.FullName.Length is 0 || writable is null)) - { - var fullPathStr = resourceNode.FullPath.FullName; - var ext = resourceNode.PossibleGamePaths.Length == 1 - ? Path.GetExtension(resourceNode.GamePath.ToString()) - : Path.GetExtension(fullPathStr); - _fileDialog.OpenSavePicker($"Export {Path.GetFileName(fullPathStr)} to...", ext, Path.GetFileNameWithoutExtension(fullPathStr), ext, - (success, name) => - { - if (!success) - return; - - try - { - _editor.Compactor.WriteAllBytes(name, writable!.Write()); - } - catch (Exception e) - { - Penumbra.Log.Error($"Could not export {fullPathStr}:\n{e}"); - } - }, null, false); - } - ImGui.SameLine(); if (!_quickImportActions!.TryGetValue((resourceNode.GamePath, writable), out var quickImport)) { @@ -121,24 +79,6 @@ public partial class ModEditWindow } } - private record RawFileWritable(string Path) : IWritable - { - public bool Valid - => true; - - public byte[] Write() - => File.ReadAllBytes(Path); - } - - private record RawGameFileWritable(FileResource FileResource) : IWritable - { - public bool Valid - => true; - - public byte[] Write() - => FileResource.Data; - } - public class QuickImportAction { public const string FallbackOptionName = "the current option"; diff --git a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs index 952d8489..5a0fb849 100644 --- a/Penumbra/UI/AdvancedWindow/ModEditWindow.cs +++ b/Penumbra/UI/AdvancedWindow/ModEditWindow.cs @@ -667,7 +667,7 @@ public partial class ModEditWindow : Window, IDisposable, IUiService _center = new CombinedTexture(_left, _right); _textureSelectCombo = new TextureDrawer.PathSelectCombo(textures, editor, () => GetPlayerResourcesOfType(ResourceType.Tex)); _resourceTreeFactory = resourceTreeFactory; - _quickImportViewer = resourceTreeViewerFactory.Create(2, OnQuickImportRefresh, DrawQuickImportActions); + _quickImportViewer = resourceTreeViewerFactory.Create(1, OnQuickImportRefresh, DrawQuickImportActions); _communicator.ModPathChanged.Subscribe(OnModPathChange, ModPathChanged.Priority.ModEditWindow); IsOpen = _config is { OpenWindowAtStart: true, Ephemeral.AdvancedEditingOpen: true }; if (IsOpen && selection.Mod != null) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 617ba30f..00003451 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -4,16 +4,20 @@ using Dalamud.Interface.Colors; using Dalamud.Interface.ImGuiNotification; using Dalamud.Interface.Utility; using Dalamud.Plugin.Services; +using Lumina.Data; using OtterGui; using OtterGui.Classes; +using OtterGui.Compression; using OtterGui.Extensions; using OtterGui.Raii; using OtterGui.Text; using Penumbra.Api.Enums; +using Penumbra.GameData.Files; using Penumbra.GameData.Structs; using Penumbra.Interop.ResourceTree; using Penumbra.Services; using Penumbra.String; +using Penumbra.String.Classes; using Penumbra.UI.Classes; namespace Penumbra.UI.AdvancedWindow; @@ -25,17 +29,20 @@ public class ResourceTreeViewer( IncognitoService incognito, int actionCapacity, Action onRefresh, - Action drawActions, + Action drawActions, CommunicatorService communicator, PcpService pcpService, - IDataManager gameData) + IDataManager gameData, + FileDialogService fileDialog, + FileCompactor compactor) { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; private readonly HashSet _unfolded = []; - private readonly Dictionary _filterCache = []; + private readonly Dictionary _filterCache = []; + private readonly Dictionary _writableCache = []; private TreeCategory _categoryFilter = AllCategories; private ChangedItemIconFlag _typeFilter = ChangedItemFlagExtensions.AllFlags; @@ -115,7 +122,7 @@ public class ResourceTreeViewer( ImUtf8.InputText("##note"u8, ref _note, "Export note..."u8); - using var table = ImRaii.Table("##ResourceTree", actionCapacity > 0 ? 4 : 3, + using var table = ImRaii.Table("##ResourceTree", 4, ImGuiTableFlags.SizingFixedFit | ImGuiTableFlags.RowBg); if (!table) continue; @@ -123,9 +130,8 @@ public class ResourceTreeViewer( ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthStretch, 0.2f); ImGui.TableSetupColumn("Game Path", ImGuiTableColumnFlags.WidthStretch, 0.3f); ImGui.TableSetupColumn("Actual Path", ImGuiTableColumnFlags.WidthStretch, 0.5f); - if (actionCapacity > 0) - ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, - (actionCapacity - 1) * 3 * ImGuiHelpers.GlobalScale + actionCapacity * ImGui.GetFrameHeight()); + ImGui.TableSetupColumn(string.Empty, ImGuiTableColumnFlags.WidthFixed, + actionCapacity * 3 * ImGuiHelpers.GlobalScale + (actionCapacity + 1) * ImGui.GetFrameHeight()); ImGui.TableHeadersRow(); DrawNodes(tree.Nodes, 0, unchecked(tree.DrawObjectAddress * 31), 0); @@ -211,6 +217,7 @@ public class ResourceTreeViewer( finally { _filterCache.Clear(); + _writableCache.Clear(); _unfolded.Clear(); onRefresh(); } @@ -221,7 +228,6 @@ public class ResourceTreeViewer( { var debugMode = config.DebugMode; var frameHeight = ImGui.GetFrameHeight(); - var cellHeight = actionCapacity > 0 ? frameHeight : 0.0f; foreach (var (resourceNode, index) in resourceNodes.WithIndex()) { @@ -291,7 +297,7 @@ public class ResourceTreeViewer( 0 => "(none)", 1 => resourceNode.GamePath.ToString(), _ => "(multiple)", - }, false, hasGamePaths ? 0 : ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + }, false, hasGamePaths ? 0 : ImGuiSelectableFlags.Disabled, new Vector2(ImGui.GetContentRegionAvail().X, frameHeight)); if (hasGamePaths) { var allPaths = string.Join('\n', resourceNode.PossibleGamePaths); @@ -312,7 +318,7 @@ public class ResourceTreeViewer( using (var color = ImRaii.PushColor(ImGuiCol.Text, (hasMod ? ColorId.NewMod : ColorId.DisabledMod).Value())) { ImUtf8.Selectable(modName, false, ImGuiSelectableFlags.AllowItemOverlap, - new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + new Vector2(ImGui.GetContentRegionAvail().X, frameHeight)); } ImGui.SameLine(); @@ -322,7 +328,7 @@ public class ResourceTreeViewer( else { ImGui.Selectable(resourceNode.FullPath.ToPath(), false, ImGuiSelectableFlags.AllowItemOverlap, - new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + new Vector2(ImGui.GetContentRegionAvail().X, frameHeight)); } if (ImGui.IsItemClicked()) @@ -336,20 +342,17 @@ public class ResourceTreeViewer( else { ImUtf8.Selectable(GetPathStatusLabel(resourceNode.FullPathStatus), false, ImGuiSelectableFlags.Disabled, - new Vector2(ImGui.GetContentRegionAvail().X, cellHeight)); + new Vector2(ImGui.GetContentRegionAvail().X, frameHeight)); ImGuiUtil.HoverTooltip( $"{GetPathStatusDescription(resourceNode.FullPathStatus)}{GetAdditionalDataSuffix(resourceNode.AdditionalData)}"); } mutedColor.Dispose(); - if (actionCapacity > 0) - { - ImGui.TableNextColumn(); - using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, - ImGui.GetStyle().ItemSpacing with { X = 3 * ImGuiHelpers.GlobalScale }); - drawActions(resourceNode, new Vector2(frameHeight)); - } + ImGui.TableNextColumn(); + using var spacing = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, + ImGui.GetStyle().ItemSpacing with { X = 3 * ImGuiHelpers.GlobalScale }); + DrawActions(resourceNode, new Vector2(frameHeight)); if (unfolded) DrawNodes(resourceNode.Children, level + 1, unchecked(nodePathHash * 31), filterIcon); @@ -402,6 +405,51 @@ public class ResourceTreeViewer( || node.FullPath.InternalName.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase) || Array.Exists(node.PossibleGamePaths, path => path.Path.ToString().Contains(_nodeFilter, StringComparison.OrdinalIgnoreCase)); } + + void DrawActions(ResourceNode resourceNode, Vector2 buttonSize) + { + if (!_writableCache!.TryGetValue(resourceNode.FullPath, out var writable)) + { + var path = resourceNode.FullPath.ToPath(); + if (resourceNode.FullPath.IsRooted) + { + writable = new RawFileWritable(path); + } + else + { + var file = gameData.GetFile(path); + writable = file is null ? null : new RawGameFileWritable(file); + } + + _writableCache.Add(resourceNode.FullPath, writable); + } + + if (ImUtf8.IconButton(FontAwesomeIcon.Save, "Export this file."u8, buttonSize, + resourceNode.FullPath.FullName.Length is 0 || writable is null)) + { + var fullPathStr = resourceNode.FullPath.FullName; + var ext = resourceNode.PossibleGamePaths.Length == 1 + ? Path.GetExtension(resourceNode.GamePath.ToString()) + : Path.GetExtension(fullPathStr); + fileDialog.OpenSavePicker($"Export {Path.GetFileName(fullPathStr)} to...", ext, Path.GetFileNameWithoutExtension(fullPathStr), ext, + (success, name) => + { + if (!success) + return; + + try + { + compactor.WriteAllBytes(name, writable!.Write()); + } + catch (Exception e) + { + Penumbra.Log.Error($"Could not export {fullPathStr}:\n{e}"); + } + }, null, false); + } + + drawActions(resourceNode, writable, new Vector2(frameHeight)); + } } private static ReadOnlySpan GetPathStatusLabel(ResourceNode.PathStatus status) @@ -465,4 +513,22 @@ public class ResourceTreeViewer( Visible = 1, DescendentsOnly = 2, } + + private record RawFileWritable(string Path) : IWritable + { + public bool Valid + => true; + + public byte[] Write() + => File.ReadAllBytes(Path); + } + + private record RawGameFileWritable(FileResource FileResource) : IWritable + { + public bool Valid + => true; + + public byte[] Write() + => FileResource.Data; + } } diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs index 43b60716..6518ae67 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewerFactory.cs @@ -1,5 +1,7 @@ using Dalamud.Plugin.Services; +using OtterGui.Compression; using OtterGui.Services; +using Penumbra.GameData.Files; using Penumbra.Interop.ResourceTree; using Penumbra.Services; @@ -12,8 +14,11 @@ public class ResourceTreeViewerFactory( IncognitoService incognito, CommunicatorService communicator, PcpService pcpService, - IDataManager gameData) : IService + IDataManager gameData, + FileDialogService fileDialog, + FileCompactor compactor) : IService { - public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) - => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator, pcpService, gameData); + public ResourceTreeViewer Create(int actionCapacity, Action onRefresh, Action drawActions) + => new(config, treeFactory, changedItemDrawer, incognito, actionCapacity, onRefresh, drawActions, communicator, pcpService, gameData, + fileDialog, compactor); } From b3379a97105d37f685dd0686d89d0bf27c1c0807 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 30 Aug 2025 16:55:20 +0200 Subject: [PATCH 1329/1381] Stop redacting external paths --- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index 00003451..cb765fcf 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -37,7 +37,7 @@ public class ResourceTreeViewer( FileCompactor compactor) { private const ResourceTreeFactory.Flags ResourceTreeFactoryFlags = - ResourceTreeFactory.Flags.RedactExternalPaths | ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; + ResourceTreeFactory.Flags.WithUiData | ResourceTreeFactory.Flags.WithOwnership; private readonly HashSet _unfolded = []; From f3ec4b2e081a4cb477f7c85189ac1525586f97c7 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sat, 30 Aug 2025 19:19:07 +0200 Subject: [PATCH 1330/1381] Only display the file name and last dir for externals --- Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs index cb765fcf..ae450bec 100644 --- a/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs +++ b/Penumbra/UI/AdvancedWindow/ResourceTreeViewer.cs @@ -325,6 +325,18 @@ public class ResourceTreeViewer( ImGui.SetCursorPosX(textPos); ImUtf8.Text(resourceNode.ModRelativePath); } + else if (resourceNode.FullPath.IsRooted) + { + var path = resourceNode.FullPath.FullName; + var lastDirectorySeparator = path.LastIndexOf('\\'); + var secondLastDirectorySeparator = lastDirectorySeparator > 0 + ? path.LastIndexOf('\\', lastDirectorySeparator - 1) + : -1; + if (secondLastDirectorySeparator >= 0) + path = $"…{path.AsSpan(secondLastDirectorySeparator)}"; + ImGui.Selectable(path.AsSpan(), false, ImGuiSelectableFlags.AllowItemOverlap, + new Vector2(ImGui.GetContentRegionAvail().X, frameHeight)); + } else { ImGui.Selectable(resourceNode.FullPath.ToPath(), false, ImGuiSelectableFlags.AllowItemOverlap, From 5503bb32e059ed1438ebb139c5da6306e870f3b2 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 31 Aug 2025 04:13:56 +0200 Subject: [PATCH 1331/1381] CloudApi testing in Debug tab --- Penumbra/Interop/CloudApi.cs | 29 ++++++++++++++++++++++ Penumbra/UI/Tabs/Debug/DebugTab.cs | 39 ++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 Penumbra/Interop/CloudApi.cs diff --git a/Penumbra/Interop/CloudApi.cs b/Penumbra/Interop/CloudApi.cs new file mode 100644 index 00000000..9ec29fa5 --- /dev/null +++ b/Penumbra/Interop/CloudApi.cs @@ -0,0 +1,29 @@ +namespace Penumbra.Interop; + +public static unsafe partial class CloudApi +{ + private const int CfSyncRootInfoBasic = 0; + + public static bool IsCloudSynced(string path) + { + var buffer = stackalloc long[1]; + var hr = CfGetSyncRootInfoByPath(path, CfSyncRootInfoBasic, buffer, sizeof(long), out var length); + Penumbra.Log.Information($"{nameof(CfGetSyncRootInfoByPath)} returned HRESULT {hr}"); + if (hr < 0) + return false; + + if (length != sizeof(long)) + { + Penumbra.Log.Warning($"Expected {nameof(CfGetSyncRootInfoByPath)} to return {sizeof(long)} bytes, got {length} bytes"); + return false; + } + + Penumbra.Log.Information($"{nameof(CfGetSyncRootInfoByPath)} returned {{ SyncRootFileId = 0x{*buffer:X16} }}"); + + return true; + } + + [LibraryImport("cldapi.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int CfGetSyncRootInfoByPath(string filePath, int infoClass, void* infoBuffer, uint infoBufferLength, + out uint returnedLength); +} diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index d41dd25a..05f77e29 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -9,6 +9,7 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.UI.Agent; using Dalamud.Bindings.ImGui; +using Dalamud.Interface.Colors; using Microsoft.Extensions.DependencyInjection; using OtterGui; using OtterGui.Classes; @@ -41,6 +42,7 @@ using Penumbra.GameData.Data; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; using Penumbra.GameData.Files.StainMapStructs; +using Penumbra.Interop; using Penumbra.String.Classes; using Penumbra.UI.AdvancedWindow.Materials; @@ -206,6 +208,7 @@ public class DebugTab : Window, ITab, IUiService _hookOverrides.Draw(); DrawPlayerModelInfo(); _globalVariablesDrawer.Draw(); + DrawCloudApi(); DrawDebugTabIpc(); } @@ -1199,6 +1202,42 @@ public class DebugTab : Window, ITab, IUiService } + private string _cloudTesterPath = string.Empty; + private bool? _cloudTesterReturn; + private Exception? _cloudTesterError; + + private void DrawCloudApi() + { + if (!ImUtf8.CollapsingHeader("Cloud API"u8)) + return; + + using var id = ImRaii.PushId("CloudApiTester"u8); + + if (ImUtf8.InputText("Path"u8, ref _cloudTesterPath, flags: ImGuiInputTextFlags.EnterReturnsTrue)) + { + try + { + _cloudTesterReturn = CloudApi.IsCloudSynced(_cloudTesterPath); + _cloudTesterError = null; + } + catch (Exception e) + { + _cloudTesterReturn = null; + _cloudTesterError = e; + } + } + + if (_cloudTesterReturn.HasValue) + ImUtf8.Text($"Is Cloud Synced? {_cloudTesterReturn}"); + + if (_cloudTesterError is not null) + { + using var color = ImRaii.PushColor(ImGuiCol.Text, ImGuiColors.DalamudRed); + ImUtf8.Text($"{_cloudTesterError}"); + } + } + + /// Draw information about IPC options and availability. private void DrawDebugTabIpc() { From d59be1e660e26adce11664ffdbef5631e2511aeb Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 31 Aug 2025 05:25:37 +0200 Subject: [PATCH 1332/1381] Refine IsCloudSynced --- Penumbra/Interop/CloudApi.cs | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/Penumbra/Interop/CloudApi.cs b/Penumbra/Interop/CloudApi.cs index 9ec29fa5..603d4c9f 100644 --- a/Penumbra/Interop/CloudApi.cs +++ b/Penumbra/Interop/CloudApi.cs @@ -4,21 +4,39 @@ public static unsafe partial class CloudApi { private const int CfSyncRootInfoBasic = 0; + /// Determines whether a file or directory is cloud-synced using OneDrive or other providers that use the Cloud API. + /// Can be expensive. Callers should cache the result when relevant. public static bool IsCloudSynced(string path) { - var buffer = stackalloc long[1]; - var hr = CfGetSyncRootInfoByPath(path, CfSyncRootInfoBasic, buffer, sizeof(long), out var length); - Penumbra.Log.Information($"{nameof(CfGetSyncRootInfoByPath)} returned HRESULT {hr}"); + var buffer = stackalloc long[1]; + int hr; + uint length; + try + { + hr = CfGetSyncRootInfoByPath(path, CfSyncRootInfoBasic, buffer, sizeof(long), out length); + } + catch (DllNotFoundException) + { + Penumbra.Log.Debug($"{nameof(CfGetSyncRootInfoByPath)} threw DllNotFoundException"); + return false; + } + catch (EntryPointNotFoundException) + { + Penumbra.Log.Debug($"{nameof(CfGetSyncRootInfoByPath)} threw EntryPointNotFoundException"); + return false; + } + + Penumbra.Log.Debug($"{nameof(CfGetSyncRootInfoByPath)} returned HRESULT 0x{hr:X8}"); if (hr < 0) return false; if (length != sizeof(long)) { - Penumbra.Log.Warning($"Expected {nameof(CfGetSyncRootInfoByPath)} to return {sizeof(long)} bytes, got {length} bytes"); + Penumbra.Log.Debug($"Expected {nameof(CfGetSyncRootInfoByPath)} to return {sizeof(long)} bytes, got {length} bytes"); return false; } - Penumbra.Log.Information($"{nameof(CfGetSyncRootInfoByPath)} returned {{ SyncRootFileId = 0x{*buffer:X16} }}"); + Penumbra.Log.Debug($"{nameof(CfGetSyncRootInfoByPath)} returned {{ SyncRootFileId = 0x{*buffer:X16} }}"); return true; } From 2cf60b78cd73f01b6207325a2359663b39745079 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Sun, 31 Aug 2025 06:42:45 +0200 Subject: [PATCH 1333/1381] Reject and warn about cloud-synced base directories --- Penumbra/Mods/Manager/ModManager.cs | 4 ++++ Penumbra/Penumbra.cs | 13 ++++++++----- Penumbra/UI/Tabs/SettingsTab.cs | 13 +++++++++++++ 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/Penumbra/Mods/Manager/ModManager.cs b/Penumbra/Mods/Manager/ModManager.cs index 32dac049..77385bbd 100644 --- a/Penumbra/Mods/Manager/ModManager.cs +++ b/Penumbra/Mods/Manager/ModManager.cs @@ -1,5 +1,6 @@ using OtterGui.Services; using Penumbra.Communication; +using Penumbra.Interop; using Penumbra.Mods.Editor; using Penumbra.Mods.Manager.OptionEditor; using Penumbra.Services; @@ -303,6 +304,9 @@ public sealed class ModManager : ModStorage, IDisposable, IService if (!firstTime && _config.ModDirectory != BasePath.FullName) TriggerModDirectoryChange(BasePath.FullName, Valid); } + + if (CloudApi.IsCloudSynced(BasePath.FullName)) + Penumbra.Log.Warning($"Mod base directory {BasePath.FullName} is cloud-synced. This may cause issues."); } private void TriggerModDirectoryChange(string newPath, bool valid) diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index b22d049d..f036adc7 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -23,6 +23,7 @@ using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; using Penumbra.GameData; using Penumbra.GameData.Data; +using Penumbra.Interop; using Penumbra.Interop.Hooks; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Hooks.ResourceLoading; @@ -211,10 +212,11 @@ public class Penumbra : IDalamudPlugin public string GatherSupportInformation() { - var sb = new StringBuilder(10240); - var exists = _config.ModDirectory.Length > 0 && Directory.Exists(_config.ModDirectory); - var hdrEnabler = _services.GetService(); - var drive = exists ? new DriveInfo(new DirectoryInfo(_config.ModDirectory).Root.FullName) : null; + var sb = new StringBuilder(10240); + var exists = _config.ModDirectory.Length > 0 && Directory.Exists(_config.ModDirectory); + var cloudSynced = exists && CloudApi.IsCloudSynced(_config.ModDirectory); + var hdrEnabler = _services.GetService(); + var drive = exists ? new DriveInfo(new DirectoryInfo(_config.ModDirectory).Root.FullName) : null; sb.AppendLine("**Settings**"); sb.Append($"> **`Plugin Version: `** {_validityChecker.Version}\n"); sb.Append($"> **`Commit Hash: `** {_validityChecker.CommitHash}\n"); @@ -223,7 +225,8 @@ public class Penumbra : IDalamudPlugin sb.Append($"> **`Operating System: `** {(Dalamud.Utility.Util.IsWine() ? "Mac/Linux (Wine)" : "Windows")}\n"); if (Dalamud.Utility.Util.IsWine()) sb.Append($"> **`Locale Environment Variables:`** {CollectLocaleEnvironmentVariables()}\n"); - sb.Append($"> **`Root Directory: `** `{_config.ModDirectory}`, {(exists ? "Exists" : "Not Existing")}\n"); + sb.Append( + $"> **`Root Directory: `** `{_config.ModDirectory}`, {(exists ? "Exists" : "Not Existing")}{(cloudSynced ? ", Cloud-Synced" : "")}\n"); sb.Append( $"> **`Free Drive Space: `** {(drive != null ? Functions.HumanReadableSize(drive.AvailableFreeSpace) : "Unknown")}\n"); sb.Append($"> **`Game Data Files: `** {(_gameData.HasModifiedGameDataFiles ? "Modified" : "Pristine")}\n"); diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index ded56bb1..308cc471 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -14,6 +14,7 @@ using OtterGui.Text; using OtterGui.Widgets; using Penumbra.Api; using Penumbra.Collections; +using Penumbra.Interop; using Penumbra.Interop.Hooks.PostProcessing; using Penumbra.Interop.Services; using Penumbra.Mods.Manager; @@ -59,6 +60,9 @@ public class SettingsTab : ITab, IUiService private readonly TagButtons _sharedTags = new(); + private string _lastCloudSyncTestedPath = string.Empty; + private bool _lastCloudSyncTestResult = false; + public SettingsTab(IDalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, @@ -208,6 +212,15 @@ public class SettingsTab : ITab, IUiService if (IsSubPathOf(gameDir, newName)) return ("Path is not allowed to be inside your game folder.", false); + if (_lastCloudSyncTestedPath != newName) + { + _lastCloudSyncTestResult = CloudApi.IsCloudSynced(newName); + _lastCloudSyncTestedPath = newName; + } + + if (_lastCloudSyncTestResult) + return ("Path is not allowed to be cloud-synced.", false); + return selected ? ($"Press Enter or Click Here to Save (Current Directory: {old})", true) : ($"Click Here to Save (Current Directory: {old})", true); From ad1659caf637c6919f4cb3f03e918496cf5fc23b Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 2 Sep 2025 11:29:58 +0200 Subject: [PATCH 1334/1381] Update libraries. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.CrashHandler/Penumbra.CrashHandler.csproj | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Penumbra.csproj | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/OtterGui b/OtterGui index 4a9b71a9..f3544447 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 4a9b71a93e76aa5eed818542288329e34ec0dd89 +Subproject commit f354444776591ae423e2d8374aae346308d81424 diff --git a/Penumbra.Api b/Penumbra.Api index 953dd227..dd141317 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 953dd227afda6b3943b0b88cc965d8aee8a879b5 +Subproject commit dd14131793e5ae47cc8e9232f46469216017b5aa diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj index abcb8e3d..1b1f0a28 100644 --- a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/Penumbra.GameData b/Penumbra.GameData index 73010350..3450df1f 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 73010350338ecd7b98ad85d127bed08d7d8718d4 +Subproject commit 3450df1f377543a226ded705e3db9e77ed2a0510 diff --git a/Penumbra.String b/Penumbra.String index 878acce4..c8611a0c 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 878acce46e286867d6ef1f8ecedb390f7bac34fd +Subproject commit c8611a0c546b6b2ec29214ab319fc2c38fe74793 diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 3159b736..fa45ffbf 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,4 +1,4 @@ - + Penumbra absolute gangstas From 4e788f7c2bfb5bf04f8e22d6ac56b489ff6ad942 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 2 Sep 2025 11:51:59 +0200 Subject: [PATCH 1335/1381] Update sig. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 3450df1f..27893a85 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3450df1f377543a226ded705e3db9e77ed2a0510 +Subproject commit 27893a85adb57a301dd93fd2c7d318bfd4c12a0f From f5f6dd3246202a186ca205afec4d4673219a673a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 2 Sep 2025 16:12:01 +0200 Subject: [PATCH 1336/1381] Handle some TODOs. --- Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs | 3 +-- .../Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 4 ++-- Penumbra/Interop/Structs/StructExtensions.cs | 5 +---- Penumbra/Mods/Editor/ModMerger.cs | 1 - 5 files changed, 5 insertions(+), 10 deletions(-) diff --git a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs index e0eb7ec5..cdd82b95 100644 --- a/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs +++ b/Penumbra/Interop/Hooks/Animation/LoadTimelineResources.cs @@ -63,8 +63,7 @@ public sealed unsafe class LoadTimelineResources : FastHook**)timeline)[0][29](timeline); + var idx = timeline->GetOwningGameObjectIndex(); if (idx >= 0 && idx < objects.TotalCount) { var obj = objects[idx]; diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index b9c21556..dd708e51 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -434,7 +434,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private static MaterialResourceHandle* GetMaterialResourceHandle(ModelRendererStructs.UnkPayload* unkPayload) { // TODO ClientStructs-ify - var unkPointer = *(nint*)((nint)unkPayload->ModelResourceHandle + 0xE8) + unkPayload->UnkIndex * 0x24; + var unkPointer = unkPayload->ModelResourceHandle.*(nint*)((nint)unkPayload->ModelResourceHandle + 0xE8) + unkPayload->UnkIndex * 0x24; var materialIndex = *(ushort*)(unkPointer + 8); var material = unkPayload->Params->Model->Materials[materialIndex]; if (material == null) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 23fe26b8..345dd0fd 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -242,10 +242,10 @@ public class ResourceTree( } private unsafe void AddSkeleton(List nodes, ResolveContext context, CharacterBase* model, string prefix = "") - => AddSkeleton(nodes, context, model->EID, model->Skeleton, model->BonePhysicsModule, *(void**)((nint)model + 0x160), prefix); + => AddSkeleton(nodes, context, model->EID, model->Skeleton, model->BonePhysicsModule, model->BoneKineDriverModule, prefix); private unsafe void AddSkeleton(List nodes, ResolveContext context, void* eid, Skeleton* skeleton, BonePhysicsModule* physics, - void* kineDriver, string prefix = "") + BoneKineDriverModule* kineDriver, string prefix = "") { var eidNode = context.CreateNodeFromEid((ResourceHandle*)eid); if (eidNode != null) diff --git a/Penumbra/Interop/Structs/StructExtensions.cs b/Penumbra/Interop/Structs/StructExtensions.cs index 5a29bb6f..7349f6cc 100644 --- a/Penumbra/Interop/Structs/StructExtensions.cs +++ b/Penumbra/Interop/Structs/StructExtensions.cs @@ -66,11 +66,8 @@ internal static class StructExtensions public static unsafe CiByteString ResolveKdbPathAsByteString(ref this CharacterBase character, uint partialSkeletonIndex) { - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1561) - var vf80 = (delegate* unmanaged)((nint*)character.VirtualTable)[80]; var pathBuffer = stackalloc byte[CharacterBase.PathBufferSize]; - return ToOwnedByteString(vf80((CharacterBase*)Unsafe.AsPointer(ref character), pathBuffer, CharacterBase.PathBufferSize, - partialSkeletonIndex)); + return ToOwnedByteString(character.ResolveKdbPath(pathBuffer, CharacterBase.PathBufferSize, partialSkeletonIndex)); } private static unsafe CiByteString ToOwnedByteString(CStringPointer str) diff --git a/Penumbra/Mods/Editor/ModMerger.cs b/Penumbra/Mods/Editor/ModMerger.cs index bb84173a..eb270e13 100644 --- a/Penumbra/Mods/Editor/ModMerger.cs +++ b/Penumbra/Mods/Editor/ModMerger.cs @@ -372,7 +372,6 @@ public class ModMerger : IDisposable, IService } else { - // TODO DataContainer <> Option. var (group, _, _) = _editor.FindOrAddModGroup(result, originalGroup.Type, originalGroup.Name); var (option, _, _) = _editor.FindOrAddOption(group!, originalOption.GetName()); var folder = Path.Combine(dir.FullName, group!.Name, option!.Name); From 5a6e06df3ba6a7ed056199b03f540ac567a52be9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 2 Sep 2025 16:22:02 +0200 Subject: [PATCH 1337/1381] git is stupid --- .../Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs | 2 +- Penumbra/Interop/ResourceTree/ResourceTree.cs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs index dd708e51..b9c21556 100644 --- a/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs +++ b/Penumbra/Interop/Hooks/PostProcessing/ShaderReplacementFixer.cs @@ -434,7 +434,7 @@ public sealed unsafe class ShaderReplacementFixer : IDisposable, IRequiredServic private static MaterialResourceHandle* GetMaterialResourceHandle(ModelRendererStructs.UnkPayload* unkPayload) { // TODO ClientStructs-ify - var unkPointer = unkPayload->ModelResourceHandle.*(nint*)((nint)unkPayload->ModelResourceHandle + 0xE8) + unkPayload->UnkIndex * 0x24; + var unkPointer = *(nint*)((nint)unkPayload->ModelResourceHandle + 0xE8) + unkPayload->UnkIndex * 0x24; var materialIndex = *(ushort*)(unkPointer + 8); var material = unkPayload->Params->Model->Materials[materialIndex]; if (material == null) diff --git a/Penumbra/Interop/ResourceTree/ResourceTree.cs b/Penumbra/Interop/ResourceTree/ResourceTree.cs index 345dd0fd..1ebfe53d 100644 --- a/Penumbra/Interop/ResourceTree/ResourceTree.cs +++ b/Penumbra/Interop/ResourceTree/ResourceTree.cs @@ -261,8 +261,7 @@ public class ResourceTree( for (var i = 0; i < skeleton->PartialSkeletonCount; ++i) { var phybHandle = physics != null ? physics->BonePhysicsResourceHandles[i] : null; - // TODO ClientStructs-ify (aers/FFXIVClientStructs#1562) - var kdbHandle = kineDriver != null ? *(ResourceHandle**)((nint)kineDriver + 0x20 + 0x18 * i) : null; + var kdbHandle = kineDriver != null ? kineDriver->PartialSkeletonEntries[i].KineDriverResourceHandle : null; if (context.CreateNodeFromPartialSkeleton(&skeleton->PartialSkeletons[i], phybHandle, kdbHandle, (uint)i) is { } sklbNode) { if (context.Global.WithUiData) From 6348c4a639811786d2302ac021914dcd89a65a2b Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 2 Sep 2025 14:25:55 +0000 Subject: [PATCH 1338/1381] [CI] Updating repo.json for 1.5.1.2 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index e9a52799..9ff227b6 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.0", - "TestingAssemblyVersion": "1.5.1.0", + "AssemblyVersion": "1.5.1.2", + "TestingAssemblyVersion": "1.5.1.2", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.0/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.0/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.0/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From c3b00ff42613270e3a8452dcafebaa795b9c226b Mon Sep 17 00:00:00 2001 From: Stoia <23234609+StoiaCode@users.noreply.github.com> Date: Sat, 6 Sep 2025 14:22:18 +0200 Subject: [PATCH 1339/1381] Integrate FileWatcher HEAVY WIP --- Penumbra/Configuration.cs | 2 + Penumbra/Penumbra.cs | 2 + Penumbra/Services/FileWatcher.cs | 136 +++++++++++++++++++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 47 ++++++++++- 4 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 Penumbra/Services/FileWatcher.cs diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index f9cad217..500d5d57 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -53,6 +53,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; + public string WatchDirectory { get; set; } = string.Empty; public bool? UseCrashHandler { get; set; } = null; public bool OpenWindowAtStart { get; set; } = false; @@ -76,6 +77,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HideRedrawBar { get; set; } = false; public bool HideMachinistOffhandFromChangedItems { get; set; } = true; public bool DefaultTemporaryMode { get; set; } = false; + public bool EnableDirectoryWatch { get; set; } = false; public bool EnableCustomShapes { get; set; } = true; public PcpSettings PcpSettings = new(); public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index f036adc7..0f5703a3 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -44,6 +44,7 @@ public class Penumbra : IDalamudPlugin private readonly TempModManager _tempMods; private readonly TempCollectionManager _tempCollections; private readonly ModManager _modManager; + private readonly FileWatcher _fileWatcher; private readonly CollectionManager _collectionManager; private readonly Configuration _config; private readonly CharacterUtility _characterUtility; @@ -81,6 +82,7 @@ public class Penumbra : IDalamudPlugin _residentResources = _services.GetService(); _services.GetService(); // Initialize because not required anywhere else. _modManager = _services.GetService(); + _fileWatcher = _services.GetService(); _collectionManager = _services.GetService(); _tempCollections = _services.GetService(); _redrawService = _services.GetService(); diff --git a/Penumbra/Services/FileWatcher.cs b/Penumbra/Services/FileWatcher.cs new file mode 100644 index 00000000..8a2f9402 --- /dev/null +++ b/Penumbra/Services/FileWatcher.cs @@ -0,0 +1,136 @@ +using System.Threading.Channels; +using OtterGui.Services; +using Penumbra.Mods.Manager; + +namespace Penumbra.Services; +public class FileWatcher : IDisposable, IService +{ + private readonly FileSystemWatcher _fsw; + private readonly Channel _queue; + private readonly CancellationTokenSource _cts = new(); + private readonly Task _consumer; + private readonly ConcurrentDictionary _pending = new(StringComparer.OrdinalIgnoreCase); + private readonly ModImportManager _modImportManager; + private readonly Configuration _config; + private readonly bool _enabled; + + public FileWatcher(ModImportManager modImportManager, Configuration config) + { + _config = config; + _modImportManager = modImportManager; + _enabled = config.EnableDirectoryWatch; + + if (!_enabled) return; + + _queue = Channel.CreateBounded(new BoundedChannelOptions(256) + { + SingleReader = true, + SingleWriter = false, + FullMode = BoundedChannelFullMode.DropOldest + }); + + _fsw = new FileSystemWatcher(_config.WatchDirectory) + { + IncludeSubdirectories = false, + NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime, + InternalBufferSize = 32 * 1024 + }; + + // Only wake us for the exact patterns we care about + _fsw.Filters.Add("*.pmp"); + _fsw.Filters.Add("*.pcp"); + _fsw.Filters.Add("*.ttmp"); + _fsw.Filters.Add("*.ttmp2"); + + _fsw.Created += OnPath; + _fsw.Renamed += OnPath; + + _consumer = Task.Factory.StartNew( + () => ConsumerLoopAsync(_cts.Token), + _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); + + _fsw.EnableRaisingEvents = true; + } + + private void OnPath(object? sender, FileSystemEventArgs e) + { + // Cheap de-dupe: only queue once per filename until processed + if (!_enabled || !_pending.TryAdd(e.FullPath, 0)) return; + _ = _queue.Writer.TryWrite(e.FullPath); + } + + private async Task ConsumerLoopAsync(CancellationToken token) + { + if (!_enabled) return; + var reader = _queue.Reader; + while (await reader.WaitToReadAsync(token).ConfigureAwait(false)) + { + while (reader.TryRead(out var path)) + { + try + { + await ProcessOneAsync(path, token).ConfigureAwait(false); + } + catch (OperationCanceledException) { Penumbra.Log.Debug($"[FileWatcher] Canceled via Token."); } + catch (Exception ex) + { + Penumbra.Log.Debug($"[FileWatcher] Error during Processing: {ex}"); + } + finally + { + _pending.TryRemove(path, out _); + } + } + } + } + + private async Task ProcessOneAsync(string path, CancellationToken token) + { + // Downloads often finish via rename; file may be locked briefly. + // Wait until it exists and is readable; also require two stable size checks. + const int maxTries = 40; + long lastLen = -1; + + for (int i = 0; i < maxTries && !token.IsCancellationRequested; i++) + { + if (!File.Exists(path)) { await Task.Delay(100, token); continue; } + + try + { + var fi = new FileInfo(path); + var len = fi.Length; + if (len > 0 && len == lastLen) + { + _modImportManager.AddUnpack(path); + return; + } + + lastLen = len; + } + catch (IOException) { Penumbra.Log.Debug($"[FileWatcher] File is still being written to."); } + catch (UnauthorizedAccessException) { Penumbra.Log.Debug($"[FileWatcher] File is locked."); } + + await Task.Delay(150, token); + } + } + + public void UpdateDirectory(string newPath) + { + if (!_enabled || _fsw is null || !Directory.Exists(newPath) || string.IsNullOrWhiteSpace(newPath)) return; + + _fsw.EnableRaisingEvents = false; + _fsw.Path = newPath; + _fsw.EnableRaisingEvents = true; + } + + public void Dispose() + { + if (!_enabled) return; + _fsw.EnableRaisingEvents = false; + _cts.Cancel(); + _fsw.Dispose(); + _queue.Writer.TryComplete(); + try { _consumer.Wait(TimeSpan.FromSeconds(5)); } catch { /* swallow */ } + _cts.Dispose(); + } +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 308cc471..c84214f3 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -37,6 +37,7 @@ public class SettingsTab : ITab, IUiService private readonly Penumbra _penumbra; private readonly FileDialogService _fileDialog; private readonly ModManager _modManager; + private readonly FileWatcher _fileWatcher; private readonly ModExportManager _modExportManager; private readonly ModFileSystemSelector _selector; private readonly CharacterUtility _characterUtility; @@ -65,7 +66,7 @@ public class SettingsTab : ITab, IUiService public SettingsTab(IDalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, - CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, HttpApi httpApi, + CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, FileWatcher fileWatcher, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, @@ -82,6 +83,7 @@ public class SettingsTab : ITab, IUiService _characterUtility = characterUtility; _residentResources = residentResources; _modExportManager = modExportManager; + _fileWatcher = fileWatcher; _httpApi = httpApi; _dalamudSubstitutionProvider = dalamudSubstitutionProvider; _compactor = compactor; @@ -647,6 +649,10 @@ public class SettingsTab : ITab, IUiService DrawDefaultModImportFolder(); DrawPcpFolder(); DrawDefaultModExportPath(); + Checkbox("Enable Automatic Import of Mods from Directory", + "Enables a File Watcher that automatically listens for Mod files that enter, causing Penumbra to automatically import these mods.", + _config.EnableDirectoryWatch, v => _config.EnableDirectoryWatch = v); + DrawFileWatcherPath(); } @@ -726,6 +732,45 @@ public class SettingsTab : ITab, IUiService + "Keep this empty to use the root directory."); } + private string _tempWatchDirectory = string.Empty; + /// Draw input for the Automatic Mod import path. + private void DrawFileWatcherPath() + { + var tmp = _config.WatchDirectory; + var spacing = new Vector2(UiHelpers.ScaleX3); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, spacing); + ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); + if (ImGui.InputText("##fileWatchPath", ref tmp, 256)) + _tempWatchDirectory = tmp; + + if (ImGui.IsItemDeactivatedAfterEdit()) + _fileWatcher.UpdateDirectory(_tempWatchDirectory); + + ImGui.SameLine(); + if (ImGuiUtil.DrawDisabledButton($"{FontAwesomeIcon.Folder.ToIconString()}##fileWatch", UiHelpers.IconButtonSize, + "Select a directory via dialog.", false, true)) + { + var startDir = _config.WatchDirectory.Length > 0 && Directory.Exists(_config.WatchDirectory) + ? _config.WatchDirectory + : Directory.Exists(_config.ModDirectory) + ? _config.ModDirectory + : null; + _fileDialog.OpenFolderPicker("Choose Automatic Import Directory", (b, s) => + { + if (b) + { + _fileWatcher.UpdateDirectory(s); + _config.WatchDirectory = s; + _config.Save(); + } + }, startDir, false); + } + + style.Pop(); + ImGuiUtil.LabeledHelpMarker("Automatic Import Director", + "Choose the Directory the File Watcher listens to."); + } + /// Draw input for the default name to input as author into newly generated mods. private void DrawDefaultModAuthor() { From 97c8d82b338be04c513df4d15f1ef72a6fbbed4c Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 7 Sep 2025 10:45:28 +0200 Subject: [PATCH 1340/1381] Prevent default-named collection from being renamed and always put it at the top of the selector. --- Penumbra/UI/CollectionTab/CollectionPanel.cs | 44 ++++++++++--------- .../UI/CollectionTab/CollectionSelector.cs | 3 +- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index 26fa2b14..e41ceade 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -11,6 +11,7 @@ using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; using OtterGui.Raii; +using OtterGui.Text; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; @@ -222,26 +223,31 @@ public sealed class CollectionPanel( ImGui.EndGroup(); ImGui.SameLine(); ImGui.BeginGroup(); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); - var name = _newName ?? collection.Identity.Name; - var identifier = collection.Identity.Identifier; - var width = ImGui.GetContentRegionAvail().X; - var fileName = saveService.FileNames.CollectionFile(collection); - ImGui.SetNextItemWidth(width); - if (ImGui.InputText("##name", ref name, 128)) - _newName = name; - if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null && _newName != collection.Identity.Name) + var width = ImGui.GetContentRegionAvail().X; + using (ImRaii.Disabled(_collections.DefaultNamed == collection)) { - collection.Identity.Name = _newName; - saveService.QueueSave(new ModCollectionSave(mods, collection)); - selector.RestoreCollections(); - _newName = null; - } - else if (ImGui.IsItemDeactivated()) - { - _newName = null; + using var style = ImRaii.PushStyle(ImGuiStyleVar.ButtonTextAlign, new Vector2(0, 0.5f)); + var name = _newName ?? collection.Identity.Name; + ImGui.SetNextItemWidth(width); + if (ImGui.InputText("##name", ref name, 128)) + _newName = name; + if (ImGui.IsItemDeactivatedAfterEdit() && _newName != null && _newName != collection.Identity.Name) + { + collection.Identity.Name = _newName; + saveService.QueueSave(new ModCollectionSave(mods, collection)); + selector.RestoreCollections(); + _newName = null; + } + else if (ImGui.IsItemDeactivated()) + { + _newName = null; + } } + if (_collections.DefaultNamed == collection) + ImUtf8.HoverTooltip(ImGuiHoveredFlags.AllowWhenDisabled, "The Default collection can not be renamed."u8); + var identifier = collection.Identity.Identifier; + var fileName = saveService.FileNames.CollectionFile(collection); using (ImRaii.PushFont(UiBuilder.MonoFont)) { if (ImGui.Button(collection.Identity.Identifier, new Vector2(width, 0))) @@ -375,9 +381,7 @@ public sealed class CollectionPanel( ImGuiUtil.TextWrapped(type.ToDescription()); switch (type) { - case CollectionType.Default: - ImGui.TextUnformatted("Overruled by any other Assignment."); - break; + case CollectionType.Default: ImGui.TextUnformatted("Overruled by any other Assignment."); break; case CollectionType.Yourself: ImGuiUtil.DrawColoredText(("Overruled by ", 0), ("Individual ", ColorId.NewMod.Value()), ("Assignments.", 0)); break; diff --git a/Penumbra/UI/CollectionTab/CollectionSelector.cs b/Penumbra/UI/CollectionTab/CollectionSelector.cs index e54f994e..79254090 100644 --- a/Penumbra/UI/CollectionTab/CollectionSelector.cs +++ b/Penumbra/UI/CollectionTab/CollectionSelector.cs @@ -116,7 +116,8 @@ public sealed class CollectionSelector : ItemSelector, IDisposabl public void RestoreCollections() { Items.Clear(); - foreach (var c in _storage.OrderBy(c => c.Identity.Name)) + Items.Add(_storage.DefaultNamed); + foreach (var c in _storage.OrderBy(c => c.Identity.Name).Where(c => c != _storage.DefaultNamed)) Items.Add(c); SetFilterDirty(); SetCurrent(_active.Current); From e9f67a009be51377226186d61b10340683f5d3f3 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Fri, 19 Sep 2025 03:50:28 +0200 Subject: [PATCH 1341/1381] Lift "shaders known" restriction for saving materials --- Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs index e15d1c90..2c7c889e 100644 --- a/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs +++ b/Penumbra/UI/AdvancedWindow/Materials/MtrlTab.cs @@ -216,7 +216,7 @@ public sealed partial class MtrlTab : IWritable, IDisposable } public bool Valid - => _shadersKnown && Mtrl.Valid; + => Mtrl.Valid; // FIXME This should be _shadersKnown && Mtrl.Valid but the algorithm for _shadersKnown is flawed as of 7.2. public byte[] Write() { From a59689ebfe043b14d4c87f09bad3baddd10bea78 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Sep 2025 13:00:12 +0200 Subject: [PATCH 1342/1381] CS API update and add http API routes. --- Penumbra/Api/HttpApi.cs | 58 +++++++++++++++++++--- Penumbra/Interop/Services/RedrawService.cs | 4 +- 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index 8f8b44f4..dca9426a 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -5,6 +5,7 @@ using EmbedIO.WebApi; using OtterGui.Services; using Penumbra.Api.Api; using Penumbra.Api.Enums; +using Penumbra.Mods.Settings; namespace Penumbra.Api; @@ -13,13 +14,15 @@ public class HttpApi : IDisposable, IApiService private partial class Controller : WebApiController { // @formatter:off - [Route( HttpVerbs.Get, "/mods" )] public partial object? GetMods(); - [Route( HttpVerbs.Post, "/redraw" )] public partial Task Redraw(); - [Route( HttpVerbs.Post, "/redrawAll" )] public partial Task RedrawAll(); - [Route( HttpVerbs.Post, "/reloadmod" )] public partial Task ReloadMod(); - [Route( HttpVerbs.Post, "/installmod" )] public partial Task InstallMod(); - [Route( HttpVerbs.Post, "/openwindow" )] public partial void OpenWindow(); - [Route( HttpVerbs.Post, "/focusmod" )] public partial Task FocusMod(); + [Route( HttpVerbs.Get, "/moddirectory" )] public partial string GetModDirectory(); + [Route( HttpVerbs.Get, "/mods" )] public partial object? GetMods(); + [Route( HttpVerbs.Post, "/redraw" )] public partial Task Redraw(); + [Route( HttpVerbs.Post, "/redrawAll" )] public partial Task RedrawAll(); + [Route( HttpVerbs.Post, "/reloadmod" )] public partial Task ReloadMod(); + [Route( HttpVerbs.Post, "/installmod" )] public partial Task InstallMod(); + [Route( HttpVerbs.Post, "/openwindow" )] public partial void OpenWindow(); + [Route( HttpVerbs.Post, "/focusmod" )] public partial Task FocusMod(); + [Route( HttpVerbs.Post, "/setmodsettings")] public partial Task SetModSettings(); // @formatter:on } @@ -65,6 +68,12 @@ public class HttpApi : IDisposable, IApiService private partial class Controller(IPenumbraApi api, IFramework framework) { + public partial string GetModDirectory() + { + Penumbra.Log.Debug($"[HTTP] {nameof(GetModDirectory)} triggered."); + return api.PluginState.GetModDirectory(); + } + public partial object? GetMods() { Penumbra.Log.Debug($"[HTTP] {nameof(GetMods)} triggered."); @@ -116,6 +125,7 @@ public class HttpApi : IDisposable, IApiService Penumbra.Log.Debug($"[HTTP] {nameof(OpenWindow)} triggered."); api.Ui.OpenMainWindow(TabType.Mods, string.Empty, string.Empty); } + public async partial Task FocusMod() { var data = await HttpContext.GetRequestDataAsync().ConfigureAwait(false); @@ -124,6 +134,30 @@ public class HttpApi : IDisposable, IApiService api.Ui.OpenMainWindow(TabType.Mods, data.Path, data.Name); } + public async partial Task SetModSettings() + { + var data = await HttpContext.GetRequestDataAsync().ConfigureAwait(false); + Penumbra.Log.Debug($"[HTTP] {nameof(SetModSettings)} triggered."); + await framework.RunOnFrameworkThread(() => + { + var collection = data.CollectionId ?? api.Collection.GetCollection(ApiCollectionType.Current)!.Value.Id; + if (data.Inherit.HasValue) + { + api.ModSettings.TryInheritMod(collection, data.ModPath, data.ModName, data.Inherit.Value); + if (data.Inherit.Value) + return; + } + + if (data.State.HasValue) + api.ModSettings.TrySetMod(collection, data.ModPath, data.ModName, data.State.Value); + if (data.Priority.HasValue) + api.ModSettings.TrySetModPriority(collection, data.ModPath, data.ModName, data.Priority.Value.Value); + foreach (var (group, settings) in data.Settings ?? []) + api.ModSettings.TrySetModSettings(collection, data.ModPath, data.ModName, group, settings); + } + ).ConfigureAwait(false); + } + private record ModReloadData(string Path, string Name) { public ModReloadData() @@ -151,5 +185,15 @@ public class HttpApi : IDisposable, IApiService : this(string.Empty, RedrawType.Redraw, -1) { } } + + private record SetModSettingsData( + Guid? CollectionId, + string ModPath, + string ModName, + bool? Inherit, + bool? State, + ModPriority? Priority, + Dictionary>? Settings) + { } } } diff --git a/Penumbra/Interop/Services/RedrawService.cs b/Penumbra/Interop/Services/RedrawService.cs index 08e9ddf5..2d741277 100644 --- a/Penumbra/Interop/Services/RedrawService.cs +++ b/Penumbra/Interop/Services/RedrawService.cs @@ -421,9 +421,9 @@ public sealed unsafe partial class RedrawService : IDisposable return; - foreach (ref var f in currentTerritory->Furniture) + foreach (ref var f in currentTerritory->FurnitureManager.FurnitureMemory) { - var gameObject = f.Index >= 0 ? currentTerritory->HousingObjectManager.Objects[f.Index].Value : null; + var gameObject = f.Index >= 0 ? currentTerritory->FurnitureManager.ObjectManager.ObjectArray.Objects[f.Index].Value : null; if (gameObject == null) continue; From a0c3e820b0e9be6080f83d10447971bdaba5681d Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 27 Sep 2025 11:02:39 +0000 Subject: [PATCH 1343/1381] [CI] Updating repo.json for testing_1.5.1.3 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 9ff227b6..bac039b8 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.1.2", - "TestingAssemblyVersion": "1.5.1.2", + "TestingAssemblyVersion": "1.5.1.3", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.3/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From c6b596169c0f970a7e4ee7bdf21f89347de8c0d3 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 27 Sep 2025 14:01:21 +0200 Subject: [PATCH 1344/1381] Add default constructor. --- Penumbra/Api/HttpApi.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index dca9426a..995a6cd7 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -194,6 +194,10 @@ public class HttpApi : IDisposable, IApiService bool? State, ModPriority? Priority, Dictionary>? Settings) - { } + { + public SetModSettingsData() + : this(null, string.Empty, string.Empty, null, null, null, null) + {} + } } } From eb53f04c6b2b88806227981fdbc8c53f193e0ada Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 27 Sep 2025 12:03:35 +0000 Subject: [PATCH 1345/1381] [CI] Updating repo.json for testing_1.5.1.4 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index bac039b8..f404b8af 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.1.2", - "TestingAssemblyVersion": "1.5.1.3", + "TestingAssemblyVersion": "1.5.1.4", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.3/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.4/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 699745413e224f2b55e9eb7bf014e13c821408c9 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sun, 28 Sep 2025 12:40:52 +0200 Subject: [PATCH 1346/1381] Make priority an int. --- Penumbra/Api/HttpApi.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Penumbra/Api/HttpApi.cs b/Penumbra/Api/HttpApi.cs index 995a6cd7..79348a88 100644 --- a/Penumbra/Api/HttpApi.cs +++ b/Penumbra/Api/HttpApi.cs @@ -151,7 +151,7 @@ public class HttpApi : IDisposable, IApiService if (data.State.HasValue) api.ModSettings.TrySetMod(collection, data.ModPath, data.ModName, data.State.Value); if (data.Priority.HasValue) - api.ModSettings.TrySetModPriority(collection, data.ModPath, data.ModName, data.Priority.Value.Value); + api.ModSettings.TrySetModPriority(collection, data.ModPath, data.ModName, data.Priority.Value); foreach (var (group, settings) in data.Settings ?? []) api.ModSettings.TrySetModSettings(collection, data.ModPath, data.ModName, group, settings); } @@ -192,7 +192,7 @@ public class HttpApi : IDisposable, IApiService string ModName, bool? Inherit, bool? State, - ModPriority? Priority, + int? Priority, Dictionary>? Settings) { public SetModSettingsData() From 23c0506cb875f8613513f4169630eeb6549cc6ef Mon Sep 17 00:00:00 2001 From: Actions User Date: Sun, 28 Sep 2025 10:43:01 +0000 Subject: [PATCH 1347/1381] [CI] Updating repo.json for testing_1.5.1.5 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index f404b8af..d6a7dd4c 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.1.2", - "TestingAssemblyVersion": "1.5.1.4", + "TestingAssemblyVersion": "1.5.1.5", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.4/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.5/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From 0881dfde8a26ebcea56bab0c9c5eadeca8884039 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 7 Oct 2025 12:27:35 +0200 Subject: [PATCH 1348/1381] Update signatures. --- Penumbra.GameData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 27893a85..7e7d510a 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 27893a85adb57a301dd93fd2c7d318bfd4c12a0f +Subproject commit 7e7d510a2ce78e2af78312a8b2215c23bf43a56f From 049baa4fe49c0386532dd096663fc4368fd9dcf8 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Tue, 7 Oct 2025 12:42:54 +0200 Subject: [PATCH 1349/1381] Again. --- Penumbra.GameData | 2 +- Penumbra/Penumbra.cs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 7e7d510a..3baace73 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 7e7d510a2ce78e2af78312a8b2215c23bf43a56f +Subproject commit 3baace73c828271dcb71a8156e3e7b91e1dd12ae diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index f036adc7..d433a0fb 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -21,7 +21,6 @@ using Penumbra.UI; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; -using Penumbra.GameData; using Penumbra.GameData.Data; using Penumbra.Interop; using Penumbra.Interop.Hooks; From 300e0e6d8484f44c00a9320b48e068b10ea2ab1c Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 7 Oct 2025 10:45:04 +0000 Subject: [PATCH 1350/1381] [CI] Updating repo.json for 1.5.1.6 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index d6a7dd4c..2a31b75e 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.2", - "TestingAssemblyVersion": "1.5.1.5", + "AssemblyVersion": "1.5.1.6", + "TestingAssemblyVersion": "1.5.1.6", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.5/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.2/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From ebbe957c95d44d2b1569c4e22b3a7cd672246385 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 11 Oct 2025 20:09:52 +0200 Subject: [PATCH 1351/1381] Remove login screen log spam. --- Penumbra/Interop/PathResolving/CollectionResolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/PathResolving/CollectionResolver.cs b/Penumbra/Interop/PathResolving/CollectionResolver.cs index 10795e6d..136393d4 100644 --- a/Penumbra/Interop/PathResolving/CollectionResolver.cs +++ b/Penumbra/Interop/PathResolving/CollectionResolver.cs @@ -137,7 +137,7 @@ public sealed unsafe class CollectionResolver( { var item = charaEntry.Value; var identifier = actors.CreatePlayer(new ByteString(item->Name), item->HomeWorldId); - Penumbra.Log.Verbose( + Penumbra.Log.Excessive( $"Identified {identifier.Incognito(null)} in cutscene for actor {idx + 200} at 0x{(ulong)gameObject:X} of race {(gameObject->IsCharacter() ? ((Character*)gameObject)->DrawData.CustomizeData.Race.ToString() : "Unknown")}."); if (identifier.IsValid && CollectionByIdentifier(identifier) is { } coll) { From 7ed81a982365fa99164a2ab5d8cdb6801987c0d7 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Oct 2025 17:53:02 +0200 Subject: [PATCH 1352/1381] Update OtterGui. --- OtterGui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OtterGui b/OtterGui index f3544447..9af1e5fc 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit f354444776591ae423e2d8374aae346308d81424 +Subproject commit 9af1e5fce4c13ef98842807d4f593dec8ae80c87 From f05cb52da2a77dc8b6bcd5cad3dd4b32d97febb3 Mon Sep 17 00:00:00 2001 From: Stoia <23234609+StoiaCode@users.noreply.github.com> Date: Wed, 22 Oct 2025 18:20:44 +0200 Subject: [PATCH 1353/1381] Add Option to notify instead of auto install. And General Fixes --- Penumbra/Configuration.cs | 1 + Penumbra/Services/FileWatcher.cs | 42 +++++++++++++++++++++-------- Penumbra/Services/MessageService.cs | 32 ++++++++++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 11 +++++--- 4 files changed, 72 insertions(+), 14 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index 500d5d57..e337997b 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -78,6 +78,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public bool HideMachinistOffhandFromChangedItems { get; set; } = true; public bool DefaultTemporaryMode { get; set; } = false; public bool EnableDirectoryWatch { get; set; } = false; + public bool EnableAutomaticModImport { get; set; } = false; public bool EnableCustomShapes { get; set; } = true; public PcpSettings PcpSettings = new(); public RenameField ShowRename { get; set; } = RenameField.BothDataPrio; diff --git a/Penumbra/Services/FileWatcher.cs b/Penumbra/Services/FileWatcher.cs index 8a2f9402..e7172f58 100644 --- a/Penumbra/Services/FileWatcher.cs +++ b/Penumbra/Services/FileWatcher.cs @@ -1,5 +1,6 @@ using System.Threading.Channels; using OtterGui.Services; +using Penumbra.Services; using Penumbra.Mods.Manager; namespace Penumbra.Services; @@ -11,16 +12,16 @@ public class FileWatcher : IDisposable, IService private readonly Task _consumer; private readonly ConcurrentDictionary _pending = new(StringComparer.OrdinalIgnoreCase); private readonly ModImportManager _modImportManager; + private readonly MessageService _messageService; private readonly Configuration _config; - private readonly bool _enabled; - public FileWatcher(ModImportManager modImportManager, Configuration config) + public FileWatcher(ModImportManager modImportManager, MessageService messageService, Configuration config) { - _config = config; _modImportManager = modImportManager; - _enabled = config.EnableDirectoryWatch; + _messageService = messageService; + _config = config; - if (!_enabled) return; + if (!_config.EnableDirectoryWatch) return; _queue = Channel.CreateBounded(new BoundedChannelOptions(256) { @@ -55,13 +56,13 @@ public class FileWatcher : IDisposable, IService private void OnPath(object? sender, FileSystemEventArgs e) { // Cheap de-dupe: only queue once per filename until processed - if (!_enabled || !_pending.TryAdd(e.FullPath, 0)) return; + if (!_config.EnableDirectoryWatch || !_pending.TryAdd(e.FullPath, 0)) return; _ = _queue.Writer.TryWrite(e.FullPath); } private async Task ConsumerLoopAsync(CancellationToken token) { - if (!_enabled) return; + if (!_config.EnableDirectoryWatch) return; var reader = _queue.Reader; while (await reader.WaitToReadAsync(token).ConfigureAwait(false)) { @@ -101,8 +102,27 @@ public class FileWatcher : IDisposable, IService var len = fi.Length; if (len > 0 && len == lastLen) { - _modImportManager.AddUnpack(path); - return; + if (_config.EnableAutomaticModImport) + { + _modImportManager.AddUnpack(path); + return; + } + else + { + var invoked = false; + Action installRequest = args => + { + if (invoked) return; + invoked = true; + _modImportManager.AddUnpack(path); + }; + + _messageService.PrintModFoundInfo( + Path.GetFileNameWithoutExtension(path), + installRequest); + + return; + } } lastLen = len; @@ -116,7 +136,7 @@ public class FileWatcher : IDisposable, IService public void UpdateDirectory(string newPath) { - if (!_enabled || _fsw is null || !Directory.Exists(newPath) || string.IsNullOrWhiteSpace(newPath)) return; + if (!_config.EnableDirectoryWatch || _fsw is null || !Directory.Exists(newPath) || string.IsNullOrWhiteSpace(newPath)) return; _fsw.EnableRaisingEvents = false; _fsw.Path = newPath; @@ -125,7 +145,7 @@ public class FileWatcher : IDisposable, IService public void Dispose() { - if (!_enabled) return; + if (!_config.EnableDirectoryWatch) return; _fsw.EnableRaisingEvents = false; _cts.Cancel(); _fsw.Dispose(); diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index 70ccf47b..6c13fc38 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -1,19 +1,44 @@ +using Dalamud.Bindings.ImGui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; +using Dalamud.Interface.ImGuiNotification.EventArgs; using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; using OtterGui.Log; using OtterGui.Services; +using OtterGui.Text; using Penumbra.GameData.Data; using Penumbra.Mods.Manager; using Penumbra.String.Classes; +using static OtterGui.Classes.MessageService; using Notification = OtterGui.Classes.Notification; namespace Penumbra.Services; +public class InstallNotification(string message, Action installRequest) : IMessage +{ + private readonly Action _installRequest = installRequest; + private bool _invoked = false; + + public string Message { get; } = message; + + public NotificationType NotificationType => NotificationType.Info; + + public uint NotificationDuration => 10000; + + public void OnNotificationActions(INotificationDrawArgs args) + { + if (ImUtf8.ButtonEx("Install"u8, "Install this mod."u8, disabled: _invoked)) + { + _installRequest(true); + _invoked = true; + } + } +} + public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INotificationManager notificationManager) : OtterGui.Classes.MessageService(log, builder, chat, notificationManager), IService { @@ -55,4 +80,11 @@ public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INoti $"Cowardly refusing to load replacement for {originalGamePath.Filename().ToString().ToLowerInvariant()} by {mod.Name}{(messageComplement.Length > 0 ? ":\n" : ".")}{messageComplement}", NotificationType.Warning, 10000)); } + + public void PrintModFoundInfo(string fileName, Action installRequest) + { + AddMessage( + new InstallNotification($"A new mod has been found: {fileName}", installRequest) + ); + } } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index c84214f3..217b6788 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -53,6 +53,7 @@ public class SettingsTab : ITab, IUiService private readonly MigrationSectionDrawer _migrationDrawer; private readonly CollectionAutoSelector _autoSelector; private readonly CleanupService _cleanupService; + private readonly MessageService _messageService; private readonly AttributeHook _attributeHook; private readonly PcpService _pcpService; @@ -69,7 +70,7 @@ public class SettingsTab : ITab, IUiService CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, FileWatcher fileWatcher, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, - MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, + MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, MessageService messageService, AttributeHook attributeHook, PcpService pcpService) { _pluginInterface = pluginInterface; @@ -96,6 +97,7 @@ public class SettingsTab : ITab, IUiService _migrationDrawer = migrationDrawer; _autoSelector = autoSelector; _cleanupService = cleanupService; + _messageService = messageService; _attributeHook = attributeHook; _pcpService = pcpService; } @@ -649,9 +651,12 @@ public class SettingsTab : ITab, IUiService DrawDefaultModImportFolder(); DrawPcpFolder(); DrawDefaultModExportPath(); - Checkbox("Enable Automatic Import of Mods from Directory", - "Enables a File Watcher that automatically listens for Mod files that enter, causing Penumbra to automatically import these mods.", + Checkbox("Enable Directory Watcher", + "Enables a File Watcher that automatically listens for Mod files that enter, causing Penumbra to open a Popup to import these mods.", _config.EnableDirectoryWatch, v => _config.EnableDirectoryWatch = v); + Checkbox("Enable Fully Automatic Import", + "Uses the File Watcher in order to not just open a Popup, but fully automatically import new mods.", + _config.EnableAutomaticModImport, v => _config.EnableAutomaticModImport = v); DrawFileWatcherPath(); } From cbedc878b94ceda8cc91105d5b2456b76bda2fdb Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 22 Oct 2025 21:56:16 +0200 Subject: [PATCH 1354/1381] Slight cleanup and autoformat. --- Penumbra/Configuration.cs | 2 +- Penumbra/Penumbra.cs | 2 - Penumbra/Services/FileWatcher.cs | 91 +++++++++++++++++++---------- Penumbra/Services/MessageService.cs | 3 +- Penumbra/UI/Tabs/SettingsTab.cs | 8 +-- 5 files changed, 66 insertions(+), 40 deletions(-) diff --git a/Penumbra/Configuration.cs b/Penumbra/Configuration.cs index e337997b..2991230e 100644 --- a/Penumbra/Configuration.cs +++ b/Penumbra/Configuration.cs @@ -53,7 +53,7 @@ public class Configuration : IPluginConfiguration, ISavable, IService public string ModDirectory { get; set; } = string.Empty; public string ExportDirectory { get; set; } = string.Empty; - public string WatchDirectory { get; set; } = string.Empty; + public string WatchDirectory { get; set; } = string.Empty; public bool? UseCrashHandler { get; set; } = null; public bool OpenWindowAtStart { get; set; } = false; diff --git a/Penumbra/Penumbra.cs b/Penumbra/Penumbra.cs index 8ed2c585..d433a0fb 100644 --- a/Penumbra/Penumbra.cs +++ b/Penumbra/Penumbra.cs @@ -43,7 +43,6 @@ public class Penumbra : IDalamudPlugin private readonly TempModManager _tempMods; private readonly TempCollectionManager _tempCollections; private readonly ModManager _modManager; - private readonly FileWatcher _fileWatcher; private readonly CollectionManager _collectionManager; private readonly Configuration _config; private readonly CharacterUtility _characterUtility; @@ -81,7 +80,6 @@ public class Penumbra : IDalamudPlugin _residentResources = _services.GetService(); _services.GetService(); // Initialize because not required anywhere else. _modManager = _services.GetService(); - _fileWatcher = _services.GetService(); _collectionManager = _services.GetService(); _tempCollections = _services.GetService(); _redrawService = _services.GetService(); diff --git a/Penumbra/Services/FileWatcher.cs b/Penumbra/Services/FileWatcher.cs index e7172f58..141825f5 100644 --- a/Penumbra/Services/FileWatcher.cs +++ b/Penumbra/Services/FileWatcher.cs @@ -1,40 +1,41 @@ using System.Threading.Channels; using OtterGui.Services; -using Penumbra.Services; using Penumbra.Mods.Manager; namespace Penumbra.Services; + public class FileWatcher : IDisposable, IService { - private readonly FileSystemWatcher _fsw; - private readonly Channel _queue; - private readonly CancellationTokenSource _cts = new(); - private readonly Task _consumer; - private readonly ConcurrentDictionary _pending = new(StringComparer.OrdinalIgnoreCase); - private readonly ModImportManager _modImportManager; - private readonly MessageService _messageService; - private readonly Configuration _config; + private readonly FileSystemWatcher _fsw; + private readonly Channel _queue; + private readonly CancellationTokenSource _cts = new(); + private readonly Task _consumer; + private readonly ConcurrentDictionary _pending = new(StringComparer.OrdinalIgnoreCase); + private readonly ModImportManager _modImportManager; + private readonly MessageService _messageService; + private readonly Configuration _config; public FileWatcher(ModImportManager modImportManager, MessageService messageService, Configuration config) { _modImportManager = modImportManager; - _messageService = messageService; - _config = config; + _messageService = messageService; + _config = config; - if (!_config.EnableDirectoryWatch) return; + if (!_config.EnableDirectoryWatch) + return; _queue = Channel.CreateBounded(new BoundedChannelOptions(256) { SingleReader = true, SingleWriter = false, - FullMode = BoundedChannelFullMode.DropOldest + FullMode = BoundedChannelFullMode.DropOldest, }); _fsw = new FileSystemWatcher(_config.WatchDirectory) { IncludeSubdirectories = false, - NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime, - InternalBufferSize = 32 * 1024 + NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime, + InternalBufferSize = 32 * 1024, }; // Only wake us for the exact patterns we care about @@ -56,13 +57,17 @@ public class FileWatcher : IDisposable, IService private void OnPath(object? sender, FileSystemEventArgs e) { // Cheap de-dupe: only queue once per filename until processed - if (!_config.EnableDirectoryWatch || !_pending.TryAdd(e.FullPath, 0)) return; + if (!_config.EnableDirectoryWatch || !_pending.TryAdd(e.FullPath, 0)) + return; + _ = _queue.Writer.TryWrite(e.FullPath); } private async Task ConsumerLoopAsync(CancellationToken token) { - if (!_config.EnableDirectoryWatch) return; + if (!_config.EnableDirectoryWatch) + return; + var reader = _queue.Reader; while (await reader.WaitToReadAsync(token).ConfigureAwait(false)) { @@ -72,7 +77,10 @@ public class FileWatcher : IDisposable, IService { await ProcessOneAsync(path, token).ConfigureAwait(false); } - catch (OperationCanceledException) { Penumbra.Log.Debug($"[FileWatcher] Canceled via Token."); } + catch (OperationCanceledException) + { + Penumbra.Log.Debug($"[FileWatcher] Canceled via Token."); + } catch (Exception ex) { Penumbra.Log.Debug($"[FileWatcher] Error during Processing: {ex}"); @@ -90,15 +98,19 @@ public class FileWatcher : IDisposable, IService // Downloads often finish via rename; file may be locked briefly. // Wait until it exists and is readable; also require two stable size checks. const int maxTries = 40; - long lastLen = -1; + long lastLen = -1; - for (int i = 0; i < maxTries && !token.IsCancellationRequested; i++) + for (var i = 0; i < maxTries && !token.IsCancellationRequested; i++) { - if (!File.Exists(path)) { await Task.Delay(100, token); continue; } + if (!File.Exists(path)) + { + await Task.Delay(100, token); + continue; + } try { - var fi = new FileInfo(path); + var fi = new FileInfo(path); var len = fi.Length; if (len > 0 && len == lastLen) { @@ -112,7 +124,9 @@ public class FileWatcher : IDisposable, IService var invoked = false; Action installRequest = args => { - if (invoked) return; + if (invoked) + return; + invoked = true; _modImportManager.AddUnpack(path); }; @@ -122,13 +136,19 @@ public class FileWatcher : IDisposable, IService installRequest); return; - } + } } lastLen = len; } - catch (IOException) { Penumbra.Log.Debug($"[FileWatcher] File is still being written to."); } - catch (UnauthorizedAccessException) { Penumbra.Log.Debug($"[FileWatcher] File is locked."); } + catch (IOException) + { + Penumbra.Log.Debug($"[FileWatcher] File is still being written to."); + } + catch (UnauthorizedAccessException) + { + Penumbra.Log.Debug($"[FileWatcher] File is locked."); + } await Task.Delay(150, token); } @@ -136,21 +156,32 @@ public class FileWatcher : IDisposable, IService public void UpdateDirectory(string newPath) { - if (!_config.EnableDirectoryWatch || _fsw is null || !Directory.Exists(newPath) || string.IsNullOrWhiteSpace(newPath)) return; + if (!_config.EnableDirectoryWatch || _fsw is null || !Directory.Exists(newPath) || string.IsNullOrWhiteSpace(newPath)) + return; _fsw.EnableRaisingEvents = false; - _fsw.Path = newPath; + _fsw.Path = newPath; _fsw.EnableRaisingEvents = true; } public void Dispose() { - if (!_config.EnableDirectoryWatch) return; + if (!_config.EnableDirectoryWatch) + return; + _fsw.EnableRaisingEvents = false; _cts.Cancel(); _fsw.Dispose(); _queue.Writer.TryComplete(); - try { _consumer.Wait(TimeSpan.FromSeconds(5)); } catch { /* swallow */ } + try + { + _consumer.Wait(TimeSpan.FromSeconds(5)); + } + catch + { + /* swallow */ + } + _cts.Dispose(); } } diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index 6c13fc38..3dc6a90c 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -20,7 +20,6 @@ namespace Penumbra.Services; public class InstallNotification(string message, Action installRequest) : IMessage { - private readonly Action _installRequest = installRequest; private bool _invoked = false; public string Message { get; } = message; @@ -33,7 +32,7 @@ public class InstallNotification(string message, Action installRequest) : { if (ImUtf8.ButtonEx("Install"u8, "Install this mod."u8, disabled: _invoked)) { - _installRequest(true); + installRequest(true); _invoked = true; } } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 217b6788..46f4d38f 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -53,7 +53,6 @@ public class SettingsTab : ITab, IUiService private readonly MigrationSectionDrawer _migrationDrawer; private readonly CollectionAutoSelector _autoSelector; private readonly CleanupService _cleanupService; - private readonly MessageService _messageService; private readonly AttributeHook _attributeHook; private readonly PcpService _pcpService; @@ -70,7 +69,7 @@ public class SettingsTab : ITab, IUiService CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, FileWatcher fileWatcher, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, - MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, MessageService messageService, + MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, AttributeHook attributeHook, PcpService pcpService) { _pluginInterface = pluginInterface; @@ -97,7 +96,6 @@ public class SettingsTab : ITab, IUiService _migrationDrawer = migrationDrawer; _autoSelector = autoSelector; _cleanupService = cleanupService; - _messageService = messageService; _attributeHook = attributeHook; _pcpService = pcpService; } @@ -652,10 +650,10 @@ public class SettingsTab : ITab, IUiService DrawPcpFolder(); DrawDefaultModExportPath(); Checkbox("Enable Directory Watcher", - "Enables a File Watcher that automatically listens for Mod files that enter, causing Penumbra to open a Popup to import these mods.", + "Enables a File Watcher that automatically listens for Mod files that enter a specified directory, causing Penumbra to open a popup to import these mods.", _config.EnableDirectoryWatch, v => _config.EnableDirectoryWatch = v); Checkbox("Enable Fully Automatic Import", - "Uses the File Watcher in order to not just open a Popup, but fully automatically import new mods.", + "Uses the File Watcher in order to skip the query popup and automatically import any new mods.", _config.EnableAutomaticModImport, v => _config.EnableAutomaticModImport = v); DrawFileWatcherPath(); } From 5bf901d0c45f7c0384480387cab03eb626d25899 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 Oct 2025 17:30:29 +0200 Subject: [PATCH 1355/1381] Update actorobjectmanager when setting cutscene index. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.GameData | 2 +- Penumbra/Interop/PathResolving/CutsceneService.cs | 1 + 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/OtterGui b/OtterGui index 9af1e5fc..a63f6735 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 9af1e5fce4c13ef98842807d4f593dec8ae80c87 +Subproject commit a63f6735cf4bed4f7502a022a10378607082b770 diff --git a/Penumbra.Api b/Penumbra.Api index dd141317..c23ee05c 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit dd14131793e5ae47cc8e9232f46469216017b5aa +Subproject commit c23ee05c1e9fa103eaa52e6aa7e855ef568ee669 diff --git a/Penumbra.GameData b/Penumbra.GameData index 3baace73..283d51f6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3baace73c828271dcb71a8156e3e7b91e1dd12ae +Subproject commit 283d51f6f6c7721a810548d95ba83eef2484e17e diff --git a/Penumbra/Interop/PathResolving/CutsceneService.cs b/Penumbra/Interop/PathResolving/CutsceneService.cs index 6be19c46..97e64f84 100644 --- a/Penumbra/Interop/PathResolving/CutsceneService.cs +++ b/Penumbra/Interop/PathResolving/CutsceneService.cs @@ -75,6 +75,7 @@ public sealed class CutsceneService : IRequiredService, IDisposable return false; _copiedCharacters[copyIdx - CutsceneStartIdx] = (short)parentIdx; + _objects.InvokeRequiredUpdates(); return true; } From 912c183fc6e05e58920552ff902078f4accbbde0 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 23 Oct 2025 23:45:20 +0200 Subject: [PATCH 1356/1381] Improve file watcher. --- Penumbra.GameData | 2 +- Penumbra/Services/FileWatcher.cs | 200 +++++++++++++---------- Penumbra/Services/InstallNotification.cs | 39 +++++ Penumbra/Services/MessageService.cs | 31 ---- Penumbra/UI/Tabs/SettingsTab.cs | 26 +-- 5 files changed, 165 insertions(+), 133 deletions(-) create mode 100644 Penumbra/Services/InstallNotification.cs diff --git a/Penumbra.GameData b/Penumbra.GameData index 283d51f6..d889f9ef 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 283d51f6f6c7721a810548d95ba83eef2484e17e +Subproject commit d889f9ef918514a46049725052d378b441915b00 diff --git a/Penumbra/Services/FileWatcher.cs b/Penumbra/Services/FileWatcher.cs index 141825f5..1d572f05 100644 --- a/Penumbra/Services/FileWatcher.cs +++ b/Penumbra/Services/FileWatcher.cs @@ -1,37 +1,69 @@ -using System.Threading.Channels; -using OtterGui.Services; +using OtterGui.Services; using Penumbra.Mods.Manager; namespace Penumbra.Services; public class FileWatcher : IDisposable, IService { - private readonly FileSystemWatcher _fsw; - private readonly Channel _queue; - private readonly CancellationTokenSource _cts = new(); - private readonly Task _consumer; + // TODO: use ConcurrentSet when it supports comparers in Luna. private readonly ConcurrentDictionary _pending = new(StringComparer.OrdinalIgnoreCase); private readonly ModImportManager _modImportManager; private readonly MessageService _messageService; private readonly Configuration _config; + private bool _pausedConsumer; + private FileSystemWatcher? _fsw; + private CancellationTokenSource? _cts = new(); + private Task? _consumer; + public FileWatcher(ModImportManager modImportManager, MessageService messageService, Configuration config) { _modImportManager = modImportManager; _messageService = messageService; _config = config; - if (!_config.EnableDirectoryWatch) + if (_config.EnableDirectoryWatch) + { + SetupFileWatcher(_config.WatchDirectory); + SetupConsumerTask(); + } + } + + public void Toggle(bool value) + { + if (_config.EnableDirectoryWatch == value) return; - _queue = Channel.CreateBounded(new BoundedChannelOptions(256) + _config.EnableDirectoryWatch = value; + _config.Save(); + if (value) { - SingleReader = true, - SingleWriter = false, - FullMode = BoundedChannelFullMode.DropOldest, - }); + SetupFileWatcher(_config.WatchDirectory); + SetupConsumerTask(); + } + else + { + EndFileWatcher(); + EndConsumerTask(); + } + } - _fsw = new FileSystemWatcher(_config.WatchDirectory) + internal void PauseConsumer(bool pause) + => _pausedConsumer = pause; + + private void EndFileWatcher() + { + if (_fsw is null) + return; + + _fsw.Dispose(); + _fsw = null; + } + + private void SetupFileWatcher(string directory) + { + EndFileWatcher(); + _fsw = new FileSystemWatcher { IncludeSubdirectories = false, NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime, @@ -46,49 +78,81 @@ public class FileWatcher : IDisposable, IService _fsw.Created += OnPath; _fsw.Renamed += OnPath; + UpdateDirectory(directory); + } + + private void EndConsumerTask() + { + if (_cts is not null) + { + _cts.Cancel(); + _cts = null; + } + _consumer = null; + } + + private void SetupConsumerTask() + { + EndConsumerTask(); + _cts = new CancellationTokenSource(); _consumer = Task.Factory.StartNew( () => ConsumerLoopAsync(_cts.Token), _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); + } - _fsw.EnableRaisingEvents = true; + public void UpdateDirectory(string newPath) + { + if (_config.WatchDirectory != newPath) + { + _config.WatchDirectory = newPath; + _config.Save(); + } + + if (_fsw is null) + return; + + _fsw.EnableRaisingEvents = false; + if (!Directory.Exists(newPath) || newPath.Length is 0) + { + _fsw.Path = string.Empty; + } + else + { + _fsw.Path = newPath; + _fsw.EnableRaisingEvents = true; + } } private void OnPath(object? sender, FileSystemEventArgs e) - { - // Cheap de-dupe: only queue once per filename until processed - if (!_config.EnableDirectoryWatch || !_pending.TryAdd(e.FullPath, 0)) - return; - - _ = _queue.Writer.TryWrite(e.FullPath); - } + => _pending.TryAdd(e.FullPath, 0); private async Task ConsumerLoopAsync(CancellationToken token) { - if (!_config.EnableDirectoryWatch) - return; - - var reader = _queue.Reader; - while (await reader.WaitToReadAsync(token).ConfigureAwait(false)) + while (true) { - while (reader.TryRead(out var path)) + var (path, _) = _pending.FirstOrDefault(); + if (path is null || _pausedConsumer) { - try - { - await ProcessOneAsync(path, token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - Penumbra.Log.Debug($"[FileWatcher] Canceled via Token."); - } - catch (Exception ex) - { - Penumbra.Log.Debug($"[FileWatcher] Error during Processing: {ex}"); - } - finally - { - _pending.TryRemove(path, out _); - } + await Task.Delay(500, token).ConfigureAwait(false); + continue; + } + + try + { + await ProcessOneAsync(path, token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + Penumbra.Log.Debug("[FileWatcher] Canceled via Token."); + } + catch (Exception ex) + { + Penumbra.Log.Warning($"[FileWatcher] Error during Processing: {ex}"); + } + finally + { + _pending.TryRemove(path, out _); } } } @@ -115,28 +179,10 @@ public class FileWatcher : IDisposable, IService if (len > 0 && len == lastLen) { if (_config.EnableAutomaticModImport) - { _modImportManager.AddUnpack(path); - return; - } else - { - var invoked = false; - Action installRequest = args => - { - if (invoked) - return; - - invoked = true; - _modImportManager.AddUnpack(path); - }; - - _messageService.PrintModFoundInfo( - Path.GetFileNameWithoutExtension(path), - installRequest); - - return; - } + _messageService.AddMessage(new InstallNotification(_modImportManager, path), false); + return; } lastLen = len; @@ -154,34 +200,10 @@ public class FileWatcher : IDisposable, IService } } - public void UpdateDirectory(string newPath) - { - if (!_config.EnableDirectoryWatch || _fsw is null || !Directory.Exists(newPath) || string.IsNullOrWhiteSpace(newPath)) - return; - - _fsw.EnableRaisingEvents = false; - _fsw.Path = newPath; - _fsw.EnableRaisingEvents = true; - } public void Dispose() { - if (!_config.EnableDirectoryWatch) - return; - - _fsw.EnableRaisingEvents = false; - _cts.Cancel(); - _fsw.Dispose(); - _queue.Writer.TryComplete(); - try - { - _consumer.Wait(TimeSpan.FromSeconds(5)); - } - catch - { - /* swallow */ - } - - _cts.Dispose(); + EndConsumerTask(); + EndFileWatcher(); } } diff --git a/Penumbra/Services/InstallNotification.cs b/Penumbra/Services/InstallNotification.cs new file mode 100644 index 00000000..e3956076 --- /dev/null +++ b/Penumbra/Services/InstallNotification.cs @@ -0,0 +1,39 @@ +using Dalamud.Bindings.ImGui; +using Dalamud.Interface.ImGuiNotification; +using Dalamud.Interface.ImGuiNotification.EventArgs; +using OtterGui.Text; +using Penumbra.Mods.Manager; + +namespace Penumbra.Services; + +public class InstallNotification(ModImportManager modImportManager, string filePath) : OtterGui.Classes.MessageService.IMessage +{ + public string Message + => "A new mod has been found!"; + + public NotificationType NotificationType + => NotificationType.Info; + + public uint NotificationDuration + => uint.MaxValue; + + public string NotificationTitle { get; } = Path.GetFileNameWithoutExtension(filePath); + + public string LogMessage + => $"A new mod has been found: {Path.GetFileName(filePath)}"; + + public void OnNotificationActions(INotificationDrawArgs args) + { + var region = ImGui.GetContentRegionAvail(); + var buttonSize = new Vector2((region.X - ImGui.GetStyle().ItemSpacing.X) / 2, 0); + if (ImUtf8.ButtonEx("Install"u8, ""u8, buttonSize)) + { + modImportManager.AddUnpack(filePath); + args.Notification.DismissNow(); + } + + ImGui.SameLine(); + if (ImUtf8.ButtonEx("Ignore"u8, ""u8, buttonSize)) + args.Notification.DismissNow(); + } +} diff --git a/Penumbra/Services/MessageService.cs b/Penumbra/Services/MessageService.cs index 3dc6a90c..70ccf47b 100644 --- a/Penumbra/Services/MessageService.cs +++ b/Penumbra/Services/MessageService.cs @@ -1,43 +1,19 @@ -using Dalamud.Bindings.ImGui; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Game.Text.SeStringHandling.Payloads; using Dalamud.Interface; using Dalamud.Interface.ImGuiNotification; -using Dalamud.Interface.ImGuiNotification.EventArgs; using Dalamud.Plugin.Services; using Lumina.Excel.Sheets; using OtterGui.Log; using OtterGui.Services; -using OtterGui.Text; using Penumbra.GameData.Data; using Penumbra.Mods.Manager; using Penumbra.String.Classes; -using static OtterGui.Classes.MessageService; using Notification = OtterGui.Classes.Notification; namespace Penumbra.Services; -public class InstallNotification(string message, Action installRequest) : IMessage -{ - private bool _invoked = false; - - public string Message { get; } = message; - - public NotificationType NotificationType => NotificationType.Info; - - public uint NotificationDuration => 10000; - - public void OnNotificationActions(INotificationDrawArgs args) - { - if (ImUtf8.ButtonEx("Install"u8, "Install this mod."u8, disabled: _invoked)) - { - installRequest(true); - _invoked = true; - } - } -} - public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INotificationManager notificationManager) : OtterGui.Classes.MessageService(log, builder, chat, notificationManager), IService { @@ -79,11 +55,4 @@ public class MessageService(Logger log, IUiBuilder builder, IChatGui chat, INoti $"Cowardly refusing to load replacement for {originalGamePath.Filename().ToString().ToLowerInvariant()} by {mod.Name}{(messageComplement.Length > 0 ? ":\n" : ".")}{messageComplement}", NotificationType.Warning, 10000)); } - - public void PrintModFoundInfo(string fileName, Action installRequest) - { - AddMessage( - new InstallNotification($"A new mod has been found: {fileName}", installRequest) - ); - } } diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 46f4d38f..86c01cb2 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -66,7 +66,8 @@ public class SettingsTab : ITab, IUiService public SettingsTab(IDalamudPluginInterface pluginInterface, Configuration config, FontReloader fontReloader, TutorialService tutorial, Penumbra penumbra, FileDialogService fileDialog, ModManager modManager, ModFileSystemSelector selector, - CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, FileWatcher fileWatcher, HttpApi httpApi, + CharacterUtility characterUtility, ResidentResourceManager residentResources, ModExportManager modExportManager, + FileWatcher fileWatcher, HttpApi httpApi, DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, @@ -651,7 +652,7 @@ public class SettingsTab : ITab, IUiService DrawDefaultModExportPath(); Checkbox("Enable Directory Watcher", "Enables a File Watcher that automatically listens for Mod files that enter a specified directory, causing Penumbra to open a popup to import these mods.", - _config.EnableDirectoryWatch, v => _config.EnableDirectoryWatch = v); + _config.EnableDirectoryWatch, _fileWatcher.Toggle); Checkbox("Enable Fully Automatic Import", "Uses the File Watcher in order to skip the query popup and automatically import any new mods.", _config.EnableAutomaticModImport, v => _config.EnableAutomaticModImport = v); @@ -735,19 +736,24 @@ public class SettingsTab : ITab, IUiService + "Keep this empty to use the root directory."); } - private string _tempWatchDirectory = string.Empty; + private string? _tempWatchDirectory; + /// Draw input for the Automatic Mod import path. private void DrawFileWatcherPath() { - var tmp = _config.WatchDirectory; - var spacing = new Vector2(UiHelpers.ScaleX3); - using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, spacing); + var tmp = _tempWatchDirectory ?? _config.WatchDirectory; + var spacing = new Vector2(UiHelpers.ScaleX3); + using var style = ImRaii.PushStyle(ImGuiStyleVar.ItemSpacing, spacing); ImGui.SetNextItemWidth(UiHelpers.InputTextMinusButton3); if (ImGui.InputText("##fileWatchPath", ref tmp, 256)) _tempWatchDirectory = tmp; - if (ImGui.IsItemDeactivatedAfterEdit()) - _fileWatcher.UpdateDirectory(_tempWatchDirectory); + if (ImGui.IsItemDeactivated() && _tempWatchDirectory is not null) + { + if (ImGui.IsItemDeactivatedAfterEdit()) + _fileWatcher.UpdateDirectory(_tempWatchDirectory); + _tempWatchDirectory = null; + } ImGui.SameLine(); if (ImGuiUtil.DrawDisabledButton($"{FontAwesomeIcon.Folder.ToIconString()}##fileWatch", UiHelpers.IconButtonSize, @@ -761,11 +767,7 @@ public class SettingsTab : ITab, IUiService _fileDialog.OpenFolderPicker("Choose Automatic Import Directory", (b, s) => { if (b) - { _fileWatcher.UpdateDirectory(s); - _config.WatchDirectory = s; - _config.Save(); - } }, startDir, false); } From c4b6e4e00bd4a52b1b5be5059effccae58c8befb Mon Sep 17 00:00:00 2001 From: Actions User Date: Thu, 23 Oct 2025 21:50:20 +0000 Subject: [PATCH 1357/1381] [CI] Updating repo.json for testing_1.5.1.7 --- repo.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/repo.json b/repo.json index 2a31b75e..34405eb6 100644 --- a/repo.json +++ b/repo.json @@ -6,7 +6,7 @@ "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", "AssemblyVersion": "1.5.1.6", - "TestingAssemblyVersion": "1.5.1.6", + "TestingAssemblyVersion": "1.5.1.7", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -19,7 +19,7 @@ "LoadRequiredState": 2, "LoadSync": true, "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.7/Penumbra.zip", "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } From ce54aa5d2559abc8552edfe0b270e61c450226c4 Mon Sep 17 00:00:00 2001 From: Karou Date: Sun, 2 Nov 2025 17:58:20 -0500 Subject: [PATCH 1358/1381] Added IPC call to allow for redrawing only members of specified collections --- Penumbra.Api | 2 +- Penumbra/Api/Api/RedrawApi.cs | 29 ++++++++++++++++--- Penumbra/Api/IpcProviders.cs | 1 + .../Api/IpcTester/CollectionsIpcTester.cs | 4 +++ 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index c23ee05c..874a3773 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit c23ee05c1e9fa103eaa52e6aa7e855ef568ee669 +Subproject commit 874a3773bc4f637de1ef1fa8756b4debe3d8f68b diff --git a/Penumbra/Api/Api/RedrawApi.cs b/Penumbra/Api/Api/RedrawApi.cs index ec4de892..4cbb9f29 100644 --- a/Penumbra/Api/Api/RedrawApi.cs +++ b/Penumbra/Api/Api/RedrawApi.cs @@ -2,11 +2,14 @@ using Dalamud.Game.ClientState.Objects.Types; using Dalamud.Plugin.Services; using OtterGui.Services; using Penumbra.Api.Enums; +using Penumbra.Collections; +using Penumbra.Collections.Manager; +using Penumbra.GameData.Interop; using Penumbra.Interop.Services; -namespace Penumbra.Api.Api; - -public class RedrawApi(RedrawService redrawService, IFramework framework) : IPenumbraApiRedraw, IApiService +namespace Penumbra.Api.Api; + +public class RedrawApi(RedrawService redrawService, IFramework framework, CollectionManager collections, ObjectManager objects, ApiHelpers helpers) : IPenumbraApiRedraw, IApiService { public void RedrawObject(int gameObjectIndex, RedrawType setting) { @@ -28,9 +31,27 @@ public class RedrawApi(RedrawService redrawService, IFramework framework) : IPen framework.RunOnFrameworkThread(() => redrawService.RedrawAll(setting)); } + public void RedrawCollectionMembers(Guid collectionId, RedrawType setting) + { + + if (!collections.Storage.ById(collectionId, out var collection)) + collection = ModCollection.Empty; + framework.RunOnFrameworkThread(() => + { + foreach (var actor in objects.Objects) + { + helpers.AssociatedCollection(actor.ObjectIndex, out var modCollection); + if (collection == modCollection) + { + framework.RunOnFrameworkThread(() => redrawService.RedrawObject(actor.ObjectIndex, setting)); + } + } + }); + } + public event GameObjectRedrawnDelegate? GameObjectRedrawn { add => redrawService.GameObjectRedrawn += value; remove => redrawService.GameObjectRedrawn -= value; } -} +} diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 0c80626f..5f04540f 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -88,6 +88,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.RedrawObject.Provider(pi, api.Redraw), IpcSubscribers.RedrawAll.Provider(pi, api.Redraw), IpcSubscribers.GameObjectRedrawn.Provider(pi, api.Redraw), + IpcSubscribers.RedrawCollectionMembers.Provider(pi, api.Redraw), IpcSubscribers.ResolveDefaultPath.Provider(pi, api.Resolve), IpcSubscribers.ResolveInterfacePath.Provider(pi, api.Resolve), diff --git a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs index c06bdeb4..f033b7c3 100644 --- a/Penumbra/Api/IpcTester/CollectionsIpcTester.cs +++ b/Penumbra/Api/IpcTester/CollectionsIpcTester.cs @@ -121,6 +121,10 @@ public class CollectionsIpcTester(IDalamudPluginInterface pi) : IUiService }).ToArray(); ImGui.OpenPopup("Changed Item List"); } + IpcTester.DrawIntro(RedrawCollectionMembers.Label, "Redraw Collection Members"); + if (ImGui.Button("Redraw##ObjectCollection")) + new RedrawCollectionMembers(pi).Invoke(collectionList[0].Id, RedrawType.Redraw); + } private void DrawChangedItemPopup() From 5be021b0eb248eede38e8d205bc75bd95b2305df Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 13 Nov 2025 19:53:50 +0100 Subject: [PATCH 1359/1381] Add integration settings sections --- Penumbra.Api | 2 +- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/Api/UiApi.cs | 26 +++-- Penumbra/Api/IpcProviders.cs | 2 + .../IntegrationSettingsRegistry.cs | 110 ++++++++++++++++++ Penumbra/UI/Tabs/SettingsTab.cs | 8 +- 6 files changed, 139 insertions(+), 11 deletions(-) create mode 100644 Penumbra/UI/Integration/IntegrationSettingsRegistry.cs diff --git a/Penumbra.Api b/Penumbra.Api index 874a3773..b97784bd 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 874a3773bc4f637de1ef1fa8756b4debe3d8f68b +Subproject commit b97784bd7cd911bd0a323cd8e717714de1875469 diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 7304c9c7..c4026c72 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -17,7 +17,7 @@ public class PenumbraApi( UiApi ui) : IDisposable, IApiService, IPenumbraApi { public const int BreakingVersion = 5; - public const int FeatureVersion = 12; + public const int FeatureVersion = 13; public void Dispose() { diff --git a/Penumbra/Api/Api/UiApi.cs b/Penumbra/Api/Api/UiApi.cs index b14f67ae..6fb116f3 100644 --- a/Penumbra/Api/Api/UiApi.cs +++ b/Penumbra/Api/Api/UiApi.cs @@ -5,20 +5,24 @@ using Penumbra.GameData.Data; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI; +using Penumbra.UI.Integration; +using Penumbra.UI.Tabs; namespace Penumbra.Api.Api; public class UiApi : IPenumbraApiUi, IApiService, IDisposable { - private readonly CommunicatorService _communicator; - private readonly ConfigWindow _configWindow; - private readonly ModManager _modManager; + private readonly CommunicatorService _communicator; + private readonly ConfigWindow _configWindow; + private readonly ModManager _modManager; + private readonly IntegrationSettingsRegistry _integrationSettings; - public UiApi(CommunicatorService communicator, ConfigWindow configWindow, ModManager modManager) + public UiApi(CommunicatorService communicator, ConfigWindow configWindow, ModManager modManager, IntegrationSettingsRegistry integrationSettings) { - _communicator = communicator; - _configWindow = configWindow; - _modManager = modManager; + _communicator = communicator; + _configWindow = configWindow; + _modManager = modManager; + _integrationSettings = integrationSettings; _communicator.ChangedItemHover.Subscribe(OnChangedItemHover, ChangedItemHover.Priority.Default); _communicator.ChangedItemClick.Subscribe(OnChangedItemClick, ChangedItemClick.Priority.Default); } @@ -98,4 +102,12 @@ public class UiApi : IPenumbraApiUi, IApiService, IDisposable var (type, id) = data.ToApiObject(); ChangedItemTooltip.Invoke(type, id); } + + public PenumbraApiEc RegisterSettingsSection(Action draw) + => _integrationSettings.RegisterSection(draw); + + public PenumbraApiEc UnregisterSettingsSection(Action draw) + => _integrationSettings.UnregisterSection(draw) + ? PenumbraApiEc.Success + : PenumbraApiEc.NothingChanged; } diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 5f04540f..197cf3d2 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -130,6 +130,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.PostSettingsDraw.Provider(pi, api.Ui), IpcSubscribers.OpenMainWindow.Provider(pi, api.Ui), IpcSubscribers.CloseMainWindow.Provider(pi, api.Ui), + IpcSubscribers.RegisterSettingsSection.Provider(pi, api.Ui), + IpcSubscribers.UnregisterSettingsSection.Provider(pi, api.Ui), ]; if (_characterUtility.Ready) _initializedProvider.Invoke(); diff --git a/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs b/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs new file mode 100644 index 00000000..ab26a68f --- /dev/null +++ b/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs @@ -0,0 +1,110 @@ +using Dalamud.Plugin; +using OtterGui.Services; +using OtterGui.Text; +using Penumbra.Api.Enums; + +namespace Penumbra.UI.Integration; + +public sealed class IntegrationSettingsRegistry : IService, IDisposable +{ + private readonly IDalamudPluginInterface _pluginInterface; + + private readonly List<(string InternalName, string Name, Action Draw)> _sections = []; + + private bool _disposed = false; + + public IntegrationSettingsRegistry(IDalamudPluginInterface pluginInterface) + { + _pluginInterface = pluginInterface; + + _pluginInterface.ActivePluginsChanged += OnActivePluginsChanged; + } + + public void Dispose() + { + _disposed = true; + + _pluginInterface.ActivePluginsChanged -= OnActivePluginsChanged; + + _sections.Clear(); + } + + public void Draw() + { + foreach (var (internalName, name, draw) in _sections) + { + if (!ImUtf8.CollapsingHeader($"Integration with {name}###IntegrationSettingsHeader.{internalName}")) + continue; + + using var id = ImUtf8.PushId($"IntegrationSettings.{internalName}"); + try + { + draw(); + } + catch (Exception e) + { + Penumbra.Log.Error($"Error while drawing {internalName} integration settings: {e}"); + } + } + } + + public PenumbraApiEc RegisterSection(Action draw) + { + if (_disposed) + return PenumbraApiEc.SystemDisposed; + + var plugin = GetPlugin(draw); + if (plugin is null) + return PenumbraApiEc.InvalidArgument; + + var section = (plugin.InternalName, plugin.Name, draw); + + var index = FindSectionIndex(plugin.InternalName); + if (index >= 0) + { + if (_sections[index] == section) + return PenumbraApiEc.NothingChanged; + _sections[index] = section; + } + else + _sections.Add(section); + _sections.Sort((lhs, rhs) => string.Compare(lhs.Name, rhs.Name, StringComparison.CurrentCultureIgnoreCase)); + + return PenumbraApiEc.Success; + } + + public bool UnregisterSection(Action draw) + { + var index = FindSectionIndex(draw); + if (index < 0) + return false; + + _sections.RemoveAt(index); + return true; + } + + private void OnActivePluginsChanged(IActivePluginsChangedEventArgs args) + { + if (args.Kind is PluginListInvalidationKind.Loaded) + return; + + foreach (var internalName in args.AffectedInternalNames) + { + var index = FindSectionIndex(internalName); + if (index >= 0 && GetPlugin(_sections[index].Draw) is null) + { + _sections.RemoveAt(index); + Penumbra.Log.Warning($"Removed stale integration setting section of {internalName} (reason: {args.Kind})"); + } + } + } + + private IExposedPlugin? GetPlugin(Delegate @delegate) + => null; // TODO Use IDalamudPluginInterface.GetPlugin(Assembly) when it's in Dalamud stable. + + private int FindSectionIndex(string internalName) + => _sections.FindIndex(section => section.InternalName.Equals(internalName, StringComparison.Ordinal)); + + private int FindSectionIndex(Action draw) + => _sections.FindIndex(section => section.Draw == draw); +} diff --git a/Penumbra/UI/Tabs/SettingsTab.cs b/Penumbra/UI/Tabs/SettingsTab.cs index 86c01cb2..09c7c58d 100644 --- a/Penumbra/UI/Tabs/SettingsTab.cs +++ b/Penumbra/UI/Tabs/SettingsTab.cs @@ -20,6 +20,7 @@ using Penumbra.Interop.Services; using Penumbra.Mods.Manager; using Penumbra.Services; using Penumbra.UI.Classes; +using Penumbra.UI.Integration; using Penumbra.UI.ModsTab; namespace Penumbra.UI.Tabs; @@ -55,6 +56,7 @@ public class SettingsTab : ITab, IUiService private readonly CleanupService _cleanupService; private readonly AttributeHook _attributeHook; private readonly PcpService _pcpService; + private readonly IntegrationSettingsRegistry _integrationSettings; private int _minimumX = int.MaxValue; private int _minimumY = int.MaxValue; @@ -71,7 +73,7 @@ public class SettingsTab : ITab, IUiService DalamudSubstitutionProvider dalamudSubstitutionProvider, FileCompactor compactor, DalamudConfigService dalamudConfig, IDataManager gameData, PredefinedTagManager predefinedTagConfig, CrashHandlerService crashService, MigrationSectionDrawer migrationDrawer, CollectionAutoSelector autoSelector, CleanupService cleanupService, - AttributeHook attributeHook, PcpService pcpService) + AttributeHook attributeHook, PcpService pcpService, IntegrationSettingsRegistry integrationSettings) { _pluginInterface = pluginInterface; _config = config; @@ -99,6 +101,7 @@ public class SettingsTab : ITab, IUiService _cleanupService = cleanupService; _attributeHook = attributeHook; _pcpService = pcpService; + _integrationSettings = integrationSettings; } public void DrawHeader() @@ -129,6 +132,7 @@ public class SettingsTab : ITab, IUiService DrawColorSettings(); DrawPredefinedTagsSection(); DrawAdvancedSettings(); + _integrationSettings.Draw(); DrawSupportButtons(); } @@ -1133,7 +1137,7 @@ public class SettingsTab : ITab, IUiService } #endregion - + /// Draw the support button group on the right-hand side of the window. private void DrawSupportButtons() { From e240a42a2ccd35d06be417033d034448c5c8be35 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 13 Nov 2025 19:55:32 +0100 Subject: [PATCH 1360/1381] Replace GetPlugin(Delegate) stub by actual implementation --- Penumbra/UI/Integration/IntegrationSettingsRegistry.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs b/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs index ab26a68f..2d3da488 100644 --- a/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs +++ b/Penumbra/UI/Integration/IntegrationSettingsRegistry.cs @@ -100,7 +100,12 @@ public sealed class IntegrationSettingsRegistry : IService, IDisposable } private IExposedPlugin? GetPlugin(Delegate @delegate) - => null; // TODO Use IDalamudPluginInterface.GetPlugin(Assembly) when it's in Dalamud stable. + => @delegate.Method.DeclaringType + switch + { + null => null, + var type => _pluginInterface.GetPlugin(type.Assembly), + }; private int FindSectionIndex(string internalName) => _sections.FindIndex(section => section.InternalName.Equals(internalName, StringComparison.Ordinal)); From 338e3bc1a5107267aace6ae9b1a89e30a7e7a757 Mon Sep 17 00:00:00 2001 From: Exter-N Date: Thu, 20 Nov 2025 18:41:32 +0100 Subject: [PATCH 1361/1381] Update Penumbra.Api --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index b97784bd..704d62f6 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit b97784bd7cd911bd0a323cd8e717714de1875469 +Subproject commit 704d62f64f791b8cfd42363beaa464ad6f98ae48 From 5dd74297c623430ea63ad7a01531ba9b58e75eb7 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 28 Nov 2025 22:10:17 +0000 Subject: [PATCH 1362/1381] [CI] Updating repo.json for 1.5.1.8 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 34405eb6..7ddffd7c 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.6", - "TestingAssemblyVersion": "1.5.1.7", + "AssemblyVersion": "1.5.1.8", + "TestingAssemblyVersion": "1.5.1.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 13, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/testing_1.5.1.7/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.6/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.8/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.8/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.8/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From ccb5b01290c717b0581ce5c782e9c7554ff27357 Mon Sep 17 00:00:00 2001 From: Karou Date: Sat, 29 Nov 2025 12:14:10 -0500 Subject: [PATCH 1363/1381] Api version bump and remove redundant framework thread call --- Penumbra.Api | 2 +- Penumbra/Api/Api/PenumbraApi.cs | 2 +- Penumbra/Api/Api/RedrawApi.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Penumbra.Api b/Penumbra.Api index 874a3773..3d6cee1a 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 874a3773bc4f637de1ef1fa8756b4debe3d8f68b +Subproject commit 3d6cee1a11922ccd426f36060fd026bc1a698adf diff --git a/Penumbra/Api/Api/PenumbraApi.cs b/Penumbra/Api/Api/PenumbraApi.cs index 7304c9c7..c4026c72 100644 --- a/Penumbra/Api/Api/PenumbraApi.cs +++ b/Penumbra/Api/Api/PenumbraApi.cs @@ -17,7 +17,7 @@ public class PenumbraApi( UiApi ui) : IDisposable, IApiService, IPenumbraApi { public const int BreakingVersion = 5; - public const int FeatureVersion = 12; + public const int FeatureVersion = 13; public void Dispose() { diff --git a/Penumbra/Api/Api/RedrawApi.cs b/Penumbra/Api/Api/RedrawApi.cs index 4cbb9f29..08f1f9df 100644 --- a/Penumbra/Api/Api/RedrawApi.cs +++ b/Penumbra/Api/Api/RedrawApi.cs @@ -43,7 +43,7 @@ public class RedrawApi(RedrawService redrawService, IFramework framework, Collec helpers.AssociatedCollection(actor.ObjectIndex, out var modCollection); if (collection == modCollection) { - framework.RunOnFrameworkThread(() => redrawService.RedrawObject(actor.ObjectIndex, setting)); + redrawService.RedrawObject(actor.ObjectIndex, setting); } } }); From 3e7511cb348d936736621b9152ae54772e58ef21 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Wed, 17 Dec 2025 18:33:10 +0100 Subject: [PATCH 1364/1381] Update SDK. --- OtterGui | 2 +- Penumbra.Api | 2 +- .../Penumbra.CrashHandler.csproj | 2 +- Penumbra.CrashHandler/packages.lock.json | 8 ++--- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Penumbra.csproj | 2 +- Penumbra/UI/CollectionTab/CollectionPanel.cs | 2 +- Penumbra/UI/Tabs/CollectionsTab.cs | 2 +- Penumbra/UI/Tabs/Debug/DebugTab.cs | 3 +- Penumbra/UI/Tabs/ModsTab.cs | 3 +- Penumbra/UI/Tabs/ResourceTab.cs | 2 +- Penumbra/packages.lock.json | 36 ++++--------------- 13 files changed, 23 insertions(+), 45 deletions(-) diff --git a/OtterGui b/OtterGui index a63f6735..6f323645 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit a63f6735cf4bed4f7502a022a10378607082b770 +Subproject commit 6f3236453b1edfaa25c8edcc8b39a9d9b2fc18ac diff --git a/Penumbra.Api b/Penumbra.Api index 3d6cee1a..e4934ccc 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 3d6cee1a11922ccd426f36060fd026bc1a698adf +Subproject commit e4934ccca0379f22dadf989ab2d34f30b3c5c7ea diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj index 1b1f0a28..4c864d39 100644 --- a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/Penumbra.CrashHandler/packages.lock.json b/Penumbra.CrashHandler/packages.lock.json index 1d395083..0a160ea5 100644 --- a/Penumbra.CrashHandler/packages.lock.json +++ b/Penumbra.CrashHandler/packages.lock.json @@ -1,12 +1,12 @@ { "version": 1, "dependencies": { - "net9.0-windows7.0": { + "net10.0-windows7.0": { "DotNet.ReproducibleBuilds": { "type": "Direct", - "requested": "[1.2.25, )", - "resolved": "1.2.25", - "contentHash": "xCXiw7BCxHJ8pF6wPepRUddlh2dlQlbr81gXA72hdk4FLHkKXas7EH/n+fk5UCA/YfMqG1Z6XaPiUjDbUNBUzg==" + "requested": "[1.2.39, )", + "resolved": "1.2.39", + "contentHash": "fcFN01tDTIQqDuTwr1jUQK/geofiwjG5DycJQOnC72i1SsLAk1ELe+apBOuZ11UMQG8YKFZG1FgvjZPbqHyatg==" } } } diff --git a/Penumbra.GameData b/Penumbra.GameData index d889f9ef..2ff50e68 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit d889f9ef918514a46049725052d378b441915b00 +Subproject commit 2ff50e68f7c951f0f8b25957a400a2e32ed9d6dc diff --git a/Penumbra.String b/Penumbra.String index c8611a0c..0315144a 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit c8611a0c546b6b2ec29214ab319fc2c38fe74793 +Subproject commit 0315144ab5614c11911e2a4dddf436fb18c5d7e3 diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index fa45ffbf..f04928a5 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,4 +1,4 @@ - + Penumbra absolute gangstas diff --git a/Penumbra/UI/CollectionTab/CollectionPanel.cs b/Penumbra/UI/CollectionTab/CollectionPanel.cs index e41ceade..7a8ca032 100644 --- a/Penumbra/UI/CollectionTab/CollectionPanel.cs +++ b/Penumbra/UI/CollectionTab/CollectionPanel.cs @@ -7,6 +7,7 @@ using Dalamud.Interface.ManagedFontAtlas; using Dalamud.Interface.Utility; using Dalamud.Plugin; using Dalamud.Bindings.ImGui; +using Dalamud.Plugin.Services; using OtterGui; using OtterGui.Classes; using OtterGui.Extensions; @@ -17,7 +18,6 @@ using Penumbra.Collections.Manager; using Penumbra.GameData.Actors; using Penumbra.GameData.Enums; using Penumbra.Mods.Manager; -using Penumbra.Mods.Settings; using Penumbra.Services; using Penumbra.UI.Classes; diff --git a/Penumbra/UI/Tabs/CollectionsTab.cs b/Penumbra/UI/Tabs/CollectionsTab.cs index f2a041eb..b458fc16 100644 --- a/Penumbra/UI/Tabs/CollectionsTab.cs +++ b/Penumbra/UI/Tabs/CollectionsTab.cs @@ -1,6 +1,6 @@ using Dalamud.Bindings.ImGui; -using Dalamud.Game.ClientState.Objects; using Dalamud.Plugin; +using Dalamud.Plugin.Services; using OtterGui.Raii; using OtterGui.Services; using OtterGui.Widgets; diff --git a/Penumbra/UI/Tabs/Debug/DebugTab.cs b/Penumbra/UI/Tabs/Debug/DebugTab.cs index 05f77e29..c7f0635d 100644 --- a/Penumbra/UI/Tabs/Debug/DebugTab.cs +++ b/Penumbra/UI/Tabs/Debug/DebugTab.cs @@ -9,6 +9,7 @@ using FFXIVClientStructs.FFXIV.Client.Game.Object; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.UI.Agent; using Dalamud.Bindings.ImGui; +using Dalamud.Game.ClientState.Objects.SubKinds; using Dalamud.Interface.Colors; using Microsoft.Extensions.DependencyInjection; using OtterGui; @@ -1033,7 +1034,7 @@ public class DebugTab : Window, ITab, IUiService /// Draw information about the models, materials and resources currently loaded by the local player. private unsafe void DrawPlayerModelInfo() { - var player = _clientState.LocalPlayer; + var player = _objects.Objects.LocalPlayer; var name = player?.Name.ToString() ?? "NULL"; if (!ImGui.CollapsingHeader($"Player Model Info: {name}##Draw") || player == null) return; diff --git a/Penumbra/UI/Tabs/ModsTab.cs b/Penumbra/UI/Tabs/ModsTab.cs index 79dcbb9e..1d24c597 100644 --- a/Penumbra/UI/Tabs/ModsTab.cs +++ b/Penumbra/UI/Tabs/ModsTab.cs @@ -27,7 +27,6 @@ public class ModsTab( TutorialService tutorial, RedrawService redrawService, Configuration config, - IClientState clientState, CollectionSelectHeader collectionHeader, ITargetManager targets, ObjectManager objects) @@ -113,7 +112,7 @@ public class ModsTab( ImGui.SetTooltip($"The supported modifiers for '/penumbra redraw' are:\n{TutorialService.SupportedRedrawModifiers}"); using var id = ImRaii.PushId("Redraw"); - using var disabled = ImRaii.Disabled(clientState.LocalPlayer == null); + using var disabled = ImRaii.Disabled(objects.Objects.LocalPlayer is null); ImGui.SameLine(); var buttonWidth = frameHeight with { X = ImGui.GetContentRegionAvail().X / 5 }; var tt = !objects[0].Valid diff --git a/Penumbra/UI/Tabs/ResourceTab.cs b/Penumbra/UI/Tabs/ResourceTab.cs index 593adde1..2223075d 100644 --- a/Penumbra/UI/Tabs/ResourceTab.cs +++ b/Penumbra/UI/Tabs/ResourceTab.cs @@ -1,5 +1,5 @@ using Dalamud.Bindings.ImGui; -using Dalamud.Game; +using Dalamud.Plugin.Services; using FFXIVClientStructs.FFXIV.Client.System.Resource; using FFXIVClientStructs.FFXIV.Client.System.Resource.Handle; using FFXIVClientStructs.Interop; diff --git a/Penumbra/packages.lock.json b/Penumbra/packages.lock.json index 7499bffa..c904870a 100644 --- a/Penumbra/packages.lock.json +++ b/Penumbra/packages.lock.json @@ -1,12 +1,12 @@ { "version": 1, "dependencies": { - "net9.0-windows7.0": { + "net10.0-windows7.0": { "DotNet.ReproducibleBuilds": { "type": "Direct", - "requested": "[1.2.25, )", - "resolved": "1.2.25", - "contentHash": "xCXiw7BCxHJ8pF6wPepRUddlh2dlQlbr81gXA72hdk4FLHkKXas7EH/n+fk5UCA/YfMqG1Z6XaPiUjDbUNBUzg==" + "requested": "[1.2.39, )", + "resolved": "1.2.39", + "contentHash": "fcFN01tDTIQqDuTwr1jUQK/geofiwjG5DycJQOnC72i1SsLAk1ELe+apBOuZ11UMQG8YKFZG1FgvjZPbqHyatg==" }, "EmbedIO": { "type": "Direct", @@ -33,7 +33,6 @@ "resolved": "0.40.0", "contentHash": "yP/aFX1jqGikVF7u2f05VEaWN4aCaKNLxSas82UgA2GGVECxq/BcqZx3STHCJ78qilo1azEOk1XpBglIuGMb7w==", "dependencies": { - "System.Buffers": "4.6.0", "ZstdSharp.Port": "0.8.5" } }, @@ -66,10 +65,7 @@ "FlatSharp.Runtime": { "type": "Transitive", "resolved": "7.9.0", - "contentHash": "Bm8+WqzEsWNpxqrD5x4x+zQ8dyINlToCreM5FI2oNSfUVc9U9ZB+qztX/jd8rlJb3r0vBSlPwVLpw0xBtPa3Vw==", - "dependencies": { - "System.Memory": "4.5.5" - } + "contentHash": "Bm8+WqzEsWNpxqrD5x4x+zQ8dyINlToCreM5FI2oNSfUVc9U9ZB+qztX/jd8rlJb3r0vBSlPwVLpw0xBtPa3Vw==" }, "JetBrains.Annotations": { "type": "Transitive", @@ -102,33 +98,15 @@ "SharpGLTF.Core": "1.0.5" } }, - "System.Buffers": { - "type": "Transitive", - "resolved": "4.6.0", - "contentHash": "lN6tZi7Q46zFzAbRYXTIvfXcyvQQgxnY7Xm6C6xQ9784dEL1amjM6S6Iw4ZpsvesAKnRVsM4scrDQaDqSClkjA==" - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.5.5", - "contentHash": "XIWiDvKPXaTveaB7HVganDlOCRoj03l+jrwNvcge/t8vhGYKvqV+dMv6G4SAX2NoNmN0wZfVPTAlFwZcZvVOUw==" - }, "System.Security.Cryptography.Pkcs": { "type": "Transitive", "resolved": "8.0.1", "contentHash": "CoCRHFym33aUSf/NtWSVSZa99dkd0Hm7OCZUxORBjRB16LNhIEOf8THPqzIYlvKM0nNDAPTRBa1FxEECrgaxxA==" }, - "System.ValueTuple": { - "type": "Transitive", - "resolved": "4.5.0", - "contentHash": "okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==" - }, "Unosquare.Swan.Lite": { "type": "Transitive", "resolved": "3.1.0", - "contentHash": "X3s5QE/KMj3WAPFqFve7St+Ds10BB50u8kW8PmKIn7FVkn7yEXe9Yxr2htt1WV85DRqfFR0MN/BUNHkGHtL4OQ==", - "dependencies": { - "System.ValueTuple": "4.5.0" - } + "contentHash": "X3s5QE/KMj3WAPFqFve7St+Ds10BB50u8kW8PmKIn7FVkn7yEXe9Yxr2htt1WV85DRqfFR0MN/BUNHkGHtL4OQ==" }, "ZstdSharp.Port": { "type": "Transitive", @@ -154,7 +132,7 @@ "FlatSharp.Compiler": "[7.9.0, )", "FlatSharp.Runtime": "[7.9.0, )", "OtterGui": "[1.0.0, )", - "Penumbra.Api": "[5.10.0, )", + "Penumbra.Api": "[5.13.0, )", "Penumbra.String": "[1.0.6, )" } }, From 7717251c6a1184075b2a685def2a44c33a9bfdff Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 18 Dec 2025 20:45:15 +0100 Subject: [PATCH 1365/1381] Update to TerraFX. --- Penumbra.GameData | 2 +- Penumbra/Api/Api/ModSettingsApi.cs | 21 ++++ Penumbra/Api/Api/ResolveApi.cs | 34 +++++ Penumbra/Api/Api/UiApi.cs | 6 + Penumbra/Api/IpcProviders.cs | 3 + Penumbra/Import/Textures/TextureManager.cs | 85 ++++++++++--- .../Interop/Services/TextureArraySlicer.cs | 116 +++++++++++------- Penumbra/Penumbra.csproj | 12 +- Penumbra/Services/StaticServiceManager.cs | 1 + 9 files changed, 211 insertions(+), 69 deletions(-) diff --git a/Penumbra.GameData b/Penumbra.GameData index 2ff50e68..3d4d8510 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 2ff50e68f7c951f0f8b25957a400a2e32ed9d6dc +Subproject commit 3d4d8510f832dfd95d7069b86e6b3da4ec612558 diff --git a/Penumbra/Api/Api/ModSettingsApi.cs b/Penumbra/Api/Api/ModSettingsApi.cs index 3ba17cf4..d49c2904 100644 --- a/Penumbra/Api/Api/ModSettingsApi.cs +++ b/Penumbra/Api/Api/ModSettingsApi.cs @@ -73,6 +73,27 @@ public class ModSettingsApi : IPenumbraApiModSettings, IApiService, IDisposable return (ret.Item1, (ret.Item2.Value.Item1, ret.Item2.Value.Item2, ret.Item2.Value.Item3, ret.Item2.Value.Item4)); } + public PenumbraApiEc GetSettingsInAllCollections(string modDirectory, string modName, + out Dictionary>, bool, bool)> settings, + bool ignoreTemporaryCollections = false) + { + settings = []; + if (!_modManager.TryGetMod(modDirectory, modName, out var mod)) + return PenumbraApiEc.ModMissing; + + var collections = ignoreTemporaryCollections + ? _collectionManager.Storage.Where(c => c != ModCollection.Empty) + : _collectionManager.Storage.Where(c => c != ModCollection.Empty).Concat(_collectionManager.Temp.Values); + settings = []; + foreach (var collection in collections) + { + if (GetCurrentSettings(collection, mod, false, false, 0) is { } s) + settings.Add(collection.Identity.Id, s); + } + + return PenumbraApiEc.Success; + } + public (PenumbraApiEc, (bool, int, Dictionary>, bool, bool)?) GetCurrentModSettingsWithTemp(Guid collectionId, string modDirectory, string modName, bool ignoreInheritance, bool ignoreTemporary, int key) { diff --git a/Penumbra/Api/Api/ResolveApi.cs b/Penumbra/Api/Api/ResolveApi.cs index 481ea7ad..00a0c86f 100644 --- a/Penumbra/Api/Api/ResolveApi.cs +++ b/Penumbra/Api/Api/ResolveApi.cs @@ -1,5 +1,6 @@ using Dalamud.Plugin.Services; using OtterGui.Services; +using Penumbra.Api.Enums; using Penumbra.Collections; using Penumbra.Collections.Manager; using Penumbra.Interop.PathResolving; @@ -41,6 +42,19 @@ public class ResolveApi( return ret.Select(r => r.ToString()).ToArray(); } + public PenumbraApiEc ResolvePath(Guid collectionId, string gamePath, out string resolvedPath) + { + resolvedPath = gamePath; + if (!collectionManager.Storage.ById(collectionId, out var collection)) + return PenumbraApiEc.CollectionMissing; + + if (!collection.HasCache) + return PenumbraApiEc.CollectionInactive; + + resolvedPath = ResolvePath(gamePath, modManager, collection); + return PenumbraApiEc.Success; + } + public string[] ReverseResolvePlayerPath(string moddedPath) { if (!config.EnableMods) @@ -64,6 +78,26 @@ public class ResolveApi( return (resolved, reverseResolved.Select(a => a.Select(p => p.ToString()).ToArray()).ToArray()); } + public PenumbraApiEc ResolvePaths(Guid collectionId, string[] forward, string[] reverse, out string[] resolvedForward, + out string[][] resolvedReverse) + { + resolvedForward = forward; + resolvedReverse = []; + if (!config.EnableMods) + return PenumbraApiEc.Success; + + if (!collectionManager.Storage.ById(collectionId, out var collection)) + return PenumbraApiEc.CollectionMissing; + + if (!collection.HasCache) + return PenumbraApiEc.CollectionInactive; + + resolvedForward = forward.Select(p => ResolvePath(p, modManager, collection)).ToArray(); + var reverseResolved = collection.ReverseResolvePaths(reverse); + resolvedReverse = reverseResolved.Select(a => a.Select(p => p.ToString()).ToArray()).ToArray(); + return PenumbraApiEc.Success; + } + public async Task<(string[], string[][])> ResolvePlayerPathsAsync(string[] forward, string[] reverse) { if (!config.EnableMods) diff --git a/Penumbra/Api/Api/UiApi.cs b/Penumbra/Api/Api/UiApi.cs index b14f67ae..70f018bb 100644 --- a/Penumbra/Api/Api/UiApi.cs +++ b/Penumbra/Api/Api/UiApi.cs @@ -81,6 +81,12 @@ public class UiApi : IPenumbraApiUi, IApiService, IDisposable public void CloseMainWindow() => _configWindow.IsOpen = false; + public PenumbraApiEc RegisterSettingsSection(Action draw) + => throw new NotImplementedException(); + + public PenumbraApiEc UnregisterSettingsSection(Action draw) + => throw new NotImplementedException(); + private void OnChangedItemClick(MouseButton button, IIdentifiedObjectData data) { if (ChangedItemClicked == null) diff --git a/Penumbra/Api/IpcProviders.cs b/Penumbra/Api/IpcProviders.cs index 5f04540f..fdacc73b 100644 --- a/Penumbra/Api/IpcProviders.cs +++ b/Penumbra/Api/IpcProviders.cs @@ -66,6 +66,7 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.GetCurrentModSettings.Provider(pi, api.ModSettings), IpcSubscribers.GetCurrentModSettingsWithTemp.Provider(pi, api.ModSettings), IpcSubscribers.GetAllModSettings.Provider(pi, api.ModSettings), + IpcSubscribers.GetSettingsInAllCollections.Provider(pi, api.ModSettings), IpcSubscribers.TryInheritMod.Provider(pi, api.ModSettings), IpcSubscribers.TrySetMod.Provider(pi, api.ModSettings), IpcSubscribers.TrySetModPriority.Provider(pi, api.ModSettings), @@ -98,6 +99,8 @@ public sealed class IpcProviders : IDisposable, IApiService IpcSubscribers.ReverseResolvePlayerPath.Provider(pi, api.Resolve), IpcSubscribers.ResolvePlayerPaths.Provider(pi, api.Resolve), IpcSubscribers.ResolvePlayerPathsAsync.Provider(pi, api.Resolve), + IpcSubscribers.ResolvePath.Provider(pi, api.Resolve), + IpcSubscribers.ResolvePaths.Provider(pi, api.Resolve), IpcSubscribers.GetGameObjectResourcePaths.Provider(pi, api.ResourceTree), IpcSubscribers.GetPlayerResourcePaths.Provider(pi, api.ResourceTree), diff --git a/Penumbra/Import/Textures/TextureManager.cs b/Penumbra/Import/Textures/TextureManager.cs index 073fef2f..177722ec 100644 --- a/Penumbra/Import/Textures/TextureManager.cs +++ b/Penumbra/Import/Textures/TextureManager.cs @@ -7,12 +7,12 @@ using OtterGui.Log; using OtterGui.Services; using OtterGui.Tasks; using OtterTex; -using SharpDX.Direct3D11; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.Formats.Tga; using SixLabors.ImageSharp.PixelFormats; -using DxgiDevice = SharpDX.DXGI.Device; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; using Image = SixLabors.ImageSharp.Image; namespace Penumbra.Import.Textures; @@ -125,11 +125,11 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur switch (_type) { case TextureType.Png: - data?.SaveAsync(_outputPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.NoCompression }, cancel) + data?.SaveAsync(_outputPath, new PngEncoder { CompressionLevel = PngCompressionLevel.NoCompression }, cancel) .Wait(cancel); return; case TextureType.Targa: - data?.SaveAsync(_outputPath, new TgaEncoder() + data?.SaveAsync(_outputPath, new TgaEncoder { Compression = TgaCompression.None, BitsPerPixel = TgaBitsPerPixel.Pixel32, @@ -204,11 +204,16 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur rgba, width, height), CombinedTexture.TextureSaveType.AsIs when imageTypeBehaviour is TextureType.Dds => AddMipMaps(image.AsDds!, _mipMaps), CombinedTexture.TextureSaveType.Bitmap => ConvertToRgbaDds(image, _mipMaps, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC1 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC1UNorm, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC3 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC3UNorm, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC4 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC4UNorm, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC5 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC5UNorm, cancel, rgba, width, height), - CombinedTexture.TextureSaveType.BC7 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC7UNorm, cancel, rgba, width, height), + CombinedTexture.TextureSaveType.BC1 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC1UNorm, cancel, rgba, + width, height), + CombinedTexture.TextureSaveType.BC3 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC3UNorm, cancel, rgba, + width, height), + CombinedTexture.TextureSaveType.BC4 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC4UNorm, cancel, rgba, + width, height), + CombinedTexture.TextureSaveType.BC5 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC5UNorm, cancel, rgba, + width, height), + CombinedTexture.TextureSaveType.BC7 => _textures.ConvertToCompressedDds(image, _mipMaps, DXGIFormat.BC7UNorm, cancel, rgba, + width, height), _ => throw new Exception("Wrong save type."), }; @@ -390,7 +395,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur } /// Create a BC3 or BC7 block-compressed .dds from the input (optionally with mipmaps). Returns input (+ mipmaps) if it is already the correct format. - public ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, DXGIFormat format, CancellationToken cancel) + public unsafe ScratchImage CreateCompressed(ScratchImage input, bool mipMaps, DXGIFormat format, CancellationToken cancel) { if (input.Meta.Format == format) return input; @@ -406,11 +411,58 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur // See https://github.com/microsoft/DirectXTex/wiki/Compress#parameters for the format condition. if (format is DXGIFormat.BC6HUF16 or DXGIFormat.BC6HSF16 or DXGIFormat.BC7UNorm or DXGIFormat.BC7UNormSRGB) { - var device = new Device(uiBuilder.DeviceHandle); - var dxgiDevice = device.QueryInterface(); + ref var device = ref *(ID3D11Device*)uiBuilder.DeviceHandle; + IDXGIDevice* dxgiDevice; + Marshal.ThrowExceptionForHR(device.QueryInterface(TerraFX.Interop.Windows.Windows.__uuidof(), (void**)&dxgiDevice)); - using var deviceClone = new Device(dxgiDevice.Adapter, device.CreationFlags, device.FeatureLevel); - return input.Compress(deviceClone.NativePointer, format, CompressFlags.Parallel); + try + { + IDXGIAdapter* adapter = null; + Marshal.ThrowExceptionForHR(dxgiDevice->GetAdapter(&adapter)); + try + { + dxgiDevice->Release(); + dxgiDevice = null; + + ID3D11Device* deviceClone = null; + ID3D11DeviceContext* contextClone = null; + var featureLevel = device.GetFeatureLevel(); + Marshal.ThrowExceptionForHR(DirectX.D3D11CreateDevice( + adapter, + D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_UNKNOWN, + HMODULE.NULL, + device.GetCreationFlags(), + &featureLevel, + 1, + D3D11.D3D11_SDK_VERSION, + &deviceClone, + null, + &contextClone)); + try + { + adapter->Release(); + adapter = null; + return input.Compress((nint)deviceClone, format, CompressFlags.Parallel); + } + finally + { + if (contextClone is not null) + contextClone->Release(); + if (deviceClone is not null) + deviceClone->Release(); + } + } + finally + { + if (adapter is not null) + adapter->Release(); + } + } + finally + { + if (dxgiDevice is not null) + dxgiDevice->Release(); + } } return input.Compress(format, CompressFlags.BC7Quick | CompressFlags.Parallel); @@ -456,7 +508,7 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur GC.KeepAlive(input); } - private readonly struct ImageInputData + private readonly struct ImageInputData : IEquatable { private readonly string? _inputPath; @@ -524,5 +576,8 @@ public sealed class TextureManager(IDataManager gameData, Logger logger, ITextur public override int GetHashCode() => _inputPath != null ? _inputPath.ToLowerInvariant().GetHashCode() : HashCode.Combine(_width, _height); + + public override bool Equals(object? obj) + => obj is ImageInputData o && Equals(o); } } diff --git a/Penumbra/Interop/Services/TextureArraySlicer.cs b/Penumbra/Interop/Services/TextureArraySlicer.cs index 11498878..7b873f26 100644 --- a/Penumbra/Interop/Services/TextureArraySlicer.cs +++ b/Penumbra/Interop/Services/TextureArraySlicer.cs @@ -1,8 +1,7 @@ using Dalamud.Bindings.ImGui; using FFXIVClientStructs.FFXIV.Client.Graphics.Kernel; using OtterGui.Services; -using SharpDX.Direct3D; -using SharpDX.Direct3D11; +using TerraFX.Interop.DirectX; namespace Penumbra.Interop.Services; @@ -22,46 +21,78 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable if (texture == null) throw new ArgumentNullException(nameof(texture)); if (sliceIndex >= texture->ArraySize) - throw new ArgumentOutOfRangeException(nameof(sliceIndex), $"Slice index ({sliceIndex}) is greater than or equal to the texture array size ({texture->ArraySize})"); + throw new ArgumentOutOfRangeException(nameof(sliceIndex), + $"Slice index ({sliceIndex}) is greater than or equal to the texture array size ({texture->ArraySize})"); + if (_activeSlices.TryGetValue(((nint)texture, sliceIndex), out var state)) { state.Refresh(); return new ImTextureID((nint)state.ShaderResourceView); } - var srv = (ShaderResourceView)(nint)texture->D3D11ShaderResourceView; - var description = srv.Description; - switch (description.Dimension) + + ref var srv = ref *(ID3D11ShaderResourceView*)(nint)texture->D3D11ShaderResourceView; + srv.AddRef(); + try { - case ShaderResourceViewDimension.Texture1D: - case ShaderResourceViewDimension.Texture2D: - case ShaderResourceViewDimension.Texture2DMultisampled: - case ShaderResourceViewDimension.Texture3D: - case ShaderResourceViewDimension.TextureCube: - // This function treats these as single-slice arrays. - // As per the range check above, the only valid slice (i. e. 0) has been requested, therefore there is nothing to do. - break; - case ShaderResourceViewDimension.Texture1DArray: - description.Texture1DArray.FirstArraySlice = sliceIndex; - description.Texture2DArray.ArraySize = 1; - break; - case ShaderResourceViewDimension.Texture2DArray: - description.Texture2DArray.FirstArraySlice = sliceIndex; - description.Texture2DArray.ArraySize = 1; - break; - case ShaderResourceViewDimension.Texture2DMultisampledArray: - description.Texture2DMSArray.FirstArraySlice = sliceIndex; - description.Texture2DMSArray.ArraySize = 1; - break; - case ShaderResourceViewDimension.TextureCubeArray: - description.TextureCubeArray.First2DArrayFace = sliceIndex * 6; - description.TextureCubeArray.CubeCount = 1; - break; - default: - throw new NotSupportedException($"{nameof(TextureArraySlicer)} does not support dimension {description.Dimension}"); + D3D11_SHADER_RESOURCE_VIEW_DESC description; + srv.GetDesc(&description); + switch (description.ViewDimension) + { + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE1D: + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE2D: + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE2DMS: + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE3D: + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURECUBE: + // This function treats these as single-slice arrays. + // As per the range check above, the only valid slice (i. e. 0) has been requested, therefore there is nothing to do. + break; + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE1DARRAY: + description.Texture1DArray.FirstArraySlice = sliceIndex; + description.Texture2DArray.ArraySize = 1; + break; + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE2DARRAY: + description.Texture2DArray.FirstArraySlice = sliceIndex; + description.Texture2DArray.ArraySize = 1; + break; + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: + description.Texture2DMSArray.FirstArraySlice = sliceIndex; + description.Texture2DMSArray.ArraySize = 1; + break; + case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURECUBEARRAY: + description.TextureCubeArray.First2DArrayFace = sliceIndex * 6u; + description.TextureCubeArray.NumCubes = 1; + break; + default: + throw new NotSupportedException($"{nameof(TextureArraySlicer)} does not support dimension {description.ViewDimension}"); + } + + ID3D11Device* device = null; + srv.GetDevice(&device); + ID3D11Resource* resource = null; + srv.GetResource(&resource); + try + { + ID3D11ShaderResourceView* slicedSrv = null; + Marshal.ThrowExceptionForHR(device->CreateShaderResourceView(resource, &description, &slicedSrv)); + resource->Release(); + device->Release(); + + state = new SliceState(slicedSrv); + _activeSlices.Add(((nint)texture, sliceIndex), state); + return new ImTextureID((nint)state.ShaderResourceView); + } + finally + { + if (resource is not null) + resource->Release(); + if (device is not null) + device->Release(); + } + } + finally + { + srv.Release(); } - state = new SliceState(new ShaderResourceView(srv.Device, srv.Resource, description)); - _activeSlices.Add(((nint)texture, sliceIndex), state); - return new ImTextureID((nint)state.ShaderResourceView); } public void Tick() @@ -73,10 +104,9 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable if (!slice.Tick()) _expiredKeys.Add(key); } + foreach (var key in _expiredKeys) - { _activeSlices.Remove(key); - } } finally { @@ -87,14 +117,12 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable public void Dispose() { foreach (var slice in _activeSlices.Values) - { slice.Dispose(); - } } - private sealed class SliceState(ShaderResourceView shaderResourceView) : IDisposable + private sealed class SliceState(ID3D11ShaderResourceView* shaderResourceView) : IDisposable { - public readonly ShaderResourceView ShaderResourceView = shaderResourceView; + public readonly ID3D11ShaderResourceView* ShaderResourceView = shaderResourceView; private uint _timeToLive = InitialTimeToLive; @@ -108,13 +136,15 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable if (unchecked(_timeToLive--) > 0) return true; - ShaderResourceView.Dispose(); + if (ShaderResourceView is not null) + ShaderResourceView->Release(); return false; } public void Dispose() { - ShaderResourceView.Dispose(); + if (ShaderResourceView is not null) + ShaderResourceView->Release(); } } } diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index f04928a5..43f853f3 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -38,16 +38,8 @@ $(DalamudLibPath)Iced.dll False - - $(DalamudLibPath)SharpDX.dll - False - - - $(DalamudLibPath)SharpDX.Direct3D11.dll - False - - - $(DalamudLibPath)SharpDX.DXGI.dll + + $(DalamudLibPath)TerraFX.Interop.Windows.dll False diff --git a/Penumbra/Services/StaticServiceManager.cs b/Penumbra/Services/StaticServiceManager.cs index 27582395..be482d1d 100644 --- a/Penumbra/Services/StaticServiceManager.cs +++ b/Penumbra/Services/StaticServiceManager.cs @@ -48,6 +48,7 @@ public static class StaticServiceManager .AddDalamudService(pi) .AddDalamudService(pi) .AddDalamudService(pi) + .AddDalamudService(pi) .AddDalamudService(pi) .AddDalamudService(pi) .AddDalamudService(pi) From 4c8ff408211eda482cd3978c5ec502c19e6d48b6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Thu, 18 Dec 2025 20:47:49 +0100 Subject: [PATCH 1366/1381] Fix private Unks. --- .../UI/Tabs/Debug/GlobalVariablesDrawer.cs | 9 +++++---- Penumbra/Util/PointerExtensions.cs | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 Penumbra/Util/PointerExtensions.cs diff --git a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs index f0ab1125..bc5f0765 100644 --- a/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs +++ b/Penumbra/UI/Tabs/Debug/GlobalVariablesDrawer.cs @@ -9,6 +9,7 @@ using OtterGui.Text; using Penumbra.Interop.Services; using Penumbra.Interop.Structs; using Penumbra.String; +using Penumbra.Util; using ResidentResourceManager = Penumbra.Interop.Services.ResidentResourceManager; namespace Penumbra.UI.Tabs.Debug; @@ -178,10 +179,10 @@ public unsafe class GlobalVariablesDrawer( if (_schedulerFilterMap.Length is 0 || resource->Name.Buffer.IndexOf(_schedulerFilterMapU8.Span) >= 0) { ImUtf8.DrawTableColumn($"[{total:D4}]"); - ImUtf8.DrawTableColumn($"{resource->Name.Unk1}"); + ImUtf8.DrawTableColumn($"{resource->Name.GetField(16)}"); // Unk1 ImUtf8.DrawTableColumn(new CiByteString(resource->Name.Buffer, MetaDataComputation.None).Span); ImUtf8.DrawTableColumn($"{resource->Consumers}"); - ImUtf8.DrawTableColumn($"{resource->Unk1}"); // key + ImUtf8.DrawTableColumn($"{PointerExtensions.GetField(resource, 120)}"); // key, Unk1 ImGui.TableNextColumn(); Penumbra.Dynamis.DrawPointer(resource); ImGui.TableNextColumn(); @@ -227,10 +228,10 @@ public unsafe class GlobalVariablesDrawer( if (_schedulerFilterList.Length is 0 || resource->Name.Buffer.IndexOf(_schedulerFilterListU8.Span) >= 0) { ImUtf8.DrawTableColumn($"[{total:D4}]"); - ImUtf8.DrawTableColumn($"{resource->Name.Unk1}"); + ImUtf8.DrawTableColumn($"{resource->Name.GetField(16)}"); // Unk1 ImUtf8.DrawTableColumn(new CiByteString(resource->Name.Buffer, MetaDataComputation.None).Span); ImUtf8.DrawTableColumn($"{resource->Consumers}"); - ImUtf8.DrawTableColumn($"{resource->Unk1}"); // key + ImUtf8.DrawTableColumn($"{PointerExtensions.GetField(resource, 120)}"); // key, Unk1 ImGui.TableNextColumn(); Penumbra.Dynamis.DrawPointer(resource); ImGui.TableNextColumn(); diff --git a/Penumbra/Util/PointerExtensions.cs b/Penumbra/Util/PointerExtensions.cs new file mode 100644 index 00000000..c70e2177 --- /dev/null +++ b/Penumbra/Util/PointerExtensions.cs @@ -0,0 +1,20 @@ +namespace Penumbra.Util; + +public static class PointerExtensions +{ + public static unsafe ref TField GetField(this ref TPointer reference, int offset) + where TPointer : unmanaged + where TField : unmanaged + { + var pointer = (byte*)Unsafe.AsPointer(ref reference) + offset; + return ref *(TField*)pointer; + } + + public static unsafe ref TField GetField(TPointer* itemPointer, int offset) + where TPointer : unmanaged + where TField : unmanaged + { + var pointer = (byte*)itemPointer + offset; + return ref *(TField*)pointer; + } +} From febced07080a84e7526e56b1944128ecd6dc8d9a Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 00:47:19 +0100 Subject: [PATCH 1367/1381] Fix bug in slicer. --- Penumbra/Interop/Services/TextureArraySlicer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra/Interop/Services/TextureArraySlicer.cs b/Penumbra/Interop/Services/TextureArraySlicer.cs index 7b873f26..3cd57a33 100644 --- a/Penumbra/Interop/Services/TextureArraySlicer.cs +++ b/Penumbra/Interop/Services/TextureArraySlicer.cs @@ -48,7 +48,7 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable break; case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE1DARRAY: description.Texture1DArray.FirstArraySlice = sliceIndex; - description.Texture2DArray.ArraySize = 1; + description.Texture1DArray.ArraySize = 1; break; case D3D_SRV_DIMENSION.D3D11_SRV_DIMENSION_TEXTURE2DARRAY: description.Texture2DArray.FirstArraySlice = sliceIndex; From ebcbc5d98a896c96756588c916aa52294a91773d Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 00:51:39 +0100 Subject: [PATCH 1368/1381] Update SDK. --- OtterGui | 2 +- Penumbra.Api | 2 +- Penumbra.CrashHandler/Penumbra.CrashHandler.csproj | 2 +- Penumbra.GameData | 2 +- Penumbra.String | 2 +- Penumbra/Penumbra.csproj | 2 +- Penumbra/Penumbra.json | 2 +- repo.json | 4 ++-- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/OtterGui b/OtterGui index 6f323645..ff1e6543 160000 --- a/OtterGui +++ b/OtterGui @@ -1 +1 @@ -Subproject commit 6f3236453b1edfaa25c8edcc8b39a9d9b2fc18ac +Subproject commit ff1e6543845e3b8c53a5f8b240bc38faffb1b3bf diff --git a/Penumbra.Api b/Penumbra.Api index e4934ccc..1750c41b 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit e4934ccca0379f22dadf989ab2d34f30b3c5c7ea +Subproject commit 1750c41b53e1000c99a7fb9d8a0f082aef639a41 diff --git a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj index 4c864d39..e07bb745 100644 --- a/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj +++ b/Penumbra.CrashHandler/Penumbra.CrashHandler.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/Penumbra.GameData b/Penumbra.GameData index 3d4d8510..0e973ed6 160000 --- a/Penumbra.GameData +++ b/Penumbra.GameData @@ -1 +1 @@ -Subproject commit 3d4d8510f832dfd95d7069b86e6b3da4ec612558 +Subproject commit 0e973ed6eace6afd31cd298f8c58f76fa8d5ef60 diff --git a/Penumbra.String b/Penumbra.String index 0315144a..9bd016fb 160000 --- a/Penumbra.String +++ b/Penumbra.String @@ -1 +1 @@ -Subproject commit 0315144ab5614c11911e2a4dddf436fb18c5d7e3 +Subproject commit 9bd016fbef5fb2de467dd42165267fdd93cd9592 diff --git a/Penumbra/Penumbra.csproj b/Penumbra/Penumbra.csproj index 43f853f3..f9e33219 100644 --- a/Penumbra/Penumbra.csproj +++ b/Penumbra/Penumbra.csproj @@ -1,4 +1,4 @@ - + Penumbra absolute gangstas diff --git a/Penumbra/Penumbra.json b/Penumbra/Penumbra.json index 32032282..975c5bb3 100644 --- a/Penumbra/Penumbra.json +++ b/Penumbra/Penumbra.json @@ -8,7 +8,7 @@ "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "Tags": [ "modding" ], - "DalamudApiLevel": 13, + "DalamudApiLevel": 14, "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, diff --git a/repo.json b/repo.json index 7ddffd7c..5b780560 100644 --- a/repo.json +++ b/repo.json @@ -9,8 +9,8 @@ "TestingAssemblyVersion": "1.5.1.8", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", - "DalamudApiLevel": 13, - "TestingDalamudApiLevel": 13, + "DalamudApiLevel": 14, + "TestingDalamudApiLevel": 14, "IsHide": "False", "IsTestingExclusive": "False", "DownloadCount": 0, From fb299d71f0921c6efad318d0b648bad1c0076e61 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 00:54:09 +0100 Subject: [PATCH 1369/1381] Remove unimplemented ipc. --- Penumbra/Api/Api/UiApi.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Penumbra/Api/Api/UiApi.cs b/Penumbra/Api/Api/UiApi.cs index 6a293678..6fb116f3 100644 --- a/Penumbra/Api/Api/UiApi.cs +++ b/Penumbra/Api/Api/UiApi.cs @@ -85,12 +85,6 @@ public class UiApi : IPenumbraApiUi, IApiService, IDisposable public void CloseMainWindow() => _configWindow.IsOpen = false; - public PenumbraApiEc RegisterSettingsSection(Action draw) - => throw new NotImplementedException(); - - public PenumbraApiEc UnregisterSettingsSection(Action draw) - => throw new NotImplementedException(); - private void OnChangedItemClick(MouseButton button, IIdentifiedObjectData data) { if (ChangedItemClicked == null) From 37f30443767b9367970e16b1aba03d9608885592 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 00:56:50 +0100 Subject: [PATCH 1370/1381] Update dotnet. --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/test_release.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7901a653..85ea0953 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,7 +16,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '9.x.x' + dotnet-version: '10.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 377919b2..e4a17130 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '9.x.x' + dotnet-version: '10.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 2bece720..8af4a8c8 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -15,7 +15,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '9.x.x' + dotnet-version: '10.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud From 59fec5db822240213457b8e0b92566a9fad0ab89 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 01:05:50 +0100 Subject: [PATCH 1371/1381] Needs both versions for now due to flatsharp? --- .github/workflows/build.yml | 4 +++- .github/workflows/release.yml | 4 +++- .github/workflows/test_release.yml | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 85ea0953..26b1219d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,7 +16,9 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '10.x.x' + dotnet-version: | + '10.x.x' + '9.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e4a17130..a4442c14 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,7 +15,9 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '10.x.x' + dotnet-version: | + '10.x.x' + '9.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 8af4a8c8..914eb136 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -15,7 +15,9 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '10.x.x' + dotnet-version: | + '10.x.x' + '9.x.x' - name: Restore dependencies run: dotnet restore - name: Download Dalamud From 953f243caf7f03a58e67ae75dae3962e89cd55f6 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 01:08:18 +0100 Subject: [PATCH 1372/1381] . --- .github/workflows/build.yml | 8 ++++---- .github/workflows/release.yml | 8 ++++---- .github/workflows/test_release.yml | 8 ++++---- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 26b1219d..1a61439e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,15 +10,15 @@ jobs: build: runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 with: submodules: recursive - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - '10.x.x' - '9.x.x' + 10.x.x + 9.x.x - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a4442c14..c72b4800 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,15 +9,15 @@ jobs: build: runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 with: submodules: recursive - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - '10.x.x' - '9.x.x' + 10.x.x + 9.x.x - name: Restore dependencies run: dotnet restore - name: Download Dalamud diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 914eb136..90a8b176 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -9,15 +9,15 @@ jobs: build: runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 with: submodules: recursive - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v5 with: dotnet-version: | - '10.x.x' - '9.x.x' + 10.x.x + 9.x.x - name: Restore dependencies run: dotnet restore - name: Download Dalamud From deb3686df5cf1f30365d70b3a2f382863136e953 Mon Sep 17 00:00:00 2001 From: Actions User Date: Fri, 19 Dec 2025 00:12:44 +0000 Subject: [PATCH 1373/1381] [CI] Updating repo.json for 1.5.1.9 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 5b780560..611de678 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.8", - "TestingAssemblyVersion": "1.5.1.8", + "AssemblyVersion": "1.5.1.9", + "TestingAssemblyVersion": "1.5.1.9", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 14, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.8/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.8/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.8/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.9/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.9/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.9/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 9cf7030f87142f6ae446b64601f56f9e849e67ca Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Fri, 19 Dec 2025 01:13:02 +0100 Subject: [PATCH 1374/1381] ... --- .github/workflows/test_release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test_release.yml b/.github/workflows/test_release.yml index 90a8b176..c6b4e459 100644 --- a/.github/workflows/test_release.yml +++ b/.github/workflows/test_release.yml @@ -9,7 +9,7 @@ jobs: build: runs-on: windows-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v5 with: submodules: recursive - name: Setup .NET From eff3784a85c6fb498ba7f9655d6b9d26b524953e Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Dec 2025 15:34:08 +0100 Subject: [PATCH 1375/1381] Fix multi-release bug in texturearrayslicer. --- Penumbra/Interop/Services/TextureArraySlicer.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Penumbra/Interop/Services/TextureArraySlicer.cs b/Penumbra/Interop/Services/TextureArraySlicer.cs index 3cd57a33..a3db4d04 100644 --- a/Penumbra/Interop/Services/TextureArraySlicer.cs +++ b/Penumbra/Interop/Services/TextureArraySlicer.cs @@ -18,7 +18,7 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable /// Caching this across frames will cause a crash to desktop. public ImTextureID GetImGuiHandle(Texture* texture, byte sliceIndex) { - if (texture == null) + if (texture is null) throw new ArgumentNullException(nameof(texture)); if (sliceIndex >= texture->ArraySize) throw new ArgumentOutOfRangeException(nameof(sliceIndex), @@ -74,9 +74,6 @@ public sealed unsafe class TextureArraySlicer : IUiService, IDisposable { ID3D11ShaderResourceView* slicedSrv = null; Marshal.ThrowExceptionForHR(device->CreateShaderResourceView(resource, &description, &slicedSrv)); - resource->Release(); - device->Release(); - state = new SliceState(slicedSrv); _activeSlices.Add(((nint)texture, sliceIndex), state); return new ImTextureID((nint)state.ShaderResourceView); From 9aa566f521d0375959ceeffee2e9fcbce660c999 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Dec 2025 15:34:50 +0100 Subject: [PATCH 1376/1381] Fix typo in new IPC providers. --- Penumbra.Api | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Penumbra.Api b/Penumbra.Api index 1750c41b..52a3216a 160000 --- a/Penumbra.Api +++ b/Penumbra.Api @@ -1 +1 @@ -Subproject commit 1750c41b53e1000c99a7fb9d8a0f082aef639a41 +Subproject commit 52a3216a525592205198303df2844435e382cf87 From 069323cfb8220b893df878b5067ee9d87656ab9a Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 20 Dec 2025 14:38:27 +0000 Subject: [PATCH 1377/1381] [CI] Updating repo.json for 1.5.1.11 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 611de678..f337e8ff 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.9", - "TestingAssemblyVersion": "1.5.1.9", + "AssemblyVersion": "1.5.1.11", + "TestingAssemblyVersion": "1.5.1.11", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 14, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.9/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.9/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.9/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.11/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.11/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.11/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 73f02851a64e2a0ea9447173a7981d098a38bac1 Mon Sep 17 00:00:00 2001 From: Ottermandias Date: Sat, 20 Dec 2025 21:51:34 +0100 Subject: [PATCH 1378/1381] Cherry pick API support for other block compression types from Luna branch. --- Penumbra/Api/Api/EditingApi.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Penumbra/Api/Api/EditingApi.cs b/Penumbra/Api/Api/EditingApi.cs index e50b7a1b..5a1fc347 100644 --- a/Penumbra/Api/Api/EditingApi.cs +++ b/Penumbra/Api/Api/EditingApi.cs @@ -19,6 +19,12 @@ public class EditingApi(TextureManager textureManager) : IPenumbraApiEditing, IA TextureType.Bc3Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, inputFile, outputFile), TextureType.Bc7Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, inputFile, outputFile), TextureType.Bc7Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, inputFile, outputFile), + TextureType.Bc1Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC1, mipMaps, true, inputFile, outputFile), + TextureType.Bc1Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC1, mipMaps, false, inputFile, outputFile), + TextureType.Bc4Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC4, mipMaps, true, inputFile, outputFile), + TextureType.Bc4Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC4, mipMaps, false, inputFile, outputFile), + TextureType.Bc5Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC5, mipMaps, true, inputFile, outputFile), + TextureType.Bc5Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC5, mipMaps, false, inputFile, outputFile), _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), }; @@ -36,6 +42,12 @@ public class EditingApi(TextureManager textureManager) : IPenumbraApiEditing, IA TextureType.Bc3Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC3, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), TextureType.Bc7Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), TextureType.Bc7Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC7, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc1Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC1, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc1Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC1, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc4Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC4, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc4Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC4, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc5Tex => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC5, mipMaps, true, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), + TextureType.Bc5Dds => textureManager.SaveAs(CombinedTexture.TextureSaveType.BC5, mipMaps, false, new BaseImage(), outputFile, rgbaData, width, rgbaData.Length / 4 / width), _ => Task.FromException(new Exception($"Invalid input value {textureType}.")), }; // @formatter:on From 6ba735eefba180538190842973604e8b0a592d0d Mon Sep 17 00:00:00 2001 From: Actions User Date: Sat, 20 Dec 2025 20:53:36 +0000 Subject: [PATCH 1379/1381] [CI] Updating repo.json for 1.5.1.12 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index f337e8ff..583e5e52 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.11", - "TestingAssemblyVersion": "1.5.1.11", + "AssemblyVersion": "1.5.1.12", + "TestingAssemblyVersion": "1.5.1.12", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 14, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.11/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.11/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.11/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.12/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.12/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.12/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ] From 13500264b7f046cacbddae41df704089be7e7908 Mon Sep 17 00:00:00 2001 From: Marc-Aurel Zent Date: Mon, 22 Dec 2025 14:41:32 +0100 Subject: [PATCH 1380/1381] Use iced to create AsmHooks in PapRewriter. --- .../Hooks/ResourceLoading/PapRewriter.cs | 85 ++++++++++++------- 1 file changed, 54 insertions(+), 31 deletions(-) diff --git a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs index caf43d08..ff794d81 100644 --- a/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs +++ b/Penumbra/Interop/Hooks/ResourceLoading/PapRewriter.cs @@ -1,6 +1,7 @@ using System.Text.Unicode; using Dalamud.Hooking; using Iced.Intel; +using static Iced.Intel.AssemblerRegisters; using OtterGui.Extensions; using Penumbra.String.Classes; using Swan; @@ -46,36 +47,32 @@ public sealed class PapRewriter(PeSigScanner sigScanner, PapRewriter.PapResource stackAccesses.RemoveAll(instr => instr.IP == hp.IP); var detourPointer = Marshal.GetFunctionPointerForDelegate(papResourceHandler); - var targetRegister = hookPoint.Op0Register.ToString().ToLower(); + var targetRegister = GetRegister64(hookPoint.Op0Register); var hookAddress = new IntPtr((long)detourPoint.IP); var caveAllocation = NativeAllocCave(16); - var hook = new AsmHook( - hookAddress, - [ - "use64", - $"mov {targetRegister}, 0x{stringAllocation:x8}", // Move our char *path into the relevant register (rdx) + var assembler = new Assembler(64); + assembler.mov(targetRegister, stringAllocation); // Move our char *path into the relevant register (rdx) - // After this asm stub, we have a call to Crc32(); since r9 is a volatile, unused register, we can use it ourselves - // We're essentially storing the original 2 arguments ('this', 'path'), in case they get mangled in our call - // We technically don't need to save rdx ('path'), since it'll be stringLoc, but eh - $"mov r9, 0x{caveAllocation:x8}", - "mov [r9], rcx", - "mov [r9+0x8], rdx", + // After this asm stub, we have a call to Crc32(); since r9 is a volatile, unused register, we can use it ourselves + // We're essentially storing the original 2 arguments ('this', 'path'), in case they get mangled in our call + // We technically don't need to save rdx ('path'), since it'll be stringLoc, but eh + assembler.mov(r9, caveAllocation); + assembler.mov(__qword_ptr[r9], rcx); + assembler.mov(__qword_ptr[r9 + 8], rdx); - // We can use 'rax' here too since it's also volatile, and it'll be overwritten by Crc32()'s return anyway - $"mov rax, 0x{detourPointer:x8}", // Get a pointer to our detour in place - "call rax", // Call detour + // We can use 'rax' here too since it's also volatile, and it'll be overwritten by Crc32()'s return anyway + assembler.mov(rax, detourPointer); + assembler.call(rax); - // Do the reverse process and retrieve the stored stuff - $"mov r9, 0x{caveAllocation:x8}", - "mov rcx, [r9]", - "mov rdx, [r9+0x8]", + // Do the reverse process and retrieve the stored stuff + assembler.mov(r9, caveAllocation); + assembler.mov(rcx, __qword_ptr[r9]); + assembler.mov(rdx, __qword_ptr[r9 + 8]); - // Plop 'rax' (our return value, the path size) into r8, so it's the third argument for the subsequent Crc32() call - "mov r8, rax", - ], $"{name}.PapRedirection" - ); + // Plop 'rax' (our return value, the path size) into r8, so it's the third argument for the subsequent Crc32() call + assembler.mov(r8, rax); + var hook = new AsmHook(hookAddress, AssembleToBytes(assembler), $"{name}.PapRedirection"); _hooks.Add(hookAddress, hook); hook.Enable(); @@ -95,19 +92,45 @@ public sealed class PapRewriter(PeSigScanner sigScanner, PapRewriter.PapResource if (_hooks.ContainsKey(hookAddress)) continue; - var targetRegister = stackAccess.Op0Register.ToString().ToLower(); - var hook = new AsmHook( - hookAddress, - [ - "use64", - $"mov {targetRegister}, 0x{stringAllocation:x8}", - ], $"{name}.PapStackAccess[{index}]" - ); + var targetRegister = GetRegister64(stackAccess.Op0Register); + var assembler = new Assembler(64); + assembler.mov(targetRegister, stringAllocation); + var hook = new AsmHook(hookAddress, AssembleToBytes(assembler), $"{name}.PapStackAccess[{index}]"); _hooks.Add(hookAddress, hook); hook.Enable(); } } + + private static AssemblerRegister64 GetRegister64(Register reg) + => reg switch + { + Register.RAX => rax, + Register.RCX => rcx, + Register.RDX => rdx, + Register.RBX => rbx, + Register.RSP => rsp, + Register.RBP => rbp, + Register.RSI => rsi, + Register.RDI => rdi, + Register.R8 => r8, + Register.R9 => r9, + Register.R10 => r10, + Register.R11 => r11, + Register.R12 => r12, + Register.R13 => r13, + Register.R14 => r14, + Register.R15 => r15, + _ => throw new ArgumentOutOfRangeException(nameof(reg), reg, "Unsupported register."), + }; + + private static byte[] AssembleToBytes(Assembler assembler) + { + using var stream = new MemoryStream(); + var writer = new StreamCodeWriter(stream); + assembler.Assemble(writer, 0); + return stream.ToArray(); + } private static IEnumerable ScanStackAccesses(IEnumerable instructions, Instruction hookPoint) { From eec8ee709411f18704b95b543fb4966b525b0428 Mon Sep 17 00:00:00 2001 From: Actions User Date: Tue, 27 Jan 2026 15:30:23 +0000 Subject: [PATCH 1381/1381] [CI] Updating repo.json for 1.5.1.13 --- repo.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/repo.json b/repo.json index 583e5e52..22a682ee 100644 --- a/repo.json +++ b/repo.json @@ -5,8 +5,8 @@ "Punchline": "Runtime mod loader and manager.", "Description": "Runtime mod loader and manager.", "InternalName": "Penumbra", - "AssemblyVersion": "1.5.1.12", - "TestingAssemblyVersion": "1.5.1.12", + "AssemblyVersion": "1.5.1.13", + "TestingAssemblyVersion": "1.5.1.13", "RepoUrl": "https://github.com/xivdev/Penumbra", "ApplicableVersion": "any", "DalamudApiLevel": 14, @@ -18,9 +18,9 @@ "LoadPriority": 69420, "LoadRequiredState": 2, "LoadSync": true, - "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.12/Penumbra.zip", - "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.12/Penumbra.zip", - "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.12/Penumbra.zip", + "DownloadLinkInstall": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.13/Penumbra.zip", + "DownloadLinkTesting": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.13/Penumbra.zip", + "DownloadLinkUpdate": "https://github.com/xivdev/Penumbra/releases/download/1.5.1.13/Penumbra.zip", "IconUrl": "https://raw.githubusercontent.com/xivdev/Penumbra/master/images/icon.png" } ]